text
stringlengths
14
6.51M
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Doom3 MD5 mesh and animation vector file format implementation. } unit VXS.FileMD5; interface uses System.Classes, System.SysUtils, VXS.VectorFileObjects, VXS.Utils, VXS.ApplicationFileIO, VXS.VectorTypes, VXS.VectorGeometry, VXS.VectorLists; type TVXMD5VectorFile = class(TVXVectorFile) private FMD5String, FTempString, FBoneNames: TStringList; FCurrentPos: Integer; FBasePose: TVXSkeletonFrame; FFramePositions: TAffineVectorList; FFrameQuaternions: TQuaternionList; FJointFlags: TIntegerList; FNumFrames, FFirstFrame, FFrameRate, FNumJoints: Integer; function ReadLine: String; public class function Capabilities: TVXDataFileCapabilities; override; procedure LoadFromStream(aStream: TStream); override; end; var vMD5TextureExtensions: TStringList; // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ----------- // ----------- TVXMD5VectorFile ----------- // ----------- function TVXMD5VectorFile.ReadLine: String; begin Result := ''; if not Assigned(FMD5String) then exit; if FCurrentPos >= FMD5String.Count then exit; repeat Result := FMD5String[FCurrentPos]; Result := StringReplace(Result, '(', '', [rfReplaceAll]); Result := StringReplace(Result, ')', '', [rfReplaceAll]); Result := Trim(Result); Inc(FCurrentPos); until (Result <> '') or (FCurrentPos >= FMD5String.Count); end; class function TVXMD5VectorFile.Capabilities: TVXDataFileCapabilities; begin Result := [dfcRead]; end; procedure TVXMD5VectorFile.LoadFromStream(aStream: TStream); procedure AllocateMaterial(var shader: String); { const cTexType : array[0..2] of String = ('_local', '_d', '_s'); var shader_nopath, temp : String; libmat : TVXLibMaterial; i, j : Integer;// } begin { if Assigned(Owner.MaterialLibrary) then begin shader:=StringReplace(shader,'/','\',[rfReplaceAll]); if not DirectoryExists(ExtractFilePath(shader)) then shader:=ExtractFileName(shader); if not Assigned(Owner.MaterialLibrary.Materials.GetLibMaterialByName(shader)) then begin libmat:=Owner.MaterialLibrary.Materials.Add; libmat.Name:=shader; for i:=0 to High(cTexType) do begin temp:=ChangeFileExt(shader, '')+cTexType[i]; for j:=0 to vMD5TextureExtensions.Count-1 do begin if FileExists(temp+vMD5TextureExtensions[j]) then begin with libmat.Material.TextureEx.Add do begin Texture.Image.LoadFromFile(temp+vMD5TextureExtensions[j]); Texture.Enabled:=True; end; Break; end; end; end; end; end else// } shader := ''; end; function QuaternionMakeFromImag(ix, iy, iz: Single): TQuaternion; var rr: Single; begin with Result do begin ImagPart.X := ix; ImagPart.Y := iy; ImagPart.Z := iz; rr := 1 - (ix * ix) - (iy * iy) - (iz * iz); if rr < 0 then RealPart := 0 else RealPart := sqrt(rr); end; end; procedure ReadBone(BoneNum: Integer; BoneString: String); var bonename: String; pos: TAffineVector; quat: TQuaternion; mat, rmat: TMatrix; ParentBoneID: Integer; bone, parentbone: TVXSkeletonBone; begin FTempString.CommaText := BoneString; bonename := FTempString[0]; ParentBoneID := StrToInt(FTempString[1]); pos.X := VXS.Utils.StrToFloatDef(FTempString[2]); pos.Y := VXS.Utils.StrToFloatDef(FTempString[4]); pos.Z := VXS.Utils.StrToFloatDef(FTempString[3]); quat := QuaternionMakeFromImag(VXS.Utils.StrToFloatDef(FTempString[5]), VXS.Utils.StrToFloatDef(FTempString[7]), VXS.Utils.StrToFloatDef(FTempString[6])); FFramePositions.Add(pos); FFrameQuaternions.Add(quat); if bonename <> '' then begin FBoneNames.Add(bonename); if ParentBoneID = -1 then bone := TVXSkeletonBone.CreateOwned(Owner.Skeleton.RootBones) else begin parentbone := Owner.Skeleton.RootBones.BoneByID(ParentBoneID); bone := TVXSkeletonBone.CreateOwned(parentbone); mat := QuaternionToMatrix(quat); mat.W := PointMake(pos); rmat := QuaternionToMatrix(FFrameQuaternions[ParentBoneID]); rmat.W := PointMake(FFramePositions[ParentBoneID]); InvertMatrix(rmat); mat := MatrixMultiply(mat, rmat); pos := AffineVectorMake(mat.W); quat := QuaternionFromMatrix(mat); end; with bone do begin BoneID := BoneNum; Name := bonename; end; end; FBasePose.Position[BoneNum] := pos; FBasePose.Quaternion[BoneNum] := quat; end; procedure ReadJoints; var temp: String; i: Integer; begin i := 0; repeat temp := ReadLine; if temp <> '}' then begin ReadBone(i, temp); Inc(i); end; until temp = '}'; Owner.Skeleton.CurrentFrame.Assign(FBasePose); Owner.Skeleton.CurrentFrame.FlushLocalMatrixList; Owner.Skeleton.RootBones.PrepareGlobalMatrices; end; procedure ReadMesh; var temp, shader: String; mesh: TVXSkeletonMeshObject; fg: TFGVertexIndexList; vnum, wnum, numverts, numweights: Integer; VertexWeightID, VertexWeightCount, VertexBoneRef: TIntegerList; VertexWeight: TSingleList; VertexWeighted: TAffineVectorList; blendedVert, transformedVert: TAffineVector; i, j, k: Integer; mat: TMatrix; begin VertexWeightID := TIntegerList.Create; VertexWeightCount := TIntegerList.Create; VertexBoneRef := TIntegerList.Create; VertexWeight := TSingleList.Create; VertexWeighted := TAffineVectorList.Create; numverts := 0; mesh := TVXSkeletonMeshObject.CreateOwned(Owner.MeshObjects); fg := TFGVertexIndexList.CreateOwned(mesh.FaceGroups); mesh.Mode := momFaceGroups; fg.Mode := fgmmTriangles; repeat temp := ReadLine; FTempString.CommaText := temp; if FTempString.Count > 1 then begin temp := LowerCase(FTempString[0]); if temp = 'shader' then begin shader := FTempString[1]; AllocateMaterial(shader); fg.MaterialName := shader; end else if temp = 'numverts' then begin numverts := StrToInt(FTempString[1]); mesh.TexCoords.Count := numverts; VertexWeightID.Count := numverts; VertexWeightCount.Count := numverts; end else if temp = 'vert' then begin if FTempString.Count >= 6 then begin vnum := StrToInt(FTempString[1]); mesh.TexCoords[vnum] := AffineVectorMake(VXS.Utils.StrToFloatDef(FTempString[2]), 1 - VXS.Utils.StrToFloatDef(FTempString[3]), 0); VertexWeightID[vnum] := StrToInt(FTempString[4]); VertexWeightCount[vnum] := StrToInt(FTempString[5]); if VertexWeightCount[vnum] > mesh.BonesPerVertex then mesh.BonesPerVertex := VertexWeightCount[vnum]; end; end else if temp = 'numtris' then begin fg.VertexIndices.Capacity := StrToInt(FTempString[1]) * 3; end else if temp = 'tri' then begin if FTempString.Count >= 5 then begin fg.VertexIndices.Add(StrToInt(FTempString[2])); fg.VertexIndices.Add(StrToInt(FTempString[3])); fg.VertexIndices.Add(StrToInt(FTempString[4])); end; end else if temp = 'numweights' then begin numweights := StrToInt(FTempString[1]); VertexBoneRef.Count := numweights; VertexWeight.Count := numweights; VertexWeighted.Count := numweights; end else if temp = 'weight' then begin if FTempString.Count >= 7 then begin wnum := StrToInt(FTempString[1]); VertexBoneRef[wnum] := StrToInt(FTempString[2]); VertexWeight[wnum] := VXS.Utils.StrToFloatDef(FTempString[3]); VertexWeighted[wnum] := AffineVectorMake(VXS.Utils.StrToFloatDef(FTempString[4]), VXS.Utils.StrToFloatDef(FTempString[6]), VXS.Utils.StrToFloatDef(FTempString[5])); end; end; end; until temp = '}'; mesh.Vertices.Count := numverts; mesh.VerticeBoneWeightCount := numverts; for i := 0 to numverts - 1 do begin blendedVert := NullVector; for j := 0 to mesh.BonesPerVertex - 1 do begin if j < VertexWeightCount[i] then begin k := VertexWeightID[i] + j; mesh.VerticesBonesWeights^[i]^[j].BoneID := VertexBoneRef[k]; mesh.VerticesBonesWeights^[i]^[j].Weight := VertexWeight[k]; mat := Owner.Skeleton.RootBones.BoneByID(VertexBoneRef[k]) .GlobalMatrix; transformedVert := VectorTransform(VertexWeighted[k], mat); AddVector(blendedVert, VectorScale(transformedVert, VertexWeight[k])); end else begin mesh.VerticesBonesWeights^[i]^[j].BoneID := 0; mesh.VerticesBonesWeights^[i]^[j].Weight := 0; end; end; mesh.Vertices[i] := blendedVert; end; mesh.BuildNormals(fg.VertexIndices, momTriangles); VertexWeightID.Free; VertexWeightCount.Free; VertexBoneRef.Free; VertexWeight.Free; VertexWeighted.Free; end; procedure ReadHierarchy; var temp: String; bone: TVXSkeletonBone; begin if not Assigned(FJointFlags) then begin FJointFlags := TIntegerList.Create; Assert(Owner.Skeleton.Frames.Count > 0, 'The md5mesh file must be loaded before md5anim files!'); FJointFlags.Count := Owner.Skeleton.Frames[0].Position.Count; end; repeat temp := ReadLine; FTempString.CommaText := temp; if FTempString.Count >= 3 then begin bone := Owner.Skeleton.BoneByName(FTempString[0]); if Assigned(bone) then FJointFlags[bone.BoneID] := StrToInt(FTempString[2]); end; until temp = '}'; end; procedure ReadBaseFrame; var temp: String; pos: TAffineVector; quat: TQuaternion; begin FFramePositions.Clear; FFrameQuaternions.Clear; repeat temp := ReadLine; FTempString.CommaText := temp; if FTempString.Count >= 6 then begin pos := AffineVectorMake(VXS.Utils.StrToFloatDef(FTempString[0]), VXS.Utils.StrToFloatDef(FTempString[1]), VXS.Utils.StrToFloatDef(FTempString[2])); quat := QuaternionMakeFromImag(VXS.Utils.StrToFloatDef(FTempString[3]), VXS.Utils.StrToFloatDef(FTempString[4]), VXS.Utils.StrToFloatDef(FTempString[5])); FFramePositions.Add(pos); FFrameQuaternions.Add(quat); end; until temp = '}'; end; procedure ReadFrame(framenum: Integer); var temp: String; i, j: Integer; frame: TVXSkeletonFrame; pos: TAffineVector; quat: TQuaternion; begin frame := Owner.Skeleton.Frames[FFirstFrame + framenum]; frame.TransformMode := sftQuaternion; frame.Position.Count := FNumJoints; frame.Quaternion.Count := FNumJoints; for i := 0 to FJointFlags.Count - 1 do begin pos := FFramePositions[i]; quat := FFrameQuaternions[i]; if FJointFlags[i] > 0 then begin temp := ReadLine; FTempString.CommaText := temp; j := 0; if FJointFlags[i] and 1 > 0 then begin pos.X := VXS.Utils.StrToFloatDef(FTempString[j]); Inc(j); end; if FJointFlags[i] and 2 > 0 then begin pos.Y := VXS.Utils.StrToFloatDef(FTempString[j]); Inc(j); end; if FJointFlags[i] and 4 > 0 then begin pos.Z := VXS.Utils.StrToFloatDef(FTempString[j]); Inc(j); end; if FJointFlags[i] and 8 > 0 then begin quat.ImagPart.X := VXS.Utils.StrToFloatDef(FTempString[j]); Inc(j); end; if FJointFlags[i] and 16 > 0 then begin quat.ImagPart.Y := VXS.Utils.StrToFloatDef(FTempString[j]); Inc(j); end; if FJointFlags[i] and 32 > 0 then quat.ImagPart.Z := VXS.Utils.StrToFloatDef(FTempString[j]); end; pos := AffineVectorMake(pos.X, pos.Z, pos.Y); quat := QuaternionMakeFromImag(quat.ImagPart.X, quat.ImagPart.Z, quat.ImagPart.Y); frame.Position[i] := pos; frame.Quaternion[i] := quat; end; end; procedure InitializeMeshes; var i: Integer; begin for i := 0 to Owner.MeshObjects.Count - 1 do TVXSkeletonMeshObject(Owner.MeshObjects[i]) .PrepareBoneMatrixInvertedMeshes; end; var str, temp: String; nummeshes, md5Version, meshid, i: Integer; begin FCurrentPos := 0; FMD5String := TStringList.Create; FTempString := TStringList.Create; FBoneNames := TStringList.Create; meshid := 0; nummeshes := 0; md5Version := 0; try FMD5String.LoadFromStream(aStream); // Version checking str := ReadLine; FTempString.CommaText := str; if FTempString.Count >= 2 then if LowerCase(FTempString[0]) = 'md5version' then md5Version := StrToInt(FTempString[1]); Assert(md5Version = 10, 'Invalid or missing md5Version number.'); repeat str := ReadLine; FTempString.CommaText := str; if FTempString.Count > 1 then begin temp := LowerCase(FTempString[0]); if (temp = 'numjoints') then begin FNumJoints := StrToInt(FTempString[1]); FFramePositions := TAffineVectorList.Create; FFrameQuaternions := TQuaternionList.Create; if Owner.Skeleton.Frames.Count = 0 then begin FBasePose := TVXSkeletonFrame.CreateOwned(Owner.Skeleton.Frames); FBasePose.Position.Count := FNumJoints; FBasePose.TransformMode := sftQuaternion; FBasePose.Quaternion.Count := FNumJoints; end else FBasePose := Owner.Skeleton.Frames[0]; end else if (temp = 'joints') then begin ReadJoints; if Owner is TVXActor then TVXActor(Owner).Reference := aarSkeleton; end else if (temp = 'nummeshes') then begin nummeshes := StrToInt(FTempString[1]); end else if (temp = 'mesh') then begin if meshid < nummeshes then begin ReadMesh; if meshid = nummeshes - 1 then InitializeMeshes; Inc(meshid); end else begin repeat str := ReadLine; until str = '}'; end; end else if (temp = 'hierarchy') then begin ReadHierarchy; end else if (temp = 'numframes') then begin FNumFrames := StrToInt(FTempString[1]); if FNumFrames > 0 then begin FFirstFrame := Owner.Skeleton.Frames.Count; for i := 1 to FNumFrames do TVXSkeletonFrame.CreateOwned(Owner.Skeleton.Frames); if Owner is TVXActor then begin with TVXActor(Owner).Animations.Add do begin Name := ChangeFileExt(ExtractFileName(ResourceName), ''); Reference := aarSkeleton; StartFrame := FFirstFrame; EndFrame := FFirstFrame + FNumFrames - 1; end; end; end; end else if (temp = 'framerate') then begin FFrameRate := StrToInt(FTempString[1]); end else if (temp = 'baseframe') then begin ReadBaseFrame; end else if (temp = 'frame') then begin ReadFrame(StrToInt(FTempString[1])); end; end; until str = ''; finally if Assigned(FFramePositions) then FreeAndNil(FFramePositions); if Assigned(FFrameQuaternions) then FreeAndNil(FFrameQuaternions); if Assigned(FJointFlags) then FreeAndNil(FJointFlags); FBoneNames.Free; FTempString.Free; FMD5String.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterVectorFileFormat('md5mesh', 'Doom3 mesh files', TVXMD5VectorFile); RegisterVectorFileFormat('md5anim', 'Doom3 animation files', TVXMD5VectorFile); vMD5TextureExtensions := TStringList.Create; with vMD5TextureExtensions do begin Add('.bmp'); Add('.dds'); Add('.jpg'); Add('.tga'); end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ finalization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ vMD5TextureExtensions.Free; end.
unit uClasseException; interface uses System.SysUtils, Vcl.Forms; type TCapturaExcecoes = class private LogFile : String; // function ObterNomeUsuario: string; // function ObterVersaoWindows: string; //procedure GravarImagemFormulario(const NomeArquivo: string; Formulario: TForm); public constructor Create; procedure CapturarExcecao(Sender: TObject; E: Exception); end; implementation uses Winapi.Windows, System.UITypes, Vcl.Dialogs, Vcl.Graphics, Vcl.Imaging.jpeg, Vcl.ClipBrd, Vcl.ComCtrls; { TCapturaExcecoes } constructor TCapturaExcecoes.Create; begin LogFile := ChangeFileExt('LogErros','.log'); Application.OnException := CapturarExcecao; end; procedure TCapturaExcecoes.CapturarExcecao(Sender: TObject; E: Exception); var ArquivoLog: TextFile; StringBuilder: TStringBuilder; DataHora: string; begin AssignFile(ArquivoLog, LogFile); // Se o arquivo existir, abre para edição, // Caso contrário, cria o arquivo if FileExists(LogFile) then Append(ArquivoLog) else ReWrite(ArquivoLog); DataHora := FormatDateTime('dd-mm-yyyy_hh-nn-ss', Now); WriteLn(ArquivoLog, 'Data/Hora.......: ' + DateTimeToStr(Now)); WriteLn(ArquivoLog, 'Mensagem........: ' + E.Message); WriteLn(ArquivoLog, 'Classe Exceção..: ' + E.ClassName); WriteLn(ArquivoLog, 'Formulário......: ' + Screen.ActiveForm.Name); WriteLn(ArquivoLog, 'Unit............: ' + Sender.UnitName); WriteLn(ArquivoLog, 'Controle Visual.: ' + Screen.ActiveControl.Name); //WriteLn(ArquivoLog, 'Usuario.........: ' + ObterNomeUsuario); //WriteLn(ArquivoLog, 'Versão Windows..: ' + ObterVersaoWindows); WriteLn(ArquivoLog, StringOfChar('-', 70)); // Fecha o arquivo CloseFile(ArquivoLog); //GravarImagemFormulario(DataHora, Screen.ActiveForm); // * Código para que a exceção seja exibida para o usuário * StringBuilder := TStringBuilder.Create; try // Exibe a mensagem para o usuário StringBuilder.AppendLine(E.Message); {StringBuilder.AppendLine(' Ocorreu um erro na aplicação. ') .AppendLine(' Entre em contato com o desenvolvedor ') .AppendLine(EmptyStr) .AppendLine(' Descrição técnica: ') .AppendLine(E.Message); } MessageDlg(StringBuilder.ToString, mtWarning, [mbOK], 0); finally StringBuilder.Free; end; end; var TratarExcept : TCapturaExcecoes; initialization TratarExcept := TCapturaExcecoes.create; Finalization TratarExcept.free; { procedure TCapturaExcecoes.GravarImagemFormulario(const NomeArquivo: string; Formulario: TForm); var Bitmap: TBitmap; JPEG: TJpegImage; begin Bitmap := TBitmap.Create; JPEG := TJpegImage.Create; try Bitmap.Assign(Formulario.GetFormImage); JPEG.Assign(Bitmap); JPEG.SaveToFile(Format('%s\%s.jpg', [GetCurrentDir, NomeArquivo])); finally JPEG.Free; Bitmap.Free; end; end; } { function TCapturaExcecoes.ObterNomeUsuario: string; var Size: DWord; begin // retorna o login do usuário do sistema operacional Size := 1024; SetLength(result, Size); GetUserName(PChar(result), Size); SetLength(result, Size - 1); end; function TCapturaExcecoes.ObterVersaoWindows: string; begin case System.SysUtils.Win32MajorVersion of 5: case System.SysUtils.Win32MinorVersion of 1: result := 'Windows XP'; end; 6: case System.SysUtils.Win32MinorVersion of 0: result := 'Windows Vista'; 1: result := 'Windows 7'; 2: result := 'Windows 8'; 3: result := 'Windows 8.1'; end; 10: case System.SysUtils.Win32MinorVersion of 0: result := 'Windows 10'; end; end; end; } end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmComboBox Purpose : Standard Combobox or MRU with registry save. Date : 01-01-1999 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmComboBox; interface {$I CompilerDefines.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, buttons, rmBtnEdit, rmSpeedBtns, rmScrnCtrls{$IFDEF rmDebug}, rmMsgList{$ENDIF}; type TRegKey = (rkHKEY_CLASSES_ROOT, rkHKEY_CURRENT_USER, rkHKEY_LOCAL_MACHINE, rkHKEY_USERS); TrmCustomComboBox = class(TrmCustomBtnEdit) private FScreenListBox: TrmCustomScreenListBox; fDropDownIndex : integer; fDropDownWidth: integer; fDropDownCount: integer; FEditorEnabled: Boolean; FOnDropDown: TNotifyEvent; fOnCloseUp: TNotifyEvent; FOnChanged: TNotifyEvent; {$IFDEF rmDebug} fMsg: TrmMsgEvent; {$ENDIF} procedure DoLBKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DoLBMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DoLBExit(Sender: Tobject); procedure ToggleListBox(Sender: TObject); procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER; procedure CMFontchanged(var Message: TMessage); message CM_FontChanged; procedure WMPaste(var Message: TWMPaste); message WM_PASTE; procedure WMCut(var Message: TWMCut); message WM_CUT; procedure CMCancelMode(var Message: TCMCancelMode); message CM_CancelMode; procedure wmKillFocus(var Message: TMessage); message wm_killfocus; procedure SetComboItems(const Value: TStrings); function GetComboItems: TStrings; function GetItemHeight: integer; function GetItemIndex: integer; procedure SetItemIndex(const Value: integer); protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure keyPress(var key: char); override; procedure CreateParams(var Params: TCreateParams); override; procedure InternalChanged; virtual; function GetEnabled: Boolean; override; procedure SetEnabled(Value: Boolean); override; property DropDownCount: integer read FDropDownCount write fDropDownCount default 8; property DropDownWidth: integer read fDropDownWidth write fDropDownWidth default 0; property EditorEnabled: Boolean read FEditorEnabled write FEditorEnabled default True; property Enabled default True; property Items: TStrings read GetComboItems write SetComboItems; property ItemHeight: integer read GetItemHeight; property OnChanged: TNotifyEvent read fOnChanged write fOnChanged; property OnDropDown: TNotifyEvent read FOnDropDown write fOnDropDown; property OnCloseUp: TNotifyEvent read fOnCloseUp write fOnCloseUp; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure WndProc(var Message: TMessage); override; function DroppedDown: boolean; {$IFDEF rmDebug} property OnMessage: TrmMsgEvent read fMsg write fMsg; {$ENDIF} property ItemIndex : integer read GetItemIndex write SetItemIndex; end; TrmNewComboBox = class(TrmCustomComboBox) published {$IFDEF D4_OR_HIGHER} property Anchors; property Constraints; {$ENDIF} property BiDiMode; property BorderStyle; property CharCase; property Color; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Text; property Visible; property EditorEnabled; property DropDownCount; property DropDownWidth; property Items; property ItemHeight; property OnChanged; property OnDropDown; property OnCloseUp; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; TrmComboBox = class(TCustomComboBox) private { Private declarations } FTextCompletion: Boolean; fHistory: TStringList; fEditText: string; fKeyBuffer: char; fMaxHistory: integer; fRegKey: TRegKey; fRegPath: string; fRegName: string; fMRUCombo: boolean; fCompletionInProgress: boolean; fAutoUpdateHistory: boolean; fLastCharIndex: integer; fLastCompletionIndex: integer; fDroppedDown: boolean; FOnCloseUp: TNotifyEvent; procedure FixRegPath; procedure SetMaxHistory(const Value: integer); procedure SetHistory(const Value: TStringList); procedure SetRegPath(const value: string); procedure SetRegName(const Value: string); procedure SetText; function GetTextCompletion: Boolean; procedure SetTextCompletion(const Value: Boolean); procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; protected { Protected declarations } procedure Change; override; procedure KeyPress(var Key: Char); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure DoEnter; override; procedure DoExit; override; public { Public declarations } constructor create(AOwner: TComponent); override; destructor destroy; override; procedure loaded; override; procedure DropDown; override; procedure InsertText(NewText: string); procedure LoadHistory; procedure SaveHistory; procedure UpdateHistory; procedure ClearHistory; {$IFNDEF D6_or_higher} procedure CloseUp; dynamic; {$ENDIF} published { Published declarations } property Style; {Must be published before Items} property Anchors; property AutoUpdateHistory: boolean read fAutoUpdateHistory write fAutoUpdateHistory default true; property BiDiMode; property CharCase; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property DropDownCount; property Enabled; property Font; property ImeMode; property ImeName; property ItemHeight; property Items; property MRUCombo: boolean read fMRUCombo write fMRUCombo default False; property MaxHistory: integer read fMaxHistory write SetMaxHistory default 20; property History: TStringList read fHistory write SetHistory; property MaxLength; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property RegKey: TRegKey read fRegKey write fRegKey; property RegPath: string read fRegPath write SetRegPath; property RegName: string read fRegName write SetRegName; property ShowHint; property Sorted; property TabOrder; property TabStop; property Text; property TextCompletion: Boolean read GetTextCompletion write SetTextCompletion default false; property Visible; property OnChange; property OnClick; property OnCloseUp: TNotifyEvent read FOnCloseUp write FOnCloseUp; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnDropDown; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; property OnStartDock; property OnStartDrag; end; implementation uses Registry; { TrmComboBox } procedure TrmComboBox.Change; begin case fKeyBuffer of #13: begin if fAutoUpdateHistory then SetText; end; #27: begin Text := fEditText; SelectAll; end; end; inherited; end; procedure TrmComboBox.ClearHistory; begin fHistory.Clear; end; {$IFNDEF D6_or_higher} procedure TrmComboBox.CloseUp; begin if Assigned(FOnCloseUp) then FOnCloseUp(Self); end; {$ENDIF} procedure TrmComboBox.CNCommand(var Message: TWMCommand); begin inherited; if Message.NotifyCode = CBN_CLOSEUP then begin fDroppedDown := false; CloseUp; end; end; constructor TrmComboBox.create(AOwner: TComponent); begin inherited create(AOwner); fHistory := TStringList.create; fMaxHistory := 20; fMRUCombo := false; FTextCompletion := false; fCompletionInProgress := false; fAutoUpdateHistory := true; fLastCharIndex := 0; fLastCompletionIndex := -1; fDroppedDown := false; end; destructor TrmComboBox.destroy; begin fHistory.free; inherited; end; procedure TrmComboBox.DoEnter; begin fEditText := Text; inherited; end; procedure TrmComboBox.DoExit; begin if fAutoUpdateHistory and (Text <> fEditText) then UpdateHistory; inherited; end; procedure TrmComboBox.DropDown; begin if fMRUCombo then LoadHistory; fDroppedDown := true; inherited; end; procedure TrmComboBox.FixRegPath; begin if (fRegName <> '') then begin if length(RegPath) > 0 then begin if fRegPath[length(fRegPath)] <> '\' then fRegPath := fRegPath + '\'; end; end else begin if length(RegPath) > 0 then begin if fRegPath[length(fRegPath)] = '\' then Delete(fRegPath, length(fRegPath), 1); end; end end; function TrmComboBox.GetTextCompletion: Boolean; begin Result := fTextCompletion; end; procedure TrmComboBox.InsertText(NewText: string); begin text := NewText; SetText; end; procedure TrmComboBox.KeyDown(var Key: Word; Shift: TShiftState); var Index, TextLength: Integer; wText: string; begin inherited; if FTextCompletion then begin if (key = vk_left) then begin SelLength := 0; key := 0; selstart := fLastCharIndex; fCompletionInProgress := false; end else if (key = vk_right) then begin selLength := 0; selstart := length(text); flastcharindex := selstart; fCompletionInProgress := false; key := 0; end else if (key = vk_down) and not (ssalt in shift) and not (fDroppedDown) then begin fCompletionInProgress := true; wText := copy(text, 0, selstart); Index := Perform(CB_FINDSTRING, fLastCompletionIndex, Integer(PChar(wText))); if Index <> CB_ERR then begin fLastCompletionIndex := index; TextLength := Length(wText); ItemIndex := Index; SelStart := TextLength; SelLength := Length(Text) - TextLength; fLastCharIndex := selstart; end; key := 0; end; end; end; procedure TrmComboBox.KeyPress(var Key: Char); begin inherited; fKeyBuffer := key; if ((fKeyBuffer = #13) or (fKeyBuffer = #27)) and (text <> fEditText) then Change; end; procedure TrmComboBox.KeyUp(var Key: Word; Shift: TShiftState); var Index, TextLength: Integer; begin inherited; fCompletionInProgress := false; if FTextCompletion then begin if (key <> vk_delete) and (key <> VK_BACK) then begin if (SelStart = Length(Text)) then begin fCompletionInProgress := true; Index := Perform(CB_FINDSTRING, -1, Integer(PChar(Text))); if Index <> CB_ERR then begin fLastCompletionIndex := index; TextLength := Length(Text); ItemIndex := Index; SelStart := TextLength; SelLength := Length(Text) - TextLength; fLastCharIndex := selstart; end end end; end; end; procedure TrmComboBox.loaded; begin inherited; if not (csdesigning in componentstate) then begin if fMRUCombo then LoadHistory; end; end; procedure TrmComboBox.LoadHistory; const Keys: array[TRegKey] of HKEY = (HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS); var Reg: TRegistry; loop: integer; wStr : string; begin if fHistory.Text = '' then begin if (fRegPath <> '') and (fRegName <> '') then begin Reg := TRegistry.create; try Reg.RootKey := Keys[fRegKey]; if Reg.OpenKeyReadOnly(fRegPath + fRegName) then begin try loop := 0; while loop < fMaxHistory do begin if Reg.ValueExists('Item_' + inttostr(loop)) then begin wstr := Reg.ReadString('Item_' + inttostr(loop)); if fHistory.IndexOf(wstr) = -1 then fHistory.Add(wstr); end; inc(loop); end; finally Reg.CloseKey; end; end; finally Reg.free; end; end; end; Items.Text := fHistory.Text; end; procedure TrmComboBox.SaveHistory; const Keys: array[TRegKey] of HKEY = (HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS); var Reg: TRegistry; loop: integer; begin Reg := TRegistry.create; try Reg.RootKey := Keys[fRegKey]; if Reg.OpenKey(fRegPath + fRegName, True) then begin try loop := 0; while (loop < fMaxHistory) and (loop < fHistory.Count) do begin Reg.WriteString('Item_' + inttostr(loop), fHistory.Strings[loop]); inc(loop); end; finally Reg.CloseKey; end; end; finally Reg.free; end; end; procedure TrmComboBox.SetHistory(const Value: TStringList); begin fHistory.assign(Value); end; procedure TrmComboBox.SetMaxHistory(const Value: integer); begin fMaxHistory := Value; end; procedure TrmComboBox.SetRegName(const Value: string); begin fRegName := Value; FixRegPath; end; procedure TrmComboBox.SetRegPath(const value: string); begin fRegPath := value; FixRegPath; end; procedure TrmComboBox.SetText; var index: integer; begin fEditText := Text; SelectAll; try if fMRUCombo then begin index := fHistory.IndexOf(fEditText); if index = -1 then fHistory.Insert(0, fEditText) else fHistory.Move(index, 0); SaveHistory; end; finally SelLength := 0; SelStart := length(text); end; end; procedure TrmComboBox.SetTextCompletion(const Value: Boolean); begin fTextCompletion := Value; end; procedure TrmComboBox.UpdateHistory; begin SetText; end; { TrmCustomComboBox } constructor TrmCustomComboBox.Create(AOwner: TComponent); begin inherited Create(AOwner); fDropDownCount := 8; OnBtn1Click := ToggleListBox; UseDefaultGlyphs := false; Btn1Glyph := nil; with GetButton(1) do begin font.name := 'Marlett'; font.size := 10; caption := '6'; end; FScreenListBox := TrmCustomScreenListBox.create(nil); with FScreenListBox do begin width := self.width; height := self.height * 8; visible := false; Parent := self; OnKeyDown := DoLBKeyDown; OnMousedown := DoLBMouseDown; Font.assign(self.font); end; FScreenListBox.hide; OnExit := doLBExit; Text := ''; ControlStyle := ControlStyle - [csSetCaption]; FEditorEnabled := True; end; destructor TrmCustomComboBox.Destroy; begin FScreenListBox.free; inherited Destroy; end; procedure TrmCustomComboBox.KeyDown(var Key: Word; Shift: TShiftState); var wIndex: integer; begin if not FEditorEnabled then begin if (key in [vk_delete]) then key := 0; end; if (((Key = VK_DOWN) or (key = VK_UP)) and (ssAlt in Shift)) or ((key = vk_f4) and (shift = [])) then begin if not FScreenListbox.visible then ToggleListBox(self) else begin Try if assigned(fOnCloseUp) then fOnCloseUp(self); except //Do Nothing... end; FScreenListbox.hide; end; key := 0; end else if ((Key = VK_DOWN) or (key = VK_UP)) and (shift = []) then begin if not fScreenListbox.visible then begin wIndex := FScreenListBox.ItemIndex; if (key = vk_up) and (wIndex > 0) then begin fScreenListBox.itemIndex := wIndex - 1; end; if (key = vk_down) and (wIndex < FScreenListBox.Items.Count) then begin fScreenListBox.itemIndex := wIndex + 1; end; if fScreenListBox.itemIndex <> wIndex then begin Self.Text := fScreenListBox.items[fScreenListBox.itemIndex]; InternalChanged; Self.SelectAll; end; end; key := 0; end else inherited KeyDown(Key, Shift); end; procedure TrmCustomComboBox.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or WS_CLIPCHILDREN or ES_MULTILINE; end; procedure TrmCustomComboBox.WMPaste(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TrmCustomComboBox.WMCut(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TrmCustomComboBox.CMEnter(var Message: TCMGotFocus); begin inherited; if AutoSelect and not (csLButtonDown in ControlState) then SelectAll; end; procedure TrmCustomComboBox.SetComboItems(const Value: TStrings); begin FScreenListBox.Items.assign(Value); end; procedure TrmCustomComboBox.ToggleListBox(Sender: TObject); var CP, SP: TPoint; begin CP.X := Left; CP.Y := Top + Height; SP := parent.ClientToScreen(CP); if assigned(fonDropdown) then fOnDropDown(self); SetFocus; SelectAll; with FScreenListBox do begin if fDropDownWidth = 0 then Width := self.width else width := fDropDownWidth; if Items.Count > fDropDownCount then Height := itemheight * fDropDownCount else begin Height := itemheight * Items.Count; if height = 0 then height := itemheight; end; height := height + 2; fDropDownIndex := ItemIndex; FScreenListBox.itemindex := fDropDownIndex; Left := SP.X; if assigned(screen.ActiveForm) then begin if (SP.Y + FScreenListBox.height < screen.activeForm.Monitor.Height) then FScreenListBox.Top := SP.Y else FScreenListBox.Top := (SP.Y - self.height) - FScreenListBox.height; end else begin if (SP.Y + FScreenListBox.height < screen.Height) then FScreenListBox.Top := SP.Y else FScreenListBox.Top := (SP.Y - self.height) - FScreenListBox.height; end; Show; SetWindowPos(handle, hwnd_topMost, 0, 0, 0, 0, swp_nosize or swp_NoMove); end; end; procedure TrmCustomComboBox.DoLBMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (FScreenListBox.ItemIndex <> -1) then begin FScreenListBox.hide; Text := FScreenListBox.items[fscreenlistbox.itemindex]; self.setfocus; self.SelectAll; end; if (FScreenListBox.ItemIndex <> fDropDownIndex) then InternalChanged; end; procedure TrmCustomComboBox.DoLBExit(Sender: Tobject); begin if FScreenListBox.visible then FScreenListBox.visible := false; end; procedure TrmCustomComboBox.DoLBKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key = vk_escape) then begin FScreenListBox.hide; self.setfocus; self.SelectAll; key := 0; end else if (key = vk_Return) then begin key := 0; FScreenListBox.hide; if FScreenListBox.ItemIndex <> fDropDownIndex then Text := FScreenListBox.items[fscreenlistbox.itemindex]; if Self.CanFocus then self.setfocus; self.SelectAll; InternalChanged; end end; procedure TrmCustomComboBox.WndProc(var Message: TMessage); begin {$IFDEF rmDebug} if assigned(OnMessage) then try OnMessage(Message); except end; {$ENDIF} case Message.Msg of WM_CHAR, WM_KEYDOWN, WM_KEYUP: if (FScreenListBox.visible) then begin if GetCaptureControl = nil then begin Message.result := SendMessage(FScreenListBox.Handle, message.msg, message.wParam, message.LParam); if message.result = 0 then exit; end; end; end; inherited WndProc(message); end; procedure TrmCustomComboBox.CMCancelMode(var Message: TCMCancelMode); begin inherited; if message.sender = fScreenListbox then exit; if (FScreenListBox.visible) then begin try if assigned(fOnCloseUp) then fOnCloseUp(self); except //Do Nothing. end; FScreenListBox.Hide; end; end; function TrmCustomComboBox.GetComboItems: TStrings; begin Result := fscreenlistbox.Items; end; procedure TrmCustomComboBox.keyPress(var key: char); begin if not FEditorEnabled then key := #0 else if key = #13 then key := #0; inherited; end; function TrmCustomComboBox.DroppedDown: boolean; begin Result := FScreenListBox.Visible; end; procedure TrmCustomComboBox.CMFontchanged(var Message: TMessage); begin inherited; fScreenListBox.Font.assign(self.Font); end; function TrmCustomComboBox.GetItemHeight: integer; begin Result := FScreenListBox.ItemHeight; end; procedure TrmCustomComboBox.wmKillFocus(var Message: TMessage); begin inherited; if (FScreenListBox.visible) then begin try if assigned(fOnCloseUp) then fOnCloseUp(self); except //Do Nothing. end; FScreenListBox.Hide; end; end; function TrmCustomComboBox.GetEnabled: Boolean; begin result := inherited GetEnabled; end; function TrmCustomComboBox.GetItemIndex: integer; begin result := FScreenListBox.Items.indexof(text); end; procedure TrmCustomComboBox.SetEnabled(Value: Boolean); begin inherited Setenabled(value); Btn1Enabled := value; end; procedure TrmCustomComboBox.SetItemIndex(const Value: integer); begin text := FScreenListBox.Items[Value]; end; procedure TrmCustomComboBox.InternalChanged; begin try modified := true; if assigned(fOnchanged) then fOnchanged(self); except //do nothing end; end; end.
unit GDIPng; interface uses Windows, SysUtils,Classes, Graphics,GR32,GR32_Backends; procedure Bitmap32ToPNGStream(ABitmap:TBitmap32;Stream: TStream;Transparent:boolean); procedure Bitmap32FromStream(ABitmap:TBitmap32;Stream: TStream;BGColor:TColor32); implementation uses ActiveX; type GdiplusStartupInput = packed record GdiplusVersion : Cardinal; DebugEventCallback : Pointer; SuppressBackgroundThread: BOOL; SuppressExternalCodecs : BOOL; end; TGdiplusStartupInput = GdiplusStartupInput; PGdiplusStartupInput = ^TGdiplusStartupInput; GPIMAGE =Pointer; GPBITMAP =Pointer; GPGRAPHICS =Pointer; const DLL='gdiplus.dll'; function GdipSaveImageToStream(image: GPIMAGE;stream: ISTREAM;ClsidEncoder: PGUID;pParams: Pointer): integer; stdcall;external DLL; function GdipDisposeImage(image: GPIMAGE): integer; stdcall;external DLL; function GdipCreateBitmapFromScan0(Width,Height,Stride,Format: Integer;Scan0: Pointer; out Bitmap: GPBITMAP):integer; stdcall;external DLL; function GdiplusStartup(out token: ULONG; input: PGdiplusStartupInput;output: Pointer): Integer; stdcall;external DLL; function GdiplusShutdown(token: ULONG):integer; stdcall;external DLL; function GdipCreateBitmapFromStream(stream: ISTREAM;out bitmap: GPBITMAP): integer; stdcall;external DLL; function GdipDrawImage(graphics: GPGRAPHICS; image: GPIMAGE; x,y: Single): integer; stdcall;external DLL; function GdipDeleteGraphics(graphics: GPGRAPHICS): Integer; stdcall;external DLL; function GdipCreateFromHDC(hdc: HDC;out graphics: GPGRAPHICS): integer; stdcall;external DLL; function GdipGetImageWidth(image: GPIMAGE;var width: UINT): integer; stdcall;external DLL; function GdipGetImageHeight(image: GPIMAGE;var height: UINT): integer; stdcall;external DLL; procedure Bitmap32ToPNGStream(ABitmap:TBitmap32;Stream: TStream;Transparent:boolean); const PNGEncoder:TGuid = '{557CF406-1A04-11D3-9A73-0000F81EF32E}'; PixelFormat32bppARGB = $26200A; PixelFormat32bppRGB = $22009; USESALPHA:array[boolean] of integer=(PixelFormat32bppRGB,PixelFormat32bppARGB); var Str:TStreamAdapter; Img:Pointer; begin with ABitmap do if GdipCreateBitmapFromScan0(Width,Height,Width*4,USESALPHA[Transparent],Bits,Img)=0 then begin Str:=TStreamAdapter.Create(Stream); GdipSaveImageToStream(Img,Str as IStream,@PNGEncoder,nil); GdipDisposeImage(Img); end; end; procedure Bitmap32FromStream(ABitmap:TBitmap32;Stream: TStream;BGColor:TColor32); var W,H:Cardinal; Img,Gr:Pointer; begin with ABitmap do if GdipCreateBitmapFromStream(TStreamAdapter.Create(Stream)as istream, Img)= 0 then begin GdipGetImageWidth(Img,W); GdipGetImageHeight(Img,H); SetSize(W,H); if DrawMode=dmOpaque then Clear(BGColor); GdipCreateFromHDC(Canvas.Handle,Gr); GdipDrawImage(Gr,Img,0,0); GdipDeleteGraphics(Gr); GdipDisposeImage(Img); end; end; var StartupInput: TGDIPlusStartupInput; GdiplusToken: ULONG; initialization StartupInput.GdiplusVersion := 1; GdiplusStartup(GdiplusToken, @StartupInput, nil); finalization GdiplusShutdown(GdiplusToken); end.
library UFRTesting; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} uses {$IFnDEF FPC} xmldom, XMLDoc, XMLIntf, Windows, {$ELSE} LCLIntf, LCLType, LMessages, DOM, UfrXmlToolsFp, {$ENDIF} Classes, SysUtils, ActiveX, IniFiles, UfrTypes, TitanDrv; const //Номер версии драйвера CNST__DRIVER_VERSION = 6; //Описание драйвера CNST__DRIVER_DESC = 'Titan Driver for UniFR'; type TArray4096OfByte = array[0..4095] of Byte; //поля LastShiftNum, SaledValue, CashRegValue, LastDocNum, LastReceiptNum и ShiftState нужны только для тестового драйвера TPrintDeviceCfg = record ComNum, DeviceNumber, LastErrorCode, LastShiftNum: Integer; LastDocNum, LastReceiptNum: DWord; SaledValue, CashRegValue: Int64; ShiftState: TShiftState; // MainAdminPass, Oper :DWord; LastErrorMess: string; InterfaceCallback: TInterfaceCallbackProc; DevAddr: string; TitanDriver: TTitanDriver; end; TArrayOfByte = array of Byte; const MessDeviceNotReady = 'Device not ready'; MessShiftMore24 = 'Shift more than 24 hours'; MessInvalidXML = 'Invalid XML parameters'; MessItemsPaysDifferent = 'Goods price is differ than cash paid'; var PrintDevices: array of TPrintDeviceCfg = nil; SendCommandSection: TRTLCriticalSection; stCustomError, WhereMe: string; CustomErrorCode: Integer; CriticalSections: array[0..8] of TRTLCriticalSection; //пароль 1-го оператора 33554433 //Вызывать InterfaceCallback надо только из того потока, из которого идет вызов экспортируемых функций dll(чаще всего это будет главный поток приложения). //Это надо: во-первых, чтобы юзер мог менять GUI в InterfaceCallback(т.к. в потоке dll не работает Synchronize и его "ручные" аналоги), //во-вторых, чтобы у юзера не возникало проблем с "отложенным" вызововом Callback'ов, т.е. когда юзер вызвал уже следующую экспортируемую процедуру, а //Callback'и еще выполняются для предыдущей. С другой стороны, нельзя чтобы Callback'и тормозили выполнение команд, нарушая тайм-ауты протокала ФР(нельзя //ждать, пока они у юзера завершат работу). Поэтому в процессе выполнения SendCommandAndGetAnswer(как и экспортируемых процедур) копим логи в очередь, а в //конце процедуры последовательно вызываем Callback'и для всей очереди и очищаем ее type TLogEvent = record DevIndex: Integer; FRLog: TFRLog; end; var LogEvents: array of TLogEvent = nil; LogEventsSection: TRTLCriticalSection; procedure FlushLogsQueue(); var j: Integer; begin if (Length(LogEvents) = 0) or (Length(PrintDevices) = 0) then Exit; EnterCriticalSection(LogEventsSection); for j := 0 to High(LogEvents) do with LogEvents[j] do begin PrintDevices[DevIndex].InterfaceCallback( hInstance, PrintDevices[DevIndex].DeviceNumber, cpfLog, 1, @FRLog); try FreeMem(FRLog.TextData); if FRLog.BinDataSize <> 0 then FreeMem(FRLog.BinData); except end; end; LogEvents := nil; LeaveCriticalSection(LogEventsSection); end; procedure AddLogEvent(const _DevIndex, _LogEventType: Integer; stTextData: string; const _BinDataSize: Integer = 0; const _BinData: Pointer = nil); var j: Integer; begin if not Assigned(PrintDevices[_DevIndex].InterfaceCallback) then Exit; EnterCriticalSection(LogEventsSection); j := Length(LogEvents); SetLength(LogEvents, j + 1); with LogEvents[j], FRLog do begin DevIndex := _DevIndex; Size := SizeOf(TFRLog); LogEventType := _LogEventType; stTextData := stTextData + #0; GetMem(TextData, Length(stTextData)); Move(stTextData[1], TextData^, Length(stTextData)); BinDataSize := _BinDataSize; if BinDataSize <> 0 then begin GetMem(BinData, BinDataSize); Move(_BinData^, BinData^, BinDataSize); end; end; LeaveCriticalSection(LogEventsSection); end; function GetDeviceIndex(const DeviceNumber: Integer): Integer; begin Result := 0; while Result <= High(PrintDevices) do begin if PrintDevices[Result].DeviceNumber = DeviceNumber then Exit; Inc(Result); end; Result := 0; //если юзер неверно задал DeviceNumber, то считаем что 0 end; procedure SaveConfig(const Number: Integer); var DevInd: Integer; begin DevInd := GetDeviceIndex(Number); with TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'UFR_TitanDrv.ini') do begin WriteInteger('Counters Configuration', 'LastDocNum' + IntToStr( Number), PrintDevices[DevInd].LastDocNum); WriteInteger('Counters Configuration', 'LastReceiptNum' + IntToStr( Number), PrintDevices[DevInd].LastReceiptNum); WriteInteger('Counters Configuration', 'LastShiftNum' + IntToStr( Number), PrintDevices[DevInd].LastShiftNum); WriteInteger('Money Counters', 'SaledValue' + IntToStr(Number), PrintDevices[DevInd].SaledValue); WriteInteger('Money Counters', 'CashRegValue' + IntToStr(Number), PrintDevices[DevInd].CashRegValue); WriteString('Device', 'DevAddr', PrintDevices[DevInd].DevAddr); Free(); end; end; procedure LoadConfig(const DevNumber: Integer); var DevInd: Integer; begin DevInd := GetDeviceIndex(DevNumber); with TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'UFR_TitanDrv.ini') do begin PrintDevices[DevInd].LastDocNum := ReadInteger('Counters Configuration', 'LastDocNum' + IntToStr(DevNumber), 0); PrintDevices[DevInd].LastReceiptNum := ReadInteger('Counters Configuration', 'LastReceiptNum' + IntToStr(DevNumber), 0); PrintDevices[DevInd].LastShiftNum := ReadInteger('Counters Configuration', 'LastShiftNum' + IntToStr(DevNumber), 0); PrintDevices[DevInd].SaledValue := ReadInteger('Money Counters', 'SaledValue' + IntToStr(DevNumber), 0); PrintDevices[DevInd].CashRegValue := ReadInteger('Money Counters', 'CashRegValue' + IntToStr(DevNumber), 0); PrintDevices[DevInd].DevAddr := ReadString('Device', 'DevAddr', '192.168.1.48'); Free(); end; end; function Int64ToCurr(AValue: Int64): Currency; begin Result := AValue / 100; end; procedure _UFRDone(DevNumber: Integer); var i, j: Integer; begin FlushLogsQueue; for i := 0 to High(PrintDevices) do begin if PrintDevices[i].DeviceNumber = DevNumber then begin SaveConfig(DevNumber); CoUninitialize(); if Assigned(PrintDevices[i].TitanDriver) then FreeAndNil(PrintDevices[i].TitanDriver); for j := i to High(PrintDevices) - 1 do PrintDevices[j] := PrintDevices[j + 1]; SetLength(PrintDevices, High(PrintDevices)); if Length(PrintDevices) = 0 then begin {$ifdef FPC} DoneCriticalSection(SendCommandSection); DoneCriticalSection(LogEventsSection); {$else} DeleteCriticalSection(SendCommandSection); DeleteCriticalSection(LogEventsSection); {$endif} end; Exit; end; end; end; procedure UFRDone(DevNumber: Integer); stdcall; var j: Integer; begin if Length(PrintDevices) = 0 then Exit; EnterCriticalSection(CriticalSections[1]); _UFRDone(DevNumber); LeaveCriticalSection(CriticalSections[1]); if Length(PrintDevices) = 0 then for j := 0 to High(CriticalSections) do DoneCriticalSection(CriticalSections[j]); end; function UFRMaxProtocolSupported: Integer; stdcall; begin Result := 1; end; function WriteLog(const stLog: string): Boolean; var fLog: TextFile; begin Result := False; AssignFile(fLog, WhereMe + 'UFR_TitanDrv.log'); if FileExists(WhereMe + 'UFR_TitanDrv.log') then Append(fLog) else Rewrite(fLog); if IOResult <> 0 then Exit; WriteLn(fLog, stLog); CloseFile(fLog); Result := True; end; function _UFRInit(DevNumber: Integer; XMLParams: PChar; InterfaceCallback: TInterfaceCallbackProc; PropCallback: TPropCallbackProc): Integer; var XMLDocument: TDOMDocument; XMLNode: TDOMNode; j, MaxLen: Integer; fErr: TextFile; begin if Length(PrintDevices) = 0 then begin WhereMe := ExtractFilePath(ParamStr(0)); stCustomError := ''; CustomErrorCode := 0; AssignFile(fErr, WhereMe + 'FRNextOpError.txt'); Reset(fErr); if IOResult = 0 then begin Read(fErr, stCustomError); try j := Pos(' ', stCustomError); CustomErrorCode := StrToInt(Copy(stCustomError, 1, j - 1)); Delete(stCustomError, 1, j); except stCustomError := ''; end; CloseFile(fErr); end; InitCriticalSection(SendCommandSection); InitCriticalSection(LogEventsSection); end; { Result:=-1; } Result := 0; CoInitialize(nil); XMLDocument := CreateXMLDoc(XMLParams); try if XMLDocument = nil then begin Result := errAssertInvalidXMLInitializationParams; Exit; end; WriteLog(Format( 'UFRInit (%d)-----------------------------------------------------------------'#13#10, [DevNumber]) + XMLParams); MaxLen := Length(PrintDevices); SetLength(PrintDevices, MaxLen + 1); PrintDevices[MaxLen].InterfaceCallback := InterfaceCallback; PrintDevices[MaxLen].TitanDriver := TTitanDriver.Create(nil); with PrintDevices[MaxLen] do try DeviceNumber := DevNumber; AddLogEvent(MaxLen, letInitializing, 'Driver initializing'); XMLNode := GetFirstNode(XMLDocument); XMLNode := XMLNode.firstChild; LastErrorCode := 0; LastErrorMess := ''; LoadConfig(DevNumber); PrintDevices[MaxLen].TitanDriver.DevAddr := PrintDevices[MaxLen].DevAddr; if LastReceiptNum > 0 then ShiftState := ssShiftOpened else ShiftState := ssShiftClosed; except Result := errLogicError; AddLogEvent(MaxLen, letError, 'Driver initializing error'); SetLength(PrintDevices, High(PrintDevices)); UFRDone(DevNumber); Exit; end; finally if Result <> 0 then CoUninitialize; XMLDocument.Free(); end; AddLogEvent(MaxLen, letInitialized, 'Driver successfully initialized'); end; function _UFRGetStatus(Number: Integer; var Status: TUFRStatus; FieldsNeeded: DWord): Integer; var DevInd: Integer; td: TTitanDriver; begin Result := 0; DevInd := GetDeviceIndex(Number); AddLogEvent(DevInd, letOther, 'Getting the device status'); if FlagPresented(FieldsNeeded, [fnBusy, fnShiftState, fnUnfiscalPrint, fnSerialNumber, fnLastShiftNum, fnCashRegValue]) then begin td := PrintDevices[DevInd].TitanDriver; td.GetDevState(); td.GetDocState(); td.LastReceipt(); if td.IsStateUpdated then begin td.IsStateUpdated := False; Status.Busy := td.Busy; Status.SerialNum := td.DevInfo.Model + ' ' + td.DevInfo.SerialNum; Status.LastShiftNum := td.DevInfo.CurrZ; end; //Status.Busy := False; Status.ShiftState := PrintDevices[DevInd].ShiftState; Status.CanNotPrintUnfiscal := False; //Status.LastShiftNum := PrintDevices[DevInd].LastShiftNum; // Сумма в кассе, в копейках Status.CashRegValue := PrintDevices[DevInd].CashRegValue; //необнуляемый итог Status.SaledValue := PrintDevices[DevInd].SaledValue; end; if (FieldsNeeded and fnLastDocNum) <> 0 then begin //Status.LastDocNum := PrintDevices[DevInd].LastDocNum; //Status.LastReceiptNum := PrintDevices[DevInd].LastReceiptNum; // Последний номер документа (в том числе инкассации и т.п.) Status.LastDocNum := td.DevInfo.ChkId; // Последний номер чека Status.LastReceiptNum := td.LastDocInfo.DocNum; end; if Result = 0 then AddLogEvent(DevInd, letOther, 'The device status has successfully obtained'); end; procedure SaveError(const DevInd, errCode: Integer); var errMess: string; begin case errCode of errLogicPrinterNotReady: errMess := MessDeviceNotReady; errLogic24hour: errMess := MessShiftMore24; errAssertInvalidXMLParams: errMess := MessInvalidXML; errAssertItemsPaysDifferent: errMess := MessItemsPaysDifferent; 0: Exit; end; PrintDevices[DevInd].LastErrorCode := errCode; PrintDevices[DevInd].LastErrorMess := errMess; end; function _UFRUnfiscalPrint(Number: Integer; XMLBuffer: PChar; Flags: Integer): Integer; const BarCodeTypes: array[0..8] of string = ('UPCA', 'UPCE', 'EAN13', 'EAN8', 'CODE39', 'ITF', 'CODABAR', 'CODE93', 'CODE128'); TextPosition: array[0..3] of string = ('NO', 'TOP', 'BOTTOM', 'TOP&BOTTOM'); var XMLDocument: TXMLDocument; XMLNode: TDOMNode; sBarCodeType, st: string; DevInd: Integer; td: TTitanDriver; tmpDoc: TFrDoc; begin DevInd := GetDeviceIndex(Number); AddLogEvent(DevInd, letOther, 'Start the non-fiscal printing'); td := PrintDevices[DevInd].TitanDriver; td.GetDevState(); //Result:=0; XMLDocument := CreateXMLDoc(XMLBuffer); if XMLDocument = nil then begin Result := errAssertInvalidXMLParams; AddLogEvent(DevInd, letError, MessInvalidXML); SaveError(DevInd, errAssertInvalidXMLParams); Exit; end; WriteLog('UFRUnfiscalPrint -----------------------------------------------------------------'#13#10 + XMLBuffer); tmpDoc := TFrDoc.Create(frdNonFiscal); try XMLNode := GetFirstNode(XMLDocument); XMLNode := XMLNode.firstChild; while XMLNode <> nil do begin if NodeNameIs(XMLNode, 'TextBlock') or NodeNameIs(XMLNode, 'TextLine') or NodeNameIs(XMLNode, 'TextPart') then begin if XMLNode.NodeName[5] = 'B' then st := string(XMLNode.FirstChild.NodeValue) //печатаемые строки текста else st := FindAttrByName(XMLNode, 'Text'); tmpDoc.AddText(st); end else if NodeNameIs(XMLNode, 'BarCode') then //печать штрих-кода begin sBarCodeType := FindAttrByName(XMLNode, 'Type'); st := FindAttrByName(XMLNode, 'Value'); if (sBarCodeType = 'EAN13') or (sBarCodeType = 'EAN-13') then begin tmpDoc.AddBarcode(st, 1); end; end else if NodeNameIs(XMLNode, 'Pass') then begin end else if NodeNameIs(XMLNode, 'Wait') then Sleep(GetIntValByName(XMLNode, 'MSecs', 1)); XMLNode := XMLNode.nextSibling; end; XMLNode := GetFirstNode(XMLDocument); if GetIntValByName(XMLNode, 'CutAfter', 0) = 1 then begin end; td.SendFrDoc(tmpDoc); stCustomError := td.DevInfo.Err; if stCustomError = '' then begin Result := 0; AddLogEvent(DevInd, letOther, 'The non-fiscal printing has been successfully completed'); end else begin Result := CustomErrorCode; AddLogEvent(DevInd, letError, stCustomError); end; SaveError(DevInd, Result); finally tmpDoc.Free(); if Assigned(XMLDocument) then FreeAndNil(XMLDocument); end; WriteLog('<Printing is complete>'#13#10); end; function _UFRFiscalDocument(Number: Integer; XMLDoc: PChar; var Status: TUFRStatus; var FieldsFilled: cardinal): Integer; const stDocType: array[0..7] of string = ('Receipt', 'Return', 'Deletion', 'ReceiptCopy', 'CashInOut', 'CollectAll', 'Report', 'Invoice'); SuccessfullyCompleted = 'The fiscal printing has been successfully completed'; var XMLDocument: TXMLDocument; MainNode: TDOMNode; st: string; ReportType: string; DevInd, DocType: Integer; ItemsPresented, UnfiscalPresented, ReceiptOpened: Boolean; CashRes: int64; //это только для отладочной версии td: TTitanDriver; tmpDoc: TFrDoc; //при pPrint=False только проверяется равенство цены покупаемых товаров и заплаченными за них деньгами function _PrintFiscal(const pPrint: Boolean): Integer; var XMLNode, XMLNode2, XMLNode3, XMLNode4: TDOMNode; st2: string; i, j, Discount: Integer; Quantity, PricePerOne, Val64, Val64_2, Sum: int64; begin Result := 0; Sum := 0; CashRes := 0; ReceiptOpened := False; tmpDoc := TFrDoc.Create(frdFiscal); //признак что начали печатать чек(его фискальную часть) while MainNode <> nil do begin if NodeNameIs(MainNode, 'Header') then begin XMLNode := MainNode.FirstChild; while XMLNode <> nil do begin if NodeNameIs(XMLNode, 'Unfiscal') and XMLNode.HasChildNodes then begin st := string(XMLNode.FirstChild.nodeValue); if st <> '' then UnfiscalPresented := True else begin XMLNode2 := XMLNode.FirstChild; while XMLNode2 <> nil do begin UnfiscalPresented := True; st := FindAttrByName(XMLNode2, 'Text'); if st = '' then st := ' ' else begin tmpDoc.AddText(st); end; XMLNode2 := XMLNode2.NextSibling; end; end; end; XMLNode := XMLNode.NextSibling; end; end else if NodeNameIs(MainNode, 'Receipt') and (DocType < 3) then begin XMLNode := MainNode.FirstChild; while XMLNode <> nil do begin if NodeNameIs(XMLNode, 'Items') then begin XMLNode2 := XMLNode.FirstChild; while XMLNode2 <> nil do begin if NodeNameIs(XMLNode2, 'Item') then begin ItemsPresented := True; st := FindAttrByName(XMLNode2, 'Name'); if Length(st) > 40 then st := FindAttrByName(XMLNode2, 'ShortName'); //в ФР указывается цена одного товара, в XML-параметрах может быть указана как цена одного товара(PricePerOne), так и //общая цена(Value=цена одного*количество) товаров. Параметр PricePerOne надо использовать в первую очередь. //количество указывается в тысячах как для ФР, так и в XML-параметрах, т.е. 1шт = 1000, 2шт = 2000 и т.п. Val64 := GetIntValByName(XMLNode2, 'Quantity', 1000); Quantity := Val64; if FindAttrByName(XMLNode2, 'PricePerOne') <> '' then begin //если указана стоимость одного товара, то надо использовать ее PricePerOne := GetIntValByName(XMLNode2, 'PricePerOne', 0); //получаем цену всех товаров для подсчета Sum if FindAttrByName(XMLNode2, 'Value') <> '' then Val64 := GetIntValByName(XMLNode2, 'Value', 0) else Val64 := PricePerOne * Quantity div 1000; Inc(Sum, Val64); end else begin //иначе используем параметр Value с ценой всех товаров Val64 := GetIntValByName(XMLNode2, 'Value', 0); Inc(Sum, Val64); //цена единицы товара PricePerOne := Val64 * 1000 div Quantity; end; // --- добавление строки продажи товара tmpDoc.AddSale(st, '', Int64ToCurr(PricePerOne), (Currency(Quantity) / 1000)); XMLNode3 := XMLNode2.firstChild; i := 1; st2 := ''; while XMLNode3 <> nil do begin if NodeNameIs(XMLNode3, 'Taxes') then begin XMLNode4 := XMLNode3.firstChild; while XMLNode4 <> nil do begin if NodeNameIs(XMLNode4, 'Tax') then begin if i < 5 then Inc(i); end; XMLNode4 := XMLNode4.nextSibling; end; end else if NodeNameIs(XMLNode3, 'Discounts') then begin //скидки и надбавки XMLNode4 := XMLNode3.firstChild; while XMLNode4 <> nil do begin if NodeNameIs(XMLNode4, 'Discount') then begin Val64 := GetIntValByName(XMLNode4, 'Value', 0); Inc(Sum, Val64); if Val64 < 0 then Val64 := Abs(Val64); //скидка end; XMLNode4 := XMLNode4.nextSibling; end; end else if NodeNameIs(XMLNode3, 'Unfiscal') then st2 := string(XMLNode3.firstChild.nodeValue); XMLNode3 := XMLNode3.nextSibling; end; if pPrint then begin ReceiptOpened := True; end; end; XMLNode2 := XMLNode2.nextSibling; end; end else if NodeNameIs(XMLNode, 'Discounts') then begin //скидки и надбавки Discount := 0; XMLNode2 := XMLNode.firstChild; while XMLNode2 <> nil do begin if NodeNameIs(XMLNode2, 'Discount') then begin Val64 := GetIntValByName(XMLNode2, 'Value', 0); Inc(Sum, Val64); Inc(Discount, Val64); // --- добавление скидки tmpDoc.AddDiscount(Int64ToCurr(Val64), 0); end; XMLNode2 := XMLNode2.nextSibling; end; if pPrint and ItemsPresented then begin end; end else if NodeNameIs(XMLNode, 'Payments') then begin //расплата и закрытие чека XMLNode2 := XMLNode.firstChild; Inc(CashRes, Sum); while XMLNode2 <> nil do begin if NodeNameIs(XMLNode2, 'Payment') then begin j := GetIntValByName(XMLNode2, 'TypeIndex', 0); if j > 4 then j := 4; Val64_2 := GetIntValByName(XMLNode2, 'Value', 1); Dec(Sum, Val64_2); // --- добавление строки оплаты tmpDoc.AddPayment(Int64ToCurr(Val64_2), j); end; XMLNode2 := XMLNode2.nextSibling; end; if pPrint and ItemsPresented then begin ReceiptOpened := False; end; end; XMLNode := XMLNode.nextSibling; end; end else if NodeNameIs(MainNode, 'Payment') and (DocType in [4, 8]) and pPrint then begin //внесение или выплата Val64 := GetIntValByName(MainNode, 'Value', 0); Inc(CashRes, Val64); end; MainNode := MainNode.nextSibling; end; // --- Отправка чека на печать td.SendFrDoc(tmpDoc); tmpDoc.Free(); if Sum <> 0 then Result := errAssertItemsPaysDifferent; //внесенная оплата не равна цене покупаемого товара SaveError(DevInd, Result); end; procedure _XMLError(); begin Result := errAssertInvalidXMLParams; AddLogEvent(DevInd, letError, MessInvalidXML); SaveError(DevInd, errAssertInvalidXMLParams); end; begin FillChar(Status, SizeOf(Status), 0); Result := 0; DevInd := GetDeviceIndex(Number); XMLDocument := CreateXMLDoc(XMLDoc); if XMLDocument = nil then begin _XMLError(); Exit; end; WriteLog('UFRFiscalDocument -----------------------------------------------------------------'#13#10 + XMLDoc); td := PrintDevices[DevInd].TitanDriver; td.GetDevState(); MainNode := GetFirstNode(XMLDocument); st := UpperCase(FindAttrByName(MainNode, 'DocType')); DocType := 0; while DocType <= High(stDocType) do begin if st = stDocType[DocType] then Break; Inc(DocType); end; MainNode := MainNode.firstChild; ReportType := ''; if DocType in [3, 5, 6] then begin case DocType of 3: begin //ReceiptCopy(копия последнего чека) end; 5: begin //CollectAll(выплата всех денег из кассы) PrintDevices[DevInd].CashRegValue := 0; SaveConfig(Number); end; 6: begin //отчеты while (MainNode <> nil) and (not NodeNameIs(MainNode, 'Report')) do MainNode := MainNode.nextSibling; if MainNode = nil then Exit; ReportType := UpperCase(FindAttrByName(MainNode, 'ReportType')); if ReportType = 'X' then begin // --- печать X-отчета td.PrintReport(REPORT_X1); end else if ReportType = 'Z' then begin // --- печать Z-отчета td.PrintReport(REPORT_Z1); end else if (ReportType = 'BRIEFBYDATE') or (ReportType = 'DETAILBYDATE') then begin st := FindAttrByName(MainNode, 'Parameters'); {DateFrom := ; DateTo := ; if (ReportType = 'BRIEFBYDATE') then td.PrintFMReport(FM_REPORT_SHORT_BY_DATE, DateFrom, DateTo) else if (ReportType = 'DETAILBYDATE') then td.PrintFMReport(FM_REPORT_FULL_BY_DATE, DateFrom, DateTo);} end else if (ReportType = 'BRIEFBYNUMBER') or (ReportType = 'DETAILBYNUMBER') then begin end else AddLogEvent(DevInd, letOther, SuccessfullyCompleted); end; end; if stCustomError = '' then AddLogEvent(DevInd, letOther, SuccessfullyCompleted) else begin Result := CustomErrorCode; AddLogEvent(DevInd, letError, stCustomError); end; SaveError(DevInd, Result); if Result = 0 then begin Inc(PrintDevices[DevInd].LastDocNum); if (DocType = 6) and (ReportType = 'Z') then //Z-report begin PrintDevices[DevInd].LastDocNum := 0; PrintDevices[DevInd].LastReceiptNum := 0; PrintDevices[DevInd].SaledValue := 0; Inc(PrintDevices[DevInd].LastShiftNum); PrintDevices[DevInd].ShiftState := ssShiftClosed; SaveConfig(Number); end; end; FreeAndNil(XMLDocument); Exit; end; ItemsPresented := False; UnfiscalPresented := False; Result := _PrintFiscal(False); if Result = 0 then begin // AutoClosingShift(DevInd); AddLogEvent(DevInd, letFiscCommand, 'Start the fiscal printing'); MainNode := GetFirstNode(XMLDocument); MainNode := MainNode.firstChild; Result := _PrintFiscal(True); if stCustomError = '' then begin if Result = 0 then AddLogEvent(DevInd, letOther, 'The fiscal printing has been successfully completed'); end else begin Result := CustomErrorCode; AddLogEvent(DevInd, letError, stCustomError); end; end; if Result = 0 then begin Inc(PrintDevices[DevInd].LastDocNum); if DocType in [0, 7] then begin Inc(PrintDevices[DevInd].LastReceiptNum); PrintDevices[DevInd].ShiftState := ssShiftOpened; end; if DocType in [0, 1, 2] then Inc(PrintDevices[DevInd].SaledValue, CashRes); Inc(PrintDevices[DevInd].CashRegValue, CashRes); SaveConfig(Number); end; FreeAndNil(XMLDocument); WriteLog('<Printing is complete>'#13#10); end; function _UFRProgram(Number: Integer; XMLDoc: PChar): Integer; var XMLDocument: TXMLDocument; XMLNode, XMLNode2: TDOMNode; TaxName, NewName, DefaultDepartmentName: string; DevInd: Integer; _YearHour, _MonthMin, _DaySec, TaxValue: word; begin Result := 0; DevInd := GetDeviceIndex(Number); XMLDocument := CreateXMLDoc(XMLDoc); if XMLDocument = nil then begin Result := errAssertInvalidXMLParams; AddLogEvent(DevInd, letError, MessInvalidXML); SaveError(DevInd, errAssertInvalidXMLParams); Exit; end; XMLNode := GetFirstNode(XMLDocument); if XMLNode = nil then begin FreeAndNil(XMLDocument); Exit; end; XMLNode := XMLNode.FirstChild; while XMLNode <> nil do begin if NodeNameIs(XMLNode, 'ProgramDateTime') then begin if UpperCase(FindAttrByName(XMLNode, 'Source')) = 'SYSTEM' then begin //дата DecodeDate(Now(), _YearHour, _MonthMin, _DaySec); Dec(_YearHour, 2000); //время DecodeTime(Time, _YearHour, _MonthMin, _DaySec, TaxValue); end; end else if NodeNameIs(XMLNode, 'ProgramTaxes') then begin XMLNode2 := XMLNode.FirstChild; while XMLNode2 <> nil do begin TaxName := FindAttrByName(XMLNode2, 'TaxName'); TaxValue := GetIntValByName(XMLNode2, 'RateValue', 1300); //делаем по умолчанию налог 13 XMLNode2 := XMLNode2.NextSibling; end; end else if NodeNameIs(XMLNode, 'ProgramDepartments') then begin DefaultDepartmentName := FindAttrByName(XMLNode, 'DefaultDepartmentName'); XMLNode2 := XMLNode.FirstChild; while XMLNode2 <> nil do begin //формируем данные для программирования параметров отдела NewName := FindAttrByName(XMLNode2, 'Name'); if NewName = '' then NewName := DefaultDepartmentName; XMLNode2 := XMLNode2.NextSibling; end; end; XMLNode := XMLNode.NextSibling; end; FreeAndNil(XMLDocument); SaveError(DevInd, 0); end; function _UFROpenDrawer(Number: Integer): Integer; var DevInd: Integer; begin Result := 0; DevInd := GetDeviceIndex(Number); end; function _UFRGetOptions(Number: Integer; var Options: int64): Integer; var DevInd: Integer; //FRVer :String[3]; begin DevInd := GetDeviceIndex(Number); AddLogEvent(DevInd, letOther, 'Getting the device options'); Options := foText or foDeleteReceipt or foZReport or foMoneyInOut or foXReport or foProgram or foTextInReceipt or foZeroReceipt or foBarCodeInNotFisc or //foCheckCopy or foTextInLine or foCalcChange or foDrawerOpen or foAllMoneyOut or foZWhenClosedShift or foAbsDiscountSum; //or foFixedNames //or foZClearMoney //ФР поддерживает специальные отчёты: // итоговый/детализированный отчет по датам; // итоговый отчет по сменам. Options := Options or foSpecialReport; //определяем - это ККМ(поддерживает ЭКЛЗ) или ЧПМ(не поддерживает ЭКЛЗ) { FRVer:='123'; FRVer:=CP866ToAnsi(FRVer); If FRVer<>'НЕТ' then Options:=Options or foSpecialReport or foFullLastShift;} Result := 0; SaveError(DevInd, 0); AddLogEvent(DevInd, letOther, 'The device options has successfully obtained'); end; function _UFRGetZReportData(Number: Integer; XMLData: PChar; var XMLDataSize: Integer): Integer; stdcall; var DevInd: Integer; stRes: string; begin Result := 0; DevInd := GetDeviceIndex(Number); AddLogEvent(DevInd, letOther, 'Getting Z-Report data'); stRes := '<ZReportData> '#13 + ' <DepartmentValues />' + '</ZReportData>'#0; if (XMLData = nil) or (XMLDataSize < Length(stRes)) then begin XMLDataSize := Length(stRes); Result := errAssertInsufficientBufferSize; AddLogEvent(DevInd, letError, 'Insufficient buffer size'); SaveError(DevInd, errAssertInsufficientBufferSize); Exit; end; Move(stRes[1], XMLData^, Length(stRes)); AddLogEvent(DevInd, letOther, 'Z-Report has successfully obtained'); end; function UFRCustomerDisplay(Number: Integer; XMLBuffer: PChar; Flags: Integer): Integer; stdcall; begin Result := errFunctionNotSupported; end; function UFRInit(DevNumber: Integer; XMLParams: PChar; InterfaceCallback: TInterfaceCallbackProc; PropCallback: TPropCallbackProc): Integer; stdcall; var j: Integer; begin if Length(PrintDevices) = 0 then for j := 0 to High(CriticalSections) do InitCriticalSection(CriticalSections[j]); EnterCriticalSection(CriticalSections[0]); Result := _UFRInit(DevNumber, XMLParams, InterfaceCallback, PropCallback); FlushLogsQueue; LeaveCriticalSection(CriticalSections[0]); end; function UFRGetStatus(Number: Integer; var Status: TUFRStatus; FieldsNeeded: DWord): Integer; stdcall; begin EnterCriticalSection(CriticalSections[2]); Result := _UFRGetStatus(Number, Status, FieldsNeeded); FlushLogsQueue(); LeaveCriticalSection(CriticalSections[2]); end; function UFRUnfiscalPrint(Number: Integer; XMLBuffer: PChar; Flags: Integer): Integer; stdcall; begin EnterCriticalSection(CriticalSections[3]); Result := _UFRUnfiscalPrint(Number, XMLBuffer, Flags); FlushLogsQueue(); LeaveCriticalSection(CriticalSections[3]); end; function UFRFiscalDocument(Number: Integer; XMLDoc: PChar; var Status: TUFRStatus; var FieldsFilled: cardinal): Integer; stdcall; begin EnterCriticalSection(CriticalSections[4]); Result := _UFRFiscalDocument(Number, XMLDoc, Status, FieldsFilled); FlushLogsQueue(); LeaveCriticalSection(CriticalSections[4]); end; function UFRProgram(Number: Integer; XMLDoc: PChar): Integer; stdcall; begin EnterCriticalSection(CriticalSections[5]); Result := _UFRProgram(Number, XMLDoc); FlushLogsQueue(); LeaveCriticalSection(CriticalSections[5]); end; function UFRGetOptions(Number: Integer; var Options: int64; var DriverName, VersionInfo, DriverState: OpenString): Integer; stdcall; begin Result := errLogicPrinterNotReady; DriverName := CNST__DRIVER_DESC; VersionInfo := SysUtils.IntToStr(CNST__DRIVER_VERSION); DriverState := 'No device initialized'; if PrintDevices = nil then Exit; DriverState := ''; EnterCriticalSection(CriticalSections[6]); Result := _UFRGetOptions(Number, Options); if Options and foSpecialReport <> 0 then DriverName := DriverName + 'K'; FlushLogsQueue(); LeaveCriticalSection(CriticalSections[6]); end; function UFROpenDrawer(Number: Integer; DrawerNum: Integer): Integer; stdcall; begin EnterCriticalSection(CriticalSections[7]); Result := _UFROpenDrawer(Number); LeaveCriticalSection(CriticalSections[7]); end; function UFRGetZReportData(Number: Integer; XMLData: PChar; var XMLDataSize: Integer): Integer; stdcall; begin EnterCriticalSection(CriticalSections[8]); Result := _UFRGetZReportData(Number, XMLData, XMLDataSize); FlushLogsQueue(); LeaveCriticalSection(CriticalSections[8]); end; procedure UFRGetLastLogicError(Number: Integer; var LogicError: TUFRLogicError); stdcall; begin if PrintDevices <> nil then begin LogicError.LogicError := PrintDevices[GetDeviceIndex(Number)].LastErrorCode; LogicError.LogicErrorText := PrintDevices[GetDeviceIndex(Number)].LastErrorMess; end; end; //для проверки правильности типов procedure CheckFuncTypes(); begin CheckFiscRegFuncTypes( UFRMaxProtocolSupported, UFRInit, UFRDone, UFRGetOptions, UFRGetStatus, UFRUnfiscalPrint, UFRFiscalDocument, UFRGetZReportData, UFROpenDrawer, UFRCustomerDisplay, UFRProgram, UFRGetLastLogicError); end; exports UFRInit, UFRMaxProtocolSupported, UFRDone, UFRGetStatus, UFRUnfiscalPrint, UFRFiscalDocument, UFRProgram, UFRGetOptions, UFRCustomerDisplay, UFRGetLastLogicError, UFROpenDrawer, UFRGetZReportData; end.
unit uPrintSpPostForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, uFControl, uLabeledFControl, uDateControl, uSpravControl, uPrintSpPostData, frxClass, frxDBSet, frxDesgn, frxExportPDF, frxExportRTF, frxExportXML, frxExportXLS, frxExportHTML, frxExportTXT; type TfmPrintSpPost = class(TForm) OkButton: TBitBtn; CancelButton: TBitBtn; Cur_Date: TqFDateControl; PostDS: TfrxDBDataset; PostReport: TfrxReport; frxDesigner1: TfrxDesigner; frxTXTExport1: TfrxTXTExport; frxHTMLExport1: TfrxHTMLExport; frxXLSExport1: TfrxXLSExport; frxXMLExport1: TfrxXMLExport; frxRTFExport1: TfrxRTFExport; frxPDFExport1: TfrxPDFExport; procedure OkButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private DM: TdmPrintSpPost; Design: Boolean; public constructor Create(AOwner: TComponent; DM: TdmPrintSpPost); reintroduce; end; var fmPrintSpPost: TfmPrintSpPost; implementation {$R *.dfm} uses qFTools; constructor TfmPrintSpPost.Create(AOwner: TComponent; DM: TdmPrintSpPost); begin inherited Create(AOwner); Self.DM := DM; Cur_Date.Value := Date; end; procedure TfmPrintSpPost.OkButtonClick(Sender: TObject); begin DM.ReportDS.Close; DM.ReportDS.ParamByName('Cur_Date').AsDate := Cur_Date.Value; DM.ReportDS.ParamByName('R1').AsInteger := 199; DM.ReportDS.ParamByName('R2').AsInteger := 299; DM.ReportDS.ParamByName('R3').AsInteger := 399; DM.ReportDS.ParamByName('R4').AsInteger := 499; DM.ReportDS.ParamByName('R5').AsInteger := 599; DM.ReportDS.ParamByName('R6').AsInteger := 699; DM.ReportDS.ParamByName('R7').AsInteger := 799; DM.ReportDS.ParamByName('R8').AsInteger := 899; DM.ReportDS.ParamByName('R9').AsInteger := 999; DM.ReportDS.Open; PostReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Asup\AsupPostSalary2.fr3'); PostReport.Variables['Cur_Date'] := QuotedStr(DateToStr(Cur_Date.Value)); if Design then PostReport.DesignReport else PostReport.ShowReport; end; procedure TfmPrintSpPost.CancelButtonClick(Sender: TObject); begin Close; end; procedure TfmPrintSpPost.FormClose(Sender: TObject; var Action: TCloseAction); begin qFAutoSaveIntoRegistry(Self, nil); end; procedure TfmPrintSpPost.FormShow(Sender: TObject); begin qFAutoLoadFromRegistry(Self, nil); end; procedure TfmPrintSpPost.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if ( ssCtrl in Shift) and ( ssAlt in Shift ) and ( ssShift in Shift ) then Design := not Design; end; end.
unit Biomasse; {- peuplement : - mySite : Site - initialisation de plante (parcelle.dateSemis), densité … (Bdd) - paramètre variétaux : kEpsiB, kRdt, tabSla(numPhase), penteBiom, kRepBiomLeaf, kResGrain, biomGrain, kdf (Bdd) - - Ltr : Lai, kdf - Assimilation : mySite.Par, KepsiB, ltr - Lai : - LaiIni : tabSla(numPhaseIni), biomTotIni - Lai : - Phase BVP… PSP LaiDev : tabSla(numPhase), penteBiom, kRepBiomLeaf, biomTot - Phase RPR…matu2 LaiScenescence : LaiFlo (chgt phase PSP->RPR), penteScen, Plante.cstr ou tr/trMax - Kcp : kcMax, ltr - Biomasse Totale : - BiomTotIni : densite, kResGrain, biomGrain - RespMaintenance : kRespMaint, biomTot, mySite.temp, - BiomTot : assimilation, respMaintenance, Plante.cstr - RdtPot : biomTotIp(phase psp->Rpr), biomTotFlo(phase Rpr->MatuRemplissage), kRdt (calculé lors du chgt de phase RPR->Matu - PuitRdt : rdtPot, biomTotFlo(phase Rpr->MatuRemplissage) (calculé lors du chgt de phase RPR-Matu - rendement : rdtPot, seuilTemp(matu remplissage), cstr ou tr/trMax - plante : - initialise Racine - paramètre variétaux : tabSeuilTemp(phase), tabSeuilRoot(Vrac, phase), kPhotoper (Bdd) - cstr : indice de contrainte hydrique Racine.DisponibleTrWater, Racine.MaxDisponibleTrWater - FAO - Eagleman - trMax : kcp, Site.Eto - tr : trMax, cstr - phase phéno : Peuplement.degDay, numphase, tabSeuilTemp(numPhase), sumDegDay ou datePhotoper - photopériode : cas phase phéno - déduit de la date de fin de saison des pluies (site.FinPluie), donne une date de fin de photopériode datePhotoper - calculé : kPhotoper - Racine : - paramètre variétaux : tabSeuilRoot(Vrac, phase) (Bdd) - mySol : Sol - myLastSousStrate : SousStrate - rootSpeed : tabSeuilRoot(Vrac, phase), Plante.phase - rootDepth : myLastSousStrate.depth - MaxDisponibleWater : mySol.MaxTrWater(myLastSousStrate) - DisponibleWater : mySol.DisponibleTrWater(myLastSousStrate) - ConsommeTr : mySol.ConsommeTrWater(myLastSousStrate), Plante.tr - UpDateTr : consommeTr, plante.tr (si tout n'as pu être consommer) } interface {Proc. d'initialisation du peuplement (Plante)} Procedure EvalBiomIni (Const SlaBVP,KResGrain, kPenteAero, kBaseAero,densite, biomGrain,SeuilTempGermi : Double; Var biomTot, BiomAero, sla, numphase,VRac,SeuilTemp :Double); // ok Procedure SumTemp(Const tempMoy, kTempPhase : Double; Var sumDD : Double); //ok Procedure EvolSDJOpt(Const TMoy,TBase,TOpt: Double; Var sumDD : Double); //ok Procedure EvalSumPhotoPer (Const DayLength, KPPCrit, kPPSens, kPPForme: Double; Var sumPP, SeuilPP : Double); Procedure EvolPhenoTemp(Const SeuilPP, TempGermi, TempBvp, TempRPR, TempMatu1, TempMatu2, RootSpeedBVP, RootSpeedPSP, RootSpeedRPR, RootSpeedMatu1,RootSpeedMatu2, KRdt, ThisDate, DateSemis,BiomTot : Double; Var NoPhase, Vrac, SumDD, sumPP, SeuilTemp, SumDDPhasePrec, biomtotStadeIp, cycleReel, RdtPot,DateMaturite : Double); Procedure EvolPhenoTempC(Const SeuilPP, TempGermi, TempBvp, TempRPR, TempMatu1, TempMatu2, RootSpeedBVP, RootSpeedPSP, RootSpeedRPR, RootSpeedMatu1,RootSpeedMatu2, KRdt, ThisDate, DateSemis,BiomTot, ConstRdt : Double; Var NoPhase, Vrac, SumDD, sumPP, SeuilTemp, SumDDPhasePrec, biomtotStadeIp, cycleReel, RdtPot,DateMaturite : Double); Procedure EvalLtr(Const Kdf, Lai : Double; Var ltr : Double); Procedure FreinEpsiBTemp(Const Tbase,TOpt, TMin, Tmax : Double; Var IndTemp : Double ); //ok Procedure AssimilatPotRapLeaf(Const KEpsiB, Par, Ltr, MaxBiomLeaf, BiomLeaf, NumPhase: double; Var assimPot :Double); // pas retenue Procedure AssimilatPotTemp(Const TabKassim : array of double; KEpsiB, Par, sumDD, SeuilTemp, Ltr, IndTemp,sumDDPhasePrec: double; numPhase : Integer; Var assimPot :Double); Procedure AssimilatPot(Const KAssimBVP, KAssimMatu1, KAssimMatu2, KEpsiB, Par, sumDD, SeuilTemp, Ltr, sumDDPhasePrec, NoPhase: double; Var assimPot :Double); Procedure AssimWUE(Const KAssimBVP, KAssimMatu1, KAssimMatu2,Par,KEpsiB, KWP, Tr, sumDD, SeuilTemp, Ltr, sumDDPhasePrec,NoPhase: double; Var assimPot :Double); Procedure AssimRUExWUE(Const KAssimBVP, KAssimMatu1, KAssimMatu2, KEpsiB, Par, sumDD, SeuilTemp, Ltr, sumDDPhasePrec, Tr, TrPot,NoPhase: double; Var assimPot :Double); Procedure AssimRUESwitchWUE(Const KAssimBVP, KAssimMatu1, KAssimMatu2, KEpsiB, Par, sumDD, SeuilTemp, Ltr, sumDDPhasePrec, KWP, Tr, TrPot,NoPhase: double; Var assimPot :Double); //ok Procedure Assimilats(Const KEpsiB, Par, Ltr, Cstr: double; Var assim :Double); //ok Procedure EvalRespMaint(Const biomTot, tempMoy, KtempMaint, kRespMaint, BiomFeuilles, Numphase : double; Var respMaint : Double); //ok Procedure EvolBiomasse(Const assimPot, tr, trPot, respMaint, KpenteAero,KbaseAero : double; Var dayBiomAero, dayBiomTot, biomTot, biomAero : Double) ; //ok Procedure EvolBiomTot(Const assimPot, respMaint, KpenteAero, KbaseAero : double; Var dayBiomAero, dayBiomTot, biomTot, biomAero : Double) ; Procedure EvalSlaRapBiom(Const SlaBVP, SlaRPR, KpenteSla, dayBiomLeaf, BiomLeaf : Double; Var sla : Double); Procedure EvolBiomLeaf(Const KpenteLaiDev, biomAero, KbaseLaiDev, dayRdt, dayBiomTot, Krealloc, RespMaint, AssimPot, Nophase : Double; Var biomLeaf, dayBiomLeaf, rdt, ManqueAssim, MaxBiomLeaf : Double); //ok Procedure EvolLAI(Const sla, biomLeaf : Double; Var lai : Double); //ok Procedure EvolKcp(Const KcMax, Ltr : Double; Var Kcp : Double); Procedure EvolRdt(Const SeuilTempMatu1,rdtPot, tempMoy, KTempPhase, tr, trPot, Nophase : Double; Var dayRdt : Double); // A supprimer plus tard Procedure EvalRdtPot(Const biomTotStadeFlor, biomTotStadeIp, Krdt : Double; Var rdtPot : Double); implementation uses UChaines, Math, ModelsManage, Main, GestionDesErreurs,SysUtils; {Proc. d'evolution du peuplement (Plante)} //-------------------------------------------------------------------------// // Initialisation des variables de la culture (Crop) //-------------------------------------------------------------------------// Procedure InitCrop(Const SeuilTempBVP,SeuilTempGermi,SeuilTempMatu1,SeuilTempMatu2,SeuilTempRPR: double; var numPhase,SumDDMax,SeuilTemp,DegreDay:double); begin numPhase:=1; SumDDMax:= SeuilTempBVP+SeuilTempGermi+SeuilTempMatu1+SeuilTempMatu2+SeuilTempRPR; SeuilTemp:=SeuilTempGermi; //DegreDay:=0; end; Procedure EvalRdtPot(Const biomTotStadeFlor, biomTotStadeIp, Krdt : Double; Var rdtPot : Double); { Evaluation du rendement potentiel en fonction de l'état de la plante définie par la différence de biomasse totale du stade Ip a Floraison Ie durant la phase RPR (reproductive) Nota : pas de prise ne compte d'un effet photoP sur la longueur du cycle et donc du rendement. } Begin rdtPot := max(0,kRdt * (biomTotStadeFlor - biomTotStadeIp)); End; Procedure EvalSumPhotoPer (Const DayLength, KPPCrit, kPPSens, kPPForme: Double; Var sumPP, SeuilPP : Double); { TODO : Modif jours court ou jours long implique une nouvelle variable type KPPShortDay, algo ecrit non fonctionnel } { KPPCrit : duree du jour pour la mise en place de la floraison permet une definition d'un jour donnee en ayant kForme=3 kPPSens : amplifie l'effet de la formulation de la photoperiode (Ex : si representation lineaire modifie la pente 0,2..1..5) kForme : forme de la courbe d'evolution de la photoperiode 1 : lineaire 2 : parabole 3 : exponentielle Quand SumPP est >= a seuilPP alors déclenchement de la phase Matu1 gere dans le module de gestion des phases IN: stRurMax : mm RuSurf : mm evap : mm trPot : mm evaPot : mm INOUT : stRuSurf : mm tr : mm stRur : mm stRu : mm OUT: etr : mm etm : mm } Var PPActual : Double; Begin try {cas jours court ou jours long : If KPPShortDay then PPactual := max(0.01, DayLength - KPPCrit); else PPactual := max(0.01, KPPCrit - DayLength ); } PPactual := max(0.01, DayLength - KPPCrit); seuilPP := power(10, kPPForme); sumPP := sumPP + kPPSens/power(PPActual,kPPForme); MainForm.memDeroulement.Lines.Add(TimeToStr(Time)+#9+'DayLength '+ FloatToStr(DayLength)+'sEUILPP '+ FloatToStr(SeuilPP)+' SummPP '+FloatToStr(Sumpp)); except AfficheMessageErreur('EvalSumPhotoPer',UBiomasse); end; End; Procedure SumTemp(Const tempMoy, kTempPhase : Double; Var sumDD : Double); { Simple cumul de degré/jour } Begin sumDD := sumDD + tempMoy -kTempPhase; End; //////////////////////////////////////////////////////////////////////////////// Procedure EvolSDJOpt(Const TMoy,TBase,TOpt: Double; Var sumDD : Double); { On ne somme que les valeurs sup a Tbase, et on borne a Topt les degres jours a ajouter. } Begin sumDD:=sumDD+max(min(TOpt,TMoy),TBase)-Tbase; End; //////////////////////////////////////////////////////////////////////////////// Procedure EvolPhenoTemp(Const SeuilPP, TempGermi, TempBvp, TempRPR, TempMatu1, TempMatu2, RootSpeedBVP, RootSpeedPSP, RootSpeedRPR, RootSpeedMatu1,RootSpeedMatu2, KRdt, ThisDate, DateSemis,BiomTot : Double; Var NoPhase, Vrac, SumDD, sumPP, SeuilTemp, SumDDPhasePrec, biomtotStadeIp, cycleReel, RdtPot,DateMaturite : Double); { InOut : SumDD, SeuilPP, SumPP, NoPhase } Var Change : Boolean; NumPhase : Integer; Begin Numphase := trunc(NoPhase); If NumPhase = 3 Then // Photoper PSP change := (sumPP >= seuilPP) else change := (SumDD >= SeuilTemp); begin If change then begin inc(numPhase); NoPhase := NumPhase; SumDDPhasePrec := sumDD; Case NumPhase Of 2 : Begin // BVP Developpement vegetatif seuilTemp := seuilTemp + TempBVP; Vrac := RootSpeedBVP; end; 3 : Begin // PSP Photoper SumPP := 0; Vrac := RootSpeedPSP; end; 4 : Begin // RPR Stade initiation paniculaire seuilTemp := SumDD + TempRPR; Vrac := RootSpeedRPR; biomtotStadeIp := BiomTot; end; 5 : Begin // Matu1 remplissage grains seuilTemp := seuilTemp + TempMatu1; if RootSpeedMatu1 = NullValue then Vrac := 0 else Vrac := RootSpeedMatu1; rdtPot := max(0,kRdt * (biomTot - biomTotStadeIp)); end; 6 : Begin // Matu2 dessication seuilTemp := seuilTemp + TempMatu2; if RootSpeedMatu2 = NullValue then Vrac := 0 else Vrac := RootSpeedMatu2; end; 7 :begin // Recolte CycleReel := ThisDate-Datesemis; DateMaturite := ThisDate; end; End; // Csae NumPhase end; // End change end; End; //////////////////////////////////////////////////////////////////////////////// Procedure EvolPhenoTempC(Const SeuilPP, TempGermi, TempBvp, TempRPR, TempMatu1, TempMatu2, RootSpeedBVP, RootSpeedPSP, RootSpeedRPR, RootSpeedMatu1,RootSpeedMatu2, KRdt, ThisDate, DateSemis,BiomTot, ConstRdt : Double; Var NoPhase, Vrac, SumDD, sumPP, SeuilTemp, SumDDPhasePrec, biomtotStadeIp, cycleReel, RdtPot,DateMaturite : Double); { InOut : SumDD, SeuilPP, SumPP, NoPhase } Var Change : Boolean; NumPhase : Integer; Begin try Numphase := trunc(NoPhase); If NumPhase = 3 Then // Photoper PSP Begin MainForm.memDeroulement.Lines.Add(TimeToStr(Time)+#9+'EvolPheno sEUILPP '+ FloatToStr(SeuilPP)+' SummPP '+FloatToStr(Sumpp)); change := (sumPP >= seuilPP); end else change := (SumDD >= SeuilTemp); begin If change then begin inc(numPhase); NoPhase := NumPhase; SumDDPhasePrec := sumDD; Case NumPhase Of 2 : Begin // BVP Developpement vegetatif seuilTemp := seuilTemp + TempBVP; Vrac := RootSpeedBVP; end; 3 : Begin // PSP Photoper SumPP := 0; Vrac := RootSpeedPSP; end; 4 : Begin // RPR Stade initiation paniculaire seuilTemp := SumDD + TempRPR; Vrac := RootSpeedRPR; biomtotStadeIp := BiomTot; end; 5 : Begin // Matu1 remplissage grains seuilTemp := seuilTemp + TempMatu1; if RootSpeedMatu1 = NullValue then Vrac := 0 else Vrac := RootSpeedMatu1; rdtPot := max(0,ConstRdt + kRdt * (biomTot - biomTotStadeIp)); end; 6 : Begin // Matu2 dessication seuilTemp := seuilTemp + TempMatu2; if RootSpeedMatu2 = NullValue then Vrac := 0 else Vrac := RootSpeedMatu2; end; 7 :begin // Recolte CycleReel := ThisDate-Datesemis; DateMaturite := ThisDate; end; End; // Csae NumPhase end; // End change end; except AfficheMessageErreur('EvolPhenoTempCereales',UBiomasse); end; End; //////////////////////////////////////////////////////////////////////////////// procedure EvalLtr(const Kdf, Lai : Double; var ltr : Double); begin try ltr := exp(-KDf * lai) ; except AfficheMessageErreur('EvalLtr',UBiomasse); end; end; Procedure FreinEpsiBTemp(Const Tbase,TOpt, TMin, Tmax : Double; Var IndTemp : Double ); Var TempBorne,Topt1 : Double; Begin Topt1 :=25; // TempBorne := 0.25* TMin + 0.75 * Tmax; TempBorne := (TMin+TMax)/2; TempBorne := Min (TempBorne, Topt1); TempBorne := Max (TempBorne, TBase); IndTemp := (TempBorne - TBase)/Topt1-TBase; End; // Pas retenue // validation avec cstreagle 22/08/2002 Procedure AssimilatPotTemp(Const TabKassim: array of double; KEpsiB, Par, sumDD, SeuilTemp, Ltr, IndTemp,sumDDPhasePrec: double; numPhase : Integer; Var assimPot :Double); { AssimPot de matiere seche Kg/ha/j rg Mj/m²/j (* 10000 = 1 ha) KEpsiB en g/Mj (/1000 = 1 kg) kpar = 0.5 ou 0.48 } Var KAssim : Double; PhasePred : Integer; Begin PhasePred := numPhase-1; // On rapporte SumDD et SeuilTemp au rapport de degré jour // sur la seule phase en cours, avant floraison Kassim tjs a 1 // => second membre = 0 pour phases avant floraison KAssim := TabKAssim[PhasePred] + (sumDD-sumDDPhasePrec)*(TabKAssim[numPhase]-TabKAssim[PhasePred]) / (SeuilTemp-sumDDPhasePrec); assimPot := Par * KEpsiB * KAssim * 10 * (1-LTR)* IndTemp; End; // validation avec cstreagle 22/08/2002 Procedure AssimilatPot(Const KAssimBVP, KAssimMatu1, KAssimMatu2, KEpsiB, Par, sumDD, SeuilTemp, Ltr, sumDDPhasePrec, NoPhase: double; Var assimPot :Double); { AssimPot de matiere seche Kg/ha/j rg Mj/m²/j (* 10000 = 1 ha) KEpsiB en g/Mj (/1000 = 1 kg) kpar = 0.5 ou 0.48 } Var KAssim : Double; NumPhase : Integer; Begin try NumPhase := trunc(NoPhase); // Pas d'assimilation durant la germination // Pour les phases de maturations,On reduit progressivement KAssim : // en fonction de l'évolution des degres jours sur le delta de la phase en cours Case NumPhase of 1 : assimPot := 0; 2..4 : assimPot := Par * KEpsiB * KAssimBVP * 10 * (1-LTR); 5 : begin KAssim := KAssimBVP + (sumDD-sumDDPhasePrec)*(KAssimMatu1 -KAssimBVP) / (SeuilTemp-sumDDPhasePrec); assimPot := Par * KEpsiB * KAssim * 10 * (1-LTR); end; 6 : begin KAssim := KAssimMatu1 + (sumDD-sumDDPhasePrec)*(KAssimMatu2 -KAssimMatu1) / (SeuilTemp-sumDDPhasePrec); assimPot := Par * KEpsiB * KAssim * 10 * (1-LTR); end; end; // Case except AfficheMessageErreur('AssimilatPot',UBiomasse); end; End; Procedure AssimWUE(Const KAssimBVP, KAssimMatu1, KAssimMatu2,Par,KEpsiB, KWP, Tr, sumDD, SeuilTemp, Ltr, sumDDPhasePrec,NoPhase: double; Var assimPot :Double); { AssimPot de matiere seche Kg/ha/j rg Mj/m²/j (* 10000 = 1 ha) KEpsiB en g/Mj (/1000 = 1 kg) kpar = 0.5 ou 0.48 KWP * 10 0000 pour rapporter en Kg/Ha de conv eau/sucre } Var KAssim : Double; NumPhase : Integer; Begin try NumPhase := trunc(NoPhase); // Pas d'assimilation durant la germination // Pour les phases de maturations,On reduit progressivement KAssim : // en fonction de l'évolution des degres jours sur le delta de la phase en cours Case NumPhase of 1 : assimPot := 0; 2..4 : assimPot := Par * KEpsiB * KAssimBVP * 10 * (1-LTR); 5 : begin KAssim := KAssimBVP + (sumDD-sumDDPhasePrec)*(KAssimMatu1 -KAssimBVP) / (SeuilTemp-sumDDPhasePrec); assimPot := KWP * 10000 * Tr * Kassim; end; 6 : begin KAssim := KAssimMatu1 + (sumDD-sumDDPhasePrec)*(KAssimMatu2 -KAssimMatu1) / (SeuilTemp-sumDDPhasePrec); assimPot := KWP * 10000 * Tr * Kassim; end; end; // Case except AfficheMessageErreur('AssimWUE',UBiomasse); end; End; { TODO : // AssimilatRUExWUEremplacera a terme AssimilatPot et EvolBiomasse avec EvolBiomTot } Procedure AssimRUExWUE(Const KAssimBVP, KAssimMatu1, KAssimMatu2, KEpsiB, Par, sumDD, SeuilTemp, Ltr, sumDDPhasePrec, Tr, TrPot,NoPhase: double; Var assimPot :Double); { AssimPot de matiere seche Kg/ha/j rg Mj/m²/j (* 10000 = 1 ha) KEpsiB en g/Mj (/1000 = 1 kg) kpar = 0.5 ou 0.48 } Var KAssim : Double; NumPhase : Integer; Begin try NumPhase := trunc(NoPhase); // Pas d'assimilation durant la germination // Pour les phases de maturations,On reduit progressivement KAssim : // en fonction de l'évolution des degres jours sur le delta de la phase en cours Case NumPhase of 1 : assimPot := 0; 2..4 : assimPot := Par * KEpsiB * KAssimBVP * 10 * (1-LTR); 5 : begin KAssim := KAssimBVP + (sumDD-sumDDPhasePrec)*(KAssimMatu1 -KAssimBVP) / (SeuilTemp-sumDDPhasePrec); assimPot := Par * KEpsiB * KAssim * 10 * (1-LTR) * Tr/TrPot; end; 6 : begin KAssim := KAssimMatu1 + (sumDD-sumDDPhasePrec)*(KAssimMatu2 -KAssimMatu1) / (SeuilTemp-sumDDPhasePrec); assimPot := Par * KEpsiB * KAssim * 10 * (1-LTR) * Tr/TrPot; end; end; // Case except AfficheMessageErreur('AssimRUExWUE',UBiomasse); end; End; Procedure AssimRUESwitchWUE(Const KAssimBVP, KAssimMatu1, KAssimMatu2, KEpsiB, Par, sumDD, SeuilTemp, Ltr, sumDDPhasePrec, KWP, Tr, TrPot,NoPhase: double; Var assimPot :Double); { AssimPot de matiere seche Kg/ha/j rg Mj/m²/j (* 10000 = 1 ha) KEpsiB en g/Mj (/1000 = 1 kg) kpar = 0.5 ou 0.48 KWP * 10 0000 pour rapporter en Kg/Ha de conv eau/sucre} Var KAssim, assimWUE : Double; NumPhase : Integer; Begin try NumPhase := trunc(NoPhase); // Pas d'assimilation durant la germination // Pour les phases de maturations,On reduit progressivement KAssim : // en fonction de l'évolution des degres jours sur le delta de la phase en cours Case NumPhase of 1 : Begin assimPot := 0; assimWUE := 0; end; 2..4 : Begin assimPot := Par * KEpsiB * KAssimBVP * 10 * (1-LTR); assimWue := KWP * 10000 * Tr * KassimBVP; end; 5 : begin KAssim := KAssimBVP + (sumDD-sumDDPhasePrec)*(KAssimMatu1 -KAssimBVP) / (SeuilTemp-sumDDPhasePrec); assimPot := Par * KEpsiB * KAssim * 10 * (1-LTR) * Tr/TrPot; assimWue := KWP * 10000 * Tr * Kassim; end; 6 : begin KAssim := KAssimMatu1 + (sumDD-sumDDPhasePrec)*(KAssimMatu2 -KAssimMatu1) / (SeuilTemp-sumDDPhasePrec); assimPot := Par * KEpsiB * KAssim * 10 * (1-LTR) * Tr/TrPot; assimWue := KWP * 10000 * Tr * Kassim; end; end; // Case assimpot := min(assimpot, assimWUE); except AfficheMessageErreur('AssimRUESwitchWUE',UBiomasse); end; End; // Pas retenue // validation avec cstreagle 22/08/2002 Procedure AssimilatPotRapLeaf(Const KEpsiB, Par, Ltr, MaxBiomLeaf, BiomLeaf, NumPhase: double; Var assimPot :Double); { AssimPot de matiere seche Kg/ha/j rg Mj/m²/j (* 10000 = 1 ha) KEpsiB en g/Mj (/1000 = 1 kg) kpar = 0.5 ou 0.48 } Var KAssim : Double; Begin try KAssim := min (1,1-max(0,(BiomLeaf-MaxBiomLeaf)/(0.3*BiomLeaf))); assimPot := Par * KEpsiB * KAssim * 10 * (1-LTR); // prise en compte de la non assimilation en periode de germination if numphase < 2 then assimpot := 0; except AfficheMessageErreur('AssimilatPotRapLeaf',UBiomasse); end; End; (* jeu d'essai avec reduction d'assimilation et TMin Procedure AssimilatPot(Const TabKassim : array of double; KEpsiB, Par, sumDD, SeuilTemp, Ltr, TMin: double; numPhase : Integer; Var assimPot :Double); { AssimPot de matiere seche Kg/ha/j rg Mj/m²/j (* 10000 = 1 ha) KEpsiB en g/Mj (/1000 = 1 kg) kpar = 0.5 ou 0.48 } Var KAssim, Ktemp : Double; PhasePred : Integer; Begin PhasePred := numPhase-1; { TODO : Revoir rapport sumdd et SeuilTemp : rapport sur phase seule. } KAssim := TabKAssim[PhasePred] + sumDD*(TabKAssim[numPhase]-TabKAssim[PhasePred]) / SeuilTemp; { If Tmoy < 20 then KTemp := Max( 0,Tmoy-10)/10 else if Tmoy < 40 then Ktemp := 1 else if Tmoy < 60 then Ktemp := 1 - ((TMoy-40)/ 20) else Ktemp := 0; } If TMin < 22 then KTemp := Max( 0,TMin-10)/12 else Ktemp := 1 ; assimPot := Par * KEpsiB * KAssim * Ktemp * 10 * (1-LTR); End; *) Procedure Assimilats(Const KEpsiB, Par, Ltr, Cstr: double; {Proc 76} Var assim :Double); // ViB: à supprimer, spé palmier // proc reprise par Palmier.EvolOffreBruteJour Proc 205 Begin try assim := Par * KEpsiB * Cstr * 10 * (1-LTR); except AfficheMessageErreur('Assimilats',UBiomasse); end; End; procedure EvalRespMaint(const biomTot, tempMoy, KtempMaint, kRespMaint, BiomFeuilles, Numphase : Double; var respMaint : Double); { RespMaint Kg/ha/j en équivalent matière sèche KRespMaint (0.015) KTempMaint °C (25 ) } begin try respMaint := kRespMaint * biomTot * power(2, (tempMoy - kTempMaint) / 10); if (Numphase > 4) then begin if (Biomfeuilles = 0) then begin respMaint := 0; end; end; except AfficheMessageErreur('EvalRespMaint',UBiomasse); end; end; Procedure EvolBiomasse(Const assimPot, tr, trPot, respMaint, KpenteAero, KbaseAero : double; Var dayBiomAero, dayBiomTot, biomTot, biomAero : Double) ; { Biomtot en Kg/ha/j Basé sur des relations allométriques bornées aux extrèmes } Begin try dayBiomTot := assimPot* tr/trPot - RespMaint; biomTot := biomTot + dayBiomTot; dayBiomAero := BiomAero; BiomAero := Min(0.9, kPenteAero * biomTot + kBaseAero)* biomTot ; dayBiomAero := BiomAero - dayBiomAero; except AfficheMessageErreur('EvolBiomasse' + FloatToStr(trpot-RespMaint),UBiomasse); end; End; Procedure EvolBiomTot(Const assimPot, respMaint, KpenteAero, KbaseAero : double; Var dayBiomAero, dayBiomTot, biomTot, biomAero : Double) ; { Biomtot en Kg/ha/j Basé sur des relations allométriques bornées aux extrèmes } Begin try dayBiomTot := assimPot - RespMaint; biomTot := biomTot + dayBiomTot; dayBiomAero := BiomAero; BiomAero := Min(0.9, kPenteAero * biomTot + kBaseAero)* biomTot ; dayBiomAero := BiomAero - dayBiomAero; except AfficheMessageErreur('EvolBiomTot',UBiomasse); end; End; Procedure EvalSlaRapBiom(Const SlaBVP, SlaRPR, KpenteSla, dayBiomLeaf, BiomLeaf : Double; Var sla : Double); { On suppose que les jeunes feuilles on un SLA supérieur aux vieilles feuilles. La fraction de jeunes (nouvelles) feuilles fait donc monter le SLA global du couvert. Le paramètre penteSLA provoque une chute générale du SLA (penteSLA = chute relative par jour = fraction de différence entre SLAmax et SLAmin). Fonctionnement conçu surtout pour les légumineuses, mais peut être aussi adapté aux autres espèces. Paramètres : SLAmax (0.001 … 0.01), ex : 0.007 SLAmin (0.001 … 0.01), ex : 0.002 penteSLA (0 … 0.2), ex : 0.1 Avec : SLAini = SLAmax Equation : SLA(j) = min (SLAmax , max (SLAmin , [(SLA(j-1) - dSLA*(SLAmax-SLAmin)) * (BMfeuille(j-1)) / BMfeuille(j)) + SLAmax * (BMfeuille(j)-BMfeuille(j-1)) / BMfeuille(j)])) } Begin try /// Modif cb 03/01/29 { If dayBiomLeaf >0 then sla := (sla - KpenteSla * (sla- TabSla[ord(phRPR)])) * (BiomLeaf- dayBiomLeaf)/BiomLeaf + TabSla[ord(phBVP)] * (dayBiomLeaf/BiomLeaf) else sla := sla - KpenteSla * (sla- TabSla[ord(phRPR)]); } If dayBiomLeaf >0 then sla := (sla - KpenteSla * (sla- SlaRPR)) * (BiomLeaf- dayBiomLeaf)/BiomLeaf + SlaBVP * (dayBiomLeaf/BiomLeaf); /// Modif cb 03/01/29 sla := min(SlaBVP, max(SlaRPR , sla)); except AfficheMessageErreur('EvalSlaRapBiom',UBiomasse); end; End; //////////////////////////////////////////////////////////////////////////////// Procedure EvalSlaCereales(Const SlaBVP, SlaRPR, KpenteSla, dayBiomLeaf, BiomLeaf, NumPhase : Double; Var sla : Double); { On suppose que les jeunes feuilles on un SLA supérieur aux vieilles feuilles. La fraction de jeunes (nouvelles) feuilles fait donc monter le SLA global du couvert. Le paramètre penteSLA provoque une chute générale du SLA (penteSLA = chute relative par jour = fraction de différence entre SLAmax et SLAmin). Fonctionnement conçu surtout pour les légumineuses, mais peut être aussi adapté aux autres espèces. Paramètres : SLAmax (0.001 … 0.01), ex : 0.007 SLAmin (0.001 … 0.01), ex : 0.002 penteSLA (0 … 0.2), ex : 0.1 Avec : SLAini = SLAmax Equation : SLA(j) = min (SLAmax , max (SLAmin , [(SLA(j-1) - dSLA*(SLAmax-SLAmin)) * (BMfeuille(j-1)) / BMfeuille(j)) + SLAmax * (BMfeuille(j)-BMfeuille(j-1)) / BMfeuille(j)])) } Begin try /// Modif cb 03/01/29 { If dayBiomLeaf >0 then sla := (sla - KpenteSla * (sla- TabSla[ord(phRPR)])) * (BiomLeaf- dayBiomLeaf)/BiomLeaf + TabSla[ord(phBVP)] * (dayBiomLeaf/BiomLeaf) else sla := sla - KpenteSla * (sla- TabSla[ord(phRPR)]); } // Modif 19/08/04 { If dayBiomLeaf >0 then sla := (sla - KpenteSla * (sla - SlaRPR)) * (BiomLeaf- dayBiomLeaf)/BiomLeaf + SlaBVP * (dayBiomLeaf/BiomLeaf); } If Numphase = 1 then sla := SlaBvp; sla := (sla - KpenteSla * (sla - SlaRPR)) * (BiomLeaf- dayBiomLeaf)/BiomLeaf + (SlaBVP+sla)/2 * (dayBiomLeaf/BiomLeaf); /// Modif cb 03/01/29 sla := min(SlaBVP, max(SlaRPR , sla)); except AfficheMessageErreur('EvalSlaCereales',UBiomasse); end; End; //////////////////////////////////////////////////////////////////////////////// Procedure EvolBiomLeaf(Const KpenteLaiDev, biomAero, KbaseLaiDev, dayRdt, dayBiomTot, Krealloc, RespMaint, AssimPot, Nophase : Double; Var biomLeaf, dayBiomLeaf, rdt, ManqueAssim, MaxBiomLeaf : Double); { Evolution du LAI en 2 étapes : Avant Floraison : Relation allométrique biomasse Aérienne-Foliaire, bornée aux extrèmes Pb Apparent : la biomasse foliaire chute pendant la phase RPR en cycle Long! pb de calage des la pente et du bornage ? Après floraison : concept de compétition (répartition assimilats), une scénescence peut apparaitre si l'apport en assimilat (dayBiomTot) est inf à la demande (dayRdt)pour la croissance des grains, on retranche alors cette différence à la biomasse aérienne. Remarque : avec les réserve (palmier a huile) on instituait une réallocation moindre que la différence des demandes On borne cette diminution à 10 kg/ha pour des problèmes de simulation (division/0) dans les calculs de transpiration } //Krealloc := 0.5; Var NewBLeaf, cM, bM : Double; NumPhase : Integer; Begin try //!!! Kchimique dans rdt...mil sorgho = 1 donc sans effet mais ? If NoPhase <= 4 then begin // PhRPR phase reproductive //!!! Test scenescence et dayBiomTot!!! // if daybiomTot < 0 then TRes[biomLeaf] := max (TRes[biomLeaf]+daybiomTot, 1) // else begin // equation de Misterlich : y = aM + bM * cM puiss x // Bornes des valeurs : Am -0.12..0.12, bM 0..1, x 0..50, cM // lissage de la relation linéaire au point de changement de pente // (bornage à 0.1 ou 0.2) // données d'entrées pente relation allometrique, seuil asymptotique (bornage) // base de la pente // relation lineaire pour faire le lien avec la pente de Misterlich // aM = seuil et bM = base - seuil) // cM = (penteAllom / bM + 0.78)/0.75 //Attention valeurs rapporte en T/Ha pour ne pas partir dans les choux bM := kBaseLaiDev - 0.1; cM := ((kPenteLaiDev*1000)/ bM + 0.78)/0.75; NewBLeaf := (0.1 + bM * power(cM,BiomAero/1000))* BiomAero; // NewBLeaf := max(0.1, kPenteLaiDev * BiomAero + kBaseLaiDev) * BiomAero; NewBLeaf := min(NewBLeaf,BiomAero); // end; end else Begin // phase de scenescence ie il ne peut y avoir que decroissance de biomleaf ManqueAssim := 0; if NoPhase = 5 then // Phase Matu1 begin //dans ManqueAssim on ne rajoute pas le manque en assimilat // (dayBiomTot < 0) pour l'evaluation du puit du rendement //? et pour les feuilles quelle est alors la part a retrancher, // faut il ajouter ce manque de daybiomtot? ManqueAssim := max(0,(dayRdt - max(0,dayBiomTot))); // en attendant diminution de l'augmentation de rdt // Krealloc : pourcentage d'assimilat realloue par les feuilles/?Tiges // modif du 11/01/05 cb // avant rdt:= rdt + max(0, dayRdt - ManqueAssim * KRealloc); // bornage de la croissance de rendement par la qte restante de feuilles rdt:= rdt + min((biomleaf-10)* KRealloc*0.5,max(0, dayRdt - ManqueAssim * KRealloc)); // Fin modif du 11/01/05 cb end; // on ajoute au ManqueAssim ce qui est pris pour la respMaint, // ie dayBiomtot en val negative ManqueAssim := ManqueAssim - min(0,dayBiomTot); // else ManqueAssim := max(0,(RespMaint) - AssimPot); NewBLeaf := max (biomLeaf- (ManqueAssim * KRealloc)*0.5, 10); // NewBLeaf := max (biomLeaf- ManqueAssim, 10); // NewBLeaf := max (biomLeaf- (ManqueAssim * KRealloc), 10); End; dayBiomLeaf := NewBLeaf - biomLeaf; biomLeaf := NewBLeaf; // Test reduction KAssim avec des rapports de biomasse feuilles MaxBiomLeaf := Max(MaxBiomLeaf, BiomLeaf) ; except AfficheMessageErreur('EvolBiomLeaf',UBiomasse); end; End; //////////////////////////////////////////////////////////////////////////////// /// ATTENTION faire une nouveau module pour tester la diff.... Procedure EvolBiomLeaf2(Const KpenteLaiDev, biomAero, KbaseLaiDev, dayRdt, dayBiomTot, Krealloc, RespMaint, AssimPot, Nophase : Double; Var biomLeaf, dayBiomLeaf, rdt, ManqueAssim, MaxBiomLeaf : Double); { Evolution du LAI en 2 étapes : Avant Floraison : Relation allométrique biomasse Aérienne-Foliaire, bornée aux extrèmes Pb Apparent : la biomasse foliaire chute pendant la phase RPR en cycle Long! pb de calage des la pente et du bornage ? Après floraison : concept de compétition (répartition assimilats), une scénescence peut apparaitre si l'apport en assimilat (dayBiomTot) est inf à la demande (dayRdt)pour la croissance des grains, on retranche alors cette différence à la biomasse aérienne. Remarque : avec les réserve (palmier a huile) on instituait une réallocation moindre que la différence des demandes On borne cette diminution à 10 kg/ha pour des problèmes de simulation (division/0) dans les calculs de transpiration } //Krealloc := 0.5; Var NewBLeaf, cM, bM : Double; NumPhase : Integer; Begin try //!!! Kchimique dans rdt...mil sorgho = 1 donc sans effet mais ? If NoPhase <= 4 then begin // PhRPR phase reproductive //!!! Test scenescence et dayBiomTot!!! // if daybiomTot < 0 then TRes[biomLeaf] := max (TRes[biomLeaf]+daybiomTot, 1) // else begin // equation de Misterlich : y = aM + bM * cM puiss x // Bornes des valeurs : Am -0.12..0.12, bM 0..1, x 0..50, cM // lissage de la relation linéaire au point de changement de pente // (bornage à 0.1 ou 0.2) // données d'entrées pente relation allometrique, seuil asymptotique (bornage) // base de la pente // relation lineaire pour faire le lien avec la pente de Misterlich // aM = seuil et bM = base - seuil) // cM = (penteAllom / bM + 0.78)/0.75 //Attention valeurs rapporte en T/Ha pour ne pas partir dans les choux bM := kBaseLaiDev - 0.1; cM := ((kPenteLaiDev*1000)/ bM + 0.78)/0.75; NewBLeaf := (0.1 + bM * power(cM,BiomAero/1000))* BiomAero; // NewBLeaf := max(0.1, kPenteLaiDev * BiomAero + kBaseLaiDev) * BiomAero; NewBLeaf := min(NewBLeaf,BiomAero); // end; end else Begin // phase de scenescence ie il ne peut y avoir que decroissance de biomleaf ManqueAssim := 0; if NoPhase = 5 then // Phase Matu1 begin //dans ManqueAssim on ne rajoute pas le manque en assimilat // (dayBiomTot < 0) pour l'evaluation du puit du rendement //? et pour les feuilles quelle est alors la part a retrancher, // faut il ajouter ce manque de daybiomtot? ManqueAssim := max(0,(dayRdt - max(0,dayBiomTot))); // en attendant diminution de l'augmentation de rdt // Krealloc : pourcentage d'assimilat realloue par les feuilles/?Tiges // modif du 11/01/05 cb // avant rdt:= rdt + max(0, dayRdt - ManqueAssim * KRealloc); // bornage de la croissance de rendement par la qte restante de feuilles rdt:= rdt + min((biomleaf-10)* KRealloc*0.5,max(0, dayRdt - ManqueAssim *(1- KRealloc))); // Fin modif du 11/01/05 cb end; // on ajoute au ManqueAssim ce qui est pris pour la respMaint, // ie dayBiomtot en val negative ManqueAssim := ManqueAssim - min(0,dayBiomTot); // else ManqueAssim := max(0,(RespMaint) - AssimPot); NewBLeaf := max (biomLeaf- (ManqueAssim * KRealloc)*0.5, 10); // NewBLeaf := max (biomLeaf- ManqueAssim, 10); // NewBLeaf := max (biomLeaf- (ManqueAssim * KRealloc), 10); End; dayBiomLeaf := NewBLeaf - biomLeaf; biomLeaf := NewBLeaf; // Test reduction KAssim avec des rapports de biomasse feuilles MaxBiomLeaf := Max(MaxBiomLeaf, BiomLeaf) ; except AfficheMessageErreur('EvolBiomLeaf2',UBiomasse); end; end; //////////////////////////////////////////////////////////////////////////////// Procedure EvolLAI(Const sla, biomLeaf : Double; Var lai : Double); { Evolution du LAI en fonction de la surface massique et de la biomasse foliaire } Begin try lai := sla * biomLeaf; except AfficheMessageErreur('EvolLAI',UBiomasse); end; End; procedure EvolKcp(const KcMax, Ltr : Double; var Kcp : Double); begin try kcp := KcMax * (1 - Ltr); except AfficheMessageErreur('EvolKcp',UBiomasse); end; end; Procedure EvolRdt(Const SeuilTempMatu1, rdtPot, tempMoy, KTempPhase, tr, trPot, Nophase : Double; Var dayRdt : Double); { } Begin try If (NoPhase = 5)Then // PhMatu1 dayRdt := RdtPot * ((tempMoy -kTempPhase)/SeuilTempMatu1) * tr/trPot else dayRdt := 0; except AfficheMessageErreur('EvolRdt',UBiomasse); end; End; Procedure EvalBiomIni (Const SlaBVP,KResGrain, kPenteAero, kBaseAero,densite, biomGrain,SeuilTempGermi : Double; Var biomTot, BiomAero, sla, numphase,VRac,SeuilTemp :Double); Begin try BiomTot := densite * kResGrain * BiomGrain/1000; BiomAero := Min(0.9, kPenteAero * biomTot + kBaseAero)* biomTot; sla := SlaBVP; numphase := 1; //Vrac := 0; SeuilTemp := SeuilTempGermi; except AfficheMessageErreur('EvalBiomIni',UBiomasse); end; End; Procedure SortiesResCrop (Const ThisDate, rdt : double; Var DateMaturite, RdtCrop : double); Begin try DateMaturite := ThisDate; RdtCrop := rdt; except AfficheMessageErreur('SortiesResCrop',UBiomasse); end; End; //////////////////////////////////////////////////////////////////////////////////// //Liste de toutes les procedures redef en dyn de l'unite ///////////////////////////////////////////////////////////////////////////////////// // Rajouter stdcall à la fin pour permettre l'utilisation de procédures dans des dll. Procedure EvalLtrDyn (Var T : TPointeurProcParam); Begin EvalLtr(T[0], T[1], T[2]); end; Procedure EvalRespMaintDyn (Var T : TPointeurProcParam); Begin EvalRespMaint(T[0], T[1], T[2],T[3], T[4],T[5],T[6]); end; Procedure SumTempDyn(Var T : TPointeurProcParam); Begin SumTemp(T[0], T[1], T[2]); end; Procedure EvolSDJOptDyn(Var T : TPointeurProcParam); Begin EvolSDJOpt(T[0], T[1], T[2], T[3]); end; Procedure EvalSumPhotoPerDyn (Var T : TPointeurProcParam); Begin EvalSumPhotoPer(T[0],T[1],T[2],T[3],T[4],T[5]); end; Procedure EvalRdtPotDyn (Var T : TPointeurProcParam); Begin EvalRdtPot(T[0],T[1],T[2],T[3]); end; Procedure FreinEpsiBTempDyn (Var T : TPointeurProcParam); Begin FreinEpsiBTemp(T[0],T[1],T[2],T[3],T[4]); end; Procedure AssimilatPotRapLeafDyn (Var T : TPointeurProcParam); Begin AssimilatPotRapLeaf(T[0],T[1],T[2],T[3],T[4],T[5],T[6]); end; Procedure AssimilatsDyn (Var T : TPointeurProcParam); Begin Assimilats(T[0],T[1],T[2],T[3],T[4]); end; Procedure EvolBiomasseDyn (Var T : TPointeurProcParam); Begin EvolBiomasse(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9]); end; Procedure EvolBiomTotDyn (Var T : TPointeurProcParam); Begin EvolBiomTot(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]); end; Procedure EvolLAIDyn (Var T : TPointeurProcParam); Begin EvolLAI(T[0],T[1],T[2]); end; Procedure EvolKcpDyn (Var T : TPointeurProcParam); Begin EvolKcp(T[0],T[1],T[2]); end; Procedure EvolPhenoTempDyn (Var T : TPointeurProcParam); Begin EvolPhenoTemp(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12],T[13],T[14],T[15],T[16],T[17],T[18],T[19], T[20],T[21],T[22],T[23],T[24]); end; Procedure EvolPhenoTempCDyn (Var T : TPointeurProcParam); Begin EvolPhenoTempC(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12],T[13],T[14],T[15],T[16],T[17],T[18],T[19], T[20],T[21],T[22],T[23],T[24],T[25]); end; Procedure AssimilatPotDyn (Var T : TPointeurProcParam); Begin AssimilatPot(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10]); end; Procedure AssimRUESwitchWUEDyn (Var T : TPointeurProcParam); Begin AssimRUESwitchWUE(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12],T[13]); end; Procedure AssimRUExWUEDyn (Var T : TPointeurProcParam); Begin AssimRUExWUE(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12]); end; Procedure AssimWUEDyn (Var T : TPointeurProcParam); Begin AssimWUE(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12]); end; Procedure EvolBiomLeafDyn (Var T : TPointeurProcParam); Begin EvolBiomLeaf(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12],T[13]); end; Procedure EvolBiomLeaf2Dyn (Var T : TPointeurProcParam); Begin EvolBiomLeaf2(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12],T[13]); end; Procedure EvalSlaRapBiomDyn (Var T : TPointeurProcParam); Begin EvalSlaRapBiom(T[0],T[1],T[2],T[3],T[4],T[5]); end; Procedure EvalSlaCerealesDyn (Var T : TPointeurProcParam); Begin EvalSlaCereales(T[0],T[1],T[2],T[3],T[4],T[5],T[6]); end; Procedure EvolRdtDyn (Var T : TPointeurProcParam); Begin EvolRdt(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]); end; Procedure EvalBiomIniDyn (Var T : TPointeurProcParam); Begin EvalBiomIni(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12]); end; Procedure InitCropDyn (Var T : TPointeurProcParam); begin InitCrop(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8]); end; initialization TabProc.AjoutProc('EvalLtr', EvalLtrDyn); TabProc.AjoutProc('EvalRespMaint', EvalRespMaintDyn); TabProc.AjoutProc('SumTemp', SumTempDyn); TabProc.AjoutProc('EvolSDJOpt', EvolSDJOptDyn); TabProc.AjoutProc('EvalSumPhotoPer', EvalSumPhotoPerDyn); TabProc.AjoutProc('EvalRdtPot', EvalRdtPotDyn); TabProc.AjoutProc('FreinEpsiBTemp', FreinEpsiBTempDyn); TabProc.AjoutProc('AssimilatPotRapLeaf', AssimilatPotRapLeafDyn); TabProc.AjoutProc('Assimilats', AssimilatsDyn); TabProc.AjoutProc('EvolBiomasse', EvolBiomasseDyn); TabProc.AjoutProc('EvolBiomTot', EvolBiomTotDyn); TabProc.AjoutProc('EvolBiomLeaf', EvolBiomLeafDyn); TabProc.AjoutProc('EvolBiomLeaf2', EvolBiomLeaf2Dyn); TabProc.AjoutProc('EvolLai', EvolLAIDyn); TabProc.AjoutProc('EvolKcp', EvolKcpDyn); TabProc.AjoutProc('InitCrop', InitCropDyn); TabProc.AjoutProc('EvolPhenoTemp', EvolPhenoTempDyn); TabProc.AjoutProc('EvolPhenoTempC', EvolPhenoTempCDyn); TabProc.AjoutProc('AssimilatPot', AssimilatPotDyn); TabProc.AjoutProc('AssimRUESwitchWUE', AssimRUESwitchWUEDyn); TabProc.AjoutProc('AssimRUExWUE', AssimRUExWUEDyn); TabProc.AjoutProc('AssimWUE', AssimWUEDyn); TabProc.AjoutProc('EvalSlaRapBiom', EvalSlaRapBiomDyn); TabProc.AjoutProc('EvalSlaCereales', EvalSlaCerealesDyn); TabProc.AjoutProc('EvolRdt', EvolRdtDyn); TabProc.AjoutProc('EvalBiomIni', EvalBiomIniDyn) end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmBtnCombo Purpose : An edit control with a Elipsis button and combo button combination. Date : 01-26-01 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmBtnCombo; interface {$I CompilerDefines.inc} uses Windows, Classes, StdCtrls, Controls, Messages, SysUtils, Forms, Graphics, Buttons, rmBtnEdit, rmSpeedBtns, rmScrnCtrls{$IFDEF rmDebug}, rmMsgList{$ENDIF}; type { TrmCustomBtnCombo } TrmCustomBtnCombo = class(TrmCustomBtnEdit) private FScreenListBox: TrmCustomScreenListBox; fDropDownWidth: integer; FDropDownHeight: integer; FEditorEnabled: Boolean; FOnDropDown: TNotifyEvent; FOnChanged: TNotifyEvent; {$IFDEF rmDebug} fMsg: TrmMsgEvent; {$ENDIF} FOnBtnClick: TNotifyEvent; fOnCloseUp: TNotifyEvent; procedure DoLBKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DoLBMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DoLBExit(Sender: Tobject); procedure ToggleListBox(Sender: TObject); procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER; procedure WMPaste(var Message: TWMPaste); message WM_PASTE; procedure WMCut(var Message: TWMCut); message WM_CUT; procedure WMContextMenu(var Message: TWMContextMenu); message WM_CONTEXTMENU; procedure CMFontchanged(var Message: TMessage); message CM_FontChanged; procedure CMCancelMode(var Message: TCMCancelMode); message CM_CancelMode; procedure wmKillFocus(var Message: TMessage); message wm_killfocus; {$IFDEF D4_OR_HIGHER} procedure SetEnabled(value: Boolean); reintroduce; (* reintroduce is D4 Modification *) function GetEnabled: Boolean; reintroduce; (* reintroduce is D4 Modification *) {$ELSE} procedure SetEnabled(value: Boolean); {$ENDIF} procedure SetComboItems(const Value: TStrings); function GetComboItems: TStrings; function GetEllipsisBtnVisible: boolean; procedure SetEllipsisBtnVisible(const Value: boolean); function GetItemIndex: integer; procedure SetItemIndex(const Value: integer); procedure SetEditorEnabled(const Value: Boolean); function GetDroppedDown: boolean; protected procedure DownClick(Sender: TObject); procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure keyPress(var key: char); override; property DropDownHeight: integer read FDropDownHeight write fDropDownHeight default 0; property DropDownWidth: integer read fDropDownWidth write fDropDownWidth default 0; property EditorEnabled: Boolean read FEditorEnabled write SetEditorEnabled default True; property Enabled: Boolean read GetEnabled write SetEnabled default True; property Items: TStrings read GetComboItems write SetComboItems; property ItemIndex: integer read GetItemIndex write SetItemIndex; property OnChanged: TNotifyEvent read fOnChanged write fOnChanged; property OnDropDown: TNotifyEvent read FOnDropDown write fOnDropDown; property OnBtnClick: TNotifyEvent read FOnBtnClick write FOnBtnClick; property OnCloseUp: TNotifyEvent read fOnCloseUp write fOnCloseUp; property EllipsisBtnVisible: boolean read GetEllipsisBtnVisible write SetEllipsisBtnVisible; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure WndProc(var Message: TMessage); override; {$IFDEF rmDebug} property OnMessage: TrmMsgEvent read fMsg write fMsg; {$ENDIF} procedure CloseUp; virtual; property DroppedDown : boolean read GetDroppedDown; end; TrmBtnCombo = class(TrmCustomBtnCombo) published property EditorEnabled; property Enabled; property DropDownHeight; property DropDownWidth; property Items; property ItemIndex; property Text; property EllipsisBtnVisible; {$IFDEF D4_OR_HIGHER} property Anchors; property Constraints; {$ENDIF} property Font; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnBtnClick; property OnDropDown; property OnChange; property OnClick; property OnCloseUp; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; implementation uses rmLibrary; {$R rmBtnCombo.RES} { TrmCustomBtnCombo } constructor TrmCustomBtnCombo.Create(AOwner: TComponent); begin inherited Create(AOwner); with GetButton(1) do begin Font.name := 'Marlett'; font.size := 10; Font.color := clBtnText; Caption := '6'; Glyph := nil; end; OnBtn1Click := ToggleListBox; Btn2Visible := true; OnBtn2Click := DownClick; FScreenListBox := TrmCustomScreenListBox.create(nil); with FScreenListBox do begin width := self.width; height := self.height * 8; visible := false; Parent := self; OnKeyDown := DoLBKeyDown; OnMousedown := DoLBMouseDown; end; FScreenListBox.hide; OnExit := doLBExit; Text := ''; ControlStyle := ControlStyle - [csSetCaption]; FEditorEnabled := True; end; destructor TrmCustomBtnCombo.Destroy; begin FScreenListBox.free; inherited Destroy; end; procedure TrmCustomBtnCombo.KeyDown(var Key: Word; Shift: TShiftState); var wIndex: integer; begin if not FEditorEnabled then begin if (key in [vk_delete]) then key := 0; end; if (((Key = VK_DOWN) or (key = VK_UP)) and (shift = [ssALT])) or ((key = vk_f4) and (shift = [])) then begin if not FScreenListbox.visible then ToggleListBox(self) else begin FScreenListbox.hide; CloseUp; end; end else if (key in [vk_Down, VK_up, vk_left, vk_right, vk_home, vk_end, vk_prior, vk_next]) and (shift = []) then begin if not FScreenListbox.visible then begin try wIndex := fScreenListBox.items.Indexof(Text); case key of vk_down, vk_right: inc(wIndex); vk_up, vk_left: dec(wIndex); vk_home: wIndex := 0; vk_end: wIndex := FScreenListBox.Items.Count - 1; vk_next: inc(wIndex, (DropDownHeight div FScreenListBox.ItemHeight) - 1); vk_prior: dec(wIndex, (DropDownHeight div FScreenListBox.ItemHeight) - 1); end; if wIndex < 0 then wIndex := 0 else if wIndex >= FScreenListBox.Items.Count then wIndex := FScreenListBox.Items.Count - 1; FScreenListBox.ItemIndex := wIndex; Text := FScreenListBox.Items[wIndex]; except //do nothing end; setfocus; selectall; key := 0; end else begin setfocus; selectall; key := 0; end; end else if ((key = VK_RETURN) and (shift = [ssCTRL]) and not FScreenListbox.visible) then begin DownClick(self); key := 0 end else inherited KeyDown(Key, Shift); end; procedure TrmCustomBtnCombo.WMPaste(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TrmCustomBtnCombo.WMCut(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TrmCustomBtnCombo.CMEnter(var Message: TCMGotFocus); begin if AutoSelect and not (csLButtonDown in ControlState) then SelectAll; inherited; end; procedure TrmCustomBtnCombo.SetEnabled(value: Boolean); begin inherited enabled := value; Btn1Enabled := Value; Btn2Enabled := value; end; function TrmCustomBtnCombo.GetEnabled: Boolean; begin result := inherited Enabled; end; procedure TrmCustomBtnCombo.DownClick(Sender: TObject); begin if assigned(fonbtnClick) then fonbtnClick(self); end; procedure TrmCustomBtnCombo.SetComboItems(const Value: TStrings); begin FScreenListBox.Items.assign(Value); end; procedure TrmCustomBtnCombo.ToggleListBox(Sender: TObject); var CP, SP: TPoint; begin CP.X := Left; CP.Y := Top + Height; SP := parent.ClientToScreen(CP); if assigned(fonDropdown) then fOnDropDown(self); SetFocus; SelectAll; FScreenListBox.Font := Font; if fDropDownWidth = 0 then FScreenListBox.Width := self.width else FScreenListBox.width := fDropDownWidth; if fDropDownHeight = 0 then FScreenListBox.Height := self.Height * 8 else FScreenListBox.Height := fDropDownHeight; try fScreenListBox.itemindex := fScreenListBox.Items.indexof(text); except fScreenListBox.itemindex := -1; end; FScreenListBox.Left := SP.X; if assigned(screen.ActiveForm) then begin if (SP.Y + FScreenListBox.height < screen.activeForm.Monitor.Height) then FScreenListBox.Top := SP.Y else FScreenListBox.Top := (SP.Y - self.height) - FScreenListBox.height; end else begin if (SP.Y + FScreenListBox.height < screen.Height) then FScreenListBox.Top := SP.Y else FScreenListBox.Top := (SP.Y - self.height) - FScreenListBox.height; end; FScreenListBox.Show; SetWindowPos(FScreenListBox.handle, hwnd_topMost, 0, 0, 0, 0, swp_nosize or swp_NoMove); end; procedure TrmCustomBtnCombo.DoLBMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FScreenListBox.hide; if FScreenListBox.ItemIndex <> -1 then Text := FScreenListBox.items[fscreenlistbox.itemindex]; closeup; self.setfocus; self.SelectAll; if (FScreenListBox.ItemIndex <> -1) and assigned(fonchanged) then fOnchanged(self); end; procedure TrmCustomBtnCombo.DoLBExit(Sender: Tobject); begin if FScreenListBox.visible then begin FScreenListBox.visible := false; CloseUp; end; end; procedure TrmCustomBtnCombo.DoLBKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key = vk_escape) then begin FScreenListBox.hide; CloseUp; self.setfocus; self.SelectAll; key := 0; end else if (key = vk_Return) then begin FScreenListBox.hide; if FScreenListBox.ItemIndex <> -1 then Text := FScreenListBox.items[fscreenlistbox.itemindex]; CloseUp; self.setfocus; self.SelectAll; key := 0; if assigned(fonchanged) then fOnchanged(self); end end; procedure TrmCustomBtnCombo.WndProc(var Message: TMessage); begin {$IFDEF rmDebug} if assigned(OnMessage) then try OnMessage(Message); except end; {$ENDIF} case Message.Msg of WM_CHAR, WM_KEYDOWN, WM_KEYUP: if (FScreenListBox.visible) then begin if GetCaptureControl = nil then begin Message.result := SendMessage(FScreenListBox.Handle, message.msg, message.wParam, message.LParam); if message.result = 0 then exit; end; end; end; inherited WndProc(message); end; procedure TrmCustomBtnCombo.CMCancelMode(var Message: TCMCancelMode); begin inherited; if Message.Sender = FScreenListBox then exit; if FScreenListBox.visible then begin FScreenListBox.Hide; CloseUp; end; end; function TrmCustomBtnCombo.GetComboItems: TStrings; begin Result := fscreenlistbox.Items; end; procedure TrmCustomBtnCombo.keyPress(var key: char); begin if not FEditorEnabled then key := #0 else if key = #13 then key := #0; inherited; end; procedure TrmCustomBtnCombo.wmKillFocus(var Message: TMessage); begin inherited; if FScreenListBox.visible then begin FScreenListBox.Hide; CloseUp; end; end; procedure TrmCustomBtnCombo.CMFontchanged(var Message: TMessage); begin inherited; FScreenListBox.Font.Assign(self.font); end; function TrmCustomBtnCombo.GetEllipsisBtnVisible: boolean; begin Result := Btn2Visible; end; procedure TrmCustomBtnCombo.SetEllipsisBtnVisible(const Value: boolean); begin Btn2Visible := value; end; procedure TrmCustomBtnCombo.CloseUp; begin try if assigned(fOnCloseUp) then fOnCloseUp(self); except //Do Nothing... end; end; function TrmCustomBtnCombo.GetItemIndex: integer; begin result := items.IndexOf(Text); end; procedure TrmCustomBtnCombo.SetItemIndex(const Value: integer); begin if value = -1 then text := '' else text := items[value]; end; procedure TrmCustomBtnCombo.SetEditorEnabled(const Value: Boolean); var styles : TControlStyle; begin FEditorEnabled := Value; styles := ControlStyle; if FEditorEnabled then include(Styles, csMenuEvents) else exclude(Styles, csMenuEvents); ControlStyle := Styles; end; procedure TrmCustomBtnCombo.WMContextMenu(var Message: TWMContextMenu); begin if not EditorEnabled and not assigned(popupmenu) then message.result := 1; inherited; end; function TrmCustomBtnCombo.GetDroppedDown: boolean; begin result := FScreenListBox.Visible; end; end.
unit Sp_f1dfFirm_Control; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxCheckBox, cxTextEdit, cxMaskEdit, cxContainer, cxEdit, cxLabel, ExtCtrls, cxControls, cxGroupBox, Unit_Sp_VidOpl_Consts, cxButtonEdit, cxDropDownEdit, cxCalendar, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, PackageLoad, ZTypes, IBase, ActnList, Unit_ZGlobal_Consts, ZProc; type TZF1dfFirmControl = class(TForm) DirectorBox: TcxGroupBox; YesBtn: TcxButton; CancelBtn: TcxButton; DSourceFund: TDataSource; DSourceNachisl: TDataSource; DataBase: TpFIBDatabase; DSetNachisl: TpFIBDataSet; DSetFund: TpFIBDataSet; DefaultTransaction: TpFIBTransaction; ActionList1: TActionList; Action1: TAction; GlavBuhgBox: TcxGroupBox; NameBox: TcxGroupBox; PeriodBox: TcxGroupBox; LabelDirectorTin: TcxLabel; ButtonEditDirectorTin: TcxButtonEdit; LabelDirector: TcxLabel; EditDirector: TcxLabel; LabelDirectorTel: TcxLabel; MaskEditDirectorTel: TcxMaskEdit; ButtonEditGlBuhgTin: TcxButtonEdit; LabelGlBuhgTin: TcxLabel; LabelGlBuhgTel: TcxLabel; MaskEditGlBuhgTel: TcxMaskEdit; LabelglBuhg: TcxLabel; EditGlBuhg: TcxLabel; MaskEditDPI: TcxMaskEdit; LabelDPI: TcxLabel; LabelKodDPI: TcxLabel; MaskEditKodDPI: TcxMaskEdit; LabelFileDa: TcxLabel; MaskEditFileDa: TcxMaskEdit; LabelOkpo: TcxLabel; MaskEditOkpo: TcxMaskEdit; LabelShortName: TcxLabel; MaskEditShortName: TcxMaskEdit; LabelFullName: TcxLabel; MaskEditFullName: TcxMaskEdit; procedure CancelBtnClick(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure ButtonEditDirectorTinPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure ButtonEditGlBuhgTinPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); private PLanguageIndex:byte; public constructor Create(AOwner: TComponent;ComeDB:TISC_DB_HANDLE);reintroduce; end; implementation {$R *.dfm} const Grant_Caption :array[1..2] of string = ('Стипендія','Стипендия'); LabelKodSetup_Caption :array[1..2] of string = ('Період стипендії','Период стипендии'); LabelDefaultSmeta_Caption :array[1..2] of string = ('Кошторис за умовчанням','Смета по умолчанию'); LabelBudgetGrant_Caption :array[1..2] of string = ('Властивість бюджетної стипендії','Свойство бюджетной стипендии'); LabelPropFaculty_Caption :array[1..2] of string = ('Факультети для стипендії','Факультеты для стипендии'); VidOpl_Caption :array[1..2] of string = ('Види операцій','Виды операций'); Other_Caption :array[1..2] of string = ('Інше','Другое'); LabelCurrentKod_Caption :array[1..2] of string = ('Поточний період','Текущий период'); LabelDateBeg_Caption :array[1..2] of string = ('Старт системи','Старт системы'); LabelNachOk_Caption :array[1..2] of string = ('Начальник відділа кадрів','Начальник отдела кадров'); LabelDPI_Caption :array[1..2] of string = ('ДПІ','ДПИ'); LabelKodDPI_Caption :array[1..2] of string = ('Код ДПІ','Код ДПИ'); LabelForwHol_Caption :array[1..2] of string = ('Кіл-ть днів відпустки','Количество дней отпуска'); LabelOrderLevel_Caption :array[1..2] of string = ('Рівень','Уровень'); System_Caption :array[1..2] of string = ('Система','Система'); LabelZSystem_Caption :array[1..2] of string = ('ІД системи','ИД система'); LabelGrSystem_Caption :array[1..2] of string = ('ІД стипендії','ИД стипендии'); LabelRmoving_Caption :array[1..2] of string = ('Виняткові періоди','Исключительные периоды'); LabelIsFss_Caption :array[1..2] of string = ('Утримувати податок соц. захисту','Удеривать налог социальной защиты'); Labelvirtual_Caption :array[1..2] of string = ('Віртуальний табель','Виртуальный табель'); constructor TZF1dfFirmControl.Create(AOwner: TComponent;ComeDB:TISC_DB_HANDLE); begin inherited Create(Aowner); PLanguageIndex := LanguageIndex; self.NameBox.Caption :=LabelFirm_Caption[PLanguageIndex]; self.DirectorBox.Caption := LabelDirector_Caption[PLanguageIndex]; self.GlavBuhgBox.Caption := LabelGlavBuhg_Caption[PLanguageIndex]; self.LabelShortName.Caption:= LabelNameShort_Caption[PLanguageIndex]; self.LabelFullName.Caption := LabelNameFull_Caption[PLanguageIndex]; self.LabelOkpo.Caption := LabelOkpo_Caption[PLanguageIndex]; LabelDirector.Caption := LabelFIO_Caption[PLanguageIndex]; LabelDirectorTin.Caption := LabelTin_Caption[PLanguageIndex]; LabelDirectorTel.Caption := LabelTel_Caption[PLanguageIndex]; LabelglBuhg.Caption := LabelFIO_Caption[PLanguageIndex]; LabelGlBuhgTin.Caption := LabelTin_Caption[PLanguageIndex]; LabelGlBuhgTel.Caption := LabelTel_Caption[PLanguageIndex]; LabelDPI.Caption := LabelDPI_Caption[PLanguageIndex]; LabelKodDPI.Caption := LabelKodDPI_Caption[PLanguageIndex]; LabelFileDa.Caption := 'Файл'; self.YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; self.CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; //****************************************************************************** DataBase.Handle := ComeDB; DefaultTransaction.StartTransaction; end; procedure TZF1dfFirmControl.CancelBtnClick(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TZF1dfFirmControl.Action1Execute(Sender: TObject); begin if MaskEditShortName.Text<>'' then if MaskEditFullName.Text<>'' then if ButtonEditDirectorTin.Text<>'' then if MaskEditDirectorTel.Text<>'' then if ButtonEditGlBuhgTin.Text<>'' then if MaskEditGlBuhgTel.Text<>'' then if MaskEditDPI.Text<>'' then if MaskEditKodDPI.Text<>'' then if MaskEditOkpo.Text<>'' then if MaskEditFileDa.Text<>'' then begin ModalResult:=mrYes; end else MaskEditFileDa.SetFocus else MaskEditOkpo.SetFocus else MaskEditKodDPI.SetFocus else MaskEditDPI.SetFocus else MaskEditGlBuhgTel.SetFocus else ButtonEditGlBuhgTin.SetFocus else MaskEditDirectorTel.SetFocus else ButtonEditDirectorTin.SetFocus else MaskEditFullName.SetFocus else MaskEditShortName.SetFocus; end; procedure TZF1dfFirmControl.ButtonEditDirectorTinPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var ResultView:Variant; begin ResultView:=LoadPeopleModal(Self,Database.Handle); if VarArrayDimCount(ResultView)> 0 then begin EditDirector.Caption := VarToStr(ResultView[1])+' '+ VarToStr(ResultView[2])+' '+ VarToStr(ResultView[3]); ButtonEditDirectorTin.Text := VarToStr(ResultView[5]); end; end; procedure TZF1dfFirmControl.ButtonEditGlBuhgTinPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var ResultView:Variant; begin ResultView:=LoadPeopleModal(Self,Database.Handle); if VarArrayDimCount(ResultView)> 0 then begin EditGlBuhg.Caption := VarToStr(ResultView[1])+' '+ VarToStr(ResultView[2])+' '+ VarToStr(ResultView[3]); ButtonEditGlBuhgTin.Text := VarToStr(ResultView[5]); end; end; end.
{ Lua4Lazarus ActiveXObject License: New BSD Copyright(c)2010- Malcome@Japan All rights reserved. Note: } unit l4l_activex; {$mode objfpc}{$H+} interface uses Classes, SysUtils, lua54; function CreateActiveXObject(L : Plua_State) : Integer; cdecl; function CreateRefType(L : Plua_State) : Integer; cdecl; implementation uses Windows, ComObj, ActiveX, variants, varutils, l4l_object; const FIELD_ID = '___IDispatch___'; FIELD_FN = '___FuncName___'; FIELD_ID_PARENT = '___IDispatchParent___'; FIELD_ID_CLIENT = '___IDispatchClient___'; type { TInterfacedBase } TInterfacedBase = class(TObject, IUnknown) function QueryInterface(constref iid : tguid; out obj) : longint; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; end; { TEventSink } TEventSink = class(TInterfacedBase, IDispatch) private L: PLua_State; FCookie: DWORD; FCPoint: IConnectionPoint; FInfo: ITypeInfo; EventList: TStringList; public constructor Create(aL: PLua_State); destructor Destroy; override; procedure AttachEvent(server: IDispatch); procedure DetachEvent; function IsEventSupport: boolean; { IDispatch } function GetTypeInfoCount(out Count: Integer): HRESULT; stdcall; function GetTypeInfo({%H-}Index, {%H-}LocaleID: Integer; out {%H-}TypeInfo): HRESULT; stdcall; function GetIDsOfNames(const {%H-}IID: TGUID; {%H-}Names: Pointer; {%H-}NameCount, {%H-}LocaleID: Integer; {%H-}DispIDs: Pointer): HRESULT; stdcall; function Invoke(DispID: Integer; const {%H-}IID: TGUID; {%H-}LocaleID: Integer; {%H-}Flags: Word; var {%H-}Params; {%H-}VarResult, {%H-}ExcepInfo, {%H-}ArgErr: Pointer): HRESULT; stdcall; end; function call(L : Plua_State) : Integer; cdecl; forward; function gc_ID(L : Plua_State) : Integer; cdecl; forward; procedure DoCreateActiveXObject(L : Plua_State; id: IDispatch); forward; procedure ChkErr(L : Plua_State; Val: HResult; const prop: string=''); var s: string; begin if not(Succeeded(Val)) then begin case val of DISP_E_MEMBERNOTFOUND: s:= 'Member Not Found'; DISP_E_TYPEMISMATCH: s:= 'Type Mismatch'; DISP_E_UNKNOWNNAME: s:= 'Unknown Name'; DISP_E_BADPARAMCOUNT: s:= 'Bad Param Count'; E_INVALIDARG: s:= 'Invaid Arg' else s:= 'ActiveX Error'; end; s:= s + Format('(%x)', [Val]); if prop <> '' then s := s + ' in "' + prop + '".'; luaL_error(L, PChar(s)); end; end; procedure Lua2Var(L : Plua_State; va: POleVariant; index: integer; toWideStr: boolean = True); var i, j: integer; p: POleVariant; obj: TLuaObject; hp: TVarArrayBoundArray; begin VariantInit(TVarData(va^)); case lua_type(L, index) of LUA_TNIL: va^:= VarAsType(va^, varNull); LUA_TBOOLEAN: va^:= lua_toboolean(L, index); LUA_TNUMBER: begin if lua_isinteger(L, index) then va^:= lua_tointeger(L, index) else va^:= lua_tonumber(L, index); end; LUA_TSTRING: begin if toWideStr then va^:= UTF8Decode(lua_tostring(L, index)) else va^:= lua_tostring(L, index); end; LUA_TTABLE: begin lua_getmetatable(L, index); lua_getfield(L, -1, FIELD_ID); if lua_isnil(L, -1) then begin obj:= l4l_toobject(L, index); if not Assigned(obj) then begin j:= lua_rawlen(L, index); if j > 0 then begin //va^:= VarArrayCreate([0, j-1], varVariant); hp[0].LowBound:= 0; hp[0].ElementCount:= j; TVarData(va^).vType:= varVariant or varArray; TVarData(va^).vArray:= SafeArrayCreate(varVariant, 1, hp); SafeArrayAccessData(TVarData(va^).vArray, p{%H-}); for i:= 1 to j do begin lua_rawgeti(L, index, i); Lua2Var(L, p, lua_gettop(L)); lua_pop(L, 1); Inc(p); end; SafeArrayUnaccessData(TVarData(va^).vArray); end else begin TVarData(va^).vType:= varVariant or varArray; TVarData(va^).vArray:= nil; end; end else begin // TLuaObject //if obj is TLuaInteger then begin // va^:= TLuaInteger(obj).Value; //end else begin va^:= VarAsType(va^, varNull); //end; end; end else begin p:= lua_touserdata(L, -1); TVarData(va^).vtype:= varVariant or varByRef; TVarData(va^).vpointer:= p; end; lua_pop(L, 2); end; end{case}; end; function Index(L : Plua_State) : Integer; cdecl; var p: POleVariant; key: string; s: string; ws: WideString; id: IDispatch; di: TDispID; param: TDispParams; ret: OleVariant; hr: HResult; begin Result:= 0; key := LowerCase(lua_tostring(L, 2)); lua_pushstring(L, key); lua_rawget(L, 1); if not lua_isnil(L, -1) then begin // for method name is case insesitive Result:= 1; Exit; end; lua_pop(L, 1); lua_getmetatable(L, 1); lua_getfield(L, -1, FIELD_ID); p:= lua_touserdata(L, -1); lua_pop(L, 2); if TVarData(p^).vtype <> varDispatch then begin //key:= LowerCase(key); if key = 'value' then begin case VarType(p^) of varNull: lua_pushnil(L); varSmallint,varInteger,varshortint,varByte, varword,varlongword,varint64,varqword: lua_pushinteger(L, p^); varSingle,varDouble,vardecimal: lua_pushnumber(L, p^); varBoolean: lua_pushboolean(L, p^); // TODO: varArray else begin ws := p^; s := UTF8Encode(ws); lua_pushstring(L, s); end; end; end else Exit; end else begin id:= IDispatch(TVarData(p^).vDispatch); ws:= UTF8Decode(key); ChkErr(L, id.GetIDsOfNames(GUID_NULL, @ws, 1, GetUserDefaultLCID, @di), key); param.rgvarg := nil; param.rgdispidNamedArgs := nil; param.cArgs := 0; param.cNamedArgs := 0; VariantInit(TVarData({%H-}ret)); hr:= id.Invoke(di, GUID_NULL, GetUserDefaultLCID, DISPATCH_PROPERTYGET, param, @ret, nil, nil); if hr = 0 then begin // Return property value case VarType(ret) of varNull: lua_pushnil(L); varSmallint,varInteger,varshortint,varByte, varword,varlongword,varint64,varqword: lua_pushinteger(L, ret); varSingle,varDouble,vardecimal: lua_pushnumber(L, ret); varBoolean: lua_pushboolean(L, ret); varDispatch: DoCreateActiveXObject(L, ret); else begin ws := ret; s := UTF8Encode(ws); lua_pushstring(L, s); end; end; end else begin // Return Table for function(method) call lua_newtable(L); end; // Change Metatable for function call if lua_getmetatable(L, -1) = 0 then lua_newtable(L); lua_pushstring(L, FIELD_FN); lua_pushstring(L, key); lua_rawset(L, -3); lua_pushstring(L, FIELD_ID_PARENT); p:= lua_newuserdata(L, SizeOf(OleVariant)); VariantInit(TVarData(p^)); p^:= id; if lua_getmetatable(L, -1) = 0 then lua_newtable(L); lua_pushstring(L, '__gc'); lua_pushcfunction(L, @gc_ID); lua_settable(L, -3); lua_setmetatable(L, -2); lua_rawset(L, -3); lua_pushstring(L, '__call'); lua_pushcfunction(L, @call); lua_rawset(L, -3); lua_setmetatable(L, -2); if hr = DISP_E_MEMBERNOTFOUND then begin // Key is method, not property lua_pushstring(L, key); // key is Lower Case lua_pushvalue(L, -2); lua_rawset(L, 1); end; end; Result := 1; end; function NewIndex(L : Plua_State) : Integer; cdecl; var p: POleVariant; key: string; ws: WideString; id: IDispatch; di, diput: TDispID; param: TDispParams; v: OleVariant; i: integer; sink: ^TEventSink; begin Result:=0; lua_getmetatable(L, 1); lua_getfield(L, -1, FIELD_ID); p:= lua_touserdata(L, -1); lua_pop(L, 2); key := lua_tostring(L, 2); if TVarData(p^).vtype <> varDispatch then begin key:= LowerCase(key); if key = 'value' then begin Lua2Var(L, p, 3, False); end else Exit; end else begin id:= IDispatch(TVarData(p^).vDispatch); ws:= UTF8Decode(key); if lua_isfunction(L, 3) or lua_isnil(L, 3) then begin // Set event lua_getmetatable(L, 1); lua_getfield(L, -1, FIELD_ID_CLIENT); sink:= lua_touserdata(L, -1); lua_pop(L, 2); key:= LowerCase(key); if lua_isfunction(L, 3) then begin i:= sink^.EventList.IndexOf(key); if i >= 0 then begin // Release old function from REGISTRY luaL_unref(L, LUA_REGISTRYINDEX, Integer(sink^.EventList.Objects[i])); // Save new function to REGISTRY lua_pushvalue(L, 3); sink^.EventList.Objects[i]:= TObject(luaL_Ref(L, LUA_REGISTRYINDEX)); end else begin if sink^.EventList.Count = 0 then sink^.AttachEvent(id); // Start event receive // Save new function to REGISTRY lua_pushvalue(L, 3); sink^.EventList.AddObject(key, TObject(luaL_Ref(L, LUA_REGISTRYINDEX))); end; end else begin // delete event i:= sink^.EventList.IndexOf(key); if i >= 0 then begin sink^.EventList.Delete(i); if sink^.EventList.Count = 0 then sink^.DetachEvent; end; end; end else begin // Set value ChkErr(L, id.GetIDsOfNames(GUID_NULL, @ws, 1, GetUserDefaultLCID, @di), key); Lua2Var(L, @v, 3); diput := DISPID_PROPERTYPUT; param.rgvarg := @v; param.cArgs := 1; param.rgdispidNamedArgs := @diput; param.cNamedArgs := 1; ChkErr(L, id.Invoke(di, GUID_NULL, GetUserDefaultLCID, DISPATCH_PROPERTYPUT, param, nil, nil, nil), key); end; end; end; function call(L : Plua_State) : Integer; cdecl; var i, c, t: integer; p: POleVariant; id: IDispatch; di: TDispID; s, func: string; ws: WideString; arglist, pp: {$IFDEF VER2_4}lPVariantArg{$ELSE}PVariantArg{$ENDIF}; param: TDispParams; ret: OleVariant; begin Result:= 0; c:= lua_gettop(L); t:= 1; // ToDo: const? lua_getmetatable(L, 1); lua_getfield(L, -1, FIELD_ID_PARENT); p:= lua_touserdata(L, -1); lua_pop(L, 2); if TVarData(p^).vtype <> varDispatch then Exit; id:= IDispatch(TVarData(p^).vDispatch); lua_getmetatable(L, 1); lua_getfield(L, -1, FIELD_FN); func:= lua_tostring(L, -1); lua_pop(L, 2); ws:= UTF8Decode(func); ChkErr(L, id.GetIDsOfNames(GUID_NULL, @ws, 1, GetUserDefaultLCID, @di), func); GetMem(arglist, SizeOf({$IFDEF VER2_4}VariantArg{$ELSE}TVariantArg{$ENDIF}) * (c-t)); try // 逆順で pp := arglist; for i := c downto t+1 do begin Lua2Var(L, POleVariant(pp), i); Inc(pp); end; param.cArgs := c - t; {$IFDEF VER2_4} param.rgvarg := arglist; {$ELSE} param.rgvarg := PVariantArgList(arglist); {$ENDIF} param.rgdispidNamedArgs := nil; param.cNamedArgs := 0; VariantInit(TVarData({%H-}ret)); ChkErr(L, id.Invoke( di, GUID_NULL, GetUserDefaultLCID, DISPATCH_PROPERTYGET or DISPATCH_METHOD, param, @ret, nil, nil), func); finally FreeMem(arglist); end; case VarType(ret) of varNull: lua_pushnil(L); varSmallint,varInteger,varshortint,varByte, varword,varlongword,varint64,varqword: lua_pushinteger(L, ret); varSingle,varDouble,vardecimal: lua_pushnumber(L, ret); varBoolean: lua_pushboolean(L, ret); varDispatch: DoCreateActiveXObject(L, ret); else{case} begin ws := ret; s := UTF8Encode(ws); lua_pushstring(L, s); end; end; Result := 1; end; function equal(L : Plua_State) : Integer; cdecl; var p1, p2: POleVariant; ti1, ti2: ITypeInfo; ta1, ta2: lPTypeAttr; begin Result:= 1; lua_pushboolean(L, False); if lua_type(L, 2) <> LUA_TTABLE then Exit; lua_getmetatable(L, 2); lua_getfield(L, -1, FIELD_ID); if lua_isnil(L, -1) then begin lua_pop(L, 2); Exit; end; p1:= lua_touserdata(L, -1); lua_pop(L, 2); if TVarData(p1^).vtype <> varDispatch then Exit; if IDispatch(TVarData(p1^).vdispatch).GetTypeInfo(0, 0, ti1) <> S_OK then Exit; if ti1.GetTypeAttr(ta1) <> S_OK then Exit; try lua_getmetatable(L, 1); lua_getfield(L, -1, FIELD_ID); if lua_isnil(L, -1) then begin lua_pop(L, 2); Exit; end; p2:= lua_touserdata(L, -1); lua_pop(L, 2); if TVarData(p2^).vtype <> varDispatch then Exit; if IDispatch(TVarData(p2^).vdispatch).GetTypeInfo(0, 0, ti2) <> S_OK then Exit; if ti2.GetTypeAttr(ta2) <> S_OK then Exit; try if IsEqualIID(ta1^.GUID, ta2^.GUID) then begin lua_pop(L, 1); lua_pushboolean(L, True); end; finally ti2.ReleaseTypeAttr(ta2); end; finally ti1.ReleaseTypeAttr(ta1); end; end; function iterator(L : Plua_State) : Integer; cdecl; var i: integer; p: POleVariant; id: IDispatch; s: string; ws: WideString; param: TDispParams; v, ret: OleVariant; begin Result:= 0; lua_getmetatable(L, 1); lua_getfield(L, -1, FIELD_ID); p:= lua_touserdata(L, -1); lua_pop(L, 2); if TVarData(p^).vtype <> varDispatch then Exit; id:= IDispatch(TVarData(p^).vDispatch); i:= lua_tointeger(L, lua_upvalueindex(1)); {%H-}lua_pushinteger(L, i+1); lua_replace(L, lua_upvalueindex(1)); VariantInit(TVarData({%H-}v)); v := i; param.cArgs := 1; param.rgvarg := @v; param.rgdispidNamedArgs := nil; param.cNamedArgs := 0; VariantInit(TVarData({%H-}ret)); if id.Invoke( DISPID_VALUE, GUID_NULL, GetUserDefaultLCID, DISPATCH_PROPERTYGET or DISPATCH_METHOD, param, @ret, nil, nil) = 0 then begin case VarType(ret) of varNull: lua_pushnil(L); varSmallint,varInteger,varshortint,varByte, varword,varlongword,varint64,varqword: lua_pushinteger(L, ret); varSingle,varDouble,vardecimal: lua_pushnumber(L, ret); varBoolean: lua_pushboolean(L, ret); varDispatch: begin if TVarData(ret).vdispatch <> nil then begin DoCreateActiveXObject(L, ret); end else begin lua_pushnil(L); end; end; else begin ws := ret; s := UTF8Encode(ws); lua_pushstring(L, s); end; end; end else begin lua_pushnil(L); end; Result := 1; end; function pairs(L : Plua_State) : Integer; cdecl; begin lua_pushinteger(L, 0); // upvalue for loop counter lua_pushcclosure(L, @iterator, 1); // f lua_pushvalue(L, 1); // t lua_pushnil(L); // s Result:= 3; end; function gc({%H-}L : Plua_State) : Integer; cdecl; begin Result:= 0; end; function gc_ID(L : Plua_State) : Integer; cdecl; var p: POleVariant; begin Result:= 0; p:= lua_touserdata(L, 1); if TVarData(p^).vtype <> varDispatch then Exit; IDispatch(TVarData(p^).vDispatch)._Release; //p^:= Unassigned; end; function gc_ID_client(L : Plua_State) : Integer; cdecl; var sink: ^TEventSink; begin Result:= 0; sink:= lua_touserdata(L, 1); sink^.Free; end; procedure DoCreateActiveXObject(L : Plua_State; id: IDispatch); var p: POleVariant; sink: ^TEventSink; begin //id._AddRef; lua_newtable(L); lua_newtable(L); // new metatable lua_pushstring(L, '__gc'); lua_pushcfunction(L, @gc); lua_settable(L, -3); lua_pushstring(L, FIELD_ID); p:= lua_newuserdata(L, SizeOf(OleVariant)); VariantInit(TVarData(p^)); p^:= id; if lua_getmetatable(L, -1) = 0 then lua_newtable(L); lua_pushstring(L, '__gc'); lua_pushcfunction(L, @gc_ID); lua_settable(L, -3); lua_setmetatable(L, -2); lua_settable(L, -3); lua_pushstring(L, '__newindex'); lua_pushcfunction(L, @NewIndex); lua_settable(L, -3); lua_pushstring(L, '__index'); lua_pushcfunction(L, @Index); lua_settable(L, -3); lua_pushstring(L, '__eq'); lua_pushcfunction(L, @equal); lua_settable(L, -3); lua_pushstring(L, '__pairs'); lua_pushcfunction(L, @pairs); lua_settable(L, -3); lua_pushstring(L, '__ipairs'); lua_pushcfunction(L, @pairs); lua_settable(L, -3); lua_pushstring(L, FIELD_ID_CLIENT); sink:= lua_newuserdata(L, SizeOf(TEventSink)); if lua_getmetatable(L, -1) = 0 then lua_newtable(L); lua_pushstring(L, '__gc'); lua_pushcfunction(L, @gc_ID_client); lua_settable(L, -3); lua_setmetatable(L, -2); lua_settable(L, -3); sink^:= TEventSink.Create(L); lua_setmetatable(L, -2); end; function CreateActiveXObject(L : Plua_State) : Integer; cdecl; begin DoCreateActiveXObject(L, CreateOleObject(lua_tostring(L, 1))); Result := 1; end; // Make ref(ByRef) type function CreateRefType(L : Plua_State) : Integer; cdecl; var p: POleVariant; ParamCount: integer; begin ParamCount:= lua_gettop(L); lua_newtable(L); lua_newtable(L); lua_pushstring(L, FIELD_ID); p:= lua_newuserdata(L, SizeOf(OleVariant)); VariantInit(TVarData(p^)); if ParamCount > 0 then begin Lua2Var(L, p, 1, False); end; lua_settable(L, -3); lua_pushstring(L, '__newindex'); lua_pushcfunction(L, @NewIndex); lua_settable(L, -3); lua_pushstring(L, '__index'); lua_pushcfunction(L, @Index); lua_settable(L, -3); lua_pushstring(L, '__pairs'); lua_pushcfunction(L, @pairs); lua_settable(L, -3); lua_pushstring(L, '__ipairs'); lua_pushcfunction(L, @pairs); lua_settable(L, -3); lua_setmetatable(L, -2); Result := 1; end; { TInterfacedBase } function TInterfacedBase.QueryInterface(constref iid : tguid; out obj) : longint; stdcall; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TInterfacedBase._AddRef: Integer; stdcall; begin Result := -1; end; function TInterfacedBase._Release: Integer; stdcall; begin Result := -1; end; { TEventSink } function TEventSink.GetTypeInfoCount(out Count: Integer): HRESULT; stdcall; begin Count:= 0; Result:= S_OK; end; function TEventSink.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HRESULT; stdcall; begin Result:= E_NOTIMPL; end; function TEventSink.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HRESULT; stdcall; begin Result:= E_NOTIMPL; end; function TEventSink.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; stdcall; var dispparams: TDispParams; name: WideString; name2: string; i: Integer; v: OleVariant; begin Result := S_FALSE; if FInfo.GetDocumentation(DispId, @name, nil, nil, nil) <> S_OK then Exit; if name = '' then Exit; name2:= UTF8Encode(name); name:= ''; i:= EventList.IndexOf(LowerCase(name2)); if i >= 0 then begin lua_rawgeti(L, LUA_REGISTRYINDEX, Integer(EventList.Objects[i])); dispparams := TDispParams(Params); // upsidedown! for i := dispparams.cArgs - 1 downto 0 do begin try v := OleVariant(dispparams.rgvarg^[i]); except VariantInit(TVarData(v)); end; case VarType(v) of varNull: lua_pushnil(L); varSmallint,varInteger,varshortint,varByte, varword,varlongword,varint64,varqword: lua_pushinteger(L, v); varSingle,varDouble,vardecimal: lua_pushnumber(L, v); varBoolean: lua_pushboolean(L, v); varDispatch: DoCreateActiveXObject(L, v); else begin lua_pushstring(L, UTF8Encode(v)); end; end; {case} end; {for} lua_pcall(L, dispparams.cArgs, 0{result}, 0); // TODO: result end; Result := S_OK; end; constructor TEventSink.Create(aL: PLua_State); begin inherited Create; L:= aL; EventList:= TStringList.Create; EventList.Sorted:= True; FInfo:= nil; FCPoint:= nil; end; destructor TEventSink.Destroy; var i: Integer; begin for i:= 0 to EventList.Count-1 do luaL_unref(L, LUA_REGISTRYINDEX, Integer(EventList.Objects[i])); EventList.Free; if IsEventSupport then FCPoint.UnAdvise(FCookie); inherited Destroy; end; procedure TEventSink.AttachEvent(server: IDispatch); var cp_c: IConnectionPointContainer; cp: IConnectionPoint; enum: IEnumConnectionPoints; fetched: LongInt; num: LongWord; iid: TIID; ti: ITypeInfo; tl: ITypeLib; i: integer; begin if server.QueryInterface(IID_IConnectionPointContainer, cp_c) <> S_OK then Exit; ChkErr(L, cp_c.EnumConnectionPoints(enum)); if Assigned(enum) then begin enum.Reset; i:= 0; while enum.Next(1, cp, @fetched) = S_OK do begin if fetched = 1 then begin if cp.GetConnectionInterface(iid) <> S_OK then continue; if server.GetTypeInfo(0, 0, ti) <> S_OK then continue; if ti.GetContainingTypeLib(tl, num) <> S_OK then continue; if tl.GetTypeInfoOfGuid(iid, FInfo) <> S_OK then continue; if cp.Advise(Self, FCookie) <> S_OK then continue; FCPoint:= cp; end; Inc(i); Break; // TODO end; end; end; procedure TEventSink.DetachEvent; begin if Assigned(FCPoint) then begin FCPoint.UnAdvise(FCookie); end; end; function TEventSink.IsEventSupport: boolean; begin Result:= Assigned(FCPoint); end; end.
unit uMinesClasses; interface uses Classes, SysUtils, mmSystem, math; type TMines = class; TSquareList = class; TSquareStatus = (ssHidden, ssRevealed, ssQuestion, ssFlag, ssErrorFlag, ssExploded); TSquare = class private FX, FY : integer; FNeighbouringMines : integer; FMines : TMines; FStatus: TSquareStatus; FSignalled: boolean; procedure SetStatus(const Value: TSquareStatus); procedure SetSignalled(const Value: boolean); public Mine : boolean; Neighbours : TSquareList; Data : TObject; Changed : boolean; RevealRecurseLevel : integer; procedure CountNeighbouringMines; function CountNeighbouring(SquareStatus : TSquareStatus) : integer; function AsString : string; procedure ClickedReveal(Wide : boolean); procedure ClickedRevealWide; procedure ClickedFlag; procedure RecursiveReveal(Level : integer); procedure Signal; procedure SignalWide; constructor Create(X, Y : integer; Mines : TMines); destructor Destroy;override; property X : integer read FX; property Y : integer read FY; property NeighbouringMines : integer read FNeighbouringMines; property Mines : TMines read FMines; property Status : TSquareStatus read FStatus write SetStatus; property Signalled : boolean read FSignalled write SetSignalled; end; TSquareList = class(TList) private function GetItems(i: integer): TSquare; procedure SetItems(i: integer; const Value: TSquare); public property Items[i : integer] : TSquare read GetItems write SetItems;default; end; TGameState = (gsWaiting, gsActive, gsWon, gsLost); TMapSize = (msBeginner, msIntermediate, msAdvanced); TMines = class private FCountX: integer; FCountY: integer; FMineCount: integer; FGameState: TGameState; FOnGameStarted: TNotifyEvent; FOnGameReset: TNotifyEvent; FOnGameWon: TNotifyEvent; FOnGameLost: TNotifyEvent; FOnAfterUpdate: TNotifyEvent; FOnRevealedFailed: TNotifyEvent; procedure SetCountX(const Value: integer); procedure SetCountY(const Value: integer); procedure SetMineCount(const Value: integer); procedure SetOnGameLost(const Value: TNotifyEvent); procedure SetOnGameReset(const Value: TNotifyEvent); procedure SetOnGameStarted(const Value: TNotifyEvent); procedure SetOnGameWon(const Value: TNotifyEvent); procedure SetOnAfterUpdate(const Value: TNotifyEvent); procedure SetOnRevealedFailed(const Value: TNotifyEvent); public SquareList : TSquareList; MinesList : TSquareList; HiddenCount : integer; RevealedCount : integer; GameStartedTime : cardinal; GameStoppedTime : cardinal; FlagsPlaced : integer; MoveHistory : TStringList; UseWarnings : boolean; SafeFirstReveal : boolean; procedure AddMoveInformation(s : string); constructor Create; destructor Destroy;override; function GameTimePassed : single; procedure ClearSquareList; procedure BuildRandomMap(MineCount, CountX, CountY : integer); procedure BuildRandomMapSpecified(MapSize : TMapSize); procedure BuildRandomSameSize; function GetSquareForXY(X, Y : integer) : TSquare; procedure TurnOfSignals; procedure StartGame; procedure FailGame; procedure MineRevealed; procedure WinGame; published property GameState : TGameState read FGameState; property MineCount : integer read FMineCount write SetMineCount; property CountX : integer read FCountX write SetCountX; property CountY : integer read FCountY write SetCountY; // An easy way to plug into the game engine property OnGameWon : TNotifyEvent read FOnGameWon write SetOnGameWon; property OnGameLost : TNotifyEvent read FOnGameLost write SetOnGameLost; property OnGameStarted : TNotifyEvent read FOnGameStarted write SetOnGameStarted; property OnGameReset : TNotifyEvent read FOnGameReset write SetOnGameReset; property OnAfterUpdate : TNotifyEvent read FOnAfterUpdate write SetOnAfterUpdate; property OnRevealedFailed : TNotifyEvent read FOnRevealedFailed write SetOnRevealedFailed; end; implementation { TSquareList } function TSquareList.GetItems(i: integer): TSquare; begin result := Get(i); end; procedure TSquareList.SetItems(i: integer; const Value: TSquare); begin Put(i, Value); end; { TSquare } function TSquare.AsString: string; begin result := Format('%d|%d',[x,y]); end; procedure TSquare.ClickedFlag; begin // If the game is either won or lost, the clicking serves no purpose if not (Mines.GameState in [gsActive, gsWaiting]) then exit; // This method is fired whenever the user actually RIGHT-CLICKS on a square. // Only these statuses make sense for right clicking if not (Status in [ssFlag, ssHidden, ssQuestion]) then exit; Mines.AddMoveInformation(Format('clicked flag|%s',[AsString])); if Status = ssHidden then Status := ssFlag else if Status = ssFlag then Status := ssQuestion else if Status = ssQuestion then Status := ssHidden; if (not Mines.UseWarnings) and (Status=ssQuestion) then Status := ssHidden; end; procedure TSquare.ClickedReveal(Wide : boolean); begin // If the game is either won or lost, the clicking serves no purpose // Clicking a square is the only way to start a game! if Mines.GameState = gsWaiting then Mines.StartGame; if Mines.GameState <> gsActive then exit; // This method is fired whenever the user actually CLICKS on a square. // These statuses makes clicking pointless if Status in [ssFlag, ssExploded, ssRevealed] then begin if Assigned(Mines.OnRevealedFailed) and not Wide then Mines.OnRevealedFailed(Mines); exit; end; Mines.AddMoveInformation(Format('reveal|%s',[AsString])); // If it's a mine, then we're in trouble! if Mine then begin // Are we safe? if Mines.SafeFirstReveal and (Mines.RevealedCount=0) then begin // Flag it instead! ClickedFlag; end else begin Status := ssExploded; Mines.FailGame; exit; end; end; // Reveal the hidden, and it's neighbours! if (Status in [ssHidden, ssQuestion]) then begin RecursiveReveal(0); exit; end; //TSquareStatus = (ssHidden, ssRevealed, ssQuestion, ssFlag, ssExploded); end; procedure TSquare.ClickedRevealWide; var i : integer; begin // This is the same as clicking all the neighbouring squares. It can only // be done when the following conditions are met; // 1. It's revealed if Status<>ssRevealed then exit; // 2. The number on the revealed square is equal to the number of flags // that neighbour it if CountNeighbouring(ssFlag)<>FNeighbouringMines then exit; // Now, click them all! for i := 0 to Neighbours.Count-1 do Neighbours[i].ClickedReveal(true); end; function TSquare.CountNeighbouring(SquareStatus: TSquareStatus): integer; var i : integer; cnt : integer; begin cnt := 0; for i := 0 to Neighbours.Count-1 do if (Neighbours[i].Status = SquareStatus) then inc(cnt); result := cnt; end; procedure TSquare.CountNeighbouringMines; var i : integer; begin FNeighbouringMines := 0; for i := 0 to Neighbours.Count-1 do if Neighbours[i].Mine then inc(FNeighbouringMines); end; constructor TSquare.Create(X, Y : integer; Mines : TMines); begin Neighbours := TSquareList.Create; Status := ssHidden; FX := x; FY := y; FMines := Mines; Changed := false; end; destructor TSquare.Destroy; begin Neighbours.Free; inherited; end; // WIDTH FIRST REVEAL procedure TSquare.RecursiveReveal(Level : integer); var j,i : integer; Revealer : TSquare; RevealedSquares : TSquareList; procedure DoReveal(Square : TSquare); begin // If it's allready been revealed, just get out of here if (Square.Status=ssRevealed) or (Square.Status=ssFlag) then exit; { if RevealedSquares.IndexOf(Square)<>-1 then exit;//} // Reveal this node Square.Status := ssRevealed; Square.RevealRecurseLevel := Revealer.RevealRecurseLevel+1; RevealedSquares.Add(Square); end; begin // If it's allready been revealed, just get out of here if (Status=ssRevealed) or (Status=ssFlag) then exit; // Reveal this node Status := ssRevealed; RevealRecurseLevel := 0; RevealedSquares := TSquareList.Create; RevealedSquares.Add(self); j := 0; try while j < RevealedSquares.Count do begin Revealer := RevealedSquares[j]; if Revealer.NeighbouringMines=0 then for i := 0 to Revealer.Neighbours.Count-1 do DoReveal(Revealer.Neighbours[i]); inc(j); end; finally RevealedSquares.Free; end; end;//} { // DEPTH FIRST REVEAL procedure TSquare.RecursiveReveal(Level : integer); var i : integer; begin // If it's allready been revealed, just get out of here if (Status=ssRevealed) or (Status=ssFlag) then exit; // Reveal this node Status := ssRevealed; RevealRecurseLevel := Level; // If it doesn't have any neighbouring bombs, start revealing the neighbours if (NeighbouringMines=0) then for i := 0 to Neighbours.Count-1 do Neighbours[i].RecursiveReveal(Level + 1); end;//} // DEPTH FIRST REVEAL 2 {procedure TSquare.RecursiveReveal(Level : integer); var i : integer; begin // Reveal this node Status := ssRevealed; RevealRecurseLevel := Level; // If it doesn't have any neighbouring bombs, start revealing the neighbours if (NeighbouringMines=0) then for i := 0 to Neighbours.Count-1 do if not (Neighbours[i].Status in [ssRevealed, ssFlag]) then Neighbours[i].RecursiveReveal(Level + 1); end;//} procedure TSquare.SetSignalled(const Value: boolean); begin if Value <> FSignalled then Changed := true; FSignalled := Value; end; procedure TSquare.SetStatus(const Value: TSquareStatus); begin // Are we revealing a hidden non-bomb? if (Status<>ssRevealed) and (Value=ssRevealed) then Mines.MineRevealed; if (Value=ssFlag) then inc(Mines.FlagsPlaced); if (FStatus=ssFlag) then dec(Mines.FlagsPlaced); FStatus := Value; Changed := true; end; procedure TSquare.Signal; begin if Mines.GameState in [gsWon, gsLost] then exit; // Signal only works if the square if question or hidden if (Status=ssHidden) or (Status=ssQuestion) then Signalled := true; end; procedure TSquare.SignalWide; var i : integer; begin if Mines.GameState in [gsWon, gsLost] then exit; // Signal self Signal; // Signal neighbours! for i := 0 to Neighbours.Count-1 do Neighbours[i].Signal; end; { TMines } constructor TMines.Create; begin SquareList := TSquareList.Create; MinesList := TSquareList.Create; MoveHistory := TStringList.Create; GameStoppedTime := 0; GameStartedTime := 0; UseWarnings := true; SafeFirstReveal := false; end; procedure TMines.BuildRandomMap(MineCount, CountX, CountY: integer); var i,x,y, tries, CurrentMines : integer; Square, NSquare : TSquare; begin MoveHistory.Clear; AddMoveInformation(Format('new map|%d|%d|%d',[MineCount, x, y])); AddMoveInformation(Format('rand seed|%d',[RandSeed])); Assert(MineCount<CountX*CountY,'There''s no room for that many mines!'); Assert(CountX>3,'CountX must be larger than 3!'); Assert(CountY>3,'CountY must be larger than 3!'); ClearSquareList; self.MineCount := MineCount; self.CountX := CountX; self.CountY := CountY; // Create the squares for x := 0 to CountX-1 do for y := 0 to CountY-1 do begin Square := TSquare.Create(x,y, self); SquareList.Add(Square); end; // Connect them to their neigbours! for i := 0 to Squarelist.Count-1 do begin Square := Squarelist[i]; for x := -1 to 1 do for y := -1 to 1 do begin // Not neighbour with self! if (x=0) and (y=0) then continue; NSquare := GetSquareForXY(Square.X+X, Square.Y+Y); if NSquare <> nil then Square.Neighbours.Add(NSquare); end; end; // Assign random mines! tries := 10*MineCount; CurrentMines := 0; while (tries>0) and (CurrentMines<MineCount) do begin // Pick a random square Square := SquareList[random(SquareList.Count)]; // If it's allready a mine, don't use it! if not Square.Mine then begin // Make it a mine Square.Mine := true; // Add to the mines list MinesList.Add(Square); // Increase the currentmine count inc(CurrentMines); end; dec(tries); end; // Update the mine count of the squares for i := 0 to SquareList.Count-1 do SquareList[i].CountNeighbouringMines; // Set game state to waiting FGameState := gsWaiting; // The number of hidden squares, that are NOT mines HiddenCount := SquareList.Count-MinesList.Count; GameStoppedTime := 0; GameStartedTime := 0; FlagsPlaced := 0; RevealedCount := 0; if Assigned(OnGameReset) then OnGameReset(self); end; destructor TMines.Destroy; begin ClearSquareList; SquareList.Free; MinesList.Free; MoveHistory.Free; inherited; end; procedure TMines.SetCountX(const Value: integer); begin FCountX := Value; end; procedure TMines.SetCountY(const Value: integer); begin FCountY := Value; end; procedure TMines.SetMineCount(const Value: integer); begin FMineCount := Value; end; procedure TMines.ClearSquareList; var i : integer; begin for i := 0 to SquareList.Count-1 do SquareList[i].Free; SquareList.Clear; MinesList.Clear; end; function TMines.GetSquareForXY(X, Y: integer): TSquare; var i : integer; begin result := nil; for i := 0 to SquareList.Count-1 do if (SquareList[i].X=X) and (SquareList[i].Y=Y) then begin result := SquareList[i]; exit; end; end; procedure TMines.FailGame; var i : integer; begin GameStoppedTime := TimeGetTime; for i := 0 to MinesList.Count-1 do if MinesList[i].Status<>ssFlag then MinesList[i].Status := ssExploded; for i := 0 to SquareList.Count-1 do if (SquareList[i].Status=ssFlag) and not (SquareList[i].Mine) then SquareList[i].Status := ssErrorFlag; FGameState := gsLost; if Assigned(OnGameLost) then OnGameLost(self); TurnOfSignals; AddMoveInformation('game failed'); end; procedure TMines.MineRevealed; begin dec(HiddenCount); inc(RevealedCount); if HiddenCount=0 then WinGame; end; procedure TMines.WinGame; var i : integer; begin GameStoppedTime := TimeGetTime; // Yay FGameState := gsWon; for i := 0 to MinesList.Count-1 do MinesList[i].Status := ssFlag; if Assigned(OnGameWon) then OnGameWon(self); AddMoveInformation('game won'); end; procedure TMines.BuildRandomMapSpecified(MapSize: TMapSize); begin case MapSize of msBeginner : BuildRandomMap(10,9,9); msIntermediate : BuildRandomMap(40,16,16); msAdvanced : BuildRandomMap(99,30,16); end; end; procedure TMines.TurnOfSignals; var i : integer; begin for i := 0 to SquareList.Count-1 do SquareList[i].Signalled := false; end; procedure TMines.SetOnGameLost(const Value: TNotifyEvent); begin FOnGameLost := Value; end; procedure TMines.SetOnGameReset(const Value: TNotifyEvent); begin FOnGameReset := Value; end; procedure TMines.SetOnGameStarted(const Value: TNotifyEvent); begin FOnGameStarted := Value; end; procedure TMines.SetOnGameWon(const Value: TNotifyEvent); begin FOnGameWon := Value; end; procedure TMines.StartGame; begin GameStartedTime := timeGetTime; FGameState := gsActive; if Assigned(OnGameStarted) then OnGameStarted(self); AddMoveInformation('game started'); end; function TMines.GameTimePassed: single; begin if GameState=gsActive then result := (timeGetTime-GameStartedTime)/1000 else result := (GameStoppedTime-GameStartedTime)/1000; end; procedure TMines.SetOnAfterUpdate(const Value: TNotifyEvent); begin FOnAfterUpdate := Value; end; procedure TMines.AddMoveInformation(s: string); begin MoveHistory.Add(Format('%f|%s',[GameTimePassed, s])); if Assigned(OnAfterUpdate) then OnAfterUpdate(self); end; procedure TMines.BuildRandomSameSize; begin BuildRandomMap(MineCount, CountX, CountY); end; procedure TMines.SetOnRevealedFailed(const Value: TNotifyEvent); begin FOnRevealedFailed := Value; end; end.
unit pangowin32; interface uses windows, glib, pangowin32lib, pango; type IPangoWin32FontCache = interface ['{2F9C4B95-B405-4625-A5D8-9D542DDB9001}'] function Load(logfont: PLOGFONTA): HFONT; function Loadw(logfont: PLOGFONTW): HFONT; procedure Unload(hfont: HFONT); end; IPangoWin32FontMap = interface(IPangoFontMap) ['{581D7944-BF2F-4767-811E-527024BBC284}'] function GetFontCache: IPangoWin32FontCache; end; TPangoWin32FontMap = class(TPangoFontMap, IPangoWin32FontMap) protected function GetFontCache: IPangoWin32FontCache; public constructor Create; virtual; end; TPangoWin32FontCache = class(TInterfacedObject, IPangoWin32FontCache) private FPangoWin32FontCache: PPangoWin32FontCache; FOwned: Boolean; constructor CreateInternal(Handle: PPangoWin32FontCache; Owned: Boolean); protected function Load(logfont: PLOGFONTA): HFONT; function Loadw(logfont: PLOGFONTW): HFONT; procedure Unload(hfont: HFONT); public constructor Create; virtual; destructor Destroy; override; end; implementation { TPangoWin32FontCache } constructor TPangoWin32FontCache.Create; begin CreateInternal(pango_win32_font_cache_new, true); end; constructor TPangoWin32FontCache.CreateInternal(Handle: PPangoWin32FontCache; Owned: Boolean); begin Assert(Handle <> nil); FPangoWin32FontCache := Handle; FOwned := Owned; end; destructor TPangoWin32FontCache.Destroy; begin pango_win32_font_cache_free(FPangoWin32FontCache); inherited; end; function TPangoWin32FontCache.Load(logfont: PLOGFONTA): HFONT; begin Result := pango_win32_font_cache_load(FPangoWin32FontCache, logfont); end; function TPangoWin32FontCache.Loadw(logfont: PLOGFONTW): HFONT; begin Result := pango_win32_font_cache_loadw(FPangoWin32FontCache, logfont); end; procedure TPangoWin32FontCache.Unload(hfont: HFONT); begin pango_win32_font_cache_unload(FPangoWin32FontCache, hfont); end; { TPangoWin32FontMap } constructor TPangoWin32FontMap.Create; begin CreateInternal(g_object_ref(pango_win32_font_map_for_display)); end; function TPangoWin32FontMap.GetFontCache: IPangoWin32FontCache; begin TPangoWin32FontCache.CreateInternal(g_object_ref(pango_win32_font_map_get_font_cache(GetHandle)), false); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLCelShader<p> A shader that applies cel shading through a vertex program and shade definition texture.<p> <b>History : </b><font size=-1><ul> <li>05/03/10 - DanB - More state added to TGLStateCache <li>22/01/10 - Yar - Added bmp32.Blank:=false for memory allocation <li>06/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211) <li>31/03/07 - DaStr - Added $I GLScene.inc <li>21/03/07 - DaStr - Added explicit pointer dereferencing (thanks Burkhard Carstens) (Bugtracker ID = 1678644) <li>25/02/07 - DaStr - Moved registration to GLSceneRegister.pas <li>28/09/04 - SG - Vertex program now uses ARB_position_invariant option. <li>09/06/04 - SG - Added OutlineColor, vertex programs now use GL state. <li>28/05/04 - SG - Creation. </ul></font> } unit GLCelShader; interface {$I GLScene.inc} uses Classes, SysUtils, GLTexture, GLContext, GLGraphics, GLUtils, GLVectorGeometry, OpenGL1x, OpenGLTokens, ARBProgram, GLColor, GLRenderContextInfo, GLMaterial, GLState; type // TGLCelShaderOption // {: Cel shading options.<p> csoOutlines: Render a second outline pass. csoTextured: Allows for a primary texture that the cel shading is modulated with and forces the shade definition to render as a second texture. } TGLCelShaderOption = (csoOutlines, csoTextured, csoNoBuildShadeTexture); TGLCelShaderOptions = set of TGLCelShaderOption; // TGLCelShaderGetIntensity // //: An event for user defined cel intensity. TGLCelShaderGetIntensity = procedure (Sender : TObject; var intensity : Byte) of object; // TGLCelShader // {: A generic cel shader.<p> } TGLCelShader = class (TGLShader) private FOutlineWidth : Single; FCelShaderOptions : TGLCelShaderOptions; FVPHandle : Cardinal; FShadeTexture : TGLTexture; FOnGetIntensity : TGLCelShaderGetIntensity; FOutlinePass, FUnApplyShadeTexture : Boolean; FOutlineColor : TGLColor; protected procedure SetCelShaderOptions(const val : TGLCelShaderOptions); procedure SetOutlineWidth(const val : Single); procedure SetOutlineColor(const val : TGLColor); procedure BuildShadeTexture; procedure Loaded; override; function GenerateVertexProgram : String; procedure DestroyVertexProgram; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override; function DoUnApply(var rci: TRenderContextInfo) : Boolean; override; property ShadeTexture : TGLTexture read FShadeTexture; published property CelShaderOptions : TGLCelShaderOptions read FCelShaderOptions write SetCelShaderOptions; property OutlineColor : TGLColor read FOutlineColor write SetOutlineColor; property OutlineWidth : Single read FOutlineWidth write SetOutlineWidth; property OnGetIntensity : TGLCelShaderGetIntensity read FOnGetIntensity write FOnGetIntensity; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------ // ------------------ TGLCelShader ------------------ // ------------------ // Create // constructor TGLCelShader.Create(AOwner : TComponent); begin inherited; FOutlineWidth:=3; FCelShaderOptions:=[csoOutlines]; FShadeTexture:=TGLTexture.Create(Self); with FShadeTexture do begin Enabled:=True; MinFilter:=miNearest; MagFilter:=maNearest; TextureWrap:=twNone; TextureMode:=tmModulate; end; FOutlineColor:=TGLColor.Create(Self); FOutlineColor.OnNotifyChange:=NotifyChange; FOutlineColor.Initialize(clrBlack); ShaderStyle:=ssLowLevel; end; // Destroy // destructor TGLCelShader.Destroy; begin DestroyVertexProgram; FShadeTexture.Free; FOutlineColor.Free; inherited; end; // Loaded // procedure TGLCelShader.Loaded; begin inherited; BuildShadeTexture; end; // BuildShadeTexture // procedure TGLCelShader.BuildShadeTexture; var bmp32 : TGLBitmap32; i : Integer; intensity : Byte; begin if csoNoBuildShadeTexture in FCelShaderOptions then exit; with FShadeTexture do begin ImageClassName:='TGLBlankImage'; TGLBlankImage(Image).Width:=128; TGLBlankImage(Image).Height:=1; end; bmp32:=FShadeTexture.Image.GetBitmap32(GL_TEXTURE_2D); bmp32.Blank := false; for i:=0 to bmp32.Width-1 do begin intensity:=i*(256 div bmp32.Width); if Assigned(FOnGetIntensity) then FOnGetIntensity(Self, intensity) else begin if intensity>230 then intensity:=255 else if intensity>150 then intensity:=230 else if intensity>100 then intensity:=intensity+50 else intensity:=150; end; bmp32.Data^[i].r:=intensity; bmp32.Data^[i].g:=intensity; bmp32.Data^[i].b:=intensity; bmp32.Data^[i].a:=1; end; end; // DestroyVertexProgram // procedure TGLCelShader.DestroyVertexProgram; begin if FVPHandle > 0 then glDeleteProgramsARB(1, @FVPHandle); end; // GenerateVertexProgram // function TGLCelShader.GenerateVertexProgram : String; var VP : TStringList; begin VP:=TStringList.Create; VP.Add('!!ARBvp1.0'); VP.Add('OPTION ARB_position_invariant;'); VP.Add('PARAM mvinv[4] = { state.matrix.modelview.inverse };'); VP.Add('PARAM lightPos = program.local[0];'); VP.Add('TEMP temp, light, normal;'); VP.Add(' DP4 light.x, mvinv[0], lightPos;'); VP.Add(' DP4 light.y, mvinv[1], lightPos;'); VP.Add(' DP4 light.z, mvinv[2], lightPos;'); VP.Add(' ADD light, light, -vertex.position;'); VP.Add(' DP3 temp.x, light, light;'); VP.Add(' RSQ temp.x, temp.x;'); VP.Add(' MUL light, temp.x, light;'); VP.Add(' DP3 temp, vertex.normal, vertex.normal;'); VP.Add(' RSQ temp.x, temp.x;'); VP.Add(' MUL normal, temp.x, vertex.normal;'); VP.Add(' MOV result.color, state.material.diffuse;'); if csoTextured in FCelShaderOptions then begin VP.Add(' MOV result.texcoord[0], vertex.texcoord[0];'); VP.Add(' DP3 result.texcoord[1].x, normal, light;'); end else begin VP.Add(' DP3 result.texcoord[0].x, normal, light;'); end; VP.Add('END'); Result:=VP.Text; VP.Free; end; // DoApply // procedure TGLCelShader.DoApply(var rci: TRenderContextInfo; Sender: TObject); var success : Boolean; str : String; light : TVector; begin if (csDesigning in ComponentState) then exit; if FVPHandle = 0 then begin success:=false; try str:=GenerateVertexProgram; LoadARBProgram(GL_VERTEX_PROGRAM_ARB, str, FVPHandle); success:=True; finally if not success then Enabled:=False; end; end; rci.GLStates.PushAttrib([sttEnable, sttCurrent, sttColorBuffer, sttHint, sttLine, sttPolygon, sttDepthBuffer]); rci.GLStates.Disable(stLighting); glEnable(GL_VERTEX_PROGRAM_ARB); glGetLightfv(GL_LIGHT0, GL_POSITION, @light[0]); glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, 0, @light[0]); glBindProgramARB(GL_VERTEX_PROGRAM_ARB, FVPHandle); if (csoTextured in FCelShaderOptions) then FShadeTexture.ApplyAsTexture2(rci, nil) else FShadeTexture.Apply(rci); FOutlinePass:=csoOutlines in FCelShaderOptions; FUnApplyShadeTexture:=True; end; // DoUnApply // function TGLCelShader.DoUnApply(var rci: TRenderContextInfo) : Boolean; begin Result:=False; if (csDesigning in ComponentState) then exit; glDisable(GL_VERTEX_PROGRAM_ARB); if FUnApplyShadeTexture then begin if (csoTextured in FCelShaderOptions) then FShadeTexture.UnApplyAsTexture2(rci, false) else FShadeTexture.UnApply(rci); FUnApplyShadeTexture:=False; end; if FOutlinePass then begin glDisable(GL_TEXTURE_2D); rci.GLStates.Enable(stBlend); rci.GLStates.Enable(stLineSmooth); rci.GLStates.Enable(stCullFace); rci.GLStates.PolygonMode := pmLines; rci.GLStates.CullFaceMode := cmFront; rci.GLStates.LineSmoothHint := hintNicest; rci.GLStates.SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha); rci.GLStates.DepthFunc := cfLEqual; glColor4fv(FOutlineColor.AsAddress); rci.GLStates.LineWidth := FOutlineWidth; Result:=True; FOutlinePass:=False; Exit; end; rci.GLStates.PopAttrib; end; // SetCelShaderOptions // procedure TGLCelShader.SetCelShaderOptions(const val: TGLCelShaderOptions); begin if val<>FCelShaderOptions then begin FCelShaderOptions:=val; BuildShadeTexture; DestroyVertexProgram; NotifyChange(Self); end; end; // SetOutlineWidth // procedure TGLCelShader.SetOutlineWidth(const val : Single); begin if val<>FOutlineWidth then begin FOutlineWidth:=val; NotifyChange(Self); end; end; // SetOutlineColor // procedure TGLCelShader.SetOutlineColor(const val: TGLColor); begin if val<>FOutlineColor then begin FOutlineColor.Assign(val); NotifyChange(Self); end; end; end.
{------------------------------------ 功能说明:系统服务 创建日期:2014/08/14 作者:mx 版权:mx -------------------------------------} unit uSysSvc; interface uses SysUtils, Windows, Classes, uFactoryIntf; type TSysService = class(TObject, IInterface) private FRefCount: Integer; protected function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public // Constructor Create; // Destructor Destroy;override; end; function SysService: IInterface; implementation uses uSysFactoryMgr; var FSysService: IInterface; function SysService: IInterface; begin if not Assigned(FSysService) then FSysService := TSysService.Create; Result := FSysService; end; { TSysService } function TSysService._AddRef: Integer; begin Result := InterlockedIncrement(FRefCount); end; function TSysService._Release: Integer; begin Result := InterlockedDecrement(FRefCount); if Result = 0 then Destroy; end; function TSysService.QueryInterface(const IID: TGUID; out Obj): HResult; //只能存取有GUID的COM接口 var FactoryIntf: ISysFactory; begin Result := E_NOINTERFACE; if self.GetInterface(IID, Obj) then Result := S_OK else begin FactoryIntf := FactoryManager.FindFactory(IID); if Assigned(FactoryIntf) then begin FactoryIntf.CreateInstance(IID, Obj); Result := S_OK; end; end; end; initialization FSysService := nil; finalization FSysService := nil; end.
unit PromoDTO; interface uses Classes, contnrs, StoreCls, SysUtils, variants, dialogs, PromoHandleConflict; type TDiscountQualifying = class private fIDDiscount: Integer; protected procedure setIDDiscount(arg_id: Integer); function getIDDiscount(): Integer; end; TDiscountCustomerGroup = class(TDiscountQualifying) private fIdTipoPessoa: Integer; fName: String; public procedure setIDTipoPessoaStr(arg_id: String); procedure setIDTipoPessoa(arg_id: Integer); function getIDTipoPessoa(): Integer; function getIDTipoPessoaStr(): String; procedure setName(arg_name: String); function getName(): String; end; TDiscountPurchase = class(TDiscountQualifying) private fIDTag: Integer; fNameTag: String; public procedure setIDTag(arg_tag: Integer); function getIDTag(): Integer; procedure setName(arg_name: String); function getName(): String; end; TDiscountReward = class(TDiscountPurchase); TPromoDTO = class private fIsInclude: Boolean; fDiscountValidOnDays: TStringList; fDiscountCoupons: TStringList; fPurchaseTagList: TObjectList; fRewardTagList: TObjectList; fCustomerList: TObjectList; fStoreList: TObjectList; // seek for conflicts between promos and tags FHandleConfllict: TPromoHandleConflict; fIDStore: Integer; fIDDiscount: Integer; fDiscountName: String; fEndDate: TDateTime; fStartDate: TDateTime; fDayOfWeek: String; fBeginTimeOfDay: TDateTime; fEndTimeOfDay: TDateTime; fDiscType: String; fMinSubTotal: Double; fStoreDefined: Boolean; fCustomerGroupDefined: Boolean; fPurchaseTagDefined: Boolean; fRewardTagDefined: Boolean; fCouponDefined: Boolean; fCouponNumber: String; fIDTagQualifyingDiscount: Integer; fIdDiscUses: Integer; fIDTagRewards: Integer; fMaxUsesPerCustomer: Integer; fMaxUsesInTotal: Integer; fFirstTimeCustomerOnly: Boolean; fCustomerCardRequired: Boolean; fCustomerGroup: Boolean; fAllowedCustomerGroup: String; fIsStackable: Boolean; fRewardAmount: Double; fAmountType: String; fRewardQuantity: variant; fMinQuantity: variant; fMinDollarAmount: variant; fSalePrice: Double; fIsBogo: boolean; FBuyAnd: boolean; FCashierShouldWarn: boolean; function getIDDiscount: Integer; procedure setIDDiscount(const Value: Integer); function getAllowedCustomerGroup: String; function getAmountType: String; function getBeginTimeOfDay: TDateTime; //function getDayOfWeek: String; function getDiscountType: String; function getEndTimeOfDay: TDateTime; function getIsStackable: Boolean; function getMaxUsesInTotal: Integer; function getMaxUsesPerCustomer: Integer; function getMinDollarAmount: variant; function getMinQuantity: variant; function getMinSubTotal: Double; function getRewardAmount: Double; function getRewardQuantity: variant; procedure setAllowedCustomerGroup(const Value: String); procedure setAmountType(const Value: String); procedure setBeginTimeOfDay(const Value: TDateTime); procedure setCustomerCardRequired(const Value: Boolean); //procedure setDayOfWeek(const Value: String); procedure setDiscountType(const Value: String); procedure setMinDollarAmount(const Value: variant); procedure setEndTimeOfDay(const Value: TDateTime); procedure setFirstTimeCustomerOnly(const Value: Boolean); procedure setIsStackable(const Value: Boolean); procedure setMaxUsesInTotal(const Value: Integer); procedure setMaxUsesPerCustomer(const Value: Integer); procedure setMinQuantity(const Value: variant); procedure setMinSubTotal(const Value: Double); procedure setRewardAmount(const Value: Double); procedure setRewardQuantity(const Value: variant); function getCustomerCardRequired: Boolean; function getFirstTimeCustomerOnly: Boolean; function getEndDate: TDateTime; function getStartDate: TDateTime; procedure setEndDate(const Value: TDateTime); procedure setStartDate(const Value: TDateTime); function getCouponNumber: String; procedure setCouponNumber(const Value: String); function getIDDiscUses: Integer; function getIDTagQualifyingDiscount: Integer; procedure setDiscUses(const Value: Integer); procedure setIDTagQualifyingDiscount(const Value: Integer); function getIDTagRewards: Integer; procedure setIDTagRewards(const Value: Integer); function getCustomerGroup: Boolean; procedure setCustomerGroup(const Value: Boolean); function getDiscountName: String; procedure setDiscountName(const Value: String); function getCouponDefined: Boolean; function getPurchaseTagDefined: Boolean; function getRewardTagDefined: Boolean; function getStoredDefined: Boolean; procedure setCouponDefined(const Value: Boolean); procedure setPurchaseTagDefined(const Value: Boolean); procedure setRewardTagDefined(const Value: Boolean); procedure setStoreDefined(const Value: Boolean); function getCustomerGroupDefined: Boolean; procedure setCustomerGroupDefined(const Value: Boolean); function getIDStore: Integer; procedure setIDStore(const Value: Integer); function getSalePrice: Double; procedure setSalePrice(const Value: Double); function getIsBogo(): boolean; procedure setIsBogo(const value: boolean); function getBuyAnd(): boolean; procedure setBuyAnd(const value: boolean); public constructor create(); destructor destroy(); override; property IsInclude: Boolean read fIsInclude write fIsInclude; property StoreDefined: Boolean read getStoredDefined write setStoreDefined; property CustomerGroupDefined: Boolean read getCustomerGroupDefined write setCustomerGroupDefined; property PurchaseTagDefined: Boolean read getPurchaseTagDefined write setPurchaseTagDefined; property RewardTagDefined: Boolean read getRewardTagDefined write setRewardTagDefined; property CouponDefined: Boolean read getCouponDefined write setCouponDefined; property IDStore: Integer read getIDStore write setIDStore; property IDDiscount: Integer read getIDDiscount write setIDDiscount; property DiscountName: String read getDiscountName write setDiscountName; property StartDate: TDateTime read getStartDate write setStartDate; property EndDate: TDateTime read getEndDate write setEndDate; property DayOfWeek: String read FDayOfWeek write FDayOfWeek; property BeginTimeOfDay: TDateTime read getBeginTimeOfDay write setBeginTimeOfDay; property EndTimeOfDay: TDateTime read getEndTimeOfDay write setEndTimeOfDay; property DiscountType: String read getDiscountType write setDiscountType; property MinSubTotal: Double read getMinSubTotal write setMinSubTotal; property CouponNumber: String read getCouponNumber write setCouponNumber; property IDTagQualifyingDiscount: Integer read getIDTagQualifyingDiscount write setIDTagQualifyingDiscount; property IDDiscUses: Integer read getIDDiscUses write setDiscUses; property IDTagRewards: Integer read getIDTagRewards write setIDTagRewards; property MaxUsesPerCustomer: Integer read getMaxUsesPerCustomer write setMaxUsesPerCustomer; property MaxUsesInTotal: Integer read getMaxUsesInTotal write setMaxUsesInTotal; property FirstTimeCustomerOnly: Boolean read getFirstTimeCustomerOnly write setFirstTimeCustomerOnly; property CustomerCardRequired: Boolean read getCustomerCardRequired write setCustomerCardRequired; property CustomerGroup: Boolean read getCustomerGroup write setCustomerGroup; property AllowedCustomerGroup: String read getAllowedCustomerGroup write setAllowedCustomerGroup; property IsStackable: Boolean read getIsStackable write setIsStackable; property RewardAmount: Double read getRewardAmount write setRewardAmount; property AmountType: String read getAmountType write setAmountType; property RewardQuantity: variant read getRewardQuantity write setRewardQuantity; property MinQuantity: variant read getMinQuantity write setMinQuantity; property MinDollarAmount: variant read getMinDollarAmount write setMinDollarAmount; property SalePrice: Double read getSalePrice write setSalePrice; property IsBogo: boolean read getIsBogo write setIsBogo; property BuyAnd: boolean read getBuyAnd write setBuyAnd; property CashierShouldWarn: boolean read FCashierShouldWarn write FCashierShouldWarn; function getCouponsDiscount(): TStringList; function getValidOnDaysDiscount(): TStringList; function getCustomerGroupList: TObjectList; function getPurchaseTagList: TObjectList; function getRewardTagList: TObjectList; function getStoreList: TObjectList; procedure addCouponsToList(arg_coupon: String); procedure addPurchaseTagToList(arg_tag: TDiscountPurchase); procedure addRewardTagToList(arg_tag: TDiscountReward); procedure addCustomerGroupToList(arg_customGroup: TDiscountCustomerGroup); procedure addStoreToList(arg_store: TStoreRegistry); procedure addDiscountValidOnDayToList(arg_day: String); end; TCouponPromo = class(TPromoDTO) private FCouponCode: string; FCashierShouldWarn: boolean; FNeedsPhysicalCoupon: boolean; public property CouponCode: string read FCouponCode write FCouponCode; property CashierShouldWarn: boolean read FCashierShouldWarn write FCashierShouldWarn; property NeedsPhysicalCoupon: boolean read FNeedsPhysicalCoupon write FNeedsPhysicalCoupon; end; implementation { TPromoDTO } function TPromoDTO.getAllowedCustomerGroup: String; begin result := fAllowedCustomerGroup end; function TPromoDTO.getAmountType: String; begin result := fAmountType end; function TPromoDTO.getBeginTimeOfDay: TDateTime; begin result := fBeginTimeOfDay end; function TPromoDTO.getCustomerCardRequired: Boolean; begin result := fCustomerCardRequired end; (* function TPromoDTO.getDayOfWeek: String; begin Result := fDayOfWeek end; *) function TPromoDTO.getDiscountType: String; begin result := fDiscType end; function TPromoDTO.getEndDate: TDateTime; begin result := fEndDate end; function TPromoDTO.getEndTimeOfDay: TDateTime; begin result := fEndTimeOfDay end; function TPromoDTO.getFirstTimeCustomerOnly: Boolean; begin result := fFirstTimeCustomerOnly end; function TPromoDTO.getIDDiscount: Integer; begin result := fIDDiscount end; function TPromoDTO.getIsStackable: Boolean; begin result := fIsStackable end; function TPromoDTO.getMaxUsesInTotal: Integer; begin result := fMaxUsesInTotal end; function TPromoDTO.getMaxUsesPerCustomer: Integer; begin result := fMaxUsesPerCustomer end; function TPromoDTO.getMinDollarAmount: variant; begin result := fMinDollarAmount end; function TPromoDTO.getMinQuantity: variant; begin result := fMinQuantity end; function TPromoDTO.getMinSubTotal: Double; begin result := fMinSubTotal end; function TPromoDTO.getRewardAmount: Double; begin result := fRewardAmount; end; function TPromoDTO.getRewardQuantity: variant; begin result := fRewardQuantity end; function TPromoDTO.getStartDate: TDateTime; begin result := fStartDate end; procedure TPromoDTO.setAllowedCustomerGroup(const Value: String); begin fAllowedCustomerGroup := value end; procedure TPromoDTO.setAmountType(const Value: String); begin fAmountType := value end; procedure TPromoDTO.setBeginTimeOfDay(const Value: TDateTime); begin fBeginTimeOfDay := value end; procedure TPromoDTO.setCustomerCardRequired(const Value: Boolean); begin fCustomerCardRequired := value end; (* procedure TPromoDTO.setDayOfWeek(const Value: String); begin DayOfWeek := value end; *) procedure TPromoDTO.setDiscountType(const Value: String); begin fDiscType := value end; procedure TPromoDTO.setMinDollarAmount(const Value: variant); begin fMinDollarAmount := value end; procedure TPromoDTO.setEndDate(const Value: TDateTime); begin fEndDate := value end; procedure TPromoDTO.setEndTimeOfDay(const Value: TDateTime); begin fEndTimeOfDay := value end; procedure TPromoDTO.setFirstTimeCustomerOnly(const Value: Boolean); begin fFirstTimeCustomerOnly := value end; procedure TPromoDTO.setIDDiscount(const Value: Integer); begin fIDDiscount := value end; procedure TPromoDTO.setIsStackable(const Value: Boolean); begin fIsStackable := value; end; procedure TPromoDTO.setMaxUsesInTotal(const Value: Integer); begin fMaxUsesInTotal := value end; procedure TPromoDTO.setMaxUsesPerCustomer(const Value: Integer); begin fMaxUsesPerCustomer := value end; procedure TPromoDTO.setMinQuantity(const Value: variant); begin fMinQuantity := value end; procedure TPromoDTO.setMinSubTotal(const Value: Double); begin fMinSubTotal := value end; procedure TPromoDTO.setRewardAmount(const Value: Double); begin if ( pos('Sale', fAmountType) > 0 ) then begin fRewardAmount := fSalePrice; end else if ( pos('Amount', fAmountType) > 0 ) then begin fRewardAmount := value; fSalePrice := 0; end else if ( (pos('Percent', fAmountType) > 0) and ( value > 0) ) then begin fRewardAmount := value; fSalePrice := 0; end; end; procedure TPromoDTO.setRewardQuantity(const Value: variant); begin fRewardQuantity := value end; procedure TPromoDTO.setStartDate(const Value: TDateTime); begin fStartDate := value end; function TPromoDTO.getCouponNumber: String; begin result := fCouponNumber end; procedure TPromoDTO.setCouponNumber(const Value: String); begin fCouponNumber := value end; function TPromoDTO.getIDDiscUses: Integer; begin Result := fIdDiscUses end; function TPromoDTO.getIDTagQualifyingDiscount: Integer; begin result := fIDTagQualifyingDiscount end; procedure TPromoDTO.setDiscUses(const Value: Integer); begin fIdDiscUses := value end; procedure TPromoDTO.setIDTagQualifyingDiscount(const Value: Integer); begin fIDTagQualifyingDiscount := value end; function TPromoDTO.getIDTagRewards: Integer; begin result := fIDTagRewards end; procedure TPromoDTO.setIDTagRewards(const Value: Integer); begin fIDTagRewards := value end; function TPromoDTO.getCustomerGroup: Boolean; begin result := fCustomerGroup; end; procedure TPromoDTO.setCustomerGroup(const Value: Boolean); begin fCustomerGroup := value; end; constructor TPromoDTO.create; begin fPurchaseTagList := TObjectList.Create(); fRewardTagList := TObjectList.Create(); fCustomerList := TObjectList.Create(); fStoreList := TObjectList.Create(); fDiscountValidOnDays := TStringList.Create(); fDiscountCoupons := TStringList.create(); end; procedure TPromoDTO.addCustomerGroupToList(arg_customGroup: TDiscountCustomerGroup); begin fCustomerList.Add(arg_customGroup) end; procedure TPromoDTO.addPurchaseTagToList(arg_tag: TDiscountPurchase); begin // showmessage(format('Purchase Tag Object values: Id = %d, name = %s', [arg_tag.fIDTag, arg_tag.fNameTag])); fPurchaseTagList.add(arg_tag) end; procedure TPromoDTO.addRewardTagToList(arg_tag: TDiscountReward); begin // showmessage(format('Reward Tag Object values: Id = %d, name = %s', [arg_tag.fIDTag, arg_tag.fNameTag])); fRewardTagList.add(arg_tag) end; procedure TPromoDTO.addStoreToList(arg_store: TStoreRegistry); begin fStoreList.Add(arg_store); end; function TPromoDTO.getCustomerGroupList: TObjectList; begin result := fCustomerList; end; function TPromoDTO.getPurchaseTagList: TObjectList; begin result := fPurchaseTagList end; function TPromoDTO.getRewardTagList: TObjectList; begin result := fRewardTagList end; function TPromoDTO.getStoreList: TObjectList; begin result := fStoreList end; function TPromoDTO.getDiscountName: String; begin result := fDiscountName end; procedure TPromoDTO.setDiscountName(const Value: String); begin fDiscountName := value; end; function TPromoDTO.getCouponDefined: Boolean; begin result := fCouponDefined end; function TPromoDTO.getPurchaseTagDefined: Boolean; begin result := fPurchaseTagDefined end; function TPromoDTO.getRewardTagDefined: Boolean; begin result := fRewardTagDefined end; function TPromoDTO.getStoredDefined: Boolean; begin result := fStoreDefined end; procedure TPromoDTO.setCouponDefined(const Value: Boolean); begin fCouponDefined := value end; procedure TPromoDTO.setPurchaseTagDefined(const Value: Boolean); begin fPurchaseTagDefined := value end; procedure TPromoDTO.setRewardTagDefined(const Value: Boolean); begin fRewardTagDefined := value end; procedure TPromoDTO.setStoreDefined(const Value: Boolean); begin fStoreDefined := value end; function TPromoDTO.getCustomerGroupDefined: Boolean; begin result := fCustomerGroupDefined end; procedure TPromoDTO.setCustomerGroupDefined(const Value: Boolean); begin fCustomerGroupDefined := value end; procedure TPromoDTO.addDiscountValidOnDayToList(arg_day: String); begin fDiscountValidOnDays.Add(arg_day); end; destructor TPromoDTO.destroy; begin freeAndNil(fpurchaseTagList); freeAndNil(fRewardTagList); freeAndNil(fCustomerList); freeAndNil(fStoreList); freeAndNil(fDiscountValidOnDays); inherited; end; procedure TPromoDTO.addCouponsToList(arg_coupon: String); begin fDiscountCoupons.Add(arg_coupon); end; function TPromoDTO.getCouponsDiscount: TStringList; begin result := fDiscountCoupons end; function TPromoDTO.getValidOnDaysDiscount: TStringList; begin result := fDiscountValidOnDays; end; function TPromoDTO.getIDStore: Integer; begin result := fIDStore end; procedure TPromoDTO.setIDStore(const Value: Integer); begin fIDStore := value end; function TPromoDTO.getSalePrice: Double; begin result := fSalePrice; end; procedure TPromoDTO.setSalePrice(const Value: Double); begin fSalePrice := value; end; function TPromoDTO.getIsBogo: boolean; begin result := fIsBogo; end; procedure TPromoDTO.setIsBogo(const value: boolean); begin fIsBogo := value; end; function TPromoDTO.getBuyAnd: boolean; begin result := self.FBuyAnd; end; procedure TPromoDTO.setBuyAnd(const value: boolean); begin self.FBuyAnd := value; end; { TDiscountQualifying } function TDiscountQualifying.getIDDiscount: Integer; begin result := fIDDiscount end; procedure TDiscountQualifying.setIDDiscount(arg_id: Integer); begin fIDDiscount := arg_id end; { TDiscountCustomerGroup } function TDiscountCustomerGroup.getIDTipoPessoa: Integer; begin result := fIDTipoPessoa end; function TDiscountCustomerGroup.getIDTipoPessoaStr: String; begin result := intToStr(fIdTipoPessoa); end; function TDiscountCustomerGroup.getName: String; begin result := fName; end; procedure TDiscountCustomerGroup.setIDTipoPessoa(arg_id: Integer); begin fIdTipoPessoa := arg_id end; procedure TDiscountCustomerGroup.setIDTipoPessoaStr(arg_id: String); begin fIdTipoPessoa := strToInt(arg_id) end; procedure TDiscountCustomerGroup.setName(arg_name: String); begin fName := arg_name; end; { TDiscountPurchase } function TDiscountPurchase.getIDTag: Integer; begin result := fIDTag end; function TDiscountPurchase.getName: String; begin result := fNameTag end; procedure TDiscountPurchase.setIDTag(arg_tag: Integer); begin fIDTag := arg_tag; end; procedure TDiscountPurchase.setName(arg_name: String); begin fNameTag := arg_name end; end.
unit ThNotifierList; interface uses Classes; type TThNotifierList = class(TPersistent) private FNotifierList: TList; FEventList: TList; protected property EventList: TList read FEventList; property NotifierList: TList read FNotifierList; public constructor Create; destructor Destroy; override; procedure Add(inEvent: TNotifyEvent); procedure Remove(inEvent: TNotifyEvent); procedure Notify; end; implementation { TThNotifierList } constructor TThNotifierList.Create; begin FNotifierList := TList.Create; FEventList := TList.Create; end; destructor TThNotifierList.Destroy; begin FNotifierList.Free; FEventList.Free; inherited; end; procedure TThNotifierList.Add(inEvent: TNotifyEvent); begin NotifierList.Add(TMethod(inEvent).Data); EventList.Add(TMethod(inEvent).Code); end; procedure TThNotifierList.Remove(inEvent: TNotifyEvent); var i: Integer; begin i := NotifierList.IndexOf(TMethod(inEvent).Data); if i >= 0 then begin NotifierList.Delete(i); EventList.Delete(i); end; end; procedure TThNotifierList.Notify; var i: Integer; e: TNotifyEvent; begin for i := 0 to Pred(NotifierList.Count) do begin TMethod(e).Data := NotifierList[i]; TMethod(e).Code := EventList[i]; e(Self); end; end; end.
unit AdvXmlBuilders; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface Uses SysUtils, Classes, StringSupport, EncodeSupport, AdvStreams, AdvVCLStreams, AdvBuffers, AdvObjects, AdvXmlFormatters, AdvMemories, AdvStringMatches, XmlBuilder, IdSoapMsXml; Type TAdvXmlBuilder = class (TXmlBuilder) private mem : TAdvMemoryStream; buf : TAdvBuffer; xml : TAdvXMLFormatter; wantDefineNS : boolean; namespaces : TAdvStringMatch; function getNSRep(uri, name : String):String; protected procedure SetNamespace(const Value: String); override; Public constructor Create; override; destructor Destroy; override; procedure defineNS(abbrev, uri : String); Procedure Start(); overload; override; Procedure StartFragment; override; Procedure Finish; override; Procedure Build(oStream: TStream); Overload; override; Procedure Build(oStream: TAdvStream); Overload; override; Function Build : String; Overload; override; Function SourceLocation : TSourceLocation; override; Procedure Comment(Const sContent : WideString); override; Procedure AddAttribute(Const sName, sValue : WideString); override; Procedure AddAttributeNS(Const sNamespace, sName, sValue : WideString); override; function Tag(Const sName : WideString) : TSourceLocation; override; function Open(Const sName : WideString) : TSourceLocation; override; Procedure Close(Const sName : WideString); override; function Text(Const sValue : WideString) : TSourceLocation; override; function Entity(Const sValue : WideString) : TSourceLocation; override; function TagText(Const sName, sValue : WideString) : TSourceLocation; override; Procedure WriteXml(iElement : IXMLDomElement); override; End; implementation Procedure TAdvXmlBuilder.Start; var i: Integer; begin buf := TAdvBuffer.Create; mem := TAdvMemoryStream.Create; mem.Buffer := buf.Link; xml := TAdvXMLFormatter.Create; xml.HasWhitespace := IsPretty; xml.Stream := mem.Link; xml.AddAttribute('encoding', 'UTF-8'); xml.ProduceHeader; wantDefineNS := Namespace <> ''; for i := 0 to namespaces.Count - 1 do xml.AddNamespace(namespaces.ValueByIndex[i], namespaces.KeyByIndex[i]); end; Procedure TAdvXmlBuilder.StartFragment; begin raise Exception.Create('Not Supported yet'); end; Procedure TAdvXmlBuilder.Finish; begin xml.Free; xml := nil; mem.Free; mem := nil; end; function TAdvXmlBuilder.getNSRep(uri, name: String): String; begin if (uri = namespace) then result := name else if namespaces.ExistsByKey(uri) then result := namespaces.Matches[uri]+':'+name else raise Exception.Create('Unregistered namespace '+uri); end; Procedure TAdvXmlBuilder.Build(oStream: TStream); begin buf.SaveToStream(oStream); end; Procedure TAdvXmlBuilder.Build(oStream: TAdvStream); begin buf.SaveToStream(oStream); end; Function TAdvXmlBuilder.Build : String; begin result := buf.AsUnicode; end; Function TAdvXmlBuilder.SourceLocation : TSourceLocation; begin result.line := 0; //xml.line; result.col := 0; //xml.col; end; Procedure TAdvXmlBuilder.Comment(Const sContent : WideString); begin xml.ProduceComment(sContent); end; constructor TAdvXmlBuilder.create; begin inherited; namespaces := TAdvStringMatch.Create; end; procedure TAdvXmlBuilder.defineNS(abbrev, uri: String); begin namespaces.Add(uri, abbrev); end; destructor TAdvXmlBuilder.destroy; begin namespaces.Free; buf.Free; inherited; end; Procedure TAdvXmlBuilder.AddAttribute(Const sName, sValue : WideString); begin xml.AddAttribute(sName, sValue); end; Procedure TAdvXmlBuilder.AddAttributeNS(Const sNamespace, sName, sValue : WideString); begin xml.AddAttribute(getNSRep(sNamespace, sName), sValue); end; function TAdvXmlBuilder.Tag(Const sName : WideString) : TSourceLocation; begin if wantDefineNS then begin xml.AddNamespace('', Namespace); wantDefineNS := false; end; xml.ProduceTag(sName); result.line := 0; //xml.line; result.col := 0; //xml.col; end; function TAdvXmlBuilder.Open(Const sName : WideString) : TSourceLocation; begin if wantDefineNS then begin xml.AddNamespace('', Namespace); wantDefineNS := false; end; xml.ProduceOpen(sName); result.line := 0; //xml.line; result.col := 0; //xml.col; end; Procedure TAdvXmlBuilder.Close(Const sName : WideString); begin wantDefineNS := false; xml.ProduceClose(sName); end; function HtmlTrim(s: String):String; begin if s = '' then result := '' else begin result := StringTrimSet(s, [' ', #13, #10, #9]); if result = '' then result := ' '; end; end; function TAdvXmlBuilder.Text(Const sValue : WideString) : TSourceLocation; begin if IsPretty then xml.ProduceText(HtmlTrim(sValue)) else xml.ProduceText(sValue); result.line := 0; //xml.line; result.col := 0; //xml.col; end; procedure TAdvXmlBuilder.WriteXml(iElement: IXMLDomElement); begin raise Exception.Create('Not supported yet'); end; function TAdvXmlBuilder.Entity(Const sValue : WideString) : TSourceLocation; begin raise Exception.Create('entities not supported'); end; function TAdvXmlBuilder.TagText(Const sName, sValue : WideString) : TSourceLocation; begin if wantDefineNS then begin xml.AddNamespace('', Namespace); wantDefineNS := false; end; if IsPretty then xml.ProduceText(sName, StringTrimWhitespace(sValue)) else xml.ProduceText(sName, sValue); result.line := 0; //xml.line; result.col := 0; //xml.col; end; (*function TAdvXmlBuilder.setDefaultNS(uri: String): String; begin result := defnamespace; defnamespace := uri; xml.AddNamespace('', uri); end; procedure TAdvXmlBuilder.unsetDefaultNS(uri: String); begin defnamespace := uri; end; *) procedure TAdvXmlBuilder.SetNamespace(const Value: String); begin inherited; wantDefineNS := true; end; end.
unit Metric; interface uses Math; type TMetric = class private FData: array of Single; FDimension: Cardinal; FSize: Cardinal; FOrthogonal: boolean; protected // Gets function GetDimension: Cardinal; function GetData(_x,_y: Cardinal): single; function QuickGetData(_x,_y: Cardinal): single; function GetMaxElement: Cardinal; function GetMaxX: Cardinal; // Sets procedure SetDimension(_Dimension: cardinal); procedure SetData(_x,_y: Cardinal; _Value: single); procedure QuickSetData(_x,_y: Cardinal; _Value: single); public // Constructors and Destructors constructor Create; overload; constructor Create(_Dimension: integer); overload; constructor Create(_Source: TMetric); overload; destructor Destroy; override; // Gets // function IsOrthogonal: boolean; // Clone/Copy/Assign procedure Assign(_Source: TMetric); // Properties property Dimension: cardinal read GetDimension write SetDimension; property MaxX: cardinal read GetMaxX; property MaxY: cardinal read GetMaxX; property Data[_x,_y:Cardinal]:single read GetData write SetData; property UnsafeData[_x,_y:Cardinal]:single read QuickGetData write QuickSetData; property Orthogonal:boolean read FOrthogonal write FOrthogonal; end; implementation // Constructors and Destructors constructor TMetric.Create; begin FDimension := 0; Dimension := 4; // SetDimension(4); end; constructor TMetric.Create(_Dimension: Integer); begin FDimension := 0; Dimension := _Dimension; // SetDimension(_Dimension); end; constructor TMetric.Create(_Source: TMetric); begin FDimension := 0; Assign(_Source); end; destructor TMetric.Destroy; begin SetLength(FData,0); inherited Destroy; end; // Gets function TMetric.GetDimension: cardinal; begin Result := FDimension; end; function TMetric.GetMaxElement: cardinal; begin Result := FSize - 1; end; function TMetric.GetMaxX: cardinal; begin Result := FDimension - 1; end; function TMetric.GetData(_x,_y: Cardinal): single; begin if (_x < FDimension) and (_y < FDimension) then begin Result := FData[_x+(FDimension * _y)]; end else begin Result := 0; end; end; function TMetric.QuickGetData(_x,_y: Cardinal): single; begin Result := FData[_x+(FDimension * _y)]; end; { // What the hell is that? function TMetric.IsOrthogonal: boolean; var counter,i,j : cardinal; begin Result := true; for i := 0 to GetMaxX do begin counter := 0; for j := 0 to GetMaxX do begin if QuickGetData(i,j) <> 0 then begin inc(counter); if counter > 1 then exit; end; end; end; Result := false; end; } // Sets procedure TMetric.SetDimension(_Dimension: cardinal); var BackupData: array of Single; NewSize,i,j : cardinal; begin if _Dimension <> FDimension then begin if FDimension > 0 then begin NewSize := _Dimension * _Dimension; SetLength(BackupData,FSize); for i := Low(FData) to High(FData) do begin BackupData[i] := FData[i]; end; SetLength(FData,NewSize); for i := 0 to Min(FDimension,_Dimension) - 1 do for j := 0 to Min(FDimension,_Dimension) - 1 do begin FData[i+(_Dimension * j)] := BackupData[i+(FDimension*j)]; end; SetLength(BackupData,0); FDimension := _Dimension; FSize := NewSize; end else begin FDimension := _Dimension; FSize := _Dimension * _Dimension; SetLength(FData,FSize); for i := 0 to FSize - 1 do begin FData[i] := 0; end; for i := 0 to FDimension - 1 do begin FData[i + (i*FDimension)] := 1; end; end; end; end; procedure TMetric.SetData(_x,_y: Cardinal; _Value: single); begin if (_x < FDimension) and (_y < FDimension) then begin FData[_x+(FDimension * _y)] := _Value; end; end; procedure TMetric.QuickSetData(_x,_y: Cardinal; _Value: single); begin FData[_x+(FDimension * _y)] := _Value; end; // Clone/Copy/Assign procedure TMetric.Assign(_Source: TMetric); var x,y : cardinal; begin Dimension := _Source.Dimension; for x := 0 to FDimension - 1 do for y := 0 to FDimension - 1 do begin QuickSetData(x,y,_Source.QuickGetData(x,y)); end; end; end.
unit FileUnit; interface procedure saveTextToFile(const fileName : string; const sourceText : string); function loadTextFromFile(const fileName : string) : string; implementation uses System.SysUtils; procedure saveTextToFile(const fileName : string; const sourceText : string); var T : Text; begin AssignFile(T, fileName); rewrite(T); writeln(T, sourceText); closeFile(T); end; function loadTextFromFile(const fileName : string) : string; var T : text; buffer, resultString : string; begin buffer := ''; AssignFile(T, fileName); resultString := ''; if fileExists(fileName) then begin reset(T); while not Eof(T) do begin readln(T, buffer); resultString := resultString + buffer + ' '; end; CloseFile(T); end; Result := resultString; end; end.
unit InflatablesList_Item_IO; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Classes, Graphics, AuxTypes, InflatablesList_Item_Search; const IL_ITEM_SIGNATURE = UInt32($4D455449); // ITEM IL_ITEM_STREAMSTRUCTURE_00000008 = UInt32($00000008); IL_ITEM_STREAMSTRUCTURE_00000009 = UInt32($00000009); IL_ITEM_STREAMSTRUCTURE_0000000A = UInt32($0000000A); IL_ITEM_STREAMSTRUCTURE_SAVE = IL_ITEM_STREAMSTRUCTURE_0000000A; IL_ITEM_DECRYPT_CHECK = UInt64($53444E454D455449); // ITEMENDS type TILItem_IO = class(TILItem_Search) protected fFNSaveToStream: procedure(Stream: TStream) of object; fFNLoadFromStream: procedure(Stream: TStream) of object; fFNSavePicture: procedure(Stream: TStream; Pic: TBitmap) of object; fFNLoadPicture: procedure(Stream: TStream; out Pic: TBitmap) of object; procedure InitSaveFunctions(Struct: UInt32); virtual; abstract; procedure InitLoadFunctions(Struct: UInt32); virtual; abstract; procedure Save(Stream: TStream; Struct: UInt32); virtual; procedure Load(Stream: TStream; Struct: UInt32); virtual; public procedure SaveToStream(Stream: TStream); virtual; procedure LoadFromStream(Stream: TStream); virtual; procedure SaveToFile(const FileName: String); virtual; procedure LoadFromFile(const FileName: String); virtual; end; implementation uses SysUtils, BinaryStreaming, StrRect; procedure TILItem_IO.Save(Stream: TStream; Struct: UInt32); begin InitSaveFunctions(Struct); fFNSaveToStream(Stream); end; //------------------------------------------------------------------------------ procedure TILItem_IO.Load(Stream: TStream; Struct: UInt32); begin fEncryptedData.Data := PtrInt(Struct); InitLoadFunctions(Struct); fFNLoadFromStream(Stream); end; //============================================================================== procedure TILItem_IO.SaveToStream(Stream: TStream); var SelectedStruct: UInt32; begin Stream_WriteUInt32(Stream,IL_ITEM_SIGNATURE); If fEncrypted and not fDataAccessible then SelectedStruct := UInt32(fEncryptedData.Data) else SelectedStruct := IL_ITEM_STREAMSTRUCTURE_SAVE; Stream_WriteUInt32(Stream,SelectedStruct); Save(Stream,SelectedStruct); end; //------------------------------------------------------------------------------ procedure TILItem_IO.LoadFromStream(Stream: TStream); begin If Stream_ReadUInt32(Stream) = IL_ITEM_SIGNATURE then Load(Stream,Stream_ReadUInt32(Stream)) else raise Exception.Create('TILItem_IO.LoadFromStream: Invalid stream.'); end; //------------------------------------------------------------------------------ procedure TILItem_IO.SaveToFile(const FileName: String); var FileStream: TMemoryStream; begin FileStream := TMemoryStream.Create; try SaveToStream(FileStream); FileStream.SaveToFile(StrToRTL(FileName)); finally FileStream.Free; end; end; //------------------------------------------------------------------------------ procedure TILItem_IO.LoadFromFile(const FileName: String); var FileStream: TMemoryStream; begin FileStream := TMemoryStream.Create; try FileStream.LoadFromFile(StrToRTL(FileName)); FileStream.Seek(0,soBeginning); LoadFromStream(FileStream); finally FileStream.Free; end; end; end.
unit PhpController; interface uses Controls, EasyEditState, LrDockUtils, LrDocument, RawDocument, PhpEditView, PhpView; type TPhpDocument = TRawDocument; // TPhpController = class(TLrController) private FDocument: TPhpDocument; protected function GetView: TPhpViewForm; procedure SetDocument(const Value: TPhpDocument); protected TabState: TDockTabsState; EditState: TEasyEditState; LastFocus: TWinControl; public { Public declarations } constructor Create(inDocument: TPhpDocument); reintroduce; destructor Destroy; override; procedure Activate; override; procedure Deactivate; override; procedure LazyUpdate; override; public property Document: TPhpDocument read FDocument write SetDocument; property View: TPhpViewForm read GetView; end; implementation uses LrUtils, Main; constructor TPhpController.Create(inDocument: TPhpDocument); begin inherited Create(nil); Document := inDocument; TabState := TDockTabsState.Create(View); EditState := TEasyEditState.Create; end; destructor TPhpController.Destroy; begin EditState.Free; TabState.Free; inherited; end; function TPhpController.GetView: TPhpViewForm; begin Result := MainForm.PhpView; end; procedure TPhpController.SetDocument(const Value: TPhpDocument); begin FDocument := Value; end; procedure TPhpController.Activate; begin View.PhpEditForm.Strings := Document.Strings; View.PhpEditForm.OnModified := Document.ChangeEvent; // // View.ShowDocks; // ActivateDock(View.CodeDock); // TabState.Restore; // if (LastFocus <> nil) and LastFocus.CanFocus then LastFocus.SetFocus; // EditState.SetState(View.PhpEditForm.Edit); end; procedure TPhpController.Deactivate; begin LazyUpdate; TabState.Capture; LastFocus := MainForm.LastEditor; EditState.GetState(View.PhpEditForm.Edit); end; procedure TPhpController.LazyUpdate; begin Document.Strings.Assign(View.PhpEditForm.Source.Strings) end; end.
program Carre_Magique; uses crt; const MAX=5; Type Tableau2dim=Array[1..MAX,1..MAX]of integer; procedure deplacement; var i,j:integer; T :Tableau2dim; begin end; procedure placement_un; var i,j:integer; T :Tableau2dim; begin GotoXY(MAX,2); write('1'); end; procedure initialisation(T:Tableau2dim); var i:integer; j:integer; Begin for i:=1 to MAX do Begin for j:=1 to MAX do Begin T[i,j]:=0; write(T[i,j],' '); end; writeln; end; end; var i,j,nombre:integer; Matrice:array[1..MAX,1..MAX]of integer; BEGIN clrscr; initialisation(matrice); placement_un; readln; END. (* ALGORITHME : carre_magique (input,output) BUT : Créer un carré magique de taille impair définis en constante. ENTREE : SORTIE : un carré magique Const MAX = 5 : ENTIER Type Tableau2dim=Array[1..MAX,1..MAX] de type ENTIER; procedure deplacement; var i,j:ENTIER; T :Tableau2dim; DEBUT FIN procedure placement_un; var i,j:ENTIER; T :Tableau2dim; DEBUT GotoXY(MAX,2); ECRIRE('1'); FIN procedure initialisation(T:Tableau2dim); var i:ENTIER; j:ENTIER; DEBUT POUR i DE 1 A MAX FAIRE DEBUT POUR j DE 1 A MAX FAIRE DEBUT T[i,j]<-0; ECRIRE(T[i,j],' ') FINPOUR FINPOUR FIN var i,j,nombre:ENTIER; Matrice:TABLEAU[1..MAX,1..MAX] de type ENTIER; DEBUT initialisation(matrice); placement_un; deplacement; FIN. *) (*Note For (nombre:=1) to (MAX*MAX) do Suites d'action : Initialiser > Avancer > Detecter vide > placer > afficher > Avancer gauche > corriger >Avancer Droite *)
{ unit UniqueInstance; } { } { Check if previous application instance exists, if yes, the previous } { instance will be active, and current instance will be terminate. } { } { written by savetime, http://savetime.delphibbs.com 2004/6/27 } { } { Usage: } { Include this unit to your delphi project, no more job to do. } { } { Important: } { You must NOT remove the project line: Application.Initialize; } { } { Notes: } { This unit identify an application by it's EXE file name. So, if you want } { to specify another unique application name, you must change the value } { UniqueApplicationName in CheckPriviousInstance procedure. } { } unit UniqueInstance; interface uses Classes, SysUtils, Windows, Forms; implementation var UniqueMessageID: UINT; UniqueMutexHandle: THandle; PreviousWndProc: TFNWndProc; NextInitProc: Pointer; function ApplicationWndProc(hWnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LResult; stdcall; begin // Note: Use "<>" may boost application speed. if uMsg <> UniqueMessageID then Result := CallWindowProc(PreviousWndProc, hWnd, uMsg, wParam, lParam) else begin if IsIconic(Application.Handle) then Application.Restore; SetForegroundWindow(Application.Handle); Result := 0; end; end; procedure BringPreiviousInstanceForeground; const BSMRecipients: DWORD = BSM_APPLICATIONS; begin BroadcastSystemMessage(BSF_IGNORECURRENTTASK or BSF_POSTMESSAGE, @BSMRecipients, UniqueMessageID, 0, 0); Halt; end; procedure SubClassApplication; begin PreviousWndProc := TFNWndProc(SetWindowLong(Application.Handle, GWL_WNDPROC, Integer(@ApplicationWndProc))); end; procedure CheckPreviousInstance; var UniqueApplicationName: PChar; begin // Unique application name, default set to EXE file name, // you can change it to yourself. UniqueApplicationName := PChar(ExtractFileName(Application.ExeName)); // Register unique message id UniqueMessageID := RegisterWindowMessage(UniqueApplicationName); // Create mutex object UniqueMutexHandle := CreateMutex(nil, False, UniqueApplicationName); // Create mutex failed, terminate application if UniqueMutexHandle = 0 then Halt // The same named mutex exists, show previous instance else if GetLastError = ERROR_ALREADY_EXISTS then BringPreiviousInstanceForeground // No previous instance, subclass application window else SubClassApplication; // Call next InitProc if NextInitProc <> nil then TProcedure(NextInitProc); end; initialization // Must use InitProc to check privious instance, // as the reason of Application hasn't been created! NextInitProc := InitProc; InitProc := @CheckPreviousInstance; finalization // Close the mutex handle if UniqueMutexHandle <> 0 then CloseHandle(UniqueMutexHandle); end.
{****************************************************************************** lazbbosversion - Returns OS version information (Windows, Linux and Mac Component version, replace previous units sdtp - bb - january 2023 Some windows functions and windows structures are dynamically loaded in lazbbosversiobnabse unit Localization data in application .lng file ******************************************************************************} unit lazbbOsVersion; {$mode ObjFPC}{$H+} interface uses {$IFDEF WINDOWS} Windows, {$ELSE} process, {$ENDIF} Classes, SysUtils, LResources, lazbbosversionbase, lazbbinifiles; type TbbOsVersion = class(TComponent) private FPID : Integer; {platform ID} FVerMaj, FVerMin, FVerBuild: Integer; FVerSup : String; FSrvPMaj, fSrvPMin: Word; FVerMask : Integer; fProdTyp, fReserved: BYTE; FVerTyp, FVerPro : Integer; FVerProd: String; fOSName: string; fArchitecture: string; FVerDetail: string; //Description of the OS, with version, build etc. // Unix fKernelName: string; fKernelRelease: string; fKernelVersion: string; fNetworkNode: string; Init: Boolean; {$IFDEF WINDOWS} fProdStrs: TStrings; fWin10Strs: TStrings; fWin11Strs: Tstrings; procedure SetProdStrs(const value: TStrings); procedure SetWin10Strs(const value: TStrings); procedure SetWin11Strs(const value: TStrings); procedure ListChanged(Sender: Tobject); function IsWin64: Boolean; procedure GetNT32Info; {$ENDIF} protected public constructor Create(aOwner: Tcomponent); override; destructor Destroy; override; procedure GetSysInfo; procedure Translate(LngFile: TBbIniFile); published {$IFDEF WINDOWS} property VerMaj: integer read FVerMaj; // major version number property VerMin: integer read FVerMin; // Minor version number property VerBuild: integer read FVerBuild; // Build number property VerSup : String read FVerSup; // Additional version information property VerMask : Integer read FVerMask; // Product suite mask; property VerTyp: integer read FVerTyp; // Windows type property VerProd : String read FVerProd; // Version type property ProdStrs: TStrings read fProdStrs write SetProdStrs; property Win10Strs: TStrings read fWin10Strs write SetWin10Strs; property Win11Strs: TStrings read fWin11Strs write SetWin11Strs; {$ELSE} property KernelName: string read FKernelName; property KernelRelease: string read FKernelRelease; property KernelVersion: string read FKernelVersion; property NetworkNode: string read FNetworkNode; {$ENDIF} property OSName: string read FOSName; property Architecture: string read fArchitecture; property VerDetail: string read FVerDetail; //Description of the OS, with version, build etc. end; {$IFDEF WINDOWS} const // Valeurs en hexa pour info ProdStrEx: array [0..$A3] of String =('Unknown product', //00 'Ultimate Edition', //01 'Home Basic Edition', //02 'Home Premium Edition', //03 'Enterprise', //04 'Home Basic Edition', //05 'Business', //06 'Server Standard Edition (full installation)', //07 'Server Datacenter (full installation)', //08 'Small Business Server', //09 'Server Enterprise Edition (full installation)', //0A 'Starter Edition', //0B 'Server Datacenter (core installation)', //0C 'Server Standard Edition (core installation)', //0D 'Server Enterprise Edition (core installation)', //0E 'Server Enterprise Edition for Itanium-based Systems', //0F 'Business N', //10 'Web Server Edition', //11 'Cluster Server', //12 'Home Server Edition', //13 'Storage Server Express Edition', //14 'Storage Server Standard Edition', //15 'Storage Server Workgroup Edition', //16 'Storage Server Enterprise Edition', //17 'Server for Small Business Edition', //18 'Small Business Server Premium Edition', //19 'Home Premium Edition', //1A 'Enterprise N', //1B 'Ultimate Edition', //1C 'Web Server (core installation)', //1D 'Windows Essential Business Server Management Server', //1E 'Windows Essential Business Server Security Server', //1F 'Windows Essential Business Server Messaging Server', //20 'Server Foundation', //21 'Windows Home Server 2011', //22 'Windows Server 2008 without Hyper-V for Windows Essential Server Solutions', //23 'Server Standard without Hyper-V', //24 'Server Datacenter without Hyper-V (full installation)', //25 'Server Enterprise without Hyper-V (full installation)', //26 'Server Datacenter without Hyper-V (core installation)', //27 'Server Standard without Hyper-V (core installation)', //28 'Server Enterprise without Hyper-V (core installation)', //29 'Microsoft Hyper-V Server', //2A 'Storage Server Express (core installation)', //2B 'Storage Server Standard (core installation)', //2C 'Storage Server Workgroup (core installation)', //2D 'Storage Server Enterprise (core installation)', //2E 'Starter N', //2F 'Professional', //30 'Professional N', //31 'Windows Small Business Server 2011 Essentials', //32 'Server For SB Solutions', //33 'Server Solutions Premium', //34 'Server Solutions Premium (core installation)', //35 'Server For SB Solutions EM', //36 'Server For SB Solutions EM', //37 'Windows MultiPoint Server', //38 'Unknown', //39 'Unknown', //3A 'Windows Essential Server Solution Management', //3B 'Windows Essential Server Solution Additional', //3C 'Windows Essential Server Solution Management SVC', //3D 'Windows Essential Server Solution Additional SVC', //3E 'Small Business Server Premium (core installation)', //3F 'Server Hyper Core V', //40 'Unknown', //41 'Not supported', //42 'Not supported', //43 'Not supported', //44 'Not supported', //45 'Enterprise E', //46 'Not supported', //47 'Enterprise (evaluation)', //48 'Unknown', //49 'Unknown', //4A 'Unknown', //4B 'Windows MultiPoint Server Standard (full)', //4C 'Windows MultiPoint Server Premium (full)', //4D 'Unknown', //4E 'Server Standard (evaluation)', //4F 'Server Datacenter (evaluation)', //50 'Unknown', //51 'Unknown', //52 'Unknown', //53 'Enterprise N (evaluation)', //54 'Unknown', //55 'Unknown', //56 'Unknown', //57 'Unknown', //58 'Unknown', //59 'Unknown', //5A 'Unknown', //5B 'Unknown', //5C 'Unknown', //5D 'Unknown', //5E 'Storage Server Workgroup (evaluation)', //5F 'Storage Server Standard (evaluation)', //60 'Unknown', //61 'Home N', //62 'Home China', //63 'Home Single Language', //64 'Home', //65 'Unknown', //66 'Professional with Media Center', //67 'Unlicensed product', //68 'Unknown', //69 'Unknown', //6A 'Unknown', //6B 'Unknown', //6C 'Unknown', //6D 'Unknown', //6E 'Unknown', //6F 'Unknown', //70 'Unknown', //71 'Unknown', //72 'Unknown', //73 'Unknown', //74 'Unknown', //75 'Unknown', //76 'Unknown', //77 'Unknown', //78 'Education', //79 'Education N', //7A 'Unknown', //7B 'Unknown', //7C 'Enterprise 2015 LTSB', //7D 'Enterprise 2015 LTSB N', //7E 'Unknown', //7F 'Unknown', //80 'Enterprise 2015 LTSB (evaluation)', //81 'Unknown', //82 'Unknown', //83 'Unknown', //84 'Unknown', //85 'Unknown', //86 'Unknown', //87 'Unknown', //88 'Unknown', //89 'Unknown', //8A 'Unknown', //8B 'Unknown', //8C 'Unknown', //8D 'Unknown', //8E 'Unknown', //8F 'Unknown', //90 'Server Datacenter, Semi-Annual Channel (core)', //91 'Server Standard, Semi-Annual Channel (core)', //92 'Unknown', //93 'Unknown', //94 'Unknown', //95 'Unknown', //96 'Unknown', //97 'Unknown', //98 'Unknown', //99 'Unknown', //9A 'Unknown', //9B 'Unknown', //9C 'Unknown', //9D 'Unknown', //9E 'Unknown', //9F 'Unknown', //A0 'Pro for Workstations', //A1 'Windows 10 Pro for Workstations', //A2 'Unknown'); //A3 StatStr: array of String = ('Microsoft Windows 32', 'Microsoft Windows 95', 'Microsoft Windows 95-OSR2', 'Microsoft Windows 98', 'Microsoft Windows 98 SE', 'Microsoft Windows ME', 'Microsoft Windows NT 3.5', 'Microsoft Windows NT 4', 'Microsoft Windows 2000', 'Microsoft Windows XP', 'Microsoft Windows Server 2003', 'Microsoft Windows Vista', 'Microsoft Windows Server 2008', 'Microsoft Windows Server 2008 R2', 'Microsoft Windows 7', 'Microsoft Windows 8', 'Microsoft Windows Server 2012', 'Microsoft Windows 8.1', 'Windows Server 2012 R2', 'Microsoft Windows 10', 'Windows Server 2016', 'Windows Server 2019', 'Microsoft Windows 11', 'Windows Server 2022', 'Système inconnu'); ProductStrs= ''+LineEnding+ 'Home'+LineEnding+ 'Professional'+LineEnding+ 'Server'; // First element: build number, second element: english Windows10Strs = '00000=Unknown version'+LineEnding+ '10240=v 1507 "July 2015 update"'+LineEnding+ '10586=v 1511 "November 2015 update"'+LineEnding+ '14393=v 1607 "July 2016 (Anniversary update)"'+LineEnding+ '15063=v 1703 "April 2017 (Creators update)"'+LineEnding+ '16299=v 1709 "October 2017 (Fall Creators update)"'+LineEnding+ '17134=v 1803 "April 2018 update"'+LineEnding+ '17763=v 1809 "October 2018 update"'+LineEnding+ '18362=v 1903 "May 2019 update"'+LineEnding+ '18363=v 1909 "November 2019 update"'+LineEnding+ '19041=v 2004 "May 2020 update"'+LineEnding+ '19042=v 20H2 "October 2020 update"'+LineEnding+ '19043=v 21H1 "May 2021 update"'+LineEnding+ '19044=v 21H2 "November 2021 update"'+LineEnding+ '19045=v 22H2 "October 2022 update"'; Windows11Strs = '00000=Unknown version'+LineEnding+ '22000=v 21H2 "October 2021 Initial version"'+LineEnding+ '22621=v 22H2 "September 2022 update"'; var fVerProEx: DWORD; {$ENDIF} procedure Register; implementation procedure Register; begin {$I lazbbosversion_icon.lrs} RegisterComponents('lazbbcomponents',[TbbOsVersion]); end; constructor TbbOsVersion.Create(aOwner: Tcomponent); begin inherited Create(aOwner); // Initialize variables FVerMaj:=0; FVerMin:=0; FVerBuild:=0; FVerSup:=''; FVerMask:=0; FVerTyp:=0 ; FVerProd:=''; FOSName:=''; fArchitecture:=''; FKernelName:=''; FKernelRelease:=''; FKernelVersion:=''; FNetworkNode:=''; FVerDetail:=''; {$IFDEF WINDOWS} // Create and populate product type list property to allow further translation fProdStrs:= TstringList.Create; TStringList(fProdStrs).OnChange:= @ListChanged; fProdStrs.Text:= ProductStrs; // Create and populate Windows 10 version list property fWin10Strs:= TstringList.Create; TStringList(fWin10Strs).OnChange:= @ListChanged; fWin10Strs.Text:= Windows10Strs; // Windows 11 fWin11Strs:= TstringList.Create; TStringList(fWin11Strs).OnChange:= @ListChanged; fWin11Strs.Text:= Windows11Strs; {$ENDIF} init:= true; GetSysInfo; end; destructor TbbOsVersion.Destroy; begin {$IFDEF WINDOWS} if assigned(fProdStrs) then fProdStrs.free; if assigned(fWin10Strs) then fWin10Strs.free; if assigned(fWin11Strs) then fWin11Strs.free; {$ENDIF} inherited; end; {$IFDEF WINDOWS} procedure TbbOsVersion.SetProdStrs(const value: TStrings); begin if fProdStrs<>value then begin fProdStrs.Assign(value); end; end; procedure TbbOsVersion.SetWin10Strs(const value: TStrings); begin if fWin10Strs<>value then fWin10Strs.Assign(value); end; procedure TbbOsVersion.SetWin11Strs(const value: TStrings); begin if fWin11Strs<>value then fWin11Strs.Assign(value); end; procedure TbbOsVersion.ListChanged(Sender: Tobject); begin // Be sure all is intialized if init then GetSysInfo; end; function TbbOsVersion.IsWin64: Boolean; {$IFDEF WIN32} type TIsWow64Process = function(Handle: Windows.THandle; var Res: Windows.BOOL): Windows.BOOL; stdcall; var IsWOW64: Windows.BOOL; IsWOW64Process: TIsWow64Process; {$ENDIF} begin {$IFDEF WIN32} // Try to load required function from kernel32 IsWOW64Process := TIsWow64Process(Windows.GetProcAddress(Windows.GetModuleHandle('kernel32'), 'IsWow64Process')); if Assigned(IsWOW64Process) then begin // Function exists if not IsWOW64Process(Windows.GetCurrentProcess, IsWOW64) then Result:=False else Result:=IsWOW64; end else // Function not implemented: can't be running on Wow64 Result := False; {$ELSE} //if were running 64bit code, OS must be 64bit !) Result := True; {$ENDIF} end; procedure TbbOSVersion.GetSysInfo; var OsViEx : TOSVersionInfoEx; begin fVerProEx:= 0; // Free Pascal GetVersionEx function use OSVersionInfo structure instead OSVersionInfoEx, // So, we have redefined it OsViEx:= Default(TOSVersionInfoEx); OsViEx.dwOSVersionInfoSize:= SizeOf(TOSVersionInfoEx); // Before W2000 this function doesn't exists; so we exit if not (assigned(GetVersionEx) and GetVersionEx (OsViEx)) then exit; With OsViEx do begin fVerMaj:=dwMajorVersion; fVerMin:=dwMinorVersion; fVerBuild:= dwBuildNumber and $FFFF; fVerSup:= StrPas(szCSDVersion); fPid:= dWPlatformID; fSrvPMaj:= wServicePackMajor; fSrvPMin:= wServicePackMinor; fVerMask:= wSuiteMask; fProdTyp:= wProductType; fReserved:= wReserved; // Inconnu par défaut fVerTyp:= High(StatStr); Case fPid of 0 : fVerTyp:= 0; // Win32s 1 : If fVerMin < 10 then begin If fVerBuild <= 1000 then fVerTyp:= 1 // win95 4.00 build 950 else fVerTyp:= 2; // Win95-OSR2 4.00 950c end else begin if (fVerBuild >= 0) and (fVerBuild < 2000) then fVerTyp:= 3; // Win98 4.10 build 1999 if (fVerBuild >= 2000) and (fVerBuild < 3000) then fVerTyp:= 4; // Win98 SE 4.10 build 2222 if fVerBuild >= 3000 then fVerTyp:= 5 ; //Win ME 4.90 build 3000 end; 2: begin //VER_PLATFORM_WIN32_NT GetNT32Info; end; end; end; FOSName:= StatStr[High(StatStr)]; if (fVerTyp < High(StatStr)) then FOSName:= StatStr[fVerTyp]; try if fVerProEx > 0 then fVerProd:= ProdStrEx[fVerProEx] else fVerProd:= ProdStrs.Strings[fVerPro];//ProdStr[fVerPro]; except fVerProd:= ProdStrs.Strings[0];//ProdStr[0]; end; if IsWin64 then fArchitecture:= 'x86_64' else fArchitecture:= 'x86'; fVerDetail:= fOSName+' '+fVerProd+' - '+IntToStr(fVerMaj)+'.'+IntToStr(fVerMin) +'.'+IntToStr(fVerBuild)+' - '+fVerSup+' - '+fArchitecture; end; procedure TbbOSVersion.GetNT32Info ; var dwOSMajorVersion, dwOSMinorVersion, dwSpMajorVersion, dwSpMinorVersion: DWORD; A: TStringArray; i: integer; begin dwOSMajorVersion:= 0; dwOSMinorVersion:= 0; dwSpMajorVersion:= 0; dwSpMinorVersion:= 0; case fVerMaj of 3: fVerTyp:= 6; //NT 3.5 4: fVerTyp:= 7; //NT 4 5: case fVerMin of 0: begin fVerTyp:= 8; // W2000 if fProdTyp=VER_NT_WORKSTATION then fVerPro:= 2 // Professional else fVerPro:= 3; // Server end; 1: begin fVerTyp:= 9; // Windows XP if (fVerMask and VER_SUITE_PERSONAL) = VER_SUITE_PERSONAL then fVerPro:= 1 //Home Edition else fVerPro:= 2; //Professional end; 2: fVerTyp:= 10; // Windows Server 2003 end; 6: begin if Assigned(GetProductInfo) then begin GetProductInfo( dwOSMajorVersion, dwOSMinorVersion, dwSpMajorVersion, dwSpMinorVersion, fVerProEx ); if fVerProEx = $ABCDABCD then fVerProEx:= High(ProdStrEx); end; case fVerMin of 0: if fProdTyp= VER_NT_WORKSTATION then // Windows Vista begin fVerTyp:= 11; // Windows Vista if (fVerMask and VER_SUITE_PERSONAL)=VER_SUITE_PERSONAL then fVerPro:= 1 //Home Edition else fVerPro:= 2; //Professional end else fVerTyp:= 12; // Windows Server 2008 1: if fProdTyp=VER_NT_WORKSTATION then begin fVerTyp:= 14; // Windows 7 if (fVerMask and VER_SUITE_PERSONAL)=VER_SUITE_PERSONAL then fVerPro:= 1 //Home Edition else fVerPro:= 2; //Professional end else fVerTyp:= 13; // Windows Server 2008 RC2 2: if fProdTyp =VER_NT_WORKSTATION then begin fVerTyp:= 15; // Windows 8 if (fVerMask and VER_SUITE_PERSONAL)=VER_SUITE_PERSONAL then fVerPro:= 1 //Home Edition else fVerPro:= 2; //Professional end else fVerTyp:= 16; // Windows Server 2012 3: if fProdTyp= VER_NT_WORKSTATION then begin fVerTyp:= 17; // Windows 8.1 if (fVerMask and VER_SUITE_PERSONAL)=VER_SUITE_PERSONAL then fVerPro:= 1 //Home Edition else fVerPro:= 2; //Professional end else fVerTyp:= 18; // Windows 2012 Server R2 end; //case fVermin end; 10: begin if Assigned(GetProductInfo) then begin GetProductInfo( dwOSMajorVersion, dwOSMinorVersion, dwSpMajorVersion, dwSpMinorVersion, fVerProEx ); if fVerProEx = $ABCDABCD then fVerProEx:= High(ProdStrEx); end; case fVerMin of // Windows 10 , Windows 11 0: if fProdTyp=VER_NT_WORKSTATION then begin if (fVerMask and VER_SUITE_PERSONAL)=VER_SUITE_PERSONAL then fVerPro:= 1 //Home Edition else fVerPro:= 2; //Professional if FVerBuild < 22000 then begin fVerTyp:= 19; // Windows 10 build number start with 10000 // Match builds to Win 10 version commercial name, Build numbers are in Win10build array A:= Win10Strs.Strings[0].Split('='); //'Unknown version' FVersup:= A[1]; for i:= 0 to Win10Strs.Count-1 do begin A:= Win10Strs.Strings[i].Split('='); if FVerBuild=StrToInt(A[0]) then begin FVersup:= A[1]; break; end; end; end else begin fVerTyp:= 22 ; // Windows 11 build number start with 22000 A:= Win11Strs.Strings[0].Split('='); //'Unknown version' FVersup:= A[1]; for i:= 0 to Win11Strs.Count-1 do begin A:= Win11Strs.Strings[i].Split('='); if FVerBuild=StrToInt(A[0]) then begin FVersup:= A[1]; break; end; end; end; end else begin if fVerbuild < 14394 then begin fVerTyp:= 20; // Windows Server 2016 end else begin if fVerbuild < 20348 then fVerTyp:= 21 // Windows Server 2019 else fVerTyp:= 23; // Windows server 2022 end; end; end;// Case fVerMin end; // Case 10 end; // Case fVermaj end; // End of Windows code, begin Linux, Unix or Mac code {$ELSE} procedure TbbOSVersion.GetSysInfo; var P: TProcess; Function ExecParam(Param: String): String; Begin P.Parameters[0]:= '-' + Param; P.Execute; SetLength(Result, 1000); SetLength(Result, P.Output.Read(Result[1], Length(Result))); While (Length(Result) > 0) And (Result[Length(Result)] In [#8..#13,#32]) Do SetLength(Result, Length(Result) - 1); End; Begin //Default(OSInfo); P:= TProcess.Create(Nil); P.Options:= [poWaitOnExit, poUsePipes]; P.Executable:= 'uname'; P.Parameters.Add(''); fOSName:= ExecParam('o'); fKernelName:= ExecParam('s'); fKernelRelease:= ExecParam('r'); fKernelVersion:= ExecParam('v'); fNetworkNode:= ExecParam('n'); fArchitecture:= ExecParam('m'); P.Free; fVerDetail:= fOSName+' '+fKernelName+' '+fKernelVersion; End; {$ENDIF} procedure TbbOSVersion.Translate(LngFile: TBbIniFile); var i: Integer; A: TStringArray; begin if assigned (Lngfile) then with LngFile do begin {$IFDEF WINDOWS} ProdStrs.Strings[1]:= ReadString('OSVersion','Home','Famille'); ; ProdStrs.Strings[2]:= ReadString('OSVersion','Professional','Entreprise'); ProdStrs.Strings[3]:= ReadString('OSVersion','Server','Serveur'); for i:= 0 to Win10Strs.count-1 do begin A:= Win10Strs.Strings[i].split('='); Win10Strs.Strings[i]:= A[0]+'='+ReadString('OSVersion',A[0],A[1]); end; for i:= 0 to Win11Strs.count-1 do begin A:= Win11Strs.Strings[i].split('='); Win11Strs.Strings[i]:= A[0]+'='+ReadString('OSVersion',A[0],A[1]); end; {$ENDIF} end; end; end.
unit uParentToolBarFch; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentCustomFch, DB, uConfigFch, ExtCtrls, dxBar, StdCtrls, uSystemTypes, mrConfigFch; type TParentToolBarFch = class(TParentCustomFch) bmFch: TdxBarManager; bbPrint: TdxBarButton; bbFirst: TdxBarButton; bbPrior: TdxBarButton; bbNext: TdxBarButton; bbLast: TdxBarButton; bbLoop: TdxBarButton; pnlBottom: TPanel; btnOk: TButton; btnCancel: TButton; btnSave: TButton; protected procedure ConfigButtons(aActionType: TActionType); override; procedure ConfigNavigation(aCanPrior, aCanNext: Boolean); override; procedure SetPageControl(PageIndex: Integer); override; end; implementation {$R *.dfm} { TParentToolBarFch } procedure TParentToolBarFch.ConfigButtons(aActionType: TActionType); begin if aActionType in [atAppend, atEdit] then begin btnOk.Enabled := True; btnCancel.Caption := 'Cancelar'; btnSave.Enabled := True; end else begin btnOk.Enabled := False; btnCancel.Caption := 'Fechar'; btnSave.Enabled := False; end; end; procedure TParentToolBarFch.ConfigNavigation(aCanPrior, aCanNext: Boolean); begin bbFirst.Enabled := aCanPrior; bbPrior.Enabled := aCanPrior; bbNext.Enabled := aCanNext; bbLast.Enabled := aCanNext; end; procedure TParentToolBarFch.SetPageControl(PageIndex: Integer); begin end; end.
unit uFrmParentSaleFull; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmParentSales, cxClasses, cxStyles, cxGridTableView, DB, ADODB, siComp, siLangRT, uFrmPaymentReceive, clsInfoCashSale, ufrmSearchCustomer; type TFrmParentSaleFull = class(TFrmParentSales) quTestSerialNumber: TADODataSet; procedure OnProcesseSaleClick(Sender: TObject); procedure OnProcesseCloseSaleClick(Sender: TObject); procedure OnShowPaymentsClick(Sender : TObject); procedure OnHoldPrintClick(Sender : TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FPaymentChange: Double; FIsPaymentProcessed: Boolean; procedure setPaymentProcessed(arg_isProcessed: Boolean); function GetCustomerSelect(): integer; protected //amfsouza 03.18.2011 - could be Onhold button or quote button. FOnHoldSigned: boolean; FrmPaymentReceive : TFrmPaymentReceive; function ValidatePayment : Boolean; virtual; function ProcessPayment(CloseSale : Boolean) : Boolean; function FindInvoiceRefund(InvoiceNum : String) : Boolean; overload; function findInvoiceRefund(arg_IdPreInventoryMov: Integer): Boolean; overload; procedure SetSerialNumber(qty_typed: Integer = 0; arg_idpreinvmov: Integer = 0); procedure SetCustomer(AIDCustomer: Integer); function ReceivePayment(PrintReceipt : Boolean) : Boolean; procedure AfterReceivePayment(CloseSale : Boolean; pInfoCashSale: InfoCashSale = nil ); virtual; procedure BeforeReceive; virtual; procedure AfterReceive; virtual; procedure CallPuppyTracker(refund: Boolean = false); procedure DisplayCustomer; virtual; procedure DisplayPetSKU; virtual; function ValidatePuppyTrackerItems : Boolean; virtual; function IsPaymentProcessed: Boolean; public { Public declarations } end; implementation uses uMsgBox, uMsgConstant, uDM, uSystemConst, uInvoicePayment, uPrintReceipt, uFrmInvoiceRefund, uHandleError, uFrmHistoryManage, MRPuppyIntegrationCls; {$R *.dfm} { TFrmParentSaleFull } procedure TFrmParentSaleFull.AfterReceive; begin // end; procedure TFrmParentSaleFull.AfterReceivePayment(CloseSale : Boolean; pInfoCashSale: InfoCashSale); begin DM.FTraceControl.TraceIn('TFrmParentSaleFull.AfterReceivePayment'); try // Impressão do recibo with TPrintReceipt.Create(Self) do try Start(FInvoiceInfo.IDPreSale, RECEIPT_TYPE_INVOICE, (FPaymentChange*-1), pInfoCashSale); finally objInfoCashSale.setItemDiscounts(0); objInfoCashSale.setSaleDiscount(0); objInfoCashSale.setNewTotalDue(0); end; except on E: Exception do begin DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TFrmParentSaleFull'); MsgBox(MSG_CRT_ERROR_PRINT, vbCritical + vbOkOnly); end; end; DM.FTraceControl.TraceOut; end; procedure TFrmParentSaleFull.BeforeReceive; begin // end; procedure TFrmParentSaleFull.CallPuppyTracker(refund: Boolean); var PuppyIntegration: TMRPuppyIntegration; hasRefund: boolean; begin DM.FTraceControl.TraceIn('TFrmParentSaleFull.CallPuppyTracker'); try try if DM.SaleHavePuppyTrackerItem(FInvoiceInfo.IDPreSale) then begin // amfsouza 08.22.2011 - Export Puppy Sold to PuppyTracker PuppyIntegration := TMRPuppyIntegration.Create(dm.ADODBConnect); // hasRefund := ( FInvoiceInfo.IDPreSaleRefund > 0 ); PuppyIntegration.PuppySoldToPuppyTracker(FInvoiceInfo.IDInvoice, FInvoiceInfo.IDPreSale, Refund); DM.SendPuppyInfo(FInvoiceInfo.IDInvoice); DM.SendPetCenterInfo(FInvoiceInfo.IDPreSale); end; except on E: Exception do DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TFrmParentSaleFull'); end; DM.FTraceControl.TraceOut; finally freeAndNil(PuppyIntegration); end; end; function TFrmParentSaleFull.FindInvoiceRefund( InvoiceNum: String): Boolean; var iResult : Integer; iIDRefund: Integer; dRefundDate : TDatetime; begin result := false; with TFrmInvoiceRefund.Create(Self) do if Start(FInvoiceInfo.IDPreSale, InvoiceNum, iIDRefund, dRefundDate, objInfoCashSale) <> 0 then begin FInvoiceInfo.IDPreSaleRefund := iIDRefund; FInvoiceInfo.RefundDate := dRefundDate; RefreshHold; result := true; end; end; procedure TFrmParentSaleFull.OnHoldPrintClick(Sender: TObject); begin if not EmptyHold then begin SaveHoldInfo; CreateHoldNumber; //amfsouza 03.18.2011 fOnHoldSigned := true; with TPrintReceipt.Create(Self) do Start(FInvoiceInfo.IDPreSale, RECEIPT_TYPE_HOLD); end; end; procedure TFrmParentSaleFull.OnProcesseCloseSaleClick(Sender: TObject); begin // get the return of ProcessPayment setPaymentProcessed(ProcessPayment(True)); end; procedure TFrmParentSaleFull.OnProcesseSaleClick(Sender: TObject); begin (* amfsouza 09.26.2011-debug *)dm.FTraceControl.SaveTrace(dm.fUser.ID, 'Debug-Step: Proccess button pressed', '(PII):'+ self.ClassName); ProcessPayment(False); end; procedure TFrmParentSaleFull.OnShowPaymentsClick(Sender: TObject); begin with TInvoicePayment.Create(Self) do Start(FInvoiceInfo.IDPreSale, FInvoiceInfo.Layaway, FInvoiceInfo.IsInvoice); end; function TFrmParentSaleFull.ProcessPayment(CloseSale : Boolean): Boolean; begin DM.FTraceControl.TraceIn('TFrmParentSaleFull.ProcessPayment'); try if ValidatePayment then begin CreateHoldNumber; SaveHoldInfo; RefreshInfo; BeforeReceive; if FInvoiceInfo.PreSaleType = SALE_CASHREG then begin //Codigo para o Invoice //True //Result //Exit if ReceivePayment(CloseSale) then AfterReceivePayment(CloseSale, objInfoCashSale); end; AfterReceive; Result := True; end else Result := False; except on E: Exception do DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TFrmParentSaleFull'); end; DM.FTraceControl.TraceOut; end; function TFrmParentSaleFull.ReceivePayment(PrintReceipt : Boolean): Boolean; begin DM.FTraceControl.TraceIn('TFrmParentSaleFull.ReceivePayment'); try with FrmPaymentReceive do Result := Start(quPreSaleInfo, spquPreSaleValue, spquPreSaleItem, FInvoiceInfo, FFrmPromoControl, FPaymentChange); setPaymentProcessed(result); except on E: Exception do begin showmessage('Fail after payment receive ' + e.message); DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TFrmParentSaleFull'); end; end; DM.FTraceControl.TraceOut; end; procedure TFrmParentSaleFull.SetSerialNumber(qty_typed: Integer; arg_idpreinvmov: Integer); begin with DM.quFreeSQL do begin if Active then Close; SQL.Clear; SQL.Add('SELECT IDPreInventoryMov '); SQL.Add('FROM PreInventoryMov PIM '); SQL.Add('LEFT OUTER JOIN PreSerialMov PSM ON (PIM.IDPreInventoryMov = PSM.PreInventoryMovID)'); SQL.Add('JOIN Model M ON (PIM.ModelID = M.IDModel)'); SQL.Add('JOIN TabGroup TG ON (M.GroupID = TG.IDGroup)'); SQL.Add('WHERE TG.SerialNumber = 1'); SQL.Add('AND PIM.UserID = ' + IntToStr(DM.fUser.ID)); SQL.Add('AND PIM.DocumentID = ' + IntToStr(FInvoiceInfo.IDPreSale)); SQL.Add('AND PIM.IDPreInventoryMov = ' + IntToStr(arg_idpreinvmov)); SQL.Add('GROUP BY IDPreInventoryMov, PIM.Qty '); // SQL.Add('HAVING COUNT(PSM.SerialNumber) < PIM.Qty'); try try Open; // showmessage(sql.GetText); if ( not IsEmpty ) then begin dm.CreateCdsMercuryGift(); AddSerialNumber(qty_typed, arg_idpreinvmov); end; except on e: Exception do begin raise Exception.Create('Exception in setSerialNumber method '+ e.Message); end; end; finally Close; end; end; end; function TFrmParentSaleFull.ValidatePayment: Boolean; begin DM.FTraceControl.TraceIn('TFrmParentSaleFull.ValidatePayment'); Result := True; try if spquPreSaleItem.IsEmpty then begin MsgBox(MSG_CRT_NO_ITEM_PAY, vbOKOnly + vbInformation); Result := False; Exit; end; if (quPreSaleInfoIDCustomer.AsInteger = 1) and (SaleNeedCustomer) then begin MsgBox(MSG_CRT_NO_CUSTUMER, vbOKOnly + vbInformation); Result := False; DisplayCustomer; Exit; end; if (quPreSaleInfoIDCustomer.AsInteger = 1) and (FInvoiceInfo.Layaway) then begin MsgBox(MSG_CRT_NO_CUSTUMER, vbOKOnly + vbInformation); Result := False; Exit; end; if (DM.fSystem.SrvParam[PARAM_PETCENTER_INTEGRATION] <> '') then if quPreSaleInfoPuppyTracker.AsBoolean and (not ValidatePuppyTrackerItems) then begin MsgBox(Format(MSG_INF_SELECT_PET_SKU, [spquPreSaleItemModel.AsString]), vbOKOnly + vbInformation); Result := False; DisplayPetSKU; Exit; end; (* if (FInvoiceInfo.PreSaleType = SALE_PRESALE) or (FInvoiceInfo.PreSaleType = SALE_CASHREG) then begin with quTestSerialNumber do if not Active then begin Parameters.ParamByName('IDUser').Value := DM.fUser.ID; Parameters.ParamByName('DocumentID').Value := quPreSaleInfoIDPreSale.AsInteger; Open; try if not IsEmpty then begin MsgBox(MSG_CRT_NO_SERIAL_NUMBER, vbCritical + vbOkOnly); Result := False; Exit; end; finally Close; end; end; end; *) except on E: Exception do begin showMessage('3 ' + e.Message); DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TFrmParentSaleFull'); end; end; DM.FTraceControl.TraceOut; end; procedure TFrmParentSaleFull.FormCreate(Sender: TObject); begin inherited; FrmPaymentReceive := TFrmPaymentReceive.Create(Self); FOnHoldSigned := false; end; procedure TFrmParentSaleFull.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(FrmPaymentReceive); end; procedure TFrmParentSaleFull.SetCustomer(AIDCustomer: Integer); begin if AIDCustomer <> -1 then begin quPreSaleInfo.Edit; quPreSaleInfoIDCustomer.AsInteger := AIDCustomer; quPreSaleInfo.Post; OnSelectCustomer(Self); { DM.fPOS.ApplyCustomerDiscount(FInvoiceInfo.IDPreSale, AIDCustomer, Now); if FApplyPromoOnSale and (not (AIDCustomer in [0,1])) then begin FFrmPromoControl.VerifyFrequentPromo(AIDCustomer, FInvoiceInfo.IDPreSale); ApplyPromoOnAllItems; end; } RefreshHold; { if ( not dm.fSystem.SrvParam[PARAM_TAX_EXEMPT_ON_SALE] ) then begin if ( ExemptCustomerTax(AIDCustomer) ) then begin subApplyTaxExemption(true); end else begin subApplyTaxExemption(false); undoTaxExemption(); end; refreshHold(); refreshValue(); end } end else begin // tratar aqui a selecao do cliente e a obtencao do ID. AIDCustomer := GetCustomerSelect(); end; if ( not dm.fSystem.SrvParam[PARAM_TAX_EXEMPT_ON_SALE] ) then begin if ( ExemptCustomerTax(AIDCustomer) ) then begin subApplyTaxExemption(true); end else begin subApplyTaxExemption(false); undoTaxExemption(); end; refreshHold(); refreshValue(); end; end; function TFrmParentSaleFull.GetCustomerSelect(): integer; var iIDCustomer: integer; begin with TFrmSearchCustomer.Create(Self) do iIDCustomer := Start; { if (iIDCustomer <> -1) and (FDocumentInfo.IDCustomer <> iIDCustomer) then if FSaleReceive.GetPaymentTotalByType(PAYMENT_TYPE_CREDIT) > 0 then begin MsgBox(MSG_INF_DEL_CUSTOMER_CREDIT, vbInformation + vbOkOnly); Exit; end; } if iIDCustomer <> -1 then begin quPreSaleInfo.Edit; quPreSaleInfo.FieldByName('IDCustomer').AsInteger := iIDCustomer; quPreSaleInfo.Post; //RefreshCustomer; end; result := iIdCustomer; end; procedure TFrmParentSaleFull.DisplayCustomer; begin end; function TFrmParentSaleFull.ValidatePuppyTrackerItems: Boolean; var FQuery : TADOQuery; begin Result := False; try spquPreSaleItem.DisableControls; spquPreSaleItem.First; while not spquPreSaleItem.Eof do begin if spquPreSaleItemPuppyTracker.AsBoolean then try FQuery := TADOQuery.Create(Self); FQuery.Connection := DM.ADODBConnect; FQuery.SQL.Add('SELECT IDPetSale FROM Pet_PetSale WHERE IDPreInventoryMov = :IDPreInventoryMov'); FQuery.Parameters.ParamByName('IDPreInventoryMov').Value := spquPreSaleItemIDInventoryMov.AsInteger; FQuery.Open; Result := not FQuery.IsEmpty; if not Result then Break; finally FQuery.Close; FreeAndNil(FQuery); end; spquPreSaleItem.Next; end; finally spquPreSaleItem.EnableControls; end; end; procedure TFrmParentSaleFull.DisplayPetSKU; begin end; function TFrmParentSaleFull.FindInvoiceRefund(arg_IdPreInventoryMov: Integer): Boolean; var frmInvoiceRefund: TFrmInvoiceRefund; begin try frmInvoiceRefund := TfrmInvoiceRefund.Create(nil); if ( frmInvoiceRefund.StartItem(arg_IdPreInventoryMov) ) then begin FInvoiceInfo.IDPreSaleRefund := frmInvoiceRefund.getIdRefund; FInvoiceInfo.RefundDate := frmInvoiceRefund.getRefundDate; RefreshHold; end; finally freeAndNil(frmInvoiceRefund); end; end; function TFrmParentSaleFull.IsPaymentProcessed: Boolean; begin result := FIsPaymentProcessed; end; procedure TFrmParentSaleFull.setPaymentProcessed(arg_isProcessed: Boolean); begin FIsPaymentProcessed := arg_isProcessed; end; end.
unit frmDateOplUnit_AE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxControls, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, cxLookAndFeelPainters, StdCtrls, cxGroupBox, cxButtons, cnConsts; type TfrmDateOplAE = class(TForm) OkButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; Label1: TLabel; Label2: TLabel; Day_Edit: TcxTextEdit; Month_Edit: TcxTextEdit; procedure OkButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Day_EditKeyPress(Sender: TObject; var Key: Char); procedure Month_EditKeyPress(Sender: TObject; var Key: Char); private PLanguageIndex : byte; procedure FormIniLanguage(); public constructor Create(AOwner:TComponent; LanguageIndex : byte); reintroduce; end; var frmDateOplAE: TfrmDateOplAE; implementation {$R *.dfm} constructor TfrmDateOplAE.Create(AOwner:TComponent; LanguageIndex : byte); begin Screen.Cursor:=crHourGlass; inherited Create(AOwner); PLanguageIndex:= LanguageIndex; FormIniLanguage(); Screen.Cursor:=crDefault; end; procedure TfrmDateOplAE.FormIniLanguage; begin Label1.caption:= cnConsts.cn_Day[PLanguageIndex]; Label2.caption:= cnConsts.cn_Month[PLanguageIndex]; OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex]; CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex]; end; procedure TfrmDateOplAE.OkButtonClick(Sender: TObject); begin ModalResult:= mrOk; end; procedure TfrmDateOplAE.CancelButtonClick(Sender: TObject); begin close; end; procedure TfrmDateOplAE.FormShow(Sender: TObject); begin Day_Edit.SetFocus; end; procedure TfrmDateOplAE.Day_EditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then Month_Edit.SetFocus; end; procedure TfrmDateOplAE.Month_EditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then OkButton.SetFocus; end; end.
{ This is simple and probably not so efficient version of Game of Life. It works but it MAY or MAY NOT work correctly (mostly it does work as expected :) ) You can generate world using predefined settings (World Width/World Height/Cell Width/Cell Height). Just click CREATE THE WORLD button. It will create basic empty world since chance to be alive is set to 0. To create randomly placed live cells set Chance to be alive to bigger value (e.g 45). Now You can start simulations by sliding Simulation speed to right or You can make just one step using button labeled '>>' You can also manually add living cell by clicking on world grid. If there is dead cell it will rise from grave, otherwise You will kill living cell. Have fun ;) Tomek } unit mainunit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls, Buttons, ExtCtrls; type TCellStates = (csAlive, csDead); TCell = class private FCellState: TCellStates; FPrevCellState: TCellStates; FCRect: TRect; public property CellState: TCellStates read FCellState write FCellState; property PrevCellState: TCellStates read FPrevCellState write FPrevCellState; property CRect: TRect read FCRect write FCRect; end; type TWorld = array of array of TCell; TWorldType = (wtEmpty, wtRandom); type { TForm1 } TForm1 = class(TForm) Bevel1: TBevel; Bevel2: TBevel; Bevel3: TBevel; edBirthChance: TEdit; edCellHeight: TEdit; Edit1: TEdit; edWorldSeed: TEdit; edWorldWidth: TEdit; edWorldHeight: TEdit; edCellWidth: TEdit; gbWorldSettings: TGroupBox; gbCellSettings: TGroupBox; gbGeneration: TGroupBox; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label7: TLabel; lbSimulationSpeed: TLabel; Label6: TLabel; dgLoadWorld: TOpenDialog; pbScene: TPaintBox; dgSaveWorld: TSaveDialog; sbSystemInfo: TStatusBar; sbWorldContainer: TScrollBox; btnGenSeed: TSpeedButton; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; btnSaveWorld: TSpeedButton; btnLoadWorld: TSpeedButton; SpeedButton3: TSpeedButton; tbWorldSpeed: TTrackBar; tbBirthChance: TTrackBar; tbtnSimulationONOFF: TToggleBox; tWorldClock: TTimer; procedure btnGenSeedClick(Sender: TObject); procedure btnLoadWorldClick(Sender: TObject); procedure btnSaveWorldClick(Sender: TObject); procedure edBirthChanceChange(Sender: TObject); procedure edCellHeightChange(Sender: TObject); procedure edCellHeightExit(Sender: TObject); procedure edCellWidthChange(Sender: TObject); procedure edWorldHeightChange(Sender: TObject); procedure edWorldHeightExit(Sender: TObject); procedure edWorldWidthChange(Sender: TObject); procedure edWorldWidthExit(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure pbSceneMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pbSceneMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure pbSceneMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure tbBirthChanceChange(Sender: TObject); procedure tbWorldSpeedChange(Sender: TObject); procedure tbtnSimulationONOFFChange(Sender: TObject); procedure tWorldClockTimer(Sender: TObject); private procedure DrawWorld(Sender: TObject); procedure PrepareWorldCanvas; procedure SetWorldDims(AWorld: TWorld); procedure GenerateWorld(AWorld: TWorld; AWorldWidth, AWorldHeight, ACellWidth, ACellHeight: Integer; AWorldType: TWorldType; ABirthChance: integer=0); procedure FreeWorld(AWorld: TWorld; AWorldWidth, AWorldHeight: integer); procedure ShiftCellState(ACell: TCell); procedure SetWorldState(AWorld: TWorld; AState: TCellStates; AWorldWidth, AWorldHeight: integer); function GetNeighboursCount(AWorld: TWorld; ARow, ACol, AWorldWidth, AWorldHeight: integer): integer; function CellState2String(ACell: TCell): string; function String2CellState(AString: string): TCellStates; function GetCellColor(ACell: TCell):TColor; function SetCellColorMOD(ABaseColor: TColor; ANeighborsCount: Integer): TColor; function DarkenColor(AColor: TColor; APercent: UInt8): TColor; procedure Split(const Delimiter: Char; Input: string; const Strings: TStrings); public end; var Form1: TForm1; SimRunning: Boolean; WorldSpeed: integer; prevWorldSpeed: integer; WorldGenSeed: integer; World: TWorld; OldWorld: TWorld; //for calculations; WorldWidth, WorldHeight, CellWidth, CellHeight: integer; scale,oldWWidth,oldWHeight:integer; MouseIsDown: Boolean; implementation {$R *.lfm} { TForm1 } procedure TForm1.Split (const Delimiter: Char; Input: string; const Strings: TStrings); begin Assert(Assigned(Strings)) ; Strings.Clear; Strings.Delimiter := Delimiter; Strings.StrictDelimiter:=true; Strings.DelimitedText := Input; end; procedure TForm1.tbWorldSpeedChange(Sender: TObject); begin if Length(World)>0 then begin WorldSpeed := tbWorldSpeed.position; tWorldClock.Interval:=WorldSpeed; lbSimulationSpeed.Caption := 'Simulation speed: ('+IntToStr(WorldSpeed)+')'; if tbtnSimulationOnOff.Checked then begin prevWorldSpeed := WorldSpeed; end; if tbWorldSpeed.Position = 0 then tWorldClock.Enabled := false else tWorldClock.Enabled := True; if tWorldClock.Enabled then tbtnSimulationOnOff.Caption := 'ON' else tbtnSimulationOnOff.Caption := 'OFF' ; end; end; procedure TForm1.tbtnSimulationONOFFChange(Sender: TObject); begin if Length(World)>0 then begin if tbtnSimulationONOFF.Checked then Begin tbtnSimulationONOFF.Caption := 'ON'; SimRunning := true; WorldSpeed := prevWorldSpeed; tbWorldSpeed.Position := WorldSpeed; tWorldClock.Interval := WorldSpeed; tWorldClock.Enabled := true; // WorldWidth := StrToInt(edWorldWidth.text); WorldHeight := StrToInt(edWorldHeight.text); // end else Begin tbtnSimulationONOFF.Caption := 'OFF'; SimRunning := False; prevWorldSpeed := WorldSpeed; WorldSpeed := 0; tbWorldSpeed.Position := 0; tWorldClock.Interval := WorldSpeed; tWorldClock.Enabled := False; end; end; end; procedure TForm1.tWorldClockTimer(Sender: TObject); var ins,cY, cX, ns, sHeight, sWidth: Integer; bit, Bitmap:TBitmap; Dest, Source: TRect; begin // Edit1.text:=IntToStr(Length(World))+' <CURR - OLD> '+inttostr(length(oldworld)); // SetWorldState(OldWorld,csDead,WorldWidth,WorldHeight); SetWorldState(OldWorld,csDead,WorldWidth,WorldHeight); //Crude WAY! For cY:=0 to WorldHeight-1 do begin For cX:=0 to WorldWidth-1 do begin if World[cx,cy].CellState=csAlive then begin World[cX,cY].PrevCellState := World[cX,cY].CellState; ns:=GetNeighboursCount(World,cX,cY,WorldWidth,WorldHeight); if (ns=2) or (ns=3) then OldWorld[cx,cy].CellState:=csAlive; end; if World[cx,cy].CellState=csAlive then begin World[cX,cY].PrevCellState := World[cX,cY].CellState; ns:=GetNeighboursCount(World,cX,cY,WorldWidth,WorldHeight); if (ns<2) or (ns>3) {(ns=0) or (ns=1) or (ns=5)or (ns=6)or (ns=7)or (ns=8)} then OldWorld[cx,cy].CellState:=csDead; end; if World[cx,cy].CellState=csDead then begin World[cX,cY].PrevCellState := World[cX,cY].CellState; ns:=GetNeighboursCount(World,cX,cY,WorldWidth,WorldHeight); if ns=3 then oldWorld[cx,cy].CellState:=csAlive; end; end; end; SetWorldState(World,csDead,WorldWidth,WorldHeight); For cY:=0 to WorldHeight-1 do begin For cX:=0 to WorldWidth-1 do begin world[cx,cy].CellState:=Oldworld[cx,cy].CellState; end; end; pbScene.OnPaint:=@DrawWorld; pbScene.Refresh; end; procedure TForm1.DrawWorld(Sender: TObject); var ins,wRow,wCol, sWidth, sHeight:integer; cellColor: TColor; bit, Bitmap: TBitmap; Dest, Source: TRect; begin pbScene.Canvas.pen.style:=psClear; pbScene.Canvas.Brush.Color:=rgbtocolor(23,23,23); pbScene.Canvas.Rectangle(0,0,pbScene.Width,pbscene.Height); for wCol := 0 to WorldHeight-1 do begin for wRow := 0 to WorldWidth-1 do begin if (World[wRow,wCol].PrevCellState <> World[wRow,wCol].CellState) or (World[wRow,wCol].CellState=csAlive) then begin cellColor := SetCellColorMOD(RGBToColor(255,150,30),GetNeighboursCount(World,wRow,wCol,WorldWidth,WorldHeight));// toso GetCellColor(World[wRow,wCol]); if World[wRow,wCol].CellState=csAlive then begin pbScene.Canvas.Brush.Color :=cellColor; // BIG FRAME RATE DROP :P RGBToColor(Random(256),Random(256),Random(256)); pbScene.Canvas.Rectangle(World[wRow,wCol].CRect); end; end; end; end; end; procedure TForm1.PrepareWorldCanvas; begin pbScene.Width := CellWidth*WorldWidth; pbScene.Height := CellHeight*WorldHeight; end; procedure TForm1.SetWorldDims(AWorld: TWorld); begin SetLength(AWorld,WorldWidth,WorldHeight); end; procedure TForm1.GenerateWorld(AWorld: TWorld; AWorldWidth, AWorldHeight, ACellWidth, ACellHeight: Integer;AWorldType: TWorldType; ABirthChance: integer=0); var wRow,wCol: integer; tmpRect: TRect; begin // setting CRect // --- Case AWorldType of wtEmpty: Begin for wCol := 0 to AWorldHeight-1 do begin for wRow := 0 to AWorldWidth-1 do Begin tmpRect := TRect.Create(wRow*ACellWidth-1,wCol*ACellHeight-1,wRow*ACellWidth+ACellWidth+1,wCol*ACellHeight+ACellHeight+1); AWorld[wRow,wCol] := TCell.Create; AWorld[wRow,wCol].CellState := csDead; AWorld[wRow,wCol].PrevCellState := AWorld[wRow,wCol].CellState; AWorld[wRow,wCol].CRect := TRect.Create(tmpRect); // AWorld[wRow,wCol].CRect.Inflate(1,1); end; end; end; wtRandom:Begin for wCol := 0 to AWorldHeight-1 do begin for wRow := 0 to AWorldWidth-1 do Begin tmpRect := TRect.Create(wRow*ACellWidth,wCol*ACellHeight,wRow*ACellWidth+ACellWidth, wCol*ACellHeight+ACellHeight); AWorld[wRow,wCol] := TCell.Create; if (Random(100)+1)<ABirthChance then AWorld[wRow,wCol].CellState := csAlive else AWorld[wRow,wCol].CellState := csDead; AWorld[wRow,wCol].PrevCellState := AWorld[wRow,wCol].CellState; AWorld[wRow,wCol].CRect := TRect.Create(tmpRect); // AWorld[wRow,wCol].CRect.Inflate(1,1); end; end; end; end; end; procedure TForm1.FreeWorld(AWorld: TWorld; AWorldWidth, AWorldHeight: integer); var wRow,wCol:integer; begin if Length(AWorld)>0 then begin For wCol := 0 to AWorldHeight-1 do begin For wRow := 0 to AWorldWidth-1 do begin AWorld[wRow,wCol].Free; end; end; end; end; function TForm1.GetCellColor(ACell: TCell): TColor; begin Case ACell.CellState of csAlive : Result := RGBToColor(146, 196, 39); csDead : Result := RGBToColor(120, 120, 120); end; end; function TForm1.DarkenColor(AColor: TColor; APercent: UInt8): TColor; var R, G, B: UInt8; begin RedGreenBlue(AColor, R, G, B); R := Round(R * (100 - APercent) / 100); G := Round(G * (100 - APercent) / 100); B := Round(B * (100 - APercent) / 100); Result := RGBToColor(R, G, B); end; function TForm1.SetCellColorMOD(ABaseColor: TColor; ANeighborsCount: Integer): TColor; begin Result := DarkenColor(ABaseColor, ANeighborsCount * 10); end; {function TForm1.SetCellColorMOD(ACell: TCell; ANeighbours: integer): TColor; begin Case ANeighbours of 0 : Result:=RGBToColor(255,255, 50); 1 : Result:=RGBToColor(255,225, 50); 2 : Result:=RGBToColor(255,200, 50); 3 : Result:=RGBToColor(255,175, 50); 4 : Result:=RGBToColor(255,150, 50); 5 : Result:=RGBToColor(255,125, 50); 6 : Result:=RGBToColor(255,100, 50); 7 : Result:=RGBToColor(255, 75, 50); 8 : Result:=RGBToColor(255, 50, 50); end; end; } procedure TForm1.ShiftCellState(ACell: TCell); begin Case ACell.CellState of csDead : ACell.CellState := csAlive; csAlive : ACell.CellState := csDead; end; end; procedure TForm1.SetWorldState(AWorld: TWorld; AState: TCellStates; AWorldWidth, AWorldHeight: integer); var wRow, wCol: integer; begin if Length(AWorld) > 0 then Begin for wCol:=0 to AWorldHeight-1 do Begin for wRow:=0 to AWorldWidth-1 do Begin AWorld[wRow,wCol].CellState:=AState; end; end; end; end; function TForm1.GetNeighboursCount(AWorld: TWorld; ARow, ACol, AWorldWidth, AWorldHeight: integer): integer; var NC:integer; begin nc:=0; if (ACol-1>=0) and ((AWorld[ARow,ACol-1].CellState=csAlive) or (AWorld[ARow,ACol-1].CellState=csAlive))then NC:=NC+1 else nc:=nc; if (ACol+1<=AWorldHeight-1) and ((AWorld[ARow,ACol+1].CellState=csAlive) or (AWorld[ARow,ACol+1].CellState=csAlive))then NC:=NC+1 else nc:=nc; if (ARow-1>=0) and ((AWorld[ARow-1,ACol].CellState=csAlive) or (AWorld[ARow-1,ACol].CellState=csAlive)) then NC:=NC+1 else nc:=nc; if (ARow+1<=AWorldWidth-1) and ((AWorld[ARow+1,ACol].CellState=csAlive) or (AWorld[ARow+1,ACol].CellState=csAlive))then NC:=NC+1 else nc:=nc; if ((ARow-1>=0) and (ACol-1>=0)) and ((AWorld[ARow-1,ACol-1].CellState=csAlive) or (AWorld[ARow-1,ACol-1].CellState=csAlive))then NC:=NC+1 else nc:=nc; if ((ARow-1>=0) and (ACol+1<=AWorldHeight-1)) and ((AWorld[ARow-1,ACol+1].CellState=csAlive) or (AWorld[ARow-1,ACol+1].CellState=csAlive))then NC:=NC+1 else nc:=nc; if ((ARow+1<=AWorldWidth-1) and (ACol-1>=0)) and ((AWorld[ARow+1,ACol-1].CellState=csAlive) or (AWorld[ARow+1,ACol-1].CellState=csAlive))then NC:=NC+1 else nc:=nc; if ((ARow+1<=AWorldWidth-1) and (ACol+1<=AWorldHeight-1)) and ((AWorld[ARow+1,ACol+1].CellState=csAlive) or (AWorld[ARow+1,ACol+1].CellState=csAlive))then NC:=NC+1 else nc:=nc; result:=nc; end; function TForm1.CellState2String(ACell: TCell): string; begin case ACell.CellState of csAlive: Result := 'csAlive'; csDead: Result := 'csDead'; end; end; function TForm1.String2CellState(AString: string): TCellStates; begin case AString of 'csAlive': Result := csAlive; 'csDead' : Result := csDead; end; end; procedure TForm1.FormCreate(Sender: TObject); begin Randomize(); lbSimulationSpeed.Caption := 'Simulation speed: ('+IntToStr(tbWorldSpeed.Position)+')'; edBirthChance.Text := IntToStr(tbBirthChance.Position); WorldGenSeed := Random(9223372036854775807); edWorldSeed.Text := IntToStr(WorldGenSeed); tbWorldSpeed.Position := 0; WorldSpeed := 0; prevWorldSpeed := 0; tbtnSimulationOnOff.Checked := false; tbtnSimulationOnOff.Caption := 'OFF'; tWorldClock.Enabled := false; tWorldClock.Interval := 0; CellWidth := StrToInt(edCellWidth.Text); CellHeight := StrToInt(edCellHeight.Text); WorldWidth := StrToInt(edWorldWidth.Text); WorldHeight := StrToInt(edWorldHeight.Text); pbScene.Width := CellWidth*WorldWidth; pbScene.Height := CellHeight*WorldHeight; oldWWidth := WorldWidth; oldWHeight := WorldHeight; scale:=StrToInt(Edit1.text); end; procedure TForm1.FormDestroy(Sender: TObject); begin FreeWorld(World,WorldWidth,WorldHeight); FreeWorld(OldWorld,WorldWidth,WorldHeight); end; procedure TForm1.pbSceneMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var mx,my:integer; begin MouseIsDown:=true; if mouseisdown then begin mx := x div cellwidth; my := y div cellheight; ShiftCellState(World[mx,my]); end; pbScene.Invalidate; end; procedure TForm1.pbSceneMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var wRow,wCol, mx, my: integer; begin wRow := x div CellWidth; wCol := y div CellHeight; if (wRow>0) and (wCol<WorldHeight) then Begin if Length(World) > 0 then begin sbSystemInfo.Panels.Items[0].Text:=IntToStr(GetNeighboursCount(World,wRow,wCol,WorldWidth,WorldHeight)); sbSystemInfo.Panels.Items[1].Text:=CellState2String(World[wRow,wCol]); end; end; if mouseisdown then begin if (wRow>0) and (wCol<WorldHeight) then begin if World[wRow,wCol].CellState<>csAlive then begin mx := x div cellwidth; my := y div cellheight; ShiftCellState(World[mx,my]); end; end; end; pbScene.Invalidate; end; procedure TForm1.pbSceneMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin MouseIsDown:=false; end; procedure TForm1.SpeedButton1Click(Sender: TObject); begin scale:=StrToInt(Edit1.text); if oldworld<>nil then FreeWorld(OldWorld,WorldWidth,WorldHeight); if oldworld<>nil then FreeWorld(World,oldWWidth,oldWHeight); WorldWidth := StrToInt(edWorldWidth.text); WorldHeight := StrToInt(edWorldHeight.text); CellWidth:= StrToInt(edCellWidth.text); CellHeight:= StrToInt(edCellHeight.text); PrepareWorldCanvas; //set width and height SetLength(World,WorldWidth,WorldHeight); SetLength(OldWorld,WorldWidth,WorldHeight); GenerateWorld(OldWorld,WorldWidth,WorldHeight,CellWidth,CellHeight,wtEmpty); GenerateWorld(World,WorldWidth,WorldHeight,CellWidth,CellHeight,wtRandom,StrToInt(edBirthChance.text)); oldWWidth := WorldWidth; oldWHeight := WorldHeight; pbScene.OnPaint := @DrawWorld; pbScene.Invalidate; end; procedure TForm1.SpeedButton2Click(Sender: TObject); var cY, cX, ns: Integer; begin SetWorldState(OldWorld,csDead,WorldWidth,WorldHeight); //Crude WAY! For cY:=0 to WorldHeight-1 do begin For cX:=0 to WorldWidth-1 do begin if World[cx,cy].CellState=csAlive then begin ns:=GetNeighboursCount(World,cX,cY,WorldWidth,WorldHeight); World[cX,cY].PrevCellState := World[cX,cY].CellState; if (ns=2) or (ns=3) then OldWorld[cx,cy].CellState:=csAlive; end; if World[cx,cy].CellState=csAlive then begin World[cX,cY].PrevCellState := World[cX,cY].CellState; ns:=GetNeighboursCount(World,cX,cY,WorldWidth,WorldHeight); if (ns<2) or (ns>3) {(ns=0) or (ns=1) or (ns=5)or (ns=6)or (ns=7)or (ns=8)} then OldWorld[cx,cy].CellState:=csDead; end; if World[cx,cy].CellState=csDead then begin World[cX,cY].PrevCellState := World[cX,cY].CellState; ns:=GetNeighboursCount(World,cX,cY,WorldWidth,WorldHeight); if ns=3 then oldWorld[cx,cy].CellState:=csAlive; end; end; end; SetWorldState(World,csDead,WorldWidth,WorldHeight); For cY:=0 to WorldHeight-1 do begin For cX:=0 to WorldWidth-1 do begin world[cx,cy].CellState:=Oldworld[cx,cy].CellState; end; end; pbScene.OnPaint:=@DrawWorld; pbScene.Refresh; //END CRUDE WAY end; procedure TForm1.SpeedButton3Click(Sender: TObject); var cY, cX, ns: Integer; begin SetWorldState(OldWorld,csDead,WorldWidth,WorldHeight); //Crude WAY! For cY:=0 to WorldHeight-1 do begin For cX:=0 to WorldWidth-1 do begin if World[cx,cy].CellState=csDead then begin ns:=GetNeighboursCount(World,cX,cY,WorldWidth,WorldHeight); World[cX,cY].PrevCellState := World[cX,cY].CellState; if (ns=2) or (ns=3) then OldWorld[cx,cy].CellState:=csAlive; end; if World[cx,cy].CellState=csDead then begin World[cX,cY].PrevCellState := World[cX,cY].CellState; ns:=GetNeighboursCount(World,cX,cY,WorldWidth,WorldHeight); if (ns<2) or (ns>3) {(ns=0) or (ns=1) or (ns=5)or (ns=6)or (ns=7)or (ns=8)} then OldWorld[cx,cy].CellState:=csDead; end; if World[cx,cy].CellState=csAlive then begin World[cX,cY].PrevCellState := World[cX,cY].CellState; ns:=GetNeighboursCount(World,cX,cY,WorldWidth,WorldHeight); if ns=3 then oldWorld[cx,cy].CellState:=csAlive; end; end; end; SetWorldState(World,csDead,WorldWidth,WorldHeight); For cY:=0 to WorldHeight-1 do begin For cX:=0 to WorldWidth-1 do begin world[cx,cy].CellState:=Oldworld[cx,cy].CellState; end; end; pbScene.OnPaint:=@DrawWorld; pbScene.Refresh; //END CRUDE WAY end; procedure TForm1.edBirthChanceChange(Sender: TObject); begin tbBirthChance.Position := StrToInt(edBirthChance.Text); end; procedure TForm1.edCellHeightChange(Sender: TObject); begin { if edCellHeight.text<>'' then CellHeight := StrToInt(edCellHeight.text) } end; procedure TForm1.edCellHeightExit(Sender: TObject); begin { if edCellHeight.text<>'' then CellHeight := StrToInt(edCellHeight.text) } end; procedure TForm1.edCellWidthChange(Sender: TObject); begin { if edCellWidth.text<>'' then CellWidth := StrToInt(edCellWidth.text) } end; procedure TForm1.edWorldHeightChange(Sender: TObject); begin { if edWorldHeight.text<>'' then WorldHeight := StrToInt(edWorldHeight.text)} end; procedure TForm1.edWorldHeightExit(Sender: TObject); begin { if edWorldHeight.text<>'' then WorldHeight := StrToInt(edWorldHeight.text);} end; procedure TForm1.edWorldWidthChange(Sender: TObject); begin { if edWorldWidth.text<>'' then WorldWidth := StrToInt(edWorldWidth.text); } end; procedure TForm1.edWorldWidthExit(Sender: TObject); begin { if edWorldWidth.text<>'' then WorldWidth := StrToInt(edWorldWidth.text); } end; procedure TForm1.btnGenSeedClick(Sender: TObject); begin Randomize(); WorldGenSeed := Random(9223372036854775807); edWorldSeed.Text := IntToStr(WorldGenSeed); end; procedure TForm1.btnLoadWorldClick(Sender: TObject); var WorldList: TStringList; wCol, wRow, i: Integer; SetList: TStringList; tmpCellState: TCellStates; tmpRect: TRect; begin if dgLoadWorld.Execute then begin if World<>nil then FreeWorld(World,WorldWidth,WorldHeight); WorldList:=TStringList.Create; //Load World file into WorldList(TStringList) WorldList.LoadFromFile(dgLoadWorld.FileName); //Create helping StringList to parse line for WorldWidth and World Height //always saved in first line of file SetList:=TStringList.Create; //Delimit first line by ';' and add results to helping stringlist SetList Split(';',WorldList.Strings[0],SetList); //Set loaded values to WorldWidth and Height and put then in Edit Boxes WorldWidth:=StrToInt(SetList[0]); WorldHeight:=StrToInt(SetList[1]); edWorldWidth.Text:=IntToStr(WorldWidth); edWorldHeight.Text:=IntToStr(WorldHeight); //Prepare canvas with loaded values PrepareWorldCanvas; //Read info about cells and create them SetLength(World,WorldWidth,WorldHeight); SetLength(World,WorldWidth,WorldHeight); SetLength(OldWorld,WorldWidth,WorldHeight); GenerateWorld(OldWorld,WorldWidth,WorldHeight,CellWidth,CellHeight,wtEmpty); SetList.Free; For i := 1 to WorldList.Count-1 do Begin SetList := TStringList.Create; //reset helping list every step Split(';',WorldList.Strings[i],SetList); wRow:=StrToInt(SetList[0]); wCol:=StrToInt(SetList[1]); tmpCellState:=String2CellState(SetList[2]); tmpRect := TRect.Create(wRow*CellWidth,wCol*CellHeight,wRow*CellWidth+CellWidth,wCol*CellHeight+CellHeight); World[wRow,wCol]:=TCell.Create; World[wRow,wCol].CellState:=tmpCellState; World[wRow,wCol].PrevCellState:=tmpCellState; World[wRow,wCol].CRect:=TRect.Create(tmpRect); SetList.Free; end; { tmpRect := TRect.Create(wRow*ACellWidth-1,wCol*ACellHeight-1,wRow*ACellWidth+ACellWidth+1,wCol*ACellHeight+ACellHeight+1); AWorld[wRow,wCol] := TCell.Create; AWorld[wRow,wCol].CellState := csDead; AWorld[wRow,wCol].PrevCellState := AWorld[wRow,wCol].CellState; AWorld[wRow,wCol].CRect := TRect.Create(tmpRect);} end; WorldList.Free; oldWWidth := WorldWidth; oldWHeight := WorldHeight; pbScene.OnPaint:=@DrawWorld; pbScene.Invalidate; end; procedure TForm1.btnSaveWorldClick(Sender: TObject); var WorldList: TStringList; wCol, wRow: Integer; begin if dgSaveWorld.Execute then begin WorldList:=TStringList.Create; WorldList.Add(WorldWidth.ToString+';'+WorldHeight.ToString); For wCol:=0 to WorldHeight-1 do begin For wRow:=0 to WorldWidth-1 do begin WorldList.Add(wRow.toString+';'+wCol.toString+';'+CellState2String(World[wRow,wCol])); end; end; if dgSaveWorld.FileName<>'' then WorldList.SaveToFile(dgSaveWorld.FileName); WorldList.Free; end; end; procedure TForm1.tbBirthChanceChange(Sender: TObject); begin edBirthChance.Text := IntToStr(tbBirthChance.Position); end; end.
unit ExtRegistry; interface uses SysUtils,Classes,Registry; type TRegNameType=(rdUnknown, rdString, rdExpandString, rdInteger, rdBinary, rdKey); TExtRegistry = class (TRegistry) public OwnerKey : string; CurrentLevel : integer; CurrentName : string; CurrentType : TRegNameType; constructor Create; destructor Destroy; override; function SelectNames : boolean; function SelectName : boolean; private KeyNames : TStringList; ValueNames : TStringList; CurrentNName : integer; end; implementation constructor TExtRegistry.Create; begin inherited Create; KeyNames:=TStringList.Create; ValueNames:=TStringList.Create; end; destructor TExtRegistry.Destroy; begin ValueNames.Free; KeyNames.Free; end; function TExtRegistry.SelectNames : boolean; begin OpenKey(OwnerKey,false); CurrentLevel:=1; CurrentNName:=0; GetKeyNames(KeyNames); GetValueNames(ValueNames); end; function TExtRegistry.SelectName : boolean; begin if (CurrentNName<KeyNames.Count) then begin CurrentName:=KeyNames[CurrentNName]; //CurrentType:=rdKey; SelectName:=true; inc(CurrentNName); end else if (CurrentNName<KeyNames.Count+ValueNames.Count) then begin CurrentName:=ValueNames[CurrentNName-KeyNames.Count]; //CurrentType:=GetDataType(CurrentName); SelectName:=true; inc(CurrentNName); end else SelectName:=false; end; end.
unit uThreadTask; interface uses SysUtils, Classes, uRuntime, uLogger, uGOM, uThreadEx, uThreadForm; type TThreadTask = class; TTaskThreadProcedure = reference to procedure(Thread: TThreadTask; Data: Pointer); TThreadTask = class(TThreadEx) private FProc: TTaskThreadProcedure; FDataObj: TObject; FDataInterface: IUnknown; protected procedure Execute; override; public constructor Create(AOwnerForm: TThreadForm; Data: Pointer; Proc: TTaskThreadProcedure); overload; constructor Create(AOwnerForm: TThreadForm; Data: IUnknown; Proc: TTaskThreadProcedure); overload; function SynchronizeTask(Proc: TThreadProcedure): Boolean; end; TThreadTask<T> = class(TThreadEx) private FData: T; FCheckStateID: Boolean; protected procedure Execute; override; public type TTaskThreadProcedureEx = reference to procedure(Thread: TThreadTask<T>; Data: T); private FProc: TTaskThreadProcedureEx; public constructor Create(AOwnerForm: TThreadForm; Data: T; CheckStateID: Boolean; Proc: TTaskThreadProcedureEx); overload; function SynchronizeTask(Proc: TThreadProcedure): Boolean; function CheckForm: Boolean; override; end; implementation { TThreadTask } constructor TThreadTask.Create(AOwnerForm: TThreadForm; Data: Pointer; Proc: TTaskThreadProcedure); begin inherited Create(AOwnerForm, AOwnerForm.StateID); FProc := Proc; FDataObj := Data; FDataInterface := nil; end; constructor TThreadTask.Create(AOwnerForm: TThreadForm; Data: IInterface; Proc: TTaskThreadProcedure); begin inherited Create(AOwnerForm, AOwnerForm.StateID); FProc := Proc; FDataObj := nil; FDataInterface := Data; end; procedure TThreadTask.Execute; begin inherited; FreeOnTerminate := True; try if FDataObj <> nil then FProc(Self, FDataObj) else FProc(Self, Pointer(FDataInterface)); except on e: Exception do EventLog(e); end; end; function TThreadTask.SynchronizeTask(Proc: TThreadProcedure): Boolean; begin Result := SynchronizeEx(Proc); end; { TThreadTask<T> } function TThreadTask<T>.CheckForm: Boolean; begin if FCheckStateID then Result := inherited CheckForm else Result := GOM.IsObj(ThreadForm) and not IsTerminated {$IFNDEF EXTERNAL}and not DBTerminating{$ENDIF}; end; constructor TThreadTask<T>.Create(AOwnerForm: TThreadForm; Data: T; CheckStateID: Boolean; Proc: TTaskThreadProcedureEx); begin inherited Create(AOwnerForm, AOwnerForm.StateID); FProc := Proc; FData := Data; FCheckStateID := CheckStateID; end; procedure TThreadTask<T>.Execute; begin inherited; FreeOnTerminate := True; try FProc(Self, FData); except on e: Exception do EventLog(e); end; end; function TThreadTask<T>.SynchronizeTask(Proc: TThreadProcedure): Boolean; begin Result := SynchronizeEx(Proc); end; end.
unit MainModule; interface uses uniGUIMainModule, SysUtils, Classes, UniProvider, MySQLUniProvider, Data.DB, DBAccess, Uni, uniGUIBaseClasses, uniGUIClasses, uniImageList, MemDS; type TScreenMode = (SM_Browse, SM_Edit, SM_Insert, SM_Search); // to know the status of current mode to enable or do // somthing as the currrent status of screen. type TUniMainModule = class(TUniGUIMainModule) MainDB: TUniConnection; MySQLUniProvider1: TMySQLUniProvider; NAVimg: TUniNativeImageList; NAVimg24: TUniNativeImageList; ImgTol32: TUniNativeImageList; ReportQuery: TUniQuery; ReportDS: TUniDataSource; LangQry: TUniQuery; LangQryID: TIntegerField; LangQryENtext: TWideStringField; LangQryARtext: TWideStringField; LangQryFieldW: TIntegerField; LangQryIsSummry: TBooleanField; procedure UniGUIMainModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } procedure SaveRTL(const Value: Boolean);// for InterFace language // --- ---=== Global Variables ===--- --- var LoggedUserNam,UserID : String; StartPath, ReportsPath : String; gSysMessages, gSysMessagesA : TStringList; // Ar En Messages; // testTXT:String; //Company Images Path Files LoginImg,LogBgImg,HomeImg,LogoImg,PDFsPath:String; ///Settings Params; gSendSMS:String; end; function UniMainModule: TUniMainModule; implementation {$R *.dfm} uses UniGUIVars, ServerModule, uniGUIApplication; function UniMainModule: TUniMainModule; begin Result := TUniMainModule(UniApplication.UniMainModule) end; //------------------------------------------------------------------------------ procedure TUniMainModule.SaveRTL(const Value: Boolean); begin // Save RTL in Cookies UniGUIApplication.UniApplication.Cookies.SetCookie('_RTL', BoolToStr(Value), Date + 7.0); (UniApplication as TUniGUIApplication).Restart; end; procedure TUniMainModule.UniGUIMainModuleCreate(Sender: TObject); begin //Lang RTL By Cookies if UniGUIApplication.UniApplication.Cookies.Values['_RTL'] = '' then Self.RTL:=false else Self.RTL := StrToBool(UniGUIApplication.UniApplication.Cookies.Values['_RTL']); //MainDB.Password:= 'royalR*2020'; MainDB.Connect; LangQry.Open; // COmpany IMAGES Files Path; LoginImg := UniServerModule.FilesFolderPath+'/CmpImages/Login.png'; LogBgImg := UniServerModule.FilesFolderPath+'/CmpImages/LogBG.png'; HomeImg := UniServerModule.FilesFolderPath+'/CmpImages/Home.png'; LogoImg := UniServerModule.FilesFolderPath+'/CmpImages/Logo.png'; PDFsPath := UniServerModule.FilesFolderPath+'PDFs/'; // init System G_Variables StartPath := uniServerModule.StartPath; ReportsPath := StartPath + 'Reports/' ; //*Load System Messages to Parameters* gSysMessages:=TStringList.Create; gSysMessages.LoadFromFile(UniServerModule.FilesFolderPath+'MessageE.mf'); gSysMessagesA:=TStringList.Create; gSysMessagesA.LoadFromFile(UniServerModule.FilesFolderPath+'MessageA.mf'); end; initialization RegisterMainModuleClass(TUniMainModule); end.
unit QME_Classes; interface uses Windows, SysUtils, StrUtils, Classes, ItemList, Utils; type EQAReferenceError = class(Exception); TFileNameEvent = procedure(Sender: TObject; const FileName: string) of object; TQAImage = class(TMemoryStream) private FFmtName: string[31]; FOnFileName: TFileNameEvent; function GetExt: string; protected property Ext: string read GetExt; public constructor CreateFromFile(const FileName: string); function Info: string; procedure RequireFileName; property OnFileName: TFileNameEvent read FOnFileName write FOnFileName; end; TAnswerWay = (awSelect, awCreate, awPlace, awRelate); TAnswerWays = set of TAnswerWay; TQAProp = (qapID, qapText, qapImage, qapWay, qapPoints, qapSelection, qapImmediate, qapAnswer, qapComplete); TQAProps = set of TQAProp; TQAChangeEvent = procedure(Sender: TObject; Props: TQAProps) of object; TQA = class(TItem) private FID: Integer; FText: string; FImage: TQAImage; FWay: TAnswerWays; FPoints: IDStrArray; FImmediate: StrArray; FAnswer: IntArray; FComplete: Boolean; FVisObj: TObject; FSolved: Real; FSavedAnswer: StrArray; FAutoSelection: IntArray; FOnChange: TQAChangeEvent; FOnDestroy: TNotifyEvent; procedure CompleteAnswer; function GetAnswer: StrArray; function GetIndex: Integer; function GetPoints: StrArray; function GetQuestionPoints: StrArray; function GetSelection: BoolArray; function GetSolved: Real; function GetSummary: StrArray; function IDText(ID: Integer): string; procedure RestoreAnswer; procedure SaveAnswer; procedure SetAnswer(const Value: StrArray); procedure SetComplete(const Value: Boolean); procedure SetID(const Value: Integer); procedure SetImage(const Value: TQAImage); procedure SetImmediate(const Value: StrArray); procedure SetPoints(const Value: StrArray); procedure SetSelection(const Value: BoolArray); procedure SetText(const Value: string); procedure SetWay(const Value: TAnswerWays); function TextID(const Text: string): Integer; procedure UpdateIsRelate; protected FChecked: Boolean; procedure Changed(Props: TQAProps); virtual; function GetReference: TQA; virtual; procedure MixUpIDs; procedure ResetAnswer; public destructor Destroy; override; procedure EndSetImmediate; procedure MixUpPoints; procedure PrepareForEdit; property Answer: StrArray read GetAnswer write SetAnswer; property Complete: Boolean read FComplete write SetComplete; property ID: Integer read FID write SetID; property Image: TQAImage read FImage write SetImage; property Index: Integer read GetIndex; property Immediate: StrArray read FImmediate write SetImmediate; property Points: StrArray read GetPoints write SetPoints; property QuestionPoints: StrArray read GetQuestionPoints; property Reference: TQA read GetReference; property Selection: BoolArray read GetSelection write SetSelection; property Solved: Real read GetSolved; property Summary: StrArray read GetSummary; property Text: string read FText write SetText; property VisObj: TObject read FVisObj write FVisObj; property Way: TAnswerWays read FWay write SetWay; property OnChange: TQAChangeEvent read FOnChange write FOnChange; property OnDestroy: TNotifyEvent read FOnDestroy write FOnDestroy; end; TQAList = class(TItemList) private FID: Integer; FTitle: string; FAuthor: string; FRefFile: string; FReference: TQAList; FOnChange: TNotifyEvent; function GetItem(Index: Integer): TQA; function GetQA(ID: Integer): TQA; function GetReference: TQAList; function GetSolved: Real; procedure SetSource(const Value: string); procedure SetTitle(const Value: string); protected procedure Changed; virtual; procedure Notification(Item: TItem; Action: TItemAction); override; public function AllComplete: Boolean; destructor Destroy; override; constructor CreateFromFile(const FileName: string); constructor CreateFromStream(Stream: TStream); constructor CreateFromTextStream(Stream: TStream); function IncompleteCount: Integer; procedure SaveToFile(const FileName: string); procedure SaveToStream(Stream: TStream); procedure SaveToTextStream(Stream: TStream); procedure SetQuestions(ACount: Integer); procedure Sort(SortProp: TQAProp; Descending: Boolean = False); function UniqueID: Integer; property Author: string read FAuthor write SetSource; property Items[Index: Integer]: TQA read GetItem; default; property QA[ID: Integer]: TQA read GetQA; property Reference: TQAList read GetReference; property RefFile: string read FRefFile write FRefFile; property Solved: Real read GetSolved; property Title: string read FTitle write SetTitle; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; const SelectedSign = '+'; UnselectedSign = '-'; CreateSign = '*'; PointSign = '.'; ImageLinkSign = '~'; EOL = #13#10; SQAClass = '.qme'; STextClass = '.txt'; SAnyClass = '.*'; AllQAProps = [qapID, qapText, qapImage, qapWay, qapPoints, qapSelection, qapImmediate, qapAnswer, qapComplete]; function SupportPoints(Way: TAnswerWays): Boolean; function AnswerWayToStr(Way: TAnswerWays): string; var StreamImages: Boolean = True; RefsPath: string; implementation uses RTLConsts, Masks_2, ExtUtils, Math; const QASignature: array[0..3] of Char = 'QME0'; {}OldSignature: array[0..3] of Char = 'PTT0'; resourcestring SImageTmpFile = '%sQME%.8x%s'; SImageInfo = '%s, %d КБ'; SNoReference = 'Отсуствует референсный вопрос-ответ для # %d'; SInvalidReference = 'Вопрос-ответ не является референсным для # %d'; function SupportPoints(Way: TAnswerWays): Boolean; begin Result := Way * [awSelect, awPlace] <> []; end; function UnconditionalPoints(Way: TAnswerWays): Boolean; begin Result := Way * [awSelect, awPlace] = [awPlace]; end; function AnswerWayToStr(Way: TAnswerWays): string; const WaySigns: array[TAnswerWay] of Char = (SelectedSign, CreateSign, '#', '='); var I: Integer; W: TAnswerWay; Buf: array[0..15] of Char; begin if awRelate in Way then Exclude(Way, awPlace); I := 0; for W := Low(TAnswerWay) to High(TAnswerWay) do if W in Way then begin Buf[I] := WaySigns[W]; Inc(I); end; SetString(Result, Buf, I); end; { TQAImage } constructor TQAImage.CreateFromFile(const FileName: string); begin FFmtName := UpperCase(Copy(ExtractFileExt(FileName), 2, MaxInt)); LoadFromFile(FileName); end; function TQAImage.GetExt: string; begin Result := '.' + LowerCase(FFmtName); end; function TQAImage.Info: string; begin if Self <> nil then Result := Format(SImageInfo, [FFmtName, Ceil(Size / $400)]); end; procedure TQAImage.RequireFileName; var Buf: array[0..MAX_PATH - 1] of Char; FileName: string; begin if Assigned(FOnFileName) then begin GetTempPath(SizeOf(Buf), Buf); repeat FileName := Format(SImageTmpFile, [Buf, Random(MaxInt), Ext]); until not FileExists(FileName); SaveToFile(FileName); FOnFileName(Self, FileName); DeleteFile(FileName); end; end; { TQA } procedure TQA.Changed(Props: TQAProps); begin FChecked := False; if Assigned(FOnChange) then FOnChange(Self, Props); NotifyChange; end; procedure TQA.CompleteAnswer; var PC, AC, I: Integer; begin PC := Length(FPoints); AC := Length(FAnswer); SetLength(FAnswer, PC + Length(FImmediate)); if UnconditionalPoints(FWay) then for I := 0 to PC - 1 do AddInt(FAnswer, FPoints[I].ID, AC); if awCreate in FWay then for I := PC to PC + High(FImmediate) do AddInt(FAnswer, I, AC); SetLength(FAnswer, AC); end; destructor TQA.Destroy; begin if Assigned(FOnDestroy) then FOnDestroy(Self); FImage.Free; inherited; end; procedure TQA.EndSetImmediate; begin FAutoSelection := nil; end; function TQA.GetAnswer: StrArray; var I: Integer; begin SetLength(Result, Length(FAnswer)); for I := 0 to High(FAnswer) do Result[I] := IDText(FAnswer[I]); end; function TQA.GetIndex: Integer; begin Result := -1; if Owner <> nil then Result := Owner.IndexOf(Self); end; function TQA.GetPoints: StrArray; var I: Integer; begin SetLength(Result, Length(FPoints)); for I := 0 to High(FPoints) do Result[I] := FPoints[I].S; end; function TQA.GetQuestionPoints: StrArray; const MaxCount = 100; var I, J, P, Len: Integer; S: string; begin Len := Length(FText); SetLength(Result, MaxCount); P := 1; I := 0; while (P < Len) and (I < MaxCount) do begin S := Format('%d) ', [I + 1]); P := PosEx(S, FText, P); if P = 0 then Break; J := P; Inc(P, Length(S)); if (J = 1) or (FText[J - 1] = ' ') then begin J := P; while (J <= Len) and not (FText[J] in [';', '.', '?']) do Inc(J); Result[I] := Copy(FText, P, J - P); P := J + 1; Inc(I); end; end; SetLength(Result, I); end; function TQA.GetReference: TQA; begin Result := nil; if (Owner is TQAList) then Result := TQAList(Owner).Reference.GetQA(FID); if Result = nil then raise EQAReferenceError.CreateResFmt(@SNoReference, [FID]); end; function TQA.GetSelection: BoolArray; var I: Integer; begin if awSelect in FWay then begin Setlength(Result, Length(FPoints)); for I := 0 to High(FPoints) do Result[I] := IntIndex(FPoints[I].ID, FAnswer) <> -1; end; end; function TQA.GetSolved: Real; function ConvertIndexes(const Indexes: IntArray; IndexBase: Integer; const SourceStrs, TargetStrs: StrArray): IntArray; var I, J, X: Integer; Avail: BoolArray; Found: Boolean; begin if (SourceStrs <> nil) and (TargetStrs <> nil) then begin Result := Copy(Indexes, 0, MaxInt); SetLength(Avail, Length(TargetStrs)); FillChar(Avail[0], Length(Avail), True); X := IndexBase + Length(TargetStrs); for I := 0 to High(Indexes) do begin J := Indexes[I] - IndexBase; if J >= 0 then begin Found := False; with TMask.Create(SourceStrs[J]) do try for J := 0 to High(TargetStrs) do if Avail[J] and Matches(TargetStrs[J]) then begin Result[I] := IndexBase + J; Avail[J] := False; Found := True; Break; end; finally Free; end; if not Found then begin Result[I] := X; Inc(X); end; end; end; end else Result := Indexes; end; function SelectionSimilarity(const A, B: IntArray): Real; var I, Sum, Intersect: Integer; begin Sum := Length(A) + Length(B); if Sum > 0 then begin Intersect := 0; for I := 0 to High(A) do if IntIndex(A[I], B) <> -1 then Inc(Intersect); Result := Intersect / (Sum - Intersect); end else Result := 1.0; end; function OrderSimilarity(const A, B: IntArray): Real; function SumDistances(n: Integer): Integer; begin Result := (n*n*n - n) div 6; end; function SumAbsDistanceDif(const A, B: IntArray): Integer; function IndexLUT(const A: IntArray; Len: Integer): IntArray; var I: Integer; begin SetLength(Result, Len); for I := 0 to Len - 1 do Result[I] := -1; for I := 0 to High(A) do Result[A[I]] := I; end; var I, J, X, Y, D: Integer; AIndexes, BIndexes: IntArray; begin J := 0; for I := 0 to High(A) do if J < A[I] then J := A[I]; for I := 0 to High(B) do if J < B[I] then J := B[I]; Inc(J); AIndexes := IndexLUT(A, J); BIndexes := IndexLUT(B, J); Result := 0; for I := 0 to High(A) - 1 do for J := I + 1 to High(A) do begin X := BIndexes[A[I]]; Y := BIndexes[A[J]]; if (X <> -1) and (Y <> -1) then D := Y - X else D := 0; Inc(Result, Abs(D - (J - I))); end; for I := 0 to High(B) - 1 do for J := I + 1 to High(B) do if (AIndexes[B[I]] = -1) or (AIndexes[B[J]] = -1) then Inc(Result, J - I); end; var ALen, BLen: Integer; begin ALen := Length(A); BLen := Length(B); if (ALen > 1) and (BLen > 1) then Result := 1.0 - SumAbsDistanceDif(A, B) / (SumDistances(ALen) + SumDistances(BLen)) else if (ALen = BLen) and ((ALen = 0) or (A[0] = B[0])) then Result := 1.0 else Result := 0.0; end; function SequenceSimilarity(const A, B: IntArray): Real; var Len, Equal, I: Integer; begin Len := Max(Length(A), Length(B)); if Len > 0 then begin Equal := 0; for I := 0 to Min(High(A), High(B)) do if A[I] = B[I] then Inc(Equal); Result := Equal / Len; end else Result := 1.0; end; function AnswerSimilarity(AReference: TQA): Real; var A, B: IntArray; begin if (FWay <> AReference.FWay) or (Length(FPoints) <> Length(AReference.FPoints)) then raise EQAReferenceError.CreateResFmt(@SInvalidReference, [FID]); A := FAnswer; if awCreate in FWay then B := ConvertIndexes(AReference.FAnswer, Length(FPoints), AReference.FImmediate, FImmediate) else B := AReference.FAnswer; if awPlace in FWay then if awRelate in FWay then Result := SequenceSimilarity(A, B) else Result := OrderSimilarity(A, B) else Result := SelectionSimilarity(A, B); end; begin if not FChecked then begin FSolved := AnswerSimilarity(GetReference); FChecked := True; end; Result := FSolved; end; function TQA.GetSummary: StrArray; var I: Integer; procedure AddFmt(const Fmt: string; const Args: array of const); begin Result[I] := Format(Fmt, Args); Inc(I); end; function PointsToStr(APoints: IDStrArray): string; var I: Integer; begin for I := 0 to High(APoints) do with APoints[I] do Result := Format('%s%d="%s"; ', [Result, ID, S]); end; begin I := 0; SetLength(Result, 16); AddFmt('ID = %d', [FID]); AddFmt('Text = %s', [FText]); if FImage <> nil then AddFmt('Image: %d bytes, %s', [FImage.Size, FImage.FFmtName]); AddFmt('Way = %s', [AnswerWayToStr(FWay)]); AddFmt('Points (%d): %s', [Length(FPoints), PointsToStr(FPoints)]); AddFmt('Immediate (%d): %s', [Length(FImmediate), ArrayToStr(FImmediate, ', ', '"', '"')]); AddFmt('Answer (%d): %s', [Length(FAnswer), IntsToStr(FAnswer)]); AddFmt('Complete = %s', [BoolToStr(FComplete)]); AddFmt('VisObj = %.8x', [Cardinal(FVisObj)]); if FChecked then AddFmt('Solved = %g', [FSolved]); AddFmt('SavedAnswer = %s', [ArrayToStr(FSavedAnswer, ', ', '"', '"')]); AddFmt('AutoSelection: %s', [IntsToStr(FAutoSelection)]); AddFmt('Index = %d', [GetIndex]); SetLength(Result, I); end; function TQA.IDText(ID: Integer): string; var I: Integer; begin Result := '<N/A>'; if ID < Length(FPoints) then begin if SupportPoints(FWay) then begin I := IDIndex(ID, FPoints); if I <> -1 then Result := FPoints[I].S; end; end else if awCreate in FWay then begin Dec(ID, Length(FPoints)); if ID < Length(FImmediate) then Result := FImmediate[ID]; end; end; procedure TQA.MixUpIDs; var Len, I, ID: Integer; MixTable: IntArray; begin Len := Length(FPoints); MixTable := RandomOrder(Len); for I := 0 to Len - 1 do with FPoints[I] do ID := MixTable[ID]; for I := 0 to High(FAnswer) do begin ID := FAnswer[I]; if ID < Len then FAnswer[I] := MixTable[ID]; end; end; procedure TQA.MixUpPoints; var Len, I: Integer; MixTable: IntArray; A: IDStrArray; begin Len := Length(FPoints); MixTable := RandomOrder(Len); SetLength(A, Len); for I := 0 to Len - 1 do A[I] := FPoints[MixTable[I]]; FPoints := A; Changed([qapPoints, qapSelection]); end; procedure TQA.PrepareForEdit; begin SaveAnswer; end; procedure TQA.ResetAnswer; var Len, I: Integer; MixTable: IntArray; begin FImmediate := nil; if UnconditionalPoints(FWay) then begin Len := Length(FPoints); SetLength(FAnswer, Len); MixTable := RandomOrder(Len); for I := 0 to Len - 1 do FAnswer[I] := FPoints[MixTable[I]].ID; end else FAnswer := nil; FComplete := False; Changed([qapImmediate, qapAnswer, qapComplete]); MixTable := nil; end; procedure TQA.RestoreAnswer; var Len, PC, IC, AC, I, J: Integer; S: string; begin Len := Length(FSavedAnswer); SetLength(FAnswer, Len); SetLength(FImmediate, Len); PC := Length(FPoints); IC := 0; AC := 0; for I := 0 to Len - 1 do begin S := FSavedAnswer[I]; J := StrIndex(S, FPoints); if J <> -1 then begin FAnswer[AC] := FPoints[J].ID; Inc(AC); end else if awCreate in FWay then begin FImmediate[IC] := S; FAnswer[AC] := PC + IC; Inc(IC); Inc(AC); end; end; SetLength(FAnswer, AC); SetLength(FImmediate, IC); CompleteAnswer; end; procedure TQA.SaveAnswer; begin FSavedAnswer := GetAnswer; end; procedure TQA.SetAnswer(const Value: StrArray); var AC, I, ID: Integer; begin AC := 0; for I := 0 to High(Value) do begin ID := TextID(Value[I]); if ID <> -1 then AddInt(FAnswer, ID, AC); end; SetLength(FAnswer, AC); CompleteAnswer; SaveAnswer; Changed([qapAnswer]); end; procedure TQA.SetComplete(const Value: Boolean); begin FComplete := Value; Changed([qapComplete]); end; procedure TQA.SetID(const Value: Integer); begin FID := Value; Changed([qapID]); end; procedure TQA.SetImage(const Value: TQAImage); begin if FImage <> nil then FImage.Free; FImage := Value; Changed([qapImage]); end; procedure TQA.SetImmediate(const Value: StrArray); var Temp: StrArray; SC, AC, IC, I, J, ID, PC, AC1: Integer; Change: TQAProps; S: string; begin if awCreate in FWay then begin Temp := Copy(FImmediate, 0, MaxInt); if (awSelect in FWay) and (FAutoSelection <> nil) then RemoveInts(FAnswer, FAutoSelection); SC := 0; IC := 0; AC := Length(FAnswer); Change := [qapImmediate, qapAnswer]; for I := 0 to High(Value) do begin S := FilterStr(Value[I]); if S <> '' then begin J := StrIndex(S, FPoints); if J <> -1 then begin if awSelect in FWay then begin ID := FPoints[J].ID; if AddInt(FAnswer, ID, AC) then begin AddInt(FAutoSelection, ID, SC); Include(Change, qapSelection); end; end; end else AddStr(FImmediate, S, IC); end; end; SetLength(FAutoSelection, SC); SetLength(FImmediate, IC); PC := Length(FPoints); AC1 := 0; for I := 0 to AC - 1 do begin ID := FAnswer[I]; if ID >= PC then begin ID := StrIndex(Temp[ID - PC], FImmediate); if ID <> -1 then Inc(ID, PC); end; if ID <> -1 then begin FAnswer[AC1] := ID; Inc(AC1); end; end; SetLength(FAnswer, AC1); CompleteAnswer; SaveAnswer; Changed(Change); end; Temp := nil; end; procedure TQA.SetPoints(const Value: StrArray); var PC, I: Integer; IDs: IntArray; begin if SupportPoints(FWay) then begin PC := 0; for I := 0 to High(Value) do AddStr(FPoints, FilterStr(Value[I]), PC); SetLength(FPoints, PC); IDs := RandomOrder(PC); for I := 0 to PC - 1 do FPoints[I].ID := IDs[I]; RestoreAnswer; Changed([qapPoints, qapImmediate, qapAnswer, qapSelection]); end; IDs := nil; end; procedure TQA.SetSelection(const Value: BoolArray); var AC, DC, Len, I, ID: Integer; Del: IntArray; begin if awSelect in FWay then begin AC := Length(FAnswer); DC := 0; Len := Length(Value); for I := 0 to High(FPoints) do begin ID := FPoints[I].ID; if (I < Len) and Value[I] then AddInt(FAnswer, ID, AC) else AddInt(Del, ID, DC); end; SetLength(FAnswer, AC); SetLength(Del, DC); RemoveInts(FAnswer, Del); SaveAnswer; Changed([qapSelection, qapAnswer]); end; end; procedure TQA.SetText(const Value: string); begin FText := FilterStr(Value); UpdateIsRelate; Changed([qapText]); end; procedure TQA.SetWay(const Value: TAnswerWays); var Change: TQAProps; begin if Value <> FWay then begin Change := [qapWay]; if FPoints <> nil then begin if not SupportPoints(Value) then begin Change := Change + [qapPoints, qapAnswer]; if awCreate in Value then Include(Change, qapImmediate); FPoints := nil; end else if (awSelect in FWay) <> (awSelect in Value) then begin Include(Change, qapAnswer); if (awSelect in Value) then Include(Change, qapSelection); end; end; if (FImmediate <> nil) <> (awCreate in Value) then begin Change := Change + [qapImmediate, qapAnswer]; FImmediate := nil; end; FWay := Value; UpdateIsRelate; RestoreAnswer; Changed(Change); end; end; function TQA.TextID(const Text: string): Integer; begin Result := StrIndex(Text, FPoints); if Result <> -1 then Result := FPoints[Result].ID else if awCreate in FWay then begin Result := StrIndex(Text, FImmediate); if Result <> -1 then Inc(Result, Length(FPoints)); end; end; procedure TQA.UpdateIsRelate; var I, J: Integer; begin if awPlace in FWay then begin Exclude(FWay, awRelate); I := Pos('1) ', FText); J := Pos(' 2) ', FText); if (I > 0) and (J > I) then Include(FWay, awRelate); end; end; { TQAList } function TQAList.AllComplete: Boolean; begin Result := IncompleteCount = 0; end; procedure TQAList.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; constructor TQAList.CreateFromFile(const FileName: string); var Stream: TStream; CurrentDir: string; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try if SameText(ExtractFileExt(FileName), SQAClass) then CreateFromStream(Stream) else if SameText(ExtractFileExt(FileName), STextClass) then begin CurrentDir := GetCurrentDir; try SetCurrentDir(ExtractFilePath(ExpandFileName(FileName))); CreateFromTextStream(Stream); finally SetCurrentDir(CurrentDir); end; end; finally Stream.Free; end; end; constructor TQAList.CreateFromStream(Stream: TStream); var Signature: LongWord; I, J: Integer; ImageHdr: string; {}OldFormat: Boolean; begin with TReader.Create(Stream, $1000) do try Read(Signature, SizeOf(Signature)); {}OldFormat := Signature = LongWord(OldSignature); {}if not OldFormat then if Signature <> LongWord(QASignature) then raise EReadError.CreateRes(@SInvalidImage); FID := ReadInteger; FTitle := ReadString; Capacity := ReadInteger; for I := 0 to Capacity - 1 do with TQA.Create(Self) do begin FID := ReadInteger; FText := ReadString; {}if OldFormat then {}begin {} if ReadBoolean then {} begin {} FImage := TQAImage.Create; {} FImage.FFmtName := ReadString; {} DefineBinaryProperty('', FImage.LoadFromStream, nil, True); {} ReadString; {} end {}end else {}begin ImageHdr := ReadStr; if ImageHdr <> '' then if StreamImages then begin FImage := TQAImage.Create; with FImage do begin DefineBinaryProperty('', LoadFromStream, nil, True); FFmtName := ImageHdr; end; end else SkipValue; {}end; FWay := TAnswerWays(Byte(ReadInteger)); SetLength(FPoints, ReadInteger); for J := 0 to High(FPoints) do with FPoints[J] do begin ID := ReadInteger; S := ReadString; end; SetLength(FImmediate, ReadInteger); for J := 0 to High(FImmediate) do FImmediate[J] := ReadString; SetLength(FAnswer, ReadInteger); for J := 0 to High(FAnswer) do FAnswer[J] := ReadInteger; FComplete := ReadBoolean; end; FAuthor := ReadString; FRefFile := ReadString; finally Free; end; end; constructor TQAList.CreateFromTextStream(Stream: TStream); var TextReader: TTextReader; ErrorCount, Len, I, EC, PC, IC, AC: Integer; AtBegin, Success, OuterLoop: Boolean; S, P, T: PChar; C: Char; procedure SkipBlanks; begin while (P < T) and (P^ <= ' ') do Inc(P); end; function TerminateStr: Boolean; begin T := S + Len - 1; while (T >= S) and (T <= ' ') do Dec(T); Inc(T); T^ := #0; // Result := S < T; P := S; SkipBlanks; S := P; end; function GetStr: string; var Temp: string; begin SetString(Temp, P, T - P); Result := FilterStr(Temp); end; begin TextReader := TTextReader.Create(Stream{}.Read{}); try ErrorCount := 0; AtBegin := True; while TextReader.Read(S, Len) do if TerminateStr then begin repeat Success := False; OuterLoop := True; case S^ of '0'..'9': begin while P^ in ['0'..'9', 'x'] do Inc(P); if P^ <> '.' then Break; P^ := #0; Val(S, I, EC); if EC <> 0 then Break; SkipBlanks; if (P = T) or (T - P > 1024) then Break; Success := True; if QA[I] <> nil then I := UniqueID; with TQA.Create(Self) do begin FID := I; FText := GetStr; PC := 0; IC := 0; AC := 0; while TextReader.Read(S, Len) do if TerminateStr then begin C := P^; Inc(P); SkipBlanks; case C of ImageLinkSign: if (T - P <= MAX_PATH) and (FImage = nil) and StreamImages then try FImage := TQAImage.CreateFromFile(GetStr); except end; SelectedSign, UnselectedSign, CreateSign, '>', PointSign: begin case C of SelectedSign, UnselectedSign: Include(FWay, awSelect); CreateSign, '>': Include(FWay, awCreate); PointSign: Include(FWay, awPlace); end; if {C <> }not (C in [CreateSign, '>']) then begin I := PC; AddStr(FPoints, GetStr, PC); end else begin AddStr(FImmediate, GetStr, IC); I := -IC; end; if C <> UnselectedSign then AddInt(FAnswer, I, AC); end; else P := S; OuterLoop := False; Break; end; end else if FWay <> [] then Break; UpdateIsRelate; SetLength(FPoints, PC); SetLength(FImmediate, IC); SetLength(FAnswer, AC); for I := 0 to High(FAnswer) do if FAnswer[I] < 0 then begin FAnswer[I] := PC; Inc(PC); end; RandSeed := FID * FID; MixUpIDs; end; AtBegin := False; end; '#': if AtBegin and (FID = 0) then begin Inc(P); SkipBlanks; Val(P, I, EC); if (EC = 0) and (I > 0) then begin FID := I; Success := True; end; end; '@': if FAuthor = '' then begin Inc(P); SkipBlanks; if (P < T) and (T - P <= $80) then begin FAuthor := GetStr; Success := True; end; end; '[', '+', '>': if T - P <=10 then Success := True; else if AtBegin and (FTitle = '') and (T - P <= $80) then begin FTitle := GetStr; Success := True; end; end; until OuterLoop; if not Success then begin Inc(ErrorCount); if ErrorCount > Count + 10 then raise Exception.Create(''); end; end; finally TextReader.Free; end; end; destructor TQAList.Destroy; begin FReference.Free; inherited; end; function TQAList.GetItem(Index: Integer): TQA; begin Result := inherited Items[Index]; end; function TQAList.GetQA(ID: Integer): TQA; var I: Integer; begin for I := 0 to Count - 1 do begin Result := Get(I); if Result.FID = ID then Exit; end; Result := nil; end; function TQAList.GetReference: TQAList; begin if FReference = nil then begin StreamImages := False; try FReference := TQAList.CreateFromFile(RefsPath + FRefFile); finally StreamImages := True; end; end; Result := FReference; end; function TQAList.GetSolved: Real; var I, J: Integer; F: Real; begin F := 0.0; J := 0; for I := 0 to Count - 1 do if Items[I].FComplete then begin F := F + Items[I].GetSolved; Inc(J); end; if J > 0 then Result := F / J else Result := 1.0; end; function TQAList.IncompleteCount: Integer; var I: Integer; begin Result := 0; for I := 0 to Count - 1 do if not Items[I].FComplete then Inc(Result); end; procedure TQAList.Notification(Item: TItem; Action: TItemAction); var I, J: integer; begin if Action = iaAdded then with TQA(Item) do if Owner <> self then begin J := IndexOf(Item); for I := 0 to Count - 1 do if (I <> J) and (ID = Items[I].ID) then begin {!}FID := UniqueID; // very slow Break; end; end; inherited; Changed; end; procedure TQAList.SaveToFile(const FileName: string); var Stream: TStream; CurrentDir: string; begin Stream := TFileStream.Create(FileName, fmCreate); try if LowerCase(ExtractFileExt(FileName)) = SQAClass then SaveToStream(Stream) else begin CurrentDir := GetCurrentDir; try SetCurrentDir(ExtractFilePath(ExpandFileName(FileName))); SaveToTextStream(Stream); finally SetCurrentDir(CurrentDir); end; end; finally Stream.Free; end; end; procedure TQAList.SaveToStream(Stream: TStream); var I, J: Integer; begin with TWriter.Create(Stream, $1000) do try Write(QASignature, SizeOf(QASignature)); WriteInteger(FID); WriteString(FTitle); WriteInteger(Count); for I := 0 to Count - 1 do with Items[I] do begin WriteInteger(FID); WriteString(FText); if (FImage <> nil) and StreamImages then with FImage do DefineBinaryProperty(FFmtName, nil, SaveToStream, True) else WriteListEnd; WriteInteger(Byte(FWay)); WriteInteger(Length(FPoints)); for J := 0 to High(FPoints) do with FPoints[J] do begin WriteInteger(ID); WriteString(S); end; WriteInteger(Length(FImmediate)); for J := 0 to High(FImmediate) do WriteString(FImmediate[J]); WriteInteger(Length(FAnswer)); for J := 0 to High(FAnswer) do WriteInteger(FAnswer[J]); WriteBoolean(FComplete); end; WriteString(FAuthor); WriteString(FRefFile); finally Free; end; end; resourcestring SID = ' # %d' + EOL; STitle = ' %s' + EOL; SQuestion = '%d. %s' + EOL; SImageFileName = 'quest_%d%s'; SImageLink = ImageLinkSign + '%s' + EOL; SPoint = ' %s %s' + EOL; SFrom = ' @ %s' + EOL; procedure TQAList.SaveToTextStream(Stream: TStream); var Writer: TWriter; procedure WriteFmt(const Format: string; const Args: array of const); var Buffer: array[0..4095] of Char; begin Writer.Write(Buffer, FormatBuf(Buffer, SizeOf(Buffer), Pointer(Format)^, Length(Format), Args)); end; const WaySigns: array[awSelect..awPlace] of Char = (SelectedSign, CreateSign, PointSign); PointSigns: array[Boolean] of Char = (SelectedSign, PointSign); var I, J, A: Integer; C: Char; TempStr: string; PointIncl: array[Boolean] of Boolean; W: TAnswerWay; WriteWay: TAnswerWays; begin Writer := TWriter.Create(Stream, 1 shl 12); try if FID <> 0 then WriteFmt(SID, [FID]); if FTitle <> '' then WriteFmt(STitle, [FTitle]); if (FID <> 0) or (FTitle <> '') then WriteFmt(EOL, []); for I := 0 to Count - 1 do with Items[I] do begin WriteFmt(SQuestion, [FID, FText]); if (FImage <> nil) and StreamImages then try TempStr := Format(SImageFileName, [FID, FImage.Ext]); WriteFmt(SImageLink, [TempStr]); FImage.SaveToFile(TempStr); except end; FillChar(PointIncl, SizeOf(PointIncl), False); for J := 0 to High(FPoints) do PointIncl[IntIndex(FPoints[J].ID, FAnswer) <> -1] := True; WriteWay := FWay; if (PointIncl[True] and not (awPlace in FWay)) or PointIncl[False] then Exclude(WriteWay, awSelect); if FImmediate <> nil then Exclude(WriteWay, awCreate); if PointIncl[True] then Exclude(WriteWay, awPlace); for W := awSelect to awPlace do if W in WriteWay then WriteFmt(SPoint, [WaySigns[W], '']); for J := 0 to High(FAnswer) do begin A := FAnswer[J]; if A < Length(FPoints) then C := PointSigns[awPlace in FWay] else C := CreateSign; WriteFmt(SPoint, [C, IDText(A)]); end; if awSelect in FWay then for J := 0 to High(FPoints) do with FPoints[J] do if IntIndex(ID, FAnswer) = -1 then WriteFmt(SPoint, [UnselectedSign, S]); WriteFmt(EOL, []); end; WriteFmt(EOL, []); if FAuthor <> '' then WriteFmt(SFrom, [FAuthor]); finally Writer.Free; end; end; procedure TQAList.SetQuestions(ACount: Integer); var Base: TQAList; Indexes: IntArray; Temp: TQA; I: Integer; begin Base := TQAList.CreateFromFile(RefsPath + FRefFile); try if ACount > Base.Count then ACount := Base.Count; Indexes := RandomOrder(Base.Count, ACount); Clear; Capacity := ACount; for I := 0 to ACount - 1 do begin Temp := Base[Indexes[I]]; Temp.ResetAnswer; Temp.MixUpPoints; Add(Temp); end; finally Base.Free; end; end; procedure TQAList.SetSource(const Value: string); begin FAuthor := Value; Changed; end; procedure TQAList.SetTitle(const Value: string); begin FTitle := Value; Changed; end; threadvar SortByProp: TQAProp; SortDescending: Boolean; procedure TQAList.Sort(SortProp: TQAProp; Descending: Boolean); function Compare(Item1, Item2: TQA): Integer; begin case SortByProp of qapID: Result := Item1.ID - Item2.ID; qapText: Result := AnsiCompareText(Item1.Text, Item2.Text); qapImage: Result := AnsiCompareText(Item1.Image.Info, Item2.Image.Info); qapWay: Result := Byte(Item1.Way) - Byte(Item2.Way); qapPoints: Result := Length(Item1.FPoints) - Length(Item2.FPoints); qapComplete: Result := Ord(Item1.Complete) - Ord(Item2.Complete); else Result := 0; end; if SortDescending then Result := -Result; end; begin SortByProp := SortProp; SortDescending := Descending; inherited Sort(@Compare); end; function TQAList.UniqueID: Integer; function CompareIDs(Item1, Item2: TQA): Integer; begin Result := Item1.ID - Item2.ID; end; var I, J: Integer; begin with TList.Create do try Assign(Self); Sort(@CompareIDs); I := 0; while (I < Count) and (TQA(Items[I]).ID < 0) do Inc(I); Result := 0; for I := I to Count - 1 do begin J := TQA(Items[I]).ID; if J > Result then Exit; Result := J + 1; end; finally Free; end; end; initialization RefsPath := ExtractFilePath(Paramstr(0)) + 'Books\'; end.
unit uEditStyleHookColor; interface uses System.UITypes, Winapi.Windows, Winapi.Messages, VCL.StdCtrls, Vcl.ExtCtrls, Vcl.Graphics, Vcl.Controls, Vcl.Themes, Dmitry.Controls.WatermarkedEdit, DmMemo; type TEditStyleHookColor = class(TEditStyleHook) private procedure UpdateColors; protected procedure WndProc(var Message: TMessage); override; public constructor Create(AControl: TWinControl); override; end; type TWinControlForHook = class(TWinControl); implementation constructor TEditStyleHookColor.Create(AControl: TWinControl); begin inherited; // call the UpdateColors method to use the custom colors UpdateColors; end; // Here you set the colors of the style hook procedure TEditStyleHookColor.UpdateColors; var LStyle: TCustomStyleServices; begin if Control.Enabled then begin if (TWinControlForHook(Control).Color <> clWindow) and (TWinControlForHook(Control).Color <> clWhite) and (TWinControlForHook(Control).Color <> clBtnFace) then begin Brush.Color := TWinControlForHook(Control).Color; FontColor := TWinControlForHook(Control).Font.Color; // use the Control font color end; end else begin // if the control is disabled use the colors of the style LStyle := StyleServices; Brush.Color := LStyle.GetStyleColor(scEditDisabled); FontColor := LStyle.GetStyleFontColor(sfEditBoxTextDisabled); end; end; // Handle the messages of the control procedure TEditStyleHookColor.WndProc(var Message: TMessage); begin case Message.Msg of CN_CTLCOLORMSGBOX .. CN_CTLCOLORSTATIC: begin // Get the colors UpdateColors; SetTextColor(Message.WParam, ColorToRGB(FontColor)); SetBkColor(Message.WParam, ColorToRGB(Brush.Color)); Message.Result := LRESULT(Brush.Handle); Handled := True; end; CM_ENABLEDCHANGED: begin // Get the colors UpdateColors; Handled := False; end else inherited WndProc(Message); end; end; procedure ApplyVCLColorsStyleHook(ControlClass: TClass); begin if Assigned(TStyleManager.Engine) then TStyleManager.Engine.RegisterStyleHook(ControlClass, TEditStyleHookColor); end; initialization ApplyVCLColorsStyleHook(TEdit); ApplyVCLColorsStyleHook(TDmMemo); ApplyVCLColorsStyleHook(TWatermarkedEdit); ApplyVCLColorsStyleHook(TLabeledEdit); end.
{ This demo shows how to use the TOpenDialog, TSaveDialog, TFindDialog and TReplaceDialog components along with the LoadFromFile and SaveToFile methods of a TStringList (in this case the string list in Memo1). } { and now... how to spell check that memo} unit TstMain; interface uses WinTypes, WinProcs, Classes, Graphics, Controls, Menus, Forms, StdCtrls, Dialogs, ExtCtrls, MemoUtil, {$IFDEF Win32} Spell32, {$ENDIF} {$IFDEF Ver100} Spell32, {$ENDIF} {$IFDEF Ver80} Spell16, {$ENDIF} TestDlg, SpellTbl; type TForm1 = class(TForm) MainMenu1: TMainMenu; File1: TMenuItem; Memo1: TMemo; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; FindDialog1: TFindDialog; Search1: TMenuItem; Find1: TMenuItem; Replace1: TMenuItem; FindNext1: TMenuItem; ReplaceDialog1: TReplaceDialog; Actions1: TMenuItem; SpellCheck1: TMenuItem; Panel1: TPanel; CountWords1: TMenuItem; SpellDlg1: TSpellDlg; N2: TMenuItem; SpellDialog1: TMenuItem; procedure New1Click(Sender: TObject); procedure FileOpenClick(Sender: TObject); procedure Save1Click(Sender: TObject); procedure SaveAs1Click(Sender: TObject); procedure FileExitClick(Sender: TObject); procedure Find1Click(Sender: TObject); procedure Find(Sender : TObject); procedure FindNext1Click(Sender: TObject); procedure Replace1Click(Sender: TObject); procedure Replace(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure SpellCheck1Click(Sender: TObject); procedure UpdateXY; procedure Memo1Change(Sender: TObject); procedure Memo1Click(Sender: TObject); procedure Memo1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Memo1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure CountWords1Click(Sender: TObject); procedure SpellDialog1Click(Sender: TObject); end; var Form1: TForm1; implementation uses SysUtils, Search; {$R *.DFM} procedure TForm1.New1Click(Sender: TObject); begin Memo1.Clear; OpenDialog1.Filename := ''; Caption := 'Text Demo - [Untitled]'; end; procedure TForm1.FileOpenClick(Sender: TObject); var Buffer: pChar; BufferSize: Longint; f: file; begin with OpenDialog1 do if Execute then begin Memo1.Lines.LoadFromFile(FileName); try BufferSize := Memo1.GetTextLen + 1; GetMem (Buffer, BufferSize); if Memo1.GetTextBuf (Buffer, BufferSize)<>BufferSize-1 then MessageDlg ('Error Allocating Buffer...', mtError, [mbOk], 0); OemToAnsiBuff (Buffer, Buffer, BufferSize); Memo1.SetTextBuf (Buffer); finally FreeMem (Buffer, BufferSize); end; { try } Caption := 'Text Demo - ' + ExtractFilename(FileName); end; end; procedure TForm1.Save1Click(Sender: TObject); var Buffer: PChar; BufferSize: Longint; begin if OpenDialog1.Filename <> '' then begin try BufferSize := Memo1.GetTextLen + 1; GetMem (Buffer, BufferSize); if Memo1.GetTextBuf (Buffer, BufferSize)<>BufferSize-1 then MessageDlg ('Error Allocating Buffer...', mtError, [mbOk], 0); AnsiToOemBuff (Buffer, Buffer, BufferSize); Memo1.SetTextBuf (Buffer); Memo1.Lines.SaveToFile(OpenDialog1.Filename); Memo1.Modified := False; OemToAnsiBuff (Buffer, Buffer, BufferSize); Memo1.SetTextBuf (Buffer); finally FreeMem (Buffer, BufferSize); end; { try } end else SaveAs1Click(Sender); end; procedure TForm1.SaveAs1Click(Sender: TObject); begin with SaveDialog1 do if Execute then begin Memo1.Lines.SaveToFile(Filename); Caption := 'Text Demo - ' + ExtractFilename(FileName); OpenDialog1.Filename := Filename; end; end; procedure TForm1.Find1Click(Sender: TObject); begin FindDialog1.Execute; FindNext1.Enabled := True; end; procedure TForm1.Find(Sender: TObject); begin with Sender as TFindDialog do if not SearchMemo(Memo1, FindText, Options) then ShowMessage('Cannot find "' + FindText + '".'); end; procedure TForm1.Replace1Click(Sender: TObject); begin ReplaceDialog1.Execute; end; procedure TForm1.FindNext1Click(Sender: TObject); begin Find(FindDialog1); end; { Replace and ReplaceAll call this routine. } procedure TForm1.Replace(Sender: TObject); var Found: Boolean; begin with ReplaceDialog1 do begin if AnsiCompareText(Memo1.SelText, FindText) = 0 then Memo1.SelText := ReplaceText; Found := SearchMemo(Memo1, FindText, Options); while Found and (frReplaceAll in Options) do begin Memo1.SelText := ReplaceText; Found := SearchMemo(Memo1, FindText, Options); end; if (not Found) and (frReplace in Options) then ShowMessage('Cannot find "' + FindText + '".'); end; end; procedure TForm1.FileExitClick(Sender: TObject); begin Close; end; procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var MsgResult: Word; begin if Memo1.Modified then MsgResult := MessageDlg(Format('File %s has been modified. Save file?', [OpenDialog1.Filename]), mtWarning, mbYesNoCancel, 0); case MsgResult of mrYes: begin Save1Click(Sender); CanClose := True; end; mrNo: CanClose := True; mrCancel: CanClose := False; end; end; procedure TForm1.UpdateXY; var XY: TPoint; XStr: String[4]; YStr: String[4]; begin {update the status panel on bottom} XY := Memo_CursorPos (Memo1); Str (XY.X:4, XStr); Str (XY.Y:4, YStr); Panel1.Caption := XStr + ':' + YStr; end; { TForm1.UpdateXY } procedure TForm1.Memo1Change(Sender: TObject); begin UpdateXY; end; procedure TForm1.Memo1Click(Sender: TObject); begin UpdateXY; end; procedure TForm1.Memo1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin UpdateXY; {next line is version 3.5 beta} {SpellDlg1.AutoCheck (Memo1, TRUE, Key, Shift);} end; procedure TForm1.Memo1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin UpdateXY; end; procedure TForm1.SpellCheck1Click(Sender: TObject); begin SpellDlg1.ForceDialogTitle ('My Spell Dialog'); SpellDlg1.UseScanTable (ScanMax, @ScanTable); {SpellDlg1.AddDictionary ('SPANISH.DCT');} {supports multiple dictionaries!} SpellDlg1.SpellCheck (Memo1); end; procedure TForm1.CountWords1Click(Sender: TObject); var W1, U1: longint; begin SpellDlg1.WordCount (Memo1, W1, U1); end; procedure TForm1.SpellDialog1Click(Sender: TObject); begin EditSpellDialog.ShowModal; end; end.
program TreeAssignment (input, output); type TOrder = (depthFirst, breadthFirst); TInfo = char; PNode = ^TNode; TNode = record info : TInfo; left, right : PNode; end; TTree = PNode; var tree : TTree; {-------------------------------------------------------} { functions for operations with nodes } {-------------------------------------------------------} function NodeInit(aInfo : TInfo) : PNode; var theNode : PNode; begin { function NodeNew } new(theNode); with theNode^ do begin info := aInfo; left := NIL; right := NIL; end; NodeInit := theNode; end; { function NodeNew } procedure NodeDone(var aNode : PNode); begin { procedure NodeDone } dispose(aNode); aNode := NIL; end; { procedure NodeDone } function NodeInfoTest(InfoA, InfoB : TInfo) : integer; begin { function NodeInfoTest } if InfoA > InfoB then NodeInfoTest := 1 else if InfoA < InfoB then NodeInfoTest := -1 else NodeInfoTest := 0; end; { function NodeInfoTest } procedure NodeInfoPrint(aInfo : TInfo); begin { procedure NodeInfoPrint } write(aInfo, ' '); end; { procedure NodeInfoPrint } {-------------------------------------------------------} { functions for operations with trees } {-------------------------------------------------------} function TreeInit : TTree; begin { function TreeInit } TreeInit := NIL; end; { function TreeInit } procedure TreeDone(var aTree : TTree); begin {procedure TreeDone } if aTree <> NIL then begin TreeDone(aTree^.left); TreeDone(aTree^.right); NodeDone(aTree); end; end; { procedure TreeDone } procedure TreeInsert(var aTree : TTree; aNode : PNode); begin { procedure TreeInsert } if aTree = NIL then aTree := aNode else if NodeInfoTest(aNode^.info, aTree^.info) >= 0 then TreeInsert(aTree^.right, aNode) else TreeInsert(aTree^.left, aNode); end; { procedure TreeInsert } procedure TreePrint (aTree : TTree; order : TOrder; depth : integer); begin { procedure TreePrint } if (aTree <> NIL) and (depth >= 0) then begin case order of depthFirst : begin NodeInfoPrint(aTree^.info); TreePrint(aTree^.left, order, depth-1); TreePrint(aTree^.right, order, depth-1); end; breadthFirst : begin if depth = 0 then NodeInfoPrint(aTree^.info) else begin TreePrint(aTree^.left, order, depth-1); TreePrint(aTree^.right, order, depth-1); end; end; end; end; end; { procedure TreePrint } function TreeFind (aTree : TTree; aKey : TInfo; var aDepth : integer) : PNode; var test : integer; begin { function TreeFind } if aTree = NIL then TreeFind := NIL else begin test := NodeInfoTest(aKey, aTree^.info); case test of 0 : begin TreeFind := aTree; aDepth := 0; end; -1: begin TreeFind := TreeFind(aTree^.left, aKey, aDepth); aDepth := aDepth + 1; end; 1 : begin TreeFind := TreeFind(aTree^.right, aKey, aDepth); aDepth := aDepth + 1; end; end; end; end; { function TreeFind } function TreeDepth (aTree : TTree) : integer; function max (a, b : integer) : integer; begin { function max } if a > b then max := a else max := b; end; begin { function TreeFind } if aTree = NIL then TreeDepth := -1 else TreeDepth := 1 + max(TreeDepth(aTree^.left), TreeDepth(aTree^.right)); end; { function TreeFind } {-------------------------------------------------------} { functions for main tasks } {-------------------------------------------------------} procedure InputTree (var aTree : TTree); var str : packed array[1..80]of char; begin { procedure InputTree } writeln('Input the tree below, node-by-node. Input # when finished'); writeln; repeat write('>>> '); readln(str); if not (str[1] in [' ', '#']) then TreeInsert(aTree, NodeInit(str[1])); until str[1] = '#'; end; { procedure InputTree } procedure PrintOrders (aTree : TTree; aNode : PNode; tDepth, nDepth : integer); var i : integer; begin { procedure PrintOrders } writeln('The depth of the node is ', nDepth); writeln; writeln('****** There is our tree! *******'); writeln; writeln(' in depth-first traversal from node:'); TreePrint(aNode, depthFirst, MaxInt); writeln; writeln; writeln(' in breadth-first traversal up to node:'); for i := 0 to nDepth do TreePrint(aTree, breadthFirst, i); writeln; end; { procedure PrintOrders } function InputKey (var aKey : TInfo) : boolean; var str : packed array[1..80] of char; begin { function InputKey } writeln; writeln('Please, input the key below...'); repeat write('>>> '); readln(str); until str[1] <> ' '; aKey := str[1]; InputKey := (str[1] = '#'); end; { function InputKey } {-------------------------------------------------------} { functions for program body } {-------------------------------------------------------} procedure AssignmentInit; begin { procedure AssignmentInit } writeln('***************** W E L C O M E ******************'); writeln; writeln('Welcome to Binary trees test program!'); writeln; writeln; tree := TreeInit; end; { procedure AssignmentInit } procedure AssignmentRun; var quit : boolean; key : TInfo; tDepth, nDepth : integer; node : PNode; begin { procedure AssignmentRun } InputTree(tree); writeln; tDepth := TreeDepth(tree); if tDepth > 0 then writeln('The depth of tree: ', tDepth) else writeln('The tree is empty.'); repeat quit := InputKey(key); if not quit then begin node := TreeFind(tree, key, nDepth); if (node = NIL) then writeln('The tree doesn''t contains this key!') else PrintOrders(tree, node, tDepth, nDepth); end; until quit; end; { procedure AssignmentRun } procedure AssignmentDone; begin { procedure AssignmentDone } TreeDone(tree); writeln('Good bye...'); end; { procedure AssignmentDone } begin { program TreeAssignment } AssignmentInit; AssignmentRun; AssignmentDone; end. { program TreeAssignment }
unit Calculadora; interface type TCalculadora = class function Add(Value1, Value2 : Integer) : Integer; end; implementation { TCalculadora } function TCalculadora.Add(Value1, Value2: Integer): Integer; begin result := value1 + value2; end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.Logger.Provider.Sentry Description : Log Sentry Provider Author : Kike Pérez Version : 1.0 Created : 22/04/2020 Modified : 25/04/2020 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.Provider.Sentry; {$i QuickLib.inc} interface uses Classes, SysUtils, DateUtils, {$IFDEF FPC} fpjson, fpjsonrtti, Quick.Json.fpc.Compatibility, {$ELSE} {$IFDEF DELPHIXE8_UP} System.JSON, {$ELSE} Data.DBXJSON, {$ENDIF} {$ENDIF} Quick.HttpClient, Quick.Commons, Quick.Logger; type TLogSentryProvider = class (TLogProviderBase) private fHTTPClient : TJsonHTTPClient; fProtocol : string; fSentryHost : string; fProjectId : string; fPublicKey : string; fSentryVersion : string; fFullURL : string; fConnectionTimeout : Integer; fResponseTimeout : Integer; fUserAgent : string; function LogToSentry(cLogItem: TLogItem): string; function EventTypeToSentryLevel(aEventType : TEventType) : string; procedure SetDSNEntry(const Value: string); function GetProtocol: Boolean; procedure SetProtocol(const Value: Boolean); public constructor Create; override; destructor Destroy; override; property DSNKey : string write SetDSNEntry; property SentryVersion : string read fSentryVersion write fSentryVersion; property Secured : Boolean read GetProtocol write SetProtocol; property Host : string read fSentryHost write fSentryHost; property ProjectId : string read fProjectId write fProjectId; property PublicKey : string read fPublicKey write fPublicKey; property UserAgent : string read fUserAgent write fUserAgent; property JsonOutputOptions : TJsonOutputOptions read fJsonOutputOptions write fJsonOutputOptions; procedure Init; override; procedure Restart; override; procedure WriteLog(cLogItem : TLogItem); override; end; var GlobalLogSentryProvider : TLogSentryProvider; implementation const DEF_HTTPCONNECTION_TIMEOUT = 60000; DEF_HTTPRESPONSE_TIMEOUT = 60000; type TSyslogSeverity = (slEmergency, {0 - emergency - system unusable} slAlert, {1 - action must be taken immediately } slCritical, { 2 - critical conditions } slError, {3 - error conditions } slWarning, {4 - warning conditions } slNotice, {5 - normal but signification condition } slInformational, {6 - informational } slDebug); {7 - debug-level messages } constructor TLogSentryProvider.Create; begin inherited; LogLevel := LOG_ALL; fSentryVersion := '7'; fJsonOutputOptions.UseUTCTime := False; fConnectionTimeout := DEF_HTTPCONNECTION_TIMEOUT; fResponseTimeout := DEF_HTTPRESPONSE_TIMEOUT; fUserAgent := DEF_USER_AGENT; IncludedInfo := [iiAppName,iiHost,iiEnvironment]; end; destructor TLogSentryProvider.Destroy; begin if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); inherited; end; procedure TLogSentryProvider.Init; begin fFullURL := Format('%s://%s/api/%s/store/?sentry_key=%s&sentry_version=%s',[fProtocol,fSentryHost,fProjectId,fPublicKey,fSentryVersion]); fHTTPClient := TJsonHTTPClient.Create; fHTTPClient.ConnectionTimeout := fConnectionTimeout; fHTTPClient.ResponseTimeout := fResponseTimeout; fHTTPClient.ContentType := 'application/json'; fHTTPClient.UserAgent := fUserAgent; fHTTPClient.HandleRedirects := True; inherited; end; function TLogSentryProvider.EventTypeToSentryLevel(aEventType : TEventType) : string; begin case aEventType of etWarning : Result := 'warning'; etError, etException : Result := 'error'; etCritical : Result := 'fatal'; etDebug, etTrace : Result := 'debug'; else Result := 'info'; end; end; function TLogSentryProvider.GetProtocol: Boolean; begin Result := fProtocol.ToLower = 'https'; end; procedure TLogSentryProvider.SetProtocol(const Value: Boolean); begin if Value then fProtocol := 'https' else fProtocol := 'http'; end; function TLogSentryProvider.LogToSentry(cLogItem: TLogItem): string; var jsEvent : TJSONObject; jsMessage : TJSONObject; jsException : TJSONObject; jsUser : TJSONObject; jsTags : TJSONObject; tagName : string; tagValue : string; {$IFDEF FPC} json : TJSONObject; jarray : TJSONArray; {$ENDIF} begin jsEvent := TJSONObject.Create; try {$IFDEF FPC} jsEvent.Add('timestamp',TJSONInt64Number.Create(DateTimeToUnix(cLogItem.EventDate))); {$ELSE} {$IFDEF DELPHIXE7_UP} jsEvent.AddPair('timestamp',TJSONNumber.Create(DateTimeToUnix(cLogItem.EventDate,fJsonOutputOptions.UseUTCTime))); {$ELSE} jsEvent.AddPair('timestamp',TJSONNumber.Create(DateTimeToUnix(cLogItem.EventDate))); {$ENDIF} {$ENDIF} jsEvent.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('level',EventTypeToSentryLevel(cLogItem.EventType)); jsEvent.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('logger','QuickLogger'); jsEvent.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('platform','other'); jsEvent.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('server_name',SystemInfo.HostName); if iiEnvironment in IncludedInfo then jsEvent.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('environment',Environment); if cLogItem.EventType = etException then begin jsException := TJSONObject.Create; jsException.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('type',EventTypeName[cLogItem.EventType]); jsException.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('value',cLogItem.Msg); if iiThreadId in IncludedInfo then jsException.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('thread_id',cLogItem.ThreadId.ToString); {$IFNDEF FPC} jsEvent.AddPair('exception',TJSONObject.Create(TJSONPair.Create('values',TJSONArray.Create(jsException)))); {$ELSE} jarray := TJSONArray.Create; jarray.AddElement(jsException); json := TJSONObject.Create; json.AddPair(TJSONPair.Create('values',jarray)); jsEvent.Add('exception',json); {$ENDIF} end else begin jsMessage := TJSONObject.Create; jsMessage.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('formatted',cLogItem.Msg); jsEvent.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('message',jsMessage); end; jsTags := TJSONObject.Create; if iiAppName in IncludedInfo then jsTags.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('application',AppName); if iiPlatform in IncludedInfo then jsTags.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('platformtype',PlatformInfo); if iiOSVersion in IncludedInfo then jsTags.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('OS',SystemInfo.OSVersion); if iiProcessId in IncludedInfo then jsTags.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('pid',SystemInfo.ProcessId.ToString); for tagName in IncludedTags do begin if fCustomTags.TryGetValue(tagName,tagValue) then jsTags.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}(tagName,tagValue); end; jsEvent.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('tags',jsTags); if iiUserName in IncludedInfo then begin jsUser := TJSONObject.Create; //jsUser.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('id',SystemInfo.UserName); jsUser.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('username',SystemInfo.UserName); jsEvent.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('user',jsUser); end; {$IFDEF DELPHIXE8_UP} Result := jsEvent.ToJSON {$ELSE} {$IFDEF FPC} Result := jsEvent.AsJSON; {$ELSE} Result := jsEvent.ToString; {$ENDIF} {$ENDIF} finally jsEvent.Free; end; end; procedure TLogSentryProvider.Restart; begin Stop; if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); Init; end; procedure TLogSentryProvider.SetDSNEntry(const Value: string); var segments : TArray<string>; begin segments := value.Split(['/','@']); try fProtocol := segments[0].Replace(':',''); fPublicKey := segments[2]; fSentryHost := segments[3]; fProjectId := segments[4]; except raise Exception.Create('Sentry DSN not valid!'); end; end; procedure TLogSentryProvider.WriteLog(cLogItem : TLogItem); var resp : IHttpRequestResponse; begin if CustomMsgOutput then resp := fHTTPClient.Post(fFullURL,LogItemToFormat(cLogItem)) else resp := fHTTPClient.Post(fFullURL,LogToSentry(cLogItem)); if not (resp.StatusCode in [200,201,202]) then raise ELogger.Create(Format('[TLogSentryProvider] : Response %d : %s trying to post event',[resp.StatusCode,resp.StatusText])); end; initialization GlobalLogSentryProvider := TLogSentryProvider.Create; finalization if Assigned(GlobalLogSentryProvider) and (GlobalLogSentryProvider.RefCount = 0) then GlobalLogSentryProvider.Free; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: HDRScene.pas,v 1.5 2007/02/05 22:21:08 clootie Exp $ *----------------------------------------------------------------------------*) //====================================================================== // // HIGH DYNAMIC RANGE RENDERING DEMONSTRATION // Written by Jack Hoxley, October 2005 // //====================================================================== {$I DirectX.inc} unit HDRScene; interface uses Windows, DXTypes, Direct3D9, D3DX9, DXUT, DXUTcore, DXUTmisc, StrSafe; // To provide some logical grouping to the functionality offered by this // code it is wrapped up in a C++ namespace. As such, all code relating // to the rendering of the original 3D scene containing the raw High Dynamic // Range values is accessed via the HDRScene qualifier. // namespace HDRScene // This function is called when the application is first initialized or // shortly after a restore/lost-device situation. It is responsible for // creating all the geometric and rendering resources required to generate // the HDR scene. function CreateResources(const pDevice: IDirect3DDevice9; const pDisplayDesc: TD3DSurfaceDesc): HRESULT; // This following function is effectively the opposite to the above. It is // invoked when it is necessary to remove any resources that were previously // created. Typically called during a lost-device or termination event. function DestroyResources: HRESULT; // This method takes all the necessary resources and renders them // to the HDR render target for later processing. function RenderScene(const pDevice: IDirect3DDevice9): HRESULT; // This method allows the code to update any internal variables, especially // movement/animation based ones. function UpdateScene(const pDevice: IDirect3DDevice9; fTime: Single; const pCamera: CModelViewerCamera): HRESULT; // The results of rendering the HDR scene feed into several other parts // of the rendering pipeline used by this example. As such it is necessary // for them to be able to retrieve a reference to the HDR source. function GetOutputTexture(out pTexture: IDirect3DTexture9): HRESULT; // This puts the HDR source texture onto the correct part of the GUI. function DrawToScreen(const pDevice: IDirect3DDevice9; const pFont: ID3DXFont; const pTextSprite: ID3DXSprite; const pArrowTex: IDirect3DTexture9): HRESULT; // A useful utility method for the GUI - HDR pipelines can take up a large // amount of VRAM, such that it can be useful to monitor. function CalculateResourceUsage: DWORD; implementation uses Math, HDREnumeration; //-------------------------------------------------------------------------------------- // Data Structure Definitions //-------------------------------------------------------------------------------------- type TLitVertex = record p: TD3DXVector3; c: DWORD; end; const FVF_LITVERTEX = D3DFVF_XYZ or D3DFVF_DIFFUSE; type TLVertex = record p: TD3DXVector4; t: TD3DXVector2; end; const FVF_TLVERTEX = D3DFVF_XYZRHW or D3DFVF_TEX1; //-------------------------------------------------------------------------------------- // Namespace-level variables //-------------------------------------------------------------------------------------- var g_pCubeMesh: ID3DXMesh = nil; // Mesh representing the HDR source in the middle of the scene g_pCubePS: IDirect3DPixelShader9 = nil; // The pixel shader for the cube g_pCubePSConsts: ID3DXConstantTable = nil; // Interface for setting parameters/constants for the above PS g_pCubeVS: IDirect3DVertexShader9 = nil; // The vertex shader for the cube g_pCubeVSDecl: IDirect3DVertexDeclaration9 = nil; // The mapping from VB to VS g_pCubeVSConsts: ID3DXConstantTable = nil; // Interface for setting params for the cube rendering g_mCubeMatrix: TD3DXMatrixA16; // The computed world*view*proj transform for the inner cube g_pTexScene: IDirect3DTexture9 = nil; // The main, floating point, render target g_fmtHDR: TD3DFormat = D3DFMT_UNKNOWN; // Enumerated and either set to 128 or 64 bit g_pOcclusionMesh: ID3DXMesh = nil; // The occlusion mesh surrounding the HDR cube g_pOcclusionVSDecl: IDirect3DVertexDeclaration9 = nil; // The mapping for the ID3DXMesh g_pOcclusionVS: IDirect3DVertexShader9 = nil; // The shader for drawing the occlusion mesh g_pOcclusionVSConsts: ID3DXConstantTable = nil; // Entry point for configuring above shader g_mOcclusionMatrix: TD3DXMatrixA16; // The world*view*proj transform for transforming the POSITIONS g_mOcclusionNormals: TD3DXMatrixA16; // The transpose(inverse(world)) matrix for transforming NORMALS //-------------------------------------------------------------------------------------- // Function Prototypes //-------------------------------------------------------------------------------------- function LoadMesh(strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; forward; //-------------------------------------------------------------------------------------- // CreateResources( ) // // DESC: // This function creates all the necessary resources to render the HDR scene // to a render target for later use. When this function completes successfully // rendering can commence. A call to 'DestroyResources()' should be made when // the application closes. // // PARAMS: // pDevice : The current device that resources should be created with/from // pDisplayDesc : Describes the back-buffer currently in use, can be useful when // creating GUI based resources. // // NOTES: // n/a //-------------------------------------------------------------------------------------- function CreateResources(const pDevice: IDirect3DDevice9; const pDisplayDesc: TD3DSurfaceDesc): HRESULT; var pCode: ID3DXBuffer; // Container for the compiled HLSL code str: array[0..MAX_PATH-1] of WideChar; cubeVertElems: TFVFDeclaration; vertElems: TFVFDeclaration; begin //[ 0 ] DECLARATIONS //------------------ //[ 1 ] DETERMINE FP TEXTURE SUPPORT //---------------------------------- Result := V(HDREnumeration.FindBestHDRFormat(HDRScene.g_fmtHDR)); if FAILED(Result) then begin OutputDebugString('HDRScene::CreateResources() - Current hardware does not support HDR rendering!'#10); Exit; end; //[ 2 ] CREATE HDR RENDER TARGET //------------------------------ Result := V(pDevice.CreateTexture( pDisplayDesc.Width, pDisplayDesc.Height, 1, D3DUSAGE_RENDERTARGET, g_fmtHDR, D3DPOOL_DEFAULT, HDRScene.g_pTexScene, nil)); if FAILED(Result) then begin // We couldn't create the texture - lots of possible reasons for this. Best // check the D3D debug output for more details. OutputDebugString('HDRScene::CreateResources() - Could not create floating point render target. Examine D3D Debug Output for details.'#10); Exit; end; //[ 3 ] CREATE HDR CUBE'S GEOMETRY //-------------------------------- Result := V(LoadMesh('misc\Cube.x', HDRScene.g_pCubeMesh)); if FAILED(Result) then begin // Couldn't load the mesh, could be a file system error... OutputDebugString('HDRScene::CreateResources() - Could not load ''Cube.x''.'#10); Exit; end; //[ 4 ] CREATE HDR CUBE'S PIXEL SHADER //------------------------------------ Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\HDRSource.psh'); if V_Failed(Result) then Exit; Result:= V(D3DXCompileShaderFromFileW( str, nil, nil, 'main', // Entry Point found in 'HDRSource.psh' 'ps_2_0', // Profile to target 0, @pCode, nil, @HDRScene.g_pCubePSConsts )); if FAILED(Result) then begin // Couldn't compile the shader, use the 'compile_shaders.bat' script // in the 'Shader Code' folder to get a proper compile breakdown. OutputDebugString('HDRScene::CreateResources() - Compiling of ''HDRSource.psh'' failed!'#10); Exit; end; Result:= V(pDevice.CreatePixelShader(PDWORD(pCode.GetBufferPointer), HDRScene.g_pCubePS)); if FAILED(Result) then begin // Couldn't turn the compiled shader into an actual, usable, pixel shader! OutputDebugString('HDRScene::CreateResources() : Couldn''t create a pixel shader object from ''HDRSource.psh''.'#10); pCode := nil; Exit; end; pCode := nil; // [ 5 ] CREATE THE CUBE'S VERTEX DECL //------------------------------------ HDRScene.g_pCubeMesh.GetDeclaration(cubeVertElems); Result:= V(pDevice.CreateVertexDeclaration(@cubeVertElems, HDRScene.g_pCubeVSDecl)); if FAILED(Result) then begin // Couldn't create the declaration for the loaded mesh.. OutputDebugString('HDRScene::CreateResources() - Couldn''t create a vertex declaration for the HDR-Cube mesh.'#10); pCode := nil; Exit; end; // [ 6 ] CREATE THE CUBE'S VERTEX SHADER //-------------------------------------- Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\HDRSource.vsh'); if V_Failed(Result) then Exit; Result:= V(D3DXCompileShaderFromFileW( str, nil, nil, 'main', 'vs_2_0', 0, @pCode, nil, @g_pCubeVSConsts)); if FAILED(Result) then begin // Couldn't compile the shader, use the 'compile_shaders.bat' script // in the 'Shader Code' folder to get a proper compile breakdown. OutputDebugString('HDRScene::CreateResources() - Compilation of ''HDRSource.vsh'' Failed!'#10); Exit; end; Result:= V(pDevice.CreateVertexShader(PDWORD(pCode.GetBufferPointer), HDRScene.g_pCubeVS)); if FAILED(Result) then begin // Couldn't turn the compiled shader into an actual, usable, vertex shader! OutputDebugString('HDRScene::CreateResources() - Could not create a VS object from the compiled ''HDRSource.vsh'' code.'#10); pCode := nil; Exit; end; pCode := nil; //[ 5 ] LOAD THE OCCLUSION MESH //----------------------------- Result:= V(LoadMesh('misc\OcclusionBox.x', HDRScene.g_pOcclusionMesh)); if FAILED(Result) then begin // Couldn't load the mesh, could be a file system error... OutputDebugString('HDRScene::CreateResources() - Could not load ''OcclusionBox.x''.'#10); Exit; end; //[ 6 ] CREATE THE MESH VERTEX DECLARATION //---------------------------------------- HDRScene.g_pOcclusionMesh.GetDeclaration(vertElems); Result:= V(pDevice.CreateVertexDeclaration(@vertElems, HDRScene.g_pOcclusionVSDecl)); if FAILED(Result) then begin // Couldn't create the declaration for the loaded mesh.. OutputDebugString('HDRScene::CreateResources() - Couldn''t create a vertex declaration for the occlusion mesh.'#10); Exit; end; //[ 7 ] CREATE THE OCCLUSION VERTEX SHADER //---------------------------------------- Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\OcclusionMesh.vsh'); if V_Failed(Result) then Exit; Result:= V(D3DXCompileShaderFromFileW( str, nil, nil, 'main', 'vs_2_0', 0, @pCode, nil, @HDRScene.g_pOcclusionVSConsts )); if FAILED(Result) then begin // Couldn't compile the shader, use the 'compile_shaders.bat' script // in the 'Shader Code' folder to get a proper compile breakdown. OutputDebugString('HDRScene::CreateResources() - Compilation of ''OcclusionMesh.vsh'' Failed!'#10); Exit; end; Result:= V(pDevice.CreateVertexShader(PDWORD(pCode.GetBufferPointer), HDRScene.g_pOcclusionVS)); if FAILED(Result) then begin // Couldn't turn the compiled shader into an actual, usable, vertex shader! OutputDebugString('HDRScene::CreateResources() - Could not create a VS object from the compiled ''OcclusionMesh.vsh'' code.'#10); pCode := nil; Exit; end; pCode := nil; //[ 8 ] RETURN SUCCESS IF WE GOT THIS FAR //--------------------------------------- // Result:= hr; end; //-------------------------------------------------------------------------------------- // DestroyResources( ) // // DESC: // Makes sure that the resources acquired in CreateResources() are cleanly // destroyed to avoid any errors and/or memory leaks. // //-------------------------------------------------------------------------------------- function DestroyResources: HRESULT; begin SAFE_RELEASE(HDRScene.g_pCubeMesh); SAFE_RELEASE(HDRScene.g_pCubePS); SAFE_RELEASE(HDRScene.g_pCubePSConsts); SAFE_RELEASE(HDRScene.g_pTexScene); SAFE_RELEASE(HDRScene.g_pCubeVS); SAFE_RELEASE(HDRScene.g_pCubeVSConsts); SAFE_RELEASE(HDRScene.g_pCubeVSDecl); SAFE_RELEASE(HDRScene.g_pOcclusionMesh); SAFE_RELEASE(HDRScene.g_pOcclusionVSDecl); SAFE_RELEASE(HDRScene.g_pOcclusionVS); SAFE_RELEASE(HDRScene.g_pOcclusionVSConsts); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // CalculateResourceUsage( ) // // DESC: // Based on the known resources this function attempts to make an accurate // measurement of how much VRAM is being used by this part of the application. // // NOTES: // Whilst the return value should be pretty accurate, it shouldn't be relied // on due to the way drivers/hardware can allocate memory. // // Only the first level of the render target is checked as there should, by // definition, be no mip levels. // //-------------------------------------------------------------------------------------- function CalculateResourceUsage: DWORD; var usage: DWORD; texDesc: TD3DSurfaceDesc; index_size: DWORD; begin // [ 0 ] DECLARATIONS //------------------- usage := 0; // [ 1 ] RENDER TARGET SIZE //------------------------- HDRScene.g_pTexScene.GetLevelDesc(0, texDesc); usage := usage + ( (texDesc.Width*texDesc.Height) * DWORD(IfThen(HDRScene.g_fmtHDR = D3DFMT_A16B16G16R16F, 8, 16))); // [ 2 ] OCCLUSION MESH SIZE //-------------------------- usage := usage + (HDRScene.g_pOcclusionMesh.GetNumBytesPerVertex * HDRScene.g_pOcclusionMesh.GetNumVertices); index_size := IfThen(HDRScene.g_pOcclusionMesh.GetOptions and D3DXMESH_32BIT <> 0, 4, 2); usage := usage + (index_size * 3 * HDRScene.g_pOcclusionMesh.GetNumFaces); Result:= usage; end; //-------------------------------------------------------------------------------------- // RenderScene( ) // // DESC: // This is the core function for this unit - when it succesfully completes the // render target (obtainable via GetOutputTexture) will be a completed scene // that, crucially, contains values outside the LDR (0..1) range ready to be // fed into the various stages of the HDR post-processing pipeline. // // PARAMS: // pDevice : The device that is currently being used for rendering // // NOTES: // For future modifications, this is the entry point that should be used if // you require a different image/scene to be displayed on the screen. // // This function assumes that the device is already in a ready-to-render // state (e.g. BeginScene() has been called). // //-------------------------------------------------------------------------------------- function RenderScene(const pDevice: IDirect3DDevice9): HRESULT; var pPrevSurf: IDirect3DSurface9; pRTSurf: IDirect3DSurface9; begin Result:= E_FAIL; // [ 0 ] CONFIGURE GEOMETRY INPUTS //-------------------------------- pDevice.SetVertexShader(HDRScene.g_pCubeVS); pDevice.SetVertexDeclaration(HDRScene.g_pCubeVSDecl); HDRScene.g_pCubeVSConsts.SetMatrix(pDevice, 'matWorldViewProj', HDRScene.g_mCubeMatrix); // [ 1 ] PIXEL SHADER ( + PARAMS ) //-------------------------------- pDevice.SetPixelShader(HDRScene.g_pCubePS); HDRScene.g_pCubePSConsts.SetFloat(pDevice, 'HDRScalar', 5.0); pDevice.SetTexture(0, nil); // [ 2 ] GET PREVIOUS RENDER TARGET //--------------------------------- if FAILED(pDevice.GetRenderTarget(0, pPrevSurf)) then begin // Couldn't retrieve the current render target (for restoration later on) OutputDebugString('HDRScene::RenderScene() - Could not retrieve a reference to the previous render target.'#10); Exit; end; // [ 3 ] SET NEW RENDER TARGET //---------------------------- if FAILED(HDRScene.g_pTexScene.GetSurfaceLevel(0, pRTSurf)) then begin // Bad news! couldn't get a reference to the HDR render target. Most // Likely due to a failed/corrupt resource creation stage. OutputDebugString('HDRScene::RenderScene() - Could not get the top level surface for the HDR render target'#10); Exit; end; if FAILED(pDevice.SetRenderTarget(0, pRTSurf)) then begin // For whatever reason we can't set the HDR texture as the // the render target... OutputDebugString('HDRScene::RenderScene() - Could not set the HDR texture as a new render target.'#10); Exit; end; // It is worth noting that the colour used to clear the render target will // be considered for the luminance measurement stage. pDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 64, 64, 192), 1.0, 0); // [ 4 ] RENDER THE HDR CUBE //-------------------------- HDRScene.g_pCubeMesh.DrawSubset(0); // [ 5 ] DRAW THE OCCLUSION CUBE //------------------------------ pDevice.SetPixelShader(nil); pDevice.SetVertexDeclaration(HDRScene.g_pOcclusionVSDecl); pDevice.SetVertexShader(HDRScene.g_pOcclusionVS); HDRScene.g_pOcclusionVSConsts.SetMatrix(pDevice, 'matWorldViewProj', HDRScene.g_mOcclusionMatrix); HDRScene.g_pOcclusionVSConsts.SetMatrix(pDevice, 'matInvTPoseWorld', HDRScene.g_mOcclusionNormals); // Due to the way that the mesh was authored, there is // only (and always) going to be 1 subset/group to render. HDRScene.g_pOcclusionMesh.DrawSubset(0); // [ 6 ] RESTORE PREVIOUS RENDER TARGET //------------------------------------- pDevice.SetRenderTarget(0, pPrevSurf); // [ 7 ] RELEASE TEMPORARY REFERENCES //----------------------------------- SAFE_RELEASE(pRTSurf); SAFE_RELEASE(pPrevSurf); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // UpdateScene( ) // // DESC: // An entry point for updating various parameters and internal data on a // per-frame basis. // // PARAMS: // pDevice : The currently active device // fTime : The number of milliseconds elapsed since the start of execution // pCamera : The arcball based camera that the end-user controls // // NOTES: // n/a // //-------------------------------------------------------------------------------------- function UpdateScene(const pDevice: IDirect3DDevice9; fTime: Single; const pCamera: CModelViewerCamera): HRESULT; var matWorld, matTemp, m: TD3DXMatrixA16; begin // The HDR cube in the middle of the scene never changes position in world // space, but must respond to view changes. // HDRScene.g_mCubeMatrix := (*pCamera.GetViewMatrix) * (*pCamera.GetProjMatrix); D3DXMatrixMultiply(HDRScene.g_mCubeMatrix, pCamera.GetViewMatrix^, pCamera.GetProjMatrix^); // The occlusion cube must be slightly larger than the inner HDR cube, so // a scaling constant is applied to the world matrix. D3DXMatrixIdentity(matTemp); D3DXMatrixScaling(matTemp, 2.5, 2.5, 2.5); D3DXMatrixMultiply(matWorld, matTemp, pCamera.GetWorldMatrix^); //@matWorld); // The occlusion cube contains lighting normals, so for the shader to operate // on them correctly, the inverse transpose of the world matrix is needed. D3DXMatrixIdentity(matTemp); D3DXMatrixInverse(matTemp, nil, matWorld); D3DXMatrixTranspose(HDRScene.g_mOcclusionNormals, matTemp); // HDRScene.g_mOcclusionMatrix := matWorld * (*pCamera.GetViewMatrix) * (*pCamera.GetProjMatrix); D3DXMatrixMultiply(m, pCamera.GetViewMatrix^, pCamera.GetProjMatrix^); D3DXMatrixMultiply(HDRScene.g_mOcclusionMatrix, matWorld, m); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // GetOutputTexture( ) // // DESC: // The results of this modules rendering are used as inputs to several // other parts of the rendering pipeline. As such it is necessary to obtain // a reference to the internally managed texture. // // PARAMS: // pTexture : Should be NULL on entry, will be a valid reference on exit // // NOTES: // The code that requests the reference is responsible for releasing their // copy of the texture as soon as they are finished using it. // //-------------------------------------------------------------------------------------- function GetOutputTexture(out pTexture: IDirect3DTexture9): HRESULT; begin // [ 0 ] ERASE ANY DATA IN THE INPUT //---------------------------------- //SAFE_RELEASE(pTexture); // [ 1 ] COPY THE PRIVATE REFERENCE //--------------------------------- pTexture := HDRScene.g_pTexScene; // [ 2 ] INCREMENT THE REFERENCE COUNT.. //-------------------------------------- //(*pTexture).AddRef(); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // DrawToScreen( ) // // DESC: // Part of the GUI in this application displays the "raw" HDR data as part // of the process. This function places the texture, created by this // module, in the correct place on the screen. // // PARAMS: // pDevice : The device to be drawn to. // pFont : The font to use when annotating the display // pTextSprite : Used with the font for more efficient rendering // pArrowTex : Stores the 4 (up/down/left/right) icons used in the GUI // // NOTES: // n/a // //-------------------------------------------------------------------------------------- function DrawToScreen(const pDevice: IDirect3DDevice9; const pFont: ID3DXFont; const pTextSprite: ID3DXSprite; const pArrowTex: IDirect3DTexture9): HRESULT; var pSurf: IDirect3DSurface9; d: TD3DSurfaceDesc; fCellWidth, fCellHeight: Single; txtHelper: CDXUTTextHelper; v: array[0..3] of HDRScene.TLVertex; fLumCellSize: Single; fLumStartX: Single; str: array[0..99] of WideChar; begin // [ 0 ] GATHER NECESSARY INFORMATION //----------------------------------- if FAILED(pDevice.GetRenderTarget(0, pSurf)) then begin // Couldn't get the current render target! OutputDebugString('HDRScene::DrawToScreen() - Could not get current render target to extract dimensions.'#10); Result:= E_FAIL; Exit; end; pSurf.GetDesc(d); pSurf := nil; // Cache the dimensions as floats for later use fCellWidth := ( d.Width - 48.0 ) / 4.0; fCellHeight := ( d.Height - 36.0 ) / 4.0; txtHelper := CDXUTTextHelper.Create(pFont, pTextSprite, 12); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.5, 0.0, 1.0)); // [ 1 ] CREATE TILE GEOMETRY //--------------------------- v[0].p := D3DXVector4(0.0, fCellHeight + 16.0, 0.0, 1.0); v[1].p := D3DXVector4(fCellWidth, fCellHeight + 16.0, 0.0, 1.0); v[2].p := D3DXVector4(0.0, ( 2.0 * fCellHeight ) + 16.0, 0.0, 1.0); v[3].p := D3DXVector4(fCellWidth, ( 2.0 * fCellHeight ) + 16.0, 0.0, 1.0); v[0].t := D3DXVector2(0.0, 0.0); v[1].t := D3DXVector2(1.0, 0.0); v[2].t := D3DXVector2(0.0, 1.0); v[3].t := D3DXVector2(1.0, 1.0); // [ 2 ] DISPLAY TILE ON SCREEN //----------------------------- pDevice.SetVertexShader(nil); pDevice.SetFVF(HDRScene.FVF_TLVERTEX); pDevice.SetTexture(0, HDRScene.g_pTexScene); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(HDRScene.TLVertex)); // [ 3 ] RENDER CONNECTING ARROWS //------------------------------- pDevice.SetTexture(0, pArrowTex); v[0].p := D3DXVector4((fCellWidth / 2.0) - 8.0, fCellHeight, 0.0, 1.0); v[1].p := D3DXVector4((fCellWidth / 2.0) + 8.0, fCellHeight, 0.0, 1.0); v[2].p := D3DXVector4((fCellWidth / 2.0) - 8.0, fCellHeight + 16.0, 0.0, 1.0); v[3].p := D3DXVector4((fCellWidth / 2.0) + 8.0, fCellHeight + 16.0, 0.0, 1.0); v[0].t := D3DXVector2(0.0, 0.0); v[1].t := D3DXVector2(0.25, 0.0); v[2].t := D3DXVector2(0.0, 1.0); v[3].t := D3DXVector2(0.25, 1.0); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(HDRScene.TLVertex)); v[0].p := D3DXVector4(fCellWidth, fCellHeight + 8.0 + (fCellHeight / 2.0), 0.0, 1.0); v[1].p := D3DXVector4(fCellWidth + 16.0, fCellHeight + 8.0 + (fCellHeight / 2.0), 0.0, 1.0); v[2].p := D3DXVector4(fCellWidth, fCellHeight + 24.0 + (fCellHeight / 2.0), 0.0, 1.0); v[3].p := D3DXVector4(fCellWidth + 16.0, fCellHeight + 24.0 + (fCellHeight / 2.0), 0.0, 1.0); v[0].t := D3DXVector2(0.25, 0.0); v[1].t := D3DXVector2(0.50, 0.0); v[2].t := D3DXVector2(0.25, 1.0); v[3].t := D3DXVector2(0.50, 1.0); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(HDRScene.TLVertex)); fLumCellSize := ( ( d.Height - ( (2.0 * fCellHeight) + 32.0 ) ) - 32.0 ) / 3.0; fLumStartX := (fCellWidth + 16.0) - ((2.0 * fLumCellSize) + 32.0); v[0].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) - 8.0, ( 2.0 * fCellHeight ) + 16.0, 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) + 8.0, ( 2.0 * fCellHeight ) + 16.0, 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) - 8.0, ( 2.0 * fCellHeight ) + 32.0, 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) + 8.0, ( 2.0 * fCellHeight ) + 32.0, 0.0, 1.0); v[0].t := D3DXVector2(0.50, 0.0); v[1].t := D3DXVector2(0.75, 0.0); v[2].t := D3DXVector2(0.50, 1.0); v[3].t := D3DXVector2(0.75, 1.0); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(HDRScene.TLVertex)); // [ 4 ] ANNOTATE CELL //-------------------- txtHelper._Begin; //begin txtHelper.SetInsertionPos(5, Trunc( 2.0*fCellHeight + 16.0 - 25.0 )); txtHelper.DrawTextLine('Source HDR Frame'); HDRScene.g_pTexScene.GetLevelDesc(0, d); StringCchFormat(str, 100, '%dx%d', [d.Width, d.Height]); txtHelper.DrawTextLine(str); //end; txtHelper._End; txtHelper.Free; Result:= S_OK; end; //-------------------------------------------------------------------------------------- // LoadMesh( ) // // DESC: // A utility method borrowed from the DXSDK samples. Loads a .X mesh into // an ID3DXMesh object for rendering. // //-------------------------------------------------------------------------------------- function LoadMesh(strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; var pMesh: ID3DXMesh; str: array[0..MAX_PATH-1] of WideChar; rgdwAdjacency: PDWORD; pTempMesh: ID3DXMesh; begin Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, strFileName); if V_Failed(Result) then Exit; Result := D3DXLoadMeshFromXW(str, D3DXMESH_MANAGED, DXUTGetD3DDevice, nil, nil, nil, nil, pMesh); if FAILED(Result) or (pMesh = nil) then Exit; // rgdwAdjacency := nil; // Make sure there are normals which are required for lighting if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then begin Result := pMesh.CloneMeshFVF(pMesh.GetOptions, pMesh.GetFVF or D3DFVF_NORMAL, DXUTGetD3DDevice, pTempMesh); if FAILED(Result) then Exit; D3DXComputeNormals(pTempMesh, nil); //SAFE_RELEASE(pMesh); pMesh := pTempMesh; end; // Optimize the mesh to make it fast for the user's graphics card GetMem(rgdwAdjacency, SizeOf(DWORD)*pMesh.GetNumFaces*3); try // if (rgdwAdjacency = nil) then Result:= E_OUTOFMEMORY; V(pMesh.GenerateAdjacency(1e-6, rgdwAdjacency)); V(pMesh.OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, nil, nil, nil)); finally FreeMem(rgdwAdjacency); end; ppMesh := pMesh; Result:= S_OK; end; end.
unit uWinApiRuntime; interface uses Windows; type NTStatus = CARDINAL; PWSTR = ^WCHAR; PUnicodeString = ^TUnicodeString; TUnicodeString = record Length: Word; MaximumLength: Word; Buffer: PWideChar; end; type _FILE_INFORMATION_CLASS = ( // end_wdm FileEmpty, FileDirectoryInformation, //= 1, FileFullDirectoryInformation, // 2 FileBothDirectoryInformation, // 3 FileBasicInformation, // 4 wdm FileStandardInformation, // 5 wdm FileInternalInformation, // 6 FileEaInformation, // 7 FileAccessInformation, // 8 FileNameInformation, // 9 FileRenameInformation, // 10 FileLinkInformation, // 11 FileNamesInformation, // 12 FileDispositionInformation, // 13 FilePositionInformation, // 14 wdm FileFullEaInformation, // 15 FileModeInformation, // 16 FileAlignmentInformation, // 17 FileAllInformation, // 18 FileAllocationInformation, // 19 FileEndOfFileInformation, // 20 wdm FileAlternateNameInformation, // 21 FileStreamInformation, // 22 FilePipeInformation, // 23 FilePipeLocalInformation, // 24 FilePipeRemoteInformation, // 25 FileMailslotQueryInformation, // 26 FileMailslotSetInformation, // 27 FileCompressionInformation, // 28 FileObjectIdInformation, // 29 FileCompletionInformation, // 30 FileMoveClusterInformation, // 31 FileQuotaInformation, // 32 FileReparsePointInformation, // 33 FileNetworkOpenInformation, // 34 FileAttributeTagInformation, // 35 FileTrackingInformation, // 36 FileIdBothDirectoryInformation, // 37 FileIdFullDirectoryInformation, // 38 FileMaximumInformation); // begin_wdm FILE_INFORMATION_CLASS = _FILE_INFORMATION_CLASS; PFILE_INFORMATION_CLASS = ^FILE_INFORMATION_CLASS; type FILE_DIRECTORY_INFORMATION = record NextEntryOffset: ULONG; Unknown: ULONG; CreationTime, LastAccessTime, LastWriteTime, ChangeTime, EndOfFile, AllocationSize: int64; FileAttributes: ULONG; FileNameLength: ULONG; FileName: PWideChar; end; PFILE_DIRECTORY_INFORMATION = ^FILE_DIRECTORY_INFORMATION; type FILE_FULL_DIRECTORY_INFORMATION = record NextEntryOffset: ULONG; Unknown: ULONG; CreationTime, LastAccessTime, LastWriteTime, ChangeTime, EndOfFile, AllocationSize: Int64; FileAttributes: ULONG; FileNameLength: ULONG; EaInformationLength: ULONG; FileName: PWideChar; end; PFILE_FULL_DIRECTORY_INFORMATION = ^FILE_FULL_DIRECTORY_INFORMATION; type FILE_BOTH_DIRECTORY_INFORMATION = record NextEntryOffset: ULONG; Unknown: ULONG; CreationTime, LastAccessTime, LastWriteTime, ChangeTime, EndOfFile, AllocationSize: Int64; FileAttributes: ULONG; FileNameLength: ULONG; EaInformationLength: ULONG; AlternateNameLength: ULONG; AlternateName: array[0..11] of WideChar; FileName: PWideChar; end; PFILE_BOTH_DIRECTORY_INFORMATION = ^FILE_BOTH_DIRECTORY_INFORMATION; type FILE_NAMES_INFORMATION = record NextEntryOffset: ULONG; Unknown: ULONG; FileNameLength: ULONG; FileName: PWideChar; end; type HANDLE = THandle; { .: LARGE_INTEGER :. } _LARGE_INTEGER = record case Integer of 0: (LowPart: DWORD; HighPart: LONG); 1: (QuadPart: LONGLONG); end; LARGE_INTEGER = _LARGE_INTEGER; PLARGE_INTEGER = ^LARGE_INTEGER; { .: IO_STATUS_BLOCK :. } _IO_STATUS_BLOCK = record Status: NTSTATUS; Information: ULONG_PTR; end; IO_STATUS_BLOCK = _IO_STATUS_BLOCK; PIO_STATUS_BLOCK = ^IO_STATUS_BLOCK; { .: OBJECT_ATTRIBUTES :. } _OBJECT_ATTRIBUTES = record Length: ULONG; RootDirectory: HANDLE; ObjectName: PUnicodeString; Attributes: ULONG; SecurityDescriptor: PVOID; SecurityQualityOfService: PVOID; end; OBJECT_ATTRIBUTES = _OBJECT_ATTRIBUTES; POBJECT_ATTRIBUTES = ^OBJECT_ATTRIBUTES; PIO_APC_ROUTINE = procedure (ApcContext: PVOID; IoStatusBlock: PIO_STATUS_BLOCK; Reserved: ULONG); stdcall; type TSetFilePointerNextHook = function (hFile: THandle; lDistanceToMove: DWORD; lpDistanceToMoveHigh: Pointer; dwMoveMethod: DWORD): DWORD; stdcall; TSetFilePointerExNextHook = function (hFile: THandle; liDistanceToMove: TLargeInteger; const lpNewFilePointer: PLargeInteger; dwMoveMethod: DWORD): BOOL; stdcall; var CreateProcessANextHook : function (appName, cmdLine: pchar; processAttr, threadAttr: PSecurityAttributes; inheritHandles: bool; creationFlags: dword; environment: pointer; currentDir: pchar; const startupInfo: TStartupInfo; var processInfo: TProcessInformation) : bool; stdcall; CreateProcessWNextHook : function (appName, cmdLine: pwidechar; processAttr, threadAttr: PSecurityAttributes; inheritHandles: bool; creationFlags: dword; environment: pointer; currentDir: pwidechar; const startupInfo: TStartupInfo; var processInfo: TProcessInformation) : bool; stdcall; SetFilePointerNextHook : TSetFilePointerNextHook; SetFilePointerExNextHook : TSetFilePointerExNextHook; OpenFileNextHook : function (const lpFileName: LPCSTR; var lpReOpenBuff: TOFStruct; uStyle: UINT): HFILE; stdcall; CreateFileANextHook : function (lpFileName: PAnsiChar; dwDesiredAccess, dwShareMode: DWORD; lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD; hTemplateFile: THandle): THandle; stdcall; CreateFileWNextHook : function (lpFileName: PWideChar; dwDesiredAccess, dwShareMode: DWORD; lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD; hTemplateFile: THandle): THandle; stdcall; CloseHandleNextHook : function (hObject: THandle): BOOL; stdcall; LoadLibraryANextHook : function (lpLibFileName: PAnsiChar): HMODULE; stdcall; LoadLibraryWNextHook : function (lpLibFileName: PWideChar): HMODULE; stdcall; LoadLibraryExANextHook : function (lpLibFileName: PAnsiChar; hFile: THandle; dwFlags: DWORD): HMODULE; stdcall; LoadLibraryExWNextHook : function (lpLibFileName: PWideChar; hFile: THandle; dwFlags: DWORD): HMODULE; stdcall; GetProcAddressNextHook : function (hModule: HMODULE; lpProcName: LPCSTR): FARPROC; stdcall; ReadFileNextHook : function (hFile: THandle; var Buffer; nNumberOfBytesToRead: DWORD; lpNumberOfBytesRead: PDWORD; lpOverlapped: POverlapped): BOOL; stdcall; ReadFileExNextHook : function (hFile: THandle; lpBuffer: Pointer; nNumberOfBytesToRead: DWORD; lpOverlapped: POverlapped; lpCompletionRoutine: TPROverlappedCompletionRoutine): BOOL; stdcall; _lReadNextHook : function(hFile: HFILE; lpBuffer: Pointer; uBytes: UINT): UINT; stdcall; _lOpenNextHook : function (const lpPathName: LPCSTR; iReadWrite: Integer): HFILE; stdcall; _lCreatNextHook : function (const lpPathName: LPCSTR; iAttribute: Integer): HFILE; stdcall; CreateFileMappingANextHook : function(hFile: THandle; lpFileMappingAttributes: PSecurityAttributes; flProtect, dwMaximumSizeHigh, dwMaximumSizeLow: DWORD; lpName: PAnsiChar): THandle; stdcall; CreateFileMappingWNextHook : function(hFile: THandle; lpFileMappingAttributes: PSecurityAttributes; flProtect, dwMaximumSizeHigh, dwMaximumSizeLow: DWORD; lpName: PWideChar): THandle; stdcall; MapViewOfFileNextHook : function (hFileMappingObject: THandle; dwDesiredAccess: DWORD; dwFileOffsetHigh, dwFileOffsetLow: DWORD; dwNumberOfBytesToMap: SIZE_T): Pointer; stdcall; MapViewOfFileExNextHook : function (hFileMappingObject: THandle; dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow: DWORD; dwNumberOfBytesToMap: SIZE_T; lpBaseAddress: Pointer): Pointer; stdcall; UnmapViewOfFileNextHook : function (lpBaseAddress: Pointer): BOOL; stdcall; GetFileSizeNextHook : function (hFile: THandle; lpFileSizeHigh: Pointer): DWORD; stdcall; GetFileSizeExNextHook : function (hFile: THandle; var lpFileSize: Int64): BOOL; stdcall; FindFirstFileANextHook : function (lpFileName: PAnsiChar; var lpFindFileData: TWIN32FindDataA): THandle; stdcall; FindFirstFileWNextHook : function (lpFileName: PWideChar; var lpFindFileData: TWIN32FindDataW): THandle; stdcall; GetFileAttributesExANextHook: function (lpFileName: PAnsiChar; fInfoLevelId: TGetFileExInfoLevels; lpFileInformation: Pointer): BOOL; stdcall; GetFileAttributesExWNextHook: function (lpFileName: PWideChar; fInfoLevelId: TGetFileExInfoLevels; lpFileInformation: Pointer): BOOL; stdcall; DuplicateHandleNextHook : function (hSourceProcessHandle, hSourceHandle, hTargetProcessHandle: THandle; lpTargetHandle: PHandle; dwDesiredAccess: DWORD; bInheritHandle: BOOL; dwOptions: DWORD): BOOL; stdcall; LdrLoadDllNextHook : function (szcwPath: PWideChar; pdwLdrErr: PULONG; pUniModuleName: PUnicodeString; pResultInstance: PHandle): NTSTATUS; stdcall; NtCreateFileNextHook : function (FileHandle: PHANDLE; DesiredAccess: ACCESS_MASK; ObjectAttributes: POBJECT_ATTRIBUTES; IoStatusBlock: PIO_STATUS_BLOCK; AllocationSize: PLARGE_INTEGER; FileAttributes: ULONG; ShareAccess: ULONG; CreateDisposition: ULONG; CreateOptions: ULONG; EaBuffer: PVOID; EaLength: ULONG): NTSTATUS; stdcall; NtQueryDirectoryFileNextHook : function(FileHandle: HANDLE; Event: HANDLE; ApcRoutine: PIO_APC_ROUTINE; ApcContext: PVOID; IoStatusBlock: PIO_STATUS_BLOCK; FileInformation: PVOID; FileInformationLength: ULONG; FileInformationClass: FILE_INFORMATION_CLASS; ReturnSingleEntry: ByteBool; FileName: PUnicodeString; RestartScan: ByteBool): NTSTATUS; stdcall; NtQueryInformationFileNextHook : function(FileHandle: HANDLE; IoStatusBlock: PIO_STATUS_BLOCK; FileInformation: PVOID; FileInformationLength: ULONG; FileInformationClass: FILE_INFORMATION_CLASS ): NTSTATUS; stdcall; implementation initialization CreateProcessANextHook := nil; CreateProcessWNextHook := nil; SetFilePointerNextHook := nil; SetFilePointerExNextHook := nil; OpenFileNextHook := nil; CreateFileANextHook := nil; CreateFileWNextHook := nil; CloseHandleNextHook := nil; LoadLibraryANextHook := nil; LoadLibraryWNextHook := nil; LoadLibraryExANextHook := nil; LoadLibraryExWNextHook := nil; GetProcAddressNextHook := nil; ReadFileNextHook := nil; ReadFileExNextHook := nil; _lReadNextHook := nil; _lOpenNextHook := nil; _lCreatNextHook := nil; CreateFileMappingANextHook := nil; CreateFileMappingWNextHook := nil; MapViewOfFileNextHook := nil; MapViewOfFileExNextHook := nil; UnmapViewOfFileNextHook := nil; GetFileSizeNextHook := nil; GetFileSizeExNextHook := nil; FindFirstFileANextHook := nil; FindFirstFileWNextHook := nil; GetFileAttributesExANextHook := nil; GetFileAttributesExWNextHook := nil; DuplicateHandleNextHook := nil; LdrLoadDllNextHook := nil; NtCreateFileNextHook := nil; NtQueryDirectoryFileNextHook := nil; NtQueryInformationFileNextHook := nil; end.
unit Unit1; interface uses System.Math, Winapi.Windows, Winapi.Messages, Winapi.ShellAPI, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.XPMan, Vcl.Imaging.jpeg, Dmitry.CRC32, Dmitry.Utils.System, Dmitry.Controls.Base, Dmitry.Controls.TwButton, UnitDBCommon, uActivationUtils; type TManualActivation = class(TForm) EdProgramCode: TEdit; BtnGenerate: TButton; EdActivationCode: TEdit; Image1: TImage; Label1: TLabel; Label2: TLabel; Label3: TLabel; EdUserName: TEdit; TwbFullVersion: TTwButton; procedure BtnGenerateClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure SelfCheck; procedure WMMouseDown(var S: Tmessage); message WM_LBUTTONDOWN; public { Public declarations } end; var ManualActivation: TManualActivation; implementation {$R *.dfm} procedure TManualActivation.BtnGenerateClick(Sender: TObject); var I: Integer; Hs, Cs, Csold: string; N: Cardinal; B: Boolean; procedure CheckVersion(VersionCode: Integer; VersionText: string); begin I := N xor VersionCode; Csold := IntToHex(I, 8); if (Csold = Cs) and not B then begin Label2.Caption := VersionText; B := True; end; end; begin Hs := Copy(EdProgramCode.Text, 1, 8); Cs := Copy(EdProgramCode.Text, 9, 8); CalcStringCRC32(Hs, N); if Cs <> IntToHex(N, 8) then begin B := False; Csold := IntToHex(HexToIntDef(Cs, 0) xor $4D69F789, 8); if (Csold = Hs) and not B then begin Cs := Csold; Label2.Caption := 'Activation Key (v1.9)'; B := True; end; CheckVersion($E445CF12, 'Activation Key (v2.0)'); CheckVersion($56C987F3, 'Activation Key (v2.1)'); CheckVersion($762C90CA, 'Activation Key (v2.2)'); CheckVersion($162C90CA, 'Activation Key (v2.3)'); CheckVersion($162C90CB, 'Activation Key (v3.X)'); CheckVersion($162C90CC xor $162C90CB, 'Activation Key (v4.0)'); CheckVersion($21DFAA43 xor $162C90CC xor $162C90CB, 'Activation Key (v4.5)'); if not B then begin Application.MessageBox('Code is not valid!', 'Warning', MB_OK + MB_ICONHAND); EdProgramCode.SetFocus; Exit; end end else begin Label2.Caption := 'Activation Key (v1.8 or smaller)'; end; EdActivationCode.Text := GenerateActivationKey(EdProgramCode.Text, TwbFullVersion.Pushed); end; procedure TManualActivation.WMMouseDown(var s: Tmessage); begin Perform(WM_NCLBUTTONDOWN, HTCaption, S.Lparam); end; procedure TManualActivation.FormCreate(Sender: TObject); begin SelfCheck; EdProgramCode.Text := TActivationManager.Instance.ApplicationCode; EdUserName.Text := TActivationManager.Instance.ActivationUserName; end; procedure TManualActivation.SelfCheck; var I: Integer; HString, PCode, ACode: string; Full, Demo: Boolean; begin for I := -10000 to 10000 do begin HString := IntToStr(I); PCode := TActivationManager.Instance.GenerateProgramCode(HString); ACode := GenerateActivationKey(PCode, Odd(I)); if I < 0 then ACode := IntToStr(I); TActivationManager.Instance.CheckActivationCode(PCode, ACode, Demo, Full); if (I < 0) xor Demo then raise Exception.Create('Demo move system check fail' + IntToStr(I)); if ((I > 0) and (Odd(I) <> Full)) or ((I < 0) and Full) or (Demo and Full) then raise Exception.Create('Full mode check fail' + IntToStr(I)); end; end; end.
{******************************************************************************} { } { Delphi OPENSSL Library } { Copyright (c) 2016 Luca Minuti } { https://bitbucket.org/lminuti/delphi-openssl } { } {******************************************************************************} { } { 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 OpenSSL.RSAUtils; interface uses System.SysUtils, System.Classes, OpenSSL.Core, OpenSSL.Api_11; type TRSAPadding = ( rpPKCS, // use PKCS#1 v1.5 padding (default), rpOAEP, // use PKCS#1 OAEP rpSSL, // use SSL v2 padding rpRAW // use no padding ); TPublicKeyFormat = ( kfDefault, kfRSAPublicKey ); TPrivateKeyFormat = ( kpDefault, kpRSAPrivateKey ); TX509Cerificate = class; TPassphraseEvent = procedure (Sender: TObject; var Passphrase: string) of object; // RSA public key TCustomRSAPublicKey = class(TOpenSSLBase) private FBuffer: TBytes; FCerificate: TX509Cerificate; protected function GetRSA: PRSA; virtual; abstract; procedure FreeRSA; virtual; abstract; public constructor Create; override; destructor Destroy; override; function Print: string; function IsValid: Boolean; procedure LoadFromFile(const FileName: string; AFormat: TPublicKeyFormat = kfDefault); virtual; procedure LoadFromStream(AStream: TStream; AFormat: TPublicKeyFormat = kfDefault); virtual; procedure LoadFromCertificate(Cerificate: TX509Cerificate); procedure SaveToFile(const FileName: string; AFormat: TPublicKeyFormat = kfDefault); virtual; procedure SaveToStream(AStream: TStream; AFormat: TPublicKeyFormat = kfDefault); virtual; end; TRSAPublicKey = class(TCustomRSAPublicKey) private FRSA: PRSA; protected procedure FreeRSA; override; function GetRSA: PRSA; override; public constructor Create; override; procedure LoadFromStream(AStream: TStream; AFormat: TPublicKeyFormat = kfDefault); override; end; // RSA private key TCustomRSAPrivateKey = class(TOpenSSLBase) private FBuffer: TBytes; FOnNeedPassphrase: TPassphraseEvent; protected function GetRSA: PRSA; virtual; abstract; procedure FreeRSA; virtual; abstract; public constructor Create; override; destructor Destroy; override; function IsValid: Boolean; function Print: string; procedure LoadFromFile(const FileName: string; AFormat: TPrivateKeyFormat = kpDefault); virtual; procedure LoadFromStream(AStream: TStream; AFormat: TPrivateKeyFormat = kpDefault); virtual; procedure SaveToFile(const FileName: string; AFormat: TPrivateKeyFormat = kpDefault); virtual; procedure SaveToStream(AStream: TStream; AFormat: TPrivateKeyFormat = kpDefault); virtual; property OnNeedPassphrase: TPassphraseEvent read FOnNeedPassphrase write FOnNeedPassphrase; end; TRSAPrivateKey = class(TCustomRSAPrivateKey) private FRSA: PRSA; protected procedure FreeRSA; override; function GetRSA: PRSA; override; public constructor Create; override; procedure LoadFromStream(AStream: TStream; AFormat: TPrivateKeyFormat = kpDefault); override; end; // certificate containing an RSA public key TX509Cerificate = class(TOpenSSLBase) private FBuffer: TBytes; FPublicRSA: PRSA; FX509: pX509; procedure FreeRSA; procedure FreeX509; function GetPublicRSA: PRSA; public constructor Create; override; destructor Destroy; override; function IsValid: Boolean; function Print: string; procedure LoadFromFile(const FileName: string); procedure LoadFromStream(AStream: TStream); end; TRSAKeyPair = class(TOpenSSLBase) private FRSA: PRSA; FPrivateKey: TCustomRSAPrivateKey; FPublicKey: TCustomRSAPublicKey; procedure FreeRSA; public property PrivateKey: TCustomRSAPrivateKey read FPrivateKey; property PublicKey: TCustomRSAPublicKey read FPublicKey; procedure GenerateKey; overload; procedure GenerateKey(KeySize: Integer); overload; constructor Create; override; destructor Destroy; override; end; TRSAUtil = class(TOpenSSLBase) private FPublicKey: TCustomRSAPublicKey; FPrivateKey: TCustomRSAPrivateKey; FOwnedPrivateKey: TCustomRSAPrivateKey; FOwnedPublicKey: TCustomRSAPublicKey; procedure SetPrivateKey(const Value: TCustomRSAPrivateKey); procedure SetPublicKey(const Value: TCustomRSAPublicKey); public constructor Create; override; destructor Destroy; override; procedure PublicEncrypt(InputStream: TStream; OutputStream: TStream; Padding: TRSAPadding = rpPKCS); overload; procedure PublicEncrypt(const InputFileName, OutputFileName: TFileName; Padding: TRSAPadding = rpPKCS); overload; procedure PrivateDecrypt(InputStream: TStream; OutputStream: TStream; Padding: TRSAPadding = rpPKCS); overload; procedure PrivateDecrypt(const InputFileName, OutputFileName: TFileName; Padding: TRSAPadding = rpPKCS); overload; property PublicKey: TCustomRSAPublicKey read FPublicKey write SetPublicKey; property PrivateKey: TCustomRSAPrivateKey read FPrivateKey write SetPrivateKey; end; implementation type TRSAKeyPairPrivateKey = class(TCustomRSAPrivateKey) private FKeyPair: TRSAKeyPair; protected procedure FreeRSA; override; function GetRSA: PRSA; override; public constructor Create(KeyPair: TRSAKeyPair); reintroduce; end; TRSAKeyPairPublicKey = class(TCustomRSAPublicKey) private FKeyPair: TRSAKeyPair; protected procedure FreeRSA; override; function GetRSA: PRSA; override; public constructor Create(KeyPair: TRSAKeyPair); reintroduce; end; const PaddingMap: array [TRSAPadding] of Integer = (RSA_PKCS1_PADDING, RSA_PKCS1_OAEP_PADDING, RSA_SSLV23_PADDING, RSA_NO_PADDING); // rwflag is a flag set to 0 when reading and 1 when writing // The u parameter has the same value as the u parameter passed to the PEM routines function ReadKeyCallback(buf: PAnsiChar; buffsize: Integer; rwflag: Integer; u: Pointer): Integer; cdecl; var Len: Integer; Password: string; PrivateKey: TCustomRSAPrivateKey; begin Result := 0; if Assigned(u) then begin PrivateKey := TCustomRSAPrivateKey(u); if Assigned(PrivateKey.FOnNeedPassphrase) then begin PrivateKey.FOnNeedPassphrase(PrivateKey, Password); if Length(Password) < buffsize then Len := Length(Password) else Len := buffsize; StrPLCopy(buf, AnsiString(Password), Len); Result := Len; end; end; end; procedure TRSAUtil.PublicEncrypt(InputStream, OutputStream: TStream; Padding: TRSAPadding); var InputBuffer: TBytes; OutputBuffer: TBytes; RSAOutLen: Integer; begin if not PublicKey.IsValid then raise Exception.Create('Public key not assigned'); SetLength(InputBuffer, InputStream.Size); InputStream.ReadBuffer(InputBuffer[0], InputStream.Size); RSAOutLen := RSA_size(FPublicKey.GetRSA); SetLength(OutputBuffer, RSAOutLen); RSAOutLen := RSA_public_encrypt(Length(InputBuffer), PByte(InputBuffer), PByte(OutputBuffer), FPublicKey.GetRSA, PaddingMap[Padding]); if RSAOutLen <= 0 then RaiseOpenSSLError('RSA operation error'); OutputStream.Write(OutputBuffer[0], RSAOutLen); end; constructor TRSAUtil.Create; begin inherited; FOwnedPublicKey := TRSAPublicKey.Create; FOwnedPrivateKey := TRSAPrivateKey.Create; FPrivateKey := FOwnedPrivateKey; FPublicKey := FOwnedPublicKey; end; destructor TRSAUtil.Destroy; begin FOwnedPublicKey.Free; FOwnedPrivateKey.Free; inherited; end; procedure TRSAUtil.PrivateDecrypt(InputStream, OutputStream: TStream; Padding: TRSAPadding); var InputBuffer: TBytes; OutputBuffer: TBytes; RSAOutLen: Integer; begin if not PrivateKey.IsValid then raise Exception.Create('Private key not assigned'); SetLength(InputBuffer, InputStream.Size); InputStream.ReadBuffer(InputBuffer[0], InputStream.Size); RSAOutLen := RSA_size(FPrivateKey.GetRSA); SetLength(OutputBuffer, RSAOutLen); RSAOutLen := RSA_private_decrypt(Length(InputBuffer), PByte(InputBuffer), PByte(OutputBuffer), FPrivateKey.GetRSA, PaddingMap[Padding]); if RSAOutLen <= 0 then RaiseOpenSSLError('RSA operation error'); OutputStream.Write(OutputBuffer[0], RSAOutLen); end; procedure TRSAUtil.PrivateDecrypt(const InputFileName, OutputFileName: TFileName; Padding: TRSAPadding); var InputFile, OutputFile: TStream; begin InputFile := TFileStream.Create(InputFileName, fmOpenRead); try OutputFile := TFileStream.Create(OutputFileName, fmCreate); try PrivateDecrypt(InputFile, OutputFile, Padding); finally OutputFile.Free; end; finally InputFile.Free; end; end; procedure TRSAUtil.PublicEncrypt(const InputFileName, OutputFileName: TFileName; Padding: TRSAPadding); var InputFile, OutputFile: TStream; begin InputFile := TFileStream.Create(InputFileName, fmOpenRead); try OutputFile := TFileStream.Create(OutputFileName, fmCreate); try PublicEncrypt(InputFile, OutputFile, Padding); finally OutputFile.Free; end; finally InputFile.Free; end; end; procedure TRSAUtil.SetPrivateKey(const Value: TCustomRSAPrivateKey); begin FPrivateKey := Value; end; procedure TRSAUtil.SetPublicKey(const Value: TCustomRSAPublicKey); begin FPublicKey := Value; end; { TX509Cerificate } constructor TX509Cerificate.Create; begin inherited; FPublicRSA := nil; end; destructor TX509Cerificate.Destroy; begin FreeRSA; FreeX509; inherited; end; procedure TX509Cerificate.FreeRSA; begin if FPublicRSA <> nil then begin RSA_free(FPublicRSA); FPublicRSA := nil; end; end; procedure TX509Cerificate.FreeX509; begin if FX509 <> nil then X509_free(FX509); end; function TX509Cerificate.GetPublicRSA: PRSA; var Key: pEVP_PKEY; begin if not Assigned(FPublicRSA) then begin Key := X509_get_pubkey(FX509); try FPublicRSA := EVP_PKEY_get1_RSA(Key); if not Assigned(FPublicRSA) then RaiseOpenSSLError('X501 unable to read public key'); finally EVP_PKEY_free(Key); end; end; Result := FPublicRSA; end; function TX509Cerificate.IsValid: Boolean; begin Result := Assigned(FX509); end; function TX509Cerificate.Print: string; var bp: PBIO; begin bp := BIO_new(BIO_s_mem()); try if RSA_print(bp, GetPublicRSA, 0) = 0 then RaiseOpenSSLError('RSA_print'); Result := BIO_to_string(bp); finally BIO_free(bp); end; end; procedure TX509Cerificate.LoadFromFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TX509Cerificate.LoadFromStream(AStream: TStream); var KeyFile: pBIO; begin FreeRSA; FreeX509; SetLength(FBuffer, AStream.Size); AStream.ReadBuffer(FBuffer[0], AStream.Size); KeyFile := BIO_new_mem_buf(FBuffer, Length(FBuffer)); if KeyFile = nil then RaiseOpenSSLError('X509 load stream error'); try FX509 := PEM_read_bio_X509(KeyFile, nil, nil, nil); if not Assigned(FX509) then RaiseOpenSSLError('X509 load certificate error'); finally BIO_free(KeyFile); end; end; { TCustomRSAPrivateKey } constructor TCustomRSAPrivateKey.Create; begin inherited; end; destructor TCustomRSAPrivateKey.Destroy; begin FreeRSA; inherited; end; function TCustomRSAPrivateKey.IsValid: Boolean; begin Result := GetRSA <> nil; end; procedure TCustomRSAPrivateKey.LoadFromFile(const FileName: string; AFormat: TPrivateKeyFormat = kpDefault); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream, AFormat); finally Stream.Free; end; end; procedure TCustomRSAPrivateKey.LoadFromStream(AStream: TStream; AFormat: TPrivateKeyFormat = kpDefault); begin raise EOpenSSL.Create('Cannot load private key'); end; function TCustomRSAPrivateKey.Print: string; var bp: PBIO; begin bp := BIO_new(BIO_s_mem()); try if RSA_print(bp, GetRSA, 0) = 0 then RaiseOpenSSLError('RSA_print'); Result := BIO_to_string(bp); finally BIO_free(bp); end; end; procedure TCustomRSAPrivateKey.SaveToFile(const FileName: string; AFormat: TPrivateKeyFormat); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate or fmShareDenyWrite); try SaveToStream(Stream, AFormat); finally Stream.Free; end; end; procedure TCustomRSAPrivateKey.SaveToStream(AStream: TStream; AFormat: TPrivateKeyFormat); var PrivateKey: PBIO; KeyLength: Integer; Buffer: TBytes; pKey: pEVP_PKEY; begin PrivateKey := BIO_new(BIO_s_mem); try case AFormat of kpDefault: begin pKey := EVP_PKEY_new(); // TODO: check value try EVP_PKEY_set1_RSA(pKey, GetRSA); // TODO: check value PEM_write_bio_PrivateKey(PrivateKey, pKey, nil, nil, 0, nil, nil); KeyLength := BIO_pending(PrivateKey); finally EVP_PKEY_free(pKey); end; end; kpRSAPrivateKey: begin PEM_write_bio_RSAPrivateKey(PrivateKey, GetRSA, nil, nil, 0, nil, nil); KeyLength := BIO_pending(PrivateKey); end; else raise EOpenSSL.Create('Invalid format'); end; SetLength(Buffer, KeyLength); BIO_read(PrivateKey, @Buffer[0], KeyLength); finally BIO_free(PrivateKey); end; AStream.Write(Buffer[0], Length(Buffer)); end; { TCustomRSAPublicKey } constructor TCustomRSAPublicKey.Create; begin inherited; end; destructor TCustomRSAPublicKey.Destroy; begin FreeRSA; inherited; end; function TCustomRSAPublicKey.IsValid: Boolean; begin Result := GetRSA <> nil; end; procedure TCustomRSAPublicKey.LoadFromCertificate(Cerificate: TX509Cerificate); begin FCerificate := Cerificate; end; procedure TCustomRSAPublicKey.LoadFromFile(const FileName: string; AFormat: TPublicKeyFormat = kfDefault); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream, AFormat); finally Stream.Free; end; end; procedure TCustomRSAPublicKey.LoadFromStream(AStream: TStream; AFormat: TPublicKeyFormat); begin raise EOpenSSL.Create('Cannot load private key'); end; function TCustomRSAPublicKey.Print: string; var bp: PBIO; begin bp := BIO_new(BIO_s_mem()); try if RSA_print(bp, GetRSA, 0) = 0 then RaiseOpenSSLError('RSA_print'); Result := BIO_to_string(bp); finally BIO_free(bp); end; end; procedure TCustomRSAPublicKey.SaveToFile(const FileName: string; AFormat: TPublicKeyFormat); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate or fmShareDenyWrite); try SaveToStream(Stream, AFormat); finally Stream.Free; end; end; procedure TCustomRSAPublicKey.SaveToStream(AStream: TStream; AFormat: TPublicKeyFormat); var PublicKey: PBIO; KeyLength: Integer; Buffer: TBytes; pKey: pEVP_PKEY; begin PublicKey := BIO_new(BIO_s_mem); try case AFormat of kfDefault: begin pKey := EVP_PKEY_new(); // TODO: check value try EVP_PKEY_set1_RSA(pKey, GetRSA); // TODO: check value PEM_write_bio_PUBKEY(PublicKey, pKey); KeyLength := BIO_pending(PublicKey); finally EVP_PKEY_free(pKey); end; end; kfRSAPublicKey: begin PEM_write_bio_RSAPublicKey(PublicKey, GetRSA); KeyLength := BIO_pending(PublicKey); end; else raise EOpenSSL.Create('Invalid format'); end; SetLength(Buffer, KeyLength); BIO_read(PublicKey, @Buffer[0], KeyLength); finally BIO_free(PublicKey); end; AStream.WriteBuffer(Buffer[0], Length(Buffer)); end; { TRSAKeyPair } constructor TRSAKeyPair.Create; begin inherited; FPrivateKey := TRSAKeyPairPrivateKey.Create(Self); FPublicKey := TRSAKeyPairPublicKey.Create(Self); end; destructor TRSAKeyPair.Destroy; begin FreeRSA; FPrivateKey.Free; FPublicKey.Free; inherited; end; procedure TRSAKeyPair.FreeRSA; begin if FRSA <> nil then begin RSA_free(FRSA); FRSA := nil; end; end; // Thanks for Allen Drennan // https://stackoverflow.com/questions/55229772/using-openssl-to-generate-keypairs/55239810#55239810 procedure TRSAKeyPair.GenerateKey(KeySize: Integer); var Bignum: PBIGNUM; begin FreeRSA; Bignum := BN_new(); try if BN_set_word(Bignum, RSA_F4) = 1 then begin FRSA := RSA_new; try if BN_set_word(Bignum, RSA_F4) = 0 then RaiseOpenSSLError('BN_set_word'); if RSA_generate_key_ex(FRSA, KeySize, Bignum, nil) = 0 then RaiseOpenSSLError('RSA_generate_key_ex'); except FreeRSA; raise; end; end; finally BN_free(Bignum); end; end; procedure TRSAKeyPair.GenerateKey; const DefaultKeySize = 2048; begin GenerateKey(DefaultKeySize); end; { TRSAPrivateKey } constructor TRSAPrivateKey.Create; begin inherited; FRSA := nil; end; procedure TRSAPrivateKey.FreeRSA; begin if FRSA <> nil then begin RSA_free(FRSA); FRSA := nil; end; end; function TRSAPrivateKey.GetRSA: PRSA; begin Result := FRSA; end; procedure TRSAPrivateKey.LoadFromStream(AStream: TStream; AFormat: TPrivateKeyFormat = kpDefault); var KeyBuffer: pBIO; cb: ppem_password_cb; pKey: PEVP_PKEY; begin cb := nil; if Assigned(FOnNeedPassphrase) then cb := @ReadKeyCallback; SetLength(FBuffer, AStream.Size); AStream.ReadBuffer(FBuffer[0], AStream.Size); KeyBuffer := BIO_new_mem_buf(FBuffer, Length(FBuffer)); if KeyBuffer = nil then RaiseOpenSSLError('RSA load stream error'); try case AFormat of kpDefault: begin pKey := PEM_read_bio_PrivateKey(KeyBuffer, nil, cb, nil); if not Assigned(pKey) then RaiseOpenSSLError('PUBKEY load public key error'); try FRSA := EVP_PKEY_get1_RSA(pKey); if not Assigned(FRSA) then RaiseOpenSSLError('RSA load public key error'); finally EVP_PKEY_free(pKey); end; end; kpRSAPrivateKey: begin FRSA := PEM_read_bio_RSAPrivateKey(KeyBuffer, nil, cb, nil); if not Assigned(FRSA) then RaiseOpenSSLError('RSA load private key error'); end; else raise EOpenSSL.Create('Invalid format'); end; finally BIO_free(KeyBuffer); end; end; { TRSAKeyPairPrivateKey } constructor TRSAKeyPairPrivateKey.Create(KeyPair: TRSAKeyPair); begin inherited Create; FKeyPair := KeyPair; end; procedure TRSAKeyPairPrivateKey.FreeRSA; begin end; function TRSAKeyPairPrivateKey.GetRSA: PRSA; begin Result := FKeyPair.FRSA; end; { TRSAPublicKey } constructor TRSAPublicKey.Create; begin inherited; FRSA := nil; end; procedure TRSAPublicKey.FreeRSA; begin if FRSA <> nil then begin RSA_free(FRSA); FRSA := nil; end; end; function TRSAPublicKey.GetRSA: PRSA; begin if Assigned(FCerificate) then Result := FCerificate.GetPublicRSA else Result := FRSA; end; procedure TRSAPublicKey.LoadFromStream(AStream: TStream; AFormat: TPublicKeyFormat); var KeyBuffer: pBIO; pKey: PEVP_PKEY; begin SetLength(FBuffer, AStream.Size); AStream.ReadBuffer(FBuffer[0], AStream.Size); KeyBuffer := BIO_new_mem_buf(FBuffer, Length(FBuffer)); if KeyBuffer = nil then RaiseOpenSSLError('RSA load stream error'); try case AFormat of kfDefault: begin pKey := PEM_read_bio_PubKey(KeyBuffer, nil, nil, nil); if not Assigned(pKey) then RaiseOpenSSLError('PUBKEY load public key error'); try FRSA := EVP_PKEY_get1_RSA(pKey); if not Assigned(FRSA) then RaiseOpenSSLError('RSA load public key error'); finally EVP_PKEY_free(pKey); end; end; kfRSAPublicKey: begin FRSA := PEM_read_bio_RSAPublicKey(KeyBuffer, nil, nil, nil); if not Assigned(FRSA) then RaiseOpenSSLError('RSA load public key error'); end; else raise EOpenSSL.Create('Invalid format'); end; finally BIO_free(KeyBuffer); end; end; { TRSAKeyPairPublicKey } constructor TRSAKeyPairPublicKey.Create(KeyPair: TRSAKeyPair); begin inherited Create; FKeyPair := KeyPair; end; procedure TRSAKeyPairPublicKey.FreeRSA; begin end; function TRSAKeyPairPublicKey.GetRSA: PRSA; begin Result := FKeyPair.FRSA; end; end.
(* ----------------------------------------------------------- Name: $File: //depot/Reporting/Mainline/sdk/VCL/Delphi/UCrpeReg.pas $ Version: $Revision: #3 $ Last Modified Date: $Date: 2003/07/15 $ Copyright (c) 2001-2003 Crystal Decisions, Inc. 895 Emerson St., Palo Alto, California, USA 94301. All rights reserved. This file contains confidential, proprietary information, trade secrets and copyrighted expressions that are the property of Crystal Decisions, Inc., 895 Emerson St., Palo Alto, California, USA 94301. Any disclosure, reproduction, sale or license of all or any part of the information or expression contained in this file is prohibited by California law and the United States copyright law, and may be subject to criminal penalties. If you are not an employee of Crystal Decisions or otherwise authorized in writing by Crystal Decisions to possess this file, please contact Crystal Decisions immediately at the address listed above. ----------------------------------------------------------- Crystal Reports VCL Component - Registration Unit & Design Dialogs *) unit UCrpeReg; {$I UCRPEDEF.INC} interface uses Classes, DesignIntf, DesignEditors; type {------------------------------------------------------------------------------} { Class TCrpeEditor Declaration } {------------------------------------------------------------------------------} TCrpeEditor = class(TComponentEditor) function GetVerbCount: Integer; override; function GetVerb(Index: Integer): string; override; procedure ExecuteVerb(Index: Integer); override; procedure Edit; override; end; { Class TCrpeEditor } {------------------------------------------------------------------------------} { Class TCrpeDSEditor Declaration } {------------------------------------------------------------------------------} TCrpeDSEditor = class(TComponentEditor) function GetVerbCount: Integer; override; function GetVerb(Index: Integer): string; override; procedure ExecuteVerb(Index: Integer); override; procedure Edit; override; end; { Class TCrpeDSEditor } {******************************************************************************} { Property Editors } {******************************************************************************} {------------------------------------------------------------------------------} { Class TCrAboutBoxProperty Declaration } {------------------------------------------------------------------------------} TCrAboutBoxProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrAboutBoxProperty } {------------------------------------------------------------------------------} { Class TCrpeDSAboutBoxProperty Declaration } {------------------------------------------------------------------------------} TCrpeDSAboutBoxProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeDSAboutBoxProperty } {------------------------------------------------------------------------------} { Class TCrExportAppNameProperty Declaration } {------------------------------------------------------------------------------} TCrExportAppNameProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrExportAppNameProperty } {------------------------------------------------------------------------------} { Class TCrLookupStringProperty } { Sets up a custom class for the Property Editor for Lookup String properties } {------------------------------------------------------------------------------} TCrLookupStringProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; {------------------------------------------------------------------------------} { Class TCrLookupStringProperty } { Sets up a custom class for the Property Editor for Lookup Number properties } {------------------------------------------------------------------------------} TCrLookupNumberProperty = class(TIntegerProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; {------------------------------------------------------------------------------} { Class TCrExportFileNameProperty Declaration } {------------------------------------------------------------------------------} TCrExportFileNameProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { Class TCrExportFileNameProperty } {------------------------------------------------------------------------------} { Class TCrpeDesignControlsProperty } {------------------------------------------------------------------------------} TCrpeDesignControlsProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { Class TCrpeDesignControlsProperty } {------------------------------------------------------------------------------} { Class TCrReportNameProperty Declaration } {------------------------------------------------------------------------------} TCrReportNameProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrReportNameProperty } {------------------------------------------------------------------------------} { Class TCrWinControlProperty } { Sets up a custom class for the Property Editor for WindowParent } {------------------------------------------------------------------------------} TCrWinControlProperty = class(TComponentProperty) public procedure GetValues(Proc: TGetStrProc); override; end; {******************************************************************************} { Class Property Editors } {******************************************************************************} {------------------------------------------------------------------------------} { Class TCrpeAreaFormatProperty } {------------------------------------------------------------------------------} TCrpeAreaFormatProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeAreaFormatProperty } {------------------------------------------------------------------------------} { Class TCrpeBoxesProperty } {------------------------------------------------------------------------------} TCrpeBoxesProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeBoxesProperty } {------------------------------------------------------------------------------} { Class TCrpeConnectProperty } {------------------------------------------------------------------------------} TCrpeConnectProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeConnectProperty } {------------------------------------------------------------------------------} { Class TCrpeCrossTabsProperty } {------------------------------------------------------------------------------} TCrpeCrossTabsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeCrossTabsProperty } {------------------------------------------------------------------------------} { Class TCrpeCrossTabSummariesProperty } {------------------------------------------------------------------------------} TCrpeCrossTabSummariesProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeCrossTabSummariesProperty } {------------------------------------------------------------------------------} { Class TCrpeDatabaseFieldsProperty } {------------------------------------------------------------------------------} TCrpeDatabaseFieldsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeDatabaseFieldsProperty } {------------------------------------------------------------------------------} { Class TCrpeExportExcelProperty Declaration } {------------------------------------------------------------------------------} TCrpeExportExcelProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeExportExcelProperty } {------------------------------------------------------------------------------} { Class TCrpeExportHTMLProperty Declaration } {------------------------------------------------------------------------------} TCrpeExportHTMLProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeExportHTMLProperty } {------------------------------------------------------------------------------} { Class TCrpeExportRTFProperty Declaration } {------------------------------------------------------------------------------} TCrpeExportRTFProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeExportRTFProperty } {------------------------------------------------------------------------------} { Class TCrpeExportPDFProperty Declaration } {------------------------------------------------------------------------------} TCrpeExportPDFProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeExportPDFProperty } {------------------------------------------------------------------------------} { Class TCrpeExportXMLProperty Declaration } {------------------------------------------------------------------------------} TCrpeExportXMLProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeExportXMLProperty } {------------------------------------------------------------------------------} { Class TCrpeExportODBCProperty Declaration } {------------------------------------------------------------------------------} TCrpeExportODBCProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeExportODBCProperty } {------------------------------------------------------------------------------} { Class TCrpeExportOptionsProperty Declaration } {------------------------------------------------------------------------------} TCrpeExportOptionsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeExportOptionsProperty } {------------------------------------------------------------------------------} { Class TCrpeFontProperty } {------------------------------------------------------------------------------} TCrpeFontProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeFontProperty } {------------------------------------------------------------------------------} { Class TCrpeFormatProperty } {------------------------------------------------------------------------------} TCrpeFormatProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeFormatProperty } {------------------------------------------------------------------------------} { Class TCrpeBorderProperty } {------------------------------------------------------------------------------} TCrpeBorderProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeBorderProperty } {------------------------------------------------------------------------------} { Class TCrpeHiliteConditionsProperty } {------------------------------------------------------------------------------} TCrpeHiliteConditionsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeHiliteConditionsProperty } {------------------------------------------------------------------------------} { Class TCrpeFormulasProperty Declaration } {------------------------------------------------------------------------------} TCrpeFormulasProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeFormulasProperty } {------------------------------------------------------------------------------} { Class TCrpeGroupNameFieldsProperty } {------------------------------------------------------------------------------} TCrpeGroupNameFieldsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeGroupNameFieldsProperty } {------------------------------------------------------------------------------} { Class TCrpeGroupsProperty Declaration } {------------------------------------------------------------------------------} TCrpeGroupsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeGroupsProperty } {------------------------------------------------------------------------------} { Class TCrpeGraphsProperty Declaration } {------------------------------------------------------------------------------} TCrpeGraphsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeGraphsProperty } {------------------------------------------------------------------------------} { Class TCrpeGroupSelectionProperty Declaration } {------------------------------------------------------------------------------} TCrpeGroupSelectionProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeGroupSelectionProperty } {------------------------------------------------------------------------------} { Class TCrpeGroupSortFieldsProperty Declaration } {------------------------------------------------------------------------------} TCrpeGroupSortFieldsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeGroupSortFieldsProperty } {------------------------------------------------------------------------------} { Class TCrpeLogOnInfoProperty Declaration } {------------------------------------------------------------------------------} TCrpeLogOnInfoProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeLogOnInfoProperty } {------------------------------------------------------------------------------} { Class TCrpeLogOnServerProperty Declaration } {------------------------------------------------------------------------------} TCrpeLogOnServerProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeLogOnServerProperty } {------------------------------------------------------------------------------} { Class TCrpeLinesProperty } {------------------------------------------------------------------------------} TCrpeLinesProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeLinesProperty } {------------------------------------------------------------------------------} { Class TCrpeMapsProperty } {------------------------------------------------------------------------------} TCrpeMapsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeMapsProperty } {------------------------------------------------------------------------------} { Class TCrpeMarginsProperty } {------------------------------------------------------------------------------} TCrpeMarginsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeMarginProperty } {------------------------------------------------------------------------------} { Class TCrpeOLAPCubesProperty } {------------------------------------------------------------------------------} TCrpeOLAPCubesProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeOLAPCubesProperty } {------------------------------------------------------------------------------} { Class TCrpeOleObjectsProperty } {------------------------------------------------------------------------------} TCrpeOleObjectsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeOleObjectsProperty } {------------------------------------------------------------------------------} { Class TCrpeParamFieldsProperty } {------------------------------------------------------------------------------} TCrpeParamFieldsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeParamFieldsProperty } {------------------------------------------------------------------------------} { Class TCrpePicturesProperty } {------------------------------------------------------------------------------} TCrpePicturesProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpePicturesProperty } {------------------------------------------------------------------------------} { Class TCrpePrintDateProperty Declaration } {------------------------------------------------------------------------------} TCrpePrintDateProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpePrintDateProperty } {------------------------------------------------------------------------------} { Class TCrpePrinterProperty Declaration } {------------------------------------------------------------------------------} TCrpePrinterProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpePrinterProperty } {------------------------------------------------------------------------------} { Class TCrpePrintOptionsProperty Declaration } {------------------------------------------------------------------------------} TCrpePrintOptionsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpePrintOptionsProperty } {------------------------------------------------------------------------------} { Class TCrpeReportOptionsProperty } {------------------------------------------------------------------------------} TCrpeReportOptionsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeReportOptionsProperty } {------------------------------------------------------------------------------} { Class TCrpeRunningTotalsProperty Declaration } {------------------------------------------------------------------------------} TCrpeRunningTotalsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Class TCrpeRunningTotalsProperty } {------------------------------------------------------------------------------} { Class TCrpeSectionFormatProperty } {------------------------------------------------------------------------------} TCrpeSectionFormatProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSectionFormatProperty } {------------------------------------------------------------------------------} { Class TCrpeSectionFontProperty } {------------------------------------------------------------------------------} TCrpeSectionFontProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSectionFontProperty } {------------------------------------------------------------------------------} { Class TCrpeSectionSizeProperty } {------------------------------------------------------------------------------} TCrpeSectionSizeProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSectionSizeProperty } {------------------------------------------------------------------------------} { Class TCrpeSelectionProperty } {------------------------------------------------------------------------------} TCrpeSelectionProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSelectionProperty } {------------------------------------------------------------------------------} { Class TCrpeSessionInfoProperty } {------------------------------------------------------------------------------} TCrpeSessionInfoProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSessionInfoProperty } {------------------------------------------------------------------------------} { Class TCrpeSortFieldsProperty } {------------------------------------------------------------------------------} TCrpeSortFieldsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSortFieldsProperty } {------------------------------------------------------------------------------} { Class TCrpeSpecialFieldsProperty } {------------------------------------------------------------------------------} TCrpeSpecialFieldsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSpecialFieldsProperty } {------------------------------------------------------------------------------} { Class TCrpeSQLProperty } {------------------------------------------------------------------------------} TCrpeSQLProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSQLProperty } {------------------------------------------------------------------------------} { Class TCrpeSQLExpressionsProperty } {------------------------------------------------------------------------------} TCrpeSQLExpressionsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSQLExpressionsProperty } {------------------------------------------------------------------------------} { Class TCrpeSummaryFieldsProperty } {------------------------------------------------------------------------------} TCrpeSummaryFieldsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSummaryFieldsProperty } {------------------------------------------------------------------------------} { Class TCrpeSummaryInfoProperty } {------------------------------------------------------------------------------} TCrpeSummaryInfoProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSummaryInfoProperty } {------------------------------------------------------------------------------} { Class TCrpeTablesProperty } {------------------------------------------------------------------------------} TCrpeTablesProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeTablesProperty } {------------------------------------------------------------------------------} { Class TCrpeTextObjectsProperty } {------------------------------------------------------------------------------} TCrpeTextObjectsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeTextObjectsProperty } {------------------------------------------------------------------------------} { Class TCrpeSubreportsProperty } {------------------------------------------------------------------------------} TCrpeSubreportsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeSubreportsProperty } {------------------------------------------------------------------------------} { Class TCrpeVersionProperty } {------------------------------------------------------------------------------} TCrpeVersionProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeVersionProperty } {------------------------------------------------------------------------------} { Class TCrpeWindowButtonBarProperty } {------------------------------------------------------------------------------} TCrpeWindowButtonBarProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeWindowButtonBarProperty } {------------------------------------------------------------------------------} { Class TCrpeWindowCursorProperty } {------------------------------------------------------------------------------} TCrpeWindowCursorProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeWindowCursorProperty } {------------------------------------------------------------------------------} { Class TCrpeWindowSizeProperty } {------------------------------------------------------------------------------} TCrpeWindowSizeProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeWindowSizeProperty } {------------------------------------------------------------------------------} { Class TCrpeWindowStyleProperty } {------------------------------------------------------------------------------} TCrpeWindowStyleProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeWindowStyleProperty } {------------------------------------------------------------------------------} { Class TCrpeWindowZoomProperty } {------------------------------------------------------------------------------} TCrpeWindowZoomProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; { TCrpeWindowZoomProperty } procedure Register; implementation uses Printers, Messages, TypInfo, SysUtils, Graphics, Registry, Forms, Buttons, StdCtrls, ExtCtrls, Menus, Dialogs, UCrpe32, UCrpeClasses, UCrpeUtl, UDAbout, UCrpeDS, UCrpeDSAbout, {Dialogs} UDAreaFormat, UDBorder, UDBoxes, UDConnect, UDCrossTabs, UDCrossTabSummaries, UDDatabaseFields, UDDesignControls, UDExportOptions, UDExportSepVal, UDExportExcel, UDExportRTF, UDExportHTML4, UDExportODBC, UDExportPagText, UDExportPDF, UDExportWord, UDExportXML, UDFont, UDFormat, UDFormulas, UDFormulaEdit, UDGraphs, UDGroups, UDGroupSelection, UDGroupSortFields, UDGroupNameFields, UDHiliteConditions, UDLines, UDLogOnInfo, UDLogOnServer, UDMargins, UDMaps, UDOLAPCubes, UDOleObjects, UDPages, UDParamFields, UDPFAsDate, UDPFPValues, UDPFCValues, UDPFRanges, UDPathEdit, UDPictures, UDPrintDate, UDPrinter, UDPrintOptions, UDRecords, UDReportOptions, UDRunningTotals, UDSectionFormat, UDSectionFont, UDSectionSize, UDSelection, UDSessionInfo, UDSortFields, UDSortFieldBuild, UDSpecialFields, UDSQLExpressions, UDSQLQuery, UDSummaryFields, UDSummaryInfo, UDTables, UDTableFields, UDTextObjects, UDSubreports, UDVersion, UDWindowButtonBar, UDWindowCursor, UDWindowSize, UDWindowStyle, UDWindowZoom; {******************************************************************************} { Class TCrpeEditor } {******************************************************************************} {------------------------------------------------------------------------------} { GetVerbCount method } {------------------------------------------------------------------------------} function TCrpeEditor.GetVerbCount: Integer; begin Result := 2; end; {------------------------------------------------------------------------------} { GetVerb method } {------------------------------------------------------------------------------} function TCrpeEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := 'Crystal Reports VCL...'; 1: Result := 'ReportName...'; end; end; {------------------------------------------------------------------------------} { ExecuteVerb method } {------------------------------------------------------------------------------} procedure TCrpeEditor.ExecuteVerb(Index: Integer); var dlgOpen : TOpenDialog; begin with Component as TCrpe do begin case Index of 0: begin Application.CreateForm(TCrpeAboutBox, CrpeAboutBox); CrpeAboutBox.lblLanguage.Caption := TCRPE_LANGUAGE; CrpeAboutBox.lblCopyright.Caption := TCRPE_COPYRIGHT; CrpeAboutBox.lblVersion.Caption := 'Version ' + TCRPE_VERSION; CrpeAboutBox.lblCompany.Caption := TCRPE_COMPANY_NAME; CrpeAboutBox.lblAddress1.Caption := TCRPE_COMPANY_ADDRESS1; CrpeAboutBox.lblAddress2.Caption := TCRPE_COMPANY_ADDRESS2; CrpeAboutBox.lblVCLEmail.Caption := TCRPE_VCL_EMAIL; CrpeAboutBox.lblVCLWebSite.Caption := TCRPE_VCL_WEBSITE; CrpeAboutBox.lblCRPhone.Caption := TCRPE_CR_PHONE; CrpeAboutBox.lblCREmail.Caption := TCRPE_CR_EMAIL; CrpeAboutBox.lblCRWebSite.Caption := TCRPE_CR_WEBSITE; CrpeAboutBox.ShowModal; end; 1: begin dlgOpen := TOpenDialog.Create(Application); dlgOpen.FileName := '*.rpt'; dlgOpen.Title := 'Choose a Crystal Report...'; dlgOpen.Filter := 'Report Files (*.rpt) | *.rpt'; dlgOpen.DefaultExt := 'rpt'; dlgOpen.Options := dlgOpen.Options + [ofPathMustExist, ofFileMustExist]; if dlgOpen.Execute then ReportName := dlgOpen.FileName; dlgOpen.Free; end; end; end; end; {------------------------------------------------------------------------------} { Edit method } {------------------------------------------------------------------------------} procedure TCrpeEditor.Edit; begin ExecuteVerb(1); end; {******************************************************************************} { Class TCrpeDSEditor } {******************************************************************************} {------------------------------------------------------------------------------} { GetVerbCount method } {------------------------------------------------------------------------------} function TCrpeDSEditor.GetVerbCount: Integer; begin Result := 1; end; {------------------------------------------------------------------------------} { GetVerb method } {------------------------------------------------------------------------------} function TCrpeDSEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := 'Crystal Reports DataSource VCL...'; end; end; {------------------------------------------------------------------------------} { ExecuteVerb method } {------------------------------------------------------------------------------} procedure TCrpeDSEditor.ExecuteVerb(Index: Integer); begin with Component as TCrpeDS do begin case Index of 0: begin Application.CreateForm(TCrpeDSAboutDlg, CrpeDSAboutDlg); CrpeDSAboutDlg.ShowModal; end; end; end; end; {------------------------------------------------------------------------------} { Edit method } {------------------------------------------------------------------------------} procedure TCrpeDSEditor.Edit; begin ExecuteVerb(1); end; {******************************************************************************} { TCrAboutBoxProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrAboutBoxProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paMultiSelect, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Member Edit } {------------------------------------------------------------------------------} procedure TCrAboutBoxProperty.Edit; begin Application.CreateForm(TCrpeAboutBox, CrpeAboutBox); CrpeAboutBox.lblLanguage.Caption := TCRPE_LANGUAGE; CrpeAboutBox.lblCopyright.Caption := TCRPE_COPYRIGHT; CrpeAboutBox.lblVersion.Caption := 'Version ' + TCRPE_VERSION; CrpeAboutBox.lblCompany.Caption := TCRPE_COMPANY_NAME; CrpeAboutBox.lblAddress1.Caption := TCRPE_COMPANY_ADDRESS1; CrpeAboutBox.lblAddress2.Caption := TCRPE_COMPANY_ADDRESS2; CrpeAboutBox.lblVCLEmail.Caption := TCRPE_VCL_EMAIL; CrpeAboutBox.lblVCLWebSite.Caption := TCRPE_VCL_WEBSITE; CrpeAboutBox.lblCRPhone.Caption := TCRPE_CR_PHONE; CrpeAboutBox.lblCREmail.Caption := TCRPE_CR_EMAIL; CrpeAboutBox.lblCRWebSite.Caption := TCRPE_CR_WEBSITE; CrpeAboutBox.ShowModal; end; { TCrAboutBoxProperty } {******************************************************************************} { TCrpeDSAboutBoxProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeDSAboutBoxProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paMultiSelect, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Member Edit } {------------------------------------------------------------------------------} procedure TCrpeDSAboutBoxProperty.Edit; begin Application.CreateForm(TCrpeDSAboutDlg, CrpeDSAboutDlg); CrpeDSAboutDlg.ShowModal; end; { TDSAboutDlgProperty } {******************************************************************************} { TCrReportNameProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrReportNameProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrReportNameProperty.Edit; var dlgOpen : TOpenDialog; begin dlgOpen := TOpenDialog.Create(Application); dlgOpen.FileName := GetValue; dlgOpen.Title := 'Choose a Crystal Report...'; dlgOpen.Filter := 'Report Files (*.rpt) | *.rpt'; dlgOpen.DefaultExt := 'rpt'; dlgOpen.Options := dlgOpen.Options + [ofPathMustExist, ofFileMustExist]; try if dlgOpen.Execute then SetValue(dlgOpen.FileName); finally dlgOpen.Free; end; end; { Edit } {******************************************************************************} { TCrExportAppNameProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrExportAppNameProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrExportAppNameProperty.Edit; var dlgOpen : TOpenDialog; begin dlgOpen := TOpenDialog.Create(Application); dlgOpen.FileName := GetValue; dlgOpen.Title := 'Choose Export Application...'; dlgOpen.Filter := 'Application Files (*.exe) | *.exe'; dlgOpen.DefaultExt := 'exe'; dlgOpen.Options := dlgOpen.Options + [ofPathMustExist, ofFileMustExist]; try if dlgOpen.Execute then SetValue(dlgOpen.FileName); finally dlgOpen.Free; end; end; { Edit } {******************************************************************************} { TCrExportFileNameProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrExportFileNameProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrExportFileNameProperty.Edit; const FileExtensions : array [0..22] of string = ('*.rec', '*.tsv', '*.txt', '*.dif', '*.csv', '*.chr', '*.ttx', '*.rpt', '*.wk1', '*.wk3', '*.wks', '*.rtf', '*.doc', '*.xls', '*.htm', '*.htm', '*.htm', '*.htm', '*.*', '*.txt', '*.txt', '*.pdf', '*.xml'); FileTypes : array [0..22] of string = ('Record style', 'Tab-separated', 'Text', 'Data Interchange Format', 'Comma-separated', 'Character-separated', 'Tab-separated', 'Crystal Report', 'Lotus 1-2-3', 'Lotus 1-2-3', 'Lotus 1-2-3', 'Rich Text Format', 'Word for Windows', 'Excel', 'HTML 3.0 (Draft Standard)', 'HTML 3.2 (Extended)', 'HTML 3.2 (Standard)', 'HTML 4 (dHTML)', 'Not applicable to ODBC', 'Paginated Text', 'Report Definition', 'Adobe Acrobat', 'Extensible Markup Language'); var Crx : TCrpeExportOptions; dlgSave : TSaveDialog; ext : string; begin dlgSave := TSaveDialog.Create(Application); dlgSave.Title := 'Set Export FileName'; dlgSave.FileName := GetValue; ext := 'Text (*.txt) | *.txt|All Files (*.*) | *.*'; if TPersistent(GetComponent(0)) is TCrpeExportOptions then begin Crx := TCrpeExportOptions(GetComponent(0)); ext := FileExtensions[Ord(Crx.FileType)]; ext := FileTypes[Ord(Crx.FileType)] + ' (' + ext + ')|' + ext + '|All files (*.*) | *.*'; end; dlgSave.Filter := ext; dlgSave.Options := [ofPathMustExist, ofHideReadOnly, ofNoReadOnlyReturn]; try if dlgSave.Execute then SetValue(dlgSave.FileName); finally dlgSave.Free; end; end; { Edit } {******************************************************************************} { TCrpeAreaFormatProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeAreaFormatProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeAreaFormatProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bAreaFormat then begin Application.CreateForm(TCrpeAreaFormatDlg, CrpeAreaFormatDlg); CrpeAreaFormatDlg.Cr := TCrpe(GetComponent(0)); end; CrpeAreaFormatDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeBoxesProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeBoxesProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeBoxesProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bBoxes then begin Application.CreateForm(TCrpeBoxesDlg, CrpeBoxesDlg); CrpeBoxesDlg.Cr := TCrpe(GetComponent(0)); end; CrpeBoxesDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeConnectProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeConnectProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeConnectProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bConnect then begin Application.CreateForm(TCrpeConnectDlg, CrpeConnectDlg); CrpeConnectDlg.Cr := TCrpe(GetComponent(0)); end; CrpeConnectDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeCrossTabsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeCrossTabsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeCrossTabsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bCrossTabs then begin Application.CreateForm(TCrpeCrossTabsDlg, CrpeCrossTabsDlg); CrpeCrossTabsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeCrossTabsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeCrossTabSummariesProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeCrossTabSummariesProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeCrossTabSummariesProperty.Edit; begin if TPersistent(GetComponent(0)) is TCrpeCrossTabSummaries then begin if not BCrossTabSummaries then begin Application.CreateForm(TCrpeCrossTabSummariesDlg, CrpeCrossTabSummariesDlg); CrpeCrossTabSummariesDlg.Crs := TCrpeCrossTabSummaries(GetComponent(0)); end; CrpeCrossTabSummariesDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeDatabaseFieldsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeDatabaseFieldsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeDatabaseFieldsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bDatabaseFields then begin Application.CreateForm(TCrpeDatabaseFieldsDlg, CrpeDatabaseFieldsDlg); CrpeDatabaseFieldsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeDatabaseFieldsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeDesignControlsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeDesignControlsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paMultiSelect, paReadOnly]; end; {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeDesignControlsProperty.Edit; var Cr : TCrpe; OnOff : boolean; begin if GetComponent(0) is TCrpe then begin Cr := TCrpe(GetComponent(0)); if not bDesignControls then begin CrpeDesignControlsDlg := TCrpeDesignControlsDlg.Create(Application); CrpeDesignControlsDlg.Cr := Cr; {Enable/Disable buttons} OnOff := Trim(Cr.ReportName) <> ''; CrpeDesignControlsDlg.SetButtonState(1,OnOff); OnOff := (Cr.ReportWindowHandle > 0); CrpeDesignControlsDlg.SetButtonState(2,OnOff); CrpeDesignControlsDlg.SetButtonState(3,(not Cr.PrintEnded)); CrpeDesignControlsDlg.Show; end else CrpeDesignControlsDlg.SetFocus; end; end; {******************************************************************************} { TCrpeExportExcelProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeExportExcelProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeExportExcelProperty.Edit; var xExport : TCrpeExportOptions; begin if TPersistent(GetComponent(0)) is TCrpeExportOptions then begin Application.CreateForm(TCrpeExcelDlg, CrpeExcelDlg); xExport := TCrpeExportOptions(GetComponent(0)); CrpeExcelDlg.Cr := xExport.Cr; CrpeExcelDlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeExportOptionsHTMLProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeExportHTMLProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeExportHTMLProperty.Edit; var xExport : TCrpeExportOptions; begin if TPersistent(GetComponent(0)) is TCrpeExportOptions then begin Application.CreateForm(TCrpeHTML4Dlg, CrpeHTML4Dlg); xExport := TCrpeExportOptions(GetComponent(0)); CrpeHTML4Dlg.Cr := xExport.Cr; CrpeHTML4Dlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeExportOptionsRTFProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeExportRTFProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeExportRTFProperty.Edit; var xExport : TCrpeExportOptions; begin if TPersistent(GetComponent(0)) is TCrpeExportOptions then begin Application.CreateForm(TCrpeRichTextFormatDlg, CrpeRichTextFormatDlg); xExport := TCrpeExportOptions(GetComponent(0)); CrpeRichTextFormatDlg.Cr := xExport.Cr; CrpeRichTextFormatDlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeExportOptionsPDFProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeExportPDFProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeExportPDFProperty.Edit; var xExport : TCrpeExportOptions; begin if TPersistent(GetComponent(0)) is TCrpeExportOptions then begin Application.CreateForm(TCrpeAdobeAcrobatPDFDlg, CrpeAdobeAcrobatPDFDlg); xExport := TCrpeExportOptions(GetComponent(0)); CrpeAdobeAcrobatPDFDlg.Cr := xExport.Cr; CrpeAdobeAcrobatPDFDlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeExportOptionsXMLProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeExportXMLProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeExportXMLProperty.Edit; var xExport : TCrpeExportOptions; begin if TPersistent(GetComponent(0)) is TCrpeExportOptions then begin Application.CreateForm(TCrpeXML1Dlg, CrpeXML1Dlg); xExport := TCrpeExportOptions(GetComponent(0)); CrpeXML1Dlg.Cr := xExport.Cr; CrpeXML1Dlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeExportOptionsODBCProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeExportODBCProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeExportODBCProperty.Edit; var xExport : TCrpeExportOptions; begin if TPersistent(GetComponent(0)) is TCrpeExportOptions then begin Application.CreateForm(TCrpeODBCDlg, CrpeODBCDlg); xExport := TCrpeExportOptions(GetComponent(0)); CrpeODBCDlg.Cr := xExport.Cr; CrpeODBCDlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeExportOptionsProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeExportOptionsProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Member procedure Edit } {------------------------------------------------------------------------------} procedure TCrpeExportOptionsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bExportOptions then begin Application.CreateForm(TCrpeExportOptionsDlg, CrpeExportOptionsDlg); CrpeExportOptionsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeExportOptionsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeFontProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeFontProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeFontProperty.Edit; begin Application.CreateForm(TCrpeFontDlg, CrpeFontDlg); CrpeFontDlg.Crf := TCrpeFont(GetOrdValue); CrpeFontDlg.ShowModal; SetOrdValue(LongInt(CrpeFontDlg.Crf)); end; { Edit } {******************************************************************************} { TCrpeFormatProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeFormatProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeFormatProperty.Edit; var xCr : TPersistent; begin xCr := GetComponent(0); if (xCr is TCrpeObjectItemA) then begin Application.CreateForm(TCrpeFormatDlg, CrpeFormatDlg); CrpeFormatDlg.Format := TCrpeObjectItemA(xCr).Format; CrpeFormatDlg.ShowModal; end; if (xCr is TCrpeObjectItemB) then begin Application.CreateForm(TCrpeFormatDlg, CrpeFormatDlg); CrpeFormatDlg.Format := TCrpeObjectItemB(xCr).Format; CrpeFormatDlg.ShowModal; end; if (xCr is TCrpeFieldObjectItem) then begin Application.CreateForm(TCrpeFormatDlg, CrpeFormatDlg); CrpeFormatDlg.Format := TCrpeFieldObjectItem(xCr).Format; CrpeFormatDlg.ShowModal; end; if (xCr is TCrpeEmbeddedFieldsItem) then begin Application.CreateForm(TCrpeFormatDlg, CrpeFormatDlg); CrpeFormatDlg.Format := TCrpeEmbeddedFieldsItem(xCr).Format; CrpeFormatDlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeBorderProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeBorderProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeBorderProperty.Edit; var Cr : TPersistent; begin Cr := GetComponent(0); if Cr is TCrpeObjectItem then begin Application.CreateForm(TCrpeBorderDlg, CrpeBorderDlg); CrpeBorderDlg.Border := TCrpeObjectItem(Cr).Border; CrpeBorderDlg.ShowModal; end; if Cr is TCrpeEmbeddedFieldsItem then begin Application.CreateForm(TCrpeBorderDlg, CrpeBorderDlg); CrpeBorderDlg.Border := TCrpeEmbeddedFieldsItem(Cr).Border; CrpeBorderDlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeHiliteConditionsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeHiliteConditionsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsProperty.Edit; var Cr : TPersistent; begin Cr := GetComponent(0); if Cr is TCrpeFieldObjectItem then begin Application.CreateForm(TCrpeHiliteConditionsDlg, CrpeHiliteConditionsDlg); CrpeHiliteConditionsDlg.Crh := TCrpeFieldObjectItem(Cr).HiliteConditions; CrpeHiliteConditionsDlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeFormulasProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeFormulasProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeFormulasProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bFormulas then begin Application.CreateForm(TCrpeFormulasDlg, CrpeFormulasDlg); CrpeFormulasDlg.Cr := TCrpe(GetComponent(0)); end; CrpeFormulasDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeGroupNameFieldsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeGroupNameFieldsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeGroupNameFieldsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bGroupNameFields then begin Application.CreateForm(TCrpeGroupNameFieldsDlg, CrpeGroupNameFieldsDlg); CrpeGroupNameFieldsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeGroupNameFieldsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeGroupsProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeGroupsProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Member procedure Edit } {------------------------------------------------------------------------------} procedure TCrpeGroupsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bGroups then begin Application.CreateForm(TCrpeGroupsDlg, CrpeGroupsDlg); CrpeGroupsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeGroupsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeGraphsProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeGraphsProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Member procedure Edit } {------------------------------------------------------------------------------} procedure TCrpeGraphsProperty.Edit; var Cr : TPersistent; begin Cr := GetComponent(0); if Cr is TCrpe then begin if not TCrpe(Cr).OpenEngine then Exit; if not bGraphs then begin Application.CreateForm(TCrpeGraphsDlg, CrpeGraphsDlg); CrpeGraphsDlg.Cr := TCrpe(Cr); end; CrpeGraphsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeGroupSelectionProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeGroupSelectionProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeGroupSelectionProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bGroupSelection then begin Application.CreateForm(TCrpeGroupSelectionDlg, CrpeGroupSelectionDlg); CrpeGroupSelectionDlg.Cr := TCrpe(GetComponent(0)); end; CrpeGroupSelectionDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeGroupSortFieldsProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeGroupSortFieldsProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeGroupSortFieldsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bGroupSortFields then begin Application.CreateForm(TCrpeGroupSortFieldsDlg, CrpeGroupSortFieldsDlg); CrpeGroupSortFieldsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeGroupSortFieldsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeLinesProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeLinesProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeLinesProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bLines then begin Application.CreateForm(TCrpeLinesDlg, CrpeLinesDlg); CrpeLinesDlg.Cr := TCrpe(GetComponent(0)); end; CrpeLinesDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeLogOnInfoProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeLogOnInfoProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bLogOnInfo then begin Application.CreateForm(TCrpeLogOnInfoDlg, CrpeLogOnInfoDlg); CrpeLogOnInfoDlg.Cr := TCrpe(GetComponent(0)); end; CrpeLogOnInfoDlg.ShowModal; end; end; { Edit } {******************************************************************************} { TCrpeLogOnServerProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeLogOnServerProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeLogOnServerProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bLogOnServer then begin Application.CreateForm(TCrpeLogOnServerDlg, CrpeLogOnServerDlg); CrpeLogOnServerDlg.Cr := TCrpe(GetComponent(0)); end; CrpeLogOnServerDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeMapsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeMapsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeMapsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bMaps then begin Application.CreateForm(TCrpeMapsDlg, CrpeMapsDlg); CrpeMapsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeMapsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeMarginsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeMarginsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeMarginsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bMargins then begin Application.CreateForm(TCrpeMarginsDlg, CrpeMarginsDlg); CrpeMarginsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeMarginsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeOLAPCubesProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeOLAPCubesProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeOLAPCubesProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bOLAPCubes then begin Application.CreateForm(TCrpeOLAPCubesDlg, CrpeOLAPCubesDlg); CrpeOLAPCubesDlg.Cr := TCrpe(GetComponent(0)); end; CrpeOLAPCubesDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeOleObjectsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeOleObjectsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bOleObjects then begin Application.CreateForm(TCrpeOleObjectsDlg, CrpeOleObjectsDlg); CrpeOleObjectsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeOleObjectsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeParamFieldsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeParamFieldsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeParamFieldsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bParamFields then begin Application.CreateForm(TCrpeParamFieldsDlg, CrpeParamFieldsDlg); CrpeParamFieldsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeParamFieldsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpePicturesProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpePicturesProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpePicturesProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bPictures then begin Application.CreateForm(TCrpePicturesDlg, CrpePicturesDlg); CrpePicturesDlg.Cr := TCrpe(GetComponent(0)); end; CrpePicturesDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpePrintDateProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpePrintDateProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpePrintDateProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bPrintDate then begin Application.CreateForm(TCrpePrintDateDlg, CrpePrintDateDlg); CrpePrintDateDlg.Cr := TCrpe(GetComponent(0)); end; CrpePrintDateDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpePrinterProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpePrinterProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpePrinterProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bPrinter then begin Application.CreateForm(TCrpePrinterDlg, CrpePrinterDlg); CrpePrinterDlg.Cr := TCrpe(GetComponent(0)); end; CrpePrinterDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpePrintOptionsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpePrintOptionsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpePrintOptionsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bPrintOptions then begin Application.CreateForm(TCrpePrintOptionsDlg, CrpePrintOptionsDlg); CrpePrintOptionsDlg.Cr := TCrpe(GetComponent(0)); end; CrpePrintOptionsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeRunningTotalsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeRunningTotalsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeRunningTotalsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bRunningTotals then begin Application.CreateForm(TCrpeRunningTotalsDlg, CrpeRunningTotalsDlg); CrpeRunningTotalsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeRunningTotalsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSessionInfoProperty Definition } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSessionInfoProperty.GetAttributes : TPropertyAttributes; begin Result := [paSubProperties, paDialog, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSessionInfo then begin Application.CreateForm(TCrpeSessionInfoDlg, CrpeSessionInfoDlg); CrpeSessionInfoDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSessionInfoDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSQLProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSQLProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSQLProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSQLQuery then begin Application.CreateForm(TCrpeSQLQueryDlg, CrpeSQLQueryDlg); CrpeSQLQueryDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSQLQueryDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSQLExpressionsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSQLExpressionsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSQLExpressionsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSQLExpressions then begin Application.CreateForm(TCrpeSQLExpressionsDlg, CrpeSQLExpressionsDlg); CrpeSQLExpressionsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSQLExpressionsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSummaryFieldsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSummaryFieldsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSummaryFields then begin Application.CreateForm(TCrpeSummaryFieldsDlg, CrpeSummaryFieldsDlg); CrpeSummaryFieldsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSummaryFieldsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeReportOptionsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeReportOptionsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeReportOptionsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bReportOptions then begin Application.CreateForm(TCrpeReportOptionsDlg, CrpeReportOptionsDlg); CrpeReportOptionsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeReportOptionsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSectionFormatProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSectionFormatProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSectionFormatProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSectionFormat then begin Application.CreateForm(TCrpeSectionFormatDlg, CrpeSectionFormatDlg); CrpeSectionFormatDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSectionFormatDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSectionFontProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSectionFontProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSectionFontProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSectionFont then begin Application.CreateForm(TCrpeSectionFontDlg, CrpeSectionFontDlg); CrpeSectionFontDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSectionFontDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSectionSizeProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSectionSizeProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSectionSize then begin Application.CreateForm(TCrpeSectionSizeDlg, CrpeSectionSizeDlg); CrpeSectionSizeDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSectionSizeDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSelectionProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSelectionProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSelectionProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSelection then begin Application.CreateForm(TCrpeSelectionDlg, CrpeSelectionDlg); CrpeSelectionDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSelectionDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSortFieldsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSortFieldsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSortFieldsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSortFields then begin Application.CreateForm(TCrpeSortFieldsDlg, CrpeSortFieldsDlg); CrpeSortFieldsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSortFieldsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSpecialFieldsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSpecialFieldsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSpecialFieldsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSpecialFields then begin Application.CreateForm(TCrpeSpecialFieldsDlg, CrpeSpecialFieldsDlg); CrpeSpecialFieldsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSpecialFieldsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSubreportsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSubreportsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSubreportsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSubreports then begin Application.CreateForm(TCrpeSubreportsDlg, CrpeSubreportsDlg); CrpeSubreportsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSubreportsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeSummaryInfoProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeSummaryInfoProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeSummaryInfoProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bSummaryInfo then begin Application.CreateForm(TCrpeSummaryInfoDlg, CrpeSummaryInfoDlg); CrpeSummaryInfoDlg.Cr := TCrpe(GetComponent(0)); end; CrpeSummaryInfoDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeTablesProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeTablesProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeTablesProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bTables then begin Application.CreateForm(TCrpeTablesDlg, CrpeTablesDlg); CrpeTablesDlg.Cr := TCrpe(GetComponent(0)); end; CrpeTablesDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeTextObjectsProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeTextObjectsProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeTextObjectsProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bTextObjects then begin Application.CreateForm(TCrpeTextObjectsDlg, CrpeTextObjectsDlg); CrpeTextObjectsDlg.Cr := TCrpe(GetComponent(0)); end; CrpeTextObjectsDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeVersionProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeVersionProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeVersionProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bVersion then begin Application.CreateForm(TCrpeVersionDlg, CrpeVersionDlg); CrpeVersionDlg.Cr := TCrpe(GetComponent(0)); end; CrpeVersionDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeWindowButtonBarProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeWindowButtonBarProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeWindowButtonBarProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bWindowButtonBar then begin Application.CreateForm(TCrpeWindowButtonBarDlg, CrpeWindowButtonBarDlg); CrpeWindowButtonBarDlg.Cr := TCrpe(GetComponent(0)); end; CrpeWindowButtonBarDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeWindowCursorProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeWindowCursorProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeWindowCursorProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bWindowCursor then begin Application.CreateForm(TCrpeWindowCursorDlg, CrpeWindowCursorDlg); CrpeWindowCursorDlg.Cr := TCrpe(GetComponent(0)); end; CrpeWindowCursorDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeWindowSizeProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeWindowSizeProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bWindowSize then begin Application.CreateForm(TCrpeWindowSizeDlg, CrpeWindowSizeDlg); CrpeWindowSizeDlg.Cr := TCrpe(GetComponent(0)); end; CrpeWindowSizeDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeWindowStyleProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeWindowStyleProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeWindowStyleProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bWindowStyle then begin Application.CreateForm(TCrpeWindowStyleDlg, CrpeWindowStyleDlg); CrpeWindowStyleDlg.Cr := TCrpe(GetComponent(0)); end; CrpeWindowStyleDlg.Show; end; end; { Edit } {******************************************************************************} { TCrpeWindowZoomProperty } {******************************************************************************} {------------------------------------------------------------------------------} { GetAttributes } {------------------------------------------------------------------------------} function TCrpeWindowZoomProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paSubProperties, paReadOnly, paMultiSelect]; end; { GetAttributes } {------------------------------------------------------------------------------} { Edit } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomProperty.Edit; begin if GetComponent(0) is TCrpe then begin if not bWindowZoom then begin Application.CreateForm(TCrpeWindowZoomDlg, CrpeWindowZoomDlg); CrpeWindowZoomDlg.Cr := TCrpe(GetComponent(0)); end; CrpeWindowZoomDlg.Show; end; end; { Edit } {******************************************************************************} {*********** Custom Property Editor Fields ************************************} {******************************************************************************} { TCrLookupStringProperty } function TCrLookupStringProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TCrLookupStringProperty.GetValues(Proc: TGetStrProc); var i : integer; Cx : TPersistent; begin Cx := GetComponent(0); if Cx is TCrpeAreaFormat then begin for i := 0 to (TCrpeAreaFormat(Cx).Count-1) do Proc(TCrpeAreaFormat(Cx)[i].Area); end; if Cx is TCrpeSubreports then begin for i := 0 to (TCrpeSubreports(Cx).Count-1) do Proc(TCrpeSubreports(Cx)[i].Name); end; if Cx is TCrpeFormulas then begin for i := 0 to (TCrpeFormulas(Cx).Count-1) do Proc(TCrpeFormulas(Cx)[i].Name); end; if Cx is TCrpeRunningTotals then begin for i := 0 to (TCrpeRunningTotals(Cx).Count-1) do Proc(TCrpeRunningTotals(Cx)[i].Name); end; if Cx is TCrpeSectionFont then begin for i := 0 to (TCrpeSectionFont(Cx).Count-1) do Proc(TCrpeSectionFont(Cx)[i].Section); end; if Cx is TCrpeSectionFormat then begin for i := 0 to (TCrpeSectionFormat(Cx).Count-1) do Proc(TCrpeSectionFormat(Cx)[i].Section); end; if Cx is TCrpeSectionSize then begin for i := 0 to (TCrpeSectionSize(Cx).Count-1) do Proc(TCrpeSectionSize(Cx)[i].Section); end; if Cx is TCrpeSQLExpressions then begin for i := 0 to (TCrpeSQLExpressions(Cx).Count-1) do Proc(TCrpeSQLExpressions(Cx)[i].Name); end; end; { TCrLookupNumberProperty } function TCrLookupNumberProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TCrLookupNumberProperty.GetValues(Proc: TGetStrProc); var i : integer; Cx : TPersistent; begin Cx := GetComponent(0); if Cx is TCrpeContainer then begin for i := 0 to (TCrpeContainer(Cx).Count-1) do Proc(IntToStr(i)); end; end; { TCrWinControlProperty } procedure TCrWinControlProperty.GetValues(Proc: TGetStrProc); begin {Add Form name to the list} Proc(Designer.Root.Name); {Add other WinControls} inherited GetValues(Proc); end; {******************************************************************************} { Registration of Component and Property Editors } {******************************************************************************} procedure Register; begin {Register Component} RegisterComponents('Data Access', [TCrpe]); RegisterComponents('Data Access', [TCrpeDS]); {Register Property Editors} RegisterPropertyEditor(TypeInfo(TCrLookupString), TCrpeAreaFormat, 'Area', TCrLookupStringProperty); RegisterPropertyEditor(TypeInfo(TCrLookupString), TCrpeSubreports, 'Name', TCrLookupStringProperty); RegisterPropertyEditor(TypeInfo(TCrLookupString), TCrpeFormulas, 'Name', TCrLookupStringProperty); RegisterPropertyEditor(TypeInfo(TCrLookupString), TCrpeRunningTotals, 'Name', TCrLookupStringProperty); RegisterPropertyEditor(TypeInfo(TCrLookupString), TCrpeSectionFont, 'Section', TCrLookupStringProperty); RegisterPropertyEditor(TypeInfo(TCrLookupString), TCrpeSectionFormat, 'Section', TCrLookupStringProperty); RegisterPropertyEditor(TypeInfo(TCrLookupString), TCrpeSectionSize, 'Section', TCrLookupStringProperty); RegisterPropertyEditor(TypeInfo(TCrLookupString), TCrpeSQLExpressions, 'Name', TCrLookupStringProperty); RegisterPropertyEditor(TypeInfo(TCrLookupNumber), TCrpeContainer, 'Number', TCrLookupNumberProperty); RegisterPropertyEditor(TypeInfo(TCrLookupNumber), TCrpeLogOnInfo, 'Table', TCrLookupNumberProperty); RegisterPropertyEditor(TypeInfo(TCrLookupNumber), TCrpeSessionInfo, 'Table', TCrLookupNumberProperty); RegisterPropertyEditor(TypeInfo(TCrWinControl), TCrpe, '', TCrWinControlProperty); {SubClass Property Editors} RegisterPropertyEditor(TypeInfo(TCrpeAreaFormat), TCrpe, 'AreaFormat', TCrpeAreaFormatProperty); RegisterPropertyEditor(TypeInfo(TCrpeBoxes), TCrpe, 'Boxes', TCrpeBoxesProperty); RegisterPropertyEditor(TypeInfo(TCrpeConnect), TCrpe, 'Connect', TCrpeConnectProperty); RegisterPropertyEditor(TypeInfo(TCrpeCrossTabs), TCrpe, 'CrossTabs', TCrpeCrossTabsProperty); RegisterPropertyEditor(TypeInfo(TCrpeCrossTabSummaries), TCrpeCrossTabs, 'Summaries', TCrpeCrossTabSummariesProperty); RegisterPropertyEditor(TypeInfo(TCrpeDatabaseFields), TCrpe, 'DatabaseFields', TCrpeDatabaseFieldsProperty); RegisterPropertyEditor(TypeInfo(TCrpeExportOptions), TCrpe, 'ExportOptions', TCrpeExportOptionsProperty); RegisterPropertyEditor(TypeInfo(TCrpeExportExcel), TCrpeExportOptions, 'Excel', TCrpeExportExcelProperty); RegisterPropertyEditor(TypeInfo(TCrpeExportHTML), TCrpeExportOptions, 'HTML', TCrpeExportHTMLProperty); RegisterPropertyEditor(TypeInfo(TCrpeExportRTF), TCrpeExportOptions, 'RTF', TCrpeExportRTFProperty); RegisterPropertyEditor(TypeInfo(TCrpeExportPDF), TCrpeExportOptions, 'PDF', TCrpeExportPDFProperty); RegisterPropertyEditor(TypeInfo(TCrpeExportXML), TCrpeExportOptions, 'XML', TCrpeExportXMLProperty); RegisterPropertyEditor(TypeInfo(TCrpeExportODBC), TCrpeExportOptions, 'ODBC', TCrpeExportODBCProperty); RegisterPropertyEditor(TypeInfo(TCrpePersistent), TCrpePersistent, 'Format', TCrpeFormatProperty); RegisterPropertyEditor(TypeInfo(TCrpeFont), TCrpePersistent, 'Font', TCrpeFontProperty); RegisterPropertyEditor(TypeInfo(TCrpeBorder), TCrpePersistent, 'Border', TCrpeBorderProperty); RegisterPropertyEditor(TypeInfo(TCrpeHiliteConditions), TCrpePersistent, 'HiliteConditions', TCrpeHiliteConditionsProperty); RegisterPropertyEditor(TypeInfo(TCrpeFormulas), TCrpe, 'Formulas', TCrpeFormulasProperty); RegisterPropertyEditor(TypeInfo(TCrpeGraphs), TCrpe, 'Graphs', TCrpeGraphsProperty); RegisterPropertyEditor(TypeInfo(TCrpeGroupNameFields), TCrpe, 'GroupNameFields', TCrpeGroupNameFieldsProperty); RegisterPropertyEditor(TypeInfo(TCrpeGroupSelection), TCrpe, 'GroupSelection', TCrpeGroupSelectionProperty); RegisterPropertyEditor(TypeInfo(TCrpeGroupSortFields), TCrpe, 'GroupSortFields', TCrpeGroupSortFieldsProperty); RegisterPropertyEditor(TypeInfo(TCrpeGroups), TCrpe, 'Groups', TCrpeGroupsProperty); RegisterPropertyEditor(TypeInfo(TCrpeLines), TCrpe, 'Lines', TCrpeLinesProperty); RegisterPropertyEditor(TypeInfo(TCrpeLogOnInfo), TCrpe, 'LogOnInfo', TCrpeLogOnInfoProperty); RegisterPropertyEditor(TypeInfo(TCrpeLogOnServer), TCrpe, 'LogOnServer', TCrpeLogOnServerProperty); RegisterPropertyEditor(TypeInfo(TCrpeMaps), TCrpe, 'Maps', TCrpeMapsProperty); RegisterPropertyEditor(TypeInfo(TCrpeMargins), TCrpe, 'Margins', TCrpeMarginsProperty); RegisterPropertyEditor(TypeInfo(TCrpeOLAPCubes), TCrpe, 'OLAPCubes', TCrpeOLAPCubesProperty); RegisterPropertyEditor(TypeInfo(TCrpeOleObjects), TCrpe, 'OleObjects', TCrpeOleObjectsProperty); RegisterPropertyEditor(TypeInfo(TCrpeParamFields), TCrpe, 'ParamFields', TCrpeParamFieldsProperty); RegisterPropertyEditor(TypeInfo(TCrpePictures), TCrpe, 'Pictures', TCrpePicturesProperty); RegisterPropertyEditor(TypeInfo(TCrpePrintDate), TCrpe, 'PrintDate', TCrpePrintDateProperty); RegisterPropertyEditor(TypeInfo(TCrpePrinter), TCrpe, 'Printer', TCrpePrinterProperty); RegisterPropertyEditor(TypeInfo(TCrpePrintOptions), TCrpe, 'PrintOptions', TCrpePrintOptionsProperty); RegisterPropertyEditor(TypeInfo(TCrpeRunningTotals), TCrpe, 'RunningTotals', TCrpeRunningTotalsProperty); RegisterPropertyEditor(TypeInfo(TCrpeReportOptions), TCrpe, 'ReportOptions', TCrpeReportOptionsProperty); RegisterPropertyEditor(TypeInfo(TCrpeSectionFormat), TCrpe, 'SectionFormat', TCrpeSectionFormatProperty); RegisterPropertyEditor(TypeInfo(TCrpeSectionFont), TCrpe, 'SectionFont', TCrpeSectionFontProperty); RegisterPropertyEditor(TypeInfo(TCrpeSelection), TCrpe, 'Selection', TCrpeSelectionProperty); RegisterPropertyEditor(TypeInfo(TCrpeSectionSize), TCrpe, 'SectionSize', TCrpeSectionSizeProperty); RegisterPropertyEditor(TypeInfo(TCrpeSessionInfo), TCrpe, 'SessionInfo', TCrpeSessionInfoProperty); RegisterPropertyEditor(TypeInfo(TCrpeSortFields), TCrpe, 'SortFields', TCrpeSortFieldsProperty); RegisterPropertyEditor(TypeInfo(TCrpeSpecialFields), TCrpe, 'SpecialFields', TCrpeSpecialFieldsProperty); RegisterPropertyEditor(TypeInfo(TCrpeSQL), TCrpe, 'SQL', TCrpeSQLProperty); RegisterPropertyEditor(TypeInfo(TCrpeSQLExpressions), TCrpe, 'SQLExpressions', TCrpeSQLExpressionsProperty); RegisterPropertyEditor(TypeInfo(TCrpeSubreports), TCrpe, 'Subreports', TCrpeSubreportsProperty); RegisterPropertyEditor(TypeInfo(TCrpeSummaryFields), TCrpe, 'SummaryFields', TCrpeSummaryFieldsProperty); RegisterPropertyEditor(TypeInfo(TCrpeSummaryInfo), TCrpe, 'SummaryInfo', TCrpeSummaryInfoProperty); RegisterPropertyEditor(TypeInfo(TCrpeTables), TCrpe, 'Tables', TCrpeTablesProperty); RegisterPropertyEditor(TypeInfo(TCrpeTextObjects), TCrpe, 'TextObjects', TCrpeTextObjectsProperty); RegisterPropertyEditor(TypeInfo(TCrpeVersion), TCrpe, 'Version', TCrpeVersionProperty); RegisterPropertyEditor(TypeInfo(TCrpeWindowButtonBar), TCrpe, 'WindowButtonBar', TCrpeWindowButtonBarProperty); RegisterPropertyEditor(TypeInfo(TCrpeWindowCursor), TCrpe, 'WindowCursor', TCrpeWindowCursorProperty); RegisterPropertyEditor(TypeInfo(TCrpeWindowStyle), TCrpe, 'WindowStyle', TCrpeWindowStyleProperty); RegisterPropertyEditor(TypeInfo(TCrpeWindowSize), TCrpe, 'WindowSize', TCrpeWindowSizeProperty); RegisterPropertyEditor(TypeInfo(TCrpeWindowZoom), TCrpe, 'WindowZoom', TCrpeWindowZoomProperty); {Open Dialog properties} RegisterPropertyEditor(TypeInfo(TCrAboutBox), TCrpe, 'About', TCrAboutBoxProperty); RegisterPropertyEditor(TypeInfo(TCrDesignControls), TCrpe, 'DesignControls', TCrpeDesignControlsProperty); RegisterPropertyEditor(TypeInfo(TCrExportAppName), TCrpeExportOptions, 'AppName', TCrExportAppNameProperty); RegisterPropertyEditor(TypeInfo(TCrExportFileName), TCrpeExportOptions, 'FileName', TCrExportFileNameProperty); RegisterPropertyEditor(TypeInfo(TCrReportName), TCrpe, 'ReportName', TCrReportNameProperty); RegisterPropertyEditor(TypeInfo(TCrDSAbout), TCrpeDS, 'About', TCrpeDSAboutBoxProperty); {Component Editor for Right-click menu} RegisterComponentEditor(TCrpe, TCrpeEditor); RegisterComponentEditor(TCrpeDS, TCrpeDSEditor); end; end.
//------------------------------------------------------------------------------ //MobAI UNIT //------------------------------------------------------------------------------ // What it does- // Basic AI for Mob. // // Changes - // [2008/12/22] Aeomin - Created. // //------------------------------------------------------------------------------ unit MobAI; interface uses Types, Mob, AI, GameObject ; type TMobAIStatus = (msIdle, msWandering, msChasing, msAttacking); TMobAI = class(TAI) private Mob : TMob; fAIStatus : TMobAIStatus; protected procedure SetAIStatus(const AValue : TMobAIStatus); public property AIStatus : TMobAIStatus read fAIStatus write SetAIStatus; procedure Initiate;override; procedure Probe;override; procedure FoundObject(const AnObj:TGameObject); override; procedure ObjectNear(const AnObj:TGameObject); override; procedure RandomWalk; procedure WalkTo(const APoint : TPoint); function GetIdleTicket:Word; procedure FinishWalk;override; constructor Create(const AMob : TMob); end; implementation uses Math, ContNrs, Main, Character, ItemInstance, Event, MovementEvent, MobMovementEvent, WinLinux, GameConstants ; //Initiate AI. procedure TMobAI.Initiate; begin AIStatus := msIdle; Probe; end; procedure TMobAI.Probe; var Beings : TObjectList; idxX,idxY:Integer; ObjectIdx : Integer; AObject : TCharacter; begin Beings := TObjectList.Create(FALSE); try for idxY := Max(0,Mob.Position.Y-MainProc.ZoneServer.Options.CharShowArea) to Min(Mob.Position.Y+MainProc.ZoneServer.Options.CharShowArea, Mob.MapInfo.Size.Y-1) do begin for idxX := Max(0,Mob.Position.X-MainProc.ZoneServer.Options.CharShowArea) to Min(Mob.Position.X+MainProc.ZoneServer.Options.CharShowArea, Mob.MapInfo.Size.X-1) do begin for ObjectIdx := Mob.MapInfo.Cell[idxX][idxY].Beings.Count -1 downto 0 do begin if Mob.MapInfo.Cell[idxX][idxY].Beings.Objects[ObjectIdx] is TCharacter then begin AObject := Mob.MapInfo.Cell[idxX][idxY].Beings.Objects[ObjectIdx] as TCharacter; Beings.Add(AObject); end; end; end; end; if Beings.Count > 0 then begin AObject := Beings.Items[Random(Beings.Count)] as TCharacter; FoundObject(AObject); end; finally Beings.Free; end; end; procedure TMobAI.FoundObject(const AnObj:TGameObject); begin // writeln('I SAW CHIKEN!'); if AnObj is TCharacter then begin {is agressive?} end else if AnObj is TItemInstance then begin {pick 'em?} end; end; procedure TMobAI.ObjectNear(const AnObj:TGameObject); begin // writeln('CHIKEN SAW ME!'); FoundObject(AnObj); end; procedure TMobAI.RandomWalk; var APoint : TPoint; Retry:Byte; Pass : Boolean; MoveEvent : TRootEvent; function RandomPoint:TPoint; begin with MainProc.ZoneServer.Options do begin Result.X := Mob.Position.X + (Random($FFFF) mod (CharShowArea*2) - CharShowArea); Result.Y := Mob.Position.Y + (Random($FFFF) mod (CharShowArea*2) - CharShowArea); end; end; begin Pass := False; for Retry := 1 to 10 do begin APoint := RandomPoint; if Mob.MapInfo.PointInRange(APoint) AND NOT Mob.MapInfo.IsBlocked(APoint) then begin Pass := True; Break; end; end; if Pass then WalkTo(APoint) else begin //Still..heh MoveEvent := TMobMovementEvent.Create( GetTick + GetIdleTicket, Mob ); Mob.EventList.Add(MoveEvent); end; end; procedure TMobAI.WalkTo(const APoint : TPoint); var MoveEvent : TRootEvent; Speed : LongWord; begin if Mob.GetPath(Mob.Position, APoint, Mob.Path) then begin Mob.EventList.DeleteAttackEvents; Mob.EventList.DeleteMovementEvents; Mob.PathIndex := 0; if AIStatus = msIdle then begin //Gotta delay ! MoveEvent := TMobMovementEvent.Create( GetTick + GetIdleTicket, Mob ); end else begin if (Mob.Direction in Diagonals) then begin Speed := Mob.Speed * 3 DIV 2; end else begin Speed := Mob.Speed; end; Mob.MoveTick := GetTick + Speed DIV 2; MoveEvent := TMovementEvent.Create(Mob.MoveTick,Mob); end; Mob.EventList.Add(MoveEvent); end; end; function TMobAI.GetIdleTicket:Word; begin Result := 1000; case fAIStatus of msIdle: Result := (Random($FFFFFF) mod 5000)+1000; // msWandering: ; // msChasing: ; // msAttacking: ; end; end; procedure TMobAI.FinishWalk; begin if AIStatus = msWandering then begin AIStatus := msIdle; end; end; procedure TMobAI.SetAIStatus(const AValue : TMobAIStatus); begin fAIStatus := AValue; case fAIStatus of msIdle: begin // if NOT Boolean(Mob.Race AND MOBRACE_PLANT) then RandomWalk; end; msWandering: ; msChasing: ; msAttacking: ; end; end; constructor TMobAI.Create(const AMob : TMob); begin Mob := AMob; end; end.
program HowToUseGameTimer; uses SwinGame, sgTypes, sysUtils; procedure Main(); var gameTime: Timer; ticks: Integer; toDraw: String; begin OpenGraphicsWindow('Game Timer', 150, 150); gameTime := CreateTimer(); StartTimer(gameTime); repeat ProcessEvents(); ClearScreen(ColorWhite); DrawText('[P]ause', ColorBlack, 0, 0); DrawText('[R]esume', ColorBlack, 0, 10); DrawText('[S]top', ColorBlack, 0, 20); DrawText('[B]egin', ColorBlack, 0, 30); if KeyTyped(PKey) then PauseTimer(gameTime); if KeyTyped(RKey) then ResumeTimer(gameTime); if KeyTyped(SKey) then StopTimer(gameTime); if KeyTyped(BKey) then StartTimer(gameTime); ticks := TimerTicks(gameTime); Str(ticks, toDraw); DrawText(toDraw, ColorRed, 20, 70); RefreshScreen(); until WindowCloseRequested(); ReleaseAllResources(); end; begin Main(); end.
Unit XXXDetectedRequests; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} Interface Uses Windows, IRPMonRequest, IRPMonDll; Type TDriverDetectedRequest = Class (TDriverRequest) Private FDriverObject : Pointer; FDriverName : WideString; Public Constructor Create(Var ARequest:REQUEST_DRIVER_DETECTED); Overload; Function GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; Override; Property DriverObject : Pointer Read FDriverObject; Property DriverName : WideString Read FDriverName; end; TDeviceDetectedRequest = Class (TDriverRequest) Private FDriverObject : Pointer; FDeviceObject : Pointer; FDeviceName : WideString; Public Constructor Create(Var ARequest:REQUEST_DEVICE_DETECTED); Overload; Function GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; Override; Property DriverObject : Pointer Read FDriverObject; Property DeviceObject : Pointer Read FDeviceObject; Property DeviceName : WideString Read FDeviceName; end; Implementation Uses SysUtils; (** TDroverDetectedRequest **) Constructor TDriverDetectedRequest.Create(Var ARequest:REQUEST_DRIVER_DETECTED); Var dn : PWideChar; rawRequest : PREQUEST_DRIVER_DETECTED; begin Inherited Create(ARequest.Header); rawRequest := PREQUEST_DRIVER_DETECTED(Raw); FDriverObject := rawRequest.Header.Driver; dn := PWideChar(PByte(rawRequest) + SizeOf(REQUEST_DRIVER_DETECTED)); SetLength(FDriverName, rawRequest.DriverNameLength Div SizeOf(WideChar)); CopyMemory(PWideChar(FDriverName), dn, rawRequest.DriverNameLength); SetDriverName(FDriverName); end; Function TDriverDetectedRequest.GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; begin Result := True; Case AColumnType Of rlmctDeviceObject, rlmctDeviceName, rlmctResultValue, rlmctIOSBStatusValue, rlmctIOSBStatusConstant, rlmctIOSBInformation, rlmctResultConstant : Result := False; rlmctDriverObject : AResult := Format('0x%p', [FDriverObject]); rlmctDriverName : AResult := FDriverName; Else Result := Inherited GetColumnValue(AColumnType, AResult); end; end; (** TDeviceDetectedRequest **) Constructor TDeviceDetectedRequest.Create(Var ARequest:REQUEST_DEVICE_DETECTED); Var dn : PWideChar; rawRequest : PREQUEST_DEVICE_DETECTED; begin Inherited Create(ARequest.Header); rawRequest := PREQUEST_DEVICE_DETECTED(Raw); FDriverObject := rawRequest.Header.Driver; FDeviceObject := rawRequest.Header.Device; dn := PWideChar(PByte(rawRequest) + SizeOf(REQUEST_DEVICE_DETECTED)); SetLength(FDeviceName, rawRequest.DeviceNameLength Div SizeOf(WideChar)); CopyMemory(PWideChar(FDeviceName), dn, rawRequest.DeviceNameLength); SetDeviceName(FDeviceName); end; Function TDeviceDetectedRequest.GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; begin Result := True; Case AColumnType Of rlmctResultValue, rlmctIOSBStatusValue, rlmctIOSBStatusConstant, rlmctIOSBInformation, rlmctResultConstant : Result := False; rlmctDriverObject : AResult := Format('0x%p', [FDriverObject]); rlmctDeviceObject : AResult := Format('0x%p', [FDeviceObject]); rlmctDeviceName : AResult := FDeviceName; Else Result := Inherited GetColumnValue(AColumnType, AResult); end; end; End.
unit UpFBonusEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, uFControl, uLabeledFControl, uCharControl, uFloatControl, uDateControl, uSpravControl, uBoolControl, uFormControl, uInvisControl, IBase, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase; type TfmBonusEdit = class(TForm) OkButton: TBitBtn; CancelButton: TBitBtn; Percent: TqFFloatControl; IdRaise: TqFSpravControl; DateBeg: TqFDateControl; DateEnd: TqFDateControl; All_Periods: TqFBoolControl; FormControl: TqFFormControl; Smeta: TqFSpravControl; Kod_Sm_Pps: TqFSpravControl; Summa: TqFFloatControl; Label1: TLabel; Key_Session: TqFInvisControl; ActualDate: TqFInvisControl; DB: TpFIBDatabase; ReadTransaction: TpFIBTransaction; RaiseDefaults: TpFIBDataSet; Id_Order_Item: TqFInvisControl; procedure IdRaiseOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); procedure SmetaOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); procedure OkButtonClick(Sender: TObject); procedure SummaChange(Sender: TObject); procedure PercentChange(Sender: TObject); procedure IdRaiseChange(Sender: TObject); procedure FormControlModifyRecordAfterPrepare(Sender: TObject); procedure All_PeriodsChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Prepare(DBase:TISC_DB_HANDLE;KeySession:Int64;ID_Item:Int64;Actual_Date:Variant); procedure Button1Click(Sender: TObject); private PDBHandle: TISC_DB_HANDLE; public end; var fmBonusEdit: TfmBonusEdit; implementation {$R *.dfm} uses uCommonSp, GlobalSPR, qfTools; procedure TfmBonusEdit.IdRaiseOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); var sp: TSprav; begin // создать справочник sp := GetSprav('ASUP\SpRaise'); if sp <> nil then begin // заполнить входные параметры with sp.Input do begin Append; FieldValues['DBHandle'] := Integer(DB.Handle); // модальный показ FieldValues['ShowStyle'] := 0; // единичная выборка FieldValues['Select'] := 1; FieldValues['Raise_Select_Kind'] := 1; FieldValues['Actual_Date'] := Date; Post; end; sp.Show; if (sp.Output <> nil) and not sp.Output.IsEmpty then begin Value := sp.Output['Id_Raise']; DisplayText := sp.Output['Name']; end; sp.Free; end; end; procedure TfmBonusEdit.SmetaOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); var id: variant; begin id := GlobalSPR.GetSmets(Owner, TISC_DB_Handle(DB.Handle), Date, psmSmet); if (VarArrayDimCount(id) > 0) and (id[0] <> Null) then begin Value := id[0]; DisplayText := IntToStr(id[3]) + '. ' + id[2]; end; end; procedure TfmBonusEdit.OkButtonClick(Sender: TObject); begin FormControl.Ok; end; procedure TfmBonusEdit.SummaChange(Sender: TObject); begin if (not VarIsNull(Summa.Value) and (Summa.Value > 0)) or (Percent.Blocked) then Percent.Required := False else Percent.Required := True; end; procedure TfmBonusEdit.PercentChange(Sender: TObject); begin if (not VarIsNull(Percent.Value) and (Percent.Value > 0)) or (Summa.Blocked) then Summa.Required := False else Summa.Required := True; end; procedure TfmBonusEdit.IdRaiseChange(Sender: TObject); begin RaiseDefaults.Close; RaiseDefaults.ParamByName('Key_Session').AsVariant := Key_Session.Value; RaiseDefaults.ParamByName('ID_ORDER_ITEM').AsVariant := Id_Order_Item.Value; RaiseDefaults.ParamByName('Id_Raise').AsVariant := IdRaise.Value; RaiseDefaults.Open; if RaiseDefaults['ID_CALC_TYPE']=1 then begin Summa.Blocked := False; Percent.Blocked := True; All_Periods.Value := 0; All_Periods.Blocked:= True; Smeta.Blocked := False; Kod_Sm_Pps.Blocked := True; end; if RaiseDefaults['ID_CALC_TYPE']=2 then begin Summa.Blocked := True; Percent.Blocked := False; All_Periods.Value := 1; All_Periods.Blocked:= False; Smeta.Blocked := True; Kod_Sm_Pps.Blocked := True; end; if RaiseDefaults['ID_CALC_TYPE']=3 then begin Summa.Blocked := False; Percent.Blocked := False; Smeta.Blocked := False; Kod_Sm_Pps.Blocked := True; end; if Percent.Blocked then begin Percent.Required := False; Summa.Required := True; end; if Summa.Blocked then begin Percent.Required := True; Summa.Required := False; end; end; procedure TfmBonusEdit.FormControlModifyRecordAfterPrepare( Sender: TObject); begin IdRaise.Blocked := True; end; procedure TfmBonusEdit.All_PeriodsChange(Sender: TObject); begin if All_Periods.Value then begin DateBeg.Visible := False; DateEnd.Visible := False; end else begin DateBeg.Visible := True; DateEnd.Visible := True; end; end; procedure TfmBonusEdit.FormCreate(Sender: TObject); begin DateBeg.Visible := False; DateEnd.Visible := False; end; procedure TfmBonusEdit.Prepare(DBase:TISC_DB_HANDLE;KeySession,ID_Item:Int64;Actual_Date:Variant); begin DB.Handle := DBase; ReadTransaction.StartTransaction; RaiseDefaults.SQLs.SelectSQL.Text := 'SELECT * FROM UP_ORDER_MOVE_RAISE_DEFAULTS(:Key_Session,:Id_order_item,:Id_Raise)'; ActualDate.Value := Actual_Date; Key_Session.Value := KeySession; Id_Order_Item.Value := Id_Item; end; procedure TfmBonusEdit.Button1Click(Sender: TObject); begin ShowMessage('KEY_SESSION = '+VarToStrDef(Key_Session.Value,'NULL')+#13+ 'ID_ORDER_ITEM = '+VarToStrDef(Id_Order_Item.Value,'NULL')+#13+ 'ID_RAISE = '+VarToStrDef(IdRaise.Value,'NULL')+#13+ 'DATE_BEG = '+VarToStrDef(DateBeg.Value,'NULL')+#13+ 'DATE_END = '+VarToStrDef(DateEnd.Value,'NULL')+#13+ 'ALL_PERIODS = '+VarToStrDef(All_Periods.Value,'NULL')); end; initialization RegisterClass(TfmBonusEdit); end.
namespace proholz.xsdparser; type DefaultParserConfig = public class (ParserConfig) method getXsdTypesToCodeGen: Dictionary<String,String>; begin var xsdTypesToCodegen: Dictionary<String,String> := new Dictionary<String,String>(); var lstring: String := 'String'; var xmlGregorianCalendar: String := 'XMLGregorianCalendar'; var duration: String := 'Duration'; var bigInteger: String := 'BigInteger'; var linteger: String := 'Integer'; var shortString: String := 'Short'; var qName: String := 'QName'; var longString: String := 'Long'; var byteString: String := 'Byte'; xsdTypesToCodegen.Add('xsd:anyURI', lstring); xsdTypesToCodegen.Add('xs:anyURI', lstring); xsdTypesToCodegen.Add('xsd:boolean', 'Boolean'); xsdTypesToCodegen.Add('xs:boolean', 'Boolean'); xsdTypesToCodegen.Add('xsd:date', xmlGregorianCalendar); xsdTypesToCodegen.Add('xs:date', xmlGregorianCalendar); xsdTypesToCodegen.Add('xsd:dateTime', xmlGregorianCalendar); xsdTypesToCodegen.Add('xs:dateTime', xmlGregorianCalendar); xsdTypesToCodegen.Add('xsd:time', xmlGregorianCalendar); xsdTypesToCodegen.Add('xs:time', xmlGregorianCalendar); xsdTypesToCodegen.Add('xsd:duration', duration); xsdTypesToCodegen.Add('xs:duration', duration); xsdTypesToCodegen.Add('xsd:dayTimeDuration', duration); xsdTypesToCodegen.Add('xs:dayTimeDuration', duration); xsdTypesToCodegen.Add('xsd:yearMonthDuration', duration); xsdTypesToCodegen.Add('xs:yearMonthDuration', duration); xsdTypesToCodegen.Add('xsd:gDay', xmlGregorianCalendar); xsdTypesToCodegen.Add('xs:gDay', xmlGregorianCalendar); xsdTypesToCodegen.Add('xsd:gMonth', xmlGregorianCalendar); xsdTypesToCodegen.Add('xs:gMonth', xmlGregorianCalendar); xsdTypesToCodegen.Add('xsd:gMonthDay', xmlGregorianCalendar); xsdTypesToCodegen.Add('xs:gMonthDay', xmlGregorianCalendar); xsdTypesToCodegen.Add('xsd:gYear', xmlGregorianCalendar); xsdTypesToCodegen.Add('xs:gYear', xmlGregorianCalendar); xsdTypesToCodegen.Add('xsd:gYearMonth', xmlGregorianCalendar); xsdTypesToCodegen.Add('xs:gYearMonth', xmlGregorianCalendar); xsdTypesToCodegen.Add('xsd:decimal', 'BigDecimal'); xsdTypesToCodegen.Add('xs:decimal', 'BigDecimal'); xsdTypesToCodegen.Add('xsd:integer', bigInteger); xsdTypesToCodegen.Add('xs:integer', bigInteger); xsdTypesToCodegen.Add('xsd:nonPositiveInteger', bigInteger); xsdTypesToCodegen.Add('xs:nonPositiveInteger', bigInteger); xsdTypesToCodegen.Add('xsd:negativeInteger', bigInteger); xsdTypesToCodegen.Add('xs:negativeInteger', bigInteger); xsdTypesToCodegen.Add('xsd:long', longString); xsdTypesToCodegen.Add('xs:long', longString); xsdTypesToCodegen.Add('xsd:int', linteger); xsdTypesToCodegen.Add('xs:int', linteger); xsdTypesToCodegen.Add('xsd:short', shortString); xsdTypesToCodegen.Add('xs:short', shortString); xsdTypesToCodegen.Add('xsd:byte', byteString); xsdTypesToCodegen.Add('xs:byte', byteString); xsdTypesToCodegen.Add('xsd:nonNegativeInteger', bigInteger); xsdTypesToCodegen.Add('xs:nonNegativeInteger', bigInteger); xsdTypesToCodegen.Add('xsd:unsignedLong', bigInteger); xsdTypesToCodegen.Add('xs:unsignedLong', bigInteger); xsdTypesToCodegen.Add('xsd:unsignedInt', longString); xsdTypesToCodegen.Add('xs:unsignedInt', longString); xsdTypesToCodegen.Add('xsd:unsignedShort', linteger); xsdTypesToCodegen.Add('xs:unsignedShort', linteger); xsdTypesToCodegen.Add('xsd:unsignedByte', shortString); xsdTypesToCodegen.Add('xs:unsignedByte', shortString); xsdTypesToCodegen.Add('xsd:positiveInteger', bigInteger); xsdTypesToCodegen.Add('xs:positiveInteger', bigInteger); xsdTypesToCodegen.Add('xsd:double', 'Double'); xsdTypesToCodegen.Add('xs:double', 'Double'); xsdTypesToCodegen.Add('xsd:float', 'Float'); xsdTypesToCodegen.Add('xs:float', 'Float'); xsdTypesToCodegen.Add('xsd:QName', qName); xsdTypesToCodegen.Add('xs:QName', qName); xsdTypesToCodegen.Add('xsd:NOTATION', qName); xsdTypesToCodegen.Add('xs:NOTATION', qName); xsdTypesToCodegen.Add('xsd:string', lstring); xsdTypesToCodegen.Add('xs:string', lstring); xsdTypesToCodegen.Add('xsd:normalizedString', lstring); xsdTypesToCodegen.Add('xs:normalizedString', lstring); xsdTypesToCodegen.Add('xsd:token', lstring); xsdTypesToCodegen.Add('xs:token', lstring); xsdTypesToCodegen.Add('xsd:language', lstring); xsdTypesToCodegen.Add('xs:language', lstring); xsdTypesToCodegen.Add('xsd:NMTOKEN', lstring); xsdTypesToCodegen.Add('xs:NMTOKEN', lstring); xsdTypesToCodegen.Add('xsd:Name', lstring); xsdTypesToCodegen.Add('xs:Name', lstring); xsdTypesToCodegen.Add('xsd:NCName', lstring); xsdTypesToCodegen.Add('xs:NCName', lstring); xsdTypesToCodegen.Add('xsd:ID', lstring); xsdTypesToCodegen.Add('xs:ID', lstring); xsdTypesToCodegen.Add('xsd:IDREF', lstring); xsdTypesToCodegen.Add('xs:IDREF', lstring); xsdTypesToCodegen.Add('xsd:ENTITY', lstring); xsdTypesToCodegen.Add('xs:ENTITY', lstring); xsdTypesToCodegen.Add('xsd:untypedAtomic', lstring); xsdTypesToCodegen.Add('xs:untypedAtomic', lstring); exit xsdTypesToCodegen; end; method getParseMappers: ParseMappersDictionary; begin var parseMappers: ParseMappersDictionary := new ParseMappersDictionary(); parseMappers.Add(XsdAll.XSD_TAG, @XsdAll.parse); parseMappers.Add(XsdAll.XS_TAG, @XsdAll.parse); parseMappers.Add(XsdAttribute.XSD_TAG, @XsdAttribute.parse); parseMappers.Add(XsdAttribute.XS_TAG, @XsdAttribute.parse); parseMappers.Add(XsdAttributeGroup.XSD_TAG, @XsdAttributeGroup.parse); parseMappers.Add(XsdAttributeGroup.XS_TAG, @XsdAttributeGroup.parse); parseMappers.Add(XsdChoice.XSD_TAG, @XsdChoice.parse); parseMappers.Add(XsdChoice.XS_TAG, @XsdChoice.parse); parseMappers.Add(XsdComplexType.XSD_TAG, @XsdComplexType.parse); parseMappers.Add(XsdComplexType.XS_TAG, @XsdComplexType.parse); parseMappers.Add(XsdElement.XSD_TAG, @XsdElement.parse); parseMappers.Add(XsdElement.XS_TAG, @XsdElement.parse); parseMappers.Add(XsdGroup.XSD_TAG, @XsdGroup.parse); parseMappers.Add(XsdGroup.XS_TAG, @XsdGroup.parse); parseMappers.Add(XsdInclude.XSD_TAG, @XsdInclude.parse); parseMappers.Add(XsdInclude.XS_TAG, @XsdInclude.parse); parseMappers.Add(XsdImport.XSD_TAG, @XsdImport.parse); parseMappers.Add(XsdImport.XS_TAG, @XsdImport.parse); parseMappers.Add(XsdSequence.XSD_TAG, @XsdSequence.parse); parseMappers.Add(XsdSequence.XS_TAG, @XsdSequence.parse); parseMappers.Add(XsdSimpleType.XSD_TAG, @XsdSimpleType.parse); parseMappers.Add(XsdSimpleType.XS_TAG, @XsdSimpleType.parse); parseMappers.Add(XsdList.XSD_TAG, @XsdList.parse); parseMappers.Add(XsdList.XS_TAG, @XsdList.parse); parseMappers.Add(XsdRestriction.XSD_TAG, @XsdRestriction.parse); parseMappers.Add(XsdRestriction.XS_TAG, @XsdRestriction.parse); parseMappers.Add(XsdUnion.XSD_TAG, @XsdUnion.parse); parseMappers.Add(XsdUnion.XS_TAG, @XsdUnion.parse); parseMappers.Add(XsdAnnotation.XSD_TAG, @XsdAnnotation.parse); parseMappers.Add(XsdAnnotation.XS_TAG, @XsdAnnotation.parse); parseMappers.Add(XsdAppInfo.XSD_TAG, @XsdAppInfo.parse); parseMappers.Add(XsdAppInfo.XS_TAG, @XsdAppInfo.parse); parseMappers.Add(XsdComplexContent.XSD_TAG, @XsdComplexContent.parse); parseMappers.Add(XsdComplexContent.XS_TAG, @XsdComplexContent.parse); parseMappers.Add(XsdDocumentation.XSD_TAG, @XsdDocumentation.parse); parseMappers.Add(XsdDocumentation.XS_TAG, @XsdDocumentation.parse); parseMappers.Add(XsdExtension.XSD_TAG, @XsdExtension.parse); parseMappers.Add(XsdExtension.XS_TAG, @XsdExtension.parse); parseMappers.Add(XsdSimpleContent.XSD_TAG, @XsdSimpleContent.parse); parseMappers.Add(XsdSimpleContent.XS_TAG, @XsdSimpleContent.parse); parseMappers.Add(XsdEnumeration.XSD_TAG, @XsdEnumeration.parse); parseMappers.Add(XsdEnumeration.XS_TAG, @XsdEnumeration.parse); parseMappers.Add(XsdFractionDigits.XSD_TAG, @XsdFractionDigits.parse); parseMappers.Add(XsdFractionDigits.XS_TAG, @XsdFractionDigits.parse); parseMappers.Add(XsdLength.XSD_TAG, @XsdLength.parse); parseMappers.Add(XsdLength.XS_TAG, @XsdLength.parse); parseMappers.Add(XsdMaxExclusive.XSD_TAG, @XsdMaxExclusive.parse); parseMappers.Add(XsdMaxExclusive.XS_TAG, @XsdMaxExclusive.parse); parseMappers.Add(XsdMaxInclusive.XSD_TAG, @XsdMaxInclusive.parse); parseMappers.Add(XsdMaxInclusive.XS_TAG, @XsdMaxInclusive.parse); parseMappers.Add(XsdMaxLength.XSD_TAG, @XsdMaxLength.parse); parseMappers.Add(XsdMaxLength.XS_TAG, @XsdMaxLength.parse); parseMappers.Add(XsdMinExclusive.XSD_TAG, @XsdMinExclusive.parse); parseMappers.Add(XsdMinExclusive.XS_TAG, @XsdMinExclusive.parse); parseMappers.Add(XsdMinInclusive.XSD_TAG, @XsdMinInclusive.parse); parseMappers.Add(XsdMinInclusive.XS_TAG, @XsdMinInclusive.parse); parseMappers.Add(XsdMinLength.XSD_TAG, @XsdMinLength.parse); parseMappers.Add(XsdMinLength.XS_TAG, @XsdMinLength.parse); parseMappers.Add(XsdPattern.XSD_TAG, @XsdPattern.parse); parseMappers.Add(XsdPattern.XS_TAG, @XsdPattern.parse); parseMappers.Add(XsdTotalDigits.XSD_TAG, @XsdTotalDigits.parse); parseMappers.Add(XsdTotalDigits.XS_TAG, @XsdTotalDigits.parse); parseMappers.Add(XsdWhiteSpace.XSD_TAG, @XsdWhiteSpace.parse); parseMappers.Add(XsdWhiteSpace.XS_TAG, @XsdWhiteSpace.parse); exit parseMappers; end; end; end.
(* Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES Original name: 0036.PAS Description: Base Notation Author: GREG VIGNEAULT Date: 11-21-93 09:24 *) { How about a procedure that will display any integer in any base notation from 2 to 16? The following example displays the values 0 through 15 in binary (base 2), octal (base 8), decimal (base 10) and hexadecimal (base 16) notations ... } (********************************************************************) PROGRAM BaseX; (* compiler: Turbo Pascal v4.0+ *) (* Nov.14.93 Greg Vigneault *) (*------------------------------------------------------------------*) (* Display any INTEGER in any base notation from 2 to 16... *) (* *) (* number base 2 = binary notation (digits 0,1) *) (* number base 8 = octal notation (digits 0..7) *) (* number base 10 = decimal notation (digits 0..9) *) (* number base 16 = hexadecimal notation (digits 0..9,A..F) *) PROCEDURE DisplayInteger (AnyInteger :INTEGER; NumberBase :BYTE); CONST DataSize = 16; (* bit-size of an INTEGER *) VAR Index : INTEGER; Digit : ARRAY [1..DataSize] OF CHAR; BEGIN IF (NumberBase > 1) AND (NumberBase < 17) THEN BEGIN Index := 0; REPEAT INC (Index); Digit [Index] := CHR(AnyInteger MOD NumberBase + ORD('0')); IF (Digit [Index] > '9') THEN INC (Digit [Index],7); AnyInteger := AnyInteger DIV NumberBase; UNTIL (AnyInteger = 0) OR (Index = DataSize); WHILE (Index > 0) DO BEGIN Write (Digit [Index]); DEC (Index); END; {WHILE Index} END; {IF NumberBase} END {DisplayInteger}; (*------------------------------------------------------------------*) (* to test the DisplayInteger procedure... *) VAR Base, Number : INTEGER; BEGIN FOR Base := 2 TO 16 DO CASE Base OF 2,8,10,16 : BEGIN WriteLn; CASE Base OF 2 : Write ('Binary : '); 8 : Write ('Octal : '); 10 : Write ('Decimal: '); 16 : Write ('Hex : '); END; {CASE} FOR Number := 0 TO 15 DO BEGIN DisplayInteger (Number, Base); Write (' '); END; {FOR} END; END; {CASE} WriteLn; END {BaseX}.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [PCP_INSTRUCAO_OP] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit PcpInstrucaoOpController; interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller, VO, ZDataset, PcpInstrucaoOpVO; type TPcpInstrucaoOpController = class(TController) private public class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function ConsultaLista(pFiltro: String): TListaPcpInstrucaoOpVO; class function ConsultaObjeto(pFiltro: String): TPcpInstrucaoOpVO; class procedure Insere(pObjeto: TPcpInstrucaoOpVO); class function Altera(pObjeto: TPcpInstrucaoOpVO): Boolean; class function Exclui(pId: Integer): Boolean; end; implementation uses UDataModule, T2TiORM; var ObjetoLocal: TPcpInstrucaoOpVO; class function TPcpInstrucaoOpController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TPcpInstrucaoOpVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class function TPcpInstrucaoOpController.ConsultaLista(pFiltro: String): TListaPcpInstrucaoOpVO; begin try ObjetoLocal := TPcpInstrucaoOpVO.Create; Result := TListaPcpInstrucaoOpVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TPcpInstrucaoOpController.ConsultaObjeto(pFiltro: String): TPcpInstrucaoOpVO; begin try Result := TPcpInstrucaoOpVO.Create; Result := TPcpInstrucaoOpVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); finally end; end; class procedure TPcpInstrucaoOpController.Insere(pObjeto: TPcpInstrucaoOpVO); var UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TPcpInstrucaoOpController.Altera(pObjeto: TPcpInstrucaoOpVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TPcpInstrucaoOpController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TPcpInstrucaoOpVO; begin try ObjetoLocal := TPcpInstrucaoOpVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal) end; end; begin Result := FDataSet; end; begin FDataSet := pDataSet; end; begin try finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TPcpInstrucaoOpController); finalization Classes.UnRegisterClass(TPcpInstrucaoOpController); end.
unit libenv; interface uses strutils, strings, sysutils, classes, libutils; function term_set_env( name: string; value: string ): boolean; function term_get_env( name: string ): string; procedure term_set_process_output( var lines: TStringList; var output: TStrArray ); implementation var site : string = ''; path : string = ''; user : string = ''; password : string = ''; function term_set_env( name: string; value: string ): boolean; begin term_set_env := false; if name = 'site' then begin site := value; term_set_env := true; end; if name = 'user' then begin user := value; term_set_env := true; end; if name = 'path' then begin path := value; term_set_env := true; end; if name = 'password' then begin password := value; term_set_env := true; end; end; function term_get_env( name: string ): string; begin term_get_env := ''; if name = 'site' then begin term_get_env := site; end else begin if name = 'path' then begin term_get_env := path; end else begin if name = 'user' then begin term_get_env := user; end else begin if name = 'password' then begin term_get_env := password; end; end; end; end; end; procedure term_parse_var( s: string ); var space: integer = 0; name : string; value: string; begin space := pos( ' ', s ); name := copy( s, 1, space - 1 ); value:= copy( s, space + 1, length( s ) - space ); //writeln( 'space: ', space, ' name: "', name, '", value: "', value, '"' ); if name <> '' then term_set_env( name, value ); end; procedure term_set_process_output( var lines: TStringList; var output: TStrArray ); var total_lines : integer = 0; output_lines : integer = 0; i : integer = 0; j : integer = 0; headers : boolean = true; //prev_empty : boolean = false; env_var : string = ''; begin setlength( output, 0 ); //writeln( 'dumping process output...' ); total_lines := lines.count; output_lines:= total_lines; //writeln( 'total lines: ', total_lines ); j := 0; for i:=total_lines - 1 downto 0 do begin //writeln( 'line: ', j, ' len: ', length( lines[i] ), ' => ', lines[i] ); //writeln( j ); if (lines[i] = '' ) and ( j > 0 ) and ( headers = true ) then begin headers := false; output_lines := i; end; j := j + 1; end; if ( headers = false ) and ( output_lines > 0 ) then begin // decrement output lines while they're empty at the end repeat if lines[ output_lines - 1 ] = '' then output_lines -= 1; until ( output_lines = 0 ) or ( lines[ output_lines - 1 ] <> '' ); end; setLength( output, output_lines ); for i := 0 to output_lines - 1 do output[i] := lines[i]; for i := output_lines + 1 to total_lines - 1 do begin //writeln( 'parse_env_line: ', i, ' => ', lines[i] ); if length( lines[i] ) > 0 then begin if copy( lines[i], 1, 9 ) = '$SETENV: ' then begin env_var := copy( lines[i], 10, length( lines[i] ) - 9 ); //writeln( 'env: "', env_var, '"' ); term_parse_var( env_var ); end; end; end; //writeln( 'output lines: ', output_lines ); end; initialization end.
unit ParseTest; interface uses DUnitX.TestFramework, uIntXLibTypes, uIntX; type [TestFixture] TParseTest = class(TObject) public [Test] procedure Zero(); [Test] procedure WhiteSpace(); [Test] procedure Sign(); [Test] procedure Base(); procedure Null(); [Test] procedure CallNull(); procedure InvalidFormat(); [Test] procedure CallInvalidFormat(); procedure InvalidFormat2(); [Test] procedure CallInvalidFormat2(); procedure InvalidFormat3(); [Test] procedure CallInvalidFormat3(); [Test] procedure BigDec(); end; implementation [Test] procedure TParseTest.Zero(); var int1: TIntX; begin int1 := TIntX.Parse('0'); Assert.IsTrue(int1 = 0); end; [Test] procedure TParseTest.WhiteSpace(); var int1: TIntX; begin int1 := TIntX.Parse(' 7 '); Assert.IsTrue(int1 = 7); end; [Test] procedure TParseTest.Sign(); var int1: TIntX; begin int1 := TIntX.Parse('-7'); Assert.IsTrue(int1 = -7); int1 := TIntX.Parse('+7'); Assert.IsTrue(int1 = 7); end; [Test] procedure TParseTest.Base(); var int1: TIntX; begin int1 := TIntX.Parse('abcdef', 16); Assert.IsTrue(int1 = $ABCDEF); int1 := TIntX.Parse('100', 8); Assert.IsTrue(int1 = 64); int1 := TIntX.Parse('0100'); Assert.IsTrue(int1 = 64); int1 := TIntX.Parse('0100000000000'); Assert.IsTrue(int1 = $200000000); int1 := TIntX.Parse('$abcdef'); Assert.IsTrue(int1 = $ABCDEF); int1 := TIntX.Parse('$ABCDEF'); Assert.IsTrue(int1 = $ABCDEF); int1 := TIntX.Parse('020000000000'); Assert.IsTrue(int1 = $80000000); int1 := TIntX.Parse('0xdeadbeef'); Assert.IsTrue(int1 = $DEADBEEF); int1 := TIntX.Parse('0Xdeadbeef'); Assert.IsTrue(int1 = $DEADBEEF); end; procedure TParseTest.Null(); begin TIntX.Parse(''); end; [Test] procedure TParseTest.CallNull(); var TempMethod: TTestLocalMethod; begin TempMethod := Null; Assert.WillRaise(TempMethod, EArgumentNilException); end; procedure TParseTest.InvalidFormat(); begin TIntX.Parse('-123-'); end; [Test] procedure TParseTest.CallInvalidFormat(); var TempMethod: TTestLocalMethod; begin TempMethod := InvalidFormat; Assert.WillRaise(TempMethod, EFormatException); end; procedure TParseTest.InvalidFormat2(); begin TIntX.Parse('abc'); end; [Test] procedure TParseTest.CallInvalidFormat2(); var TempMethod: TTestLocalMethod; begin TempMethod := InvalidFormat2; Assert.WillRaise(TempMethod, EFormatException); end; procedure TParseTest.InvalidFormat3(); begin TIntX.Parse('987', 2); end; [Test] procedure TParseTest.CallInvalidFormat3(); var TempMethod: TTestLocalMethod; begin TempMethod := InvalidFormat3; Assert.WillRaise(TempMethod, EFormatException); end; [Test] procedure TParseTest.BigDec(); var IntX: TIntX; begin IntX := TIntX.Parse ('34589238954389567586547689234723587070897800300450823748275895896384753238944985'); Assert.AreEqual(IntX.ToString(), '34589238954389567586547689234723587070897800300450823748275895896384753238944985'); end; initialization TDUnitX.RegisterTestFixture(TParseTest); end.
program balkendiagramm; var a1,a2,b1,b2,c1,c2,d1,d2,e1,e2,f1,f2 : Integer; (*Integer auf oder abrunden*) function round(num: Integer) : Integer; var temp, temp2 : Integer; begin temp := abs(num); if num mod 10 >= 5 then temp2 := 1 else temp2 := 0; round := (temp div 10) + temp2; end; (*Zeile für einen Politiker*) function printGraph(a, b : Integer) : String; var i: Integer; begin for i := 1 to 10 - round(a) do Write(' '); for i := 1 to round(a) do Write('X'); Write(' | '); for i := 1 to round(b) do Write('X'); for i := round(b) to 10 do Write(' '); end; begin WriteLn('-- Balkendiagramm --'); WriteLn('Geben Sie die Zahlen ein: '); Read(a1,a2,b1,b2,c1,c2,d1,d2,e1,e2,f1,f2); (*Ueberpruefung der Eingabe*) if (abs(a1)+a2 > 100) or (abs(b1)+b2 > 100) or (abs(c1)+c2 > 100) or (abs(d1)+d2 > 100) or (abs(e1)+e2 > 100) or (abs(f1)+f2 > 100) then WriteLn('Eingabe zweier Zahlen groeser als 100') else begin (*Ausgabe der Zeilen für jeden Politiker*) WriteLn(' negativ positiv',#13#10,'-----------+-------------'); WriteLn('1',printGraph(a1,a2)); WriteLn('2',printGraph(b1,b2)); WriteLn('3',printGraph(c1,c2)); WriteLn('4',printGraph(d1,d2)); WriteLn('5',printGraph(e1,e2)); WriteLn('6',printGraph(f1,f2)); end; end.
unit ufrmDialogSO; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterDialog, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, Vcl.ExtCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxDBExtLookupComboBox, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, cxLookupEdit, cxDBLookupEdit, uDXUtils, uModSO, Datasnap.DBClient, cxCheckBox, cxCurrencyEdit, cxSpinEdit, uInterface; type TfrmDialogSO = class(TfrmMasterDialog, ICRUDAble) pnlTop: TPanel; lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; edtNoSO: TEdit; dtTgl: TcxDateEdit; pnl1: TPanel; lbl4: TLabel; btnAddOthersProdSO: TcxButton; btnToExcel: TcxButton; btnAddFromPOTrader: TcxButton; btnShow: TcxButton; cxGrid: TcxGrid; cxGridView: TcxGridDBTableView; clNo: TcxGridDBColumn; clStatus: TcxGridDBColumn; clPLU: TcxGridDBColumn; clNamaBarang: TcxGridDBColumn; clUOM: TcxGridDBColumn; clMinOrder: TcxGridDBColumn; clCurrStock: TcxGridDBColumn; clQTYSO: TcxGridDBColumn; clMaxOrder: TcxGridDBColumn; clSuppCode: TcxGridDBColumn; clSuppName: TcxGridDBColumn; clLeadTime: TcxGridDBColumn; clBuyPrice: TcxGridDBColumn; clDisc1: TcxGridDBColumn; clDisc2: TcxGridDBColumn; clDisc3: TcxGridDBColumn; clNetPrice: TcxGridDBColumn; cxlvMaster: TcxGridLevel; cxLookupMerchan: TcxExtLookupComboBox; cxLookupSupplierMerchan: TcxExtLookupComboBox; lblSuppMerGroup: TLabel; lblSuppMerGroupOpsional: TLabel; clADS: TcxGridDBColumn; clBarangID: TcxGridDBColumn; clSupMerchan: TcxGridDBColumn; clUOMID: TcxGridDBColumn; clROP: TcxGridDBColumn; actGenerate: TAction; actAddProd: TAction; clQTYOrder: TcxGridDBColumn; pmGrid: TPopupMenu; CheckAll1: TMenuItem; UnCheckAll1: TMenuItem; procedure actAddProdExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actGenerateExecute(Sender: TObject); procedure actPrintExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure clNoGetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: string); procedure clStatusPropertiesEditValueChanged(Sender: TObject); procedure clQTYOrderPropertiesEditValueChanged(Sender: TObject); procedure btnToExcelClick(Sender: TObject); procedure CheckAll1Click(Sender: TObject); procedure cxLookupSupplierMerchanPropertiesInitPopup(Sender: TObject); procedure cxLookupMerchanPropertiesEditValueChanged(Sender: TObject); procedure UnCheckAll1Click(Sender: TObject); private FCDS: TClientDataSet; FCDSSatuan: TClientDataset; FCDSSuplierMerchan: TClientDataSet; FModSO: TModSO; FUsingCache: Boolean; procedure AddOtherProduct; procedure ClearForm; procedure DeleteData; procedure GenerateSO; function GetCDS: TClientDataSet; function GetCDSSatuan: TClientDataset; function GetCDSSuplierMerchan: TClientDataSet; function GetModSO: TModSO; procedure InitView; procedure UpdateData; function ValidateGenerate: Boolean; property CDS: TClientDataSet read GetCDS write FCDS; property CDSSuplierMerchan: TClientDataSet read GetCDSSuplierMerchan write FCDSSuplierMerchan; property ModSO: TModSO read GetModSO write FModSO; property UsingCache: Boolean read FUsingCache write FUsingCache; { Private declarations } public procedure DoCheckGrid(State: Boolean); procedure LoadData(AID: String); property CDSSatuan: TClientDataset read GetCDSSatuan write FCDSSatuan; { Public declarations } end; var frmDialogSO: TfrmDialogSO; implementation uses uDBUtils, uDMClient, uAppUtils, uClientClasses, uModBarang, uModSuplier, uModSatuan, uConstanta, ufrmCXLookup, System.DateUtils, FireDAC.Comp.Client, Data.FireDACJSONReflect, uRetnoUnit, uDMReport; {$R *.dfm} procedure TfrmDialogSO.actAddProdExecute(Sender: TObject); begin inherited; AddOtherProduct; end; procedure TfrmDialogSO.actDeleteExecute(Sender: TObject); begin inherited; DeleteData; end; procedure TfrmDialogSO.actGenerateExecute(Sender: TObject); begin inherited; GenerateSO; end; procedure TfrmDialogSO.actPrintExecute(Sender: TObject); var FilterPeriode: string; sNomorSO: string; begin inherited; sNomorSO := ModSo.SO_NO; if sNomorSO = '' then exit; with dmReport do begin FilterPeriode := dtTgl.Text + ' s/d ' + dtTgl.Text; AddReportVariable('FilterPeriode', FilterPeriode ); AddReportVariable('UserCetak', 'Baskoro'); ExecuteReport( 'Reports/Slip_SO' , ReportClient.SO_ByDateNoBukti( dtTgl.Date, dtTgl.Date, sNomorSO, sNomorSO ),[] ); end; end; procedure TfrmDialogSO.btnToExcelClick(Sender: TObject); begin inherited; cxGridView.ExportToXLS(); end; procedure TfrmDialogSO.FormCreate(Sender: TObject); begin inherited; UsingCache := False; InitView; ClearForm; end; procedure TfrmDialogSO.FormDestroy(Sender: TObject); begin inherited; if Assigned(FModSO) then FreeAndNil(FModSO); end; procedure TfrmDialogSO.actSaveExecute(Sender: TObject); begin inherited; if not ValidateEmptyCtrl([1]) then Exit; UpdateData; Try ModSO.ID := DMClient.CrudClient.SaveToDBID(ModSO); TAppUtils.Information(CONF_ADD_SUCCESSFULLY); Self.ModalResult := mrOk; except TAppUtils.Error(ER_INSERT_FAILED); raise; End; end; procedure TfrmDialogSO.AddOtherProduct; var frm: TfrmCXLookup; lCDS: TClientDataSet; // lMem: TFDMemTable; lStart: TDateTime; begin inherited; lStart := Now(); lCDS := TClientDataSet( DMClient.DSProviderClient.BarangSupp_GetDSLookup(cxLookupMerchan.EditValue) ); frm := TfrmCXLookup.Execute(lCDS, True); frm.StartExecute := lStart; Try frm.ShowFieldsOnly(['BRG_CODE','BRG_NAME','SUP_CODE','SUP_NAME', 'SAT_CODE', 'BUYPRICE'] ); if frm.ShowModal = mrOk then begin while not frm.Data.eof do begin if CDS.Locate('BARANG_ID', frm.Data.FieldByName('BARANG_ID').AsString, [loCaseInsensitive]) then begin TAppUtils.Warning('Barang : ' + frm.Data.FieldByName('BRG_CODE').AsString + ' - ' + frm.Data.FieldByName('BRG_NAME').AsString + ' sudah ada di grid' ); end else begin CDS.Append; CDS.FieldByName('Checked').AsBoolean := True; CDS.SetFieldFrom('PLU', frm.Data, 'BRG_CODE'); CDS.SetFieldFrom('NamaBarang', frm.Data, 'BRG_NAME'); CDS.SetFieldFrom('UOM', frm.Data, 'SAT_CODE'); CDS.SetFieldFrom('MinOrder', frm.Data); CDS.SetFieldFrom('MaxOrder', frm.Data); CDS.SetFieldFrom('Stock', frm.Data); CDS.SetFieldFrom('ADS',frm.Data,'ADS'); CDS.SetFieldFrom('SupplierCode', frm.Data, 'SUP_CODE'); CDS.SetFieldFrom('SupplierName', frm.Data, 'SUP_NAME'); CDS.SetFieldFrom('LeadTime', frm.Data, 'LEADTIME'); CDS.SetFieldFrom('BuyPrice', frm.Data, 'BUYPRICE'); CDS.SetFieldFrom('Disc1', frm.Data, 'DISC1'); CDS.SetFieldFrom('Disc2', frm.Data, 'DISC2'); CDS.SetFieldFrom('Disc3', frm.Data, 'DISC3'); CDS.SetFieldFrom('NetPrice', frm.Data, 'NETPRICE'); CDS.SetFieldFrom('BARANG_ID', frm.Data, 'BARANG_ID'); CDS.SetFieldFrom('SATUAN_ID', frm.Data, 'SATUAN_ID'); CDS.SetFieldFrom('SUPLIER_MERCHAN_ID', frm.Data, 'SUPLIER_MERCHAN_GRUP_ID'); CDS.SetFieldFrom('BARANG_SUPLIER_ID', frm.Data, 'BARANG_SUPLIER_ID'); CDS.FieldByName('ROP').AsFloat := 0; CDS.FieldByName('QTYSO').AsFloat := 0; CDS.FieldByName('QTY').AsFloat := 0; CDS.Post; end; frm.Data.Next; end; cxGridView.ApplyBestFit(); end; Finally frm.Free; lCDS.Free; End; end; procedure TfrmDialogSO.CheckAll1Click(Sender: TObject); begin inherited; DoCheckGrid(True); end; procedure TfrmDialogSO.ClearForm; begin dtTgl.Date := Now(); // Self.ClearByTag([2],pnlTop); edtNoSo.Text := DMClient.CrudClient.GenerateNo(TModSO.ClassName); end; procedure TfrmDialogSO.clNoGetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: string); begin inherited; If Assigned(ARecord) then AText := IntToStr(ARecord.RecordIndex +1); end; procedure TfrmDialogSO.clQTYOrderPropertiesEditValueChanged(Sender: TObject); begin inherited; cxGridView.DataController.Post(); CDS.Edit; CDS.FieldByName('Checked').AsBoolean := CDS.FieldByName('QTY').AsFloat > 0; CDS.Post; end; procedure TfrmDialogSO.clStatusPropertiesEditValueChanged(Sender: TObject); begin inherited; cxGridView.DataController.Post; CDS.Edit; if CDS.FieldByName('Checked').AsBoolean then CDS.FieldByName('QTY').AsFloat := CDS.FieldByName('QTYSO').AsFloat else CDS.FieldByName('QTY').AsFloat := 0; CDS.Post; end; procedure TfrmDialogSO.cxLookupMerchanPropertiesEditValueChanged( Sender: TObject); begin inherited; cxLookupSupplierMerchan.DS.Filtered := True; cxLookupSupplierMerchan.DS.Filter := '[REF$MERCHANDISE_ID] = ' + QuotedStr(cxLookupMerchan.EditValue); end; procedure TfrmDialogSO.cxLookupSupplierMerchanPropertiesInitPopup( Sender: TObject); begin inherited; if VarIsNull(cxLookupMerchan.EditValue) then TAppUtils.Warning('Merchan Grup wajib diisi terlebih dahulu'); end; procedure TfrmDialogSO.DeleteData; var i: Integer; begin if not Assigned(ModSO) then Raise Exception.Create('Data not Loaded'); if ModSO.ID = '' then begin TAppUtils.Error('Tidak ada data yang dihapus'); exit; end; for i := 0 to ModSO.SODetails.Count-1 do begin if ModSO.SODetails[i].SOD_IS_ORDERED = 1 then begin TAppUtils.Error('SO sudah diproses PO , tidak bisa dihapus'); exit; end; end; Try DMClient.CrudClient.DeleteFromDB(ModSO); TAppUtils.Information(CONF_DELETE_SUCCESSFULLY); Self.ModalResult := mrOk; except TAppUtils.Error(ER_DELETE_FAILED); raise; End; end; procedure TfrmDialogSO.DoCheckGrid(State: Boolean); var lCDS: TClientDataSet; begin lCDS := TClientDataSet.Create(Self); CDS.DisableControls; Try lCDS.CloneCursor(CDS, True); lCDS.First; while not lCDS.Eof do begin lCDS.Edit; lCDS.FieldByName('Checked').AsBoolean := State; if lCDS.FieldByName('Checked').AsBoolean then lCDS.FieldByName('QTY').AsFloat := lCDS.FieldByName('QTYSO').AsFloat else lCDS.FieldByName('QTY').AsFloat := 0; lCDS.Post; lCDS.Next; end; Finally CDS.EnableControls; lCDS.Free; End; end; procedure TfrmDialogSO.GenerateSO; var lCDS: TClientDataSet; lSO: TSuggestionOrderClient; SupMerchanID: string; begin if not ValidateGenerate then exit; SupMerchanID := ''; If not VarIsNull(cxLookupSupplierMerchan.EditValue) then SupMerchanID := cxLookupSupplierMerchan.EditValue; lSO := TSuggestionOrderClient.Create(DMClient.RestConn, False); lCDS := TClientDataSet(lSO.GenerateSO(dtTgl.Date, cxLookupMerchan.EditValue, SupMerchanID)); CDS.DisableControls; Try CDS.EmptyDataSet; while not lCDS.eof do begin CDS.Append; CDS.SetFieldFrom('PLU', lCDS, 'KODEBARANG'); CDS.SetFieldFrom('NamaBarang', lCDS); CDS.SetFieldFrom('UOM', lCDS, 'SATUAN'); CDS.SetFieldFrom('MinOrder', lCDS, 'MINQTY'); CDS.SetFieldFrom('MaxOrder', lCDS, 'MAXQTY'); CDS.SetFieldFrom('STOCK', lCDS); CDS.SetFieldFrom('ROP', lCDS); CDS.SetFieldFrom('ADS', lCDS); CDS.SetFieldFrom('QTYSO', lCDS); CDS.SetFieldFrom('QTY', lCDS, 'QTYSO'); CDS.SetFieldFrom('SupplierCode', lCDS); CDS.SetFieldFrom('SupplierName', lCDS); CDS.SetFieldFrom('LeadTime', lCDS); CDS.SetFieldFrom('BuyPrice', lCDS); CDS.SetFieldFrom('Disc1', lCDS); CDS.SetFieldFrom('Disc2', lCDS); CDS.SetFieldFrom('Disc3', lCDS); CDS.SetFieldFrom('NetPrice', lCDS); CDS.SetFieldFrom('BARANG_ID', lCDS); CDS.SetFieldFrom('BARANG_SUPLIER_ID', lCDS); CDS.SetFieldFrom('SATUAN_ID', lCDS); CDS.SetFieldFrom('SUPLIER_MERCHAN_ID', lCDS); CDS.SetFieldFrom('IS_BKP', lCDS); CDS.SetFieldFrom('IS_REGULAR', lCDS); CDS.SetFieldFrom('IS_STOCK', lCDS); CDS.FieldByName('Checked').AsBoolean := CDS.FieldByName('QTY').AsFloat > 0; CDS.Post; lCDS.Next; end; Finally CDS.EnableControls; cxGridView.ApplyBestFit(); lSO.Free; lCDS.Free; End; end; function TfrmDialogSO.GetCDS: TClientDataSet; begin If not Assigned(FCDS) then begin FCDS := TClientDataSet.Create(Self); FCDS.AddField('No',ftInteger); FCDS.AddField('Checked',ftBoolean); FCDS.AddField('PLU',ftString); FCDS.AddField('NamaBarang',ftString); FCDS.AddField('UOM',ftString); FCDS.AddField('MinOrder',ftFloat); FCDS.AddField('MaxOrder',ftFloat); FCDS.AddField('STOCK',ftFloat); FCDS.AddField('ADS',ftFloat); FCDS.AddField('ROP',ftFloat); FCDS.AddField('QTYSO',ftFloat); FCDS.AddField('QTY',ftFloat); FCDS.AddField('SupplierCode',ftString); FCDS.AddField('SupplierName',ftString); FCDS.AddField('LeadTime',ftString); FCDS.AddField('BuyPrice',ftFloat); FCDS.AddField('Disc1',ftFloat); FCDS.AddField('Disc2',ftFloat); FCDS.AddField('Disc3',ftFloat); FCDS.AddField('NetPrice',ftFloat); FCDS.AddField('Barang_ID',ftString); FCDS.AddField('Barang_Suplier_ID',ftString); FCDS.AddField('Satuan_ID',ftString); FCDS.AddField('SUPLIER_MERCHAN_ID',ftString); FCDS.AddField('IS_BKP',ftInteger); FCDS.AddField('IS_REGULAR',ftInteger); FCDS.AddField('IS_STOCK',ftInteger); FCDS.CreateDataSet; end; Result := FCDS; end; function TfrmDialogSO.GetCDSSatuan: TClientDataset; begin if not Assigned(FCDSSatuan) then FCDSSatuan := TDBUtils.DSToCDS( DMClient.DSProviderClient.Satuan_GetDSLookup, Self); Result := FCDSSatuan; end; function TfrmDialogSO.GetCDSSuplierMerchan: TClientDataSet; begin if not Assigned(FCDSSuplierMerchan) then begin FCDSSuplierMerchan := TDBUtils.DSToCDS( DMClient.DSProviderClient.SuplierMerchan_GetDSLookup, Self); end; Result := FCDSSuplierMerchan; end; function TfrmDialogSO.GetModSO: TModSO; begin if not Assigned(FModSO) then begin FModSO := TModSO.Create; FModSO.AUTUNIT := TRetno.UnitStore; end; Result := FModSO; end; procedure TfrmDialogSO.InitView; var lCDS: TClientDataSet; begin With DMClient.DSProviderClient do begin lCDS := TClientDataSet.Create(Self); lCDS.CloneCursor(CDSSuplierMerchan, True); cxLookupSupplierMerchan.LoadFromCDS(CDSSuplierMerchan, 'SUPLIER_MERCHAN_GRUP_ID' , 'SUP_NAME', Self); cxLookupSupplierMerchan.SetVisibleColumnsOnly(['SUP_CODE', 'SUP_NAME', 'MERCHANGRUP_NAME']); cxLookupMerchan.LoadFromDS(Merchandise_GetDSLookup, 'REF$MERCHANDISE_ID','MERCHAN_NAME' ,Self); end; cxLookupMerchan.SetDefaultValue(); //debug only cxLookupMerchan.DS.Locate('MERCHAN_NAME','DRY FOOD', [loCaseInsensitive]); cxLookupMerchan.EditValue := cxLookupMerchan.DS.FieldByName('REF$MERCHANDISE_ID').AsString; cxGridView.LoadFromCDS(CDS, False); //inisialisasi end; procedure TfrmDialogSO.LoadData(AID: String); var // i: Integer; // lBrg: TModBarang; lCDS: TDataSet; // lDetail: TModSODetail; // lDisc: Double; lSO: TSuggestionOrderClient; begin If Assigned(FModSO) then FModSO.Free; FModSO := DMClient.CrudClient.RetrieveSingle(TModSO.ClassName, AID) as TModSO; edtNoSo.Text := ModSO.SO_NO; dtTgl.Date := ModSO.SO_DATE; cxLookupMerchan.EditValue := ModSo.Merchandise.ID; cxLookupSupplierMerchan.EditValue := ModSo.SupplierMerchan.ID; CDS.DisableControls; Screen.Cursor := crHourGlass; Application.ProcessMessages; lSO := TSuggestionOrderClient.Create(DMClient.RestConn, False); lCDS := lSO.RetrieveDetails(FModSO.ID); Try while not lCDS.Eof do begin CDS.Append; CDS.SetFieldFrom('PLU', lCDS, 'KODEBARANG'); CDS.SetFieldFrom('NamaBarang', lCDS); CDS.SetFieldFrom('UOM', lCDS, 'SATUAN'); CDS.SetFieldFrom('MinOrder', lCDS, 'MINQTY'); CDS.SetFieldFrom('MaxOrder', lCDS, 'MAXQTY'); CDS.SetFieldFrom('STOCK', lCDS); CDS.SetFieldFrom('ROP', lCDS); CDS.SetFieldFrom('ADS', lCDS); CDS.SetFieldFrom('QTYSO', lCDS); CDS.SetFieldFrom('QTY', lCDS); CDS.SetFieldFrom('SupplierCode', lCDS); CDS.SetFieldFrom('SupplierName', lCDS); CDS.SetFieldFrom('LeadTime', lCDS); CDS.SetFieldFrom('BuyPrice', lCDS); CDS.SetFieldFrom('Disc1', lCDS); CDS.SetFieldFrom('Disc2', lCDS); CDS.SetFieldFrom('Disc3', lCDS); CDS.SetFieldFrom('NetPrice', lCDS); CDS.SetFieldFrom('BARANG_ID', lCDS); CDS.SetFieldFrom('BARANG_SUPLIER_ID', lCDS); CDS.SetFieldFrom('SATUAN_ID', lCDS); CDS.SetFieldFrom('SUPLIER_MERCHAN_ID', lCDS); CDS.SetFieldFrom('IS_BKP', lCDS); CDS.SetFieldFrom('IS_REGULAR', lCDS); CDS.SetFieldFrom('IS_STOCK', lCDS); CDS.FieldByName('Checked').AsBoolean := CDS.FieldByName('QTY').AsFloat > 0; CDS.Post; lCDS.Next; end; // for i := 0 to ModSO.SODetails.Count-1 do // begin // lDetail := ModSO.SODetails[i]; // CDS.Append; // CDS.FieldByName('Checked').AsBoolean := lDetail.SOD_QTY > 0; // CDS.FieldByName('STOCK').AsFloat := lDetail.SOD_STOCK; // CDS.FieldByName('ADS').AsFloat := lDetail.SOD_ADS; // CDS.FieldByName('ROP').AsFloat := lDetail.SOD_ROP; // CDS.FieldByName('QTYSO').AsFloat := lDetail.SOD_QTYSO; // CDS.FieldByName('QTY').AsFloat := lDetail.SOD_QTY; // CDS.FieldByName('BuyPrice').AsFloat := lDetail.SOD_PRICE; // CDS.FieldByName('Disc1').AsFloat := lDetail.SOD_DISC1; // CDS.FieldByName('Disc2').AsFloat := lDetail.SOD_DISC2; // CDS.FieldByName('Disc3').AsFloat := lDetail.SOD_DISC3; // CDS.FieldByName('NetPrice').AsFloat := lDetail.SOD_PRICE; // CDS.FieldByName('Barang_ID').AsString := lDetail.BARANG.ID; // CDS.FieldByName('Barang_Suplier_ID').AsString := lDetail.BARANG_SUPPLIER.ID; // CDS.FieldByName('Satuan_ID').AsString := lDetail.Satuan.ID; // CDS.FieldByName('SUPLIER_MERCHAN_ID').AsString := lDetail.SupplierMerchan.ID; // CDS.FieldByName('IS_BKP').AsInteger := lDetail.SOD_IS_BKP; // CDS.FieldByName('IS_REGULAR').AsInteger := lDetail.SOD_IS_REGULAR; // CDS.FieldByName('IS_STOCK').AsInteger := lDetail.SOD_IS_STOCK; // // lDisc := (lDetail.SOD_DISC1/100) * lDetail.SOD_PRICE ; // lDisc := lDisc + ((lDetail.SOD_DISC2/100) * (lDetail.SOD_PRICE-lDisc)) ; // lDisc := lDisc + lDetail.SOD_DISC3; // // CDS.FieldByName('NetPrice').AsFloat := lDetail.SOD_PRICE - lDisc; // // if CDSSuplierMerchan.Locate('SUPLIER_MERCHAN_GRUP_ID', lDetail.SupplierMerchan.ID, [loCaseInsensitive]) then // begin // CDS.FieldByName('SupplierCode').AsString := CDSSuplierMerchan.FieldByName('SUP_CODE').AsString; // CDS.FieldByName('SupplierName').AsString := CDSSuplierMerchan.FieldByName('SUP_NAME').AsString; // CDS.FieldByName('LeadTime').AsInteger := CDSSuplierMerchan.FieldByName('SUPMG_LEAD_TIME').AsInteger; // end; // // if CDSSatuan.Locate('ref$satuan_id', lDetail.Satuan.ID, [loCaseInsensitive]) then // begin // CDS.FieldByName('UOM').AsString := CDSSatuan.FieldByName('SAT_CODE').AsString; // end; // // lBrg := DMClient.CrudClient.RetrieveSingle(TModBarang.ClassName, lDetail.BARANG.ID) as TModBarang; // Try // if Assigned(lBrg) then // begin // CDS.FieldByName('PLU').AsString := lBrg.BRG_CODE; // CDS.FieldByName('NamaBarang').AsString := lBrg.BRG_NAME; // end; // Finally // FreeAndNil(lBrg); // End; // // CDS.Post; // // end; Finally // TAppUtils.FinalisasiProgressBar(); lSO.Free; CDS.EnableControls; cxGridView.ApplyBestFit(); Screen.Cursor := crDefault; End; end; procedure TfrmDialogSO.UnCheckAll1Click(Sender: TObject); begin inherited; DoCheckGrid(False); end; procedure TfrmDialogSO.UpdateData; var lDetail: TModSODetail; lDisc: Double; begin ModSO.SO_DATE := dtTgl.Date; ModSO.SO_NO := edtNoSO.Text; ModSO.Merchandise := TModMerchandise.CreateID(cxLookupMerchan.EditValue); If not VarIsNull(cxLookupSupplierMerchan.EditValue) then ModSO.SupplierMerchan := TModSuplierMerchanGroup.CreateID(cxLookupSupplierMerchan.EditValue); ModSO.SODetails.Clear; CDS.DisableControls; Try CDS.First; while not CDS.Eof do begin lDetail := TModSODetail.Create; lDetail.BARANG := TModBarang.CreateID(CDS.FieldByName('Barang_ID').AsString); lDetail.BARANG_SUPPLIER := TModBarangSupplier.CreateID(CDS.FieldByName('Barang_Suplier_ID').AsString ); lDetail.Satuan := TModSatuan.CreateID(CDS.FieldByName('Satuan_ID').AsString); lDetail.SupplierMerchan := TModSuplierMerchanGroup.CreateID(CDS.FieldByName('SUPLIER_MERCHAN_ID').AsString); lDetail.SOD_QTYSO := CDS.FieldByName('QTYSO').AsFloat; lDetail.SOD_QTY := CDS.FieldByName('QTY').AsFloat; lDetail.SOD_ADS := CDS.FieldByName('ADS').AsFloat; lDetail.SOD_STOCK := CDS.FieldByName('STOCK').AsFloat; lDetail.SOD_ROP := CDS.FieldByName('ROP').AsFloat; lDetail.SOD_IS_BKP := CDS.FieldByName('IS_BKP').AsInteger; lDetail.SOD_IS_REGULAR := CDS.FieldByName('IS_REGULAR').AsInteger; lDetail.SOD_PRICE := CDS.FieldByName('BuyPrice').AsFloat; lDetail.SOD_DISC1 := CDS.FieldByName('Disc1').AsFloat; lDetail.SOD_DISC2 := CDS.FieldByName('Disc2').AsFloat; lDetail.SOD_DISC3 := CDS.FieldByName('Disc3').AsFloat; lDetail.SOD_IS_ORDERED := 0; //diupdate oleh PO lDetail.SOD_TOTAL := CDS.FieldByName('NetPrice').AsFloat * lDetail.SOD_QTY; lDetail.SOD_IS_STOCK := CDS.FieldByName('IS_STOCK').AsInteger; lDisc := (lDetail.SOD_DISC1/100) * lDetail.SOD_PRICE ; lDisc := lDisc + ((lDetail.SOD_DISC2/100) * (lDetail.SOD_PRICE-lDisc)) ; lDisc := lDisc + lDetail.SOD_DISC3; lDetail.SOD_TOTAL_DISC := lDetail.SOD_QTY * lDisc; ModSO.SODetails.Add(lDetail); CDS.Next; end; Finally CDS.EnableControls; End; end; function TfrmDialogSO.ValidateGenerate: Boolean; begin Result := False; if VarIsNull(cxLookupMerchan.EditValue) then begin TAppUtils.Warning('Merchan Grup wajib diisi'); cxLookupMerchan.SetFocus; exit; end; if CDS.RecordCount > 0 then begin if not TAppUtils.Confirm('Grid akan direset, Anda yakin akan generate SO ?') then exit; end; Result := True; end; end.
unit ibSHDBObjectEditors; interface uses SysUtils, Classes, Controls, StrUtils, DesignIntf, TypInfo, Dialogs, SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors; type // -> Property Editors TibBTDBObjectPropEditor = class(TibBTPropertyEditor) private FDBObject: IibSHDBObject; public constructor Create(APropertyEditor: TObject); override; destructor Destroy; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; property DBObject: IibSHDBObject read FDBObject; end; IibSHDBDescriptionProp = interface ['{39E8022F-8802-443C-BED2-A0988C3654AE}'] end; // IibSHDBSourceDDLProp = interface // ['{B166E696-1544-4C92-AD52-667301F335A5}'] // end; IibSHDBParams = interface ['{D6F62758-DFEA-4F6B-A1E1-311647463458}'] end; IibSHDBReturns = interface ['{251C3DFE-EDDD-4147-8B11-E770956C5C02}'] end; IibSHDBFields = interface ['{7ACECF5B-BF40-4AC9-9510-4967B4D8FB30}'] end; IibSHDBReferenceFields = interface ['{476159EF-22D0-43C8-A255-F779890E79AB}'] end; IibSHDBConstraints = interface ['{40BB81AE-6B71-4E9E-AF90-19E45C42ABD9}'] end; IibSHDBIndices = interface ['{43D2B734-110B-48CC-9361-E5F1DE31FB4C}'] end; IibSHDBTriggers = interface ['{1CE8C3F7-BFA6-413C-A9EF-1E7B7E092C0E}'] end; IibSHDBGrants = interface ['{BDF6C39E-C7E8-42CA-99E5-5B2600BFF7D5}'] end; IibSHDBTRParams = interface ['{C30DC65E-B8F7-4BE9-9542-9AC299443D50}'] end; // IibSHDBBLR = interface // ['{1D2ABDF1-52D8-4809-AC62-B3877D1A0FE0}'] // end; IibSHDBDefaultExpression = interface ['{65F0AE3C-897C-4258-952A-5116B676E438}'] end; IibSHDBCheckConstraint = interface ['{96C53198-F13B-47B6-8317-77D9B24CF5AA}'] end; IibSHDBCheckSource = interface ['{02D5347D-B9A3-46EC-9FD7-AF3916FECEDF}'] end; IibSHComputedSource = interface ['{F9D83140-04F8-4D61-AB71-B6839EFF0BFE}'] end; TibBTDBDescriptionProp = class(TibBTDBObjectPropEditor, IibSHDBDescriptionProp); // TibBTDBSourceDDLProp = class(TibBTDBObjectPropEditor, IibSHDBSourceDDLProp); TibBTDBParams = class(TibBTDBObjectPropEditor, IibSHDBParams); TibBTDBReturns = class(TibBTDBObjectPropEditor, IibSHDBReturns); TibBTDBFields = class(TibBTDBObjectPropEditor, IibSHDBFields); TibBTDBReferenceFields = class(TibBTDBObjectPropEditor, IibSHDBReferenceFields); TibBTDBConstraints = class(TibBTDBObjectPropEditor, IibSHDBConstraints); TibBTDBIndices = class(TibBTDBObjectPropEditor, IibSHDBIndices); TibBTDBTriggers = class(TibBTDBObjectPropEditor, IibSHDBTriggers); TibBTDBGrants = class(TibBTDBObjectPropEditor, IibSHDBGrants); TibBTDBTRParams = class(TibBTDBObjectPropEditor, IibSHDBTRParams); // TibBTDBBLR = class(TibBTDBObjectPropEditor, IibSHDBBLR); TibBTDBDefaultExpression = class(TibBTDBObjectPropEditor, IibSHDBDefaultExpression); TibBTDBCheckConstraint = class(TibBTDBObjectPropEditor, IibSHDBCheckConstraint); TibBTDBCheckSource = class(TibBTDBObjectPropEditor, IibSHDBCheckSource); TibBTComputedSource = class(TibBTDBObjectPropEditor, IibSHComputedSource); TibBTTableNamePropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibBTStatusPropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibBTTypePrefixPropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibBTTypeSuffixPropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibBTRecordCountEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; TibBTChangeCountPropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; TibBTDataTypePropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibBTCollatePropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibBTBlobSubTypePropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibBTMechanismPropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibBTPrecisionPropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibBTScalePropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; implementation uses ibSHConsts, ibSHValues; { TibBTDBObjectPropEditor } constructor TibBTDBObjectPropEditor.Create(APropertyEditor: TObject); begin inherited Create(APropertyEditor); Supports(Component, IibSHDBObject, FDBObject); end; destructor TibBTDBObjectPropEditor.Destroy; begin inherited Destroy; end; function TibBTDBObjectPropEditor.GetAttributes: TPropertyAttributes; begin Result := []; if Supports(Self, IibSHDBParams) or Supports(Self, IibSHDBReturns) or Supports(Self, IibSHDBDefaultExpression) or Supports(Self, IibSHDBCheckConstraint) or Supports(Self, IibSHDBCheckSource) or Supports(Self, IibSHComputedSource) then Result := Result + [paReadOnly]; if Supports(Self, IibSHDBDescriptionProp) or // Supports(Self, IibSHDBSourceDDLProp) or Supports(Self, IibSHDBGrants) or Supports(Self, IibSHDBTRParams) or // Supports(Self, IibSHDBBLR) or Supports(Self, IibSHDBFields) or Supports(Self, IibSHDBReferenceFields) or Supports(Self, IibSHDBConstraints) or Supports(Self, IibSHDBIndices) or Supports(Self, IibSHDBTriggers) then Result := Result + [paReadOnly, paDialog]; if (Supports(DBObject, IibSHIndex) or Supports(DBObject, IibSHConstraint)) and Supports(Self, IibSHDBFields) then Result := Result - [paDialog]; if Supports(DBObject, IibSHConstraint) and Supports(Self, IibSHDBReferenceFields) then Result := Result - [paDialog]; end; function TibBTDBObjectPropEditor.GetValue: string; begin Result := inherited GetValue; if Supports(Self, IibSHDBDescriptionProp) then Result := TrimRight(DBObject.Description.Text); // if Supports(Self, IibSHDBSourceDDLProp) or // Supports(Self, IibSHDBBLR) then // Result := 'Text'; if Supports(Self, IibSHDBParams) or Supports(Self, IibSHDBReturns) or Supports(Self, IibSHDBFields) or Supports(Self, IibSHDBReferenceFields) or Supports(Self, IibSHDBConstraints) or Supports(Self, IibSHDBIndices) or Supports(Self, IibSHDBTriggers) or Supports(Self, IibSHDBTRParams) then begin if Supports(Self, IibSHDBParams) then Result := Trim(DBObject.Params.CommaText); if Supports(Self, IibSHDBReturns) then Result := Trim(DBObject.Returns.CommaText); if Supports(Self, IibSHDBFields) then Result := Trim(DBObject.Fields.CommaText); if Supports(Self, IibSHDBReferenceFields) then Result := Trim((DBObject as IibSHConstraint).ReferenceFields.CommaText); if Supports(Self, IibSHDBConstraints) then Result := Trim(DBObject.Constraints.CommaText); if Supports(Self, IibSHDBIndices) then Result := Trim(DBObject.Indices.CommaText); if Supports(Self, IibSHDBTriggers) then Result := Trim(DBObject.Triggers.CommaText); if Supports(Self, IibSHDBTRParams) then Result := Trim(DBObject.TRParams.CommaText); Result := AnsiReplaceStr(Result, '"', ''); Result := AnsiReplaceStr(Result, ',', ', '{ + SLineBreak}); end; if Supports(Self, IibSHDBDefaultExpression) then Result := Trim((DBObject as IibSHDomain).DefaultExpression.Text); if Supports(Self, IibSHDBCheckConstraint) then Result := Trim((DBObject as IibSHDomain).CheckConstraint.Text); if Supports(Self, IibSHDBCheckSource) then Result := Trim((DBObject as IibSHConstraint).CheckSource.Text); if Supports(Self, IibSHComputedSource) then Result := Trim((DBObject as IibSHField).ComputedSource.Text); if Supports(Self, IibSHDBGrants) then Result := 'Show'; end; procedure TibBTDBObjectPropEditor.GetValues(AValues: TStrings); begin inherited GetValues(AValues); end; procedure TibBTDBObjectPropEditor.SetValue(const Value: string); begin inherited SetValue(Value); end; procedure TibBTDBObjectPropEditor.Edit; begin if Supports(Self, IibSHDBParams) or Supports(Self, IibSHDBReturns) or Supports(Self, IibSHDBTRParams) then begin if IsPositiveResult(Designer.ShowModal(Component, PropName)) then Designer.UpdateObjectInspector; Exit; end; // if Supports(Self, IibSHDBSourceDDLProp) then // begin // if Designer.ExistsComponent(Component, SCallSourceDDL) then // Designer.ChangeNotification(Component, SCallSourceDDL, opInsert) // else // DBObject.CommitObject; // Exit; // end; // if Supports(Self, IibSHDBBLR) then // begin // Designer.UnderConstruction; // Exit; // end; if Supports(Self, IibSHDBDescriptionProp) then begin Designer.ChangeNotification(Component, SCallDescription, opInsert); Exit; end; if Supports(Self, IibSHDBFields) then begin Designer.ChangeNotification(Component, SCallFields, opInsert); Exit; end; if Supports(Self, IibSHDBConstraints) then begin Designer.ChangeNotification(Component, SCallConstraints, opInsert); Exit; end; if Supports(Self, IibSHDBIndices) then begin Designer.ChangeNotification(Component, SCallIndices, opInsert); Exit; end; if Supports(Self, IibSHDBTriggers) then begin Designer.ChangeNotification(Component, SCallTriggers, opInsert); Exit; end; end; { TibBTTableNamePropEditor } function TibBTTableNamePropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibBTTableNamePropEditor.GetValues(AValues: TStrings); begin AValues.Text := GetTableList; end; procedure TibBTTableNamePropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetTableList) then inherited SetStrValue(Value); end; { TibBTStatusPropEditor } function TibBTStatusPropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibBTStatusPropEditor.GetValues(AValues: TStrings); begin AValues.Text := GetStatus; end; procedure TibBTStatusPropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetStatus) then inherited SetStrValue(Value); end; { TibBTTypePrefixPropEditor } function TibBTTypePrefixPropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibBTTypePrefixPropEditor.GetValues(AValues: TStrings); begin AValues.Text := GetTypePrefix; end; procedure TibBTTypePrefixPropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetTypePrefix) then inherited SetStrValue(Value); end; { TibBTTypeSuffixPropEditor } function TibBTTypeSuffixPropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibBTTypeSuffixPropEditor.GetValues(AValues: TStrings); begin // TODO проверить Component на версию сервера GetTypeSuffixIB или GetTypeSuffixFB AValues.Text := GetTypeSuffixFB; end; procedure TibBTTypeSuffixPropEditor.SetValue(const Value: string); begin // TODO проверить Component на версию сервера GetTypeSuffixYA или GetTypeSuffixFB if Assigned(Designer) and Designer.CheckPropValue(Value, GetTypeSuffixFB) then inherited SetStrValue(Value); end; { TibBTRecordCountEditor } function TibBTRecordCountEditor.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paNotNestable, paReadOnly]; end; procedure TibBTRecordCountEditor.Edit; var ibBTTableIntf: IibSHTable; ibBTViewIntf: IibSHView; begin if Assigned(Component) and Assigned(Designer) then begin if Supports(Component, IibSHTable, ibBTTableIntf) then ibBTTableIntf.SetRecordCount; if Supports(Component, IibSHView, ibBTViewIntf) then ibBTViewIntf.SetRecordCount; Designer.UpdateObjectInspector; end; end; { TibBTChangeCountPropEditor } function TibBTChangeCountPropEditor.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paNotNestable, paReadOnly]; end; procedure TibBTChangeCountPropEditor.Edit; var ibBTTableIntf: IibSHTable; begin if Assigned(Component) and Assigned(Designer) then begin if Supports(Component, IibSHTable, ibBTTableIntf) then ibBTTableIntf.SetChangeCount; Designer.UpdateObjectInspector; end; end; { TibBTDataTypePropEditor } function TibBTDataTypePropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibBTDataTypePropEditor.GetValues(AValues: TStrings); begin // TODO деребанится по версии сервера и диалекта AValues.Text := GetDataTypeFB15; end; procedure TibBTDataTypePropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetDataTypeFB15) then begin inherited SetStrValue(Value); Designer.UpdateObjectInspector; end; end; { TibBTCollatePropEditor } function TibBTCollatePropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paSortList]; end; procedure TibBTCollatePropEditor.GetValues(AValues: TStrings); begin // TODO from ServerVersions and ID AValues.Text := GetCollateFB15; end; procedure TibBTCollatePropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetCollateFB15) then inherited SetStrValue(Value); end; { TibBTBlobSubTypePropEditor } function TibBTBlobSubTypePropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibBTBlobSubTypePropEditor.GetValues(AValues: TStrings); begin AValues.Text := GetBlobSubType; end; procedure TibBTBlobSubTypePropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetBlobSubType) then inherited SetStrValue(Value); end; { TibBTMechanismPropEditor } function TibBTMechanismPropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibBTMechanismPropEditor.GetValues(AValues: TStrings); begin AValues.Text := GetMechanism; end; procedure TibBTMechanismPropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetMechanism) then inherited SetStrValue(Value); end; { TibBTPrecisionPropEditor } function TibBTPrecisionPropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; function TibBTPrecisionPropEditor.GetValue: string; begin Result := IntToStr(GetOrdValue(0)); end; procedure TibBTPrecisionPropEditor.GetValues(AValues: TStrings); begin AValues.Text := GetPrecision; end; procedure TibBTPrecisionPropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetPrecision) then inherited SetOrdValue(StrToInt(Value)); end; { TibBTScalePropEditor } function TibBTScalePropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; function TibBTScalePropEditor.GetValue: string; begin Result := IntToStr(GetOrdValue(0)); end; procedure TibBTScalePropEditor.GetValues(AValues: TStrings); begin AValues.Text := GetScale; end; procedure TibBTScalePropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetScale) then inherited SetOrdValue(StrToInt(Value)); end; end.
unit ConsultaSenha; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, TFlatButtonUnit, StdCtrls, adLabelComboBox, adLabelEdit, funcsql, DB, ADODB,funcoes; type TFmSenha = class(TForm) FlatButton1: TFlatButton; FlatButton2: TFlatButton; edit: TadLabelEdit; cbUsuarios: TadLabelComboBox; Conexao: TADOConnection; cbLoja: TadLabelComboBox; cbJustificativa: TadLabelComboBox; lbMsg: TLabel; lbMsgTelaSimples: TLabel; procedure VerificaSenha(Sender:Tobject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure editKeyDown(Sender: TObject; var Key: Word; shift: TShiftState); procedure FlatButton1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure habilitaJustificativa(Sender:Tobject); function verificaErros(Sender:Tobject):string; procedure FlatButton2Click(Sender: TObject); procedure cbLojaChange(Sender: TObject); procedure desabilitaJustificativa(); procedure preparaSenhaSimples(Senha:String); procedure autorizacaoGeral(); procedure autorizacaoSimples(); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var FmSenha: TFmSenha; PERFIL:INTEGER; implementation {$R *.dfm} procedure TFmSenha.desabilitaJustificativa(); begin cbLoja.Visible := false; cbUsuarios.Visible := true; cbUsuarios.Top := 20; cbJustificativa.Visible := false; edit.Visible := true; edit.Top := cbUsuarios.Top + cbUsuarios.Height + 20; FlatButton1.top := edit.top + edit.Height + 20; FlatButton2.top := FlatButton1.top; fmSenha.ClientHeight := FlatButton1.Top + FlatButton1.Height + 30; end; procedure TFmSenha.habilitaJustificativa(Sender:Tobject); begin fmSenha.cbLoja.Visible := false; fmSenha.cbJustificativa.visible := true; cbUsuarios.Top := 20; edit.Top := 60; cbJustificativa.Top := 100; fmSenha.flatButton1.top := 130; fmSenha.flatButton2.top := flatButton1.top; fmSenha.Height := 210; end; function FEncryptDecrypt(pTexto : String; pT : String) : String; var wStr : String; wReturn : String; wLB : Integer; wS : Integer; wB : Integer; i : Integer; begin // Retornará o pTexto Encrypt ou decrypt // ptexto - String a ser (E)criptografada ou (D)descriptografada // pT - Letra (E ou D) que identifica a função a ser usada em pTexto. pT := UpperCase(pT); wStr := '0A1b2C3d4E5f6G7h8I9j10L11m12N13o14P15q16R17s18T19u20V21x22Z23'; wLB := Length(wStr); wReturn := ''; wS := 0; wB := 0; For i := 1 To Length(pTexto) do begin wB := wB Mod wLB + 1; wS := wS + Ord(wStr[wB]); If pT = 'E' Then wReturn := wReturn + Chr(Ord((pTexto[i])) + (ord(wStr[wB]) + wS) Mod 128) Else If pT = 'D' Then wReturn := wReturn + Chr(Ord((pTexto[i])) - (ord(wStr[wB]) + wS) Mod 128); result := wReturn; end; end; procedure TFmSenha.VerificaSenha(Sender: Tobject); begin modalREsult := MrOk; end; procedure TFmSenha.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = VK_Return then begin Perform (CM_DialogKey, VK_TAB, 0); key:=VK_TAB; if FlatButton1.Focused = true then FlatButton1Click(Sender); end; end; procedure TFmSenha.editKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = VK_Return then begin if cbJustificativa.Visible = false then FlatButton1.SetFocus else cbJustificativa.SetFocus; end; end; procedure TFmSenha.autorizacaoSimples; begin lbMsgTelaSimples.Visible := true; if ( UpperCase(edit.Text) = UpperCase(cbLoja.LabelDefs.Caption) ) then begin lbMsgTelaSimples.Caption := 'Ok!'; lbMsgTelaSimples.Refresh(); sleep(500); ModalResult := mrOk end else begin lbMsgTelaSimples.Caption := 'Erro!'; lbMsgTelaSimples.Refresh(); sleep(500); ModalResult := mrNo; end; end; procedure TFmSenha.autorizacaoGeral; var s1,s2:String; begin if verificaErros(nil) = '' then begin screen.Cursor := crHourglass; Conexao.Connected := true; s1:= FEncryptDecrypt(trim(copy(edit.text,01,06)), 'E') ; if cbUsuarios.ItemIndex > -1 then {P_WSEN_OPE} s2 := trim(copy( funcsql.GetValorWell( 'O','Select SN_OPE FROM DSUSU where CD_USU = ' + trim(copy(cbUsuarios.Items[cbUsuarios.Itemindex],100,10)) ,'SN_OPE' , Conexao ), 01,06)); if ( s1 <> '' ) and ( s2 <> '' ) then begin if( s1 = s2 ) then begin ModalREsult := MrOk; Conexao.Close(); end else begin funcoes.MsgTela(APPLICATION.Title,' Senha incorreta '+#13+#13 , mb_IconError + mb_ok ); edit.Text := ''; edit.SetFocus; end; end else begin funcoes.MsgTela(APPLICATION.Title,' Escolha o usuário e informe a senha ', mb_IconError + mb_ok ); ModalResult := MrCancel; end; end else funcoes.MsgTela(APPLICATION.Title, verificaErros(nil), mb_iconerror + mb_Ok ); screen.Cursor := crDefault; end; procedure TFmSenha.FormShow(Sender: TObject); begin if (FmSenha.cbUsuarios.Visible = true) then FmSenha.cbUsuarios.SetFocus; end; function TFmSenha.verificaErros(Sender: Tobject): string; var err:string; begin err:= ''; if cbUsuarios.ItemIndex < 0 then err := err + ' - Escolha um usuário para autorização' + #13; if edit.Text = '' then err := err + ' - Informe a Senha' + #13; if cbJustificativa.visible then if cbJustificativa.itemindex < 0 then err := err + ' - Informe uma justificativa' + #13; if err <> '' then err := ' Erros encontrados: ' +#13+ ERR; Result := err; end; procedure TFmSenha.FlatButton2Click(Sender: TObject); begin Conexao.Close(); FmSenha.Close; ModalResult := mrAbort; end; procedure TFmSenha.cbLojaChange(Sender: TObject); begin cbUsuarios.Items := funcsql.getUsuariosPorLoja(Conexao, trim(copy(fmSenha.cbLoja.Items[fmSenha.cbLoja.Itemindex],50,10)) ); end; procedure TFmSenha.preparaSenhaSimples(Senha:String); begin cbLoja.Visible := false; cbJustificativa.Visible := false; cbUsuarios.Visible := false; cbUsuarios.Items.Add('--------------'); cbUsuarios.ItemIndex := 0; edit.Top := cbLoja.Top; cbLoja.LabelDefs.Caption := senha; with FlatButton2 do begin Caption := ''; Width := 20; top := cbUsuarios.Top -15; Left := (edit.Width + edit.Left) - FlatButton2.Width; end; with FlatButton1 do begin Caption := ''; Width := 20; top := FlatButton2.Top ; Left := FlatButton2.Left - Width - 10; end; PERFIL := 2; FmSenha.ClientHeight := FlatButton1.Top + FlatButton1.Height + 20; end; procedure TFmSenha.FlatButton1Click(Sender: TObject); begin if (PERFIL = 2) then autorizacaoSimples() else autorizacaoGeral(); end; procedure TFmSenha.FormClose(Sender: TObject; var Action: TCloseAction); begin Conexao.Close(); action := CaFree; end; end.
unit Lib.JSONUtils; interface uses System.Types, System.SysUtils, System.Classes, System.JSON; function JSONValueToInt(AValue: TJSONValue; Default: Integer=0): Integer; function JSONAddPairObject(jsObject: TJSONObject; const Name: string): TJSONObject; procedure JSONSetPairValue(jsPair: TJSONPair; jsValue: TJSONValue); procedure JSONClearPairValue(jsPair: TJSONPair); function JSONRectToObject(const Rect: TRect): TJSONObject; function JSONObjectToRect(jsRect: TJSONObject; const Default: TRect): TRect; procedure JSONSetRect(jsRect: TJSONObject; const Rect: TRect); function JSONStringsToArray(Strings: TStrings): TJSONArray; function JSONForceObject(const Path: string; jsRoot: TJSONObject; Created: Boolean): TJSONObject; function JSONTryGetObject(jsRoot: TJSONObject; const Name: string; out jsObject: TJSONObject; out PairName: string; Created: Boolean): Boolean; procedure JSONSetValue(jsRoot: TJSONObject; const Name: string; jsValue: TJSONValue); implementation function JSONValueToInt(AValue: TJSONValue; Default: Integer=0): Integer; begin Result:=Default; if Assigned(AValue) then Result:=AValue.GetValue<Integer>; end; function JSONAddPairObject(jsObject: TJSONObject; const Name: string): TJSONObject; begin if not jsObject.TryGetValue(Name,Result) then begin Result:=TJSONObject.Create; jsObject.AddPair(Name,Result); end; end; {$IF CompilerVersion > 29.0} // > XE8 procedure JSONSetPairValue(jsPair: TJSONPair; jsValue: TJSONValue); begin if Assigned(jsValue) then jsPair.JsonValue:=jsValue; end; {$ELSE} procedure JSONSetPairValue(jsPair: TJSONPair; jsValue: TJSONValue); begin if Assigned(jsValue) then begin jsPair.JsonValue.Free; jsPair.JsonValue:=jsValue; end; end; {$ENDIF} procedure JSONClearPairValue(jsPair: TJSONPair); begin if jsPair.JsonValue is TJSONObject then JSONSetPairValue(jsPair,TJSONObject.Create) else if jsPair.JsonValue is TJSONArray then JSONSetPairValue(jsPair,TJSONArray.Create); end; function JSONRectToObject(const Rect: TRect): TJSONObject; begin Result:=TJSONObject.Create; Result.AddPair('left',TJSONNumber.Create(Rect.Left)); Result.AddPair('top',TJSONNumber.Create(Rect.Top)); Result.AddPair('right',TJSONNumber.Create(Rect.Right)); Result.AddPair('bottom',TJSONNumber.Create(Rect.Bottom)); end; function JSONObjectToRect(jsRect: TJSONObject; const Default: TRect): TRect; begin Result:=Rect( JSONValueToInt(jsRect.Values['left'],Default.Left), JSONValueToInt(jsRect.Values['top'],Default.Top), JSONValueToInt(jsRect.Values['right'],Default.Right), JSONValueToInt(jsRect.Values['bottom'],Default.Bottom)); end; procedure JSONSetRect(jsRect: TJSONObject; const Rect: TRect); begin JSONSetValue(jsRect,'left',TJSONNumber.Create(Rect.Left)); JSONSetValue(jsRect,'top',TJSONNumber.Create(Rect.Top)); JSONSetValue(jsRect,'right',TJSONNumber.Create(Rect.Right)); JSONSetValue(jsRect,'bottom',TJSONNumber.Create(Rect.Bottom)); end; function JSONStringsToArray(Strings: TStrings): TJSONArray; var S: string; begin Result:=nil; for S in Strings do begin if not Assigned(Result) then Result:=TJSONArray.Create; Result.Add(S); end; end; function JSONForceObject(const Path: string; jsRoot: TJSONObject; Created: Boolean): TJSONObject; var I: Integer; begin if not jsRoot.TryGetValue(Path,Result) then if Created then begin I:=Path.IndexOf('.'); if I=-1 then Result:=JSONAddPairObject(jsRoot,Path) else Result:=JSONForceObject(Path.Substring(I+1),JSONAddPairObject(jsRoot,Path.Substring(0,I)),True); end else Result:=nil; end; function JSONTryGetObject(jsRoot: TJSONObject; const Name: string; out jsObject: TJSONObject; out PairName: string; Created: Boolean): Boolean; var I: Integer; begin I:=Name.LastIndexOf('.'); if I=-1 then begin jsObject:=jsRoot; PairName:=Name; Result:=True; end else begin jsObject:=JSONForceObject(Name.Substring(0,I),jsRoot,Created); PairName:=Name.Substring(I+1); Result:=Assigned(jsObject); end; end; function JSONTryGetPair(jsObject: TJSONObject; const PairName: string; out jsObjectPair: TJSONPair): Boolean; var jsPair: TJSONPair; begin Result:=False; for jsPair in jsObject do if jsPair.JsonString.Value=PairName then begin jsObjectPair:=jsPair; Exit(True); end; end; procedure JSONSetValue(jsRoot: TJSONObject; const Name: string; jsValue: TJSONValue); var jsObject: TJSONObject; PairName: string; jsPair: TJSONPair; begin if JSONTryGetObject(jsRoot,Name,jsObject,PairName,Assigned(jsValue)) then if JSONTryGetPair(jsObject,PairName,jsPair) then if Assigned(jsValue) then JSONSetPairValue(jsPair,jsValue) else JSONClearPairValue(jsPair) else if Assigned(jsValue) then jsObject.AddPair(PairName,jsValue); end; end.
unit AddManBonusRemoveUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, GoodFunctionsUnit, DtManBonusItemsUnit; type TAddManBonusRemoveForm = class(TForm) Label9: TLabel; DateRemove: TDateTimePicker; Label10: TLabel; NumItemEdit: TEdit; SelectNumItemButton: TButton; OkButton: TBitBtn; CancelButton: TBitBtn; procedure OkButtonClick(Sender: TObject); procedure SelectNumItemButtonClick(Sender: TObject); private { Private declarations } public id_order: Integer; end; var AddManBonusRemoveForm: TAddManBonusRemoveForm; implementation {$R *.dfm} procedure TAddManBonusRemoveForm.OkButtonClick(Sender: TObject); begin if not CheckForFill(NumItemEdit, 'пункт наказу') then exit; ModalResult := mrOk; end; procedure TAddManBonusRemoveForm.SelectNumItemButtonClick(Sender: TObject); var form: TDtManBonusItemsForm; begin Form := TDtManBonusItemsForm.Create(self); Form.id_order := ID_ORDER; Form.aID_TYPE := 1; Form.Prepare; if Form.ShowModal = mrOk then begin NumItemEdit.Text := IntToStr(form.ResultQueryNUM_ITEM.Value); end; Form.Free; end; end.
(* Parser 03.05.17 *) (* Syntax Analysator (scanner) UE6 *) UNIT Parser; INTERFACE VAR success: BOOLEAN; PROCEDURE S; PROCEDURE InitParser(outputFileName: STRING; ok: BOOLEAN); IMPLEMENTATION USES Lex; VAR outputFile : TEXT; tab : STRING; TYPE Mode = (printTitle, printHead, printEnd, printCurlyBegin, printCurlyEnd, printCompBegin, printOpt, printCompEnd, printIsNotSy, printNonTerminal, printTerminal); (* Init parser with the file to write to*) PROCEDURE InitParser(outputFileName: STRING; ok: BOOLEAN); BEGIN Assign(outputFile, outputFileName); {$I-} Rewrite(outputFile); {$I+} ok := IOResult = 0; END; (* tab control *) PROCEDURE IncTab; BEGIN tab := tab + ' '; END; PROCEDURE DecTab; BEGIN Delete(tab, Length(tab)-1, 2); END; (* Check sy; returns false if sy is not expected sy *) FUNCTION SyIsNot(expectedSy: SymbolCode): BOOLEAN; BEGIN success := success AND (sy = expectedSy); SyIsNot := NOT success; END; (* write pascal syntax to outputfile *) PROCEDURE WritePas(m: Mode; msg: STRING); BEGIN CASE m OF printTitle: BEGIN WriteLn(outputFile, '(* PARSER Generated *)'); END; printHead: BEGIN tab := ' '; WriteLn(outputFile, 'PROCEDURE ', msg, ';'); WriteLn(outputFile, 'BEGIN'); END; printEnd: BEGIN DecTab; WriteLn(outputFile, 'END;'); END; printCurlyBegin: BEGIN WriteLn(outputFile, tab, 'WHILE sy = .... DO BEGIN'); IncTab; END; printCurlyEnd: BEGIN DecTab; WriteLn(outputFile, tab, 'END;'); END; printCompBegin: BEGIN WriteLn(outputFile, tab, 'IF sy = .... THEN BEGIN'); IncTab; END; printOpt: BEGIN DecTab; WriteLn(outputFile, tab, 'END ELSE'); END; printCompEnd: BEGIN IncTab; WriteLn(outputFile, tab, 'success := FALSE'); END; printIsNotSy: BEGIN WriteLn(outputFile,'FUNCTION SyIsNot(expectedSy: Symbol):', 'BOOLEAN;'); WriteLn(outputFile,'BEGIN'); WriteLn(outputFile,' success:= success AND (sy = expectedSy);'); WriteLn(outputFile,' SyIsNot := NOT success;'); WriteLn(outputFile,'END;'); WriteLn(outputFile); END; printNonTerminal: BEGIN WriteLn(outputFile, tab, msg, '; IF NOT success THEN EXIT;'); END; printTerminal: BEGIN WriteLn(outputFile, tab, 'IF SyIsNot(', msg, 'Sy) THEN EXIT;'); WriteLn(outputFile, tab, 'NewSy;'); END; END; END; (*======== PARSER ========*) PROCEDURE Seq; FORWARD; PROCEDURE Stat; FORWARD; PROCEDURE Fact; FORWARD; PROCEDURE S; BEGIN success := TRUE; Seq; IF NOT success OR SyIsNot(eofSy) THEN BEGIN WriteLn('----- Error ------'); WriteLn('Error in line ', syLnr, ' at position ', syCnr) END ELSE WriteLn('Finished writing to output file'); WriteLn('Sucessfully parsed'); Close(outputFile); END; PROCEDURE Seq; BEGIN WriteLn('Creating output..'); WritePas(printTitle, ''); WritePas(printIsNotSy, ''); WHILE sy <> eofSy DO BEGIN IF SyIsNot(identSy) THEN EXIT; WritePas(printHead, identStr); NewSy; IF SyIsNot(equalsSy) THEN EXIT; NewSy; Stat; IF NOT success THEN EXIT; IF SyIsNot(periodSy) THEN EXIT; NewSy; WritePas(printEnd, ''); WriteLn(outputFile); END; END; PROCEDURE Stat; BEGIN Fact; IF NOT success THEN EXIT; WHILE (sy = identSy) OR (sy = optSy) OR (sy = leftCompSy) OR (sy = leftCurlySy) OR (sy = leftParSy) DO BEGIN Fact; IF NOT success THEN EXIT; END; END; PROCEDURE Fact; BEGIN CASE sy OF identSy: BEGIN (* term or non-term symbol check *) IF identStr[1] IN ['A'..'Z'] THEN WritePas(printNonTerminal, identStr) ELSE WritePas(printTerminal, identStr); NewSy; END; optSy: BEGIN WritePas(printOpt, ''); WritePas(printCompBegin, ''); NewSy; END; leftCompSy: BEGIN NewSy; WritePas(printCompBegin, ''); Stat; IF NOT success THEN EXIT; IF sy <> rightCompSy THEN BEGIN success := FALSE; EXIT; END; WritePas(printOpt, ''); WritePas(printCompEnd, ''); NewSy; END; leftCurlySy: BEGIN NewSy; WritePas(printCurlyBegin, ''); Stat; IF NOT success THEN EXIT; IF sy <> rightCurlySy THEN BEGIN success := FALSE; EXIT; END; WritePas(printCurlyEnd, ''); NewSy; END; leftParSy: BEGIN NewSy; Stat; IF NOT success THEN EXIT; IF sy <> rightParSy THEN BEGIN success := FALSE; EXIT; END; NewSy; END; END; END; BEGIN tab := ''; END.
(* Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED Original name: 0147.PAS Description: Pentium FDIV Errors Author: BOB SWART Date: 05-26-95 23:20 *) { From: bobs@dragons.nest.nl (Bob Swart) On the BPASCAL forum on CompuServe, DJ Murdoch [71631,122] reported something that isn't a Borland bug, but looks as though it'll affect BP programs when they run on a Pentium: 64. For certain very rare pairs x and y, a $N+ division x/y will only be accurate to about 4 decimal digits when calculated on a Pentium produced before Fall 1994. Dr. Bob's further detailed analysis resulted in the following function which will generate 11 series of infinite "buggy" numbers for which the following does not hold on a Pentium chip (a reciprocal of a reciprocal): x = 1/1/x Try it on a Pentium with for example the magic number... 357914069 I also found that a power of 2 times any number that goes wrong also goes wrong (i.e. X, 2*X, 4*X, 8*X, etc). Also, once you've found a "wrong number" (and the serie), you can start a new serie by multiplying with 4 and adding 383 (= 256 + 128 - 1). Below follows a general function that is able to produce 11 series of (just about infinite) numbers that generate incorrect results. Note that the initial difference (for the first digit in a serie) is 21 1/3, and the difference increases with the same power of two as the original number... } {* N+,E- *} program DrBob5; { Digits found in one night (source for analysis): 357914069, 715828138, 1431656276, 1431655893 (new series = 4 * X - 383 ) } function PentiumBug(Const Serie,Index: Word): Extended; { Serie max = 11 } Const Magic = 357914069; Factor= 256 + 128 - 1; var tmp: Extended; i: Integer; begin tmp := Magic; for i:=2 to Serie do tmp := 4.0 * tmp - Factor; for i:=2 to Index do tmp := tmp + tmp; PentiumBug := tmp end {PentiumBug}; var i,j: Integer; x,y,z: Double; begin for i:=1 to 11 do begin for j:=1 to 16 do begin x := PentiumBug(i,j); y := 1 / x; z := 1 / y; { z should be x, but isn't... } writeln('x = ',x:12:0,' 1/x =',y,' 1/1/x = ',z:12:0,' diff ',x-z:5:0) end; writeln end end. { The bug is in the FDIV instruction, which for about 1 in 10^10 pairs of randomly chosen divisors suffers a catastrophic loss of precision, ending up accurate to 4 to 6 digits instead of the usual 18. Apparently Intel chose a division algorithm which is fast but which isn't 100% guaranteed to work. I still don't know why the difference is 0 again starting with the 12th serie, but I'm sure given enough time I can reproduce the exact buggy FDIV algorithm Intel uses... }
unit UMenu; interface uses UIState, Vcl.Forms, Vcl.StdCtrls; type TMenu1 = class(TInterfacedObject, IState) private label1: Tlabel; published constructor create(AOwner: TForm); public procedure destroy; end; implementation { Menu } constructor TMenu1.create(AOwner: TForm); begin // название в меню label1 := Tlabel.create(AOwner); Label1.Font.Height:=-20; Label1.Font.Name:='Tahoma'; Label1.Left:=64; Label1.Top:=144; label1.Parent := AOwner; label1.caption := 'Численные методы оптимизации'; end; procedure TMenu1.destroy; begin label1.Free; end; end.
// // Generated by JavaToPas v1.5 20150830 - 104031 //////////////////////////////////////////////////////////////////////////////// unit android.widget.RadioGroup; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Util, android.widget.RadioGroup_LayoutParams, android.widget.LinearLayout_LayoutParams, android.view.accessibility.AccessibilityEvent, android.view.accessibility.AccessibilityNodeInfo; type JRadioGroup_OnCheckedChangeListener = interface; // merged JRadioGroup = interface; JRadioGroupClass = interface(JObjectClass) ['{12D0ECB9-D3DF-4799-B52C-0C55DE08344A}'] function generateLayoutParams(attrs : JAttributeSet) : JRadioGroup_LayoutParams; cdecl;// (Landroid/util/AttributeSet;)Landroid/widget/RadioGroup$LayoutParams; A: $1 function getCheckedRadioButtonId : Integer; cdecl; // ()I A: $1 function init(context : JContext) : JRadioGroup; cdecl; overload; // (Landroid/content/Context;)V A: $1 function init(context : JContext; attrs : JAttributeSet) : JRadioGroup; cdecl; overload;// (Landroid/content/Context;Landroid/util/AttributeSet;)V A: $1 procedure addView(child : JView; &index : Integer; params : JViewGroup_LayoutParams) ; cdecl;// (Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V A: $1 procedure check(id : Integer) ; cdecl; // (I)V A: $1 procedure clearCheck ; cdecl; // ()V A: $1 procedure onInitializeAccessibilityEvent(event : JAccessibilityEvent) ; cdecl;// (Landroid/view/accessibility/AccessibilityEvent;)V A: $1 procedure onInitializeAccessibilityNodeInfo(info : JAccessibilityNodeInfo) ; cdecl;// (Landroid/view/accessibility/AccessibilityNodeInfo;)V A: $1 procedure setOnCheckedChangeListener(listener : JRadioGroup_OnCheckedChangeListener) ; cdecl;// (Landroid/widget/RadioGroup$OnCheckedChangeListener;)V A: $1 procedure setOnHierarchyChangeListener(listener : JViewGroup_OnHierarchyChangeListener) ; cdecl;// (Landroid/view/ViewGroup$OnHierarchyChangeListener;)V A: $1 end; [JavaSignature('android/widget/RadioGroup$OnCheckedChangeListener')] JRadioGroup = interface(JObject) ['{B9DE6DDA-0E66-497B-AAB9-85CE580A9DAE}'] function generateLayoutParams(attrs : JAttributeSet) : JRadioGroup_LayoutParams; cdecl;// (Landroid/util/AttributeSet;)Landroid/widget/RadioGroup$LayoutParams; A: $1 function getCheckedRadioButtonId : Integer; cdecl; // ()I A: $1 procedure addView(child : JView; &index : Integer; params : JViewGroup_LayoutParams) ; cdecl;// (Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V A: $1 procedure check(id : Integer) ; cdecl; // (I)V A: $1 procedure clearCheck ; cdecl; // ()V A: $1 procedure onInitializeAccessibilityEvent(event : JAccessibilityEvent) ; cdecl;// (Landroid/view/accessibility/AccessibilityEvent;)V A: $1 procedure onInitializeAccessibilityNodeInfo(info : JAccessibilityNodeInfo) ; cdecl;// (Landroid/view/accessibility/AccessibilityNodeInfo;)V A: $1 procedure setOnCheckedChangeListener(listener : JRadioGroup_OnCheckedChangeListener) ; cdecl;// (Landroid/widget/RadioGroup$OnCheckedChangeListener;)V A: $1 procedure setOnHierarchyChangeListener(listener : JViewGroup_OnHierarchyChangeListener) ; cdecl;// (Landroid/view/ViewGroup$OnHierarchyChangeListener;)V A: $1 end; TJRadioGroup = class(TJavaGenericImport<JRadioGroupClass, JRadioGroup>) end; // Merged from: .\android.widget.RadioGroup_OnCheckedChangeListener.pas JRadioGroup_OnCheckedChangeListenerClass = interface(JObjectClass) ['{FBF351CF-B63B-4007-A526-6CFEB8BB088F}'] procedure onCheckedChanged(JRadioGroupparam0 : JRadioGroup; Integerparam1 : Integer) ; cdecl;// (Landroid/widget/RadioGroup;I)V A: $401 end; [JavaSignature('android/widget/RadioGroup_OnCheckedChangeListener')] JRadioGroup_OnCheckedChangeListener = interface(JObject) ['{0E6702B1-548D-409F-889B-38F6993C6EA9}'] procedure onCheckedChanged(JRadioGroupparam0 : JRadioGroup; Integerparam1 : Integer) ; cdecl;// (Landroid/widget/RadioGroup;I)V A: $401 end; TJRadioGroup_OnCheckedChangeListener = class(TJavaGenericImport<JRadioGroup_OnCheckedChangeListenerClass, JRadioGroup_OnCheckedChangeListener>) end; implementation end.
unit Objekt.DHLShipmentorderResponseList; interface uses System.SysUtils, System.Classes, Objekt.DHLShipmentorderResponse, Objekt.DHLBaseList, System.Contnrs; type TDHLShipmentorderResponseList = class(TDHLBaseList) private fShipmentorderResponse: TDHLShipmentorderResponse; fStatusText: string; fStatusCode: Integer; fStatusMessageText: string; function getShipmentorderResponse(Index: Integer): TDHLShipmentorderResponse; public constructor Create; override; destructor Destroy; override; property Item[Index: Integer]: TDHLShipmentorderResponse read getShipmentorderResponse; function Add: TDHLShipmentorderResponse; property StatusText: string read fStatusText write fStatusText; property StatusCode: Integer read fStatusCode write fStatusCode; property StatusMessage: string read fStatusMessageText write fStatusMessageText; end; implementation { TDHLShipmentorderResponseList } constructor TDHLShipmentorderResponseList.Create; begin inherited; end; destructor TDHLShipmentorderResponseList.Destroy; begin inherited; end; function TDHLShipmentorderResponseList.getShipmentorderResponse(Index: Integer): TDHLShipmentorderResponse; begin Result := nil; if Index > fList.Count -1 then exit; Result := TDHLShipmentorderResponse(fList[Index]); end; function TDHLShipmentorderResponseList.Add: TDHLShipmentorderResponse; begin fShipmentorderResponse := TDHLShipmentorderResponse.Create; fList.Add(fShipmentorderResponse); Result := fShipmentorderResponse; end; end.
unit UnitInstalledApplications; interface uses windows; function ListarProgramasInstalados: widestring; implementation uses UnitConstantes; function RegReadString(Key: HKey; SubKey: widestring; DataType: integer; Data: widestring): widestring; var RegKey: HKey; Buffer: array[0..9999] of WideChar; BufSize: Integer; begin BufSize := SizeOf(Buffer); Result := ''; if RegOpenKeyW(Key,pwidechar(SubKey),RegKey) = ERROR_SUCCESS then begin; if RegQueryValueExW(RegKey, pwidechar(Data), nil, @DataType, @Buffer, @BufSize) = ERROR_SUCCESS then begin; RegCloseKey(RegKey); Result := widestring(Buffer); end; end; end; function _regEnumKeys(hkKey: HKEY; lpSubKey: PWideChar): widestring; var dwIndex, lpcbName: DWORD; phkResult: HKEY; lpName: Array[0..MAX_PATH * 2] of WideChar; begin Result := ''; if RegOpenKeyExW(hkKey, lpSubKey, 0, KEY_READ, phkResult) = ERROR_SUCCESS then begin dwIndex := 0; lpcbName := sizeof(lpName); ZeroMemory(@lpName, sizeof(lpName)); while RegEnumKeyExW(phkResult, dwIndex, @lpName, lpcbName, nil, nil, nil, nil) <> ERROR_NO_MORE_ITEMS do begin Result := Result + RegReadString(HKEY_LOCAL_MACHINE,'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\' + lpName + '\',REG_SZ,'DisplayName') ; Result := Result + delimitadorComandos; Result := Result + RegReadString(HKEY_LOCAL_MACHINE,'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\' + lpName + '\',REG_SZ,'DisplayVersion') ; Result := Result + delimitadorComandos; Result := Result + RegReadString(HKEY_LOCAL_MACHINE,'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\' + lpName + '\',REG_SZ,'Publisher') ; Result := Result + delimitadorComandos; Result := Result + RegReadString(HKEY_LOCAL_MACHINE,'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\' + lpName + '\',REG_SZ,'UninstallString') ; Result := Result + delimitadorComandos; Result := Result + RegReadString(HKEY_LOCAL_MACHINE,'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\' + lpName + '\',REG_SZ,'QuietUninstallString') ; Result := Result + delimitadorComandos + #13#10; ZeroMemory(@lpName, sizeof(lpName)); lpcbName := sizeof(lpName); inc(dwIndex); end; RegCloseKey(phkResult); end; end; function ListarProgramasInstalados: widestring; begin result := _regEnumKeys(HKEY_LOCAL_MACHINE,'software\microsoft\windows\currentversion\uninstall\'); end; end.
unit uImportPicturesUtils; interface uses System.DateUtils, System.SysUtils, Dmitry.Utils.System, Dmitry.PathProviders, Dmitry.PathProviders.FileSystem, CCR.Exif, uConstants, uMemory, uExplorerPortableDeviceProvider, uRawExif, uAssociations, uDateUtils, uStringUtils, uExifUtils; function FormatPath(Patern: string; Date: TDate; ItemsLabel: string): string; function GetImageDate(PI: TPathItem): TDateTime; implementation function FormatPath(Patern: string; Date: TDate; ItemsLabel: string): string; var SR: TStringReplacer; begin SR := TStringReplacer.Create(Patern); try SR.CaseSencetive := True; SR.AddPattern('''LABEL''', IIF(ItemsLabel = '', '', '''' + ItemsLabel + '''')); SR.AddPattern('[LABEL]', IIF(ItemsLabel = '', '', '[' + ItemsLabel + ']')); SR.AddPattern('(LABEL)', IIF(ItemsLabel = '', '', '(' + ItemsLabel + ')')); SR.AddPattern('LABEL', ItemsLabel); SR.AddPattern('YYYY', FormatDateTime('yyyy', Date)); SR.AddPattern('YY', FormatDateTime('yy', Date)); SR.AddPattern('mmmm', MonthToString(Date, 'Date')); SR.AddPattern('MMMM', UpperCaseFirstLetter(MonthToString(Date, 'Date'))); SR.AddPattern('mmm', MonthToString(Date, 'Month')); SR.AddPattern('MMM', UpperCaseFirstLetter(MonthToString(Date, 'Month'))); SR.AddPattern('MM', FormatDateTime('mm', Date)); SR.AddPattern('M', FormatDateTime('M', Date)); SR.AddPattern('DDD', UpperCaseFirstLetter(WeekDayToString(Date))); SR.AddPattern('ddd', WeekDayToString(Date)); SR.AddPattern('DD', FormatDateTime('dd', Date)); SR.AddPattern('D', FormatDateTime('d', Date)); Result := SR.Result; finally F(SR); end; end; function GetImageDate(PI: TPathItem): TDateTime; var RAWExif: TRAWExif; ExifData: TExifData; begin Result := MinDateTime; if PI is TPortableFSItem then Result := TPortableImageItem(PI).Date else if PI is TFileItem then begin Result := TFileItem(PI).TimeStamp; if IsGraphicFile(PI.Path) then begin if IsRAWImageFile(PI.Path) then begin RAWExif := TRAWExif.Create; try RAWExif.LoadFromFile(PI.Path); if RAWExif.IsEXIF then Result := DateOf(RAWExif.TimeStamp); finally F(RAWExif); end; end else begin ExifData := TExifData.Create; try ExifData.LoadFromGraphic(PI.Path); if not ExifData.Empty and (ExifData.ImageDateTime > 0) and (YearOf(ExifData.ImageDateTime) > cMinEXIFYear) then Result := DateOf(ExifData.ImageDateTime); finally F(ExifData); end; end; end; end; end; end.
// Given a sequence of numbers, construct a natural number having its digits in // reverse order. uses SysUtils; type IntegerArray = array of Integer; function makeInteger(xs: IntegerArray): Integer; var i, n, m: Integer; begin n := 0; m := 1; for i := 0 to Length(xs) - 1 do begin n := n + xs[i] * m; m := m * 10; end; Result := n; end; function readArray(xs: IntegerArray): IntegerArray; var i: Integer; s: String; begin i := 0; while True do begin Readln(s); if (s = 'done') then break else begin SetLength(xs, i+1); xs[i] := StrToInt(s); i := i+1; end; end; Result := xs; end; var n: Integer; xs: IntegerArray; begin Writeln('Enter some natural numbers (''done'' to stop):'); xs := readArray(xs); n := makeInteger(xs); writeln(n); end.
{******************************************************************************* Title: T2Ti ERP Description: Controller relacionado à tabela [NFCE_OPERADOR] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> Albert Eije (T2Ti.COM) @version 2.0 *******************************************************************************} unit NfceOperadorController; interface uses Classes, SysUtils, Windows, Forms, Controller, VO, NfceOperadorVO; type TNfceOperadorController = class(TController) private public class function ConsultaLista(pFiltro: String): TListaNfceOperadorVO; class function ConsultaObjeto(pFiltro: String): TNfceOperadorVO; class function Usuario(pLogin, pSenha: String): TNfceOperadorVO; end; implementation uses T2TiORM; var ObjetoLocal: TNfceOperadorVO; class function TNfceOperadorController.ConsultaLista(pFiltro: String): TListaNfceOperadorVO; begin try ObjetoLocal := TNfceOperadorVO.Create; Result := TListaNfceOperadorVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TNfceOperadorController.ConsultaObjeto(pFiltro: String): TNfceOperadorVO; begin try Result := TNfceOperadorVO.Create; Result := TNfceOperadorVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); finally end; end; class function TNfceOperadorController.Usuario(pLogin, pSenha: String): TNfceOperadorVO; var Filtro: String; begin try Filtro := 'LOGIN = '+QuotedStr(pLogin)+' AND SENHA = '+QuotedStr(pSenha); Result := TNfceOperadorVO.Create; Result := TNfceOperadorVO(TT2TiORM.ConsultarUmObjeto(Result, Filtro, True)); finally end; end; end.
unit ModflowFmpSoilUnit; interface uses OrderedCollectionUnit, ModflowBoundaryUnit, SysUtils, Classes, ModflowFmpBaseClasses; type TSoilType = (stSandyLoam, stSilt, stSiltyClay, stOther); TSoilItem = class(TCustomZeroFarmItem) private const CapillaryFringePosition = 0; ACoeffPosition = 1; BCoeffPosition = 2; CCoeffPosition = 3; DCoeffPosition = 4; ECoeffPosition = 5; var FSoilName: string; FSoilType: TSoilType; function GetACoeff: string; function GetBCoeff: string; function GetCapillaryFringe: string; function GetCCoeff: string; function GetDCoeff: string; function GetECoeff: string; procedure SetACoeff(const Value: string); procedure SetBCoeff(const Value: string); procedure SetCapillaryFringe(const Value: string); procedure SetCCoeff(const Value: string); procedure SetDCoeff(const Value: string); procedure SetECoeff(const Value: string); procedure SetSoilName(Value: string); procedure SetSoilType(const Value: TSoilType); protected // See @link(BoundaryFormula). function GetBoundaryFormula(Index: integer): string; override; // See @link(BoundaryFormula). procedure SetBoundaryFormula(Index: integer; const Value: string); override; function BoundaryFormulaCount: integer; override; // @name checks whether AnotherItem is the same as the current @classname. function IsSame(AnotherItem: TOrderedItem): boolean; override; procedure SetIndex(Value: Integer); override; public procedure Assign(Source: TPersistent); override; destructor Destroy; override; published property SoilName: string read FSoilName write SetSoilName; property SoilType: TSoilType read FSoilType write SetSoilType; property CapillaryFringe: string read GetCapillaryFringe write SetCapillaryFringe; property ACoeff: string read GetACoeff write SetACoeff; property BCoeff: string read GetBCoeff write SetBCoeff; property CCoeff: string read GetCCoeff write SetCCoeff; property DCoeff: string read GetDCoeff write SetDCoeff; property ECoeff: string read GetECoeff write SetECoeff; end; TSoilRecord = record SoilID: integer; SoilType: TSoilType; CapillaryFringe: double; ACoeff: double; BCoeff: double; CCoeff: double; DCoeff: double; ECoeff: double; end; TSoilArray = array of TSoilRecord; TSoilCollection = class(TCustomFarmCollection) private FSoilArray: TSoilArray; function GetItems(Index: Integer): TSoilItem; procedure SetItems(Index: Integer; const Value: TSoilItem); protected class function ItemClass: TBoundaryItemClass; override; procedure DeleteItemsWithZeroDuration; override; public property SoilArray: TSoilArray read FSoilArray; property Items[Index: Integer]: TSoilItem read GetItems write SetItems; default; procedure EvaluateSoils; end; implementation uses PhastModelUnit, ModflowPackageSelectionUnit, RbwParser, frmFormulaErrorsUnit, GoPhastTypes; resourcestring StrSoilVariable = 'Soil Variable'; //const // CapillaryFringePosition = 0; // ACoeffPosition = 1; // BCoeffPosition = 2; // CCoeffPosition = 3; // DCoeffPosition = 4; // ECoeffPosition = 5; { TSoilItem } procedure TSoilItem.Assign(Source: TPersistent); var SourceItem: TSoilItem; begin if Source is TSoilItem then begin SourceItem := TSoilItem(Source); SoilName := SourceItem.SoilName; SoilType := SourceItem.SoilType; end; inherited; end; function TSoilItem.BoundaryFormulaCount: integer; begin result := 6 end; destructor TSoilItem.Destroy; var LocalModel: TPhastModel; Position: integer; begin if (Model <> nil) and (SoilName <> '') then begin LocalModel := Model as TPhastModel; Position := LocalModel.GlobalVariables.IndexOfVariable(SoilName); if Position >= 0 then begin LocalModel.GlobalVariables.Delete(Position); end; end; inherited; end; function TSoilItem.GetACoeff: string; begin Result := FFormulaObjects[ACoeffPosition].Formula; ResetItemObserver(ACoeffPosition); end; function TSoilItem.GetBCoeff: string; begin Result := FFormulaObjects[BCoeffPosition].Formula; ResetItemObserver(BCoeffPosition); end; function TSoilItem.GetBoundaryFormula(Index: integer): string; begin case Index of CapillaryFringePosition: result := CapillaryFringe; ACoeffPosition: result := ACoeff; BCoeffPosition: result := BCoeff; CCoeffPosition: result := CCoeff; DCoeffPosition: result := DCoeff; ECoeffPosition: result := ECoeff; else Assert(False); end; end; function TSoilItem.GetCapillaryFringe: string; begin Result := FFormulaObjects[CapillaryFringePosition].Formula; ResetItemObserver(CapillaryFringePosition); end; function TSoilItem.GetCCoeff: string; begin Result := FFormulaObjects[CCoeffPosition].Formula; ResetItemObserver(CCoeffPosition); end; function TSoilItem.GetDCoeff: string; begin Result := FFormulaObjects[DCoeffPosition].Formula; ResetItemObserver(DCoeffPosition); end; function TSoilItem.GetECoeff: string; begin Result := FFormulaObjects[ECoeffPosition].Formula; ResetItemObserver(ECoeffPosition); end; function TSoilItem.IsSame(AnotherItem: TOrderedItem): boolean; var OtherItem: TSoilItem; begin Result := (AnotherItem is TSoilItem) and inherited IsSame(AnotherItem); if Result then begin OtherItem := TSoilItem(AnotherItem); result := (SoilName = OtherItem.SoilName) and (SoilType = OtherItem.SoilType) end; end; procedure TSoilItem.SetACoeff(const Value: string); begin if FFormulaObjects[ACoeffPosition].Formula <> Value then begin UpdateFormula(Value, ACoeffPosition, FFormulaObjects[ACoeffPosition]); end; end; procedure TSoilItem.SetBCoeff(const Value: string); begin if FFormulaObjects[BCoeffPosition].Formula <> Value then begin UpdateFormula(Value, BCoeffPosition, FFormulaObjects[BCoeffPosition]); end; end; procedure TSoilItem.SetBoundaryFormula(Index: integer; const Value: string); begin case Index of CapillaryFringePosition: CapillaryFringe := Value; ACoeffPosition: ACoeff := Value; BCoeffPosition: BCoeff := Value; CCoeffPosition: CCoeff := Value; DCoeffPosition: DCoeff := Value; ECoeffPosition: ECoeff := Value; else Assert(False); end; end; procedure TSoilItem.SetCapillaryFringe(const Value: string); begin if FFormulaObjects[CapillaryFringePosition].Formula <> Value then begin UpdateFormula(Value, CapillaryFringePosition, FFormulaObjects[CapillaryFringePosition]); end; end; procedure TSoilItem.SetCCoeff(const Value: string); begin if FFormulaObjects[CCoeffPosition].Formula <> Value then begin UpdateFormula(Value, CCoeffPosition, FFormulaObjects[CCoeffPosition]); end; end; procedure TSoilItem.SetDCoeff(const Value: string); begin if FFormulaObjects[DCoeffPosition].Formula <> Value then begin UpdateFormula(Value, DCoeffPosition, FFormulaObjects[DCoeffPosition]); end; end; procedure TSoilItem.SetECoeff(const Value: string); begin if FFormulaObjects[ECoeffPosition].Formula <> Value then begin UpdateFormula(Value, ECoeffPosition, FFormulaObjects[ECoeffPosition]); end; end; procedure TSoilItem.SetIndex(Value: Integer); var ChangeGlobals: TDefineGlobalObject; begin if {(Index <> Value) and} (Model <> nil) and (FSoilName <> '') then begin ChangeGlobals := TDefineGlobalObject.Create(Model, FSoilName, FSoilName, StrSoilVariable); try ChangeGlobals.SetValue(Value+1); finally ChangeGlobals.Free; end; end; inherited; end; procedure TSoilItem.SetSoilName(Value: string); var ChangeGlobals: TDefineGlobalObject; begin if (FSoilName <> Value) and (Model <> nil) and not (csReading in Model.ComponentState) then begin Value := GenerateNewName(Value, nil, '_'); end; ChangeGlobals := TDefineGlobalObject.Create(Model, FSoilName, Value, StrSoilVariable); try if FSoilName <> Value then begin if (Model <> nil) and (Value <> '') then begin ChangeGlobals.Rename; end; FSoilName := Value; InvalidateModel; end; if (Model <> nil) and (FSoilName <> '') then begin ChangeGlobals.SetValue(Index+1); end; finally ChangeGlobals.Free; end; end; procedure TSoilItem.SetSoilType(const Value: TSoilType); begin if FSoilType <> Value then begin FSoilType := Value; InvalidateModel; end; end; { TSoilCollection } procedure TSoilCollection.DeleteItemsWithZeroDuration; begin // inherited; // Don't delete based on duration. end; procedure TSoilCollection.EvaluateSoils; var CurrentRecord: TSoilRecord; Compiler: TRbwParser; PhastModel: TPhastModel; Formula: string; Expression: TExpression; Index: integer; CurrentItem: TSoilItem; FarmProcess: TFarmProcess; begin PhastModel := Model as TPhastModel; FarmProcess := PhastModel.ModflowPackages.FarmProcess; SetLength(FSoilArray, Count); Compiler := PhastModel.rpThreeDFormulaCompiler; for Index := 0 to Count - 1 do begin CurrentItem := Items[Index]; CurrentRecord.SoilID := Index+1; Expression := nil; Formula := CurrentItem.CapillaryFringe; try Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; // only global variables are used so there should be no need // to update the variables. Expression.Evaluate; except on E: ERbwParserError do begin frmFormulaErrors.AddFormulaError('', Format( 'Error in Capillary Fringe for "%s" in the Farm Process', [CurrentItem.SoilName]), Formula, E.Message); CurrentItem.CapillaryFringe := '0.'; Formula := CurrentItem.CapillaryFringe; Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; Expression.Evaluate; end; end; CurrentRecord.CapillaryFringe := Expression.DoubleResult; CurrentRecord.SoilType := CurrentItem.SoilType; if (FarmProcess.CropConsumptiveConcept = cccConcept1) and (CurrentItem.SoilType = stOther) then begin Expression := nil; Formula := CurrentItem.ACoeff; try Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; // only global variables are used so there should be no need // to update the variables. Expression.Evaluate; except on E: ERbwParserError do begin frmFormulaErrors.AddFormulaError('', Format( 'Error in A-Coeff for "%s" in the Farm Process', [CurrentItem.SoilName]), Formula, E.Message); CurrentItem.ACoeff := '0.'; Formula := CurrentItem.ACoeff; Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; Expression.Evaluate; end; end; CurrentRecord.ACoeff := Expression.DoubleResult; Expression := nil; Formula := CurrentItem.BCoeff; try Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; // only global variables are used so there should be no need // to update the variables. Expression.Evaluate; except on E: ERbwParserError do begin frmFormulaErrors.AddFormulaError('', Format( 'Error in B-Coeff for "%s" in the Farm Process', [CurrentItem.SoilName]), Formula, E.Message); CurrentItem.BCoeff := '0.'; Formula := CurrentItem.BCoeff; Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; Expression.Evaluate; end; end; CurrentRecord.BCoeff := Expression.DoubleResult; Expression := nil; Formula := CurrentItem.CCoeff; try Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; // only global variables are used so there should be no need // to update the variables. Expression.Evaluate; except on E: ERbwParserError do begin frmFormulaErrors.AddFormulaError('', Format( 'Error in C-Coeff for "%s" in the Farm Process', [CurrentItem.SoilName]), Formula, E.Message); CurrentItem.CCoeff := '0.'; Formula := CurrentItem.CCoeff; Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; Expression.Evaluate; end; end; CurrentRecord.CCoeff := Expression.DoubleResult; Expression := nil; Formula := CurrentItem.DCoeff; try Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; // only global variables are used so there should be no need // to update the variables. Expression.Evaluate; except on E: ERbwParserError do begin frmFormulaErrors.AddFormulaError('', Format( 'Error in D-Coeff for "%s" in the Farm Process', [CurrentItem.SoilName]), Formula, E.Message); CurrentItem.DCoeff := '0.'; Formula := CurrentItem.DCoeff; Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; Expression.Evaluate; end; end; CurrentRecord.DCoeff := Expression.DoubleResult; Expression := nil; Formula := CurrentItem.ECoeff; try Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; // only global variables are used so there should be no need // to update the variables. Expression.Evaluate; except on E: ERbwParserError do begin frmFormulaErrors.AddFormulaError('', Format( 'Error in E-Coeff for "%s" in the Farm Process', [CurrentItem.SoilName]), Formula, E.Message); CurrentItem.ECoeff := '0.'; Formula := CurrentItem.ECoeff; Compiler.Compile(Formula); Expression := Compiler.CurrentExpression; Expression.Evaluate; end; end; CurrentRecord.ECoeff := Expression.DoubleResult; end; FSoilArray[Index] := CurrentRecord; end; end; function TSoilCollection.GetItems(Index: Integer): TSoilItem; begin result := inherited Items[Index] as TSoilItem; end; class function TSoilCollection.ItemClass: TBoundaryItemClass; begin result := TSoilItem; end; procedure TSoilCollection.SetItems(Index: Integer; const Value: TSoilItem); begin inherited Items[Index] := Value; end; end.
unit PhpDocumentController; interface uses LrDocument, CodeDocumentController, CodeEdit; type TPhpDocumentController = class(TCodeDocumentController) public class function GetDescription: string; override; class function GetExt: string; override; protected function GetEditForm: TCodeEditForm; override; end; implementation uses PhpDocumentHost; const cDescription = 'PHP Document'; cExt = '.php'; class function TPhpDocumentController.GetDescription: string; begin Result := cDescription; end; class function TPhpDocumentController.GetExt: string; begin Result := cExt; end; function TPhpDocumentController.GetEditForm: TCodeEditForm; begin Result := PhpDocumentHostForm; end; end.
unit uAnimatedJPEG; interface uses Generics.Collections, System.SysUtils, System.Classes, System.Math, Winapi.Windows, Vcl.Graphics, Vcl.Imaging.jpeg, Dmitry.Utils.System, CCR.Exif, CCR.Exif.StreamHelper, uMemory, uBitmapUtils, uJpegUtils, Dmitry.Graphics.Types; type TAnimatedJPEG = class(TBitmap) private FImages: TList<TBitmap>; FIsRedCyan: Boolean; function GetCount: Integer; function GetImageByIndex(Index: Integer): TBitmap; protected public constructor Create; override; destructor Destroy; override; procedure LoadFromStream(Stream: TStream); override; procedure ResizeTo(Width, Height: Integer); procedure LoadRedCyanImage; property Count: Integer read GetCount; property Images[Index: Integer]: TBitmap read GetImageByIndex; property IsRedCyan: Boolean read FIsRedCyan write FIsRedCyan; end; const MPOHeader: array[0..3] of Byte = (Ord('M'), Ord('P'), Ord('F'), $00); LittleIndianHeader: array[0..3] of Byte = ($49, $49, $2A, $00); BigIndianHeader: array[0..3] of Byte = ($4D, $4D, $00, $2A); const Tag_MPFVersion = $B000; Tag_NumberOfImages = $B001; Tag_MPEntry = $B002; Tag_ImageUIDList = $B003; Tag_TotalFrames = $B004; type TMPEntry = record IndividualImageAttributes: DWORD; IndividualImageSize: DWORD; IndividualImageDataOffset: DWORD; DependentImage1EntryNumber: WORD; DependentImage2EntryNumber: WORD; function IsDependentParentImage: Boolean; function IsDependentChildImage: Boolean; function IsRepresentativeImage: Boolean; function MPTypeCode: Integer; end; type TMPOData = class private FIsvalid: Boolean; FEndianness: TEndianness; MMEntries: array of TMPEntry; public procedure ReadFromStream(S: TCustomMemoryStream; HeaderOffset: Int64); constructor Create; property Isvalid: Boolean read FIsvalid; end; implementation { TAnimatedJPEG } constructor TAnimatedJPEG.Create; begin FImages := TList<TBitmap>.Create; FIsRedCyan := False; end; destructor TAnimatedJPEG.Destroy; begin FreeList(FImages); inherited; end; function TAnimatedJPEG.GetCount: Integer; begin Result := FImages.Count; end; function TAnimatedJPEG.GetImageByIndex(Index: Integer): TBitmap; begin Result := FImages[Index]; end; procedure TAnimatedJPEG.LoadFromStream(Stream: TStream); var I: Integer; Pos: Int64; J: TJpegImage; B, BHalf: TBitmap; Exif: TExifData; M: TMPOData; procedure LoadImageFromImages; begin if FImages.Count > 0 then begin if not FIsRedCyan or (FImages.Count = 1) then Assign(FImages[0]) else LoadRedCyanImage; end; end; procedure LoadJpegFromStream; begin J := TJpegImage.Create; try try J.LoadFromStream(Stream); B := TBitmap.Create; try AssignJpeg(B, J); FImages.Add(B); B := nil; finally F(B); end; except //failed to load image //don't throw any exceptions if this is not first image if FImages.Count = 0 then raise; end; finally F(J); end; end; begin Pos := Stream.Position; FreeList(FImages, False); Exif := TExifData.Create; try Exif.LoadFromGraphic(Stream); if Exif.HasMPOExtension then begin M := TMPOData.Create; try M.ReadFromStream(Exif.MPOData.Data, Exif.MPOBlockOffset + 8); for I := 0 to Length(M.MMEntries) - 1 do begin //single representative image if M.MMEntries[I].IsRepresentativeImage and not M.MMEntries[I].IsDependentChildImage then begin Stream.Seek(M.MMEntries[I].IndividualImageDataOffset, TSeekOrigin.soBeginning); LoadJpegFromStream; LoadImageFromImages; Exit; end; end; //no representative image, load as animated for I := 0 to Length(M.MMEntries) - 1 do begin if not M.MMEntries[I].IsDependentChildImage then begin Stream.Seek(M.MMEntries[I].IndividualImageDataOffset, TSeekOrigin.soBeginning); LoadJpegFromStream; if FImages.Count = 2 then Break; end; end; LoadImageFromImages; finally F(M); end; end; finally F(Exif); end; Stream.Seek(Pos, TSeekOrigin.soBeginning); LoadJpegFromStream; if FImages.Count = 1 then begin B := FImages[0]; BHalf := TBitmap.Create; try if B.Width > 2 then begin BHalf.PixelFormat := pf24Bit; BHalf.SetSize(B.Width div 2, B.Height); DrawImageExRect(BHalf, B, 0, 0, B.Width div 2, B.Height, 0, 0); FImages.Add(BHalf); BHalf := nil; BHalf := TBitmap.Create; BHalf.PixelFormat := pf24Bit; BHalf.SetSize(B.Width div 2, B.Height); DrawImageExRect(BHalf, B, B.Width div 2, 0, B.Width div 2, B.Height, 0, 0); FImages.Add(BHalf); FImages[0].Free; FImages.Delete(0); BHalf := nil; end; finally F(BHalf); end; end; LoadImageFromImages; end; procedure TAnimatedJPEG.LoadRedCyanImage; var I, J, W, H: Integer; PS1, PS2, PD: PARGB; B: TBitmap; begin if FImages.Count < 2 then begin Assign(FImages[0]); Exit; end; B := TBitmap.Create; try B.PixelFormat := pf24Bit; FImages[0].PixelFormat := pf24Bit; FImages[1].PixelFormat := pf24Bit; W := Min(FImages[0].Width, FImages[1].Width); H := Min(FImages[0].Height, FImages[1].Height); B.SetSize(W, H); for I := 0 to H - 1 do begin PS1 := FImages[0].ScanLine[I]; PS2 := FImages[1].ScanLine[I]; PD := B.ScanLine[I]; for J := 0 to W - 1 do begin PD[J].R := PS1[J].R; PD[J].G := PS2[J].G; PD[J].B := PS2[J].B; end; end; Assign(B); finally F(B); end; end; procedure TAnimatedJPEG.ResizeTo(Width, Height: Integer); var B, BI: TBitmap; I: Integer; begin B := TBitmap.Create; try for I := 0 to Count - 1 do begin BI := FImages[I]; uBitmapUtils.KeepProportions(B, 500, 500); FImages[I] := BI; end; if FIsRedCyan then LoadRedCyanImage else begin B.Assign(Self); uBitmapUtils.KeepProportions(B, 500, 500); Assign(B); end; finally F(B); end; end; { TMPOData } constructor TMPOData.Create; begin FIsvalid := False; FEndianness := SmallEndian; end; //http://www.cipa.jp/english/hyoujunka/kikaku/pdf/DC-007_E.pdf procedure TMPOData.ReadFromStream(S: TCustomMemoryStream; HeaderOffset: Int64); var SourceHeader: array[0..3] of Byte; SourceByteOrder: array[0..3] of Byte; OffsetToFirstIFD: DWORD; Version: AnsiString; NumberOfImages: DWORD; OffsetOfNextIFD: DWORD; MPEntryDataSize: DWORD; MPEntryOffset: DWORD; TotalNumberOfcapturedImages: DWORD; I, J: Integer; TagId: WORD; TagCount: WORD; TagSize: WORD; DataSize: DWORD; begin FIsvalid := False; Version := ''; NumberOfImages := 0; SetLength(MMEntries, 0); if (S <> nil) then begin S.Seek(0, soFromBeginning); S.ReadBuffer(SourceHeader, SizeOf(SourceHeader)); if CompareMem(@SourceHeader, @MPOHeader, SizeOf(MPOHeader)) then FIsvalid := True; if FIsvalid then begin S.ReadBuffer(SourceByteOrder, SizeOf(SourceByteOrder)); if CompareMem(@SourceByteOrder, @BigIndianHeader, SizeOf(BigIndianHeader)) then FEndianness := BigEndian; S.ReadLongWord(FEndianness, OffsetToFirstIFD); OffsetOfNextIFD := S.Seek(OffsetToFirstIFD - 8, TSeekOrigin.soCurrent); if (OffsetOfNextIFD > 0) and (OffsetOfNextIFD < S.Size) then begin S.Seek(OffsetOfNextIFD, TSeekOrigin.soBeginning); S.ReadWord(FEndianness, TagCount); MPEntryDataSize := 0; MPEntryOffset := 0; for I := 1 to TagCount do begin S.ReadWord(FEndianness, TagId); S.ReadWord(FEndianness, TagSize); S.ReadLongWord(FEndianness, DataSize); if TagId = Tag_MPFVersion then begin SetLength(Version, 4); S.Read(Version[1], 4); end; if TagId = Tag_NumberOfImages then S.ReadLongWord(FEndianness, NumberOfImages); if TagId = Tag_TotalFrames then S.ReadLongWord(FEndianness, TotalNumberOfcapturedImages); if TagId = Tag_MPEntry then begin if DataSize / 16 = NumberOfImages then begin MPEntryDataSize := DataSize; S.ReadLongWord(FEndianness, MPEntryOffset); MPEntryOffset := MPEntryOffset + 4; end; end; end; S.ReadLongWord(FEndianness, OffsetOfNextIFD); if MPEntryDataSize > 0 then begin S.Seek(MPEntryOffset, TSeekOrigin.soBeginning); Setlength(MMEntries, NumberOfImages); for J := 0 to NumberOfImages - 1 do begin S.ReadLongWord(FEndianness, DWORD(MMEntries[J].IndividualImageAttributes)); S.ReadLongWord(FEndianness, MMEntries[J].IndividualImageSize); S.ReadLongWord(FEndianness, MMEntries[J].IndividualImageDataOffset); if MMEntries[J].IndividualImageDataOffset > 0 then MMEntries[J].IndividualImageDataOffset := MMEntries[J].IndividualImageDataOffset + HeaderOffset; S.ReadWord(FEndianness, MMEntries[J].DependentImage1EntryNumber); S.ReadWord(FEndianness, MMEntries[J].DependentImage2EntryNumber); end; end; end; end; end; end; { TMPEntry } function TMPEntry.IsDependentChildImage: Boolean; begin Result := (Self.IndividualImageAttributes and $40000000) > 0; end; function TMPEntry.IsDependentParentImage: Boolean; begin Result := (Self.IndividualImageAttributes and $80000000) > 0; end; function TMPEntry.IsRepresentativeImage: Boolean; begin Result := (Self.IndividualImageAttributes and $20000000) > 0; end; function TMPEntry.MPTypeCode: Integer; begin Result := Self.IndividualImageAttributes and $FFFFFF; end; end.
unit ZC4B.Credential; interface uses ZC4B.Interfaces; type ZC4BCredential = class(TInterfacedObject, iZC4BCredential) private [weak] FParent : iZC4B; FBaseURL : string; public constructor Create(Parent : iZC4B); destructor Destroy; override; class function New(Parent : iZC4B) : iZC4BCredential; function BaseURL(const aValue : string) : iZC4BCredential; overload; function BaseURL : string; overload; function &End : iZC4B; end; implementation { ZC4BCredential } function ZC4BCredential.BaseURL(const aValue : string) : iZC4BCredential; begin result:= self; FBaseURL:= aValue; end; function ZC4BCredential.&End: iZC4B; begin Result:= FParent; end; function ZC4BCredential.BaseURL: string; begin result:= FBaseURL; end; constructor ZC4BCredential.Create(Parent: iZC4B); begin FParent:= Parent; end; destructor ZC4BCredential.Destroy; begin inherited; end; class function ZC4BCredential.New(Parent: iZC4B): iZC4BCredential; begin result:= self.Create(Parent); end; end.
unit Chapter03._08_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math, DeepStar.Utils, DeepStar.UString; // 3. Longest Substring Without Repeating Characters // https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ // // 滑动窗口 // 时间复杂度: O(len(s)) // 空间复杂度: O(len(charset)) type TSolution = class(TObject) public function LengthOfLongestSubstring(s: UString): integer; end; procedure Main; implementation procedure Main; var ret: integer; begin with TSolution.Create do begin ret := LengthOfLongestSubstring('abcabcbb'); Free; end; WriteLn(ret); end; { TSolution } function TSolution.LengthOfLongestSubstring(s: UString): integer; var freg: TArr_int; l, r, ret: integer; begin SetLength(freg, 256); //滑动窗口为s[l...r] l := 0; r := -1; ret := 0; // 整个循环从 l == 0; r == -1 这个空窗口开始 // 到l == s.size(); r == s.size()-1 这个空窗口截止 // 在每次循环里逐渐改变窗口, 维护freq, 并记录当前窗口中是否找到了一个新的最优值 while l < Length(s) do begin if (r + 1 < Length(s)) and (freg[Ord(s.Chars[r + 1])] = 0) then begin r += 1; freg[Ord(s.Chars[r])] += 1; end else begin freg[Ord(s.Chars[l])] -= 1; l += 1; end; ret := Max(ret, r-l+1); end; Result := ret; end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* EXVOICE0.PAS 4.06 *} {*********************************************************} {**********************Description************************} {*Demonstrates receiving and interpreting DTMF tones *} {* using TAPI. *} {*********************************************************} unit ExVoice0; interface uses WinTypes, WinProcs, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, AdPort, AdTapi, AdTStat, AdTUtil, OoMisc; type TForm1 = class(TForm) CallerID: TEdit; Label1: TLabel; CallerIDName: TEdit; Label2: TLabel; Button1: TButton; Panel1: TPanel; Label3: TLabel; ApdComPort1: TApdComPort; AnswerButton: TButton; CancelCall: TButton; Pad1: TSpeedButton; Pad2: TSpeedButton; Pad3: TSpeedButton; Pad4: TSpeedButton; Pad5: TSpeedButton; Pad6: TSpeedButton; PadAsterisk: TSpeedButton; Pad0: TSpeedButton; PadPound: TSpeedButton; Pad7: TSpeedButton; Pad8: TSpeedButton; Pad9: TSpeedButton; ApdTapiDevice1: TApdTapiDevice; GroupBox1: TGroupBox; Label4: TLabel; Timer1: TTimer; procedure Button1Click(Sender: TObject); procedure AnswerButtonClick(Sender: TObject); procedure CancelCallClick(Sender: TObject); procedure ApdTapiDevice1TapiConnect(Sender: TObject); procedure ApdTapiDevice1TapiCallerID(CP: TObject; ID, IDName: string); procedure Timer1Timer(Sender: TObject); procedure ApdTapiDevice1TapiDTMF(CP: TObject; Digit: Char; ErrorCode: Longint); procedure FormCreate(Sender: TObject); procedure ApdTapiDevice1TapiWaveNotify(CP: TObject; Msg: TWaveMessage); private { Private declarations } public { Public declarations } end; const CurrentState : Integer = 0; StateGreeting = 0; StateMenu = 1; StatePlayingWav = 2; StateEndCall = 3; var Form1: TForm1; LastDigit: Char; WaveFileDir: String; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); begin ApdTapiDevice1.SelectDevice; ApdTapiDevice1.EnableVoice := True; end; procedure TForm1.AnswerButtonClick(Sender: TObject); begin if ApdTapiDevice1.EnableVoice then ApdTapiDevice1.AutoAnswer else MessageDlg('The Selected device does not support Voice Extensions.', mtInformation, [mbOk], 0); end; procedure TForm1.CancelCallClick(Sender: TObject); begin ApdTapiDevice1.CancelCall; CallerId.Text := ''; CallerIdName.Text := ''; Timer1.Enabled := True; end; procedure TForm1.ApdTapiDevice1TapiConnect(Sender: TObject); begin CancelCall.Enabled := True; CurrentState := StateGreeting; {Play Greeting} Label4.Caption := 'Playing Greeting'; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'greeting.wav'); end; procedure TForm1.ApdTapiDevice1TapiCallerID(CP: TObject; ID, IDName: string); begin CallerId.Text := ID; CallerIdName.Text := IDName; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Pad9.Down := False; PadPound.Down := False; try ApdTapiDevice1.AutoAnswer; Timer1.Enabled := False; except end; end; procedure TForm1.ApdTapiDevice1TapiDTMF(CP: TObject; Digit: Char; ErrorCode: Longint); var S: String; begin LastDigit := Digit; if (Digit = '') or (Digit = ' ') then Exit; if Digit = '*' then PadAsterisk.Down := True else if Digit = '#' then PadPound.Down := True else TSpeedButton(FindComponent('Pad'+Digit)).Down := True; {Simple DTMF State Machine} case CurrentState of StateMenu: begin case Digit of '0'..'8': S := WaveFileDir+'choice'+Digit+'.wav'; '9': begin ApdTapiDevice1.InterruptWave := False; S := WaveFileDir+'choice9.wav'; CurrentState := StateEndCall; end; '*': begin S := WaveFileDir+'Greeting.wav'; CurrentState := StateGreeting; end; '#': begin ApdTapiDevice1.InterruptWave := False; S := WaveFileDir+'Goodbye.wav'; CurrentState := StateEndCall; end; end; end; StateGreeting: begin S := WaveFileDir+'menu.wav'; CurrentState := StateMenu; end; end; if S <> '' then begin Label4.Caption := 'Playing Wave File: '+ S; ApdTapiDevice1.PlayWaveFile(S); end; end; procedure TForm1.FormCreate(Sender: TObject); begin WaveFileDir := ExtractFilePath(ParamStr(0)); WaveFileDir := Copy(WaveFileDir, 1, Pos('EXAMPLES',UpperCase(WaveFileDir))+8); end; procedure TForm1.ApdTapiDevice1TapiWaveNotify(CP: TObject; Msg: TWaveMessage); begin if Msg = waPlayDone then Label4.Caption := 'Wave Device Idle...'; if CurrentState = StateEndCall then if (Msg = waPlayDone) then CancelCallClick(Self); end; end.
{ @abstract(Desginer for TSynUniSyn) @authors(Vit [nevzorov@yahoo.com], Fantasist [walking_in_the_sky@yahoo.com], Vitalik [vetal-x@mail.ru]) @created(2003) @lastmod(2004-05-12) } (****************************************************************************** Authors: Vit (Vitaly Nevzorov nevzorov@yahoo.com) Fantasist (Kirill Burtsev walking_in_the_sky@yahoo.com) Vitalik (Vitaly Lyapota vetal-x@mail.ru) Official Site: http://www.unihighlighter.com With all questions, please visit http://forum.vingrad.ru/index.php?showforum=170 ******************************************************************************) unit SynUniDesigner; //{$DEFINE SYNPLUS} //*SCHMaster*// {$I SynUniHighlighter.inc} interface uses Windows, Messages, Controls, SynUniHighlighter, SynUniDesignerForm; type TSynUniDesigner = class(TObject) private Form: TfmDesigner; function Execute(FormTitle: string; LangFile: string): boolean; procedure SetSample(const Value: string); function GetSample: string; procedure SetTitle(const Value: string); function GetTitle: string; public constructor Create(Highlighter: TSynUniSyn); destructor Destroy; override; property Title: string read GetTitle write SetTitle; property Sample: string read GetSample write SetSample; class function EditHighlighter(OriginalSyn: TSynUniSyn; FormTitle: string = ''; LangFile: string = ''): boolean; end; implementation constructor TSynUniDesigner.Create(Highlighter: TSynUniSyn); begin inherited Create; Form := TfmDesigner.Create(nil); {$IFDEF UNIDESIGNER18} Form.OriginalSyn := Highlighter; {$ENDIF} {$IFDEF UNIDESIGNER20} Form.TotalClear(); Form.SynUniSyn := Highlighter; Form.TempStart(); {$ENDIF} {$IFDEF NEWUNIDESIGNER} //... {$ENDIF} end; destructor TSynUniDesigner.Destroy; begin Form.SampleMemo.Highlighter := nil; Form.Free; inherited; end; class function TSynUniDesigner.EditHighlighter(OriginalSyn: TSynUniSyn; FormTitle: string; LangFile: string): boolean; begin with Create(OriginalSyn) do begin Result := Execute(FormTitle, LangFile); Free; end; end; procedure TSynUniDesigner.SetSample(const Value: string); begin Form.SampleMemo.Text := Value; end; function TSynUniDesigner.GetSample: string; begin Result := Form.SampleMemo.Text; end; procedure TSynUniDesigner.SetTitle(const Value: string); begin Form.Caption := Value; end; function TSynUniDesigner.GetTitle: string; begin Result := Form.Caption; end; {$IFDEF SYNPLUS} //*SCHMaster*// function TSynUniDesigner.Execute(FormTitle: string; LangFile: string): boolean; var msg : TMsg; TcClosed: boolean; begin if FormTitle <> '' then Title := FormTitle; //###Form.Translate(LangFile); TcClosed := False; Form.ModalResult := mrNone; Form.Show; while (Form.ModalResult = mrNone) do begin GetMessage(msg, 0, 0, 0); if (msg.message = WM_QUIT) then begin TcClosed := True; Form.ModalResult := mrCancel; result:=False; end else begin Result := (Form.ModalResult = mrOk); TranslateMessage(msg); DispatchMessage(msg); end; end; Result := (Form.ModalResult = mrOk); if TcClosed then PostMessage(msg.hwnd, msg.message, msg.wParam, msg.lParam); end; {$ELSE} function TSynUniDesigner.Execute(FormTitle: string; LangFile: string): boolean; begin if FormTitle <> '' then Title := FormTitle; {$IFDEF UNIDESIGNER18}Form.Translate(LangFile);{$ENDIF} Result := (Form.ShowModal = mrOk); end; {$ENDIF} end.
unit NewFrontiers.GUI.StringGridAdapter; interface uses AdvGrid, BaseGrid, AdvObj, Generics.Collections, NewFrontiers.GUI.Binding, NewFrontiers.Reflection, System.TypInfo; type TBoundColumn = class protected _propertyName: string; _header: string; public property PropertyName: string read _propertyName write _propertyName; property Header: string read _header write _header; end; /// <summary> /// Für jede Zelle eines Grids wird ein BoundCell-Objekt angelegt und im /// Grid verankert. Es stellt die Beziehung zwischen dem reinen String-Grid /// und den jeweiligen Enitäten dar. /// </summary> TBoundCell = class protected _value: string; _grid: TAdvStringGrid; _x, _y: integer; _kind: TTypeKind; _source: TObject; _binding: TBinding; procedure setValue(const Value: string); public property Value: string read _value write setValue; property Grid: TAdvStringGrid read _grid write _grid; property X: integer read _x write _x; property Y: integer read _y write _y; property Kind: TTypeKind read _kind write _kind; property Source: TObject read _source write _source; property Binding: TBinding read _binding write _binding; destructor Destroy; override; procedure updateGrid; procedure cellUpdated(aNewValue: string); end; /// <summary> /// Der String-Grid Adapter verwaltet die Bindungen einer Liste /// (DataSource) zu einem AdvStringGrid. Zu diesem Zweck hängt er sich an /// die jeewiligen Events. /// </summary> TStringGridAdapter<T: class> = class private procedure HeaderSetzen; procedure datensatzEintragen(aktObject: T; y: Integer); procedure setSelected(const Value: T); protected _grid: TAdvStringGrid; _dataSource: TList<T>; _columns: TObjectList<TBoundColumn>; _selected: T; _UseFieldBinding: boolean; // TODO: Orderntlich machen _settingUp: boolean; procedure gridEditCellDone(Sender: TObject; ACol, ARow: Integer); procedure gridGetEditorType(Sender: TObject; ACol, ARow: Integer; var AEditor: TEditorType); procedure gridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); procedure listNotify(Sender: TObject; const Item: T; Action: TCollectionNotification); procedure setupGrid; procedure setupDataSource; public constructor Create; destructor Destroy; override; property Grid: TAdvStringGrid read _grid write _grid; property DataSource: TList<T> read _dataSource write _dataSource; property Selected: T read _selected write setSelected; property UseFieldBinding: boolean read _UseFieldBinding write _UseFieldBinding; /// <summary> /// Bereitet den Adapter und die beteiligten Klassen auf die Verwendung /// vor. Kann erst aufgerufen werden wenn Grid und Datasource gesetzt /// wurden. /// </summary> procedure setup; /// <summary> /// Fügt dem Grid eine Spalte hinzu /// </summary> /// <param name="aProperty"> /// Name der Property, die in der Spalte angezeigt werden soll /// </param> /// <param name="aHeader"> /// Überschrift der Spalte. Wird keine Überschrift angegeben wird der /// Name der Property angezeigt. /// </param> procedure addColumn(aProperty: string; aHeader: string = ''); end; implementation uses NewFrontiers.Reflection.ValueConvert, System.Rtti, SysUtils, NewFrontiers.GUI.BindingTarget, Math; { TStringGridAdapter } procedure TStringGridAdapter<T>.addColumn(aProperty, aHeader: string); var columnToAdd: TBoundColumn; begin if (aHeader = '') then aHeader := aProperty; columnToAdd := TBoundColumn.Create; columnToAdd.PropertyName := aProperty; columnToAdd.Header := aHeader; _columns.add(columnToAdd); end; procedure TStringGridAdapter<T>.datensatzEintragen(aktObject: T; y: Integer); var aktColumn: TBoundColumn; bound: TBoundCell; binding: TBinding; x: integer; begin // TODO: Hier könnte es von Vorteil sein statt der Einzelbindungen // eine BindingGroup zu verwenden je Datensatz x := 0; for aktColumn in _columns do begin bound := TBoundCell.Create; bound.Source := aktObject; bound.Grid := _grid; bound.X := x; bound.Y := y; binding := TBinding.Create; binding.Target := TBindingTargetFactory.createTarget(bound, 'Value'); // TODO: Anders machen if (self.UseFieldBinding) then binding.Source := TBindingTargetFactory.createFieldTarget(aktObject, aktColumn.PropertyName) else binding.Source := TBindingTargetFactory.createTarget(aktObject, aktColumn.PropertyName); binding.registerWithDictionary; bound.Binding := binding; grid.Objects[x, y] := bound; inc(x); end; end; procedure TStringGridAdapter<T>.HeaderSetzen; var aktColumn: TBoundColumn; i: Integer; begin // Header i := 0; for aktColumn in _columns do begin Grid.Cells[i, 0] := aktColumn.Header; inc(i); end; end; constructor TStringGridAdapter<T>.Create; begin _columns := TObjectList<TBoundColumn>.Create(true); end; destructor TStringGridAdapter<T>.Destroy; var i,j: integer; begin Grid.OnEditCellDone := nil; Grid.OnGetEditorType := nil; Grid.OnRowChanging := nil; _dataSource.OnNotify := nil; if (_grid <> nil) then begin // BoundCells freigeben for i := 0 to _grid.ColCount-1 do begin for j := 0 to _grid.RowCount-1 do begin if (Grid.Objects[i, j] <> nil) then begin Grid.Objects[i, j].Free; Grid.Objects[i, j] := nil; end; end; end; _grid.ClearNormalCells; end; _columns.Free; inherited; end; procedure TStringGridAdapter<T>.gridEditCellDone(Sender: TObject; ACol, ARow: Integer); begin if (grid.Objects[aCol, aRow] = nil) then exit; TBoundCell(grid.Objects[aCol, aRow]).cellUpdated(grid.Cells[aCol, aRow]); end; procedure TStringGridAdapter<T>.gridGetEditorType(Sender: TObject; ACol, ARow: Integer; var AEditor: TEditorType); begin if (grid.Objects[aCol, aRow] <> nil) then begin // TODO: Richtigen Editor auswählen end; end; procedure TStringGridAdapter<T>.gridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); begin if (grid.Objects[0, NewRow] <> nil) then Selected := TBoundCell(grid.Objects[0, NewRow]).Source as T; end; procedure TStringGridAdapter<T>.listNotify(Sender: TObject; const Item: T; Action: TCollectionNotification); var index: integer; i: Integer; begin if _settingUp then exit; if Action = cnAdded then begin // TODO: Was ist mit Einfügen in der Mitte? Grid.BeginUpdate; Grid.AddRow; datensatzEintragen(Item, Grid.RowCount-1); Grid.AutoSizeColumns(true); Grid.SelectRows(Grid.RowCount-1, 1); Grid.EndUpdate; Grid.ScrollInView(0, Grid.RowCount-1); Selected := Item; end else if Action = cnRemoved then begin Grid.BeginUpdate; // Zeile suchen // Scheinbar wird das Item erst entfernt und dann das Notify-Ereignis aufgerufen // Für unseren Zweck natütlich denkbar ungeeignet. Als Work-Around erst mal // die Zeile über das Grid ermitteln // index := _dataSource.IndexOf(Item); index := -1; for i := 0 to _grid.RowCount-1 do begin if (Grid.Objects[0, i] <> nil) and (TBoundCell(Grid.Objects[0, i]).Source.GetHashCode = Item.GetHashCode) then begin index := i; break; end; end; for i := 0 to _grid.ColCount-1 do begin if (Grid.Objects[i, index] <> nil) then Grid.Objects[i, index].Free; end; Grid.RemoveRows(index, 1); // +1 da ja noch der Header dazu kommt Grid.EndUpdate; end else if Action = cnExtracted then // TODO end; procedure TStringGridAdapter<T>.setSelected(const Value: T); var gridIndex: integer; begin _selected := Value; TBindingDictionary.getInstance.propertyChanged(self, 'Selected'); end; procedure TStringGridAdapter<T>.setup; begin if (Grid = nil) then raise EArgumentException.Create('Es wurde noch kein Grid gesetzt'); if (DataSource = nil) then raise EArgumentException.Create('Es wurde noch keine DataSource gesetzt'); _settingUp := true; setupDataSource; setupGrid; _settingUp := false; end; procedure TStringGridAdapter<T>.setupDataSource; begin // Bindet an das OnNotify der Liste _dataSource.OnNotify := listNotify; end; procedure TStringGridAdapter<T>.setupGrid; var aktObject: T; x, y: integer; converter: TValueConverter; temp: TValue; begin Grid.BeginUpdate; Grid.ColCount := _columns.Count; Grid.RowCount := max(_dataSource.Count + 1, 2); Grid.FixedRows := 1; Grid.OnEditCellDone := gridEditCellDone; Grid.OnGetEditorType := gridGetEditorType; Grid.OnRowChanging := gridRowChanging; HeaderSetzen; // Daten y := 1; for aktObject in _dataSource do begin datensatzEintragen(aktObject, y); inc(y); end; Grid.AutoSizeColumns(true); Grid.EndUpdate; if (_dataSource.Count > 0) then Selected := _dataSource[0]; end; { TBoundCell } procedure TBoundCell.cellUpdated(aNewValue: string); begin _value := aNewValue; TBindingDictionary.getInstance.propertyChanged(self, 'Value'); end; destructor TBoundCell.Destroy; begin // Wenn eine gebundene Zelle zerstört wird, dann muss auch das Binding // entfernt werden. binding.Destroy; binding := nil; inherited; end; procedure TBoundCell.setValue(const Value: string); begin _value := Value; updateGrid; end; procedure TBoundCell.updateGrid; begin grid.Cells[x,y] := _value; end; end.
unit UEngineFileFind; (*==================================================================== Class for searched items. ======================================================================*) {$A-} interface uses UTypes, UCollections, UApiTypes, UBaseTypes; type PFSearchItem = ^TFSearchItem; TFSearchItem = object(TQObject) Disk : TPQString; Dir : TPQString; LongName : TPQString; ShortDesc : TPQString; // copy of the part of description Ext : TExt; FileType : TFileType; Attr : word; Time : Longint; Size : Longint; Description : TFilePointer; SelfFilePos : TFilePointer; // copy from OneFile Position : Integer; // position of found string constructor FileInit (OneFile: TOneFile; ADisk: ShortString; ADir: ShortString; AShortDesc: ShortString); constructor EmptiesInit (ADisk: ShortString; QDiskFree, QDiskSize: longInt; AShortDesc: ShortString); destructor Done; virtual; end; implementation uses SysUtils, UBaseUtils, UCallbacks; //=== TFSearchItem =========================================================== constructor TFSearchItem.FileInit (OneFile: TOneFile; ADisk, ADir, AShortDesc: ShortString); begin inherited Init; LongName := QNewStr(OneFile.LongName); Size := OneFile.Size; Time := OneFile.Time; Attr := OneFile.Attr; Ext := OneFile.Ext; Description := OneFile.Description; SelfFilePos := OneFile.SelfFilePos; if GetPQString(LongName) = '..' then FileType := ftParent else if Attr and faDirectory = faDirectory then FileType := ftDir else FileType := ftFile; Disk := QNewStr(ADisk); Dir := QNewStr(ADir); ShortDesc := QNewStr(AShortDesc); end; //----------------------------------------------------------------------------- constructor TFSearchItem.EmptiesInit (ADisk: ShortString; QDiskFree, QDiskSize: longInt; AShortDesc: ShortString); begin inherited Init; FileType := TFileType(0); Attr := 0; LongName := nil; ShortDesc := QNewStr(AShortDesc); Dir := nil; Ext := ''; Disk := QNewStr(ADisk); Size := QDiskSize; Time := QDiskFree; end; //----------------------------------------------------------------------------- destructor TFSearchItem.Done; begin QDisposeStr(Dir); QDisposeStr(LongName); QDisposeStr(Disk); QDisposeStr(ShortDesc); end; //----------------------------------------------------------------------------- end.
unit UFrmCadastroRequisicao; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls , URequisicaoEstoque , UUtilitarios , URegraCRUDRequisicaoEstoque , URegraCRUDTipoMovimentacao , Mask , URegraCRUDStatus , URegraCRUDEmpresaMatriz , URegraCRUDProduto , URegraCRUDDeposito , URegraCRUDLote , URegraCRUDUsuario ; type TFrmCadastroRequisicao = class(TFrmCRUD) gbInformacoes: TGroupBox; lbCodigoPais: TLabel; edNumDocumento: TLabeledEdit; btnLocalizarTipoMovimento: TButton; edTipoMovimento: TEdit; stNomeTipoMovimento: TStaticText; edDataEmissao: TMaskEdit; Label1: TLabel; Label2: TLabel; edDataEntrada: TMaskEdit; edDataCancelamento: TMaskEdit; lblDataCancel: TLabel; GroupBox1: TGroupBox; pnlStatus: TPanel; Label4: TLabel; edFornecedor: TEdit; btnLocalizarFornecedor: TButton; stNomeFornecedor: TStaticText; edQuantidade: TLabeledEdit; edValorUnitario: TLabeledEdit; Label5: TLabel; edProduto: TEdit; btnLocalizarProduto: TButton; stNomeProduto: TStaticText; edDepositoOrigem: TEdit; lblDepositoOrigem: TLabel; btnLocalizarDepositoOrigem: TButton; stNomeDepositoOrigem: TStaticText; edDepositoDestino: TEdit; Label7: TLabel; btnLocalizarDepositoDestino: TButton; stNomeDepositoDestino: TStaticText; edLote: TEdit; Lote: TLabel; btnLocalizarLote: TButton; stLote: TStaticText; Label8: TLabel; stNomeUsuario: TStaticText; Label9: TLabel; stDataModificacao: TStaticText; procedure edTipoMovimentoExit(Sender: TObject); procedure btnLocalizarTipoMovimentoClick(Sender: TObject); procedure btnLocalizarFornecedorClick(Sender: TObject); procedure edFornecedorExit(Sender: TObject); procedure edLoteExit(Sender: TObject); procedure btnLocalizarLoteClick(Sender: TObject); procedure btnLocalizarProdutoClick(Sender: TObject); procedure edProdutoExit(Sender: TObject); procedure edDepositoOrigemExit(Sender: TObject); procedure btnLocalizarDepositoOrigemClick(Sender: TObject); procedure btnLocalizarDepositoDestinoClick(Sender: TObject); procedure edDepositoDestinoExit(Sender: TObject); procedure btnGravarClick(Sender: TObject); protected FREQUISICAO: TREQUISICAOESTOQUE; FRegraCRUDTipoMovimento : TRegraCrudTipoMovimentacao; FregraCRUDRequisicao : TRegraCrudRequisicaoEstoque; FregraCRUDStatus : TRegraCrudStatus; FregraCRUDEmpresa : TregraCRUDEEmpresaMatriz; FregraCRUDProduto : TRegraCRUDProduto; FregraCRUDDepositoDestino : TregraCRUDDEPOSITO; FregraCRUDDepositoOrigem : TregraCRUDDEPOSITO; FregraCRUDUsuario : TRegraCRUDUsuario; FregraCRUDLote : TRegraCRUDLote; public procedure Inicializa; override; procedure Finaliza; override; procedure PreencheEntidade; override; procedure PreencheFormulario; override; procedure PosicionaCursorPrimeiroCampo; override; procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override; procedure SetaVisibilidadeDepositoOrigem; end; var FrmCadastroRequisicao: TFrmCadastroRequisicao; implementation {$R *.dfm} uses UOpcaoPesquisa , UEntidade , UFrmPesquisa , UTipoMovimentacao , UStatus , UEmpresaMatriz , UProduto , UDeposito , ULote , UUSuario , UDialogo , UUsuarioLogado ; procedure TFrmCadastroRequisicao.btnGravarClick(Sender: TObject); begin if FREQUISICAO.STATUS.ID = 1 then FREQUISICAO.STATUS := TSTATUS( FregraCRUDStatus.Retorna(2)); pnlStatus.Caption := EmptyStr; inherited; end; procedure TFrmCadastroRequisicao.btnLocalizarDepositoDestinoClick( Sender: TObject); begin inherited; edDepositoDestino.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa .Create .DefineVisao(VW_DEPOSITO) .DefineNomeCampoRetorno(VW_DEPOSITO_ID) .DefineNomePesquisa(STR_DEPOSITO) .AdicionaFiltro(VW_DEPOSITO_DESCRICAO)); if Trim(edDepositoDestino.Text) <> EmptyStr then edDepositoDestino.OnExit(btnLocalizarDepositoDestino); end; procedure TFrmCadastroRequisicao.btnLocalizarDepositoOrigemClick( Sender: TObject); begin inherited; edDepositoOrigem.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa .Create .DefineVisao(VW_DEPOSITO) .DefineNomeCampoRetorno(VW_DEPOSITO_ID) .DefineNomePesquisa(STR_DEPOSITO) .AdicionaFiltro(VW_DEPOSITO_DESCRICAO)); if Trim(edDepositoOrigem.Text) <> EmptyStr then edDepositoOrigem.OnExit(btnLocalizarDepositoOrigem); end; procedure TFrmCadastroRequisicao.btnLocalizarFornecedorClick(Sender: TObject); begin inherited; edFornecedor.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa .Create .DefineVisao(VW_EMPRESA) .DefineNomeCampoRetorno(VW_EMPRESA_ID) .DefineNomePesquisa(STR_EMPRESAMATRIZ) .AdicionaFiltro(VW_EMPRESA_NOME)); if Trim(edFornecedor.Text) <> EmptyStr then edFornecedor.OnExit(btnLocalizarFornecedor); end; procedure TFrmCadastroRequisicao.btnLocalizarLoteClick(Sender: TObject); begin inherited; edLote.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa .Create .DefineVisao(VW_LOTE) .DefineNomeCampoRetorno(VW_LOTE_ID) .DefineNomePesquisa(STR_LOTE) .AdicionaFiltro(VW_LOTE_DESCRICAO)); if Trim(edLote.Text) <> EmptyStr then edLote.OnExit(btnLocalizarLote); end; procedure TFrmCadastroRequisicao.btnLocalizarProdutoClick(Sender: TObject); begin inherited; edProduto.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa .Create .DefineVisao(VW_PRODUTO) .DefineNomeCampoRetorno(VW_PRODUTO_ID) .DefineNomePesquisa(STR_PRODUTO) .AdicionaFiltro(VW_PRODUTO_DESCRICAO)); if Trim(edProduto.Text) <> EmptyStr then edProduto.OnExit(btnLocalizarProduto); end; procedure TFrmCadastroRequisicao.btnLocalizarTipoMovimentoClick( Sender: TObject); begin inherited; edTipoMovimento.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa .Create .DefineVisao(VW_TIPO_MOVIMENTACAO) .DefineNomeCampoRetorno(VW_TIPO_MOVIMENTACAO_ID) .DefineNomePesquisa(STR_TIPO_MOVIMENTACAO) .AdicionaFiltro(VW_TIPO_MOVIMENTACAO_NOME)); if Trim(edTipoMovimento.Text) <> EmptyStr then edTipoMovimento.OnExit(btnLocalizarTipoMovimento); end; procedure TFrmCadastroRequisicao.edDepositoDestinoExit(Sender: TObject); begin inherited; stNomeDepositoDestino.Caption := EmptyStr; if Trim(edDepositoDestino.Text) <> EmptyStr then try FregraCRUDDepositoDestino.ValidaExistencia(StrToIntDef(edDepositoDestino.Text, 0)); FREQUISICAO.DEPOSITO_DESTINO := TDEPOSITO( FregraCRUDDepositoDestino.Retorna(StrToIntDef(edDepositoDestino.Text, 0))); stNomeDepositoDestino.Caption := FREQUISICAO.DEPOSITO_DESTINO.DESCRICAO; except on E: Exception do begin TDialogo.Excecao(E); edDepositoDestino.SetFocus; end; end; end; procedure TFrmCadastroRequisicao.edDepositoOrigemExit(Sender: TObject); begin inherited; stNomeDepositoOrigem.Caption := EmptyStr; if Trim(edDepositoOrigem.Text) <> EmptyStr then try FregraCRUDDepositoOrigem := TregraCRUDDEPOSITO.Create; FregraCRUDDepositoOrigem.ValidaExistencia(StrToIntDef(edDepositoOrigem.Text, 0)); FREQUISICAO.DEPOSITO_ORIGEM := TDEPOSITO( FregraCRUDDepositoOrigem.Retorna(StrToIntDef(edDepositoOrigem.Text, 0))); stNomeDepositoOrigem.Caption := FREQUISICAO.DEPOSITO_ORIGEM.DESCRICAO; except on E: Exception do begin TDialogo.Excecao(E); edDepositoOrigem.SetFocus; end; end else FREQUISICAO.DEPOSITO_ORIGEM.ID := 0; end; procedure TFrmCadastroRequisicao.edFornecedorExit(Sender: TObject); begin inherited; stNomeFornecedor.Caption := EmptyStr; if Trim(edFornecedor.Text) <> EmptyStr then try FregraCRUDEmpresa.ValidaExistencia(StrToIntDef(edFornecedor.Text, 0)); FREQUISICAO.EMPRESA := TEmpresa( FregraCRUDEmpresa.Retorna(StrToIntDef(edFornecedor.Text, 0))); stNomeFornecedor.Caption := FREQUISICAO.EMPRESA.NOME; except on E: Exception do begin TDialogo.Excecao(E); edFornecedor.SetFocus; end; end; end; procedure TFrmCadastroRequisicao.edLoteExit(Sender: TObject); begin inherited; stLote.Caption := EmptyStr; if Trim(edLote.Text) <> EmptyStr then try FregraCRUDLote.ValidaExistencia(StrToIntDef(edLote.Text, 0)); FREQUISICAO.LOTE := TLOTE( FregraCRUDLote.Retorna(StrToIntDef(edLote.Text, 0))); stLote.Caption := FREQUISICAO.LOTE.LOTE; except on E: Exception do begin TDialogo.Excecao(E); edLote.SetFocus; end; end; end; procedure TFrmCadastroRequisicao.edProdutoExit(Sender: TObject); begin inherited; stNomeProduto.Caption := EmptyStr; if Trim(edProduto.Text) <> EmptyStr then try FregraCRUDProduto.ValidaExistencia(StrToIntDef(edProduto.Text, 0)); FREQUISICAO.PRODUTO := TPRODUTO( FregraCRUDProduto.Retorna(StrToIntDef(edProduto.Text, 0))); stNomeProduto.Caption := FREQUISICAO.PRODUTO.DESCRICAO; except on E: Exception do begin TDialogo.Excecao(E); edProduto.SetFocus; end; end; end; procedure TFrmCadastroRequisicao.edTipoMovimentoExit(Sender: TObject); begin inherited; stNomeTipoMovimento.Caption := EmptyStr; if Trim(edTipoMovimento.Text) <> EmptyStr then try FRegraCRUDTipoMovimento.ValidaExistencia(StrToIntDef(edTipoMovimento.Text, 0)); FREQUISICAO.TIPO_MOVIMENTACAO := TTIPOMOVIMENTACAO( FRegraCRUDTipoMovimento.Retorna(StrToIntDef(edTipoMovimento.Text, 0))); //ATRIBUINDO STATUS FREQUISICAO.STATUS := TSTATUS( FregraCRUDStatus.Retorna(1)); stNomeTipoMovimento.Caption := FREQUISICAO.TIPO_MOVIMENTACAO.FNOME; except on E: Exception do begin TDialogo.Excecao(E); edTipoMovimento.SetFocus; end; end; SetaVisibilidadeDepositoOrigem; end; procedure TFrmCadastroRequisicao.Finaliza; begin inherited; FreeAndNil(FRegraCRUDTipoMovimento); FreeAndNil(FregraCRUDStatus); FreeAndNil(FregraCRUDEmpresa); FreeAndNil(FregraCRUDProduto); FreeAndNil(FregraCRUDDepositoDestino); FreeAndNil(FregraCRUDDepositoOrigem); FreeAndNil(FregraCRUDUsuario); FreeAndNil(FregraCRUDLote); end; procedure TFrmCadastroRequisicao.HabilitaCampos( const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); begin inherited; gbInformacoes.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao]; end; procedure TFrmCadastroRequisicao.Inicializa; begin inherited; DefineEntidade(@FREQUISICAO, TREQUISICAOESTOQUE); DefineRegraCRUD(@FregraCRUDRequisicao, TRegraCrudRequisicaoEstoque); AdicionaOpcaoPesquisa(TOpcaoPesquisa .Create .AdicionaFiltro(FLD_REQUISICAO_ESTOQUE_NUMERO_DOCUMENTO) .DefineNomeCampoRetorno(FLD_ENTIDADE_ID) .DefineNomePesquisa(STR_REQUISICAO_ESTOQUE) .DefineVisao(TBL_REQUISICAO_ESTOQUE)); FRegraCRUDTipoMovimento := TRegraCrudTipoMovimentacao.Create; FregraCRUDStatus := TRegraCrudStatus.Create; FregraCRUDEmpresa := TregraCRUDEEmpresaMatriz.Create; FregraCRUDProduto := TRegraCRUDProduto.Create; FregraCRUDDepositoDestino := TregraCRUDDEPOSITO.Create; FregraCRUDDepositoOrigem := TregraCRUDDEPOSITO.Create; FregraCRUDUsuario := TRegraCRUDUsuario.Create; FregraCRUDLote := TRegraCRUDLote.Create; end; procedure TFrmCadastroRequisicao.PosicionaCursorPrimeiroCampo; begin inherited; edTipoMovimento.SetFocus; end; procedure TFrmCadastroRequisicao.PreencheEntidade; var defaultDate : TDateTime; begin inherited; FREQUISICAO.DATA_EMISSAO := StrToDateDef(edDataEmissao.Text, Now); FREQUISICAO.DATA_ENTRADA := StrToDateDef(edDataEntrada.Text, Now); FREQUISICAO.DATA_CANCELAMENTO := StrToDateDef(edDataCancelamento.Text, defaultDate); FREQUISICAO.DATA_INCLUSAO := Now; FREQUISICAO.QUANTIDADE := StrToIntDef(edQuantidade.Text, 0); FREQUISICAO.CUSTO_UNITARIO := StrToFloatDef(edValorUnitario.Text, 0); FREQUISICAO.NUMERO_DOCUMENTO := StrToIntDef(edNumDocumento.Text, 0); //informações de usuário FREQUISICAO.USUARIO.LOGIN := TUsuarioLogado.USUARIO.LOGIN; FREQUISICAO.USUARIO.NOME := TUsuarioLogado.USUARIO.NOME; FREQUISICAO.USUARIO.ID := TUsuarioLogado.USUARIO.ID end; procedure TFrmCadastroRequisicao.PreencheFormulario; begin inherited; edTipoMovimento.Text := IntToStr(FREQUISICAO.TIPO_MOVIMENTACAO.ID); stNomeTipoMovimento.Caption := FREQUISICAO.TIPO_MOVIMENTACAO.FNOME; edFornecedor.Text := IntToStr(FREQUISICAO.EMPRESA.ID); stNomeFornecedor.Caption := FREQUISICAO.EMPRESA.NOME; edDataEmissao.Text := DateToStr(FREQUISICAO.DATA_EMISSAO); edDataEntrada.Text := DateToStr(FREQUISICAO.DATA_ENTRADA); stDataModificacao.Caption := DateToStr(FREQUISICAO.DATA_INCLUSAO); edNumDocumento.Text := IntToStr(FREQUISICAO.NUMERO_DOCUMENTO); edLote.Text := IntToStr(FREQUISICAO.LOTE.ID); stLote.Caption := FREQUISICAO.LOTE.LOTE; edProduto.Text := IntToStr(FREQUISICAO.PRODUTO.ID); stNomeProduto.Caption := FREQUISICAO.PRODUTO.DESCRICAO; edQuantidade.Text := FloatToStr(FREQUISICAO.QUANTIDADE); edValorUnitario.Text := FloatToStr(FREQUISICAO.CUSTO_UNITARIO); edDepositoDestino.Text := IntToStr(FREQUISICAO.DEPOSITO_DESTINO.ID); stNomeDepositoDestino.Caption := FREQUISICAO.DEPOSITO_DESTINO.DESCRICAO; stNomeUsuario.Caption := FREQUISICAO.USUARIO.LOGIN; pnlStatus.Caption := FREQUISICAO.STATUS.NOME; if FREQUISICAO.DEPOSITO_ORIGEM.ID > 0 then begin edDepositoOrigem.Text := IntToStr(FREQUISICAO.DEPOSITO_ORIGEM.ID); stNomeDepositoOrigem.Caption := FREQUISICAO.DEPOSITO_ORIGEM.DESCRICAO; end; if FREQUISICAO.DATA_CANCELAMENTO > FREQUISICAO.DATA_ENTRADA then edDataCancelamento.Text := DateToStr(FREQUISICAO.DATA_CANCELAMENTO); SetaVisibilidadeDepositoOrigem; lblDataCancel.Visible := FREQUISICAO.STATUS.ID = 3; edDataCancelamento.Visible := FREQUISICAO.STATUS.ID = 3; end; procedure TFrmCadastroRequisicao.SetaVisibilidadeDepositoOrigem; begin lblDepositoOrigem.Visible := FREQUISICAO.TIPO_MOVIMENTACAO.ID = 2; stNomeDepositoOrigem.Visible := FREQUISICAO.TIPO_MOVIMENTACAO.ID = 2; edDepositoOrigem.Visible := FREQUISICAO.TIPO_MOVIMENTACAO.ID = 2; btnLocalizarDepositoOrigem.Visible := FREQUISICAO.TIPO_MOVIMENTACAO.ID = 2; end; end.
program PMMail_Sent_Status_Changer_1_1; (* This proggy changes the status of all messages in a PMMail 1.5 message directory to 'sent'. Useful when rebuilding the index of the Sent Mail folder or migrating it from PMMail 1.1 where PMMail 1.5 gives the messages the 'read' status. Copyright 1996-1997 Samuel Audet <guardia@cam.org> distribute freely! *) uses strings; const bagname = 'folder.bag'; (* index filenames *) bakname = 'folder.bak'; var bag,tmp_file : text; statpos : pchar; temp : array[0..400] of char; (* Enlarge if an entry of folder.bag is bigger. *) filename,changedir : string; begin Writeln('PMMail 1.5 Utilities 1.1, Sent Status Changer - Copyright 1996-1997 Samuel Audet'); changedir := paramstr(1); if (changedir <> '') and (copy(changedir,length(changedir),1) <> '\') then changedir := changedir + '\'; (* command line parameter formatting *) assign(bag,changedir + bagname); (* Renames the original folder.bag to folder.bak, and *) {$I-} rename(bag,changedir + bakname); {$I+} (* opens writing to folder.bag. *) case ioresult of 2: if changedir = '' then begin writeln('Error: ' + bagname + ' does not exist in the current directory'); halt; end else begin writeln('Error: ' + bagname + ' does not exist in ' + changedir); halt; end; 3: begin writeln('Error: the directory ' + changedir + ' does not exist'); halt; end; 5: begin assign(bag,changedir + bakname); erase(bag); assign(bag,changedir + bagname); rename(bag,changedir + bakname); end; end; assign(tmp_file,changedir + bagname); reset(bag); rewrite(tmp_file); while not eof(bag) do begin readln(bag,temp); statpos := strscan(temp,chr(222)); if statpos = nil then writeln('Error: bad entry in ' + changedir + bagname) else begin statpos := statpos - 1; statpos^ := '3'; (* change the current message status to 'sent' *) writeln(tmp_file,temp); end; end; close(bag); close(tmp_file); erase(bag); end.
// THIS DEMO IS PART OF THE GLSCENE PROJECT { Version History: 30.01.2008 - mrqzzz - Initial version. 06.02.2008 - mrqzzz - Added "RayCastIntersect" for Actorproxy in demo. 15.03.2008 - DaStr - Updated RayCastIntersect stuff because of changes in the TGLActorProxy component. } unit unit1; interface uses SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GLScene, GLProxyObjects, GLVectorFileObjects, GLObjects, VectorGeometry, ExtCtrls, GLCadencer, GLTexture, GLGeomObjects, GLViewer, GLFileSMD, StdCtrls, GLCrossPlatform, GLMaterial, GLCoordinates; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLMaterialLibrary1: TGLMaterialLibrary; GLCadencer1: TGLCadencer; GLCamera1: TGLCamera; InvisibleDummyCube: TGLDummyCube; GLDummyCube2: TGLDummyCube; MasterActor: TGLActor; GLActorProxy1: TGLActorProxy; GLArrowLine1: TGLArrowLine; GLLightSource1: TGLLightSource; Timer1: TTimer; GLSphere1: TGLSphere; GLArrowLine3: TGLArrowLine; GLActorProxy2: TGLActorProxy; GLArrowLine2: TGLArrowLine; Panel1: TPanel; cbActorsAreTurning: TCheckBox; procedure FormCreate(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); procedure Timer1Timer(Sender: TObject); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); private mousex, mousey: integer; procedure DoRaycastStuff; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.lfm} uses FileUtil; procedure TForm1.FormCreate(Sender: TObject); var i: integer; path: UTF8String; p: integer; begin path := ExtractFilePath(ParamStrUTF8(0)); p := Pos('DemosLCL', path); Delete(path, p + 5, Length(path)); path := IncludeTrailingPathDelimiter(path) + IncludeTrailingPathDelimiter('media'); SetCurrentDirUTF8(path); MasterActor.LoadFromFile('TRINITYrage.smd'); MasterActor.AddDataFromFile('run.smd'); MasterActor.AddDataFromFile('jump.smd'); MasterActor.Animations.Items[0].Name := 'still'; MasterActor.Animations.Items[1].Name := 'walk'; MasterActor.Animations.Items[2].Name := 'jump'; for i := 0 to MasterActor.Animations.Count - 1 do begin MasterActor.Animations[i].MakeSkeletalTranslationStatic; MasterActor.SwitchToAnimation(i); // forces animations to be initialized for ActorsProxies end; MasterActor.SwitchToAnimation(0); // revert back to empty animation (not necessary) MasterActor.AnimationMode := aamLoop; // animationmode is shared between proxies. GLActorProxy1.StoreBonesMatrix := True; GLActorProxy2.StoreBonesMatrix := True; GLActorProxy1.Animation := MasterActor.Animations[1].Name; GLActorProxy2.Animation := MasterActor.Animations[2].Name; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); begin // Align object to hand GLArrowLine1.Matrix := GLActorProxy1.BoneMatrix('Bip01 R Finger1'); GLArrowLine2.Matrix := GLActorProxy2.BoneMatrix('Bip01 R Finger1'); // turn actors if cbActorsAreTurning.Checked then begin GLActorProxy1.Turn(-deltaTime * 130); GLActorProxy2.Turn(deltaTime * 100); end; DoRaycastStuff; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); begin mousex := x; mouseY := y; end; procedure TForm1.DoRaycastStuff; var rayStart, rayVector, iPoint, iNormal: TVector; begin SetVector(rayStart, GLCamera1.AbsolutePosition); SetVector(rayVector, GLSceneViewer1.Buffer.ScreenToVector( AffineVectorMake(mousex, GLSceneViewer1.Height - mousey, 0))); NormalizeVector(rayVector); if GLActorProxy1.RayCastIntersect(rayStart, rayVector, @iPoint, @iNormal) then begin GLSphere1.Position.AsVector := iPoint; GLSphere1.Direction.AsVector := VectorNormalize(iNormal); end else if GLActorProxy2.RayCastIntersect(rayStart, rayVector, @iPoint, @iNormal) then begin GLSphere1.Position.AsVector := iPoint; GLSphere1.Direction.AsVector := VectorNormalize(iNormal); end else begin GLSphere1.Position.AsVector := rayStart; GLSphere1.Direction.AsVector := rayVector; end; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption := GLSceneViewer1.FramesPerSecondText(0); GLSceneViewer1.ResetPerformanceMonitor; end; end.
unit tExecuteTask; interface uses SysUtils, Classes, ShellAPI, OoMisc, uDMThread, ActiveX; type TSyncLogEvent = procedure(Sender: TObject; const Client: string) of object; TThreadExecuteTask = class(TThread) private { Private declarations } fSyncDate: TSyncLogEvent; FDMThread: TDMThread; FRepSince: Integer; FMainStore: Integer; FSQLBatchCount: Integer; FStoreList: TStringList; FStoreTables: WideString; FLocalPath: WideString; FConnectionString: WideString; FExcepTables: WideString; FGlobalTables: WideString; FClient: WideString; FDisableUpdateQty: Boolean; procedure ConfigureThread; protected procedure ExecuteJobs; procedure DoSyncDate; procedure Execute; override; public property OnSyncDate: TSyncLogEvent read fSyncDate write fSyncDate; property DMThread: TDMThread read FDMThread; property LocalPath: WideString read FLocalPath write FLocalPath; property ConnectionString: WideString read FConnectionString write FConnectionString; property RepSince: Integer read FRepSince write FRepSince; property MainStore: Integer read FMainStore write FMainStore; property StoreList: TStringList read FStoreList write FStoreList; property GlobalTables: WideString read FGlobalTables write FGlobalTables; property StoreTables: WideString read FStoreTables write FStoreTables; property ExcepTables: WideString read FExcepTables write FExcepTables; property SQLBatchCount: Integer read FSQLBatchCount write FSQLBatchCount; property Client: WideString read FClient write FClient; property DisableUpdateQty : Boolean read FDisableUpdateQty write FDisableUpdateQty; constructor Create(CreateSuspended: Boolean); destructor Destroy; override; end; implementation uses uDMServer, uDMRepl, uMainConf; { TThreadExecuteTask } procedure TThreadExecuteTask.DoSyncDate; begin if Assigned(fSyncDate) then fSyncDate(Self, fClient); end; procedure TThreadExecuteTask.ExecuteJobs; begin try fClient := FDMThread.Client; FDMThread.ExeSingleReplication; finally DoSyncDate; end; end; procedure TThreadExecuteTask.Execute; begin { Place thread code here } CoInitialize(nil); try FDMThread := TDMThread.Create(nil); try ConfigureThread; ExecuteJobs; finally FDMThread.Free; FDMThread := nil; end; finally CoUninitialize; end; end; constructor TThreadExecuteTask.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); FStoreList := TStringList.Create; end; destructor TThreadExecuteTask.Destroy; begin if FDMThread <> nil then FDMThread.Free; FStoreList.Free; inherited Destroy; end; procedure TThreadExecuteTask.ConfigureThread; begin FDMThread.LocalPath := FLocalPath; FDMThread.ConnectionString := FConnectionString; FDMThread.RepSince := FRepSince; FDMThread.MainStore := FMainStore; FDMThread.StoreList.Assign(FStoreList); FDMThread.GlobalTables := FGlobalTables; FDMThread.StoreTables := FStoreTables; FDMThread.ExcepTables := FExcepTables; FDMThread.SQLBatchCount := FSQLBatchCount; FDMThread.Client := FClient; FDMThread.DisableUpdateQty := FDisableUpdateQty; end; end.
{ Copyright (c) 1985, 87 by Borland International, Inc. } unit MCDISPLY; interface uses Crt, Dos, MCVars, MCUtil; var InsCursor, ULCursor, NoCursor, OldCursor : Word; procedure MoveToScreen(var Source, Dest; Len : Word); { Moves memory to screen memory } procedure MoveFromScreen(var Source, Dest; Len : Word); { Moves memory from screen memory } procedure WriteXY(S : String; Col, Row : Word); { Writes text in a particular location } procedure MoveText(OldX1, OldY1, OldX2, OldY2, NewX1, NewY1 : Word); { Moves text from one location to another } procedure Scroll(Direction, Lines, X1, Y1, X2, Y2, Attrib : Word); { Scrolls an area of the screen } function GetCursor : Word; { Returns the current cursor } procedure SetCursor(NewCursor : Word); { Sets a new cursor } function GetSetCursor(NewCursor : Word) : Word; { Sets a new cursor and returns the current one } procedure SetColor(Color : Word); { Sets the foreground and background color based on a single color } procedure PrintCol; { Prints the column headings } procedure PrintRow; { Prints the row headings } procedure ClearInput; { Clears the input line } procedure ChangeCursor(InsMode : Boolean); { Changes the cursor shape based on the current insert mode } procedure ShowCellType; { Prints the type of cell and what is in it } procedure PrintFreeMem; { Prints the amount of free memory } procedure ErrorMsg(S : String); { Prints an error message at the bottom of the screen } procedure WritePrompt(Prompt : String); { Prints a prompt on the screen } function EGAInstalled : Boolean; { Tests for the presence of an EGA } implementation const MaxLines = 43; type ScreenType = array[1..MaxLines, 1..80] of Word; ScreenPtr = ^ScreenType; var DisplayPtr : ScreenPtr; procedure MoveToScreen; external; procedure MoveFromScreen; external; {$L MCMVSMEM.OBJ} procedure WriteXY; begin GotoXY(Col, Row); Write(S); end; { WriteXY } procedure MoveText; var Counter, Len : Word; begin Len := Succ(OldX2 - OldX1) shl 1; if NewY1 < OldY1 then begin for Counter := 0 to OldY2 - OldY1 do MoveFromScreen(DisplayPtr^[OldY1 + Counter, OldX1], DisplayPtr^[NewY1 + Counter, NewX1], Len) end else begin for Counter := OldY2 - OldY1 downto 0 do MoveFromScreen(DisplayPtr^[OldY1 + Counter, OldX1], DisplayPtr^[NewY1 + Counter, NewX1], Len) end; end; { MoveText } procedure Scroll; begin if Lines = 0 then Window(X1, Y1, X2, Y2) else begin case Direction of UP : begin MoveText(X1, Y1 + Lines, X2, Y2, X1, Y1); Window(X1, Succ(Y2 - Lines), X2, Y2); end; DOWN : begin MoveText(X1, Y1, X2, Y2 - Lines, X1, Y1 + Lines); Window(X1, Y1, X2, Pred(Y1 + Lines)); end; LEFT : begin MoveText(X1 + Lines, Y1, X2, Y2, X1, Y1); Window(Succ(X2 - Lines), Y1, X2, Y2); end; RIGHT : begin MoveText(X1, Y1, X2 - Lines, Y2, X1 + Lines, Y1); Window(X1, Y1, Pred(X1 + Lines), Y2); end; end; { case } end; SetColor(Attrib); ClrScr; Window(1, 1, 80, ScreenRows + 5); end; { Scroll } function GetCursor; var Reg : Registers; begin with Reg do begin AH := 3; BH := 0; Intr($10, Reg); GetCursor := CX; end; { Reg } end; { GetCursor } procedure SetCursor; var Reg : Registers; begin with Reg do begin AH := 1; BH := 0; CX := NewCursor; Intr($10, Reg); end; { with } end; { SetCursor } function GetSetCursor; begin GetSetCursor := GetCursor; SetCursor(NewCursor); end; { GetSetCursor } procedure SetColor; begin TextAttr := ColorTable[Color]; end; { SetColor } procedure InitColorTable(BlackWhite : Boolean); { Sets up the color table } var Color, FG, BG, FColor, BColor : Word; begin if not BlackWhite then begin for Color := 0 to 255 do ColorTable[Color] := Color; end else begin for FG := Black to White do begin case FG of Black : FColor := Black; Blue..LightGray : FColor := LightGray; DarkGray..White : FColor := White; end; { case } for BG := Black to LightGray do begin if BG = Black then BColor := Black else begin if FColor = White then FColor := Black; BColor := LightGray; end; ColorTable[FG + (BG shl 4)] := FColor + (BColor shl 4); end; end; for FG := 128 to 255 do ColorTable[FG] := ColorTable[FG - 128] or $80; end; end; { InitColorTable } procedure PrintCol; var Col : Word; begin Scroll(UP, 0, 1, 2, 80, 2, HEADERCOLOR); for Col := LeftCol to RightCol do WriteXY(CenterColString(Col), ColStart[Succ(Col - LeftCol)], 2); end; { PrintCol } procedure PrintRow; var Row : Word; begin SetColor(HEADERCOLOR); for Row := 0 to Pred(ScreenRows) do WriteXY(Pad(WordToString(Row + TopRow, 1), LEFTMARGIN), 1, Row + 3); end; { PrintRow } procedure ClearInput; begin SetColor(TXTCOLOR); GotoXY(1, ScreenRows + 5); ClrEol; end; { ClearInput } procedure ChangeCursor; begin if InsMode then SetCursor(InsCursor) else SetCursor(ULCursor); end; { ChangeCursor } procedure ShowCellType; var ColStr : String[2]; S : IString; Color : Word; begin FormDisplay := not FormDisplay; S := CellString(CurCol, CurRow, Color, NOFORMAT); ColStr := ColString(CurCol); SetColor(CELLTYPECOLOR); GotoXY(1, ScreenRows + 3); if CurCell = Nil then Write(ColStr, CurRow, ' ', MSGEMPTY, ' ':10) else begin case CurCell^.Attrib of TXT : Write(ColStr, CurRow, ' ', MSGTEXT, ' ':10); VALUE : Write(ColStr, CurRow, ' ', MSGVALUE, ' ':10); FORMULA : Write(ColStr, CurRow, ' ', MSGFORMULA, ' ':10); end; { case } end; SetColor(CELLCONTENTSCOLOR); WriteXY(Pad(S, 80), 1, ScreenRows + 4); FormDisplay := not FormDisplay; end; { ShowCellType } procedure PrintFreeMem; begin SetColor(MEMORYCOLOR); GotoXY(Length(MSGMEMORY) + 2, 1); Write(MemAvail:6); end; { PrintFreeMem } procedure ErrorMsg; var Ch : Char; begin Sound(1000); { Beeps the speaker } Delay(500); NoSound; SetColor(ERRORCOLOR); WriteXY(S + ' ' + MSGKEYPRESS, 1, ScreenRows + 5); GotoXY(Length(S) + Length(MSGKEYPRESS) + 3, ScreenRows + 5); Ch := ReadKey; ClearInput; end; { ErrorMsg } procedure WritePrompt; begin SetColor(PROMPTCOLOR); GotoXY(1, ScreenRows + 4); ClrEol; Write(Prompt); end; { WritePrompt } procedure InitDisplay; { Initializes various global variables - must be called before using the above procedures and functions. } var Reg : Registers; begin Reg.AH := 15; Intr($10, Reg); ColorCard := Reg.AL <> 7; if ColorCard then DisplayPtr := Ptr($B800, 0) else DisplayPtr := Ptr($B000, 0); InitColorTable((not ColorCard) or (Reg.AL = 0) or (Reg.AL = 2)); end; { InitDisplay } function EGAInstalled; var Reg : Registers; begin Reg.AX := $1200; Reg.BX := $0010; Reg.CX := $FFFF; Intr($10, Reg); EGAInstalled := Reg.CX <> $FFFF; end; { EGAInstalled } begin InitDisplay; NoCursor := $2000; OldCursor := GetSetCursor(NoCursor); OldMode := LastMode; if (LastMode and Font8x8) <> 0 then ScreenRows := 38 else ScreenRows := 20; Window(1, 1, 80, ScreenRows + 5); if ColorCard then begin ULCursor := $0607; InsCursor := $0507; end else begin ULCursor := $0B0C; InsCursor := $090C; end; if EGAInstalled then begin UCommandString := UCOMMAND; UMenuString := UMNU; end else begin UCommandString := Copy(UCOMMAND, 1, 2); UMenuString := Copy(UMNU, 1, 23); end; end. 
unit uDMServiceOrder; interface uses SysUtils, Classes, DB, ADODB, PowerADOQuery, LookUpADOQuery, uSystemTypes; const SO_STATUS_OPEN = 1; SO_STATUS_CLOSE = 2; type TDMServiceOrder = class(TDataModule) LookUpSOStatus: TLookUpADOQuery; dsLookUpSOStatus: TDataSource; LookUpSOStatusIDSOStatus: TIntegerField; LookUpSOStatusSOStatus: TStringField; LookUpSOStatusColor: TStringField; dsSOCutomerProduct: TDataSource; LookUpSOCutomerProduct: TLookUpADOQuery; LookUpSOCutomerProductIDSOCustomerProduct: TIntegerField; LookUpSOCutomerProductModel: TStringField; LookUpSOCutomerProductDescription: TStringField; spApplyPayDiscount: TADOStoredProc; function LookUpSOStatusClickButton(Sender: TPowerADOQuery; ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean; function LookUpSOCutomerProductClickButton(Sender: TPowerADOQuery; ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean; private { Private declarations } public function DeleteSO(AIDSO : Integer) : Boolean; function DeleteSOItem(AIDSOItem : Integer) : Boolean; function ApplyPaymentDiscount(AIDSO : Integer; APercent : Double) : Boolean; end; var DMServiceOrder: TDMServiceOrder; implementation uses uDM, uFchSOStatus,uFchSOCustomerProduct; {$R *.dfm} function TDMServiceOrder.DeleteSOItem(AIDSOItem : Integer): Boolean; begin try DM.ADODBConnect.BeginTrans; DM.RunSQL('DELETE InventoryMov WHERE DocumentID IN (SELECT IDSOItemProduct FROM Ser_SOItemProduct WHERE IDSOItem = '+ InttoStr(AIDSOItem)+') AND InventMovTypeID = 50'); DM.RunSQL('DELETE Ser_SOItemProduct WHERE IDSOItem = ' + InttoStr(AIDSOItem)); DM.RunSQL('DELETE Ser_SOItemDefect WHERE IDSOItem = ' + InttoStr(AIDSOItem)); DM.RunSQL('DELETE Ser_SOItem WHERE IDSOItem = ' + InttoStr(AIDSOItem)); DM.ADODBConnect.CommitTrans; Result := True; except DM.ADODBConnect.RollbackTrans; raise; Result := False; end; end; function TDMServiceOrder.DeleteSO(AIDSO: Integer): Boolean; var sSQL : String; begin try DM.ADODBConnect.BeginTrans; sSQL := 'DELETE InventoryMov ' + 'WHERE InventMovTypeID = 50 AND DocumentID IN (SELECT SOI.IDSOItemProduct FROM Ser_SOItemProduct SOI ' + 'JOIN Ser_SOItem SO ON (SOI.IDSOItem = SO.IDSOItem) ' + 'WHERE SO.IDServiceOrder = ' + IntToStr(AIDSO) + ' ) '; DM.RunSQL(sSQL); sSQL := 'DELETE SOI FROM Ser_SOItemProduct SOI ' + 'JOIN Ser_SOItem SO ON ((SOI.IDSOItem = SO.IDSOItem)) ' + 'WHERE SO.IDServiceOrder = ' + IntToStr(AIDSO); DM.RunSQL(sSQL); sSQL := 'DELETE SOD FROM Ser_SOItemDefect SOD ' + 'JOIN Ser_SOItem SO ON (SOD.IDSOItem = SO.IDSOItem) ' + 'WHERE SO.IDServiceOrder = ' + IntToStr(AIDSO); DM.RunSQL(sSQL); sSQL := 'DELETE Ser_SOItem WHERE IDServiceOrder = ' + IntToStr(AIDSO); DM.RunSQL(sSQL); sSQL := 'DELETE History WHERE IDServiceOrder = ' + IntToStr(AIDSO); DM.RunSQL(sSQL); sSQL := 'DELETE Ser_ServiceOrder WHERE IDServiceOrder = ' + IntToStr(AIDSO); DM.RunSQL(sSQL); DM.ADODBConnect.CommitTrans; Result := True; except DM.ADODBConnect.RollbackTrans; raise; Result := False; end; end; function TDMServiceOrder.LookUpSOStatusClickButton(Sender: TPowerADOQuery; ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean; begin if (DM.IsFormsRestric('FchSOStatus') and (ClickedButton = btInc))then Exit; with TFchSOStatus.Create(Self) do begin Result := Start(ClickedButton, Sender, False, PosID1, PosID2, nil); Free; end; end; function TDMServiceOrder.LookUpSOCutomerProductClickButton( Sender: TPowerADOQuery; ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean; begin if (DM.IsFormsRestric('FchSOCustomerProduct') and (ClickedButton = btInc))then Exit; with TFchSOCustomerProduct.Create(Self) do begin Result := Start(ClickedButton, Sender, False, PosID1, PosID2, nil); Free; end; end; function TDMServiceOrder.ApplyPaymentDiscount(AIDSO: Integer; APercent: Double): Boolean; begin with spApplyPayDiscount do try Parameters.ParambyName('@IDServiceOrder').Value := AIDSO; Parameters.ParambyName('@PercDiscount').Value := APercent; ExecProc; Result := True; except Result := False; end; end; end.
unit HierarchyAnimation; interface uses BasicMathsTypes, TransformAnimation; {$INCLUDE source/Global_Conditionals.inc} type THierarchyAnimation = class private FDesiredTimeRate: int64; FTransformFramesPerSecond: single; FTransformLastChange: int64; public // Euclidean transformations CurrentTransformationFrame: integer; ExecuteTransformAnimation: boolean; ExecuteTransformAnimationLoop: boolean; CurrentTransformAnimation: integer; NumTransformationFrames: integer; NumSectors: integer; TransformAnimations: array of TTransformAnimation; // constructors and destructors constructor Create(_NumSectors, _NumFrames: integer); overload; constructor Create(_NumSectors: integer); overload; constructor Create(const _Source: THierarchyAnimation); overload; destructor Destroy; override; procedure Initialize; procedure Clear; procedure Reset(_NumSectors, _NumFrames: integer); // Executes procedure ExecuteAnimation(_NumSection: integer); overload; procedure ExecuteAnimation(const _Scale:TVector3f; _NumSection: integer); overload; function DetectTransformationAnimationFrame: boolean; procedure ApplyPivot(_Pivot: TVector3f); procedure PlayTransformAnim; procedure PauseTransformAnim; procedure StopTransformAnim; // Sets procedure SetTransformFPS(_FPS: single); // Copy procedure Assign(const _Source: THierarchyAnimation); end; PHierarchyAnimation = ^THierarchyAnimation; implementation uses Math3D, dglOpenGL, Windows; constructor THierarchyAnimation.Create(_NumSectors: integer); begin NumSectors := _NumSectors; NumTransformationFrames := 1; Initialize; end; constructor THierarchyAnimation.Create(_NumSectors, _NumFrames: integer); begin NumSectors := _NumSectors; NumTransformationFrames := _NumFrames; Initialize; end; constructor THierarchyAnimation.Create(const _Source: THierarchyAnimation); begin Assign(_Source); end; destructor THierarchyAnimation.Destroy; begin Clear; SetLength(TransformAnimations, 0); inherited Destroy; end; procedure THierarchyAnimation.Initialize; begin QueryPerformanceCounter(FTransformLastChange); CurrentTransformationFrame := 0; CurrentTransformAnimation := 0; ExecuteTransformAnimation := false; ExecuteTransformAnimationLoop := false; FTransformFramesPerSecond := 0; SetLength(TransformAnimations, 1); TransformAnimations[0] := TTransformAnimation.Create(NumSectors, NumTransformationFrames); end; procedure THierarchyAnimation.Clear; var i: integer; begin for i := Low(TransformAnimations) to High(TransformAnimations) do begin TransformAnimations[i].Free; end; end; procedure THierarchyAnimation.Reset(_NumSectors, _NumFrames: integer); begin Clear; NumSectors := _NumSectors; NumTransformationFrames := _NumFrames; Initialize; end; // Executes procedure THierarchyAnimation.ExecuteAnimation(_NumSection: integer); begin TransformAnimations[CurrentTransformAnimation].ApplyMatrix(_NumSection, CurrentTransformationFrame); end; procedure THierarchyAnimation.ExecuteAnimation(const _Scale: TVector3f; _NumSection: integer); begin TransformAnimations[CurrentTransformAnimation].ApplyMatrix(_Scale, _NumSection, CurrentTransformationFrame); end; function THierarchyAnimation.DetectTransformationAnimationFrame: boolean; var temp : int64; t2: int64; begin Result := false; if ExecuteTransformAnimation then begin // determine the current frame here if FTransformFramesPerSecond > 0 then begin QueryPerformanceCounter(temp); t2 := temp - FTransformLastChange; if t2 >= FDesiredTimeRate then begin CurrentTransformationFrame := (CurrentTransformationFrame + 1) mod NumTransformationFrames; Result := true; if (not (ExecuteTransformAnimationLoop)) and (CurrentTransformationFrame = 0) then begin ExecuteTransformAnimation := false; end; QueryPerformanceCounter(FTransformLastChange); end; end else begin CurrentTransformationFrame := (CurrentTransformationFrame + 1) mod NumTransformationFrames; Result := true; if (not (ExecuteTransformAnimationLoop)) and (CurrentTransformationFrame = 0) then begin ExecuteTransformAnimation := false; end; end; end; end; procedure THierarchyAnimation.ApplyPivot(_Pivot: TVector3f); begin glTranslatef(_Pivot.X, _Pivot.Y, _Pivot.Z); end; procedure THierarchyAnimation.PlayTransformAnim; begin CurrentTransformationFrame := 0; ExecuteTransformAnimation := true; end; procedure THierarchyAnimation.PauseTransformAnim; begin ExecuteTransformAnimation := false; end; procedure THierarchyAnimation.StopTransformAnim; begin CurrentTransformationFrame := 0; ExecuteTransformAnimation := false; end; // Sets procedure THierarchyAnimation.SetTransformFPS(_FPS: single); var Frequency: int64; begin FTransformFramesPerSecond := _FPS; if FTransformFramesPerSecond > 0 then begin QueryPerformanceFrequency(Frequency); // get high-resolution Frequency FDesiredTimeRate := Round(Frequency / FTransformFramesPerSecond); end; end; // Copy procedure THierarchyAnimation.Assign(const _Source: THierarchyAnimation); var i: integer; begin FDesiredTimeRate := _Source.FDesiredTimeRate; FTransformFramesPerSecond := _Source.FTransformFramesPerSecond; FTransformLastChange := _Source.FTransformLastChange; CurrentTransformationFrame := _Source.CurrentTransformationFrame; ExecuteTransformAnimation := _Source.ExecuteTransformAnimation; ExecuteTransformAnimationLoop := _Source.ExecuteTransformAnimationLoop; CurrentTransformAnimation := _Source.CurrentTransformAnimation; NumTransformationFrames := _Source.NumTransformationFrames; NumSectors := _Source.NumSectors; SetLength(TransformAnimations, High(_Source.TransformAnimations) + 1); for i := Low(TransformAnimations) to High(TransformAnimations) do begin TransformAnimations[i] := TTransformAnimation.Create(_Source.TransformAnimations[i]); end; end; end.
unit mpofiles; {$mode objfpc}{$H+} interface uses Classes, SysUtils, strutils; (* PO file entry as defined in chapter 3 The Format of PO Files (https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html#PO-Files) of GNU gettext utilities white-space # translator-comments #. extracted-comments #: reference… #, flag… #| msgctxt previous-context #| msgid previous-untranslated-string msgctxt context msgid untranslated-string msgstr translated-string The format for the #, flag line is: #, fuzzy, format-string [, format-string] To my knowledge, Lazarus never generates translator-comments extracted-commants previous-context fields in PO files and fuzzy is the only flag used } *) type { TPoEntry } TPoEntry = class private FTranslatorComments: TStrings; // #<space> FExtractedComments: TStrings; // #. FReference: string; // #: FFlag: string; // #, FPrevmsgctxt: string; // #| msgctxt FPrevmsgid: TStrings; // #| msgid FMsgctxt: string; // msgctxt FMsgid: TStrings; // msgid FMsgstr: TStrings; // msgstr FIsFuzzy: boolean; protected procedure SetFuzzy(value: boolean); public { True if another entry has the same reference. This field is for use by the TPoFile.UpdateCount method only. } HasDuplicateReference: boolean; { True if another entry has the same msgid. This field is for use by the TPoFile.UpdateCount method only. } HasDuplicateMsgid: boolean; { True if another entry has the same msgstr. This field is for use by the TPoFile.UpdateCount method only. } HasDuplicateMsgstr: boolean; constructor Create; destructor Destroy; override; { Properties HasDuplicateReference, HasDuplicateMsgid, HasDuplicateMsgstr, and IsAmbiguous are set to false, and the other fields are copied from source. } procedure Assign(source: TPoEntry); { Override of parent Equals to handle objects that are of type TPoEntry } function Equals(Obj: TObject): Boolean; override; overload; { Returns true if the entry and the source entry have the same reference, msgid and msgstr} function Equals(source: TPoEntry): boolean; overload; { Returns true if msgid in not empty } function HasMsgid: boolean; { Returns true if msgstr is not empty } function HasMsgstr: boolean; { Returns true if prevmsgid is not empty } function HasPrevmsgid: boolean; { PO entry translator-comments field } property TranslatorComments: TStrings read FTranslatorComments; { PO entry extracted-comments field } property ExtractedComments: TStrings read FExtractedComments; { PO entry reference field. In the Free Pascal / Lazarus implemenation this is a fully qualified name to a resource string (something like TForm1.Label3.caption) guaranteed to be unique if the application compiles.} property Reference: string read FReference; { PO entry flag field. Only the fuzzy flag is used here, but format flags will not be changed. This is a read only property, use the IsFuzzy property to add or remove "fuzzy" from the Flag property.} property Flag: string read FFlag; { PO entry previous-context field. } property Prevmsgctxt: string read FPrevmsgctxt; { PO entry previious-unstranslated-string field} property Prevmsgid: TStrings read FPrevmsgid; { PO entry context field. If present in a Free Pascal / Lazarus generated file, it will be the qualitifed name in Reference. The context is in quotes in the PO file, but they are stripped here} property Msgctxt: string read FMsgctxt; { PO entry untranslated-string field. These strings are quoted in the PO file but not in here} property Msgid: TStrings read FMsgId; { PO entry translated-string field. These strings are quoted in the PO file but not in here} property Msgstr: TStrings read FMsgstr; property IsFuzzy: boolean read FisFuzzy write SetFuzzy; end; { TPoFile } TPoFile = class private FList: TList; FFilename: string; FPrevmsgidCount: integer; FDuplicateReferenceCount: integer; FDuplicateMsgidCount: integer; FDuplicateMsgstrCount: integer; FMissingReferenceCount: integer; FErrorCount: integer; FFuzzyCount: integer; FEmptyMsgidCount: integer; FEmptyMsgstrCount: integer; FVerbose: boolean; protected function Compare(i,j: integer): integer; procedure Exchange(i, j: integer); function FoundMsgid(const value: TStrings; lastIndex: integer): integer; function FoundMsgstr(const value: TStrings; lastIndex: integer): integer; function FoundReference(const value: string; lastIndex: integer): integer; function GetCount: integer; function GetEntry(index: integer): TPoEntry; function LastEntry: TPoEntry; procedure LoadFile; procedure QuickSort(L, R: Integer); procedure SetFilename(const aFilename: string); procedure UpdateCounts; public { Creates an empty PO file object. By default Verbose is true. Set the filename property to load a PO file.) } constructor Create; { Creates a PO file object, sets the Verbose flag to false and then quietly loads aFilename} constructor Create(const aFilename: string); destructor Destroy; override; { Removes all PO Entries } procedure Clear; { Deletes the PO Entry at the specified Index} procedure Delete(Index: integer); { Searches all Entries from 0 to Index-1 and returns the index of the first of the searched entries that is equal to Entries[Index]. If none of the previous entries is equal then returns -1. Entries are duplicates if they have the same reference, msgid and msgstr (see TPoEntry.Equals). It should be safe to eliminate such duplicates.} function FindDuplicateEntry(Index: integer): integer; { Returns true if Entries[0] is a header entry without reference, without msgid but with a msgstr. There is no check of the validity of the meta data in msgstr.} function HasHeader: boolean; { Searches all Entries starting at Index 0 and returns the Index of the first entry that has the same msgid. If none is found returns -1. The string comparison is case sensitive.} function IndexOfMsgid(const Value: TStrings): integer; { Searches all Entries starting at Index 0 and returns the Index of the first entry that has the same reference. If none is found returns -1. While references generated by the Lazarus IDE are always lower case, Pascal identifiers are case insensitive so the string comparison is case insensitive.} function IndexOfReference(const Value: string): integer; { Inserts a blank TPoEntry at the specified position in the Entries array. If Index = Count, then this effectively adds a blank TPoEntry.} function Insert(Index: integer): TPoEntry; { Save the Entries to a text file of the given name. If the trimmed aFilename is empty, the procedure does nothing. If the Filename property is blank then it is set to aFilename without calling LoadFile.} procedure SaveToFile(const aFilename: string); { Alphabetically sorts the Entries according to their reference. } procedure Sort; { Updates counts and writes summary statistics } procedure WriteStatistics(const filelabel: string; const aFilename: string = ''); { Number of entries } property Count: integer read GetCount; { Number of entries with a reference already in the .po file. Empty references are ignored } property DuplicateReferenceCount: integer read FDuplicateReferenceCount; { Number of entries with a msgid already in the .po file. Empty msgid are ignored } property DuplicateMsgidCount: integer read FDuplicateMsgidCount; { Number of entries with a msgstr already in the .po file. Empty msgstr are ignored } property DuplicateMsgstrCount: integer read FDuplicateMsgstrCount; { Array of all TPoEntry Found in the file } property Entries[Index: integer]: TPoEntry read GetEntry; default; { Number of errors encountered in the LoadFile method } property ErrorCount: integer read FErrorCount; { Name of file containing the source of the object. It is set explicitely with the assignment Filename := aFilename implicetly with the constructor create(aFilename). In both cases the or explicitely} property Filename: string read FFilename write SetFilename; { Number of Entries with the fuzzy attribute } property FuzzyCount: integer read FFuzzyCount; { Number of entries with a empty msgid } property EmptyMsgidCount: integer read FEmptyMsgidCount; { Number of entries with a empty msgstr } property EmptyMsgstrCount: integer read FEmptyMsgstrCount; { Number of entries that do not have a reference. } property MissingReferenceCount: integer read FMissingReferenceCount; { Number of entries with an alternate msgid } property PrevmsgidCount: integer read FPrevmsgidCount; { Flag that determines if LoadFile is verbose or not. See constructors. } property Verbose: boolean read FVerbose write FVerbose; end; implementation { TPoEntry } constructor TPoEntry.Create; begin inherited create; FTranslatorComments := TStringList.create; FExtractedComments := TStringList.create; Fprevmsgid := TStringList.create; Fmsgid := TStringList.create; Fmsgstr := TStringList.create; end; destructor TPoEntry.Destroy; begin msgstr.free; msgid.free; prevmsgid.free; extractedcomments.free; translatorcomments.free; inherited destroy; end; procedure TPoEntry.Assign(source: TPoEntry); begin HasDuplicateReference := false; HasDuplicateMsgid := false; HasDuplicateMsgstr := false; FIsFuzzy := source.IsFuzzy; FTranslatorComments.assign(source.translatorcomments); FExtractedComments.assign(source.extractedcomments); FReference := source.Reference; FFlag := source.Flag; FPrevmsgctxt := source.prevmsgctxt; Fmsgctxt := source.msgctxt; Fmsgid.assign(source.msgid); Fmsgstr.assign(source.msgstr); Fprevmsgid.assign(source.prevmsgid); end; function TPoEntry.Equals(Obj: TObject): Boolean; begin if Obj is TPoEntry then Result := Equals(TPoEntry(Obj)) else Result := inherited Equals(Obj); end; function TPoEntry.Equals(source: TPoEntry): boolean; begin result := (Reference = source.Reference) and msgid.Equals(source.msgid) and msgstr.Equals(source.msgstr) end; function TPoEntry.HasPrevmsgid: boolean; begin result := ((prevmsgid.Count = 1) and ( prevmsgid[0] <> '')) or (prevmsgid.Count > 1); end; function TPoEntry.HasMsgid: boolean; begin result := ((msgid.Count = 1) and ( msgid[0] <> '')) or (msgid.Count > 1); end; function TPoEntry.HasMsgstr: boolean; begin result := ((msgstr.Count = 1) and ( msgstr[0] <> '')) or (msgstr.Count > 1); end; procedure TPoEntry.SetFuzzy(value: boolean); var i: integer; sl: TStrings; wd: string; begin i := pos('fuzzy', FFlag); if (i > 0) and not value then begin FIsFuzzy := false; sl := TStringList.create; try i := 1; repeat wd := trim(ExtractWord(i, FFlag, [','])); inc(i); if wd = 'fuzzy' then continue else if wd <> '' then sl.add(wd); until wd = ''; if sl.count = 0 then FFlag := '' else begin FFlag := sl[0]; for i := 1 to sl.count-1 do FFlag := FFlag + ', ' + sl[i]; end; finally sl.free; end; end else if (i < 0) and value then begin if length(FFlag) > 0 then FFlag := 'fuzzy, ' + FFlag else FFlag := 'fuzzy'; FIsFuzzy := true; end; end; { TPoFile } constructor TPoFile.Create; begin inherited; FList := TList.Create; Clear; FVerbose := true; end; constructor TPoFile.Create(const aFilename: string); begin create; FVerbose := false; FFilename := trim(aFilename); if FFilename <> '' then LoadFile; end; destructor TPoFile.Destroy; begin Clear; FList.free; inherited destroy; end; procedure TPoFile.Clear; var i: integer; begin for i := FList.Count-1 downto 0 do TPoEntry(FList[i]).Free; FList.Clear; FPrevmsgidCount := -1; FDuplicateReferenceCount := -1; FDuplicateMsgidCount := -1; FDuplicateMsgstrCount := -1; FMissingReferenceCount := -1; FErrorCount := -1; FFuzzyCount := -1; FEmptyMsgidCount := -1; FEmptyMsgstrCount := -1; end; function TPoFile.Compare(i,j: integer): integer; // compare function for sort begin // Possible comparisons of two references //result := CompareStrt(Entries[i].Reference, Entries[j].Reference); // case sensitve, ASCII only //result := CompareText(Entries[i].Reference, Entries[j].Reference); // case insensitive, ASCII only //result := AnsiCompareStr(Entries[i].Reference, Entries[j].Reference); // case sensitve, ignore accents result := AnsiCompareText(Entries[i].Reference, Entries[j].Reference); // case insensitive, ignore accents //result := UnicodeCpareStr(Entries[i].Reference, Entries[j].Reference); // case sensitive needs unit cwstrings //result := UnicodeCompareText(Entries[i].Reference, Entries[j].Reference); // case insensitive end; procedure TPoFile.Delete(Index: integer); begin TPoEntry(FList[Index]).free; Flist.delete(Index); end; procedure TPoFile.Exchange(i, j: integer); var temp: TPoEntry; begin if i = j then exit; temp := TPoEntry.create; temp.assign(Entries[i]); Entries[i].assign(Entries[j]); Entries[j].assign(temp); temp.free; end; function TPoFile.FindDuplicateEntry(Index: integer): integer; var i: integer; begin for i := 0 to Index-1 do begin if Entries[i].Equals(Entries[Index]) then begin result := i; exit; end; end; result := -1; end; function TPoFile.HasHeader: boolean; begin result := (Count > 0) and not Entries[0].Hasmsgid; end; function TPoFile.FoundReference(const Value: string; lastIndex: integer): integer; var i: integer; begin for i := 0 to lastIndex-1 do if AnsiSameText(Entries[i].Reference, Value) then begin result := i; exit; end; result := -1; end; function TPoFile.FoundMsgid(const value: TStrings; lastIndex: integer): integer; var i: integer; begin for i := 0 to lastIndex-1 do if Entries[i].msgid.Equals(value) then begin result := i; exit; end; result := -1; end; function TPoFile.FoundMsgstr(const value: TStrings; lastIndex: integer): integer; var i: integer; begin for i := 0 to lastIndex-1 do if Entries[i].msgstr.Equals(value) then begin result := i; exit; end; result := -1; end; function TPoFile.GetCount: integer; begin result := FList.Count; end; function TPoFile.GetEntry(Index: integer): TPoEntry; begin result := TPoEntry(FList[Index]); end; function TPoFile.IndexOfReference(const Value: string): integer; begin result := FoundReference(Value, Count); end; function TPoFile.IndexOfMsgid(const Value: TStrings): integer; begin result := FoundMsgId(value, count); end; function TPoFile.Insert(Index: integer): TPoEntry; begin result := TPoEntry.create; FList.Insert(Index, result); end; procedure TPoFile.QuickSort(L, R: Integer); var Pivot, vL, vR: Integer; begin if R - L <= 1 then begin // a little bit of time saver if L < R then if Compare(L, R) > 0 then Exchange(L, R); Exit; end; vL := L; vR := R; Pivot := L + Random(R - L); // they say random is best while vL < vR do begin while (vL < Pivot) and (Compare(vL, Pivot) <= 0) do Inc(vL); while (vR > Pivot) and (Compare(vR, Pivot) > 0) do Dec(vR); Exchange(vL, vR); if Pivot = vL then // swap pivot if we just hit it from one side Pivot := vR else if Pivot = vR then Pivot := vL; end; if Pivot - 1 >= L then QuickSort(L, Pivot - 1); if Pivot + 1 <= R then QuickSort(Pivot + 1, R); end; function TPoFile.LastEntry: TPoEntry; begin result := TPoEntry(FList[FList.Count-1]); end; type TReadStatus = ( rsIdle, // starting rsTranslatorComments, rsExtractedComments, rsReference, rsFlag, rsPrevMsgctxt, rsPrevMsgid, rsMsgctxt, rsMsgId, rsMsgstr, rsError); procedure TPoFile.LoadFile; var src: TextFile; currentLineNumber: integer; currentLine: string; // trimmed current line from src status: TReadStatus; procedure Report(const msg: string); begin if FVerbose then begin writeln(FErrorCount:6, ' Error: ', msg, ' in line ', currentLineNumber) end; end; procedure CheckLastEntry; begin if Count < 1 then exit; if (Count = 1) and (Entries[0].Reference = '') then with Entries[0] do begin if HasMsgid then begin inc(FErrorCount); Report('Entry 0 with no reference has an msgid'); end; if not HasMsgstr then begin inc(FErrorCount); Report('Entry 0 with no reference does not have a msgstr'); end; end else with Entries[Count-1] do begin if Reference = '' then begin inc(FErrorCount); Report(Format('Entry %d does not have a reference', [Count-1])); end; if not HasMsgid then begin inc(FErrorCount); Report(Format('Entry %d (%s) does not have a msgid', [Count-1, Reference])); end; end; end; procedure AddEntry; begin CheckLastEntry; Insert(Count); end; function StartsWith(const value: string): boolean; begin result := value = copy(currentLine, 1, length(value)); end; procedure ReadTranslatorComments; { # a comment } begin system.delete(currentline, 1, 2); if status in [rsIdle, rsMsgId, rsMsgstr, rsError] then AddEntry; LastEntry.TranslatorComments.add(trim(currentLine)); status := rsTranslatorComments; end; procedure ReadExtractedComments; { #. a comment } begin system.delete(currentline, 1, 2); if status in [rsIdle, rsMsgId, rsMsgstr, rsError] then AddEntry; LastEntry.ExtractedComments.add(trim(currentLine)); status := rsExtractedComments; end; procedure ReadFlag; (* #, flag {, flag} where flag = fuzzy | format-string *) begin system.delete(currentLine, 1, 2); // delete leading #, currentLine := trim(currentLine); if length(currentLine) < 1 then begin status := rsError; inc(FErrorCount); Report('missing flag (fuzzy or format-string)'); exit; end; if status in [rsIdle, rsMsgId, rsMsgstr, rsError] then AddEntry; LastEntry.FFlag := currentLine; LastEntry.FIsFuzzy := pos('fuzzy', currentLine) > 0; status := rsFlag; end; procedure ReadReference; { #: tform1.caption } begin system.delete(currentLine, 1, 2); // skip #: if status in [rsIdle, rsMsgId, rsMsgstr, rsError] then AddEntry else if LastEntry.FReference <> '' then begin inc(FErrorCount); Report('Reference already defined'); end; LastEntry.FReference := trim(currentLine); // removes any leading space if LastEntry.Reference = '' then begin inc(FErrorCount); Report('Reference empty'); end; status := rsReference; end; procedure ReadPrevious; { #| msgctxt "oldctxt" or #| msgid "oldid" or #| msgid "" #| "Default names\n" #| "(%d is number)\n" } var q, n: integer; begin if status in [rsIdle, rsMsgId, rsMsgstr, rsError] then AddEntry; system.delete(currentLine, 1, 2); // eliminate #| currentLine := trim(currentLine); if startsWith('msgctxt') then begin status := rsPrevMsgctxt; if (LastEntry.Prevmsgctxt <> '') then begin inc(FErrorCount); Report('More than one #| msgctxt'); // carry on end; end else if startsWith('msgid') then begin status := rsPrevmsgId; if LastEntry.HasPrevmsgid then begin inc(FErrorCount); Report('More than one #| msgid'); // carry on end; end else if status <> rsPrevmsgId then begin inc(FErrorCount); Report('Previous context should be only one line'); status := rsError; exit; end; q := pos('"', currentLine); if q < 1 then begin inc(FErrorCount); status := rsError; Report('Missing leading " quote in prevmsgid'); exit; end; system.delete(currentLine, 1, q); n := length(currentLine); if currentLine[n] = '"' then system.delete(currentLine, n, 1) else begin inc(FErrorCount); Report('Missing trailing " quote in prevmsgid'); // carry on as if ok end; if status = rsPrevmsgId then LastEntry.prevmsgid.Add(currentLine) else if status = rsPrevmsgctxt then begin LastEntry.Fprevmsgctxt := currentLine; if currentLine = '' then begin inc(FErrorCount); Report('Missing previous msgctxt'); end; end; end; {ReadExtraLines #: appconsts.ssavefilechanges msgid "" "Save changes to\n" "%currentLine\n" "before proceeding?\n" msgstr "" } procedure ReadExtraLine; var n: integer; begin system.delete(currentLine, 1, 1); // delete first " n := length(currentLine); if currentLine[n] = '"' then system.delete(currentLine, n, 1); if status = rsmsgId then LastEntry.msgid.Add(currentLine) else if status = rsMsgstr then LastEntry.msgstr.Add(currentLine) else if status = rsPrevmsgid then LastEntry.prevmsgid.Add(currentLine) else begin status := rsError; inc(FErrorCount); Report('Line starting with " quote while not in msgid, msgstr or altmsgid section'); end; end; procedure ReadMsgctxt; var q, n: integer; begin if status in [rsIdle, rsMsgId, rsMsgstr, rsError] then AddEntry; q := pos('"', currentLine); if q < 1 then begin inc(FErrorCount); status := rsError; Report('Missing leading " quote in msgctx'); exit; end; system.delete(currentLine, 1, q); n := length(currentLine); if currentLine[n] = '"' then system.delete(currentLine, n, 1) else begin inc(FErrorCount); Report('Missing trailing " quote in msgctx'); // carry on as if ok end; LastEntry.FMsgctxt := trim(currentLine); status := rsMsgctxt; end; procedure ReadMsgid; var q, n: integer; begin if status in [rsIdle, rsMsgstr, rsError] then begin AddEntry; // starting new entry end; // msg must start with " quote q := pos('"', currentLine); if q < 1 then begin inc(FErrorCount); status := rsError; Report('Missing leading " quote in msgid'); exit; end; system.delete(currentLine, 1, q); // ignore 'msgid "' n := length(currentLine); if currentLine[n] = '"' then system.delete(currentLine, n, 1) else begin inc(FErrorCount); Report('Missing trailing " quote in msgid'); // carry on as if ok end; LastEntry.msgid.add(currentLine); status := rsMsgid; end; procedure ReadMsgstr; var q, n: integer; begin if status in [rsIdle, rsError] then AddEntry; q := pos('"', currentLine); if q < 1 then begin inc(FErrorCount); status := rsError; Report('Missing leading " quote in msgstr'); exit; end; system.delete(currentLine, 1, q); n := length(currentLine); if currentLine[n] = '"' then system.delete(currentLine, n, 1) else begin inc(FErrorCount); Report('Missing trailing " quote in msgstr'); // carry on as if ok end; LastEntry.msgstr.add(currentLine); //Writeln('dbg: Added msgstr in line ', currentLineNumber); status := rsMsgstr; end; begin if not fileexists(Filename) then begin if fileexists(Filename + '.po') then FFilename := FFilename + '.po' else Raise Exception.CreateFmt('"%s" does not exist', [Filename]); end; status := rsIdle; FErrorCount := 0; assign(src, Filename); currentLineNumber := 0; try reset(src); while not eof(src) do begin readln(src, currentLine); inc(currentLineNumber); currentLine := trim(currentLine); if currentLine = '' then continue else if currentLine = '#' then currentLine := '# '; // allow empty translator comment //writeln('dbg: ', currentline); if currentLine[1] = '"' then ReadExtraLine else if currentLine[1] = '#' then begin if length(currentLine) < 2 then begin status := rsError; inc(FErrorCount); Report('Missing operand after #'); continue; end; case currentLine[2] of ' ': ReadTranslatorComments; '.': ReadExtractedComments; ',': ReadFlag; ':': ReadReference; '|': ReadPrevious; else begin status := rsError; inc(FErrorCount); Report('Unknown operand afer #'); continue; end; end; end else if StartsWith('msgctxt') then ReadMsgctxt else if StartsWith('msgid') then ReadMsgid else if StartsWith('msgstr') then ReadMsgstr else begin status := rsError; inc(FErrorCount); Report('Unknow msg identifier'); end; end; finally CheckLastEntry; closefile(src); end; end; procedure TPoFile.SaveToFile(const aFilename: string); var dst: Textfile; i,j: integer; begin if trim(aFilename) = '' then exit; if FFilename = '' then FFilename := trim(aFilename); assign(dst, trim(aFilename)); try rewrite(dst); for i := 0 to Count-1 do with Entries[i] do begin // dbg:: writeln(Format('Writing entry %d, reference: <%s>', [i, reference])); if i > 0 then writeln(dst); for j := 0 to TranslatorComments.count-1 do writeln(dst, '# ', TranslatorComments[j]); for j := 0 to ExtractedComments.count-1 do writeln(dst, '#. ', ExtractedComments[j]); if Reference <> '' then writeln(dst, '#: ', Reference); if Flag <> '' then writeln(dst, '#, ', Flag); if Prevmsgctxt <> '' then writeln(dst, '#| msgctxt "', Prevmsgctxt, '"'); if (prevmsgid.Count > 0) then begin writeln(dst, '#| msgid "', Prevmsgid[0], '"'); for j := 1 to prevmsgid.count-1 do writeln(dst, '#| "', Prevmsgid[j], '"'); end; if msgctxt <> '' then writeln(dst, 'msgctxt "', Msgctxt, '"'); if (msgid.count = 0) then writeln(dst, 'msgid ""') else begin writeln(dst, 'msgid "', msgid[0], '"'); for j := 1 to msgid.count-1 do writeln(dst, '"', msgid[j], '"'); end; if (msgstr.count = 0) then writeln(dst, 'msgstr ""') else begin writeln(dst, 'msgstr "', Msgstr[0], '"'); for j := 1 to msgstr.count-1 do writeln(dst, '"', Msgstr[j], '"'); end; { #: dmulist.sinvalidperiods #, fuzzy msgctxt "dmulist.sinvalidperiods" msgid "%d is an invalid number of periods" msgstr "Nombre de périodes, %d, incorrect" } end; finally closefile(dst); end; end; procedure TPoFile.SetFilename(const aFilename: string); begin if AnsiCompareFilename(aFilename, FFilename) = 0 then exit; FFilename := aFilename; Clear; if FFilename <> '' then LoadFile end; procedure TPoFile.Sort; var first: integer; begin if Count < 2 then exit; if HasHeader then first := 1 else first := 0; QuickSort(first, FList.Count-1); end; procedure TPoFile.WriteStatistics(const filelabel: string; const aFilename: string); var Ecount: integer; procedure writeStat(const msg: string; value: integer); begin if (value > 0) then writeln(' ', msg, ': ', value, Format(' (%.1f%%)', [100*value/Ecount])) else if Verbose then writeln(' ', msg, ': ', value) end; begin UpdateCounts; write(Filelabel, ': '); if aFilename <> '' then writeln(aFilename) else writeln(Filename); writeln(' Errors: ', ErrorCount); if hasHeader then begin Ecount := Count-1; writeln(' Entries: ', Ecount, ' plus a header'); end else begin Ecount := Count; writeln(' Entries: ', Ecount, ' and no header'); end; writestat('Missing references', MissingReferenceCount); writestat('Duplicate references', DuplicateReferenceCount); writestat('Empty msgids', EmptyMsgidCount); writestat('Duplicate msgids', DuplicateMsgidCount); if Verbose then writestat('Previous msgids', PrevMsgidCount); writestat('Empty msgstrs', EmptyMsgstrCount); writestat('Duplicate msgstrs', DuplicateMsgstrCount); writestat('Fuzzys', FuzzyCount); end; procedure TPoFile.UpdateCounts; var i, first: integer; begin FPrevmsgidCount := 0; FDuplicateReferenceCount := 0; FDuplicateMsgidCount := 0; FDuplicateMsgstrCount := 0; FMissingReferenceCount := 0; //FErrorCount := 0; FFuzzyCount := 0; FEmptyMsgidCount := 0; FEmptyMsgstrCount := 0; if HasHeader then first := 1 else first := 0; for i := first to Count-1 do begin if (Entries[i].Reference = '') then inc(FMissingReferenceCount) else Entries[i].HasDuplicateReference := FoundReference(Entries[i].Reference, i) >= 0; if Entries[i].HasMsgid then begin Entries[i].HasDuplicateMsgid := FoundMsgId(Entries[i].msgid, i) >= 0; end else inc(FEmptyMsgidCount); if Entries[i].HasMsgstr then Entries[i].HasDuplicateMsgstr := FoundMsgstr(Entries[i].msgstr, i) >= 0 else inc(FEmptyMsgstrCount); if Entries[i].HasPrevmsgid then inc(FPrevmsgidCount); if Entries[i].HasDuplicateReference then inc(FDuplicateReferenceCount); if Entries[i].HasDuplicateMsgid then inc(FDuplicateMsgIdCount); if Entries[i].HasDuplicateMsgstr then inc(FDuplicateMsgstrCount); if Entries[i].IsFuzzy then inc(FFuzzyCount); end; end; end.
unit uFrUninstall; interface {$WARN SYMBOL_PLATFORM OFF} uses System.SysUtils, System.Classes, Winapi.Windows, Winapi.Messages, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uInstallFrame, uInstallUtils, uTranslate, uMemory, uConstants, uInstallScope, uAssociations, uVistaFuncs; type TFrUninstall = class(TInstallFrame) cbYesUninstall: TCheckBox; GbUninstallOptions: TGroupBox; CbDeleteAllRegisteredCollection: TCheckBox; CbUnInstallAllUserSettings: TCheckBox; procedure YesUninstallClick(Sender: TObject); procedure CbDeleteAllRegisteredCollectionClick(Sender: TObject); private FDeletingColectionBlockWarning: Boolean; { Private declarations } public { Public declarations } procedure Init; override; procedure LoadLanguage; override; function ValidateFrame: Boolean; override; procedure InitInstall; override; end; implementation {$R *.dfm} { TFrLicense } procedure TFrUninstall.YesUninstallClick(Sender: TObject); begin CbUnInstallAllUserSettings.Enabled := cbYesUninstall.Checked; CbDeleteAllRegisteredCollection.Enabled := cbYesUninstall.Checked; FrameChanged; end; procedure TFrUninstall.CbDeleteAllRegisteredCollectionClick(Sender: TObject); begin if FDeletingColectionBlockWarning then Exit; FDeletingColectionBlockWarning := True; try if ID_YES <> TaskDialog(0, L('Do you really want to delete all collection files (*.photodb)?'), TA('Warning'), '', TD_BUTTON_YESNO, TD_ICON_WARNING) then CbDeleteAllRegisteredCollection.Checked := False; finally FDeletingColectionBlockWarning := False; end; end; procedure TFrUninstall.Init; begin inherited; FDeletingColectionBlockWarning := False; cbYesUninstall.OnClick := YesUninstallClick; CurrentInstall.IsUninstall := True; end; procedure TFrUninstall.InitInstall; var I: Integer; begin inherited; for I := 0 to TFileAssociations.Instance.Count - 1 do TFileAssociations.Instance[I].State := TAS_UNINSTALL; CurrentInstall.DestinationPath := IncludeTrailingBackslash(ExtractFileDir(GetInstalledFileName)); CurrentInstall.UninstallOptions.DeleteUserSettings := CbUnInstallAllUserSettings.Checked; CurrentInstall.UninstallOptions.DeleteAllCollections := CbDeleteAllRegisteredCollection.Checked; end; procedure TFrUninstall.LoadLanguage; begin inherited; cbYesUninstall.Caption := L('Yes, I want to uninstall this program'); CbUnInstallAllUserSettings.Caption := L('Delete all user settings'); CbDeleteAllRegisteredCollection.Caption := L('Delete all registered collections'); GbUninstallOptions.Caption := L('Uninstall options'); end; function TFrUninstall.ValidateFrame: Boolean; begin Result := cbYesUninstall.Checked; end; end.
unit frmPestUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, frmCustomGoPhastUnit, Vcl.StdCtrls, JvPageList, JvExControls, Vcl.ComCtrls, JvExComCtrls, JvPageListTreeView, ArgusDataEntry, PestPropertiesUnit, Vcl.Buttons, Vcl.ExtCtrls, UndoItems, frameGridUnit, frameAvailableObjectsUnit, PestObsUnit, frameParentChildUnit, PestObsGroupUnit, System.Generics.Collections, Vcl.Mask, JvExMask, JvToolEdit; type TPestObsGroupColumn = (pogcName, pogcUseTarget, pogcTarget, pogcFileName); TUndoPestOptions = class(TCustomUndo) private FOldPestProperties: TPestProperties; FNewPestProperties: TPestProperties; FOldObsList: TObservationObjectList; FNewObsList: TObservationObjectList; OldPestLocation: string; NewPestLocation: string; protected function Description: string; override; procedure UpdateProperties(PestProperties: TPestProperties; ObsList: TObservationList); public constructor Create(var NewPestProperties: TPestProperties; var NewObsList: TObservationObjectList; PestDirectory: String); destructor Destroy; override; procedure DoCommand; override; procedure Undo; override; end; TfrmPEST = class(TfrmCustomGoPhast) tvPEST: TJvPageListTreeView; plMain: TJvPageList; jvspBasic: TJvStandardPage; cbPEST: TCheckBox; rdePilotPointSpacing: TRbwDataEntry; lblPilotPointSpacing: TLabel; cbShowPilotPoints: TCheckBox; pnlBottom: TPanel; btnHelp: TBitBtn; btnOK: TBitBtn; btnCancel: TBitBtn; comboTemplateCharacter: TComboBox; lblTemplateCharacter: TLabel; comboFormulaMarker: TComboBox; lblFormulaMarker: TLabel; jvspControlDataMode: TJvStandardPage; cbSaveRestart: TCheckBox; lblPestMode: TLabel; comboPestMode: TComboBox; jvspDimensions: TJvStandardPage; rdeMaxCompDim: TRbwDataEntry; lblMaxCompDim: TLabel; rdeZeroLimit: TRbwDataEntry; lblZeroLimit: TLabel; jvspInversionControls: TJvStandardPage; rdeInitialLambda: TRbwDataEntry; lblInitialLambda: TLabel; rdeLambdaAdj: TRbwDataEntry; comboLambdaAdj: TLabel; rdeIterationClosure: TRbwDataEntry; lblIterationClosure: TLabel; rdeLambdaTermination: TRbwDataEntry; lblLambdaTermination: TLabel; rdeMaxLambdas: TRbwDataEntry; lblMaxLambdas: TLabel; rdeJacobianUpdate: TRbwDataEntry; lblJacobianUpdate: TLabel; cbLamForgive: TCheckBox; cbDerForgive: TCheckBox; jvspParameterAdjustmentControls: TJvStandardPage; rdeMaxRelParamChange: TRbwDataEntry; lblMaxRelParamChange: TLabel; rdeMaxFacParamChange: TRbwDataEntry; lblMaxFacParamChange: TLabel; rdeFactorOriginal: TRbwDataEntry; lblFactorOriginal: TLabel; rdeBoundStick: TRbwDataEntry; lblBoundStick: TLabel; cbParameterBending: TCheckBox; jvspInversionControls2: TJvStandardPage; rdeSwitchCriterion: TRbwDataEntry; lblSwitchCriterion: TLabel; rdeSwitchCount: TRbwDataEntry; lblSwitchCount: TLabel; rdeSplitSlopeCriterion: TRbwDataEntry; lblSplitSlopeCriterion: TLabel; comboAutomaticUserIntervation: TComboBox; lblAutomaticUserIntervation: TLabel; cbSensitivityReuse: TCheckBox; cbBoundsScaling: TCheckBox; jvspIterationControls: TJvStandardPage; rdeMaxIterations: TRbwDataEntry; lblMaxIterations: TLabel; rdePhiReductionCriterion: TRbwDataEntry; lblPhiReductionCriterion: TLabel; rdePhiReductionCount: TRbwDataEntry; lblPhiReductionCount: TLabel; rdeNoReductionCount: TRbwDataEntry; lblNoReductionCount: TLabel; rdeSmallParameterReduction: TRbwDataEntry; rdeSmallParameterReductionCount: TRbwDataEntry; lblSmallParameterReduction: TLabel; lblrdeSmallParameterReductionCount: TLabel; rdePhiStoppingThreshold: TRbwDataEntry; lblPhiStoppingThreshold: TLabel; cbLastRun: TCheckBox; rdeAbandon: TRbwDataEntry; lblAbandon: TLabel; jvspOutputOptions: TJvStandardPage; jvspSingularValueDecomp: TJvStandardPage; cbWriteCov: TCheckBox; cbWriteCorrCoef: TCheckBox; cbWriteEigenvectors: TCheckBox; cbWriteResolution: TCheckBox; cbWriteJacobian: TCheckBox; cbWriteJacobianEveryIteration: TCheckBox; cbWriteVerboseRunRecord: TCheckBox; cbWriteIntermResidualForEveryIteration: TCheckBox; cbSaveParamValuesIteration: TCheckBox; cbSaveParamValuesModelRun: TCheckBox; splMain: TSplitter; comboSvdMode: TComboBox; lblSvdMode: TLabel; rdeMaxSingularValues: TRbwDataEntry; lblMaxSingularValues: TLabel; rdeEigenThreshold: TRbwDataEntry; lblEigenThreshold: TLabel; comboEigenWrite: TComboBox; lblEigenWrite: TLabel; jvspLqsr: TJvStandardPage; cbUseLqsr: TCheckBox; rdeMatrixTolerance: TRbwDataEntry; lblMatrixTolerance: TLabel; rdeRightHandSideTolerance: TRbwDataEntry; lblRightHandSideTolerance: TLabel; rdeConditionNumberLimit: TRbwDataEntry; lblConditionNumberLimit: TLabel; rdeMaxLqsrIterations: TRbwDataEntry; lblMaxLqsrIterations: TLabel; cbWriteLsqrOutput: TCheckBox; jvspObservationGroups: TJvStandardPage; frameObservationGroups: TframeGrid; dlgOpenCovarianceMatrixFile: TOpenDialog; jvspObsGroupAssignments: TJvStandardPage; frameParentObsGroups: TframeParentChild; diredPest: TJvDirectoryEdit; lblPestDirectory: TLabel; procedure FormCreate(Sender: TObject); override; procedure MarkerChange(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure cbUseLqsrClick(Sender: TObject); procedure comboSvdModeChange(Sender: TObject); procedure frameObservationGroupsGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure frameObservationGroupsGridButtonClick(Sender: TObject; ACol, ARow: Integer); procedure FormDestroy(Sender: TObject); override; procedure plMainChange(Sender: TObject); procedure frameObservationGroupssbDeleteClick(Sender: TObject); procedure frameObservationGroupssbInsertClick(Sender: TObject); procedure frameObservationGroupsseNumberChange(Sender: TObject); procedure frameObservationGroupsGridSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string); procedure diredPestChange(Sender: TObject); // procedure comboObsGroupChange(Sender: TObject); private FObsList: TObservationList; FNewObsList: TObservationObjectList; FLocalObsGroups: TPestObservationGroups; InvalidateModelEvent: TNotifyEvent; FGroupDictionary: TDictionary<TPestObservationGroup, TTreeNode>; FGroupNameDictionary: TDictionary<string, TPestObservationGroup>; FNoNameNode: TTreeNode; procedure GetData; procedure SetData; procedure FixObsGroupNames; procedure HandleGroupDeletion(Group: TPestObservationGroup); procedure HandleAddedGroup(ObsGroup: TPestObservationGroup); procedure CheckPestDirectory; { Private declarations } public // procedure btnOK1Click(Sender: TObject); { Public declarations } end; var frmPEST: TfrmPEST; const StrNone = '(none)'; implementation uses frmGoPhastUnit, GoPhastTypes, RbwDataGrid4, JvComCtrls, PhastModelUnit; resourcestring StrObservationGroupNa = 'Observation Group Name (OBGNME)'; StrUseGroupTargetGT = 'Use Group Target (GTARG)'; StrGroupTargetGTARG = 'Group Target (GTARG)'; StrCovarianceMatrixFi = 'Covariance Matrix File Name (optional) (COVFLE)'; {$R *.dfm} procedure TfrmPEST.MarkerChange(Sender: TObject); begin inherited; if comboTemplateCharacter.Text = comboFormulaMarker.Text then begin comboTemplateCharacter.Color := clRed; comboFormulaMarker.Color := clRed; Beep; end else begin comboTemplateCharacter.Color := clWindow; comboFormulaMarker.Color := clWindow; end; end; procedure TfrmPEST.plMainChange(Sender: TObject); var Grid: TRbwDataGrid4; RowIndex: Integer; begin inherited; if plMain.ActivePage = jvspObservationGroups then begin FixObsGroupNames; // comboObsGroup.Items.Clear; // comboObsGroup.Items.Capacity := frameObservationGroups.seNumber.AsInteger; Grid := frameObservationGroups.Grid; for RowIndex := 1 to frameObservationGroups.seNumber.AsInteger do begin if Grid.Cells[Ord(pogcName), RowIndex] <> '' then begin // comboObsGroup.Items.AddObject(Grid.Cells[Ord(pogcName), RowIndex], // Grid.Objects[Ord(pogcName), RowIndex]); end; end; end; end; procedure TfrmPEST.btnOKClick(Sender: TObject); begin inherited; SetData; end; procedure TfrmPEST.cbUseLqsrClick(Sender: TObject); begin inherited; if cbUseLqsr.Checked then begin comboSvdMode.ItemIndex := 0; end; end; //procedure TfrmPEST.comboObsGroupChange(Sender: TObject); //var // AName: string; // ObsIndex: Integer; // AnObs: TCustomObservationItem; //begin // inherited; // if comboObsGroup.ItemIndex >= 0 then // begin // AName := comboObsGroup.Text; // frameObsGroupAssignments.lbSrcObjects.Items.BeginUpdate; // frameObsGroupAssignments.lbDstObjects.Items.BeginUpdate; // try // frameObsGroupAssignments.lbSrcObjects.Items.Clear; // frameObsGroupAssignments.lbDstObjects.Items.Clear; // for ObsIndex := 0 to FNewObsList.Count - 1 do // begin // AnObs := FNewObsList[ObsIndex]; // if AnObs.ObservationGroup = AName then // begin // // end; // end; // finally // frameObsGroupAssignments.lbDstObjects.Items.EndUpdate; // frameObsGroupAssignments.lbSrcObjects.Items.EndUpdate; // end; // end; //end; procedure TfrmPEST.comboSvdModeChange(Sender: TObject); begin inherited; if comboSvdMode.ItemIndex > 0 then begin cbUseLqsr.Checked := False; end; end; procedure TfrmPEST.diredPestChange(Sender: TObject); begin inherited; CheckPestDirectory; end; procedure TfrmPEST.FormCreate(Sender: TObject); var NewNode: TJvPageIndexNode; ControlDataNode: TJvPageIndexNode; ObservationNode: TJvPageIndexNode; begin inherited; FObsList := TObservationList.Create; FNewObsList := TObservationObjectList.Create; InvalidateModelEvent := nil; FLocalObsGroups := TPestObservationGroups.Create(InvalidateModelEvent); FGroupDictionary := TDictionary<TPestObservationGroup, TTreeNode>.Create; FGroupNameDictionary := TDictionary<string, TPestObservationGroup>.Create; NewNode := tvPEST.Items.AddChild( nil, 'Basic') as TJvPageIndexNode; NewNode.PageIndex := jvspBasic.PageIndex; ControlDataNode := tvPEST.Items.AddChild( nil, 'Control Data') as TJvPageIndexNode; ControlDataNode.PageIndex := -1; NewNode := tvPEST.Items.AddChild( ControlDataNode, 'Mode') as TJvPageIndexNode; NewNode.PageIndex := jvspControlDataMode.PageIndex; NewNode := tvPEST.Items.AddChild( ControlDataNode, 'Dimensions') as TJvPageIndexNode; NewNode.PageIndex := jvspDimensions.PageIndex; NewNode := tvPEST.Items.AddChild( ControlDataNode, 'Inversion Controls 1') as TJvPageIndexNode; NewNode.PageIndex := jvspInversionControls.PageIndex; NewNode := tvPEST.Items.AddChild( ControlDataNode, 'Parameter Adjustment Controls') as TJvPageIndexNode; NewNode.PageIndex := jvspParameterAdjustmentControls.PageIndex; NewNode := tvPEST.Items.AddChild( ControlDataNode, 'Inversion Controls 2') as TJvPageIndexNode; NewNode.PageIndex := jvspInversionControls2.PageIndex; NewNode := tvPEST.Items.AddChild( ControlDataNode, 'Iteration Controls') as TJvPageIndexNode; NewNode.PageIndex := jvspIterationControls.PageIndex; NewNode := tvPEST.Items.AddChild( ControlDataNode, 'Output') as TJvPageIndexNode; NewNode.PageIndex := jvspOutputOptions.PageIndex; NewNode := tvPEST.Items.AddChild( nil, 'Singular Value Decomposition') as TJvPageIndexNode; NewNode.PageIndex := jvspSingularValueDecomp.PageIndex; NewNode := tvPEST.Items.AddChild( nil, 'LQSR') as TJvPageIndexNode; NewNode.PageIndex := jvspLqsr.PageIndex; ObservationNode := tvPEST.Items.AddChild( nil, 'Observations') as TJvPageIndexNode; ControlDataNode.PageIndex := -1; NewNode := tvPEST.Items.AddChild( ObservationNode, 'Observation Groups') as TJvPageIndexNode; NewNode.PageIndex := jvspObservationGroups.PageIndex; NewNode := tvPEST.Items.AddChild( ObservationNode, 'Observation Group Assignments') as TJvPageIndexNode; NewNode.PageIndex := jvspObsGroupAssignments.PageIndex; plMain.ActivePageIndex := 0; GetData end; procedure TfrmPEST.FormDestroy(Sender: TObject); begin inherited; FGroupNameDictionary.Free; FGroupDictionary.Free; FLocalObsGroups.Free; FObsList.Free; FNewObsList.Free; end; procedure TfrmPEST.frameObservationGroupsGridButtonClick(Sender: TObject; ACol, ARow: Integer); begin inherited; dlgOpenCovarianceMatrixFile.FileName := frameObservationGroups.Grid.Cells[ACol, ARow]; if dlgOpenCovarianceMatrixFile.Execute then begin frameObservationGroups.Grid.Cells[ACol, ARow] := dlgOpenCovarianceMatrixFile.FileName; end; end; procedure TfrmPEST.frameObservationGroupsGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin inherited; if (ARow > 0) and (ACol = Ord(pogcTarget)) then begin CanSelect := frameObservationGroups.Grid.Checked[Ord(pogcUseTarget), ARow]; end; end; procedure TfrmPEST.frameObservationGroupsGridSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string); var Grid: TRbwDataGrid4; Group: TPestObservationGroup; OtherGroup: TPestObservationGroup; TreeNode: TTreeNode; begin inherited; Grid := frameObservationGroups.Grid; if (ARow >= Grid.FixedRows) and (ACol = Ord(pogcName)) then begin Group := Grid.Objects[ACol, ARow] as TPestObservationGroup; if Group <> nil then begin if FGroupNameDictionary.TryGetValue(UpperCase(Group.ObsGroupName), OtherGroup) then begin if Group = OtherGroup then begin FGroupNameDictionary.Remove(UpperCase(Group.ObsGroupName)); end; end; Group.ObsGroupName := ValidObsGroupName(Value); if Group.ObsGroupName <> '' then begin if not FGroupNameDictionary.ContainsKey(UpperCase(Group.ObsGroupName)) then begin FGroupNameDictionary.Add(UpperCase(Group.ObsGroupName), Group) end; end; if FGroupDictionary.TryGetValue(Group, TreeNode) then begin TreeNode.Text := Group.ObsGroupName; end; end; end; end; procedure TfrmPEST.frameObservationGroupssbDeleteClick(Sender: TObject); var Grid: TRbwDataGrid4; Group: TPestObservationGroup; begin inherited; Grid := frameObservationGroups.Grid; if Grid.SelectedRow >= Grid.FixedRows then begin if Grid.Objects[Ord(pogcName), Grid.SelectedRow] <> nil then begin Group := Grid.Objects[Ord(pogcName), Grid.SelectedRow] as TPestObservationGroup; HandleGroupDeletion(Group); Group.Free; Grid.Objects[Ord(pogcName), Grid.SelectedRow] := nil; end; end; frameObservationGroups.sbDeleteClick(Sender); end; procedure TfrmPEST.frameObservationGroupssbInsertClick(Sender: TObject); var NewGroup: TPestObservationGroup; Grid: TRbwDataGrid4; begin inherited; Grid := frameObservationGroups.Grid; NewGroup := nil; if Grid.SelectedRow >= Grid.FixedRows then begin NewGroup := FLocalObsGroups.Add; end; frameObservationGroups.sbInsertClick(Sender); if NewGroup <> nil then begin Grid.Objects[Ord(pogcName), Grid.SelectedRow] := NewGroup; NewGroup.Index := Grid.SelectedRow -1; HandleAddedGroup(NewGroup); end; end; procedure TfrmPEST.frameObservationGroupsseNumberChange(Sender: TObject); var Grid: TRbwDataGrid4; NewGroup: TPestObservationGroup; Names: TStrings; OldGroup: TPestObservationGroup; index: Integer; begin inherited; Grid := frameObservationGroups.Grid; Names := Grid.Cols[Ord(pogcName)]; frameObservationGroups.seNumberChange(Sender); while frameObservationGroups.seNumber.AsInteger > FLocalObsGroups.Count do begin NewGroup := FLocalObsGroups.Add; Grid.Objects[Ord(pogcName), FLocalObsGroups.Count] := NewGroup; NewGroup.ObsGroupName := ValidObsGroupName( Grid.Cells[Ord(pogcName), FLocalObsGroups.Count]); HandleAddedGroup(NewGroup); end; while frameObservationGroups.seNumber.AsInteger < FLocalObsGroups.Count do begin OldGroup := FLocalObsGroups.Last as TPestObservationGroup; index := Names.IndexOfObject(OldGroup); HandleGroupDeletion(OldGroup); OldGroup.Free; if index >= 1 then begin Grid.Objects[Ord(pogcName),index] := nil; end; end; end; procedure TfrmPEST.GetData; var PestProperties: TPestProperties; PestControlData: TPestControlData; SvdProperties: TSingularValueDecompositionProperties; LsqrProperties: TLsqrProperties; Grid: TRbwDataGrid4; ObsGroups: TPestObservationGroups; ItemIndex: Integer; ObsGroup: TPestObservationGroup; index: Integer; AnObs: TCustomObservationItem; ATempObs: TCustomObservationItem; Tree: TTreeView; NewNode: TTreeNode; GroupIndex: Integer; TreeNode: TTreeNode; Locations: TProgramLocations; // InvalidateModelEvent: TNotifyEvent; begin Locations := frmGoPhast.PhastModel.ProgramLocations; PestProperties := frmGoPhast.PhastModel.PestProperties; {$REGION 'PEST Basic'} cbPEST.Checked := PestProperties.PestUsed; comboTemplateCharacter.ItemIndex := comboTemplateCharacter.Items.IndexOf(PestProperties.TemplateCharacter); comboFormulaMarker.ItemIndex := comboFormulaMarker.Items.IndexOf(PestProperties.ExtendedTemplateCharacter); cbShowPilotPoints.Checked := PestProperties.ShowPilotPoints; rdePilotPointSpacing.RealValue := PestProperties.PilotPointSpacing; diredPest.Text := Locations.PestDirectory; CheckPestDirectory; {$ENDREGION} {$REGION 'Control Data'} PestControlData := PestProperties.PestControlData; cbSaveRestart.Checked := Boolean(PestControlData.PestRestart); comboPestMode.ItemIndex := Ord(PestControlData.PestMode); {$ENDREGION} {$REGION 'Dimensions'} rdeMaxCompDim.IntegerValue := PestControlData.MaxCompressionDimension; rdeZeroLimit.RealValue := PestControlData.ZeroLimit; {$ENDREGION} {$REGION 'Inversion Controls'} rdeInitialLambda.RealValue := PestControlData.InitalLambda; rdeLambdaAdj.RealValue := PestControlData.LambdaAdjustmentFactor; rdeIterationClosure.RealValue := PestControlData.PhiRatioSufficient; rdeLambdaTermination.RealValue := PestControlData.PhiReductionLambda; rdeMaxLambdas.IntegerValue := PestControlData.NumberOfLambdas; rdeJacobianUpdate.IntegerValue := PestControlData.JacobianUpdate; cbLamForgive.Checked := Boolean(PestControlData.LambdaForgive); cbDerForgive.Checked := Boolean(PestControlData.DerivedForgive); {$ENDREGION} {$REGION 'Parameter Adjustment Controls'} rdeMaxRelParamChange.RealValue := PestControlData.RelativeMaxParamChange; rdeMaxFacParamChange.RealValue := PestControlData.FactorMaxParamChange; rdeFactorOriginal.RealValue := PestControlData.FactorOriginal; rdeBoundStick.IntegerValue := PestControlData.BoundStick; cbParameterBending.Checked := Boolean(PestControlData.UpgradeParamVectorBending); {$ENDREGION} {$REGION 'Inversion Controls 2'} rdeSwitchCriterion.RealValue := PestControlData.SwitchCriterion; rdeSwitchCount.IntegerValue := PestControlData.OptSwitchCount; rdeSwitchCriterion.RealValue := PestControlData.SplitSlopeCriterion; comboAutomaticUserIntervation.ItemIndex := Ord(PestControlData.AutomaticUserIntervation); cbSensitivityReuse.Checked := Boolean(PestControlData.SensitivityReuse); cbBoundsScaling.Checked := Boolean(PestControlData.Boundscaling); {$ENDREGION} {$REGION 'Iteration Controls'} rdeMaxIterations.IntegerValue := PestControlData.MaxIterations; rdePhiReductionCriterion.RealValue := PestControlData.SlowConvergenceCriterion; rdePhiReductionCount.IntegerValue := PestControlData.SlowConvergenceCountCriterion; rdeNoReductionCount.IntegerValue := PestControlData.ConvergenceCountCriterion; rdeSmallParameterReduction.RealValue := PestControlData.ParameterChangeConvergenceCriterion; rdeSmallParameterReductionCount.IntegerValue := PestControlData.ParameterChangeConvergenceCount; rdePhiStoppingThreshold.RealValue := PestControlData.ObjectiveCriterion; cbLastRun.Checked := Boolean(PestControlData.MakeFinalRun); rdeAbandon.RealValue := PestControlData.PhiAbandon; {$ENDREGION} {$REGION 'Output Controls'} cbWriteCov.Checked := Boolean(PestControlData.WriteCovariance); cbWriteCorrCoef.Checked := Boolean(PestControlData.WriteCorrelations); cbWriteEigenvectors.Checked := Boolean(PestControlData.WriteEigenVectors); cbWriteResolution.Checked := Boolean(PestControlData.SaveResolution); cbWriteJacobian.Checked := Boolean(PestControlData.SaveJacobian); cbWriteJacobianEveryIteration.Checked := Boolean(PestControlData.SaveJacobianIteration); cbWriteVerboseRunRecord.Checked := Boolean(PestControlData.VerboseRecord); cbWriteIntermResidualForEveryIteration.Checked := Boolean(PestControlData.SaveInterimResiduals); cbSaveParamValuesIteration.Checked := Boolean(PestControlData.SaveParamIteration); cbSaveParamValuesModelRun.Checked := Boolean(PestControlData.SaveParamRun); {$ENDREGION} {$REGION 'Singular Value Decomposition'} SvdProperties := PestProperties.SvdProperties; comboSvdMode.ItemIndex := Ord(SvdProperties.Mode); rdeMaxSingularValues.IntegerValue := SvdProperties.MaxSingularValues; rdeEigenThreshold.RealValue := SvdProperties.EigenThreshold; comboEigenWrite.ItemIndex := Ord(SvdProperties.EigenWrite); {$ENDREGION} {$REGION 'LQSR'} LsqrProperties := PestProperties.LsqrProperties; cbUseLqsr.Checked := Boolean(LsqrProperties.Mode); rdeMatrixTolerance.RealValue := LsqrProperties.MatrixTolerance; rdeRightHandSideTolerance.RealValue := LsqrProperties.RightHandSideTolerance; rdeConditionNumberLimit.RealValue := LsqrProperties.ConditionNumberLimit; rdeMaxLqsrIterations.IntegerValue := LsqrProperties.MaxIteration; cbWriteLsqrOutput.Checked := Boolean(LsqrProperties.LsqrWrite); {$ENDREGION} {$REGION 'Observation Groups'} ObsGroups := nil; Grid := frameObservationGroups.Grid; Grid.BeginUpdate; try Grid.Cells[Ord(pogcName), 0] := StrObservationGroupNa; Grid.Cells[Ord(pogcUseTarget), 0] := StrUseGroupTargetGT; Grid.Cells[Ord(pogcTarget), 0] := StrGroupTargetGTARG; Grid.Cells[Ord(pogcFileName), 0] := StrCovarianceMatrixFi; ObsGroups := PestProperties.ObservationGroups; FLocalObsGroups.Assign(ObsGroups); frameObservationGroups.seNumber.AsInteger := FLocalObsGroups.Count; for ItemIndex := 0 to FLocalObsGroups.Count - 1 do begin ObsGroup := FLocalObsGroups[ItemIndex]; Grid.Objects[Ord(pogcName), ItemIndex+1] := ObsGroup; Grid.Cells[Ord(pogcName), ItemIndex+1] := ObsGroup.ObsGroupName; Grid.Checked[Ord(pogcUseTarget), ItemIndex+1] := ObsGroup.UseGroupTarget; Grid.RealValue[Ord(pogcTarget), ItemIndex+1] := ObsGroup.GroupTarget; Grid.Cells[Ord(pogcFileName), ItemIndex+1] := ObsGroup.AbsoluteCorrelationFileName; end; finally Grid.EndUpdate; if ObsGroups <> nil then begin frameObservationGroups.seNumber.AsInteger := ObsGroups.Count; end; end; {$ENDREGION} {$REGION 'Observation Group Assignments'} FGroupDictionary.Clear; FGroupNameDictionary.Clear; Tree := frameParentObsGroups.tvTree; Tree.Items.Clear; FNoNameNode := Tree.Items.AddChild(nil, StrNone); for GroupIndex := 0 to FLocalObsGroups.Count - 1 do begin ObsGroup := FLocalObsGroups[GroupIndex]; HandleAddedGroup(ObsGroup); end; frmGoPhast.PhastModel.FillObsItemList(FObsList, True); FNewObsList.Capacity := FObsList.Count; for index := 0 to FObsList.Count - 1 do begin AnObs := FObsList[index]; ATempObs := TCustomObservationItem.Create(nil); FNewObsList.Add(ATempObs); ATempObs.Assign(AnObs); if FGroupNameDictionary.TryGetValue(UpperCase(ATempObs.ObservationGroup), ObsGroup) then begin if FGroupDictionary.TryGetValue(ObsGroup, TreeNode) then begin NewNode := Tree.Items.AddChild(TreeNode, ATempObs.Name); end else begin NewNode := Tree.Items.AddChild(FNoNameNode, ATempObs.Name); end; end else begin NewNode := Tree.Items.AddChild(FNoNameNode, ATempObs.Name); end; NewNode.Data := ATempObs; end; {$ENDREGION} end; procedure TfrmPEST.SetData; var PestProperties: TPestProperties; InvalidateModelEvent: TNotifyEvent; PestControlData: TPestControlData; SvdProperties: TSingularValueDecompositionProperties; LsqrProperties: TLsqrProperties; RowIndex: Integer; Grid: TRbwDataGrid4; ObsGroups: TPestObservationGroups; AnObsGroup: TPestObservationGroup; ANode: TTreeNode; ObsGroup: TPestObservationGroup; ChildNode: TTreeNode; AnObs: TCustomObservationItem; begin InvalidateModelEvent := nil; PestProperties := TPestProperties.Create(InvalidateModelEvent); try {$REGION 'PEST Basics'} PestProperties.PestUsed := cbPEST.Checked; if comboTemplateCharacter.Text <> '' then begin PestProperties.TemplateCharacter := comboTemplateCharacter.Text[1]; end; if comboFormulaMarker.Text <> '' then begin PestProperties.ExtendedTemplateCharacter := comboFormulaMarker.Text[1]; end; PestProperties.ShowPilotPoints := cbShowPilotPoints.Checked; PestProperties.PilotPointSpacing := rdePilotPointSpacing.RealValue; {$ENDREGION} {$REGION 'Control Data'} PestControlData := PestProperties.PestControlData; PestControlData.PestRestart := TPestRestart(cbSaveRestart.Checked); PestControlData.PestMode := TPestMode(comboPestMode.ItemIndex); {$ENDREGION} {$REGION 'Dimensions'} if rdeMaxCompDim.Text <> '' then begin PestControlData.MaxCompressionDimension := rdeMaxCompDim.IntegerValue; end; if rdeZeroLimit.Text <> '' then begin PestControlData.ZeroLimit := rdeZeroLimit.RealValue; end; {$ENDREGION} {$REGION 'Inversion Controls'} if rdeInitialLambda.Text <> '' then begin PestControlData.InitalLambda := rdeInitialLambda.RealValue; end; if rdeLambdaAdj.Text <> '' then begin PestControlData.LambdaAdjustmentFactor := rdeLambdaAdj.RealValue; end; if rdeIterationClosure.Text <> '' then begin PestControlData.PhiRatioSufficient := rdeIterationClosure.RealValue; end; if rdeLambdaTermination.Text <> '' then begin PestControlData.PhiReductionLambda := rdeLambdaTermination.RealValue; end; if rdeMaxLambdas.Text <> '' then begin PestControlData.NumberOfLambdas := rdeMaxLambdas.IntegerValue; end; if rdeJacobianUpdate.Text <> '' then begin PestControlData.JacobianUpdate := rdeJacobianUpdate.IntegerValue; end; PestControlData.LambdaForgive := TLambdaForgive(cbLamForgive.Checked); PestControlData.DerivedForgive := TDerivedForgive(cbDerForgive.Checked); {$ENDREGION} {$REGION 'Parameter Adjustment Controls'} if rdeMaxRelParamChange.Text <> '' then begin PestControlData.RelativeMaxParamChange := rdeMaxRelParamChange.RealValue; end; if rdeMaxFacParamChange.Text <> '' then begin PestControlData.FactorMaxParamChange := rdeMaxFacParamChange.RealValue; end; if rdeFactorOriginal.Text <> '' then begin PestControlData.FactorOriginal := rdeFactorOriginal.RealValue; end; if rdeBoundStick.Text <> '' then begin PestControlData.BoundStick := rdeBoundStick.IntegerValue; end; PestControlData.UpgradeParamVectorBending := TUpgradeParamVectorBending(cbLamForgive.Checked); {$ENDREGION} {$REGION 'Inversion Controls 2'} if rdeSwitchCriterion.Text <> '' then begin PestControlData.SwitchCriterion := rdeSwitchCriterion.RealValue; end; if rdeSwitchCount.Text <> '' then begin PestControlData.OptSwitchCount := rdeSwitchCount.IntegerValue; end; if rdeSwitchCriterion.Text <> '' then begin PestControlData.SplitSlopeCriterion := rdeSwitchCriterion.RealValue; end; PestControlData.AutomaticUserIntervation := TAutomaticUserIntervation(comboAutomaticUserIntervation.ItemIndex); PestControlData.SensitivityReuse := TSensitivityReuse(cbSensitivityReuse.Checked); PestControlData.Boundscaling := TBoundsScaling(cbBoundsScaling.Checked); {$ENDREGION} {$REGION 'Iteration Controls'} if rdeMaxIterations.Text <> '' then begin PestControlData.MaxIterations := rdeMaxIterations.IntegerValue; end; if rdePhiReductionCriterion.Text <> '' then begin PestControlData.SlowConvergenceCriterion := rdePhiReductionCriterion.RealValue; end; if rdePhiReductionCount.Text <> '' then begin PestControlData.SlowConvergenceCountCriterion := rdePhiReductionCount.IntegerValue; end; if rdeNoReductionCount.Text <> '' then begin PestControlData.ConvergenceCountCriterion := rdeNoReductionCount.IntegerValue; end; if rdeSmallParameterReduction.Text <> '' then begin PestControlData.ParameterChangeConvergenceCriterion := rdeSmallParameterReduction.RealValue; end; if rdeSmallParameterReductionCount.Text <> '' then begin PestControlData.ParameterChangeConvergenceCount := rdeSmallParameterReductionCount.IntegerValue; end; if rdePhiStoppingThreshold.Text <> '' then begin PestControlData.ObjectiveCriterion := rdePhiStoppingThreshold.RealValue; end; PestControlData.MakeFinalRun := TMakeFinalRun(cbLastRun.Checked); if rdeAbandon.Text <> '' then begin PestControlData.PhiAbandon := rdeAbandon.RealValue; end; {$ENDREGION} {$REGION 'Output Options'} PestControlData.WriteCovariance := TWriteMatrix(cbWriteCov.Checked); PestControlData.WriteCorrelations := TWriteMatrix(cbWriteCorrCoef.Checked); PestControlData.WriteEigenVectors := TWriteMatrix(cbWriteEigenvectors.Checked); PestControlData.SaveResolution := TSaveResolution(cbWriteResolution.Checked); PestControlData.SaveJacobian := TSaveJacobian(cbWriteJacobian.Checked); PestControlData.SaveJacobianIteration := TSaveJacobianIteration(cbWriteJacobianEveryIteration.Checked); PestControlData.VerboseRecord := TVerboseRecord(cbWriteVerboseRunRecord.Checked); PestControlData.SaveInterimResiduals := TSaveInterimResiduals(cbWriteIntermResidualForEveryIteration.Checked); PestControlData.SaveParamIteration := TSaveParamIteration(cbSaveParamValuesIteration.Checked); PestControlData.SaveParamRun := TSaveParamRun(cbSaveParamValuesModelRun.Checked); {$ENDREGION} {$REGION 'Singular Value Decomposition'} SvdProperties := PestProperties.SvdProperties; SvdProperties.Mode := TSvdMode(comboSvdMode.ItemIndex); if rdeMaxSingularValues.Text <> '' then begin SvdProperties.MaxSingularValues := rdeMaxSingularValues.IntegerValue; end; if rdeEigenThreshold.Text <> '' then begin SvdProperties.EigenThreshold := rdeEigenThreshold.RealValue; end; SvdProperties.EigenWrite := TEigenWrite(comboEigenWrite.ItemIndex); {$ENDREGION} {$REGION 'LQSR'} LsqrProperties := PestProperties.LsqrProperties; LsqrProperties.Mode := TLsqrMode(cbUseLqsr.Checked); if rdeMatrixTolerance.Text <> '' then begin LsqrProperties.MatrixTolerance := rdeMatrixTolerance.RealValue; end; if rdeRightHandSideTolerance.Text <> '' then begin LsqrProperties.RightHandSideTolerance := rdeRightHandSideTolerance.RealValue; end; if rdeConditionNumberLimit.Text <> '' then begin LsqrProperties.ConditionNumberLimit := rdeConditionNumberLimit.RealValue; end; if rdeMaxLqsrIterations.Text <> '' then begin LsqrProperties.MaxIteration := rdeMaxLqsrIterations.IntegerValue; end; LsqrProperties.LsqrWrite := TLsqrWrite(cbWriteLsqrOutput.Checked); {$ENDREGION} {$REGION 'Observation Groups'} ObsGroups := PestProperties.ObservationGroups; Grid := frameObservationGroups.Grid; for RowIndex := 1 to frameObservationGroups.seNumber.AsInteger do begin if Grid.Cells[Ord(pogcName), RowIndex] <> '' then begin AnObsGroup := ObsGroups.Add; AnObsGroup.ObsGroupName := Grid.Cells[Ord(pogcName), RowIndex]; AnObsGroup.UseGroupTarget := Grid.Checked[Ord(pogcUseTarget), RowIndex]; AnObsGroup.GroupTarget := Grid.RealValueDefault[Ord(pogcTarget), RowIndex, 0]; AnObsGroup.AbsoluteCorrelationFileName := Grid.Cells[Ord(pogcFileName), RowIndex]; end; end; {$ENDREGION} {$REGION 'Observation Group Assignments'} ANode := FNoNameNode; while ANode <> nil do begin ObsGroup := ANode.Data; ChildNode := ANode.getFirstChild; while ChildNode <> nil do begin AnObs := ChildNode.Data; if ObsGroup = nil then begin AnObs.ObservationGroup := ''; end else begin AnObs.ObservationGroup := ObsGroup.ObsGroupName; end; ChildNode := ChildNode.GetNextSibling; end; ANode := ANode.GetNextSibling; end; {$ENDREGION} frmGoPhast.UndoStack.Submit(TUndoPestOptions.Create(PestProperties, FNewObsList, diredPest.Text)); finally PestProperties.Free end; end; procedure TfrmPEST.FixObsGroupNames; var Grid: TRbwDataGrid4; RowIndex: Integer; ValidName: string; begin Grid := frameObservationGroups.Grid; for RowIndex := 1 to frameObservationGroups.seNumber.AsInteger do begin if Grid.Cells[Ord(pogcName), RowIndex] <> '' then begin ValidName := ValidObsGroupName(Grid.Cells[Ord(pogcName), RowIndex]); if ValidName <> Grid.Cells[Ord(pogcName), RowIndex] then begin Grid.Cells[Ord(pogcName), RowIndex] := ValidName; end; end; end; end; procedure TfrmPEST.HandleGroupDeletion(Group: TPestObservationGroup); var OtherGroup: TPestObservationGroup; TreeNode: TTreeNode; ChildNode: TTreeNode; begin if FGroupNameDictionary.TryGetValue( UpperCase(Group.ObsGroupName), OtherGroup) then begin if Group = OtherGroup then begin FGroupNameDictionary.Remove(UpperCase(Group.ObsGroupName)); end; end; if FGroupDictionary.TryGetValue(Group, TreeNode) then begin ChildNode := TreeNode.getFirstChild; while ChildNode <> nil do begin ChildNode.MoveTo(FNoNameNode, naAddChild); ChildNode := TreeNode.getFirstChild; end; end; end; procedure TfrmPEST.HandleAddedGroup(ObsGroup: TPestObservationGroup); var NewNode: TTreeNode; begin NewNode := frameParentObsGroups.tvTree.Items.AddChild(nil, ObsGroup.ObsGroupName); NewNode.Data := ObsGroup; FGroupDictionary.Add(ObsGroup, NewNode); if ObsGroup.ObsGroupName <> '' then begin if not FGroupNameDictionary.ContainsKey(UpperCase(ObsGroup.ObsGroupName)) then begin FGroupNameDictionary.Add(UpperCase(ObsGroup.ObsGroupName), ObsGroup); end; end; end; procedure TfrmPEST.CheckPestDirectory; begin if DirectoryExists(diredPest.Text) then begin diredPest.Color := clWindow; end else begin diredPest.Color := clRed; end; end; { TUndoPestOptions } constructor TUndoPestOptions.Create(var NewPestProperties: TPestProperties; var NewObsList: TObservationObjectList; PestDirectory: String); var InvalidateModelEvent: TNotifyEvent; TempList: TObservationList; index: Integer; AnObs: TCustomObservationItem; ATempObs: TCustomObservationItem; Locations: TProgramLocations; begin Locations := frmGoPhast.PhastModel.ProgramLocations; OldPestLocation := Locations.PestDirectory; NewPestLocation := PestDirectory; InvalidateModelEvent := nil; FOldPestProperties := TPestProperties.Create(InvalidateModelEvent); FOldPestProperties.Assign(frmGoPhast.PhastModel.PestProperties); FNewPestProperties := NewPestProperties; NewPestProperties := nil; TempList := TObservationList.Create; try frmGoPhast.PhastModel.FillObsItemList(TempList, True); FOldObsList := TObservationObjectList.Create; FOldObsList.Capacity := TempList.Count; for index := 0 to TempList.Count - 1 do begin AnObs := TempList[index]; ATempObs := TCustomObservationItem.Create(nil); FOldObsList.Add(ATempObs); ATempObs.Assign(AnObs); end; finally TempList.Free; end; FNewObsList := NewObsList; NewObsList := nil; end; function TUndoPestOptions.Description: string; begin result := 'change PEST properties'; end; destructor TUndoPestOptions.Destroy; begin FOldObsList.Free; FNewObsList.Free; FOldPestProperties.Free; FNewPestProperties.Free; inherited; end; procedure TUndoPestOptions.DoCommand; var Locations: TProgramLocations; begin inherited; // frmGoPhast.PhastModel.PestProperties := FNewPestProperties; UpdateProperties(FNewPestProperties, FNewObsList); Locations := frmGoPhast.PhastModel.ProgramLocations; Locations.PestDirectory := NewPestLocation; end; procedure TUndoPestOptions.Undo; var Locations: TProgramLocations; begin inherited; UpdateProperties(FOldPestProperties, FOldObsList); Locations := frmGoPhast.PhastModel.ProgramLocations; Locations.PestDirectory := OldPestLocation; end; procedure TUndoPestOptions.UpdateProperties(PestProperties: TPestProperties; ObsList: TObservationList); var ShouldUpdateView: Boolean; TempList: TObservationList; AnObs: TCustomObservationItem; NewObs: TCustomObservationItem; ObsIndex: Integer; begin ShouldUpdateView := frmGoPhast.PhastModel.PestProperties.ShouldDrawPilotPoints <> PestProperties.ShouldDrawPilotPoints; if PestProperties.ShouldDrawPilotPoints and (PestProperties.PilotPointSpacing <> frmGoPhast.PhastModel.PestProperties.PilotPointSpacing) then begin ShouldUpdateView := True; end; frmGoPhast.PhastModel.PestProperties := PestProperties; TempList := TObservationList.Create; try frmGoPhast.PhastModel.FillObsItemList(TempList, True); Assert(TempList.Count = ObsList.Count); for ObsIndex := 0 to TempList.Count - 1 do begin AnObs := TempList[ObsIndex]; NewObs := ObsList[ObsIndex]; AnObs.Assign(NewObs); end; finally TempList.Free; end; if ShouldUpdateView then begin frmGoPhast.SynchronizeViews(vdTop); end; end; end.
{..............................................................................} { Summary Placing a new port object. } { Copyright (c) 2004 by Altium Limited } {..............................................................................} {..............................................................................} Procedure PlaceAPort; Var SchPort : ISch_Port; FSchDoc : ISch_Document; CurView : IServerDocumentView; Begin // Check if Schematic server exists or not. If SchServer = Nil Then Exit; // Obtain the Schematid sheet interfac.e FSchDoc := SchServer.GetCurrentSchDocument; If FSchDoc = Nil Then Exit; // Create a new port object SchPort := SchServer.SchObjectFactory(ePort,eCreate_GlobalCopy); If SchPort = Nil Then Exit; // Set up parameters for the port object. // the port is placed at 500,500 mils respectively. SchPort.Location := Point(MilsToCoord(500),MilsToCoord(500)); SchPort.Style := ePortRight; SchPort.IOType := ePortBidirectional; SchPort.Alignment := eHorizontalCentreAlign; SchPort.Width := MilsToCoord(1000); SchPort.AreaColor := 0; SchPort.TextColor := $FFFFFF; SchPort.Name := 'A new port with no net.'; // Add a port object onto the existing schematic document FSchDoc.RegisterSchObjectInContainer(SchPort); // Refresh the schematic sheet. FSchDoc.GraphicallyInvalidate; End; {..............................................................................} {..............................................................................}
{*******************************************************} { } { 单元功能:系统日志单元 } { } { 版权所有 (C) 2011 公司名 } { } {*******************************************************} // 约定:0 - Information // 1 - Notice // 2 - Warning // 3 - Error // 4 - Report unit UntTIO; interface uses Classes, SysUtils, ComCtrls, StdCtrls, Forms, StrUtils,windows; type TGameLogFile = class private FFileParth: string; //路径 FText: Cardinal; //是否是每次启动程序都创建新的记录文件 否则就是当天只会有1个文件 FIsCreateToNew: boolean; //日志文件名(带路径) FLogFileName: string; public {带入日志文件存放的目录位置} constructor Create(Iparth: string); destructor Destroy; override; {写入内容即可自动记录} procedure AddLog(Icon: ansistring; const LogLevel: Integer = 0); procedure AddShow(ICon: ansistring; const Args: array of const; const LogLevel: Integer = 0); overload; procedure AddShow(ICon: ansistring; const LogLevel: Integer = 0); overload; //设置日志路径 procedure SetFileParth(Iparth: string); property IsCreateToNew: boolean read FIsCreateToNew write FIsCreateToNew; end; TEventShowed = procedure(ILogCon: string) of object; TIOer = class(TObject) private FFileParth: string; //路径 FIsAddTime: boolean; //是否在每条日志前加时间 FAfterShowed: TEventShowed; //显示后触发的事件 可以用来做日志 FIsNeedSplt: boolean; //是否需要分割字符 FSplitChar: string; //分割的字符 FLog: TGameLogFile; //删除历史日志,默认保留 30 天 FDelBeforeLog: Double; procedure SetDelBeforeLog(const Value: Double); procedure SetFileParth(const Value: string); protected FClearTager: Word; //显示多少条后清空一下 function DoAdd(Icon: string; const LogLevel: Integer = 0): Integer; virtual; public FShower: TComponent; //日志显示容器 function AddShow(ICon: string; const Args: array of const; const LogLevel: Integer = 0): Integer; overload; function AddShow(ICon: string; const LogLevel: Integer = 0): Integer; overload; {如果带入记录文件存放路径的话就自动生成记录类} constructor Create(IShower: TComponent; IlogFIleDir: string = ''); destructor Destroy; override; //显示多少条后清空一下(默认为500) property ClearTager: Word read FClearTager write FClearTager; //是否在每条日志前加时间(默认是) property IsAddTime: boolean read FIsAddTime write FIsAddTime; //是否需要分割字符(默认否) property IsNeedSplitChar: boolean read FIsNeedSplt write FIsNeedSplt; //分割的字符(默认====) property SplitChar: string read FSplitChar write FSplitChar; //显示后触发的事件 可以用来做日志 property AfterShowed: TEventShowed read FAfterShowed write FAfterShowed; //删除历史日志,默认保留 30 天 property DelBeforeLog: Double read FDelBeforeLog write SetDelBeforeLog; //日志文件路径 property FileParth: string read FFileParth write SetFileParth; end; var //日志对象 SysLog: TIOer; X_thread:TRTLCriticalSection; G_IsAlterListView:boolean=false; G_Log:boolean; implementation const {分割符号} CSplitStr = '==============================================================='; ClogFileName = '.txt'; { TGameLogFile } procedure TGameLogFile.AddLog(Icon: ansistring; const LogLevel: integer = 0); var ltep: string; begin if RightStr(FFileParth, 1) <> '\' then FFileParth := FFileParth + '\'; if not DirectoryExists(FFileParth) then if not ForceDirectories(FFileParth) then raise Exception.Create('错误的路径,日志类对象不能被创建'); //创建日志文件 if FText = 0 then begin if FIsCreateToNew then Ltep := FormatDateTime('yyyymmddhhnnss', Now) else Ltep := FormatDateTime('yyyymmdd', Now); FLogFileName := FFileParth + ltep + ClogFileName; if not FileExists(FLogFileName) then FText := FileCreate(FLogFileName) else FText := FileOpen(FLogFileName, fmOpenWrite); FileSeek(FText, soFromEnd, soFromEnd); end; if not FIsCreateToNew then begin Ltep := FormatDateTime('yyyymmdd', Now); //跨天生成新的文件 if not SameText(FLogFileName, FFileParth + ltep + ClogFileName) then begin if FText <> 0 then FileClose(FText); FLogFileName := FFileParth + ltep + ClogFileName; if not FileExists(FLogFileName) then FText := FileCreate(FLogFileName) else FText := FileOpen(FLogFileName, fmOpenWrite); FileSeek(FText, soFromEnd, soFromEnd); end; end; Icon := Icon + #13#10; FileWrite(FText, PansiChar(Icon)^, Length(ICon)); end; procedure TGameLogFile.AddShow(ICon: ansistring; const Args: array of const; const LogLevel: Integer = 0); begin AddLog(Format(ICon, args)); end; procedure TGameLogFile.AddShow(ICon: ansistring; const LogLevel: Integer = 0); begin AddLog(ICon); end; constructor TGameLogFile.Create(Iparth: string); begin FIsCreateToNew := False; FFileParth := Iparth; if RightStr(FFileParth, 1) <> '\' then FFileParth := FFileParth + '\'; if not DirectoryExists(FFileParth) then if not ForceDirectories(FFileParth) then raise Exception.Create('错误的路径,日志类对象不能被创建'); FLogFileName := ''; FText := 0; end; destructor TGameLogFile.Destroy; var RosStr: string; begin try RosStr := '-----------------------------------------------------------------' + #13#10; FileWrite(FText, PansiChar(RosStr)^, Length(RosStr)); if FText <> 0 then FileClose(FText); except end; inherited; end; { TGameIO } function TIOer.AddShow(ICon: string; const Args: array of const; const LogLevel: Integer = 0): Integer; begin Result := 0; try EnterCriticalSection(X_thread); //进入临界区 try ICon := Format(ICon, Args); if FIsAddTime then ICon := DateTimeToStr(Now) + ' ' + Icon; if FIsNeedSplt then ICon := ICon + #13#10 + FSplitChar; Result := DoAdd(ICon, LogLevel); if assigned(FLog) then FLog.AddLog(ICon); if Assigned(FAfterShowed) then FAfterShowed(ICon); except end; finally LeaveCriticalSection(X_thread); //离开临界区 end; end; function TIOer.AddShow(ICon: string; const LogLevel: Integer = 0): Integer; begin try EnterCriticalSection(X_thread); //进入临界区 if FIsAddTime then ICon := DateTimeToStr(Now) + ' ' + Icon; if FIsNeedSplt then ICon := ICon + #13#10 + FSplitChar; Result := DoAdd(ICon, LogLevel); if assigned(FLog) then FLog.AddLog(ICon); if Assigned(FAfterShowed) then FAfterShowed(ICon); finally LeaveCriticalSection(X_thread); //离开临界区 end; end; constructor TIOer.Create(IShower: TComponent; IlogFIleDir: string); begin InitializeCriticalSection(X_thread); FClearTager := 500; IsAddTime := True; FIsNeedSplt := False; FSplitChar := CSplitStr; FShower := IShower; FDelBeforeLog := 30; FFileParth := IlogFIleDir; if IlogFIleDir <> '' then FLog := TGameLogFile.Create(IlogFIleDir); end; destructor TIOer.Destroy; begin if Assigned(FLog) then FLog.Free; inherited; DeleteCriticalSection(X_thread); end; function TIOer.DoAdd(Icon: string; const LogLevel: Integer = 0): Integer; var ListItem: TListItem; Is_ClearLog: Boolean; begin if G_IsAlterListView then exit; if (LogLevel=0) then begin if (not G_Log) then exit; end; Is_ClearLog := False; Result := -1; if Application.Terminated then exit; if (FShower = nil) then exit; if (FShower is TMemo) then begin Result := TMemo(FShower).Lines.Add(Icon); if Result >= FClearTager then begin TMemo(FShower).Clear; Is_ClearLog := True; end; end else if (FShower is TRichEdit) then begin Result := TRichEdit(FShower).Lines.Add(Icon); if Result >= FClearTager then begin TRichEdit(FShower).Clear; Is_ClearLog := True; end; end else if (FShower is TListBox) then begin Result := TListBox(FShower).Items.Add(Icon); if Result >= FClearTager then begin TListBox(FShower).Clear; Is_ClearLog := True; end; end else if (FShower is TListView) then begin ListItem := TListView(FShower).Items.Add; ListItem.Caption := FormatDateTime('yyyy-mm-dd hh:nn:ss', Now); ListItem.ImageIndex := LogLevel; ListItem.SubItems.Add(Icon); if TListView(FShower).Items.Count >= FClearTager then begin TListView(FShower).Items.Clear; Is_ClearLog := True; end; end else if Pos('默认容器错误', Icon) = 0 then DoAdd('默认容器错误:' + FShower.ClassName); end; procedure TGameLogFile.SetFileParth(Iparth: string); begin FFileParth := Iparth; if RightStr(FFileParth, 1) <> '\' then FFileParth := FFileParth + '\'; if not DirectoryExists(FFileParth) then if not ForceDirectories(FFileParth) then raise Exception.Create('错误的路径,日志类对象不能被创建'); end; procedure TIOer.SetDelBeforeLog(const Value: Double); begin FDelBeforeLog := Value; end; procedure TIOer.SetFileParth(const Value: string); begin FFileParth := Value; if Assigned(FLog) then FLog.SetFileParth(FFileParth) else FLog := TGameLogFile.Create(FFileParth); end; initialization finalization end.
unit Datapar.Conexao.Factory; interface uses Data.DB, Datapar.Conexao, Datapar.Conexao.FireDac, Datapar.Conexao.DbExpress, Datapar.Conexao.DOA; type TDataparFactory = class public class function CreateInstance(AModo: TDataparModoConexao; AProvider: TDataparProvider): TDataparQuery; end; implementation { TDataparFactory } class function TDataparFactory.CreateInstance( AModo: TDataparModoConexao; AProvider: TDataparProvider): TDataparQuery; begin case AModo of mcFireDac: Result := TFireQuery.create(AProvider); mcDBExpress: Result := TExpressQuery.create(AProvider); mcUniDac: Result := Nil; mcDOA: Result := TDoaQuery.Create(AProvider) end; end; end.
unit DOSWIN; interface type doswinconverter = object public procedure decode_char (var ch : char); procedure decode_string (var s : string); procedure uncode_char (var ch : char); procedure uncode_string (var s : string); end; implementation procedure doswinconverter.decode_char (var ch : char); begin if ord (ch) in [192..239] then ch := chr (ord (ch) - 64) else if ord (ch) in [240..255] then ch := chr (ord (ch) - 16) else if ord (ch) = 189 then ch := chr (ord (241)) else if ord (ch) = 168 then ch := chr (ord (240)) end; procedure doswinconverter.decode_string (var s : string); var i : byte; begin for i := 1 to Length (s) do decode_char (s[i]) end; procedure doswinconverter.Uncode_char (var ch : char); begin if ord (ch) in [128..175] then ch := chr (ord (ch) + 64) else if ord (ch) in [224..239] then ch := chr (ord (ch) + 16) else if ord (ch) = 241 then ch := chr (ord (189)) else if ord (ch) = 240 then ch := chr (ord (168)) end; procedure doswinconverter.uncode_string (var s : string); var i : byte; begin for i := 1 to Length (s) do uncode_char (s[i]) end; end.
unit Ils.Kafka.Disp; //------------------------------------------------------------------------------ // модуль класса-диспетчеризатора данных от kafka //------------------------------------------------------------------------------ // работает по заданному критерию //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, IniFiles, SyncObjs, Ils.Kafka, Ils.Logger, CINIFilesData, ULibKafka, JsonDataObjects; //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! запись инициализации kafka //------------------------------------------------------------------------------ TKafkaConfig = record BootStrap: string; Group: string; Topic: string; constructor Create( const ABootStrap: string; const AGroup: string; const ATopic: string ); end; //------------------------------------------------------------------------------ //! формат процедуры обратного вызова //------------------------------------------------------------------------------ TKafkaDispCallback = procedure( const AJSONObj: TJsonObject ) of object; //------------------------------------------------------------------------------ //! запись с информаций об обратном вызове //------------------------------------------------------------------------------ TKafkaDispCallbackInfo = record CB: TKafkaDispCallback; Ref: string; end; TKafkaDispCallbackInfoArray = TArray<TKafkaDispCallbackInfo>; //------------------------------------------------------------------------------ //! класс диспетчеризатор //------------------------------------------------------------------------------ TKafkaDisp = class private FKafka: TKafkaConsumer; FRecIndex: Int64; FCallbacks: TKafkaDispCallbackInfoArray; FLock: TCriticalSection; //! function FindHallMark( const AHallmark: string ): Integer; //! callback от kafka function OnKafkaData( const AMessage: AnsiString; const AOffset: Int64; const ATopic: AnsiString ): Boolean; public constructor Create( const Config: TKafkaConfig; const RecIndexIniFileName: string; const RecIndexRecord: string ); destructor Destroy(); override; //! начать чтение из kafka procedure StartUp(); //! подписатся procedure Subscribe( const AHallmark: string; const ACallback: TKafkaDispCallback ); //! отписаться procedure UnSubscribe( const AHallmark: string ); end; //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ // TKafkaConfig //------------------------------------------------------------------------------ constructor TKafkaConfig.Create( const ABootStrap: string; const AGroup: string; const ATopic: string ); begin BootStrap := ABootStrap; Group := AGroup; Topic := ATopic; end; //------------------------------------------------------------------------------ // TAPF //------------------------------------------------------------------------------ constructor TKafkaDisp.Create( const Config: TKafkaConfig; const RecIndexIniFileName: string; const RecIndexRecord: string ); var INIFile: TIniFile; RecIndexStr: string; //------------------------------------------------------------------------------ begin inherited Create(); // FLock := TCriticalSection.Create(); INIFile := TIniFile.Create(RecIndexIniFileName); try RecIndexStr := INIFile.ReadString(CIniKafkaIndexSection, RecIndexRecord, ''); finally INIFile.Free(); end; ToLog(Format('KAFKA прочитанное смещение => "%s"', [RecIndexStr])); FRecIndex := StrToInt64Def(RecIndexStr, RD_KAFKA_OFFSET_BEGINNING); ToLog(Format('KAFKA установленное смещение => "%d"', [FRecIndex])); FKafka := TKafkaConsumer.Create(Config.BootStrap, Config.Group, Config.Topic, OnKafkaData, ToLog); end; destructor TKafkaDisp.Destroy(); begin FKafka.Free(); FLock.Free(); // inherited Destroy(); end; procedure TKafkaDisp.StartUp(); begin FKafka.Start(FRecIndex); end; procedure TKafkaDisp.Subscribe( const AHallmark: string; const ACallback: TKafkaDispCallback ); var Index: Integer; Len: Integer; //------------------------------------------------------------------------------ begin FLock.Acquire(); try Index := FindHallMark(AHallmark); if (Index = -1) then begin Len := Length(FCallbacks); SetLength(FCallbacks, Len + 1); FCallbacks[Len].CB := ACallback; FCallbacks[Len].Ref := AHallmark; end else FCallbacks[Index].CB := ACallback; finally FLock.Release(); end; end; procedure TKafkaDisp.UnSubscribe( const AHallmark: string ); var Index: Integer; NewLen: Integer; //------------------------------------------------------------------------------ begin FLock.Acquire(); try Index := FindHallMark(AHallmark); if (Index = -1) then Exit; NewLen := High(FCallbacks); FCallbacks[Index] := FCallbacks[NewLen]; SetLength(FCallbacks, NewLen); finally FLock.Release(); end; end; function TKafkaDisp.FindHallMark( const AHallmark: string ): Integer; begin for Result := Low(FCallbacks) to High(FCallbacks) do begin if (FCallbacks[Result].Ref = AHallmark) then Exit; end; Result := -1; end; function TKafkaDisp.OnKafkaData( const AMessage: AnsiString; const AOffset: Int64; const ATopic: AnsiString ): Boolean; var JSONObj: TJsonObject; //------------------------------------------------------------------------------ begin // end; end.
unit uCadEmpregados; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, adLabelEdit, adLabelComboBox, Db, Buttons, fCtrls, DBGrids, funcsql, FUNCOES, ADODB, Grids, SoftDBGrid, TFlatCheckBoxUnit, Menus; type TfmCadEmpregados = class(TForm) gpListaEmp: TGroupBox; gpEmp: TGroupBox; edNome: TadLabelEdit; edMatricula: TadLabelEdit; edCartaoPonto: TadLabelEdit; rgHoraFlexivel: TRadioGroup; edFuncao: TadLabelEdit; edLocalizacao: TadLabelEdit; edHorario: TadLabelEdit; btCarregaHorario: TfsBitBtn; lbHorario: TLabel; lbLocalizacao: TLabel; fsBitBtn1: TfsBitBtn; Panel2: TPanel; fsBitBtn2: TfsBitBtn; fsBitBtn3: TfsBitBtn; lbDataAdmissao: TLabel; lbEmpresa: TLabel; gridEmp: TSoftDBGrid; DataSource1: TDataSource; qr: TADOQuery; edLocEmp: TadLabelEdit; cbLojas: TComboBox; cbBatePonto: TFlatCheckBox; PopupMenu1: TPopupMenu; RemoveEmpregadodocadastro1: TMenuItem; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbEmpClick(Sender: TObject); procedure btCarregaHorarioClick(Sender: TObject); procedure fsBitBtn1Click(Sender: TObject); procedure fsBitBtn3Click(Sender: TObject); procedure fsBitBtn2Click(Sender: TObject); procedure FormActivate(Sender: TObject); procedure gridEmpTitleClick(Column: TColumn); procedure gridEmpDblClick(Sender: TObject); procedure edLocEmpKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure carregaCadastro(); procedure cbLojasChange(Sender: TObject); procedure RemoveEmpregadodocadastro1Click(Sender: TObject); procedure FormResize(Sender: TObject); private { Private declarations } public { Public declarations } end; var fmCadEmpregados: TfmCadEmpregados; implementation uses uUtil, UmanBat, uListas, uHorarios; {$R *.dfm} procedure TfmCadEmpregados.FormClose(Sender: TObject; var Action: TCloseAction); begin form2.MsgDeRodape(''); action := caFree; fmCadEmpregados := nil; end; procedure TfmCadEmpregados.cbEmpClick(Sender: TObject); var ds:TdataSet; begin gpEmp.Visible := false; ds := uUtil.getDetalheEmpregado( qr.fieldByname('cartaoPonto').asString); edMatricula.Text := ds.FieldByName('matricula').AsString; edCartaoPonto.Text := ds.FieldByName('cartaoPonto').AsString; edFuncao.Text := ds.FieldByName('funcao').AsString; edNome.Text := ds.FieldByName('nome').AsString; rgHoraFlexivel.ItemIndex := ds.FieldByName('isHoraFlexivel').AsInteger; edLocalizacao.Text := ds.FieldByName('ds_uo').AsString; lbLocalizacao.caption := ds.FieldByName('localizacao').AsString; lbDataAdmissao.Caption := ds.FieldByName('dataAdmissao').AsString; lbEmpresa.Caption := ds.FieldByName('empresa').AsString; cbBatePonto.Checked := (ds.FieldByName('dataDemissao').AsString = ''); edHorario.Text := ds.FieldByName('descricao').AsString; lbHorario.Caption := ds.FieldByName('horario_num').AsString; gpEmp.Visible := true; gridEmp.Enabled := false; end; procedure TfmCadEmpregados.btCarregaHorarioClick(Sender: TObject); begin Application.CreateForm(TfmListas, fmListas ); fmListas.CarregaHorarios(); fmListas.ShowModal; if (fmListas.ModalResult = mrOk) then begin edHorario.Text := fmListas.tb.FieldByName('descricao').AsString; lbHorario.Caption := fmListas.tb.FieldByName('num').AsString; end; end; procedure TfmCadEmpregados.fsBitBtn1Click(Sender: TObject); begin Application.CreateForm(TfmListas, fmListas ); fmListas.carregaLocalizacoes(); fmListas.ShowModal; if (fmListas.ModalResult = mrOk) then begin edLocalizacao.Text := fmListas.tb.FieldByName('ds_uo').AsString; lbLocalizacao.Caption := fmListas.tb.FieldByName('localizacao').AsString; end; end; procedure TfmCadEmpregados.fsBitBtn3Click(Sender: TObject); var dataDemissao:String; begin if (cbBatePonto.Checked= false) then dataDemissao := '01/01/1900' else dataDemissao := ''; if( uUtil.deletaEmpregado(edMatricula.Text) = true) and ( uUtil.insereEmpregado( lbEmpresa.Caption, edMatricula.Text, edCartaoPonto.Text, edNome.Text, edFuncao.Text, lbDataAdmissao.Caption, intToStr(rgHoraFlexivel.ItemIndex), lbHorario.Caption, lbLocalizacao.Caption, dataDemissao ) ) then MsgTela('','Dados Salvos com sucesso.', MB_OK + MB_ICONEXCLAMATION); fsBitBtn2Click(nil); end; procedure TfmCadEmpregados.fsBitBtn2Click(Sender: TObject); begin gridEmp.Enabled := true; edLocEmp.Text := ''; edLocEmp.SetFocus(); gpEmp.Visible := false; carregaCadastro(); end; procedure TfmCadEmpregados.carregaCadastro(); var cmd:String; begin cmd:= 'select e.Matricula, e.cartaoPonto, e.Localizacao, e.Nome, L.ds_uo as Local, H.descricao ' + 'from zcf_pontoEmpregados e (nolock) ' + 'left join zcf_pontoLocalizacao L (nolock) on e.localizacao = L.localizacao ' + 'left join zcf_pontoHorarios H (nolock) on e.horario_num = H.num '; if (cbLojas.ItemIndex > 1 ) then cmd := cmd + ' where e.localizacao =' + uUtil.getNumLocalEmpresa(cbLojas); if (cbLojas.ItemIndex = 1 ) then cmd := cmd + ' where e.localizacao = 0 '; uUtil.getQuery(qr, cmd ); gridEmp.columns[0].Width := 70; gridEmp.columns[1].Width := 70; gridEmp.columns[2].Width := 70; gridEmp.columns[3].Width := 200; gridEmp.columns[4].Width := 100; gridEmp.columns[5].Width := 100; form2.MsgDeRodape('Quantidade de empregados: ' + intTostr(qr.RecordCount)); end; procedure TfmCadEmpregados.FormActivate(Sender: TObject); begin cbLojas.Items := uUtil.getNomeLojasPonto(True, true); cbLojas.ItemIndex := 0 ; carregaCadastro(); cbBatePonto.Hint := 'Se estiver desmarcado, o empregado '+#13+'não aparece no relógio de ponto'; cbBatePonto.ShowHint := true; end; procedure TfmCadEmpregados.gridEmpTitleClick(Column: TColumn); begin uUtil.organizarQuery(qr, Column); end; procedure TfmCadEmpregados.gridEmpDblClick(Sender: TObject); begin cbEmpClick(nil); end; procedure TfmCadEmpregados.edLocEmpKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin qr.Locate('nome',edLocEmp.Text, [loPartialKey] ); end; procedure TfmCadEmpregados.cbLojasChange(Sender: TObject); begin carregaCadastro(); end; procedure TfmCadEmpregados.RemoveEmpregadodocadastro1Click(Sender: TObject); var cmd:String; begin cmd:= ' Se você remover o funcionário ele não aparecerá mais no cadastro do ponto, continua ?'; if (funcoes.msgTela('',cmd, MB_ICONWARNING + MB_YESNO) = mrOk) then begin cmd := 'Delete from zcf_PontoCadDigitais where id = ' + funcSQL.executeSQL(cmd, Form2.Conexao); cmd := 'delete from zcf_pontoEmpregados where matricula= ' + qr.fieldByName('Matricula').AsString; funcSQL.executeSQL(cmd, Form2.Conexao); carregaCadastro(); end; end; procedure TfmCadEmpregados.FormResize(Sender: TObject); begin gpListaEmp.Width := fmCadEmpregados.Width - 20; gpListaEmp.Height := fmCadEmpregados.Height - (gpListaEmp.Top + 50); end; end.
{ @abstract(TSynUniSyn main source) @authors(Fantasist [walking_in_the_sky@yahoo.com], Vit [nevzorov@yahoo.com], Vitalik [2vitalik@gmail.com], Quadr0 [quadr02005@gmail.com]) @created(2003) @lastmod(2006-07-19) } {$IFNDEF QSynUniHighlighter} unit SynUniHighlighter; {$ENDIF} {$I SynUniHighlighter.inc} interface uses {$IFDEF SYN_CLX} Qt, Types, QGraphics, QSynEditTypes, QSynEditHighlighter, QSynUniClasses, QSynUniRules, {$ELSE} Windows, Graphics, Registry, {$IFDEF DEBUG} Dialogs, {$ENDIF} SynEditTypes, SynEditHighlighter, {$IFDEF CODEFOLDING} SynEditCodeFolding, {$ENDIF} SynUniClasses, SynUniRules, {$ENDIF} Classes, SysUtils; type TSynUniSyn = class(TSynCustomHighlighter) private fActiveScheme: TSynScheme; fFileName: string; fImportFormats: TList; fMainRules: TSynRange; function AttributeExists(AName: string): Boolean; function GetAttributeName(AName: string): string; procedure AddAllAttributes(ARange: TSynRange); //: for working with fAttributes procedure SetScheme(Value: TSynScheme); procedure ReadSyntax(Reader: TReader); procedure WriteSyntax(Writer: TWriter); protected // procedure LoadAdditionalAttributes(ANode: IXMLNode); virtual; //!!EK // procedure SaveAdditionalAttributes(ANode: IXMLNode); virtual; //!!EK public {$IFNDEF SYN_CPPB_1} class {$ENDIF} function GetLanguageName: string; override; protected CurrRange: TSynRange; CurrToken: TSynToken; fEol: Boolean; fLine: PChar; fLineNumber: Integer; fPrEol: Boolean; fPrepared: Boolean; fTokenPos: Integer; Run: LongInt; procedure DefineProperties(Filer: TFiler); override; function GetIdentChars(): TSynIdentChars; override; function GetSampleSource(): string; override; procedure SetSampleSource(Value: string); override; public EditorProperties: TEditorProperties; Info: TSynInfo; Schemes: TSynUniSchemes; FormatVersion: string; //SchemeFileName: string; //ver1.8 //SchemeName: string; //ver1.8 //fSchemes: TStringList; //ver1.8 //fSchemeIndex: Integer; //ver1.8 //fImportFormats: TList; //ver1.8 constructor Create(AOwner: TComponent); overload; override; destructor Destroy(); override; function GetAsStream(): TMemoryStream; function GetDefaultAttribute(Index: Integer): TSynHighlighterAttributes; override; function GetEol(): Boolean; override; function GetRange(): Pointer; override; { Returns current Range } function GetToken(): string; override; // Current token (string from fTokenPos to Run) function GetTokenAttribute(): TSynHighlighterAttributes; override; {Abstract} function GetTokenKind(): Integer; override; function GetTokenPos(): Integer; override; procedure Next(); override; procedure ResetRange(); override; { Reset current range to MainRules } procedure SetLine(NewValue: string; LineNumber: Integer); override; { Set current line in SynEdit for highlighting } procedure SetRange(Value: Pointer); override; procedure Reset(); procedure Clear(); procedure Prepare(); procedure LoadFromStream(AStream: TStream); procedure LoadFromFile(AFileName: string); procedure SaveToStream(AStream: TStream); procedure SaveToFile(AFileName: string); //procedure CreateStandardRules(); вернуть! property ActiveScheme: TSynScheme read fActiveScheme write SetScheme; property FileName: string read fFileName write fFileName; property MainRules: TSynRange read fMainRules; end; implementation uses SynUniFormatNativeXml20, SynUniFormatNativeXmlAuto; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * * * TSynUniSyn * * * * * * * * * * * * * * * * * *} //---------------------------------------------------------------------------- constructor TSynUniSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF PROTECTED_ATTRIBUTES} fAttributes.Duplicates := dupIgnore;//dupError; //: for working with fAttributes fAttributes.Sorted := FALSE;//TRUE; //: for working with fAttributes {$ENDIF} fPrepared := False; Info := TSynInfo.Create(); Schemes := TSynUniSchemes.Create(); fMainRules := TSynRange.Create(); fMainRules.Parent := fMainRules; fEol := False; fPrEol := False; CurrRange := MainRules; fImportFormats := TList.Create(); EditorProperties := TEditorProperties.Create(); FormatVersion := ''; end; //---------------------------------------------------------------------------- destructor TSynUniSyn.Destroy(); begin {$IFDEF PROTECTED_ATTRIBUTES} fAttributes.Clear(); //: for working with fAttributes {$ENDIF} FreeAndNil(fMainRules); FreeAndNil(Info); FreeAndNil(Schemes); FreeList(fImportFormats); FreeAndNil(EditorProperties); inherited; end; //---------------------------------------------------------------------------- function TSynUniSyn.AttributeExists(AName: string): Boolean; var i: Integer; begin Result := False; for i := 0 to AttrCount - 1 do begin if Attribute[i].Name = AName then begin Result := True; Exit; end; end; end; //---------------------------------------------------------------------------- function TSynUniSyn.GetAttributeName(AName: string): string; var i: Integer; NewName: string; begin Result := AName; if AttributeExists(AName) then begin i := 1; while True and (i <= 100) { а что? :-) } do begin Inc(i); NewName := AName + ' (' + IntToStr(i) + ')'; if not AttributeExists(NewName) then begin Result := NewName; break; end; end; end; end; //---------------------------------------------------------------------------- procedure TSynUniSyn.AddAllAttributes(ARange: TSynRange); //: for working with fAttributes var i: Integer; begin {$IFDEF WRITABLE_ATTRIBUTE_NAME} ARange.Attributes.Name := GetAttributeName(ARange.Name); {$ENDIF} //###try AddAttribute(Range.Attributes); except end; try AddAttribute(ARange.ValidAttribs); except end; for i := 0 to ARange.KeyListCount - 1 do begin {$IFDEF WRITABLE_ATTRIBUTE_NAME} ARange.KeyLists[i].Attributes.Name := GetAttributeName(ARange.KeyLists[i].Name); {$ENDIF} //###AddAttribute(Range.KeyLists[i].Attributes); AddAttribute(ARange.KeyLists[i].ValidAttribs); end; for i := 0 to ARange.SetCount - 1 do begin {$IFDEF WRITABLE_ATTRIBUTE_NAME} ARange.Sets[i].Attributes.Name := GetAttributeName(ARange.Sets[i].Name); {$ENDIF} AddAttribute(ARange.Sets[i].Attributes); end; for i := 0 to ARange.RangeCount - 1 do AddAllAttributes(ARange.Ranges[i]); end; //---------------------------------------------------------------------------- procedure TSynUniSyn.SetScheme(Value: TSynScheme); procedure AssignScheme(ARange: TSynRange); var i: Integer; Item: TSynAttributes; begin if ARange <> MainRules then begin Item := Value.GetStyleName(ARange.Style); if Item <> nil then ARange.Attributes.AssignColorAndStyle(Item); end; for i := 0 to aRange.RangeCount - 1 do begin Item := Value.GetStyleName(ARange.Ranges[i].Style); if Item <> nil then ARange.Ranges[i].Attributes.AssignColorAndStyle(Item); if (ARange.Ranges[i].RangeCount > 0) or (ARange.Ranges[i].KeyListCount > 0) or (ARange.Ranges[i].SetCount > 0) then AssignScheme(ARange.Ranges[i]); end; for i := 0 to aRange.KeyListCount - 1 do begin Item := Value.GetStyleName(ARange.KeyLists[i].Style); if Item <> nil then ARange.KeyLists[i].Attributes.AssignColorAndStyle(Item); end; for i := 0 to ARange.SetCount - 1 do begin Item := Value.GetStyleName(ARange.Sets[i].Style); if Item <> nil then ARange.Sets[i].Attributes.AssignColorAndStyle(Item); end; end; begin fActiveScheme := Value; AssignScheme(fMainRules); end; //---------------------------------------------------------------------------- procedure TSynUniSyn.SetLine(NewValue: string; LineNumber: Integer); begin if not CurrRange.Prepared then // If current Range isn't ready, Prepare(); // then prepare it and its sub-ranges fLine := PChar(NewValue); // Current string of SynEdit Run := 0; // Set Position of "parser" at the first char of string fTokenPos := 0; // Set Position of current token at the first char of string fLineNumber := LineNumber; // Number of current line in SynEdit fEol := False; // End of Line fPrEol := False; // Previous End of Line CurrToken := nil; Next(); // Find first token in the line end; //---------------------------------------------------------------------------- procedure TSynUniSyn.Next(); var atr: TSynHighlighterAttributes; begin if Assigned(CurrToken) and CurrToken.Temporary then FreeAndNil(CurrToken); if fPrEol then begin // if it was end of line then // if current range close on end of line then if (CurrRange.CloseOnEol) or (CurrRange.CloseOnTerm) then begin if CurrRange.AllowPreviousClose then begin CurrRange := CurrRange.Parent; while (CurrRange.CloseOnEol) or (CurrRange.CloseOnTerm) do CurrRange := CurrRange.Parent; end else CurrRange := CurrRange.Parent; end; {atr := TSynHighlighterAttributes.Create('123'); atr.Foreground := clRed; atr.Background := clYellow; CurrToken := TSynToken.Create(atr); CurrToken.Temporary := True;} fEol := True; // We are at the end of line Exit; end; fTokenPos := Run; // Start of cf current token is end of previsious // if current range closes on delimeter and current symbol is delimeter then if (CurrRange.CloseOnTerm) and (fLine[Run] in CurrRange.Delimiters) then begin if CurrRange.AllowPreviousClose then begin CurrRange := CurrRange.Parent; while (CurrRange.CloseOnTerm) do CurrRange := CurrRange.Parent; end else CurrRange := CurrRange.Parent; end; if not CurrRange.SymbolList[CurrRange.CaseFunct(fLine[Run])].GetToken(CurrRange, fLine, Run, CurrToken) then begin // If we can't find token from current position //TODO: возможно стоит запихнуть это в TDefaultParser (для наглядности) CurrToken := CurrRange.fDefaultSynToken; // Current token is just default symbol while not ((fLine[Run] in CurrRange.Delimiters) or CurrRange.HasNodeAnyStart[CurrRange.CaseFunct(fLine[Run])]) do begin {$IFDEF SYN_MBCSSUPPORT} // DW if StrByteType(fLine, Run) = mbLeadByte then Inc(Run); {$ENDIF} Inc(Run); // Goes to the first non-delimeter symbol end; end else // We have found token! if (CurrRange.ClosingToken = CurrToken) then begin // If current token closes current range // if (CurrRange.fClosingSymbol <> nil) and (CurrRange.fClosingSymbol.Symbol = CurrToken.Symbol) then if CurrRange.AllowPreviousClose then begin CurrRange := CurrRange.Parent; while (CurrRange.ClosingToken <> nil) and (CurrRange.ClosingToken.Symbol = CurrToken.Symbol) do CurrRange := CurrRange.Parent; end else CurrRange := CurrRange.Parent end else // !!! можно вставить свойство, типа если один range закрывается и сразу открывается другой... Тогда этого else не будет... if (CurrToken <> nil) and (CurrToken.fOpenRule <> nil) then begin // else if current token open range then if CurrToken.fOpenRule is TSynRange then begin CurrRange := TSynRange(CurrToken.fOpenRule); // open range CurrRange.ClosingToken := CurrToken.ClosingToken; end; end; if fLine[Run] = #0 then // If end of line fPrEol := True; // It's now a previous end of line} end; //---------------------------------------------------------------------------- function TSynUniSyn.GetDefaultAttribute(Index: Integer): TSynHighlighterAttributes; begin case Index of SYN_ATTR_COMMENT: Result := CurrRange.Attributes; SYN_ATTR_IDENTIFIER: Result := CurrRange.Attributes; SYN_ATTR_KEYWORD: Result := CurrRange.Attributes; SYN_ATTR_STRING: Result := CurrRange.Attributes; SYN_ATTR_WHITESPACE: Result := CurrRange.Attributes; else Result := nil; end; end; //---------------------------------------------------------------------------- function TSynUniSyn.GetEol(): Boolean; begin Result := fEol; end; //---------------------------------------------------------------------------- function TSynUniSyn.GetRange(): Pointer; begin Result := CurrRange; end; //---------------------------------------------------------------------------- function TSynUniSyn.GetToken(): string; var Len: LongInt; begin Len := Run - fTokenPos; Setstring(Result, (fLine + fTokenPos), Len); end; //---------------------------------------------------------------------------- function TSynUniSyn.GetTokenAttribute(): TSynHighlighterAttributes; begin Result := CurrToken.Attributes; end; //---------------------------------------------------------------------------- function TSynUniSyn.GetTokenPos(): Integer; begin Result := fTokenPos; end; //---------------------------------------------------------------------------- procedure TSynUniSyn.ResetRange(); begin CurrRange := MainRules; end; //---------------------------------------------------------------------------- procedure TSynUniSyn.SetRange(Value: Pointer); begin CurrRange := TSynRange(Value); end; //---------------------------------------------------------------------------- procedure TSynUniSyn.Reset(); begin MainRules.Reset(); end; //---------------------------------------------------------------------------- function TSynUniSyn.GetIdentChars(): TSynIdentChars; // Get word break chars begin Result := [#32..#255] - CurrRange.Delimiters; end; //---------------------------------------------------------------------------- function TSynUniSyn.GetTokenKind(): Integer; //TODO: Заюзать для каких-нибудь целей begin Result := 1; //TODO: Брать индекс стиля ;) end; //---------------------------------------------------------------------------- procedure TSynUniSyn.Clear(); begin {$IFDEF PROTECTED_ATTRIBUTES} fAttributes.Clear(); //: for working with fAttributes {$ENDIF} MainRules.Clear(); Schemes.Clear(); Info.Clear(); {$IFDEF CODEFOLDING} FoldRegions.Clear(); {$ENDIF} end; //---------------------------------------------------------------------------- procedure TSynUniSyn.Prepare(); begin {$IFDEF PROTECTED_ATTRIBUTES} fAttributes.Clear(); //: for working with fAttributes AddAllAttributes(MainRules); //: for working with fAttributes {$ENDIF} fMainRules.Prepare(fMainRules); DefHighlightChange(Self); end; //---------------------------------------------------------------------------- procedure TSynUniSyn.DefineProperties(Filer: TFiler); //! Never used ???? var iHasData: Boolean; begin inherited; if Filer.Ancestor <> nil then iHasData := True else iHasData := MainRules.RangeCount > 0; Filer.DefineProperty( 'Syntax', ReadSyntax, WriteSyntax, {True}iHasData ); end; //---------------------------------------------------------------------------- procedure TSynUniSyn.ReadSyntax(Reader: TReader); //: This is some metods for reading ??? ??? ??? var iBuffer: TStringStream; begin // iBuffer := nil; // try iBuffer := TStringStream.Create( Reader.ReadString ); iBuffer.Position := 0; LoadFromStream( iBuffer ); // finally FreeAndNil(iBuffer); // end; end; //---------------------------------------------------------------------------- procedure TSynUniSyn.WriteSyntax(Writer: TWriter); //: This is some metods for writing ??? ??? ??? var iBuffer: TStringStream; begin iBuffer := TStringStream.Create( '' ); try SaveToStream( iBuffer ); iBuffer.Position := 0; Writer.WriteString( iBuffer.DataString ); finally FreeAndNil(iBuffer); end; end; //---------------------------------------------------------------------------- function TSynUniSyn.GetSampleSource(): string; //: Get sample text begin Result := Info.General.Sample; end; //---------------------------------------------------------------------------- procedure TSynUniSyn.SetSampleSource(Value: string); //: Set sample text begin Info.General.Sample := Value; end; //---------------------------------------------------------------------------- class function TSynUniSyn.GetLanguageName: string; begin Result := 'UniLanguage'; //TODO: возвращать название подсветки с префиксом 'uni'? end; //------------------------------------------------------------------------------ //procedure TSynUniSyn.LoadAdditionalAttributes(ANode: IXMLNode); //!!EK // begin // virtual holder // end; //------------------------------------------------------------------------------ //procedure TSynUniSyn.SaveAdditionalAttributes(ANode: IXMLNode); //!!EK // begin // virtual holder //end; //---------------------------------------------------------------------------- procedure TSynUniSyn.LoadFromStream(AStream: TStream); begin TSynUniFormatNativeXmlAuto.ImportFromStream(Self, AStream); end; //---------------------------------------------------------------------------- procedure TSynUniSyn.LoadFromFile(AFileName: string); begin TSynUniFormatNativeXmlAuto.ImportFromFile(Self, AFileName); end; //---------------------------------------------------------------------------- function TSynUniSyn.GetAsStream(): TMemoryStream; begin Result := TMemoryStream.Create(); SaveToStream(Result); end; //---------------------------------------------------------------------------- procedure TSynUniSyn.SaveToStream(AStream: TStream); begin TSynUniFormatNativeXml20.ExportToStream(Self, AStream); end; //---------------------------------------------------------------------------- procedure TSynUniSyn.SaveToFile(AFileName: string); begin TSynUniFormatNativeXml20.ExportToFile(Self, AFileName); end; initialization {$IFNDEF SYN_CPPB_1} RegisterPlaceableHighlighter(TSynUniSyn); {$ENDIF} end.
unit C_FileNames; //------------------------------------------------------------------------------ // Модуль строковых констант // // !!! // вопроки названию содержит ВСЕ строковые константы // !!! //------------------------------------------------------------------------------ // Описания в комментариях в коде //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils; //------------------------------------------------------------------------------ const //------------------------------------------------------------------------------ //! строка формата даты-времени //------------------------------------------------------------------------------ CDateTimeFormat: string = 'yyyy"."mm"."dd" "hh":"nn":"ss'; //------------------------------------------------------------------------------ //! универсальный разделитель //------------------------------------------------------------------------------ CSemicolon = ';'; //------------------------------------------------------------------------------ //! блок разделителей пути к файлам //------------------------------------------------------------------------------ CPathDelim = PathDelim; CDriveDelim = DriveDelim; CExtDelim = '.'; CPathSep = PathSep; //------------------------------------------------------------------------------ //! блок файлов логов //------------------------------------------------------------------------------ CLogDefExt = 'log'; CLogDefExtDotted = CExtDelim + CLogDefExt; CErrorLogSuffix = '_ERR'; //------------------------------------------------------------------------------ //! блок ini-файлов //------------------------------------------------------------------------------ CIniDefExt = 'ini'; CIniDefExtDotted = CExtDelim + CIniDefExt; //------------------------------------------------------------------------------ //! блок cfg-файлов //------------------------------------------------------------------------------ CCfgDefExt = 'cfg'; CCfgDefExtDotted = CExtDelim + CCfgDefExt; //------------------------------------------------------------------------------ //! префикс имени файлов, отправляемых на сервер клиента //------------------------------------------------------------------------------ CToClientSrvPrefix = 'R'; //------------------------------------------------------------------------------ //! префикс имени файлов, получаемых с сервера клиента //------------------------------------------------------------------------------ CFromClientSrvPrefix = 'S'; //------------------------------------------------------------------------------ //! суффикс имени объединённых файлов //------------------------------------------------------------------------------ CZeroNamePart = '000000'; //------------------------------------------------------------------------------ //! имя файлов для отправки //------------------------------------------------------------------------------ CNameSend = 'ToSend'; //------------------------------------------------------------------------------ //! суффикс имени файлов для отправки на экспедитор (иначе конфликт с CSendName) //------------------------------------------------------------------------------ CSendAffix = '_tosend'; //------------------------------------------------------------------------------ //! конечный символ расширения (при временном переименовании исходных файлов соединителем файлов) //------------------------------------------------------------------------------ CSharp = '#'; //------------------------------------------------------------------------------ //! расширение файлов фактических точек //------------------------------------------------------------------------------ CDeviceDataExt = 'pnt'; CDeviceDataExtDotted = CExtDelim + CDeviceDataExt; //------------------------------------------------------------------------------ //! расширение файлов плановых точек для экспедитора //------------------------------------------------------------------------------ CExpPlanExt = 'cpt'; CExpPlanExtDotted = CExtDelim + CExpPlanExt; //------------------------------------------------------------------------------ //! расширение файлов сообщений для экспедитора //------------------------------------------------------------------------------ CExpMessagesExt = 'cms'; CExpMessagesExtDotted = CExtDelim + CExpMessagesExt; //------------------------------------------------------------------------------ //! расширение файлов сообщений ОТ экспедитора //------------------------------------------------------------------------------ CSrvMessagesExt = 'mms'; CSrvMessagesExtDotted = CExtDelim + CSrvMessagesExt; //------------------------------------------------------------------------------ //! расширение файлов статуса ОТ экспедитора //------------------------------------------------------------------------------ CExpStatusOfExt = 'mps'; CExpStatusOfExtDotted = CExtDelim + CExpStatusOfExt; //------------------------------------------------------------------------------ //! расширение файлов накладных для экспедитора //------------------------------------------------------------------------------ CExpBillExt = 'cwb'; CExpBillExtDotted = CExtDelim + CExpBillExt; //------------------------------------------------------------------------------ //! расширение файлов изменения накладных ОТ экспедитора //------------------------------------------------------------------------------ CChangeBillExt = 'mwb'; CChangeBillExtDotted = CExtDelim + CChangeBillExt; //------------------------------------------------------------------------------ //! расширение для пересылаемых для и ОТ экспедитора файлов //------------------------------------------------------------------------------ CExpAnyExt = 'any'; CExpAnyExtDotted = CExtDelim + CExpAnyExt; //------------------------------------------------------------------------------ //! каталог логов приборов //------------------------------------------------------------------------------ CDeviceLogPathSlashed = CPathDelim + 'Logs' + CPathDelim; //------------------------------------------------------------------------------ //! каталог логов "приборов" экспедитора //------------------------------------------------------------------------------ CExpeditorLogPathSlashed = CPathDelim + 'ExpLogs' + CPathDelim; //------------------------------------------------------------------------------ //! каталог лога запросов WDLoader'а //------------------------------------------------------------------------------ CWDMLogs = 'WebLogs'; //------------------------------------------------------------------------------ implementation end.
unit NfeDetalhe; {$mode objfpc}{$H+} interface uses HTTPDefs, BrookRESTActions, BrookUtils, FPJson, SysUtils, BrookHTTPConsts; type TNfeDetalheOptions = class(TBrookOptionsAction) end; TNfeDetalheRetrieve = class(TBrookRetrieveAction) procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override; end; TNfeDetalheShow = class(TBrookShowAction) end; TNfeDetalheCreate = class(TBrookCreateAction) end; TNfeDetalheUpdate = class(TBrookUpdateAction) end; TNfeDetalheDestroy = class(TBrookDestroyAction) end; implementation procedure TNfeDetalheRetrieve.Request(ARequest: TRequest; AResponse: TResponse); var VRow: TJSONObject; Campo: String; Filtro: String; Opcao: String; begin Campo := Values['campo'].AsString; Filtro := Values['filtro'].AsString; Opcao := Values['opcao'].AsString; Values.Clear; Table.Where(Campo + ' = "' + Filtro + '"'); if Opcao = 'registro' then begin if Execute then begin Table.GetRow(VRow); try Write(VRow.AsJSON); finally FreeAndNil(VRow); end; end else begin AResponse.Code := BROOK_HTTP_STATUS_CODE_NOT_FOUND; AResponse.CodeText := BROOK_HTTP_REASON_PHRASE_NOT_FOUND; end; end else inherited Request(ARequest, AResponse); end; initialization TNfeDetalheOptions.Register('nfe_detalhe', '/nfe_detalhe'); TNfeDetalheRetrieve.Register('nfe_detalhe', '/nfe_detalhe/:campo/:filtro/:opcao/'); TNfeDetalheShow.Register('nfe_detalhe', '/nfe_detalhe/:id'); TNfeDetalheCreate.Register('nfe_detalhe', '/nfe_detalhe'); TNfeDetalheUpdate.Register('nfe_detalhe', '/nfe_detalhe/:id'); TNfeDetalheDestroy.Register('nfe_detalhe', '/nfe_detalhe/:id'); end.
unit Odontologia.Controlador.Paciente; interface uses Data.DB, System.SysUtils, System.Generics.Collections, Odontologia.Controlador.Paciente.Interfaces, Odontologia.Controlador.Estado, Odontologia.Controlador.Estado.Interfaces, Odontologia.Modelo, Odontologia.Modelo.Entidades.Paciente, Odontologia.Modelo.Paciente.Interfaces, Odontologia.Modelo.Estado.Interfaces; type TControllerPaciente = class(TInterfacedObject, iControllerPaciente) private FModel : iModelPaciente; FDataSource : TDataSource; FEstado : iControllerEstado; procedure DataChange (sender : tobject ; field : Tfield) ; public constructor Create; destructor Destroy; override; class function New : iControllerPaciente; function DataSource (aDataSource : TDataSource) : iControllerPaciente; function Buscar (aPaciente : String) : iControllerPaciente; overload; function Buscar : iControllerPaciente; overload; function Insertar : iControllerPaciente; function Modificar : iControllerPaciente; function Eliminar : iControllerPaciente; function Entidad : TDPACIENTE; function Estado : iControllerEstado; end; implementation { TControllerPaciente } function TControllerPaciente.Buscar: iControllerPaciente; begin Result := Self; FDataSource.dataset.DisableControls; FModel.DAO.SQL.Fields('DPACIENTE.PAC_CODIGO AS CODIGO,') .Fields('DPACIENTE.PAC_NOMBRE AS NOMBRE,') .Fields('DPACIENTE.PAC_DOCUMENTO AS DOCUMENTO,') .Fields('DPACIENTE.PAC_TELEFONO AS TELEFONO,') .Fields('DPACIENTE.PAC_DIRECCION AS DIRECCION,') .Fields('DPACIENTE.PAC_FOTO AS FOTO,') .Fields('DPACIENTE.PAC_COD_ESTADO AS CODESTADO,') .Fields('FSITUACION.SIT_SITUACION AS ESTADO ') .Join('INNER JOIN FSITUACION ON FSITUACION.SIT_CODIGO = DPACIENTE.PAC_COD_ESTADO') .Where('') .OrderBy('NOMBRE') .&End.Find; FDataSource.dataset.EnableControls; FDataSource.dataset.FieldByName('CODIGO').Visible := False; FDataSource.dataset.FieldByName('DIRECCION').Visible := False; FDataSource.dataset.FieldByName('FOTO').Visible := False; FDataSource.dataset.FieldByName('CODESTADO').Visible := False; FDataSource.dataset.FieldByName('NOMBRE').DisplayWidth := 50; end; function TControllerPaciente.Buscar(aPaciente: String): iControllerPaciente; begin Result := Self; FDataSource.dataset.DisableControls; FModel.DAO.SQL.Fields('DPACIENTE.PAC_CODIGO AS CODIGO,') .Fields('DPACIENTE.PAC_NOMBRE AS NOMBRE,') .Fields('DPACIENTE.PAC_DOCUMENTO AS DOCUMENTO,') .Fields('DPACIENTE.PAC_TELEFONO AS TELEFONO,') .Fields('DPACIENTE.PAC_DIRECCION AS DIRECCION,') .Fields('DPACIENTE.PAC_ESPECIALIDAD AS ESPECIALIDAD,') .Fields('DPACIENTE.PAC_FOTO AS FOTO,') .Fields('DPACIENTE.PAC_COD_ESTADO AS CODESTADO,') .Fields('FSITUACION.SIT_SITUACION AS ESTADO ') .Join('INNER JOIN FSITUACION ON FSITUACION.SIT_CODIGO = DPACIENTE.PAC_COD_ESTADO') .Where('DPACIENTE.PAC_NOMBRE LIKE ' +QuotedStr(aPaciente) + '') .OrderBy('NOMBRE') .&End.Find; FDataSource.dataset.EnableControls; FDataSource.dataset.FieldByName('CODIGO').Visible := False; FDataSource.dataset.FieldByName('DIRECCION').Visible := False; FDataSource.dataset.FieldByName('FOTO').Visible := False; FDataSource.dataset.FieldByName('CODESTADO').Visible := False; FDataSource.dataset.FieldByName('NOMBRE').DisplayWidth := 50; end; constructor TControllerPaciente.Create; begin FModel := TModel.New.Paciente; end; procedure TControllerPaciente.DataChange(sender: tobject; field: Tfield); begin end; function TControllerPaciente.DataSource(aDataSource: TDataSource) : iControllerPaciente; begin Result := Self; FDataSource := aDataSource; FModel.DataSource(FDataSource); FDataSource.OnDataChange := DataChange; end; destructor TControllerPaciente.Destroy; begin inherited; end; function TControllerPaciente.Eliminar: iControllerPaciente; begin Result := Self; FModel.DAO.Delete(FModel.Entidad); end; function TControllerPaciente.Estado: iControllerEstado; begin Result := FEstado; end; function TControllerPaciente.Entidad: TDPACIENTE; begin Result := FModel.Entidad; end; function TControllerPaciente.Insertar: iControllerPaciente; begin Result := Self; FModel.DAO.Insert(FModel.Entidad); end; function TControllerPaciente.Modificar: iControllerPaciente; begin Result := Self; FModel.DAO.Update(FModel.Entidad); end; class function TControllerPaciente.New: iControllerPaciente; begin Result := Self.Create; end; end.
namespace ComplexNumbers; interface type ConsoleApp = class public class method Main; end; implementation class method ConsoleApp.Main; var x: Double; a,b: Complex; begin a := 5.0; // operator Implicit a.Imaginary := -3; Console.WriteLine(a.ToString); b := new Complex(2,9); Console.WriteLine(b); Console.WriteLine(-b); // operator Minus Console.WriteLine(a-b); // operator Subtract x := Double(a); // operator Explicit Console.WriteLine(x); a := new Complex(3, 2); b := new Complex(4, 5); Console.WriteLine('a*b='+a*b); Console.WriteLine('a/b='+a/b); Console.ReadLine(); end; end.
unit Chapter06._03_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, AI.TreeNode, DeepStar.Utils, DeepStar.DSA.Linear.Stack; /// 144. Binary Tree Preorder Traversal /// https://leetcode.com/problems/binary-tree-preorder-traversal/description/ /// 非递归的二叉树的前序遍历 /// 时间复杂度: O(n), n为树的节点个数 /// 空间复杂度: O(h), h为树的高度 type TSolution = class(TObject) public function preorderTraversal(root: TTreeNode): TList_int; end; type TStack_TreeNode = specialize TStack<TTreeNode>; procedure Main; implementation procedure Main; var a: TArr_int; l: TList_int; t: TTreeNode; begin a := [1, 3, 2]; TArrayUtils_int.Print(a); t := TTreeNode.Create(a); with TSolution.Create do begin l := preorderTraversal(t); TArrayUtils_int.Print(l.ToArray); Free; end; l.Free; t.ClearAndFree; end; { TSolution } function TSolution.preorderTraversal(root: TTreeNode): TList_int; type TCmdType = (go, print); TCmd = record node: TTreeNode; cmdType: TCmdType; end; TStack_TreeNode = specialize TStack<TCmd>; function __cmd__(node: TTreeNode; cmdType: TCmdType): TCmd; begin Result.node := node; Result.cmdType := cmdType; end; var stack: TStack_TreeNode; ret: TList_int; cmd: TCmd; begin stack := TStack_TreeNode.Create; ret := TList_int.Create; stack.Push(__cmd__(root, TCmdType.go)); while not stack.IsEmpty do begin cmd := stack.Pop; if cmd.cmdType = TCmdType.print then begin ret.AddLast(cmd.node.Val); end else begin if cmd.node.Right <> nil then stack.Push(__cmd__(cmd.node.Right, TCmdType.go)); if cmd.node.Left <> nil then stack.Push(__cmd__(cmd.node.Left, TCmdType.go)); stack.Push(__cmd__(cmd.node, TCmdType.print)); end; end; Result := ret; stack.Free; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFPostDataElement; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefPostDataElementRef = class(TCefBaseRefCountedRef, ICefPostDataElement) protected function IsReadOnly: Boolean; procedure SetToEmpty; procedure SetToFile(const fileName: ustring); procedure SetToBytes(size: NativeUInt; bytes: Pointer); function GetType: TCefPostDataElementType; function GetFile: ustring; function GetBytesCount: NativeUInt; function GetBytes(size: NativeUInt; bytes: Pointer): NativeUInt; public class function UnWrap(data: Pointer): ICefPostDataElement; class function New: ICefPostDataElement; end; TCefPostDataElementOwn = class(TCefBaseRefCountedOwn, ICefPostDataElement) protected FDataType: TCefPostDataElementType; FValueByte: Pointer; FValueStr: TCefString; FSize: NativeUInt; FReadOnly: Boolean; procedure Clear; function IsReadOnly: Boolean; virtual; procedure SetToEmpty; virtual; procedure SetToFile(const fileName: ustring); virtual; procedure SetToBytes(size: NativeUInt; bytes: Pointer); virtual; function GetType: TCefPostDataElementType; virtual; function GetFile: ustring; virtual; function GetBytesCount: NativeUInt; virtual; function GetBytes(size: NativeUInt; bytes: Pointer): NativeUInt; virtual; public constructor Create(readonly: Boolean); virtual; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions; function cef_post_data_element_is_read_only(self: PCefPostDataElement): Integer; stdcall; begin with TCefPostDataElementOwn(CefGetObject(self)) do Result := Ord(IsReadOnly) end; procedure cef_post_data_element_set_to_empty(self: PCefPostDataElement); stdcall; begin with TCefPostDataElementOwn(CefGetObject(self)) do SetToEmpty; end; procedure cef_post_data_element_set_to_file(self: PCefPostDataElement; const fileName: PCefString); stdcall; begin with TCefPostDataElementOwn(CefGetObject(self)) do SetToFile(CefString(fileName)); end; procedure cef_post_data_element_set_to_bytes(self: PCefPostDataElement; size: NativeUInt; const bytes: Pointer); stdcall; begin with TCefPostDataElementOwn(CefGetObject(self)) do SetToBytes(size, bytes); end; function cef_post_data_element_get_type(self: PCefPostDataElement): TCefPostDataElementType; stdcall; begin with TCefPostDataElementOwn(CefGetObject(self)) do Result := GetType; end; function cef_post_data_element_get_file(self: PCefPostDataElement): PCefStringUserFree; stdcall; begin with TCefPostDataElementOwn(CefGetObject(self)) do Result := CefUserFreeString(GetFile); end; function cef_post_data_element_get_bytes_count(self: PCefPostDataElement): NativeUInt; stdcall; begin with TCefPostDataElementOwn(CefGetObject(self)) do Result := GetBytesCount; end; function cef_post_data_element_get_bytes(self: PCefPostDataElement; size: NativeUInt; bytes: Pointer): NativeUInt; stdcall; begin with TCefPostDataElementOwn(CefGetObject(self)) do Result := GetBytes(size, bytes) end; function TCefPostDataElementRef.IsReadOnly: Boolean; begin Result := PCefPostDataElement(FData)^.is_read_only(PCefPostDataElement(FData)) <> 0; end; function TCefPostDataElementRef.GetBytes(size: NativeUInt; bytes: Pointer): NativeUInt; begin Result := PCefPostDataElement(FData)^.get_bytes(PCefPostDataElement(FData), size, bytes); end; function TCefPostDataElementRef.GetBytesCount: NativeUInt; begin Result := PCefPostDataElement(FData)^.get_bytes_count(PCefPostDataElement(FData)); end; function TCefPostDataElementRef.GetFile: ustring; begin Result := CefStringFreeAndGet(PCefPostDataElement(FData)^.get_file(PCefPostDataElement(FData))); end; function TCefPostDataElementRef.GetType: TCefPostDataElementType; begin Result := PCefPostDataElement(FData)^.get_type(PCefPostDataElement(FData)); end; class function TCefPostDataElementRef.New: ICefPostDataElement; begin Result := UnWrap(cef_post_data_element_create); end; procedure TCefPostDataElementRef.SetToBytes(size: NativeUInt; bytes: Pointer); begin PCefPostDataElement(FData)^.set_to_bytes(PCefPostDataElement(FData), size, bytes); end; procedure TCefPostDataElementRef.SetToEmpty; begin PCefPostDataElement(FData)^.set_to_empty(PCefPostDataElement(FData)); end; procedure TCefPostDataElementRef.SetToFile(const fileName: ustring); var f: TCefString; begin f := CefString(fileName); PCefPostDataElement(FData)^.set_to_file(PCefPostDataElement(FData), @f); end; class function TCefPostDataElementRef.UnWrap(data: Pointer): ICefPostDataElement; begin if data <> nil then Result := Create(data) as ICefPostDataElement else Result := nil; end; // TCefPostDataElementOwn procedure TCefPostDataElementOwn.Clear; begin case FDataType of PDE_TYPE_BYTES: if (FValueByte <> nil) then begin FreeMem(FValueByte); FValueByte := nil; end; PDE_TYPE_FILE: CefStringFree(@FValueStr) end; FDataType := PDE_TYPE_EMPTY; FSize := 0; end; constructor TCefPostDataElementOwn.Create(readonly: Boolean); begin inherited CreateData(SizeOf(TCefPostDataElement)); FReadOnly := readonly; FDataType := PDE_TYPE_EMPTY; FValueByte := nil; FillChar(FValueStr, SizeOf(FValueStr), 0); FSize := 0; with PCefPostDataElement(FData)^ do begin is_read_only := cef_post_data_element_is_read_only; set_to_empty := cef_post_data_element_set_to_empty; set_to_file := cef_post_data_element_set_to_file; set_to_bytes := cef_post_data_element_set_to_bytes; get_type := cef_post_data_element_get_type; get_file := cef_post_data_element_get_file; get_bytes_count := cef_post_data_element_get_bytes_count; get_bytes := cef_post_data_element_get_bytes; end; end; function TCefPostDataElementOwn.GetBytes(size: NativeUInt; bytes: Pointer): NativeUInt; begin if (FDataType = PDE_TYPE_BYTES) and (FValueByte <> nil) then begin if size > FSize then Result := FSize else Result := size; Move(FValueByte^, bytes^, Result); end else Result := 0; end; function TCefPostDataElementOwn.GetBytesCount: NativeUInt; begin if (FDataType = PDE_TYPE_BYTES) then Result := FSize else Result := 0; end; function TCefPostDataElementOwn.GetFile: ustring; begin if (FDataType = PDE_TYPE_FILE) then Result := CefString(@FValueStr) else Result := ''; end; function TCefPostDataElementOwn.GetType: TCefPostDataElementType; begin Result := FDataType; end; function TCefPostDataElementOwn.IsReadOnly: Boolean; begin Result := FReadOnly; end; procedure TCefPostDataElementOwn.SetToBytes(size: NativeUInt; bytes: Pointer); begin Clear; if (size > 0) and (bytes <> nil) then begin GetMem(FValueByte, size); Move(bytes^, FValueByte, size); FSize := size; end else begin FValueByte := nil; FSize := 0; end; FDataType := PDE_TYPE_BYTES; end; procedure TCefPostDataElementOwn.SetToEmpty; begin Clear; end; procedure TCefPostDataElementOwn.SetToFile(const fileName: ustring); begin Clear; FSize := 0; FValueStr := CefStringAlloc(fileName); FDataType := PDE_TYPE_FILE; end; end.
unit mrBarCodeEdit; interface uses SysUtils, Classes, Controls, StdCtrls, ADODB, Types, Messages; type TmrBarCodeEdit = class(TEdit) private FRunSecondSQL : Boolean; FConnection: TADOConnection; FDataSet: TADOQuery; FSQL: TStringList; FSecondSQL: TStringList; FKeyField: String; FSecondKeyField: String; FQtyEdit: TEdit; FDisplayQty: Boolean; FCheckBarcodeDigit : Integer; FAfterSearchBarcode: TNotifyEvent; FBeforeSearchBarcode: TNotifyEvent; FBeforeSearchSecondBarcode: TNotifyEvent; FMinimalDigits: Integer; procedure SetupQtyEdit; procedure SetQtyEditPosition; procedure SetSQL(const Value: TStringList); procedure SetSecondSQL(const Value: TStringList); procedure FirstSearch; procedure SecondSearch; function GetMaxBarcodeOrder(AIDModel: Integer): Integer; protected procedure SetParent(AParent: TWinControl); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure CMVisiblechanged(var Message: TMessage); message CM_VISIBLECHANGED; procedure CMEnabledchanged(var Message: TMessage); message CM_ENABLEDCHANGED; procedure CMBidimodechanged(var Message: TMessage); message CM_BIDIMODECHANGED; procedure KeyPress(var Key: Char); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SearchBarcode; procedure SetBounds(ALeft: Integer; ATop: Integer; AWidth: Integer; AHeight: Integer); override; procedure SetParameterValue(AParameterName: String; AValue: Variant); procedure DoKeyPress(Key: Char); function GetFieldValue(AFieldName: String): Variant; function SearchResult: Boolean; property QtyEdit: TEdit read FQtyEdit write FQtyEdit; published property Connection: TADOConnection read FConnection write FConnection; property SQL: TStringList read FSQL write SetSQL; property SecondSQL : TStringList read FSecondSQL write SetSecondSQL; property KeyField: String read FKeyField write FKeyField; property SecondKeyField: String read FSecondKeyField write FSecondKeyField; property DisplayQty: Boolean read FDisplayQty write FDisplayQty; property RunSecondSQL : Boolean read FRunSecondSQL write FRunSecondSQL; property CheckBarcodeDigit : Integer read FCheckBarcodeDigit write FCheckBarcodeDigit; property MinimalDigits: Integer read FMinimalDigits write FMinimalDigits; property AfterSearchBarcode: TNotifyEvent read FAfterSearchBarcode write FAfterSearchBarcode; property BeforeSearchBarcode: TNotifyEvent read FBeforeSearchBarcode write FBeforeSearchBarcode; property BeforeSearchSecondBarcode: TNotifyEvent read FBeforeSearchSecondBarcode write FBeforeSearchSecondBarcode; end; procedure Register; implementation uses DB; procedure Register; begin RegisterComponents('MainRetail', [TmrBarCodeEdit]); end; { TmrBarCodeEdit } constructor TmrBarCodeEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FSQL := TStringList.Create; FSecondSQL := TStringList.Create; FDataSet := TADOQuery.Create(Self); FDataSet.CommandTimeout := 1800; SetupQtyEdit; end; destructor TmrBarCodeEdit.Destroy; begin FreeAndNil(FDataSet); FreeAndNil(FSQL); FreeAndNil(FSecondSQL); inherited; end; procedure TmrBarCodeEdit.SearchBarcode; begin if Trim(Text) <> '' then begin if Pos('*', Text) <> 0 then begin QtyEdit.Text := Copy(Text, 0, Pos('*', Text)-1); Text := Copy(Text, Pos('*', Text)+1, Length(Text)); end; FirstSearch; if FRunSecondSQL and (FDataSet.IsEmpty) then SecondSearch; if Assigned(FAfterSearchBarcode) then AfterSearchBarCode(Self); QtyEdit.Text := '1'; end; end; procedure TmrBarCodeEdit.SetupQtyEdit; begin if not Assigned(FQtyEdit) then begin FQtyEdit := TEdit.Create(Self); FQtyEdit.Name := 'SubQtyEdit'; FQtyEdit.Text := '1'; FQtyEdit.SetSubComponent(True); FQtyEdit.FreeNotification(Self); end; end; procedure TmrBarCodeEdit.SetQtyEditPosition; begin if Assigned(FQtyEdit) then FQtyEdit.SetBounds(Left - 50, Top, 50, Height); end; procedure TmrBarCodeEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited SetBounds(ALeft, ATop, AWidth, AHeight); SetQtyEditPosition; end; procedure TmrBarCodeEdit.CMBidimodechanged(var Message: TMessage); begin inherited; FQtyEdit.BiDiMode := BiDiMode; end; procedure TmrBarCodeEdit.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FQtyEdit) and (Operation = opRemove) then FQtyEdit := nil; end; procedure TmrBarCodeEdit.SetParent(AParent: TWinControl); begin inherited SetParent(AParent); if Assigned(FQtyEdit) then begin FQtyEdit.Parent := AParent; FQtyEdit.Visible := FDisplayQty; end; end; procedure TmrBarCodeEdit.CMEnabledchanged(var Message: TMessage); begin inherited; FQtyEdit.Enabled := Enabled; end; procedure TmrBarCodeEdit.CMVisiblechanged(var Message: TMessage); begin inherited; FQtyEdit.Visible := FDisplayQty; end; procedure TmrBarCodeEdit.KeyPress(var Key: Char); begin if Key = #32 then //Nao permitir espaco Key := #0 else if Key = #13 then begin SearchBarcode; Key := #0; end; end; procedure TmrBarCodeEdit.SetParameterValue(AParameterName: String; AValue: Variant); begin FDataSet.Parameters.ParamByName(AParameterName).Value := AValue; end; function TmrBarCodeEdit.GetFieldValue(AFieldName: String): Variant; begin Result := FDataSet.FieldByName(AFieldName).Value; end; procedure TmrBarCodeEdit.SetSQL(const Value: TStringList); begin FSQL.Assign(Value); end; function TmrBarCodeEdit.SearchResult: Boolean; begin Result := FDataSet.RecordCount > 0; end; procedure TmrBarCodeEdit.SetSecondSQL(const Value: TStringList); begin FSecondSQL.Assign(Value); end; procedure TmrBarCodeEdit.FirstSearch; var iRows, iMaxBarcodeOrder: Integer; sBarcode: String; begin with FDataSet do begin if Active then Close; Connection := FConnection; SQL.Text := FSQL.Text; Parameters.ParamByName(FKeyField).Value := Text; if Assigned(FBeforeSearchBarcode) then BeforeSearchBarCode(Self); Open; if (IsEmpty) and (FCheckBarcodeDigit <> 0) and (Length(Text)>= FMinimalDigits) then begin if Active then Close; Connection := FConnection; SQL.Text := FSQL.Text; Case FCheckBarcodeDigit of 1 : sBarcode := Copy(Text, 2, Length(Text)); 2 : sBarcode := Copy(Text, 1, Length(Text)-1); 3 : sBarcode := Copy(Text, 2, Length(Text)-2) else sBarcode := Copy(Text, 2, Length(Text)-2); end; Parameters.ParamByName(FKeyField).Value := sBarcode; Open; if (not IsEmpty) then begin iMaxBarcodeOrder := GetMaxBarcodeOrder(FieldByName('IDModel').AsInteger); FConnection.Execute( ' IF NOT EXISTS (SELECT IDBarcode FROM Barcode WHERE IDBarcode = '+QuotedStr(Text)+')' + ' BEGIN ' + ' INSERT Barcode (IDBarcode, IDModel, Data, BarcodeOrder) ' + ' SELECT ' + QuotedStr(Text)+ ', M.IDModel, GetDate(), ' + IntToStr(iMaxBarcodeOrder+1) + ' FROM Barcode B ' + ' JOIN Model M ON (M.IDModel = B.IDModel) ' + ' WHERE IDBarcode = ' + QuotedStr(sBarcode) + ' END '); end; end; end; end; procedure TmrBarCodeEdit.SecondSearch; begin with FDataSet do begin if Active then Close; SQL.Text := FSecondSQL.Text; Parameters.ParamByName(FSecondKeyField).Value := Text; if Assigned(FBeforeSearchSecondBarcode) then FBeforeSearchSecondBarcode(Self); Open; end; end; procedure TmrBarCodeEdit.DoKeyPress(Key: Char); var cKey: Char; begin cKey := Key; Self.KeyPress(cKey); end; function TmrBarCodeEdit.GetMaxBarcodeOrder(AIDModel: Integer): Integer; begin with TADOQuery.Create(Self) do try Connection := FConnection; SQL.Text := 'SELECT IsNull(MAX(BarcodeOrder), 0) MaxOrder FROM Barcode WHERE IDModel = ' + IntToStr(AIDModel); Open; Result := FieldByName('MaxOrder').AsInteger; finally Free; end; end; end.
unit FMX.Slides; interface uses FMX.Gestures, FMX.Ani,FMX.Layouts,FMX.Types,System.UITypes, FMX.Graphics, FMX.TabControl, FMX.Objects,FMX.Effects,FMX.StdCtrls,Data.DB, System.SysUtils; type TLayoutHelper = class helper for TLayout procedure Slide(ADataSet : TDataSet; Duracao : Real = 3); procedure ProximoClick(Sender: TObject); procedure AnteriorClick(Sender: TObject); procedure AnimaFinish(Sender: TObject); procedure Proximo; procedure Anterior; procedure Gestos; procedure LayoutGesture(Sender :TObject; const EventInfo : TGestureEventInfo; var Handled : Boolean); end; implementation var GestureManager : TGestureManager; { TLayoutHelper } procedure TLayoutHelper.AnimaFinish(Sender: TObject); begin if (TTabControl(FindComponent(Self.Name+'TabSlide')).TabCount -1) <> (TTabControl(FindComponent(Self.Name+'TabSlide')).TabIndex) then TTabControl(FindComponent(Self.Name+'TabSlide')).Next else TTabControl(FindComponent(Self.Name+'TabSlide')).GotoVisibleTab(0, TTabTransition.Slide,TTabTransitionDirection.Reversed ); TFloatAnimation(Sender).Start; end; procedure TLayoutHelper.Anterior; begin TTabControl(FindComponent(Self.Name+'TabSlide')).Previous; end; procedure TLayoutHelper.AnteriorClick(Sender: TObject); begin Anterior; end; procedure TLayoutHelper.Gestos; begin GestureManager := TGestureManager.Create(Self); GestureManager.Sensitivity := 10; Self.Touch.GestureManager := GestureManager; Self.Touch.StandardGestures := [TStandardGesture.sgLeft,TStandardGesture.sgRight]; Self.OnGesture := LayoutGesture; end; procedure TLayoutHelper.LayoutGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); begin if EventInfo.GestureID = sgiLeft then Proximo else if EventInfo.GestureID = sgiRight then Anterior; end; procedure TLayoutHelper.Proximo; begin if (TTabControl(FindComponent(Self.Name+'TabSlide')).TabCount -1) <> (TTabControl(FindComponent(Self.Name+'TabSlide')).TabIndex) then TTabControl(FindComponent(Self.Name+'TabSlide')).Next else TTabControl(FindComponent(Self.Name+'TabSlide')).GotoVisibleTab(0); end; procedure TLayoutHelper.ProximoClick(Sender: TObject); begin Proximo; end; procedure TLayoutHelper.Slide(ADataSet : TDataSet; Duracao : Real = 3); var TabSlide : TTabControl; TabItem :TTabItem; Fundo :TRectangle; Proximo, Anterior :TSpeedButton; Sombra : TShadowEffect; Animacao :TFloatAnimation; begin ADataSet.Open; Self.BeginUpdate; Self.HitTest := True; Gestos; TabSlide := TTabControl.Create(Self); Self.AddObject(TabSlide); TabSlide.HitTest := False; TabSlide.Align := TAlignLayout.Client; TabSlide.TabPosition := TTabPosition.None; TabSlide.Name := Self.Name+'TabSlide'; ADataSet.First; while not ADataSet.Eof do begin TabItem := TTabItem.Create(TabSlide); TabItem.Text := 'Slide '+ inttostr(ADataSet.RecNo); Fundo := TRectangle.Create(TabItem); TabItem.AddObject(Fundo); Fundo.Fill.Color := TAlphaColorRec.White; Fundo.Stroke.Color := TAlphaColorRec.White; Fundo.Align := TAlignLayout.Client; Fundo.Margins.Top := 10; Fundo.Margins.Left := 10; Fundo.Margins.Right := 10; Fundo.Margins.Bottom := 10; Fundo.HitTest := False; Fundo.Fill.Bitmap.Bitmap.LoadFromFile(ADataSet.FieldByName('Imagem').AsString); Fundo.Fill.Kind := TBrushKind.Bitmap; Fundo.Fill.Bitmap.WrapMode := TWrapMode.TileStretch; Fundo.YRadius := 5; Fundo.XRadius := 5; Sombra := TShadowEffect.Create(Fundo); Fundo.AddObject(Sombra); Sombra.Distance := 0.1; Sombra.Opacity := 0.1; TabSlide.AddObject(TabItem); ADataSet.Next; end; Proximo := TSpeedButton.Create(Self); Self.AddObject(Proximo); Proximo.BringToFront; Proximo.Text := '>'; Proximo.Size.Height := 25; Proximo.Size.Width := 25; Proximo.Position.X := Self.Width - 30; Proximo.Position.Y := (Self.Height/2)- 15; Proximo.OnClick := ProximoClick; Anterior := TSpeedButton.Create(Self); Self.AddObject(Anterior); Anterior.BringToFront; Anterior.Text := '<'; Anterior.Size.Height := 25; Anterior.Size.Width := 25; Anterior.Position.X := 5; Anterior.Position.Y := (Self.Height/2)- 15; Anterior.OnClick := AnteriorClick; Animacao := TFloatAnimation.Create(TabSlide); TabSlide.AddObject(Animacao); Animacao.Duration := Duracao; Animacao.PropertyName := 'Opacity'; Animacao.StartValue := 1; Animacao.StopValue := 1; Animacao.OnFinish := AnimaFinish; Animacao.Start; Self.EndUpdate; end; end.