text
stringlengths
14
6.51M
{ Copyright (c) 2016 by Albert Molina Copyright (c) 2017 by BlaiseCoin developers Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. This unit is a part of BlaiseCoin, a P2P crypto-currency. } unit UStreamOp; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses SysUtils, Classes; type TStreamOp = class public class function ReadAnsiString(Stream: TStream; var Value: AnsiString): Integer; class function WriteAnsiString(Stream: TStream; Value: AnsiString): Integer; end; EStreamOp = class(Exception); implementation uses ULog; { TStreamOp } class function TStreamOp.ReadAnsiString(Stream: TStream; var Value: AnsiString): Integer; var l: Word; begin if Stream.Size - Stream.Position < 2 then begin // no size word Value := ''; Result := -1; exit; end; Stream.Read(l, 2); if Stream.Size - Stream.Position < l then begin Stream.Position := Stream.Position - 2; // Go back! Value := ''; Result := -2; exit; end; SetLength(Value, l); if l > 0 then Stream.ReadBuffer(Value[1], l); Result := l; end; class function TStreamOp.WriteAnsiString(Stream: TStream; Value: AnsiString): Integer; var n: Integer; l: Word; e: String; begin n := Length(Value); if n > $FFFF then begin e := 'String too long to stream, length=' + IntToStr(n); TLog.NewLog(lterror, ClassName, e); raise EStreamOp.Create(e); end; l := n; Stream.Write(l, 2); if l > 0 then Stream.WriteBuffer(Value[1], l); Result := l; end; end.
unit Class_GkQuery; interface uses Classes,SysUtils,StrUtils,Uni,UniEngine,Class_GKJG_FL_IN_GKZF; type TGkQuery=class(TUniEngine) private FGKJGFLLX: Integer; FGKJGFLID: Integer; FGKJGFLMC: string; FFILTMARK: string; FFILTTEXT: string; FSTARTVAL: Extended; FRIGHTVAL: Extended; published property GKJGFLLX: Integer read FGKJGFLLX write FGKJGFLLX; property GKJGFLID: Integer read FGKJGFLID write FGKJGFLID; property GKJGFLMC: string read FGKJGFLMC write FGKJGFLMC; property FILTMARK: string read FFILTMARK write FFILTMARK; property FILTTEXT: string read FFILTTEXT write FFILTTEXT; property STARTVAL: Extended read FSTARTVAL write FSTARTVAL; property RIGHTVAL: Extended read FRIGHTVAL write FRIGHTVAL; public class function PrepareView(ADJLX:Integer;AListOfGkQuery:TStringList;AUniConnection:TUniConnection):Boolean; end; implementation uses Class_KzDebug; { TGkQuery } class function TGkQuery.PrepareView(ADJLX: Integer; AListOfGkQuery: TStringList; AUniConnection: TUniConnection): Boolean; var I:Integer; TMPA:string; TMPB:string; TMPC:string; TMPD:string; GkQuery:TGkQuery; begin Result:=False; if (AListOfGkQuery=nil) or (AListOfGkQuery.Count=0) then Exit; TMPA:=''; TMPB:=''; TMPC:=''; TMPD:=''; for I:=0 to AListOfGkQuery.Count -1 do begin GkQuery:=TGkQuery(AListOfGkQuery.Objects[I]); if GkQuery=nil then Continue; case TGKJGFLDATATYPE(GkQuery.GKJGFLLX) of gdtText: begin if Pos(',',GkQuery.FiltText) >0 then begin TMPA:='SELECT * FROM GKX_GKJL_EL A WHERE 1=1 $DJLX AND EXISTS (SELECT GKJL_FLID FROM GKX_GKJL_FL B WHERE 1=1 AND (B.DATA_TEXT IN ( %S ) AND B.GKJG_FLID=%D) '+' AND A.GKJL_FLID=B.GKJL_FLID AND A.GKJL_IDEX=B.GKJL_IDEX AND A.UNIT_LINK=B.UNIT_LINK AND A.GKJG_IDEX=B.GKJG_IDEX)'; TMPA:=Format(TMPA,[GkQuery.FiltText,GkQuery.GKJGFLID]); end else begin if GkQuery.FiltMark='精确' then begin TMPA:='SELECT * FROM GKX_GKJL_EL A WHERE 1=1 $DJLX AND EXISTS (SELECT GKJL_FLID FROM GKX_GKJL_FL B WHERE 1=1 AND (B.DATA_TEXT = %S AND B.GKJG_FLID=%D) '+' AND A.GKJL_FLID=B.GKJL_FLID AND A.GKJL_IDEX=B.GKJL_IDEX AND A.UNIT_LINK=B.UNIT_LINK AND A.GKJG_IDEX=B.GKJG_IDEX)'; TMPA:=Format(TMPA,[QuotedStr(GkQuery.FiltText),GkQuery.GKJGFLID]); end else begin TMPA:='SELECT * FROM GKX_GKJL_EL A WHERE 1=1 $DJLX AND EXISTS (SELECT GKJL_FLID FROM GKX_GKJL_FL B WHERE 1=1 AND (B.DATA_TEXT LIKE %S AND B.GKJG_FLID=%D) '+' AND A.GKJL_FLID=B.GKJL_FLID AND A.GKJL_IDEX=B.GKJL_IDEX AND A.UNIT_LINK=B.UNIT_LINK AND A.GKJG_IDEX=B.GKJG_IDEX)'; TMPA:=Format(TMPA,[QuotedStr('%'+GkQuery.FiltText+'%'),GkQuery.GKJGFLID]); end; end; end; gdtMemo: begin if Pos(',',GkQuery.FiltText) >0 then begin TMPA:='SELECT * FROM GKX_GKJL_EL A WHERE 1=1 $DJLX AND EXISTS (SELECT GKJL_FLID FROM GKX_GKJL_FL B WHERE 1=1 AND (B.DATA_MEMO IN ( %S ) AND B.GKJG_FLID=%D) '+' AND A.GKJL_FLID=B.GKJL_FLID AND A.GKJL_IDEX=B.GKJL_IDEX AND A.UNIT_LINK=B.UNIT_LINK AND A.GKJG_IDEX=B.GKJG_IDEX)'; TMPA:=Format(TMPA,[GkQuery.FiltText,GkQuery.GKJGFLID]); end else begin if GkQuery.FiltMark='精确' then begin TMPA:='SELECT * FROM GKX_GKJL_EL A WHERE 1=1 $DJLX AND EXISTS (SELECT GKJL_FLID FROM GKX_GKJL_FL B WHERE 1=1 AND (B.DATA_MEMO = %S AND B.GKJG_FLID=%D) '+' AND A.GKJL_FLID=B.GKJL_FLID AND A.GKJL_IDEX=B.GKJL_IDEX AND A.UNIT_LINK=B.UNIT_LINK AND A.GKJG_IDEX=B.GKJG_IDEX)'; TMPA:=Format(TMPA,[GkQuery.FiltText,GkQuery.GKJGFLID]); end else begin TMPA:='SELECT * FROM GKX_GKJL_EL A WHERE 1=1 $DJLX AND EXISTS (SELECT GKJL_FLID FROM GKX_GKJL_FL B WHERE 1=1 AND (B.DATA_MEMO LIKE %S AND B.GKJG_FLID=%D) '+' AND A.GKJL_FLID=B.GKJL_FLID AND A.GKJL_IDEX=B.GKJL_IDEX AND A.UNIT_LINK=B.UNIT_LINK AND A.GKJG_IDEX=B.GKJG_IDEX)'; TMPA:=Format(TMPA,[QuotedStr('%'+GkQuery.FiltText+'%'),GkQuery.GKJGFLID]); end; end; end; gdtDoub,gdtDate: begin if GkQuery.FiltMark='区间' then begin TMPA:='SELECT * FROM GKX_GKJL_EL A WHERE 1=1 $DJLX AND EXISTS (SELECT GKJL_FLID FROM GKX_GKJL_FL B WHERE 1=1 AND (B.DATA_DOUB >= %F AND B.DATA_DOUB <= %F AND B.GKJG_FLID=%D) '+' AND A.GKJL_FLID=B.GKJL_FLID AND A.GKJL_IDEX=B.GKJL_IDEX AND A.UNIT_LINK=B.UNIT_LINK AND A.GKJG_IDEX=B.GKJG_IDEX)'; TMPA:=Format(TMPA,[GkQuery.StartVal,GkQuery.RightVal,GkQuery.GKJGFLID]); end else begin TMPA:='SELECT * FROM GKX_GKJL_EL A WHERE 1=1 $DJLX AND EXISTS (SELECT GKJL_FLID FROM GKX_GKJL_FL B WHERE 1=1 AND (B.DATA_DOUB %S %F AND B.GKJG_FLID=%D) '+' AND A.GKJL_FLID=B.GKJL_FLID AND A.GKJL_IDEX=B.GKJL_IDEX AND A.UNIT_LINK=B.UNIT_LINK AND A.GKJG_IDEX=B.GKJG_IDEX)'; TMPA:=Format(TMPA,[GkQuery.FiltMark,GkQuery.StartVal,GkQuery.GKJGFLID]); end; end; end; TMPB := TMPB + TMPA; if I<>AListOfGkQuery.Count-1 then begin TMPB:=TMPB + ' INTERSECT '; end; end; if ADJLX=-1 then begin TMPB:=StringReplace(TMPB,'$DJLX','',[rfReplaceAll]); end else begin TMPD:=Format(' AND A.GKJL_DJLX = %D ',[ADJLX]); TMPB:=StringReplace(TMPB,'$DJLX',TMPD,[rfReplaceAll]); end; TMPC:=Format('CREATE VIEW VIEW_YOTO_GKEL AS %S',[TMPB]); if CheckExist('SYSOBJECTS',['XTYPE','V','NAME','VIEW_YOTO_GKEL'],AUniConnection) then begin ExecuteSQL('DROP VIEW VIEW_YOTO_GKEL',AUniConnection); end; ExecuteSQL(TMPC,AUniConnection); Result:=True; end; end.
unit AddRole; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, MainDM, Role; type TFormAddRole = class(TForm) EditName: TEdit; EditFullName: TEdit; ButtonOk: TButton; ButtonCancel: TButton; LabelAdd: TLabel; LabelFullName: TLabel; procedure FormCreate(Sender: TObject); procedure ButtonOkClick(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); procedure EditNameKeyPress(Sender: TObject; var Key: Char); procedure FormDestroy(Sender: TObject); private { Private declarations } FMode: Integer; FRole: TRole; public { Public declarations } FResultRole: TRole; function ValidData: Boolean; constructor Create(Owner: TComponent; theRole: TRole; Mode: Integer); end; implementation {$R *.DFM} constructor TFormAddRole.Create(Owner: TComponent; theRole: TRole; Mode: Integer); begin inherited Create(Owner); FMode := Mode; FResultRole := nil; if FMode <> fmAdd then FRole := theRole; end; procedure TFormAddRole.FormCreate(Sender: TObject); begin case FMode of fmEdit: begin Caption := 'Редагування групи'; ButtonOk.Caption := 'Прийняти'; end; fmView: begin ButtonOk.Caption := 'ОК'; ButtonCancel.Caption := 'Вийти'; EditName.Enabled := false; EditFullName.Enabled := false; end; end; if (FMode = fmEdit) or (FMode = fmView) then begin EditName.Text := FRole.RoleName; EditFullName.Text := FRole.RoleFullName; end; end; procedure TFormAddRole.ButtonOkClick(Sender: TObject); begin if not ValidData then Exit; case FMode of fmAdd : begin FRole := TRole.Create(Self, DMMain.KruAccessDB); FRole.NewRole(Trim(EditName.Text), Trim(EditFullName.Text)); if not FRole.Insert then ShowErrorMessage('Не вдалось додати групу!') else FResultRole := FRole; end; fmEdit: begin FRole.RoleName := Trim(EditName.Text); FRole.RoleFullName := Trim(EditFullName.Text); if not FRole.Update then ShowErrorMessage('Не вдалось додати групу!') else begin FResultRole := TRole.Create(Self, DMMain.KruAccessDB); FResultRole.RoleName := FRole.RoleName; FResultRole.RoleFullName := FRole.RoleFullName; FResultRole.RoleID := FRole.RoleID; end end; end; ModalResult := mrOk; end; procedure TFormAddRole.ButtonCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; function TFormAddRole.ValidData: Boolean; begin Result := false; if Trim(EditName.Text) = '' then begin EditName.SetFocus; Exit; end; if Trim(EditFullName.Text) = '' then begin EditFullName.SetFocus; Exit; end; Result := true; end; procedure TFormAddRole.EditNameKeyPress(Sender: TObject; var Key: Char); begin if Key in ['/','\'] then Key := #0; end; procedure TFormAddRole.FormDestroy(Sender: TObject); begin FResultRole.Free; end; end.
{----------------------------------------------------------------------------- Unit Name: cSimulationGrids Author: Aaron Hochwimmer (hochwimmera@pbworld.com) Purpose: non-visual classes for storing and manipulating geothermal simulation grids (e.g. MULKON/TOUGH, TETRAD) Updates: 28-Jul-2003: Version 0.1 - added TGridBlock and other code - note nothing actually works (yet) -------------------------------------------------------------------------------} unit cSimulationGrids; interface uses System.Classes, System.SysUtils, Vcl.Controls; type TSVect = array[0..2] of single; TGridLayer = class; TGridLayers = class; TSimulationGrid = class; TGridVertex = class(TObject) private fLocationE : single; fLocationN : single; fVertexLabel : string; public property LocationE:single read fLocationE write fLocationE; property LocationN:single read fLocationN write fLocationN; property VertexLabel:string read fVertexLabel write fVertexLabel; end; TRockType = class(TObject) private fColourCode : string; fRockName : string; fPermeabilityX : double; fPermeabilityY : double; fPermeabilityZ : double; fPorosity : double; fSpecificHeat : double; fThermalConductivity : double; protected procedure SetPorosity(dValue:double); public property ColourCode : string read fColourCode write fColourCode; property RockName : string read fRockName write fRockName; property PermeabilityX : double read fPermeabilityX write fPermeabilityX; property PermeabilityY : double read fPermeabilityY write fPermeabilityY; property PermeabilityZ : double read fPermeabilityZ write fPermeabilityZ; property Porosity : double read fPorosity write SetPorosity; property SpecificHeat : double read fSpecificHeat write fSpecificHeat; property ThermalConductivity : double read fThermalConductivity write fThermalConductivity; end; // cartesian xyz grid block TGridBlock = class(TObject) private fInActive : boolean; fBlockName : string; fColumn : integer; fRow : integer; fLayer : TGridLayer; fLocationE : single; fLocationN : single; fPr : single; fRockTypeCode : string; fSv : single; fTe : single; fVertices : TStringList; fTETRAD : boolean; fElevation : single; fThickness : single; protected function GetElevation : single; function GetLayerName : string; function GetLayerType : string; function GetPermeabilityX : double; function GetPermeabilityY : double; function GetPermeabilityZ : double; function GetPorosity : single; function GetThickness : single; procedure SetBlockName(sValue : string); procedure SetLocationE(dValue : single); procedure SetLocationN(dValue : single); procedure SetPr(dValue:single); procedure SetSv(dValue:single); procedure SetTe(dValue:single); public constructor Create(aLayer:TGridLayer); destructor Destroy;override; procedure ClearVertices; procedure AddVertex(sVertex:string); property InActive : boolean read fInActive write fInActive; property BlockName : string read fBlockName write SetBlockName; property Column : integer read fColumn write fColumn; property Elevation : single read GetElevation write fElevation; property Layer : TGridLayer read fLayer write fLayer; property LayerName : string read GetLayerName; property LayerType : string read GetLayerType; property LocationE : single read fLocationE write SetLocationE; property LocationN : single read fLocationN write SetLocationN; property Pr : single read fPr write SetPr; property PermeabilityX : double read GetPermeabilityX; property PermeabilityY : double read GetPermeabilityY; property PermeabilityZ : double read GetPermeabilityZ; property Porosity : single read GetPorosity; property RockTypeCode : string read fRockTypeCode write fRockTypeCode; property Row : integer read fRow write fRow; property Sv : single read fSv write SetSv; property Te : single read fTe write SetTe; property TETRAD : boolean read fTETRAD write fTETRAD; property Thickness : single read GetThickness write fThickness; property Vertices : TStringList read fVertices write fVertices; end; TGridLayer = class(TObject) private fBlockList : TStringList; fElevation : single; // elevation of the layer (midpoint) fLayerName : string; fLayerType : string; fParent : TGridLayers; fThickNess : single; fVisible : boolean; protected procedure SetVisible(bVisible:boolean); function GetGridBlock(iIndex:integer):TGridBlock; function GetMinPr:single; function GetMinTe:single; function GetMinSv:single; function GetMaxPr:single; function GetMaxTe:single; function GetMaxSv:single; public constructor Create(aParent:TGridLayers); destructor Destroy;override; procedure AddBlock(sBlockName:string;dLocationE,dLocationN:double);virtual; procedure AddTETRADBlock(sBlockName:string;dLocationE,dLocationN,dElevation, dTHickness,dX,dY:double;iRow,iCol:integer;bActive:boolean);virtual; procedure AddVertexOrder(sBlockName:string;vo:TStringList); procedure ClearBlocks;virtual; function GetBlockByName(sBlock:string):TGridBlock; // procedure DeleteBlock(iBlock:integer);virtual; property BlockList:TStringList read fBlockList; property Elevation:single read fElevation write fElevation; property LayerName:string read fLayerName write fLayerName; property LayerType:string read fLayerType write fLayerType; property MinPr : single read GetMinPr; property MinSv : single read GetMinSv; property MinTe : single read GetMinTe; property MaxPr : single read GetMaxPr; property MaxSv : single read GetMaxSv; property MaxTe : single read GetMaxTe; property Parent:TGridLayers read fParent; property Thickness:single read fThickNess write fThickness; property Block[iIndex:integer]:TGridBLock read GetGridBlock; property Visible:boolean read fVisible write SetVisible; end; TGridLayers = class(TObject) private fGrid : TSimulationGrid; fLayerList : TStringList; protected public constructor Create(aGrid:TSimulationGrid); destructor Destroy;override; procedure AddLayer(sLayerName,sLayerType:string; delevation,dthickness:single);virtual; procedure ClearLayers;virtual; procedure DeleteLayer(iIndex:integer);virtual; property Grid:TSimulationGrid read fGrid; property LayerList:TStringList read fLayerList; end; // bounds on vertices... TSimulationGrid = class(TObject) private fComment : string; fGridDate : TDate; fGridName : string; fRockTypeList : TStringlist; fVertexList : TStringList; function GetRockType(iIndex:integer):TRockType; function GetGridVertex(iIndex:integer):TGridVertex; function GetVertexCount:integer; function GetMinVertexLimit : TSVect; function GetMaxVertexLimit : TSVect; public constructor Create; destructor Destroy;override; procedure AddVertex(sVertex:string;x,y:single); procedure AddRockType(sRock:string;dPermX,dPermY,dPermZ:double;dPorosity, dThermalConductivity,dSpecificHeat:single;sColourCode:string); procedure ClearAll; procedure ClearRockTypes; procedure ClearVertices; procedure DeleteVertex(iIndex:integer); procedure DeleteVertexByLabel(sLabel:string); function GetRockTypeByName(sRock:string):TRockType; function GetVertexByLabel(sLabel:string):TGridVertex; property Comment:string read fComment write fComment; property GridDate:TDate read fGridDate write fGridDate; property GridName:string read fGridName write fGridName; property MinVertexLimit : TSVect read GetMinVertexLimit; property MaxVertexLimit : TSVect read GetMaxVertexLimit; property RockType[iIndex:integer]:TRockType read GetRockType; property Vertex[iIndex:integer]:TGridVertex read GetGridVertex; property VertexCount:integer read GetVertexCount; end; implementation // ============================================================================= // TRockType Implementation // ============================================================================= procedure TRockType.SetPorosity(dValue:double); begin // porosity must be [0.0,1.0] if (dValue > 1.0) then fPorosity := 1.0 else if (dValue < 0.0) then fPorosity := 0.0 else fPorosity := dValue; end; // ============================================================================= // TGRIDBLOCK Implementation // ============================================================================= // ----- TGridBlock.GetElevation ----------------------------------------------- function TGridBlock.GetElevation:single; begin if TETRAD then result := fElevation else result := TGridLayer(Layer).Elevation; end; // ----- TGridBlock.GetLayerName ----------------------------------------------- function TGridBlock.GetLayerName:string; begin result := TGridLayer(Layer).LayerName; end; // ----- TGridBlock.GetLayerType ----------------------------------------------- function TGridBlock.GetLayerType:string; begin result := TGridLayer(Layer).LayerType; end; // ----- TGridBlock.GetPermeabilityX ------------------------------------------- function TGridBlock.GetPermeabilityX:double; var aRock : TRockType; begin aRock := TGridLayer(fLayer).Parent.Grid.GetRockTypeByName(RockTypeCode); if (aRock <> nil) then result := aRock.PermeabilityX else result := 0; end; // ----- TGridBlock.GetPermeabilityY ------------------------------------------- function TGridBlock.GetPermeabilityY:double; var aRock : TRockType; begin aRock := TGridLayer(fLayer).Parent.Grid.GetRockTypeByName(RockTypeCode); if (aRock <> nil) then result := aRock.PermeabilityY else result := 0; end; // ----- TGridBlock.GetPermeabilityZ ------------------------------------------- function TGridBlock.GetPermeabilityZ:double; var aRock : TRockType; begin aRock := TGridLayer(fLayer).Parent.Grid.GetRockTypeByName(RockTypeCode); if (aRock <> nil) then result := aRock.PermeabilityZ else result := 0; end; // ----- TGridBlock.GetPorosity ------------------------------------------------ function TGridBlock.GetPorosity:single; var aRock : TRockType; begin aRock := TGridLayer(fLayer).Parent.Grid.GetRockTypeByName(RockTypeCode); if (aRock <> nil) then result := aRock.Porosity else result := 0.0; // should really be null end; // ----- TGridBlock.GetThickness ----------------------------------------------- function TGridBlock.GetThickness:single; begin if TETRAD then result := fThickness else result := TGridLayer(Layer).Thickness; end; //------ TGridBlock.SetBlockName ----------------------------------------------- procedure TGridBlock.SetBlockName(sValue:string); begin if (fBlockName <> sValue) then fBlockName := sValue; end; // ----- TGridBlock.SetLocationE ----------------------------------------------- procedure TGridBlock.SetLocationE(dValue:single); begin if (fLocationE <> dValue) then fLocationE := dValue; end; // ----- TGridBlock.SetLocationN ----------------------------------------------- procedure TGridBlock.SetLocationN(dValue:single); begin if (fLocationN <> dValue) then fLocationN := dValue; end; // ----- TGridBlock.SetPr ------------------------------------------------------ procedure TGridBlock.SetPr(dValue:single); begin if (fPr <> dValue) then fPr := dValue; end; // ----- TGridBlock.SetSv ------------------------------------------------------ procedure TGridBlock.SetSv(dValue:single); begin if (fSv <> dValue) then begin // saturation must be [0.0,1.0] if (dValue > 1.0) then fSv := 1.0 else if (dValue < 0.0) then fSv := 0.0 else fSv := dValue; end; end; // ----- TGridBlock.SetTe ------------------------------------------------------ procedure TGridBlock.SetTe(dValue:single); begin if (fTe <> dValue) then fTe := dValue; end; // ----- TGridBlock.Create ----------------------------------------------------- constructor TGridBlock.Create(aLayer:TGridLayer); begin inherited Create; fLayer := aLayer; fTETRAD := false; fInActive := false; Vertices := TStringList.Create; end; // ----- TGridBlock.Destroy ---------------------------------------------------- destructor TGridBlock.Destroy; begin ClearVertices; Vertices.Free; inherited Destroy; end; // ----- TGridBlock.AddVertex -------------------------------------------------- procedure TGridBlock.AddVertex(sVertex:string); begin Vertices.Add(sVertex); end; // ----- TGridBlock.ClearVertices ---------------------------------------------- procedure TGridBlock.ClearVertices; begin Vertices.Clear; end; // ============================================================================= // TGRIDLAYER Implementation // ============================================================================= procedure TGridLayer.SetVisible(bVisible:boolean); begin fVisible := bVisible; // set block visibility ... end; // ----- TGridLayer.GetMinPr --------------------------------------------------- // loop all blocks - looking for min Pressure function TGridLayer.GetMinPr:single; var i:integer; begin for i:=0 to fBlockList.Count-1 do begin with TGridBlock(fBlockList.Objects[i]) do begin if i=0 then result := Pr else if (result > Pr) then result := Pr; end; end; end; // ----- TGridLayer.GetMinTe --------------------------------------------------- function TGridLayer.GetMinTe:single; var i:integer; begin for i:=0 to fBlockList.Count-1 do begin with TGridBlock(fBlockList.Objects[i]) do begin if i=0 then result := Te else if (result > Te) then result := Te; end; end; end; // ----- TGridLayer.GetMinSv --------------------------------------------------- function TGridLayer.GetMinSv:single; var i:integer; begin for i:=0 to fBlockList.Count-1 do begin with TGridBlock(fBlockList.Objects[i]) do begin if i=0 then result := Sv else if (result > Sv) then result := Sv; end; end; end; // ----- TGridLayer.GetMaxPr --------------------------------------------------- function TGridLayer.GetMaxPr:single; var i:integer; begin for i:=0 to fBlockList.Count-1 do begin with TGridBlock(fBlockList.Objects[i]) do begin if i=0 then result := Pr else if (result < Pr) then result := Pr; end; end; end; // ----- TGridLayer.GetMaxTe --------------------------------------------------- function TGridLayer.GetMaxTe: single; var i:integer; begin for i:=0 to fBlockList.Count-1 do begin with TGridBlock(fBlockList.Objects[i]) do begin if i=0 then result := Te else if (result < Te) then result := Te; end; end; end; // ----- TGridLayer.GetMaxSv --------------------------------------------------- function TGridLayer.GetMaxSv:single; var i:integer; begin for i:=0 to fBlockList.Count-1 do begin with TGridBlock(fBlockList.Objects[i]) do begin if i=0 then result := Sv else if (result < Sv) then result := Sv; end; end; end; // ----- TGridLayer.GetGridBlock ----------------------------------------------- function TGridLayer.GetGridBlock(iIndex:integer):TGridBlock; begin if (iIndex >=0) and (iIndex < fBlockList.Count) then result := TGridBlock(fBlockList.Objects[iIndex]) else result := nil; end; // ----- TGridLayer.Create ----------------------------------------------------- constructor TGridLayer.Create(aParent:TGridLayers); begin inherited Create; fParent := aParent; fBlockList :=TStringList.Create; end; // ----- TGridLayer.Destroy ---------------------------------------------------- destructor TGridLayer.Destroy; begin ClearBlocks; fBlockList.Free; inherited Destroy; end; // ----- TGridLayer.AddBlock --------------------------------------------------- procedure TGridLayer.AddBlock(sBlockName:string;dLocationE,dLocationN:double); var iIndex : integer; block : TGridBlock; begin // check to see if this block is already in the list... if (fBlockList.IndexOf(sBlockName) = -1) then begin block := TGridBlock.Create(self); fBlockList.AddObject(sBlockName,block); iIndex := fBlockList.IndexOf(sBlockName); with TGridBlock(fBlockList.Objects[iIndex]) do begin TETRAD := false; BlockName := sBlockName; LocationE := dLocationE; LocationN := dLocationN; end; end; end; procedure TGridLayer.AddTETRADBlock(sBlockName:string;dLocationE,dLocationN, dElevation,dThickness,dX,dY:double;iRow,iCol:integer;bActive:boolean); var iIndex:integer; block : TGridBlock; begin // check to see if this block is already in the list... if (fBlockList.IndexOf(sBlockName) = -1) then begin block := TGridBlock.Create(self); fBlockList.AddObject(sBlockName,block); iIndex := fBlockList.IndexOf(sBlockName); with TGridBlock(fBlockList.Objects[iIndex]) do begin TETRAD := true; BlockName := sBlockName; LocationE := dLocationE; LocationN := dLocationN; Elevation := dElevation; Thickness := dThickness; Vertices.Add(FloatToStr(dx)); Vertices.Add(FloatToStr(dy)); Row := iRow; Column := iCol; InActive := not bActive; end; end; end; // ----- TGridLayer.AddVertexOrder --------------------------------------------- procedure TGridLayer.AddVertexOrder(sBlockName:string;vo:TStringList); var iIndex : integer; begin iIndex := BlockList.IndexOf(sBlockName); if (iIndex <> -1) then TGridBlock(BlockList.Objects[iIndex]).Vertices.Assign(vo); end; // ----- TGridLayer.ClearBlocks ------------------------------------------------ procedure TGridLayer.ClearBlocks; begin while (fBlockList.Count > 0) do begin TGridBlock(fBlockList.Objects[0]).Free; fBlockList.Delete(0); end; fBlockList.Clear; end; // ----- TGRidLayer.GetBlockByName --------------------------------------------- function TGRidLayer.GetBlockByName(sBlock:string):TGridBlock; begin result := GetGridBlock(fBlockList.IndexOf(sBlock)); end; // ============================================================================= // TGRIDLAYERS Implementation // ============================================================================= constructor TGridLayers.Create(aGRid:TSimulationGrid); begin inherited Create; fGrid := aGrid; fLayerList := TStringList.Create; end; // ----- TGRidLayers.Destroy --------------------------------------------------- destructor TGridLayers.Destroy; begin fLayerList.Free; inherited Destroy; end; // ----- TGridLayers.AddLayer -------------------------------------------------- procedure TGridLayers.AddLayer(sLayerName,sLayerType:string; delevation,dthickness:single); var iIndex : integer; layer : TGridLayer; begin // check to see if this layer is already in the list... if (fLayerList.IndexOf(sLayerName) = -1) then begin layer := TGridLayer.Create(self); fLayerList.AddObject(sLayerName,layer); iIndex := fLayerList.IndexOf(sLayerName); with TGridLayer(fLayerList.Objects[iIndex]) do begin LayerName := sLayerName; LayerType := sLayerType; Elevation := dElevation; Thickness := dThickness; end; end; end; // ----- TGridLayers.ClearLayers ----------------------------------------------- procedure TGridLayers.ClearLayers; begin while (fLayerList.Count > 0) do begin TGridLayer(fLayerList.Objects[0]).Free; fLayerList.Delete(0); end; fLayerList.Clear; end; // ----- TGridLayers.DeleteLayer ----------------------------------------------- procedure TGridLayers.DeleteLayer(iIndex:integer); begin if (iIndex >=0) and (iIndex < fLayerList.Count) then begin TGridLayer(fLayerList.Objects[iIndex]).Free; fLayerList.Delete(iIndex); end; end; // ============================================================================= // TSIMULATIONGRID Implementation // ============================================================================= // ----- TSimulationGrid.GetRockType ------------------------------------------- function TSimulationGrid.GetRockType(iIndex:integer):TRockType; begin if (iIndex >=0) and (iIndex < fRockTypeList.Count) then result := TRockType(fRockTypeList.Objects[iIndex]) else result := nil; end; // ----- TSimulationGrid.GetGridVertex ----------------------------------------- function TSimulationGrid.GetGridVertex(iIndex:integer):TGridVertex; begin if (iIndex >=0) and (iIndex < fVertexList.Count) then result := TGridVertex(fVertexList.Objects[iIndex]) else result := nil; end; // ----- TSimulationGrid.GetVertexCount ---------------------------------------- function TSimulationGrid.GetVertexCount:integer; begin result := fVertexList.Count; end; // ----- TSimulationGrid.GetMinVertexLimit ------------------------------------- function TSimulationGrid.GetMinVertexLimit : TSVect; var i:integer; begin if VertexCount > 0 then begin for i:=0 to VertexCount-1 do begin // max singles result[0] := 3.4e+38; result[1] := result[0]; result[2] := result[0]; with TGridVertex(fVertexList.Objects[i]) do begin if (result[0] > LocationE) then result[0] := LocationE; if (result[1] > LocationN) then result[1] := LocationN; end; end; end else begin result[0] := 0.0; result[1] := 0.0; result[2] := 0.0; end; end; // ----- TSimulationGrid.GetMaxVertexLimit ------------------------------------- function TSimulationGrid.GetMaxVertexLimit : TSVect; var i:integer; begin if VertexCount > 0 then begin for i:=0 to VertexCount-1 do begin // max singles result[0] := -3.4e+38; result[1] := result[0]; result[2] := result[0]; with TGridVertex(fVertexList.Objects[i]) do begin if (result[0] < LocationE) then result[0] := LocationE; if (result[1] < LocationN) then result[1] := LocationN; end; end; end else begin result[0] := 0.0; result[1] := 0.0; result[2] := 0.0; end; end; // ----- TSimulationGrid.Create ------------------------------------------------ constructor TSimulationGrid.Create; begin inherited Create; fRockTypeList := TStringList.Create; fVertexList := TStringList.Create; // fGridLayers := TGridLayers.Create(self); end; // ----- TSimulationGrid.Destroy ----------------------------------------------- destructor TSimulationGrid.Destroy; begin ClearRockTypes; fRockTypeList.Free; fVertexList.Free; // fGridLayers.Free; inherited Destroy; end; // ----- TSimulationGrid.AddRockType ------------------------------------------- procedure TSimulationGrid.AddRockType(sRock:string;dPermX,dPermY,dPermZ:double; dPorosity,dThermalConductivity,dSpecificHeat:single;sColourCode:string); var iIndex : integer; rock : TRockType; begin // check to see if this rock is already in the list... if (fRockTypeList.IndexOf(sRock) = -1) then begin rock := TRockType.Create; fRockTypeList.AddObject(sRock,rock); iIndex := fRockTypeList.IndexOf(sRock); with TRockType(fRockTypeList.Objects[iIndex]) do begin RockName := sRock; PermeabilityX := dPermX; PermeabilityY := dPermY; PermeabilityZ := dPermZ; Porosity := dPorosity; ThermalConductivity := dThermalConductivity; SpecificHeat := dSpecificHeat; ColourCode := sColourCode; end; end; end; // ----- TSimulationGrid.AddVertex --------------------------------------------- procedure TSimulationGrid.AddVertex(sVertex:string;x,y:single); var iIndex : integer; v : TGridVertex; begin // check to see if this vertex is already in the list... if (fVertexList.IndexOf(sVertex) = -1) then begin v := TGridVertex.Create; fVertexList.AddObject(sVertex,v); iIndex := fVertexList.IndexOf(sVertex); with TGridVertex(fVertexList.Objects[iIndex]) do begin VertexLabel := sVertex; LocationE := x; LocationN := y; end; end; end; // ----- TSimulationGrid.ClearRockTypes ---------------------------------------- procedure TSimulationGrid.ClearRockTypes; begin while (fRockTypeList.Count > 0) do begin TRockType(fRockTypeList.Objects[0]).Free; fRockTypeList.Delete(0); end; fRockTypeList.Clear; end; // ----- TSimulationGrid.ClearVertices ----------------------------------------- procedure TSimulationGrid.ClearVertices; begin while (fVertexList.Count>0) do DeleteVertex(0); fVertexList.Clear; end; // ----- TSimulationGrid.DeleteVertex ------------------------------------------ procedure TSimulationGrid.DeleteVertex(iIndex:integer); begin if (iIndex >=0) and (iIndex < fVertexList.Count) then begin TGridVertex(fVertexList.Objects[iIndex]).Free; fVertexList.Delete(iIndex); end; end; // ----- TSimulationGrid.DeleteVertexByLabel ----------------------------------- procedure TSimulationGrid.DeleteVertexByLabel(sLabel:string); begin DeleteVertex(fVertexList.IndexOf(sLabel)); end; // ----- TSimulationGrid.GetRockTypeByName ------------------------------------- function TSimulationGrid.GetRockTypeByName(sRock:string):TRockType; begin result := GetRockType(fRockTypeList.IndexOf(sRock)); end; // ----- TSimulationGrid.GetVertexByLabel -------------------------------------- function TSimulationGrid.GetVertexByLabel(sLabel:string):TGridVertex; begin result := GetGridVertex(fVertexList.IndexOf(sLabel)); end; // ----- TSimulationGrid.ClearAll ---------------------------------------------- procedure TSimulationGrid.ClearAll; begin ClearRockTypes; ClearVertices; end; // ============================================================================= end.
unit uExplorerThreadPool; interface uses Windows, Math, Classes, SysUtils, SyncObjs, ExplorerTypes, uConstants, uMemory, uTime, uRuntime, uMultiCPUThreadManager, uThreadEx, uDBEntities; type TExplorerThreadPool = class(TThreadPoolCustom) protected procedure AddNewThread(Thread: TMultiCPUThread); override; public class function Instance: TExplorerThreadPool; procedure ExtractImage(Sender: TMultiCPUThread; Info: TMediaItem; CryptedFile: Boolean; FileID: TGUID); procedure ExtractDirectoryPreview(Sender: TMultiCPUThread; DirectoryPath: string; FileID: TGUID); procedure ExtractBigImage(Sender: TMultiCPUThread; FileName: string; ID, Rotated: Integer; FileID: TGUID); end; implementation uses ExplorerThreadUnit, ExplorerUnit; var ExplorerThreadPool: TExplorerThreadPool = nil; { TExplorerThreadPool } procedure TExplorerThreadPool.AddNewThread(Thread: TMultiCPUThread); var ExplorerViewInfo: TExplorerViewInfo; begin ExplorerViewInfo := TExplorerThread(Thread).ExplorerInfo; ExplorerViewInfo.View := -1; ExplorerViewInfo.PictureSize := 0; if (Thread <> nil) and (AvaliableThreadsCount + BusyThreadsCount < Min(MAX_THREADS_USE, ProcessorCount + 1)) then AddAvaliableThread(TExplorerThread.Create(nil, '', '', THREAD_TYPE_THREAD_PREVIEW, ExplorerViewInfo, nil, TUpdaterInfo.Create, Thread.StateID)); end; procedure TExplorerThreadPool.ExtractImage(Sender: TMultiCPUThread; Info: TMediaItem; CryptedFile: Boolean; FileID: TGUID); var Thread: TExplorerThread; Avaliablethread: TExplorerThread; begin Thread := Sender as TExplorerThread; if Thread = nil then raise Exception.Create('Sender is not TExplorerThread!'); Avaliablethread := TExplorerThread(GetAvaliableThread(Sender)); if Avaliablethread <> nil then begin Avaliablethread.ThreadForm := Sender.ThreadForm; Avaliablethread.FContext := Thread.FContext; Avaliablethread.FSender := TExplorerForm(Sender.ThreadForm); Avaliablethread.UpdaterInfo.Assign(Thread.UpdaterInfo); Avaliablethread.ExplorerInfo := Thread.ExplorerInfo; Avaliablethread.StateID := Thread.StateID; Avaliablethread.FInfo.Assign(Info, True); Avaliablethread.IsCryptedFile := CryptedFile; Avaliablethread.FFileID := FileID; Avaliablethread.Mode := THREAD_PREVIEW_MODE_IMAGE; Avaliablethread.OwnerThreadType := Thread.ThreadType; Avaliablethread.LoadingAllBigImages := Thread.LoadingAllBigImages; StartThread(Thread, Avaliablethread); end; end; procedure TExplorerThreadPool.ExtractBigImage(Sender: TMultiCPUThread; FileName: string; ID, Rotated: Integer; FileID: TGUID); var Thread : TExplorerThread; Avaliablethread : TExplorerThread; begin Thread := Sender as TExplorerThread; if Thread = nil then raise Exception.Create('Sender is not TExplorerThread!'); Avaliablethread := TExplorerThread(GetAvaliableThread(Sender)); if Avaliablethread <> nil then begin Avaliablethread.ThreadForm := Sender.ThreadForm; Avaliablethread.FSender := TExplorerForm(Sender.ThreadForm); Avaliablethread.UpdaterInfo.Assign(Thread.UpdaterInfo); Avaliablethread.ExplorerInfo := Thread.ExplorerInfo; Avaliablethread.StateID := Thread.StateID; Avaliablethread.FInfo.FileName := FileName; Avaliablethread.FInfo.Rotation := Rotated; Avaliablethread.FInfo.ID := ID; Avaliablethread.IsCryptedFile := False; Avaliablethread.FFileID := FileID; Avaliablethread.Mode := THREAD_PREVIEW_MODE_BIG_IMAGE; Avaliablethread.OwnerThreadType := Thread.ThreadType; Avaliablethread.LoadingAllBigImages := Thread.LoadingAllBigImages; StartThread(Thread, Avaliablethread); end; end; procedure TExplorerThreadPool.ExtractDirectoryPreview(Sender: TMultiCPUThread; DirectoryPath: string; FileID: TGUID); var Thread : TExplorerThread; Avaliablethread : TExplorerThread; begin Thread := Sender as TExplorerThread; if Thread = nil then raise Exception.Create('Sender is not TExplorerThread!'); Avaliablethread := TExplorerThread(GetAvaliableThread(Sender)); if Avaliablethread <> nil then begin Avaliablethread.ThreadForm := Sender.ThreadForm; Avaliablethread.FSender := TExplorerForm(Sender.ThreadForm); Avaliablethread.UpdaterInfo.Assign(Thread.UpdaterInfo); Avaliablethread.ExplorerInfo := Thread.ExplorerInfo; Avaliablethread.StateID := Thread.StateID; Avaliablethread.FInfo.FileName := DirectoryPath; Avaliablethread.IsCryptedFile := False; Avaliablethread.FFileID := FileID; Avaliablethread.Mode := THREAD_PREVIEW_MODE_DIRECTORY; Avaliablethread.OwnerThreadType := Thread.ThreadType; Avaliablethread.LoadingAllBigImages := Thread.LoadingAllBigImages; StartThread(Thread, Avaliablethread); end; end; class function TExplorerThreadPool.Instance: TExplorerThreadPool; begin if ExplorerThreadPool = nil then ExplorerThreadPool := TExplorerThreadPool.Create; Result := ExplorerThreadPool; end; initialization finalization F(ExplorerThreadPool); end.
unit Lib.VCL.HTTPGraphic; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Imaging.JPEG, Vcl.Imaging.GIFImg, Vcl.Imaging.PNGImage, Lib.HTTPContent; function PictureLoadFromContent(Picture: TPicture; Content: TContent): Boolean; implementation type TContentStream = class(TMemoryStream) public constructor Create(const Content: TBytes); end; constructor TContentStream.Create(const Content: TBytes); begin SetPointer(Pointer(Content),Length(Content)); end; function GetContentTypeGraphicClass(const ContentType: string): TGraphicClass; begin Result:=nil; if ContentType.StartsWith('image/jpeg') then Result:=TJPEGImage else if ContentType.StartsWith('image/gif') then Result:=TGIFImage else if ContentType.StartsWith('image/png') then Result:=TPNGImage else if ContentType.StartsWith('image/vnd.microsoft.icon') then Result:=TIcon; end; function CreatePictureGraphic(Picture: TPicture; const ContentType: string): Boolean; var Graphic: TGraphic; GraphicClass: TGraphicClass; begin GraphicClass:=GetContentTypeGraphicClass(ContentType); if Assigned(GraphicClass) then begin if GraphicClass=TPNGImage then Graphic:=TPNGImage.CreateBlank(0,1,0,0) else Graphic:=GraphicClass.Create; Picture.Graphic:=Graphic; Graphic.Free; end else Picture.Graphic:=nil; Result:=Assigned(Picture.Graphic); end; function PictureLoadFromContent(Picture: TPicture; Content: TContent): Boolean; var Stream: TContentStream; begin Result:=False; if CreatePictureGraphic(Picture,Content.Headers.ContentType) then try Stream:=TContentStream.Create(Content.Content); try Picture.Graphic.LoadFromStream(Stream); if Picture.Graphic is TGIFImage then TGIFImage(Picture.Graphic).Animate:=True; Result:=True; finally Stream.Free; end; except Picture.Graphic:=nil; end; end; end.
unit odg_gui; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, LCLIntf, odg_main, odg_asciidoc, oslog, odg_pyasciidoc, StdCtrls, EditBtn; type { TForm1 } TForm1 = class(TForm) Bsave_ascii_show: TButton; ButtonConvert: TButton; ButtonPythonConvert: TButton; ButtonSave: TButton; ButtonOpen: TButton; Memo1: TMemo; Memo2: TMemo; OpenDialog1: TOpenDialog; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; SaveDialog1: TSaveDialog; Splitter1: TSplitter; procedure Bsave_ascii_showClick(Sender: TObject); procedure ButtonConvertClick(Sender: TObject); procedure ButtonOpenClick(Sender: TObject); procedure ButtonPythonConvertClick(Sender: TObject); procedure ButtonSaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); private public end; var Form1: TForm1; infilename : string; implementation {$R *.lfm} { TForm1 } { procedure TForm1.ButtonOpenClick(Sender: TObject); begin Memo1.Lines.Clear; Memo2.Lines.Clear; if OpenDialog1.Execute then begin infilename := OpenDialog1.FileName; sourcelist.LoadFromFile(infilename); memo1.Lines.Assign(sourcelist); if ExtractFileExt(infilename) = '.opsiscript' then begin ButtonPythonConvert.enabled:=false; ButtonConvert.enabled:=true; end else begin ButtonConvert.enabled:=false; ButtonPythonConvert.enabled:=true; end end; end; } procedure TForm1.ButtonOpenClick(Sender: TObject); var filecount, totallines : integer; tempfile : TStringList; begin Memo1.Lines.Clear; Memo2.Lines.Clear; tempfile := TStringList.Create; tempfile.Clear; sourcelist.Clear; OpenDialog1.Options:= [ofAllowMultiSelect, ofFileMustExist]; if OpenDialog1.Execute then begin for filecount:= 0 to OpenDialog1.Files.Count-1 do begin tempfile.LoadFromFile(OpenDialog1.Files[filecount]); //sourcelist.Append(tempfile.Text); sourcelist.AddStrings(tempfile); end; totallines:= sourcelist.Count; memo1.Lines.Assign(sourcelist); ButtonConvert.enabled:=true; ButtonPythonConvert.enabled:=true; end; end; procedure TForm1.ButtonSaveClick(Sender: TObject); var savefilename : string; begin if SaveDialog1.Execute then begin savefilename := SaveDialog1.FileName; targetlist.SaveToFile(savefilename); end; end; procedure TForm1.FormCreate(Sender: TObject); begin caption := 'opsi doc generator Version: '+myversion; end; procedure TForm1.ButtonConvertClick(Sender: TObject); begin convertOslibToAsciidoc(infilename); memo2.Lines.Assign(targetlist); end; procedure TForm1.ButtonPythonConvertClick(Sender: TObject); begin convertPylibToAsciidoc(infilename); memo2.Lines.Assign(targetlist); end; procedure TForm1.Bsave_ascii_showClick(Sender: TObject); begin if ExtractFileExt(infilename) = '.opsiscript' then convertOslibToAsciidoc(infilename) else convertPylibToAsciidoc(infilename); memo2.Lines.Assign(targetlist); save_compile_show(infilename); end; initialization end.
// 第1版Union-Find unit DSA.Tree.UnionFind1; interface uses System.SysUtils, DSA.Interfaces.DataStructure, DSA.Utils; type { TUnionFind1 } TUnionFind1 = class(TInterfacedObject, IUnionFind) private __id: TArray_int; /// <summary> 查找元素p所对应的集合编号 </summary> function __find(p: integer): integer; public constructor Create(newSize: integer); function GetSize: integer; /// <summary> 查看元素p和元素q是否所属一个集合 </summary> function IsConnected(p, q: integer): boolean; /// <summary> 合并元素p和元素q所属的集合 </summary> procedure UnionElements(p, q: integer); end; implementation { TUnionFind1 } constructor TUnionFind1.Create(newSize: integer); var i: integer; begin SetLength(__id, newSize); for i := 0 to newSize - 1 do __id[i] := i; end; function TUnionFind1.GetSize: integer; begin Result := Length(__id); end; function TUnionFind1.IsConnected(p, q: integer): boolean; begin Result := __find(p) = __find(q); end; procedure TUnionFind1.UnionElements(p, q: integer); var pid, qid, i: integer; begin pid := __find(p); qid := __find(q); if pid = qid then Exit; for i := 0 to Length(__id) - 1 do begin if __id[i] = pid then __id[i] := qid; end; end; function TUnionFind1.__find(p: integer): integer; begin if (p < 0) and (p >= Length(__id)) then raise Exception.Create('p is out of bound.'); Result := __id[p]; end; end.
unit manager; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, Grids, Buttons, fphttpclient, Fpjson, jsonparser; type { TManageForm } TManageForm = class(TForm) btnOK: TButton; btnSendMoney: TButton; editMoney: TLabeledEdit; GroupBox2: TGroupBox; Label1: TLabel; Panel1: TPanel; PricesData: TStringGrid; procedure btnSendMoneyClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure PricesDataEditingDone(Sender: TObject); procedure SetHash(input: String); procedure SetName(input: String); procedure SetID(input: String); private public end; var ManageForm: TManageForm; StationHash: String; StationName: String; StationID: String; RequestAnswer: String; implementation {$R *.lfm} { TManageForm } procedure TManageForm.SetHash(input: String); begin StationHash := input; end; procedure TManageForm.SetName(input: String); begin StationName := input; end; procedure TManageForm.SetID(input: String); begin StationID := input; end; procedure TManageForm.btnSendMoneyClick(Sender: TObject); var postJson: TJSONObject; moneyToSend: Integer; begin if TryStrToInt(editMoney.Text, Longint(moneyToSend)) = True then begin if (moneyToSend > 0) and (moneyToSend <= 999) then begin postJson := TJSONObject.Create; postJson.Add('hash', TJSONString.Create(StationHash)); postJson.Add('amount', moneyToSend); editMoney.Text := '0'; With TFPHttpClient.Create(Nil) do try try AddHeader('Content-Type', 'application/json'); RequestBody := TStringStream.Create(postJson.AsJSON); Post('http://localhost:8020/add-service-amount'); except end; finally Free; end; end; end; end; procedure TManageForm.FormShow(Sender: TObject); var postJson: TJSONObject; i: Integer; Key: String; Value: String; begin for i := 1 to 6 do begin Key := 'price' + IntToStr(i); postJson := TJSONObject.Create; postJson.Add('hash', TJSONString.Create(StationHash)); postJson.Add('key', TJSONString.Create(Key)); With TFPHttpClient.Create(Nil) do try AddHeader('Content-Type', 'application/json'); RequestBody := TStringStream.Create(postJson.AsJSON); RequestAnswer := Post('http://localhost:8020/load'); Value := RequestAnswer.Substring(1,RequestAnswer.Length-3); PricesData.Cells[i, 1] := Value; finally Free; end; end; end; procedure TManageForm.PricesDataEditingDone(Sender: TObject); var valueInsideText: Integer; postJson: TJSONObject; keyPairJson: TJSONObject; i: Integer; valueFromGrid: Integer; Key: String; begin valueInsideText := -1; if TryStrToInt(PricesData.Cells[PricesData.Col, PricesData.Row], Longint(valueInsideText)) then begin if valueInsideText > 99 then PricesData.Cells[PricesData.Col, PricesData.Row] := IntToStr(99); if valueInsideText < 10 then PricesData.Cells[PricesData.Col, PricesData.Row] := IntToStr(10); end else begin PricesData.Cells[PricesData.Col, PricesData.Row] := IntToStr(10); end; i := PricesData.Col; Key := 'price' + IntToStr(i); valueFromGrid := -1; // Numeric value in grid cell check if TryStrToInt(PricesData.Cells[i, 1], Longint(valueFromGrid)) then begin postJson := TJSONObject.Create; keyPairJson := TJSONObject.Create; postJson.Add('hash', TJSONString.Create(StationHash)); keyPairJson.Add('key', TJSONString.Create(Key)); keyPairJson.Add('value', TJSONString.Create(PricesData.Cells[i, 1])); postJson.Add('KeyPair', keyPairJson); With TFPHttpClient.Create(Nil) do try AddHeader('Content-Type', 'application/json'); RequestBody := TStringStream.Create(postJson.AsJSON); Post('http://localhost:8020/save'); finally Free; end; end; end; end.
unit USWinEvents; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, Buttons, ExtCtrls, ClipBrd, Dialogs; type TCrpeWindowEventsDlg = class(TForm) SaveDialog1: TSaveDialog; pnlBottom: TPanel; pnlUpper: TPanel; pnlTopEdge: TPanel; memoWindowEvents: TMemo; pnlRightEdge: TPanel; pnlLeftEdge: TPanel; pnlBBar2: TPanel; sbActivatedEvents: TSpeedButton; sbClear: TSpeedButton; sbCut: TSpeedButton; sbCopy: TSpeedButton; sbPaste: TSpeedButton; sbSaveToFile: TSpeedButton; btnOk: TButton; procedure sbActivatedEventsClick(Sender: TObject); procedure sbClearClick(Sender: TObject); procedure sbCutClick(Sender: TObject); procedure sbCopyClick(Sender: TObject); procedure sbPasteClick(Sender: TObject); procedure sbSaveToFileClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var CrpeWindowEventsDlg : TCrpeWindowEventsDlg; bWindowEventsDlg : Boolean; implementation uses UCrpeUtl, USActvEvents, UnitMain; {$R *.DFM} {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.FormCreate(Sender: TObject); begin LoadFormSize(Self); bWindowEventsDlg := True; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.FormShow(Sender: TObject); begin memoWindowEvents.Clear; end; {------------------------------------------------------------------------------} { sbActivatedEventsClick } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.sbActivatedEventsClick(Sender: TObject); begin CrpeActiveEventsDlg := TCrpeActiveEventsDlg.Create(Application); CrpeActiveEventsDlg.ShowModal; end; {------------------------------------------------------------------------------} { sbClearClick } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.sbClearClick(Sender: TObject); begin memoWindowEvents.Clear; end; {------------------------------------------------------------------------------} { sbCutClick } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.sbCutClick(Sender: TObject); begin memoWindowEvents.CutToClipboard; end; {------------------------------------------------------------------------------} { sbCopyClick } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.sbCopyClick(Sender: TObject); begin memoWindowEvents.CopyToClipboard; end; {------------------------------------------------------------------------------} { sbPasteClick } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.sbPasteClick(Sender: TObject); begin if Clipboard.HasFormat(CF_TEXT) then memoWindowEvents.PasteFromClipboard; end; {------------------------------------------------------------------------------} { sbSaveToFileClick } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.sbSaveToFileClick(Sender: TObject); begin SaveDialog1.Title := 'Save Window Events List...'; SaveDialog1.FileName := '*.txt'; SaveDialog1.Filter := 'Text files (*.TXT)|*.txt|All files (*.*)|*.*'; if SaveDialog1.Execute then memoWindowEvents.Lines.SaveToFile(SaveDialog1.FileName); end; {------------------------------------------------------------------------------} { btnOKClick } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.btnOKClick(Sender: TObject); begin SaveFormSize(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeWindowEventsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bWindowEventsDlg := False; Release; end; end.
unit IdServerWebsocketContext; interface uses Classes, IdCustomTCPServer, IdIOHandlerWebsocket, IdServerBaseHandling, IdServerSocketIOHandling, IdContext, IdIOHandlerStack; type TIdServerWSContext = class; TWebsocketChannelRequest = procedure(const AContext: TIdServerWSContext; aType: TWSDataType; const strmRequest, strmResponse: TMemoryStream) of object; TIdServerWSContext = class(TIdServerContext) private FWebSocketKey: string; FWebSocketVersion: Integer; FPath: string; FWebSocketProtocol: string; FResourceName: string; FOrigin: string; FQuery: string; FHost: string; FWebSocketExtensions: string; FCookie: string; //FSocketIOPingSend: Boolean; FOnCustomChannelExecute: TWebsocketChannelRequest; FSocketIO: TIdServerSocketIOHandling; FOnDestroy: TIdContextEvent; public function IOHandler: TIdIOHandlerStack; function WebsocketImpl: TWebsocketImplementationProxy; public function IsSocketIO: Boolean; property SocketIO: TIdServerSocketIOHandling read FSocketIO write FSocketIO; //property SocketIO: TIdServerBaseHandling read FSocketIO write FSocketIO; property OnDestroy: TIdContextEvent read FOnDestroy write FOnDestroy; public destructor Destroy; override; property Path : string read FPath write FPath; property Query : string read FQuery write FQuery; property ResourceName: string read FResourceName write FResourceName; property Host : string read FHost write FHost; property Origin : string read FOrigin write FOrigin; property Cookie : string read FCookie write FCookie; property WebSocketKey : string read FWebSocketKey write FWebSocketKey; property WebSocketProtocol : string read FWebSocketProtocol write FWebSocketProtocol; property WebSocketVersion : Integer read FWebSocketVersion write FWebSocketVersion; property WebSocketExtensions: string read FWebSocketExtensions write FWebSocketExtensions; public property OnCustomChannelExecute: TWebsocketChannelRequest read FOnCustomChannelExecute write FOnCustomChannelExecute; end; implementation uses StrUtils; { TIdServerWSContext } destructor TIdServerWSContext.Destroy; begin if Assigned(OnDestroy) then OnDestroy(Self); inherited; end; function TIdServerWSContext.IOHandler: TIdIOHandlerStack; begin Result := Self.Connection.IOHandler as TIdIOHandlerStack; end; function TIdServerWSContext.IsSocketIO: Boolean; begin //FDocument = '/socket.io/1/websocket/13412152' Result := StartsText('/socket.io/1/websocket/', FPath); end; function TIdServerWSContext.WebsocketImpl: TWebsocketImplementationProxy; begin Result := (IOHandler as IWebsocketFunctions).WebsocketImpl; end; end.
unit AddGameList; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, bsSkinData, BusinessSkinForm, ExtCtrls, RzPanel, StdCtrls, RzLabel, Mask, RzEdit, bsSkinCtrls, bsSkinBoxCtrls; type TAddGameListFrm = class(TForm) bsBusinessSkinForm1: TbsBusinessSkinForm; bsSkinData1: TbsSkinData; bsCompressedStoredSkin1: TbsCompressedStoredSkin; RzGroupBox1: TRzGroupBox; RzLabel1: TRzLabel; RzLabel2: TRzLabel; RzLabel3: TRzLabel; RzLabel4: TRzLabel; RzLabel5: TRzLabel; RzLabel6: TRzLabel; ServerNameEdt: TRzEdit; ServerIPEdt: TRzEdit; ServerNoticeURLEdt: TRzEdit; ServerHomeURLEdt: TRzEdit; ServerArrayEdt: TbsSkinComboBox; ServerPortEdt: TbsSkinSpinEdit; OK: TbsSkinButton; Cancel: TbsSkinButton; procedure CancelClick(Sender: TObject); procedure OKClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); private { Private declarations } procedure Clear(); function Check():Boolean; public { Public declarations } procedure Add(); procedure Change(ServerArray,ServerName,ServerIp,ServerPort,ServerNoticeURL,ServerHomeURL:String); end; var AddGameListFrm: TAddGameListFrm; WirteType: Integer; implementation uses Main; {$R *.dfm} function TAddGameListFrm.Check():Boolean; var I: Integer; begin if ServerArrayEdt.items[ServerArrayEdt.ItemIndex] = '' then begin MainFrm.Mes.MessageDlg('请选择服务器分组',mtInformation,[mbOK],0); ServerArrayEdt.SetFocus; Result:=FALSE; exit; end; if ServerNameEdt.Text = '' then begin MainFrm.Mes.MessageDlg('请添写服务器名称',mtInformation,[mbOK],0); ServerNameEdt.SetFocus; Result:=FALSE; exit; end; for I:=1 to Length(ServerNameEdt.Text) do begin if ServerNameEdt.Text[I] in ['\','/',':','*','?','"','<','>','|'] then begin Application.MessageBox('服务器名称不能包含下列任何字符之一:' + #13#10 + ' \/:*?"<>|', '提示', MB_OK + MB_ICONINFORMATION); ServerNameEdt.SetFocus; Result:=False; Exit; end; end; if ServerIpEdt.Text = '' then begin MainFrm.Mes.MessageDlg('请添写服务器IP地址',mtInformation,[mbOK],0); ServerIpEdt.SetFocus; Result:=FALSE; exit; end; if ServerPortEdt.Text = '' then begin MainFrm.Mes.MessageDlg('请添写服务器端口',mtInformation,[mbOK],0); ServerPortEdt.SetFocus; Result:=FALSE; exit; end; if ServerNoticeURLEdt.Text = '' then begin MainFrm.Mes.MessageDlg('请添写服务器公告地址',mtInformation,[mbOK],0); ServerNoticeURLEdt.SetFocus; Result:=FALSE; exit; end; if ServerHomeURLEdt.Text = '' then begin MainFrm.Mes.MessageDlg('请添写服务器主页地址',mtInformation,[mbOK],0); ServerHomeURLEdt.SetFocus; Result:=FALSE; exit; end; Result:=TRUE; end; procedure TAddGameListFrm.Clear(); begin ServerArrayEdt.Items.Clear; ServerNameEdt.Text := ''; ServerIpEdt.Text := ''; ServerNoticeURLEdt.Text := ''; ServerHomeURLEdt.Text := ''; end; procedure TAddGameListFrm.Add(); begin Caption := '增加服务器列表'; Clear(); ServerArrayEdt.Items.Text := MainFrm.ComboBox1.Items.Text; ServerArrayEdt.ItemIndex := 0; WirteType := 0; ShowModal; end; procedure TAddGameListFrm.Change(ServerArray,ServerName,ServerIp,ServerPort,ServerNoticeURL,ServerHomeURL:String); begin Caption := '修改服务器列表'; Clear(); ServerPortEdt.Text := ''; ServerNameEdt.Text := ServerName; ServerIpEdt.Text := ServerIp; ServerPortEdt.Text := ServerPort; ServerNoticeURLEdt.Text := ServerNoticeURL; ServerHomeURLEdt.Text := ServerHomeURL; ServerArrayEdt.Items.Text := MainFrm.ComboBox1.Items.Text; ServerArrayEdt.ItemIndex := ServerArrayEdt.Items.IndexOf(ServerArray); WirteType:=1; ShowModal; end; procedure TAddGameListFrm.CancelClick(Sender: TObject); begin Close; end; procedure TAddGameListFrm.OKClick(Sender: TObject); begin if Check() then begin case WirteType of 0:MainFrm.AddListView(ServerArrayEdt.Text,ServerNameEdt.Text,ServerIPEdt.Text,ServerPortEdt.Text,ServerNoticeURLEdt.Text,ServerHomeURLEdt.Text); 1:MainFrm.ChangeListView(ServerArrayEdt.Text,ServerNameEdt.Text,ServerIPEdt.Text,ServerPortEdt.Text,ServerNoticeURLEdt.Text,ServerHomeURLEdt.Text); end; Close; end; end; procedure TAddGameListFrm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TAddGameListFrm.FormDestroy(Sender: TObject); begin AddGameListFrm := nil; end; end.
{******************************************************************************* * uLabeledFControl * * * * Библиотека компонентов для работы с формой редактирования (qFControls) * * Базовый класс для компонента с надписью слева (TqFLabeledControl) * * Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет * *******************************************************************************} unit uLabeledFControl; interface uses SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics; type TqFLabeledControl = class(TqFControl) protected IsCreated: Boolean; FLabel: TLabel; procedure PrepareLabel; procedure SetLabelPosition; virtual; procedure SetDisplayName(Name: String); override; procedure SetLabelColor(Color: TColor); override; procedure SetSemicolon(Val: Boolean); override; procedure SetAsterisk(Val: Boolean); override; procedure SetRequired(Val: Boolean); override; procedure SetInterval(Int: Integer); override; procedure Resize; override; procedure PrepareRest; virtual; public constructor Create(AOwner: TComponent); override; procedure ShowFocus; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; end; implementation uses Types, qFStrings; constructor TqFLabeledControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FLabel := TLabel.Create(Self); FLabel.Parent := Self; PrepareLabel; IsCreated := True; end; procedure TqFLabeledControl.ShowFocus; var p: TPoint; begin inherited ShowFocus; p.X := qFMouseX + Interval; p.Y := qFMouseY; Mouse.CursorPos := FLabel.ClientToScreen(p); end; procedure TqFLabeledControl.Resize; begin inherited Resize; PrepareRest; Repaint; end; procedure TqFLabeledControl.SetInterval(Int: Integer); begin inherited SetInterval(Int); PrepareRest; end; procedure TqFLabeledControl.SetLabelPosition; begin FLabel.Top := (Height - FLabel.Height) div 2; end; procedure TqFLabeledControl.PrepareLabel; begin FLabel.Font := Font; FLabel.Font.Color := LabelColor; SetLabelPosition; FLabel.Caption := DisplayName; if Semicolon then FLabel.Caption := FLabel.Caption + ':'; if Asterisk then if Required then FLabel.Caption := '* ' + FLabel.Caption else FLabel.Caption := ' ' + FLabel.Caption else FLabel.Caption := ' ' + FLabel.Caption; end; procedure TqFLabeledControl.SetDisplayName(Name: String); begin inherited SetDisplayName(Name); PrepareLabel; end; procedure TqFLabeledControl.SetRequired(Val: Boolean); begin inherited SetRequired(Val); PrepareLabel; end; procedure TqFLabeledControl.SetSemicolon(Val: Boolean); begin inherited SetSemicolon(Val); PrepareLabel; end; procedure TqFLabeledControl.SetAsterisk(Val: Boolean); begin inherited SetAsterisk(Val); PrepareLabel; end; procedure TqFLabeledControl.SetLabelColor(Color: TColor); begin inherited SetLabelColor(Color); PrepareLabel; end; procedure TqFLabeledControl.PrepareRest; begin end; procedure TqFLabeledControl.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; if IsCreated then PrepareRest; end; end.
//Autor Bajenov Andrey //All right reserved. //Saint-Petersburg, Russia //2007.02.03 //neyro@mail.ru //DreamChat is published under a double license. You can choose which one fits //better for you, either Mozilla Public License (MPL) or Lesser General Public //License (LGPL). For more info about MPL read the MPL homepage. For more info //about LGPL read the LGPL homepage. unit DChatCommPlugin; interface uses Windows, Messages, SysUtils, Classes, DChatPlugin; type TLoadErrorEvent = procedure(Sender: TObject; ErrorMess: string) of object; type TInitFunction = function (ModuleHandle: HMODULE; pCallBackFunction:pointer; ExePath:PChar):PChar; TShutDownFunction = function ():PChar; TSendCommDisconnect = function (pProtoName, pNameOfLocalComputer, pNameOfRemoteComputer, pLineName:PChar):Pchar; TSendCommConnect = function (pProtoName, pLocalNickName, pNetbiosNameOfRemoteComputer, pLineName,pNameOfRemoteComputer, pMessageStatusX:PChar; Status:Byte):Pchar; TSendCommText = function (pProtoName, pNameOfRemoteComputer:PChar;pNickNameOfRemoteComputer:PChar;MessageText:PChar; ChatLine:Pchar;Increment:integer):Pchar; TSendCommReceived = function (pProtoName, pNameOfRemoteComputer:PChar;MessAboutReceived:PChar):Pchar; TSendCommStatus = function (pProtoName, pNameOfRemoteComputer:PChar;LocalUserStatus:cardinal;StatusMessage:Pchar):Pchar; TSendCommBoard = function (pProtoName, pNameOfRemoteComputer:PChar;pMessageBoard:Pchar;MaxSizeOfPart:cardinal):Pchar; TSendCommRefresh = function (pProtoName, pNameOfRemoteComputer, pLineName, pLocalNickName:Pchar;LocalUserStatus:cardinal;pAwayMess:Pchar;pReceiver:Pchar;Increment:integer):Pchar; TSendCommRename = function (pProtoName, pNameOfRemoteComputer:Pchar;pNewNickNameMess:Pchar):Pchar; TSetVersion = function (Version:PChar):PChar; TGetIncomingMessageCount = function ():cardinal; TGetNextIncomingMessage = function (BufferForMessage:Pointer; BufferSize:cardinal):cardinal; TSendCommCreate = function (pProtoName, pNameOfRemoteComputer, pPrivateChatLineName:Pchar):Pchar; TGetIP = function ():PChar; TSendCommCreateLine = function (pProtoName, pNameOfRemoteComputer, pPrivateChatLineName, pPassword:Pchar):Pchar; TSendCommStatus_Req = function (pProtoName, pNetbiosNameOfRemoteComputer:PChar):Pchar; TSendCommMe = function (pProtoName, pNameOfRemoteComputer:PChar;pNickNameOfRemoteComputer:PChar;MessageText:PChar; ChatLine:Pchar;Increment:integer):Pchar; type TDChatCommPlugin = class(TDChatPlugin) private { Private declarations } FOnErrorLoading: TLoadErrorEvent; FOnErrorGetProc: TLoadErrorEvent; public { Public declarations } CommunicationInit : TInitFunction; CommunicationShutDown : TShutDownFunction; SendCommDisconnect : TSendCommDisconnect; SendCommConnect : TSendCommConnect; SendCommText : TSendCommText; SendCommReceived : TSendCommReceived; SendCommStatus : TSendCommStatus; SendCommBoard : TSendCommBoard; SendCommRefresh : TSendCommRefresh; SendCommRename : TSendCommRename; SetVersion : TSetVersion; GetIncomingMessageCount : TGetIncomingMessageCount; GetNextIncomingMessage : TGetNextIncomingMessage; SendCommCreate : TSendCommCreate; GetLocalIP : TGetIP; SendCommCreateLine : TSendCommCreateLine; SendCommStatus_Req : TSendCommStatus_Req; SendCommMe : TSendCommMe; //FUNCTION CallBackFunction(Buffer:Pchar; Destination:cardinal):PChar; property OnErrorLoading: TLoadErrorEvent read FOnErrorLoading write FOnErrorLoading; property OnErrorGetProc: TLoadErrorEvent read FOnErrorGetProc write FOnErrorGetProc; constructor Create(NativePlugin: TDChatPlugin); destructor Destroy; override; end; implementation FUNCTION {TDChatCommPlugin.}CallBackFunction(Buffer:Pchar; Destination:cardinal):PChar; BEGIN //DLL может вызвать эту функцию когда ей захочется result := Buffer; END; Constructor TDChatCommPlugin.Create(NativePlugin: TDChatPlugin); var ErrorMess: string; Begin //тут мы получаем плагин-предок этого типа. //нам надо создать объект более высокого класса, но и заполнить свойства //от уже существующего предка. //и так, если в конструкторе происходит исключение, то выполнение конструктора прерывается // и управление передается сразу на END конструктора. inherited Create(NativePlugin.Path + NativePlugin.Filename); // self.GetPluginType := NativePlugin.GetPluginType; self.GetPluginInfo := NativePlugin.GetPluginInfo; self.PluginInfo := NativePlugin.PluginInfo; self.Filename := NativePlugin.Filename; self.Path := NativePlugin.Path; self.DLLHandle := NativePlugin.DLLHandle; CommunicationInit := GetProcAddress(DLLHandle, 'Init'); if not Assigned(CommunicationInit) then raise EExportFunctionError.Create('Error GetProcAddress of CommunicationInit in Plug-in "' + FileName + '"'); CommunicationShutDown := GetProcAddress(DLLHandle, 'ShutDown'); if not Assigned(CommunicationShutDown) then raise EExportFunctionError.Create('Error GetProcAddress of CommunicationShutDown in Plug-in "' + FileName + '"'); SendCommDisconnect := GetProcAddress(DLLHandle, 'SendCommDisconnect'); if not Assigned(SendCommDisconnect) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommDisconnect in Plug-in "' + FileName + '"'); SendCommConnect := GetProcAddress(DLLHandle, 'SendCommConnect'); if not Assigned(SendCommConnect) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommConnect in Plug-in "' + FileName + '"'); SendCommText := GetProcAddress(DLLHandle, 'SendCommText'); if not Assigned(SendCommText) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommText in Plug-in "' + FileName + '"'); SendCommReceived := GetProcAddress(DLLHandle, 'SendCommReceived'); if not Assigned(SendCommReceived) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommReceived in Plug-in "' + FileName + '"'); SendCommStatus := GetProcAddress(DLLHandle, 'SendCommStatus'); if not Assigned(SendCommStatus) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommStatus in Plug-in "' + FileName + '"'); SendCommBoard := GetProcAddress(DLLHandle, 'SendCommBoard'); if not Assigned(SendCommBoard) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommBoard in Plug-in "' + FileName + '"'); SendCommRefresh := GetProcAddress(DLLHandle, 'SendCommRefresh'); if not Assigned(SendCommRefresh) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommRefresh in Plug-in "' + FileName + '"'); SendCommRename := GetProcAddress(DLLHandle, 'SendCommRename'); if not Assigned(SendCommRename) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommRename in Plug-in "' + FileName + '"'); SetVersion := GetProcAddress(DLLHandle, 'SetVersion'); if not Assigned(SetVersion) then raise EExportFunctionError.Create('Error GetProcAddress of SetVersion in Plug-in "' + FileName + '"'); GetIncomingMessageCount := GetProcAddress(DLLHandle, 'GetIncomingMessageCount'); if not Assigned(GetIncomingMessageCount) then raise EExportFunctionError.Create('Error GetProcAddress of GetIncomingMessageCount in Plug-in "' + FileName + '"'); GetNextIncomingMessage := GetProcAddress(DLLHandle, 'GetNextIncomingMessage'); if not Assigned(GetNextIncomingMessage) then raise EExportFunctionError.Create('Error GetProcAddress of GetNextIncomingMessage in Plug-in "' + FileName + '"'); SendCommCreate := GetProcAddress(DLLHandle, 'SendCommCreate'); if not Assigned(SendCommCreate) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommCreate in Plug-in "' + FileName + '"'); GetLocalIP := GetProcAddress(DLLHandle, 'GetIP'); if not Assigned(GetLocalIP) then raise EExportFunctionError.Create('Error GetProcAddress of GetIP in Plug-in "' + FileName + '"'); SendCommCreateLine := GetProcAddress(DLLHandle, 'SendCommCreateLine'); if not Assigned(SendCommCreateLine) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommCreateLine in Plug-in "' + FileName + '"'); SendCommStatus_Req := GetProcAddress(DLLHandle, 'SendCommStatus_Req'); if not Assigned(SendCommStatus_Req) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommStatus_Req in Plug-in "' + FileName + '"'); SendCommMe := GetProcAddress(DLLHandle, 'SendCommMe'); if not Assigned(SendCommMe) then raise EExportFunctionError.Create('Error GetProcAddress of SendCommMe in Plug-in "' + FileName + '"'); //ErrorMessage := CommunicationInit(CommunicationLibHandle, @CallBackFunction, PChar(ExePath)); CommunicationInit(self.DLLHandle, @CallBackFunction, PChar(self.Path)); End; Destructor TDChatCommPlugin.Destroy; {override;} Begin inherited Destroy; //MessageBox(0, PChar('TDChatTestPlugin.Destroy'), PChar(IntToStr(0)), MB_OK); End; {как из DLL получить полный путь до нее procedure ShowDllPath stdcall; var TheFileName: array[0..MAX_PATH] of char; begin FillChar(TheFileName, sizeof(TheFileName), #0); GetModuleFileName(hInstance, TheFileName, sizeof(TheFileName)); MessageBox(0, TheFileName, ?The DLL file name is:?, mb_ok); end;} end.
unit uClienteModel; interface uses System.SysUtils; type TCliente = class private FID: Integer; FNome: string; FDocumento: string; FTipo: string; FTelefone: string; procedure SetNome(const Value: string); public property ID: Integer read FID write FID; property Nome: string read FNome write FNome; property Tipo: string read FTipo write FTipo; property Documento: string read FDocumento write FDocumento; property Telefone: string read FTelefone write FTelefone; end; implementation { TCliente } procedure TCliente.SetNome(const Value: string); begin if Value = EmptyStr then raise Exception.Create('''Nome'' precisa ser preenchido.'); FNome := Value; end; end.
unit USPreview; interface uses Windows, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls, SysUtils, ComCtrls, UCrpe32; type TCrpePreviewDlg = class(TForm) cbKeepOpen: TCheckBox; btnPreview: TBitBtn; pnlPreview: TPanel; btnWindowZoom: TButton; btnWindowStyle: TButton; btnWindowButtonBar: TButton; btnWindowCursor: TBitBtn; btnWindowSize: TButton; btnOk: TButton; btnCancel: TButton; cbWindowEvents: TCheckBox; rgInterfaceStyle: TRadioGroup; rgDialogHandle: TRadioGroup; rgWindowState: TRadioGroup; cbSetFocus: TCheckBox; btnHideWindow: TButton; btnShowWindow: TButton; btnCloseWindow: TButton; editSearch: TEdit; sbSearch: TSpeedButton; procedure rgInterfaceStyleClick(Sender: TObject); procedure btnPreviewClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure rgWindowStateClick(Sender: TObject); procedure UpdatePreviewForm; procedure FormShow(Sender: TObject); procedure cbWindowEventsClick(Sender: TObject); procedure btnWindowCursorClick(Sender: TObject); procedure btnHideWindowClick(Sender: TObject); procedure btnShowWindowClick(Sender: TObject); procedure btnCloseWindowClick(Sender: TObject); procedure cbSetFocusClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnWindowButtonBarClick(Sender: TObject); procedure btnWindowSizeClick(Sender: TObject); procedure btnWindowStyleClick(Sender: TObject); procedure btnWindowZoomClick(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure editSearchKeyPress(Sender: TObject; var Key: Char); procedure sbSearchClick(Sender: TObject); procedure editSearchEnter(Sender: TObject); procedure editSearchExit(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; end; var CrpePreviewDlg: TCrpePreviewDlg; bPreview : boolean; implementation {$R *.DFM} uses UnitMain, UCrpeUtl, USWinEvents, UDWindowParent, UDWindowCursor, UDWindowButtonBar, UDWindowSize, UDWindowStyle, UDWindowZoom; {------------------------------------------------------------------------------} { FormCreate procedure } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.FormCreate(Sender: TObject); begin bPreview := True; LoadFormPos(Self); btnOk.Tag := 1; btnCancel.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow procedure } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.FormShow(Sender: TObject); begin rgInterfaceStyle.ItemIndex := 0; rgDialogHandle.ItemIndex := 0; rgDialogHandle.Enabled := False; cbWindowEvents.Enabled := (Cr.Version.Crpe.Major > 5); btnWindowCursor.Enabled := (Cr.Version.Crpe.Major > 5); {Reset items for non-Parent Window} rgInterfaceStyleClick(Self); UpdatePreviewForm; end; {------------------------------------------------------------------------------} { UpdatePreviewForm procedure } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.UpdatePreviewForm; var OnOff : boolean; begin {Enable/Disable controls} OnOff := not IsStrEmpty(Cr.ReportName); InitializeControls(OnOff); if OnOff then begin {WindowState} case Cr.WindowState of wsNormal : rgWindowState.ItemIndex := 2; wsMinimized : rgWindowState.ItemIndex := 1; wsMaximized : rgWindowState.ItemIndex := 0; end; {WindowEvents} cbWindowEvents.Checked := Cr.WindowEvents; end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TBitBtn then TBitBtn(Components[i]).Enabled := OnOff; end; end; end; {------------------------------------------------------------------------------} { Interface Style } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.rgInterfaceStyleClick(Sender: TObject); begin case rgInterfaceStyle.ItemIndex of 0: begin rgDialogHandle.Enabled := False; Cr.WindowButtonBar.Visible := True; Cr.WindowStyle.BorderStyle := bsSizeable; Cr.WindowStyle.SystemMenu := True; end; 1: begin rgDialogHandle.Enabled := True; Cr.WindowButtonBar.Visible := False; Cr.WindowStyle.BorderStyle := bsNone; Cr.WindowStyle.SystemMenu := False; end; end; end; {------------------------------------------------------------------------------} { WindowState } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.rgWindowStateClick(Sender: TObject); begin case rgWindowState.ItemIndex of 0: Cr.WindowState := wsMaximized; 1: Cr.WindowState := wsMinimized; 2: Cr.WindowState := wsNormal; end; end; {------------------------------------------------------------------------------} { WindowEvents } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.cbWindowEventsClick(Sender: TObject); begin Cr.WindowEvents := cbWindowEvents.Checked; if Cr.WindowEvents then begin Cr.wOnCloseWindow := frmMain.Crpe1wOnCloseWindow; Cr.wOnPrintBtnClick := frmMain.Crpe1wOnPrintBtnClick; Cr.wOnExportBtnClick := frmMain.Crpe1wOnExportBtnClick; Cr.wOnFirstPageBtnClick := frmMain.Crpe1wOnFirstPageBtnClick; Cr.wOnPreviousPageBtnClick := frmMain.Crpe1wOnPreviousPageBtnClick; Cr.wOnNextPageBtnClick := frmMain.Crpe1wOnNextPageBtnClick; Cr.wOnLastPageBtnClick := frmMain.Crpe1wOnLastPageBtnClick; Cr.wOnCancelBtnClick := frmMain.Crpe1wOnCancelBtnClick; Cr.wOnActivateWindow := frmMain.Crpe1wOnActivateWindow; Cr.wOnDeActivateWindow := frmMain.Crpe1wOnDeActivateWindow; Cr.wOnPrintSetupBtnClick := frmMain.Crpe1wOnPrintSetupBtnClick; Cr.wOnRefreshBtnClick := frmMain.Crpe1wOnRefreshBtnClick; Cr.wOnZoomLevelChange := frmMain.Crpe1wOnZoomLevelChange; Cr.wOnCloseBtnClick := frmMain.Crpe1wOnCloseBtnClick; Cr.wOnSearchBtnClick := frmMain.Crpe1wOnSearchBtnClick; Cr.wOnGroupTreeBtnClick := frmMain.Crpe1wOnGroupTreeBtnClick; Cr.wOnReadingRecords := frmMain.Crpe1wOnReadingRecords; Cr.wOnStartEvent := frmMain.Crpe1wOnStartEvent; Cr.wOnStopEvent := frmMain.Crpe1wOnStopEvent; Cr.wOnShowGroup := frmMain.Crpe1wOnShowGroup; Cr.wOnDrillGroup := frmMain.Crpe1wOnDrillGroup; Cr.wOnDrillDetail := frmMain.Crpe1wOnDrillDetail; Cr.wOnMouseClick := frmMain.Crpe1wOnMouseClick; Cr.wOnDrillHyperLink := frmMain.Crpe1wOnDrillHyperLink; Cr.wOnLaunchSeagateAnalysis := frmMain.Crpe1wOnLaunchSeagateAnalysis; end else begin Cr.wOnCloseWindow := nil; Cr.wOnPrintBtnClick := nil; Cr.wOnExportBtnClick := nil; Cr.wOnFirstPageBtnClick := nil; Cr.wOnPreviousPageBtnClick := nil; Cr.wOnNextPageBtnClick := nil; Cr.wOnLastPageBtnClick := nil; Cr.wOnCancelBtnClick := nil; Cr.wOnActivateWindow := nil; Cr.wOnDeActivateWindow := nil; Cr.wOnPrintSetupBtnClick := nil; Cr.wOnRefreshBtnClick := nil; Cr.wOnZoomLevelChange := nil; Cr.wOnCloseBtnClick := nil; Cr.wOnSearchBtnClick := nil; Cr.wOnGroupTreeBtnClick := nil; Cr.wOnReadingRecords := nil; Cr.wOnStartEvent := nil; Cr.wOnStopEvent := nil; Cr.wOnShowGroup := nil; Cr.wOnDrillGroup := nil; Cr.wOnDrillDetail := nil; Cr.wOnMouseClick := nil; Cr.wOnDrillHyperLink := nil; Cr.wOnLaunchSeagateAnalysis := nil; end; end; {------------------------------------------------------------------------------} { btnWindowCursorClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnWindowCursorClick(Sender: TObject); begin if not bWindowCursor then begin CrpeWindowCursorDlg := TCrpeWindowCursorDlg.Create(Application); CrpeWindowCursorDlg.Cr := Cr; end; CrpeWindowCursorDlg.Show; end; {------------------------------------------------------------------------------} { btnWindowButtonBarClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnWindowButtonBarClick(Sender: TObject); begin if not bWindowButtonBar then begin CrpeWindowButtonBarDlg := TCrpeWindowButtonBarDlg.Create(Application); CrpeWindowButtonBarDlg.Cr := Cr; end; CrpeWindowButtonBarDlg.Show; end; {------------------------------------------------------------------------------} { btnWindowSizeClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnWindowSizeClick(Sender: TObject); begin if not bWindowSize then begin CrpeWindowSizeDlg := TCrpeWindowSizeDlg.Create(Application); CrpeWindowSizeDlg.Cr := Cr; end; CrpeWindowSizeDlg.Show; end; {------------------------------------------------------------------------------} { btnWindowStyleClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnWindowStyleClick(Sender: TObject); begin if not bWindowStyle then begin CrpeWindowStyleDlg := TCrpeWindowStyleDlg.Create(Application); CrpeWindowStyleDlg.Cr := Cr; end; CrpeWindowStyleDlg.Show; end; {------------------------------------------------------------------------------} { btnWindowZoomClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnWindowZoomClick(Sender: TObject); begin if not bWindowZoom then begin CrpeWindowZoomDlg := TCrpeWindowZoomDlg.Create(Application); CrpeWindowZoomDlg.Cr := Cr; end; CrpeWindowZoomDlg.Show; end; {------------------------------------------------------------------------------} { Set Focus click } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.cbSetFocusClick(Sender: TObject); begin if cbSetFocus.Checked then begin if not Cr.Focused then Cr.SetFocus; end; end; {------------------------------------------------------------------------------} { editSearchEnter } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.editSearchEnter(Sender: TObject); begin btnOk.Default := False; end; {------------------------------------------------------------------------------} { editSearchExit } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.editSearchExit(Sender: TObject); begin btnOk.Default := True; end; {------------------------------------------------------------------------------} { editSearchKeyPress } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.editSearchKeyPress(Sender: TObject; var Key: Char); begin if Ord(Key) = 13 then sbSearchClick(Self); end; {------------------------------------------------------------------------------} { sbSearchClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.sbSearchClick(Sender: TObject); begin Cr.Search(editSearch.Text); end; {------------------------------------------------------------------------------} { Preview Button } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnPreviewClick(Sender: TObject); var prevOut : TCrOutput; begin SaveFormPos(Self); {WindowEvents} if Cr.WindowEvents = True then begin if not bWindowEventsDlg then CrpeWindowEventsDlg := TCrpeWindowEventsDlg.Create(Application); CrpeWindowEventsDlg.Show; end; {Check Interface Style: Parent or Crystal Window} if rgInterfaceStyle.ItemIndex = 1 then begin {Create Parent Window} if not bWindowParent then begin CrpeWindowParentDlg := TCrpeWindowParentDlg.Create(Application); CrpeWindowParentDlg.Cr := Cr; end; {Size Parent Window from the VCL WindowSize settings} if Cr.WindowSize.Top > -1 then CrpeWindowParentDlg.Top := Cr.WindowSize.Top; if Cr.WindowSize.Left > -1 then CrpeWindowParentDlg.Left := Cr.WindowSize.Left; if Cr.WindowSize.Width > -1 then CrpeWindowParentDlg.Width := Cr.WindowSize.Width; if Cr.WindowSize.Height > -1 then CrpeWindowParentDlg.Height := Cr.WindowSize.Height; {Attach Crystal Window to Parent Window} Cr.WindowParent := CrpeWindowParentDlg; {Set ParentWindow WindowState to Crpe WindowState} CrpeWindowParentDlg.WindowState := Cr.WindowState; {If minimized, set the Crpe Window to Normal} if Cr.WindowState = wsMinimized then Cr.WindowState := wsNormal; {Set Parent Caption to Crpe WindowTitle} CrpeWindowParentDlg.Caption := Cr.WindowStyle.Title; {Crystal Window Size Settings} Cr.WindowSize.Top := CrpeWindowParentDlg.pnlBtnBar.Height; Cr.WindowSize.Left := 0; Cr.WindowSize.Height := CrpeWindowParentDlg.ClientHeight; Cr.WindowSize.Width := CrpeWindowParentDlg.ClientWidth; Cr.WindowStyle.SystemMenu := False; Cr.WindowStyle.BorderStyle := bsNone; {Check Dialog Handle} if rgDialogHandle.ItemIndex = 0 then Cr.DialogParent := nil else Cr.DialogParent := CrpeWindowParentDlg; {Show the Parent Form} CrpeWindowParentDlg.Show; end else begin Cr.WindowParent := nil; Cr.DialogParent := nil; end; {Preserve previous Output setting} prevOut := Cr.Output; {Set Output and Execute} Cr.Output := toWindow; {Run the Report} if Cr.Execute then begin frmMain.btnDiscardSavedData.Enabled := Cr.HasSavedData; frmMain.miDiscardSavedData.Enabled := Cr.HasSavedData; end; {Restore Output setting} Cr.Output := prevOut; if cbSetFocus.Checked then begin if not Cr.Focused then Cr.SetFocus; end; if not cbKeepOpen.Checked then Close; end; {------------------------------------------------------------------------------} { btnHideWindowClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnHideWindowClick(Sender: TObject); begin Cr.HideWindow; end; {------------------------------------------------------------------------------} { btnShowWindowClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnShowWindowClick(Sender: TObject); begin Cr.ShowWindow; end; {------------------------------------------------------------------------------} { btnCloseWindowClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnCloseWindowClick(Sender: TObject); begin Cr.CloseWindow; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpePreviewDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bPreview := False; Release; end; end.
procedure TextDiagon(Const Text: string); // // Gera um texto colorido e na diagonal no form // // deve ser declarada da seguinte forma: // // procedure TForm1.TextDiagon(Const Text: string); // var logfont:TLogFont; font: Thandle; count: integer; begin LogFont.lfheight:=20; logfont.lfwidth:=20; logfont.lfweight:=750; LogFont.lfEscapement:=-200; logfont.lfcharset:=1; logfont.lfoutprecision:=out_tt_precis; logfont.lfquality:=draft_quality; logfont.lfpitchandfamily:=FF_Modern; font:=createfontindirect(logfont); Selectobject(Form1.canvas.handle,font); SetTextColor(Form1.canvas.handle,rgb(0,0,200)); SetBKmode(Form1.canvas.handle,transparent); for count:=1 to 100 do begin canvas.textout(Random(form1.width),Random(form1.height),Text); SetTextColor(form1.canvas.handle,rgb(Random(255),Random(255),Random (255))); end; Deleteobject(font); end;
(* Generate a cave with tunnels *) unit cave; {$mode objfpc}{$H+} {$RANGECHECKS OFF} interface uses globalutils, map, process_cave; type coordinates = record x, y: smallint; end; var r, c, i, p, t, listLength, firstHalf, lastHalf, iterations, tileCounter: smallint; caveArray, tempArray: array[1..globalutils.MAXROWS, 1..globalutils.MAXCOLUMNS] of char; totalRooms, roomSquare: smallint; (* Player starting position *) startX, startY: smallint; (* start creating corridors once this rises above 1 *) roomCounter: smallint; (* TESTING - Write cave to text file *) filename: ShortString; myfile: Text; (* Draw straight line between 2 points *) procedure drawLine(x1, y1, x2, y2: smallint); (* Draw a circular room *) procedure drawCircle(centreX, centreY, radius: smallint); (* Carve a horizontal tunnel *) procedure carveHorizontally(x1, x2, y: smallint); (* Carve a vertical tunnel *) procedure carveVertically(y1, y2, x: smallint); (* Carve corridor between rooms *) procedure createCorridor(fromX, fromY, toX, toY: smallint); (* Create a room *) procedure createRoom(gridNumber: smallint); (* Generate a cave *) procedure generate; (* sort room list in order from left to right *) procedure leftToRight; implementation procedure leftToRight; var i, j, n, tempX, tempY: smallint; begin n := length(globalutils.currentDgncentreList) - 1; for i := n downto 2 do for j := 0 to i - 1 do if globalutils.currentDgncentreList[j].x > globalutils.currentDgncentreList[j + 1].x then begin tempX := globalutils.currentDgncentreList[j].x; tempY := globalutils.currentDgncentreList[j].y; globalutils.currentDgncentreList[j].x := globalutils.currentDgncentreList[j + 1].x; globalutils.currentDgncentreList[j].y := globalutils.currentDgncentreList[j + 1].y; globalutils.currentDgncentreList[j + 1].x := tempX; globalutils.currentDgncentreList[j + 1].y := tempY; end; end; procedure drawLine(x1, y1, x2, y2: smallint); var i, deltax, deltay, numpixels, d, dinc1, dinc2, x, xinc1, xinc2, y, yinc1, yinc2: smallint; begin (* Calculate delta X and delta Y for initialisation *) deltax := abs(x2 - x1); deltay := abs(y2 - y1); (* Initialize all vars based on which is the independent variable *) if deltax >= deltay then begin (* x is independent variable *) numpixels := deltax + 1; d := (2 * deltay) - deltax; dinc1 := deltay shl 1; dinc2 := (deltay - deltax) shl 1; xinc1 := 1; xinc2 := 1; yinc1 := 0; yinc2 := 1; end else begin (* y is independent variable *) numpixels := deltay + 1; d := (2 * deltax) - deltay; dinc1 := deltax shl 1; dinc2 := (deltax - deltay) shl 1; xinc1 := 0; xinc2 := 1; yinc1 := 1; yinc2 := 1; end; (* Make sure x and y move in the right directions *) if x1 > x2 then begin xinc1 := -xinc1; xinc2 := -xinc2; end; if y1 > y2 then begin yinc1 := -yinc1; yinc2 := -yinc2; end; (* Start drawing at *) x := x1; y := y1; (* Draw the pixels *) for i := 1 to numpixels do begin caveArray[y][x] := ':'; if d < 0 then begin d := d + dinc1; x := x + xinc1; y := y + yinc1; end else begin d := d + dinc2; x := x + xinc2; y := y + yinc2; end; end; end; procedure drawCircle(centreX, centreY, radius: smallint); var d, x, y: smallint; begin d := 3 - (2 * radius); x := 0; y := radius; while (x <= y) do begin drawLine(centreX, centreY, centreX + X, centreY + Y); drawLine(centreX, centreY, centreX + X, centreY - Y); drawLine(centreX, centreY, centreX - X, centreY + Y); drawLine(centreX, centreY, centreX - X, centreY - Y); drawLine(centreX, centreY, centreX + Y, centreY + X); drawLine(centreX, centreY, centreX + Y, centreY - X); drawLine(centreX, centreY, centreX - Y, centreY + X); drawLine(centreX, centreY, centreX - Y, centreY - X); if (d < 0) then d := d + (4 * x) + 6 else begin d := d + 4 * (x - y) + 10; y := y - 1; end; Inc(x); end; end; procedure carveHorizontally(x1, x2, y: smallint); var x: byte; begin if x1 < x2 then begin for x := x1 to x2 do caveArray[y][x] := ':'; end; if x1 > x2 then begin for x := x2 to x1 do caveArray[y][x] := ':'; end; end; procedure carveVertically(y1, y2, x: smallint); var y: byte; begin if y1 < y2 then begin for y := y1 to y2 do caveArray[y][x] := ':'; end; if y1 > y2 then begin for y := y2 to y1 do caveArray[y][x] := ':'; end; end; procedure createCorridor(fromX, fromY, toX, toY: smallint); var direction: byte; begin // flip a coin to decide whether to first go horizontally or vertically direction := Random(2); // horizontally first if direction = 1 then begin carveHorizontally(fromX, toX, fromY); carveVertically(fromY, toY, toX); end // vertically first else begin carveVertically(fromY, toY, toX); carveHorizontally(fromX, toX, fromY); end; end; procedure createRoom(gridNumber: smallint); var topLeftX, topLeftY, roomHeight, roomWidth, drawHeight, drawWidth: smallint; begin // initialise variables topLeftX := 0; topLeftY := 0; roomHeight := 0; roomWidth := 0; drawHeight := 0; drawWidth := 0; // row 1 if (gridNumber >= 1) and (gridNumber <= 13) then begin topLeftX := (gridNumber * 5) - 3; topLeftY := 2; end; // row 2 if (gridNumber >= 14) and (gridNumber <= 26) then begin topLeftX := (gridNumber * 5) - 68; topLeftY := 8; end; // row 3 if (gridNumber >= 27) and (gridNumber <= 39) then begin topLeftX := (gridNumber * 5) - 133; topLeftY := 14; end; // row 4 if (gridNumber >= 40) and (gridNumber <= 52) then begin topLeftX := (gridNumber * 5) - 198; topLeftY := 20; end; // row 5 if (gridNumber >= 53) and (gridNumber <= 65) then begin topLeftX := (gridNumber * 5) - 263; topLeftY := 26; end; // row 6 if (gridNumber >= 66) and (gridNumber <= 78) then begin topLeftX := (gridNumber * 5) - 328; topLeftY := 32; end; (* Randomly select room dimensions between 2 - 5 tiles in height / width *) roomHeight := Random(2) + 3; roomWidth := Random(2) + 3; (* Save coordinates of the centre of the room *) listLength := Length(globalutils.currentDgncentreList); SetLength(globalutils.currentDgncentreList, listLength + 1); globalutils.currentDgncentreList[listLength].x := topLeftX + (roomWidth div 2); globalutils.currentDgncentreList[listLength].y := topLeftY + (roomHeight div 2); (* Draw room within the grid square *) drawCircle(globalutils.currentDgncentreList[listLength].x, globalutils.currentDgncentreList[listLength].y, roomHeight); for drawHeight := 0 to roomHeight do begin for drawWidth := 0 to roomWidth do begin caveArray[topLeftY + drawHeight][topLeftX + drawWidth] := ':'; end; end; end; procedure generate; var pillars: byte; begin pillars := 0; roomCounter := 0; // initialise the array SetLength(globalutils.currentDgncentreList, 1); // fill map with walls for r := 1 to globalutils.MAXROWS do begin for c := 1 to globalutils.MAXCOLUMNS do begin caveArray[r][c] := '*'; end; end; for r := 2 to (globalutils.MAXROWS - 1) do begin for c := 2 to (globalutils.MAXCOLUMNS - 1) do begin (* 50% chance of drawing a wall tile *) if (Random(100) <= 50) then caveArray[r][c] := '*' else caveArray[r][c] := ':'; end; end; (* Run through the process 5 times *) for iterations := 1 to 5 do begin for r := 2 to globalutils.MAXROWS - 1 do begin for c := 2 to globalutils.MAXCOLUMNS - 1 do begin (* A tile becomes a wall if it was a wall and 4 or more of its 8 neighbours are walls, or if it was not but 5 or more neighbours were *) tileCounter := 0; if (caveArray[r - 1][c] = '*') then // NORTH Inc(tileCounter); if (caveArray[r - 1][c + 1] = '*') then // NORTH EAST Inc(tileCounter); if (caveArray[r][c + 1] = '*') then // EAST Inc(tileCounter); if (caveArray[r + 1][c + 1] = '*') then // SOUTH EAST Inc(tileCounter); if (caveArray[r + 1][c] = '*') then // SOUTH Inc(tileCounter); if (caveArray[r + 1][c - 1] = '*') then // SOUTH WEST Inc(tileCounter); if (caveArray[r][c - 1] = '*') then // WEST Inc(tileCounter); if (caveArray[r - 1][c - 1] = '*') then // NORTH WEST Inc(tileCounter); (* Set tiles in temporary array *) if (caveArray[r][c] = '*') then begin if (tileCounter >= 4) then tempArray[r][c] := '*' else tempArray[r][c] := ':'; end; if (caveArray[r][c] = ':') then begin if (tileCounter >= 5) then tempArray[r][c] := '*' else tempArray[r][c] := ':'; end; end; end; (* Copy temporary map back to main dungeon map array *) for r := 1 to globalutils.MAXROWS do begin for c := 1 to globalutils.MAXCOLUMNS do begin caveArray[r][c] := tempArray[r][c]; end; end; end; // Random(Range End - Range Start) + Range Start; totalRooms := Random(5) + 10; // between 10 - 15 rooms for i := 1 to totalRooms do begin // randomly choose grid location from 1 to 78 roomSquare := Random(77) + 1; createRoom(roomSquare); Inc(roomCounter); end; leftToRight(); for i := 1 to (totalRooms - 1) do begin createCorridor(globalutils.currentDgncentreList[i].x, globalutils.currentDgncentreList[i].y, globalutils.currentDgncentreList[i + 1].x, globalutils.currentDgncentreList[i + 1].y); end; // connect random rooms so the map isn't totally linear // from the first half of the room list firstHalf := (totalRooms div 2); p := random(firstHalf - 1) + 1; t := random(firstHalf - 1) + 1; createCorridor(globalutils.currentDgncentreList[p].x, globalutils.currentDgncentreList[p].y, globalutils.currentDgncentreList[t].x, globalutils.currentDgncentreList[t].y); // from the second half of the room list lastHalf := (totalRooms - firstHalf); p := random(lastHalf) + firstHalf; t := random(lastHalf) + firstHalf; createCorridor(globalutils.currentDgncentreList[p].x, globalutils.currentDgncentreList[p].y, globalutils.currentDgncentreList[t].x, globalutils.currentDgncentreList[t].y); (* draw top and bottom border *) for i := 1 to globalutils.MAXCOLUMNS do begin caveArray[1][i] := '*'; caveArray[globalutils.MAXROWS][i] := '*'; end; (* draw left and right border *) for i := 1 to globalutils.MAXROWS do begin caveArray[i][1] := '*'; caveArray[i][globalutils.MAXCOLUMNS] := '*'; end; (* Add random pillars *) for pillars := 1 to randomRange(5, 10) do begin // (* Choose random location on the map *) repeat r := globalutils.randomRange(1, MAXROWS); c := globalutils.randomRange(1, MAXCOLUMNS); (* choose a location that is a floor tile surrounded by floor tiles *) until (caveArray[r][c] = ':') and (caveArray[r + 1][c] = ':') and (caveArray[r - 1][c] = ':') and (caveArray[r][c + 1] = ':') and (caveArray[r][c - 1] = ':'); (* Place a pillar *) caveArray[r][c] := '*'; end; (* set player start coordinates, and make sure it isn't a pillar *) caveArray[globalutils.currentDgncentreList[1].y] [globalutils.currentDgncentreList[1].x] := ':'; map.startX := globalutils.currentDgncentreList[1].x; map.startY := globalutils.currentDgncentreList[1].y; ///////////////////////////// // Write map to text file for testing //filename := 'output_cave.txt'; //AssignFile(myfile, filename); //rewrite(myfile); //for r := 1 to MAXROWS do //begin // for c := 1 to MAXCOLUMNS do // begin // Write(myfile, caveArray[r][c]); // end; // Write(myfile, sLineBreak); //end; //closeFile(myfile); ////////////////////////////// process_cave.prettify; ///////////////////////////// // Write map to text file for testing //filename := 'output_processed_cave.txt'; //AssignFile(myfile, filename); //rewrite(myfile); //for r := 1 to MAXROWS do //begin // for c := 1 to MAXCOLUMNS do // begin // Write(myfile, globalutils.dungeonArray[r][c]); // end; // Write(myfile, sLineBreak); //end; //closeFile(myfile); ////////////////////////////// (* Copy total rooms to main dungeon *) globalutils.currentDgnTotalRooms := totalRooms; (* Set flag for type of dungeon *) map.mapType := 0; end; end.
unit uImageZoomHelper; interface uses System.Math, System.Classes, Winapi.Windows, Vcl.StdCtrls, Vcl.ExtCtrls; type TImageZoomHelper = class class procedure ReAlignScrolls(IsCenter: Boolean; FHorizontalScrollBar, FVerticalScrollBar: TScrollBar; Block: TPanel; ImageSize, ClientSize: TSize; Zoom: Double; ZoomerOn: Boolean); class function GetImageVisibleRect(FHorizontalScrollBar, FVerticalScrollBar: TScrollBar; ImageSize, ClientSize: TSize; Zoom: Double): TRect; end; implementation class procedure TImageZoomHelper.ReAlignScrolls(IsCenter: Boolean; FHorizontalScrollBar, FVerticalScrollBar: TScrollBar; Block: TPanel; ImageSize, ClientSize: TSize; Zoom: Double; ZoomerOn: Boolean); var Inc_: Integer; Pos, M, Ps: Integer; V1, V2: Boolean; begin if Block <> nil then Block.Visible := False; if not ZoomerOn then begin FHorizontalScrollBar.Position := 0; FHorizontalScrollBar.Visible := False; FVerticalScrollBar.Position := 0; FVerticalScrollBar.Visible := False; Exit; end; V1 := FHorizontalScrollBar.Visible; V2 := FVerticalScrollBar.Visible; if not FHorizontalScrollBar.Visible and not FVerticalScrollBar.Visible then begin FHorizontalScrollBar.Visible := ImageSize.cx * Zoom > ClientSize.cx; if FHorizontalScrollBar.Visible then Inc_ := FHorizontalScrollBar.Height else Inc_ := 0; FVerticalScrollBar.Visible := ImageSize.cy * Zoom > ClientSize.cy - Inc_; end; begin if FVerticalScrollBar.Visible then Inc_ := FVerticalScrollBar.Width else Inc_ := 0; FHorizontalScrollBar.Visible := ImageSize.cx * Zoom > ClientSize.cx - Inc_; FHorizontalScrollBar.Width := ClientSize.cx - Inc_; if FHorizontalScrollBar.Visible then Inc_ := FHorizontalScrollBar.Height else Inc_ := 0; FHorizontalScrollBar.Top := ClientSize.cy - Inc_; end; begin if FHorizontalScrollBar.Visible then Inc_ := FHorizontalScrollBar.Height else Inc_ := 0; FVerticalScrollBar.Visible := ImageSize.cy * Zoom > ClientSize.cy - Inc_; FVerticalScrollBar.Height := ClientSize.cy - Inc_; if FVerticalScrollBar.Visible then Inc_ := FVerticalScrollBar.Width else Inc_ := 0; FVerticalScrollBar.Left := ClientSize.cx - Inc_; end; begin if FVerticalScrollBar.Visible then Inc_ := FVerticalScrollBar.Width else Inc_ := 0; FHorizontalScrollBar.Visible := ImageSize.cx * Zoom > ClientSize.cx - Inc_; FHorizontalScrollBar.Width := ClientSize.cx - Inc_; if FHorizontalScrollBar.Visible then Inc_ := FHorizontalScrollBar.Height else Inc_ := 0; FHorizontalScrollBar.Top := ClientSize.cy - Inc_; end; if not FHorizontalScrollBar.Visible then FHorizontalScrollBar.Position := 0; if not FVerticalScrollBar.Visible then FVerticalScrollBar.Position := 0; if FHorizontalScrollBar.Visible and not V1 then begin FHorizontalScrollBar.PageSize := 0; FHorizontalScrollBar.Position := 0; FHorizontalScrollBar.Max := 100; FHorizontalScrollBar.Position := 50; end; if FVerticalScrollBar.Visible and not V2 then begin FVerticalScrollBar.PageSize := 0; FVerticalScrollBar.Position := 0; FVerticalScrollBar.Max := 100; FVerticalScrollBar.Position := 50; end; if Block <> nil then begin Block.Width := FVerticalScrollBar.Width; Block.Height := FHorizontalScrollBar.Height; Block.Left := ClientSize.cx - Block.Width; Block.Top := ClientSize.cy - Block.Height; Block.Visible := FHorizontalScrollBar.Visible and FVerticalScrollBar.Visible; end; if FHorizontalScrollBar.Visible then begin if FVerticalScrollBar.Visible then Inc_ := FVerticalScrollBar.Width else Inc_ := 0; M := Round(ImageSize.cx * Zoom); Ps := ClientSize.cx - Inc_; if Ps > M then Ps := 0; if (FHorizontalScrollBar.Max <> FHorizontalScrollBar.PageSize) then Pos := Round(FHorizontalScrollBar.Position * ((M - Ps) / (FHorizontalScrollBar.Max - FHorizontalScrollBar.PageSize))) else Pos := FHorizontalScrollBar.Position; if M < FHorizontalScrollBar.PageSize then FHorizontalScrollBar.PageSize := Ps; FHorizontalScrollBar.Max := M; FHorizontalScrollBar.PageSize := Ps; FHorizontalScrollBar.LargeChange := Ps div 10; FHorizontalScrollBar.Position := Min(FHorizontalScrollBar.Max, Pos); end; if FVerticalScrollBar.Visible then begin if FHorizontalScrollBar.Visible then Inc_ := FHorizontalScrollBar.Height else Inc_ := 0; M := Round(ImageSize.cy * Zoom); Ps := ClientSize.cy - Inc_; if Ps > M then Ps := 0; if FVerticalScrollBar.Max <> FVerticalScrollBar.PageSize then Pos := Round(FVerticalScrollBar.Position * ((M - Ps) / (FVerticalScrollBar.Max - FVerticalScrollBar.PageSize))) else Pos := FVerticalScrollBar.Position; if M < FVerticalScrollBar.PageSize then FVerticalScrollBar.PageSize := Ps; FVerticalScrollBar.Max := M; FVerticalScrollBar.PageSize := Ps; FVerticalScrollBar.LargeChange := Ps div 10; FVerticalScrollBar.Position := Min(FVerticalScrollBar.Max, Pos); end; if FHorizontalScrollBar.Position > FHorizontalScrollBar.Max - FHorizontalScrollBar.PageSize then FHorizontalScrollBar.Position := FHorizontalScrollBar.Max - FHorizontalScrollBar.PageSize; if FVerticalScrollBar.Position > FVerticalScrollBar.Max - FVerticalScrollBar.PageSize then FVerticalScrollBar.Position := FVerticalScrollBar.Max - FVerticalScrollBar.PageSize; end; class function TImageZoomHelper.GetImageVisibleRect(FHorizontalScrollBar, FVerticalScrollBar: TScrollBar; ImageSize, ClientSize: TSize; Zoom: Double): TRect; var Increment: Integer; FX, FY, FH, FW: Integer; begin if FHorizontalScrollBar.Visible then begin FX := 0; end else begin if FVerticalScrollBar.Visible then Increment := FVerticalScrollBar.width else Increment := 0; FX := Max(0, Round(ClientSize.cx / 2 - Increment - ImageSize.cx * Zoom / 2)); end; if FVerticalScrollBar.Visible then begin FY := 0; end else begin if FHorizontalScrollBar.Visible then Increment := FHorizontalScrollBar.Height else Increment := 0; FY := Max(0, Round(ClientSize.cy / 2 - Increment - ImageSize.cy * Zoom / 2)); end; if FVerticalScrollBar.Visible then Increment := FVerticalScrollBar.width else Increment := 0; FW := Round(Min(ClientSize.cx - Increment, ImageSize.cx * Zoom)); if FHorizontalScrollBar.Visible then Increment := FHorizontalScrollBar.Height else Increment := 0; FH := Round(Min(ClientSize.cy - Increment, ImageSize.cy * Zoom)); FH := FH; Result := Rect(FX, FY, FW + FX, FH + FY); end; end.
{======================================================================================================================= ComboBoxesFrame Unit Raize Components - Demo Program Source Unit Copyright © 1995-2015 by Raize Software, Inc. All Rights Reserved. =======================================================================================================================} {$I RCDemo.inc} unit ComboBoxesFrame; interface uses Forms, RzPanel, RzRadGrp, RzCmboBx, Controls, StdCtrls, RzLabel, RzRadChk, RzButton, Classes, ExtCtrls, RzCommon, RzBorder, ImgList, RzStatus; type TFmeComboBoxes = class(TFrame) grpTRzComboBox: TRzGroupBox; cbxStandard: TRzComboBox; optDropDown: TRzRadioButton; optDropDownList: TRzRadioButton; grpTRzMRUComboBox: TRzGroupBox; grpTRzColorComboBox: TRzGroupBox; grpTRzFontComboBox: TRzGroupBox; cbxColors: TRzColorComboBox; cbxFonts: TRzFontComboBox; cbxMRU: TRzMRUComboBox; OptShowSysColors: TRzCheckBox; OptShowColorNames: TRzCheckBox; OptShowDefault: TRzCheckBox; OptShowCustom: TRzCheckBox; GrpFontDevice: TRzRadioGroup; GrpFontType: TRzRadioGroup; GrpShowStyle: TRzRadioGroup; RzLabel1: TRzLabel; chkAllowEdit: TRzCheckBox; RzRegIniFile1: TRzRegIniFile; pnlHeader: TRzPanel; RzBorder1: TRzBorder; RzBorder2: TRzBorder; RzBorder3: TRzBorder; RzBorder4: TRzBorder; pnlPreview: TRzPanel; RzGroupBox1: TRzGroupBox; RzBorder5: TRzBorder; ImageList1: TImageList; RzGroupBox2: TRzGroupBox; RzBorder6: TRzBorder; cbxStates: TRzComboBox; cbxImages: TRzImageComboBox; chkAutoComplete: TRzCheckBox; RzLabel2: TRzLabel; stsStateAbbr: TRzStatusPane; RzLabel3: TRzLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ComboStyleChange(Sender: TObject); procedure OptShowSysColorsClick(Sender: TObject); procedure OptShowColorNamesClick(Sender: TObject); procedure OptShowDefaultClick(Sender: TObject); procedure OptShowCustomClick(Sender: TObject); procedure GrpFontDeviceClick(Sender: TObject); procedure GrpFontTypeClick(Sender: TObject); procedure GrpShowStyleClick(Sender: TObject); procedure cbxFontsChange(Sender: TObject); procedure cbxColorsChange(Sender: TObject); procedure chkAllowEditClick(Sender: TObject); procedure chkAutoCompleteClick(Sender: TObject); procedure cbxStatesChange(Sender: TObject); private { Private declarations } public { Public declarations } procedure Init; procedure UpdateVisualStyle( VS: TRzVisualStyle; GCS: TRzGradientColorStyle ); end; implementation {$R *.dfm} uses MainForm; const RC_SettingsKey = 'Software\Raize\Raize Components\2.5'; procedure TFmeComboBoxes.Init; begin // ParentBackground := False; cbxMRU.MruPath := RC_SettingsKey; cbxImages.AddItem( 'Embarcadero Products', 0, 0 ); cbxImages.AddItem( 'Developer Tools', 9, 1 ); cbxImages.AddItem( 'Konopka Signature VCL Controls', 7, 2 ); cbxImages.AddItem( 'CodeSite', 3, 2 ); cbxImages.AddItem( 'Consumer Products', 10, 1 ); cbxImages.AddItem( 'BabyType', 2, 2 ); cbxImages.AddItem( 'ScratchPad', 8, 2 ); cbxImages.ItemIndex := 2; cbxStates.Value := 'IL'; stsStateAbbr.Caption := 'IL'; end; procedure TFmeComboBoxes.UpdateVisualStyle( VS: TRzVisualStyle; GCS: TRzGradientColorStyle ); begin pnlHeader.VisualStyle := VS; pnlHeader.GradientColorStyle := GCS; end; procedure TFmeComboBoxes.FormClose(Sender: TObject; var Action: TCloseAction); begin FrmMain.RestoreMainNotes; Action := caFree; end; procedure TFmeComboBoxes.ComboStyleChange(Sender: TObject); begin if OptDropDown.Checked then cbxStandard.Style := csDropDown else cbxStandard.Style := csDropDownList; ChkAllowEdit.Enabled := cbxStandard.Style = csDropDown; cbxStandard.ItemIndex := -1; cbxStandard.ClearSearchString; end; procedure TFmeComboBoxes.OptShowSysColorsClick(Sender: TObject); begin cbxColors.ShowSysColors := OptShowSysColors.Checked; end; procedure TFmeComboBoxes.OptShowColorNamesClick(Sender: TObject); begin cbxColors.ShowColorNames := OptShowColorNames.Checked; end; procedure TFmeComboBoxes.OptShowDefaultClick(Sender: TObject); begin cbxColors.ShowDefaultColor := OptShowDefault.Checked; end; procedure TFmeComboBoxes.OptShowCustomClick(Sender: TObject); begin cbxColors.ShowCustomColor := OptShowCustom.Checked; end; procedure TFmeComboBoxes.GrpFontDeviceClick(Sender: TObject); begin cbxFonts.FontDevice := TRzFontDevice( GrpFontDevice.ItemIndex ); end; procedure TFmeComboBoxes.GrpFontTypeClick(Sender: TObject); begin cbxFonts.FontType := TRzFontType( GrpFontType.ItemIndex ); end; procedure TFmeComboBoxes.GrpShowStyleClick(Sender: TObject); begin cbxFonts.ShowStyle := TRzShowStyle( GrpShowStyle.ItemIndex ); if cbxFonts.ShowStyle = ssFontNameAndSample then cbxFonts.DropDownWidth := 300 else cbxFonts.DropDownWidth := cbxFonts.Width; end; procedure TFmeComboBoxes.cbxFontsChange(Sender: TObject); begin if cbxFonts.SelectedFont <> nil then PnlPreview.Font.Name := cbxFonts.SelectedFont.Name; end; procedure TFmeComboBoxes.cbxColorsChange(Sender: TObject); begin pnlPreview.Color := cbxColors.SelectedColor; end; procedure TFmeComboBoxes.chkAllowEditClick(Sender: TObject); begin cbxStandard.AllowEdit := chkAllowEdit.Checked; end; procedure TFmeComboBoxes.chkAutoCompleteClick(Sender: TObject); begin cbxStandard.AutoComplete := chkAutoComplete.Checked; end; procedure TFmeComboBoxes.cbxStatesChange(Sender: TObject); begin stsStateAbbr.Caption := cbxStates.Value; end; end.
{ Unit: wzm.br.Util.Ribbon } { Author: William Zonta } { License: GNU ==> http://www.gnu.org/ } { Date: 2011-01 } { E-mail: williamzontamendonca@gmail.com } { Website: http://www.wzmsoftware.com.br/ } unit uRibbonDynamic; interface uses Classes, ImgList, Forms, Graphics, SysUtils, Ribbon, RibbonStyleActnCtrls, RibbonActnMenus, ActnMan, ActnList; {$REGION 'ActionManager'} function AddActionManager(AStyle: TActionBarStyle; AImages: TCustomImageList = nil; ALargeImages: TCustomImageList = nil; ALargeDisabledImages: TCustomImageList = nil): TActionManager; function AddActionBarItem(AActionManager: TActionManager): TActionBarItem; function AddAction(AActionManager: TActionManager; AOnExecute: TNotifyEvent; AName, ACaption: String; ACategory: String = ''; ATag: Integer = 0; AImageIndex: Integer = -1; AKeyTip: String = ''): TAction; {$ENDREGION} {$REGION 'Ribbon'} function AddRibbon(Sender: TForm; ACaption: String; AVisible: Boolean = True; AShowHelpButton: Boolean = False): TRibbon; function AddPage(ARibbon: TRibbon; ACaption: String; AKeyTip: String = ''): TCustomRibbonPage; function LocatePage(ARibbon: TRibbon; ACaption: String): TCustomRibbonPage; function AddGroup(APage: TCustomRibbonPage; AActionManager: TActionManager; ACaption: String; AKeyTip: String = ''; ARows: Integer = 3; AGroupAlign: Integer = 0): TRibbonGroup; function LocateGroup(APage: TCustomRibbonPage; ACaption: String): TRibbonGroup; procedure AddItem(AActionBegin, AActionEnd: Integer; ARibbonGroup: TRibbonGroup; AActionManager: TActionManager; ACommandStyle: Integer = 0; AButtonSize: Integer = 0; AButtonType: Integer = 0); procedure AddApplicationMenu(ARibbon: TRibbon; AActionManager: TActionManager); procedure AddRecentItem(ARibbon: TRibbon; AFileName: String); {$ENDREGION} implementation function AddActionManager(AStyle: TActionBarStyle; AImages, ALargeImages, ALargeDisabledImages: TCustomImageList): TActionManager; begin Result := TActionManager.Create(Application); //Define o estilo do componente: RibbonLunaStyle, RibbonObsidianStyle, RibbonSilverStyle Result.Style := AStyle; if AImages <> nil then Result.Images := AImages; if ALargeImages <> nil then Result.LargeImages := ALargeImages; if ALargeDisabledImages <> nil then Result.LargeDisabledImages := ALargeDisabledImages; end; function AddActionBarItem(AActionManager: TActionManager): TActionBarItem; begin Result := AActionManager.ActionBars.Add; end; function AddAction(AActionManager: TActionManager; AOnExecute: TNotifyEvent; AName, ACaption, ACategory: String; ATag, AImageIndex: Integer; AKeyTip: String): TAction; begin Result := TAction.Create(Application); Result.Name := AName; Result.Tag := ATag; Result.Caption := ACaption; Result.Category := ACategory; Result.ImageIndex := AImageIndex; Result.OnExecute := AOnExecute; Result.ActionList := AActionManager; Result.Hint := AKeyTip; end; function AddRibbon(Sender: TForm; ACaption: String; AVisible, AShowHelpButton: Boolean): TRibbon; begin Result := TRibbon.Create(Application); Result.Caption := ACaption; Result.Visible := AVisible; Result.Parent := Sender; Result.ShowHelpButton := AShowHelpButton; end; function AddPage(ARibbon: TRibbon; ACaption, AKeyTip: String): TCustomRibbonPage; begin with ARibbon.Tabs.Add do begin Caption := ACaption; KeyTip := AKeyTip; end; Result := ARibbon.Tabs[ARibbon.Tabs.Count - 1].Page; end; function LocatePage(ARibbon: TRibbon; ACaption: String): TCustomRibbonPage; begin Result := ARibbon.Tabs.GetPageFromPageCaption(ACaption); end; function AddGroup(APage: TCustomRibbonPage; AActionManager: TActionManager; ACaption, AKeyTip: String; ARows, AGroupAlign: Integer): TRibbonGroup; begin Result := TRibbonGroup.Create(APage.Parent); Result.Caption := ACaption; Result.Parent := APage; Result.ActionManager := AActionManager; Result.KeyTip := AKeyTip; //array de Integer: 1..3 if ARows > 3 then Result.Rows := 3 else if ARows < 1 then Result.Rows := 1 else Result.Rows := ARows; //Tipo de alinhamento: 0 = gaHorizontal, 1 = gaVertical case AGroupAlign of 0: Result.GroupAlign := gaHorizontal; 1: Result.GroupAlign := gaVertical; else Result.GroupAlign := gaHorizontal; end; end; function LocateGroup(APage: TCustomRibbonPage; ACaption: String): TRibbonGroup; begin Result := TRibbonGroup(APage.FindGroup(ACaption)); end; procedure AddItem(AActionBegin, AActionEnd: Integer; ARibbonGroup: TRibbonGroup; AActionManager: TActionManager; ACommandStyle, AButtonSize, AButtonType: Integer); var iAction: Integer; iActionBars: Integer; i: integer; begin iActionBars := -1; for i := 0 to AActionManager.ActionBars.Count - 1 do begin if AActionManager.ActionBars[i].ActionBar = ARibbonGroup then begin iActionBars := i; Break; end; end; if iActionBars = -1 then begin AActionManager.ActionBars.Add; iActionBars := AActionManager.ActionBars.Count - 1; end; with AActionManager.ActionBars[iActionBars] do begin //Atribui o grupo para um ActionBar ActionBar := ARibbonGroup; for iAction := AActionBegin to AActionEnd do with Items.Add do begin Action := AActionManager.Actions[iAction]; KeyTip := TAction(AActionManager.Actions[iAction]).Hint; //Style: 0 = csButton, 1 = csMenu, 2 = csSeparator, 3 = csText, 4 = csGallery, 5 = csComboBox, 6 = csCheckBox, 7 = csRadioButton, 8 = csControl, 9 = csCustom case ACommandStyle of 0: CommandStyle := csButton; 1: CommandStyle := csMenu; 2: CommandStyle := csSeparator; 3: CommandStyle := csText; 4: CommandStyle := csGallery; 5: CommandStyle := csComboBox; 6: CommandStyle := csCheckBox; 7: CommandStyle := csRadioButton; 8: CommandStyle := csControl; 9: CommandStyle := csCustom; else CommandStyle := csButton; end; //Tamanho do botão: bsSmall, bsLarge case AButtonSize of 0: (CommandProperties as TButtonProperties).ButtonSize := bsSmall; 1: (CommandProperties as TButtonProperties).ButtonSize := bsLarge; else (CommandProperties as TButtonProperties).ButtonSize := bsSmall; end; //Tipo do botão: 0 = btNone, 1 = btDropDown, 2 = btSplit, 3 = btGallery case AButtonType of 0: (CommandProperties as TButtonProperties).ButtonType := btNone; 1: (CommandProperties as TButtonProperties).ButtonType := btDropDown; 2: (CommandProperties as TButtonProperties).ButtonType := btSplit; 3: (CommandProperties as TButtonProperties).ButtonType := btGallery; else (CommandProperties as TButtonProperties).ButtonType := btNone; end; end; end; end; procedure AddApplicationMenu(ARibbon: TRibbon; AActionManager: TActionManager); var RibbonApplicationMenuBar: TRibbonApplicationMenuBar; ActionBarItem: TActionBarItem; begin //esta com defeito, corrigir { RibbonApplicationMenuBar := TRibbonApplicationMenuBar.Create(Application); RibbonApplicationMenuBar.ActionManager := AActionManager; // RibbonApplicationMenuBar.SetRibbon(ARibbon); ARibbon.ApplicationMenu.Menu := RibbonApplicationMenuBar; ActionBarItem := AddActionBarItem(AActionManager); ActionBarItem.ActionBar := RibbonApplicationMenuBar; ActionBarItem.ActionBar.RecreateControls; // with AActionManager.ActionBars.Add do // begin // ActionBar := RibbonApplicationMenuBar; // ActionBar.RecreateControls; // end; // RibbonApplicationMenuBar.OptionItems := TOptionItems.Create(Application, TOptionItem); ??? ARibbon.ApplicationMenu.Show(True); } end; procedure AddRecentItem(ARibbon: TRibbon; AFileName: String); begin if not AnsiSameText(AFileName, EmptyStr) then ARibbon.AddRecentItem(AFileName); end; end.
(*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* Unit Item *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* [2007/10/23] Helios - RaX ================================================================================ License: (FreeBSD, plus commercial with written permission clause.) ================================================================================ Project Helios - Copyright (c) 2005-2007 All rights reserved. Please refer to Helios.dpr for full license terms. ================================================================================ Overview: ================================================================================ Item base class, useableItem, miscitem, and equipmentitem will be derived from here. ================================================================================ Revisions: ================================================================================ (Format: [yyyy/mm/dd] <Author> - <Desc of Changes>) [2007/10/23] RaX - Created. *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*) unit Item; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} {Project} ItemTypes; {Third Party} //none type (*= CLASS =====================================================================* TItem *------------------------------------------------------------------------------* Overview: *------------------------------------------------------------------------------* Common class for Items, TEquipmentItem, TMiscItem and TUseableItem will be descendants. *------------------------------------------------------------------------------* Revisions: *------------------------------------------------------------------------------* (Format: [yyyy/mm/dd] <Author> - <Description of Change>) [2007/10/23] RaX - Created. [2007/10/26] RaX - Added basic item properties. *=============================================================================*) TItem = class(TObject) protected fName : String; fID : LongWord; fWeight : LongWord; fPrice : LongWord; //The price of the item in a standard shop fSell : LongWord; //The selling price of an item to a shop fType : TItemType; fSpriteID : LongWord; public Property Name : String Read fName Write fName; Property ID : LongWord Read fID Write fID; Property Weight : LongWord Read fWeight Write fWeight; Property Price : LongWord Read fPrice Write fPrice; Property Sell : LongWord Read fSell Write fSell; Property ItemType: TItemType Read fType Write fType; Property SpriteID : LongWord Read fSpriteID Write fSpriteID; Constructor Create; Destructor Destroy;override; End;(* TItem *== CLASS ====================================================================*) implementation //uses {RTL/VCL} {Project} {Third Party} //none (*- Cons ----------------------------------------------------------------------* TItem.Create -------------------------------------------------------------------------------- Overview: -- Creates our TItem. -- Post: EventList and Path lists are both created and initialized. -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/10/23] RaX - Created. *-----------------------------------------------------------------------------*) Constructor TItem.Create; begin inherited; End; (* Cons TBeing.Create *-----------------------------------------------------------------------------*) (*- Dest ----------------------------------------------------------------------* TItem.Destroy -- Overview: -- Destroys our TItem -- Pre: Post: -- Revisions: -- [2007/10/23] RaX - Created. *-----------------------------------------------------------------------------*) Destructor TItem.Destroy; Begin //Pre //-- //Always clean up your owned objects/memory first, then call ancestor. inherited; End;(* Dest TItem.Destroy *-----------------------------------------------------------------------------*) end.
unit TabExplorerView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, ToolWin, VirtualTrees, VirtualExplorerTree, cxControls, cxPC; type TTabExplorerForm = class(TForm) RecentDropdown: TPopupMenu; TabControl: TcxTabControl; ExplorerTree: TVirtualExplorerTree; ToolBar1: TToolBar; ToolButton2: TToolButton; ToolButton1: TToolButton; ToolButton3: TToolButton; procedure TabControlChange(Sender: TObject); procedure ExplorerTreeChange(Sender: TBaseVirtualTree; Node: PVirtualNode); private { Private declarations } FAnyFolder: string; FSourceFolder: string; FPublishFolder: string; procedure SetAnyFolder(const Value: string); procedure SetPublishFolder(const Value: string); procedure SetSourceFolder(const Value: string); function Tab: string; procedure UpdateTabs; public { Public declarations } procedure SelectTab(inIndex: Integer); property SourceFolder: string read FSourceFolder write SetSourceFolder; property PublishFolder: string read FPublishFolder write SetPublishFolder; property AnyFolder: string read FAnyFolder write SetAnyFolder; end; var TabExplorerForm: TTabExplorerForm; implementation {$R *.dfm} { TExplorerForm } function TTabExplorerForm.Tab: string; begin with TabControl do Result := Tabs[TabIndex].Caption; end; procedure TTabExplorerForm.ExplorerTreeChange(Sender: TBaseVirtualTree; Node: PVirtualNode); begin if Tab = 'All' then FAnyFolder := ExplorerTree.SelectedPath; end; procedure TTabExplorerForm.TabControlChange(Sender: TObject); begin if Tab = 'Source' then ExplorerTree.RootFolderCustomPath := SourceFolder else if Tab = 'Publish' then ExplorerTree.RootFolderCustomPath := PublishFolder else if Tab = 'All' then begin ExplorerTree.RootFolder := rfDesktop; if AnyFolder <> '' then ExplorerTree.BrowseTo(AnyFolder, false); end; end; procedure TTabExplorerForm.UpdateTabs; begin TabControl.Tabs.BeginUpdate; try TabControl.Tabs.Clear; if SourceFolder <> '' then TabControl.Tabs.Add('Source'); if PublishFolder <> '' then TabControl.Tabs.Add('Publish'); TabControl.Tabs.Add('All'); finally TabControl.Tabs.EndUpdate; end; end; procedure TTabExplorerForm.SetAnyFolder(const Value: string); begin FAnyFolder := Value; UpdateTabs; end; procedure TTabExplorerForm.SetPublishFolder(const Value: string); begin FPublishFolder := Value; UpdateTabs; end; procedure TTabExplorerForm.SetSourceFolder(const Value: string); begin FSourceFolder := Value; UpdateTabs; end; procedure TTabExplorerForm.SelectTab(inIndex: Integer); begin TabControl.TabIndex := inIndex; TabControl.OnChange(TabControl); end; end.
unit tod_dlg; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, StdCtrls; type { TTODdialog } TTODdialog = class(TForm) BitBtn1: TBitBtn; Content: TPanel; Footer: TPanel; Label1: TLabel; btnConfigure: TSpeedButton; procedure btnConfigureClick(Sender: TObject); procedure FormCreate(Sender: TObject); private FConfiguring: boolean; FContentHeight: integer; procedure SetConfiguring(AValue: boolean); { private declarations } public { public declarations } property ContentHeight : integer read FContentHeight write FContentHeight; property Configuring : boolean read FConfiguring write SetConfiguring; end; // TTODConfigPanel = class( var TODdialog: TTODdialog; implementation {$R *.lfm} { TTODdialog } procedure TTODdialog.FormCreate(Sender: TObject); begin FContentHeight := Footer.Top; Footer.Color := clBtnFace; Content.Align :=alClient; end; procedure TTODdialog.btnConfigureClick(Sender: TObject); begin Configuring := not Configuring; end; procedure TTODdialog.SetConfiguring(AValue: boolean); begin if FConfiguring=AValue then Exit; FConfiguring:=AValue; btnConfigure.Down := AValue; if AValue then begin end; end; end.
unit uModBarcodeUsage; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModApp, uModOrganization, uModUnit, uModAR, System.Generics.Collections, uModBarcodeRequest, uModSuplier, uModRekening; type TModBarcodeUsageItem = class; TModBarcodeUsage = class(TModApp) private FBarcodeUsageItems: TOBjectList<TModBarcodeUsageItem>; FBU_AR: TModAR; FBU_KETERANGAN: string; FBU_NO: string; FBU_SUPMG: TModOrganization; FBU_TANGGAL: tdatetime; FBU_TOTAL: Double; FBU_UNIT: TModUnit; function GetBarcodeUsageItems: TOBjectList<TModBarcodeUsageItem>; function GetBU_TOTAL: Double; public property BarcodeUsageItems: TOBjectList<TModBarcodeUsageItem> read GetBarcodeUsageItems write FBarcodeUsageItems; published property BU_AR: TModAR read FBU_AR write FBU_AR; [AttributeOfSize('120')] property BU_KETERANGAN: string read FBU_KETERANGAN write FBU_KETERANGAN; [AttributeOfCode] property BU_NO: string read FBU_NO write FBU_NO; property BU_SUPMG: TModOrganization read FBU_SUPMG write FBU_SUPMG; property BU_TANGGAL: tdatetime read FBU_TANGGAL write FBU_TANGGAL; property BU_TOTAL: Double read GetBU_TOTAL write FBU_TOTAL; property BU_UNIT: TModUnit read FBU_UNIT write FBU_UNIT; end; TModBarcodeUsageItem = class(TModApp) private FBUI_BarcodeRequest: TModBarcodeRequest; FBUI_BarcodeUsage: TModBarcodeUsage; FBUI_KETERANGAN: string; FBUI_NOMINAL: Double; FBUI_REKENING: TModRekening; published property BUI_BarcodeRequest: TModBarcodeRequest read FBUI_BarcodeRequest write FBUI_BarcodeRequest; [AttributeOfHeader] property BUI_BarcodeUsage: TModBarcodeUsage read FBUI_BarcodeUsage write FBUI_BarcodeUsage; property BUI_KETERANGAN: string read FBUI_KETERANGAN write FBUI_KETERANGAN; property BUI_NOMINAL: Double read FBUI_NOMINAL write FBUI_NOMINAL; property BUI_REKENING: TModRekening read FBUI_REKENING write FBUI_REKENING; end; implementation function TModBarcodeUsage.GetBarcodeUsageItems: TOBjectList<TModBarcodeUsageItem>; begin if FBarcodeUsageItems = nil then begin FBarcodeUsageItems := TObjectList<TModBarcodeUsageItem>.Create; end; Result := FBarcodeUsageItems; end; function TModBarcodeUsage.GetBU_TOTAL: Double; var I: Integer; begin FBU_TOTAL := 0; for I := 0 to BarcodeUsageItems.Count - 1 do begin FBU_TOTAL := FBU_TOTAL + BarcodeUsageItems[i].FBUI_NOMINAL; end; Result := FBU_TOTAL; end; Initialization TModBarcodeUsage.RegisterRTTI; TModBarcodeUsageItem.RegisterRTTI; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls; type TForm1 = class(TForm) MainMenu1: TMainMenu; N1: TMenuItem; AddWindowMenu: TMenuItem; CloseLastWindowMenu: TMenuItem; CloseMenu: TMenuItem; CloseAllMenu: TMenuItem; WindowBtnBox: TGroupBox; procedure AddWindowMenuClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CloseMenuClick(Sender: TObject); procedure FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); procedure showHide(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure CloseLastWindowMenuClick(Sender: TObject); procedure CloseAllMenuClick(Sender: TObject); procedure deleteSomeWindow(caption: String); procedure fillCreatedWindowsList(); private { Private declarations } public { Public declarations } end; var Form1: TForm1; iterator,totalCount:Integer; startTopPosition:Integer; implementation uses Unit2; {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin startTopPosition:=16; iterator:=1; totalCount:=0; if (not Assigned(Form2)) then Form2:=TForm2.Create(Form1); WindowBtnBox.Align:=alClient; end; procedure TForm1.deleteSomeWindow(caption: String); begin WindowBtnBox.FindComponent('createdBtn'+caption).Free; dec(iterator); end; procedure TForm1.fillCreatedWindowsList(); var i:integer; begin Form2.createdWindowsList.Items.Clear; for i:=0 to WindowBtnBox.ComponentCount-1 do Form2.createdWindowsList.Items.Add( (WindowBtnBox.Components[i] as TButton).Caption); end; procedure TForm1.AddWindowMenuClick(Sender: TObject); var createdBtn: TButton; createdForm: TForm; memoFromCreatedForm: TMemo; begin if not (iterator>11) then begin createdBtn:= TButton.Create(WindowBtnBox); createdBtn.Parent:=WindowBtnBox; createdBtn.Left:=8; createdBtn.Height:=25; createdBtn.Width:=129; createdBtn.onMouseDown:=showHide; createdBtn.Top:=startTopPosition+(iterator-1)*24; inc(iterator); inc(totalCount); createdBtn.Caption:=IntToStr(totalCount); createdBtn.Name:='createdBtn'+IntToStr(totalCount); // Создание формы createdForm:=TForm.Create(createdBtn); createdForm.ClientHeight:=232; createdForm.ClientWidth:=374; createdForm.top:=294; createdForm.Left:=543; createdForm.BorderIcons:=[]; createdForm.Visible:=true; createdForm.Name:='createdForm'+IntToStr(totalCount); createdForm.Caption:=IntToStr(totalCount); memoFromCreatedForm:=TMemo.Create(createdForm); memoFromCreatedForm.Parent:=createdForm; memoFromCreatedForm.Width:=300; memoFromCreatedForm.Height:=200; memoFromCreatedForm.Align:=alClient; memoFromCreatedForm.WordWrap:=true; memoFromCreatedForm.Name:='memoFromCreatedForm'; memoFromCreatedForm.Text:=''; memoFromCreatedForm.ScrollBars:=ssVertical; end else begin showMessage('Нельзя создать еще одну форму. Максимальное количество: 11'); end; end; procedure TForm1.showHide(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Sender is TButton then if Button=mbRight then begin if ((((Sender as TButton).Components[0]) as TForm).Visible) then (((Sender as TButton).Components[0]) as TForm).Visible:=false else (((Sender as TButton).Components[0]) as TForm).Visible:=true; end else if not (((Sender as TButton).Components[0]) as TForm).Focused and (((Sender as TButton).Components[0]) as TForm).visible then (((Sender as TButton).Components[0]) as TForm).SetFocus; end; procedure TForm1.CloseMenuClick(Sender: TObject); begin Form2.visible:=true; fillCreatedWindowsList(); end; procedure TForm1.FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); begin Resize:=False; end; procedure TForm1.CloseLastWindowMenuClick(Sender: TObject); begin if (WindowBtnBox.ComponentCount>0) then begin (WindowBtnBox.Components[WindowBtnBox.ComponentCount-1] as TButton).Free; dec(iterator); end; end; procedure TForm1.CloseAllMenuClick(Sender: TObject); var i:integer; begin if (WindowBtnBox.ComponentCount>0) then begin for i:=0 to WindowBtnBox.ComponentCount-1 do (WindowBtnBox.Components[0] as TButton).Free; iterator:=1; end; end; end.
object DemoOptions: TDemoOptions Left = 681 Top = 337 BorderStyle = bsDialog Caption = 'Demo interface options' ClientHeight = 215 ClientWidth = 234 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poMainFormCenter PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 10 Top = 19 Width = 29 Height = 13 Caption = 'Model' end object Label2: TLabel Left = 10 Top = 41 Width = 49 Height = 13 Caption = 'Period(ms)' end object Label3: TLabel Left = 10 Top = 85 Width = 76 Height = 13 Caption = 'Noise Amplitude' end object Label4: TLabel Left = 10 Top = 63 Width = 46 Height = 13 Caption = 'Amplitude' end object Label5: TLabel Left = 10 Top = 107 Width = 81 Height = 13 Caption = 'Event Frequency' end object cbTagStart: TCheckBoxV Left = 9 Top = 127 Width = 210 Height = 17 Alignment = taLeftJustify Caption = 'Use Tag Channels' TabOrder = 0 UpdateVarOnToggle = False end object BOK: TButton Left = 48 Top = 159 Width = 56 Height = 20 Caption = 'OK' ModalResult = 1 TabOrder = 1 end object Bcancel: TButton Left = 126 Top = 159 Width = 56 Height = 20 Caption = 'Cancel' ModalResult = 2 TabOrder = 2 end object cbModel: TcomboBoxV Left = 100 Top = 16 Width = 122 Height = 21 ItemHeight = 13 TabOrder = 3 Text = 'cbModel' Tnum = G_byte UpdateVarOnExit = False UpdateVarOnChange = False end object enPeriod: TeditNum Left = 100 Top = 38 Width = 121 Height = 21 TabOrder = 4 Text = '1000' Tnum = G_byte Max = 255.000000000000000000 UpdateVarOnExit = False Decimal = 0 Dxu = 1.000000000000000000 end object enNoise: TeditNum Left = 100 Top = 82 Width = 121 Height = 21 TabOrder = 5 Text = '1000' Tnum = G_byte Max = 255.000000000000000000 UpdateVarOnExit = False Decimal = 0 Dxu = 1.000000000000000000 end object enAmplitude: TeditNum Left = 100 Top = 60 Width = 121 Height = 21 TabOrder = 6 Text = '1000' Tnum = G_byte Max = 255.000000000000000000 UpdateVarOnExit = False Decimal = 0 Dxu = 1.000000000000000000 end object enFreq: TeditNum Left = 100 Top = 104 Width = 121 Height = 21 TabOrder = 7 Text = '1000' Tnum = G_byte Max = 255.000000000000000000 UpdateVarOnExit = False Decimal = 0 Dxu = 1.000000000000000000 end end
unit InflatablesList_Item_Comp; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses InflatablesList_Types, InflatablesList_Item_Draw; type TILItem_Comp = class(TILItem_Draw) public Function Contains(const Text: String; Value: TILItemSearchResult): Boolean; overload; virtual; Function Contains(const Text: String): Boolean; overload; virtual; Function Compare(WithItem: TILItem_Comp; WithValue: TILItemValueTag; Reversed: Boolean; CaseSensitive: Boolean): Integer; virtual; procedure Filter(FilterSettings: TILFilterSettings); virtual; end; implementation uses SysUtils, AuxTypes, BitOps, InflatablesList_Utils, InflatablesList_LocalStrings, InflatablesList_ItemShop; Function TILItem_Comp.Contains(const Text: String; Value: TILItemSearchResult): Boolean; var SelShop: TILItemShop; i: Integer; Function CheckInPicture(Index: Integer; const Text: String): Boolean; begin If fPictures.CheckIndex(Index) then Result := IL_ContainsText(fPictures[Index].PictureFile,Text) else Result := False; end; begin // search only in editable values If fDataAccessible then case Value of ilisrItemPicFile: Result := CheckInPicture(fPictures.IndexOfItemPicture,Text); ilisrSecondaryPicFile: begin Result := False; For i := fPictures.LowIndex to fPictures.HighIndex do If not fPictures[i].ItemPicture and not fPictures[i].PackagePicture then If CheckInPicture(i,Text) then begin Result := True; Break{For i}; end; end; ilisrPackagePicFile: Result := CheckInPicture(fPictures.IndexOfPackagePicture,Text); ilisrType: Result := IL_ContainsText(fDataProvider.GetItemTypeString(fItemType),Text); ilisrTypeSpec: Result := IL_ContainsText(fItemTypeSpec,Text); ilisrPieces: Result := IL_ContainsText(IL_Format('%dpcs',[fPieces]),Text); ilisrUserID: Result := IL_ContainsText(fUserID,Text); ilisrManufacturer: Result := IL_ContainsText(fDataProvider.ItemManufacturers[fManufacturer].Str,Text); ilisrManufacturerStr: Result := IL_ContainsText(fManufacturerStr,Text); ilisrTextID: Result := IL_ContainsText(fTextID,Text); ilisrNumID: Result := IL_ContainsText(IntToStr(fNumID),Text); ilisrFlagOwned: Result := (ilifOwned in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifOwned),Text); ilisrFlagWanted: Result := (ilifWanted in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifWanted),Text); ilisrFlagOrdered: Result := (ilifOrdered in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifOrdered),Text); ilisrFlagBoxed: Result := (ilifBoxed in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifBoxed),Text); ilisrFlagElsewhere: Result := (ilifElsewhere in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifElsewhere),Text); ilisrFlagUntested: Result := (ilifUntested in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifUntested),Text); ilisrFlagTesting: Result := (ilifTesting in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifTesting),Text); ilisrFlagTested: Result := (ilifTested in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifTested),Text); ilisrFlagDamaged: Result := (ilifDamaged in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifDamaged),Text); ilisrFlagRepaired: Result := (ilifRepaired in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifRepaired),Text); ilisrFlagPriceChange: Result := (ilifPriceChange in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifPriceChange),Text); ilisrFlagAvailChange: Result := (ilifAvailChange in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifAvailChange),Text); ilisrFlagNotAvailable: Result := (ilifNotAvailable in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifNotAvailable),Text); ilisrFlagLost: Result := (ilifLost in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifLost),Text); ilisrFlagDiscarded: Result := (ilifDiscarded in fFlags) and IL_ContainsText(fDataProvider.GetItemFlagString(ilifDiscarded),Text); ilisrTextTag: Result := IL_ContainsText(fTextTag,Text); ilisrNumTag: Result := IL_ContainsText(IntToStr(fNumTag),Text); ilisrWantedLevel: Result := IL_ContainsText(IntToStr(fWantedLevel),Text); ilisrVariant: Result := IL_ContainsText(fVariant,Text); ilisrVariantTag: Result := IL_ContainsText(fVariantTag,Text); ilisrSurfaceFinish: Result := IL_ContainsText(fDataProvider.GetItemSurfaceFinishString(fSurfaceFinish),Text); ilisrMaterial: Result := IL_ContainsText(fDataProvider.GetItemMaterialString(fMaterial),Text); ilisrThickness: Result := IL_ContainsText(IL_Format('%dum',[fThickness]),Text); ilisrSizeX: Result := IL_ContainsText(IL_Format('%dmm',[fSizeX]),Text); ilisrSizeY: Result := IL_ContainsText(IL_Format('%dmm',[fSizeY]),Text); ilisrSizeZ: Result := IL_ContainsText(IL_Format('%dmm',[fSizeZ]),Text); ilisrUnitWeight: Result := IL_ContainsText(IL_Format('%dg',[fUnitWeight]),Text); ilisrNotes: Result := IL_ContainsText(fNotes,Text); ilisrReviewURL: Result := IL_ContainsText(fReviewURL,Text); ilisrUnitPriceDefault: Result := IL_ContainsText(IL_Format('%d%s',[fUnitPriceDefault,IL_CURRENCY_SYMBOL]),Text); ilisrRating: Result := IL_ContainsText(IL_Format('%d%%',[fRating]),Text); ilisrRatingDetails: Result := IL_ContainsText(fRatingDetails,Text); ilisrSelectedShop: If ShopsSelected(SelShop) then Result := IL_ContainsText(SelShop.Name,Text) else Result := False; else Result := False; end else Result := False; end; //------------------------------------------------------------------------------ Function TILItem_Comp.Contains(const Text: String): Boolean; begin If fDataAccessible then // search only in editable values Result := Contains(Text,ilisrItemPicFile) or Contains(Text,ilisrSecondaryPicFile) or Contains(Text,ilisrPackagePicFile) or Contains(Text,ilisrType) or Contains(Text,ilisrTypeSpec) or Contains(Text,ilisrPieces) or Contains(Text,ilisrUserID) or Contains(Text,ilisrManufacturer) or Contains(Text,ilisrManufacturerStr) or Contains(Text,ilisrTextID) or Contains(Text,ilisrNumID) or Contains(Text,ilisrFlagOwned) or Contains(Text,ilisrFlagWanted) or Contains(Text,ilisrFlagOrdered) or Contains(Text,ilisrFlagBoxed) or Contains(Text,ilisrFlagElsewhere) or Contains(Text,ilisrFlagUntested) or Contains(Text,ilisrFlagTesting) or Contains(Text,ilisrFlagTested) or Contains(Text,ilisrFlagDamaged) or Contains(Text,ilisrFlagRepaired) or Contains(Text,ilisrFlagPriceChange) or Contains(Text,ilisrFlagAvailChange) or Contains(Text,ilisrFlagNotAvailable) or Contains(Text,ilisrFlagLost) or Contains(Text,ilisrFlagDiscarded) or Contains(Text,ilisrTextTag) or Contains(Text,ilisrNumTag) or Contains(Text,ilisrWantedLevel) or Contains(Text,ilisrVariant) or Contains(Text,ilisrVariantTag) or Contains(Text,ilisrSurfaceFinish) or Contains(Text,ilisrMaterial) or Contains(Text,ilisrThickness) or Contains(Text,ilisrSizeX) or Contains(Text,ilisrSizeY) or Contains(Text,ilisrSizeZ) or Contains(Text,ilisrUnitWeight) or Contains(Text,ilisrNotes) or Contains(Text,ilisrReviewURL) or Contains(Text,ilisrUnitPriceDefault) or Contains(Text,ilisrRating) or Contains(Text,ilisrRatingDetails) or Contains(Text,ilisrSelectedShop) else Result := False; end; //------------------------------------------------------------------------------ Function TILItem_Comp.Compare(WithItem: TILItem_Comp; WithValue: TILItemValueTag; Reversed: Boolean; CaseSensitive: Boolean): Integer; var SelShop1: TILItemShop; SelShop2: TILItemShop; I1,I2: Integer; Function CompareText_Internal(const A,B: String): Integer; begin If CaseSensitive then Result := IL_SortCompareStr(A,B) else Result := IL_SortCompareText(A,B) end; begin If (fDataAccessible and WithItem.DataAccessible) or (WithValue = ilivtItemEncrypted) then case WithValue of // internals = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ilivtItemEncrypted: Result := IL_SortCompareBool(fEncrypted,WithItem.Encrypted); ilivtUniqueID: Result := IL_SortCompareGUID(fUniqueID,WithItem.UniqueID); ilivtTimeOfAdd: Result := IL_SortCompareDateTime(fTimeOfAddition,WithItem.TimeOfAddition); ilivtDescriptor: Result := CompareText_Internal(Descriptor,WithItem.Descriptor); // pictures = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ilivtMainPicFilePres: Result := IL_SortCompareBool(fPictures.CheckIndex(fPictures.IndexOfItemPicture), WithItem.Pictures.CheckIndex(WithItem.Pictures.IndexOfItemPicture)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtPackPicFilePres: Result := IL_SortCompareBool(fPictures.CheckIndex(fPictures.IndexOfPackagePicture), WithItem.Pictures.CheckIndex(WithItem.Pictures.IndexOfPackagePicture)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtCurrSecPicPres: Result := IL_SortCompareBool(fPictures.CheckIndex(fPictures.CurrentSecondary), WithItem.Pictures.CheckIndex(WithItem.Pictures.CurrentSecondary)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtMainPictureFile, ilivtPackPictureFile, ilivtCurrSecPicFile: begin case WithValue of ilivtMainPictureFile: begin I1 := fPictures.IndexOfItemPicture; I2 := WithItem.Pictures.IndexOfItemPicture; end; ilivtPackPictureFile: begin I1 := fPictures.IndexOfPackagePicture; I2 := WithItem.Pictures.IndexOfPackagePicture; end; else {ilivtCurrSecPicFile} I1 := fPictures.CurrentSecondary; I2 := WithItem.Pictures.CurrentSecondary; end; If fPictures.CheckIndex(I1) and WithItem.Pictures.CheckIndex(I2) then Result := CompareText_Internal(fPictures[I1].PictureFile,WithItem.Pictures[I2].PictureFile) else If fPictures.CheckIndex(I1) and not WithItem.Pictures.CheckIndex(I2) then Result := IL_NegateValue(+1,Reversed) else If not fPictures.CheckIndex(I1) and WithItem.Pictures.CheckIndex(I2) then Result := IL_NegateValue(-1,Reversed) else Result := 0; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtMainPictureThumb, ilivtPackPictureThumb, ilivtCurrSecPicThumb: begin case WithValue of ilivtMainPictureThumb: begin I1 := fPictures.IndexOfItemPicture; I2 := WithItem.Pictures.IndexOfItemPicture; end; ilivtPackPictureThumb: begin I1 := fPictures.IndexOfPackagePicture; I2 := WithItem.Pictures.IndexOfPackagePicture; end; else {ilivtCurrSecPicThumb} I1 := fPictures.CurrentSecondary; I2 := WithItem.Pictures.CurrentSecondary; end; If fPictures.CheckIndex(I1) and WithItem.Pictures.CheckIndex(I2) then Result := IL_SortCompareBool(Assigned(fPictures[I1].Thumbnail),Assigned(WithItem.Pictures[I2].Thumbnail)) else If fPictures.CheckIndex(I1) and not WithItem.Pictures.CheckIndex(I2) then Result := IL_NegateValue(+1,Reversed) else If not fPictures.CheckIndex(I1) and WithItem.Pictures.CheckIndex(I2) then Result := IL_NegateValue(-1,Reversed) else Result := 0; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtPictureCount: Result := IL_SortCompareInt32(fPictures.Count,WithItem.Pictures.Count); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtSecPicCount: Result := IL_SortCompareInt32(fPictures.SecondaryCount(False),WithItem.Pictures.SecondaryCount(False)); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtSecPicThumbCount: Result := IL_SortCompareInt32(fPictures.SecondaryCount(True),WithItem.Pictures.SecondaryCount(True)); // basic specs = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ilivtItemType: If fItemType <> WithItem.ItemType then begin If not(fItemType in [ilitUnknown,ilitOther]) and not(WithItem.ItemType in [ilitUnknown,ilitOther]) then Result := CompareText_Internal( fDataProvider.GetItemTypeString(fItemType), fDataProvider.GetItemTypeString(WithItem.ItemType)) // push others and unknowns to the end else If not(fItemType in [ilitUnknown,ilitOther]) and (WithItem.ItemType in [ilitUnknown,ilitOther]) then Result := IL_NegateValue(+1,Reversed) else If (fItemType in [ilitUnknown,ilitOther]) and not(WithItem.ItemType in [ilitUnknown,ilitOther]) then Result := IL_NegateValue(-1,Reversed) // both are either unknown or other, but differs, push unknown to the end... else begin If fItemType = ilitOther then Result := IL_NegateValue(+1,Reversed) else If WithItem.ItemType = ilitOther then Result := IL_NegateValue(-1,Reversed) else Result := 0; end; end else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtItemTypeSpec: Result := CompareText_Internal(fItemTypeSpec,WithItem.ItemTypeSpec); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtPieces: Result := IL_SortCompareUInt32(fPieces,WithItem.Pieces); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtUserID: If (Length(fUserID) > 0) and (Length(WithItem.UserID) > 0) then Result := CompareText_Internal(fUserID,WithItem.UserID) else If (Length(fUserID) > 0) and (Length(WithItem.UserID) <= 0) then Result := IL_NegateValue(+1,Reversed) else If (Length(fUserID) <= 0) and (Length(WithItem.UserID) > 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtManufacturer: If fManufacturer <> WithItem.Manufacturer then begin If not(fManufacturer in [ilimUnknown,ilimOthers]) and not(WithItem.Manufacturer in [ilimUnknown,ilimOthers]) then Result := CompareText_Internal( fDataProvider.ItemManufacturers[fManufacturer].Str, fDataProvider.ItemManufacturers[WithItem.Manufacturer].Str) // push others and unknowns to the end else If not(fManufacturer in [ilimUnknown,ilimOthers]) and (WithItem.Manufacturer in [ilimUnknown,ilimOthers]) then Result := IL_NegateValue(+1,Reversed) else If (fManufacturer in [ilimUnknown,ilimOthers]) and not(WithItem.Manufacturer in [ilimUnknown,ilimOthers]) then Result := IL_NegateValue(-1,Reversed) // both are either unknown or other, but differs, push unknown to the end... else begin If fManufacturer = ilimOthers then Result := IL_NegateValue(+1,Reversed) else If WithItem.Manufacturer = ilimOthers then Result := IL_NegateValue(-1,Reversed) else Result := 0; // this should not happen end; end else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtManufacturerStr: Result := CompareText_Internal(fManufacturerStr,WithItem.ManufacturerStr); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtTextID: Result := CompareText_Internal(fTextID,WithItem.TextID); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtNumID: Result := IL_SortCompareInt32(fNumID,WithItem.NumID); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtIDStr: Result := CompareText_Internal(IDStr,WithItem.IDStr); // flags = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ilivtFlagOwned: Result := IL_SortCompareBool(ilifOwned in fFlags,ilifOwned in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagWanted: Result := IL_SortCompareBool(ilifWanted in fFlags,ilifWanted in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagOrdered: Result := IL_SortCompareBool(ilifOrdered in fFlags,ilifOrdered in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagBoxed: Result := IL_SortCompareBool(ilifBoxed in fFlags,ilifBoxed in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagElsewhere: Result := IL_SortCompareBool(ilifElsewhere in fFlags,ilifElsewhere in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagUntested: Result := IL_SortCompareBool(ilifUntested in fFlags,ilifUntested in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagTesting: Result := IL_SortCompareBool(ilifTesting in fFlags,ilifTesting in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagTested: Result := IL_SortCompareBool(ilifTested in fFlags,ilifTested in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagDamaged: Result := IL_SortCompareBool(ilifDamaged in fFlags,ilifDamaged in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagRepaired: Result := IL_SortCompareBool(ilifRepaired in fFlags,ilifRepaired in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagPriceChange: Result := IL_SortCompareBool(ilifPriceChange in fFlags,ilifPriceChange in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagAvailChange: Result := IL_SortCompareBool(ilifAvailChange in fFlags,ilifAvailChange in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagNotAvailable: Result := IL_SortCompareBool(ilifNotAvailable in fFlags,ilifNotAvailable in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagLost: Result := IL_SortCompareBool(ilifLost in fFlags,ilifLost in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtFlagDiscarded: Result := IL_SortCompareBool(ilifDiscarded in fFlags,ilifDiscarded in WithItem.Flags); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtTextTag: If (Length(fTextTag) > 0) and (Length(WithItem.TextTag) > 0) then Result := CompareText_Internal(fTextTag,WithItem.TextTag) else If (Length(fTextTag) > 0) and (Length(WithItem.TextTag) <= 0) then Result := IL_NegateValue(+1,Reversed) else If (Length(fTextTag) <= 0) and (Length(WithItem.TextTag) > 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtNumTag: If (fNumTag <> 0) and (WithItem.NumTag <> 0) then Result := IL_SortCompareInt32(fNumTag,WithItem.NumTag) else If (fNumTag <> 0) and (WithItem.NumTag = 0) then Result := IL_NegateValue(+1,Reversed) else If (fNumTag = 0) and (WithItem.NumTag <> 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // extended specs = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ilivtWantedLevel: If (ilifWanted in fFlags) and (ilifWanted in WithItem.Flags) then Result := IL_SortCompareUInt32(fWantedLevel,WithItem.WantedLevel) else If not(ilifWanted in fFlags) and (ilifWanted in WithItem.Flags) then Result := IL_NegateValue(-1,Reversed) // those without the flag set goes at the end else If (ilifWanted in fFlags) and not(ilifWanted in WithItem.Flags) then Result := IL_NegateValue(+1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtVariant: Result := CompareText_Internal(fVariant,WithItem.Variant); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtVariantTag: If (Length(fVariantTag) > 0) and (Length(WithItem.VariantTag) > 0) then Result := CompareText_Internal(fVariantTag,WithItem.VariantTag) else If (Length(fVariantTag) > 0) and (Length(WithItem.VariantTag) <= 0) then Result := IL_NegateValue(+1,Reversed) else If (Length(fVariantTag) <= 0) and (Length(WithItem.VariantTag) > 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtSurfaceFinish: If fSurfaceFinish <> WithItem.SurfaceFinish then begin If not(fSurfaceFinish in [ilisfUnknown,ilisfOther]) and not(WithItem.SurfaceFinish in [ilisfUnknown,ilisfOther]) then Result := CompareText_Internal( fDataProvider.GetItemSurfaceFinishString(fSurfaceFinish), fDataProvider.GetItemSurfaceFinishString(WithItem.SurfaceFinish)) // push others and unknowns to the end else If not(fSurfaceFinish in [ilisfUnknown,ilisfOther]) and (WithItem.SurfaceFinish in [ilisfUnknown,ilisfOther]) then Result := IL_NegateValue(+1,Reversed) else If (fSurfaceFinish in [ilisfUnknown,ilisfOther]) and not(WithItem.SurfaceFinish in [ilisfUnknown,ilisfOther]) then Result := IL_NegateValue(-1,Reversed) // both are either unknown or other, but differs, push unknown to the end... else begin If fSurfaceFinish = ilisfOther then Result := IL_NegateValue(+1,Reversed) else If WithItem.SurfaceFinish = ilisfOther then Result := IL_NegateValue(-1,Reversed) else Result := 0; // this should not happen end; end else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtMaterial: If fMaterial <> WithItem.Material then begin If not(fMaterial in [ilimtUnknown,ilimtOther]) and not(WithItem.Material in [ilimtUnknown,ilimtOther]) then Result := CompareText_Internal( fDataProvider.GetItemMaterialString(fMaterial), fDataProvider.GetItemMaterialString(WithItem.Material)) // push others and unknowns to the end else If not(fMaterial in [ilimtUnknown,ilimtOther]) and (WithItem.Material in [ilimtUnknown,ilimtOther]) then Result := IL_NegateValue(+1,Reversed) else If (fMaterial in [ilimtUnknown,ilimtOther]) and not(WithItem.Material in [ilimtUnknown,ilimtOther]) then Result := IL_NegateValue(-1,Reversed) // both are either unknown or other, but differs, push unknown to the end... else begin If fMaterial = ilimtOther then Result := IL_NegateValue(+1,Reversed) else If WithItem.Material = ilimtOther then Result := IL_NegateValue(-1,Reversed) else Result := 0; // this should not happen end; end else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtThickness: If (fThickness > 0) and (WithItem.Thickness > 0) then Result := IL_SortCompareUInt32(fThickness,WithItem.Thickness) else If (fThickness > 0) and (WithItem.Thickness <= 0) then Result := IL_NegateValue(+1,Reversed) // push items with 0 thickness to the end else If (fThickness <= 0) and (WithItem.Thickness > 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtSizeX: Result := IL_SortCompareUInt32(fSizeX,WithItem.SizeX); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtSizeY: Result := IL_SortCompareUInt32(fSizeY,WithItem.SizeY); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtSizeZ: Result := IL_SortCompareUInt32(fSizeZ,WithItem.SizeZ); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtTotalSize: If (TotalSize > 0) and (WithItem.TotalSize > 0) then Result := IL_SortCompareInt64(TotalSize,WithItem.TotalSize) else If (TotalSize > 0) and (WithItem.TotalSize <= 0) then Result := IL_NegateValue(+1,Reversed) // push items with 0 total size to the end else If (TotalSize <= 0) and (WithItem.TotalSize > 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtUnitWeight: If (fUnitWeight > 0) and (WithItem.UnitWeight > 0) then Result := IL_SortCompareUInt32(fUnitWeight,WithItem.UnitWeight) else If (fUnitWeight > 0) and (WithItem.UnitWeight <= 0) then Result := IL_NegateValue(+1,Reversed) // push items with 0 weight to the end else If (fUnitWeight <= 0) and (WithItem.UnitWeight > 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtTotalWeight: If (TotalWeight > 0) and (WithItem.TotalWeight > 0) then Result := IL_SortCompareUInt32(TotalWeight,WithItem.TotalWeight) else If (TotalWeight > 0) and (WithItem.TotalWeight <= 0) then Result := IL_NegateValue(+1,Reversed) // push items with 0 total weight to the end else If (TotalWeight <= 0) and (WithItem.TotalWeight > 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // others = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ilivtNotes: Result := CompareText_Internal(fNotes,WithItem.Notes); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtReviewURL: Result := CompareText_Internal(fReviewURL,WithItem.ReviewURL); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtReview: Result := IL_SortCompareBool(Length(fReviewURL) > 0,Length(WithItem.ReviewURL) > 0); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtUnitPriceDefault: Result := IL_SortCompareUInt32(fUnitPriceDefault,WithItem.UnitPriceDefault); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtRating: If ((ilifOwned in fFlags) and not(ilifWanted in fFlags)) and ((ilifOwned in WithItem.Flags) and not(ilifWanted in WithItem.Flags)) then Result := IL_SortCompareUInt32(fRating,WithItem.Rating) // those without proper flag combination goes at the end else If ((ilifOwned in fFlags) and not(ilifWanted in fFlags)) and not((ilifOwned in WithItem.Flags) and not(ilifWanted in WithItem.Flags)) then Result := IL_NegateValue(+1,Reversed) else If not((ilifOwned in fFlags) and not(ilifWanted in fFlags)) and ((ilifOwned in WithItem.Flags) and not(ilifWanted in WithItem.Flags)) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtRatingDetails: Result := CompareText_Internal(fRatingDetails,WithItem.RatingDetails); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtSomethingUnknown: If (ilifOwned in fFlags) and (ilifOwned in WithItem.Flags) then Result := IL_SortCompareBool(SomethingIsUnknown,WithItem.SomethingIsUnknown) else If not(ilifOwned in fFlags) and (ilifOwned in WithItem.Flags) then Result := IL_NegateValue(-1,Reversed) // those without the flag set goes at the end else If (ilifOwned in fFlags) and not(ilifOwned in WithItem.Flags) then Result := IL_NegateValue(+1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtUnitPriceLowest: Result := IL_SortCompareUInt32(fUnitPriceLowest,WithItem.UnitPriceLowest); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtTotalPriceLowest: Result := IL_SortCompareUInt32(TotalPriceLowest,WithItem.TotalPriceLowest); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtUnitPriceSel: Result := IL_SortCompareUInt32(fUnitPriceSelected,WithItem.UnitPriceSelected); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtTotalPriceSel: Result := IL_SortCompareUInt32(TotalPriceSelected,WithItem.TotalPriceSelected); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtTotalPrice: Result := IL_SortCompareUInt32(TotalPrice,WithItem.TotalPrice); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtAvailable: If (fAvailableSelected < 0) and (WithItem.AvailableSelected < 0) then Result := IL_SortCompareInt32(Abs(fAvailableSelected),Abs(WithItem.AvailableSelected)) else If (fAvailableSelected < 0) and (WithItem.AvailableSelected >= 0) then begin If Abs(fAvailableSelected) = WithItem.AvailableSelected then Result := IL_NegateValue(-1,Reversed) else Result := IL_SortCompareInt32(Abs(fAvailableSelected),WithItem.AvailableSelected) end else If (fAvailableSelected >= 0) and (WithItem.AvailableSelected < 0) then begin If fAvailableSelected = Abs(WithItem.AvailableSelected) then Result := IL_NegateValue(+1,Reversed) else Result := IL_SortCompareInt32(fAvailableSelected,Abs(WithItem.AvailableSelected)) end else Result := IL_SortCompareInt32(fAvailableSelected,WithItem.AvailableSelected); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtShopCount: Result := IL_SortCompareUInt32(fShopCount,WithItem.ShopCount); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtUsefulShopCount: Result := IL_SortCompareUInt32(ShopsUsefulCount,WithItem.ShopsUsefulCount); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtUsefulShopRatio: If (fShopCount > 0) and (WithItem.ShopCount > 0) then Result := IL_SortCompareFloat(ShopsUsefulRatio,WithItem.ShopsUsefulRatio) else If (fShopCount > 0) and (WithItem.ShopCount <= 0) then Result := IL_NegateValue(+1,Reversed) // push items with no shop to the end else If (fShopCount <= 0) and (WithItem.ShopCount > 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtSelectedShop: If ShopsSelected(SelShop1) and WithItem.ShopsSelected(SelShop2) then Result := CompareText_Internal(SelShop1.Name,SelShop2.Name) else If ShopsSelected(SelShop1) and not WithItem.ShopsSelected(SelShop2) then Result := IL_NegateValue(+1,Reversed) else If not ShopsSelected(SelShop1) and WithItem.ShopsSelected(SelShop2) then Result := IL_NegateValue(-1,Reversed) // push items with no shop selected at the end else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ilivtWorstUpdateResult: If (fShopCount > 0) and (WithItem.ShopCount > 0) then Result := IL_SortCompareInt32(Ord(ShopsWorstUpdateResult),Ord(WithItem.ShopsWorstUpdateResult)) else If (fShopCount > 0) and (WithItem.ShopCount <= 0) then Result := IL_NegateValue(+1,Reversed) // push items with no shop to the end else If (fShopCount <= 0) and (WithItem.ShopCount > 0) then Result := IL_NegateValue(-1,Reversed) else Result := 0; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - else {vtNone} Result := 0; end else begin // push items that have inaccessible data to the end If fDataAccessible and not WithItem.DataAccessible then Result := IL_NegateValue(+1,Reversed) else If not fDataAccessible and WithItem.DataAccessible then Result := IL_NegateValue(-1,Reversed) else Result := 0; end; If Result < -1 then Result := -1 else If Result > 1 then Result := 1; If Reversed then Result := -Result; end; //------------------------------------------------------------------------------ procedure TILItem_Comp.Filter(FilterSettings: TILFilterSettings); var FlagsMap: UInt32; FlagsMask: UInt32; i: Integer; StateSet: Boolean; State: Boolean; // true = filtered-in, false = filtered-out procedure CheckItemFlag(BitMask: UInt32; ItemFlag: TILItemFlag; FlagSet, FlagClr: TILFilterFlag); begin If FlagSet in FilterSettings.Flags then begin BitOps.SetFlagStateValue(FlagsMap,BitMask,ItemFlag in fFlags); BitOps.SetFlagValue(FlagsMask,BitMask); end else If FlagClr in FilterSettings.Flags then begin BitOps.SetFlagStateValue(FlagsMap,BitMask,not(ItemFlag in fFlags)); BitOps.SetFlagValue(FlagsMask,BitMask); end else begin BitOps.ResetFlagValue(FlagsMap,BitMask); BitOps.ResetFlagValue(FlagsMask,BitMask); end; end; begin If fDataAccessible then begin FlagsMap := 0; FlagsMask := 0; If FilterSettings.Flags <> [] then begin CheckItemFlag($00000001,ilifOwned,ilffOwnedSet,ilffOwnedClr); CheckItemFlag($00000002,ilifWanted,ilffWantedSet,ilffWantedClr); CheckItemFlag($00000004,ilifOrdered,ilffOrderedSet,ilffOrderedClr); CheckItemFlag($00000008,ilifBoxed,ilffBoxedSet,ilffBoxedClr); CheckItemFlag($00000010,ilifElsewhere,ilffElsewhereSet,ilffElsewhereClr); CheckItemFlag($00000020,ilifUntested,ilffUntestedSet,ilffUntestedClr); CheckItemFlag($00000040,ilifTesting,ilffTestingSet,ilffTestingClr); CheckItemFlag($00000080,ilifTested,ilffTestedSet,ilffTestedClr); CheckItemFlag($00000100,ilifDamaged,ilffDamagedSet,ilffDamagedClr); CheckItemFlag($00000200,ilifRepaired,ilffRepairedSet,ilffRepairedClr); CheckItemFlag($00000400,ilifPriceChange,ilffPriceChangeSet,ilffPriceChangeClr); CheckItemFlag($00000800,ilifAvailChange,ilffAvailChangeSet,ilffAvailChangeClr); CheckItemFlag($00001000,ilifNotAvailable,ilffNotAvailableSet,ilffNotAvailableClr); CheckItemFlag($00002000,ilifLost,ilffLostSet,ilffLostClr); CheckItemFlag($00004000,ilifDiscarded,ilffDiscardedSet,ilffDiscardedClr); end; StateSet := False; State := False; // will be later set to true value If FlagsMask <> 0 then begin For i := 0 to Ord(High(TILItemFlag)) do begin If FlagsMask and 1 <> 0 then begin If StateSet then begin case FilterSettings.Operator of ilfoOR: State := State or (FlagsMap and 1 <> 0); ilfoXOR: State := State xor (FlagsMap and 1 <> 0); else {ilfoAND} State := State and (FlagsMap and 1 <> 0); end; end else begin State := FlagsMap and 1 <> 0; StateSet := True; end; end; FlagsMap := FlagsMap shr 1; FlagsMask := FlagsMask shr 1; end; end else State := True; fFilteredOut := not State; end else fFilteredOut := False; end; end.
unit InflatablesList_HTML_Utils; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses SysUtils, AuxTypes; //============================================================================== //- special parsing exception -------------------------------------------------- type EILHTMLParseError = class(Exception); //============================================================================== //- unicode strings manipulation ----------------------------------------------- Function IL_UTF16HighSurrogate(CodePoint: UInt32): UnicodeChar; Function IL_UTF16LowSurrogate(CodePoint: UInt32): UnicodeChar; Function IL_UTF16CodePoint(HighSurrogate,LowSurrogate: UnicodeChar): UInt32; Function IL_UTF16CharInSet(UTF16Char: UnicodeChar; CharSet: TSysCharSet): Boolean; Function IL_UnicodeCompareString(const A,B: UnicodeString; CaseSensitive: Boolean): Integer; Function IL_UnicodeSameString(const A,B: UnicodeString; CaseSensitive: Boolean): Boolean; implementation uses StrRect; //============================================================================== //- unicode strings manipulation ----------------------------------------------- Function IL_UTF16HighSurrogate(CodePoint: UInt32): UnicodeChar; begin If CodePoint >= $10000 then Result := UnicodeChar(((CodePoint - $10000) shr 10) + $D800) else Result := UnicodeChar(CodePoint); end; //------------------------------------------------------------------------------ Function IL_UTF16LowSurrogate(CodePoint: UInt32): UnicodeChar; begin If CodePoint >= $10000 then Result := UnicodeChar(((CodePoint - $10000) and $3FF) + $DC00) else Result := UnicodeChar(CodePoint); end; //------------------------------------------------------------------------------ Function IL_UTF16CodePoint(HighSurrogate,LowSurrogate: UnicodeChar): UInt32; begin Result := UInt32(((Ord(HighSurrogate) - $D800) shl 10) + (Ord(LowSurrogate) - $DC00) + $10000); end; //------------------------------------------------------------------------------ Function IL_UTF16CharInSet(UTF16Char: UnicodeChar; CharSet: TSysCharSet): Boolean; begin If Ord(UTF16Char) <= $FF then Result := AnsiChar(UTF16Char) in CharSet else Result := False end; //------------------------------------------------------------------------------ Function IL_UnicodeCompareString(const A,B: UnicodeString; CaseSensitive: Boolean): Integer; begin Result := StrRect.UnicodeStringCompare(A,B,CaseSensitive); end; //------------------------------------------------------------------------------ Function IL_UnicodeSameString(const A,B: UnicodeString; CaseSensitive: Boolean): Boolean; begin Result := StrRect.UnicodeStringCompare(A,B,CaseSensitive) = 0; end; end.
unit uOpHelper; {$I ..\Include\IntXLib.inc} interface uses Math, SysUtils, uConstants, uDigitHelper, uStrings, uDigitOpHelper, uXBits, uEnums, uIMultiplier, uMultiplyManager, uPcgRandomMinimal, uMillerRabin, uUtils, uIntXLibTypes, uIntX; type /// <summary> /// Contains helping methods for operations over <see cref="TIntX" />. /// </summary> TOpHelper = class sealed(TObject) public const /// <summary> /// Constant used for internal operations. /// </summary> kcbitUint = Integer(32); type /// <summary> /// record used for internal operations. /// </summary> /// <remarks> /// Both record fields are aligned at zero offsets. /// </remarks> TDoubleUlong = packed record case Byte of 0: ( /// <summary> /// Double variable used for internal operations. /// </summary> dbl: Double ); 1: ( /// <summary> /// UInt64 variable used for internal operations. /// </summary> uu: UInt64 ); end; type /// <summary> /// Record used for internal building operations. /// </summary> TBuilder = record private // class var /// <summary> /// Integer variable used for internal operations. /// </summary> /// <remarks>For a single UInt32, _iuLast is 0.</remarks> _iuLast: Integer; /// <summary> /// UInt32 variable used for internal operations. /// </summary> /// <remarks>Used if _iuLast = 0.</remarks> _uSmall: UInt32; /// <summary> /// <see cref="TIntXLibUInt32Array" /> used for internal operations. /// </summary> /// <remarks>Used if _iuLast > 0.</remarks> _rgu: TIntXLibUInt32Array; public /// <summary> /// Used to create an Instance of <see cref="TOpHelper.TBuilder" />. for internal use only. /// </summary> constructor Create(bn: TIntX; var sign: Integer); /// <summary> /// Function used for Internal operations. /// </summary> procedure GetApproxParts(out exp: Integer; out man: UInt64); end; public /// <summary> /// Function used for Internal operations. /// </summary> class function CbitHighZero(u: UInt32): Integer; overload; static; /// <summary> /// Function used for Internal operations. /// </summary> class function CbitHighZero(uu: UInt64): Integer; overload; static; /// <summary> /// Function used for Internal operations. /// </summary> class function MakeUlong(uHi: UInt32; uLo: UInt32): UInt64; static; { /// <summary> /// Helper method used in computing Integer SquareRoot. /// </summary> /// <param name="n"> /// Internal variable /// </param> /// <param name="g"> /// Internal variable /// </param> /// <param name="last"> /// Internal variable /// </param> class function Guesser(n: TIntX; g: TIntX; last: TIntX): TIntX; static; } /// <summary> /// Returns the number of trailing 0-bits in x, starting at the least significant /// bit position. /// </summary> /// <param name="x">value to get number of trailing zero bits.</param> /// <returns>number of trailing 0-bits.</returns> /// <remarks>If x is 0, the result is undefined as per GCC Implementation.</remarks> class function __builtin_ctz(x: UInt32): Integer; inline; static; public /// <summary> /// Adds two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Resulting big integer.</returns> /// <exception cref="EArgumentException"><paramref name="int1" /> or <paramref name="int2" /> is too big for add operation.</exception> class function Add(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// Subtracts two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Resulting big integer.</returns> class function Sub(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// Adds/subtracts one <see cref="TIntX" /> to/from another. /// Determines which operation to use basing on operands signs. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <param name="subtract">Was subtraction initially.</param> /// <returns>Add/subtract operation result.</returns> /// <exception cref="EArgumentNilException"><paramref name="int1" /> or <paramref name="int2" /> is a null reference.</exception> class function AddSub(int1: TIntX; int2: TIntX; subtract: Boolean) : TIntX; static; /// <summary> /// Returns a specified big integer raised to the specified power. /// </summary> /// <param name="value">Number to raise.</param> /// <param name="power">Power.</param> /// <param name="multiplyMode">Multiply mode set explicitly.</param> /// <returns>Number in given power.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class function Pow(value: TIntX; power: UInt32; multiplyMode: TMultiplyMode) : TIntX; static; /// <summary> /// Returns a Non-Negative Random <see cref="TIntX" /> object using Pcg Random. /// </summary> /// <returns>Random TIntX value.</returns> class function Random(): TIntX; static; /// <summary> /// Returns a Non-Negative Random <see cref="TIntX" /> object using Pcg Random within the specified Range. (Max not Included) /// </summary> /// <param name="Min">Minimum value.</param> /// <param name="Max">Maximum value (Max not Included)</param> /// <returns>Random TIntX value.</returns> class function RandomRange(Min: UInt32; Max: UInt32): TIntX; static; /// <summary> /// Returns a non negative big integer. /// </summary> /// <param name="value">value to get its absolute value.</param> /// <returns>Absolute number.</returns> class function AbsoluteValue(value: TIntX): TIntX; static; /// <summary> /// The base-10 logarithm of the value. /// </summary> /// <param name="value">The value.</param> /// <returns>The base-10 logarithm of the value.</returns> /// <remarks> Source : Microsoft .NET Reference on GitHub </remarks> class function Log10(value: TIntX): Double; static; /// <summary> /// Calculates the natural logarithm of the value. /// </summary> /// <param name="value">The value.</param> /// <returns>The natural logarithm.</returns> /// <remarks> Source : Microsoft .NET Reference on GitHub </remarks> class function Ln(value: TIntX): Double; static; /// <summary> /// Calculates Logarithm of a number <see cref="TIntX" /> object for a specified base. /// the largest power the base can be raised to that does not exceed the number. /// </summary> /// <param name="base">base.</param> /// <param name="value">number to get log of.</param> /// <returns>Log value.</returns> /// <remarks> Source : Microsoft .NET Reference on GitHub </remarks> class function LogN(base: Double; value: TIntX): Double; static; /// <summary> /// Calculates Integer Logarithm of a number <see cref="TIntX" /> object for a specified base. /// the largest power the base can be raised to that does not exceed the number. /// </summary> /// <param name="base">base.</param> /// <param name="number">number to get Integer log of.</param> /// <returns>Integer Log.</returns> /// <seealso href="http://gist.github.com/dharmatech/409723">[IntegerLogN Implementation]</seealso> class function IntegerLogN(base: TIntX; number: TIntX): TIntX; static; /// <summary> /// Returns a specified big integer raised to the power of 2. /// </summary> /// <param name="value">Number to get its square.</param> /// <returns>Squared number.</returns> class function Square(value: TIntX): TIntX; static; /// <summary> /// Calculates Integer SquareRoot of <see cref="TIntX" /> object /// </summary> /// <param name="value">value to get Integer squareroot of.</param> /// <returns>Integer SquareRoot.</returns> /// <seealso href="http://www.dahuatu.com/RkWdPBx6W8.html">[IntegerSquareRoot Implementation]</seealso> class function IntegerSquareRoot(value: TIntX): TIntX; static; /// <summary> /// Returns a specified big integer holding the factorial of value. /// </summary> /// <param name="value">Number to get its factorial.</param> /// <returns>factorialed number.</returns> /// <exception cref="EArgumentException"><paramref name="value" /> is a negative value.</exception> class function Factorial(value: TIntX): TIntX; static; /// <summary> /// (Optimized GCD). /// Returns a specified big integer holding the GCD (Greatest common Divisor) of /// two big integers using Binary GCD (Stein's algorithm). /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>GCD number.</returns> /// <seealso href="http://lemire.me/blog/archives/2013/12/26/fastest-way-to-compute-the-greatest-common-divisor/">[GCD Implementation]</seealso> /// <seealso href="https://hbfs.wordpress.com/2013/12/10/the-speed-of-gcd/">[GCD Implementation Optimizations]</seealso> class function GCD(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// (LCM). /// Returns a specified big integer holding the LCM (Least Common Multiple) of /// two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>LCM number.</returns> /// <exception cref="EArgumentNilException"><paramref name="int1" /> is a null reference.</exception> /// <exception cref="EArgumentNilException"><paramref name="int2" /> is a null reference.</exception> class function LCM(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// Calculate Modular Inverse for two <see cref="TIntX" /> objects using Euclids Extended Algorithm. /// returns Zero if no Modular Inverse Exists for the Inputs /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Modular Inverse.</returns> /// <seealso href="https://en.wikipedia.org/wiki/Modular_multiplicative_inverse">[Modular Inverse Explanation]</seealso> /// <seealso href="http://www.di-mgt.com.au/euclidean.html">[Modular Inverse Implementation]</seealso> class function InvMod(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// Calculates Calculates Modular Exponentiation of <see cref="TIntX" /> object. /// </summary> /// <param name="value">value to compute ModPow of.</param> /// <param name="exponent">exponent to use.</param> /// <param name="modulus">modulus to use.</param> /// <returns>Computed value.</returns> /// <seealso href="https://en.wikipedia.org/wiki/Modular_exponentiation">[Modular Exponentiation Explanation]</seealso> class function ModPow(value: TIntX; exponent: TIntX; modulus: TIntX) : TIntX; static; /// <summary> /// Calculates Bézoutsidentity for two <see cref="TIntX" /> objects using Euclids Extended Algorithm /// </summary> /// <param name="int1">first value.</param> /// <param name="int2">second value.</param> /// <param name="bezOne">first bezout value.</param> /// <param name="bezTwo">second bezout value.</param> /// <returns>GCD (Greatest Common Divisor) value.</returns> /// <seealso href="https://en.wikipedia.org/wiki/Bézout's_identity">[Bézout's identity Explanation]</seealso> /// <seealso href="https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode">[Bézout's identity Pseudocode using Extended Euclidean algorithm]</seealso> class function Bezoutsidentity(int1: TIntX; int2: TIntX; out bezOne: TIntX; out bezTwo: TIntX): TIntX; static; /// <summary> /// Checks if a <see cref="TIntX" /> object is Probably Prime using Miller–Rabin primality test. /// </summary> /// <param name="value">big integer to check primality.</param> /// <param name="Accuracy">Accuracy parameter `k´ of the Miller-Rabin algorithm. Default is 5. The execution time is proportional to the value of the accuracy parameter.</param> /// <returns>Boolean value.</returns> /// <seealso href="https://en.wikipedia.org/wiki/Miller–Rabin_primality_test">[Miller–Rabin primality test Explanation]</seealso> /// <seealso href="https://github.com/cslarsen/miller-rabin">[Miller–Rabin primality test Implementation in C]</seealso> class function IsProbablyPrime(value: TIntX; Accuracy: Integer = 5) : Boolean; static; /// <summary> /// The Max Between Two TIntX values. /// </summary> /// <param name="left">left value.</param> /// <param name="right">right value.</param> /// <returns>The Maximum TIntX value.</returns> class function Max(left: TIntX; right: TIntX): TIntX; static; /// <summary> /// The Min Between Two TIntX values. /// </summary> /// <param name="left">left value.</param> /// <param name="right">right value.</param> /// <returns>The Minimum TIntX value.</returns> class function Min(left: TIntX; right: TIntX): TIntX; static; /// <summary> /// Compares 2 <see cref="TIntX" /> objects. /// Returns "-2" if any argument is null, "-1" if <paramref name="int1" /> &lt; <paramref name="int2" />, /// "0" if equal and "1" if &gt;. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <param name="throwNullException">Raises or not <see cref="EArgumentNilException" />.</param> /// <returns>Comparison result.</returns> /// <exception cref="EArgumentNilException"><paramref name="int1" /> or <paramref name="int2" /> is a null reference and <paramref name= "throwNullException" /> is set to true.</exception> class function Cmp(int1: TIntX; int2: TIntX; throwNullException: Boolean) : Integer; overload; static; /// <summary> /// Compares <see cref="TIntX" /> object to int. /// Returns "-1" if <paramref name="int1" /> &lt; <paramref name="int2" />, "0" if equal and "1" if &gt;. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second integer.</param> /// <returns>Comparison result.</returns> class function Cmp(int1: TIntX; int2: Integer): Integer; overload; static; /// <summary> /// Compares <see cref="TIntX" /> object to unsigned int. /// Returns "-1" if <paramref name="int1" /> &lt; <paramref name="int2" />, "0" if equal and "1" if &gt;. /// For internal use. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second unsigned integer.</param> /// <returns>Comparison result.</returns> class function Cmp(int1: TIntX; int2: UInt32): Integer; overload; static; /// <summary> /// Shifts <see cref="TIntX" /> object. /// Determines which operation to use based on shift sign. /// </summary> /// <param name="IntX">Big integer.</param> /// <param name="shift">Bits count to shift.</param> /// <param name="toLeft">If true the shifting to the left.</param> /// <returns>Bitwise shift operation result.</returns> /// <exception cref="EArgumentNilException"><paramref name="IntX" /> is a null reference.</exception> class function Sh(IntX: TIntX; shift: Int64; toLeft: Boolean) : TIntX; static; /// <summary> /// Performs bitwise OR for two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Resulting big integer.</returns> /// <exception cref="EArgumentNilException"><paramref name="int1" /> or <paramref name="int2" /> is a null reference.</exception> class function BitwiseOr(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// Performs bitwise AND for two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Resulting big integer.</returns> /// <exception cref="EArgumentNilException"><paramref name="int1" /> or <paramref name="int2" /> is a null reference.</exception> class function BitwiseAnd(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// Performs bitwise XOR for two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Resulting big integer.</returns> /// <exception cref="EArgumentNilException"><paramref name="int1" /> or <paramref name="int2" /> is a null reference.</exception> class function ExclusiveOr(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// Performs bitwise NOT for big integer. /// </summary> /// <param name="value">Big integer.</param> /// <returns>Resulting big integer.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class function OnesComplement(value: TIntX): TIntX; static; /// <summary> /// Function used for Internal operations. /// </summary> /// <param name="mdbl"> /// internal variable /// </param> /// <param name="sign"> /// variable used to indicate sign /// </param> /// <param name="exp"> /// internal variable /// </param> /// <param name="man"> /// internal variable /// </param> /// <param name="fFinite"> /// internal variable /// </param> /// <remarks> /// Source : Microsoft .NET Reference on GitHub /// </remarks> class procedure GetDoubleParts(mdbl: Double; out sign: Integer; out exp: Integer; out man: UInt64; out fFinite: Boolean); static; /// <summary> /// Function used for Internal operations. /// </summary> /// <param name="sign"> /// variable indicating sign /// </param> /// <param name="exp"> /// variable used for internal operations /// </param> /// <param name="man"> /// variable used for internal operations /// </param> /// <remarks> /// Source : Microsoft .NET Reference on GitHub /// </remarks> class function GetDoubleFromParts(sign: Integer; exp: Integer; man: UInt64) : Double; static; /// <summary> /// function used for Internal operations /// </summary> /// <param name="value"> /// value to process /// </param> /// <param name="digits"> /// digits array to process /// </param> /// <param name="newInt"> /// output result /// </param> /// <remarks> /// Source : Microsoft .NET Reference on GitHub /// </remarks> class procedure SetDigitsFromDouble(value: Double; var digits: TIntXLibUInt32Array; out newInt: TIntX); end; implementation constructor TOpHelper.TBuilder.Create(bn: TIntX; var sign: Integer); var n, mask: Integer; begin _rgu := bn._digits; if bn.isZero then n := 0 else if bn.IsNegative then n := -1 else n := 1; mask := TUtils.Asr32(n, (kcbitUint - 1)); sign := (sign xor mask) - mask; _iuLast := bn._length - 1; // Length(_rgu) - 1 _uSmall := _rgu[0]; while ((_iuLast > 0) and (_rgu[_iuLast] = 0)) do Dec(_iuLast); end; procedure TOpHelper.TBuilder.GetApproxParts(out exp: Integer; out man: UInt64); var cuLeft, cbit: Integer; begin if (_iuLast = 0) then begin man := UInt64(_uSmall); exp := 0; Exit; end; cuLeft := _iuLast - 1; man := MakeUlong(_rgu[cuLeft + 1], _rgu[cuLeft]); exp := cuLeft * kcbitUint; cbit := CbitHighZero(_rgu[cuLeft + 1]); if ((cuLeft > 0) and (cbit > 0)) then begin // Get 64 bits. {$IFDEF DEBUG} Assert(cbit < kcbitUint); {$ENDIF DEBUG} man := (man shl cbit) or (_rgu[cuLeft - 1] shr (kcbitUint - cbit)); exp := exp - cbit; end; end; class function TOpHelper.MakeUlong(uHi: UInt32; uLo: UInt32): UInt64; begin result := (UInt64(uHi) shl kcbitUint) or uLo; end; class function TOpHelper.CbitHighZero(u: UInt32): Integer; var cbit: Integer; begin if (u = 0) then begin result := 32; Exit; end; cbit := 0; if ((u and $FFFF0000) = 0) then begin cbit := cbit + 16; u := u shl 16; end; if ((u and $FF000000) = 0) then begin cbit := cbit + 8; u := u shl 8; end; if ((u and $F0000000) = 0) then begin cbit := cbit + 4; u := u shl 4; end; if ((u and $C0000000) = 0) then begin cbit := cbit + 2; u := u shl 2; end; if ((u and $80000000) = 0) then cbit := cbit + 1; result := cbit; end; class function TOpHelper.CbitHighZero(uu: UInt64): Integer; begin if ((uu and $FFFFFFFF00000000) = 0) then result := 32 + CbitHighZero(UInt32(uu)) else result := CbitHighZero(UInt32(uu shr 32)); end; { class function TOpHelper.Guesser(n: TIntX; g: TIntX; last: TIntX): TIntX; begin if ((last >= (g - 1)) and (last <= (g + 1))) then begin result := g; Exit; end else begin result := Guesser(n, (g + (n div g)) shr 1, g); Exit; end; end; } class function TOpHelper.Add(int1: TIntX; int2: TIntX): TIntX; var x, smallerInt, biggerInt, newInt: TIntX; begin // Process zero values in special way if ((int1._length = 0) and (int2._length = 0)) then begin result := TIntX.Create(0); Exit; end; if (int2._length = 0) then begin result := TIntX.Create(int1); Exit; end; if (int1._length = 0) then begin x := TIntX.Create(int2); x._negative := int1._negative; // always get sign of the first big integer result := x; Exit; end; // Determine big int with lower length TDigitHelper.GetMinMaxLengthObjects(int1, int2, smallerInt, biggerInt); // Check for add operation possibility if (biggerInt._length = TConstants.MaxUInt32Value) then begin raise EArgumentException.Create(uStrings.IntegerTooBig); end; // Create new big int object of needed length newInt := TIntX.Create(biggerInt._length + 1, int1._negative); // Do actual addition newInt._length := TDigitOpHelper.Add(biggerInt._digits, biggerInt._length, smallerInt._digits, smallerInt._length, newInt._digits); // Normalization may be needed newInt.TryNormalize(); result := newInt; end; class function TOpHelper.Sub(int1: TIntX; int2: TIntX): TIntX; var smallerInt, biggerInt, newInt: TIntX; compareResult: Integer; tempState: Boolean; begin // Process zero values in special way if ((int1._length = 0) and (int2._length = 0)) then begin result := TIntX.Create(0); Exit; end; if (int1._length = 0) then begin result := TIntX.Create(int2._digits, True); Exit; end; if (int2._length = 0) then begin result := TIntX.Create(int1); Exit; end; // Determine lower big int (without sign) compareResult := TDigitOpHelper.Cmp(int1._digits, int1._length, int2._digits, int2._length); if (compareResult = 0) then begin result := TIntX.Create(0); // integers are equal Exit; end; if (compareResult < 0) then begin smallerInt := int1; biggerInt := int2; end else begin smallerInt := int2; biggerInt := int1; end; tempState := TIntX.CompareRecords(int1, smallerInt); // Create new big TIntX object newInt := TIntX.Create(biggerInt._length, tempState xor int1._negative); // Do actual subtraction newInt._length := TDigitOpHelper.Sub(biggerInt._digits, biggerInt._length, smallerInt._digits, smallerInt._length, newInt._digits); // Normalization may be needed newInt.TryNormalize(); result := newInt; end; class function TOpHelper.AddSub(int1: TIntX; int2: TIntX; subtract: Boolean): TIntX; begin // Exceptions if TIntX.CompareRecords(int1, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' int1'); if TIntX.CompareRecords(int2, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' int2'); // Determine real operation type and result sign if (subtract xor int1._negative = int2._negative) then result := Add(int1, int2) else result := Sub(int1, int2); end; class function TOpHelper.Pow(value: TIntX; power: UInt32; multiplyMode: TMultiplyMode): TIntX; var msb: Integer; multiplier: IIMultiplier; res: TIntX; powerMask: UInt32; begin // Exception if TIntX.CompareRecords(value, Default (TIntX)) then begin raise EArgumentNilException.Create('value'); end; // Return one for zero pow if (power = 0) then begin result := 1; Exit; end; // Return the number itself from a power of one if (power = 1) then begin result := TIntX.Create(value); Exit; end; // Return zero for a zero if (value._length = 0) then begin result := TIntX.Create(0); Exit; end; // optimization if value (base) is 2. if value = 2 then begin result := TIntX.One shl power; Exit; end; // Get first one bit msb := TBits.msb(power); // Get multiplier multiplier := TMultiplyManager.GetMultiplier(multiplyMode); // Do actual raising res := value; powerMask := UInt32(1) shl (msb - 1); while powerMask <> 0 do begin // Always square res := multiplier.Multiply(res, res); // Maybe mul if ((power and powerMask) <> 0) then begin res := multiplier.Multiply(res, value); end; powerMask := powerMask shr 1; end; result := res; end; class function TOpHelper.Random(): TIntX; begin result := TPcg.NextUInt32(); end; class function TOpHelper.RandomRange(Min: UInt32; Max: UInt32): TIntX; begin result := TPcg.NextUInt32(Min, Max); end; class function TOpHelper.AbsoluteValue(value: TIntX): TIntX; begin if value._negative then result := -value else result := value; end; class function TOpHelper.Log10(value: TIntX): Double; begin result := TIntX.LogN(10, value); end; class function TOpHelper.Ln(value: TIntX): Double; begin result := TIntX.LogN(TConstants.EulersNumber, value); end; (* class function TOpHelper.LogN(base: Double; value: TIntX): Double; var c, d: Double; uintLength, topbits, bitlen, index: Int64; indbit: UInt32; const DoubleZero: Double = 0; constOne: Double = 1.0; DoubleNaN: Double = 0.0 / 0.0; DoublePositiveInfinity: Double = 1.0 / 0.0; ZeroPointZero: Double = 0.0; Log2: Double = 0.69314718055994529; kcbitUint: Integer = 32; begin c := 0; d := 0.5; if ((value.IsNegative) or (base = constOne)) then begin result := DoubleNaN; Exit; end; if (base = DoublePositiveInfinity) then begin if value.isOne then begin result := ZeroPointZero; Exit; end else begin result := DoubleNaN; Exit; end; end; if ((base = ZeroPointZero) and (not(value.isOne))) then begin result := DoubleNaN; Exit; end; if (value._digits = Nil) then begin result := Math.LogN(base, DoubleZero); Exit; end; uintLength := Int64(Length(value._digits)); topbits := Int64(TBits.BitLengthOfUInt(value._digits[uintLength - 1])); bitlen := Int64((uintLength - 1) * kcbitUint + topbits); indbit := Int64(UInt32(1 shl (topbits - 1))); index := uintLength - 1; while index >= 0 do begin while (indbit <> 0) do begin if ((value._digits[index] and indbit) <> 0) then begin c := c + d; end; d := d * 0.5; indbit := indbit shr 1; end; indbit := $80000000; Dec(index); end; result := (System.Ln(c) + Log2 * bitlen) / System.Ln(base); end; *) class function TOpHelper.LogN(base: Double; value: TIntX): Double; var tempD, tempTwo, pa, pb, pc, tempDouble: Double; c: Integer; b: Int64; h, m, l, x: UInt64; const constOne: Double = 1.0; DoubleNaN: Double = 0.0 / 0.0; DoublePositiveInfinity: Double = 1.0 / 0.0; DoubleNegativeInfinity: Double = -1.0 / 0.0; ZeroPointZero: Double = 0.0; begin if ((value.IsNegative) or (base = constOne)) then begin result := DoubleNaN; Exit; end; if (base = DoublePositiveInfinity) then begin if value.IsOne then begin result := ZeroPointZero; Exit; end else begin result := DoubleNaN; Exit; end; end; if ((base = ZeroPointZero) and (not(value.IsOne))) then begin result := DoubleNaN; Exit; end; if (value._digits = Nil) then begin result := DoubleNegativeInfinity; Exit; end; if (value <= TConstants.MaxUInt64Value) then begin tempDouble := UInt64(value); result := Math.LogN(base, tempDouble); Exit; end; // h := value._digits[Length(value._digits) - 1]; h := value._digits[value._length - 1]; // if Length(value._digits) > 1 then if value._length > 1 then // m := value._digits[Length(value._digits) - 2] m := value._digits[value._length - 2] else m := 0; // if Length(value._digits) > 2 then if value._length > 2 then // l := value._digits[Length(value._digits) - 3] l := value._digits[value._length - 3] else l := 0; // measure the exact bit count c := CbitHighZero(UInt32(h)); // b := ((Int64(Length(value._digits))) * 32) - c; b := ((Int64(value._length)) * 32) - c; // extract most significant bits x := (h shl (32 + c)) or (m shl c) or (l shr (32 - c)); tempD := x; tempTwo := 2; pa := Math.LogN(base, tempD); pc := Math.LogN(tempTwo, base); pb := (b - 64) / pc; result := pa + pb; end; class function TOpHelper.IntegerLogN(base: TIntX; number: TIntX): TIntX; var lo, b_lo, hi, mid, b_mid, b_hi: TIntX; begin lo := TIntX.Zero; b_lo := TIntX.One; hi := TIntX.One; b_hi := base; while (b_hi < number) do begin lo := hi; b_lo := b_hi; hi := hi * 2; b_hi := b_hi * b_hi; end; while ((hi - lo) > 1) do begin mid := (lo + hi) div 2; b_mid := b_lo * Integer(TIntX.Pow(base, UInt32(mid - lo))); if number < b_mid then begin hi := mid; b_hi := b_mid; end; if number > b_mid then begin lo := mid; b_lo := b_mid; end; if number = b_mid then begin result := mid; Exit; end; end; if b_hi = number then result := hi else result := lo; end; class function TOpHelper.Square(value: TIntX): TIntX; begin result := TIntX.Pow(value, 2); end; class function TOpHelper.IntegerSquareRoot(value: TIntX): TIntX; var // sn: String; a, b, mid, eight: TIntX; begin if (value.isZero) then begin result := TIntX.Zero; Exit; end; if (value.IsOne) then begin result := TIntX.One; Exit; end; a := TIntX.One; eight := TIntX.Create(8); b := (value shr 5) + eight; while b.CompareTo(a) >= 0 do begin mid := (a + b) shr 1; if (mid * mid).CompareTo(value) > 0 then begin b := (mid - TIntX.One); end else begin a := (mid + TIntX.One); end; end; result := a - TIntX.One; { if (value > 999) then begin sn := value.ToString(); result := Guesser(value, TIntX.Parse(Copy(sn, 1, Length(sn) shr 1)), TIntX.Zero); Exit; end else begin result := Guesser(value, value shr 1, TIntX.Zero); Exit; end; } end; class function TOpHelper.Factorial(value: TIntX): TIntX; var I: TIntX; begin // Exception if (value < 0) then raise EArgumentException.Create(Format(uStrings.NegativeFactorial, [value.ToString], TIntX._FS)); result := 1; // using iterative approach // recursive approach is slower and causes much overhead. it is also limiting (stackoverflow) I := 1; while I <= value do begin result := result * I; Inc(I); end; end; class function TOpHelper.__builtin_ctz(x: UInt32): Integer; var n: Integer; begin // This uses a binary search algorithm from Hacker's Delight. n := 1; if ((x and $0000FFFF) = 0) then begin n := n + 16; x := x shr 16; end; if ((x and $000000FF) = 0) then begin n := n + 8; x := x shr 8; end; if ((x and $0000000F) = 0) then begin n := n + 4; x := x shr 4; end; if ((x and $00000003) = 0) then begin n := n + 2; x := x shr 2; end; result := n - Integer(x and 1); end; class function TOpHelper.GCD(int1: TIntX; int2: TIntX): TIntX; var shift: Integer; temp: TIntX; begin // check if int1 is negative and returns the absolute value of it. if int1._negative then int1 := AbsoluteValue(int1); // check if int2 is negative and returns the absolute value of it. if int2._negative then int2 := AbsoluteValue(int2); // simple cases (termination) if (int1 = int2) then begin result := int1; Exit; end; if (int1 = 0) then begin result := int2; Exit; end; if (int2 = 0) then begin result := int1; Exit; end; shift := __builtin_ctz(UInt32(int1 or int2)); int1 := int1 shr __builtin_ctz(UInt32(int1)); while (int2 <> 0) do begin int2 := int2 shr __builtin_ctz(UInt32(int2)); if (int1 > int2) then begin temp := int2; int2 := int1; int1 := temp; end; int2 := int2 - int1; end; result := int1 shl shift; end; class function TOpHelper.LCM(int1: TIntX; int2: TIntX): TIntX; begin result := (TIntX.AbsoluteValue(int1 * int2)) div (TIntX.GCD(int1, int2)); end; class function TOpHelper.InvMod(int1: TIntX; int2: TIntX): TIntX; var u1, u3, v1, v3, t1, t3, q, iter: TIntX; begin // /* Step X1. Initialize */ u1 := 1; u3 := int1; v1 := 0; v3 := int2; // /* Remember odd/even iterations */ iter := 1; // /* Step X2. Loop while v3 != 0 */ while (v3 <> 0) do begin /// * Step X3. Divide and "Subtract" */ q := u3 div v3; t3 := u3 mod v3; t1 := u1 + q * v1; // /* Swap */ u1 := v1; v1 := t1; u3 := v3; v3 := t3; iter := -iter; end; // /* Make sure u3 = gcd(u,v) == 1 */ if (u3 <> 1) then // u3 is now holding the GCD Value begin result := 0; // /* Error: No inverse exists */ Exit; end; // /* Ensure a positive result */ // result will hold the Modular Inverse (InvMod) if (iter < 0) then result := int2 - u1 else result := u1; end; class function TOpHelper.ModPow(value: TIntX; exponent: TIntX; modulus: TIntX): TIntX; begin result := 1; value := value mod modulus; while exponent > 0 do begin if exponent.IsOdd then begin result := (result * value) mod modulus; end; exponent := exponent shr 1; value := (value * value) mod modulus; end; end; class function TOpHelper.Bezoutsidentity(int1: TIntX; int2: TIntX; out bezOne: TIntX; out bezTwo: TIntX): TIntX; var s, t, r, old_s, old_t, old_r, quotient, prov: TIntX; begin if int1._negative then raise EArgumentNilException.Create(uStrings.BezoutNegativeNotAllowed + ' int1'); if int2._negative then raise EArgumentNilException.Create(uStrings.BezoutNegativeNotAllowed + ' ' + ' int2'); if (int1 = 0) or (int2 = 0) then raise EArgumentException.Create(uStrings.BezoutNegativeCantComputeZero); s := 0; t := 1; r := int2; old_s := 1; old_t := 0; old_r := int1; while r <> 0 do begin quotient := old_r div r; prov := r; r := old_r - quotient * prov; old_r := prov; prov := s; s := old_s - quotient * prov; old_s := prov; prov := t; t := old_t - quotient * prov; old_t := prov; end; if old_r._negative then begin old_r := TIntX.AbsoluteValue(old_r); end; bezOne := old_s; // old_s holds the first value of bezout identity bezTwo := old_t; // old_t holds the second value of bezout identity result := old_r; // old_r holds the GCD Value end; class function TOpHelper.IsProbablyPrime(value: TIntX; Accuracy: Integer = 5): Boolean; begin result := TMillerRabin.IsProbablyPrimeMR(value, Accuracy); end; class function TOpHelper.Max(left: TIntX; right: TIntX): TIntX; begin if (left.CompareTo(right) < 0) then result := right else result := left; end; class function TOpHelper.Min(left: TIntX; right: TIntX): TIntX; begin if (left.CompareTo(right) <= 0) then result := left else result := right; end; class function TOpHelper.Cmp(int1: TIntX; int2: TIntX; throwNullException: Boolean): Integer; var isNull1, isNull2: Boolean; begin // If one of the operands is null, throw exception or return -2 isNull1 := TIntX.CompareRecords(int1, Default (TIntX)); isNull2 := TIntX.CompareRecords(int2, Default (TIntX)); if (isNull1 or isNull2) then begin if (throwNullException) then begin if isNull1 then raise EArgumentNilException.Create(uStrings.CantBeNullCmp + ' int1') else if isNull2 then raise EArgumentNilException.Create(uStrings.CantBeNullCmp + ' int2') end else begin if (isNull1 and isNull2) then begin result := 0; Exit; end else begin result := -2; Exit; end; end; end; // Compare sign if (int1._negative and not int2._negative) then begin result := -1; Exit; end; if (not int1._negative and int2._negative) then begin result := 1; Exit; end; // Compare presentation if int1._negative then result := TDigitOpHelper.Cmp(int1._digits, int1._length, int2._digits, int2._length) * -1 else result := TDigitOpHelper.Cmp(int1._digits, int1._length, int2._digits, int2._length) * 1; end; class function TOpHelper.Cmp(int1: TIntX; int2: Integer): Integer; var digit2: UInt32; negative2, zeroinithelper: Boolean; begin // Special processing for zero if (int2 = 0) then begin if int1._length = 0 then begin result := 0; Exit; end else begin if int1._negative then begin result := -1; Exit; end else begin result := 1; Exit; end; end; end; if (int1._length = 0) then begin if int2 > 0 then begin result := -1; Exit; end else begin result := 1; Exit; end; end; // Compare presentation if (int1._length > 1) then begin if int1._negative then begin result := -1; Exit; end else begin result := 1; Exit; end; end; TDigitHelper.ToUInt32WithSign(int2, digit2, negative2, zeroinithelper); // Compare sign if (int1._negative and not negative2) then begin result := -1; Exit; end; if (not int1._negative and negative2) then begin result := 1; Exit; end; if int1._digits[0] = digit2 then begin result := 0; Exit; end else begin if (int1._digits[0]) < (digit2 xor UInt32(Ord(negative2))) then begin result := -1; Exit; end else begin result := 1; Exit; end; end; end; class function TOpHelper.Cmp(int1: TIntX; int2: UInt32): Integer; begin // Special processing for zero if (int2 = 0) then begin if int1._length = 0 then begin result := 0; Exit; end else begin if int1._negative then begin result := -1; Exit; end else begin result := 1; Exit; end; end; end; if (int1._length = 0) then begin result := -1; Exit; end; // Compare presentation if (int1._negative) then begin result := -1; Exit; end; if (int1._length > 1) then begin result := 1; Exit; end; if int1._digits[0] = int2 then begin result := 0; Exit; end else begin if int1._digits[0] < int2 then begin result := -1; Exit; end else begin result := 1; Exit; end; end; end; class function TOpHelper.Sh(IntX: TIntX; shift: Int64; toLeft: Boolean): TIntX; var bitCount, intXBitCount, newBitCount: UInt64; negativeShift, zeroinithelper: Boolean; msb, smallShift: Integer; newLength, fullDigits: UInt32; newInt: TIntX; begin // Exceptions if TIntX.CompareRecords(IntX, Default (TIntX)) then begin raise EArgumentNilException.Create(uStrings.CantBeNullOne + ' intX'); end; // Zero can't be shifted if (IntX._length = 0) then begin result := TIntX.Create(0); Exit; end; // Can't shift on zero value if (shift = 0) then begin result := TIntX.Create(IntX); Exit; end; // Determine real bits count and direction TDigitHelper.ToUInt64WithSign(shift, bitCount, negativeShift, zeroinithelper); toLeft := toLeft xor negativeShift; msb := TBits.msb(IntX._digits[IntX._length - 1]); intXBitCount := UInt64(IntX._length - 1) * TConstants.DigitBitCount + UInt64(msb) + UInt64(1); // If shifting to the right and shift is too big then return zero if (not toLeft and (bitCount >= intXBitCount)) then begin result := TIntX.Create(0); Exit; end; // Calculate new bit count if toLeft then newBitCount := intXBitCount + bitCount else newBitCount := intXBitCount - bitCount; // If shifting to the left and shift is too big to fit in big integer, throw an exception if (toLeft and (newBitCount > TConstants.MaxBitCount)) then begin raise EArgumentException.Create(uStrings.IntegerTooBig + ' intX'); end; // Get exact length of new big integer (no normalize is ever needed here). // Create new big integer with given length if newBitCount mod TConstants.DigitBitCount = 0 then newLength := UInt32(newBitCount div TConstants.DigitBitCount + UInt64(0)) else begin newLength := UInt32(newBitCount div TConstants.DigitBitCount + UInt64(1)); end; newInt := TIntX.Create(newLength, IntX._negative); newInt._zeroinithelper := zeroinithelper; // Get full and small shift values fullDigits := UInt32(bitCount div TConstants.DigitBitCount); smallShift := Integer(bitCount mod TConstants.DigitBitCount); // We can just copy (no shift) if small shift is zero if (smallShift = 0) then begin if (toLeft) then begin Move(IntX._digits[0], newInt._digits[fullDigits], IntX._length * SizeOf(UInt32)); end else begin Move(IntX._digits[fullDigits], newInt._digits[0], newLength * SizeOf(UInt32)); end end else begin // Do copy with real shift in the needed direction if (toLeft) then begin TDigitOpHelper.ShiftRight(IntX._digits, 0, IntX._length, newInt._digits, fullDigits + 1, TConstants.DigitBitCount - smallShift); end else begin // If new result length is smaller then original length we shouldn't lose any digits if (newLength < (IntX._length - fullDigits)) then begin Inc(newLength); end; TDigitOpHelper.ShiftRight(IntX._digits, fullDigits, newLength, newInt._digits, 0, smallShift); end; end; result := newInt; end; class function TOpHelper.BitwiseOr(int1: TIntX; int2: TIntX): TIntX; var smallerInt, biggerInt, newInt: TIntX; begin // Exceptions if TIntX.CompareRecords(int1, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' int1'); if TIntX.CompareRecords(int2, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' int2'); // Process zero values in special way if (int1._length = 0) then begin result := TIntX.Create(int2); Exit; end; if (int2._length = 0) then begin result := TIntX.Create(int1); Exit; end; // Determine big int with lower length TDigitHelper.GetMinMaxLengthObjects(int1, int2, smallerInt, biggerInt); // Create new big int object of needed length newInt := TIntX.Create(biggerInt._length, int1._negative or int2._negative); // Do actual operation TDigitOpHelper.BitwiseOr(biggerInt._digits, biggerInt._length, smallerInt._digits, smallerInt._length, newInt._digits); result := newInt; end; class function TOpHelper.BitwiseAnd(int1: TIntX; int2: TIntX): TIntX; var smallerInt, biggerInt, newInt: TIntX; begin // Exceptions if TIntX.CompareRecords(int1, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' int1'); if TIntX.CompareRecords(int2, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' int2'); // Process zero values in special way if ((int1._length = 0) or (int2._length = 0)) then begin result := TIntX.Create(0); Exit; end; // Determine big int with lower length TDigitHelper.GetMinMaxLengthObjects(int1, int2, smallerInt, biggerInt); // Create new big int object of needed length newInt := TIntX.Create(smallerInt._length, int1._negative and int2._negative); // Do actual operation newInt._length := TDigitOpHelper.BitwiseAnd(biggerInt._digits, smallerInt._digits, smallerInt._length, newInt._digits); // Normalization may be needed newInt.TryNormalize(); result := newInt; end; class function TOpHelper.ExclusiveOr(int1: TIntX; int2: TIntX): TIntX; var smallerInt, biggerInt, newInt: TIntX; begin // Exceptions if TIntX.CompareRecords(int1, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' int1'); if TIntX.CompareRecords(int2, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' int2'); // Process zero values in special way if (int1._length = 0) then begin result := TIntX.Create(int2); Exit; end; if (int2._length = 0) then begin result := TIntX.Create(int1); Exit; end; // Determine big int with lower length TDigitHelper.GetMinMaxLengthObjects(int1, int2, smallerInt, biggerInt); // Create new big int object of needed length newInt := TIntX.Create(biggerInt._length, int1._negative xor int2._negative); // Do actual operation newInt._length := TDigitOpHelper.ExclusiveOr(biggerInt._digits, biggerInt._length, smallerInt._digits, smallerInt._length, newInt._digits); // Normalization may be needed newInt.TryNormalize(); result := newInt; end; class function TOpHelper.OnesComplement(value: TIntX): TIntX; var newInt: TIntX; begin // Exception if TIntX.CompareRecords(value, Default (TIntX)) then begin raise EArgumentNilException.Create(uStrings.CantBeNull + ' value'); end; // Process zero values in special way if (value._length = 0) then begin result := TIntX.Create(0); Exit; end; // Create new big TIntX object of needed length newInt := TIntX.Create(value._length, not value._negative); // Do actual operation newInt._length := TDigitOpHelper.OnesComplement(value._digits, value._length, newInt._digits); // Normalization may be needed newInt.TryNormalize(); result := newInt; end; class procedure TOpHelper.GetDoubleParts(mdbl: Double; out sign: Integer; out exp: Integer; out man: UInt64; out fFinite: Boolean); var du: TDoubleUlong; begin du.uu := 0; du.dbl := mdbl; sign := 1 - (Integer(du.uu shr 62) and 2); man := du.uu and $000FFFFFFFFFFFFF; exp := Integer(du.uu shr 52) and $7FF; if (exp = 0) then begin // Denormalized number. fFinite := True; if (man <> 0) then exp := -1074; end else if (exp = $7FF) then begin // NaN or Inifite. fFinite := False; exp := TConstants.MaxIntValue; end else begin fFinite := True; man := man or $0010000000000000; exp := exp - 1075; end; end; class function TOpHelper.GetDoubleFromParts(sign: Integer; exp: Integer; man: UInt64): Double; var du: TDoubleUlong; cbitShift: Integer; begin du.dbl := 0; if (man = 0) then du.uu := 0 else begin // Normalize so that $0010 0000 0000 0000 is the highest bit set. cbitShift := CbitHighZero(man) - 11; if (cbitShift < 0) then man := man shr - cbitShift else begin man := man shl cbitShift; end; exp := exp - cbitShift; {$IFDEF DEBUG} Assert((man and $FFF0000000000000) = $0010000000000000); {$ENDIF DEBUG} // Move the point to just behind the leading 1: $001.0 0000 0000 0000 // (52 bits) and skew the exponent (by $3FF == 1023). exp := exp + 1075; if (exp >= $7FF) then begin // Infinity. du.uu := $7FF0000000000000; end else if (exp <= 0) then begin // Denormalized. Dec(exp); if (exp < -52) then begin // Underflow to zero. du.uu := 0; end else begin du.uu := man shr - exp; {$IFDEF DEBUG} Assert(du.uu <> 0); {$ENDIF DEBUG} end end else begin // Mask off the implicit high bit. du.uu := (man and $000FFFFFFFFFFFFF) or (UInt64(exp) shl 52); end; end; if (sign < 0) then du.uu := du.uu or $8000000000000000; result := du.dbl; end; class procedure TOpHelper.SetDigitsFromDouble(value: Double; var digits: TIntXLibUInt32Array; out newInt: TIntX); var sign, exp, kcbitUlong, kcbitUint, cu, cbit: Integer; man: UInt64; fFinite, tempSign: Boolean; begin kcbitUint := 32; kcbitUlong := 64; TOpHelper.GetDoubleParts(value, sign, exp, man, fFinite); if (man = 0) then begin newInt := TIntX.Zero; Exit; end; {$IFDEF DEBUG} Assert(man < (UInt64(1) shl 53)); Assert((exp <= 0) or (man >= (UInt64(1) shl 52))); {$ENDIF DEBUG} if (exp <= 0) then begin if (exp <= -kcbitUlong) then begin newInt := TIntX.Zero; Exit; end; newInt := man shr - exp; if (sign < 0) then newInt._negative := True; end else if (exp <= 11) then begin newInt := man shl exp; if (sign < 0) then newInt._negative := True; end else begin // Overflow into at least 3 uints. // Move the leading 1 to the high bit. man := man shl 11; exp := exp - 11; // Compute cu and cbit so that exp = 32 * cu - cbit and 0 <= cbit < 32. cu := ((exp - 1) div kcbitUint) + 1; cbit := cu * kcbitUint - exp; {$IFDEF DEBUG} Assert((0 <= cbit) and (cbit < kcbitUint)); Assert(cu >= 1); {$ENDIF DEBUG} // Populate the uints. SetLength(digits, cu + 2); digits[cu + 1] := UInt32((man shr (cbit + kcbitUint))); digits[cu] := UInt32(man shr cbit); if (cbit > 0) then digits[cu - 1] := UInt32(man) shl (kcbitUint - cbit); if sign < 0 then tempSign := True else tempSign := False; newInt := TIntX.Create(digits, tempSign); newInt._negative := tempSign; end; end; end.
namespace swingsample; //Sample app by Brian Long (http://blong.com) { This example demonstrates using Java Swing See: - http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/package-frame.html - http://www.java2s.com/Code/JavaAPI/javax.swing/Catalogjavax.swing.htm } interface uses java.util, javax.swing, java.awt, java.awt.event; type SwingSample = class(JFrame) private var label3: JLabel; method actionPerformed(e: ActionEvent); public constructor; class method Main(args: array of String); end; implementation //App entry point class method SwingSample.Main(args: array of String); begin new SwingSample(); end; constructor SwingSample(); begin //Ensure app closes when you click the close button DefaultCloseOperation := JFrame.EXIT_ON_CLOSE; //Set window caption and size Title := "Oxygene and Java Swing"; Size := new Dimension(500, 150); //We will have a horizontal row of vertical control sets var hBox := Box.createHorizontalBox; //Ensure there is a little gap at the top of the window hBox.add(Box.createHorizontalStrut(20)); //1st vertical control set var vBox1 := Box.createVerticalBox; var label1 := new JLabel("Trivial example"); vBox1.add(label1); //A gap between the label and the button vBox1.add(Box.createVerticalStrut(10)); var button1 := new JButton("Update label"); //Handler added via inline interface implementation using an anonymous method button1.addActionListener(new interface ActionListener(actionPerformed := method(e: ActionEvent) begin label1.Text := "Clicked the button!" end)); vBox1.add(button1); hBox.add(vBox1); //2nd vertical control set var vBox2 := Box.createVerticalBox; var label2 := new JLabel("Message Box"); vBox2.add(label2); //A gap between the label and the button vBox2.add(Box.createVerticalStrut(10)); var button2 := new JButton("Show message box"); //Handler added via inline interface implementation using a lambda expression button2.addActionListener(new interface ActionListener(actionPerformed := (e) -> begin JOptionPane.showMessageDialog(self, 'There is no news...', 'News', JOptionPane.INFORMATION_MESSAGE); JButton(e.Source).Text := 'Click again!' end)); vBox2.add(button2); hBox.add(vBox2); //3rd vertical control set var vBox3 := Box.createVerticalBox; // the other way: label3 := new JLabel("Confirmation Box"); vBox3.add(label3); //A gap between the label and the button vBox3.add(Box.createVerticalStrut(10)); var button3 := new JButton("Show confirmation box"); //Handler added via inline interface implementation using a regular method button3.addActionListener(new interface ActionListener( actionPerformed := @actionPerformed)); vBox3.add(button3); hBox.add(vBox3); //Add the controls to the frame and show it add(hBox); Visible := true; end; method SwingSample.actionPerformed(e: ActionEvent); begin label3.Text := case JOptionPane.showConfirmDialog(self, 'Happy?', 'Mood test', JOptionPane.YES_NO_CANCEL_OPTION) of JOptionPane.YES_OPTION: ':o)'; JOptionPane.NO_OPTION: ':o('; else ':o|'; end; end; end.
unit openvpn; interface uses Windows, SysUtils, Forms, Dialogs, Registry, formload, ShellAPI, WinInet, Unit4; type TConsoleInput = function(ConsoleIdx: Integer; InputStr: PChar): LongBool; stdcall; //external 'UtilDll.dll'; //TOnConsoleOutput = procedure(const OutputStr: string); stdcall; TOnConsoleOutput = procedure(OutputStr: PChar); stdcall; TOpenConsole = function(CmdLine: PChar; WorkDir: PChar; ShowWindow: Word; pProcInfo: PProcessInformation; OnConsoleOutput: TOnConsoleOutput): Integer; stdcall; //external 'UtilDll.dll'; //TConsoleInput = function(ConsoleIdx: Integer; InputStr: PChar): LongBool; //stdcall; external 'UtilDll.dll'; TCloseConsole = function(ConsoleIdx: Integer): Integer; stdcall; //external 'UtilDll.dll'; TConsoleInputF4 = function(ConsoleIdx: Integer): Integer; stdcall; //external 'UtilDll.dll'; TRouteInit = function(LogEnabled: Boolean = False): Boolean; stdcall; TRouteAdd = function(ProcName, Gateway: PChar): Boolean; stdcall; TRouteGetDefaultGateway = function: PChar; stdcall; TRouteRestore = function(ProcName: PChar): Boolean; TRouteAddCustom = function(Dest, Mask, Gateway: PChar): Boolean; stdcall; TRouteRemoveCustom = function(Dest: PChar): Boolean; stdcall; TRouteGetDetectInterval = function: Cardinal; stdcall; TRouteSetDetectInterval = function(Interval: Cardinal): Boolean; stdcall; TRouteGetRestoreDelay = function(ProcName: PChar): Cardinal; stdcall; TRouteSetRestoreDelay = function(ProcName: PChar; Delay: Cardinal): Boolean; stdcall; TRouteUninit = function: Boolean; stdcall; procedure LoadDll(DllFileName: string); //procedure OnConsoleOutput(const OutputStr: string); stdcall; procedure OnConsoleOutput(OutputStr: PChar); stdcall; function OVPN(CmdLine: string; WorkDir: string = ''): Boolean; procedure cvpn; procedure EnableProxy(Enabled: Boolean); var handle: Integer; DllHandle: Cardinal; RouteInit: TRouteInit; RouteAdd: TRouteAdd; RouteGetDefaultGateway: TRouteGetDefaultGateway; RouteRestore: TRouteRestore; RouteAddCustom: TRouteAddCustom; RouteRemoveCustom: TRouteRemoveCustom; RouteGetDetectInterval: TRouteGetDetectInterval; RouteSetDetectInterval: TRouteSetDetectInterval; RouteGetRestoreDelay: TRouteGetRestoreDelay; RouteSetRestoreDelay: TRouteSetRestoreDelay; RouteUninit: TRouteUninit; OpenConsole: TOpenConsole; ConsoleInput: TConsoleInput; CloseConsole: TCloseConsole; ConsoleInputF4: TConsoleInputF4; ConsoleIdx: Integer; ProcInfo: TProcessInformation; Needdisconnect: Boolean; NeedNIC: Boolean; UserNameSent: Boolean; ProxyUnameSent: Boolean; ProxyPwordSent: Boolean; PasswordSent: Boolean; Completed: Boolean; NICVERSION: Boolean; WAITNIC: Boolean; SIGTERM: Boolean; wrong: Boolean; RESOLVE: Boolean; Establish: Boolean; TimeOUT: Boolean; TcpTimeOut: Boolean; Reset: Boolean; HTTPPROXY: Boolean; HttpProxyStatus: Boolean; Exiting: Boolean; NoNIC: Boolean; ProxyError: Boolean; ProxyError1: Boolean; PauthErr: Boolean; SocketErro: Boolean; TcpReadErr: Boolean; SocketProxy: Boolean; ChangeIe: Boolean; isa: Boolean; route: Boolean; HTTPForbidden: Boolean; NoRoute: Boolean; retry: Integer = 0; Sockserr: Boolean; Routing: Boolean; brokendriver, addition, tlserror, processexiting, newdriver, AUTH_FAILED: Boolean; implementation uses unit1, Unit3; procedure EnableProxy(Enabled: Boolean); var Info: INTERNET_PROXY_INFO; Reg: TRegistry; begin info.lpszProxy := pchar(regproxy); Reg := TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Internet Settings', False) then begin Reg.WriteInteger('ProxyEnable', Integer(Enabled)); end; finally Reg.CloseKey; Reg.Free; end; if (Enabled) then begin Info.dwAccessType := INTERNET_OPEN_TYPE_PROXY; //InternetSetOption(nil, INTERNET_OPTION_PROXY, @Info, SizeOf(Info)); InternetSetOption(nil, INTERNET_OPTION_REFRESH, nil, 0); InternetSetOption(nil, INTERNET_OPTION_SETTINGS_CHANGED, nil, 0); end else begin Info.dwAccessType := INTERNET_OPEN_TYPE_DIRECT; InternetSetOption(nil, INTERNET_OPTION_PROXY, @Info, SizeOf(Info)); InternetSetOption(nil, INTERNET_OPTION_REFRESH, nil, 0); InternetSetOption(nil, INTERNET_OPTION_SETTINGS_CHANGED, nil, 0); end; //EnableProxy(True); end; procedure LoadDll(DllFileName: string); begin DllHandle := LoadLibrary(PChar(DllFileName)); if DllHandle <> 0 then begin @OpenConsole := GetProcAddress(DllHandle, 'OpenConsole'); @ConsoleInput := GetProcAddress(DllHandle, 'ConsoleInput'); @CloseConsole := GetProcAddress(DllHandle, 'CloseConsole'); @ConsoleInputF4 := GetProcAddress(DllHandle, 'ConsoleInputF4'); @RouteInit := GetProcAddress(DllHandle, 'RouteInit'); @RouteAdd := GetProcAddress(DllHandle, 'RouteAdd'); @RouteGetDefaultGateway := GetProcAddress(DllHandle, 'RouteGetDefaultGateway'); @RouteRestore := GetProcAddress(DllHandle, 'RouteRestore'); @RouteAddCustom := GetProcAddress(DllHandle, 'RouteAddCustom'); @RouteRemoveCustom := GetProcAddress(DllHandle, 'RouteRemoveCustom'); @RouteGetDetectInterval := GetProcAddress(DllHandle, 'RouteGetDetectInterval'); @RouteSetDetectInterval := GetProcAddress(DllHandle, 'RouteSetDetectInterval'); @RouteGetRestoreDelay := GetProcAddress(DllHandle, 'RouteGetRestoreDelay'); @RouteSetRestoreDelay := GetProcAddress(DllHandle, 'RouteSetRestoreDelay'); @RouteUninit := GetProcAddress(DllHandle, 'RouteUninit'); end; end; //procedure OnConsoleOutput(const OutputStr: string); stdcall; procedure OnConsoleOutput(OutputStr: PChar); stdcall; var y: string; x: string; acct: Boolean; begin // 以下开始分析显示数据,并自动做相应操作。 // 是否处于用户名输入界面 if Pos('Enter Auth Username:', OutputStr) <> 0 then begin // 如果还未发送用户名,则发送用户名。 if not UserNameSent then begin UserNameSent := True; ConsoleInput(ConsoleIdx, PAnsiChar(form1.Edit1.Text + #13)); //PAnsiChar(form1.Edit1.Text + #13)); end; end; // 是否处于密码输入界面 if Pos('Enter Auth Password:', OutputStr) <> 0 then begin // 如果还未发送密码,则发送密码。 if not PasswordSent then begin PasswordSent := True; ConsoleInput(ConsoleIdx, PAnsiChar(form1.Edit2.Text + #13)); end; end; // 是否处于HTTP代理服务器用户名输入界面 if Pos('Enter HTTP Proxy Username:', OutputStr) <> 0 then begin // 如果还未发送密码,则发送密码。 if not ProxyUnameSent then begin ProxyUnameSent := True; ConsoleInput(ConsoleIdx, PAnsiChar(form1.puser.Text + #13)); end; end; // 是否处于HTTP代理服务器密码输入界面 if Pos('Enter HTTP Proxy Password:', OutputStr) <> 0 then begin // 如果还未发送密码,则发送密码。 if not ProxyPwordSent then begin ProxyPwordSent := True; ConsoleInput(ConsoleIdx, PAnsiChar(form1.ppass.Text + #13)); end; end; if Pos('There are no TAP', OutputStr) <> 0 then begin if not NoNIC then begin NoNIC := True; Form1.StatusBar1.Panels[0].Text := '未检测到疾风网络加速器虚拟网卡!再次点击连接按钮会自动安装!'; Needdisconnect := True; NeedNIC := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end else if Pos('requires a TAP-Windows', OutputStr) <> 0 then begin if not newdriver then begin newdriver := True; Form1.StatusBar1.Panels[0].Text := '正在更新您的虚拟网卡!'; Needdisconnect := True; NeedNIC := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end else if Pos('CreateFile failed on TAP device', OutputStr) <> 0 then begin if not brokendriver then begin brokendriver := True; if RunningInWow64 then begin formload.extrafiles64; end else begin formload.extrafiles32; end; // uninstall nic winexec(PChar('tapinstall.exe remove tap0901'), SW_HIDE); end; end; if Pos('Initialization Sequence Completed', OutputStr) <> 0 then begin // 检测连接是否成功。 if not Completed then begin Completed := True; //showmessage('连接成功'); Form1.StatusBar1.Panels[0].Text := 'OpenVPN连接成功!'; form1.Button1.caption := '断开'; form1.Button1.Enabled := true; Form1.Hide; Form1.rztrycn1.Enabled := True; Sleep(1000); try usertime := Form1.idhtp1.Get(pchar('http://' + server1 + '/check.php?lang=cn&date=') + form1.Edit1.Text); except try usertime := Form1.idhtp1.Get(pchar('http://' + server2 + '/check.php?lang=cn&date=') + form1.Edit1.Text); except end; end; try usertype := Form1.idhtp1.Get(pchar('http://' + server1 + '/check.php?lang=cn&usergroup=') + form1.Edit1.Text); except try usertype := Form1.idhtp1.Get(pchar('http://' + server2 + '/check.php?lang=cn&usergroup=') + form1.Edit1.Text); except end; end; if Form1.Socksproxy.Checked = False then begin if cmwap = False then begin Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', usertype + #13 + usertime); end else begin Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', Utf8ToAnsi(usertype) + #13 + Utf8ToAnsi(usertime)); end; end; if Form1.noproxy.Checked = True then begin //Sleep(1); if cmwap = False then begin Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', usertype + #13 + usertime); end else begin GetDosRes('tcping -n 1 10.0.0.172 80', y); GetDosRes('tcping -n 1 10.0.0.200 80', x); if Pos('1 successful', y) > 0 then begin Form1.idhtp1.ProxyParams.ProxyServer := '10.0.0.172'; Form1.idhtp1.ProxyParams.ProxyPort := 80; end else if Pos('1 successful', x) > 0 then begin Form1.idhtp1.ProxyParams.ProxyServer := '10.0.0.200'; Form1.idhtp1.ProxyParams.ProxyPort := 80; end; usertime := Form1.idhtp1.Get(pchar('http://' + server1 + '/check.php?lang=cn&date=') + form1.Edit1.Text); usertype := Form1.idhtp1.Get(pchar('http://' + server1 + '/check.php?lang=cn&usergroup=') + form1.Edit1.Text); if usertime <> '' then begin Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', Utf8ToAnsi(usertype) + #13 + Utf8ToAnsi(usertime)); end; end; end; if Form1.useie.Checked = True then begin EnableProxy(False); ChangeIe := True; { reg := TRegistry.Create; reg.RootKey := HKEY_CURRENT_USER; reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Internet Settings', True); reg.WriteInteger('ProxyEnable', 0); reg.CloseKey; reg.Free; x if FindProcess('iexplore.exe') then begin case Application.MessageBox('系统自动去掉了你的IE代理设,您必须重新启动互联网浏览器!!!' + #13#10#13#10 + '是否立即关闭浏览器?', '疾风网络加速器', MB_OKCANCEL + MB_ICONQUESTION) of IDOK: begin EndProcess('iexplore.exe'); end; IDCANCEL: begin Application.MessageBox('您将稍后重启浏览器!', '疾风网络加速器', MB_OK + MB_ICONINFORMATION); end; end; end else begin Application.MessageBox('系统自动去掉了你的IE代理设,强烈建议您重新启动互联网浏览器!', '疾风网络加速器', MB_OK + MB_ICONWARNING); end; } end; if Form1.httpproxy.Checked = True then begin EnableProxy(False); ChangeIe := True; { reg := TRegistry.Create; reg.RootKey := HKEY_CURRENT_USER; reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Internet Settings', True); if reg.ReadInteger('ProxyEnable') = 1 then begin case Application.MessageBox('发现IE还在使用HTTP代理服务器,是否自动取消?', '疾风网络加速器', MB_YESNO + MB_ICONQUESTION) of IDYES: begin reg.WriteInteger('ProxyEnable', 0); ChangeIe := True; if FindProcess('iexplore.exe') then begin case Application.MessageBox('系统自动去掉了你的IE代理设,您必须重新启动互联网浏览器!!!' + #13#10#13#10 + '是否立即关闭浏览器?', '疾风网络加速器', MB_OKCANCEL + MB_ICONQUESTION) of IDOK: begin EndProcess('iexplore.exe'); end; IDCANCEL: begin Application.MessageBox('您将稍后重启浏览器!', '疾风网络加速器', MB_OK + MB_ICONINFORMATION); end; end; end else begin Application.MessageBox('系统自动去掉了你的IE代理设,强烈建议您重新启动互联网浏览器!', '疾风网络加速器', MB_OK + MB_ICONWARNING); end; end; IDNO: begin Application.MessageBox('IE还在使用代理服务器,您的IE将不会突破内网限制!', '疾风网络加速器', MB_OK + MB_ICONWARNING); end; end; end; reg.CloseKey; reg.Free; } end; if Form1.chk2.Checked = True then begin usertime := GetWebPage(pchar('http://' + server1 + '/check.php?lang=cn&date=') + form1.Edit1.Text); usertype := GetWebPage(pchar('http://' + server1 + '/check.php?lang=cn&usergroup=') + form1.Edit1.Text); Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', usertype + #13 + usertime); end; if Form1.Socksproxy.Checked = True then begin usertime := GetWebPage(pchar('http://' + server1 + '/check.php?lang=cn&date=') + form1.Edit1.Text); usertype := GetWebPage(pchar('http://' + server1 + '/check.php?lang=cn&usergroup=') + form1.Edit1.Text); Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', usertype + #13 + usertime); end; if Form1.CheckBox1.Checked = True then begin reg := TRegistry.Create; reg.RootKey := HKEY_CURRENT_USER; reg.OpenKey('Software\JFVPN\', True); reg.WriteString('User', Form1.Edit1.Text); reg.WriteString('Pass', newbase64(Form1.Edit2.Text)); //保存服务器列表 reg.WriteString('ListIndex', IntToStr(Form1.ComboBox2.ItemIndex)); if Form1.noproxy.Checked = True then begin Reg.WriteString('NTLM', '0'); Reg.WriteString('Proxy', ''); Reg.WriteString('ProxyAddr', ''); Reg.WriteString('ProxyPort', ''); Reg.WriteString('ProxyUser', ''); Reg.WriteString('ProxyPass', ''); end; if Form1.httpproxy.Checked = True then begin reg.WriteString('Proxy', 'HTTP'); reg.WriteString('ProxyAddr', Form1.proxyadd.Text); reg.WriteString('ProxyPort', Form1.proxyport.Text); Reg.WriteString('ProxyUser', ''); Reg.WriteString('ProxyPass', ''); Reg.WriteString('NTLM', '0'); if Form1.chk1.Checked then begin reg.WriteString('ProxyUser', Form1.puser.Text); reg.WriteString('ProxyPass', newbase64(Form1.ppass.Text)); if Form1.chk2.Checked then begin reg.WriteString('NTLM', '1'); end else begin reg.WriteString('NTLM', '0'); end; end; end; if Form1.Socksproxy.Checked then begin reg.WriteString('Proxy', 'Socks'); reg.WriteString('ProxyAddr', Form1.proxyadd.Text); reg.WriteString('ProxyPort', Form1.proxyport.Text); Reg.WriteString('NTLM', '0'); Reg.WriteString('ProxyUser', ''); Reg.WriteString('ProxyPass', ''); end; if Form1.useie.Checked then begin reg.WriteString('Proxy', 'HTTP'); reg.WriteString('ProxyAddr', ''); reg.WriteString('ProxyPort', ''); Reg.WriteString('NTLM', '0'); Reg.WriteString('ProxyUser', ''); Reg.WriteString('ProxyPass', ''); end; if Form1.CheckBox1.Checked = False then begin Reg.WriteString('NTLM', '0'); Reg.WriteString('User', ''); Reg.WriteString('Pass', ''); Reg.WriteString('Proxy', ''); Reg.WriteString('ProxyAddr', ''); Reg.WriteString('ProxyPort', ''); Reg.WriteString('ProxyUser', ''); Reg.WriteString('ProxyPass', ''); reg.WriteString('ListIndex', ''); end; reg.CloseKey; reg.Free; end; if usertype = '尊敬的免费用户' then begin Application.MessageBox('您是免费会员' + #13#10 + #13#10 + '每半小时将会断线一次,速度是付费会员的1/8.', '疾风网络加速器', MB_OK + MB_ICONINFORMATION); end; if not acct then begin acct := True; shellexecute(handle, nil, pchar('http://www.so169.com/acct.php'), nil, nil, sw_shownormal); end; end; {连接成功后路由正常RouteType键值为1} if Pos('The route addition failed', OutputStr) <> 0 then begin if not addition then begin if not route then begin route := True; if Pos('route.exe ADD 127.0.0.1 MASK', OutputStr) = 0 then begin Form1.rztrycn1.Enabled := True; form1.rztrycn1.ShowBalloonHint('疾风网络加速器', '您的计算机禁止疾风修改路由,您可能无法正常使用!' + #13#10 + #13#10 + '尝试重启计算机解决此问题!'); reg := TRegistry.Create; reg.RootKey := HKEY_CURRENT_USER; reg.OpenKey('Software\JFVPN\', True); if reg.ValueExists('Routetype') then begin if reg.ReadString('RouteType') <> '1' then begin reg.WriteString('RouteType', '1'); end else begin reg.WriteString('RouteType', '0'); end; end else begin reg.WriteString('RouteType', '0'); end; reg.CloseKey; reg.Free; //Needdisconnect := True; end else begin end; end; end; { if update = True then begin autoupdate; end; } end; if not Routing then begin Routing := True; //WinExec('ipconfig.exe /flushdns', SW_HIDE); RouteAddCustom(PChar('10.0.0.0'), PChar('255.0.0.0'), PChar(gateway)); RouteAddCustom(PChar('192.168.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.16.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.17.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.18.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.19.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.20.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.21.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.22.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.23.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.24.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.25.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.26.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.27.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.28.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.29.0.0'), PChar('255.255.0.0'), PChar(gateway)); RouteAddCustom(PChar('172.30.0.0'), PChar('255.255.0.0'), PChar(gateway)); { WinExec(PChar('route.exe add 10.0.0.0 mask 255.0.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 192.168.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.16.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.17.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.18.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.19.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.20.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.21.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.22.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.23.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.24.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.25.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.26.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.27.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.28.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.29.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.30.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); WinExec(PChar('route.exe add 172.31.0.0 mask 255.255.0.0 ' + gateway), SW_HIDE); } end; threadconnectend := true; end; if Pos('SIGTERM[hard,] received, process exiting', OutputStr) <> 0 then begin if not SIGTERM then begin SIGTERM := True; form1.Button1.caption := '连接'; form1.Button1.Enabled := true; Needdisconnect := True; end; end; if Pos('ISA Server requires authorization', OutputStr) <> 0 then begin if not isa then begin isa := True; form1.Button1.caption := '连接'; form1.Button1.Enabled := true; Needdisconnect := True; Form1.rztrycn1.Enabled := True; form1.rztrycn1.ShowBalloonHint('疾风网络加速器', 'ISA代理服务器,需要勾选NTLM,请勾选后再进行连接!'); end; end; if Pos('TCP port read failed', OutputStr) <> 0 then begin if not TcpReadErr then begin TcpReadErr := True; form1.Button1.caption := '连接'; form1.Button1.Enabled := true; Needdisconnect := True; Form1.StatusBar1.Panels[0].Text := 'TCP 端口连接错误,请检查端口是否可用'; //Form1.rztrycn1.Enabled := True; //Form1.rztrycn1.ShowBalloonHint('疾风OpenVPNPN',Form1.StatusBar1.Panels[0].Text); end; end; if Pos('Socks proxy returned bad status', OutputStr) <> 0 then begin if not SocketErro then begin SocketErro := True; form1.Button1.caption := '连接'; form1.Button1.Enabled := true; Form1.rztrycn1.Enabled := True; form1.rztrycn1.ShowBalloonHint('疾风网络加速器', 'Socks代理服务器返回错误,连接断开!'); Needdisconnect := True; end; end; if Pos('SIGUSR1[soft,connection-reset] received', OutputStr) <> 0 then begin if not wrong then begin wrong := True; form1.Button1.Enabled := false; Form1.StatusBar1.Panels[0].Text := '当前状态:用户名密码错误!'; Needdisconnect := True; end; end; if Pos('RESOLVE: Cannot resolve host address', OutputStr) <> 0 then begin if not RESOLVE then begin RESOLVE := True; Form1.StatusBar1.Panels[0].Text := '无法解析DNS,无法正常使用VPN!'; Needdisconnect := True; end; end; if Pos('Waiting for TUN/TAP interface to come up', OutputStr) <> 0 then begin if not WAITNIC then begin WAITNIC := True; Form1.StatusBar1.Panels[0].Text := '等待虚拟网卡响应。'; end; end; if Pos('Driver Version', OutputStr) <> 0 then begin if not NICVERSION then begin NICVERSION := True; Form1.StatusBar1.Panels[0].Text := '成功加载虚拟网卡。'; end; end; if Pos('AUTH_FAILED', OutputStr) <> 0 then begin if not AUTH_FAILED then begin AUTH_FAILED := True; Form1.StatusBar1.Panels[0].Text := '用户名或密码错误!'; Needdisconnect := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; if Pos('Attempting to establish TCP connection with', OutputStr) <> 0 then begin if not Establish then begin Establish := True; Form1.StatusBar1.Panels[0].Text := '正在连接远程服务器。'; end; end; if Pos('Connection timed out (WSAETIMEDOUT)', OutputStr) <> 0 then begin if not TimeOUT then begin TimeOUT := True; Form1.StatusBar1.Panels[0].Text := '连接超时。'; Needdisconnect := True; end; end; if Pos('Connection reset, restarting', OutputStr) <> 0 then begin begin if not Reset then begin Reset := True; Form1.StatusBar1.Panels[0].Text := '连接被重置请重新尝试其他服务器进行连接。'; Needdisconnect := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; end; if Pos('Send to HTTP proxy:', OutputStr) <> 0 then begin if not httpproxy then begin httpproxy := True; Form1.StatusBar1.Panels[0].Text := '正在连接HTTP代理服务器。'; end; end; if Pos('HTTP/1.1 403 Forbidden', OutputStr) <> 0 then begin if not HTTPForbidden then begin HTTPForbidden := True; Form1.StatusBar1.Panels[0].Text := 'HTTP代理服务器禁止连接!'; Needdisconnect := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; if Pos('TCP connection established with ' + form1.proxyadd.Text + ':' + form1.proxyport.Text, OutputStr) <> 0 then begin if not SocketProxy then begin SocketProxy := True; if Form1.Socksproxy.Checked = True then begin Form1.StatusBar1.Panels[0].Text := '正在连接Socks代理服务器。'; end; end; end; if Pos('200 Connection established ', OutputStr) <> 0 then begin if not httpproxystatus then begin httpproxystatus := True; Form1.StatusBar1.Panels[0].Text := 'HTTP代理服务器连接成功!'; end; end; if Pos('No Route to Host', OutputStr) <> 0 then begin if not NoRoute then begin NoRoute := True; Form1.StatusBar1.Panels[0].Text := '您的计算机根本无法上网!不能连接至加速服务器!'; Needdisconnect := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; if Pos('TCP port read timeout', OutputStr) <> 0 then begin if not TcpTimeOut then begin TcpTimeOut := True; Form1.StatusBar1.Panels[0].Text := '连接遇到错误,TCP端口读取错误!强烈建议重启计算机!'; Needdisconnect := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; if (Pos('Exiting', OutputStr) <> 0) or (Pos('exiting', OutputStr) <> 0) then begin if not exiting then begin exiting := True; //Form1.StatusBar1.Panels[0].Text := '连接遇到错误,请检查设置并重新连接!'; Needdisconnect := True; //Form1.rztrycn1.Enabled := True; //Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; if Pos('TLS handshake failed', OutputStr) <> 0 then begin if not tlserror then begin tlserror := True; Form1.StatusBar1.Panels[0].Text := '如果你系统时间正确,那就是网管软件太厉害了!设置SOCKS代理127.0.0.1端口1080试试看!'; Needdisconnect := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; if Pos('Socks proxy returned bad reply', OutputStr) <> 0 then begin if not exiting then begin exiting := True; Form1.StatusBar1.Panels[0].Text := 'Socks代理服务器返回错误!'; Needdisconnect := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; if Pos(Form1.proxyport.Text + ' failed', OutputStr) <> 0 then begin if not ProxyError then begin ProxyError := True; Form1.StatusBar1.Panels[0].Text := '代理服务器连接错误,请检查代理服务器设置!'; Needdisconnect := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; if Pos(' 407 ', OutputStr) <> 0 then begin if not PauthErr then begin if Form1.chk1.Checked = True then begin PauthErr := True; Form1.StatusBar1.Panels[0].Text := 'HTTP代理服务器认证错误,请检查代理服务器用户名密码是否正确!'; Needdisconnect := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end else begin if Form1.useie.Checked = True then begin PauthErr := True; Form1.StatusBar1.Panels[0].Text := 'HTTP代理服务器需要身份认证,很有可能就是您登录WINDOWS的用户密码!'; Needdisconnect := True; //自动检测用户IE设置的代理需要用户名密码认证 Form1.httpproxy.Checked := True; Form1.proxyadd.Enabled := True; Form1.proxyport.Enabled := True; Form1.puser.Enabled := False; Form1.ppass.Enabled := False; Form1.chk1.Enabled := True; form1.chk2.Enabled := False; Form1.puser.Text := '代理用户名'; Form1.ppass.Text := '代理密码'; //自动检测用户IE设置的代理需要用户名密码认证 Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end else begin PauthErr := True; Form1.StatusBar1.Panels[0].Text := 'HTTP代理服务器需要身份认证,您必须填写代理服务器用户密码!'; Needdisconnect := True; Form1.rztrycn1.Enabled := True; Form1.rztrycn1.ShowBalloonHint('疾风网络加速器', form1.StatusBar1.Panels[0].Text); end; end; end; end; end; {启动openvpn} function OVPN(CmdLine: string; WorkDir: string = ''): Boolean; //var // CmdLine: PChar; // WorkDir: PChar; begin form1.Button1.Enabled := false; // CmdLine := PChar('"' + ExtractFilePath(Application.ExeName) + 'openvpn.exe" --config 1.ovpn'); // WorkDir := PChar(Application.ExeName); ConsoleIdx := OpenConsole(pchar(CmdLine), pchar(WorkDir), SW_HIDE, @ProcInfo, OnConsoleOutput); Result := ConsoleIdx <> -1; // if ConsoleIdx = -1 then // begin // Application.MessageBox('启动openvpn失败!', PChar(Application.Title), MB_OK + // MB_ICONWARNING); // end end; { 调用 OVPN('"' + ExtractFilePath(Application.ExeName) + 'openvpn.exe" --config 1.ovpn', extractfiledir(Application.ExeName)) } {正常退出关闭软件} procedure cvpn; begin form1.Button1.Enabled := false; ConsoleInputF4(ConsoleIdx); if ChangeIe = True then begin { reg := TRegistry.Create; reg.RootKey := HKEY_CURRENT_USER; reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Internet Settings', True); reg.WriteInteger('ProxyEnable', 1); reg.CloseKey; reg.Free; //listuseieproxy := False; } EnableProxy(True); end; if ProcInfo.hProcess <> 0 then begin //WaitForSingleObject(ProcInfo.hProcess, INFINITE); closeconsole(consoleidx); UserNameSent := False; PasswordSent := False; ProxyUnameSent := False; ProxyPwordSent := False; Completed := False; SIGTERM := False; wrong := False; RESOLVE := False; WAITNIC := False; Needdisconnect := False; NICVERSION := False; Establish := False; TimeOUT := False; TcpTimeOut := False; Reset := False; httpproxy := False; httpproxystatus := False; exiting := False; NoNIC := False; ProxyError := False; ProxyError := False; PauthErr := False; SocketErro := False; TcpReadErr := False; SocketProxy := False; cmwap := False; ChangeIe := False; isa := False; route := False; endprocdure := False; HTTPForbidden := False; NoRoute := False; retry := 0; Sockserr := False; Form1.tmrCVPN.Enabled := False; Form1.tmrPPTP.Enabled := False; end; form1.Button1.Enabled := true; form1.Button1.Caption := '连接'; Form1.StatusBar1.Panels[0].Text := '断开OpenVPN成功!'; //repairnet; end; {窗口关闭时询问是否关闭 procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if MessageBox(Handle, '确认要退出并断开吗?', '疾风OpenVPN', MB_YESNO or MB_ICONQUESTION or MB_DEFBUTTON2) = IDYES then begin if CanClose = true then begin cvpn; application.Terminate; end; end else begin CanClose := false; end; end; } {点击按钮1 procedure TForm1.Button1Click(Sender: TObject); begin if button1.caption = '连接' then begin OVPN; end else if button1.caption = '断开' then begin cvpn; end; end; } end. d.
namespace RemObjects.Elements.System; interface [assembly:NamespaceAlias('com.remobjects.oxygene.system', ['remobjects.elements.system'])] [assembly:NamespaceAlias('com.remobjects.oxygene.system.linq', ['remobjects.elements.system.linq'])] [assembly:NamespaceAlias('com.remobjects.elements.system', ['remobjects.elements.system'])] [assembly:NamespaceAlias('com.remobjects.elements.system.linq', ['remobjects.elements.system.linq'])] {$G+} operator Pow(a, b: Double): Double; public; operator Pow(a, b: Int64): Int64; public; operator Pow(a, b: Integer): Integer; public; type AnsiChar = public record mapped to SByte end; extension method &Class.IsFloat: Boolean; extension method &Class.IsIntegerOrFloat: Boolean; extension method &Class.IsInteger: Boolean; extension method &Class.IsSigned: Boolean; operator &Add(aLeft, aRight: String): String; public; begin if aLeft = nil then exit aRight; if aRight = nil then exit aLeft; exit aLeft.concat(aRight); end; operator &Add(aLeft: Object; aRight: String): String; public; begin if aLeft = nil then exit aRight.toString(); if aRight = nil then exit aLeft.toString(); exit aLeft.toString().concat(aRight.toString()); end; operator &Add(aLeft: String; aRight: Object): String; public; begin if aLeft = nil then exit aRight.toString(); if aRight = nil then exit aLeft.toString(); exit aLeft.toString().concat(aRight.toString()); end; operator Equal(aLeft, aRight: String): Boolean; public; begin if Object(aLeft) = nil then exit Object(aRight) = nil; if aRight = nil then exit false; exit aLeft.equals(aRight) end; operator Equal(aLeft: Char; aRight: String): Boolean; public; begin if aRight = nil then exit false; exit aLeft.toString().equals(aRight) end; operator Equal(aRight: String; aLeft: Char): Boolean; public; begin if aRight = nil then exit false; exit aLeft.toString().equals(aRight) end; operator NotEqual(aLeft, aRight: String): Boolean; public; begin exit not (aLeft = aRight); end; operator NotEqual(aLeft: Char; aRight: String): Boolean; public; begin exit not (aLeft = aRight); end; operator NotEqual(aRight: String; aLeft: Char): Boolean; public; begin exit not (aLeft = aRight); end; implementation extension method &Class.IsFloat: Boolean; begin exit (self = typeOf(nullable Single)) or (self = typeOf(nullable Double)); end; extension method &Class.IsInteger: Boolean; begin exit (self = typeOf(nullable SByte)) or (self = typeOf(nullable Int16)) or (self = typeOf(nullable Int32)) or (self = typeOf(nullable Int64)) or (self = typeOf(UnsignedByte)) or (self = typeOf(UnsignedShort)) or (self = typeOf(UnsignedInteger)) or (self = typeOf(UnsignedLong)); end; extension method &Class.IsIntegerOrFloat: Boolean; begin exit (self = typeOf(nullable Single)) or (self = typeOf(nullable Double)) or (self = typeOf(nullable SByte)) or (self = typeOf(nullable Int16)) or (self = typeOf(nullable Int32)) or (self = typeOf(nullable Int64)) or (self = typeOf(UnsignedByte)) or (self = typeOf(UnsignedShort)) or (self = typeOf(UnsignedInteger)) or (self = typeOf(UnsignedLong)); end; extension method &Class.IsSigned: Boolean; begin exit (self = typeOf(nullable SByte)) or (self = typeOf(nullable Int16)) or (self = typeOf(nullable Int32)) or (self = typeOf(nullable Int64)); end; operator Pow(a, b: Double): Double; begin exit java.lang.Math.pow(a,b); end; operator Pow(a, b: Int64): Int64; begin result := 1; if b < 0 then exit 0; while b <> 0 do begin if (b and 1) <> 0 then result := result * a; a := a * a; b := b shr 1; end; end; operator Pow(a, b: Integer): Integer; begin result := 1; if b < 0 then exit 0; while b <> 0 do begin if (b and 1) <> 0 then result := result * a; a := a * a; b := b shr 1; end; end; end.
// ------------------------------------------------------------- // Programa que troca os valores de duas variáveis, a e b. :~ // ------------------------------------------------------------- Program ExemploPzim ; var a,b: integer; Begin // Solicita valores de a e b writeln('Digite dois valores inteiros:'); write('Valor de a: '); readln(a); write('Valor de b: '); readln(b); // Troca dos valores de a e b a:= a+b; b:= (a-b); a:= (a-b); writeln('Os valores foram trocados'); writeln('-------------------------'); writeln('Valor de a = ',a); writeln('Valor de b = ',b); End.
unit TpControls; interface uses SysUtils, ThTag, ThWebControl; const tpClass = 'tpClass'; type TTpEvent = string; TTpEventType = procedure(inSender: TObject) of object; // TTpGraphicControl = class(TThWebGraphicControl) private FOnGenerate: TTpEvent; protected procedure Tag(inTag: TThTag); override; protected property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; end; // TTpControl = class(TThWebControl) private FOnGenerate: TTpEvent; protected procedure Tag(inTag: TThTag); override; protected property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; end; function TpAttr(const inName, inValue: string): string; overload; function TpAttr(const inName: string; inValue: Integer): string; overload; function PropertyIsJsEvent(const inName: string): Boolean; function PropertyIsPhpEvent(const inName: string): Boolean; implementation {.$R TpPaletteIcons.res} function TpAttr(const inName, inValue: string): string; begin if (inValue = '') then Result := '' else Result := ' ' + inName + '="' + inValue + '"'; end; function TpAttr(const inName: string; inValue: Integer): string; begin Result := TpAttr(inName, IntToStr(inValue)); end; function PropertyIsJsEvent(const inName: string): Boolean; begin Result := Copy(inName, 1, 2) = 'on'; end; function PropertyIsPhpEvent(const inName: string): Boolean; begin Result := Copy(inName, 1, 2) = 'On'; end; { TTpGraphicControl } procedure TTpGraphicControl.Tag(inTag: TThTag); begin inherited; inTag.Add('tpOnGenerate', OnGenerate); end; { TTpControl } procedure TTpControl.Tag(inTag: TThTag); begin inherited; inTag.Add('tpOnGenerate', OnGenerate); end; end.
Program HelloWorld(output) var msg : String begin msg = 'Hello, world!'; Writeln(msg) end.
unit uBASE_DialogForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, ExtCtrls, StdCtrls, cxButtons, uParams; type TBASE_DialogForm = class(TForm) btnCancel: TcxButton; btnOK: TcxButton; Bevel: TBevel; btnEdit: TcxButton; procedure btnOKClick(Sender: TObject); procedure btnEditClick(Sender: TObject); private FParams: TParamCollection; function GetReadOnly: boolean; procedure SetReadOnly(const Value: boolean); { Private declarations } protected procedure Check; virtual; public property Params: TParamCollection read FParams; property ReadOnly: boolean read GetReadOnly write SetReadOnly; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var BASE_DialogForm: TBASE_DialogForm; implementation {$R *.dfm} procedure TBASE_DialogForm.btnOKClick(Sender: TObject); begin Check; ModalResult:=mrOK; end; procedure TBASE_DialogForm.Check; begin // end; constructor TBASE_DialogForm.Create(AOwner: TComponent); begin inherited; FParams:=TParamCollection.Create(TParamItem); ReadOnly:=false; end; destructor TBASE_DialogForm.Destroy; begin Params.Free; inherited; end; function TBASE_DialogForm.GetReadOnly: boolean; begin result:=not btnOK.Visible; end; procedure TBASE_DialogForm.SetReadOnly(const Value: boolean); begin if Value then begin btnOK.Visible:=false; btnCancel.Caption:='Закрыть'; btnEdit.Visible:=true; end else begin btnOK.Visible:=true; btnCancel.Caption:='Отмена'; end; end; procedure TBASE_DialogForm.btnEditClick(Sender: TObject); begin ReadOnly:=false; btnEdit.Visible:=false; Caption:=Caption + ' (режим редактирования)'; end; end.
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } { XMI-export. See UML-specen page 591 for a description of XMI mapping of UML } unit uXmiExport; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, uIntegrator, uModelEntity, uModel, uFeedback, uConst; type TXMIExporter = class(TExportIntegrator) private Ids : TStringList; LaterList : TStringList; Output : TMemoryStream; NextId : integer; Feedback : IEldeanFeedback; procedure WritePackage(P : TAbstractPackage); procedure WriteLogicPackage(L : TLogicPackage); procedure WriteUnitPackage(U : TUnitPackage); procedure WriteClass(C : TClass); procedure WriteInterface(I : TInterface); procedure WriteEntityHeader(E : TModelEntity; const XmiName : string); procedure WriteFeatures(C : TClassifier); procedure WriteDataType(T : TDataType); function MakeTypeRef(C : TClassifier) : string; procedure FlushLaterList; procedure MakeGeneral(Child,Parent : TClassifier); procedure MakeAbstract(Client,Supplier : TClassifier); function MakeId(const S : string) : string; function XmlClose(const S : string) : string; function XmlOpen(const S : string) : string; function Xml(const S : string) : string; procedure Write(const S : string); public constructor Create(om: TObjectModel; AFeedback : IEldeanFeedback = nil); reintroduce; destructor Destroy; override; procedure InitFromModel; override; procedure ShowSaveDialog; procedure SaveTo(const FileName : string); function GetXmi : string; function GetXMIId(E : TModelEntity) : string; end; implementation const Core = 'Foundation.Core.'; CoreModelElement = Core + 'ModelElement.'; XmiHeader = '<?xml version="1.0" encoding="UTF-8"?>'#13#10 + '<XMI xmi.version="1.0">'#13#10 + '<XMI.header>'#13#10 + '<XMI.metamodel xmi.name="UML" xmi.version="1.3"/>'#13#10 + '<XMI.documentation>'#13#10 + '<XMI.exporter>' + uConst.ProgName + '</XMI.exporter>'#13#10 + '<XMI.exporterVersion>' + uConst.ProgVersion + '</XMI.exporterVersion>'#13#10 + '</XMI.documentation>'#13#10 + '</XMI.header>'#13#10 + '<XMI.content>'; XmiFooter = '</XMI.content>'#13#10 + '</XMI>'; { TXMIExporter } constructor TXMIExporter.Create(om: TObjectModel; AFeedback : IEldeanFeedback = nil); begin inherited Create(om); Output := TMemoryStream.Create; LaterList := TStringList.Create; Ids := TStringList.Create; Ids.Sorted := True; Ids.Duplicates := dupIgnore; NextId := 0; Self.Feedback := AFeedback; if Feedback=nil then Self.Feedback := NilFeedback end; destructor TXMIExporter.Destroy; begin FreeAndNil(Output); FreeAndNil(Ids); FreeAndNil(LaterList); inherited; end; procedure TXMIExporter.InitFromModel; begin Write(XmiHeader); Write( XmlOpen('Model_Management.Model') ); WritePackage(Model.ModelRoot); Write( XmlClose('Model_Management.Model') ); Write(XmiFooter); Feedback.Message('XMI finished.'); end; function TXMIExporter.MakeId(const S : string): string; var I : integer; begin I := Ids.IndexOf(S); if I=-1 then begin Inc(NextId); I := Ids.Add(S); end; Result := 'xmi_' + IntToStr(I); end; procedure TXMIExporter.ShowSaveDialog; var D : TSaveDialog; Dir : string; begin D := TSaveDialog.Create(nil); try Dir := ExtractFilePath( Model.ModelRoot.GetConfigFile ); D.DefaultExt := 'xmi'; D.InitialDir := Dir; D.Filter := 'Xmi files (*.xmi)|*.xmi|All files (*.*)|*.*'; D.Options := D.Options + [ofOverwritePrompt]; if D.Execute then SaveTo( D.FileName ); finally D.Free; end; end; procedure TXMIExporter.Write(const S: string); begin Output.Write(S[1],Length(S)); Output.Write(#13#10,2); end; procedure TXMIExporter.WriteClass(C: TClass); var Mi : IModelIterator; begin WriteEntityHeader(C, Core + 'Class'); WriteFeatures(C); if Assigned(C.Ancestor) then begin Write( XmlOpen( Core + 'GeneralizableElement.generalization') ); MakeGeneral(C,C.Ancestor); Write( XmlClose( Core + 'GeneralizableElement.generalization') ); end; //Implements Mi := C.GetImplements; if Mi.HasNext then begin Write( XmlOpen( CoreModelElement + 'clientDependency') ); while Mi.HasNext do MakeAbstract(C, Mi.Next as TClassifier); Write( XmlClose( CoreModelElement + 'clientDependency') ); end; Mi := C.GetDescendants; if Mi.HasNext then begin Write( XmlOpen( Core + 'GeneralizableElement.specialization') ); while Mi.HasNext do MakeGeneral( Mi.Next as TClassifier, C); Write( XmlClose( Core + 'GeneralizableElement.specialization') ); end; Write( XmlClose(Core + 'Class') ); end; procedure TXMIExporter.WriteFeatures(C: TClassifier); var Mi : IModelIterator; F : TModelEntity; procedure WriteAttribute(A : TAttribute); begin WriteEntityHeader(A, Core + 'Attribute'); if Assigned(A.TypeClassifier) then begin Write( XmlOpen(Core + 'StructuralFeature.type') ); Write( MakeTypeRef(A.TypeClassifier) ); Write( XmlClose(Core + 'StructuralFeature.type') ); end; Write( XmlClose(Core + 'Attribute') ); end; procedure WriteOperation(O : TOperation); var Mio : IModelIterator; P : TParameter; begin WriteEntityHeader(O, Core + 'Operation'); Write( XmlOpen(Core + 'BehavioralFeature.parameter') ); if Assigned(O.ReturnValue) then begin Write( XmlOpen(Core + 'Parameter') ); Write( '<' + Core + 'Parameter.kind xmi.value="return"/>'); Write( XmlOpen(Core + 'Parameter.type') ); Write( MakeTypeRef( O.ReturnValue ) ); Write( XmlClose(Core + 'Parameter.type') ); Write( XmlClose(Core + 'Parameter') ); end; Mio := O.GetParameters; while Mio.HasNext do begin P := Mio.Next as TParameter; WriteEntityHeader(P, Core + 'Parameter'); if Assigned(P.TypeClassifier) then begin Write( XmlOpen(Core + 'Parameter.type') ); Write( MakeTypeRef(P.TypeClassifier) ); Write( XmlClose(Core + 'Parameter.type') ); end; Write( XmlClose(Core + 'Parameter') ); end; Write( XmlClose(Core + 'BehavioralFeature.parameter') ); Write( XmlClose(Core + 'Operation') ); end; begin Mi := C.GetFeatures; if Mi.HasNext then begin Write( XmlOpen(Core + 'Classifier.feature') ); while Mi.HasNext do begin F := Mi.Next; if F is TAttribute then WriteAttribute(F as TAttribute) else if F is TOperation then WriteOperation(F as TOperation); end; Write( XmlClose(Core + 'Classifier.feature') ); end; end; procedure TXMIExporter.WriteEntityHeader(E: TModelEntity; const XmiName: string); const VisibilityMap: array[TVisibility] of string = ('private', 'protected', 'public', 'public'); //(viPrivate,viProtected,viPublic,viPublished); begin { <Foundation.Core.Attribute xmi.id="xmi.3"> <Foundation.Core.ModelElement.name>x</Foundation.Core.ModelElement.name> <Foundation.Core.ModelElement.visibility xmi.value="private"/> } Write( '<' + XmiName + ' xmi.id="' + MakeId(E.FullName) + '">' ); Write( XmlOpen(CoreModelElement + 'name') + Xml(E.Name) + XmlClose(CoreModelElement + 'name') ); Write( '<' + CoreModelElement + 'visibility xmi.value="' + VisibilityMap[E.Visibility] + '"/>'); // Write( '<' + CoreModelElement + 'documentation xmi.value="' + E.Documentation.Description + '"/>'); if E.Documentation.Description<>'' then begin Write( XmlOpen( CoreModelElement + 'documentation') ); Write( E.Documentation.Description ); Write( XmlClose( CoreModelElement + 'documentation') ); end; end; procedure TXMIExporter.WritePackage(P: TAbstractPackage); begin Feedback.Message('XMI generating package ' + P.Name + '...'); WriteEntityHeader(P,'Model_Management.Package'); if P is TLogicPackage then WriteLogicPackage(P as TLogicPackage) else if P is TUnitPackage then WriteUnitPackage(P as TUnitPackage); //Laterlist contains generalizations etc that belongs to this package FlushLaterList; Write( XmlClose('Model_Management.Package') ); end; procedure TXMIExporter.WriteLogicPackage(L: TLogicPackage); var Mi : IModelIterator; begin Mi := L.GetPackages; while Mi.HasNext do WritePackage( Mi.Next as TAbstractPackage ); end; procedure TXMIExporter.WriteUnitPackage(U: TUnitPackage); var Mi : IModelIterator; C : TModelEntity; begin Mi := U.GetClassifiers; while Mi.HasNext do begin C := Mi.Next; if C is TClass then WriteClass(C as TClass) else if C is TInterface then WriteInterface(C as TInterface) else if C is TDataType then WriteDataType(C as TDataType); end; end; function TXMIExporter.XmlClose(const S: string): string; begin Result := '</' + S + '>'; end; function TXMIExporter.XmlOpen(const S: string): string; begin Result := '<' + S + '>'; end; //Writes a reference to a classifier function TXMIExporter.MakeTypeRef(C: TClassifier) : string; var S : string; begin if C is TClass then S := 'Class' else if C is TDataType then S := 'DataType' else if C is TInterface then S := 'Interface'; Result := '<' + Core + S +' xmi.idref="' + MakeId(C.FullName) + '"/>'; end; //Check that string does not contain xml-chars like < and > function TXMIExporter.Xml(const S: string): string; var I : integer; begin Result := S; for I:=1 to Length(Result) do case Result[I] of '<' : Result[I]:='('; '>' : Result[I]:=')'; end; end; procedure TXMIExporter.WriteInterface(I: TInterface); { <Foundation.Core.ModelElement.supplierDependency> <Foundation.Core.Abstraction xmi.idref="xmi.37"/> </Foundation.Core.ModelElement.supplierDependency> } var Mi : IModelIterator; begin WriteEntityHeader(I, Core + 'Interface'); WriteFeatures(I); //Implementing classes Mi := I.GetImplementingClasses; if Mi.HasNext then begin Write( XmlOpen( CoreModelElement + 'supplierDependency') ); while Mi.HasNext do MakeAbstract(Mi.Next as TClassifier,I); Write( XmlClose( CoreModelElement + 'supplierDependency') ); end; Write( XmlClose(Core + 'Interface') ); end; procedure TXMIExporter.WriteDataType(T: TDataType); begin WriteEntityHeader(T, Core + 'DataType'); Write( XmlClose(Core + 'DataType') ); end; procedure TXMIExporter.FlushLaterList; var I : integer; begin for I := 0 to LaterList.Count-1 do Write(LaterList[I]); LaterList.Clear; end; //Creates a reference to a generalization. //Also create the generalization if it did not already exist. procedure TXMIExporter.MakeGeneral(Child, Parent: TClassifier); var ID,S : string; begin { <Foundation.Core.Generalization xmi.id="xmi.12"> <Foundation.Core.Generalization.child> <Foundation.Core.Class xmi.idref="xmi.11"/> </Foundation.Core.Generalization.child> <Foundation.Core.Generalization.parent> <Foundation.Core.Class xmi.idref="xmi.36"/> </Foundation.Core.Generalization.parent> </Foundation.Core.Generalization> } S := 'General ' + Child.FullName + ' - ' + Parent.FullName; if Ids.IndexOf(S)=-1 then begin //Crate generalization ID := MakeId(S); LaterList.Add( '<' + Core + 'Generalization xmi.id="' + ID + '">'); LaterList.Add( XmlOpen(Core + 'Generalization.child') ); LaterList.Add( MakeTypeRef(Child) ); LaterList.Add( XmlClose(Core + 'Generalization.child') ); LaterList.Add( XmlOpen(Core + 'Generalization.parent') ); LaterList.Add( MakeTypeRef(Parent) ); LaterList.Add( XmlClose(Core + 'Generalization.parent') ); LaterList.Add( XmlClose(Core + 'Generalization') ); end else ID := MakeId(S); //Write reference Write( '<' + Core + 'Generalization xmi.idref="' + ID + '"/>'); end; //Creates a reference to an Abstraction. //Also create the Abstraction if it did not already exist. procedure TXMIExporter.MakeAbstract(Client, Supplier: TClassifier); { <Foundation.Core.Abstraction xmi.id="xmi.37"> <Foundation.Core.ModelElement.isSpecification xmi.value="false"/> <Foundation.Core.ModelElement.namespace> <Model_Management.Model xmi.idref="xmi.1"/> </Foundation.Core.ModelElement.namespace> <Foundation.Core.Dependency.client> <Foundation.Core.Class xmi.idref="xmi.36"/> </Foundation.Core.Dependency.client> <Foundation.Core.Dependency.supplier> <Foundation.Core.Interface xmi.idref="xmi.47"/> </Foundation.Core.Dependency.supplier> </Foundation.Core.Abstraction> } var ID,S : string; begin S := 'Abstract ' + Client.FullName + ' - ' + Supplier.FullName; if Ids.IndexOf(S)=-1 then begin //Create the Abstraction ID := MakeId(S); LaterList.Add( '<' + Core + 'Abstraction xmi.id="' + ID + '">'); LaterList.Add( XmlOpen(Core + 'Dependency.client') ); LaterList.Add( MakeTypeRef(Client) ); LaterList.Add( XmlClose(Core + 'Dependency.client') ); LaterList.Add( XmlOpen(Core + 'Dependency.supplier') ); LaterList.Add( MakeTypeRef(Supplier) ); LaterList.Add( XmlClose(Core + 'Dependency.supplier') ); LaterList.Add( XmlClose(Core + 'Abstraction') ); end else ID := MakeId(S); //Write reference Write( '<' + Core + 'Abstraction xmi.idref="' + ID + '"/>'); end; procedure TXMIExporter.SaveTo(const FileName: string); var F : TFileStream; begin F := TFileStream.Create( FileName ,fmCreate); try F.CopyFrom(Output, 0); finally F.Free; end; end; //Returns the whole xmi-file as a string. function TXMIExporter.GetXmi: string; begin SetLength(Result,Output.Size); Move(Output.Memory^,Result[1],Output.Size); end; //Used by htmldoc to get id of packages. function TXMIExporter.GetXMIId(E: TModelEntity): string; begin Result := MakeID(E.FullName); end; end.
unit St_sp_Hostel_Add_Room; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, FIBDataSet, pFIBDataSet, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxMaskEdit, cxDropDownEdit, cxTextEdit, cxLabel, cxContainer, cxGroupBox, StdCtrls, cxButtons, cxCheckBox, St_sp_Hostel_Form, cxCurrencyEdit; type TBuildsFormAddRoom = class(TForm) OKButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; RoomLabel: TcxLabel; RoomEdit: TcxTextEdit; cxLabel1: TcxLabel; TypeEdit: TcxPopupEdit; cxGrid1: TcxGrid; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1DBTableView1ID_TYPE_ROOM: TcxGridDBColumn; cxGrid1DBTableView1NAME_TYPE_ROOM: TcxGridDBColumn; cxGrid1DBTableView1SHORT_NAME: TcxGridDBColumn; cxGrid1DBTableView1MAX_PEOPLE_COUNT: TcxGridDBColumn; cxGrid1DBTableView1SIZE: TcxGridDBColumn; cxGrid1Level1: TcxGridLevel; pFIBDataSet1: TpFIBDataSet; DataSource1: TDataSource; procedure FormCreate(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure cxGrid1DBTableView1CellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure OKButtonClick(Sender: TObject); private { Private declarations } public id_type_room_original : integer; room_original : String; isModify : boolean; id_type_room : integer; end; var BuildsFormAddRoom: TBuildsFormAddRoom; implementation //uses DataModule1_Unit, Unit_of_Utilits, St_sp_Hostel_Form; {$R *.dfm} function IntegerCheck(const s : string) : boolean; var i : integer; k : char; begin Result := false; if s = '' then exit; for i := 1 to Length(s) do begin k := s[i]; if not (k in ['0'..'9',#8, #13]) then k := #0; if k = #0 then exit; end; Result := true; end; procedure TBuildsFormAddRoom.FormCreate(Sender: TObject); begin id_type_room := -1; end; procedure TBuildsFormAddRoom.CancelButtonClick(Sender: TObject); begin close; end; procedure TBuildsFormAddRoom.FormClose(Sender: TObject; var Action: TCloseAction); begin pFIBDataSet1.Close; action:=caFree; end; procedure TBuildsFormAddRoom.FormShow(Sender: TObject); begin if RoomEdit.Text <> '' then room_original := RoomEdit.Text else room_original := '-1'; id_type_room_original := id_type_room; pFIBDataSet1.Open; if id_type_room <> -1 then begin pFIBDataSet1.Locate('ID_TYPE_ROOM', id_type_room, []); TypeEdit.Text := pFIBDataSet1['NAME_TYPE_ROOM']; end; if id_type_room = -1 then begin pFIBDataSet1.First; TypeEdit.Text := pFIBDataSet1['NAME_TYPE_ROOM']; id_type_room := pFIBDataSet1['ID_TYPE_ROOM']; end; RoomEdit.SetFocus; end; procedure TBuildsFormAddRoom.cxGrid1DBTableView1CellClick( Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin TypeEdit.DroppedDown := false; id_type_room := pFIBDataSet1['ID_TYPE_ROOM']; TypeEdit.Text := pFIBDataSet1['NAME_TYPE_ROOM']; end; procedure TBuildsFormAddRoom.OKButtonClick(Sender: TObject); begin {if not IntegerCheck(RoomEdit.Text) then begin ShowMessage('Комната введена неверно.'); RoomEdit.SetFocus; exit; end;} if id_type_room = -1 then begin ShowMessage('Необходимо указать тип комнаты.'); exit; end; if TBuildsForm(Owner).RoomDataSet.Locate('ROOM;ID_TYPE_ROOM', VarArrayOf([RoomEdit.Text, id_type_room]), []) then begin if (TBuildsForm(Owner).RoomDataSet['ROOM'] <> room_original) or (TBuildsForm(Owner).RoomDataSet['ID_TYPE_ROOM'] <> id_type_room_original) then begin ShowMessage('Данная комната уже существует.'); exit; end; end; ModalResult := mrOK; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { A shader that applies a render pass for each material in its assigned MaterialLibrary. } unit VXS.MultiMaterialShader; interface uses System.Classes, VXS.Material, VXS.RenderContextInfo, VXS.State; type TVXMultiMaterialShader = class(TVXShader) private FPass : Integer; FMaterialLibrary : TVXMaterialLibrary; FVisibleAtDesignTime: boolean; FShaderActiveAtDesignTime : boolean; FShaderStyle: TVXShaderStyle; procedure SetVisibleAtDesignTime(const Value: boolean); procedure SetShaderStyle(const Value: TVXShaderStyle); protected procedure SetMaterialLibrary(const val : TVXMaterialLibrary); procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; function DoUnApply(var rci : TVXRenderContextInfo) : Boolean; override; public constructor Create(aOwner : TComponent); override; published property MaterialLibrary : TVXMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; property VisibleAtDesignTime : boolean read FVisibleAtDesignTime write SetVisibleAtDesignTime; property ShaderStyle:TVXShaderStyle read FShaderStyle write SetShaderStyle; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------ // ------------------ TVXMultiMaterialShader ------------------ // ------------------ // Create // constructor TVXMultiMaterialShader.Create(aOwner : TComponent); begin inherited; FShaderStyle:=ssReplace; FVisibleAtDesignTime := False; end; // DoApply // procedure TVXMultiMaterialShader.DoApply(var rci: TVXRenderContextInfo; Sender : TObject); begin if not Assigned(FMaterialLibrary) then exit; FShaderActiveAtDesignTime := FVisibleAtDesignTime; FPass:=1; if (not (csDesigning in ComponentState)) or FShaderActiveAtDesignTime then begin rci.ignoreDepthRequests := True; rci.VXStates.Enable(stDepthTest); rci.VXStates.DepthFunc := cfLEqual; if FMaterialLibrary.Materials.Count>0 then FMaterialLibrary.Materials[0].Apply(rci); rci.ignoreDepthRequests := False; end; end; // DoUnApply // function TVXMultiMaterialShader.DoUnApply( var rci: TVXRenderContextInfo): Boolean; begin Result:=False; if not Assigned(FMaterialLibrary) then exit; if (not (csDesigning in ComponentState)) or FShaderActiveAtDesignTime then begin if FMaterialLibrary.Materials.Count>0 then // handle multi-pass materials if FMaterialLibrary.Materials[FPass-1].UnApply(rci) then begin Result:=true; Exit; end; if (FPass >= FMaterialLibrary.Materials.Count) then begin rci.VXStates.DepthFunc := cfLess; exit; end; FMaterialLibrary.Materials[FPass].Apply(rci); Result:=True; Inc(FPass); end; end; // SetMaterialLibrary // procedure TVXMultiMaterialShader.SetMaterialLibrary( const val: TVXMaterialLibrary); begin if val<>FMaterialLibrary then begin FMaterialLibrary:=val; NotifyChange(Self); end; end; procedure TVXMultiMaterialShader.SetShaderStyle(const Value: TVXShaderStyle); begin FShaderStyle := Value; inherited ShaderStyle :=FShaderStyle; end; procedure TVXMultiMaterialShader.SetVisibleAtDesignTime( const Value: boolean); begin FVisibleAtDesignTime := Value; if csDesigning in ComponentState then NotifyChange(Self); end; end.
unit StdRut; interface type TFlagsArray = class private flags: array of boolean ; Size, StartIdx: integer ; public constructor Create( StartIdx0, EndIdx: integer ) ; procedure clear ; procedure setFlag( i: integer ) ; function hasFlag( i: integer ) : boolean ; end ; TSmIntPairArray = class private Size: integer ; public a1, a2: array of smallint ; last: integer ; constructor Create( sz: integer ) ; procedure SortByA2 ; end ; TSmallIntArray = array of smallint ; TSmIntRealPairArray = class private Size: integer ; public a: TSmallIntArray ; r: array of real ; last: integer ; constructor Create( sz: integer ) ; procedure Add( aEl: integer ; rEl: real ) ; procedure SortByR ; procedure tst ; end ; function MinInt(A, B: integer): integer; function MaxInt(A, B: integer): integer; implementation uses Dialogs ; procedure StdRutMsgHalt(s:string; koda: smallint) ; // Kode=4: Prekoracitev meja arrayev, oz. konstant begin MessageDlgPos(s, mtConfirmation, [mbOK] , 0, 80, 10) ; Halt ; end ; function MinInt(A, B: integer): integer; // Vrne manjsega od obeh parametrov begin if A < B then MinInt := A else MinInt := B; end; function MaxInt(A, B: integer): integer; // Vrne vecjega od obeh parametrov begin if A > B then MaxInt := A else MaxInt := B; end; // ******* // ******* class TFlagsArray constructor TFlagsArray.Create( StartIdx0, EndIdx: integer ) ; begin Size := 1+EndIdx-StartIdx ; StartIdx := StartIdx0 ; SetLength( flags, size ) ; end ; procedure TFlagsArray.clear ; var i: integer ; begin for i := 0 to Size-1 do flags[i] := false ; end ; procedure TFlagsArray.setFlag( i: integer ) ; begin if (i < StartIdx) or (i+StartIdx >= Size) then StdRutMsgHalt( 'TFlagsArray.setFlag: index out of bounds',4 ) ; flags[i+StartIdx] := true ; end ; function TFlagsArray.hasFlag( i: integer ) : boolean ; begin if (i < StartIdx) or (i+StartIdx >= Size) then StdRutMsgHalt( 'TFlagsArray.hasFlag: index out of bounds',4 ) ; hasFlag := flags[i+StartIdx] ; end ; // ******* // ******* class TSmIntPairArray constructor TSmIntPairArray.Create( Sz: integer ) ; begin Size := sz ; SetLength( a1, Size ) ; SetLength( a2, Size ) ; last := -1 ; end ; procedure TSmIntPairArray.SortbyA2 ; procedure QuickSort(iLo, iHi: Integer); var Lo, Hi, Mid, T: Integer; begin Lo := iLo; Hi := iHi; Mid := A2[(Lo + Hi) div 2]; repeat while A2[Lo] < Mid do Inc(Lo); while A2[Hi] > Mid do Dec(Hi); if Lo <= Hi then begin T := A1[Lo]; A1[Lo] := A1[Hi]; A1[Hi] := T; T := A2[Lo]; A2[Lo] := A2[Hi]; A2[Hi] := T; Inc(Lo); Dec(Hi); end; until Lo > Hi; if Hi > iLo then QuickSort(iLo, Hi); if Lo < iHi then QuickSort(Lo, iHi); end; begin // sorts by a2, changes also a1 if last < Low(A2) then StdRutMsgHalt( 'TSmIntPair.Sort: last', 4 ) ; QuickSort(Low(A2), last); end; // ******* // ******* class TSmIntrealPairArray constructor TSmIntRealPairArray.Create( Sz: integer ) ; begin Size := sz ; SetLength( a, Size ) ; SetLength( r, Size ) ; last := -1 ; end ; procedure TSmIntRealPairArray.Add( aEl: integer ; rEl: real ) ; begin last := last + 1 ; if last >= Size then StdRutMsgHalt( 'TSmIntRealPairArray.Add: Prevec elementov',4 ) ; a[last] := aEl ; r[last] := rEl ; end ; procedure TSmIntRealPairArray.SortbyR ; procedure QuickSort(iLo, iHi: Integer); var Lo, Hi, T: integer; TR, Mid : real ; begin Lo := iLo; Hi := iHi; Mid := R[(Lo + Hi) div 2]; repeat while R[Lo] < Mid do Inc(Lo); while R[Hi] > Mid do Dec(Hi); if Lo <= Hi then begin T := A[Lo]; A[Lo] := A[Hi]; A[Hi] := T; TR := R[Lo]; R[Lo] := R[Hi]; R[Hi] := TR; Inc(Lo); Dec(Hi); end; until Lo > Hi; if Hi > iLo then QuickSort(iLo, Hi); if Lo < iHi then QuickSort(Lo, iHi); end; begin // sorts by a2, changes also a1 if last < Low(R) then StdRutMsgHalt( 'TSmIntRealPair.Sort: last',4 ) ; QuickSort(Low(R), last); end; procedure TSmIntRealPairArray.tst ; var i: integer ; begin for i := 0 to High(r) do begin a[i] := i ; r[i] := - i / 10 ; end ; last := 4 ; SortByR ; last := 19 ; SortByR ; last := 4 ; SortByR ; end ; end.
unit Unit2; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Math.Vectors, REST.Types, REST.Client, Data.Bind.Components, System.JSON, Data.Bind.ObjectScope, FMX.Objects, FMX.Controls3D, FMX.Layers3D, FMX.Layouts, FMX.ListBox, FMX.Edit, FMX.StdCtrls, FMX.Controls.Presentation, FMX.TabControl; type TForm2 = class(TForm) MaterialOxfordBlueSB: TStyleBook; WedgewoodLightSB: TStyleBook; TabControl1: TTabControl; TabItem1: TTabItem; Label1: TLabel; Button1: TButton; Button2: TButton; Rectangle2: TRectangle; Edit1: TEdit; SearchEditButton1: TSearchEditButton; Layout25: TLayout; Label17: TLabel; ListBox13: TListBox; Layout3D1: TLayout3D; Rectangle1: TRectangle; Image1: TImage; Image2: TImage; Label10: TLabel; Label11: TLabel; edtPAT: TEdit; RESTClient1: TRESTClient; RESTRequest1: TRESTRequest; procedure DoTrashButtonClick(Sender: TObject); procedure DoRebootButtonClick(Sender: TObject); procedure DoStartButtonClick(Sender: TObject); procedure DoReinstallButtonClick(Sender: TObject); procedure edtPATKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure Button1Click(Sender: TObject); private FPersonalAccessToken: string; { Private declarations } function CreateInstance(): String; procedure DeleteInstance(AnInstanceID: string; AItemIndex: integer); function GetAllInstance(APage: integer): TJSONObject; function InstanceCommand(AnInstanceID: string; ACommand: string; AData: TJSONObject = nil): boolean; function CreateListBoxItem(AIndex: integer; AId: string; AName: string): TListBoxItem; public { Public declarations } property PersonalAccessToken: string read FPersonalAccessToken write FPersonalAccessToken; end; const VULTR_API_BASE_PATH = 'https://api.vultr.com/v2'; var Form2: TForm2; implementation {$R *.fmx} {$R *.Macintosh.fmx MACOS} {$R *.Windows.fmx MSWINDOWS} { TForm2 } procedure TForm2.Button1Click(Sender: TObject); begin CreateInstance; end; function TForm2.CreateInstance: String; var LRestClient: TRESTClient; LRestRequest: TRESTRequest; LReqBody, LResp: TJSONObject; LItemLB: TListBoxItem; begin LRestClient := TRESTClient.Create(VULTR_API_BASE_PATH + '/instances'); LRestRequest:= TRESTRequest.Create(nil); LReqBody := TJSONObject.Create; try // creating new instance req body LReqBody.AddPair('region','ewr'); LReqBody.AddPair('plan','vc2-6c-16gb'); LReqBody.AddPair('label','VULTR.Delphi'+ListBox13.Count.ToString+'.Instance'); LReqBody.AddPair('os_id', TJSONNumber.Create(215)); LReqBody.AddPair('backups','enabled'); LRestRequest.Method := rmPOST; LRestRequest.AddParameter('Authorization', 'Bearer ' + PersonalAccessToken, TRESTRequestParameterKind.pkHTTPHEADER, [poDoNotEncode]); LRestRequest.AddBody(LReqBody.ToJSON, TRESTContentType.ctAPPLICATION_JSON); LRestRequest.Client := LRestClient; LRestRequest.Execute; LResp := (LRestRequest.Response.JSONValue as TJSONObject).GetValue('instance') as TJSONObject; LItemLB := CreateListBoxItem(ListBox13.Count, LResp.GetValue('id').Value, LResp.GetValue('label').Value); ListBox13.AddObject(LItemLB); Result := LRestRequest.Response.JSONText; finally LRestRequest.Free; LRestClient.Free; LReqBody.Free; end; end; function TForm2.CreateListBoxItem(AIndex: integer; AId: string; AName: string): TListBoxItem; var LLayout: TLayout; LBtnTrash, LBtnReboot, LBtnStart, LBtnReinstall: TButton; LDroplLabel: TLabel; begin Result := TListBoxItem.Create(ListBox13); Result.Height := 40; LLayout := TLayout.Create(nil); LLayout.Align := TAlignLayout.Top; LLayout.Size.Height := 40; LLayout.Size.PlatformDefault := False; LLayout.Size.Width := 636; // delete instance LBtnTrash:= TButton.Create(LLayout); LBtnTrash.StyleLookup := 'trashtoolbutton'; LBtnTrash.Anchors := [TAnchorKind.akTop, TAnchorKind.akRight, TAnchorKind.akBottom]; LBtnTrash.Align := TAlignLayout.Right; LBtnTrash.ControlType := TControlType.Styled; LBtnTrash.Size.Height := 35; LBtnTrash.Size.PlatformDefault := False; LBtnTrash.Size.Width := 35; LBtnTrash.OnClick := DoTrashButtonClick; LBtnTrash.Tag := index; LBtnTrash.TagString := AId; LLayout.AddObject(LBtnTrash); // reboot instance LBtnReboot:= TButton.Create(LLayout); LBtnReboot.StyleLookup := 'refreshtoolbutton'; LBtnReboot.Anchors := [TAnchorKind.akTop, TAnchorKind.akRight, TAnchorKind.akBottom]; LBtnReboot.Align := TAlignLayout.Right; LBtnReboot.ControlType := TControlType.Styled; LBtnReboot.Size.Height := 35; LBtnReboot.Size.PlatformDefault := False; LBtnReboot.Size.Width := 35; LBtnReboot.OnClick := DoRebootButtonClick; LBtnReboot.Tag := index; LBtnReboot.TagString := AId; LLayout.AddObject(LBtnReboot); // start instance LBtnStart:= TButton.Create(LLayout); LBtnStart.StyleLookup := 'playtoolbutton'; LBtnStart.Anchors := [TAnchorKind.akTop, TAnchorKind.akRight, TAnchorKind.akBottom]; LBtnStart.Align := TAlignLayout.Right; LBtnStart.ControlType := TControlType.Styled; LBtnStart.Size.Height := 35; LBtnStart.Size.PlatformDefault := False; LBtnStart.Size.Width := 35; LBtnStart.OnClick := DoStartButtonClick; LBtnStart.Tag := index; LBtnStart.TagString := AId; LLayout.AddObject(LBtnStart); // reinstall instance LBtnReinstall:= TButton.Create(LLayout); LBtnReinstall.StyleLookup := 'replytoolbutton'; LBtnReinstall.Anchors := [TAnchorKind.akTop, TAnchorKind.akRight, TAnchorKind.akBottom]; LBtnReinstall.Align := TAlignLayout.Right; LBtnReinstall.ControlType := TControlType.Styled; LBtnReinstall.Size.Height := 35; LBtnReinstall.Size.PlatformDefault := False; LBtnReinstall.Size.Width := 35; LBtnReinstall.OnClick := DoReinstallButtonClick; LBtnReinstall.Tag := index; LBtnReinstall.TagString := AId; LLayout.AddObject(LBtnReinstall); LDroplLabel := TLabel.Create(LLayout); LDroplLabel.Align := TAlignLayout.Client; LDroplLabel.Text := AName; LLayout.AddObject(LDroplLabel); Result.AddObject(LLayout); end; procedure TForm2.DeleteInstance(AnInstanceID: string; AItemIndex: integer); var LRestClient: TRESTClient; LRestRequest: TRESTRequest; begin LRestClient := TRESTClient.Create(VULTR_API_BASE_PATH + '/instances/' + AnInstanceID); LRestRequest:= TRESTRequest.Create(nil); try try LRestRequest.Method := rmDELETE; LRestRequest.AddParameter('Authorization', 'Bearer ' + PersonalAccessToken, TRESTRequestParameterKind.pkHTTPHEADER, [poDoNotEncode]); LRestRequest.Client := LRestClient; LRestRequest.Execute; ListBox13.Items.Delete(AItemIndex); except on E:Exception do ShowMessage('Delete instance failed'); end; finally LRestRequest.Free; LRestClient.Free; end; end; procedure TForm2.DoRebootButtonClick(Sender: TObject); begin InstanceCommand((Sender as TButton).TagString, 'reboot'); end; procedure TForm2.DoReinstallButtonClick(Sender: TObject); begin InstanceCommand((Sender as TButton).TagString, 'reinstall'); end; procedure TForm2.DoStartButtonClick(Sender: TObject); begin InstanceCommand((Sender as TButton).TagString, 'start'); end; procedure TForm2.DoTrashButtonClick(Sender: TObject); begin DeleteInstance((Sender as TButton).TagString, (Sender as TButton).Tag); end; procedure TForm2.edtPATKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin case Key of vkReturn: GetAllInstance(1); end; end; function TForm2.GetAllInstance(APage: integer): TJSONObject; var LRestClient: TRESTClient; LRestRequest: TRESTRequest; LDroplets: TJSONArray; I: Integer; LLBInstance: TListBoxItem; LLayout: TLayout; LBtnTrash: TButton; LDroplLabel: TLabel; begin LRestClient := TRESTClient.Create(VULTR_API_BASE_PATH + '/instances'); LRestRequest:= TRESTRequest.Create(nil); try LRestRequest.Method := rmGET; LRestRequest.AddParameter('Authorization', 'Bearer ' + edtPAT.Text, TRESTRequestParameterKind.pkHTTPHEADER, [poDoNotEncode]); LRestRequest.Client := LRestClient; LRestRequest.Execute; Result := LRestRequest.Response.JSONValue as TJSONObject; LDroplets := Result.GetValue('instances') as TJSONArray; I := 0; for I := 0 to LDroplets.Count - 1 do begin LLBInstance := CreateListBoxItem(I, (LDroplets.Items[I] as TJSONObject).GetValue('id').Value, (LDroplets.Items[I] as TJSONObject).GetValue('label').Value); ListBox13.AddObject(LLBInstance); end; PersonalAccessToken := edtPAT.Text; edtPAT.Visible := False; finally LRestRequest.Free; LRestClient.Free; end; end; function TForm2.InstanceCommand(AnInstanceID, ACommand: string; AData: TJSONObject = nil): boolean; var LRestClient: TRESTClient; LRestRequest: TRESTRequest; begin Result := False; LRestClient := TRESTClient.Create(VULTR_API_BASE_PATH + '/instances/'+AnInstanceID+'/'+ACommand); LRestRequest:= TRESTRequest.Create(nil); try LRestRequest.Method := rmPOST; LRestRequest.AddParameter('Authorization', 'Bearer ' + PersonalAccessToken, TRESTRequestParameterKind.pkHTTPHEADER, [poDoNotEncode]); if AData <> nil then LRestRequest.AddBody(AData.ToJSON, TRESTContentType.ctAPPLICATION_JSON); LRestRequest.Client := LRestClient; LRestRequest.Execute; Result := True; finally LRestRequest.Free; LRestClient.Free; end; end; end.
unit MyDocumentController; interface uses Classes, LrDocument, LrOpenDocumentsController, MyDocumentHost; type TMyDocument = class(TLrDocument) private FText: TStringList; protected procedure SetText(const Value: TStringList); public constructor Create; override; destructor Destroy; override; procedure Load; override; procedure Save; override; property Text: TStringList read FText write SetText; end; // TMyDocumentController = class(TLrDocumentController) public class function GetDescription: string; override; class function GetExt: string; override; public function New: TLrDocument; override; procedure DocumentActivate(inDocument: TLrDocument); override; procedure DocumentDeactivate(inDocument: TLrDocument); override; procedure DocumentUpdate(inDocument: TLrDocument); override; end; implementation { TMyDocument } constructor TMyDocument.Create; begin inherited; FText := TStringList.Create; end; destructor TMyDocument.Destroy; begin FText.Free; inherited; end; procedure TMyDocument.SetText(const Value: TStringList); begin FText.Assign(Value); end; procedure TMyDocument.Save; begin inherited; FText.SaveToFile(Filename); end; procedure TMyDocument.Load; begin inherited; FText.LoadFromFile(Filename); end; { TMyDocumentController } class function TMyDocumentController.GetDescription: string; begin Result := 'My Document'; end; class function TMyDocumentController.GetExt: string; begin Result := '.txt'; end; procedure TMyDocumentController.DocumentUpdate(inDocument: TLrDocument); begin TMyDocument(inDocument).Text.Assign(MyDocumentHostForm.Memo.Lines); end; procedure TMyDocumentController.DocumentActivate(inDocument: TLrDocument); begin with MyDocumentHostForm do begin Memo.Lines.Assign(TMyDocument(inDocument).Text); Memo.OnChange := inDocument.DoModified; Show; end; end; procedure TMyDocumentController.DocumentDeactivate(inDocument: TLrDocument); begin with MyDocumentHostForm do begin Memo.OnChange := nil; Hide; end; end; function TMyDocumentController.New: TLrDocument; begin Result := CreateDocument(TMyDocument); end; end.
unit PasswordRecovery; { '******************************************************* '* Module : GTalk-Password Recovery '* Author : Arethusa '* GTalk Password Recovery, thanks to kscm, who gave '* me a snippet which wasn't working, but it was a '* beginning... This snippet has no author :( So I '* don't know, who I should give credits... '* Leave Credits if you use this module! '******************************************************* } interface uses StrUtils,Windows, CryptAPI, xMiniReg; Function GetGTalkPW(Delimitador: string): String; implementation function SysErrorMessage(ErrorCode: Integer): string; var Buffer: array[0..255] of Char; var Len: Integer; begin Len := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_IGNORE_INSERTS or FORMAT_MESSAGE_ARGUMENT_ARRAY, nil, ErrorCode, 0, Buffer, SizeOf(Buffer), nil); while (Len > 0) and (Buffer[Len - 1] in [#0..#32, '.']) do Dec(Len); SetString(Result, Buffer, Len); end; const SEED_CONSTANT = $BA0DA71D; SecretKey : Array[0..15] Of Byte = ($A3,$1E,$F3,$69, $07,$62,$D9,$1F, $1E,$E9,$35,$7D, $4F,$D2,$7D,$48); type PByteArray = ^TByteArray; TByteArray = array[0..32767] of Byte; TCharArray = Array[0..1023] Of Char; _TOKEN_USER = record User: SID_AND_ATTRIBUTES; end; type TOKEN_USER = _TOKEN_USER; TTokenUser = TOKEN_USER; PTokenUser = ^TOKEN_USER; function Decode(var Output: String; PassEntry: String; EntryLen: DWORD): Boolean; var Ret : Integer; hToken : nativeuint; SID, Name, Domain : Array[0..511] Of Char; SIDSize, I, J : DWORD; CCHName, CCHDomain : DWORD; PEUse : SID_NAME_USE; SIDUser : PTokenUser; StaticKey : TByteArray; SeedArr: TByteArray; Seed : DWORD; A, B : PByteArray; DataIn, DataEntropy, DataOut : DATA_BLOB; test:cardinal; Pass:TByteArray; begin Ret := 0; SIDSize := 0; SIDUser := PTokenUser(@SID); Move(SecretKey,StaticKey,SizeOf(SecretKey)); If OpenProcessToken(GetCurrentProcess,TOKEN_QUERY,hToken) Then begin If GetTokenInformation(hToken,TokenUser,SIDUser,SizeOf(SID),SIDSize) Then begin CCHName := SizeOf(Name); CCHDomain := SizeOf(Domain); If LookupAccountSID(nil,SIDUser.User.Sid,Name,CCHName,Domain,CCHDomain,PEUse) Then begin Seed := SEED_CONSTANT; i:=0; While (i<=CCHName-1) do begin test:=StaticKey[(I MOD 4)*4+3]*$1000000+StaticKey[(I MOD 4)*4+2]*$10000+StaticKey[(I MOD 4)*4+1]*$100+StaticKey[(I MOD 4)*4]*1; test:=test xor (ord(Name[i])*Seed); StaticKey[(i MOD 4)*4+3] := ((test and $FF000000) div $1000000); StaticKey[(i MOD 4)*4+2] := ((test and $00FF0000) div $10000); StaticKey[(i MOD 4)*4+1] := ((test and $0000FF00) div $100); StaticKey[(i MOD 4)*4+0] := test and $000000FF; Seed := Seed * $BC8F; inc(i); end; For J := 0 To CCHDomain - 1 Do begin test:=StaticKey[(I MOD 4)*4+3]*$1000000+StaticKey[(I MOD 4)*4+2]*$10000+StaticKey[(I MOD 4)*4+1]*$100+StaticKey[(I MOD 4)*4]*1; test:=test xor (ord(Domain[j])*Seed); StaticKey[(i MOD 4)*4+3] := ((test and $FF000000) div $1000000); StaticKey[(i MOD 4)*4+2] := ((test and $00FF0000) div $10000); StaticKey[(i MOD 4)*4+1] := ((test and $0000FF00) div $100); StaticKey[(i MOD 4)*4+0] := test and $000000FF; Seed := Seed * $BC8F; Inc(I); end; SeedArr[0]:=StaticKey[0]; SeedArr[1]:=StaticKey[1]; SeedArr[2]:=StaticKey[2]; SeedArr[3]:=StaticKey[3]; SeedArr[0]:=SeedArr[0] or 1; Seed := (SeedArr[3]*$1000000+SeedArr[2]*$10000+SeedArr[1]*$100+(SeedArr[0]*1)); A := PByteArray(@PassEntry[5]); B := PByteArray(@PassEntry[6]); I := 0; While I < EntryLen Do begin Pass[I div 2] := Byte(((A[I] - 1) * 16) Or (B[I] - 33) - (Seed AND $0000FFFF)); Seed := Seed * $10FF5; Inc(I,2); end; DataEntropy.cbData := SizeOf(SecretKey); DataEntropy.pbData := @StaticKey; DataIn.cbData := I div 2 -2; DataIn.pbData := @Pass; If CryptUnprotectData(@DataIn,nil,@DataEntropy,nil,nil,1,@DataOut) Then begin Output:=PChar(DataOut.pbData); SetLength(Output,DataOut.cbData); LocalFree(DWORD(Pointer(DataOut.pbData))); Ret := 1; end Else begin Output:=(SysErrorMessage(GetLastError)); end; end Else begin Output:=(SysErrorMessage(GetLastError)); end; end Else begin Output:=(SysErrorMessage(GetLastError)); end; CloseHandle(hToken); end Else begin Output:=(SysErrorMessage(GetLastError)); end; Result := Boolean(Ret); end; Function PrepareAndGetPW(EncryptedKey:String):string; var PWD : TCharArray; aOut : String; I : Integer; begin for i:=1 To Length(EncryptedKey) do PWD[i-1]:=EncryptedKey[i]; PWD[Length(EncryptedKey)+1]:=#0; For I := 0 To High(PWD) Do If (PWD[I] = #13) Or (PWD[I] = #10) Then PWD[I] := #0; If Decode(aOut,PWD,Length(EncryptedKey)) Then begin Result:=aOut; end Else begin Result:='Error'; end; end; Function GetGTalkPW(Delimitador: string): String; var SL, TempStr, s: widestring; Encrypted: String; begin Result:=''; if xMiniReg.RegKeyExists(HKEY_CURRENT_USER, 'Software\Google\Google Talk\Accounts\') then xMiniReg.RegEnumValues(HKEY_CURRENT_USER, 'Software\Google\Google Talk\Accounts\', SL); if SL <> '' then begin while SL <> '' do begin s := copy(sl, 1, posex(RegeditDelimitador, sl) - 1); delete(sl, 1, posex(RegeditDelimitador, sl) - 1); delete(sl, 1, length(RegeditDelimitador)); delete(s, 1, posex(DelimitadorComandos, s) - 1); delete(s, 1, length(DelimitadorComandos)); delete(s, 1, posex(DelimitadorComandos, s) - 1); delete(s, 1, length(DelimitadorComandos)); s := Copy(s, 1, posex(DelimitadorComandos, s) - 3); while s <> '' do begin if posex(#13, s) > 0 then begin TempStr := TempStr + copy(s, 1, posex(#13, s) - 1) + #13#10; delete(s, 1, posex(#13, s)); end else begin TempStr := TempStr + s + #13#10; s := ''; end; end; end; if TempStr = '' then Exit; Sl := TempStr; TempStr := ''; s := ''; while posex(#13#10, sl) > 0 do begin TempStr := Copy(sl, 1, posex(#13#10, sl) - 1); delete(sl, 1, posex(#13#10, sl) + 1); Result := Result + 'Google Talk' + Delimitador + TempStr + Delimitador; s := ''; if xMiniReg.RegGetString(HKEY_CURRENT_USER, 'Software\Google\Google Talk\Accounts\' + TempStr + '\' + 'pw', s) then begin Encrypted := s; if Encrypted <> '' then Result := Result + PrepareAndGetPW(Encrypted) + Delimitador + #13#10 else Result := Result + Delimitador + #13#10; end else Result := Result + Delimitador + #13#10; end; end else Result := ''; end; end.
unit MoneyOutAdd; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, CurrEdit, ToolEdit, Mask, Db, DBTables, uCommonForm,uOilQuery,Ora, uOilStoredProc, MemDS, DBAccess; type TfrmMoneyOutAdd = class(TCommonForm) pButtons: TPanel; bbOK: TBitBtn; bbCancel: TBitBtn; qProperties: TOilQuery; Panel1: TPanel; Label8: TLabel; Label6: TLabel; sbDogClear: TSpeedButton; Label7: TLabel; Label5: TLabel; Label2: TLabel; Label3: TLabel; Label1: TLabel; Label4: TLabel; mComment: TMemo; edPay: TRxCalcEdit; ceDogName: TComboEdit; ceOperName: TComboEdit; ceOrgName: TComboEdit; ceDepName: TComboEdit; dePayDate: TDateEdit; edPayNum: TEdit; procedure ceDepNameButtonClick(Sender: TObject); procedure ceOrgNameButtonClick(Sender: TObject); procedure ceOperNameButtonClick(Sender: TObject); procedure ceDogNameButtonClick(Sender: TObject); procedure bbOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure sbDogClearClick(Sender: TObject); private { Private declarations } public DepID, DepINST, OrgID, OrgInst, DogId, DogInst, OperId, CurrId, RekvId, RekvInst : Integer; flEdit : Boolean; end; var frmMoneyOutAdd: TfrmMoneyOutAdd; implementation uses DogRef, OperTypeRef, ChooseOrg, Main, UDbFunc, OilStd; {$R *.DFM} procedure TfrmMoneyOutAdd.FormCreate(Sender: TObject); begin inherited; dePayDate.Date := now; end; procedure TfrmMoneyOutAdd.ceDepNameButtonClick(Sender: TObject); var vName : String; begin inherited; if ChooseOrg.CaptureOrg(4,Main.MAIN_ID,Main.INST,'yyy',DepID,DepINST,vName) then ceDepName.Text:=vName; end; procedure TfrmMoneyOutAdd.ceOrgNameButtonClick(Sender: TObject); var vName : String; begin inherited; if ChooseOrg.CaptureOrg(4,0,0,'yyy',OrgID,OrgINST,vName) then ceOrgName.Text:=vName; qProperties.Close; qProperties.ParamByName('p_OrgId').Value:=OrgId; qProperties.ParamByName('p_OrgInst').Value:=OrgInst; qProperties.Open; RekvId := qProperties.FieldByName('id').AsInteger; RekvInst := qProperties.FieldByName('inst').AsInteger; end; procedure TfrmMoneyOutAdd.ceOperNameButtonClick(Sender: TObject); var OperTypeRefForm: TOperTypeRefForm; begin inherited; OperTypeRefForm:=TOperTypeRefForm.Create(Self); OperTypeRefForm.sgrpId:=OpG_OPLATA; OperTypeRefForm.bbClear.Enabled:=False; OperTypeRefForm.ShowModal; if (OperTypeRefForm.ModalResult=MrOk) then begin ceOperName.Text:=OperTypeRefForm.q.FieldByName('name').AsString; OperId := OperTypeRefForm.q.FieldByName('id').AsInteger; end; OperTypeRefForm.free; end; procedure TfrmMoneyOutAdd.ceDogNameButtonClick(Sender: TObject); var DogRefForm : TDogRefForm; begin DogRefForm:= TDogRefForm.Create(Self); try if (DogRefForm.ShowModal = mrOK) then begin DogId:= DogRefForm.q.FieldByName('id').AsInteger; DogInst:= DogRefForm.q.FieldByName('inst').AsInteger; ceDogName.Text := DogRefForm.q.FieldByName('Dog').AsString; end; finally DogRefForm.Free; end; end; procedure TfrmMoneyOutAdd.bbOKClick(Sender: TObject); begin if edPayNum.Text = '' then raise Exception.Create(TranslateText('Не введен номер оплаты')); if ceDepName.Text = '' then raise Exception.Create(TranslateText('Не указано подразделение')); if ceOrgName.Text = '' then raise Exception.Create(TranslateText('Не указана организация')); if ceOperName.Text = '' then raise Exception.Create(TranslateText('Не указана операция')); if edPay.Value <=0 then raise Exception.Create(TranslateText('Не указана сумма')); if not flEdit then CurrId := GetSeqNextVal('S_OIL_MONEY_OUT'); StartSQL; try _ExecProc('OIL.INSORUPDOIL_MONEY_OUT', ['ID#', CurrId, 'INST#', Main.INST, 'STATE#','Y', 'PAY_NUM#',edPayNum.Text, 'PAY_DATE#',dePayDate.Date, 'PAY#',edPay.Value, 'OPER_ID#',OperId, 'DEP_ID#',DepId, 'DEP_INST#',DepInst, 'ORG_ID#',OrgId, 'ORG_INST#',OrgInst, 'REKV_ID#',RekvId, 'REKV_INST#',RekvInst, 'DOG_ID#',DogId, 'DOG_INST#',DogInst, 'PAY_COMMENT#',mComment.Text ], TRUE ); CommitSQL; ModalResult := mrOk; except on E:Exception do begin RollBackSQL; MessageDlg(TranslateText('Ошибка:')+E.Message,mtError,[mbOk],0); end; end; end; procedure TfrmMoneyOutAdd.sbDogClearClick(Sender: TObject); begin DogId:=0; DogInst:=0; ceDogName.Clear; end; end.
unit ThImageButton; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThInterfaces, ThCssStyle, ThStyledCtrl, ThWebControl, ThPicture, ThTag, ThAnchor, ThTextPaint, ThLabel, ThAttributeList, ThStyleList, ThImage; type TThImageButton = class(TThCustomImage, IThFormInput) protected procedure Tag(inTag: TThTag); override; published property Align; property AltText; property Anchor; property AutoAspect; property AutoSize; property Border; property HAlign; property Picture; property Style; property StyleClass; property VAlign; property Visible; end; implementation procedure TThImageButton.Tag(inTag: TThTag); begin inherited; with inTag do begin Element := 'input'; Add('type', 'image'); end; end; end.
unit uOpenAPI; interface uses System.SysUtils, System.Classes, System.JSON, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TOpenAPIDM = class(TDataModule) private { Private declarations } public { Public declarations } function CreateDoc(const AHost, APort: String; ADataSet, AInfoDataSet: TFDDataSet): String; end; var OpenAPIDM: TOpenAPIDM; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses StrUtils, REST.JSON, Swag.Common.Types, Swag.Doc.Path, Swag.Doc.Path.Operation, Swag.Doc.Path.Operation.RequestParameter, Swag.Doc.Path.Operation.Response, Swag.Doc.Path.Operation.ResponseHeaders, Swag.Doc.Definition, Swag.Doc; function CreateJsonSomeSubType: TJsonObject; var vJsonType: TJsonObject; vJsonProperities: TJsonObject; begin Result := TJsonObject.Create; Result.AddPair('type','object'); vJsonType := TJsonObject.Create; vJsonType.AddPair('type', 'string'); vJsonProperities := TJsonObject.Create; vJsonProperities.AddPair('id', vJsonType); Result.AddPair('properties', vJsonProperities); end; function CreateJsonSomeType(pJsonObjectSubType: TJsonObject): TJsonObject; var vJsonId: TJsonObject; vJsonCost: TJsonObject; vJsonProperities: TJsonObject; begin Result := TJsonObject.Create; Result.AddPair('type', 'object'); vJsonId := TJsonObject.Create; vJsonId.AddPair('type', 'integer'); vJsonId.AddPair('format', 'int64'); vJsonProperities := TJsonObject.Create; vJsonProperities.AddPair('id', vJsonId); vJsonProperities.AddPair('subType', pJsonObjectSubType); vJsonCost := TJsonObject.Create; vJsonCost.AddPair('type', 'string'); vJsonCost.AddPair('format', 'decimel'); vJsonCost.AddPair('multipleOf', TJsonNumber.Create(0.01)); vJsonCost.AddPair('minimum', TJsonNumber.Create(-9999999999.99)); vJsonCost.AddPair('maximum', TJsonNumber.Create(9999999999.99)); vJsonCost.AddPair('title', 'Total Cost'); vJsonCost.AddPair('description', 'Total Cost'); vJsonCost.AddPair('example', TJsonNumber.Create(9999999999.99)); vJsonProperities.AddPair('cost', vJsonCost); Result.AddPair('properties', vJsonProperities); end; function TOpenAPIDM.CreateDoc(const AHost, APort: String; ADataSet,AInfoDataSet: TFDDataSet): String; var I: Integer; SL: TStringList; QueryString: String; vSwagDoc: TSwagDoc; vPath: TSwagPath; vOperation: TSwagPathOperation; vParam: TSwagRequestParameter; vResponse: TSwagResponse; vDefinitionSomeType: TSwagDefinition; vDefinitionResponseSomeType: TSwagDefinition; vDefinitionSomeSubType: TSwagDefinition; vResponseHeader: TSwagHeaders; begin SL := TStringList.Create; SL.StrictDelimiter := True; vSwagDoc := TSwagDoc.Create; try vSwagDoc.Info.Title := AInfoDataSet.FieldByName('Title').AsString; vSwagDoc.Info.Version := AInfoDataSet.FieldByName('Version').AsString; vSwagDoc.Info.TermsOfService := AInfoDataSet.FieldByName('TermsOfService').AsString; vSwagDoc.Info.Description := AInfoDataSet.FieldByName('Description').AsString; vSwagDoc.Info.Contact.Name := AInfoDataSet.FieldByName('ContactName').AsString; vSwagDoc.Info.Contact.Email := AInfoDataSet.FieldByName('ContactEmail').AsString; vSwagDoc.Info.Contact.Url := AInfoDataSet.FieldByName('ContactURL').AsString; vSwagDoc.Info.License.Name := AInfoDataSet.FieldByName('LicenseName').AsString; vSwagDoc.Info.License.Url := AInfoDataSet.FieldByName('LicenseURL').AsString; vSwagDoc.Host := AHost + ':' + APort; vSwagDoc.BasePath := '/'+AInfoDataSet.FieldByName('RootSegment').AsString; vSwagDoc.Consumes.Add('application/json'); vSwagDoc.Produces.Add('application/xml'); vSwagDoc.Produces.Add('application/json'); vSwagDoc.Produces.Add('application/octet-stream'); vSwagDoc.Produces.Add('text/csv'); vSwagDoc.Schemes := [tpsHttp,tpsHttps]; { vDefinitionSomeSubType := TSwagDefinition.Create; vDefinitionSomeSubType.Name := 'SomeSubType'; vDefinitionSomeSubType.JsonSchema := CreateJsonSomeSubType; vSwagDoc.Definitions.Add(vDefinitionSomeSubType); vDefinitionSomeType := TSwagDefinition.Create; vDefinitionSomeType.Name := 'SomeType'; vDefinitionSomeType.JsonSchema := CreateJsonSomeType(vDefinitionSomeSubType.GenerateJsonRefDefinition); vSwagDoc.Definitions.Add(vDefinitionSomeType); } ADataSet.First; while not ADataSet.Eof do begin SL.Clear; SL.CommaText := ADataSet.FieldByName('Params').AsString; QueryString := ''; for I := 0 to SL.Count-1 do begin QueryString := QueryString + IfThen(I=0,'?','&') + SL[I] + '={' + SL[I] + '}'; end; //ADataSet.FieldByName('RequestType').AsString + ' '; vPath := TSwagPath.Create; vPath.Uri := ADataSet.FieldByName('EndPoint').AsString + '/' + IfThen(QueryString<>'',QueryString,''); vOperation := TSwagPathOperation.Create; if ADataSet.FieldByName('RequestType').AsString='GET' then begin vOperation.Operation := ohvGet; vOperation.OperationId := 'RequestData'; vOperation.Description := 'Requests some data'; end else if ADataSet.FieldByName('RequestType').AsString='POST' then begin vOperation.Operation := ohvPost; vOperation.OperationId := 'AddOrUpdateData'; vOperation.Description := 'Add or update some data'; end else if ADataSet.FieldByName('RequestType').AsString='DELETE' then begin vOperation.Operation := ohvDelete; vOperation.OperationId := 'DeleteData'; vOperation.Description := 'Delete some data'; end; {vParam := TSwagRequestParameter.Create; vParam.Name := 'param1'; vParam.InLocation := rpiPath; vParam.Description := 'A param required'; vParam.Required := True; vParam.TypeParameter := 'string'; vOperation.Parameters.Add(vParam); } vParam := TSwagRequestParameter.Create; vParam.Name := 'X-Embarcadero-Session-Token'; vParam.InLocation := rpiHeader; vParam.Description := 'EMS User Authentication'; vParam.Required := False; vParam.TypeParameter := 'string'; vOperation.Parameters.Add(vParam); vParam := TSwagRequestParameter.Create; vParam.Name := 'X-Embarcadero-Tenant-Id'; vParam.InLocation := rpiHeader; vParam.Description := 'EMS Tenant Id'; vParam.Required := False; vParam.TypeParameter := 'string'; vOperation.Parameters.Add(vParam); vParam := TSwagRequestParameter.Create; vParam.Name := 'X-Embarcadero-Tenant-Secret'; vParam.InLocation := rpiHeader; vParam.Description := 'EMS Tenant Secret'; vParam.Required := False; vParam.TypeParameter := 'string'; vOperation.Parameters.Add(vParam); for I := 0 to SL.Count-1 do begin vParam := TSwagRequestParameter.Create; vParam.Name := SL[I]; vParam.InLocation := rpiQuery; vParam.Description := 'A param called '+SL[I]; vParam.Required := True; vParam.TypeParameter := 'string'; vOperation.Parameters.Add(vParam); end; if ADataSet.FieldByName('RequestType').AsString='POST' then begin vParam := TSwagRequestParameter.Create; vParam.Name := 'Body'; vParam.InLocation := rpiBody; vParam.Description := 'Post Body'; vParam.Required := False; vParam.TypeParameter := 'string'; vOperation.Parameters.Add(vParam); end; { vParam := TSwagRequestParameter.Create; vParam.Name := 'param3'; vParam.InLocation := rpiBody; vParam.Required := True; vParam.Schema.Name := 'SomeType'; vOperation.Parameters.Add(vParam); } vResponse := TSwagResponse.Create; vResponse.StatusCode := '200'; vResponse.Description := 'Successfully retrieved data'; //vResponse.Schema.Name := 'SomeType'; vOperation.Responses.Add('200', vResponse); {vResponseHeader := TSwagHeaders.Create; vResponseHeader.Name := 'X-Rate-Limit-Limit'; vResponseHeader.Description := 'The number of allowed requests in the current period'; vResponseHeader.ValueType := 'integer'; vResponse.Headers.Add(vResponseHeader); } vResponse := TSwagResponse.Create; vResponse.StatusCode := 'default'; vResponse.Description := 'Error occured'; vOperation.Responses.Add('default',vResponse); vOperation.Tags.Add(ADataSet.FieldByName('EndPoint').AsString); vPath.Operations.Add(vOperation); vSwagDoc.Paths.Add(vPath); ADataSet.Next; end; vSwagDoc.GenerateSwaggerJson; Result := REST.Json.TJson.Format(vSwagDoc.SwaggerJson); finally FreeAndNil(vSwagDoc); end; end; end.
unit pSHCompletionProposal; {$I SynEdit.inc} interface uses Classes, Controls, Messages, Windows, Graphics, Forms, StdCtrls, SynCompletionProposal, SynEdit, SynEditTypes, pSHIntf,pSHSqlTxtRtns; type TpSHCompletionProposal = class(TSynCompletionProposal) private FNeedObjectType: TpSHNeedObjectType; FCompletionProposalWndProc: TWndMethod; FCompletionProposalOptions: IpSHCompletionProposalOptions; procedure CompletionProposalWndProc(var Message: TMessage); procedure WindowClose(Sender: TObject); protected function NeedHint(var ATextHeight, ATextWidth: Integer; var AHint: string; var AMousePos: TPoint): boolean; procedure DoAfterCodeCompletion(Sender: TObject; const Value: string; Shift: TShiftState; Index: Integer; EndToken: Char); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ExecuteEx(s: string; x, y: integer; Kind: SynCompletionType {$IFDEF SYN_COMPILER_4_UP} = ctCode {$ENDIF}); override; procedure ActivateCompletion(AEditor: TSynEdit); overload; property CompletionProposalOptions: IpSHCompletionProposalOptions read FCompletionProposalOptions write FCompletionProposalOptions; property NeedObjectType: TpSHNeedObjectType read FNeedObjectType write FNeedObjectType; published end; TpSHCompletionProposalHintWnd = class(THintWindow) private FActivating: Boolean; FCompletionProposal: TpSHCompletionProposal; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; protected procedure Paint; override; public function CalcHintRect(MaxWidth: Integer; const AHint: string; AData: Pointer): TRect; override; procedure ActivateHint(Rect: TRect; const AHint: string); override; procedure ActivateHintData(Rect: TRect; const AHint: string; AData: Pointer); override; end; TpSHCompletionProposalHintWndClass = class of TpSHCompletionProposalHintWnd; implementation uses SynEditHighlighter, pSHSynEdit, pSHHighlighter, SysUtils, pSHStrUtil, StrUtils; { TBTCompletionProposal } procedure TpSHCompletionProposal.CompletionProposalWndProc(var Message: TMessage); var vMousePos: TPoint; vTextHeight: Integer; vTextWidth: Integer; s: string; begin FCompletionProposalWndProc(Message); with Message do case Msg of CM_HINTSHOWPAUSE: with TCMHintShowPause(Message) do begin if NeedHint(vTextHeight, vTextWidth, s, vMousePos) then Pause^ := 0 else Pause^ := Application.HintPause; end; CM_HINTSHOW: with TCMHintShow(Message), PHintInfo(TCMHintShow(Message).HintInfo)^ do begin if NeedHint(vTextHeight, vTextWidth, HintStr, vMousePos) then begin HintWindowClass := TpSHCompletionProposalHintWnd; HintPos.X := Form.Left + 3; HintPos.Y := Form.Top + ((vMousePos.Y - 3) div vTextHeight) * vTextHeight + 2; CursorRect := Rect(HintPos.X, HintPos.Y, HintPos.X + vTextWidth, HintPos.Y + vTextHeight); HintMaxWidth := vTextWidth + 1; ReshowTimeout := 10000; HideTimeout := 0; HintData := Self; Result := 0; end else Result := -1; end; end; end; procedure TpSHCompletionProposal.WindowClose(Sender: TObject); begin if Assigned(FCompletionProposalOptions) then begin FCompletionProposalOptions.LinesCount := NbLinesInWindow; FCompletionProposalOptions.Width := Width; end; end; function TpSHCompletionProposal.NeedHint(var ATextHeight, ATextWidth: Integer; var AHint: string; var AMousePos: TPoint): boolean; var vHintItem: Integer; vScrollBar: TScrollBar; vItmList: TStrings; function FindScrollBar(AComponent: TComponent): TScrollBar; var I: Integer; begin Result := nil; for I := 0 to AComponent.ComponentCount - 1 do begin if AComponent.Components[I].ClassType = TScrollBar then begin Result := TScrollBar(AComponent.Components[I]); break; end; end; end; begin Result := False; if (DisplayType = ctCode) then begin GetCursorPos(AMousePos); ScreenToClient(Form.Handle, AMousePos); vScrollBar := FindScrollBar(Form); if Assigned(vScrollBar) then begin ATextHeight := Form.Canvas.TextHeight('W') + 3; vHintItem := ((AMousePos.Y - 3) div ATextHeight) + vScrollBar.Position; if scoLimitToMatchedText in Options then vItmList := Form.AssignedList else vItmList := ItemList; if ((vHintItem >= 0) and (vHintItem < vItmList.Count)) then begin AHint := vItmList[vHintItem]; ATextWidth := FormattedTextWidth(Form.Canvas, AHint, Form.Columns, Images); Result := ATextWidth > (Form.Width - 7 - vScrollBar.Width); end; end; end; end; procedure TpSHCompletionProposal.DoAfterCodeCompletion(Sender: TObject; const Value: string; Shift: TShiftState; Index: Integer; EndToken: Char); begin if Length(Value)>2 then if (Value[Length(Value)]=')') and (Value[Length(Value)-1]='(') then with Form.CurrentEditor do CaretX:=CaretX-1 end; constructor TpSHCompletionProposal.Create(AOwner: TComponent); begin inherited Create(AOwner); DefaultType := ctCode; FNeedObjectType := ntAll; Form.ShowHint := True; Form.ItemHeight := Form.Canvas.TextHeight('W') + 3; FCompletionProposalWndProc := Form.WindowProc; Form.WindowProc := CompletionProposalWndProc; OnClose := WindowClose; // EndOfTokenChr := EndOfTokenChr + '='; EndOfTokenChr := '()[]= '; OnAfterCodeCompletion:=DoAfterCodeCompletion; Options := Options + [scoConsiderWordBreakChars]; end; destructor TpSHCompletionProposal.Destroy; begin Form.WindowProc := FCompletionProposalWndProc; inherited; end; procedure TpSHCompletionProposal.ExecuteEx(s: string; x, y: integer; Kind: SynCompletionType); const CharsAfterClause =[' ',#13,#9,'(',',',';']; CharsBeforeClause=[' ',#10,')',#9]; var vHiAttr: TSynHighlighterAttributes; vToken: string; vTokenStart: Integer; vTokenKind: Integer; lookup: string; TmpYUp, TmpYDown: Integer; vCurrentCaretX: Integer; vCurrentCaretY: Integer; NeedObjectNameSearch: Boolean; CanExecute: Boolean; TmpLine: string; function FindFullLineUp(var Y: Integer): Boolean;//перескакиваем вверх на полную строку var vLLLength: Integer; begin Result := False; with TpSHSynEdit(Form.CurrentEditor) do begin while Y > 0 do begin vLLLength := Length(Lines[Y - 1]); if vLLLength > 0 then begin vCurrentCaretX := length(Lines[Y - 1]); Result := True; Break; end else Dec(Y); end; end; end; procedure SkipSpaces(var ALineNo: Integer); var vBufferCoord: TBufferCoord; begin vTokenKind := Ord(tkSpace); while ((vTokenKind = Ord(tkSpace)) or (vTokenKind = Ord(tkNull))) and (ALineNo > 0) do begin if vCurrentCaretX > 1 then Dec(vCurrentCaretX) else begin // repeat while (vCurrentCaretX <= 1) and (ALineNo > 1) do begin Dec(ALineNo); vCurrentCaretX := Length(TpSHSynEdit(Form.CurrentEditor).Lines[ALineNo - 1]); end; // until (vCurrentCaretX > 1) or (ALineNo = 1); end; if (vCurrentCaretX > 1) and (vCurrentCaretX <= Length(TpSHSynEdit(Form.CurrentEditor).Lines[ALineNo - 1])) and (TpSHSynEdit(Form.CurrentEditor).Lines[ALineNo - 1][vCurrentCaretX] = ')') then begin repeat { if vCurrentCaretX = 0 then begin if ALineNo = 1 then Break; Dec(ALineNo); vCurrentCaretX := Length(TpSHSynEdit(Form.CurrentEditor).Lines[ALineNo - 1]); end else Dec(vCurrentCaretX); } Dec(vCurrentCaretX); while (vCurrentCaretX = 0) do begin if ALineNo = 1 then Break; Dec(ALineNo); vCurrentCaretX := Length(TpSHSynEdit(Form.CurrentEditor).Lines[ALineNo - 1]); end; if ALineNo = 1 then begin vCurrentCaretX := 1; Break; end; until (TpSHSynEdit(Form.CurrentEditor).Lines[ALineNo - 1][vCurrentCaretX] = '(' ); Dec(vCurrentCaretX); end; vBufferCoord.Char := vCurrentCaretX; vBufferCoord.Line := ALineNo; TpSHSynEdit(Form.CurrentEditor).GetHighlighterAttriAtRowColEx( vBufferCoord, vToken, vTokenKind, vTokenStart, vHiAttr); if (vCurrentCaretX <= 1) and (ALineNo = 1) then Break; end; end; function FindObjectAtLine(var ALineNo: Integer): Boolean; var vLookUp: string; vLineNo: Integer; begin vLineNo := ALineNo; Result := False; with TpSHSynEdit(Form.CurrentEditor) do begin if ((ALineNo <= 0) or (ALineNo > Lines.Count)) then exit; if Assigned(Highlighter) then begin // vCurrentCaretX := GetTokenPos(vLineNo, 1, lookup); vCurrentCaretX := PosExtCI(lookup, Lines[vLineNo - 1], CharsBeforeClause,CharsAfterClause); // vIdent := Length(Lines[vLineNo - 1]) - (Length(lookup) + 1); // vCurrentCaretX := GetTokenPos(vLineNo, vIdent, lookup); if (vCurrentCaretX = 1) and (vLineNo > 0) then begin Dec(vLineNo); vCurrentCaretX := Length(Lines[vLineNo - 1]) + 1; end; if vCurrentCaretX > 0 then // while (vIdent > 0) and (not Result) do begin SkipSpaces(vLineNo); if vCurrentCaretX > 0 then begin vlookup := GetTokenAt(TBufferCoord(Point(vCurrentCaretX, vLineNo)), vTokenKind); Result := vTokenKind = Ord(tkTableName); if Result then lookup := vlookup; end; end; end; end; end; //Buzz procedure GetObjectTypeFromText(CaretX,CaretY:integer) ; var p:TSQLParser; SQLText:string; PosInText:integer; PosIn:TSQLSections; bgStatement:integer; // vSQLKind:TSQLKind; begin SQLText:=TpSHSynEdit(Form.CurrentEditor).Lines.Text; p:=TSQLParser.Create(SQLText); with TpSHSynEdit(Form.CurrentEditor) do try { TODO -oBuzz -cProposal : Добиться правильного распарсивания DDL (триггеров процедур) } // vSQLKind:=p.SQLKind; PosInText:=(CaretX-Length(Lines[CaretY-1])); if PosInText>0 then PosInText:=SelStart-PosInText+1 else PosInText:=SelStart ; bgStatement:= p.BeginSimpleStatementForPos(PosInText); if bgStatement<>1 then begin Dec(PosInText,bgStatement-1); p.SQLText:=Copy(p.SQLText,bgStatement,MaxInt); end; PosIn:=p.PosInSections(PosInText); if Length(PosIn)>0 then case PosIn[Length(PosIn)-1] of stFields: if (Length(PosIn)=1) or (PosIn[Length(PosIn)-2]<>stInsert) then NeedObjectType :=ntFieldOrVariableOrFunction else NeedObjectType :=ntField; stUpdate: NeedObjectType:=ntTableOrView; stSet: NeedObjectType:=ntField; stFrom: if (Length(PosIn)>1) then begin if (PosIn[Length(PosIn)-2]=stDelete) then NeedObjectType :=ntTableOrView else NeedObjectType :=ntTableOrViewOrProcedure; end else NeedObjectType :=ntTableOrViewOrProcedure; stWhere: NeedObjectType :=ntFieldOrVariableOrFunction; stInto: if (Length(PosIn)>1) and (PosIn[Length(PosIn)-2]=stInsert) then NeedObjectType :=ntTableOrView else NeedObjectType :=ntVariable; stValues: NeedObjectType :=ntFieldOrVariableOrFunction; stReturning: NeedObjectType :=ntField; stReturningValues: NeedObjectType :=ntVariable; stException: NeedObjectType :=ntException; stExecute: NeedObjectType :=ntExecutable; stProcedure: NeedObjectType :=ntProcedure; stNeedReturningValues: NeedObjectType :=ntReturningValues; stDeclareVariables: NeedObjectType :=ntDeclareVariables; end; finally p.Free end; end; function GetFirstTableName:string; var p:TSQLParser; SQLText:string; PosInText:integer; bgStatement:integer; begin SQLText:=TpSHSynEdit(Form.CurrentEditor).Lines.Text; p:=TSQLParser.Create(SQLText); try case p.SQLKind of skSelect: Result:=p.MainFrom; skUpdate,skInsert,skDelete: Result:=p.ModifiedTables; else with TpSHSynEdit(Form.CurrentEditor) do begin PosInText:=(CaretX-Length(Lines[CaretY-1])); if PosInText>0 then PosInText:=SelStart-PosInText+1 else PosInText:=SelStart ; bgStatement:= p.BeginSimpleStatementForPos(PosInText); if bgStatement<>1 then begin p.SQLText:=Copy(p.SQLText,bgStatement,MaxInt); end; case p.SQLKind of skSelect: begin Result:=CutTableName(p.MainFrom); end; skUpdate,skInsert,skDelete: Result:=p.ModifiedTables; else Result:='' end; end end finally p.Free end end; //end Buzz begin with TpSHSynEdit(Form.CurrentEditor) do begin //данная прелюдия к вызову наследованного метода обусловлена необходимостью //определить, что нужно пропосалу - все, поля к таблице (с вычислением ее //имени по псевдониму, поля таблице в триггере, переменные процедуры NeedObjectNameSearch := False; if Assigned(Highlighter) and (Kind = ctCode) then //если не насильственный вызов пропосала на определенный тип объектов if not (NeedObjectType in [ntDomain..ntBuildInFunctions]) then begin vCurrentCaretX := CaretX - 1; vCurrentCaretY := CaretY; vToken := GetTokenAt(TBufferCoord(Point(vCurrentCaretX, CaretY)), vTokenKind); //Buzz GetObjectTypeFromText(vCurrentCaretX, CaretY); //End Buzz case TtkTokenKind(vTokenKind) of tkVariable: NeedObjectType := ntVariable; tkSymbol: if vToken = '.' then NeedObjectNameSearch := True else begin if (TpSHHighlighter(Highlighter).SQLDialect = sqlSybase) and (vToken = '@') then NeedObjectType := ntVariable else if (TpSHHighlighter(Highlighter).SQLDialect in [sqlOracle, sqlIngres, sqlInterbase]) and (vToken = ':') then NeedObjectType := ntVariable; end; tkString: if TpSHHighlighter(Highlighter).SQLDialect = sqlInterbase then begin vCurrentCaretX := CaretX; SkipSpaces(vCurrentCaretY); vCurrentCaretX := vTokenStart; SkipSpaces(vCurrentCaretY); NeedObjectNameSearch := (TtkTokenKind(vTokenKind) = tkSymbol) and (vToken = '.'); end; else if (TtkTokenKind(vTokenKind) <> tkSpace) and (Length(vToken) > 0) then begin vCurrentCaretX := CaretX; SkipSpaces(vCurrentCaretY); vCurrentCaretX := vTokenStart; SkipSpaces(vCurrentCaretY); NeedObjectNameSearch := (TtkTokenKind(vTokenKind) = tkSymbol) and (vToken = '.'); end; end; //если поле таблицы/триггера if NeedObjectNameSearch then begin // CompletionStart := vCurrentCaretX + 1; заремлено после исправления бага от Воинова - отремлено Options := Options + [scoConsiderWordBreakChars]; в Create SkipSpaces(vCurrentCaretY); //вычисляем, что до точки, если вобще что-то там есть //если нет - работаем по стандартной схеме, х.з., что в голове у //юзеров разных серверов :) if TtkTokenKind(vTokenKind) = tkKey then begin if TpSHHighlighter(Highlighter).SQLDialect = sqlInterbase then begin if (AnsiUpperCase(vToken) = 'NEW') or (AnsiUpperCase(vToken) = 'OLD') then NeedObjectType := ntField; end; end else if TtkTokenKind(vTokenKind) <> tkTableName then begin //если нам подсунули псевдоним - придется поработать TmpYUp := vCurrentCaretY; Inc(vCurrentCaretY); TmpYDown := vCurrentCaretY; vCurrentCaretX := vTokenStart - 1; lookup := vToken; //пока не найдем эту гребанную таблицу while ((TmpYUp > 0) or (TmpYDown <= Lines.Count)) do begin //если есть выше или ниже if FindObjectAtLine(TmpYUp) or FindObjectAtLine(TmpYDown) then begin vToken := lookup; NeedObjectType := ntField; Break; end else //если не нашли расширяемся в обе стороны begin if (TmpYDown < vCurrentCaretY) then TmpYDown := vCurrentCaretY + 1; vCurrentCaretY := TmpYDown; if TmpYUp > 0 then Dec(TmpYUp); //пропускаем пустые строки while ((TmpYUp > 0) and (Length(Lines[TmpYUp - 1]) = 0)) do Dec(TmpYUp); if TmpYDown <= Lines.Count then Inc(TmpYDown); while ((TmpYDown <= Lines.Count) and (Length(Lines[TmpYDown - 1]) = 0)) do Inc(TmpYDown); end; end; end else NeedObjectType := ntField; end else begin vToken := s; if NeedObjectType in [ntField,ntFieldOrFunction,ntFieldOrVariableOrFunction] then begin // vToken:=CutTableName(GetFirstTableName); vToken:=GetFirstTableName; if vToken='' then NeedObjectType :=ntAll end end; end; CanExecute := True; //Обрабатываем возможное наличие кавычки для сдвига CompletionStart if (Form.CurrentEditor.Lines.Count > 0) and (Form.CurrentEditor.CaretY <= Form.CurrentEditor.Lines.Count) then begin TmpLine := Form.CurrentEditor.Lines[Form.CurrentEditor.CaretY - 1]; if (CompletionStart > 1) and (CompletionStart - 1 <= Length(TmpLine)) and (TmpLine[CompletionStart - 1] = '"') then CompletionStart := CompletionStart - 1; end; if Assigned(Form.CurrentEditor.Highlighter) and Assigned(TpSHHighlighter(Form.CurrentEditor.Highlighter).ObjectNamesManager) then TpSHHighlighter(Form.CurrentEditor.Highlighter).ObjectNamesManager.ExecuteNotify(Ord(Kind), Self, vToken, x, y, CanExecute); ResetAssignedList; Form.CurrentString := vToken; { if CanExecute and (Form.AssignedList.Count > 0) then begin if Assigned(FCompletionProposalOptions) then begin NbLinesInWindow := FCompletionProposalOptions.LinesCount; Self.Width := FCompletionProposalOptions.Width; end; inherited ExecuteEx(vToken, x, y, Kind); end; } if (not CanExecute) or (Form.AssignedList.Count = 0) then begin ItemList.Clear; InsertList.Clear; end; if Assigned(FCompletionProposalOptions) then begin NbLinesInWindow := FCompletionProposalOptions.LinesCount; Self.Width := FCompletionProposalOptions.Width; end; if vToken<>'.' then vToken :=s; inherited ExecuteEx(vToken, x, y, Kind); if Kind = ctCode then NeedObjectType := ntAll; end; end; procedure TpSHCompletionProposal.ActivateCompletion(AEditor: TSynEdit); begin DoExecute(AEditor); end; { TpSHCompletionProposalHintWnd } procedure TpSHCompletionProposalHintWnd.CMTextChanged( var Message: TMessage); begin inherited; { Avoid flicker when calling ActivateHint } if FActivating then Exit; if Assigned(FCompletionProposal) then begin Width := FormattedTextWidth(Canvas, Caption, FCompletionProposal.Columns, FCompletionProposal.Images) + 6; Height := Height + 3; end; end; procedure TpSHCompletionProposalHintWnd.Paint; var R: TRect; begin if Assigned(FCompletionProposal) then begin R := ClientRect; Inc(R.Left, 1); Inc(R.Top, 1); // Canvas.Rectangle(-1,-1, Width, Height); // Canvas.Font.Color := clInfoText; FormattedTextOut(Canvas, R, Caption, False, FCompletionProposal.Columns, FCompletionProposal.Images); end else inherited; end; function TpSHCompletionProposalHintWnd.CalcHintRect(MaxWidth: Integer; const AHint: string; AData: Pointer): TRect; var vMousePos: TPoint; vTextHeight: Integer; vTextWidth: Integer; s: string; begin if Assigned(AData) and TpSHCompletionProposal(AData).NeedHint(vTextHeight, vTextWidth, s, vMousePos) then begin Result := Rect(0, 0, vTextWidth, vTextHeight); Inc(Result.Right, 6); Dec(Result.Bottom, 1); end else Result := inherited CalcHintRect(MaxWidth, AHint, AData); end; procedure TpSHCompletionProposalHintWnd.ActivateHint(Rect: TRect; const AHint: string); begin FActivating := True; try inherited; finally FActivating := False; end; end; procedure TpSHCompletionProposalHintWnd.ActivateHintData(Rect: TRect; const AHint: string; AData: Pointer); begin if AData <> nil then begin FCompletionProposal := TpSHCompletionProposal(AData); Canvas.Font.Assign(FCompletionProposal.Form.Canvas.Font); Canvas.Font.Style := Canvas.Font.Style - [fsBold]; end else FCompletionProposal := nil; inherited; end; end.
{*******************************************************} { } { fFrameSearch.pas { Copyright @2014/5/20 16:00:27 by 姜梁 { } { 功能描述: { 函数说明: {*******************************************************} unit fFrameSearch; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,tSreachThread,tCompareThread, dDataModelFileInfo, dDataModelSearchCondition, ComCtrls, ExtCtrls; type BreakSreachEvent = procedure() of object; FinishSreachEvent = procedure(title,context:string) of object; type TFrameSearchProcess = class(TFrame) pbSreach: TProgressBar; lblText: TLabel; btnNo: TButton; grpGroup: TGroupBox; lblFileAnaText: TLabel; lblTimeText: TLabel; lblClonedText: TLabel; lblFileNum: TLabel; lblTimeNum: TLabel; lblClonedNum: TLabel; tmrTime: TTimer; procedure btnNoClick(Sender: TObject); procedure tmrTimeTimer(Sender: TObject); private myFileList: TListFileInfo; sec,min:Integer; //秒分 index,indexSame:Integer; MySreachThread: TThreadSearchFile; MyCompareThread: TThreadCompareFile; procedure GetProgress(var Msg:TMessage);message WM_EndSreach; procedure GetCompare(var Msg:TMessage);message WM_IncProgress; public MyBreakSreachEvent:BreakSreachEvent; MyFinishSreachEvent:FinishSreachEvent; mySreachCondition: TMySreachCondition; myListSameFile:TListSameFileData; procedure BeginThread(); end; implementation {$R *.dfm} /// <summary> /// 初始化窗体必须调用,启动线程 /// </summary> procedure TFrameSearchProcess.BeginThread; begin pbSreach.Position := 0; myFileList:= TListFileInfo.Create; lblText.Caption := 'Getting File Directory'; lblFileNum.Caption := '0'; lblClonedNum.Caption := '0'; lblTimeNum.Caption := '00:00'; pbSreach.Style := TProgressBarStyle.pbstMarquee; MySreachThread:= TThreadSearchFile.Create(True); MySreachThread.MySreachCondition := mySreachCondition; MySreachThread.MyListFileInfo := myFileList; MySreachThread.MainHandle:= Handle; MySreachThread.Resume; tmrTime.Enabled := True; min:= 0; sec:= 0; index:= 0; indexSame:= 0; end; procedure TFrameSearchProcess.btnNoClick(Sender: TObject); begin if Assigned(MySreachThread)then MySreachThread.Terminate; if Assigned(MyCompareThread) then MyCompareThread.Terminate; if Assigned(MyBreakSreachEvent) then MyBreakSreachEvent; pbSreach.Position :=0; end; /// <summary> /// 取得比较线程通知消息 /// </summary> procedure TFrameSearchProcess.GetCompare(var Msg: TMessage); begin if Msg.WParam = EndCompareNum then begin if Assigned(MyFinishSreachEvent) then begin MyFinishSreachEvent('Sreach Complicated', 'Cloned Files Total:'+ lblClonedNum.Caption); lblText.Caption:=''; tmrTime.Enabled :=False; btnNo.Hide; myFileList.Free; end; end else if Msg.WParam = AddNum then begin Inc(indexSame); lblClonedNum.Caption := IntToStr(indexSame); end else begin pbSreach.Position:= pbSreach.Position+ Msg.WParam ; end; end; /// <summary> /// 取得查找线程通知消息 /// </summary> procedure TFrameSearchProcess.GetProgress(var Msg: TMessage); begin if Msg.LParam = 0 then begin inc(index); lblFileNum.Caption := IntToStr(index); Exit; end; pbSreach.Max := index*2; pbSreach.Style := TProgressBarStyle.pbstNormal; lblText.Caption := 'Sreach the cloned Files'; MyCompareThread:= TThreadCompareFile.Create(myFileList); MyCompareThread.MainHandle:= Handle; MyCompareThread.ListTotalSameData := myListSameFile; MyCompareThread.Resume; end; procedure TFrameSearchProcess.tmrTimeTimer(Sender: TObject); begin sec:=sec+1; if sec >59 then begin min:=min+1 ; sec:=0; if min > 59 then begin sec:= 0; min:= 0; end; end; lblTimeNum.Caption := format('%2.2d',[min])+':'+format('%2.2d',[sec]); end; end.
PROGRAM DataTypes; // VAR // x: BYTE; // y: CHAR; // BEGIN // WriteLn(Low(BYTE)); // WriteLn(High(BYTE)); // // FOR x := Low(x) TO High(BYTE) DO Write(x, ' '); // x := 3; // WriteLn(Succ(x)); // nachfolger // WriteLn(Pred(x)); // vorgänger // {* funktioniert auch bei CHAR *} // y := Low(y); // WHILE y <= High(y) DO BEGIN // Write(y, ' '); // // y := Succ(y); // Inc(x); // END; // END. // VAR // d: (Mon, Tue, Wed, Thu, Fri, Sat, Sun); // BEGIN // d := Mon; // d := High(d); // WriteLn(d); // FOR d := Tue TO Thu DO // WriteLn(d); // END. // VAR // x: 10..20; // Interval // d: (Mon, Tue, Wed, Thu, Fri, Sat, Sun); // d2: Mon..Fri; // BEGIN // x := 11; // x := Low(x); // x := High(x); // WriteLn(x); // d2 := Fri; // WriteLn(d2); // END. TYPE Day = (Mon, Tue, Wed, Thu, Fri, Sat, Sun); WeekDay = Mon..Fri; VAR x: ARRAY[BYTE] OF REAL; y: ARRAY[1..10] OF REAL; z: ARRAY[Day] OF REAL; i: WeekDay; BEGIN x[0] := 1.3; x[6] := 7.5; END.
unit Video; interface uses Aurelius.Mapping.Attributes, MediaFile, VideoFormat; type [Entity] [DiscriminatorValue('VIDEO')] TVideo = class(TMediaFile) private FVideoFormat: TVideoFormat; public [Association([], [])] [JoinColumn('ID_VIDEO_FORMAT', [])] property VideoFormat: TVideoFormat read FVideoFormat write FVideoFormat; end; implementation end.
unit Odontologia.Modelo.Paciente; interface uses Data.DB, SimpleDAO, SimpleInterface, SimpleQueryRestDW, System.SysUtils, Odontologia.Modelo.Conexion.RestDW, Odontologia.Modelo.Paciente.Interfaces, Odontologia.Modelo.Estado, Odontologia.Modelo.Estado.Interfaces, Odontologia.Modelo.Entidades.Paciente; type TModelPaciente = class(TInterfacedOBject, iModelPaciente) private FEntidad : TDPACIENTE; FDAO : iSimpleDao<TDPACIENTE>; FDataSource : TDataSource; FEmpresa : iModelEstado; public constructor Create; destructor Destroy; override; class function New : iModelPaciente; function Entidad : TDPACIENTE; overload; function Entidad(aEntidad: TDPACIENTE) : iModelPaciente; overload; function DAO : iSimpleDAO<TDPACIENTE>; function DataSource(aDataSource: TDataSource) : iModelPaciente; function Estado : iModelEstado; end; implementation { TModelPaciente } constructor TModelPaciente.Create; begin FEntidad := TDPACIENTE.Create; FDAO := TSimpleDAO<TDPACIENTE> .New(TSimpleQueryRestDW<TDPACIENTE> .New(ModelConexion.RESTDWDataBase1)); FEmpresa := TModelEstado.New; end; function TModelPaciente.DAO: iSimpleDao<TDPACIENTE>; begin Result := FDAO; end; function TModelPaciente.DataSource(aDataSource: TDataSource): iModelPaciente; begin Result := Self; FDataSource := aDataSource; FDAO.DataSource(FDataSource); end; destructor TModelPaciente.Destroy; begin FreeAndNil(FEntidad); inherited; end; function TModelPaciente.Entidad(aEntidad: TDPACIENTE): iModelPaciente; begin Result := Self; FEntidad := aEntidad; end; function TModelPaciente.Entidad: TDPACIENTE; begin Result := FEntidad; end; class function TModelPaciente.New: iModelPaciente; begin Result := Self.Create; end; function TModelPaciente.Estado: iModelEstado; begin Result := FEmpresa; end; end.
{$I ogem.inc} unit NF_OPS; interface const NF_ID_NAME : pchar = 'NF_NAME'; NF_ID_VERSION : pchar = 'NF_VERSION'; NF_ID_STDERR : pchar = 'NF_STDERR'; NF_ID_SHUTDOWN : pchar = 'NF_SHUTDOWN'; NF_ID_EXIT : pchar = 'NF_EXIT'; NF_ID_DEBUG : pchar = 'DEBUGPRINTF'; NF_ID_ETHERNET : pchar = 'ETHERNET'; NF_ID_HOSTFS : pchar = 'HOSTFS'; NF_ID_AUDIO : pchar = 'AUDIO'; NF_ID_BOOTSTRAP : pchar = 'BOOTSTRAP'; NF_ID_CDROM : pchar = 'CDROM'; NF_ID_CLIPBRD : pchar = 'CLIPBRD'; NF_ID_JPEG : pchar = 'JPEG'; NF_ID_OSMESA : pchar = 'OSMESA'; NF_ID_PCI : pchar = 'PCI'; NF_ID_FVDI : pchar = 'fVDI'; NF_ID_USBHOST : pchar = 'USBHOST'; NF_ID_XHDI : pchar = 'XHDI'; NF_ID_SCSI : pchar = 'NF_SCSIDRV'; NF_ID_HOSTEXEC : pchar = 'HOSTEXEC'; NF_ID_CONFIG : pchar = 'NF_CONFIG'; (* * return the NF id to use for feature_name, * or zero when not available. *) function nf_get_id(feature_name: pchar): longint; (* * return the version of the NatFeat implementation, * or zero when not available. *) function nf_version: longint; (* * return the name of the NatFeat implementor, * or NULL when not available. *) procedure nf_get_name(buf: Pchar; bufsize: longint); (* * return the full name of the NatFeat implementor, * or NULL when not available. *) procedure nf_get_fullname(buf: Pchar; bufsize: longint); (* * Write a string to the host's terminal. * returns TRUE when available, FALSE otherwise. *) function nf_debug(const s: string): boolean; (* * Shutdown the emulator. * May only be called from Supervisor. *) function nf_shutdown(mode: integer): longint; (* * Shutdown the emulator. * May be called from user mode. *) function nf_exit(exitcode: integer): longint; implementation {$IFDEF FPC} uses xbios; {$ELSE} uses tos; {$ENDIF} const NATFEAT_ID = $7300; NATFEAT_CALL = $7301; var nf_available: boolean; nf_inited: boolean; nf_stderr: longint; {$IFDEF HAVE_CDECL} type Tnf_id = function(id: Pchar): longint; cdecl; Tnf_call = function(id: longint): longint; cdecl; varargs; {$ELSE} type Tnf_id = function(d1, d2: pointer; d3,d4,d5: longint; id: Pchar): longint; Tnf_call = function(d1, d2: pointer; d3,d4,d5: longint; id: longint; arg1: pointer; arg2: longint): longint; {$ENDIF} var cnf_call: Tnf_call; const nf_id_opcodes: array[0..1] of word = (NATFEAT_ID, $4e75); nf_call_opcodes: array[0..1] of word = (NATFEAT_CALL, $4e75); function nf_id(id: Pchar): longint; var cnf_id: Tnf_id; begin cnf_id := Tnf_id(@nf_id_opcodes); {$IFDEF HAVE_CDECL} nf_id := cnf_id(id); {$ELSE} nf_id := cnf_id(nil, nil, 0, 0, 0, id); {$ENDIF} end; {$IFDEF XXXX} function nf_call(id: longint; const Args: array of const): longint; cdecl; varargs; begin cnf_call := Tnf_call(@nf_call_opcodes); {$IFDEF HAVE_CDECL} nf_call := cnf_call(id, args); {$ELSE} nf_call := cnf_call(nil, nil, 0, 0, 0, id, args); {$ENDIF} end; {$ENDIF} {$IFDEF FPC} const nf_version_str: array[0..11] of char = 'NF_VERSION'; function nf_detect: longint; assembler; nostackframe; asm {$IFDEF CPUCFV4E} (* * on ColdFire, the NATFEAT_ID opcode is actually * "mvs.b d0,d1". * But since there is no emulator that emulates a ColdFire, * this feature isn't available. *) moveq #0,d0 {$ELSE} pea nf_version_str moveq #0,d0 (* assume no NatFeats available *) move.l d0,-(sp) lea @nf_illegal,a1 move.l $0010,a0 (* illegal instruction vector *) move.l a1,$0010 move.l sp,a1 (* save the ssp *) nop (* flush pipelines (for 68040+) *) dc.w NATFEAT_ID (* Jump to NATFEAT_ID *) tst.l d0 beq.s @nf_illegal moveq #1,d0 (* NatFeats detected *) move.l d0,(sp) @nf_illegal: move.l a1,sp move.l a0,$0010 nop (* flush pipelines (for 68040+) *) move.l (sp)+,d0 addq.l #4,sp (* pop nf_version argument *) {$ENDIF} end; {$ELSE} const nf_detect_opcodes: array[0..29] of word = ( $487a, $002e, (* pea.l nf_version_str(pc) *) $7000, (* moveq.l #0,d0 *) $2f00, (* move.l d0,-(a7) *) $43fa, $0018, (* lea.l $00000024(pc),a1 *) $2078, $0010, (* movea.l ($00000010).w,a0 *) $21c9, $0010, (* move.l a1,($00000010).w *) $224f, (* movea.l a7,a1 *) $4e71, (* nop *) $7300, (* nf_id *) $4a80, (* tst.l d0 *) $6704, (* beq.s $00000024 *) $7001, (* moveq.l #1,d0 *) $2e80, (* move.l d0,(a7) *) $2e49, (* movea.l a1,a7 *) $21c8, $0010, (* move.l a0,($00000010).w *) $4e71, (* nop *) $201f, (* move.l (a7)+,d0 *) $588f, (* addq.l #4,a7 *) $4e75, (* rts *) $4e46, $5f56, $4552, $5349, $4f4e, $0000 ); {$ENDIF} function nf_init: boolean; var ret: longint; begin if not nf_inited then begin {$IFDEF FPC} ret := xbios_supexec(@nf_detect); {$ELSE} ret := supexec(LongIntFunc(@nf_detect_opcodes)); {$ENDIF} nf_available := ret <> 0; nf_inited := true; cnf_call := Tnf_call(@nf_call_opcodes); end; nf_init := nf_available; end; function nf_get_id(feature_name: pchar): longint; begin nf_get_id := 0; if nf_init then nf_get_id := nf_id(feature_name); end; function nf_version: longint; var id: longint; begin nf_version := 0; id := nf_get_id(NF_ID_VERSION); if id <> 0 then {$IFDEF HAVE_CDECL} nf_version := cnf_call(id); {$ELSE} nf_version := cnf_call(nil,nil,0,0,0, id, nil, 0); {$ENDIF} end; procedure nf_get_name(buf: Pchar; bufsize: longint); var id: longint; begin id := nf_get_id(NF_ID_NAME); if id <> 0 then {$IFDEF HAVE_CDECL} cnf_call(id or 0, buf, bufsize) {$ELSE} cnf_call(nil,nil,0,0,0, id or 0, buf, bufsize) {$ENDIF} else buf^ := #0; end; procedure nf_get_fullname(buf: Pchar; bufsize: longint); var id: longint; begin id := nf_get_id(NF_ID_NAME); if id <> 0 then {$IFDEF HAVE_CDECL} cnf_call(id or 1, buf, bufsize) {$ELSE} cnf_call(nil,nil,0,0,0, id or 1, buf, bufsize) {$ENDIF} else buf^ := #0; end; function nf_debug(const s: string): boolean; var ps: array[0..255] of char; begin {$IFDEF FPC} ps := s; {$ELSE} PascalToCstring(s, Addr(ps[0])); {$ENDIF} nf_debug := false; if nf_stderr = 0 then nf_stderr := nf_get_id(NF_ID_STDERR); if nf_stderr <> 0 then begin {$IFDEF FPC} cnf_call(nf_stderr, Addr(ps[0])); {$ELSE} cnf_call(nil,nil,0,0,0, nf_stderr, Addr(ps[0]), 0); {$ENDIF} nf_debug := true; end; end; function nf_shutdown(mode: integer): longint; var id: longint; begin nf_shutdown := 0; id := nf_get_id(NF_ID_SHUTDOWN); if id <> 0 then {$IFDEF HAVE_CDECL} nf_shutdown := cnf_call(id or mode); {$ELSE} nf_shutdown := cnf_call(nil,nil,0,0,0, id or mode, nil, 0); {$ENDIF} end; function nf_exit(exitcode: integer): longint; var id: longint; begin nf_exit := 0; id := nf_get_id(NF_ID_EXIT); if id <> 0 then {$IFDEF HAVE_CDECL} nf_exit := cnf_call(id or 0, longint(exitcode)); {$ELSE} nf_exit := cnf_call(nil,nil,0,0,0, id or 0, pointer(longint(exitcode)), 0); {$ENDIF} end; begin end.
unit uFrmAdvertisingConfig; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Menus, Mask, DBCtrls, cxDBEdit, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxImageComboBox, cxSpinEdit, cxCalendar, CheckLst, cxCheckBox, siComp; type TFrmAdvertisingConfig = class(TForm) pnlButtons: TPanel; btnClose: TBitBtn; pnlFilter: TPanel; grdAdvertisingDB: TcxGridDBTableView; grdAdvertisingLevel1: TcxGridLevel; grdAdvertising: TcxGrid; dsAdvertising: TDataSource; grdAdvertisingDBDescription: TcxGridDBColumn; grdAdvertisingDBFileName: TcxGridDBColumn; grdAdvertisingDBStartDate: TcxGridDBColumn; grdAdvertisingDBEndDate: TcxGridDBColumn; grdAdvertisingDBDaysOfWeekString: TcxGridDBColumn; grdAdvertisingDBDuration: TcxGridDBColumn; Button1: TButton; OP: TOpenDialog; grdAdvertisingDBTypeString: TcxGridDBColumn; dtStart: TcxDateEdit; Label10: TLabel; Label11: TLabel; dtEnd: TcxDateEdit; cbxAdType: TcxComboBox; Label12: TLabel; grdAdvertisingDBDisplayDescription: TcxGridDBColumn; siLang: TsiLang; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCloseClick(Sender: TObject); procedure Button1Click(Sender: TObject); private FResult : Boolean; public function Start : Boolean; end; implementation uses uDM, DBClient, uDMGlobal; {$R *.dfm} { TFrmAdvertisingConfig } function TFrmAdvertisingConfig.Start: Boolean; begin FResult := False; ShowModal; Result := FResult; end; procedure TFrmAdvertisingConfig.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmAdvertisingConfig.btnCloseClick(Sender: TObject); begin FResult := False; Close; end; procedure TFrmAdvertisingConfig.Button1Click(Sender: TObject); var AFilter : String; begin if dtStart.Text <> '' then AFilter := 'StartDate >= ' + QuotedStr(FormatDateTime('ddddd', dtStart.Date)); if dtEnd.Text <> '' then if AFilter = '' then AFilter := 'EndDate < ' + QuotedStr(FormatDateTime('ddddd', dtEnd.Date + 1)) else AFilter := AFilter + ' AND EndDate < ' + QuotedStr(FormatDateTime('ddddd', dtEnd.Date + 1)); if cbxAdType.Text <> '' then if AFilter = '' then AFilter := 'Type = ' + IntToStr(cbxAdType.ItemIndex) else AFilter := AFilter + ' AND Type = ' + IntToStr(cbxAdType.ItemIndex); with DM.cdsAdvertising do begin Filtered := False; Filter := AFilter; Filtered := True; end; end; end.
unit uSystemTypes; interface type TCaixa = array[0..12] of Integer; TCaixaPotencia = array[0..12] of Double; TBtnCommandType = (btInc, btAlt, btExc, btPos, btFlt, btImp, btRest, btAgrupa, btSelCol, btRodape, btGrade); TDesativadoState = (STD_DESATIVADO, STD_NAODESATIVADO, STD_AMBOSDESATIVADO); TOrderByState = (STD_ORDER_ASC, STD_ORDER_DESC); THiddenState = (STD_HIDDEN, STD_NAOHIDDEN, STD_AMBOSHIDDEN); TSetCommandType = set of TBtnCommandType; const aCaixaPotencia : TCaixaPotencia = ( 100, 50, 20, 10, 5, 2, 1, 1, 0.5, 0.25, 0.1, 0.05, 0.01 ); BT_FLT = 0; BT_INC = 1; BT_ALT = 2; BT_EXC = 3; BT_CON = 4; BT_POS = 5; BT_IMP = 6; BT_REF = 7; implementation end.
{----------------------------------------------------------------------------- Unit Name: frmBreakPoints Author: Kiriakos Vlahos Purpose: Breakpoints Window History: -----------------------------------------------------------------------------} unit frmBreakPoints; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, JvDockControlForm, JvComponent, frmIDEDockWin, ExtCtrls, Contnrs, TB2Item, Menus, TBX, TBXThemes, VirtualTrees, JvComponentBase; type TBreakPointsWindow = class(TIDEDockWindow) TBXPopupMenu: TTBXPopupMenu; mnClear: TTBXItem; Breakpoints1: TTBXItem; BreakPointsView: TVirtualStringTree; mnSetCondition: TTBXItem; TBXSeparatorItem1: TTBXSeparatorItem; TBXSeparatorItem2: TTBXSeparatorItem; mnCopyToClipboard: TTBXItem; procedure TBXPopupMenuPopup(Sender: TObject); procedure mnCopyToClipboardClick(Sender: TObject); procedure mnSetConditionClick(Sender: TObject); procedure BreakPointsViewChecked(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure BreakPointLVDblClick(Sender: TObject); procedure mnClearClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BreakPointsViewInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure BreakPointsViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); private { Private declarations } fBreakPointsList : TObjectList; protected procedure TBMThemeChange(var Message: TMessage); message TBM_THEMECHANGE; public { Public declarations } procedure UpdateWindow; end; var BreakPointsWindow: TBreakPointsWindow; implementation uses frmPyIDEMain, uEditAppIntfs, dmCommands, uCommonFunctions, Clipbrd, JvDockGlobals; {$R *.dfm} Type TBreakPointInfo = class FileName : string; Line : integer; Disabled : Boolean; Condition : string; end; PBreakPointRec = ^TBreakPointRec; TBreakPointRec = record BreakPoint : TBreakPointInfo; end; procedure TBreakPointsWindow.UpdateWindow; Var i, j : integer; BL : TList; BreakPoint : TBreakPointInfo; begin BreakPointsView.Clear; fBreakPointsList.Clear; for i := 0 to GI_EditorFactory.Count - 1 do begin BL := GI_EditorFactory.Editor[i].BreakPoints; for j := 0 to BL.Count -1 do begin BreakPoint := TBreakPointInfo.Create; BreakPoint.FileName := GI_EditorFactory.Editor[i].GetFileNameOrTitle; BreakPoint.Line := TBreakPoint(BL[j]).LineNo; BreakPoint.Disabled := TBreakPoint(BL[j]).Disabled; BreakPoint.Condition := TBreakPoint(BL[j]).Condition; fBreakPointsList.Add(BreakPoint); end; end; BreakPointsView.RootNodeCount := fBreakPointsList.Count; end; procedure TBreakPointsWindow.BreakPointLVDblClick(Sender: TObject); Var Node : PVirtualNode; BreakPoint : TBreakPointInfo; begin Node := BreakPointsView.GetFirstSelected(); if Assigned(Node) then begin BreakPoint := PBreakPointRec(BreakPointsView.GetNodeData(Node))^.BreakPoint; if (BreakPoint.FileName ='') then Exit; // No FileName or LineNumber PyIDEMainForm.ShowFilePosition(BreakPoint.FileName, BreakPoint.Line, 1); end; end; procedure TBreakPointsWindow.mnClearClick(Sender: TObject); Var Editor : IEditor; Node : PVirtualNode; begin Node := BreakPointsView.GetFirstSelected(); if Assigned(Node) then with PBreakPointRec(BreakPointsView.GetNodeData(Node))^.BreakPoint do begin if FileName = '' then Exit; // No FileName or LineNumber Editor := GI_EditorFactory.GetEditorByNameOrTitle(FileName); if Assigned(Editor) then PyIDEMainForm.PyDebugger.ToggleBreakpoint(Editor, Line); end; end; procedure TBreakPointsWindow.mnSetConditionClick(Sender: TObject); Var Editor : IEditor; Node : PVirtualNode; begin Node := BreakPointsView.GetFirstSelected(); if Assigned(Node) then with PBreakPointRec(BreakPointsView.GetNodeData(Node))^.BreakPoint do begin if FileName = '' then Exit; // No FileName or LineNumber Editor := GI_EditorFactory.GetEditorByNameOrTitle(FileName); if Assigned(Editor) then begin if InputQuery('Edit Breakpoint Condition', 'Enter Python expression:', Condition) then PyIDEMainForm.PyDebugger.SetBreakPoint(FileName, Line, Disabled, Condition); end; end; end; procedure TBreakPointsWindow.mnCopyToClipboardClick(Sender: TObject); begin Clipboard.AsText := BreakPointsView.ContentToText(tstAll, #9); end; procedure TBreakPointsWindow.FormActivate(Sender: TObject); begin inherited; if not HasFocus then begin FGPanelEnter(Self); PostMessage(BreakPointsView.Handle, WM_SETFOCUS, 0, 0); end; end; procedure TBreakPointsWindow.FormCreate(Sender: TObject); begin inherited; fBreakPointsList := TObjectList.Create(True); // Onwns objects // Let the tree know how much data space we need. BreakPointsView.NodeDataSize := SizeOf(TBreakPointRec); BreakPointsView.OnAdvancedHeaderDraw := CommandsDataModule.VirtualStringTreeAdvancedHeaderDraw; BreakPointsView.OnHeaderDrawQueryElements := CommandsDataModule.VirtualStringTreeDrawQueryElements; end; procedure TBreakPointsWindow.FormDestroy(Sender: TObject); begin fBreakPointsList.Free; inherited; end; procedure TBreakPointsWindow.TBMThemeChange(var Message: TMessage); begin inherited; if Message.WParam = TSC_VIEWCHANGE then begin BreakPointsView.Header.Invalidate(nil, True); BreakPointsView.Colors.HeaderHotColor := CurrentTheme.GetItemTextColor(GetItemInfo('active')); end; end; procedure TBreakPointsWindow.BreakPointsViewInitNode( Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); begin Assert(BreakPointsView.GetNodeLevel(Node) = 0); Assert(Integer(Node.Index) < fBreakPointsList.Count); PBreakPointRec(BreakPointsView.GetNodeData(Node))^.BreakPoint := fBreakPointsList[Node.Index] as TBreakPointInfo; Node.CheckType := ctCheckBox; if TBreakPointInfo(fBreakPointsList[Node.Index]).Disabled then Node.CheckState := csUnCheckedNormal else Node.CheckState := csCheckedNormal; end; procedure TBreakPointsWindow.BreakPointsViewGetText( Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); begin Assert(BreakPointsView.GetNodeLevel(Node) = 0); Assert(Integer(Node.Index) < fBreakPointsList.Count); with PBreakPointRec(BreakPointsView.GetNodeData(Node))^.BreakPoint do case Column of 0: CellText := FileName; 1: if Line > 0 then CellText := IntToStr(Line) else CellText := ''; 2: CellText := Condition; end; end; procedure TBreakPointsWindow.BreakPointsViewChecked(Sender: TBaseVirtualTree; Node: PVirtualNode); begin with PBreakPointRec(BreakPointsView.GetNodeData(Node))^.BreakPoint do begin if Node.CheckState = csCheckedNormal then Disabled := False else Disabled := True; PyIDEMainForm.PyDebugger.SetBreakPoint(FileName, Line, Disabled, Condition); end; end; procedure TBreakPointsWindow.TBXPopupMenuPopup(Sender: TObject); begin mnClear.Enabled := Assigned(BreakPointsView.GetFirstSelected()); mnSetCondition.Enabled := Assigned(BreakPointsView.GetFirstSelected()); mnCopyToClipboard.Enabled := fBreakPointsList.Count > 0; end; end.
unit HCEmrViewIH; interface {$I HCEmrView.inc} uses Windows, Classes, SysUtils, Messages, Imm, {$IFDEF VIEWTOOL}HCViewTool{$ELSE}HCView{$ENDIF}, HCCallBackMethod, frm_InputHelper, HCCustomData, HCItem, HCStyle, HCRectItem; type THCEmrViewIH = class({$IFDEF VIEWTOOL}THCViewTool{$ELSE}THCView{$ENDIF}) private FInputHelper: TfrmInputHelper; {$IFDEF GLOBALSHORTKEY} // 全局alt + space显示辅助输入窗体 FPProc: Pointer; /// <summary> 低级键盘钩子的回调函数,在里面过滤消息 </summary> /// <param name="nCode">Hook的标志</param> /// <param name="wParam">表示消息的类型</param> /// <param name="lParam">指向KBDLLHOOKSTRUCT结构的指针</param> /// <returns>如果不为0,Windows丢掉这个消息程序不会再收到这个消息</returns> function KeyboardProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; procedure SetIHKeyHook; // 设置低级键盘钩子 procedure UnSetIHKeyHook; // 卸载低级键盘钩子 {$ENDIF} function GetInputHelpEnable: Boolean; procedure SetInputHelpEnable(const Value: Boolean); protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; /// <summary> 是否上屏输入法输入的词条屏词条ID和词条 </summary> function DoProcessIMECandi(const ACandi: string): Boolean; virtual; procedure WMImeNotify(var Message: TMessage); message WM_IME_NOTIFY; procedure UpdateImeComposition(const ALParam: Integer); override; procedure UpdateImePosition; override; // IME 通知输入法更新位置 /// <summary> 光标移动后取光标前后文本 </summary> procedure DoCaretChange; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function PreProcessMessage(var Msg: TMsg): Boolean; override; property InputHelpEnable: Boolean read GetInputHelpEnable write SetInputHelpEnable; end; implementation const CARETSTOPCHAR = ',,。;;::'; {$IFDEF GLOBALSHORTKEY} WH_KEYBOARD_LL = 13; // //低级键盘钩子的索引值 LLKHF_ALTDOWN = $20; type tagKBDLLHOOKSTRUCT = packed record // 在Windows NT 4 sp3以上系统中才能使用 vkCode: DWORD;//虚拟键值 scanCode: DWORD;//扫描码值(没有用过,我也不懂^_^) {一些扩展标志,这个标志值的第六位数(二进制)为1时ALT键按下为0相反。} flags: DWORD; time: DWORD;//消息时间戳 dwExtraInfo: DWORD;//和消息相关的扩展信息 end; KBDLLHOOKSTRUCT = tagKBDLLHOOKSTRUCT; PKBDLLHOOKSTRUCT = ^KBDLLHOOKSTRUCT; var HHKLowLevelKybd: HHOOK; {$ENDIF} { THCEmrViewIH } constructor THCEmrViewIH.Create(AOwner: TComponent); {$IFDEF GLOBALSHORTKEY} var vM: TMethod; {$ENDIF} begin inherited Create(AOwner); {$IFDEF GLOBALSHORTKEY} vM.Code := @THCEmrViewIH.KeyboardProc; vM.Data := Self; FPProc := HCMakeInstruction(vM); SetIHKeyHook; // 调试时可关掉提升效率 {$ENDIF} FInputHelper := TfrmInputHelper.Create(nil); end; destructor THCEmrViewIH.Destroy; begin FreeAndNil(FInputHelper); {$IFDEF GLOBALSHORTKEY} UnSetIHKeyHook; // 调试时可关掉提升效率 HCFreeInstruction(FPProc); {$ENDIF} inherited Destroy; end; procedure THCEmrViewIH.DoCaretChange; {$REGION '取光标前后字符串'} function GetCharBefor(const AOffset: Integer; var AChars: string): Boolean; var i: Integer; begin Result := False; for i := AOffset downto 1 do begin if Pos(AChars[i], CARETSTOPCHAR) > 0 then begin AChars := System.Copy(AChars, i + 1, AOffset - i); Result := True; Break; end; end; end; procedure GetBeforString(const AData: THCCustomData; const AStartItemNo: Integer; var ABefor: string); var i: Integer; vText: string; begin for i := AStartItemNo - 1 downto 0 do // 向前 begin vText := AData.Items[i].Text; if (vText <> '') and GetCharBefor(Length(vText), vText) then begin ABefor := vText + ABefor; Break; end else ABefor := vText + ABefor; end; end; function GetCharAfter(const AOffset: Integer; var AChars: string): Boolean; var i: Integer; begin Result := False; for i := AOffset to Length(AChars) do begin if Pos(AChars[i], CARETSTOPCHAR) > 0 then begin AChars := System.Copy(AChars, AOffset, i - AOffset); Result := True; Break; end; end; end; procedure GetAfterString(const AData: THCCustomData; const AStartItemNo: Integer; var AAfter: string); var i: Integer; vText: string; begin for i := AStartItemNo + 1 to AData.Items.Count - 1 do // 向前 begin vText := AData.Items[i].Text; if (vText <> '') and GetCharAfter(1, vText) then begin AAfter := AAfter + vText; Break; end else AAfter := AAfter + vText; end; end; {$ENDREGION} var vTopData: THCCustomData; vCurItemNo: Integer; vCurItem: THCCustomItem; vText, vsBefor, vsAfter: string; begin inherited DoCaretChange; if not FInputHelper.EnableEx then Exit; if not Self.Style.UpdateInfo.ReStyle then Exit; vsBefor := ''; vsAfter := ''; vTopData := Self.ActiveSectionTopLevelData; vCurItemNo := vTopData.SelectInfo.StartItemNo; vCurItem := vTopData.GetActiveItem; if vCurItem.StyleNo < THCStyle.Null then // 光标在RectItem begin if vTopData.SelectInfo.StartItemOffset = OffsetBefor then // 光标在前 GetBeforString(vTopData, vCurItemNo - 1, vsBefor) else // 光标在后 GetAfterString(vTopData, vCurItemNo + 1, vsAfter); end else // 文本 begin // 取光标前 vText := vCurItem.Text; if GetCharBefor(vTopData.SelectInfo.StartItemOffset, vText) then // 从当前位置往前 vsBefor := vText else // 当前没取到 begin vsBefor := System.Copy(vText, 1, vTopData.SelectInfo.StartItemOffset); GetBeforString(vTopData, vCurItemNo - 1, vsBefor); end; // 取光标后 vText := vCurItem.Text; if GetCharAfter(vTopData.SelectInfo.StartItemOffset + 1, vText) then // 从当前位置往后 vsAfter := vText else // 当前没取到 begin vsAfter := System.Copy(vText, vTopData.SelectInfo.StartItemOffset + 1, Length(vText) - vTopData.SelectInfo.StartItemOffset); GetAfterString(vTopData, vCurItemNo + 1, vsAfter); end; end; FInputHelper.SetCaretString(vsBefor, vsAfter); end; function THCEmrViewIH.DoProcessIMECandi(const ACandi: string): Boolean; begin Result := True; end; function THCEmrViewIH.GetInputHelpEnable: Boolean; begin Result := FInputHelper.EnableEx; end; {$IFDEF GLOBALSHORTKEY} function THCEmrViewIH.KeyboardProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; var vEatKeystroke: Boolean; vPKB: PKBDLLHOOKSTRUCT; begin Result := 0; vEatKeystroke := False; if nCode = HC_ACTION then // 表示WParam和LParam参数包涵了按键消息 begin case WParam of WM_SYSKEYDOWN, WM_SYSKEYUP: begin vPKB := PKBDLLHOOKSTRUCT(LParam); if vPKB.flags = LLKHF_ALTDOWN then begin if vPKB.vkCode = VK_SPACE then begin FInputHelper.ShowEx; vEatKeystroke := True; end; end; end; //WM_SYSKEYDOWN, //WM_KEYDOWN, //WM_KEYUP: ; //vEatKeystroke := ((vPKB.vkCode = VK_SPACE) and ((vPKB.flags and LLKHF_ALTDOWN) <> 0)); //(p.vkCode = VK_RWIN) or (p.vkCode = VK_LWIN) //or ((p.vkCode = VK_TAB) and ((p.flags and LLKHF_ALTDOWN) <> 0)) //or ((p.vkCode = VK_ESCAPE) and ((GetKeyState(VK_CONTROL) and $8000) <> 0)); end; end; if vEatKeystroke then Result := 1 else if nCode <> 0 then Result := CallNextHookEx(0, nCode, WPARAM, LParam); end; procedure THCEmrViewIH.SetIHKeyHook; begin if HHKLowLevelKybd = 0 then // 没设置过 begin HHKLowLevelKybd := SetWindowsHookExW(WH_KEYBOARD_LL, FPProc, Hinstance, 0); if HHKLowLevelKybd = 0 then MessageBox(Handle, 'HCView辅助输入快捷键设置失败!', '提示', MB_OK); end; end; procedure THCEmrViewIH.UnSetIHKeyHook; begin if HHKLowLevelKybd <> 0 then begin if UnhookWindowsHookEx(HHKLowLevelKybd) then // 卸载成功 HHKLowLevelKybd := 0; end; end; {$ENDIF} procedure THCEmrViewIH.KeyDown(var Key: Word; Shift: TShiftState); function IsImeExtShow: Boolean; begin Result := (Shift = [ssCtrl{, ssAlt}]) and (Key = Ord('H')); // ctrl + h主动弹出 end; function IsImeExtClose: Boolean; begin Result := (Shift = []) and (Key = VK_ESCAPE); end; begin if (not ReadOnly) and FInputHelper.EnableEx and IsImeExtShow then FInputHelper.ShowEx else if (not ReadOnly) and FInputHelper.EnableEx and IsImeExtClose then FInputHelper.CloseEx else inherited KeyDown(Key, Shift); end; function THCEmrViewIH.PreProcessMessage(var Msg: TMsg): Boolean; var vVirtualKey: Cardinal; vText: string; begin if (FInputHelper.VisibleEx) and (Msg.message = WM_KEYDOWN) and (Msg.wParam = VK_PROCESSKEY) then // 输入法转换的键 begin //Msg.WParam := ImmGetVirtualKey(Msg.hwnd); // 原样返回按啥显示啥 vVirtualKey := ImmGetVirtualKey(Msg.hwnd); if vVirtualKey - 127 = 59 then // ; 需要设置输入法;号的功能,如二三候选 begin FInputHelper.ActiveEx := not FInputHelper.ActiveEx; Result := True; Exit; end else if FInputHelper.ActiveEx and (vVirtualKey in [32, 49..57]) then // 空格, 1..9 begin keybd_event(VK_ESCAPE, 0, 0, 0); keybd_event(VK_ESCAPE, 0, KEYEVENTF_KEYUP, 0); if vVirtualKey = 32 then vVirtualKey := 49; vText := FInputHelper.GetCandiText(vVirtualKey - 49); Self.InsertText(vText); Result := True; Exit; end; end; Result := inherited PreProcessMessage(Msg); end; procedure THCEmrViewIH.SetInputHelpEnable(const Value: Boolean); begin FInputHelper.EnableEx := Value; end; procedure THCEmrViewIH.UpdateImeComposition(const ALParam: Integer); function GetCompositionStr(const AhImc: HIMC; const AType: Cardinal): string; var vSize: Integer; vBuffer: TBytes; begin Result := ''; if AhImc <> 0 then begin vSize := ImmGetCompositionString(AhImc, AType, nil, 0); // 获取IME结果字符串的大小 if vSize > 0 then // 如果IME结果字符串不为空,且没有错误 begin // 取出字符串 SetLength(vBuffer, vSize); ImmGetCompositionString(AhImc, AType, vBuffer, vSize); Result := WideStringOf(vBuffer); end; end; end; var vhIMC: HIMC; vS: string; vCF: TCompositionForm; begin vhIMC := ImmGetContext(Handle); if vhIMC <> 0 then begin try if FInputHelper.EnableEx and ((ALParam and GCS_COMPSTR) <> 0) then // 输入内容有变化 begin vS := GetCompositionStr(vhIMC, GCS_COMPSTR); FInputHelper.SetCompositionString(vS); if FInputHelper.SizeChange then // 知识输入法窗体大小有变化时重新处理输入法窗体位置 begin if ImmGetCompositionWindow(vhIMC, @vCF) then begin if FInputHelper.ResetImeCompRect(vCF.ptCurrentPos) then ImmSetCompositionWindow(vhIMC, @vCF); end; end; end; if (ALParam and GCS_RESULTSTR) <> 0 then // 通知检索或更新上屏字符串 begin // 处理上屏文本一次性插入,否则会不停的触发KeyPress事件 vS := GetCompositionStr(vhIMC, GCS_RESULTSTR); if vS <> '' then begin if DoProcessIMECandi(vS) then InsertText(vS); end; end finally ImmReleaseContext(Handle, vhIMC); end; end; end; procedure THCEmrViewIH.UpdateImePosition; var vhIMC: HIMC; vCF: TCompositionForm; begin vhIMC := ImmGetContext(Handle); try // 告诉输入法当前光标位置信息 vCF.ptCurrentPos := Point(Caret.X, Caret.Y + Caret.Height + 4); // 输入法弹出窗体位置 if FInputHelper.EnableEx then FInputHelper.ResetImeCompRect(vCF.ptCurrentPos); vCF.dwStyle := CFS_FORCE_POSITION; // 强制按我的位置 CFS_RECT vCF.rcArea := ClientRect; ImmSetCompositionWindow(vhIMC, @vCF); if FInputHelper.EnableEx then begin //ImmGetCompositionWindow() 输入法窗体可能会适配桌面区域,所以要重新计算位置 FInputHelper.CompWndMove(Self.Handle, Caret.X, Caret.Y + Caret.Height); end; finally ImmReleaseContext(Handle, vhIMC); end; end; procedure THCEmrViewIH.WMImeNotify(var Message: TMessage); begin inherited; if FInputHelper.EnableEx then begin case Message.WParam of {IMN_OPENSTATUSWINDOW: // 打开输入法 FImeExt.ImeOpen := True; IMN_CLOSESTATUSWINDOW: // 关闭了输入法 FImeExt.ImeOpen := False; } IMN_SETCOMPOSITIONWINDOW, // 输入法输入窗体位置变化 IMN_CLOSECANDIDATE: // 关了备选 FInputHelper.CompWndMove(Self.Handle, Caret.X, Caret.Y + Caret.Height); end; end; end; procedure THCEmrViewIH.WMKillFocus(var Message: TWMKillFocus); begin inherited; if Assigned(FInputHelper) and FInputHelper.EnableEx then FInputHelper.Close; end; end.
unit frmRepairReason; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, StdCtrls, ComCtrls, Buttons, DBClient, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ExtCtrls; type TRepairReasonFrm = class(TForm) Panel1: TPanel; GroupBox1: TGroupBox; Panel2: TPanel; btnAdd: TSpeedButton; btnEdit: TSpeedButton; btnDelete: TSpeedButton; btnSave: TSpeedButton; edtReasonCode: TEdit; cbReasonType: TComboBox; edtReasonInfo: TEdit; cbOperationCode: TComboBox; cbQualityType: TComboBox; moRemark: TMemo; chbIsActive: TCheckBox; GroupBox2: TGroupBox; lvDetail: TListView; sbAdd: TSpeedButton; sbEdit: TSpeedButton; sbDelete: TSpeedButton; sbSave: TSpeedButton; edtItemName: TEdit; edtItemValue: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; gbOperation: TGroupBox; lbOperation: TListBox; btnMoveUpOperation: TSpeedButton; btnMoveDownOperation: TSpeedButton; btnDelOperation: TSpeedButton; btnAddOperation: TSpeedButton; cbbOperation: TComboBox; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; sbPreview: TSpeedButton; lvMaster: TListView; edtDepartment: TComboBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnAddOperationClick(Sender: TObject); procedure btnDelOperationClick(Sender: TObject); procedure btnMoveUpOperationClick(Sender: TObject); procedure btnMoveDownOperationClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure sbAddClick(Sender: TObject); procedure sbEditClick(Sender: TObject); procedure sbDeleteClick(Sender: TObject); procedure sbSaveClick(Sender: TObject); procedure lbOperationDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure sbPreviewClick(Sender: TObject); procedure cbbOperationKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lvMasterChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure lvDetailChange(Sender: TObject; Item: TListItem; Change: TItemChange); private AddNew: string; DumbList: TStringList; Max_Reason_Code: string; { Private declarations } public { Public declarations } end; var RepairReasonFrm: TRepairReasonFrm; implementation uses cxDropDownEdit, uDictionary, ServerDllPub, uGlobal, uLogin, UGridDecorator, uShowMessage, uFNMArtInfo, StrUtils; {$R *.dfm} procedure TRepairReasonFrm.FormCreate(Sender: TObject); begin cbbOperation.Align := alClient; DumbList := TStringList.Create; Max_Reason_Code := ''; FillItemsFromDataSet(Dictionary.cds_RepairReasonList, 'Reason_Type', '', '','', cbReasonType.Items); FillItemsFromDataSet(Dictionary.cds_RepairReasonList, 'Quality_Type', '', '','', cbQualityType.Items); FillItemsFromDataSet(Dictionary.cds_OperationHdrList, 'Operation_Code', 'Operation_CHN', 'Operation_Code','->', cbOperationCode.Items); cbbOperation.Items := cbOperationCode.Items; cbbOperation.OnDblClick := TGlobal.DblClickAWinControl; with Dictionary.cds_RepairReasonList do begin Filtered := False; First; while not Eof do begin if DumbList.IndexOf(FieldByName('Reason_Code').AsString) > -1 then begin Next; Continue; end; DumbList.Add(FieldByName('Reason_Code').AsString); with lvMaster.Items.Add do begin if Max_Reason_Code < FieldByName('Reason_Code').AsString then Max_Reason_Code := FieldByName('Reason_Code').AsString; Caption := FieldByName('Reason_Code').AsString; SubItems.Add(FieldByName('Reason_Type').AsString); SubItems.Add(FieldByName('Reason_Info').AsString); SubItems.Add(FieldByName('Quality_Type').AsString); SubItems.Add(FieldByName('Department').AsString); SubItems.Add(FieldByName('Quality_Operation').AsString); SubItems.Add(FieldByName('Remark').AsString); SubItems.Add(FieldByName('Is_Active').AsString); SubItems.Add(FieldByName('Repair_Operation').AsString); end; Next; end; end; edtReasonCode.Enabled := False; cbReasonType.Enabled := False; edtReasonInfo.Enabled := False; cbQualityType.Enabled := False; edtDepartment.Enabled := False; cbOperationCode.Enabled := False; moRemark.Enabled := False; chbIsActive.Enabled := False; gbOperation.Enabled := False; btnSave.Enabled := False; edtItemName.Enabled := False; edtItemValue.Enabled := False; sbSave.Enabled := False; end; procedure TRepairReasonFrm.FormDestroy(Sender: TObject); begin DumbList.Free; RepairReasonFrm := nil; end; procedure TRepairReasonFrm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TRepairReasonFrm.btnAddOperationClick(Sender: TObject); begin if cbbOperation.Text = '' then Exit; with lbOperation do begin if ItemIndex <> -1 then Items.Insert(ItemIndex+1,cbbOperation.Text) else Items.Add(cbbOperation.Text); cbbOperation.ItemIndex := -1; end; end; procedure TRepairReasonFrm.btnDelOperationClick(Sender: TObject); begin with lbOperation do if ItemIndex <> -1 then DeleteSelected; end; procedure TRepairReasonFrm.btnMoveUpOperationClick(Sender: TObject); begin with lbOperation do begin if ItemIndex = 0 then Exit; if ItemIndex <> -1 then Items.Exchange(ItemIndex,ItemIndex -1); end; end; procedure TRepairReasonFrm.btnMoveDownOperationClick(Sender: TObject); begin with lbOperation do begin if ItemIndex = Items.Count - 1 then Exit; if ItemIndex <> -1 then Items.Exchange(ItemIndex,ItemIndex +1); end; end; procedure TRepairReasonFrm.btnAddClick(Sender: TObject); begin lbOperation.Items.Clear; edtReasonCode.Text := ''; cbReasonType.Text := ''; edtReasonInfo.Text := ''; cbQualityType.Text := ''; edtDepartment.Text := ''; cbOperationCode.Text := ''; moRemark.Text := ''; chbIsActive.Checked := True; gbOperation.Enabled := btnAdd.Caption = '新增'; edtReasonCode.Enabled := btnAdd.Caption = '新增'; cbReasonType.Enabled := btnAdd.Caption = '新增'; edtReasonInfo.Enabled := btnAdd.Caption = '新增'; cbQualityType.Enabled := btnAdd.Caption = '新增'; edtDepartment.Enabled := btnAdd.Caption = '新增'; cbOperationCode.Enabled := btnAdd.Caption = '新增'; moRemark.Enabled := btnAdd.Caption = '新增'; chbIsActive.Enabled := btnAdd.Caption = '新增'; lvMaster.Enabled := btnAdd.Caption = '放弃'; btnEdit.Enabled := btnAdd.Caption = '放弃'; btnDelete.Enabled := btnAdd.Caption = '放弃'; btnSave.Enabled := btnAdd.Caption = '新增';; if btnAdd.Caption = '放弃' then btnAdd.Caption := '新增' else btnAdd.Caption := '放弃'; end; procedure TRepairReasonFrm.btnEditClick(Sender: TObject); begin edtReasonCode.Enabled := False; cbReasonType.Enabled := btnEdit.Caption = '编辑'; edtReasonInfo.Enabled := btnEdit.Caption = '编辑'; cbQualityType.Enabled := btnEdit.Caption = '编辑'; edtDepartment.Enabled := btnEdit.Caption = '编辑'; cbOperationCode.Enabled := btnEdit.Caption = '编辑'; moRemark.Enabled := btnEdit.Caption = '编辑'; chbIsActive.Enabled := btnEdit.Caption = '编辑'; gbOperation.Enabled := btnEdit.Caption = '编辑'; lvMaster.Enabled := btnEdit.Caption = '放弃'; btnAdd.Enabled := btnEdit.Caption = '放弃'; btnDelete.Enabled := btnEdit.Caption = '放弃'; btnSave.Enabled := btnEdit.Caption = '编辑'; if btnEdit.Caption = '放弃' then btnEdit.Caption := '编辑' else btnEdit.Caption := '放弃'; end; procedure TRepairReasonFrm.btnDeleteClick(Sender: TObject); var sErrorMsg: WideString; begin if edtReasonCode.Text = '' then exit; if MessageDlg('你确认要删除内回修记录吗?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then Exit; try TStatusBarMessage.ShowMessageOnMainStatsusBar('正在删除数据稍等!', crHourGlass); FNMServerObj.DeleteRepairReason(edtReasonCode.text,'',0,sErrorMsg); if sErrorMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; lvMaster.DeleteSelected; TMsgDialog.ShowMsgDialog('删除数据成功',mtInformation); finally TStatusBarMessage.ShowMessageOnMainStatsusBar('', crDefault); end; end; procedure TRepairReasonFrm.btnSaveClick(Sender: TObject); var vData: OleVariant; sErrorMsg: WideString; OperationList,IsActive: string; i, j: Integer; begin //Check Data if (cbReasonType.Text = '') or (edtReasonInfo.Text = '') or (cbQualityType.Text = '') or (cbQualityType.Text = '') then begin TMsgDialog.ShowMsgDialog('请输入回修类型,回修原因,类型,责任部门',mtError); Exit; end; if chbIsActive.Checked then IsActive := '1' else IsActive := '0'; OperationList := ''; for i := 0 to lbOperation.Items.Count - 1 do begin j := Pos('->', lbOperation.Items[i]); OperationList := OperationList + Copy(lbOperation.Items[i],j-3,3) + '/' ; end; if OperationList<>'' then OperationList := Copy(OperationList, 1, Length(OperationList)-1); vData := VarArrayCreate([0, 1], VarVariant); vData[0]:=varArrayOf([edtReasonCode.Text, cbReasonType.Text, edtReasonInfo.Text, Copy(cbOperationCode.Text,1,3), cbQualityType.Text, edtDepartment.Text, moRemark.Text, OperationList, IsActive, Login.LoginName]); FNMServerObj.SaveRepairReason(vData,0,sErrorMsg); if sErrorMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; if edtReasonCode.Text = '' then begin with lvMaster.Items.Add do begin Caption := 'FR' + RightStr('000'+IntToStr(StrToInt(Copy(Max_Reason_Code,3,3))+1),3); SubItems.Add(cbReasonType.Text); SubItems.Add(edtReasonInfo.Text); SubItems.Add(cbQualityType.Text); SubItems.Add(edtDepartment.Text); SubItems.Add(cbOperationCode.Text); SubItems.Add(moRemark.Text); if chbIsActive.Checked then SubItems.Add('True') else SubItems.Add('False'); SubItems.Add(OperationList); end; end else begin with lvMaster.Selected do begin SubItems[0] := cbReasonType.Text; SubItems[1] := edtReasonInfo.Text; SubItems[2] := cbQualityType.Text; SubItems[3] := edtDepartment.Text; SubItems[4] := cbOperationCode.Text; SubItems[5] := moRemark.Text; if chbIsActive.Checked then SubItems[6] := 'True' else SubItems[6] := 'False'; SubItems[7] := OperationList; end; end; edtReasonCode.Text := 'FR' + RightStr('000'+IntToStr(StrToInt(Copy(Max_Reason_Code,3,3))+1),3); edtReasonCode.Enabled := False; cbReasonType.Enabled := False; edtReasonInfo.Enabled := False; cbQualityType.Enabled := False; edtDepartment.Enabled := False; cbOperationCode.Enabled := False; moRemark.Enabled := False; chbIsActive.Enabled := False; gbOperation.Enabled := False ; lvMaster.Enabled := True; btnAdd.Caption := '新增'; btnAdd.Enabled := True; btnEdit.Caption := '编辑'; btnEdit.Enabled := True; btnDelete.Enabled := True; btnSave.Enabled := False; TMsgDialog.ShowMsgDialog('保存数据成功', mtInformation); end; procedure TRepairReasonFrm.sbAddClick(Sender: TObject); begin AddNew := '1'; edtItemName.Enabled := sbAdd.Caption = '新增'; edtItemValue.Enabled := sbAdd.Caption = '新增'; edtItemName.Clear; edtItemValue.Clear; lvDetail.Enabled := sbAdd.Caption = '放弃'; sbEdit.Enabled := sbAdd.Caption = '放弃'; sbDelete.Enabled := sbAdd.Caption = '放弃'; sbSave.Enabled := sbAdd.Caption = '新增'; if sbAdd.Caption = '放弃' then sbAdd.Caption := '新增' else sbAdd.Caption := '放弃'; end; procedure TRepairReasonFrm.sbEditClick(Sender: TObject); begin AddNew := '0'; edtItemName.Enabled := sbEdit.Caption = '编辑'; edtItemValue.Enabled := sbEdit.Caption = '编辑'; lvDetail.Enabled := sbEdit.Caption = '放弃'; sbAdd.Enabled := sbEdit.Caption = '放弃'; sbDelete.Enabled := sbEdit.Caption = '放弃'; sbSave.Enabled := sbEdit.Caption = '编辑'; if sbEdit.Caption = '放弃' then sbEdit.Caption := '编辑' else sbEdit.Caption := '放弃'; end; procedure TRepairReasonFrm.sbDeleteClick(Sender: TObject); var sErrorMsg: WideString; begin if lvDetail.SelCount = 0 then Exit; if MessageDlg('你确认要删除此条回修原因明细记录吗?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then Exit; try TStatusBarMessage.ShowMessageOnMainStatsusBar('正在删除数据稍等!', crHourGlass); FNMServerObj.DeleteRepairReason(edtItemName.Hint,edtItemName.Text,1,sErrorMsg); if sErrorMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; lvDetail.DeleteSelected; TMsgDialog.ShowMsgDialog('删除数据成功',mtInformation); finally TStatusBarMessage.ShowMessageOnMainStatsusBar('', crDefault); end; end; procedure TRepairReasonFrm.sbSaveClick(Sender: TObject); var vData: OleVariant; sErrorMsg: WideString; i: Integer; begin if edtItemName.Text = '' then Exit; //Check Data if (AddNew = '1') and (lvDetail.Items.Count > 0) then for i := 0 to lvDetail.Items.Count -1 do if lvDetail.Items[i].SubItems[0] = edtItemName.Text then Exit; vData := VarArrayCreate([0, 1], VarVariant); vData[0] := varArrayOf([AddNew, edtItemName.Hint, edtItemName.Text, edtItemValue.Text]); FNMServerObj.SaveRepairReason(vData,1,sErrorMsg); if sErrorMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg,mtError); Exit; end; if AddNew = '1' then begin with lvDetail.Items.Add do begin Caption := lvMaster.Selected.Caption; SubItems.Add(edtItemName.Text); SubItems.Add(edtItemValue.Text); end; end else begin with lvDetail.Selected do begin SubItems[0] := edtItemName.Text; SubItems[1] := edtItemValue.Text; end; end; edtItemName.Enabled := False; edtItemValue.Enabled := False; lvDetail.Enabled := True; sbAdd.Caption := '新增'; sbAdd.Enabled := True; sbEdit.Caption := '编辑'; sbEdit.Enabled := True; sbDelete.Enabled := True; sbSave.Enabled := False; TMsgDialog.ShowMsgDialog('保存数据成功', mtInformation); end; procedure TRepairReasonFrm.lbOperationDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin lbOperation.Canvas.TextOut(Rect.Left,Rect.Top,IntToStr(Index) + ') ' + lbOperation.Items[Index]); end; procedure TRepairReasonFrm.sbPreviewClick(Sender: TObject); begin ShowMessage(edtItemName.Text + ':' + #13+ '------------' + #13 + StringReplace(edtItemValue.Text,'/',#13,[rfReplaceAll])); end; procedure TRepairReasonFrm.cbbOperationKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: btnAddOperation.Click; end; end; procedure TRepairReasonFrm.lvMasterChange(Sender: TObject; Item: TListItem; Change: TItemChange); var i: Integer; begin edtReasonCode.Enabled := False; cbReasonType.Enabled := False; edtReasonInfo.Enabled := False; cbQualityType.Enabled := False; edtDepartment.Enabled := False; cbOperationCode.Enabled := False; moRemark.Enabled := False; chbIsActive.Enabled := False; gbOperation.Enabled := False; btnSave.Enabled := False; if lvMaster.ItemIndex = -1 then Exit; edtReasonCode.Text := lvMaster.Selected.Caption; cbReasonType.Text := lvMaster.Selected.SubItems[0]; edtReasonInfo.Text := lvMaster.Selected.SubItems[1]; cbQualityType.Text := lvMaster.Selected.SubItems[2]; edtDepartment.Text := lvMaster.Selected.SubItems[3]; cbOperationCode.Text := lvMaster.Selected.SubItems[4]; moRemark.Text := lvMaster.Selected.SubItems[5]; chbIsActive.Checked := lvMaster.Selected.SubItems[6] = 'True'; DumbList.Delimiter :='/'; DumbList.DelimitedText := lvMaster.Selected.SubItems[7]; lbOperation.Items.Clear; Dictionary.cds_OperationHdrList.Filtered := False; for i := 0 to DumbList.Count - 1 do begin if Dictionary.cds_OperationHdrList.Locate('Operation_Code',DumbList[i],[]) then lbOperation.Items.Add(Dictionary.cds_OperationHdrList.FieldByName('Operation_Code').AsString + '->' + Dictionary.cds_OperationHdrList.FieldByName('Operation_CHN').AsString); end; lvDetail.Clear; with Dictionary.cds_RepairReasonList do begin Filtered := False; Filter := 'Reason_Code = ' + QuotedStr(lvMaster.Selected.Caption); Filtered := True; First; while not Eof do begin with lvDetail.Items.Add do begin Caption := lvMaster.Selected.Caption; SubItems.Add(FieldByName('Item_Name').AsString); SubItems.Add(FieldByName('Enum_Value').AsString); end; Next; end; end; end; procedure TRepairReasonFrm.lvDetailChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin AddNew :=''; edtItemName.Enabled := False; edtItemValue.Enabled := False; sbAdd.Enabled := True; sbEdit.Enabled := True; sbDelete.Enabled := True; sbSave.Enabled := False; if lvDetail.ItemIndex = -1 then Exit; edtItemName.Hint := lvDetail.Selected.Caption; edtItemName.Text := lvDetail.Selected.SubItems[0]; edtItemValue.Text := lvDetail.Selected.SubItems[1]; end; end.
{Procedural Texture Demo / Tobias Peirick } //The Original is at GLScene //Greatly changed..altered by Ivan Lee Herring. unit CCProceduralCloudsFrm; interface uses Winapi.Windows, Winapi.Messages, Winapi.ShellApi,//help display System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Samples.Spin, Vcl.ComCtrls, Vcl.Buttons, Vcl.Imaging.Jpeg, GLScene, GLObjects, GLTexture, GLTextureFormat, GLHUDObjects, GLCadencer, GLWin32Viewer, GLFileTGA, GLMaterial, GLGraphics,//for bitmap saving GLProcTextures, GLCoordinates, GLCrossPlatform, GLBaseClasses; type TProceduralCloudsForm = class(TForm) GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCamera1: TGLCamera; Panel1: TPanel; Label1: TLabel; CBFormat: TComboBox; Label2: TLabel; Label3: TLabel; CBCompression: TComboBox; Label5: TLabel; RBDefault: TRadioButton; RBDouble: TRadioButton; LAUsedMemory: TLabel; RBQuad: TRadioButton; LARGB32: TLabel; LACompression: TLabel; GLCadencer1: TGLCadencer; CheckBox1: TCheckBox; Label4: TLabel; Label6: TLabel; CheckBox2: TCheckBox; GLPlane1: TGLPlane; TileTrackBar: TTrackBar; Timer1: TTimer; CloudRandomSeedUsedEdit: TEdit; CloudImageSizeUsedEdit: TEdit; UseCloudFileCB: TCheckBox; CloudFileOpenBtn: TSpeedButton; CloudFileUsedEdit: TEdit; MakeAndSaveCloudNoiseFile: TSpeedButton; Label61: TLabel; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; SaveImageBtn: TSpeedButton; SpeedButton1: TSpeedButton; HelpBtn: TSpeedButton; MinCutTrackBar: TTrackBar; MinCutLabel: TLabel; SharpnessLabel: TLabel; SharpnessTrackBar: TTrackBar; procedure FormCreate(Sender: TObject); procedure HelpBtnClick(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure TileTrackBarChange(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure GLSceneViewer1AfterRender(Sender: TObject); procedure CBFormatChange(Sender: TObject); procedure CloudFileOpenBtnClick(Sender: TObject); procedure MakeAndSaveCloudNoiseFileClick(Sender: TObject); procedure SaveImageBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Déclarations privées } public { Déclarations publiques } newSelection : Boolean; FirstTime:Boolean; end; var ProceduralCloudsForm: TProceduralCloudsForm; implementation {$R *.DFM} uses CCEditorFrm; procedure TProceduralCloudsForm.FormCreate(Sender: TObject); begin FirstTime:=True; end; procedure TProceduralCloudsForm.FormShow(Sender: TObject); begin If FirstTime then begin FirstTime:=False; Timer1.Enabled:=True; GLCadencer1.Enabled:=True; CBFormat.ItemIndex:=1;//3; CBCompression.ItemIndex:=0; CBFormatChange(Sender); end; end; procedure TProceduralCloudsForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Timer1.Enabled:=False; GLCadencer1.Enabled:=False; end; procedure TProceduralCloudsForm.HelpBtnClick(Sender: TObject); begin ShellExecute( Application.Handle, // handle to parent window 'open', // pointer to string that specifies operation to perform PChar(ExtractFilePath(ParamStr(0))+'ProceduralClouds.htm'),// pointer to filename or folder name string '',// pointer to string that specifies executable-file parameters //+'help' PChar(ExtractFilePath(ParamStr(0))),// pointer to string that specifies default directory SW_SHOWNORMAL); end; procedure TProceduralCloudsForm.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin if CheckBox1.Checked then TGLProcTextureNoise(GLPlane1.Material.Texture.Image).NoiseAnimate(deltaTime); end; procedure TProceduralCloudsForm.TileTrackBarChange(Sender: TObject); begin GLPlane1.XTiles:= TileTrackBar.Position; GLPlane1.YTiles:= TileTrackBar.Position; {EnvColor clrLightBlue TextureMode Blend} end; procedure TProceduralCloudsForm.Timer1Timer(Sender: TObject); begin Caption:=GLSceneViewer1.FramesPerSecondText; GLSceneViewer1.ResetPerformanceMonitor; end; procedure TProceduralCloudsForm.GLSceneViewer1AfterRender(Sender: TObject); var rgb : Integer; begin // update compression stats, only the 1st time after a new selection if newSelection then with GLPlane1.Material.Texture do begin rgb:=Image.Width*Image.Height*4; LARGB32.Caption:=Format('RGBA 32bits would require %d kB', [rgb div 1024]); LAUsedMemory.Caption:=Format('Required memory : %d kB', [TextureImageRequiredMemory div 1024]); LACompression.Caption:=Format('Compression ratio : %d %%', [100-100*TextureImageRequiredMemory div rgb]); newSelection:=False; end; end; procedure TProceduralCloudsForm.CBFormatChange(Sender: TObject); var aPERM: array [0..255] of Byte; outfile:Textfile; s:string; i : Integer; begin // adjust settings from selection and reload the texture map with GLPlane1.Material.Texture do begin If (UseCloudFileCB.Checked and (FileExists(CloudFileUsedEdit.Text)))then begin Try AssignFile(outfile, CloudFileUsedEdit.Text); { File selected in dialog box } Reset(outfile); Readln(outfile, s{'Cloud Base V1.0'}); For I := 0 to 255 do begin Readln(outfile, s); aPERM[I]:=strtoint(s); end; Finally CloseFile(outfile); End; TGLProcTextureNoise(Image).SetPermFromData(aPERM); end else TGLProcTextureNoise(Image).SetPermToDefault; TextureFormat:=TGLTextureFormat(Integer(tfRGB)+CBFormat.ItemIndex); Compression:=TGLTextureCompression(Integer(tcNone)+CBCompression.ItemIndex); TGLProcTextureNoise(Image).MinCut := MinCutTrackBar.Position; TGLProcTextureNoise(Image).NoiseSharpness := SharpnessTrackBar.Position /100; TGLProcTextureNoise(Image).Height :=strtoint(CloudImageSizeUsedEdit.Text); TGLProcTextureNoise(Image).Width :=strtoint(CloudImageSizeUsedEdit.Text); TGLProcTextureNoise(Image).NoiseRandSeed :=strtoint(CloudRandomSeedUsedEdit.Text); ; TGLProcTextureNoise(Image).Seamless := CheckBox2.Checked; SharpnessLabel.Caption:=Inttostr(SharpnessTrackBar.Position); MinCutLabel.Caption:=Inttostr(MinCutTrackBar.Position); if RBDefault.Checked then begin GLPlane1.Width:= 50; GLPlane1.Height:=50; end else if RBDouble.Checked then begin GLPlane1.Width:=100; GLPlane1.Height:=100; end else begin GLPlane1.Width:=400; GLPlane1.Height:=400; end; end; newSelection:=True; end; procedure TProceduralCloudsForm.CloudFileOpenBtnClick(Sender: TObject); begin OpenDialog1.Filter := 'Cloud base (*.clb)|*.clb'; OpenDialog1.InitialDir := ExtractFilePath(ParamStr(0)); OpenDialog1.Filename:='*.clb' ; if OpenDialog1.execute then begin CloudFileUsedEdit.Text := OpenDialog1.Filename; end; end; procedure TProceduralCloudsForm.MakeAndSaveCloudNoiseFileClick(Sender: TObject); var aPERM: array [0..255] of Byte; outfile:Textfile; i:Integer; Procedure RandomPerm; var Idiot,Count,More, Less,again:Integer; begin MakeAndSaveCloudNoiseFile.Caption:=inttostr(0); Application.ProcessMessages; For Idiot := 0 to 255 do begin aPERM[Idiot]:=Random(256); //Label61.Caption:= inttostr(Idiot); //Application.ProcessMessages; end; Count:=0; repeat again:=0; Less:= Random(256); For Idiot := 0 to Count do begin more:= aPERM[Idiot]; If (Less = more) then inc(again); end; Label61.Caption:= inttostr(again); //these can be removed.. just for debugging Application.ProcessMessages; If (again = 0) then begin aPERM[Count+1]:=Less; inc(Count); MakeAndSaveCloudNoiseFile.Caption:= inttostr(Less)+','+inttostr(Count); Application.ProcessMessages; end; until Count = 255 end; begin SaveDialog1.Filter := 'Cloud base (*.clb)|*.clb'; SaveDialog1.InitialDir:=ExtractFilePath(ParamStr(0)); SaveDialog1.DefaultExt:='rnd'; SaveDialog1.Filename:='*.clb' ; if (SaveDialog1.Execute) then begin if UpperCase(ExtractFileExt(SaveDialog1.FileName)) = '.CLB' then begin Application.ProcessMessages; Randomize; RandomPerm; Try AssignFile(outfile, SaveDialog1.FileName); { File selected in dialog box } Rewrite(outfile); Writeln(outfile, 'Cloud Base V1.0'); For I := 0 to 255 do Writeln(outfile, inttostr(aPERM[I])); Finally CloseFile(outfile); End; Label61.Caption:='Done'; MakeAndSaveCloudNoiseFile.Caption:=''; end; end; end; procedure TProceduralCloudsForm.SaveImageBtnClick(Sender: TObject); var fName : String; Saved:TGLBitmap32; Saved2:TBitmap; tga : TTGAImage; begin //SaveDialog1.Filter := 'Cloud image (*.bmp)|*.bmp'; SaveDialog1.Filter := 'Cloud image (*.bmp;*.tga)|*.bmp;*.tga'; SaveDialog1.InitialDir:=ImagePath;//ExtractFilePath(ParamStr(0)); SaveDialog1.DefaultExt:='bmp'; SaveDialog1.Filename:='';//'*.bmp' ; If SaveDialog1.Execute then begin if (GLPlane1.Material.Texture.Image is TGLProcTextureNoise) then begin Saved:=TGLProcTextureNoise(GLPlane1.Material.Texture.Image).GetBitmap32(); //(1) Saved2:=Saved.Create32BitsBitmap; fName:=SaveDialog1.FileName; if ExtractFileExt(fName)='' then fName:=fName+'.bmp' else if ExtractFileExt(fName)='.bmp' then begin {do nothing} end else changefileext(fName,'.tga'); if LowerCase(ExtractFileExt(fName))='.tga' then begin tga:=TTGAImage.Create; try tga.Assign(Saved2{bmp}{pic.Bitmap}); tga.SaveToFile(fName) finally tga.Free; end; end else //bmp.SaveToFile(fName); Saved2.SaveToFile(SaveDialog1.FileName); end; end; end; end.
unit TestULancamentoPadraoController; { 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, ULancamentoPadraoVo, UContasPagarVO, UCondominioVO, SysUtils, DBClient, DBXJSON, UPessoasVO, UCondominioController, ULancamentoPadraoController, DBXCommon, UHistoricoVO, UPessoasController, UPlanoCOntasController, Classes, UController, UContasReceberVo, DB, UPlanoContasVO, ConexaoBD, SQLExpr, ULoteVO, Generics.Collections; type // Test methods for class TLancamentoPadraoController TestTLancamentoPadraoController = class(TTestCase) strict private FLancamentoPadraoController: TLancamentoPadraoController; public procedure SetUp; override; procedure TearDown; override; published procedure TestConsultarPorId; procedure TestConsultarPorIdNaoEncontrado; end; implementation procedure TestTLancamentoPadraoController.SetUp; begin FLancamentoPadraoController := TLancamentoPadraoController.Create; end; procedure TestTLancamentoPadraoController.TearDown; begin FLancamentoPadraoController.Free; FLancamentoPadraoController := nil; end; procedure TestTLancamentoPadraoController.TestConsultarPorId; var ReturnValue: TLancamentoPadraoVO; begin ReturnValue := FLancamentoPadraoController.ConsultarPorId(1); if(returnvalue <> nil) then check(true,'Lancamento pesquisado com sucesso!') else check(false,'Lancamento nao encontrado!'); end; procedure TestTLancamentoPadraoController.TestConsultarPorIdNaoEncontrado; var ReturnValue: TLancamentoPadraoVO; begin ReturnValue := FLancamentoPadraoController.ConsultarPorId(4); if(returnvalue <> nil) then check(false,'Lancamento pesquisado com sucesso!') else check(true,'Lancamento nao encontrado!'); end; initialization // Register any test cases with the test runner RegisterTest(TestTLancamentoPadraoController.Suite); end.
Unit OOP3; interface uses Stack, Graph, WinCrt; type Proc = Procedure (p: pointer); PLocation = ^TLocation; TLocation = object(TStackable) X, Y: Integer; constructor Init(InitX, InitY:Integer); function GetX:Integer; function GetY:Integer; destructor Done; virtual; end; PFigure = ^TFigure; TFigure = object(TLocation) Visible: Boolean; constructor Init(InitX, InitY:Integer); destructor Done; virtual; procedure Show; virtual; procedure Hide; virtual; function IsVisible: Boolean; procedure Crowl(dX,dY: Integer); virtual; procedure MoveTo(NewX, NewY: Integer); function Inside: Boolean; virtual; end; PCircle = ^TCircle; TCircle = object(TFigure) Radius:Integer; constructor Init(InitX, InitY, InitRadius:Integer); destructor Done; virtual; procedure Show; virtual; procedure Hide; virtual; procedure Resize(Step:Integer); virtual; procedure Crowl(dX,dY: Integer); virtual; function Inside: Boolean; virtual; end; PQuasiStack = ^TQuasiStack; TQuasiStack = object(TStack) procedure ForEach(p:proc); procedure Delete(p:pStackable); end; implementation {Реализация методов класса Location} constructor TLocation.Init(InitX, InitY:Integer); begin X := InitX; Y := InitY; inherited Init; end; function TLocation.GetX:Integer; begin GetX := X; end; function TLocation.GetY:Integer; begin GetY := Y; end; destructor TLocation.Done; begin end; {Реализация методов класса TFigure} constructor TFigure.Init(InitX, InitY:Integer); begin inherited Init(InitX, InitY); Visible := False; end; destructor TFigure.Done; begin Hide; end; function TFigure.IsVisible:Boolean; begin IsVisible := Visible; end; procedure TFigure.Show; begin RunError(211); {Run-time error: Call to abstract method} end; procedure TFigure.Hide; begin RunError(211); {Run-time error: Call to abstract method} end; procedure TFigure.Crowl(dX, dY: Integer); begin RunError(211); {Run-time error: Call to abstract method} end; function TFigure.Inside: Boolean; begin RunError(211); {Run-time error: Call to abstract method} end; procedure TFigure.MoveTo(NewX, NewY:Integer); begin Hide; X := NewX; Y := NewY; Show; end; {Реализация методов класса Circle} constructor TCircle.Init(InitX, InitY, InitRadius:Integer); begin inherited Init(InitX, InitY); Radius := InitRadius; end; procedure TCircle.Show; begin Visible := True; Graph.Circle(X, Y, Radius); end; procedure TCircle.Hide; var TempColor:Word; begin TempColor := Graph.GetColor; Graph.SetColor(GetBkColor()); Visible := False; Graph.Circle(X, Y, Radius); Graph.SetColor(TempColor); end; procedure TCircle.Crowl(dX,dY: Integer); var dr,i, X0, Y0: Integer; sx, sy: Real; begin dr:=Round(Sqrt(Sqr(dX)+Sqr(dY))); If dr>0 Then Begin X0:=X; Y0:=Y; for i:=1 to dr Do Begin Resize(1); Delay(1); End; sx:= Int(dX)/Int(dr); sy:= Int(dy)/Int(dr); for i:=1 to dr Do Begin Resize(-1); MoveTo(X0+Round(i*sx),Y0+Round(i*sy)); Delay(1); End; End; end; destructor TCircle.Done; begin Hide; end; procedure TCircle.Resize(Step:Integer); begin Hide; Inc(Radius,Step); if Radius<0 then Radius:=0; Show; end; function TCircle.Inside: Boolean; Begin Inside:= (X>Radius) and (X<Graph.GetMaxX-Radius) and (Y>Radius) and (Y<Graph.GetMaxY-Radius); End; {Реализация методов класса TQuasiStack} procedure TQuasiStack.ForEach(p:proc); Var ip, oldip: PStackable; begin ip:=top; While ip<>nil do begin oldip:=ip; ip:=ip^.getprev; p(oldip); end; end; procedure TQuasiStack.Delete(p:pStackable); Var ip, oldip : pStackable; begin ip:=top; oldip:=Nil; While (ip<>p) and (ip<>nil) do begin oldip:=ip; ip:=ip^.getprev; end; If ip=nil then begin Error(2); Exit; end; If oldip<>nil then oldip^.SetPrev(ip^.GetPrev) else top:=ip^.GetPrev; end; end.
unit About; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Dialogs, Buttons, ExtCtrls, HTTPApp, OleCtrls, SHDocVw, registry, Shellapi; type TAboutBox = class(TForm) OKButton: TButton; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure RegisterOCX; function GetSystemDirectory(var S: String): Boolean; function GetWindowsDirectory(var S: String): Boolean; function IsWindows64: Boolean; procedure OKButtonClick(Sender: TObject); private FAllInOneFlag : Boolean; { Private declarations } public { Public declarations } end; var AboutBox: TAboutBox; registered:Boolean; implementation uses mainunit; {$R *.dfm} function GetFileSize(const fn: string): integer; var f: file; Buffer: PAnsiChar; begin Result := -1; ShowMessage(IntToStr(Result)); AssignFile(F, fn); Reset(F); try result:= FileSize(F); finally CloseFile(F); end; end; function IsUserAnAdmin(): BOOL; external shell32; function IsWindowsAdministrator: Boolean; // Returns TRUE if the user has administrator priveleges // Returns a boolean indicating whether or not user has admin // privileges. Call only when running under NT. Win9.x will return false! var hAccessToken : tHandle; ptgGroups : pTokenGroups; dwInfoBufferSize : DWORD; psidAdministrators : PSID; int : integer; // counter blnResult : boolean; // return flag const SECURITY_NT_AUTHORITY: SID_IDENTIFIER_AUTHORITY = (Value: (0,0,0,0,0,5)); // ntifs SECURITY_BUILTIN_DOMAIN_RID: DWORD = $00000020; DOMAIN_ALIAS_RID_ADMINS: DWORD = $00000220; DOMAIN_ALIAS_RID_USERS : DWORD = $00000221; DOMAIN_ALIAS_RID_GUESTS: DWORD = $00000222; DOMAIN_ALIAS_RID_POWER_: DWORD = $00000223; begin Result := False; blnResult := OpenThreadToken( GetCurrentThread, TOKEN_QUERY, True, hAccessToken ); if ( not blnResult ) then begin if GetLastError = ERROR_NO_TOKEN then blnResult := OpenProcessToken( GetCurrentProcess, TOKEN_QUERY, hAccessToken ); end; ptgGroups := nil; if ( blnResult ) then try GetMem(ptgGroups, 1024); blnResult := GetTokenInformation( hAccessToken, TokenGroups, ptgGroups, 1024, dwInfoBufferSize ); CloseHandle( hAccessToken ); if ( blnResult ) then begin AllocateAndInitializeSid( SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators ); {$IFOPT R+} {$DEFINE RMINUS} {$R-} {$ENDIF} for int := 0 to ptgGroups.GroupCount - 1 do if EqualSid( psidAdministrators, ptgGroups.Groups[ int ].Sid ) then begin Result := True; Break; end; {$IFDEF IMINUS} {$R-} {$UNDEF IMINUS} {$ENDIF} FreeSid( psidAdministrators ); end; finally If ptgGroups <> nil then FreeMem( ptgGroups ); end; end; function GetComputerNetName: string; var buffer: array[0..255] of char; size: dword; begin size := 256; if GetComputerName(buffer, size) then Result := buffer else Result := '' end; Function GetUserFromWindows: string; Var UserName : string; UserNameLen : Dword; Begin UserNameLen := 255; SetLength(userName, UserNameLen) ; If GetUserName(PChar(UserName), UserNameLen) Then Result := Copy(UserName,1,UserNameLen - 1) Else Result := 'Unknown'; End; function TAboutBox.GetSystemDirectory(var S: String): Boolean; var Len: Integer; begin Len := Windows.GetSystemDirectory(nil, 0); if Len > 0 then begin SetLength(S, Len); Len := Windows.GetSystemDirectory(PChar(S), Len); SetLength(S, Len); Result := Len > 0; end else Result := False; end; function TAboutBox.GetWindowsDirectory(var S: String): Boolean; var Len: Integer; begin Len := Windows.GetWindowsDirectory(nil, 0); if Len > 0 then begin SetLength(S, Len); Len := Windows.GetWindowsDirectory(PChar(S), Len); SetLength(S, Len); Result := Len > 0; end else Result := False; end; function TAboutBox.IsWindows64: Boolean; type TIsWow64Process = function(AHandle:THandle; var AIsWow64: BOOL): BOOL; stdcall; var vKernel32Handle: DWORD; vIsWow64Process: TIsWow64Process; vIsWow64 : BOOL; begin Result := False; vKernel32Handle := LoadLibrary('kernel32.dll'); if (vKernel32Handle = 0) then Exit; // Loading kernel32.dll was failed, just return try @vIsWow64Process := GetProcAddress(vKernel32Handle, 'IsWow64Process'); if not Assigned(vIsWow64Process) then Exit; // Loading IsWow64Process was failed, just return vIsWow64 := False; if (vIsWow64Process(GetCurrentProcess, vIsWow64)) then Result := vIsWow64; // use the returned value finally FreeLibrary(vKernel32Handle); // unload the library end; end; procedure TAboutBox.OKButtonClick(Sender: TObject); begin close; end; function ExecAndWait(const ExecuteFile, ParamString : string): boolean; var SEInfo: TShellExecuteInfo; ExitCode: DWORD; begin FillChar(SEInfo, SizeOf(SEInfo), 0); SEInfo.cbSize := SizeOf(TShellExecuteInfo); with SEInfo do begin fMask := SEE_MASK_NOCLOSEPROCESS; Wnd := Application.Handle; lpFile := PChar(ExecuteFile); lpParameters := PChar(ParamString); nShow := SW_HIDE; end; if ShellExecuteEx(@SEInfo) then begin repeat //Showmessage('ew'); Application.ProcessMessages; GetExitCodeProcess(SEInfo.hProcess, ExitCode); until (ExitCode <> STILL_ACTIVE) or Application.Terminated; Result:=True; end else Result:=False; end; function getFileSizeInBytes(const fn: string): integer; var f: File of byte; begin Result := -1; if (FileExists(fn)) then begin try {$I-} AssignFile(f, fn); Reset(f); {$I+} if (IOResult = 0) then begin Result := FileSize(f); end else begin Result := 0; end; finally {$I-}CloseFile(f);{$I+} end; end; end; procedure TAboutBox.FormCreate(Sender: TObject); var reg: TRegistry; regkey:String; admin, update:Boolean; aHandle : THandle; ocxPath, WinDir, SystemDir, SystemDir64 : string; rStream: TResourceStream; fStream: TFileStream; Fname: string; begin registered:=true; update:=False; if IsUserAnAdmin() then Admin:=True else Admin:=False; Reg:=TRegistry.Create;//() Reg.RootKey := HKEY_CLASSES_ROOT; if IsWindows64 then regkey:='\Wow6432Node\CLSID\{673AB001-9A0B-11D4-B2A4-FD6847C75367}' else regkey:='\CLSID\{673AB001-9A0B-11D4-B2A4-FD6847C75367}'; try GetSystemDirectory(SystemDir); GetWindowsDirectory(WinDir); systemDir:=SystemDir+'\'; if IsWindows64 then begin SystemDir:=WinDIr+'\SysWOW64\'; ocxPath := SystemDir + lowercase('fitter.dll'); end else ocxPath := SystemDir + lowercase('fitter.dll');; if Admin then begin if getFileSizeInBytes(SystemDir + 'fitter.dll')<210000 then begin DeleteFIle(SystemDir + 'fitter.dll'); update:=True; end; if not FileExists(SystemDir + 'fitter.dll') then begin Fname := SystemDir + 'fitter.dll'; rStream := TResourceStream.Create(hInstance, 'fitter', RT_RCDATA); try fStream := TFileStream.Create(Fname, fmCreate); try fStream.CopyFrom(rStream, 0); finally fStream.Free; end; finally rStream.Free; end; end; if not FileExists(SystemDir + 'lmhelper.dll') then begin Fname := SystemDir + 'lmhelper.dll'; rStream := TResourceStream.Create(hInstance, 'lmhelper', RT_RCDATA); try fStream := TFileStream.Create(Fname, fmCreate); try fStream.CopyFrom(rStream, 0); finally fStream.Free; end; finally rStream.Free; end; end; end; except ShowMessage(Format('Unable to register %s', [ocxPath])); end; if Admin then if (Reg.OpenKey(regkey,false)=false) or update then begin RegisterOCX; registered:=False; ShowMEssage('Fitter.dll is needed for fitting and it is automatically registered!'); ShellExecute(Handle, nil, PChar(Application.ExeName), nil, nil, SW_SHOWNORMAL); end; Reg.Free; if registered=False then Application.Terminate; end; procedure TAboutBox.RegisterOCX; type TRegFunc = function : HResult; stdcall; var ARegFunc : TRegFunc; aHandle : THandle; ocxPath, WinDir, SystemDir, SystemDir64 : string; rStream: TResourceStream; fStream: TFileStream; Fname: string; begin try GetSystemDirectory(SystemDir); GetWindowsDirectory(WinDir); systemDir:=SystemDir+'\'; if IsWindows64 then begin SystemDir:=WinDIr+'\SysWOW64\'; ocxPath := SystemDir + 'Fitter.dll'; end else ocxPath := SystemDir + 'Fitter.dll';; if fileexists(ocxPath) then deletefile(ocxPath); if not FileExists(SystemDir + 'fitter.dll') then begin Fname := SystemDir + 'fitter.dll'; rStream := TResourceStream.Create(hInstance, 'fitter', RT_RCDATA); try fStream := TFileStream.Create(Fname, fmCreate); try fStream.CopyFrom(rStream, 0); finally fStream.Free; end; finally rStream.Free; end; end; aHandle := LoadLibrary(PChar(ocxPath)); if aHandle <> 0 then begin ARegFunc := GetProcAddress(aHandle,'DllRegisterServer'); if Assigned(ARegFunc) then begin ExecAndWait(SystemDir+'regsvr32','/s ' + ocxPath); //ShowMessage(SystemDir+'regsvr32'); end; FreeLibrary(aHandle); end; except ShowMessage(Format('Unable to register %s', [ocxPath])); end; end; end.
{$C-} program PlayWithTurtle; { TURTLEGRAPHICS DEMO PROGRAM Version 1.00A This programs demonstrates the use of Turtlegraphics with TURBO PASCAL Version 3.0. NOTE: You must have a color graphics adapter to use this program. PSEUDO CODE 1. Initialize program variables. 2. Play with the turtle routines. a. Start with medium resolution graphics. b. Read a character and manipulate the turtle until the user pressed <ESC> or ^C. 3. Reset screen to text mode and quit. Here is a list of the commands that this program uses: Function Keys: F1 Turns turtle to the left. F2 Turns turtle to the right. Cursor Keys: They point the turtle: Up arrow, north Down arrow, south Right arrow, east Left arrow: west Home, northwest PgUp, northeast PgDn, southeast End: southwest Alpha keys: 0 thru 9: Set the magnitude for speed. (i.e. 0 is stop, 1 is slow, 9 is fast) H: Sets video mode to High resolution. M: Sets video mode to Medium resolution. W: TOGGLE: Wrap on / off P: TOGGLE: PenUp / PenDown. T: TOGGLE: Hide / show the turtle. C: Changes the color (or intensity) of the lines. +: Homes the turtle. <ESC>: Quits the turtle demo. } {$I turt} const TurtleSpeed = 50; Yellow = 14; type ToggleCommands = (PenOn, WrapOn, TurtleOn); var ToggleRay : array[PenOn..TurtleOn] of boolean; Magnitude, { Sets speed: 0 = stopped, 9 = fast } Color, { Current palette color } CurentPalette: Integer; { Current Palette } function upcase( c : char ) : char; begin if ( c >= 'a' ) and ( c <= 'z' ) then upcase := chr( ord(c) - 32 ) else upcase := c; end; Procedure Init; var Toggle: ToggleCommands; procedure VerifyGraphicsCard; var ch : char; begin ClrScr; Writeln('You must have a color graphics adapter to use this program.'); write('CONTINUE? (Y/N): '); repeat read(kbd, ch); if upcase(ch) in ['N', #27, ^C] then begin TextMode; Halt; end; until upcase(ch) = 'Y'; end; { VerifyGraphicsCard } begin VerifyGraphicsCard; Magnitude := 0; { Stopped } Color := 0; for Toggle := PenOn to TurtleOn do ToggleRay[Toggle] := true; { Start with all commands toggled on } end; Procedure PlayWithTurtle; var InKey: Char; FunctionKey: Boolean; { TRUE if a function key was pressed } procedure NewScreen(SetRes : char); procedure DrawBox(x, y, w, h : integer); begin Draw(x, y, x + w, y, 1); { top } Draw(x, y, x, y + h, 1); { left side } Draw(x, y + h, x + w, y + h, 1); { bottom } Draw(x + w, y + h, x + w, y, 1); { right side } end; (* DrawBox *) procedure HiResOn; const CharHeight = 10; begin HiRes; HiResColor(Yellow); DrawBox(0, 0, 639, 199-CharHeight); TurtleWindow(319, 99-(CharHeight DIV 2), 638, 198-CharHeight); end; { HiResOn } procedure MediumResOn; const CharHeight = 20; begin GraphMode; DrawBox(0, 0, 319, 199-CharHeight); TurtleWindow(159, 99-(CharHeight DIV 2), 318, 198-CharHeight); end; { MediumResOn } begin case SetRes of 'M' : begin MediumResOn; GoToXY(1, 24); {writeln('SPEED:0-9 TOGGLES:Pen,Wrap,Turtle,Color'); write(' TURN: F1,F2, HOME: +, RES: Hi,Med'); } end; 'H' : begin HiResOn; GoToXY(1, 25); {write(' SPEED: 0-9 TOGGLES: Pen,Wrap,Turtle,Color'); write(' TURN: F1,F2 HOME: + RES: Hi,Med');} end; end; (* case *) Showturtle; home; Wrap; Magnitude := 0; end; { NewScreen } Function GetKey(var FunctionKey: Boolean): char; var ch: char; begin read(kbd,Ch); If (Ch = #27) AND KeyPressed Then { it must be a function key } begin read(kbd,Ch); FunctionKey := true; end else FunctionKey := false; GetKey := Ch; end; Procedure TurtleDo(InKey : char; FunctionKey : boolean); const NorthEast = 45; SouthEast = 135; SouthWest = 225; NorthWest = 315; procedure DoFunctionCommand(FunctionKey: char); begin case FunctionKey of 'H': SetHeading(North); { Up arrow Key } 'P': SetHeading(South); { Down arrow Key } 'M': SetHeading(East); { Left arrow Key } 'K': SetHeading(West); { Right arrow Key } 'I': SetHeading(NorthEast); { PgUp } 'Q': SetHeading(SouthEast); { PgDn } 'G': SetHeading(NorthWest); { Home } 'O': SetHeading(SouthWest); { End } '<': SetHeading(Heading+5); { F1 } ';': SetHeading(Heading-5); { F2 } end end { Do function command }; begin If FunctionKey then DoFunctionCommand(Upcase(InKey)) else case upcase(InKey) of 'P': begin ToggleRay[PenOn] := NOT ToggleRay[PenOn]; case ToggleRay[PenOn] of true : PenUp; false : PenDown; end; (* case *) end; 'W': begin ToggleRay[WrapOn] := NOT ToggleRay[WrapOn]; case ToggleRay[WrapOn] of true : Wrap; false : NoWrap; end; (* case *) end; 'T': begin ToggleRay[TurtleOn] := NOT ToggleRay[TurtleOn]; case ToggleRay[TurtleOn] of true : ShowTurtle; false : HideTurtle; end; (* case *) end; '+': Home; 'C': begin Color := succ(color) mod 4; SetPenColor(Color); end; '0'..'9': Magnitude := Sqr(ord(inkey) - ord('0')); 'M': begin NewScreen('M'); { medium resolution graphics } end; 'H': begin NewScreen('H'); { HiRes graphics } end; end; { case } end; (* TurtleDo *) begin NewScreen('M'); { start with medium resolution graphics } repeat TurtleDelay(TurtleSpeed); repeat if Magnitude <> 0 then forwd(Magnitude); until KeyPressed; Inkey := GetKey(FunctionKey); TurtleDo(InKey, FunctionKey); until UpCase(Inkey) in [#27, ^C]; end; { PlayWithTurtle } begin Init; PlayWithTurtle; ClearScreen; TextMode; end.
{************************************************************* Author: Stéphane Vander Clock (SVanderClock@Arkadia.com) www: http://www.arkadia.com EMail: SVanderClock@Arkadia.com product: ALcinoe SQL parser Function Version: 3.05 Description: SQL function to create easily sql string without take care if it's an update or insert sql Statement. just add the value in a tstringList like fieldname=value and at the end contruct the sql string Legal issues: Copyright (C) 1999-2005 by Arkadia Software Engineering This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Know bug : History : Link : Please send all your feedback to SVanderClock@Arkadia.com **************************************************************} unit ALFcnSQL; interface uses classes; Type {----------------------------} TAlStrSelectSQLClause = record Distinct : Boolean; Select: String; Where: string; From: string; Join: string; GroupBy: string; Having: string; OrderBy: String; end; TALStrUpdateSQLClause = record Update: Boolean; Table: string; Value: string; Where: string; end; TAlLstSelectSQLClause = record Distinct : Boolean; Select: TStrings; Where: Tstrings; From: Tstrings; Join: Tstrings; GroupBy: Tstrings; Having: Tstrings; OrderBy: TStrings; end; TALLstUpdateSQLClause = record Update: Boolean; Table: String; Value: Tstrings; Where: Tstrings; end; {---------------------------------------------------------} Function AlEmptyStrUpdateSqlClause: TAlStrUpdateSQLClause; Function AlEmptyLstUpdateSqlClause: TAlLstUpdateSQLClause; Function AlEmptyStrSelectSqlClause: TAlStrSelectSQLClause; Function AlEmptyLstSelectSqlClause: TAlLstSelectSQLClause; Procedure ALFreeLstUpdateSqlClause(Var aLstUpdateSQLClause: TAlLstUpdateSQLClause); Procedure ALFreeLstSelectSqlClause(Var aLstSelectSQLClause: TAlLstSelectSQLClause); Function AlSQLFromStrSelectSqlClause(SqlClause: TAlStrSelectSQLClause) :String; Function AlSQLFromLstSelectSqlClause(SqlClause: TAlLstSelectSQLClause) :String; Function AlSQLFromStrUpdateSqlClause(SqlClause: TAlStrUpdateSQLClause): String; Function AlSQLFromLstUpdateSqlClause(SqlClause: TAlLstUpdateSQLClause): String; implementation uses sysutils; {********************************************************} Function ALEmptyStrSelectSqlClause: TAlStrSelectSQLClause; Begin with result do begin Distinct := False; Select:= ''; Where:= ''; From:= ''; Join:= ''; GroupBy:= ''; Having:= ''; OrderBy:= ''; end; end; {********************************************************} Function ALEmptyStrUpdateSqlClause: TAlStrUpdateSQLClause; Begin with result do begin Update := False; table:= ''; Value:= ''; Where:= ''; end; end; {********************************************************} Function ALEmptyLstSelectSqlClause: TAlLstSelectSQLClause; {------------------------} Function alg001: Tstrings; Begin Result := TstringList.create; with result as TstringList do begin Sorted := True; Duplicates := dupIgnore; Delimiter := ';'; QuoteChar := ''''; end; end; Begin with result do begin Distinct := False; Select:= alg001; Where:= alg001; From:= alg001; Join:= alg001; GroupBy:= alg001; Having:= alg001; OrderBy:= alg001; end; end; {********************************************************} Function ALEmptyLstUpdateSqlClause: TAlLstUpdateSQLClause; {------------------------} Function alg001: Tstrings; Begin Result := TstringList.create; with result as TstringList do begin Sorted := True; Duplicates := dupIgnore; Delimiter := ';'; QuoteChar := ''''; end; end; Begin with result do begin Update := False; table:= ''; Value:= alg001; Where:= alg001; end; end; {*********************************************************************************} Procedure ALFreeLstSelectSqlClause(Var aLstSelectSQLClause: TAlLstSelectSQLClause); Begin with aLstSelectSQLClause do begin Select.free; Where.free; From.free; Join.free; GroupBy.free; Having.free; OrderBy.free; end; end; {*********************************************************************************} Procedure ALFreeLstUpdateSqlClause(Var aLstUpdateSQLClause: TAlLstUpdateSQLClause); Begin with aLstUpdateSQLClause do begin Value.free; Where.free; end; end; {*****************************************************************************} Function ALSQLFromStrSelectSqlClause(SqlClause: TAlStrSelectSQLClause) :String; Var Lst : TstringList; i : integer; Flag : Boolean; S : String; Begin Result := 'Select '; If SqlClause.Distinct then Result := result + 'distinct '; Lst := TstringList.Create; Try Lst.Sorted := True; Lst.Duplicates := dupIgnore; Lst.Delimiter := ';'; Lst.QuoteChar := ''''; {------------} Flag := False; Lst.DelimitedText := trim(SqlClause.Select); For i := 0 to lst.Count - 1 do If trim(lst[i]) <> '' then begin Flag := True; Result := Result + Lst[i] + ', '; end; IF not flag then result := result + '*' else Delete(Result,length(result)-1,2); {---------------------------} Result := Result + ' From '; Lst.DelimitedText := trim(SqlClause.From); For i := 0 to lst.Count - 1 do If trim(lst[i]) <> '' then Result := Result + Lst[i] + ', '; Delete(Result,length(result)-1,2); {----------------------------------------} Lst.DelimitedText := trim(SqlClause.join); For i := 0 to lst.Count - 1 do If trim(lst[i]) <> '' then Result := Result + ' ' + Lst[i] + ' '; {---------------------------------------} If trim(SqlClause.where) <> '' then begin Lst.DelimitedText := trim(SqlClause.where); S := ''; If Lst.Count > 0 then begin For i := 0 to lst.Count - 1 do If trim(lst[i]) <> '' then S := S + '(' + Lst[i] + ') and '; If s <> '' then begin delete(S,length(S)-3,4); Result := Result + ' Where ' + S; end; end; end; {-----------------------------------------} If trim(SqlClause.groupby) <> '' then begin Lst.DelimitedText := trim(SqlClause.groupby); S := ''; If Lst.Count > 0 then begin For i := 0 to lst.Count - 1 do If trim(lst[i]) <> '' then S := S + Lst[i] + ' and '; If s <> '' then begin Delete(S,length(S)-3,4); Result := Result + ' group by ' + S; end; end; end; {----------------------------------------} If trim(SqlClause.having) <> '' then begin Lst.DelimitedText := trim(SqlClause.having); If Lst.Count > 0 then begin S := ''; For i := 0 to lst.Count - 1 do If trim(lst[i]) <> '' then S := S + Lst[i] + ' and '; If s <> '' then begin Delete(S,length(S)-3,4); Result := Result + ' Having ' + S; end; end; end; {-----------------------------------------} If trim(SqlClause.orderby) <> '' then begin Lst.DelimitedText := trim(SqlClause.orderby); If Lst.Count > 0 then begin S := ''; For i := 0 to lst.Count - 1 do If trim(lst[i]) <> '' then S := S + Lst[i] + ', '; If s <> '' then begin Delete(S,length(S)-1,2); Result := Result + ' order by ' + S; end; end; end; finally Lst.Free; end; end; {*****************************************************************************} Function ALSQLFromStrUpdateSqlClause(SqlClause: TAlStrUpdateSQLClause): String; Var Lst : TstringList; i : integer; S1, S2 : String; Begin Lst := TstringList.Create; Try Lst.Sorted := True; Lst.Duplicates := dupIgnore; Lst.Delimiter := ';'; Lst.QuoteChar := ''''; Lst.DelimitedText := trim(SqlClause.Value); {----Update------------------} If SqlClause.Update then Begin Result := ''; for i := 0 to Lst.Count- 1 do If Trim(Lst[i]) <> '' then Result := Result + trim(Lst[i]) + ', '; delete(Result,length(result)-1,2); if result = '' then exit; Result := 'Update ' + SqlClause.Table + ' Set ' + result; If trim(SqlClause.Where) <> '' then begin Lst.DelimitedText := trim(SqlClause.where); If Lst.Count > 0 then begin Result := Result + ' Where '; For i := 0 to lst.Count - 1 do If trim(lst[i]) <> '' then Result := Result + '(' + trim(Lst[i]) + ') and '; delete(Result,length(result)-3,4); end; end; end {-Insert-} else Begin S1 := ''; S2 :=''; for i := 0 to Lst.Count-1 do If Trim(Lst[i]) <> '' then begin S1 := S1 + trim(Lst.Names[i]) + ', '; S2 := S2 + trim(Lst.ValueFromIndex[i]) + ', '; end; delete(S1,length(S1)-1,2); delete(S2,length(S2)-1,2); If (S1='') or (S2='') then begin result := ''; exit; end; Result := 'Insert into ' + SqlClause.Table + ' (' + S1 + ') Values (' + s2 + ')'; end; finally Lst.Free; end; end; {*****************************************************************************} Function ALSQLFromLstSelectSqlClause(SqlClause: TAlLstSelectSQLClause) :String; Var i : integer; Flag : Boolean; S : String; Begin Result := 'Select '; If SqlClause.Distinct then Result := result + 'distinct '; {------------} Flag := False; For i := 0 to SqlClause.Select.Count - 1 do If trim(SqlClause.Select[i]) <> '' then begin Flag := True; Result := Result + SqlClause.Select[i] + ', '; end; IF not flag then result := result + '*' else Delete(Result,length(result)-1,2); {--------------------------} Result := Result + ' From '; For i := 0 to SqlClause.From.Count - 1 do If trim(SqlClause.From[i]) <> '' then Result := Result + SqlClause.From[i] + ', '; Delete(Result,length(result)-1,2); {---------------------------------------} For i := 0 to SqlClause.join.Count - 1 do If trim(SqlClause.join[i]) <> '' then Result := Result + ' ' + SqlClause.join[i] + ' '; {--------------------------------------} If SqlClause.where.Count > 0 then begin S := ''; For i := 0 to SqlClause.where.Count - 1 do If trim(SqlClause.where[i]) <> '' then S := S + '(' + SqlClause.where[i] + ') and '; If s <> '' then begin delete(S,length(S)-3,4); Result := Result + ' Where ' + S; end; end; {-----------------------------------------} If SqlClause.groupby.Count > 0 then begin S := ''; For i := 0 to SqlClause.groupby.Count - 1 do If trim(SqlClause.groupby[i]) <> '' then S := S + SqlClause.groupby[i] + ' and '; If s <> '' then begin Delete(S,length(S)-3,4); Result := Result + ' group by ' + S; end; end; {----------------------------------------} If SqlClause.having.Count > 0 then begin S := ''; For i := 0 to SqlClause.having.Count - 1 do If trim(SqlClause.having[i]) <> '' then S := S + SqlClause.having[i] + ' and '; If s <> '' then begin Delete(S,length(S)-3,4); Result := Result + ' Having ' + S; end; end; {-----------------------------------------} If SqlClause.orderby.Count > 0 then begin S := ''; For i := 0 to SqlClause.orderby.Count - 1 do If trim(SqlClause.orderby[i]) <> '' then S := S + SqlClause.orderby[i] + ', '; If s <> '' then begin Delete(S,length(S)-1,2); Result := Result + ' order by ' + S; end; end; end; {******************************************************************************} Function ALSQLFromLstUpdateSqlClause(SqlClause: TAlLstUpdateSQLClause): String; var i : integer; S1, S2 : String; Begin {----Update------------------} If SqlClause.Update then Begin Result := ''; for i := 0 to SqlClause.Value.Count- 1 do If Trim(SqlClause.Value[i]) <> '' then Result := Result + trim(SqlClause.Value[i]) + ', '; delete(Result,length(result)-1,2); if result = '' then exit; Result := 'Update ' + SqlClause.Table + ' Set ' + result; If SqlClause.where.Count > 0 then begin Result := Result + ' Where '; For i := 0 to SqlClause.where.Count - 1 do If trim(SqlClause.where[i]) <> '' then Result := Result + '(' + trim(SqlClause.where[i]) + ') and '; delete(Result,length(result)-3,4); end; end {-Insert-} else Begin S1 := ''; S2 :=''; for i := 0 to SqlClause.Value.Count-1 do If Trim(SqlClause.Value[i]) <> '' then begin S1 := S1 + trim(SqlClause.Value.Names[i]) + ', '; S2 := S2 + trim(SqlClause.Value.ValueFromIndex[i]) + ', '; end; delete(S1,length(S1)-1,2); delete(S2,length(S2)-1,2); If (S1='') or (S2='') then begin result := ''; exit; end; Result := 'Insert into ' + SqlClause.Table + ' (' + S1 + ') Values (' + s2 + ')'; end; end; end.
(*------------------------------------------------------------------------------ PacketTypes Tsusai 2006 Types used with communications are listed here. TBuffer : Basic Buffer TCBuffer : Used for string buffer procedures TThreadLink : Used for linking accounts or characters to the client socket -- Revisions: -------------------------------------------------------------------------------- [2007/03/28] CR - Cleaned up uses clauses, using Icarus as a guide. // December 26th, 2007 - Tsusai - Removed TMD5String class. ------------------------------------------------------------------------------*) unit PacketTypes; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} //none {Project} Account, Character, CharacterServerInfo, Database, ZoneServerInfo, CharAccountInfo, {3rd Party} IdContext ; type TBufSize = 0..(High(Word) div 2); TBuffer = array[TBufSize] of Byte; TCBuffer = array[TBufSize] of Char; TReadPts = array of TBufSize; TThreadLink = class Parent : TIdContext; DatabaseLink : TDatabase; Constructor Create(AClient : TIdContext); Destructor Destroy();override; end; TClientLink = class(TThreadLink) AccountLink : TAccount; CharacterLink : TCharacter; AccountInfo : TCharAccountInfo; Transfering : Boolean; NewCharName : String; EncKey1 : LongWord; EncKey2 : LongWord; procedure InitializeMessageID(const Key1,Key2:LongWord); function DecryptMessageID(const ID:Word):Word; constructor Create(AClient : TIdContext); Destructor Destroy();override; end; TCharaServerLink = class(TThreadLink) Info : TCharaServerInfo; Destructor Destroy();override; end; TZoneServerLink = class(TThreadLink) Info : TZoneServerInfo; Destructor Destroy();override; end; Function ReadPoints( Args : array of Word ) : TReadPts; implementation uses {RTL/VCL} Math {Project} //none {3rd Party} //none ; (*-----------------------------------------------------------------------------* Func ReadPoints -- Overview: -- TODO -- Pre: TODO Post: TODO -- Revisions: -- [2005/07/10] CR - Added Comment Header [yyyy/mm/dd] <Author> - <Comment> *-----------------------------------------------------------------------------*) Function ReadPoints( Args : array of Word ) : TReadPts; Var Idx : Integer; Begin SetLength(Result, Length(Args)); for Idx := Low(Args) to High(Args) do begin Result[Idx] := EnsureRange(Args[Idx], 0, High(TBufSize)); end; End; (* Func ReadPoints *-----------------------------------------------------------------------------*) Constructor TThreadLink.Create(AClient : TIdContext); begin inherited Create; Parent := AClient; end; Destructor TThreadLink.Destroy; begin inherited; end; constructor TClientLink.Create(AClient : TIdContext); begin inherited Create(AClient); EncKey1 := 0; EncKey2 := 0; NewCharName := ''; end; procedure TClientLink.InitializeMessageID(const Key1,Key2:LongWord); var TemporaryCode : array[1..8] of Byte; ShiftTemporary : LongWord; Index : Byte; AWord : LongWord; begin ShiftTemporary := Key1; for Index := 8 downto 1 do begin TemporaryCode[Index] := ShiftTemporary AND $F; ShiftTemporary := ShiftTemporary shr 4; end; AWord := (TemporaryCode[6] shl 12) + (TemporaryCode[4] shl 8) + (TemporaryCode[7] shl 4) + (TemporaryCode[1]); EncKey1 := (TemporaryCode[2] shl 12) + (TemporaryCode[3] shl 8) + (TemporaryCode[5] shl 4) + (TemporaryCode[8]); EncKey2 := ((((EncKey1 mod $F3AC) + AWord) shl 16) or ((EncKey1 mod $49DF)+EncKey1)) mod Key2; end; function TClientLink.DecryptMessageID(const ID:Word):Word; begin EncKey1 := (($343FD * EncKey1) + EncKey2) AND $FFFFFFFF; Result := (ID mod ((EncKey1 shr 16) and $7FFF)) and $FFF; end; Destructor TClientLink.Destroy; begin if Assigned(AccountLink) then begin AccountLink.Free; end; //We do NOT own the characters, only the zone's character list does. We don't //free them here. inherited; end; Destructor TCharaServerLink.Destroy; begin if Assigned(Info) then begin Info.Free; end; inherited; end; Destructor TZoneServerLink.Destroy; begin if Assigned(Info) then begin Info.Free; end; inherited; end; end.
unit uTroco; interface type TCedula = ( CeNota100, CeNota50, CeNota20, CeNota10, CeNota5, CeNota2, CeMoeda100, CeMoeda50, CeMoeda25, CeMoeda10, CeMoeda5, CeMoeda1 ); TTroco = class private FTipo: TCedula; FQuantidade: Integer; public constructor Create( Tipo: TCedula; Quantidade: Integer ); reintroduce; function GetTipo: TCedula; function GetQuantidade: Integer; function GetvalorCedula( Tipo: TCedula ): Double; procedure SetQuantidade( Quantidade: Integer ); end; const CValorCedula: array [ TCedula ] of Double = ( 100, 50, 20, 10, 5, 2, 1, 0.5, 0.25, 0.1, 0.05, 0.01 ); implementation constructor TTroco.Create( Tipo: TCedula; Quantidade: Integer ); begin inherited Create; FTipo := Tipo; FQuantidade := Quantidade; end; function TTroco.GetTipo: TCedula; begin Result := FTipo; end; function TTroco.GetvalorCedula( Tipo: TCedula ): Double; begin Result := CValorCedula[ Tipo ]; end; function TTroco.GetQuantidade: Integer; begin Result := FQuantidade; end; procedure TTroco.SetQuantidade( Quantidade: Integer ); begin FQuantidade := Quantidade; end; end.
unit CluesConfig; interface uses Classes, Generics.Collections; type TCluesConfig = class _config : TDictionary<string, string>; _history : TStringList; _name : string; // filename of the config file _sourcePath : string; // folder where clue stores the output (usually the folder where the exe can be found) _basePath : string; // target folder for processed data _folderPattern : string; _startNum : integer; _valid, _changed: Boolean; private function getLastDir: integer; function getPattern(pattern: string; start: integer): string; procedure save; procedure load; procedure setFolderPattern(folderPattern: string); procedure setStartNum(startNum: string); function getProperty(key : string) : string; procedure setProperty(key: string; const Value: string); function configKeys: TStrings; function getSourcePath: string; function getPatternProp: string; public constructor Create(configname : string); destructor Destroy; override; function getScenarioFolder : string; function getStartNumAsString: string; property configname : string read _name write _name; property sourceFolder : string read getSourcePath; property startNum : integer read _startNum write _startNum; procedure nextFolder; property isValid : boolean read _valid; property item[key : string] : string read getProperty write setProperty; property keys : TStrings read configKeys; property history : TStringList read _history; property pattern : string read getPatternProp write setFolderPattern; end; var config : TCluesConfig; implementation uses typinfo, sysutils, ioutils, system.types, json.types, json.readers, json.writers, regularexpressions, math; type // scenario folders look like: <name-part>_<number-part> TScenarioFolderFilter = class _pattern : string; _regex : TRegEx; _match : TMatch; _value : integer; public constructor Create(folderPattern : string); function accept(foldername : string) : boolean; property value : integer read _value; end; constructor TScenarioFolderFilter.Create(folderPattern : string); var name_part : string; begin // first determine the <name-part> and use that for the following matches // this allows for multiple scenario setups in the same folder _regex := TRegEx.Create('([a-zA-Z_]*)_([0-9]{0,9})'); _match := _regex.Match(folderPattern); // reset the regex to use the pattern based on the user provided name-part if _match.Success then begin name_part := _match.Groups.Item[1].Value; _pattern := '(' + name_part + '_)([0-9]{0,9})'; _regex := TRegEx.Create(_pattern); end; end; function TScenarioFolderFilter.accept(foldername : string): boolean; begin _value := -1; _match := _regex.Match(foldername); accept := _match.Success; if _match.Success then _value := StrToInt(_match.Groups.Item[2].Value); end; //--------------------- TCluesConfig -------------------- function TCluesConfig.configKeys: TStrings; var key : string; ts : TStringList; begin ts := TStringList.Create; for key in _config.Keys do ts.Add(key); result := ts; end; constructor TCluesConfig.Create(configname : string); begin _config := TDictionary<string, string>.Create; _history := TStringList.Create; _name := configname; // apply some defaults, possibly overruled by the load _folderPattern := 'scen_00001'; _startNum := 1; _valid := false; load; _changed := false; end; function TCluesConfig.getScenarioFolder: string; begin Result := IncludeTrailingPathDelimiter(_basePath) + getPattern(_folderPattern, _startNum); end; function TCluesConfig.getSourcePath: string; begin result := ExpandFileName(_config.Items['CluesOutputFolder']); end; destructor TCluesConfig.Destroy; begin save; _config.Free; inherited; end; function TCluesConfig.getProperty(key : string) : string; begin if _config.ContainsKey(key) then getProperty := _config[key] else getProperty := ''; end; procedure TCluesConfig.setProperty(key: string; const Value: string); begin // don't allow setting of empty values if length(Value) = 0 then exit; if key = 'CluesOutputFolder' then _sourcePath := Value; if key = 'BaseDestinationFolder' then _basePath := Value; if key = 'SubfolderPattern' then _folderPattern := Value; if _config.ContainsKey(key) then begin if _config[key] <> value then begin _config[key] := Value; _changed := true; end; end else begin _config.Add(key, Value); _changed := true; end; end; function TCluesConfig.getStartNumAsString : string; begin getStartNumAsString := intToStr(_startNum); end; procedure TCluesConfig.load; var reader : TJsonTextReader; str_read : TStreamReader; stream : TFileStream; key : string; value : string; isPair : boolean; curDir : string; begin if FileExists(_name) then begin stream := TFileStream.Create(_name, fmOpenRead); str_read := TStreamReader.Create(stream); reader := TJsonTextReader.Create(str_read); try // very simple configuration reader, should be adapted to the actual structure. while reader.read do begin case reader.TokenType of TJsonToken.startobject: begin end; TJsonToken.PropertyName : begin isPair := true; key := reader.Value.AsString; end; TJsonToken.String : begin value := reader.Value.AsString; _config.Add(key, value); isPair := false; end; TJsonToken.EndObject: begin end; end; end finally reader.Close; str_read.Free; stream.Free; end; curDir := GetCurrentDir; if _config.ContainsKey('CluesOutputFolder') then _sourcePath := ExpandFileName(_config.Items['CluesOutputFolder']); if _config.ContainsKey('BaseDestinationFolder') then begin _basePath := ExpandFileName(_config.Items['BaseDestinationFolder']); if DirectoryExists(_basePath) then _startNum := getLastDir + 1; end; if _config.ContainsKey('SubfolderPattern') then _folderPattern := _config.items['SubfolderPattern']; end; _valid := DirectoryExists(_basePath); end; procedure TCluesConfig.setStartNum(startNum : string); var value : integer; begin try value := StrToInt(startNum); except on EConvertError do value := 0; end; _startNum := value; end; procedure TCluesConfig.setFolderPattern(folderPattern : string); begin _folderPattern := folderPattern; item['SubfolderPattern'] := _folderPattern; _startNum := getLastDir + 1; // recalc startnum, update folder list. end; function TCluesConfig.getPattern(pattern : string; start : integer) : string; var regex : TRegEx; match : TMatch; namePattern, numPattern : string; len : integer; begin regex := TRegEx.Create('([a-zA-Z_]*)([0]{0,9})'); match := regex.Match(pattern); namePattern := ''; len := 5; if match.Success then begin namePattern := match.Groups.Item[1].Value; numPattern := match.Groups.Item[2].Value; if length(pattern) > 0 then len := length(numPattern); end; if start > 0 then namePattern := namePattern + Format('%.*d', [len, start]) else namePattern := namePattern + '00123456789'.substring(0, len); getPattern := namePattern; end; function TCluesConfig.getPatternProp: string; begin getPatternProp := _folderPattern; end; // Get the highest scenarionumber from the folder names matching the folder pattern // The path should exist! function TCluesConfig.getLastDir : integer; var filter : TScenarioFolderFilter; max, value : integer; i : integer; folders : TStringDynArray; begin if length(_folderPattern) = 0 then getLastDir := 1; if _history.Count > 0 then _history.Clear; folders := TDirectory.getDirectories(_basePath); filter := TScenarioFolderFilter.Create(_folderPattern); max := 0; for i := 0 to length(folders) - 1 do begin if filter.accept(folders[i]) then begin value := filter.value; _history.Add(ExpandFileName(folders[i])); if value > max then max := value; end; end; _history.Sort; // A to Z getLastDir := max; end; procedure TCluesConfig.save; var writer : TJsonTextWriter; stream : TFileStream; key : string; begin if not _changed then exit; stream := TFileStream.Create(_name, fmOpenWrite or fmCreate); writer := TJsonTextWriter.Create(stream); writer.Formatting := TJsonFormatting.Indented; try writer.WriteStartObject; writer.WritePropertyName('Configuration'); writer.WriteStartObject; for key in _config.keys do begin writer.WritePropertyName(key); writer.WriteValue(_config.items[key]); end; writer.WriteEndObject; writer.WriteEndObject; finally writer.Close; stream.Free; end; end; procedure TCluesConfig.nextFolder; begin inc(_startNum); end; initialization finalization config.Free; end.
//модуль системных подпрограмм и типов данных // unit sysfun; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls; //<-------------------------------------------------------------------------->\\ //<-------------------------------ТИПЫ ДАННЫХ-------------------------------->\\ //<-------------------------------------------------------------------------->\\ type TGameState = (gs_MainMenu, gs_Pause, gs_IngameMenu, gs_GameOver, gs_Shutdown, gs_Editor); //тип возможных состояний игры: Главное меню, Пауза, Внутриигровое меню, Конец игры, Выход, Редактор //<-------------------------------------------------------------------------->\\ //<------------------------------ПОДПРОГРАММЫ-------------------------------->\\ //<-------------------------------------------------------------------------->\\ procedure GameLoop (gs: TGameState); //основая подпрограмма игрового цикла implementation //процедура основного игрового цикла procedure GameLoop (gs: TGameState); begin case gs of gs_MainMenu: begin {place Main Menu state code here} end; gs_Pause: begin {place Pause state code here} end; gs_IngameMenu: begin {place In-game Menu state code here} end; gs_GameOver: begin {place Game Over state code here} end; gs_Shutdown: begin {place Shutdown state code here} end; gs_Editor: begin {place Editor state code here} end; else end; end; end.
object AboutBox: TAboutBox Left = 368 Top = 298 ActiveControl = OKButton BorderStyle = bsDialog Caption = 'About' ClientHeight = 242 ClientWidth = 346 Color = clBtnFace DefaultMonitor = dmMainForm Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] FormStyle = fsStayOnTop OldCreateOrder = False Position = poMainFormCenter PixelsPerInch = 96 TextHeight = 13 object Panel1: TPanel Left = 0 Top = 0 Width = 346 Height = 242 Align = alClient BevelInner = bvRaised BevelOuter = bvLowered TabOrder = 0 ExplicitHeight = 249 object ProductName: TLabel Left = 6 Top = 4 Width = 221 Height = 13 Caption = 'Settings utility for SUPER_WDX content plugin' IsControl = True end object Version: TLabel Left = 3 Top = 56 Width = 340 Height = 13 Alignment = taCenter AutoSize = False Caption = 'Version/'#1042#1077#1088#1089#1080#1103': 2.3b (26.12.08)' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [fsBold] ParentFont = False IsControl = True end object Copyright: TLabel Left = 8 Top = 80 Width = 136 Height = 13 Caption = 'Deverlopers/'#1056#1072#1079#1088#1072#1073#1086#1090#1095#1080#1082#1080':' IsControl = True end object Label1: TLabel Left = 6 Top = 25 Width = 318 Height = 13 Caption = #1055#1088#1086#1075#1088#1072#1084#1084#1072' '#1085#1072#1089#1090#1088#1086#1081#1082#1080' '#1076#1083#1103' '#1082#1086#1085#1090#1077#1085#1090#1085#1086#1075#1086' '#1087#1083#1072#1075#1080#1085#1072' SUPER_WDX' IsControl = True end object Label2: TLabel Left = 144 Top = 96 Width = 126 Height = 13 Caption = 'Pavel Dubrovsky aka D1P' IsControl = True end object Label3: TLabel Left = 144 Top = 116 Width = 126 Height = 13 Caption = 'Vorotilin Dmitry aka Genius' IsControl = True end object Label4: TLabel Left = 8 Top = 136 Width = 133 Height = 13 Caption = 'Thanks to/'#1041#1083#1072#1075#1086#1076#1072#1088#1085#1086#1089#1090#1080':' IsControl = True end object Label5: TLabel Left = 144 Top = 150 Width = 75 Height = 13 Caption = 'Christian Ghisler' end object Label6: TLabel Left = 144 Top = 165 Width = 130 Height = 13 Caption = 'Andrey Pyasetsky aka Ergo' end object Label7: TLabel Left = 144 Top = 180 Width = 29 Height = 13 Caption = 'Alextp' end object Label8: TLabel Left = 144 Top = 195 Width = 31 Height = 13 Caption = 'Zhang' end object Label9: TLabel Left = 144 Top = 210 Width = 38 Height = 13 Caption = 'Xcaliber' end object Label10: TLabel Left = 144 Top = 224 Width = 45 Height = 13 Caption = 'Raymond' end end object OKButton: TButton Left = 273 Top = 212 Width = 65 Height = 26 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 1 OnClick = OKButtonClick IsControl = True end end
unit SignalSystem; {$mode delphi} interface uses SysUtils, Graphics, Classes, LCLIntf, Contnrs, Entity, TrafficSignal; type TSignalSystemState = Integer; TSignalSystemEntity = class(TEntity) protected LastShift: LongInt; SignalList: TFPObjectList; State: TSignalSystemState; Announced: Boolean; AllRed: Boolean; NextStateIn: LongInt; procedure Shift; function GetSignal(id: String): TSignalEntity; public constructor Create; function Think: Boolean; override; procedure AddSignal(Signal: TSignalEntity); property Signals[id: String]: TSignalEntity read GetSignal; end; implementation constructor TSignalSystemEntity.Create; begin self.SignalList := TFPObjectList.Create; self.AllRed := true; end; procedure TSignalSystemEntity.AddSignal; begin self.SignalList.Add(Signal); end; function TSignalSystemEntity.GetSignal; var i: Integer; s: TSignalEntity; begin for i := 0 to self.SignalList.Count - 1 do begin s := self.SignalList.Items[i] as TSignalEntity; if s.ID = ID then Result := s; end; end; function TSignalSystemEntity.Think; var Now: LongInt; begin Now := GetTickCount; if Now - self.LastShift > self.NextStateIn then begin self.Shift; self.LastShift := Now; end; Result := True; end; procedure TSignalSystemEntity.Shift; begin if self.AllRed then begin self.Signals['einbahn1'].Sequence := Stop; self.Signals['einbahn2'].Sequence := Stop; self.Signals['haupt1'].Sequence := Stop; self.Signals['haupt2'].Sequence := Stop; self.Signals['fuss1'].Sequence := Stop; self.Signals['fuss2'].Sequence := Stop; self.Signals['fuss3'].Sequence := Stop; self.Signals['fuss4'].Sequence := Stop; self.NextStateIn := 5000; end else begin inc(self.State); if self.State > 2 then self.State := 1; case self.State of 1: begin self.Signals['haupt1'].Sequence := Go; self.Signals['haupt2'].Sequence := Go; self.Signals['einbahn1'].Sequence := Stop; self.Signals['einbahn2'].Sequence := Stop; self.Signals['fuss1'].Sequence := Go; self.Signals['fuss2'].Sequence := Go; self.Signals['fuss3'].Sequence := Stop; self.Signals['fuss4'].Sequence := Stop; end; 2: begin self.Signals['haupt1'].Sequence := Stop; self.Signals['haupt2'].Sequence := Stop; self.Signals['einbahn1'].Sequence := Go; self.Signals['einbahn2'].Sequence := Go; self.Signals['fuss1'].Sequence := Stop; self.Signals['fuss2'].Sequence := Stop; self.Signals['fuss3'].Sequence := Go; self.Signals['fuss4'].Sequence := Go; end; end; self.NextStateIn := 5000; end; self.AllRed := not self.AllRed; end; end.
unit CFMMTimer; interface uses Windows, Classes, MMSystem, TypInfo; type TCFMMTimer = class(TObject) private FInternal: Cardinal; // 定时器的间隔时间,单位为毫秒,默认为1000毫秒 FEnable: Boolean; // 定时器是否在运行,默认为FALSE FProcCallback: TFnTimeCallback; // 回调函数指针 FOnTimer: TNotifyEvent; // 周期回调时触发的定时器事件 FHTimerID: Integer; // 定时器ID停止定时器使用 procedure SetInternal(const Value: Cardinal); procedure SetEnable(const Value: Boolean); public property Internal: Cardinal read FInternal write SetInternal default 1000; property Enable: Boolean read FEnable write SetEnable default FALSE; property OnTimer: TNotifyEvent read FOnTimer write FOnTimer; constructor Create; destructor Destroy; override; end; implementation { TCFMMTimer } procedure DoTimer(uTimerID, uMessage: UINT; dwUser, dw1, dw2: DWORD_PTR) stdcall; var vObj: TCFMMTimer; begin vObj := TCFMMTimer(dwUser); // dwUser实际上是定时器对象的地址 ?? if Assigned(vObj.OnTimer)then vObj.OnTimer(vObj); end; constructor TCFMMTimer.Create; begin inherited Create; FInternal := 1000; // 默认为1秒 FEnable := False; // 创建并不启动定时器 FOnTimer := nil; FProcCallback := DoTimer; // 对象中的函数指针只有一个,需要考虑利用dwUser来区分不同的对象函数回调 end; destructor TCFMMTimer.Destroy; begin SetEnable(False); inherited Destroy; end; procedure TCFMMTimer.SetEnable(const Value: Boolean); begin if FEnable <> Value then begin FEnable := Value; if FEnable then FHTimerID := TimeSetEvent(FInternal, 0, FProcCallback, Integer(Self), 1 ) // 这里把对象地址传入,回调时传回,最后一个参数表示周期回调,第二个参数0为最高精度 else TimeKillEvent( FHTimerID ); end; end; procedure TCFMMTimer.SetInternal(const Value: Cardinal); begin if FInternal <> Value then begin FInternal := Value; if FEnable then // 如果定时器已经启动并更改周期时长则需要先停止再重新启动定时器 begin Enable := False; Enable := True; end; end; end; end.
unit Demo.BaseFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIFrame, DB, uniGUIBaseClasses, uniPanel, System.Actions, Vcl.ActnList, uniMemo, uniSyntaxEditorEx, uniSyntaxEditorBase, uniToolBar, cfs.GCharts.uniGUI, Vcl.Menus, uniMainMenu; type TDemoBaseFrame = class(TUniFrame) ActionList1: TActionList; actRun: TAction; actShowDelphiCode: TAction; UniToolBar1: TUniToolBar; UniToolButton1: TUniToolButton; UniToolButton2: TUniToolButton; MainPanel: TUniPanel; ResultPanel: TUniPanel; DelphiPanel: TUniPanel; panDelphiCode: TUniPanel; DelphiCode: TUniSyntaxEditEx; actGoogleGuide: TAction; SourhPanel: TUniPanel; panEvents: TUniPanel; EventsMemo: TUniMemo; CenterPanel: TUniPanel; ChartsPanel: TUniPanel; UniToolButton5: TUniToolButton; actShowHTML: TAction; UniToolButton6: TUniToolButton; actClearMemo: TAction; UniPopupMenu: TUniPopupMenu; iclassfabfahtml5inbspHTMLnbsp1: TUniMenuItem; actRefresh: TAction; UniToolButton3: TUniToolButton; procedure UniFrameCreate(Sender: TObject); procedure actShowDelphiCodeExecute(Sender: TObject); procedure actGoogleGuideExecute(Sender: TObject); procedure actShowHTMLExecute(Sender: TObject); procedure actClearMemoExecute(Sender: TObject); procedure EventsMemoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure actRefreshExecute(Sender: TObject); private FGChartsFrame: TuniGChartsFrame; FGoogleGuideLink: string; FHtml: string; procedure LoadUnitName(const UnitName: string); procedure BeforeDocumentPost(Sender: TComponent; var HTMLDocument: string); procedure OnSelectEvent(Sender: TuniGChartsFrame; const ChartId, Row, Column, Value, Category: string); protected procedure CreateDynamicComponents; dynamic; procedure GenerateChart; dynamic; abstract; property GChartsFrame: TuniGChartsFrame read FGChartsFrame; public property GoogleGuideLink: string read FGoogleGuideLink write FGoogleGuideLink; end; implementation {$R *.dfm} uses uniGUIVars, MainModule, uniGUIApplication; procedure TDemoBaseFrame.UniFrameCreate(Sender: TObject); begin LoadUnitName(UnitName); FGChartsFrame := TuniGChartsFrame.Create(Self); FGChartsFrame.Parent := ChartsPanel; FGChartsFrame.OnSelect := OnSelectEvent; FGChartsFrame.BeforeDocumentPost := BeforeDocumentPost; FGChartsFrame.AutoResize := True; //FGChartsFrame.BorderStyle := TUniBorderStyle.ubsNone; DelphiCode.BorderStyle := TUniBorderStyle.ubsNone; CreateDynamicComponents; GenerateChart; end; procedure TDemoBaseFrame.actClearMemoExecute(Sender: TObject); begin EventsMemo.Lines.Text := ''; end; procedure TDemoBaseFrame.actGoogleGuideExecute(Sender: TObject); begin if GoogleGuideLink <> '' then UniSession.AddJS('window.open(' + GoogleGuideLink.QuotedString + ', ''_blank'');'); end; procedure TDemoBaseFrame.actRefreshExecute(Sender: TObject); begin GenerateChart; end; procedure TDemoBaseFrame.actShowDelphiCodeExecute(Sender: TObject); begin DelphiPanel.Collapsed := not DelphiPanel.Collapsed; end; procedure TDemoBaseFrame.actShowHTMLExecute(Sender: TObject); begin if SourhPanel.Collapsed then SourhPanel.Collapsed := False; EventsMemo.Lines.Text := FHtml + sLineBreak + sLineBreak; end; procedure TDemoBaseFrame.BeforeDocumentPost(Sender: TComponent; var HTMLDocument: string); begin FHtml := HTMLDocument; end; procedure TDemoBaseFrame.CreateDynamicComponents; begin end; procedure TDemoBaseFrame.EventsMemoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbRight then uniPopupMenu.Popup(X, Y, EventsMemo); end; procedure TDemoBaseFrame.LoadUnitName(const UnitName: string); var UN: string; FileName: string; begin UN := UnitName + '.pas'; DelphiPanel.Title := 'Delphi Code'; {$ifdef RELEASE} FileName := ExpandFileName(ExtractFileDir(Application.ExeName) + '\GChartsDemoSamplesSource\' + UN); {$else} FileName := ExpandFileName(ExtractFileDir(Application.ExeName) + '\..\..\' + UN); {$endif} if FileExists(FileName) then Self.DelphiCode.Lines.LoadFromFile(FileName) else Self.DelphiCode.Lines.Text := '// Source file not found: ' + FileName; end; procedure TDemoBaseFrame.OnSelectEvent(Sender: TuniGChartsFrame; const ChartId, Row, Column, Value, Category: string); begin EventsMemo.Lines.Add(Format('Select: ChartId=%s, Row=%s, Column=%s, Value=%s, Category=%s', [ChartId, Row, Column, Value, Category])); if SourhPanel.Collapsed then SourhPanel.Collapsed := False; end; end.
unit PKCS11LibrarySelectDlg; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SDUForms, ComCtrls, SDUComCtrls, StdCtrls, PKCS11KnownLibs; type TPKCS11LibrarySelectDialog = class(TSDUForm) Label1: TLabel; pbOK: TButton; pbCancel: TButton; lvLibraries: TSDListView; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure pbOKClick(Sender: TObject); procedure lvLibrariesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); protected FKnownLibs: array of TPKCS11KnownLibrary; FSelectedLibrary: TPKCS11KnownLibrary; procedure AddCol(colCaption: string); public procedure Add(lib: TPKCS11KnownLibrary); procedure EnableDisableControls(); published property SelectedLibrary: TPKCS11KnownLibrary read FSelectedLibrary; end; implementation {$R *.dfm} uses SDUi18n, SDUGeneral; procedure TPKCS11LibrarySelectDialog.Add(lib: TPKCS11KnownLibrary); begin SetLength(FKnownLibs, length(FKnownLibs)+1); FKnownLibs[length(FKnownLibs)-1] := lib; end; procedure TPKCS11LibrarySelectDialog.AddCol(colCaption: string); var newCol: TListColumn; begin newCol := lvLibraries.columns.Add(); newCol.Caption := colCaption; // Note: DON'T set AutoSize to TRUE; otherwise if the user resizes the // dialog, any user set column widths will be reverted // (n/a in our case) newCol.AutoSize := TRUE; end; procedure TPKCS11LibrarySelectDialog.EnableDisableControls(); begin SDUEnableControl(pbOK, (lvLibraries.SelCount = 1)); end; procedure TPKCS11LibrarySelectDialog.FormShow(Sender: TObject); var i: integer; begin AddCol(_('Library')); AddCol(_('Description')); lvLibraries.ResizeColumns(); for i:=low(FKnownLibs) to high(FKnownLibs) do begin lvLibraries.AppendRow( [ FKnownLibs[i].DLLFilename, PKCS11KnownLibraryPrettyDesc(FKnownLibs[i]) ], Pointer(i) ); end; EnableDisableControls(); end; procedure TPKCS11LibrarySelectDialog.FormCreate(Sender: TObject); begin lvLibraries.RowSelect := TRUE; end; procedure TPKCS11LibrarySelectDialog.pbOKClick(Sender: TObject); var arrIdx: integer; begin arrIdx := integer(lvLibraries.Items[lvLibraries.SelectedIdx].Data); FSelectedLibrary := FKnownLibs[arrIdx]; ModalResult := mrOK; end; procedure TPKCS11LibrarySelectDialog.lvLibrariesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin EnableDisableControls(); end; END.
unit UnitSlideShowUpdateInfoThread; interface uses ActiveX, Classes, SysUtils, DB, uThreadForm, uThreadEx, uMemory, uDBConnection, uDBContext, uDBEntities, uExifUtils, uConstants; type TSlideShowUpdateInfoThread = class(TThreadEx) private { Private declarations } FContext: IDBContext; FFileName: string; DS: TDataSet; FInfo: TMediaItem; protected procedure Execute; override; procedure DoUpdateWithSlideShow; procedure DoSetNotDBRecord; procedure SetNoInfo; public constructor Create(AOwner: TThreadForm; AState: TGUID; Context: IDBContext; FileName: string); destructor Destroy; override; end; implementation uses SlideShow; { TSlideShowUpdateInfoThread } constructor TSlideShowUpdateInfoThread.Create(AOwner: TThreadForm; AState: TGUID; Context: IDBContext; FileName: string); begin inherited Create(AOwner, AState); FContext := Context; FFileName := FileName; FInfo := nil; end; destructor TSlideShowUpdateInfoThread.Destroy; begin F(FInfo); inherited; end; procedure TSlideShowUpdateInfoThread.DoSetNotDBRecord; begin ViewerForm.DoSetNoDBRecord(FInfo); end; procedure TSlideShowUpdateInfoThread.DoUpdateWithSlideShow; begin ViewerForm.DoUpdateRecordWithDataSet(FFileName, DS); end; procedure TSlideShowUpdateInfoThread.Execute; begin inherited; FreeOnTerminate := True; CoInitializeEx(nil, COM_MODE); try DS := FContext.CreateQuery(dbilRead); try SetSQL(DS, 'SELECT * FROM $DB$ WHERE FolderCRC = ' + IntToStr(GetPathCRC(FFileName, True)) + ' AND FFileName LIKE :FFileName'); SetStrParam(DS, 0, AnsiLowerCase(FFileName)); try OpenDS(DS); except SetNoInfo; Exit; end; if DS.RecordCount = 0 then SetNoInfo else SynchronizeEx(DoUpdateWithSlideShow); finally FreeDS(DS); end; finally CoUninitialize; end; end; procedure TSlideShowUpdateInfoThread.SetNoInfo; begin FInfo := TMediaItem.CreateFromFile(FFileName); UpdateImageRecordFromExif(FInfo, False); SynchronizeEx(DoSetNotDBRecord); end; end.
//*****************************************// // Carlo Pasolini // // http://pasotech.altervista.org // // email: cdpasop@hotmail.it // //*****************************************// //this is the CodeInjection Unit: it supplies the kernel of Code Injection //implementation unit uCodeInjection; interface uses Windows;//, KOL;//, SysUtils, Classes; function SizeOfProc(pAddr: pointer): Cardinal; function OpenProcessEx(dwDesiredAccess: Cardinal; bInheritableHandle: LongBool; dwProcessId: Cardinal): Cardinal; function RemoteGetModuleHandle(hProcess: Cardinal; nomeModulo: PAnsiChar; var BaseAddr: Cardinal): Boolean; function RemoteGetProcAddress(hProcess: Cardinal; hModule: Cardinal; ProcName: PAnsiChar; var FuncAddress: Cardinal): Boolean; function InjectData(hProcess: Cardinal; localData: Pointer; DataSize: Cardinal; Esecuzione: Boolean; var remoteData: Pointer): Boolean; function UnloadData(hProcess: Cardinal; remoteData: Pointer): Boolean; function InjectThread(hProcess: Cardinal; remoteFunction: Pointer; remoteParameter: Pointer; var outputValue: Cardinal; var errorCode: Cardinal; Synch: Boolean): Boolean; implementation uses uDecls;//, uUtils; function Int2Str(I: integer): string; begin Str(I, Result); end; function Str2Int(S: string): integer; begin Val(S, Result, Result); end; //SizeOfProc: this function returns the Size in bytes of a function //whose implementation begins at address "pAddr" function SizeOfProc(pAddr: pointer): Cardinal; var dwSize: Cardinal; begin dwSize := 0; repeat inc(dwSize); until PByte(Cardinal(pAddr)+dwSize-1)^ = $C3; Result := dwSize; end; //ModifyPrivilege: this function enables (fEnable = true) or disable (fEnable = false) //a Privilege //http://pasotech.altervista.org/delphi/articolo23.htm //(nell'articolo l'implementazione è più elementare; quella che viene presentata //di seguito invece è completa di tutto function ModificaPrivilegio(szPrivilege: pChar; fEnable: Boolean): Boolean; var NewState: TTokenPrivileges; luid: TLargeInteger; hToken: Cardinal; ReturnLength: Cardinal; begin Result := False; hToken := 0; try if not OpenThreadToken( GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, False, hToken) then begin if GetLastError = ERROR_NO_TOKEN then begin if not OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, hToken) then begin //ErrStr('OpenProcessExToken'); Exit; end; end else begin //ErrStr('OpenThreadToken'); Exit; end; end; //ricavo il LUID (Locally Unique Identifier) corrispondente al privilegio //specificato: si tratta in sostanza di un identificativo univoco del privilegio; //varia da sessione a sessione ed anche tra un riavvio e l' altro del sistema if not LookupPrivilegeValue(nil, szPrivilege, luid) then begin //ErrStr('LookupPrivilegeValue'); Exit; end; //lavoro su NewState (di tipo TTokenPrivileges). Rappresenta un elenco di privilegi; //nel caso specifico conterrà un solo privilegio (ProvilegeCount = 1). L' arrary //Privileges contiene oggetti con 2 campi: il luid del privilegio (Luid) ed //il livello di abilitazione del medesimo (Attributes) NewState.PrivilegeCount := 1; NewState.Privileges[0].Luid := luid; if fEnable then //abilitiamo il privilegio NewState.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED else //disabilitiamo il privilegio NewState.Privileges[0].Attributes := 0; //eseguiamo la modifica sullo stato di abilitazione del privilegio //nel contesto del token di accesso aperto if not AdjustTokenPrivileges( hToken, FALSE, NewState, sizeof(NewState), nil, ReturnLength) then begin //ErrStr('AdjustTokenPrivileges'); Exit; end; Result := True; finally //chiudo l' handle al token di accesso aperto if hToken <> 0 then begin if not CloseHandle(hToken) then begin //ErrStr('CloseHandle'); end; end; end; end; //Variante dell' api win32 OpenProcess: se la OpenProcess fallisce, allora tenta //di abilitare il privilegio di debug ed in caso di successo richiama la OpenProcess function OpenProcessEx(dwDesiredAccess: Cardinal; bInheritableHandle: LongBool; dwProcessId: Cardinal): Cardinal; var hProcess: Cardinal; begin hProcess := OpenProcess(dwDesiredAccess, bInheritableHandle, dwProcessId); //provo ad ottenere un handle al processo if hProcess = 0 then //se non ci riesco provo ad assegnare il privilegio di debug begin if ModificaPrivilegio('SeDebugPrivilege', True) then begin hProcess := OpenProcess(dwDesiredAccess, bInheritableHandle, dwProcessId); end; end; result := hProcess; end; //Restituisce l'indirizzo del Process Environment Block //N.B. il PEB si trova sempre all'indirizzo 7ffdf000 (Vista escluso) //http://pasotech.altervista.org/delphi/articolo81.htm function GetPEBptr( hProcess: Cardinal; //handle del processo var addr: Cardinal //indirizzo del PEB ): Boolean; type TProcessBasicInformation = record ExitStatus: Integer; PebBaseAddress: Cardinal; AffinityMask: Integer; BasePriority: Integer; UniqueProcessID: Integer; InheritedFromUniqueProcessID: Integer; end; var ProcInfo: TProcessBasicInformation; status: Integer; begin result := False; //prelevo le informazioni di base relative al processo status := NtQueryInformationProcess(hProcess, 0, @ProcInfo, SizeOf(TProcessBasicInformation), nil); if status <> 0 then begin //ErrStrNative('NtQueryInformationProcess', status); Exit; end; addr := ProcInfo.PebBaseAddress; Result := True; end; //restituisce l'indirizzo dell' LDR //http://pasotech.altervista.org/delphi/articolo81.htm function GetPebLdrData( hProcess: Cardinal; //handle del processo var addr: Cardinal //indirizzo del Loader Data ): Boolean; var PEBptr: Cardinal; BytesRead: dword; begin Result := False; if not GetPEBptr(hProcess, PEBptr) then begin Exit; end; if not ReadProcessMemory( hProcess, pointer(PEBptr + 12), @addr, 4, BytesRead ) then begin //ErrStr('ReadProcessMemory'); Exit; end; result := True; end; //GetModuleHandle eseguita su un processo remoto //http://pasotech.altervista.org/delphi/articolo81.htm function RemoteGetModuleHandle( hProcess: Cardinal; //in: handle al processo nomeModulo: PAnsiChar; //in: nome del modulo var BaseAddr: Cardinal //out: indirizzo di base ): Boolean; var pPeb_ldr_data: Cardinal; LdrData: PEB_LDR_DATA; LdrModule: LDR_MODULE; dwSize: Cardinal; readAddr, readAddrHead: Pointer; BaseDllName: PWideChar; begin result := False; //verifica sui valori dei parametri if (hProcess = 0) or (PAnsiChar(NomeModulo) = nil) then begin Exit; end; if not GetPebLdrData( hProcess, pPeb_ldr_data ) then begin Exit; end; //prelevo PEB_LDR_DATA if not ReadProcessMemory( hProcess, Pointer(pPeb_ldr_data), @LdrData, sizeof(LdrData), dwSize ) then begin //ErrStr('ReadProcessMemory'); Exit; end; readAddrHead := Pointer(pPeb_ldr_data + 12); readAddr := Pointer(LdrData.InLoadOrderModuleList.Flink); repeat // readAddr := Pointer(Cardinal(readAddr)); //estraggo il modulo if not ReadProcessMemory( hProcess, readAddr, @LdrModule, sizeof(LdrModule), dwSize ) then begin //ErrStr('ReadProcessMemory'); Exit; end; //leggo il nome della DLL GetMem(BaseDllName, LdrModule.BaseDllName.MaximumLength); if ReadProcessMemory( hProcess, LdrModule.BaseDllName.Buffer, BaseDllName, LdrModule.BaseDllName.MaximumLength, dwSize ) then begin if lstrcmpiA( nomeModulo, PAnsiChar(WideCharToString(BaseDllName)) ) = 0 then begin BaseAddr := LdrModule.DllBase; Result := True; Break; end; end; FreeMem(BaseDllName); //* passo al successivo LDR_MODULE */ readAddr := Pointer(LdrModule.InLoadOrderLinks.Flink); // until readAddr = readAddrHead; end; //GetProcAddress eseguita su un processo remoto; il primo parametro //è l'handle al processo remoto, il secondo ed il terzo corrispondono ai 2 //parametri di GetProcAddress mentre il quarto è il risultato. //http://pasotech.altervista.org/delphi/articolo82.htm function RemoteGetProcAddress( //in: handle al processo hProcess: Cardinal; //in: Indirizzo di base del modulo (ottenuto con RemoteGetModuleHandle) hModule: Cardinal; //in: puntatore ad una stringa che definisce il nome della funzione o un //valore intero positivo minore di FFFF nel caso si voglia specificare //l'Ordinal della funzione (è lo stesso significato del secondo parametro //dell' api win32 GetProcAddress) ProcName: PAnsiChar; //out: risultato var FuncAddress: Cardinal): Boolean; var DosHeader : TImageDosHeader; //Dos Header NtHeaders : TImageNtHeaders; //PE Header ExportDirectory : TImageExportDirectory; //Export Directory BytesRead: Cardinal; //var per ReadProcessMemory //estremo inferiore e superiore della Export Directory ExportDataDirectoryLow, ExportDataDirectoryHigh: cardinal; //valore Base di IMAGE_EXPORT_DIRECTORY: valore base degli Ordinal BaseOrdinal: Cardinal; // NumberOfFunctions: Cardinal; NumberOfNames: Cardinal; //puntatori ai 3 array First_AddressOfFunctions: Cardinal; First_AddressOfNames: Cardinal; First_AddressOfNameOrdinals: Cardinal; Actual_AddressOfFunctions: Cardinal; Actual_AddressOfNames: Cardinal; Actual_AddressOfNameOrdinals: Cardinal; // //indice della funzione nell'array puntato da //IMAGE_EXPORT_DIRECTORY.AddressOfFunctions: //l'elemento dell'array che si trova in questa //posizione contiene l'RVA della funzione FunctionIndex: Cardinal; //RVA presente in un elemento dell'array puntato //da IMAGE_EXPORT_DIRECTORY.AddressOfNames FunctionNameRVA: Cardinal; //nome puntato dall'RVA presente in un //elemento dell'array puntato da //IMAGE_EXPORT_DIRECTORY.AddressOfNames FunctionName: PAnsiChar; FunctionNameFound: Boolean; //RVA della funzione che cerchiamo: è presente //in un elemento dell'array puntato da //IMAGE_EXPORT_DIRECTORY.AddressOfFunctions FunctionRVA: Cardinal; //Forwarding FunctionForwardName: PAnsiChar; ForwardPuntoPos: Cardinal; FunctionForward_ModuleName: string; FunctionForward_FunctionName: string; FunctionForward_FunctionOrdinal: Word; FunctionForwardByOrdinal: Boolean; FunctionForward: Pointer; FunctionForward_ModuleBaseAddr: Cardinal; FunctionForward_FunctionAddr: Cardinal; // i: Cardinal; begin Result := False; //verifica sui valori dei parametri if (hProcess = 0) or (ProcName = nil) then begin Exit; end; try //inizializzo le variabili che prenderò poi //in esame nel blocco finally FunctionName := nil; FunctionForwardName := nil; //prelevo il Dos Header if not ReadProcessMemory( hProcess, Pointer(hModule), @DosHeader, sizeof(DosHeader), BytesRead ) then begin //ErrStr('ReadProcessMemory'); Exit; end; //verifica della validità if (DosHeader.e_magic <> IMAGE_DOS_SIGNATURE) then Exit; //prelevo il PE Header if not ReadProcessMemory( hProcess, Pointer(hModule + DosHeader._lfanew), @NtHeaders, sizeof(NtHeaders), BytesRead ) then begin //ErrStr('ReadProcessMemory'); Exit; end; //verifica della validità if (NtHeaders.Signature <> IMAGE_NT_SIGNATURE) then Exit; //se il modulo non ha la directory di Export allora esco //valuto l' RVA della directory di export if NTHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress = 0 then Exit; //calcolo il range di definizione della Export Directory //mi servirà per valutare se l'RVA di una funzione punta alla definizione //della funzione (valore esterno all'intervallo) oppure punta ad una stringa //del tipo <nome_dll>.<nome_funzione> (valore interno all'intervallo) with NTHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] do begin ExportDataDirectoryLow := VirtualAddress; ExportDataDirectoryHigh := VirtualAddress + Size; end; //prelevo la Export Directory if not ReadProcessMemory( hProcess, Pointer(hModule + ExportDataDirectoryLow), @ExportDirectory, sizeof(ExportDirectory), BytesRead ) then begin //ErrStr('ReadProcessMemory'); Exit; end; //Determino il valore base degli Ordinal BaseOrdinal := ExportDirectory.Base; // NumberOfFunctions := ExportDirectory.NumberOfFunctions; NumberOfNames := ExportDirectory.NumberOfNames; First_AddressOfFunctions := hModule + Cardinal(ExportDirectory.AddressOfFunctions); First_AddressOfNames := hModule + Cardinal(ExportDirectory.AddressOfNames); First_AddressOfNameOrdinals := hModule + Cardinal(ExportDirectory.AddressOfNameOrdinals); //allocazione di memoria per puntatori //che riceveranno stringhe di caratteri GetMem(FunctionName, 100); GetMem(FunctionForwardName, 100); FunctionIndex := 0; if Cardinal(ProcName) <= $FFFF then //ho passato l'Ordinal della funzione begin FunctionIndex := Cardinal(ProcName) - BaseOrdinal; //verifico di aver passato un Ordinal valido if (FunctionIndex < 0) or (FunctionIndex > NumberOfFunctions) then Exit; end else //ho passato il puntatore ad una stringa //che rappresenta il nome della funzione begin //scanno l'array puntato da IMAGE_EXPORT_DIRECTORY.AddressOfNames //che contiene i nomi delle funzioni esportate con associato un nome; //ogni elemento dell'array è 4 byte (è infatti l'RVA del nome della funzione) FunctionNameFound := False; for i := 0 to NumberOfNames - 1 do {for each export do} begin Actual_AddressOfNames := First_AddressOfNames + SizeOf(Cardinal) * i; //prelevo l'RVA del nome: FunctionNameRVA ReadProcessMemory( hProcess, Pointer(Actual_AddressOfNames) , @FunctionNameRVA, 4, BytesRead); //prelevo il nome: FunctionName ReadProcessMemory( hProcess, Pointer(hModule + FunctionNameRVA) , FunctionName, 100, BytesRead ); //vado a vedere se il nome che ho //trovato equivale a quello che cerco if lstrcmpiA(FunctionName, ProcName) = 0 then begin //vado nell'array puntato da IMAGE_EXPORT_DIRECTORY.AddressOfNameOrdinals: //l'elemento di posizione i contiene l'indice della funzione nell'array //puntato da IMAGE_EXPORT_DIRECTORY.AddressOfFunctions Actual_AddressOfNameOrdinals := First_AddressOfNameOrdinals + SizeOf(Word) * i; //prelevo l'indice: FunctionIndex ReadProcessMemory( hProcess, Pointer(Actual_AddressOfNameOrdinals) , @FunctionIndex, 2, BytesRead ); FunctionNameFound := True; Break; end; end; //verifico di aver trovato il nome specificato tra i nomi di funzione //in caso contrario esco if not FunctionNameFound then Exit; end; //Perfetto, ho ottenuto l'indice nell'array puntato //da IMAGE_EXPORT_DIRECTORY.AddressOfFunctions; a questo //punto posso prelevare l'RVA della funzione Actual_AddressOfFunctions := First_AddressOfFunctions + SizeOf(Cardinal) * FunctionIndex; //prelevo l'RVA ReadProcessMemory( hProcess, Pointer(Actual_AddressOfFunctions) , @FunctionRVA, 4, BytesRead ); //Bene: ho l'RVA della funzione; devo ora vedere se //rientra nella Export Directory: in tal caso punta //ad una stringa del tipo <nome_dll>.<nome_funzione> o //<nome_dll>.#Ordinal ossia si è di fronte ad un //Forwarding e dovremo chiamare RemoteGetProcAddress //su questi nuovi valori if (FunctionRVA > ExportDataDirectoryLow) and (FunctionRVA <= ExportDataDirectoryHigh) then //questo è un forwarding begin //prelevo la stringa modello <nome_dll>.<nome_funzione> o //<nome_dll>.#Ordinal ReadProcessMemory( hProcess, Pointer(hModule + FunctionRVA) , FunctionForwardName, 100, BytesRead ); //estraggo nome del modulo e della funzione ForwardPuntoPos := Posex('.', FunctionForwardName); if (ForwardPuntoPos > 0) then begin FunctionForward_ModuleName := Copy( FunctionForwardName, 1, ForwardPuntoPos - 1 ) + '.dll'; FunctionForward_FunctionName := Copy( FunctionForwardName, ForwardPuntoPos + 1, Length(FunctionForwardName) ); //Vado a vedere se FunctionForward_FunctionName è del tipo #Ordinal //in tal caso significa che la funzione a cui si punta è definita //tramite il suo Ordinal FunctionForwardByOrdinal := False; if string(FunctionForward_FunctionName)[1] = '#' then begin FunctionForwardByOrdinal := True; FunctionForward_FunctionOrdinal := Str2Int(Copy( FunctionForward_FunctionName, 2, Length(FunctionForward_FunctionName) )); end; //vado a rieseguire GetRemoteProcAddress sui valori di Forwarding //prima di tutto calcolo il base address del nuovo modulo: //deve esistere per forza, però non si sa mai, sempre meglio //gestire il caso in cui la funzione RemoteGetModuleHandle //per qualche motivo fallisce if not RemoteGetModuleHandle( hProcess, PAnsiChar(FunctionForward_ModuleName), FunctionForward_ModuleBaseAddr) then Exit; //una volta trovato il base address del modulo, chiamo //RemoteGetProcAddress if FunctionForwardByOrdinal then //<nome_dll>.#Ordinal FunctionForward := Pointer(FunctionForward_FunctionOrdinal) else //<nome_dll>.<nome_funzione> FunctionForward := PAnsiChar(FunctionForward_FunctionName); if not RemoteGetProcAddress( hProcess, FunctionForward_ModuleBaseAddr, FunctionForward, FunctionForward_FunctionAddr ) then Exit; //se tutto è andato OK FuncAddress := FunctionForward_FunctionAddr; end; end else //non si tratta di un Forwarding begin //sommo all'RVA della funzione il Base Address del modulo: //in questo modo ottengo il Virtual Address della funzione //ossia il risultato finale FuncAddress := hModule + FunctionRVA; end; Result := True; finally if FunctionName <> nil then FreeMem(Pointer(FunctionName)); if FunctionForwardName <> nil then FreeMem(Pointer(FunctionForwardName)); end; end; //mappa la sequenza di byte che inizia all'indirizzo localData e di dimensione //pari a DataSize, nello spazio di memoria del processo specificato dall'handle //hProcess function InjectData( hProcess: Cardinal; //in: handle al processo remoto localData: Pointer; //in: indirizzo della sequenza di byte DataSize: Cardinal; //in: dimensione della sequenza di byte Esecuzione: Boolean;//in: specifica se il dato copiato verrà eseguito; //ad esempio se si tratta di una funzione allora andrà settato a True, //se si tratta invece dei parametri della funzione andrà settato a //False var remoteData: Pointer //out: puntatore al dato nel processo remoto ): Boolean; var BytesWritten: Cardinal; protezione: Cardinal; begin Result := False; //controllo la validità dei valori dei parametri if ((hProcess = 0) or (localData = nil) or (DataSize = 0)) then Exit; try if Esecuzione then protezione := PAGE_EXECUTE_READWRITE else protezione := PAGE_READWRITE; remoteData := VirtualAllocEx( hProcess, nil, DataSize, MEM_COMMIT, protezione); if remoteData = nil then begin //ErrStr('VirtualAllocEx'); Exit; end; if not WriteProcessMemory(hProcess, remoteData, localData, DataSize, BytesWritten) then begin //ErrStr('WriteProcessMemory'); Exit; end; Result := True; finally if not result then begin if remoteData <> nil then begin if VirtualFreeEx(hProcess, remoteData, 0, MEM_RELEASE) = nil then begin //ErrStr('VirtualFreeEx'); end; end; end; end; end; //annulla l'operato della InjectData function UnloadData( hProcess: Cardinal; //handle al processo remoto remoteData: Pointer //valore del parametro RemoteData della InjectData ): Boolean; begin Result := False; //controllo la validità dei valori dei parametri if (hProcess = 0) or (remoteData = nil) then Exit; try if VirtualFreeEx(hProcess, remoteData, 0, MEM_RELEASE) = nil then begin //ErrStr('VirtualFreeEx'); Exit; end; Result := True; finally end; end; //Il succo del CodeInjection è il seguente: //1) copiamo la funzione che vogliamo eseguire, nello spazio di memoria //del processo remoto //2) copiamo i parametri della funzione che vogliamo eseguire, nello spazio di memoria //del processo remoto //3) eseguiamo la funzione copiata, utilizzando l'api win32 CreateRemoteThread //La funzione InjectThread si occupa appunto del punto 3) function InjectThread(hProcess: Cardinal; remoteFunction: Pointer; remoteParameter: Pointer; var outputValue: Cardinal; var errorCode: Cardinal; Synch: Boolean): Boolean; var hThread: Cardinal; TID: Cardinal; lpExitCode: Cardinal; bytesRead: Cardinal; begin //N.B. i parametri outputValue e errorCode hanno senso solo se Synch=True Result := False; //controllo la valdità dei valori dei parametri if ((hProcess = 0) or (remoteFunction = nil) or (remoteParameter = nil)) then Exit; try hThread := CreateRemoteThread(hProcess, nil, 0, remoteFunction, remoteParameter, 0, TID); if hThread = 0 then begin //ErrStr('CreateRemoteThread'); Exit; end; //mi metto in attesa della terminazione del thread if Synch then begin case WaitForSingleObject(hThread, INFINITE) of WAIT_FAILED: begin //ErrStr('WaitForSingleObject'); Exit; end; end; if not GetExitCodeThread(hThread, lpExitCode) then begin //ErrStr('GetExitCodeThread'); Exit; end; //c'è stato un errore (lpExitCode è l'output della funzione eseguita dal //thread remoto che nel nostro caso è RemoteLoadLibraryThread; più precisamente è l'argomento //della ExitThread) if lpExitCode = 0 then //ExitThread(0) begin //leggo il codice dell' errore che si è verificato nel thread remoto //nel nostro caso TRemoteLoadLibraryData.errorcod if not ReadProcessMemory(hProcess, remoteParameter, @errorcode, 4, bytesRead) then begin //ErrStr('ReadProcessMemory'); Exit; end; end else begin //leggo il valore significativo generato nel thread remoto //nel nostro caso TRemoteLoadLibraryData.output if not ReadProcessMemory(hProcess, Pointer(Cardinal(remoteParameter)+4), @outputvalue, 4, bytesRead) then begin //ErrStr('ReadProcessMemory'); Exit; end; end; end; Result := True; finally if hThread <> 0 then begin if not CloseHandle(hThread) then begin //ErrStr('CloseHandle'); end; end; end; end; end.
unit GetWebFile; interface uses Windows, WinInet; function GetInetFile(FileURL : String) : String; implementation function GetInetFile(FileURL : String) : String; const BufferSize = 1024; var hSession : hInternet; hURL : hInternet; BufLen : DWORD; Buffer : Array [0..1023] of Char; begin Result := ''; hSession := InternetOpen(PChar('Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)'), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); try hURL := InternetOpenURL(hSession, PChar(FileURL),nil,0,0,0); try FillChar(Buffer, SizeOf(Buffer), 0); repeat Result := Result + Buffer; FillChar(Buffer, SizeOf(Buffer), 0); InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufLen); until BufLen = 0; finally InternetCloseHandle(hURL) end finally InternetCloseHandle(hSession) end; end; end.
{: Benchmark for GLCanvas.<p> This project pits TGLCanvas against TCanvas in direct mode (hardware acceleration should be available on both sides).<p> You may usually bet on TGLCanvas being 3 to 5 times faster, but on fast 3D hardware, or when PenWidth is not 1, the performance ratio can reach 1:100.<p> However, this is not really an apples-to-apples comparison, because GDI (or any other software implementations) are useless when it comes to drawing to an OpenGL buffer, so, this is more to show that GLCanvas is far from a "decelerator" if you have some 2D stuff to draw on your 3D Scene.<p> Figures for PenWidth = 1, GLCanvas / GDI<p> CPU Graphics Board Lines Ellipses Points TextOut Tbird 1.2 GF3 Ti200 5.2 / 227 64 / 756 27 / 408 75 / 208 ----29/09/02 - Added TextOut bench Tbird 1.2 GF2 Pro 7.1 / 162 92 / 557 40 / 223 Duron 800 TNT2 M64 105.0 / 571 400 / 1148 126 / 676 ----21/01/02 - Initial } unit Unit1; {$MODE Delphi} interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GLScene, ExtCtrls, StdCtrls, GLLCLViewer, GLBitmapFont, GLWindowsFont, GLTexture, GLCrossPlatform, GLCoordinates, GLBaseClasses, GLRenderContextInfo; type TForm1 = class(TForm) BULines: TButton; BUEllipses: TButton; GLSceneViewer: TGLSceneViewer; PaintBox: TPaintBox; LAGLCanvas: TLabel; LAGDI: TLabel; Bevel1: TBevel; GLScene1: TGLScene; GLCamera1: TGLCamera; RBPenWidth1: TRadioButton; RBPenWidth2: TRadioButton; BUPoints: TButton; BURects: TButton; BUTextOut: TButton; WindowsBitmapFont: TGLWindowsBitmapFont; GLDirectOpenGL1: TGLDirectOpenGL; procedure BULinesClick(Sender: TObject); procedure BUEllipsesClick(Sender: TObject); procedure BUPointsClick(Sender: TObject); procedure BURectsClick(Sender: TObject); procedure BUTextOutClick(Sender: TObject); procedure GLDirectOpenGL1Render(Sender: TObject; var rci: TRenderContextInfo); private { Private declarations } procedure PaintTheBox; procedure Bench; public { Public declarations } end; var Form1: TForm1; implementation {$R *.lfm} uses GLCanvas; type TWhat = (wLines, wEllipses, wRects, wPoints, wTextOut); var vWhat: TWhat; vPenWidth: integer; const cNbLines = 20000; cNbEllipses = 20000; cNbRects = 5000; cNbPoints = 200000; cNbTextOuts = 20000; procedure TForm1.BULinesClick(Sender: TObject); begin vWhat := wLines; Bench; end; procedure TForm1.BUEllipsesClick(Sender: TObject); begin vWhat := wEllipses; Bench; end; procedure TForm1.BURectsClick(Sender: TObject); begin vWhat := wRects; Bench; end; procedure TForm1.BUPointsClick(Sender: TObject); begin vWhat := wPoints; Bench; end; procedure TForm1.BUTextOutClick(Sender: TObject); begin vWhat := wTextOut; Bench; end; procedure TForm1.Bench; var t: int64; begin if RBPenWidth1.Checked then vPenWidth := 1 else vPenWidth := 2; Application.ProcessMessages; RandSeed := 0; t := StartPrecisionTimer; GLSceneViewer.Refresh; LAGLCanvas.Caption := Format('GLCanvas: %.2f msec', [StopPrecisionTimer(t) * 1000]); Application.ProcessMessages; RandSeed := 0; t := StartPrecisionTimer; PaintTheBox; LAGDI.Caption := Format('GDI: %.1f msec', [StopPrecisionTimer(t) * 1000]); end; procedure TForm1.GLDirectOpenGL1Render(Sender: TObject; var rci: TRenderContextInfo); var i, x, y: integer; glc: TGLCanvas; r: TRect; color: TColor; begin glc := TGLCanvas.Create(256, 256); with glc do begin PenWidth := vPenWidth; case vWhat of wLines: begin for i := 1 to cNbLines do begin PenColor := Random(256 * 256 * 256); MoveTo(Random(256), Random(256)); LineTo(Random(256), Random(256)); end; end; wEllipses: begin for i := 1 to cNbEllipses do begin PenColor := Random(256 * 256 * 256); Ellipse(Random(256), Random(256), Random(256), Random(256)); end; end; wRects: begin for i := 1 to cNbRects do begin PenColor := Random(256 * 256 * 256); r := Rect(Random(256), Random(256), Random(256), Random(256)); FillRect(r.Left, r.Top, r.Right, r.Bottom); end; end; wPoints: begin for i := 1 to cNbPoints do begin PenColor := Random(256 * 256 * 256); PlotPixel(Random(256), Random(256)); end; end; wTextOut: begin for i := 1 to cNbTextOuts do begin color := Random(256 * 256 * 256); x := Random(256); y := Random(256); WindowsBitmapFont.TextOut(rci, x, y, 'Hello', color); end; end; end; end; glc.Free; end; procedure TForm1.PaintTheBox; var i, x, y: integer; r: TRect; begin with PaintBox.Canvas do begin Brush.Style := bsClear; Pen.Width := vPenWidth; case vWhat of wLines: begin for i := 1 to cNbLines do begin Pen.Color := Random(256 * 256 * 256); MoveTo(Random(256), Random(256)); LineTo(Random(256), Random(256)); end; end; wEllipses: begin for i := 1 to cNbEllipses do begin Pen.Color := Random(256 * 256 * 256); Ellipse(Random(256), Random(256), Random(256), Random(256)); end; end; wRects: begin Brush.Style := bsSolid; for i := 1 to cNbRects do begin Brush.Color := Random(256 * 256 * 256); r := Rect(Random(256), Random(256), Random(256), Random(256)); FillRect(r); end; end; wPoints: begin for i := 1 to cNbPoints do begin Pixels[Random(256), Random(256)] := Random(256 * 256 * 256); end; end; wTextOut: begin Font := WindowsBitmapFont.Font; for i := 1 to cNbTextOuts do begin Font.Color := Random(256 * 256 * 256); x := Random(256); y := Random(256); TextOut(x, y, 'Hello'); end; end; end; end; end; end.
unit VlcPlayer_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, AXVLC_TLB; type TVlcPlayPosEvent = procedure(Sender: TObject; pos, len: integer) of object; TVlcPlayer = class(TForm) VLCPlugin21: TVLCPlugin2; procedure VLCPlugin21MediaPlayerPositionChanged(ASender: TObject; position: Single); procedure VLCPlugin21MediaPlayerLengthChanged(ASender: TObject; length: Integer); procedure VLCPlugin21MediaPlayerPlaying(Sender: TObject); procedure VLCPlugin21MediaPlayerPaused(Sender: TObject); procedure VLCPlugin21MediaPlayerStopped(Sender: TObject); procedure VLCPlugin21MediaPlayerTimeChanged(ASender: TObject; time: Integer); procedure FormClose(Sender: TObject; var Action: TCloseAction); private fPlayLen: integer; fPlayPos: integer; fVolume: integer; fPlayState: integer; fOnPlayPosEvent: TVlcPlayPosEvent; fOnStopEvent: TNotifyEvent; fOnChange: TNotifyEvent; function GetPlayState: integer; procedure setPlayPos(const Value: integer); procedure setVolume(const Value: integer); procedure doChange(); public playFileName: string; playFileID: integer; procedure play(id, typ: integer; s, title: string; withPause:boolean = false; seek: integer = 0); procedure pause(); procedure stop(); property volume: integer read fVolume write setVolume; property playLen: integer read fPlayLen; property playPos: integer read fPlayPos write setPlayPos; property playState: integer read GetPlayState; property onChange:TNotifyEvent read fOnChange write fOnChange; property onPlayPosEvent: TVlcPlayPosEvent read fOnPlayPosEvent write fOnPlayPosEvent; property onStopEvent: TNotifyEvent read fOnStopEvent write fOnStopEvent; end; var VlcPlayer: TVlcPlayer; implementation uses Math; {$R *.dfm} { TVlcPlayer } function TVlcPlayer.GetPlayState: integer; begin Result := fPlayState; //if (VLCPlugin21.playlist.isPlaying) then Result := 2; end; procedure TVlcPlayer.pause; begin VLCPlugin21.playlist.togglePause; end; procedure TVlcPlayer.play(id, typ: integer; s, title: string; withPause: boolean; seek: integer); begin stop; VLCPlugin21.playlist.clear; VLCPlugin21.playlist.add(s, NULL, NULL); VLCPlugin21.playlist.play; playFileName := s; playFileID := id; //VLCPlugin21.Anchors.volume := 30; Show; end; procedure TVlcPlayer.setPlayPos(const Value: integer); begin VLCPlugin21.input.time := Value * 1000; end; procedure TVlcPlayer.setVolume(const Value: integer); begin fVolume := Value; VLCPlugin21.audio.volume := round(fVolume * 100 / 320); end; procedure TVlcPlayer.stop; begin VLCPlugin21.playlist.stop; while VLCPlugin21.playlist.isPlaying do Sleep(10); Hide; end; procedure TVlcPlayer.VLCPlugin21MediaPlayerPositionChanged(ASender: TObject; position: Single); begin // end; procedure TVlcPlayer.VLCPlugin21MediaPlayerLengthChanged(ASender: TObject; length: Integer); begin fPlayLen := length div 1000; if (Assigned(fOnPlayPosEvent)) then fOnPlayPosEvent(Self, fPlayPos, fPlayLen); end; procedure TVlcPlayer.VLCPlugin21MediaPlayerPlaying(Sender: TObject); begin fPlayState := 2; doChange(); end; procedure TVlcPlayer.VLCPlugin21MediaPlayerPaused(Sender: TObject); begin fPlayState := 3; doChange(); end; procedure TVlcPlayer.VLCPlugin21MediaPlayerStopped(Sender: TObject); begin fPlayState := 4; doChange(); end; procedure TVlcPlayer.doChange; begin if (Assigned(fOnChange)) then fOnChange(Self); end; procedure TVlcPlayer.VLCPlugin21MediaPlayerTimeChanged(ASender: TObject; time: Integer); begin fPlayPos := time div 1000; if (Assigned(fOnPlayPosEvent)) then fOnPlayPosEvent(Self, fPlayPos, fPlayLen); end; procedure TVlcPlayer.FormClose(Sender: TObject; var Action: TCloseAction); begin stop; end; end.
unit uRegistry; interface uses Registry, Windows; type TDefaulRegistry = class private FRootKey : HKEY; FOpenKey : String; FKey : String; public property RookKey : HKEY read FRootKey write FRootKey; property OpenKey : String read FOpenKey write FOpenKey; property Key : String read FKey write FKey; end; TStringRegistry = class(TDefaulRegistry) private FValue : String; public property Value : String read FValue write FValue; procedure SaveStringRegistry(Value : String); function GetStringRegistry:String; end; TWinRegistry = class private FStringReg : TStringRegistry; public property StringRegistry : TStringRegistry read FStringReg write FStringReg; Constructor Create; Destructor Destroy; override; end; implementation {--------- TWinRegistry ----------} Constructor TWinRegistry.Create; begin inherited Create; FStringReg := TStringRegistry.Create; end; Destructor TWinRegistry.Destroy; begin FStringReg.Free; inherited Destroy; end; {--------- TStringRegistry ----------} procedure TStringRegistry.SaveStringRegistry(Value : String); var Reg : TRegistry; begin Try Reg := TRegistry.Create; Reg.RootKey := Self.FRootKey; Reg.OpenKey(Self.FOpenKey, True); Reg.WriteString(Self.Key, Value); Finally Reg.CloseKey; Reg.Free; end; end; function TStringRegistry.GetStringRegistry:String; var Reg : TRegistry; begin Try Reg := TRegistry.Create; Reg.RootKey := Self.FRootKey; Reg.OpenKey(Self.FOpenKey, True); Result := Reg.ReadString(Self.Key); Finally Reg.CloseKey; Reg.Free; end; end; end.
unit untMaquinaDeDinheiro; interface uses Classes; type IMaquina = interface ['{214BF960-EAF5-41C2-91D5-0E8F401D65A3}'] function MontarTroco(Troco: Double): TList; end; TCedula = (ceNota100, ceNota50, ceNota20, ceNota10, ceNota5, ceNota2, ceMoeda100, ceMoeda50, ceMoeda25, ceMoeda10, ceMoeda5, ceMoeda1); TTroco = class private FTipo: TCedula; FQuantidade: Integer; public constructor Create(Tipo: TCedula; Quantidade: Integer); function GetTipo: TCedula; function GetQuantidade: Integer; procedure SetQuantidade(Quantidade: Integer); end; TMaquinaDinheiro = class(TInterfacedObject, IMaquina) function MontarTroco(Troco: Double): TList; end; implementation uses SysUtils; { TTroco } constructor TTroco.Create(Tipo: TCedula; Quantidade: Integer); begin inherited Create(); FTipo := Tipo; FQuantidade := Quantidade; end; function TTroco.GetQuantidade: Integer; begin Result := FQuantidade; end; function TTroco.GetTipo: TCedula; begin Result := FTipo; end; procedure TTroco.SetQuantidade(Quantidade: Integer); begin FQuantidade := Quantidade; end; { TMaquinaDinheiro } function TMaquinaDinheiro.MontarTroco(Troco: Double): TList; var ListaTroco: TList; ValorTrocoRestante: Double; begin if Troco < 0 then begin raise Exception.Create('O troco não deve ser negativo, verificar chamada do método MontarTroco!'); end; ValorTrocoRestante := Troco; ListaTroco := TList.Create; if ValorTrocoRestante >= 100 then begin ListaTroco.Add(TTroco.Create(ceNota100, Round(ValorTrocoRestante) div 100)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 10000) / 100; end; if ValorTrocoRestante >= 50 then begin ListaTroco.Add(TTroco.Create(ceNota50, Round(ValorTrocoRestante) div 50)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 5000) / 100; end; if ValorTrocoRestante >= 20 then begin ListaTroco.Add(TTroco.Create(ceNota20, Round(ValorTrocoRestante) div 20)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 2000) / 100; end; if ValorTrocoRestante >= 10 then begin ListaTroco.Add(TTroco.Create(ceNota10, Round(ValorTrocoRestante) div 10)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 1000) / 100; end; if ValorTrocoRestante >= 5 then begin ListaTroco.Add(TTroco.Create(ceNota5, Round(ValorTrocoRestante) div 5)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 500) / 100; end; if ValorTrocoRestante >= 2 then begin ListaTroco.Add(TTroco.Create(ceNota2, Round(ValorTrocoRestante) div 2)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 200) / 100; end; ValorTrocoRestante := ValorTrocoRestante * 100; { Converte o valor restante em centavos } if ValorTrocoRestante >= 100 then begin ListaTroco.Add(TTroco.Create(ceMoeda100, Round(ValorTrocoRestante) div 100)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 10000) / 100; end; if ValorTrocoRestante >= 50 then begin ListaTroco.Add(TTroco.Create(ceMoeda50, Round(ValorTrocoRestante) div 50)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 5000) / 100; end; if ValorTrocoRestante >= 25 then begin ListaTroco.Add(TTroco.Create(ceMoeda25, Round(ValorTrocoRestante) div 25)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 2500) / 100; end; if ValorTrocoRestante >= 10 then begin ListaTroco.Add(TTroco.Create(ceMoeda10, Round(ValorTrocoRestante) div 10)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 1000) / 100; end; if ValorTrocoRestante >= 5 then begin ListaTroco.Add(TTroco.Create(ceMoeda5, Round(ValorTrocoRestante) div 5)); ValorTrocoRestante := (Round(ValorTrocoRestante * 100) mod 500) / 100; end; if ValorTrocoRestante >= 1 then begin ListaTroco.Add(TTroco.Create(ceMoeda1, Round(ValorTrocoRestante) div 1)); end; Result := ListaTroco; end; end.
unit Odontologia.Vistas.Direccion.Departamento; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.ImageList, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.ImgList, Vcl.StdCtrls, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.WinXPanels, Vcl.ExtCtrls, Vcl.DBCtrls, Odontologia.Controlador, Odontologia.Controlador.Departamento.Interfaces, Odontologia.Controlador.Interfaces, Odontologia.Controlador.Pais.Interfaces, Odontologia.Vistas.Template; type TPagDepartamento = class(TPagTemplate) Label1: TLabel; Label2: TLabel; Label3: TLabel; [Bind('ID')] edtCodigo: TEdit; [Bind('NOMBRE')] edtNombre: TEdit; cmbPais: TDBLookupComboBox; DataSource2: TDataSource; procedure btnNuevoClick(Sender: TObject); procedure DataSource1DataChange(Sender: TObject; Field: TField); procedure btnCerrarClick(Sender: TObject); procedure btnGuardarClick(Sender: TObject); procedure edtSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid1DblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnBorrarClick(Sender: TObject); procedure btnActualizarClick(Sender: TObject); private { Private declarations } FController : iController; FDepartamento : iControllerDepartamento; Fpais : iControllerPais; procedure prc_estado_inicial; public { Public declarations } end; var PagDepartamento : TPagDepartamento; Insercion : Boolean; implementation {$R *.dfm} procedure TPagDepartamento.btnActualizarClick(Sender: TObject); begin inherited; FDepartamento.Buscar; end; procedure TPagDepartamento.btnBorrarClick(Sender: TObject); var ShouldClose: Boolean; begin inherited; if MessageDlg('Realmente desea eliminar este registro?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin FDepartamento.Entidad.DEP_CODIGO := StrToInt(edtCodigo.Text); FDepartamento.Eliminar; FDepartamento.Buscar; prc_estado_inicial; end else begin edtNombre.SetFocus; end; end; procedure TPagDepartamento.btnCerrarClick(Sender: TObject); begin inherited; prc_estado_inicial; end; procedure TPagDepartamento.btnGuardarClick(Sender: TObject); begin inherited; if Insercion then begin FDepartamento.Entidad.DEP_NOMBRE := edtNombre.Text; FDepartamento.Entidad.DEP_COD_PAIS := DataSource2.DataSet.FieldByName ('PAI_CODIGO').AsInteger; FDepartamento.Insertar; end else begin FDepartamento.Entidad.DEP_CODIGO := StrToInt(edtCodigo.Text); FDepartamento.Entidad.DEP_NOMBRE := edtNombre.Text; FDepartamento.Entidad.DEP_COD_PAIS := DataSource2.DataSet.FieldByName ('PAI_CODIGO').AsInteger; FDepartamento.Modificar; end; prc_estado_inicial; end; procedure TPagDepartamento.btnNuevoClick(Sender: TObject); begin inherited; CardPanel1.ActiveCard := Card2; lblTitulo2.Caption := 'Agregar nuevo registro'; edtCodigo.Enabled := False; edtNombre.SetFocus; end; procedure TPagDepartamento.DataSource1DataChange(Sender: TObject; Field: TField); begin inherited; edtCodigo.Text := DataSource1.DataSet.FieldByName('DEP_CODIGO').AsString; edtNombre.Text := DataSource1.DataSet.FieldByName('DEP_NOMBRE').AsString; end; procedure TPagDepartamento.DBGrid1DblClick(Sender: TObject); begin inherited; Insercion := False; CardPanel1.ActiveCard := Card2; lblTitulo2.Caption := 'Modificar registro'; edtCodigo.Text := DataSource1.DataSet.FieldByName('CODIGO').AsString; edtNombre.Text := DataSource1.DataSet.FieldByName('NOMBRE').AsString; cmbPais.KeyValue := DataSource1.DataSet.FieldByName('COD_PAIS').AsString; end; procedure TPagDepartamento.edtSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; FDepartamento.Buscar(edtSearch.Text); end; procedure TPagDepartamento.FormCreate(Sender: TObject); begin inherited; lblTitulo.Caption := 'Registro de departamentos'; edtCodigo.Enabled := False; FController := TController.New; FDepartamento := FController.Departamento.DataSource(DataSource1); Fpais := FController.Pais.DataSource(DataSource2); prc_estado_inicial; end; procedure TPagDepartamento.prc_estado_inicial; begin Insercion := True; CardPanel1.ActiveCard := Card1; edtSearch.Text := ''; edtCodigo.Text := ''; edtNombre.Text := ''; FDepartamento.Buscar; Fpais.Buscar; end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.WebBrowser, FMX.ListBox, FMX.Layouts, FMX.MultiView; type TMainForm = class(TForm) StyleBook: TStyleBook; Panel: TPanel; WebBrowser: TWebBrowser; ToolBar: TToolBar; FlowLayout: TFlowLayout; btnReload: TSpeedButton; lblURL: TLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnReloadClick(Sender: TObject); procedure WebBrowserDidFinishLoad(ASender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} procedure TMainForm.FormCreate(Sender: TObject); begin WebBrowser.URL := 'https://mail.worksap.co.jp/webmail2'; WebBrowser.EnableCaching := False; end; procedure TMainForm.FormShow(Sender: TObject); begin WebBrowser.Navigate; end; procedure TMainForm.WebBrowserDidFinishLoad(ASender: TObject); begin lblURL.Text := WebBrowser.URL; end; procedure TMainForm.btnReloadClick(Sender: TObject); begin WebBrowser.Reload; end; end.
unit Invoice.Controller.AppInfo.Default; interface uses Invoice.Controller.Interfaces, Winapi.Windows, Winapi.Messages, Vcl.Forms; type TControllerAppInfoDefault = class(TInterfacedObject, iControllerAppInfoDefault) private FCompanyName: String; FFileDescription: String; FFileVersion: String; FInternalName: String; FLegalCopyright: String; FLegalTradeMarks: String; FOriginalFilename: String; FProductName: String; FProductVersion: String; FComments: String; public constructor Create; destructor Destroy; Override; class function New: iControllerAppInfoDefault; function CompanyName: String; function FileDescription: String; function FileVersion: String; function InternalName: String; function LegalCopyright: String; function LegalTradeMarks: String; function OriginalFilename: String; function ProductName: String; function ProductVersion: String; function Comments: String; end; implementation { TControllerAppInfoDefault } function GetAppInfo(AppInfo: String): String; var ExeApp: String; SizeOf: Integer; Buf: pchar; Value: pchar; Tmp1, Tmp2: Dword; begin ExeApp := Application.ExeName; SizeOf := GetFileVersionInfoSize(pchar(ExeApp), Tmp1); result := ''; if (SizeOf > 0) then begin Buf := AllocMem(SizeOf); // if GetFileVersionInfo(pchar(ExeApp), 0, SizeOf, Buf) then if VerQueryValue(Buf, pchar('StringFileInfo\041604E4\' + AppInfo), pointer(Value), Tmp2) then result := Value else if VerQueryValue(Buf, pchar('StringFileInfo\040904E4\' + AppInfo), pointer(Value), Tmp2) then result := Value else result := ''; // FreeMem(Buf, SizeOf); end; end; constructor TControllerAppInfoDefault.Create; begin FCompanyName := GetAppInfo('CompanyName'); FFileDescription := GetAppInfo('FileDescription'); FFileVersion := GetAppInfo('FileVersion'); FInternalName := GetAppInfo('InternalName'); FLegalCopyright := GetAppInfo('LegalCopyright'); FLegalTradeMarks := GetAppInfo('LegalTradeMarks'); FOriginalFilename := GetAppInfo('OriginalFilename'); FProductName := GetAppInfo('ProductName'); FProductVersion := GetAppInfo('ProductVersion'); FComments := GetAppInfo('Comments'); end; destructor TControllerAppInfoDefault.Destroy; begin inherited; end; class function TControllerAppInfoDefault.New: iControllerAppInfoDefault; begin Result := Self.Create; end; function TControllerAppInfoDefault.Comments: String; begin Result := FComments; end; function TControllerAppInfoDefault.CompanyName: String; begin Result := FCompanyName; end; function TControllerAppInfoDefault.FileDescription: String; begin Result := FFileDescription; end; function TControllerAppInfoDefault.FileVersion: String; begin Result := FFileVersion; end; function TControllerAppInfoDefault.InternalName: String; begin Result := FInternalName; end; function TControllerAppInfoDefault.LegalCopyright: String; begin Result := FLegalCopyright; end; function TControllerAppInfoDefault.LegalTradeMarks: String; begin Result := FLegalTradeMarks; end; function TControllerAppInfoDefault.OriginalFilename: String; begin Result := FOriginalFilename; end; function TControllerAppInfoDefault.ProductName: String; begin Result := FProductName; end; function TControllerAppInfoDefault.ProductVersion: String; begin Result := FProductVersion; end; end.
unit stmFont1; interface {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses graphics, util1,stmdef,stmObj; { Gestion de l'objet PG2 Tfont font est un objet Delphi Tfont Rappel: quand l'objet est une propriété d'un autre objet, il n'est pas nécessaire d'utiliser var pu:typeUO Il faut que la fonction owner_font renvoie directement un Tfont } procedure proTfont_Name(st:AnsiString;font:Tfont);pascal; function fonctionTfont_Name(font:Tfont):AnsiString;pascal; procedure proTfont_Size(n:smallint;font:Tfont);pascal; function fonctionTfont_Size(font:Tfont):smallint;pascal; procedure proTfont_Color(n:integer;font:Tfont);pascal; function fonctionTfont_Color(font:Tfont):integer;pascal; procedure proTfont_Style(n:smallint;font:Tfont);pascal; function fonctionTfont_Style(font:Tfont):smallint;pascal; implementation procedure proTfont_Name(st:AnsiString;font:Tfont); begin if assigned(font) then font.name:=st; end; function fonctionTfont_Name(font:Tfont):AnsiString; begin if assigned(font) then result:=font.name; end; procedure proTfont_Size(n:smallint;font:Tfont); begin if assigned(font) then font.size:=n; end; function fonctionTfont_Size(font:Tfont):smallint; begin if assigned(font) then result:=font.size; end; procedure proTfont_Color(n:integer;font:Tfont); begin if assigned(font) then font.color:=n; end; function fonctionTfont_Color(font:Tfont):integer; begin if assigned(font) then result:=font.Color; end; procedure proTfont_Style(n:smallint;font:Tfont); var sty:TFontStyles; begin if assigned(font) then begin sty:=[]; if n and 1<>0 then sty:=sty+[fsBold]; if n and 2<>0 then sty:=sty+[fsItalic]; if n and 4<>0 then sty:=sty+[fsUnderLine]; if n and 8<>0 then sty:=sty+[fsStrikeOut]; font.style:=sty; end; end; function fonctionTfont_Style(font:Tfont):smallint; var n:integer; begin if assigned(font) then with font do begin n:=0; if fsBold in style then inc(n); if fsItalic in style then inc(n,2); if fsUnderLine in style then inc(n,4); if fsStrikeOut in style then inc(n,8); result:=n; end; end; end.
unit CalledByRunDll32Impl; interface uses Winapi.Windows; ///<summary>rundll32 path\to\your.dll,EntryPoint additional parameters go here</summary> procedure EntryPoint(_HWnd: HWND; _HInstance: HINST; _CmdLine: PAnsiChar; CmdShow: Integer); stdcall; ///<summary>rundll32 path\to\your.dll,EntryPoint additional parameters go here. If EntryPointA is exported, calls /// EntryPointA first, otherwise, calls EntryPoint. ///</summary> procedure EntryPointA(_HWnd: HWND; _HInstance: HINST; _CmdLine: PAnsiChar; CmdShow: Integer); stdcall; ///<summary>rundll32 path\to\your.dll,EntryPoint additional parameters go here. If EntryPointW is exported, calls /// EntryPointW first, otherwise, calls EntryPoint. ///</summary> procedure EntryPointW(_HWnd: HWND; _HInstance: HINST; _CmdLine: PWideChar; CmdShow: Integer); stdcall; implementation uses Vcl.Dialogs, System.SysUtils; procedure EntryPoint(_HWnd: HWND; _HInstance: HINST; _CmdLine: PAnsiChar; CmdShow: Integer); begin {$IF DEFINED(WIN64)} EntryPointW(_HWnd, _HInstance, PWideChar(string(_CmdLine)), CmdShow); {$ELSEIF DEFINED(WIN32)} EntryPointA(_HWnd, _HInstance, _CmdLine, CmdShow); {$ENDIF} end; procedure EntryPointA(_HWnd: HWND; _HInstance: HINST; _CmdLine: PAnsiChar; CmdShow: Integer); begin ShowMessage(Format('This is EntryPointA: CmdLine: "%s"', [string(_CmdLine)])); end; procedure EntryPointW(_HWnd: HWND; _HInstance: HINST; _CmdLine: PWideChar; CmdShow: Integer); begin ShowMessage(Format('This is EntryPointW: CmdLine: "%s"', [string(_CmdLine)])); end; exports {$IF DEFINED(WIN64)} EntryPointW, {$ELSEIF DEFINED(WIN32)} EntryPointA, {$ENDIF} EntryPoint; end.
unit ImageRGBALongData; interface uses Windows, Graphics, Abstract2DImageData, RGBALongDataSet, BasicDataTypes; type T2DImageRGBALongData = class (TAbstract2DImageData) private FDefaultColor: TPixelRGBALongData; // Gets function GetData(_x, _y, _c: integer):longword; function GetDefaultColor:TPixelRGBALongData; // Sets procedure SetData(_x, _y, _c: integer; _value: longword); procedure SetDefaultColor(_value: TPixelRGBALongData); protected // Constructors and Destructors procedure Initialize; override; // Gets function GetBitmapPixelColor(_Position: longword):longword; override; function GetRPixelColor(_Position: longword):byte; override; function GetGPixelColor(_Position: longword):byte; override; function GetBPixelColor(_Position: longword):byte; override; function GetAPixelColor(_Position: longword):byte; override; function GetRedPixelColor(_x,_y: integer):single; override; function GetGreenPixelColor(_x,_y: integer):single; override; function GetBluePixelColor(_x,_y: integer):single; override; function GetAlphaPixelColor(_x,_y: integer):single; override; // Sets procedure SetBitmapPixelColor(_Position, _Color: longword); override; procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override; procedure SetRedPixelColor(_x,_y: integer; _value:single); override; procedure SetGreenPixelColor(_x,_y: integer; _value:single); override; procedure SetBluePixelColor(_x,_y: integer; _value:single); override; procedure SetAlphaPixelColor(_x,_y: integer; _value:single); override; public // copies procedure Assign(const _Source: TAbstract2DImageData); override; // Misc procedure ScaleBy(_Value: single); override; procedure Invert; override; // properties property Data[_x,_y,_c:integer]:longword read GetData write SetData; default; property DefaultColor:TPixelRGBALongData read GetDefaultColor write SetDefaultColor; end; implementation // Constructors and Destructors procedure T2DImageRGBALongData.Initialize; begin FDefaultColor.r := 0; FDefaultColor.g := 0; FDefaultColor.b := 0; FDefaultColor.a := 0; FData := TRGBALongDataSet.Create; end; // Gets function T2DImageRGBALongData.GetData(_x, _y, _c: integer):longword; begin if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then begin case (_c) of 0: Result := (FData as TRGBALongDataSet).Red[(_y * FXSize) + _x]; 1: Result := (FData as TRGBALongDataSet).Green[(_y * FXSize) + _x]; 2: Result := (FData as TRGBALongDataSet).Blue[(_y * FXSize) + _x]; else begin Result := (FData as TRGBALongDataSet).Alpha[(_y * FXSize) + _x]; end; end; end else begin case (_c) of 0: Result := FDefaultColor.r; 1: Result := FDefaultColor.g; 2: Result := FDefaultColor.b; else begin Result := FDefaultColor.a; end; end; end; end; function T2DImageRGBALongData.GetDefaultColor:TPixelRGBALongData; begin Result := FDefaultColor; end; function T2DImageRGBALongData.GetBitmapPixelColor(_Position: longword):longword; begin Result := RGB((FData as TRGBALongDataSet).Blue[_Position],(FData as TRGBALongDataSet).Green[_Position],(FData as TRGBALongDataSet).Red[_Position]); end; function T2DImageRGBALongData.GetRPixelColor(_Position: longword):byte; begin Result := (FData as TRGBALongDataSet).Red[_Position] and $FF; end; function T2DImageRGBALongData.GetGPixelColor(_Position: longword):byte; begin Result := (FData as TRGBALongDataSet).Green[_Position] and $FF; end; function T2DImageRGBALongData.GetBPixelColor(_Position: longword):byte; begin Result := (FData as TRGBALongDataSet).Blue[_Position] and $FF; end; function T2DImageRGBALongData.GetAPixelColor(_Position: longword):byte; begin Result := (FData as TRGBALongDataSet).Alpha[_Position] and $FF; end; function T2DImageRGBALongData.GetRedPixelColor(_x,_y: integer):single; begin Result := (FData as TRGBALongDataSet).Red[(_y * FXSize) + _x]; end; function T2DImageRGBALongData.GetGreenPixelColor(_x,_y: integer):single; begin Result := (FData as TRGBALongDataSet).Green[(_y * FXSize) + _x]; end; function T2DImageRGBALongData.GetBluePixelColor(_x,_y: integer):single; begin Result := (FData as TRGBALongDataSet).Blue[(_y * FXSize) + _x]; end; function T2DImageRGBALongData.GetAlphaPixelColor(_x,_y: integer):single; begin Result := (FData as TRGBALongDataSet).Alpha[(_y * FXSize) + _x]; end; // Sets procedure T2DImageRGBALongData.SetBitmapPixelColor(_Position, _Color: longword); begin (FData as TRGBALongDataSet).Red[_Position] := GetRValue(_Color); (FData as TRGBALongDataSet).Green[_Position] := GetGValue(_Color); (FData as TRGBALongDataSet).Blue[_Position] := GetBValue(_Color); end; procedure T2DImageRGBALongData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); begin (FData as TRGBALongDataSet).Red[_Position] := _r; (FData as TRGBALongDataSet).Green[_Position] := _g; (FData as TRGBALongDataSet).Blue[_Position] := _b; (FData as TRGBALongDataSet).Alpha[_Position] := _a; end; procedure T2DImageRGBALongData.SetRedPixelColor(_x,_y: integer; _value:single); begin (FData as TRGBALongDataSet).Red[(_y * FXSize) + _x] := Round(_value); end; procedure T2DImageRGBALongData.SetGreenPixelColor(_x,_y: integer; _value:single); begin (FData as TRGBALongDataSet).Green[(_y * FXSize) + _x] := Round(_value); end; procedure T2DImageRGBALongData.SetBluePixelColor(_x,_y: integer; _value:single); begin (FData as TRGBALongDataSet).Blue[(_y * FXSize) + _x] := Round(_value); end; procedure T2DImageRGBALongData.SetAlphaPixelColor(_x,_y: integer; _value:single); begin (FData as TRGBALongDataSet).Alpha[(_y * FXSize) + _x] := Round(_value); end; procedure T2DImageRGBALongData.SetData(_x, _y, _c: integer; _value: longword); begin if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then begin case (_c) of 0: (FData as TRGBALongDataSet).Red[(_y * FXSize) + _x] := _value; 1: (FData as TRGBALongDataSet).Green[(_y * FXSize) + _x] := _value; 2: (FData as TRGBALongDataSet).Blue[(_y * FXSize) + _x] := _value; 3: (FData as TRGBALongDataSet).Alpha[(_y * FXSize) + _x] := _value; end; end; end; procedure T2DImageRGBALongData.SetDefaultColor(_value: TPixelRGBALongData); begin FDefaultColor.r := _value.r; FDefaultColor.g := _value.g; FDefaultColor.b := _value.b; FDefaultColor.a := _value.a; end; // Copies procedure T2DImageRGBALongData.Assign(const _Source: TAbstract2DImageData); begin inherited Assign(_Source); FDefaultColor.r := (_Source as T2DImageRGBALongData).FDefaultColor.r; FDefaultColor.g := (_Source as T2DImageRGBALongData).FDefaultColor.g; FDefaultColor.b := (_Source as T2DImageRGBALongData).FDefaultColor.b; FDefaultColor.a := (_Source as T2DImageRGBALongData).FDefaultColor.a; end; // Misc procedure T2DImageRGBALongData.ScaleBy(_Value: single); var x,maxx: integer; begin maxx := (FXSize * FYSize) - 1; for x := 0 to maxx do begin (FData as TRGBALongDataSet).Red[x] := Round((FData as TRGBALongDataSet).Red[x] * _Value); (FData as TRGBALongDataSet).Green[x] := Round((FData as TRGBALongDataSet).Green[x] * _Value); (FData as TRGBALongDataSet).Blue[x] := Round((FData as TRGBALongDataSet).Blue[x] * _Value); (FData as TRGBALongDataSet).Alpha[x] := Round((FData as TRGBALongDataSet).Alpha[x] * _Value); end; end; procedure T2DImageRGBALongData.Invert; var x,maxx: integer; begin maxx := (FXSize * FYSize) - 1; for x := 0 to maxx do begin (FData as TRGBALongDataSet).Red[x] := 255 - (FData as TRGBALongDataSet).Red[x]; (FData as TRGBALongDataSet).Green[x] := 255 - (FData as TRGBALongDataSet).Green[x]; (FData as TRGBALongDataSet).Blue[x] := 255 - (FData as TRGBALongDataSet).Blue[x]; (FData as TRGBALongDataSet).Alpha[x] := 255 - (FData as TRGBALongDataSet).Alpha[x]; end; end; end.
unit Flix.Utils.Maps; interface uses Classes, SysUtils, TypInfo, System.Generics.Collections, VCL.TMSFNCMaps; type TMapService = TTMSFNCMapsService; TServiceAPIKeyDict = TDictionary<TMapService, string>; TNamesDict = TDictionary<TMapService, string>; TServicesDict = TDictionary<string, TMapService>; TServiceAPIKeys = class private FDict : TServiceAPIKeyDict; FNames: TNamesDict; FServices: TServicesDict; FFilename: String; // remembers service key that was retrieved last FLastService: TMapService; procedure InitServiceNames; public constructor Create; overload; constructor Create( AFilename: String ); overload; destructor Destroy; override; procedure AddKey( const AService: TMapService; const AKey: String); function GetKey( const AService: TMapService ): string; procedure SaveToFile( const AFilename: String ); procedure LoadFromFile( const AFilename: String ); function GetAllServices : TArray<TMapService>; function GetAllNames : TArray<string>; procedure GetServices( AList: TList<TMapService> ); function GetNameForService( AService: TMapService ) :String; function GetServiceForName( AName: String ) : TMapService; published property Filename: String read FFilename write FFilename; property LastService: TMapService read FLastService write FLastService; end; implementation uses AesObj, MiscObj; const KEY = 'Z$)5^*lQ)YE47]>8{w-kuv746wRLMJiBsPJk5dB=!cjB~)c6M4H:N]X]sZT0+Cfl'; HEADER : TBytes = [ 64, 80, 73, 1]; { TServiceAPIKeys } procedure TServiceAPIKeys.AddKey(const AService: TMapService; const AKey: String); begin FDict.Add(AService, AKey); end; constructor TServiceAPIKeys.Create; begin inherited; FDict := TServiceAPIKeyDict.Create; FNames := TNamesDict.Create; FServices := TServicesDict.Create; InitServiceNames; end; constructor TServiceAPIKeys.Create(AFilename: String); begin self.Create; self.LoadFromFile(AFilename); end; destructor TServiceAPIKeys.Destroy; begin FDict.Free; FNames.Free; FServices.Free; inherited; end; function TServiceAPIKeys.GetAllNames: TArray<string>; begin Result := FNames.Values.ToArray; end; function TServiceAPIKeys.GetAllServices: TArray<TMapService>; begin Result := FNames.Keys.ToArray; end; function TServiceAPIKeys.GetKey(const AService: TMapService): string; begin FLastService := AService; Result := FDict[ AService ]; end; function TServiceAPIKeys.GetNameForService(AService: TMapService): String; begin Result := FNames[AService]; end; function TServiceAPIKeys.GetServiceForName(AName: String): TMapService; begin Result := FServices[AName]; end; procedure TServiceAPIKeys.GetServices(AList: TList<TMapService>); var LService: TMapService; begin if Assigned( AList ) then begin AList.Clear; for LService in FDict.Keys do begin AList.Add( LService ); end; end else raise EArgumentNilException.Create('AList cannot be nil.'); end; procedure TServiceAPIKeys.InitServiceNames; var LService: TMapService; LName: String; begin FNames.Clear; FNames.Add(msGoogleMaps, 'Google Maps'); FNames.Add(msHere, 'Here'); FNames.Add(msAzureMaps, 'Microsoft Azure Maps'); FNames.Add(msBingMaps, 'Microsoft Bing Maps'); FNames.Add(msTomTom, 'TomTom'); FNames.Add(msMapBox, 'MapBox'); FNames.Add(msOpenLayers, 'OpenLayers'); for LService in FNames.Keys do begin LName:= FNames[LService]; FServices.Add(LName, LService); end; end; procedure TServiceAPIKeys.LoadFromFile(const AFilename: String); var LKey: String; LValue: String; LService: TMapService; LAES : TAESEncryption; LStream: TBinaryReader; LHeader: TBytes; LCount : Integer; LHeadEq: Boolean; i : Integer; begin LAES := TAESEncryption.Create; LStream := TBinaryReader.Create( AFilename ); FDict.Clear; try LAES.Unicode := yesUni; LAES.AType := atECB; LAES.keyLength := kl256; LAES.key := COPY( KEY, 10, 32 ); LAES.paddingMode := TPaddingMode.PKCS7; LAES.IVMode := TIVMode.rand; // header LHeader := LStream.ReadBytes(Length(HEADER)); LHeadEq := True; for i := Low( LHeader) to High( LHeader ) do begin if LHeader[i] <> HEADER[i] then begin LHeadEq := False; break; end; end; if NOT LHeadEq then begin raise Exception.Create('Invalid file format.'); end; // read number of services LCount := LStream.ReadInteger; for i := 1 to LCount do begin LKey := LAES.Decrypt( LStream.ReadString ); LValue := LAES.Decrypt( LStream.ReadString ); LService := TMapService( GetEnumValue( TypeInfo( TMapService ), LKey ) ); FDict.Add( LService, LValue ); end; Filename := AFilename; LStream.Close; finally LStream.Free; LAES.Free; end; end; procedure TServiceAPIKeys.SaveToFile(const AFilename: String); var LService: TMapService; LKey, LValue: String; LAES: TAESEncryption; LStream: TBinaryWriter; begin LAES := TAESEncryption.Create; LStream := TBinaryWriter.Create( AFilename ); try LAES.Unicode := yesUni; LAES.AType := atECB; LAES.keyLength := kl256; LAES.key := COPY( KEY, 10, 32 ); LAES.paddingMode := TPaddingMode.PKCS7; LAES.IVMode := TIVMode.rand; // header LStream.Write(HEADER); // number of services LStream.Write( Integer( FDict.Keys.Count ) ); for LService in FDict.Keys do begin LValue := FDict[ LService ]; LKey := GetEnumName( TypeInfo( TMapService ), ORD( LService ) ); LStream.Write( LAES.Encrypt( LKey ) ); LStream.Write( LAES.Encrypt( LValue ) ); end; LStream.Close; Filename := AFilename; finally LStream.Free; LAES.Free; end; end; end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.Logger.RuntimeErrorHook Description : Log Runtime Errors Author : Kike Pérez Version : 1.20 Created : 28/03/2019 Modified : 28/03/2019 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** 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 Quick.Logger.RuntimeErrorHook; {$i QuickLib.inc} interface implementation uses SysUtils, System.TypInfo, Quick.Logger; //var //RealErrorProc : procedure (ErrorCode: Byte; ErrorAddr: Pointer); procedure HandleErrorProc(ErrorCode : Byte; ErrorPtr : Pointer); var errorname : string; begin if Assigned(GlobalLoggerRuntimeError) then begin errorname := GetEnumName(TypeInfo(TRuntimeError), ErrorCode); GlobalLoggerRuntimeError(errorname,ErrorCode,ErrorPtr); end; end; initialization //RealErrorProc := ErrorProc; ErrorProc := HandleErrorProc; //runtime errors end.
unit LIB.List2; interface //#################################################################### ■ uses LIB.List1; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【インタフェース】 IHead2 = interface; IKnot2 = interface; ITail2 = interface; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% IHead2 IHead2 = interface( IHead1 ) ///// アクセス function GetValue :Boolean; procedure SetValue( const Value_:Boolean ); ///// プロパティ property Value :Boolean read GetValue write SetValue; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% IKnot2 IKnot2 = interface( IKnot1 ) ///// アクセス function GetValue :Integer; procedure SetValue( const Value_:Integer ); ///// プロパティ property Value :Integer read GetValue write SetValue; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ITail2 ITail2 = interface( ITail1 ) ///// アクセス function GetValue :Double; procedure SetValue( const Value_:Double ); ///// プロパティ property Value :Double read GetValue write SetValue; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 THead2< _TNext_:IKnot2> = class; TKnot2<_TPrev_:IHead2;_TNext_:ITail2> = class; TTail2<_TPrev_:IKnot2 > = class; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% THead2<_TNext_> THead2<_TNext_:IKnot2> = class( THead1<_TNext_>, IHead2 ) protected _Value :Boolean; ///// アクセス function GetValue :Boolean; procedure SetValue( const Value_:Boolean ); public ///// プロパティ property Value :Boolean read GetValue write SetValue; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TKnot2<_TPrev_,_TNext_> TKnot2<_TPrev_:IHead2;_TNext_:ITail2> = class( TKnot1<_TPrev_,_TNext_>, IKnot2 ) protected _Value :Integer; ///// アクセス function GetValue :Integer; procedure SetValue( const Value_:Integer ); public ///// プロパティ property Value :Integer read GetValue write SetValue; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TTail2<_TPrev_> TTail2<_TPrev_:IKnot2> = class( TTail1<_TPrev_>, ITail2 ) protected _Value :Double; ///// アクセス function GetValue :Double; procedure SetValue( const Value_:Double ); public ///// プロパティ property Value :Double read GetValue write SetValue; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TList2<_THead_,_TTail_> TList2<_THead_:IHead2,constructor; _TKnot_:IKnot2,constructor; _TTail_:ITail2,constructor> = class( TList1<_THead_,_TKnot_,_TTail_> ) protected public constructor Create; destructor Destroy; override; end; implementation //############################################################### ■ uses System.SysUtils; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% THead2<_TNext_> function THead2<_TNext_>.GetValue :Boolean; begin Result := _Value; end; procedure THead2<_TNext_>.SetValue( const Value_:Boolean ); begin _Value := Value_; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TKnot2<_TPrev_,_TNext_> function TKnot2<_TPrev_,_TNext_>.GetValue :Integer; begin Result := _Value; end; procedure TKnot2<_TPrev_,_TNext_>.SetValue( const Value_:Integer ); begin _Value := Value_; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TTail2<_TPrev_> function TTail2<_TPrev_>.GetValue :Double; begin Result := _Value; end; procedure TTail2<_TPrev_>.SetValue( const Value_:Double ); begin _Value := Value_; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TList2<_THead_,_TKnot_,_TTail_> constructor TList2<_THead_,_TKnot_,_TTail_>.Create; begin inherited; _Head.Value := True; _Knot.Value := 10; _Tail.Value := 0.1; end; destructor TList2<_THead_,_TKnot_,_TTail_>.Destroy; begin inherited; end; end. //######################################################################### ■
unit HBarpcs; {******************************************************************************* Program Modifications: -------------------------------------------------------------------------------- Date UserId Description ------------------------------------------------------------------------------- 12-20-2006 GN01 Get the MaxValue for each question to calculate the length of the HBar. *******************************************************************************} interface uses sysutils,divlines,TextMeasure,Constants,arrows,scalelabels,hbars,HBHeaders,drawing,windows; function hbarpc(x:double; var y:double;h,w:double;pagenumber:integer;Job_id:string;cn:variant;componentid:string;BreakOut:boolean):string; implementation function hbarpc(x:double; var y:double;h,w:double;pagenumber:integer;Job_id:string;cn:variant;componentid:string;BreakOut:boolean):string; var x1,x2,x3, y1,y2,y3:double; i,j:integer; t2,s,strHeader:string; bg:carray; QuestionCompareField:string; cnt:integer; HBarLength:double;//BarLength r:double; //ratio fs:double; HbarPos:Double; rsColCount:variant; BookMark : Variant; strBreakout:string; MaxValue:Double; TempStr : string; begin QuestionCompareField := 'qstncore'; rsColCount:=cn.execute(Format('Select isnull(Column_Number,0) '+ 'from apo_compdetail where job_id = %s and Page_Number = %d '+ 'and Component_ID = %s',[Job_ID,pagenumber,componentid])); ColsCount:=rsColCount.fields[0].value; rsColCount.close; rsColCount:=Unassigned; fs:=8; HBarLength:=inch*1.65; bg:= GetShade([0.7, 0.7, 2],'rg'); //blue if (not morehbars) and (rs2.state = 1) then rs2.close; if (rs2.state = 1) then if ((rs2.eof) and (rs2.bof)) then rs2.close; if (not morehbars) and ( not (rs2.state = 1)) then begin //2013-0318 The compile BINARY was altered on this date on the wsPdfGen machine using a hex editor to execute the //the line below, using a permanent x table instead of the # temp table //the original line is left here commented //because this happens multiple times, the first statement is to delete records out of this new x table //the syntax of the queries was such that it would fit exactly into the same length of the existing queries in the binary //s:= format('SELECT QstnCore,count(QstnCore) as cnt into #qstncount '+ s:= format('delete x insert into x SELECT QstnCore,count(QstnCore) '+ 'FROM %0:s '+ 'WHERE page_number = %d and Job_id= %s and component_id = %s '+ 'group by QstnCore', [hbar_stats_final,pagenumber,Job_id,componentid]); cn.execute(s); s:=format('SELECT '+ 's.Sequence,'+ 's.qstncore,'+ 's.Order_Num,'+ 's.Rank,'+ 'l.Scale_Label,'+ 'l.current_label,'+ 's.Component_Label,'+ 'class_label,'+ 's.Value1,'+ 's.Value2,'+ 's.Value3,'+ 's.Value4,'+ 's.Value5,'+ 's.Value6,'+ 's.Value7,'+ 's.MaxValue,'+ 'Label1,'+ 'Label2,'+ 'Label3,'+ 'Label4,'+ 'Label5,'+ 'Label6,'+ 'Label7,'+ 's.ValueFormat1,'+ 's.ValueFormat2,'+ 's.ValueFormat3,'+ 's.ValueFormat4,'+ 's.ValueFormat5,'+ 's.ValueFormat6,'+ 's.ValueFormat7,'+ 's.Sig1,'+ 's.Sig2,'+ 's.Sig3,'+ 's.Sig4,'+ 's.Sig5,'+ 's.Sig6,'+ 's.Sig7, '+ 'q.cnt '+ 'FROM %4:s AS l INNER JOIN %3:s AS s '+ 'ON (s.Order_Num = l.Order_Num) '+ 'AND (l.Sequence = s.Sequence) '+ 'AND (l.Component_ID = s.Component_ID) '+ 'AND (l.Page_Number = s.Page_Number) '+ 'AND (l.Job_ID = s.Job_ID) '+ //2013-0318 The compile BINARY was altered on this date on the wsPdfGen machine using a hex editor to execute the //the line below, using a permanent x table instead of the # temp table //the original line is left here commented //'left join #qstncount as q on q.qstncore = s.qstncore '+ 'left join x as q on q.qstncore = s.qstncore '+ 'WHERE s.Job_ID = %0:s '+ 'AND s.Page_Number = %1:d '+ 'AND s.Component_ID = %2:s '+ 'order by s.sequence, s.Order_Num, rank', [Job_ID, pagenumber, componentid, hbar_stats_final, hbar_labels_final]); //0 1 2 3 4 rs2.open(s,cn,1,1); //2013-0318 The compile BINARY was altered on this date on the wsPdfGen machine using a hex editor to execute the //the line below, using a permanent x table instead of the # temp table //the original line is left here commented //cn.execute('drop table #qstncount'); cn.execute('/*******************/'); end; qstncore:='-1'; s:=''; if rs2.eof then begin result:=''; Morehbars:=false; exit; end; if not rs2.eof then begin CurCol:=strtoint(vartostr(rs2.fields['current_label'].value)); if ((MeasureType in[1,3]) and (not isPepC)) then MaxValue := strtofloat(GetVal(rs2.fields['MaxValue'].value)) else MaxValue := 100; end; //DrawHBLegend:=false; Grouping:=trim(vartostr(rs2.fields['Scale_Label'].value)); GetLabels(List,false); t2:='Detail'; strHeader:=GetHeader(y,List,TitleStr,t2,fs,CurCol,ColsCount,ColPos,HBarLength,SortLegend,false); y:=y-5; while not rs2.eof do begin cnt:=rs2.fields['cnt'].value; //GN01 if ((MeasureType in [1]) and (not isPepC)) then MaxValue := strtofloat(GetVal(rs2.fields['MaxValue'].value)); if MaxValue <= 0 then MaxValue := 1; r:= HBarLength/MaxValue; if (Scale <> trim(vartostr(rs2.fields['scale_label'].value))) or ((qstncore<>trim(vartostr(rs2.fields[QuestionCompareField].value))) ) then begin if breakout then begin Bookmark := rs2.Bookmark; strBreakout := s; end; if (y<(FooterHeight+10+(cnt*h*2))) and (cnt in [1..6]) then break; if y<(FooterHeight+40) then break; qstncore:=trim(vartostr(rs2.fields[QuestionCompareField].value)); lbl:=trim(vartostr(rs2.fields['component_label'].value)); s:=strHeader+s+divline(y); HbarPos:= ColPos[CurCol]; ActiveFont:='/F2'; y:=y-fs*1.3; if breakout then s:=s+TextAt(HbarPos,y,'',fs,lbl,round(CurColWidth+HBarLength),'C',false,'') else s:=s+TextAt(HbarPos,y,'',fs,lbl,round(CurColWidth+HBarLength),'C',false,''); ActiveFont:='/F1'; Scale:=trim(vartostr(rs2.fields['scale_label'].value)); y:=yGlobal+fs; strHeader:=''; if breakout then begin s:=s+GetScaleLabel(2,Scale,'',HbarPos+20,y,false,fs); end else s:=s+GetScaleLabel(MeasureType,Scale,Grouping,HbarPos+20,y,false,fs); y:=y-20; end; w:=strToFloat(GetVal(rs2.fields[Format('value%d',[CurCol])].value)); //w:=100.0; x:=HbarPos; if w > -1 then begin x1 := x+w*r; intFormat:=rs2.fields[Format('ValueFormat%d',[CurCol])].value; end else x1:=x; lbl:=trim(vartostr(rs2.fields['class_label'].value)); ActiveFont:='/F1'; s:=s+format('0 g /F1 %f Tf '#10,[fs]); //if random(2) = 1 then // lbl := 'this is a very very long lable that will make lines wrap to three or even more lines or even longer than that'; TempStr := TextAt(x-3,y+h*0.2,'',fs,lbl,round(CurColWidth),'R',true,''); if LinesHeight > h*1.25 then begin y:= y-LinesHeight+fs; TempStr := TextAt(x-3,y,'',fs,lbl,round(CurColWidth),'R',true,''); end; s:=s+TempStr; x2 := x1 +(h/2); x3 := x + (h/2); y1 := y + (h/2); y2 := y1 + h; y3 := y + h; if (w >-1) then begin s:= s+hbar( x,y,h,w*r,bg); List[CurCol]:=FormatFloat(Formats[intFormat],round(w*10000)*0.0001); s:=s+TextAt(1+x1+h*0.5,y1,'',fs,list[CurCol],50,'L',false,''); end; //values other than hbarpc's j:=0; for i:=1 to ColsCount do List[i]:=''; for i:=1 to ColsCount do if ((i<>CurCol) and (not (i in MissingColumns))) then begin w:=strToFloat(GetVal(rs2.fields[Format('value%d',[i])].value)); if ShowSig then Sig[i]:=(trim(vartostr(rs2.fields[format('Sig%d',[i])].value))+' ')[1]; if (w > -1) then begin if IsCor[i] then intFormat:=4 else intFormat:=rs2.fields[Format('ValueFormat%d',[i])].value; List[i]:=FormatFloat(Formats[intFormat],round(w*10000)*0.0001); s:=s+TextAt( ColPos[i],y1,'',fs,List[i],round(ColWidth[i]),'C',false,''); if ShowSig then s:=s+DrawArrow(SigArrowPos-2,y1,fs,'0 g',sig[i]); end; j:=i; end; y:=y-(h*2); rs2.movenext; if y<(FooterHeight+h) then break; end; //while not rs2.eof Morehbars:= rs2.eof = false; if MoreHbars then begin if Breakout then begin s:=StrBreakout; rs2.Bookmark := Bookmark; end; end else rs2.close; result:=s; end; end.
///msg "Andrey" Это сообщение из коммандной строки! unit uCommLine; { TSharedMem } { This class simplifies the process of creating a region of shared memory. In Win32, this is accomplished by using the CreateFileMapping and MapViewOfFile functions. } interface uses SysUtils, Classes, Windows; type { THandledObject } { This is a generic class for all encapsulated WinAPI's which need to call CloseHandle when no longer needed. This code eliminates the need for 3 identical destructors in the TEvent, TMutex, and TSharedMem classes which are descended from this class. } THandledObject = class(TObject) protected FHandle: THandle; public destructor Destroy; override; property Handle: THandle read FHandle; end; TSharedMem = class(THandledObject) private FName: string; FSize: Integer; FCreated: Boolean; FFileView: Pointer; public constructor Create(const Name: string; Size: Integer); destructor Destroy; override; property Name: string read FName; property Size: Integer read FSize; property Buffer: Pointer read FFileView; property Created: Boolean read FCreated; end; const ShareMemSize = 100; type TCommandLine = class(TObject) private //ВНИМАНИЕ! Этот процес взаимодействия ТОЛЬКО 2х процессов! //больше нельзя!!! Для этого нужно прикрутить сюда мьютекс! //Взаимодействие процессов происходит следующим образом: //в начале общей памяти, первые 2а байта это ProcessId, того //процесса, которые записал данные или $FF $FF, если 2й процесс //считал данные //если тригер = $ffff, то любой процесс может записать что хочет. //1. если процесс хочет что-то записать, он проверяет, что тригер = 0 //2. устанавливает тригер = FProcessId и записывает. { Private declarations } FProcessId: DWORD; SharedMem: TSharedMem; Buffer: array [0..103] of byte; FMemFileName: string; FCommand : String; FTrigger: DWord; FIncommigCommand: boolean; FFirstCopyApplication: boolean; Function GetIncommigState():boolean; Function GetCommand():string; Procedure SendCommand(Cmd:string); Function GetTrigger():Dword; Procedure SetTrigger(TriggerState:Dword); property Trigger: Dword read GetTrigger write SetTrigger; public { Public declarations } LastError: DWORD; constructor Create(MemFileName:String); destructor Destroy; override; property IncommigCommand: boolean read GetIncommigState write FIncommigCommand; property FirstCopyApplication: boolean read FFirstCopyApplication write FFirstCopyApplication; property Command: string read GetCommand write SendCommand; end; implementation procedure Error(const Msg: string); begin // MessageBox(0, PChar(Msg), PChar('Error') ,mb_ok); raise Exception.Create(Msg); end; destructor THandledObject.Destroy; begin if FHandle <> 0 then CloseHandle(FHandle); end; { TSharedMem } constructor TSharedMem.Create(const Name: string; Size: Integer); begin try FName := Name; FSize := Size; { CreateFileMapping, when called with $FFFFFFFF for the hanlde value, creates a region of shared memory } FHandle := OpenFileMapping(FILE_MAP_WRITE, true, PChar(Name)); // if GetLastError = ERROR_FILE_NOT_FOUND then // if GetLastError <> ERROR_FILE_EXISTS then //ERROR_ACCESS_DENIED if GetLastError = ERROR_ACCESS_DENIED then begin FName := FName + inttostr(Round(Random*100)); Error(Format('TSharedMem: Error OpenFileMapping "%s", GetLastError = %d', [Name, GetLastError])); // abort; end; FHandle := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0, Size, PChar(Name)); if FHandle = 0 then abort; FCreated := GetLastError = 0; { We still need to map a pointer to the handle of the shared memory region } FFileView := MapViewOfFile(FHandle, FILE_MAP_WRITE, 0, 0, Size); if FFileView = nil then abort; except Error(Format('TSharedMem: Error creating shared memory %s (%d)', [Name, GetLastError])); end; end; destructor TSharedMem.Destroy; begin if FFileView <> nil then UnmapViewOfFile(FFileView); inherited Destroy; end; { TCommandLine } constructor TCommandLine.Create(MemFileName:String); //var // i: integer; // TempId: DWord; // MemHnd: hwnd; begin FProcessId := GetCurrentProcessId(); FMemFileName := MemFileName; try SharedMem := TSharedMem.Create(FMemFileName, ShareMemSize); except Error(Format('TCommandLine: Error creating shared memory %s (%d)', [FMemFileName, GetLastError])); end; if Trigger = 0 then begin FirstCopyApplication := true; Trigger := $FFFF; end else FirstCopyApplication := false; end; destructor TCommandLine.Destroy; begin SharedMem.Free; end; Function TCommandLine.GetTrigger():Dword; begin //проверяем состояние триггера! FTrigger := $FFFF; copymemory(@FTrigger, SharedMem.Buffer, 2); result := FTrigger; end; Procedure TCommandLine.SetTrigger(TriggerState:Dword); begin //устанавливаем состояние триггера! copymemory(SharedMem.Buffer, @TriggerState, 2); //MessageBox(0, PChar('SetTrigger'), PChar(inttostr(TriggerState)) ,mb_ok); end; Function TCommandLine.GetIncommigState():boolean; begin //проверяем есть ли входящее сообщение? if (Trigger <> $0000) and (Trigger <> $FFFF) and (Trigger <> FProcessId) then begin FIncommigCommand := true; result := true; end else begin FIncommigCommand := false; result := false; end; end; Function TCommandLine.GetCommand():string; var P:^byte; begin fcommand := ''; //читаем состояние тригера if IncommigCommand = true then begin //считываем команду из другого приложения copymemory(@buffer, SharedMem.Buffer, ShareMemSize); //пропускаем первые 2 байта (там триггер) p := @buffer; inc(p);inc(p); fcommand := PChar(p); //очищаем общую память ZeroMemory(@buffer, SizeOf(buffer)); copymemory(SharedMem.Buffer, @buffer, ShareMemSize); //сбрасываем триггер готовности для следующей команды Trigger := $FFFF; end; result := fcommand; end; Procedure TCommandLine.SendCommand(Cmd:string); var P:^byte; begin //проверяем состояние триггера! //он должен быть равен 0, т.е. предыдущая команда должна быть выполнена. if Trigger = $FFFF then begin //Записываем команду в общую память p := SharedMem.Buffer; inc(p);inc(p); copymemory(p, PChar(Cmd), length(Cmd) + 2); //устанавливаем тригер //команда может быть считана из SharedMem! Trigger := FProcessId; end; end; end.
unit uCamHelper; interface uses Windows, SysUtils, Classes, vcl.Graphics, VFrames; type TResolution = packed record W: Integer; H: Integer; end; type TCamHelper = class constructor Create(Handle: THandle); destructor Destroy; override; private Vid : TVideoImage; FCamNumber, FCamCount: Integer; FStarted: Boolean; public function StartCam(CamNumber: Integer; Resolution: Integer = 0): Boolean; function SetResolution(Resolution: Integer): Boolean; procedure StopCam; function GetImage(BMP: TBitmap; Timeout: Cardinal = INFINITE): Boolean; function GetCams: String; function GetResolutions(CamNumber: Integer): String; function GetFullList: String; function CurrentSize: TResolution; property Started: Boolean read FStarted; property CamNumber: Integer read FCamCount; property CamCount: Integer read FCamCount; end; var CamHelper: TCamHelper; implementation constructor TCamHelper.Create(Handle: THandle); begin FCamNumber := 0; Vid := TVideoImage.Create(Handle); end; function TCamHelper.StartCam(CamNumber: Integer; Resolution: Integer = 0): Boolean; begin Result := False; if Started and (FCamNumber = CamNumber) then Exit; StopCam; FStarted := Vid.VideoStart('#' + IntToStr(CamNumber), Resolution - 1); if Started then begin FCamNumber := CamNumber; end; Result := Started; end; function TCamHelper.GetImage(BMP: TBitmap; Timeout: Cardinal = INFINITE): Boolean; begin Result := False; if not Started then Exit; if Vid.HasNewFrame(1000) and FStarted then Result := Vid.GetBitmap(BMP); end; function TCamHelper.SetResolution(Resolution: Integer): Boolean; begin if Started and (FCamNumber > 0) then Result := Vid.SetResolutionByIndex(Resolution - 1) else Result := False; end; procedure TCamHelper.StopCam; begin if Vid.VideoRunning then Vid.VideoStop; FStarted := False; end; function TCamHelper.GetCams: String; var SL: TStringList; begin Result := ''; SL := TStringList.Create; try Vid.GetListOfDevices(SL); FCamCount := SL.Count; SL.Delimiter := '|'; Result := SL.DelimitedText; finally SL.Free; end; end; function TCamHelper.GetResolutions(CamNumber: Integer): String; var SL: TStringList; begin Result := ''; SL := TStringList.Create; try Vid.GetListOfSupportedVideoSizes('#' + IntToStr(CamNumber), SL); SL.Insert(0, '(Default)'); SL.Delimiter := '|'; Result := SL.DelimitedText; finally SL.Free; end; end; function TCamHelper.GetFullList: String; var SL: TStringList; I: Integer; begin Result := ''; SL := TStringList.Create; try SL.Add(GetCams); for I := 0 to FCamCount - 1 do SL.Add(GetResolutions(I)); SL.Delimiter := '|'; Result := SL.DelimitedText; finally SL.Free; end; end; destructor TCamHelper.Destroy; begin Vid.Free; end; function TCamHelper.CurrentSize: TResolution; begin if not Started then begin Result.W := 0; Result.H := 0; end else begin Result.W := Vid.VideoWidth; Result.H := Vid.VideoHeight; end; end; end.
unit uDAOdescuento; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uEstructura; var f:TextFile; posicion: integer; const IMPORTE_MINIMO='importeMinimo='; DESCUENTO='porcentajeDescuento='; procedure CrearFichero(var f:TextFile); procedure CrearFicheroDescuento(); procedure ModificarDesc(var f:TextFile; cadena1, cadena2:string); function ObtenerDescuento():integer; function ObtenerDesc(var f:TextFile): integer; function ObtenerImporteMin(var f:TextFile): integer; function ObtenerImporteMinimo():integer; implementation procedure CrearFicheroDescuento(); begin CrearFichero(f); end; procedure CrearFichero(var f:TextFile); begin assignFile(f,FICHERO_DESCUENTO); try reset(f); closeFile(f); except rewrite(f); CloseFile(f); end; end; procedure ModificarDesc(var f:TextFile; cadena1, cadena2:string); begin try Rewrite(f); WriteLn(f,IMPORTE_MINIMO+cadena1); WriteLn(f,DESCUENTO+cadena2); CloseFile(f); finally end; end; function ObtenerDescuento():integer; begin ObtenerDescuento:=ObtenerDesc(f); end; function ObtenerDesc(var f:TextFile): integer; var linea:string; LongDescuento, posicion, Longlinea:integer; begin reset(f); LongDescuento:=length(DESCUENTO); while not eof(f) do begin readLn(f,linea); Longlinea:=length(linea); posicion:=pos(DESCUENTO,linea); if(posicion<>0) then begin ObtenerDesc:=StrToint(copy(linea,(LongDescuento+1),Longlinea)); end; end; end; function ObtenerImporteMinimo():integer; begin ObtenerImporteMinimo:=ObtenerImporteMin(f); end; function ObtenerImporteMin(var f:TextFile): integer; var linea:string; LongImporteMinimo, posicion, Longlinea:integer; begin reset(f); LongImporteMinimo:=length(IMPORTE_MINIMO); while not eof(f) do begin readLn(f,linea); Longlinea:=length(linea); posicion:=pos(IMPORTE_MINIMO,linea); if(posicion<>0) then begin ObtenerImporteMin:=StrToint(copy(linea,(LongImporteMinimo+1),Longlinea)); end; end; end; end.
unit NumberEdit; // ----------------------------------------------------------------------------- // NumberEdit コントロール ver.2.0.0 for Delphi XE3 // copyright (c) みず // ----------------------------------------------------------------------------- interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, Vcl.ClipBrd; type TNumberType = (ntDecimal, ntHex); TRoundMode = (rmDown, rmRound, rmUp); TLimitOption = (loMax, loMin); TLimitOptions = set of TLimitOption; TArrowKeyDirection = (adNone, adUp, adDown); TArrowKeyEvent = procedure(Sender: TObject; Direction: TArrowKeyDirection; var NewValue: Extended) of object; TNumberEdit = class(TCustomEdit) private { Private 宣言 } // フィールド FAlignment: TAlignment; FAllowKeys: Boolean; FChangeSave: Boolean; FComma: Boolean; FFigure: Integer; FFixed: Boolean; FIncrement: Extended; FKeyin: Boolean; FLimit: Boolean; FLimitOptions: TLimitOptions; FMax: Extended; FMaxIntLength: Integer; FMin: Extended; FOnArrowKeyChange: TArrowKeyEvent; FRoundMode: TRoundMode; FValue: Extended; FNumberType: TNumberType; FValidMinus: Boolean; FWrap: Boolean; FZeroEnabled: Boolean; FZeroVisible: Boolean; // ============== プライベートメソッド function FloatToString(AValue: Extended): string; function IsValidChar(Key: Char): Boolean; function RoundStr(S: string; const F: Integer): string; function SetShowText: string; function TextToValue(var S: string): Extended; // ============== メッセージ処理 procedure WMPaste(var Message: TWMPaste); message WM_PASTE; // ============== プロパティアクセス procedure SetValue(const Val: Extended); function GetIntValue: Integer; procedure SetComma(const Val: Boolean); procedure SetFigure(const Val: Integer); procedure SetNumberType(const Val: TNumberType); procedure SetMax(const Val: Extended); procedure SetMin(const Val: Extended); procedure SetFixed(const Val: Boolean); procedure SetLimit(const Val: Boolean); procedure SetValidMinus(const Value: Boolean); procedure SetAlignment(const Value: TAlignment); procedure SetLimitOptions(const Value: TLimitOptions); function GetAsInteger: Integer; procedure SetAsInteger(const Value: Integer); function GetAsInt64: Int64; procedure SetAsInt64(const Value: Int64); procedure SetZeroVisible(const AValue: Boolean); function GetAsText: string; function GetFormattedText: string; function IsIncrimentStored: Boolean; procedure SetZeroEnabled(const Value: Boolean); protected { Protected 宣言 } // ============== プロテクトメソッド procedure Change; override; procedure CreateParams(var Params: TCreateParams); override; procedure DoArrowKeyChange(Direction: TArrowKeyDirection; var NewValue: Extended); virtual; procedure DoEnter; override; procedure DoExit; override; function GetIncrement: Extended; virtual; procedure IncValue(Direction: TArrowKeyDirection); virtual; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure SetIncrement(const Value: Extended); virtual; public { Public 宣言 } // ============== プロパティ(public) // ----- 新規 property AsInt64: Int64 read GetAsInt64 write SetAsInt64; property AsInteger: Integer read GetAsInteger write SetAsInteger; property AsText: string read GetAsText; property FormattedText: string read GetFormattedText; property IntValue: Integer read GetIntValue; // ============== メソッド constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published 宣言 } // ============== プロパティ property Align; property Alignment: TAlignment read FAlignment write SetAlignment default taRightJustify; property AllowKeys: Boolean read FAllowKeys write FAllowKeys default False; property Anchors; property AutoSelect; property AutoSize; property BevelEdges; property BevelInner; property BevelKind; property BevelOuter; property BevelWidth; property BiDiMode; property BorderStyle; property Color; property Comma: Boolean read FComma write SetComma default False; property Constraints; property Ctl3D; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property Enabled; property Figure: Integer read FFigure write SetFigure default -1; property Fixed: Boolean read FFixed write SetFixed default False; property Font; property HideSelection; property ImeMode default imClose; property ImeName; property Increment: Extended read GetIncrement write SetIncrement stored IsIncrimentStored; property Limit: Boolean read FLimit write SetLimit default False; property LimitOptions: TLimitOptions read FLimitOptions write SetLimitOptions; property MaxLength; property NumberType: TNumberType read FNumberType write SetNumberType default ntDecimal; property Max: Extended read FMax write SetMax; property MaxIntLength: Integer read FMaxIntLength write FMaxIntLength default 0; property Min: Extended read FMin write SetMin; property OEMConvert; property ParentColor; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property ReadOnly; property RoundMode: TRoundMode read FRoundMode write FRoundMode default rmDown; property ShowHint; property TabOrder; property TextHint; property ValidMinus: Boolean read FValidMinus write SetValidMinus default False; property Value: Extended read FValue write SetValue; property Visible; property Wrap: Boolean read FWrap write FWrap default False; property ZeroEnabled: Boolean read FZeroEnabled write SetZeroEnabled default True; property ZeroVisible: Boolean read FZeroVisible write SetZeroVisible default True; // =============== イベント property OnArrowKeyChange: TArrowKeyEvent read FOnArrowKeyChange write FOnArrowKeyChange; property OnCanResize; property OnChange; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDblClick; property OnDockDrop; property OnDockOver; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseActivate; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; procedure Register; implementation procedure Register; begin RegisterComponents('MIZU', [TNumberEdit]); end; var FormatSets: TFormatSettings; { TNumberEdit } // ****************************************************** Changeイベントメソッド procedure TNumberEdit.Change; var MinusFlag: Boolean; S: string; Cp: Integer; Len: Integer; V: Int64; begin if FChangeSave then Exit; S := Text; if not ((S = '') or (S = '-') or (S = '+')) then begin FValue := TextToValue(S); // ================================================= コンマの自動挿入 == if FComma and (FNumberType = ntDecimal) then begin MinusFlag := S[1] = '-'; Cp := Pos(FormatSets.DecimalSeparator, S); Len := Length(Text); if Cp = 0 then begin V := StrToInt64Def(S, 0); S := FormatFloat('#,##0', V); end else begin V := StrToInt64Def(Copy(S, 1, Cp - 1), 0); S := FormatFloat('#,##0', V) + Copy(S, Cp, Len - Cp + 1); end; if MinusFlag and (S[1] <> '-') then S := '-' + S; Cp := SelStart; FChangeSave := True; Text := S; if Len < Length(S) then Inc(Cp) else if Len > Length(S) then Dec(Cp); if Cp <= Length(S) then SelStart := Cp else SelStart := Length(S); FChangeSave := False; FValue := StrToFloat(RoundStr(Text, FFigure)); end else if FNumberType = ntDecimal then FValue := StrToFloat(RoundStr(Text, FFigure)); if FLimit then begin if (loMin in FLimitOptions) and (FValue < FMin) then FValue := FMin; if (loMax in FLimitOptions) and (FValue > FMax) then FValue := FMax; end; inherited; end else FValue := 0; end; // ************************************************************** コンストラクタ constructor TNumberEdit.Create(AOwner: TComponent); begin inherited; // フィールドのデフォルト設定 FFigure := -1; FValue := 0; FMax := 0; FMin := 0; FZeroVisible := True; FChangeSave := False; FLimit := False; FLimitOptions := [loMax, loMin]; FAlignment := taRightJustify; FIncrement := 1.0; FZeroEnabled := True; // プロパティのデフォルト設定 Text := '0'; ImeMode := imClose; end; // ******************************************************** CreateParamsメソッド procedure TNumberEdit.CreateParams(var Params: TCreateParams); begin inherited; // 右寄せ case FAlignment of taLeftJustify: Params.Style := Params.Style or ES_LEFT; taCenter : Params.Style := Params.Style or ES_CENTER; else Params.Style := Params.Style or ES_RIGHT; end; end; // **************************************************************** デストラクタ destructor TNumberEdit.Destroy; begin inherited; end; // ========================================================================== // method: OnArrowKeyChangeイベント生成 // ========================================================================== procedure TNumberEdit.DoArrowKeyChange(Direction: TArrowKeyDirection; var NewValue: Extended); begin if Assigned(FOnArrowKeyChange) then FOnArrowKeyChange(Self, Direction, NewValue); end; // ***************************************************** DoEnterイベントメソッド procedure TNumberEdit.DoEnter; begin if AutoSelect then begin SelStart := 0; SelLength := Length(Text); end else SelStart := Length(Text); inherited; FKeyin := False; end; // ****************************************************** DoExitイベントメソッド procedure TNumberEdit.DoExit; var S: string; begin // 入力テキストを表示テキストに変換 FChangeSave := True; S := Text; FValue := TextToValue(S); Text := SetShowText; Modified := FKeyin; inherited; FChangeSave := False; end; // ############################################################################# // ## メソッド: 実数を文字列に変換 function TNumberEdit.FloatToString(AValue: Extended): string; var Col: Integer; Cp: Integer; S, Res: string; begin Result := AnsiUpperCase(FloatToStr(AValue)); Cp := AnsiPos('E', Result); if Cp > 0 then begin S := Copy(Result, Cp + 2, Length(Result) - Cp + 1); Col := StrToInt(S); Res := StringOfChar('0', Col); if Result[Cp + 1] = '-' then begin Insert(FormatSets.DecimalSeparator, Res, 2); S := Copy(Result, 1, Cp - 1); Cp := AnsiPos(FormatSets.DecimalSeparator, S); if Cp > 0 then Delete(S, Cp, 1); Cp := AnsiPos('-', S); if Cp > 0 then begin Delete(S, Cp, 1); Result := '-' + Res + S; end else Result := Res + S; end else begin S := Copy(Result, 1, Cp - 1); Cp := AnsiPos(FormatSets.DecimalSeparator, S); if Cp > 0 then begin Col := Length(S) - Cp; if Col > 0 then Res := StringOfChar('0', Length(Res) - Col); Delete(S, Cp, 1); end; Result := S + Res; end; end; end; // ###################### AsInt64プロパティ取得<GetAsInt64アクセスメソッド> #### function TNumberEdit.GetAsInt64: Int64; var Cp: Integer; S: string; begin S := RoundStr(FloatToStr(FValue), 0); Cp := AnsiPos(FormatSets.DecimalSeparator, S); if Cp > 0 then S := Copy(S, 1, Cp - 1); Result := StrToInt64(S); end; // ################## AsIntegerプロパティ取得<GetAsIntegerアクセスメソッド> #### function TNumberEdit.GetAsInteger: Integer; begin Result := GetIntValue; end; // ############################################################################# // #### AsTextプロパティ取得 function TNumberEdit.GetAsText: string; var S: string; Sp: Integer; begin if FNumberType = ntDecimal then begin S := FloatToStr(Value); Sp := Pos(FormatSets.DecimalSeparator, S); if Sp = Length(S) then Result := Copy(S, 1, Sp - 1) else Result := S; end else begin if FValidMinus then begin Result := IntToHex(AsInt64, 1); if Pos('-', Text) = 1 then Result := '-' + Result; end else Result := IntToHex(AsInteger, 1); end; end; // ############################################################################# // #### FormattedTextプロパティ取得 function TNumberEdit.GetFormattedText: string; begin Result := SetShowText; end; // ========================================================================== // v method: Incrimentプロパティの取得 // ========================================================================== function TNumberEdit.GetIncrement: Extended; begin Result := FIncrement; end; // **************************************************** [取得]IntValueプロパティ function TNumberEdit.GetIntValue: Integer; var S: string; V: Int64; begin S := FloatToStr(FValue); S := RoundStr(S, 0); if Pos(FormatSets.DecimalSeparator, S) >= 1 then S := Copy(S, 1, Pos(FormatSets.DecimalSeparator, S) - 1); V := StrToInt64(S); if V < -MaxInt - 1 then Result := -MaxInt - 1 else if V > MaxInt then Result := MaxInt else Result := V; end; // ========================================================================== // v method: 数値のインクリメント // ========================================================================== procedure TNumberEdit.IncValue(Direction: TArrowKeyDirection); var NewValue: Extended; begin case Direction of adUp : NewValue := FValue + FIncrement; adDown: NewValue := FValue - FIncrement; else NewValue := FValue; end; if FLimit then begin if (loMin in FLimitOptions) and (NewValue < FMin) then begin if FWrap and (loMax in FLimitOptions) then NewValue := FMax else NewValue := FMin; end else if (loMax in FLimitOptions) and (NewValue > FMax) then begin if FWrap and (loMin in FLimitOptions) then NewValue := FMin else NewValue := FMax; end; end; DoArrowKeyChange(Direction, NewValue); SetValue(NewValue); end; // ========================================================================== // stored: Incriment // ========================================================================== function TNumberEdit.IsIncrimentStored: Boolean; begin Result := FIncrement <> 1.0; end; // ************************************** 入力キーが有効かどうかチェックする関数 function TNumberEdit.IsValidChar(Key: Char): Boolean; var Cp, L, Len: Integer; Flag: Boolean; S, SelStr: string; begin Result := (GetKeyState(VK_CONTROL) and $8000 <> 0); if FNumberType = ntDecimal then begin Result := Result or CharInSet(Key, [FormatSets.DecimalSeparator,'+','-','0'..'9', #$0008, #$0009, #$000D]); if (FMaxIntLength >= 1) and Result then begin Cp := Pos(FormatSets.DecimalSeparator, Text); if Cp = 0 then begin S := Text; Cp := Length(S) + 1; end else S := Copy(Text, 1, Cp - 1); Len := Length(S); for L := 1 to Length(S) do if CharInSet(S[L], [FormatSets.ThousandSeparator, '+', '-']) then Dec(Len); SelStr := SelText; Flag := not ((SelStr = FormatSets.ThousandSeparator) or (SelStr = FormatSets.DecimalSeparator) or (SelStr = '+') or (SelStr = '-') or (SelStr = '')) and (Cp > SelStart); Result := Result and (Len < FMaxIntLength) or CharInSet(Key, [FormatSets.DecimalSeparator, '+', '-', #$0008, #$0009, #$000D]) or (Cp <= SelStart) or Flag; end; end else Result := Result or CharInSet(Key, ['0'..'9','a'..'f','A'..'F', #$0008, #$0009, #$000D]) or (FValidMinus and (Key = '-')) or ((Key = '+') and (Text[1] = '-')); end; // ========================================================================== // ov method: KeyDown // ========================================================================== procedure TNumberEdit.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; if FAllowKeys then case Key of VK_UP : IncValue(adUp); VK_DOWN: IncValue(adDown); end; end; // **************************************************** KeyPressイベントメソッド procedure TNumberEdit.KeyPress(var Key: Char); var CursorCol: Integer; S: string; begin if not IsValidChar(Key) then Key := #0 else if (Key = '+') or (Key = '-') then begin CursorCol := SelStart; if (CursorCol = 0) and (SelLength >= 1) then begin S := Text; Delete(S, 1, SelLength); Text := S; end; if Key = '+' then begin if (FNumberType = ntHex) and (Pos('-', Text) >= 1) then Text := Copy(Text, 2, Length(Text) - 1) else if (Pos('+', Text) = 0) and (Pos('-', Text) = 0) then begin Text := '+' + Text; Inc(CursorCol); end else if Pos('-', Text) > 0 then Text := '+' + Copy(Text, 2, Length(Text) - 1) else begin Text := Copy(Text, 2, Length(Text) - 1); Dec(CursorCol); end; end else begin if (Pos('+', Text) = 0) and (Pos('-', Text) = 0) then begin Text := '-' + Text; Inc(CursorCol); end else if Pos('+', Text) > 0 then Text := '-' + Copy(Text, 2, Length(Text) - 1) else begin Text := Copy(Text, 2, Length(Text) - 1); Dec(CursorCol); end; end; if CursorCol < 0 then CursorCol := 0; SelStart := CursorCol; Key := #0; end else if Key = FormatSets.DecimalSeparator then if Pos(Key, Text) > 0 then Key := #0; if Key <> #0 then begin inherited KeyPress(Key); FKeyin := True; end; end; // ######################################### 数値を丸める<RoundStrメソッド> #### function TNumberEdit.RoundStr(S: string; const F: Integer): string; var ColUp: Integer; Cp: Integer; Deci: array of Byte; Lp: Integer; begin TextToValue(S); Cp := Pos(FormatSets.DecimalSeparator, S); if (Cp >= 1) and (Cp < Length(S)) and (F >= 0) then begin SetLength(Deci, Length(S) - Cp); for Lp := Cp + 1 to Length(S) do Deci[Lp - Cp - 1] := Ord(S[Lp]) - Ord('0'); if F < Length(Deci) then begin case FRoundMode of rmDown : ColUp := 0; rmRound: begin case Deci[F] of 0..4: ColUp := 0; else ColUp := 1; end; end; else begin ColUp := 0; for Lp := F to Length(Deci) - 1 do if Deci[Lp] >= 1 then ColUp := 1; end; end; if ColUp = 1 then begin Lp := F - 1; while (Lp >= 0) and (ColUp = 1) do begin Inc(Deci[Lp]); if Deci[Lp] >= 10 then Deci[Lp] := 0 else ColUp := 0; Dec(Lp); end; end; S := Copy(S, 1, Cp - 1); if ColUp = 1 then S := IntToStr(StrToInt(S) + 1); S := S + FormatSets.DecimalSeparator; for Lp := 0 to FFigure - 1 do S := S + IntToStr(Deci[Lp]); end; Result := S; end else Result := S; end; // ################## Alignmentプロパティ設定<SetAlignmentアクセスメソッド> #### procedure TNumberEdit.SetAlignment(const Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; // ###################### AsInt64プロパティ設定<SetAsInt64アクセスメソッド> #### procedure TNumberEdit.SetAsInt64(const Value: Int64); begin SetValue(Value); end; // ################## AsIntegerプロパティ設定<SetAsIntegerアクセスメソッド> #### procedure TNumberEdit.SetAsInteger(const Value: Integer); begin SetValue(Value); end; // ******************************************************* [設定]Commaプロパティ procedure TNumberEdit.SetComma(const Val: Boolean); begin FChangeSave := True; FComma := Val; Text := SetShowText; Invalidate; FChangeSave := False; end; // ****************************************************** [設定]Figureプロパティ procedure TNumberEdit.SetFigure(const Val: Integer); begin FFigure := Val; Text := SetShowText; Invalidate; end; // ******************************************************* [設定]Fixedプロパティ procedure TNumberEdit.SetFixed(const Val: Boolean); begin FFixed := Val; Text := SetShowText; Invalidate; end; // ========================================================================== // v method: Incrimantプロパティの設定 // ========================================================================== procedure TNumberEdit.SetIncrement(const Value: Extended); begin FIncrement := Value; end; // ################################################# [設定]Limitプロパティ ##### procedure TNumberEdit.SetLimit(const Val: Boolean); begin FLimit := Val; if FLimit and (not ((FValue = 0.0) and FZeroEnabled)) then begin if (loMin in FLimitOptions) and (FValue < FMin) then FValue := FMin; if (loMax in FLimitOptions) and (FValue > FMax) then FValue := FMax; Text := SetShowText; Invalidate; end; end; // ############ LimitOptionsプロパティ設定<SetLimitOptionsアクセスメソッド> #### procedure TNumberEdit.SetLimitOptions(const Value: TLimitOptions); begin FLimitOptions := Value; if FLimit and (not ((FValue = 0.0) and FZeroEnabled)) then begin if (loMin in Value) and (FValue < FMin) then FValue := FMin; if (loMax in Value) and (FValue > FMax) then FValue := FMax; Text := SetShowText; Invalidate; end; end; // ********************************************************* [設定]Maxプロパティ procedure TNumberEdit.SetMax(const Val: Extended); begin FMax := Val; if FMax < FMin then FMin := FMax; if ((FValue > FMax) or (FValue < FMin)) and FLimit and (loMax in FLimitOptions) then begin FValue := FMax; Text := SetShowText; Invalidate; end; end; // ********************************************************* [設定]Minプロパティ procedure TNumberEdit.SetMin(const Val: Extended); begin FMin := Val; if FMin > FMax then FMax := FMin; if ((FValue < FMin) or (FValue > FMax)) and FLimit and (loMin in FLimitOptions) then begin FValue := FMin; Text := SetShowText; Invalidate; end; end; // ************************************************** [設定]NumberTypeプロパティ procedure TNumberEdit.SetNumberType(const Val: TNumberType); var V: Integer; begin if FNumberType <> Val then begin case Val of ntDecimal: begin FNumberType := Val; Text := FloatToStr(FValue); end; ntHex: begin V := IntValue; FNumberType := Val; if FFigure >= 1 then Text := IntToHex(V, FFigure) else Text := IntToHex(V, 1); end; end; Invalidate; end; end; // ********************************************************* SetShowTextメソッド function TNumberEdit.SetShowText: string; var R: Extended; S, SS: string; Cp: Integer; isPlusMark, isMinusMark: Boolean; // マークの有無 V: Int64; begin if FLimit and (not ((FValue = 0.0) and FZeroEnabled)) then begin if (loMin in FLimitOptions) and (FValue < FMin) then FValue := FMin; if (loMax in FLimitOptions) and (FValue > FMax) then FValue := FMax; end; if FNumberType = ntHex then begin if FValidMinus then begin S := FloatToStr(FValue); FNumberType := ntDecimal; V := StrToInt64(RoundStr(S, 0)); FNumberType := ntHex; FValue := V; if FFigure >= 1 then S := IntToHex(Abs(V), FFigure) else S := IntToHex(Abs(V), 1); if V < 0 then S := '-' + S; end else begin S := FloatToStr(FValue); FNumberType := ntDecimal; V := StrToInt64(RoundStr(S, 0)); FNumberType := ntHex; if V > MaxInt then V := MaxInt else if V < -MaxInt - 1 then V := -MaxInt - 1; FValue := V; Cp := V; if FFigure >= 1 then S := IntToHex(Cp, FFigure) else S := IntToHex(Cp, 1); end; end else begin isPlusMark := Copy(Text, 1, 1) = '+'; // *********************************************** 数値を文字列に変換 ** S := FloatToString(FValue); S := RoundStr(S, FFigure); // ************************************************** 3桁ごとのコンマ ** if FComma then begin isMinusMark := Copy(S, 1, 1) = '-'; Cp := Pos(FormatSets.DecimalSeparator, S); if Cp = 0 then Cp := Length(S) + 1; SS := Copy(S, 1, Cp - 1); V := StrToInt(SS); SS := FormatFloat('#,##0', V); S := SS + Copy(S, Cp, Length(S) - Cp + 1); if isMinusMark and (Copy(S, 1, 1) <> '-') then S := '-' + S; end; // ************************************************* 小数点以下の桁数 ** if (FFigure >= 0) and FFixed then begin Cp := Pos(FormatSets.DecimalSeparator, S); if Cp = 0 then begin if FFigure >= 1 then S := S + FormatSets.DecimalSeparator + StringOfChar('0', FFigure); end else begin if FFigure = 0 then S := Copy(S, 1, Cp - 1) else begin Cp := Length(S) - Cp; if Cp < FFigure then S := S + StringOfChar('0', FFigure - Cp) else if Cp > FFigure then S := Copy(S, 1, Length(S) - (Cp - FFigure)); end; end; end; if isPlusMark then S := '+' + S; if S[Length(S)] = FormatSets.DecimalSeparator then S := Copy(S, 1, Length(S) - 1); end; SS := S; R := TextToValue(SS); if (R = 0.0) and not FZeroVisible then S := ''; Result := S; FValue := R; end; // ################ ValidMinusプロパティ設定<SetValidMinusアクセスメソッド> #### procedure TNumberEdit.SetValidMinus(const Value: Boolean); begin FValidMinus := Value; if FNumberType = ntHex then Text := SetShowText; end; // ******************************************************* [設定]Valueプロパティ procedure TNumberEdit.SetValue(const Val: Extended); begin if FLimit then begin if (Val = 0.0) and FZeroEnabled then FValue := Val else begin if (loMin in FLimitOptions) and (Val < FMin) then FValue := FMin else if (loMax in FLimitOptions) and (Val > FMax) then FValue := FMax else FValue := Val; end; end else FValue := Val; Text := SetShowText; end; // ========================================================================= // set: ZeroEnabled procedure TNumberEdit.SetZeroEnabled(const Value: Boolean); begin FZeroEnabled := Value; if not FZeroEnabled and FLimit and (FValue = 0.0) then begin if FMin > 0.0 then FValue := FMin else if FMax < 0.0 then FValue := FMax; end; end; // ############################################################################# // #### ZeroVisibleプロパティ設定: SetZeroVisibleアクセスメソッド procedure TNumberEdit.SetZeroVisible(const AValue: Boolean); var S: string; V: Extended; begin if AValue <> FZeroVisible then begin FZeroVisible := AValue; S := Text; V := TextToValue(S); if V = 0.0 then Text := SetShowText; end; end; // ################################ 文字列を数値に変換<TextToValueメソッド> #### function TNumberEdit.TextToValue(var S: string): Extended; var Cp: Integer; begin if not ((S = '') or (S = '-') or (S = '+')) then begin if FNumberType = ntDecimal then begin // ============================================= 文字列を数値に変更 == Cp := Length(S); while Cp > 0 do begin if (S[Cp] = FormatSets.ThousandSeparator) or (S[Cp] < #32) then Delete(S, Cp, 1); Dec(Cp); end; if S <> '' then begin if Pos(FormatSets.DecimalSeparator, S) = 0 then Result := StrToInt64(S) else Result := StrToFloat(S); end else Result := 0; end else begin if FValidMinus then begin if S[1] = '-' then Result := -StrToInt64('$' + Copy(S, 2, Length(S) - 1)) else Result := StrToInt64('$' + S); end else Result := StrToInt('$' + S); end; end else Result := 0; end; // *************************************************** WMPasteメッセージハンドラ procedure TNumberEdit.WMPaste(var Message: TWMPaste); var Ch: Char; Lp, Col, Loc: Integer; S, W, T: string; Check: Boolean; Pw: PChar; begin if ClipBoard.HasFormat(CF_TEXT) then begin Col := SelStart + 1; S := ClipBoard.AsText; T := Text; Delete(T, Col, SelLength); Lp := 1; Loc := Pos('-', T); if Col <= Loc then Exit; Loc := Pos('+' ,T); if Col <= Loc then Exit; while Lp <= Length(S) do begin W := Copy(S, Lp, 1); Pw := PChar(W); Ch := Pw^; if FNumberType = ntDecimal then Check := CharInSet(Ch, [FormatSets.DecimalSeparator, '+', '-', '0'..'9']) else Check := CharInSet(Ch, ['0'..'9', 'a'..'f', 'A'..'F']); if not Check then Delete(S, Lp, 1) else if (Ch = '+') or (Ch = '-') then begin if (Col <> 1) or (Lp > 1) then Delete(S, Lp, 1) else if (Pos('-', T) > 0) or (Pos('+', T) > 0) then Delete(S, Lp, 1) else begin Insert(Ch, T, Col); Inc(Lp); Inc(Col); end; end else if Ch = FormatSets.DecimalSeparator then begin if Pos(Ch, T) > 0 then Delete(S, Lp, 1) else begin Insert(Ch, T, Col); Inc(Col); Inc(Lp); end; end else begin Insert(Ch, T, Col); Inc(Col); Inc(Lp); end; end; Text := T; end; end; initialization FormatSets := TFormatSettings.Create; end.
unit ImageHistoryUnit; interface uses Graphics, Classes, uMemory; type THistoryAct = (THA_Redo, THA_Undo, THA_Add, THA_Unknown); THistoryAction = set of THistoryAct; TNotifyHistoryEvent = procedure(Sender: TObject; Action: THistoryAction) of object; type TBitmapHistoryItem = class(TObject) private FBitmap : TBitmap; FAction : string; public constructor Create(ABitmap : TBitmap; AAction : string); destructor Destroy; override; property Bitmap : TBitmap read FBitmap; property Action : string read FAction; end; TBitmapHistory = class(TObject) private { Private declarations } FArray: TList; FPosition: Integer; FOnChange: TNotifyHistoryEvent; procedure SetOnChange(const Value: TNotifyHistoryEvent); function GetImageByIndex(Index: Integer): TBitmap; function GetCount: Integer; function GetItemByIndex(Index: Integer): TBitmapHistoryItem; function GetActionByIndex(Index: Integer): string; protected property Items[Index : Integer] : TBitmapHistoryItem read GetItemByIndex; public { Public declarations } constructor Create; destructor Destroy; override; procedure Add(Image: TBitmap; Action: string); function CanBack: Boolean; function CanForward: Boolean; function GetCurrentPos: Integer; function DoBack: TBitmap; function DoForward: TBitmap; function LastImage: TBitmap; procedure Clear; property OnHistoryChange: TNotifyHistoryEvent read FOnChange write SetOnChange; property Images[Index : Integer] : TBitmap read GetImageByIndex; property Actions[Index : Integer] : string read GetActionByIndex; property Count : Integer read GetCount; property Position : Integer read FPosition; end; implementation { TBitmapHistory } procedure TBitmapHistory.Add(Image: TBitmap; Action : String); var I: Integer; procedure AddImage; var Item : TBitmapHistoryItem; begin Item := TBitmapHistoryItem.Create(Image, Action); FArray.Add(Item); FPosition := FArray.Count - 1; end; begin if FPosition = FArray.Count - 1 then AddImage else begin for I := FArray.Count - 1 downto FPosition + 1 do begin Items[I].Free; FArray.Delete(I); end; AddImage; end; if Assigned(OnHistoryChange) then OnHistoryChange(Self, [THA_Add]); end; function TBitmapHistory.CanBack: Boolean; begin if Fposition = -1 then begin Result := False; end else begin if FPosition > 0 then Result := True else Result := False; end; end; function TBitmapHistory.CanForward: Boolean; begin if FPosition = -1 then begin Result := False; Exit; end else begin if (Fposition <> FArray.Count - 1) and (FArray.Count <> 1) then Result := True else Result := False; end; end; procedure TBitmapHistory.Clear; var I: Integer; begin Fposition := -1; for I := 0 to Count - 1 do Items[I].Free; FArray.Clear; end; constructor TBitmapHistory.Create; begin inherited; FPosition := -1; FArray := TList.Create; FOnChange := nil; end; destructor TBitmapHistory.Destroy; begin Clear; F(FArray); inherited; end; function TBitmapHistory.DoBack: TBitmap; begin Result := nil; if FPosition = -1 then Exit; if FPosition = 0 then Result := TBitmapHistoryItem(FArray[0]).FBitmap else begin Dec(FPosition); Result := TBitmapHistoryItem(FArray[FPosition]).FBitmap; end; if Assigned(OnHistoryChange) then OnHistoryChange(Self, [THA_Undo]); end; function TBitmapHistory.DoForward: TBitmap; begin Result := nil; if FPosition = -1 then Exit; if (Fposition = FArray.Count - 1) or (FArray.Count = 1) then Result := Items[FArray.Count - 1].Bitmap else begin Inc(FPosition); Result := Items[FPosition].Bitmap; end; if Assigned(OnHistoryChange) then OnHistoryChange(Self, [THA_Redo]); end; function TBitmapHistory.GetActionByIndex(Index: Integer): string; begin Result := Items[Index].Action; end; function TBitmapHistory.GetCount: Integer; begin Result := FArray.Count; end; function TBitmapHistory.GetCurrentPos: integer; begin Result := FPosition + 1; end; function TBitmapHistory.GetImageByIndex(Index: Integer): TBitmap; begin Result := Items[Index].Bitmap; end; function TBitmapHistory.GetItemByIndex(Index: Integer): TBitmapHistoryItem; begin Result := FArray[Index]; end; function TBitmapHistory.LastImage: TBitmap; begin Result := nil; if FPosition = -1 then Exit; Result := Items[FPosition].Bitmap; end; procedure TBitmapHistory.SetOnChange(const Value: TNotifyHistoryEvent); begin FOnChange := Value; end; { TBitmapHistoryItem } constructor TBitmapHistoryItem.Create(ABitmap: TBitmap; AAction: string); begin FBitmap := TBitmap.Create; FBitmap.Assign(ABitmap); FAction := AAction; end; destructor TBitmapHistoryItem.Destroy; begin F(FBitmap); inherited; end; end.
Unit Un_PdfObjetos; Interface Uses Classes, Un_PdfXRef; Type //------------------------------------------------------------------------ TPdfTipoObjeto=(obj_boolean,obj_numero,obj_indireto,obj_string,obj_nome,obj_array,obj_dicionario,obj_stream,obj_nulo,obj_keyword,obj_embedded); //------------------------------------------------------------------------ TPdfObjeto=Class(TObject) Private stm_Dados:TStringStream; int_IdObj:Integer; obj_Tipo:TPdfTipoObjeto; obj_Conteudo:TObject; obj_XRef:TXRef; Public Constructor Create(Var stm_Dados:TStringStream;Var obj_XRef:TXRef;int_IdObj,int_GemObj:Integer;bol_TestaNumero:Boolean); Function ObtemValorString:String; Property Tipo:TPdfTipoObjeto Read obj_Tipo; Property Conteudo:TObject Read obj_Conteudo; Property Id:Integer Read int_IdObj; End; //------------------------------------------------------------------------ //Objetos do tipo numéricos TPdfObjNumerico=Class(TObject) Private flt_Valor:Extended; Public Constructor Create(Var stm_Dados:TStringStream;chr_Dado:AnsiChar); Function ObtemValorReal:Extended; Function ObtemValorInteiro:Int64; End; //------------------------------------------------------------------------ //Objetos do tipo string TPdfObjString=Class(TObject) Private str_Valor:String; Public Constructor Create(Var stm_Dados:TStringStream;bol_Hex:Boolean); Function ObtemValor:String; End; //------------------------------------------------------------------------ //Objetos do tipo palavra chave TPdfObjKeyword=Class(TObject) Private str_Valor:String; Public Constructor Create(Var stm_Dados:TStringStream;chr_Dado:AnsiChar); Function ObtemValor:String; End; //------------------------------------------------------------------------ //Objetos do tipo nome TPdfObjNome=Class(TObject) Private str_Valor:String; Public Constructor Create(Var stm_Dados:TStringStream); Function ObtemValor:String; End; //------------------------------------------------------------------------ //Objetos do tipo array TPdfObjArray=Class(TObject) Private lst_Valores:TList; int_Tam:Integer; Public Constructor Create(Var stm_Dados:TStringStream;Var obj_XRef:TXRef); Function ObtemValorItem(int_Indice:Integer):TPdfObjeto; Property Tamanho:Integer Read int_Tam; End; //------------------------------------------------------------------------ //Objetos do tipo dicionário TPdfObjDicionario=Class(TObject) Private stl_Conteudo:TStringList; int_Tam:Integer; Public Constructor Create(Var stm_Dados:TStringStream;Var obj_XRef:TXRef); Function ObtemValorChave(str_Chave:String):TPdfObjeto; Function ObtemValorItem(int_Indice:Integer):TPdfObjeto; Function ObtemNomeChave(int_Indice:Integer):String; Function ExisteChave(str_Chave:String):Boolean; Property Tamanho:Integer Read int_Tam; End; //------------------------------------------------------------------------ //Objeto stream TPdfObjStream=Class(TObject) Private obj_Metadados:TPdfObjDicionario; stm_Conteudo:TStringStream; int_TamStream:Int64; Public Constructor Create(Var stm_Dados:TStringStream;Var obj_XRef:TXRef;obj_Metadados:TPdfObjDicionario); Function ObtemValor:TStringStream; Function ObtemValorMetadado(str_Chave:String):TPdfObjeto; Property Tamanho:Int64 Read int_TamStream; End; //------------------------------------------------------------------------ //Objetos indiretos TPdfObjIndireto=Class(TObject) Private int_Id, int_Gen:Integer; Public Constructor Create(int_Id,int_Gen:Integer); Function ObtemId:Integer; Function ObtemGen:Integer; Function ObtemValorRef(Var obj_XRef:TXRef):TPdfObjeto; End; Implementation Uses Math, System.SysUtils, Un_PdfUtils; //----------------------------------------------------------------------------- // TPdfObjeto //----------------------------------------------------------------------------- Constructor TPdfObjeto.Create(Var stm_Dados:TStringStream;Var obj_XRef:TXRef;int_IdObj,int_GemObj:Integer;bol_TestaNumero:Boolean); Var bol_Terminou:Boolean; chr_Dado:AnsiChar; int_PosAnterior:Int64; obj_TestaNumero, obj_TestaR, obj_TestaObj, obj_TestaEnd:TPdfObjeto; int_Id, int_Gen:Integer; Begin Inherited Create; Self.int_IdObj:=int_IdObj; Self.stm_Dados:=stm_Dados; Self.obj_XRef:=obj_XRef; bol_Terminou:=False; //Enquanto tem dados para ler ... While Not bol_Terminou Do Begin stm_Dados.ReadBuffer(chr_Dado,1); If _EhCaractereBranco(chr_Dado) Then Begin While _EhCaractereBranco(chr_Dado) Do stm_Dados.ReadBuffer(chr_Dado,1); End; If chr_Dado='<' Then Begin //Lê de novo... stm_Dados.ReadBuffer(chr_Dado,1); //Achou outro "<"? If chr_Dado='<' Then Begin //Sim, então é dicionário Self.obj_Tipo:=obj_dicionario; Self.obj_Conteudo:=TPdfObjDicionario.Create(Self.stm_Dados,Self.obj_XRef); bol_Terminou:=True; End Else Begin //Não, então é um texto hexadecimal Self.obj_Tipo:=obj_string; stm_Dados.Position:=stm_Dados.Position-1; Self.obj_Conteudo:=TPdfObjString.Create(Self.stm_Dados,True); bol_Terminou:=True; End End Else If chr_Dado='(' Then Begin //É um texto literal Self.obj_Tipo:=obj_string; Self.obj_Conteudo:=TPdfObjString.Create(Self.stm_Dados,False); bol_Terminou:=True; End Else If chr_Dado='[' Then Begin //É um array Self.obj_Tipo:=obj_array; Self.obj_Conteudo:=TPdfObjArray.Create(Self.stm_Dados,Self.obj_XRef); bol_Terminou:=True; End Else If chr_Dado='/' Then Begin //É um nome Self.obj_Tipo:=obj_nome; Self.obj_Conteudo:=TPdfObjNome.Create(Self.stm_Dados); bol_Terminou:=True; End Else If chr_Dado='%' Then //É um comentário _BuscaLinha(stm_Dados) Else If (((chr_Dado>='0') And (chr_Dado<='9')) Or (chr_Dado='-') Or (chr_Dado='+') Or (chr_Dado='.')) Then Begin //É um número Self.obj_Tipo:=obj_numero; Self.obj_Conteudo:=TPdfObjNumerico.Create(Self.stm_Dados,chr_Dado); If Not bol_TestaNumero Then Begin //Pode ser o início de uma referência. int_PosAnterior:=stm_Dados.Position; //Busca o próximo objeto obj_TestaNumero:=TPdfObjeto.Create(Self.stm_Dados,Self.obj_XRef,-1,-1,True); //É objeto numérico? If (obj_TestaNumero<>Nil) And (obj_TestaNumero.Tipo=obj_numero) Then Begin //Sim, vamos buscar o próximo objeto obj_TestaR:=TPdfObjeto.Create(Self.stm_Dados,Self.obj_XRef,-1,-1,True); //É objeto palavra chave e seu conteúdo é "R" If (obj_TestaR<>Nil) And (obj_TestaR.Tipo=obj_keyword) And (obj_TestaR.ObtemValorString='R') Then Begin //Sim, então o objeto é indireto Self.obj_Tipo:=obj_indireto; //Obtém o conteúdo obtido int_Id:=TPdfObjNumerico(Self.obj_Conteudo).ObtemValorInteiro; int_Gen:=TPdfObjNumerico(obj_TestaNumero.obj_Conteudo).ObtemValorInteiro; //Limpa o conteúdo atual (não é mais numérico) Self.obj_Conteudo.Free; Self.obj_Conteudo:=TPdfObjIndireto.Create(int_Id,int_Gen); bol_Terminou:=True; End //É objeto palavra chave e seu conteúdo é "obj" Else If (obj_TestaR<>Nil) And (obj_TestaR.Tipo=obj_keyword) And (obj_TestaR.ObtemValorString='obj') Then Begin //Sim, então é um "obj", mas vamos verifica o próximo objeto... obj_TestaObj:=TPdfObjeto.Create(Self.stm_Dados,Self.obj_XRef,-1,-1,True); //... e o próximo... obj_TestaEnd:=TPdfObjeto.Create(Self.stm_Dados,Self.obj_XRef,-1,-1,True); //É palavra chave? If obj_TestaEnd.Tipo<>obj_keyword Then //Não, tá errado, é esperado as palavras chaves "stream" ou "endobj". Raise Exception.Create('Não foi encontrado "stream" ou "endobj"') Else Begin //O primeiro objeto é dicionário e o segundo é a palavra chave "stream"? If (obj_TestaObj.Tipo=obj_dicionario) And (obj_TestaEnd.ObtemValorString='stream') Then Begin //Sim, pula uma linha... _BuscaLinha(stm_Dados); //O objeto é stream Self.obj_Tipo:=obj_stream; //Carrega o conteúdo da stream Self.obj_Conteudo:=TPdfObjStream.Create(Self.stm_Dados,Self.obj_XRef,TPdfObjDicionario(obj_TestaObj.Conteudo)); //Limpa a variável "obj_TestaEnd". obj_TestaEnd.Free; //Busca o próximo objeto. obj_TestaEnd:=TPdfObjeto.Create(Self.stm_Dados,Self.obj_XRef,-1,-1,True); End Else Begin //Não, então é outro objeto, cujo conteúdo já foi lido na variável "obj_TestaObj". Self.obj_Tipo:=obj_TestaObj.Tipo; Self.obj_Conteudo:=obj_TestaObj.Conteudo; End; bol_Terminou:=True; End; If (obj_TestaEnd=Nil) Or (obj_TestaEnd.ObtemValorString<>'endobj') Then Raise Exception.Create('O objeto deve terminar com "endobj"'); End Else Begin stm_Dados.position:=int_PosAnterior; bol_Terminou:=True; End; End Else Begin stm_Dados.Position:=int_PosAnterior; bol_Terminou:=True; End; End Else bol_Terminou:=True; End Else If ((chr_Dado>='a') And (chr_Dado<='z')) Or ((chr_Dado>='A') And (chr_Dado<='Z')) Then Begin Self.obj_Tipo:=obj_keyword; Self.obj_Conteudo:=TPdfObjKeyword.Create(stm_Dados,chr_Dado); bol_Terminou:=True; End Else Begin // it's probably a closing character. // throwback Self.obj_Tipo:=obj_nulo; Self.obj_Conteudo:=Nil; stm_Dados.Position:=stm_Dados.Position-1; bol_Terminou:=True; End End; End; //----------------------------------------------------------------------------- Function TPdfObjeto.ObtemValorString:String; Var str_Result:String; I:Integer; Begin If Self.obj_Tipo=obj_boolean Then Begin End Else If Self.obj_Tipo=obj_numero Then Begin //Tem valores decimais? If TPdfObjNumerico(Self.obj_Conteudo).ObtemValorReal<>Int(TPdfObjNumerico(Self.obj_Conteudo).ObtemValorReal) Then Result:=FormatFloat('#.#',TPdfObjNumerico(Self.obj_Conteudo).ObtemValorInteiro) Else Result:=IntToStr(TPdfObjNumerico(Self.obj_Conteudo).ObtemValorInteiro); End Else If Self.obj_Tipo=obj_indireto Then Result:=IntToStr(TPdfObjIndireto(Self.Conteudo).int_Id)+' '+IntToStr(TPdfObjIndireto(Self.Conteudo).int_Gen)+' R' Else If Self.obj_Tipo=obj_string Then Result:=TPdfObjString(Self.Conteudo).str_Valor Else If Self.obj_Tipo=obj_nome Then Result:=TPdfObjString(Self.Conteudo).str_Valor Else If Self.obj_Tipo=obj_array Then Begin Result:='[ '; For I:=0 To TPdfObjArray(Self.Conteudo).int_Tam-1 Do Result:=Result+' '+TPdfObjArray(Self.Conteudo).ObtemValorItem(I).ObtemValorString; Result:=Result+' ]'; End Else If Self.obj_Tipo=obj_dicionario Then Begin Result:='<< '; For I:=0 To TPdfObjDicionario(Self.Conteudo).int_Tam-1 Do Begin Result:=Result+' /'+TPdfObjDicionario(Self.Conteudo).ObtemNomeChave(I); Result:=Result+' '+TPdfObjDicionario(Self.Conteudo).ObtemValorItem(I).ObtemValorString; End; Result:=Result+' >>'; End Else If Self.obj_Tipo=obj_stream Then Result:=TPdfObjStream(Self.Conteudo).stm_Conteudo.DataString Else If Self.obj_Tipo=obj_nulo Then Result:='' Else If Self.obj_Tipo=obj_keyword Then Result:=TPdfObjNome(Self.Conteudo).str_Valor Else If Self.obj_Tipo=obj_embedded Then Result:=''; End; //----------------------------------------------------------------------------- // TPdfObjNumerico //----------------------------------------------------------------------------- Constructor TPdfObjNumerico.Create(Var stm_Dados:TStringStream;chr_Dado:AnsiChar); Var bol_Negativo, bol_TemPonto:Boolean; flt_MultiploDecimal:Extended; chr_Valor:Char; Begin Inherited Create; //Verifica o primeiro caracter bol_Negativo:=chr_Dado='-'; bol_TemPonto:=chr_Dado='.'; flt_MultiploDecimal:=IfThen(bol_TemPonto,0.1,1); Self.flt_Valor:=IfThen((chr_Dado>='0') And (chr_Dado<='9'),Ord(chr_Dado)-Ord('0'),0); While True Do Begin stm_Dados.ReadBuffer(chr_Dado,1); If chr_Dado='.' Then Begin If bol_TemPonto Then Raise Exception.Create('Encontrado segundo "." no valor numérico'); bol_TemPonto:=True; flt_MultiploDecimal:=0.1; End Else If (chr_Dado>='0') And (chr_Dado<='9') Then Begin chr_Valor:=Chr(Ord(chr_Dado)-Ord('0')); If bol_TemPonto Then Begin Self.flt_Valor:=flt_Valor+Ord(chr_Valor)*flt_MultiploDecimal; flt_MultiploDecimal:=flt_MultiploDecimal*0.1; End Else flt_Valor:=Self.flt_Valor*10+Ord(chr_Valor); End Else Begin stm_Dados.position:=stm_Dados.position-1; Break; End; End; If bol_Negativo Then Self.flt_Valor:=-Self.flt_Valor; End; //----------------------------------------------------------------------------- Function TPdfObjNumerico.ObtemValorReal:Extended; Begin Try Result:=flt_Valor; Except On err_PdfObjeto:Exception Do Raise Exception.Create('Erro ao obter dado do objeto objeto '+Self.ClassName+': '+err_PdfObjeto.Message); End; End; //----------------------------------------------------------------------------- Function TPdfObjNumerico.ObtemValorInteiro:Int64; Begin Try Result:=Trunc(flt_Valor); Except On err_PdfObjeto:Exception Do Raise Exception.Create('Erro ao obter dado do objeto objeto '+Self.ClassName+': '+err_PdfObjeto.Message); End; End; //----------------------------------------------------------------------------- // TPdfObjString //----------------------------------------------------------------------------- Constructor TPdfObjString.Create(Var stm_Dados:TStringStream;bol_Hex:Boolean); Var int_ValHex:Integer; int_ContPar, int_ContDigOctal:Byte; chr_Dado, chr_DigOctal:AnsiChar; bol_Valido:Boolean; Begin Inherited Create; //É string hexadecimal? If bol_Hex Then Begin Repeat //Sim, lê os caracteres hexadecimais int_ValHex:=_LeParHexa(stm_Dados); If int_ValHex>=0 Then //Monta a string Self.str_Valor:=Self.str_Valor+Chr(int_ValHex); Until int_ValHex<0; stm_Dados.ReadBuffer(chr_Dado,1); End Else Begin //Como a estrutura string começa com "(", então já existe um parêntese. int_ContPar:=1; While int_ContPar>0 Do Begin //A princípio os caracteres lidos são válidos bol_Valido:=True; //Lê caractere stm_Dados.ReadBuffer(chr_Dado,1); //É abre parêntese? If chr_Dado='(' Then //Sim, incrementa contador Inc(int_ContPar) //É fecha parêntese? Else If chr_Dado=')' Then Begin //Sim, decrementa contador Dec(int_ContPar); //Já fechou todos os parênteses? If int_ContPar=0 Then Begin //Sim, então tem algo errado bol_Valido:=False; Break; End End //Quando encontra o caractere "\" tem que tratar de modo especial Else If chr_Dado='\' Then Begin //Obtém o próximo caractere... stm_Dados.ReadBuffer(chr_Dado,1); //É algum algarismo? If (chr_Dado>='0') And (chr_Dado<='9') Then Begin //Sim então deve ser um caractere no formato \ddd com 3 dígitos octais int_ContDigOctal:=0; chr_DigOctal:=#0; While (chr_Dado>='0') And (chr_Dado<='8') And (int_ContDigOctal<3) Do Begin chr_DigOctal:=AnsiChar(Chr(Ord(chr_DigOctal)*8+Ord(chr_Dado)-Ord('0'))); stm_Dados.ReadBuffer(chr_Dado,1); Inc(int_ContDigOctal); End; stm_Dados.Position:=stm_Dados.Position-1; //Obtém o caractere correspondente ao valor octal chr_Dado:=chr_DigOctal; End //É \r? Else If chr_Dado='r' Then //Insere o caractere line feed chr_Dado:=LF //É \n? Else If chr_Dado='n' Then //Insere o caractere line feed também chr_Dado:=LF //É \t Else If chr_Dado='t' Then //Insere tabulação horizontal chr_Dado:=HT //É \b? Else If chr_Dado='b' Then //Insere backspace chr_Dado:=BS Else If chr_Dado='f' Then chr_Dado:=FF Else If chr_Dado='\r' Then Begin stm_Dados.ReadBuffer(chr_Dado,1); If chr_Dado<>LF Then stm_Dados.Position:=stm_Dados.Position-1; bol_Valido:=False; End Else If chr_Dado='\n' Then bol_Valido:=False; End; If bol_Valido Then Self.str_Valor:=Self.str_Valor+chr_Dado; End; End; End; //----------------------------------------------------------------------------- Function TPdfObjString.ObtemValor:String; Begin Result:=Self.str_Valor End; //----------------------------------------------------------------------------- // TPdfObjKeyword //----------------------------------------------------------------------------- Constructor TPdfObjKeyword.Create(Var stm_Dados:TStringStream;chr_Dado:AnsiChar); Begin Inherited Create; stm_Dados:=stm_Dados; Self.str_Valor:=''; While _EhCaractereRegular(chr_Dado) Do Begin Self.str_Valor:= Self.str_Valor+chr_Dado; stm_Dados.ReadBuffer(chr_Dado,1); End; stm_Dados.Position:=stm_Dados.Position-1; End; //----------------------------------------------------------------------------- Function TPdfObjKeyword.ObtemValor:String; Begin Try Result:=str_Valor; Except On err_PdfObjeto:Exception Do Raise Exception.Create('Erro ao obter dado do objeto objeto '+Self.ClassName+': '+err_PdfObjeto.Message); End; End; //----------------------------------------------------------------------------- // TPdfObjNome //----------------------------------------------------------------------------- Constructor TPdfObjNome.Create(Var stm_Dados:TStringStream); Var chr_Dado:AnsiChar; int_ValHex:Integer; Begin Inherited Create; //Lê o primeiro caractere stm_Dados.ReadBuffer(chr_Dado,1); While _EhCaractereRegular(chr_Dado) Do Begin If (chr_Dado<'!') And (chr_Dado>'~') Then Break; //A versão 1.1 do de Pdf não permite caracteres hexadecimais nos objetos nome //If (chr_Dado='#') And (int_VersaoMaior<>1) And (int_VersaoMenor<>1) Then // Begin // int_ValHex:=_LeParHexa(stm_Dados); // If (int_ValHex>=0) Then // chr_Dado:=AnsiChar(Chr(int_ValHex)) // Else // _ExibeErro('Valor inválido no objeto nome.'); // End; Self.str_Valor:=Self.str_Valor+chr_Dado; stm_Dados.ReadBuffer(chr_Dado,1); End; stm_Dados.Position:=stm_Dados.Position-1; End; //----------------------------------------------------------------------------- Function TPdfObjNome.ObtemValor:String; Begin Try Result:=str_Valor; Except On err_PdfObjeto:Exception Do Raise Exception.Create('Erro ao obter dado do objeto objeto '+Self.ClassName+': '+err_PdfObjeto.Message); End; End; //----------------------------------------------------------------------------- // TPdfObjArray //----------------------------------------------------------------------------- Constructor TPdfObjArray.Create(Var stm_Dados:TStringStream;Var obj_XRef:TXRef); Var str_ValorItem:String; I:Byte; obj_Item:TPdfObjeto; chr_Dado:AnsiChar; Begin Inherited Create; int_Tam:=0; Self.lst_Valores:=TList.Create; Repeat obj_Item:=TPdfObjeto.Create(stm_Dados,obj_XRef,-1,-1,False); If obj_Item.Tipo<>obj_nulo Then Self.lst_Valores.Add(obj_Item); Until obj_Item.Tipo=obj_nulo; stm_Dados.ReadBuffer(chr_Dado,1); If chr_Dado<>']' Then Raise Exception.Create('Não foi encontrado "]" no final do objeto array.'); Self.int_Tam:=Self.lst_Valores.Count; End; //----------------------------------------------------------------------------- Function TPdfObjArray.ObtemValorItem(int_Indice:Integer):TPdfObjeto; Begin Try If int_Indice<lst_Valores.Count then Result:=TPdfObjeto(lst_Valores[int_Indice]) Else Result:=Nil; Except On err_PdfObjeto:Exception Do Raise Exception.Create('Erro ao obter dado do objeto objeto '+Self.ClassName+': '+err_PdfObjeto.Message); End; End; //----------------------------------------------------------------------------- // TPdfObjDicionario //----------------------------------------------------------------------------- Constructor TPdfObjDicionario.Create(Var stm_Dados:TStringStream;Var obj_XRef:TXRef); Var obj_NomeItem, obj_ValorItem:TPdfObjeto; bol_Termina:Boolean; Begin Inherited Create; Self.stl_Conteudo:=TStringList.Create; Self.int_Tam:=0; bol_Termina:=False; Repeat obj_NomeItem:=TPdfObjeto.Create(stm_Dados,obj_XRef,-1,-1,False); If obj_NomeItem.Tipo<>obj_nulo Then Begin If obj_NomeItem.Tipo<>obj_nome Then Raise Exception.Create('O primeiro item no dicionário deve ser um nome.'); obj_ValorItem:=TPdfObjeto.Create(stm_Dados,obj_XRef,-1,-1,False); If (obj_ValorItem<>Nil) And (obj_NomeItem<>Nil) Then Self.stl_Conteudo.AddObject(TPdfObjNome(obj_NomeItem.Conteudo).ObtemValor,obj_ValorItem); End; Until obj_NomeItem.Tipo=obj_nulo; Self.int_Tam:=Self.stl_Conteudo.Count; If Not _ProximoItem(stm_Dados,'>>') Then Raise Exception.Create('Não foi encontrado ">>" no final do dicionário'); End; //----------------------------------------------------------------------------- Function TPdfObjDicionario.ObtemValorChave(str_Chave:String):TPdfObjeto; Var I:Word; bol_Achou:Boolean; Begin Try Result:=Nil; If stl_Conteudo.IndexOf(str_Chave)>=0 Then Result:=TPdfObjeto(stl_Conteudo.Objects[stl_Conteudo.IndexOf(str_Chave)]) Else Result:=Nil; Except On err_PdfObjeto:Exception Do Raise Exception.Create('Erro ao obter dado do objeto objeto '+Self.ClassName+': '+err_PdfObjeto.Message); End; End; //----------------------------------------------------------------------------- Function TPdfObjDicionario.ObtemValorItem(int_Indice:Integer):TPdfObjeto; Var I:Word; bol_Achou:Boolean; Begin Try Result:=Nil; If int_Indice<=stl_Conteudo.Count Then Result:=TPdfObjeto(stl_Conteudo.Objects[int_Indice]); Except On err_PdfObjeto:Exception Do Raise Exception.Create('Erro ao obter dado do objeto objeto '+Self.ClassName+': '+err_PdfObjeto.Message); End; End; //----------------------------------------------------------------------------- Function TPdfObjDicionario.ObtemNomeChave(int_Indice:Integer):String; Var I:Word; bol_Achou:Boolean; Begin Try Result:=''; If int_Indice<=stl_Conteudo.Count Then Result:=stl_Conteudo[int_Indice]; Except On err_PdfObjeto:Exception Do Raise Exception.Create('Erro ao obter dado do objeto objeto '+Self.ClassName+': '+err_PdfObjeto.Message); End; End; //----------------------------------------------------------------------------- Function TPdfObjDicionario.ExisteChave(str_Chave:String):Boolean; Begin Result:=stl_Conteudo.IndexOf(str_Chave)>=0; End; //----------------------------------------------------------------------------- // TPdfObjStream //----------------------------------------------------------------------------- Constructor TPdfObjStream.Create(Var stm_Dados:TStringStream;Var obj_XRef:TXRef;obj_Metadados:TPdfObjDicionario); Var obj_TamStream:TPdfObjeto; int_TamStream:Int64; int_Id:Integer; Begin Inherited Create; Self.stm_Conteudo:=TStringStream.Create; Self.obj_Metadados:=obj_Metadados; obj_TamStream:=Self.obj_Metadados.ObtemValorChave('Length'); If obj_TamStream.Tipo=obj_indireto Then obj_TamStream:=TPdfObjIndireto(obj_TamStream.Conteudo).ObtemValorRef(obj_XRef); If obj_TamStream.Tipo=obj_numero Then Begin int_TamStream:=TPdfObjNumerico(obj_TamStream.Conteudo).ObtemValorInteiro; If int_TamStream>0 Then Begin Self.stm_Conteudo.CopyFrom(stm_Dados,int_TamStream); If Not _ProximoItem(stm_Dados,'endstream') Then Raise Exception.Create('Final inesperado do stream.') Else _BuscaLinha(stm_Dados); End; End Else Raise Exception.Create('Não foi possível obter o tamanho do stream'); End; //----------------------------------------------------------------------------- Function TPdfObjStream.ObtemValor:TStringStream; Begin //Result:=TStringStream.Create; Result:=Self.stm_Conteudo; End; //----------------------------------------------------------------------------- Function TPdfObjStream.ObtemValorMetadado(str_Chave:String):TPdfObjeto; Begin If Self.obj_Metadados<>Nil Then Begin If Self.obj_Metadados.ExisteChave(str_Chave) Then Result:=Self.obj_Metadados.ObtemValorChave(str_Chave) Else Result:=Nil End Else Result:=Nil; End; //----------------------------------------------------------------------------- // TPdfObjIndireto //----------------------------------------------------------------------------- Constructor TPdfObjIndireto.Create(int_Id,int_Gen:Integer); Begin Inherited Create; Self.int_Id:=int_Id; Self.int_Gen:=int_Gen; End; //----------------------------------------------------------------------------- Function TPdfObjIndireto.ObtemGen:Integer; begin Result:=Self.int_Gen; End; //----------------------------------------------------------------------------- Function TPdfObjIndireto.ObtemId: Integer; Begin Result:=Self.int_Id; End; //----------------------------------------------------------------------------- Function TPdfObjIndireto.ObtemValorRef(Var obj_XRef:TXRef):TPdfObjeto; Begin Result:=TPdfObjeto(obj_XRef.BuscaObjetoPorId(Self.int_Id)); End; End.
unit HashAlgGOST_U; // Description: GOST R 34.11-94 (Wrapper for the GOST Hashing Engine) // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, HashAlg_U, HashValue_U, HashAlgGOSTEngine_U; type THashAlgGOST = class(THashAlg) private GOSTEngine: THashAlgGOSTEngine; context: GostHashCtx; protected { Protected declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure Init(); override; procedure Update(const input: array of byte; const inputLen: cardinal); override; procedure Final(digest: THashValue); override; function PrettyPrintHashValue(const theHashValue: THashValue): string; override; published { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('Hash', [THashAlgGOST]); end; constructor THashAlgGOST.Create(AOwner: TComponent); begin inherited; GOSTEngine:= THashAlgGOSTEngine.Create(); GOSTEngine.gosthash_init(); fTitle := 'GOST R 34.11-94'; fHashLength := 256; fBlockLength := 256; end; destructor THashAlgGOST.Destroy(); begin // Nuke any existing context before freeing off the engine... GOSTEngine.gosthash_reset(context); GOSTEngine.Free(); inherited; end; procedure THashAlgGOST.Init(); begin GOSTEngine.gosthash_reset(context); end; procedure THashAlgGOST.Update(const input: array of byte; const inputLen: cardinal); begin GOSTEngine.gosthash_update(context, input, inputLen); end; procedure THashAlgGOST.Final(digest: THashValue); begin GOSTEngine.gosthash_final(context, digest); end; function THashAlgGOST.PrettyPrintHashValue(const theHashValue: THashValue): string; var retVal: string; begin retVal := inherited PrettyPrintHashValue(theHashValue); insert(' ', retVal, 57); insert(' ', retVal, 49); insert(' ', retVal, 41); insert(' ', retVal, 33); insert(' ', retVal, 25); insert(' ', retVal, 17); insert(' ', retVal, 9); Result := retVal; end; END.
unit UnitJPEGOptions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, uDBForm, JPEG, uSettings, pngimage, uFormInterfaces; type TDBJPEGOptions = record ProgressiveMode: Boolean; Compression: Integer; end; type TFormJpegOptions = class(TDBForm, IJpegOptionsForm) BtOK: TButton; BtCancel: TButton; Image1: TImage; LbInfo: TLabel; GbJPEGOption: TGroupBox; TbCompressionRate: TTrackBar; CbProgressiveMove: TCheckBox; lbCompressionRate: TLabel; CbOptimizeToSize: TCheckBox; Edit1: TEdit; LbKb: TLabel; procedure FormCreate(Sender: TObject); procedure BtCancelClick(Sender: TObject); procedure TbCompressionRateChange(Sender: TObject); procedure BtOKClick(Sender: TObject); procedure CbOptimizeToSizeClick(Sender: TObject); procedure Edit1KeyPress(Sender: TObject; var Key: Char); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FSection: string; procedure SetSection(Section: string); protected { Protected declarations } function GetFormID: string; override; procedure LoadLanguage; procedure InterfaceDestroyed; override; public { Public declarations } procedure Execute(Section: string); end; implementation {$R *.dfm} procedure TFormJpegOptions.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; procedure TFormJpegOptions.FormCreate(Sender: TObject); begin LoadLanguage; TbCompressionRateChange(Self); end; procedure TFormJpegOptions.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = Char(VK_ESCAPE) then Close; end; function TFormJpegOptions.GetFormID: string; begin Result := 'JPEG'; end; procedure TFormJpegOptions.InterfaceDestroyed; begin inherited; Release; end; procedure TFormJpegOptions.BtCancelClick(Sender: TObject); begin Close; end; procedure TFormJpegOptions.TbCompressionRateChange(Sender: TObject); begin lbCompressionRate.Caption := Format(L('JPEG compression (%d%%):'), [TbCompressionRate.Position * 5]); end; procedure TFormJpegOptions.BtOKClick(Sender: TObject); begin AppSettings.WriteInteger(FSection, 'JPEGCompression', TbCompressionRate.Position * 5); AppSettings.WriteBool(FSection, 'JPEGProgressiveMode', CbProgressiveMove.Checked); AppSettings.WriteInteger(FSection, 'JPEGOptimizeSize', StrToIntDef(Edit1.Text, 100)); AppSettings.WriteBool(FSection, 'JPEGOptimizeMode', CbOptimizeToSize.Checked); Close; end; procedure TFormJpegOptions.LoadLanguage; begin BeginTranslate; try Caption := L('JPEG compression'); LbInfo.Caption := L('Choose JPEG mode and compression rate') + ':'; GbJPEGOption.Caption := L('JPEG'); CbProgressiveMove.Caption := L('Progressive mode'); BtCancel.Caption := L('Cancel'); BtOk.Caption := L('Ok'); CbOptimizeToSize.Caption := L('Optimize to size') + ':'; LbKb.Caption := L('Kb'); finally EndTranslate; end; end; procedure TFormJpegOptions.SetSection(Section: String); begin FSection := Section; end; procedure TFormJpegOptions.Execute(Section: String); begin SetSection(Section); TbCompressionRate.Position := AppSettings.ReadInteger(FSection, 'JPEGCompression', 75) div 5; CbProgressiveMove.Checked := AppSettings.ReadBool(FSection, 'JPEGProgressiveMode', False); Edit1.Text := IntToStr(AppSettings.ReadInteger(FSection, 'JPEGOptimizeSize', 100)); CbOptimizeToSize.Checked := AppSettings.ReadBool(FSection, 'JPEGOptimizeMode', False); CbOptimizeToSizeClick(nil); ShowModal; end; procedure TFormJpegOptions.CbOptimizeToSizeClick(Sender: TObject); begin Edit1.Enabled := CbOptimizeToSize.Checked; TbCompressionRate.Enabled := not CbOptimizeToSize.Checked; end; procedure TFormJpegOptions.Edit1KeyPress(Sender: TObject; var Key: Char); begin if Key = Char(VK_RETURN) then BtOKClick(Sender); end; initialization FormInterfaces.RegisterFormInterface(IJpegOptionsForm, TFormJpegOptions); end.
{ This sample shows how to store text data into a custom resource, how to use them and how to localize them. Text resources are added by adding them into Custom.rc file and adding the rc file into the project. } unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Data; type TForm1 = class(TForm) TextLabel: TLabel; TextMemo: TMemo; TextPreviousButton: TButton; TextNextButton: TButton; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure TextPreviousButtonClick(Sender: TObject); procedure TextNextButtonClick(Sender: TObject); private FTexts: TResourceItems; procedure UpdateText; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.UpdateText; resourcestring STextCaption = '%0:d/%1:d text resource: %2:s-%3:s'; // loc Text resource label. \n %0:d is the index of the current text. \n %1:d is the total text count. \n %2:s is the resource type. \n %3:s is the resource name. var stream: TResourceStream; resource: TResourceItem; begin resource := FTexts.Current; TextLabel.Caption := Format(STextCaption, [FTexts.Index + 1, FTexts.Count, resource.ResourceType, resource.ResourceName]); stream := resource.GetStream; try TextMemo.Lines.LoadFromStream(stream); finally stream.Free; end; end; procedure TForm1.FormCreate(Sender: TObject); const NAME = 'TEXT'; begin FTexts := TResourceItems.Create; // Populate resource list FTexts.Add(NAME, 'PlainAnsi'); FTexts.Add(NAME, 'PlainUtf8'); FTexts.Add(NAME, 'PlainUtf16'); FTexts.Add(NAME, 'PlainUtf16Be'); FTexts.Add(NAME, 'SegmentedAnsi'); FTexts.Add(NAME, 'SegmentedUtf8'); FTexts.Add(NAME, 'SegmentedUtf16'); FTexts.Add(NAME, 'SegmentedUtf16Be'); UpdateText; end; procedure TForm1.FormResize(Sender: TObject); const GAP = 8; begin TextPreviousButton.Left := TextMemo.Left + (TextMemo.Width - TextPreviousButton.Width - TextNextButton.Width - GAP) div 2; TextNextButton.Left := TextPreviousButton.Left + TextPreviousButton.Width + GAP; end; procedure TForm1.TextPreviousButtonClick(Sender: TObject); begin FTexts.Previous; UpdateText; end; procedure TForm1.TextNextButtonClick(Sender: TObject); begin FTexts.Next; UpdateText; end; end.
namespace com.example.android.livecubes.cube1; {* * 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.graphics, android.os, android.service.wallpaper, android.view; type /// <summary> /// This animated wallpaper draws a rotating wireframe cube. /// </summary> CubeWallpaper1 = public class(WallpaperService) public method onCreateEngine: WallpaperService.Engine; override; end; CubeEngine nested in CubeWallpaper1 = public class(WallpaperService.Engine) private var mHandler: Handler := new Handler; var mOffset: Single; var mPaint: Paint; var mTouchX: Single := -1; var mTouchY: Single := -1; var mStartTime: Int64; var mCenterX: Single; var mCenterY: Single; var mDrawCube: Runnable; var mVisible: Boolean; public constructor (wallpaperService: CubeWallpaper1); method onCreate(holder: SurfaceHolder); override; method onDestroy; override; method onVisibilityChanged(visible: Boolean); override; method onSurfaceCreated(holder: SurfaceHolder); override; method onSurfaceDestroyed(holder: SurfaceHolder); override; method onSurfaceChanged(holder: SurfaceHolder; format, width, height: Integer); override; method onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep: Single; xPixelOffset, yPixelOffset: Integer); override; method onTouchEvent(&event: MotionEvent); override; method drawFrame; method drawCube(c: Canvas); method drawLine(c: Canvas; x1, y1, z1, x2, y2, z2: Integer); method drawTouchPoint(c: Canvas); end; implementation constructor CubeWallpaper1.CubeEngine(wallpaperService: CubeWallpaper1); begin inherited constructor(wallpaperService); mDrawCube := new interface Runnable(run := method begin drawFrame end); // Create a Paint to draw the lines for our cube mPaint := new Paint; mPaint.Color := $ffffffff as Int64; mPaint.AntiAlias := true; mPaint.StrokeWidth := 2; mPaint.StrokeCap := Paint.Cap.ROUND; mPaint.Style := Paint.Style.STROKE; mStartTime := SystemClock.elapsedRealtime; end; method CubeWallpaper1.onCreateEngine: WallpaperService.Engine; begin exit new CubeEngine(self) end; method CubeWallpaper1.CubeEngine.onCreate(holder: SurfaceHolder); begin inherited onCreate(holder); // By default we don't get touch events, so enable them. TouchEventsEnabled := true; end; method CubeWallpaper1.CubeEngine.onDestroy; begin inherited onDestroy(); mHandler.removeCallbacks(mDrawCube); end; method CubeWallpaper1.CubeEngine.onVisibilityChanged(visible: Boolean); begin mVisible := visible; if visible then drawFrame else mHandler.removeCallbacks(mDrawCube) end; method CubeWallpaper1.CubeEngine.onSurfaceCreated(holder: SurfaceHolder); begin inherited end; method CubeWallpaper1.CubeEngine.onSurfaceDestroyed(holder: SurfaceHolder); begin inherited onSurfaceDestroyed(holder); mVisible := false; mHandler.removeCallbacks(mDrawCube); end; method CubeWallpaper1.CubeEngine.onSurfaceChanged(holder: SurfaceHolder; format: Integer; width: Integer; height: Integer); begin inherited onSurfaceChanged(holder, format, width, height); // store the center of the surface, so we can draw the cube in the right spot mCenterX := width / 2.0; mCenterY := height / 2.0; drawFrame; end; method CubeWallpaper1.CubeEngine.onOffsetsChanged(xOffset: Single; yOffset: Single; xOffsetStep: Single; yOffsetStep: Single; xPixelOffset: Integer; yPixelOffset: Integer); begin mOffset := xOffset; drawFrame; end; /// <summary> /// Store the position of the touch event so we can use it for drawing later /// </summary> /// <param name="event"></param> method CubeWallpaper1.CubeEngine.onTouchEvent(&event: MotionEvent); begin if &event.Action = MotionEvent.ACTION_MOVE then begin mTouchX := &event.X; mTouchY := &event.Y end else begin mTouchX := - 1; mTouchY := - 1 end; inherited onTouchEvent(&event); end; /// <summary> /// Draw one frame of the animation. This method gets called repeatedly /// by posting a delayed Runnable. You can do any drawing you want in /// here. This example draws a wireframe cube. /// </summary> method CubeWallpaper1.CubeEngine.drawFrame; begin var holder: SurfaceHolder := SurfaceHolder; var c: Canvas := nil; try c := holder.lockCanvas; if c <> nil then begin // draw something drawCube(c); drawTouchPoint(c) end; finally if c <> nil then holder.unlockCanvasAndPost(c); end; // Reschedule the next redraw mHandler.removeCallbacks(mDrawCube); if mVisible then mHandler.postDelayed(mDrawCube, 1000 div 25) end; /// <summary> /// Draw a wireframe cube by drawing 12 3 dimensional lines between /// adjacent corners of the cube /// </summary> /// <param name="c"></param> method CubeWallpaper1.CubeEngine.drawCube(c: Canvas); begin c.save; c.translate(mCenterX, mCenterY); c.drawColor($ff000000 as Int64); drawLine(c, -400, -400, -400, 400, -400, -400); drawLine(c, 400, -400, -400, 400, 400, -400); drawLine(c, 400, 400, -400, -400, 400, -400); drawLine(c, -400, 400, -400, -400, -400, -400); drawLine(c, -400, -400, 400, 400, -400, 400); drawLine(c, 400, -400, 400, 400, 400, 400); drawLine(c, 400, 400, 400, -400, 400, 400); drawLine(c, -400, 400, 400, -400, -400, 400); drawLine(c, -400, -400, 400, -400, -400, -400); drawLine(c, 400, -400, 400, 400, -400, -400); drawLine(c, 400, 400, 400, 400, 400, -400); drawLine(c, -400, 400, 400, -400, 400, -400); c.restore end; /// <summary> /// Draw a 3 dimensional line on to the screen /// </summary> /// <param name="c"></param> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="z1"></param> /// <param name="x2"></param> /// <param name="y2"></param> /// <param name="z2"></param> method CubeWallpaper1.CubeEngine.drawLine(c: Canvas; x1: Integer; y1: Integer; z1: Integer; x2: Integer; y2: Integer; z2: Integer); begin var now: Int64 := SystemClock.elapsedRealtime; var xrot: Single := Single(now - mStartTime) div 1000; var yrot: Single := (0.5 - mOffset) * 2.0; // 3D transformations // rotation around X-axis var newy1: Single := (Math.sin(xrot) * z1) + (Math.cos(xrot) * y1); var newy2: Single := (Math.sin(xrot) * z2) + (Math.cos(xrot) * y2); var newz1: Single := (Math.cos(xrot) * z1) - (Math.sin(xrot) * y1); var newz2: Single := (Math.cos(xrot) * z2) - (Math.sin(xrot) * y2); // rotation around Y-axis var newx1: Single := (Math.sin(yrot) * newz1) + (Math.cos(yrot) * x1); var newx2: Single := (Math.sin(yrot) * newz2) + (Math.cos(yrot) * x2); newz1 := (Math.cos(yrot) * newz1) - (Math.sin(yrot) * x1); newz2 := (Math.cos(yrot) * newz2) - (Math.sin(yrot) * x2); // 3D-to-2D projection var startX: Single := newx1 / (4 - (newz1 / 400.0)); var startY: Single := newy1 / (4 - (newz1 / 400.0)); var stopX: Single := newx2 / (4 - (newz2 / 400.0)); var stopY: Single := newy2 / (4 - (newz2 / 400.0)); c.drawLine(startX, startY, stopX, stopY, mPaint); end; /// <summary> /// Draw a circle around the current touch point, if any. /// </summary> /// <param name="c"></param> method CubeWallpaper1.CubeEngine.drawTouchPoint(c: Canvas); begin if (mTouchX >= 0) and (mTouchY >= 0) then c.drawCircle(mTouchX, mTouchY, 80, mPaint) end; end.