text
stringlengths
14
6.51M
unit fntMailTest; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, o_SendMail; type TfrmMailTest = class(TForm) GroupBox1: TGroupBox; edt_MeineWebEMail: TEdit; Label1: TLabel; Label2: TLabel; edt_MeinWebPasswort: TEdit; GroupBox2: TGroupBox; Label3: TLabel; Label4: TLabel; edt_Betreff: TEdit; mem_Nachricht: TMemo; Label5: TLabel; edt_EMail: TEdit; btn_Senden: TButton; procedure FormCreate(Sender: TObject); procedure btn_SendenClick(Sender: TObject); private public end; var frmMailTest: TfrmMailTest; implementation {$R *.dfm} procedure TfrmMailTest.FormCreate(Sender: TObject); begin edt_MeineWebEMail.Text := ''; edt_MeinWebPasswort.Text := ''; edt_Betreff.Text := ''; edt_EMail.Text := ''; mem_Nachricht.Clear; end; procedure TfrmMailTest.btn_SendenClick(Sender: TObject); var SendMail: TSendMail; begin SendMail := TSendMail.Create; try SendMail.MeineEMail := edt_MeineWebEMail.Text; SendMail.MeinPasswort := edt_MeinWebPasswort.Text; SendMail.Betreff := edt_Betreff.Text; SendMail.Nachricht := mem_Nachricht.Text; SendMail.EMailAdresse := edt_EMail.Text; SendMail.SendenUeberWebDe; ShowMessage('E-Mail wurde versendet'); finally FreeAndNil(SendMail); end; end; end.
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { 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 JclBase.pas. } { } { The Initial Developer of the Original Code is Marcel van Brakel. } { Portions created by Marcel van Brakel are Copyright Marcel van Brakel. All rights reserved. } { } { Contributors: } { Marcel van Brakel, } { Peter Friese, } { Robert Marquardt (marquardt) } { Robert Rossmair (rrossmair) } { Petr Vones (pvones) } { } {**************************************************************************************************} { } { This unit contains generic JCL base classes and routines to support earlier } { versions of Delphi as well as FPC. } { } {**************************************************************************************************} // Last modified: $Date: 2005/03/15 20:12:27 $ // For history see end of file unit JclBase; {$I jcl.inc} interface uses {$IFDEF MSWINDOWS} Windows, {$ENDIF MSWINDOWS} SysUtils; // Version const JclVersionMajor = 1; // 0=pre-release|beta/1, 2, ...=final JclVersionMinor = 95; // Fifth minor release since JCL 1.90 JclVersionRelease = 3; // 0: pre-release|beta/>=1: release JclVersionBuild = 1848; // build number, days since march 1, 2000 JclVersion = (JclVersionMajor shl 24) or (JclVersionMinor shl 16) or (JclVersionRelease shl 15) or (JclVersionBuild shl 0); // EJclError type EJclError = class(Exception); // EJclWin32Error {$IFDEF MSWINDOWS} type EJclWin32Error = class(EJclError) private FLastError: DWORD; FLastErrorMsg: string; public constructor Create(const Msg: string); constructor CreateFmt(const Msg: string; const Args: array of const); constructor CreateRes(Ident: Integer); overload; constructor CreateRes(ResStringRec: PResStringRec); overload; property LastError: DWORD read FLastError; property LastErrorMsg: string read FLastErrorMsg; end; {$ENDIF MSWINDOWS} // EJclInternalError type EJclInternalError = class(EJclError); // Types type {$IFDEF MATH_EXTENDED_PRECISION} Float = Extended; {$ENDIF MATH_EXTENDED_PRECISION} {$IFDEF MATH_DOUBLE_PRECISION} Float = Double; {$ENDIF MATH_DOUBLE_PRECISION} {$IFDEF MATH_SINGLE_PRECISION} Float = Single; {$ENDIF MATH_SINGLE_PRECISION} PFloat = ^Float; type {$IFDEF FPC} Largeint = Int64; {$ELSE} PPointer = ^Pointer; {$IFDEF RTL140_UP} PByte = System.PByte; {$ELSE ~RTL140_UP} PBoolean = ^Boolean; PByte = Windows.PByte; {$ENDIF ~RTL140_UP} {$ENDIF FPC} PCardinal = ^Cardinal; {$IFNDEF COMPILER7_UP} UInt64 = Int64; {$ENDIF ~COMPILER7_UP} // Interface compatibility {$IFDEF SUPPORTS_INTERFACE} {$IFNDEF FPC} {$IFNDEF RTL140_UP} type IInterface = IUnknown; {$ENDIF ~RTL140_UP} {$ENDIF ~FPC} {$ENDIF SUPPORTS_INTERFACE} // Int64 support procedure I64ToCardinals(I: Int64; var LowPart, HighPart: Cardinal); procedure CardinalsToI64(var I: Int64; const LowPart, HighPart: Cardinal); // Redefinition of TLargeInteger to relieve dependency on Windows.pas type PLargeInteger = ^TLargeInteger; TLargeInteger = Int64; // Redefinition of TULargeInteger to relieve dependency on Windows.pas type PULargeInteger = ^TULargeInteger; TULargeInteger = record case Integer of 0: (LowPart: LongWord; HighPart: LongWord); 1: (QuadPart: Int64); end; // Dynamic Array support type TDynByteArray = array of Byte; TDynShortIntArray = array of Shortint; TDynWordArray = array of Word; TDynSmallIntArray = array of Smallint; TDynLongIntArray = array of Longint; TDynInt64Array = array of Int64; TDynCardinalArray = array of Cardinal; TDynIntegerArray = array of Integer; TDynExtendedArray = array of Extended; TDynDoubleArray = array of Double; TDynSingleArray = array of Single; TDynFloatArray = array of Float; TDynPointerArray = array of Pointer; TDynStringArray = array of string; TDynIInterfaceArray = array of IInterface; TDynObjectArray = array of TObject; // Cross-Platform Compatibility const // (rom) too basic for JclStrings AnsiLineFeed = AnsiChar(#10); AnsiCarriageReturn = AnsiChar(#13); AnsiCrLf = AnsiString(#13#10); {$IFDEF MSWINDOWS} AnsiLineBreak = AnsiCrLf; {$ENDIF MSWINDOWS} {$IFDEF UNIX} AnsiLineBreak = AnsiLineFeed; {$ENDIF UNIX} AnsiSigns = ['-', '+']; AnsiUppercaseLetters = ['A'..'Z']; AnsiLowercaseLetters = ['a'..'z']; AnsiLetters = ['A'..'Z', 'a'..'z']; AnsiDecDigits = ['0'..'9']; AnsiOctDigits = ['0'..'7']; AnsiHexDigits = ['0'..'9', 'A'..'F', 'a'..'f']; AnsiValidIdentifierLetters = ['0'..'9', 'A'..'Z', 'a'..'z', '_']; {$IFNDEF XPLATFORM_RTL} procedure RaiseLastOSError; {$ENDIF ~XPLATFORM_RTL} implementation uses JclResources; //== { EJclWin32Error } ====================================================== {$IFDEF MSWINDOWS} constructor EJclWin32Error.Create(const Msg: string); begin FLastError := GetLastError; FLastErrorMsg := SysErrorMessage(FLastError); inherited CreateFmt(Msg + AnsiLineBreak + RsWin32Prefix, [FLastErrorMsg, FLastError]); end; constructor EJclWin32Error.CreateFmt(const Msg: string; const Args: array of const); begin FLastError := GetLastError; FLastErrorMsg := SysErrorMessage(FLastError); inherited CreateFmt(Msg + AnsiLineBreak + Format(RsWin32Prefix, [FLastErrorMsg, FLastError]), Args); end; constructor EJclWin32Error.CreateRes(Ident: Integer); begin FLastError := GetLastError; FLastErrorMsg := SysErrorMessage(FLastError); inherited CreateFmt(LoadStr(Ident) + AnsiLineBreak + RsWin32Prefix, [FLastErrorMsg, FLastError]); end; constructor EJclWin32Error.CreateRes(ResStringRec: PResStringRec); begin FLastError := GetLastError; FLastErrorMsg := SysErrorMessage(FLastError); {$IFDEF FPC} inherited CreateFmt(ResStringRec^ + AnsiLineBreak + RsWin32Prefix, [FLastErrorMsg, FLastError]); {$ELSE} inherited CreateFmt(LoadResString(ResStringRec) + AnsiLineBreak + RsWin32Prefix, [FLastErrorMsg, FLastError]); {$ENDIF FPC} end; {$ENDIF MSWINDOWS} // Int64 support procedure I64ToCardinals(I: Int64; var LowPart, HighPart: Cardinal); begin LowPart := TULargeInteger(I).LowPart; HighPart := TULargeInteger(I).HighPart; end; procedure CardinalsToI64(var I: Int64; const LowPart, HighPart: Cardinal); begin TULargeInteger(I).LowPart := LowPart; TULargeInteger(I).HighPart := HighPart; end; // Cross Platform Compatibility {$IFNDEF XPLATFORM_RTL} procedure RaiseLastOSError; begin RaiseLastWin32Error; end; {$ENDIF ~XPLATFORM_RTL} // History: // $Log: JclBase.pas,v $ // Revision 1.36 2005/03/15 20:12:27 rrossmair // - version info updated, now 1.95.2, Build 1840 // // Revision 1.35 2005/03/14 08:46:53 rrossmair // - check-in in preparation for release 1.95 // // Revision 1.34 2005/03/09 23:56:45 rrossmair // - fixed compilation condition for UInt64 declaration ($IFDEF COMPILER7_UP instead of $IFDEF COMPILER7) // // Revision 1.33 2005/03/08 16:10:07 marquardt // standard char sets extended and used, some optimizations for string literals // // Revision 1.32 2005/03/08 08:33:15 marquardt // overhaul of exceptions and resourcestrings, minor style cleaning // // Revision 1.31 2005/02/24 16:34:39 marquardt // remove divider lines, add section lines (unfinished) // // Revision 1.30 2005/02/14 00:41:58 rrossmair // - supply PByte for D5/BCB5. Pbyte is required by JclMath.GetParity; including it here helps // avoid inclusion of unit Windows in the uses clause of unit JclMath just because of PByte. // // Revision 1.29 2005/02/13 22:24:25 rrossmair // moved PCardinal declaration from JclMime to JclBase // // Revision 1.28 2005/02/05 14:21:59 rrossmair // - version information updated // // Revision 1.27 2005/01/06 18:48:31 marquardt // AnsiLineBreak, AnsiLineFeed, AnsiCarriageReturn, AnsiCrLf moved to JclBase JclStrings now reexports the names // // Revision 1.26 2004/12/23 04:31:42 rrossmair // - check-in for JCL 1.94 RC 1 // // Revision 1.25 2004/12/18 03:58:05 rrossmair // - fixed to compile in Delphi 5 again // // Revision 1.24 2004/12/17 05:33:02 marquardt // updates for DCL // // Revision 1.23 2004/11/18 00:57:14 rrossmair // - check-in for release 1.93 // // Revision 1.22 2004/11/06 02:13:24 mthoma // history cleaning. // // Revision 1.21 2004/09/30 07:50:29 marquardt // remove PH contributions // // Revision 1.20 2004/09/16 19:47:32 rrossmair // check-in in preparation for release 1.92 // // Revision 1.19 2004/06/16 07:30:14 marquardt // added tilde to all IFNDEF ENDIFs, inherited qualified // // Revision 1.18 2004/06/14 11:05:50 marquardt // symbols added to all ENDIFs and some other minor style changes like removing IFOPT // // Revision 1.17 2004/06/14 06:24:52 marquardt // style cleaning IFDEF // // Revision 1.16 2004/06/06 01:31:09 rrossmair // version information updated for build #1558 // // Revision 1.15 2004/05/31 01:43:18 rrossmair // Processed documentation TODOs // // Revision 1.14 2004/05/13 07:47:30 rrossmair // Removed FPC compatibility code rendered superfluous by latest FPC updates; updated build # // // Revision 1.13 2004/05/08 19:56:55 rrossmair // FPC-related improvements // // Revision 1.12 2004/05/06 05:09:55 rrossmair // Changes for FPC v1.9.4 compatibility // // Revision 1.11 2004/05/05 00:04:10 mthoma // Updated headers: Added donors as contributors, adjusted the initial authors, added cvs names when they were not obvious. Changed $data to $date where necessary, // // Revision 1.10 2004/04/19 06:02:18 rrossmair // fixed QueryPerformanceCounter (FPC compatibility routine) // // Revision 1.9 2004/04/14 23:04:09 // add TDynLongWordArray, TDynBooleanArray // // Revision 1.8 2004/04/06 04:53:18 // adapt compiler conditions, add log entry // end.
/// <summary> /// Reader for WKT format /// </summary> /// <seealso href="http://www.geoapi.org/2.0/javadoc/org/opengis/referencing/doc-files/WKT.html"> /// see also /// </seealso> unit WKTProjections; interface uses Classes, Types, SysUtils, Contnrs; type TWktNode = class; TWKTCRSDefinition = class; EWKTError = class(EArgumentException); TWktNodeList = class(TObjectList) private function DoGetItem(Index: Integer): TWktNode; procedure DoSetItem(Index: Integer; AObject: TWktNode); protected public /// <param name="AKey"> /// node keyword /// </param> /// <returns> /// true if success and dest &lt;&gt; nil /// </returns> /// <remarks> /// use "\" symbol for specify full path to node eg PROJCS\GEOCS /// </remarks> function Find(const AKey: string; out Dest: TWktNode): Boolean; virtual; /// <summary> /// find node by attribute name /// </summary> /// <param name="AKey"> /// node keyword /// </param> /// <param name="AAtributeName"> /// attribute name /// </param> /// <param name="Dest"> /// result /// </param> /// <returns> /// true if success /// </returns> function FindByAttributeName(const AKey, AAtributeName: string; out Dest: TWktNode): Boolean; virtual; property Items[Index: Integer]: TWktNode read DoGetItem write DoSetItem; default; end; TWktNode = class(TWktNodeList) private FAttributes: TStrings; FKeyword: string; FParentNode: TWktNode; FTreeDepth: Integer; function GetAttributesContainer: TStrings; function GetAttributesCount: Integer; function GetIndent(const IndentString: string): string; protected function AttibutesAsString: string; function GetAttribute(Index: Integer): string; procedure SetAttribute(Index: Integer; const Value: string); function GetKeyword(): string; procedure SetKeyword(const Value: string); procedure InitDefaults(); virtual; function Validate: Boolean; virtual; procedure NodeNotFound(const NodeName: string); public constructor Create(AParent: TWktNode); destructor Destroy(); override; procedure AddAttribute(const AValue: string); function AddChild(const Key,Name,Value: string): TWktNode; /// <summary> /// load from Source /// </summary> procedure ParseStream(Source: TStream); virtual; /// <summary> /// save to string /// </summary> /// <param name="PrettyPrint"> /// pretty print /// </param> function SaveToString(const PrettyPrint: Boolean): string; // 0 = attribute name property AttributeValue[Index: Integer]: string read GetAttribute write SetAttribute; /// <summary> /// list of attributes (0 is name) /// </summary> property Attributes: TStrings read GetAttributesContainer; property AttributesCount: Integer read GetAttributesCount; /// <summary> /// node key word /// </summary> property Keyword: string read GetKeyWord write SetKeyword; /// <summary> /// parent node /// </summary> property Parent: TWktNode read FParentNode; /// <summary> /// node tree depth /// </summary> property TreeDepth: Integer read FTreeDepth; end; TWKTCRSDefinition = class(TWktNode) private function GetEmpty: Boolean; public procedure LoadFromFile(const AFilename: string); procedure LoadFromStream(Stream: TStream); procedure LoadFromString(const AString: string); procedure SaveToFile(const AFilename: string); function SaveToStream(AStream: TStream): Integer; property Empty: Boolean read GetEmpty; property Valid: Boolean read Validate; end; TWKTCRSDefinitionClass = class of TWKTCRSDefinition; TWKTGeoCRS = class(TWKTCRSDefinition) private FDatum: TWktNode; FSpheroid: TWktNode; FPrimem: TWktNode; FUnit: TWktNode; FToWGS: TWktNode; function GetName: string; procedure SetName(const Value: string); function GetDatumName: string; function GetPrimeMeridianName: string; function GetPrimeMeridianNameLon: string; function GetSpheroidAF: string; function GetSpheroidName: string; function GetToWGS: string; procedure SetSpheroidAF(const Value: string); procedure SetDatumName(const Value: string); procedure SetPrimeMeridianLon(const Value: string); procedure SetPrimeMeridianName(const Value: string); procedure SetSpheroidName(const Value: string); procedure SetToWGS(const Value: string); function GetAngularUnits: string; function GetUnitsConversionFactor: string; procedure SetAngularUnits(const Value: string); procedure SetUnitsConversionFactor(const Value: string); function GetQualifiedName: string; function GetDatumNode: TWktNode; function GetPrimemNode: TWktNode; function GetSpheroidNode: TWktNode; function GetUnitNode: TWktNode; protected procedure InitDefaults(); override; function Validate: Boolean; override; public function TryGetDatumNode(): TWktNode; function TrySpheroidNode(): TWktNode; property Name: string read GetName write SetName; property QualifiedName: string read GetQualifiedName; property DatumNode: TWktNode read GetDatumNode; property SpheroidNode: TWktNode read GetSpheroidNode; property PrimemNode: TWktNode read GetPrimemNode; property UnitNode: TWktNode read GetUnitNode; property DatumName: string read GetDatumName write SetDatumName; property SpheroidName: string read GetSpheroidName write SetSpheroidName; property SpheroidAF: string read GetSpheroidAF write SetSpheroidAF; property PrimeMeridianName: string read GetPrimeMeridianName write SetPrimeMeridianName; property PrimeMeridianLon: string read GetPrimeMeridianNameLon write SetPrimeMeridianLon; property UnitsName: string read GetAngularUnits write SetAngularUnits; property UnitsConversionFactor: string read GetUnitsConversionFactor write SetUnitsConversionFactor; property ToWGS: string read GetToWGS write SetToWGS; end; TWKTProjectedCRS = class(TWKTCRSDefinition) private FGeoCS: TWKTGeoCRS; FProjection: TWktNode; FUnits: TWktNode; function GetName: string; procedure SetName(const Value: string); function GetQualifiedName: string; function GetProjectionParameter(const AName: string): string; procedure SetProjectionParameter(const AName,AValue : string); function GetProjectionName: string; function GetUnitsName: string; function GetUnitsToMeters: string; procedure SetProjectionName(const Value: string); procedure SetUnitsName(const Value: string); procedure SetUnitsToMeters(const Value: string); protected function GetGeoCS: TWKTGeoCRS; virtual; function GetParameterNode(const AName,AValue: string): TWktNode; virtual; function GetProjectionNode(): TWktNode; virtual; function GetUnitsNode(): TWktNode; virtual; procedure InitDefaults(); override; function Validate: Boolean; override; public property QualifiedName: string read GetQualifiedName; property Name: string read GetName write SetName; property ProjectionNode : TWktNode read GetProjectionNode; property ParameterNode[const AName,AValue: string]: TWktNode read GetParameterNode; property UnitsNode: TWktNode read GetUnitsNode; property ProjectionName: string read GetProjectionName write SetProjectionName; property GeoCS: TWKTGeoCRS read GetGeoCS; property UnitsName: string read GetUnitsName write SetUnitsName; property UnitsToMeters: string read GetUnitsToMeters write SetUnitsToMeters; property Parameter[const Name: string]: string read GetProjectionParameter write SetProjectionParameter; end; implementation const WKT_REVERSE_SOLIDUS = '\'; WKT_BRACKET_OPEN = '['; // Open bracket (node start) // Could also be ( in wkt geometry WKT_BRACKET_CLOSE = ']'; // Close bracket (node end) // Could also be ) in wkt geometry WKT_QUOTE_CHAR = '"'; WKT_NEWLINE = sLineBreak; WKT_VALUE_SEPARATOR = ','; // Separator for values // legacy keywords WKT_KWD_GEOCCS = 'GEOCCS'; WKT_KWD_GEOGCS = 'GEOGCS'; WKT_KWD_PROJCS = 'PROJCS'; WKT_KWD_VERTCS = 'VERT_CS'; WKT_KWD_LOCALCS = 'LOCAL_CS'; WKT_KWD_VDATUM = 'VERT_DATUM'; WKT_KWD_LDATUM = 'LOCAL_DATUM'; WKT_KWD_COMPDCS = 'COMPD_CS'; WKT_KWD_ID = 'AUTHORITY'; WKT_KWD_TOWGS84 = 'TOWGS84'; WKT_KWD_EXTENSION = 'EXTENSION'; // WKT_KWD_UNKNOWN = 'UNKNOWN'; WKT_KWD_CITATION = 'CITATION'; WKT_KWD_URI = 'URI'; WKT_KWD_UNIT = 'UNIT'; WKT_KWD_ANGUNIT = 'ANGLEUNIT'; WKT_KWD_LENUNIT = 'LENGTHUNIT'; WKT_KWD_SCALEUNIT = 'SCALEUNIT'; WKT_KWD_TIMEUNIT = 'TIMEUNIT'; WKT_KWD_PARAMUNIT = 'PARAMETRICUNIT'; WKT_KWD_SCOPE = 'SCOPE'; WKT_KWD_AREA_EXTENT = 'AREA'; WKT_KWD_BBOX_EXTENT = 'BBOX'; WKT_KWD_VERT_EXTENT = 'VERTICALEXTENT'; WKT_KWD_TIME_EXTENT = 'TIMEEXTENT'; WKT_KWD_REMARK = 'REMARK'; WKT_KWD_PARAMETER = 'PARAMETER'; WKT_KWD_PARAM_FILE = 'PARAMETERFILE'; WKT_KWD_ELLIPSOID = 'ELLIPSOID'; WKT_KWD_ANCHOR = 'ANCHOR'; WKT_KWD_TIME_ORIGIN = 'TIMEORIGIN'; WKT_KWD_GEOD_DATUM = 'DATUM'; WKT_KWD_ENGR_DATUM = 'EDATUM'; WKT_KWD_IMAGE_DATUM = 'IDATUM'; WKT_KWD_PARAM_DATUM = 'PDATUM'; WKT_KWD_TIME_DATUM = 'TDATUM'; WKT_KWD_VERT_DATUM = 'VDATUM'; WKT_KWD_PRIMEM = 'PRIMEM'; WKT_KWD_ORDER = 'ORDER'; WKT_KWD_MERIDIAN = 'MERIDIAN'; WKT_KWD_BEARING = 'BEARING'; WKT_KWD_AXIS = 'AXIS'; WKT_KWD_CS = 'CS'; WKT_KWD_CONVERSION = 'CONVERSION'; WKT_KWD_DERIVING_CONV = 'DERIVINGCONVERSION'; WKT_KWD_METHOD = 'METHOD'; WKT_KWD_GEOD_CRS = 'GEODCRS'; WKT_KWD_ENGR_CRS = 'ENGCRS'; WKT_KWD_IMAGE_CRS = 'IMAGECRS'; WKT_KWD_PARAM_CRS = 'PARAMETRICCRS'; WKT_KWD_PROJ_CRS = 'PROJCRS'; WKT_KWD_TIME_CRS = 'TIMECRS'; WKT_KWD_VERT_CRS = 'VERTCRS'; WKT_KWD_COMPOUND_CRS = 'COMPOUNDCRS'; WKT_KWD_BASE_GEOD_CRS = 'BASEGEODCRS'; WKT_KWD_BASE_ENGR_CRS = 'BASEENGCRS'; WKT_KWD_BASE_PARAM_CRS = 'BASEPARAMETRICCRS'; WKT_KWD_BASE_PROJ_CRS = 'BASEPROJCRS'; WKT_KWD_BASE_TIME_CRS = 'BASETIMECRS'; WKT_KWD_BASE_VERT_CRS = 'BASEVERTCRS'; WKT_KWD_OP_ACCURACY = 'OPERATIONACCURACY'; WKT_KWD_COORD_OP = 'COORDINATEOPERATION'; WKT_KWD_BOUND_CRS = 'BOUNDCRS'; WKT_KWD_ABRTRANS = 'ABRIDGEDTRANSFORMATION'; // keywords for virtual objects WKT_KWD_EXTENT = 'extent'; WKT_KWD_BASE_CRS = 'base-crs'; WKT_KWD_CRS = 'crs'; WKT_KWD_DATUM = 'datum'; WKT_KWD_OBJECT = 'object'; // keywords that are not real objects WKT_KWD_SOURCE_CRS = 'SOURCECRS'; WKT_KWD_TARGET_CRS = 'TARGETCRS'; WKT_KWD_INTERP_CRS = 'INTERPOLATIONCRS'; // alternate keywords WKT_ALT_KWD_ID = 'ID'; WKT_ALT_KWD_ENGR_DATUM = 'ENGINEERINGDATUM'; WKT_ALT_KWD_GEOD_DATUM = 'GEODETICDATUM'; WKT_ALT_KWD_IMAGE_DATUM = 'IMAGEDATUM'; WKT_ALT_KWD_PARAM_DATUM = 'PARAMETRICDATUM'; WKT_ALT_KWD_TIME_DATUM = 'TIMEDATUM'; WKT_ALT_KWD_VERT_DATUM = 'VERTICALDATUM'; WKT_ALT_KWD_ENGR_CRS = 'ENGINEERINGCRS'; WKT_ALT_KWD_GEOD_CRS = 'GEODETICCRS'; WKT_ALT_KWD_PARAM_CRS = 'PARAMETRICCRS'; WKT_ALT_KWD_PROJ_CRS = 'PROJECTEDCCRS'; WKT_ALT_KWD_VERT_CRS = 'VERTICALCRS'; WKT_ALT_KWD_METHOD = 'PROJECTION'; WKT_ALT_KWD_ELLIPSOID = 'SPHEROID'; WKT_ALT_KWD_PRIMEM = 'PRIMEMERIDIAN'; // crs keywords WKT_CRS_KWD_UNKNOWN = 'unknown'; WKT_CRS_KWD_UNNNAMED = 'unnamed'; WKT_CRS_KWD_GEOD = 'geodetic'; WKT_CRS_KWD_PROJ = 'projected'; WKT_CRS_KWD_VERT = 'vertical'; WKT_CRS_KWD_ENGR = 'engineering'; WKT_CRS_KWD_IMAGE = 'image'; WKT_CRS_KWD_PARAM = 'parametric'; WKT_CRS_KWD_TIME = 'time'; WKT_CRS_KWD_BASE_GEOD = 'base-geodetic'; WKT_CRS_KWD_BASE_PROJ = 'base-projected'; WKT_CRS_KWD_BASE_VERT = 'base-vertical'; WKT_CRS_KWD_BASE_ENGR = 'base-engineering'; WKT_CRS_KWD_BASE_PARAM = 'base-parametric'; WKT_CRS_KWD_BASE_TIME = 'base-time'; WKT_CRS_KWD_COMPOUND = 'compound'; WKT_KWD_CRS_KWD_DEGREE = 'degree'; WKT_CRS_KWD_UNIT_METER = 'meter'; WKT_KWD_EXTENSION_PROJ4 = 'PROJ4'; WKT_KWD_DATUM_WGS84 = 'WGS_1984'; WKT_KWD_ELLIPSOID_WGS84 = 'WGS 1984'; WKT_KWD_ELLIPSOID_WGS84_AF = '6378137.0,298.257223563'; function FindChar(const C: Char; const Str: string; const StartIndex: Integer): Integer; var I: Integer; begin for I := StartIndex to Length(Str) do if Str[I] = C then Exit(I); Result := 0; end; function StripQuotes(const AValue: string): string; begin if Length(AValue) > 1 then begin if (AValue[1] = WKT_QUOTE_CHAR) and (AValue[Length(AValue)] = WKT_QUOTE_CHAR) then begin Result := Copy(AValue, 2, Length(AValue) - 2); Exit; end; end; Result := AValue; end; function StripEscapedChars(const AValue: string): string; begin Result := AValue; Result := StringReplace(Result,'\n','',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'\t','',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'\\','\',[rfReplaceAll]); Result := StringReplace(Result,'\"','"',[rfReplaceAll]); end; constructor TWktNode.Create(AParent: TWktNode); begin inherited Create(True); FTreeDepth := 0; FParentNode := AParent; if FParentNode <> nil then FTreeDepth := FParentNode.TreeDepth + 1; InitDefaults(); end; destructor TWktNode.Destroy; begin FreeAndNil(FAttributes); inherited; end; procedure TWktNode.NodeNotFound(const NodeName: string); resourcestring SRequiedNodeNotFound = 'requied node with keyword "%s" not found'; begin raise EWKTError.CreateResFmt(@SRequiedNodeNotFound,[NodeName]); end; { TWktNode } procedure TWktNode.AddAttribute(const AValue: string); begin if (AValue <> '')then Attributes.Add(AValue); end; function TWktNode.AddChild(const Key,Name,Value: string): TWktNode; begin Result := TWktNode.Create(Self); Result.Keyword := Key; Result.AddAttribute(Name); Result.AddAttribute(Value); Add(Result); end; function TWktNode.AttibutesAsString: string; var I: Integer; begin Result := ''; for I := 0 to Attributes.Count - 1 do begin if Result <> '' then Result := Result + WKT_VALUE_SEPARATOR + Attributes[I] else Result := Result + Attributes[I] end; end; function TWktNode.GetAttribute(Index: Integer): string; begin if (Index > -1) and (Index < Attributes.Count) then Result := StripQuotes(Attributes[Index]) else Result := ''; end; function TWktNode.GetAttributesContainer: TStrings; begin if FAttributes = nil then FAttributes := TStringList.Create(); Result := FAttributes; end; function TWktNode.GetAttributesCount: Integer; begin if FAttributes = nil then Result := 0 else Result := FAttributes.Count; end; function TWktNode.GetIndent(const IndentString: string): string; var I: Integer; begin Result := ''; for I := 0 to TreeDepth - 1 do Result := Result + IndentString; end; function TWktNode.GetKeyWord: string; begin Result := FKeyword; end; procedure TWktNode.InitDefaults; begin // end; procedure TWktNode.ParseStream(Source: TStream); var CurrentChar: AnsiChar; TempValue: RawByteString; BracketOpened, QuoteOpened: Boolean; LastCommaPos, CommaCount: Integer; Child: TWktNode; begin if not Assigned(Source) or (Source.Size = 0) or (Source.Position = Source.Size) then Exit; BracketOpened := False; QuoteOpened := False; CommaCount := 0; LastCommaPos := Source.Position; TempValue := ''; while Source.Read(CurrentChar, SizeOf(AnsiChar)) = SizeOf(AnsiChar) do begin case CurrentChar of WKT_BRACKET_OPEN: begin // node start if BracketOpened then begin AddAttribute(StripEscapedChars(string(TempValue))); TempValue := ''; if CommaCount <> 0 then begin // This is a sub-node not a Attribute if AttributesCount <> 0 then Attributes.Delete(AttributesCount - 1); Source.Seek(LastCommaPos, soFromBeginning); // New child Child := TWktNode.Create(Self); Add(Child); Child.ParseStream(Source); end; end else begin // Name, Attribute BracketOpened := True; Keyword := StripEscapedChars(string(TempValue)); TempValue := ''; end; end; WKT_VALUE_SEPARATOR: begin LastCommaPos := Source.Position; AddAttribute(StripEscapedChars(string(TempValue))); TempValue := ''; Inc(CommaCount); end; WKT_BRACKET_CLOSE: begin // End AddAttribute(StripEscapedChars(string(TempValue))); TempValue := ''; Break; end; ' ', #9, #10, #13: Continue; WKT_QUOTE_CHAR: begin QuoteOpened := not QuoteOpened; if QuoteOpened then begin TempValue := CurrentChar; while (Source.Read(CurrentChar, 1) = 1) do begin TempValue := TempValue + CurrentChar; if CurrentChar = WKT_QUOTE_CHAR then begin QuoteOpened := False; Break; end; end; end; end; else TempValue := TempValue + CurrentChar; end; end; Validate; end; function TWktNode.SaveToString(const PrettyPrint: Boolean): string; var I: Integer; begin if Keyword = '' then Exit(''); Result := UpperCase(Keyword) + WKT_BRACKET_OPEN; if AttributesCount > 0 then Result := Result + AttibutesAsString; for I := 0 to Count - 1 do Result := Result + WKT_VALUE_SEPARATOR + Items[I].SaveToString(PrettyPrint); Result := Result + WKT_BRACKET_CLOSE; if PrettyPrint then Result := WKT_NEWLINE + GetIndent(' ') + Result; end; procedure TWktNode.SetAttribute(Index: Integer; const Value: string); begin if (Index > -1) and (Index < Attributes.Count) and (Value <> '') then Attributes[Index] := Value else AddAttribute(Value); end; procedure TWktNode.SetKeyword(const Value: string); begin if not SameText(Value,FKeyword) then FKeyword := Value; end; function TWktNode.Validate: Boolean; begin Result := Count > 0; end; function TWktNodeList.DoGetItem(Index: Integer): TWktNode; begin Result := TWktNode(GetItem(Index)); end; // procedure TWktNodeList.DoSetItem(Index: Integer; AObject: TWktNode); begin SetItem(Index, AObject); end; function TWktNodeList.Find(const AKey: string; out Dest: TWktNode): Boolean; var I, PathDelimPos: Integer; Keyword, Nested: string; begin Dest := nil; PathDelimPos := FindChar(WKT_REVERSE_SOLIDUS, AKey, 1); // its full path n\n if PathDelimPos <> 0 then begin Keyword := Copy(AKey, 1, PathDelimPos - 1); Nested := Copy(AKey, PathDelimPos + 1, MaxInt); end else begin Keyword := AKey; Nested := ''; end; for I := 0 to Count - 1 do if CompareText(Items[I].Keyword, Keyword) = 0 then begin Dest := Items[I]; Break; end; Result := Assigned(Dest); if Result and (Nested <> '') then Result := Dest.Find(Nested, Dest); end; function TWktNodeList.FindByAttributeName(const AKey, AAtributeName: string; out Dest: TWktNode): Boolean; var I: Integer; begin for I := 0 to Count - 1 do begin Dest := Items[I]; if SameText(Dest.Keyword, AKey) and (Dest.AttributesCount > 0) and SameText(StripQuotes(Dest.Attributes[0]), AAtributeName) then Exit(True); end; Dest := nil; Result := False; end; { TWKTProjection } function TWKTCRSDefinition.GetEmpty: Boolean; begin Result := (Count = 0); end; procedure TWKTCRSDefinition.LoadFromFile(const AFilename: string); var S: TStream; begin if not Empty then Clear; if FileExists(AFilename) then begin S := TFileStream.Create(AFilename, fmOpenRead); try LoadFromStream(S); finally FreeAndNil(S); end; end; end; procedure TWKTCRSDefinition.LoadFromStream(Stream: TStream); begin if not Empty then Clear; ParseStream(Stream); end; procedure TWKTCRSDefinition.LoadFromString(const AString: string); var S: TStream; begin S := TStringStream.Create(AString); try LoadFromStream(S); finally FreeAndNil(S); end; end; procedure TWKTCRSDefinition.SaveToFile(const AFilename: string); var Str: string; S: TStream; begin Str := SaveToString(False); if Str <> '' then begin S := TFileStream.Create(AFilename, fmCreate); try S.Write(BytesOf(Str), ByteLength(Str)); finally FreeAndNil(S); end; end; end; function TWKTCRSDefinition.SaveToStream(AStream: TStream): Integer; var S: TStream; begin Result := AStream.Position; S := TStringStream.Create(SaveToString(False)); try AStream.CopyFrom(S, Self.Count); Result := AStream.Position - Result; finally FreeAndNil(S); end; end; { TWKTProjectedCRS } function TWKTProjectedCRS.GetGeoCS: TWKTGeoCRS; begin if FGeoCS = nil then begin FGeoCS := TWKTGeoCRS.Create(Self); Add(FGeoCS); end; Result := FGeoCS; end; function TWKTProjectedCRS.GetName: string; begin Result := AttributeValue[0]; end; function TWKTProjectedCRS.GetProjectionName: string; begin if FProjection = nil then FProjection := GetProjectionNode(); Result := FProjection.AttributeValue[0]; end; function TWKTProjectedCRS.GetProjectionNode(): TWktNode; begin if FProjection = nil then begin if not Find(WKT_ALT_KWD_METHOD,FProjection) then FProjection := AddChild(WKT_ALT_KWD_METHOD,WKT_KWD_UNKNOWN,''); end; Result := FProjection; end; function TWKTProjectedCRS.GetProjectionParameter(const AName: string): string; var ParamNode: TWktNode; begin if FindByAttributeName(WKT_KWD_PARAMETER,AName,ParamNode) then Result := ParamNode.AttributeValue[1] else Result := '' end; function TWKTProjectedCRS.GetUnitsNode(): TWktNode; begin if FUnits = nil then begin if not Find(WKT_KWD_UNIT,FUnits) then FUnits := AddChild(WKT_KWD_UNIT,WKT_CRS_KWD_UNKNOWN,'1') end; Result := FUnits; end; function TWKTProjectedCRS.GetQualifiedName: string; begin Result := Name + WKT_REVERSE_SOLIDUS + FGeoCS.QualifiedName; end; function TWKTProjectedCRS.GetUnitsName: string; begin Result := UnitsNode.AttributeValue[0]; end; function TWKTProjectedCRS.GetUnitsToMeters: string; begin Result := UnitsNode.AttributeValue[1]; end; procedure TWKTProjectedCRS.InitDefaults; begin inherited; Keyword := WKT_KWD_PROJCS; Name := WKT_CRS_KWD_UNNNAMED; end; procedure TWKTProjectedCRS.SetName(const Value: string); begin AttributeValue[0] := Value; end; procedure TWKTProjectedCRS.SetProjectionName(const Value: string); begin if Value.IsNullOrEmpty(Value) then ProjectionNode.AttributeValue[0] := WKT_CRS_KWD_UNKNOWN else ProjectionNode.AttributeValue[0] := Value; end; procedure TWKTProjectedCRS.SetProjectionParameter(const AName, AValue: string); var ParamNode: TWktNode; begin if AValue.IsNullOrEmpty(AValue) then begin if FindByAttributeName(WKT_KWD_PARAMETER,AName,ParamNode) then Remove(ParamNode); end else ParameterNode[AName, AValue].AttributeValue[1] := AValue; end; procedure TWKTProjectedCRS.SetUnitsName(const Value: string); begin if Value.IsNullOrEmpty(Value) then UnitsNode.AttributeValue[0] := WKT_KWD_UNKNOWN else UnitsNode.AttributeValue[0] := Value; end; procedure TWKTProjectedCRS.SetUnitsToMeters(const Value: string); begin if Value.IsNullOrEmpty(Value) then UnitsNode.AttributeValue[1] := '1' else UnitsNode.AttributeValue[1] := Value; end; function TWKTProjectedCRS.GetParameterNode(const AName, AValue: string): TWktNode; begin if not FindByAttributeName(WKT_KWD_PARAMETER,AName,Result) then begin Result := AddChild(WKT_KWD_PARAMETER,AName,AValue) end end; function TWKTProjectedCRS.Validate: Boolean; begin Result := Count > 0; end; { TWKTGeoCRS } function TWKTGeoCRS.GetAngularUnits: string; begin Result := UnitNode.AttributeValue[0]; end; function TWKTGeoCRS.GetUnitsConversionFactor: string; begin Result := UnitNode.AttributeValue[1]; end; function TWKTGeoCRS.GetDatumName: string; begin Result := DatumNode.AttributeValue[0]; end; function TWKTGeoCRS.GetDatumNode: TWktNode; begin if FDatum = nil then begin if not Find(WKT_KWD_GEOD_DATUM,FDatum) then NodeNotFound(WKT_KWD_GEOD_DATUM); // FDatum := AddChild(WKT_KWD_GEOD_DATUM,'WGS_1984',''); end; Result := FDatum; end; function TWKTGeoCRS.GetName: string; begin Result := AttributeValue[0]; end; function TWKTGeoCRS.GetPrimeMeridianName: string; begin Result := PrimemNode.AttributeValue[0]; end; function TWKTGeoCRS.GetPrimeMeridianNameLon: string; begin Result := PrimemNode.AttributeValue[1]; end; function TWKTGeoCRS.GetPrimemNode: TWktNode; begin if FPrimem = nil then begin if not Find(WKT_KWD_PRIMEM,FPrimem) then FPrimem := AddChild(WKT_KWD_PRIMEM,'Greenwich','0.0'); // silenty set to default end; Result := FPrimem; end; function TWKTGeoCRS.GetQualifiedName: string; begin Result := Name + '('+DatumName+')'; end; function TWKTGeoCRS.GetSpheroidAF: string; begin Result := SpheroidNode.AttributeValue[1]; end; function TWKTGeoCRS.GetSpheroidName: string; begin Result := SpheroidNode.AttributeValue[0]; end; function TWKTGeoCRS.GetSpheroidNode: TWktNode; begin if FSpheroid = nil then begin if not DatumNode.Find(WKT_ALT_KWD_ELLIPSOID,FSpheroid) then NodeNotFound(WKT_ALT_KWD_ELLIPSOID); end; Result := FSpheroid; end; function TWKTGeoCRS.GetToWGS: string; begin if FToWGS = nil then begin if not Find(WKT_KWD_TOWGS84,FToWGS) then Exit('') else Result:= FToWGS.AttributeValue[0] end else Result:= FToWGS.AttributeValue[0] end; function TWKTGeoCRS.GetUnitNode: TWktNode; begin if FUnit = nil then begin if not Find(WKT_KWD_UNIT,FUnit) then begin FUnit:= AddChild(WKT_KWD_UNIT,WKT_KWD_CRS_KWD_DEGREE,'0.0174532925199433'); // silently set to defalult end; end; Result := FUnit; end; procedure TWKTGeoCRS.InitDefaults; begin inherited; Keyword := WKT_KWD_GEOCCS; Name := WKT_CRS_KWD_UNNNAMED; if not Empty then begin if not Find(WKT_KWD_GEOD_DATUM,FDatum) then FDatum := AddChild(WKT_KWD_GEOD_DATUM,WKT_KWD_DATUM_WGS84,''); if not FDatum.Find(WKT_ALT_KWD_ELLIPSOID,FSpheroid) then FSpheroid := FDatum.AddChild(WKT_ALT_KWD_ELLIPSOID,WKT_KWD_ELLIPSOID_WGS84,WKT_KWD_ELLIPSOID_WGS84_AF); FDatum.Find(WKT_KWD_TOWGS84,FToWGS); if not Find(WKT_KWD_PRIMEM,FPrimem) then FPrimem := AddChild(WKT_KWD_PRIMEM,'Greenwich','0.0'); if not Find(WKT_KWD_UNIT,FUnit) then FUnit:= AddChild(WKT_KWD_UNIT,WKT_KWD_CRS_KWD_DEGREE,'0.0174532925199433'); end else begin FDatum := AddChild(WKT_KWD_GEOD_DATUM,WKT_KWD_DATUM_WGS84,''); FSpheroid := FDatum.AddChild(WKT_ALT_KWD_ELLIPSOID,WKT_KWD_ELLIPSOID_WGS84,WKT_KWD_ELLIPSOID_WGS84_AF); FToWGS := nil; FPrimem := AddChild(WKT_KWD_PRIMEM,'Greenwich','0.0'); FUnit := AddChild(WKT_KWD_UNIT,WKT_KWD_CRS_KWD_DEGREE,'0.0174532925199433'); end; end; procedure TWKTGeoCRS.SetSpheroidAF(const Value: string); begin TrySpheroidNode.AttributeValue[1] := Value; end; procedure TWKTGeoCRS.SetAngularUnits(const Value: string); begin UnitNode.AttributeValue[0] := Value; end; procedure TWKTGeoCRS.SetUnitsConversionFactor(const Value: string); begin UnitNode.AttributeValue[1] := Value; end; function TWKTGeoCRS.TryGetDatumNode: TWktNode; begin if FDatum = nil then begin if not Find(WKT_KWD_GEOD_DATUM,FDatum) then begin FDatum := AddChild(WKT_KWD_GEOD_DATUM,WKT_KWD_DATUM_WGS84,''); end; end; Result := FDatum; end; function TWKTGeoCRS.TrySpheroidNode: TWktNode; begin if FSpheroid = nil then begin if not TryGetDatumNode.Find(WKT_ALT_KWD_ELLIPSOID,FSpheroid) then begin TryGetDatumNode.AddChild(WKT_ALT_KWD_ELLIPSOID, WKT_KWD_ELLIPSOID_WGS84,WKT_KWD_ELLIPSOID_WGS84_AF); end; end; Result := FSpheroid; end; procedure TWKTGeoCRS.SetDatumName(const Value: string); begin TryGetDatumNode.AttributeValue[0] := Value; end; procedure TWKTGeoCRS.SetName(const Value: string); begin AttributeValue[0] := Value; end; procedure TWKTGeoCRS.SetPrimeMeridianLon(const Value: string); begin PrimemNode.AttributeValue[1] := Value; end; procedure TWKTGeoCRS.SetPrimeMeridianName(const Value: string); begin PrimemNode.AttributeValue[0] := Value; end; procedure TWKTGeoCRS.SetSpheroidName(const Value: string); begin TrySpheroidNode.AttributeValue[0] := Value; end; procedure TWKTGeoCRS.SetToWGS(const Value: string); begin if Value.IsNullOrEmpty(Value) then begin if FToWGS <> nil then begin // FToWGS.AttributeValue[0] := '0,0,0,0,0,0,0'; Remove(FToWGS); FToWGS := nil; end; end else begin if FToWGS = nil then begin if not DatumNode.Find(WKT_KWD_TOWGS84,FToWGS) then FToWGS := DatumNode.AddChild(WKT_KWD_TOWGS84,Value,''); end else FToWGS.AttributeValue[0] := Value; end; end; function TWKTGeoCRS.Validate: Boolean; begin Result := Assigned(FDatum) and Assigned(FSpheroid) and Assigned(FPrimem) and Assigned(FUnit); end; end.
// // Generated by JavaToPas v1.5 20150830 - 103228 //////////////////////////////////////////////////////////////////////////////// unit org.apache.http.conn.ClientConnectionManager; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, org.apache.http.conn.scheme.SchemeRegistry, org.apache.http.conn.ClientConnectionRequest, org.apache.http.conn.routing.HttpRoute, org.apache.http.conn.ManagedClientConnection, java.util.concurrent.TimeUnit; type JClientConnectionManager = interface; JClientConnectionManagerClass = interface(JObjectClass) ['{A76F3671-F3F4-4568-B9E9-D7BDD9DAF37E}'] function getSchemeRegistry : JSchemeRegistry; cdecl; // ()Lorg/apache/http/conn/scheme/SchemeRegistry; A: $401 function requestConnection(JHttpRouteparam0 : JHttpRoute; JObjectparam1 : JObject) : JClientConnectionRequest; cdecl;// (Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Object;)Lorg/apache/http/conn/ClientConnectionRequest; A: $401 procedure closeExpiredConnections ; cdecl; // ()V A: $401 procedure closeIdleConnections(Int64param0 : Int64; JTimeUnitparam1 : JTimeUnit) ; cdecl;// (JLjava/util/concurrent/TimeUnit;)V A: $401 procedure releaseConnection(JManagedClientConnectionparam0 : JManagedClientConnection; Int64param1 : Int64; JTimeUnitparam2 : JTimeUnit) ; cdecl;// (Lorg/apache/http/conn/ManagedClientConnection;JLjava/util/concurrent/TimeUnit;)V A: $401 procedure shutdown ; cdecl; // ()V A: $401 end; [JavaSignature('org/apache/http/conn/ClientConnectionManager')] JClientConnectionManager = interface(JObject) ['{5BBFB321-A071-4527-BC7F-154B40BAAC5E}'] function getSchemeRegistry : JSchemeRegistry; cdecl; // ()Lorg/apache/http/conn/scheme/SchemeRegistry; A: $401 function requestConnection(JHttpRouteparam0 : JHttpRoute; JObjectparam1 : JObject) : JClientConnectionRequest; cdecl;// (Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Object;)Lorg/apache/http/conn/ClientConnectionRequest; A: $401 procedure closeExpiredConnections ; cdecl; // ()V A: $401 procedure closeIdleConnections(Int64param0 : Int64; JTimeUnitparam1 : JTimeUnit) ; cdecl;// (JLjava/util/concurrent/TimeUnit;)V A: $401 procedure releaseConnection(JManagedClientConnectionparam0 : JManagedClientConnection; Int64param1 : Int64; JTimeUnitparam2 : JTimeUnit) ; cdecl;// (Lorg/apache/http/conn/ManagedClientConnection;JLjava/util/concurrent/TimeUnit;)V A: $401 procedure shutdown ; cdecl; // ()V A: $401 end; TJClientConnectionManager = class(TJavaGenericImport<JClientConnectionManagerClass, JClientConnectionManager>) end; implementation end.
unit tvl_ubehavebinders; {$mode objfpc}{$H+} interface uses Controls, ComCtrls, LMessages, Forms, SysUtils, StdCtrls, Menus, types, classes, ExtCtrls, LCLProc, lclintf, fgl, tvl_ucontrolbinder{, Windows}, SynEdit, SynEditTypes, Dialogs, LCLType; const LM_FOCUSCONTROLONPAGE = LM_BEHAVEBINDER + 02; type { TPageControlBehaveBinder } TPageControlBehaveBinder = class(TControlBinder) private type TPageActiveControls = specialize TFPGMap<integer, pointer>; private fPageIndex: Integer; fFirstVisiblePassed: Boolean; fActiveControls: TPageActiveControls; function GetControl: TPageControl; function GetActiveControl: TWinControl; function IsActiveControlOnActivePage: Boolean; procedure FocusActualPageControl; procedure SetFirstVisiblePage; function FindForm: TCustomForm; protected procedure DoControlWndProc(var TheMessage: TLMessage); override; public procedure BindControl; override; property Control: TPageControl read GetControl; procedure AfterConstruction; override; procedure BeforeDestruction; override; end; TPopupMenuBehaveBinder = class(TControlBinder) end; { TPopupMenuBinder } TPopupMenuBinder = class(TControlBinder) public type TBuildMenuEvent = procedure(AMenu: TMenu; AControl: TControl) of object; private fMenu: TPopupMenu; fOnBuildMenu: TBuildMenuEvent; private procedure ShowPopupMenu(const AX, AY: integer); function GetMenu: TPopupMenu; property Menu: TPopupMenu read GetMenu; protected procedure DoControlWndProc(var TheMessage: TLMessage); override; public constructor Create(AOnBuildMenu: TBuildMenuEvent); destructor Destroy; override; procedure BindControl; override; end; { TMoveControlBinder } TMoveControlBinder = class(TControlBinder) private fOriginalParentFormWndProc: TWndMethod; fHold: Boolean; fPrevPos: TPoint; fControlDelta: TPoint; fOriginalCapture: TControl; fOriginalCaptureButtons: TCaptureMouseButtons; function GetParentControl: TWinControl; function GetParentForm: TCustomForm; procedure MoveBegin; procedure MoveEnd; procedure MoveControl; procedure CorrectMousePos; procedure CorrectParent(const AMousePos: TPoint); function FindBranchParent(const AParent: TWinControl; APos: TPoint): TWinControl; function FindUpperParent(const AParent: TWinControl; ASkip: TControl; APos: TPoint): TWinControl; protected procedure DoControlWndProc(var TheMessage: TLMessage); override; procedure MouseMoveUserInputHandler(Sender: TObject; Msg: Cardinal); procedure BindControl; override; public property ParentControl: TWinControl read GetParentControl; property ParentForm: TCustomForm read GetParentForm; end; { TMoveFormBinder } TMoveFormBinder = class(TControlBinder) end; { TSynEditBinder } TSynEditBinder = class(TControlBinder) protected fFindDlg: TFindDialog; procedure OnDlgFind(Sender: TObject); function FindOptions2SynSearchOptions(const AOptions: TFindOptions): TSynSearchOptions; procedure Find; function GetFindDlg: TFindDialog; property FindDlg: TFindDialog read GetFindDlg; protected fReplaceDlg: TReplaceDialog; fLastSearchReplace: integer; procedure OnDlgReplace(Sender: TObject); procedure OnDlgReplaceFind(Sender: TObject); procedure Replace; function GetReplaceDlg: TReplaceDialog; property ReplaceDlg: TReplaceDialog read GetReplaceDlg; protected function GetControl: TCustomSynEdit; procedure DoControlWndProc(var TheMessage: TLMessage); override; public destructor Destroy; override; procedure BindControl; override; property Control: TCustomSynEdit read GetControl; end; implementation { TSynEditBinder } procedure TSynEditBinder.OnDlgFind(Sender: TObject); begin Control.SearchReplace(FindDlg.FindText, '', FindOptions2SynSearchOptions(FindDlg.Options) + [ssoFindContinue]); end; function TSynEditBinder.GetFindDlg: TFindDialog; begin if fFindDlg = nil then begin fFindDlg := TFindDialog.Create(nil); fFindDlg.Title := Format('%s (%s)', [fFindDlg.Title, Control.Name]); fFindDlg.OnFind := @OnDlgFind; end; Result := fFindDlg; end; procedure TSynEditBinder.OnDlgReplace(Sender: TObject); var mSynOptions: TSynSearchOptions; begin mSynOptions := FindOptions2SynSearchOptions(ReplaceDlg.Options); if ssoReplaceAll in mSynOptions then begin Control.SearchReplace(ReplaceDlg.FindText, ReplaceDlg.ReplaceText, mSynOptions); end else begin // replace only one then it will be after previous succesful find if (Control.SelStart = fLastSearchReplace) then begin // otherwise next is replaced and not one just finded and thus selected if ssoBackwards in mSynOptions then Control.LogicalCaretXY := Control.BlockEnd else Control.LogicalCaretXY := Control.BlockBegin; Control.SearchReplace(ReplaceDlg.FindText, ReplaceDlg.ReplaceText, mSynOptions); end; end; end; procedure TSynEditBinder.OnDlgReplaceFind(Sender: TObject); begin fLastSearchReplace := -1; if Control.SearchReplace(ReplaceDlg.FindText, ReplaceDlg.ReplaceText, FindOptions2SynSearchOptions(ReplaceDlg.Options) + [ssoFindContinue]) = 1 then fLastSearchReplace := Control.SelStart; end; procedure TSynEditBinder.Replace; begin ReplaceDlg.Execute; end; function TSynEditBinder.GetReplaceDlg: TReplaceDialog; begin if fReplaceDlg = nil then begin fReplaceDlg := TReplaceDialog.Create(nil); fReplaceDlg.Title := Format('%s (%s)', [fReplaceDlg.Title, Control.Name]); fReplaceDlg.OnFind := @OnDlgReplaceFind; fReplaceDlg.OnReplace := @OnDlgReplace; end; Result := fReplaceDlg; end; function TSynEditBinder.FindOptions2SynSearchOptions( const AOptions: TFindOptions): TSynSearchOptions; var mOp: TFindOption; begin Result := [ssoBackwards]; for mOp in TFindOption do begin if mOp in AOptions then case mOp of frDown: Result := Result - [ssoBackwards]; frFindNext:; frHideMatchCase:; frHideWholeWord:; frHideUpDown:; frMatchCase: Result := Result + [ssoMatchCase]; frDisableMatchCase:; frDisableUpDown:; frDisableWholeWord:; frReplace: Result := Result + [ssoReplace]; frReplaceAll: Result := Result + [ssoReplaceAll]; frWholeWord: Result := Result + [ssoWholeWord]; frShowHelp:; frEntireScope: Result := Result + [ssoEntireScope]; frHideEntireScope:; frPromptOnReplace: Result := Result + [ssoPrompt]; frHidePromptOnReplace:; frButtonsAtBottom:; end; end; end; procedure TSynEditBinder.Find; begin FindDlg.Execute; end; function TSynEditBinder.GetControl: TCustomSynEdit; begin Result := inherited Control as TCustomSynEdit; end; procedure TSynEditBinder.DoControlWndProc(var TheMessage: TLMessage); var mSynOptions: TSynSearchOptions; begin case TheMessage.Msg of LM_KEYDOWN: if (TLMKey(TheMessage).CharCode = VK_F) and ([ssModifier] = MsgKeyDataToShiftState(TLMKey(TheMessage).KeyData)) then begin Find; end else if (TLMKey(TheMessage).CharCode = VK_F3) and (FindDlg.FindText <> '') then begin mSynOptions := FindOptions2SynSearchOptions(FindDlg.Options); if [ssShift] = MsgKeyDataToShiftState(TLMKey(TheMessage).KeyData) then mSynOptions := mSynOptions + [ssoBackwards] else mSynOptions := mSynOptions - [ssoBackwards]; mSynOptions := mSynOptions + [ssoFindContinue]; Control.SearchReplace(FindDlg.FindText, '', mSynOptions); end else if (TLMKey(TheMessage).CharCode = VK_H) and ([ssModifier] = MsgKeyDataToShiftState(TLMKey(TheMessage).KeyData)) then begin Replace; end; end; inherited DoControlWndProc(TheMessage); end; destructor TSynEditBinder.Destroy; begin FreeAndNil(fFindDlg); FreeAndNil(fReplaceDlg); inherited Destroy; end; procedure TSynEditBinder.BindControl; begin inherited BindControl; end; { TMoveControlBinder } function TMoveControlBinder.GetParentControl: TWinControl; begin Result := Control.Parent; end; function TMoveControlBinder.GetParentForm: TCustomForm; var mParent: TWinControl; begin Result := nil; mParent := ParentControl; while (mParent <> nil) and not (mParent is TCustomForm) do mParent := mParent.Parent; if (mParent <> nil) and (mParent is TCustomForm) then Result := mParent as TCustomForm; end; procedure TMoveControlBinder.MoveControl; var mPos: TPoint; mNew: integer; mc: TControl; begin mc := Control; mPos := ParentControl.ScreenToClient(Mouse.CursorPos); mNew := mPos.X - fControlDelta.X; if Control.Left <> mNew then Control.Left := mNew; mNew := mPos.Y - fControlDelta.Y; if Control.Top <> mNew then Control.Top := mNew; end; procedure TMoveControlBinder.CorrectMousePos; var mPos: TPoint; mConPos: TPoint; mRect: TRect; begin mRect.Left := 0; mRect.Right := Control.Width; mRect.Top := 0; mRect.Bottom := Control.Height; mRect.TopLeft := Control.ClientToScreen(mRect.TopLeft); mRect.BottomRight := Control.ClientToScreen(mRect.BottomRight); mPos := Mouse.CursorPos; if mPos.X < mRect.Left then mPos.X := mRect.Left + 1 else if mPos.X > mRect.Right then mPos.X := mRect.Right - 1; if mPos.Y < mRect.Top then mPos.Y := mRect.Top + 1 else if mPos.Y > mRect.Bottom then mPos.Y := mRect.Bottom - 1; Mouse.CursorPos := mPos; end; procedure TMoveControlBinder.CorrectParent(const AMousePos: TPoint); var mPoint, mControlPoint: TPoint; mNewParent: TWinControl; begin mNewParent := FindUpperParent(ParentControl, Control, AMousePos); if (mNewParent <> nil) and (mNewParent <> ParentControl) then begin mControlPoint := Control.ScreenToClient(AMousePos); Control.Parent := mNewParent; mPoint := mNewParent.ScreenToClient(AMousePos); Control.Left := mPoint.X - mControlPoint.X; Control.Top := mPoint.y - mControlPoint.Y; if Control is TWinControl then (Control as TWinControl).SetFocus; end; end; function TMoveControlBinder.FindBranchParent(const AParent: TWinControl; APos: TPoint): TWinControl; var i: integer; mControl: TWinControl; begin Result := nil; if AParent = nil then Exit; // serach in subcontrols for i := 0 to AParent.ControlCount - 1 do begin if not (AParent.Controls[i] is TWinControl) then Continue; mControl := AParent.Controls[i] as TWinControl; Result := FindBranchParent(mControl, APos); if Result <> nil then Exit; end; if AParent is TCustomPanel then begin if PtInRect(AParent.ClientRect, AParent.ScreenToClient(APos)) then Result := AParent; end; end; function TMoveControlBinder.FindUpperParent(const AParent: TWinControl; ASkip: TControl; APos: TPoint): TWinControl; var i: integer; mControl: TWinControl; begin Result := nil; if AParent = nil then Exit; // serach in subcontrols for i := 0 to AParent.ControlCount - 1 do begin if not (AParent.Controls[i] is TWinControl) then Continue; if AParent.Controls[i] = ASkip then Continue; mControl := AParent.Controls[i] as TWinControl; Result := FindBranchParent(mControl, APos); if Result <> nil then Exit; end; // test self if ( (AParent is TCustomPanel) or (AParent is TCustomForm) or (AParent is TCustomGroupBox) ) and PtInRect(AParent.ClientRect, AParent.ScreenToClient(APos)) then begin Result := AParent; Exit; end; // extend search on upper level Result := FindUpperParent(AParent.Parent, AParent, APos); end; procedure TMoveControlBinder.MoveBegin; begin if fHold then raise Exception.Create('already moving'); fHold := True; fPrevPos := Mouse.CursorPos; fControlDelta := Control.ScreenToClient(Mouse.CursorPos); // capture only control not work, ParentForm with MouseMoveUserInputHandler yes SetCaptureControl(ParentForm); Application.AddOnUserInputHandler(@MouseMoveUserInputHandler, True); Control.BringToFront; end; procedure TMoveControlBinder.MoveEnd; begin if not fHold then raise Exception.Create('not moving'); fHold := False; CorrectParent(Mouse.CursorPos); Application.RemoveOnUserInputHandler(@MouseMoveUserInputHandler); SetCaptureControl(nil); end; procedure TMoveControlBinder.DoControlWndProc(var TheMessage: TLMessage ); begin case TheMessage.Msg of LM_LBUTTONDOWN: begin MoveBegin; end; LM_LBUTTONUP: begin if fHold then MoveEnd else inherited; end; LM_MOUSEMOVE: begin if fHold then MoveControl else inherited; end; LM_MOUSELEAVE: begin if fHold then MoveControl else inherited; end; else begin inherited; end; end; end; procedure TMoveControlBinder.MouseMoveUserInputHandler(Sender: TObject; Msg: Cardinal); begin case Msg of LM_LBUTTONUP: begin if fHold then MoveEnd; end; LM_MOUSEMOVE: begin if fHold then MoveControl; end; end; end; procedure TMoveControlBinder.BindControl; begin end; { TPopupMenuBinder } function TPopupMenuBinder.GetMenu: TPopupMenu; begin if fMenu = nil then begin fMenu := TPopupMenu.Create(nil); end; Result := fMenu; end; procedure TPopupMenuBinder.ShowPopupMenu(const AX, AY: integer); begin if Assigned(fOnBuildMenu) then fOnBuildMenu(Menu, Control); Menu.PopUp(AX, AY); end; procedure TPopupMenuBinder.DoControlWndProc(var TheMessage: TLMessage ); begin case TheMessage.Msg of LM_RBUTTONDOWN: begin inherited; ShowPopupMenu(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; else inherited; end; end; constructor TPopupMenuBinder.Create(AOnBuildMenu: TBuildMenuEvent); begin inherited Create; fOnBuildMenu := AOnBuildMenu; end; destructor TPopupMenuBinder.Destroy; begin FreeAndNil(fMenu); inherited Destroy; end; procedure TPopupMenuBinder.BindControl; begin end; { TPageControlBehaveBinder } function TPageControlBehaveBinder.GetControl: TPageControl; begin Result := inherited Control as TPageControl; end; function TPageControlBehaveBinder.GetActiveControl: TWinControl; var mForm: TCustomForm; begin Result := nil; mForm := FindForm; if mForm = nil then Exit; Result := mForm.ActiveControl; end; procedure TPageControlBehaveBinder.DoControlWndProc(var TheMessage: TLMessage ); var mControl: TWinControl; mH: THandle; begin //DebugLn('msg->%d', [TheMessage.Msg]); case TheMessage.Msg of LM_SETFOCUS: begin mControl := GetActiveControl; if mControl <> Control then fActiveControls.KeyData[Control.PageIndex] := mControl; end; 48206: // on PageIndex change will focus first or last focused control // on given tabsheed begin if TLMNotify(TheMessage).NMHdr^.code = TCN_SELCHANGE then begin fPageIndex := Control.PageIndex; inherited; if (Control.PageCount > 0) and (fPageIndex <> Control.PageIndex) then begin PostMessage(Control.Handle, LM_FOCUSCONTROLONPAGE, 0, 0) end end else inherited; end; //LM_SHOWWINDOW is received only on first show LM_PAINT: begin // on first show will set first control on tabsheet as active inherited; if not fFirstVisiblePassed and Control.Visible then begin fFirstVisiblePassed := True; SetFirstVisiblePage; mh := Control.Handle; if Control.PageCount > 0 then PostMessage(Control.Handle, LM_FOCUSCONTROLONPAGE, 0, 0); end; end; LM_FOCUSCONTROLONPAGE: begin FocusActualPageControl; end; else inherited; end; end; procedure TPageControlBehaveBinder.BindControl; begin end; procedure TPageControlBehaveBinder.AfterConstruction; begin inherited AfterConstruction; fActiveControls := TPageActiveControls.Create; end; procedure TPageControlBehaveBinder.BeforeDestruction; begin FreeAndNil(fActiveControls); inherited BeforeDestruction; end; function TPageControlBehaveBinder.IsActiveControlOnActivePage: Boolean; var mControl: TWinControl; mForm: TCustomForm; begin Result := False; mForm := FindForm; if mForm = nil then Exit; if mForm.ActiveControl = nil then Exit; mControl := mForm.ActiveControl.Parent; while mControl <> nil do begin if mControl = Control.ActivePage then begin Result := True; Break; end; mControl := mControl.Parent; end; end; procedure TPageControlBehaveBinder.FocusActualPageControl; var mControl, mFocControl: TWinControl; mTabOrder: integer; i: integer; mInd: integer; begin if not IsActiveControlOnActivePage then begin mFocControl := nil; mInd := fActiveControls.IndexOf(Control.TabIndex); if (mInd <> -1) and (fActiveControls.Data[mInd] <> nil) then mFocControl := TWinControl(fActiveControls.Data[mInd]); if (mFocControl <> nil) and mFocControl.CanFocus then mFocControl.SetFocus else begin mTabOrder := MaxInt; mFocControl := nil; for i := 0 to Control.ActivePage.ControlCount - 1 do begin if not (Control.ActivePage.Controls[i] is TWinControl) then Continue; mControl := Control.ActivePage.Controls[i] as TWinControl; if not mControl.CanFocus or not mControl.TabStop then Continue; if mControl.TabOrder < mTabOrder then begin mFocControl := mControl; mTabOrder := mControl.TabOrder; end; end; if mFocControl <> nil then begin if mFocControl.CanFocus then begin mFocControl.SetFocus; end; end; end; end; end; procedure TPageControlBehaveBinder.SetFirstVisiblePage; var i: integer; begin for i := 0 to Control.PageCount - 1 do begin if Control.Pages[i].TabVisible then begin Control.PageIndex := Control.Pages[i].PageIndex; Break; end; end; end; function TPageControlBehaveBinder.FindForm: TCustomForm; var mControl: TWinControl; begin Result := nil; mControl := Control.Parent; while mControl <> nil do begin if mControl is TCustomForm then begin Result := mControl as TCustomForm; Break; end; mControl := mControl.Parent; end; end; end.
 unit EditSongController; interface uses Generics.Collections, Song, MediaFile, Artist, SongFormat, Aurelius.Engine.ObjectManager; type TEditSongController = class private FManager: TObjectManager; FSong: TSong; public constructor Create; destructor Destroy; override; procedure SaveSong(Song: TSong); procedure Load(SongId: Variant); function GetAlbums: TList<TAlbum>; function GetArtists: TList<TArtist>; function GetSongFormats: TList<TSongFormat>; property Song: TSong read FSong; end; implementation uses DBConnection; { TMusicasController } constructor TEditSongController.Create; begin FSong := TSong.Create; FManager := TDBConnection.GetInstance.CreateObjectManager; end; destructor TEditSongController.Destroy; begin if not FManager.IsAttached(FSong) then FSong.Free; FManager.Free; inherited; end; function TEditSongController.GetAlbums: TList<TAlbum>; begin Result := FManager.FindAll<TAlbum>; end; function TEditSongController.GetArtists: TList<TArtist>; begin Result := FManager.FindAll<TArtist>; end; function TEditSongController.GetSongFormats: TList<TSongFormat>; begin Result := FManager.FindAll<TSongFormat>; end; procedure TEditSongController.Load(SongId: Variant); begin if not FManager.IsAttached(FSong) then FSong.Free; FSong := FManager.Find<TSong>(SongId); end; procedure TEditSongController.SaveSong(Song: TSong); begin if not FManager.IsAttached(Song) then FManager.SaveOrUpdate(Song); FManager.Flush; end; end.
<<<<<<< HEAD PROGRAM WorkWithQueryString(INPUT, OUTPUT); USES GPC; FUNCTION GetQueryStringParameter(Key: STRING): STRING; VAR QS: STRING; PosKey, PosAmp: INTEGER; BEGIN QS := GetEnv('QUERY_STRING'); PosKey := POS(Key, QS); PosAmp := POS('&', QS); IF PosAmp = 0 THEN GetQueryStringParameter := COPY(QS, PosKey + LENGTH(Key) + 1, LENGTH(QS)); IF PosKey < PosAmp THEN GetQueryStringParameter := COPY(QS, PosKey + Length(Key) + 1, PosAmp - LENGTH(Key) - PosKey - 1); IF PosKey > PosAmp THEN BEGIN QS := COPY(QS, PosAmp + (PosKey - PosAmp), LENGTH(QS)); PosKey := POS(Key, QS); PosAmp := POS('&', QS); IF PosAmp = 0 THEN GetQueryStringParameter := COPY(QS, PosKey + LENGTH(Key) + 1, LENGTH(QS)); IF PosKey < PosAmp THEN GetQueryStringParameter := COPY(QS, PosKey + Length(Key) + 1, PosAmp - LENGTH(Key) - PosKey - 1); END; END; BEGIN {WorkWithQueryString} WRITELN('Content-type: text/plain'); WRITELN; WRITELN('First Name: ', GetQueryStringParameter('first_name')); WRITELN('Last Name: ', GetQueryStringParameter('last_name')); WRITELN('Age: ', GetQueryStringParameter('age')) END. {WorkWithQueryString} ======= PROGRAM WorkWithQueryString(INPUT, OUTPUT); USES GPC; FUNCTION GetQueryStringParameter(Key: STRING): STRING; VAR QS: STRING; PosKey, PosAmp: INTEGER; BEGIN QS := GetEnv('QUERY_STRING'); PosKey := POS(Key, QS); PosAmp := POS('&', QS); IF PosAmp = 0 THEN GetQueryStringParameter := COPY(QS, PosKey + LENGTH(Key) + 1, LENGTH(QS)); IF PosKey < PosAmp THEN GetQueryStringParameter := COPY(QS, PosKey + Length(Key) + 1, PosAmp - LENGTH(Key) - PosKey - 1); IF PosKey > PosAmp THEN BEGIN QS := COPY(QS, PosAmp + (PosKey - PosAmp), LENGTH(QS)); PosKey := POS(Key, QS); PosAmp := POS('&', QS); IF PosAmp = 0 THEN GetQueryStringParameter := COPY(QS, PosKey + LENGTH(Key) + 1, LENGTH(QS)); IF PosKey < PosAmp THEN GetQueryStringParameter := COPY(QS, PosKey + Length(Key) + 1, PosAmp - LENGTH(Key) - PosKey - 1); END; END; BEGIN {WorkWithQueryString} WRITELN('Content-type: text/plain'); WRITELN; WRITELN('First Name: ', GetQueryStringParameter('first_name')); WRITELN('Last Name: ', GetQueryStringParameter('last_name')); WRITELN('Age: ', GetQueryStringParameter('age')) END. {WorkWithQueryString} >>>>>>> 76163f8c603274cb8cd183299e47581ba7d33420
unit uFrAutor; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uFrPadrao, Data.DB, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uAutorController; type TfrAutor = class(TfrPadrao) edtCodigo: TLabeledEdit; edtNome: TLabeledEdit; procedure btnGravarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnIncluirClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnPesquisarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure dbgPadraoDblClick(Sender: TObject); private FAutorController: TAutorController; procedure LimpaCampos(); procedure IncluirRegistro(); function GravarRegistro(): Boolean; function ExcluirRegistro(): Boolean; procedure PesquisarAutor(); function ValidaCampos(): Boolean; procedure EditarRegistro(); public end; var frAutor: TfrAutor; implementation uses uAutorModel; {$R *.dfm} procedure TfrAutor.btnCancelarClick(Sender: TObject); begin inherited; LimpaCampos(); end; procedure TfrAutor.btnExcluirClick(Sender: TObject); begin inherited; ExcluirRegistro(); PesquisarAutor(); end; procedure TfrAutor.btnGravarClick(Sender: TObject); begin inherited; GravarRegistro(); end; procedure TfrAutor.btnIncluirClick(Sender: TObject); begin inherited; IncluirRegistro(); end; procedure TfrAutor.btnPesquisarClick(Sender: TObject); begin PesquisarAutor(); end; procedure TfrAutor.dbgPadraoDblClick(Sender: TObject); begin inherited; EditarRegistro(); end; procedure TfrAutor.EditarRegistro; begin if not (qryPadrao.FieldByName('codigo').AsInteger > 0) then Exit; edtCodigo.Text := qryPadrao.FieldByName('codigo').AsString; edtNome.Text := qryPadrao.FieldByName('nome').AsString; pgcPadrao.TabIndex := 1; AjustaVisibilidadeBotoes(); end; function TfrAutor.ExcluirRegistro: Boolean; begin FAutorController.frMain := frMain; FAutorController.ExcluirRegistro(qryPadrao.FieldByName('CODIGO').AsInteger); end; procedure TfrAutor.FormCreate(Sender: TObject); begin inherited; FAutorController := TAutorController.Create; end; procedure TfrAutor.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(FAutorController); end; procedure TfrAutor.FormShow(Sender: TObject); begin inherited; PesquisarAutor(); end; function TfrAutor.GravarRegistro: Boolean; var LAutor: TAutorModel; begin if not ValidaCampos() then Exit; LAutor := TAutorModel.Create; try LAutor.Codigo := StrToIntDef(edtCodigo.Text,0); LAutor.Nome := edtNome.Text; FAutorController.frMain := frMain; if FAutorController.GravarRegistro(LAutor) then begin LimpaCampos(); ShowMessage('Registro incluído com sucesso.'); end; finally FreeAndNil(LAutor); end; end; procedure TfrAutor.IncluirRegistro; begin LimpaCampos(); end; procedure TfrAutor.LimpaCampos; begin edtCodigo.Text := ''; edtNome.Text := ''; end; procedure TfrAutor.PesquisarAutor; var LSQL: String; LPesquisaComFiltro: Boolean; begin LSQL := 'SELECT * FROM AUTOR '; LPesquisaComFiltro := Trim(edtPesquisar.Text) <> ''; if LPesquisaComFiltro then LSQL := LSQL + 'WHERE UPPER(NOME) LIKE UPPER(:nome)'; if qryPadrao.Active then qryPadrao.Close; qryPadrao.SQL.Text := LSQL; if LPesquisaComFiltro then qryPadrao.ParamByName('nome').AsString := '%' + edtPesquisar.Text + '%'; qryPadrao.Open; end; function TfrAutor.ValidaCampos: Boolean; var LCamposPreechidos: Boolean; begin LCamposPreechidos := Trim(edtNome.Text) <> ''; if not LCamposPreechidos then ShowMessage('Preencha o campo nome'); Result := LCamposPreechidos; end; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: HDRLightingUnit.pas,v 1.15 2007/02/05 22:21:08 clootie Exp $ *----------------------------------------------------------------------------*) //----------------------------------------------------------------------------- // File: HDRLighting.cpp // // Desc: This sample demonstrates some high dynamic range lighting effects // using floating point textures. // // The algorithms described in this sample are based very closely on the // lighting effects implemented in Masaki Kawase's Rthdribl sample and the tone // mapping process described in the whitepaper "Tone Reproduction for Digital // Images" // // Real-Time High Dynamic Range Image-Based Lighting (Rthdribl) // Masaki Kawase // http://www.daionet.gr.jp/~masa/rthdribl/ // // "Photographic Tone Reproduction for Digital Images" // Erik Reinhard, Mike Stark, Peter Shirley and Jim Ferwerda // http://www.cs.utah.edu/~reinhard/cdrom/ // // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- {$I DirectX.inc} unit HDRLightingUnit; interface uses Windows, DXTypes, Direct3D9, D3DX9, DXUT, DXUTcore, DXUTmisc, DXUTenum, DXUTgui, DXUTSettingsDlg, SysUtils, Math, StrSafe, GlareDefD3D; {.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders {.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders const MAX_SAMPLES = 16; // Maximum number of texture grabs NUM_LIGHTS = 2; // Number of lights in the scene EMISSIVE_COEFFICIENT = 39.78; // Emissive color multiplier for each lumen // of light intensity NUM_TONEMAP_TEXTURES = 4; // Number of stages in the 4x4 down-scaling // of average luminance textures NUM_STAR_TEXTURES = 12; // Number of textures used for the star // post-processing effect NUM_BLOOM_TEXTURES = 3; // Number of textures used for the bloom // post-processing effect type // Texture coordinate rectangle PCoordRect = ^TCoordRect; TCoordRect = record fLeftU, fTopV: Single; fRightU, fBottomV: Single; end; // World vertex format PWorldVertex = ^TWorldVertex; TWorldVertex = packed record p: TD3DXVector3; // position n: TD3DXVector3; // normal t: TD3DXVector2; // texture coordinate // static const DWORD FVF; end; const TWorldVertex_FVF = D3DFVF_XYZ or D3DFVF_NORMAL or D3DFVF_TEX1; type // Screen quad vertex format PScreenVertex = ^TScreenVertex; TScreenVertex = packed record p: TD3DXVector4; // position t: TD3DXVector2; // texture coordinate // static const DWORD FVF; end; const TScreenVertex_FVF = D3DFVF_XYZRHW or D3DFVF_TEX1; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- var g_pd3dDevice: IDirect3DDevice9; // D3D Device object g_pFont: ID3DXFont; // Font for drawing text g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls g_pEffect: ID3DXEffect; // D3DX effect interface g_Camera: CFirstPersonCamera; // A model viewing camera g_LuminanceFormat: TD3DFormat; // Format to use for luminance map g_bShowHelp: Boolean = True; // If true, it renders the UI control text g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog g_HUD: CDXUTDialog; // dialog for standard controls g_SampleUI: CDXUTDialog; // dialog for sample specific controls g_pFloatMSRT: IDirect3DSurface9; // Multi-Sample float render target g_pFloatMSDS: IDirect3DSurface9; // Depth Stencil surface for the float RT g_pTexScene: IDirect3DTexture9; // HDR render target containing the scene g_pTexSceneScaled: IDirect3DTexture9; // Scaled copy of the HDR scene g_pTexBrightPass: IDirect3DTexture9; // Bright-pass filtered copy of the scene g_pTexAdaptedLuminanceCur: IDirect3DTexture9; // The luminance that the user is currenly adapted to g_pTexAdaptedLuminanceLast: IDirect3DTexture9; // The luminance that the user is currenly adapted to g_pTexStarSource: IDirect3DTexture9; // Star effect source texture g_pTexBloomSource: IDirect3DTexture9; // Bloom effect source texture g_pTexWall: IDirect3DTexture9; // Stone texture for the room walls g_pTexFloor: IDirect3DTexture9; // Concrete texture for the room floor g_pTexCeiling: IDirect3DTexture9; // Plaster texture for the room ceiling g_pTexPainting: IDirect3DTexture9; // Texture for the paintings on the wall g_apTexBloom: array[0..NUM_BLOOM_TEXTURES-1] of IDirect3DTexture9; // Blooming effect working textures g_apTexStar: array[0..NUM_STAR_TEXTURES-1] of IDirect3DTexture9; // Star effect working textures g_apTexToneMap: array[0..NUM_TONEMAP_TEXTURES-1] of IDirect3DTexture9; // Log average luminance samples // from the HDR render target g_pWorldMesh: ID3DXMesh; // Mesh to contain world objects g_pmeshSphere: ID3DXMesh; // Representation of point light g_GlareDef: CGlareDef; // Glare defintion g_eGlareType: TEGlareLibType; // Enumerated glare type g_avLightPosition: array[0..NUM_LIGHTS-1] of TD3DXVector4; // Light positions in world space g_avLightIntensity: array[0..NUM_LIGHTS-1] of TD3DXVector4; // Light floating point intensities g_nLightLogIntensity: array[0..NUM_LIGHTS-1] of Integer; // Light intensities on a log scale g_nLightMantissa: array[0..NUM_LIGHTS-1] of Integer; // Mantissa of the light intensity g_dwCropWidth: DWORD; // Width of the cropped scene texture g_dwCropHeight: DWORD; // Height of the cropped scene texture g_fKeyValue: Single; // Middle gray key value for tone mapping g_bToneMap: Boolean; // True when scene is to be tone mapped g_bDetailedStats: Boolean; // True when state variables should be rendered g_bDrawHelp: Boolean; // True when help instructions are to be drawn g_bBlueShift: Boolean; // True when blue shift is to be factored in g_bAdaptationInvalid: Boolean; // True when adaptation level needs refreshing g_bUseMultiSampleFloat16: Boolean = False; // True when using multisampling on a floating point back buffer g_MaxMultiSampleType: TD3DMultiSampleType = D3DMULTISAMPLE_NONE; // Non-Zero when g_bUseMultiSampleFloat16 is true g_dwMultiSampleQuality: DWORD = 0; // Non-Zero when we have multisampling on a float backbuffer g_bSupportsD16: bool = False; g_bSupportsD32: bool = False; g_bSupportsD24X8: bool = False; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- const IDC_STATIC = -1; IDC_TOGGLEFULLSCREEN = 1; IDC_TOGGLEREF = 3; IDC_CHANGEDEVICE = 4; IDC_GLARETYPE = 5; IDC_LIGHT0_LABEL = 6; IDC_LIGHT1_LABEL = 7; IDC_LIGHT0 = 8; IDC_LIGHT1 = 9; IDC_KEYVALUE = 10; IDC_KEYVALUE_LABEL = 11; IDC_TONEMAP = 12; IDC_BLUESHIFT = 13; IDC_RESET = 14; //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; procedure OnLostDevice(pUserContext: Pointer); stdcall; procedure OnDestroyDevice(pUserContext: Pointer); stdcall; procedure InitApp; function LoadMesh(const pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; procedure RenderText; // Scene geometry initialization routines procedure SetTextureCoords(pVertex: PWorldVertex; u, v: Single); function BuildWorldMesh: HRESULT; function BuildColumn(var pV: PWorldVertex; x, y, z: Single; width: Single): HRESULT; // Post-processing source textures creation function Scene_To_SceneScaled: HRESULT; function SceneScaled_To_BrightPass: HRESULT; function BrightPass_To_StarSource: HRESULT; function StarSource_To_BloomSource: HRESULT; // Post-processing helper functions function GetTextureRect(const pTexture: IDirect3DTexture9; out pRect: TRect): HRESULT; function GetTextureCoords(const pTexSrc: IDirect3DTexture9; pRectSrc: PRect; pTexDest: IDirect3DTexture9; pRectDest: PRect; var pCoords: TCoordRect): HRESULT; // Sample offset calculation. These offsets are passed to corresponding // pixel shaders. function GetSampleOffsets_GaussBlur5x5(dwD3DTexWidth, dwD3DTexHeight: DWORD; var avTexCoordOffset: array of TD3DXVector2; var avSampleWeight: array of TD3DXVector4; fMultiplier: Single = 1.0): HRESULT; function GetSampleOffsets_Bloom(dwD3DTexSize: DWORD; var afTexCoordOffset: array of Single; var avColorWeight: array of TD3DXVector4; fDeviation: Single; fMultiplier: Single = 1.0): HRESULT; function GetSampleOffsets_Star(dwD3DTexSize: DWORD; var afTexCoordOffset: array {[15]} of Single; var avColorWeight: array of TD3DXVector4; fDeviation: Single): HRESULT; function GetSampleOffsets_DownScale4x4(dwWidth, dwHeight: DWORD; var avSampleOffsets: array of TD3DXVector2): HRESULT; function GetSampleOffsets_DownScale2x2(dwWidth, dwHeight: DWORD; var avSampleOffsets: array of TD3DXVector2): HRESULT; // Tone mapping and post-process lighting effects function MeasureLuminance: HRESULT; function CalculateAdaptation: HRESULT; function RenderStar: HRESULT; function RenderBloom: HRESULT; // Methods to control scene lights function AdjustLight(iLight: LongWord; bIncrement: Boolean): HRESULT; function RefreshLights: HRESULT; function RenderScene: HRESULT; function ClearTexture(pTexture: IDirect3DTexture9): HRESULT; procedure ResetOptions; procedure DrawFullScreenQuad(fLeftU, fTopV, fRightU, fBottomV: Single); overload; procedure DrawFullScreenQuad(const c: TCoordRect); overload; { DrawFullScreenQuad( c.fLeftU, c.fTopV, c.fRightU, c.fBottomV ); } procedure CreateCustomDXUTobjects; procedure DestroyCustomDXUTobjects; implementation function GaussianDistribution(x, y, rho: Single): Single; forward;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF} //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- procedure InitApp; var iY: Integer; pElement: CDXUTElement; pComboBox: CDXUTComboBox; begin // Although multisampling is supported for render target surfaces, those surfaces // exist without a parent texture, and must therefore be copied to a texture // surface if they're to be used as a source texture. This sample relies upon // several render targets being used as source textures, and therefore it makes // sense to disable multisampling altogether. { CGrowableArray<D3DMULTISAMPLE_TYPE>* pMultiSampleTypeList = DXUTGetEnumeration()->GetPossibleMultisampleTypeList(); pMultiSampleTypeList->RemoveAll(); pMultiSampleTypeList->Add( D3DMULTISAMPLE_NONE ); DXUTGetEnumeration()->SetMultisampleQualityMax( 0 ); } // Initialize dialogs g_SettingsDlg.Init(g_DialogResourceManager); g_HUD.Init(g_DialogResourceManager); g_SampleUI.Init(g_DialogResourceManager); g_HUD.SetCallback(OnGUIEvent); iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2); Inc(iY, 24); g_HUD.AddButton(IDC_RESET, 'Reset Options (R)', 35, iY, 125, 22, Ord('R')); // Title font for comboboxes g_SampleUI.SetFont(1, 'Arial', 14, FW_BOLD); pElement := g_SampleUI.GetDefaultElement(DXUT_CONTROL_STATIC, 0); if Assigned(pElement) then begin pElement.iFont := 1; pElement.dwTextFormat := DT_LEFT or DT_BOTTOM; end; pComboBox := nil; g_SampleUI.SetCallback(OnGUIEvent); iY := 10; Inc(iY, 24); g_SampleUI.AddStatic(IDC_STATIC, '(G)lare Type', 35, iY, 125, 22); Inc(iY, 24); g_SampleUI.AddComboBox(IDC_GLARETYPE, 35, iY, 125, 22, Ord('G'), False, @pComboBox); Inc(iY, 24); g_SampleUI.AddStatic(IDC_LIGHT0_LABEL, 'Light 0', 35, iY, 125, 22); Inc(iY, 24); g_SampleUI.AddSlider(IDC_LIGHT0, 35, iY, 100, 22, 0, 63); Inc(iY, 24); g_SampleUI.AddStatic(IDC_LIGHT1_LABEL, 'Light 1', 35, iY, 125, 22); Inc(iY, 24); g_SampleUI.AddSlider(IDC_LIGHT1, 35, iY, 100, 22, 0, 63); Inc(iY, 24); g_SampleUI.AddStatic(IDC_KEYVALUE_LABEL, 'Key Value', 35, iY, 125, 22); Inc(iY, 24); g_SampleUI.AddSlider(IDC_KEYVALUE, 35, iY, 100, 22, 0, 100); Inc(iY, 34); g_SampleUI.AddCheckBox(IDC_TONEMAP, '(T)one Mapping', 35, iY, 125, 20, True, Ord('T')); Inc(iY, 24); g_SampleUI.AddCheckBox(IDC_BLUESHIFT, '(B)lue Shift', 35, iY, 125, 20, True, Ord('B')); if Assigned(pComboBox) then begin pComboBox.AddItem('Disable', Pointer(GLT_DISABLE)); pComboBox.AddItem('Camera', Pointer(GLT_CAMERA)); pComboBox.AddItem('Natural Bloom', Pointer(GLT_NATURAL)); pComboBox.AddItem('Cheap Lens', Pointer(GLT_CHEAPLENS)); pComboBox.AddItem('Cross Screen', Pointer(GLT_FILTER_CROSSSCREEN)); pComboBox.AddItem('Spectral Cross', Pointer(GLT_FILTER_CROSSSCREEN_SPECTRAL)); pComboBox.AddItem('Snow Cross', Pointer(GLT_FILTER_SNOWCROSS)); pComboBox.AddItem('Spectral Snow', Pointer(GLT_FILTER_SNOWCROSS_SPECTRAL)); pComboBox.AddItem('Sunny Cross', Pointer(GLT_FILTER_SUNNYCROSS)); pComboBox.AddItem('Spectral Sunny', Pointer(GLT_FILTER_SUNNYCROSS_SPECTRAL)); pComboBox.AddItem('Cinema Vertical', Pointer(GLT_CINECAM_VERTICALSLITS)); pComboBox.AddItem('Cinema Horizontal', Pointer(GLT_CINECAM_HORIZONTALSLITS)); end; (* g_SampleUI.AddComboBox( 19, 35, iY += 24, 125, 22 ); g_SampleUI.GetComboBox( 19 )->AddItem( L"Text1", NULL ); g_SampleUI.GetComboBox( 19 )->AddItem( L"Text2", NULL ); g_SampleUI.GetComboBox( 19 )->AddItem( L"Text3", NULL ); g_SampleUI.GetComboBox( 19 )->AddItem( L"Text4", NULL ); g_SampleUI.AddCheckBox( 21, L"Checkbox1", 35, iY += 24, 125, 22 ); g_SampleUI.AddCheckBox( 11, L"Checkbox2", 35, iY += 24, 125, 22 ); g_SampleUI.AddRadioButton( 12, 1, L"Radio1G1", 35, iY += 24, 125, 22 ); g_SampleUI.AddRadioButton( 13, 1, L"Radio2G1", 35, iY += 24, 125, 22 ); g_SampleUI.AddRadioButton( 14, 1, L"Radio3G1", 35, iY += 24, 125, 22 ); g_SampleUI.GetRadioButton( 14 )->SetChecked( true ); g_SampleUI.AddButton( 17, L"Button1", 35, iY += 24, 125, 22 ); g_SampleUI.AddButton( 18, L"Button2", 35, iY += 24, 125, 22 ); g_SampleUI.AddRadioButton( 15, 2, L"Radio1G2", 35, iY += 24, 125, 22 ); g_SampleUI.AddRadioButton( 16, 2, L"Radio2G3", 35, iY += 24, 125, 22 ); g_SampleUI.GetRadioButton( 16 )->SetChecked( true ); g_SampleUI.AddSlider( 20, 50, iY += 24, 100, 22 ); g_SampleUI.GetSlider( 20 )->SetRange( 0, 100 ); g_SampleUI.GetSlider( 20 )->SetValue( 50 ); // g_SampleUI.AddEditBox( 20, L"Test", 35, iY += 24, 125, 22 ); *) // Set light positions in world space g_avLightPosition[0] := D3DXVector4(4.0, 2.0, 18.0, 1.0); g_avLightPosition[1] := D3DXVector4(11.0, 2.0, 18.0, 1.0); ResetOptions; end; //----------------------------------------------------------------------------- // Name: ResetOptions() // Desc: Reset all user-controlled options to default values //----------------------------------------------------------------------------- procedure ResetOptions; begin g_bDrawHelp := True; g_bDetailedStats := True; g_SampleUI.EnableNonUserEvents(True); g_SampleUI.GetCheckBox(IDC_TONEMAP).Checked := True; g_SampleUI.GetCheckBox(IDC_BLUESHIFT).Checked := True; g_SampleUI.GetSlider(IDC_LIGHT0).Value := 52; g_SampleUI.GetSlider(IDC_LIGHT1).Value := 43; g_SampleUI.GetSlider(IDC_KEYVALUE).Value := 18; g_SampleUI.GetComboBox(IDC_GLARETYPE).SetSelectedByData(Pointer(GLT_DEFAULT)); g_SampleUI.EnableNonUserEvents(False); end; //----------------------------------------------------------------------------- // Name: AdjustLight // Desc: Increment or decrement the light at the given index //----------------------------------------------------------------------------- function AdjustLight(iLight: LongWord; bIncrement: Boolean): HRESULT; begin if (iLight >= NUM_LIGHTS) then begin Result:= E_INVALIDARG; Exit; end; if bIncrement and (g_nLightLogIntensity[iLight] < 7) then begin Inc(g_nLightMantissa[iLight]); if (g_nLightMantissa[iLight] > 9) then begin g_nLightMantissa[iLight] := 1; Inc(g_nLightLogIntensity[iLight]); end; end; if not bIncrement and (g_nLightLogIntensity[iLight] > -4) then begin Dec(g_nLightMantissa[iLight]); if (g_nLightMantissa[iLight] < 1) then begin g_nLightMantissa[iLight] := 9; Dec(g_nLightLogIntensity[iLight]); end; end; RefreshLights; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: RefreshLights // Desc: Set the light intensities to match the current log luminance //----------------------------------------------------------------------------- function RefreshLights: HRESULT; var pStatic: CDXUTStatic; strBuffer: WideString; i: Integer; begin strBuffer := ''; for i := 0 to NUM_LIGHTS - 1 do begin g_avLightIntensity[i].x := g_nLightMantissa[i] * Power(10.0, g_nLightLogIntensity[i]); g_avLightIntensity[i].y := g_nLightMantissa[i] * Power(10.0, g_nLightLogIntensity[i]); g_avLightIntensity[i].z := g_nLightMantissa[i] * Power(10.0, g_nLightLogIntensity[i]); g_avLightIntensity[i].w := 1.0; strBuffer := WideFormat('Light %d: %d.0e%d', [i, g_nLightMantissa[i], g_nLightLogIntensity[i]]); pStatic := g_SampleUI.GetStatic(IDC_LIGHT0_LABEL + i); pStatic.Text := PWideChar(strBuffer); end; Result:= S_OK; end; //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by returning false. //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; var pD3D: IDirect3D9; begin Result:= False; // Skip backbuffer formats that don't support alpha blending pD3D := DXUTGetD3DObject; if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat)) then Exit; if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit; // No fallback yet, so need to support D3DFMT_A16B16G16R16F render target if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET or D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) then Exit; // No fallback yet, so need to support D3DFMT_R32F or D3DFMT_R16F render target if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_R32F)) then begin if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_R16F)) then Exit; end; // Need to support post-pixel processing if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET or D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_SURFACE, BackBufferFormat)) then Exit; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function is called immediately before a device is created to allow the // application to modify the device settings. The supplied pDeviceSettings parameter // contains the settings that the framework has selected for the new device, and the // application can make any desired changes directly to this structure. Note however that // DXUT will not correct invalid device settings so care must be taken // to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. //-------------------------------------------------------------------------------------- {static} var s_bFirstTime: Boolean = True; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; begin // If device doesn't support HW T&L or doesn't support 2.0 vertex shaders in HW // then switch to SWVP. if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or (pCaps.VertexShaderVersion < D3DVS_VERSION(2,0)) then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING; // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. {$IFDEF DEBUG_VS} if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then with pDeviceSettings do begin BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING; BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE; BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING; end; {$ENDIF} {$IFDEF DEBUG_PS} pDeviceSettings.DeviceType := D3DDEVTYPE_REF; {$ENDIF} // For the first device created if its a REF device, optionally display a warning dialog box if s_bFirstTime then begin s_bFirstTime := False; if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning; end; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnDestroyDevice callback. //-------------------------------------------------------------------------------------- function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var Caps: TD3DCaps9; pD3D: IDirect3D9; DisplayMode: TD3DDisplayMode; dwShaderFlags: DWORD; str: array[0..MAX_PATH-1] of WideChar; vFromPt: TD3DXVector3; vLookatPt: TD3DXVector3; vMin: TD3DXVector3; vMax: TD3DXVector3; settings: TDXUTDeviceSettings; imst: TD3DMultiSampleType; msQuality: DWORD; begin Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; // Determine which of D3DFMT_R16F or D3DFMT_R32F to use for luminance texture pD3D := DXUTGetD3DObject; if not Assigned(pD3D) then begin Result:= E_FAIL; Exit; end; pd3dDevice.GetDeviceCaps(Caps); pd3dDevice.GetDisplayMode(0, DisplayMode); // IsDeviceAcceptable already ensured that one of D3DFMT_R16F or D3DFMT_R32F is available. if FAILED(pD3D.CheckDeviceFormat(Caps.AdapterOrdinal, Caps.DeviceType, DisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_R16F)) then g_LuminanceFormat := D3DFMT_R32F else g_LuminanceFormat := D3DFMT_R16F; // Determine whether we can support multisampling on a A16B16G16R16F render target g_bUseMultiSampleFloat16 := False; g_MaxMultiSampleType := D3DMULTISAMPLE_NONE; settings := DXUTGetDeviceSettings; for imst := D3DMULTISAMPLE_2_SAMPLES to D3DMULTISAMPLE_16_SAMPLES do begin msQuality := 0; if SUCCEEDED(pD3D.CheckDeviceMultiSampleType(Caps.AdapterOrdinal, Caps.DeviceType, D3DFMT_A16B16G16R16F, settings.pp.Windowed, imst, @msQuality)) then begin g_bUseMultiSampleFloat16 := True; g_MaxMultiSampleType := imst; if (msQuality > 0) then g_dwMultiSampleQuality := msQuality-1 else g_dwMultiSampleQuality := msQuality; end; end; g_bSupportsD16 := False; if SUCCEEDED(pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D16)) then begin if SUCCEEDED(pD3D.CheckDepthStencilMatch(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DFMT_A16B16G16R16F, D3DFMT_D16)) then g_bSupportsD16 := True; end; g_bSupportsD32 := False; if SUCCEEDED(pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D32)) then begin if SUCCEEDED(pD3D.CheckDepthStencilMatch(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DFMT_A16B16G16R16F, D3DFMT_D32)) then g_bSupportsD32 := True; end; g_bSupportsD24X8 := False; if SUCCEEDED(pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D24X8)) then begin if SUCCEEDED(pD3D.CheckDepthStencilMatch(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DFMT_A16B16G16R16F, D3DFMT_D24X8)) then g_bSupportsD24X8 := True; end; // Initialize the font Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, 'Arial', g_pFont); if V_Failed(Result) then Exit; // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. dwShaderFlags := D3DXFX_NOT_CLONEABLE; {$IFDEF DEBUG} // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_VS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; {$ENDIF} {$IFDEF DEBUG_PS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; {$ENDIF} // Read the D3DX effect file Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'HDRLighting.fx'); if V_Failed(Result) then Exit; // If this fails, there should be debug output as to // they the .fx file failed to compile Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags, nil, g_pEffect, nil); if V_Failed(Result) then Exit; // Initialize the camera vFromPt := D3DXVector3(7.5, 1.8, 2); vLookatPt := D3DXVector3(7.5, 1.5, 10.0); g_Camera.SetViewParams(vFromPt, vLookatPt); // Set options for the first-person camera g_Camera.SetScalers(0.01, 15.0); g_Camera.SetDrag(True); g_Camera.SetEnableYAxisMovement(False); vMin := D3DXVector3(1.5,0.0,1.5); vMax := D3DXVector3(13.5,10.0,18.5); g_Camera.SetClipToBoundary(True, vMin, vMax); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This function loads the mesh and ensures the mesh has normals; it also optimizes the // mesh for the graphics card's vertex cache, which improves performance by organizing // the internal triangle list for less cache misses. //-------------------------------------------------------------------------------------- function LoadMesh(const pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; var pMesh: ID3DXMesh; str: array[0..MAX_PATH-1] of WideChar; rgdwAdjacency: PDWORD; pTempMesh: ID3DXMesh; begin // Load the mesh with D3DX and get back a ID3DXMesh*. For this // sample we'll ignore the X file's embedded materials since we know // exactly the model we're loading. See the mesh samples such as // "OptimizedMesh" for a more generic mesh loading example. Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, strFileName); if V_Failed(Result) then Exit; Result := D3DXLoadMeshFromXW(str, D3DXMESH_MANAGED, pd3dDevice, nil, nil, nil, nil, pMesh); if V_Failed(Result) then Exit; // rgdwAdjacency := nil; // Make sure there are normals which are required for lighting if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then begin V(pMesh.CloneMeshFVF(pMesh.GetOptions, pMesh.GetFVF or D3DFVF_NORMAL, pd3dDevice, pTempMesh)); V(D3DXComputeNormals(pTempMesh, nil)); SAFE_RELEASE(pMesh); pMesh := pTempMesh; end; // Optimize the mesh for this graphics card's vertex cache // so when rendering the mesh's triangle list the vertices will // cache hit more often so it won't have to re-execute the vertex shader // on those vertices so it will improve perf. 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; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // reset, which will happen after a lost device scenario. This is the best location to // create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever // the device is lost. Resources created here should be released in the OnLostDevice // callback. //-------------------------------------------------------------------------------------- function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var i: Integer; pBackBufferDesc: PD3DSurfaceDesc; fAspectRatio: Single; iSampleLen: Integer; Path: array[0..MAX_PATH-1] of WideChar; mProjection: TD3DXMatrix; dfmt: TD3DFormat; begin Result:= g_DialogResourceManager.OnResetDevice; if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnResetDevice; if V_Failed(Result) then Exit; g_pd3dDevice := pd3dDevice; if (g_pFont <> nil) then begin Result:= g_pFont.OnResetDevice; if V_Failed(Result) then Exit; end; if (g_pEffect <> nil) then begin Result:= g_pEffect.OnResetDevice; if V_Failed(Result) then Exit; end; // Create a sprite to help batch calls when drawing many lines of text Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite); if V_Failed(Result) then Exit; pBackBufferDesc := DXUTGetBackBufferSurfaceDesc; // Create the Multi-Sample floating point render target dfmt := D3DFMT_UNKNOWN; if g_bSupportsD16 then dfmt := D3DFMT_D16 else if g_bSupportsD32 then dfmt := D3DFMT_D32 else if g_bSupportsD24X8 then dfmt := D3DFMT_D24X8 else g_bUseMultiSampleFloat16 := False; if g_bUseMultiSampleFloat16 then begin Result := g_pd3dDevice.CreateRenderTarget(pBackBufferDesc.Width, pBackBufferDesc.Height, D3DFMT_A16B16G16R16F, g_MaxMultiSampleType, g_dwMultiSampleQuality, False, g_pFloatMSRT, nil); if FAILED(Result) then g_bUseMultiSampleFloat16 := False else begin Result := g_pd3dDevice.CreateDepthStencilSurface(pBackBufferDesc.Width, pBackBufferDesc.Height, dfmt, g_MaxMultiSampleType, g_dwMultiSampleQuality, True, g_pFloatMSDS, nil); if FAILED(Result) then begin g_bUseMultiSampleFloat16 := False; SAFE_RELEASE(g_pFloatMSRT); end; end; end; // Crop the scene texture so width and height are evenly divisible by 8. // This cropped version of the scene will be used for post processing effects, // and keeping everything evenly divisible allows precise control over // sampling points within the shaders. g_dwCropWidth := pBackBufferDesc.Width - pBackBufferDesc.Width mod 8; g_dwCropHeight := pBackBufferDesc.Height - pBackBufferDesc.Height mod 8; // Create the HDR scene texture Result := g_pd3dDevice.CreateTexture(pBackBufferDesc.Width, pBackBufferDesc.Height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A16B16G16R16F, D3DPOOL_DEFAULT, g_pTexScene, nil); if FAILED(Result) then Exit; // Scaled version of the HDR scene texture Result := g_pd3dDevice.CreateTexture(g_dwCropWidth div 4, g_dwCropHeight div 4, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A16B16G16R16F, D3DPOOL_DEFAULT, g_pTexSceneScaled, nil); if FAILED(Result) then Exit; // Create the bright-pass filter texture. // Texture has a black border of single texel thickness to fake border // addressing using clamp addressing Result := g_pd3dDevice.CreateTexture(g_dwCropWidth div 4 + 2, g_dwCropHeight div 4 + 2, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_pTexBrightPass, nil); if FAILED(Result) then Exit; // Create a texture to be used as the source for the star effect // Texture has a black border of single texel thickness to fake border // addressing using clamp addressing Result := g_pd3dDevice.CreateTexture(g_dwCropWidth div 4 + 2, g_dwCropHeight div 4 + 2, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_pTexStarSource, nil); if FAILED(Result) then Exit; // Create a texture to be used as the source for the bloom effect // Texture has a black border of single texel thickness to fake border // addressing using clamp addressing Result := g_pd3dDevice.CreateTexture(g_dwCropWidth div 8 + 2, g_dwCropHeight div 8 + 2, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_pTexBloomSource, nil); if FAILED(Result) then Exit; // Create a 2 textures to hold the luminance that the user is currently adapted // to. This allows for a simple simulation of light adaptation. Result := g_pd3dDevice.CreateTexture(1, 1, 1, D3DUSAGE_RENDERTARGET, g_LuminanceFormat, D3DPOOL_DEFAULT, g_pTexAdaptedLuminanceCur, nil); if FAILED(Result) then Exit; Result := g_pd3dDevice.CreateTexture(1, 1, 1, D3DUSAGE_RENDERTARGET, g_LuminanceFormat, D3DPOOL_DEFAULT, g_pTexAdaptedLuminanceLast, nil); if FAILED(Result) then Exit; // For each scale stage, create a texture to hold the intermediate results // of the luminance calculation for i:= 0 to NUM_TONEMAP_TEXTURES - 1 do begin iSampleLen := 1 shl (2*i); Result := g_pd3dDevice.CreateTexture(iSampleLen, iSampleLen, 1, D3DUSAGE_RENDERTARGET, g_LuminanceFormat, D3DPOOL_DEFAULT, g_apTexToneMap[i], nil); if FAILED(Result) then Exit; end; // Create the temporary blooming effect textures // Texture has a black border of single texel thickness to fake border // addressing using clamp addressing for i := 1 to NUM_BLOOM_TEXTURES - 1 do begin Result := g_pd3dDevice.CreateTexture(g_dwCropWidth div 8 + 2, g_dwCropHeight div 8 + 2, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_apTexBloom[i], nil); if FAILED(Result) then Exit; end; // Create the final blooming effect texture Result := g_pd3dDevice.CreateTexture(g_dwCropWidth div 8, g_dwCropHeight div 8, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_apTexBloom[0], nil); if FAILED(Result) then Exit; // Create the star effect textures for i := 0 to NUM_STAR_TEXTURES-1 do begin Result := g_pd3dDevice.CreateTexture(g_dwCropWidth div 4, g_dwCropHeight div 4, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A16B16G16R16F, D3DPOOL_DEFAULT, g_apTexStar[i], nil); if FAILED(Result) then Exit; end; // Create a texture to paint the walls DXUTFindDXSDKMediaFile(Path, MAX_PATH, 'misc\env2.bmp'); Result := D3DXCreateTextureFromFileW(g_pd3dDevice, Path, g_pTexWall); if FAILED(Result) then Exit; // Create a texture to paint the floor DXUTFindDXSDKMediaFile(Path, MAX_PATH, 'misc\ground2.bmp'); Result := D3DXCreateTextureFromFileW(g_pd3dDevice, Path, g_pTexFloor); if FAILED(Result) then Exit; // Create a texture to paint the ceiling DXUTFindDXSDKMediaFile(Path, MAX_PATH, 'misc\seafloor.bmp'); Result := D3DXCreateTextureFromFileW(g_pd3dDevice, Path, g_pTexCeiling); if FAILED(Result) then Exit; // Create a texture for the paintings DXUTFindDXSDKMediaFile(Path, MAX_PATH, 'misc\env3.bmp'); Result := D3DXCreateTextureFromFileW(g_pd3dDevice, Path, g_pTexPainting); if FAILED(Result) then Exit; // Textures with borders must be cleared since scissor rect testing will // be used to avoid rendering on top of the border ClearTexture(g_pTexAdaptedLuminanceCur); ClearTexture(g_pTexAdaptedLuminanceLast); ClearTexture(g_pTexBloomSource); ClearTexture(g_pTexBrightPass); ClearTexture(g_pTexStarSource); for i:= 0 to NUM_BLOOM_TEXTURES - 1 do ClearTexture(g_apTexBloom[i]); // Build the world object Result := BuildWorldMesh; if FAILED(Result) then Exit; // Create sphere mesh to represent the light Result := LoadMesh(g_pd3dDevice, 'misc\sphere0.x', g_pmeshSphere); if FAILED(Result) then Exit; // Setup the camera's projection parameters fAspectRatio := g_dwCropWidth / g_dwCropHeight; g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.2, 30.0); mProjection := g_Camera.GetProjMatrix^; // Set effect file variables g_pEffect.SetMatrix('g_mProjection', mProjection); g_pEffect.SetFloat('g_fBloomScale', 1.0); g_pEffect.SetFloat('g_fStarScale', 0.5); g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0); g_HUD.SetSize(170, 170); g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-350); g_SampleUI.SetSize(170, 300); Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: ClearTexture() // Desc: Helper function for RestoreDeviceObjects to clear a texture surface //----------------------------------------------------------------------------- function ClearTexture(pTexture: IDirect3DTexture9): HRESULT; var pSurface: IDirect3DSurface9; begin Result := pTexture.GetSurfaceLevel(0, pSurface); if SUCCEEDED(Result) then g_pd3dDevice.ColorFill(pSurface, nil, D3DCOLOR_ARGB(0, 0, 0, 0)); SAFE_RELEASE(pSurface); end; //----------------------------------------------------------------------------- // Name: BuildWorldMesh() // Desc: Creates the wall, floor, ceiling, columns, and painting mesh //----------------------------------------------------------------------------- function BuildWorldMesh: HRESULT; const fWidth = 15.0; fDepth = 20.0; fHeight = 3.0; var i: LongWord; // Loop variable pWorldMeshTemp: ID3DXMesh; pVertex: PWorldVertex; pV: PWorldVertex; pIndex: PWord; pAttribs: PDWORD; begin // Create the room Result := D3DXCreateMeshFVF(48, 96, 0, TWorldVertex_FVF, g_pd3dDevice, pWorldMeshTemp); if FAILED(Result) then Exit; Result := pWorldMeshTemp.LockVertexBuffer(0, Pointer(pVertex)); if FAILED(Result) then Exit; pV := pVertex; // Front wall SetTextureCoords(pV, 7.0, 2.0); pV.p := D3DXVector3(0.0, fHeight, fDepth); Inc(pV); pV.p := D3DXVector3(fWidth, fHeight, fDepth); Inc(pV); pV.p := D3DXVector3(fWidth, 0.0, fDepth); Inc(pV); pV.p := D3DXVector3(0.0, 0.0, fDepth); Inc(pV); // Right wall SetTextureCoords(pV, 10.5, 2.0); pV.p := D3DXVector3(fWidth, fHeight, fDepth); Inc(pV); pV.p := D3DXVector3(fWidth, fHeight, 0.0 ); Inc(pV); pV.p := D3DXVector3(fWidth, 0.0, 0.0 ); Inc(pV); pV.p := D3DXVector3(fWidth, 0.0, fDepth); Inc(pV); // Back wall SetTextureCoords(pV, 7.0, 2.0); pV.p := D3DXVector3(fWidth, fHeight, 0.0); Inc(pV); pV.p := D3DXVector3(0.0, fHeight, 0.0); Inc(pV); pV.p := D3DXVector3(0.0, 0.0, 0.0); Inc(pV); pV.p := D3DXVector3(fWidth, 0.0, 0.0); Inc(pV); // Left wall SetTextureCoords(pV, 10.5, 2.0); pV.p := D3DXVector3(0.0, fHeight, 0.0); Inc(pV); pV.p := D3DXVector3(0.0, fHeight, fDepth); Inc(pV); pV.p := D3DXVector3(0.0, 0.0, fDepth); Inc(pV); pV.p := D3DXVector3(0.0, 0.0, 0.0); Inc(pV); BuildColumn(pV, 4.0, fHeight, 7.0, 0.75); BuildColumn(pV, 4.0, fHeight, 13.0, 0.75); BuildColumn(pV, 11.0, fHeight, 7.0, 0.75); BuildColumn(pV, 11.0, fHeight, 13.0, 0.75); // Floor SetTextureCoords(pV, 7.0, 7.0); pV.p := D3DXVector3(0.0, 0.0, fDepth); Inc(pV); pV.p := D3DXVector3(fWidth, 0.0, fDepth); Inc(pV); pV.p := D3DXVector3(fWidth, 0.0, 0.0); Inc(pV); pV.p := D3DXVector3(0.0, 0.0, 0.0); Inc(pV); // Ceiling SetTextureCoords(pV, 7.0, 2.0); pV.p := D3DXVector3(0.0, fHeight, 0.0); Inc(pV); pV.p := D3DXVector3(fWidth, fHeight, 0.0); Inc(pV); pV.p := D3DXVector3(fWidth, fHeight, fDepth); Inc(pV); pV.p := D3DXVector3(0.0, fHeight, fDepth); Inc(pV); // Painting 1 SetTextureCoords(pV, 1.0, 1.0); pV.p := D3DXVector3(2.0, fHeight - 0.5, fDepth - 0.01); Inc(pV); pV.p := D3DXVector3(6.0, fHeight - 0.5, fDepth - 0.01); Inc(pV); pV.p := D3DXVector3(6.0, fHeight - 2.5, fDepth - 0.01); Inc(pV); pV.p := D3DXVector3(2.0, fHeight - 2.5, fDepth - 0.01); Inc(pV); // Painting 2 SetTextureCoords( pV, 1.0, 1.0); pV.p := D3DXVector3( 9.0, fHeight - 0.5, fDepth - 0.01); Inc(pV); pV.p := D3DXVector3(13.0, fHeight - 0.5, fDepth - 0.01); Inc(pV); pV.p := D3DXVector3(13.0, fHeight - 2.5, fDepth - 0.01); Inc(pV); pV.p := D3DXVector3( 9.0, fHeight - 2.5, fDepth - 0.01); // Inc(pV); pWorldMeshTemp.UnlockVertexBuffer; // Retrieve the indices Result := pWorldMeshTemp.LockIndexBuffer(0, Pointer(pIndex)); if FAILED(Result) then Exit; for i := 0 to pWorldMeshTemp.GetNumFaces div 2 - 1 do begin pIndex^ := (i*4) + 0; Inc(pIndex); pIndex^ := (i*4) + 1; Inc(pIndex); pIndex^ := (i*4) + 2; Inc(pIndex); pIndex^ := (i*4) + 0; Inc(pIndex); pIndex^ := (i*4) + 2; Inc(pIndex); pIndex^ := (i*4) + 3; Inc(pIndex); end; pWorldMeshTemp.UnlockIndexBuffer; // Set attribute groups to draw floor, ceiling, walls, and paintings // separately, with different shader constants. These group numbers // will be used during the calls to DrawSubset(). Result := pWorldMeshTemp.LockAttributeBuffer(0, pAttribs); if FAILED(Result) then Exit; for i:= 0 to 40-1 do begin pAttribs^ := 0; Inc(pAttribs); end; for i:= 0 to 1 do begin pAttribs^ := 1; Inc(pAttribs); end; for i:= 0 to 1 do begin pAttribs^ := 2; Inc(pAttribs); end; for i:= 0 to 3 do begin pAttribs^ := 3; Inc(pAttribs); end; pWorldMeshTemp.UnlockAttributeBuffer; D3DXComputeNormals(pWorldMeshTemp, nil); // Optimize the mesh Result := pWorldMeshTemp.CloneMeshFVF(D3DXMESH_VB_WRITEONLY or D3DXMESH_IB_WRITEONLY, TWorldVertex_FVF, g_pd3dDevice, g_pWorldMesh); if FAILED(Result) then Exit; Result := S_OK; //Clootie: Not needed in Delphi {SAFE_RELEASE( pWorldMeshTemp);} end; //----------------------------------------------------------------------------- // Name: BuildColumn() // Desc: Helper function for BuildWorldMesh to add column quads to the scene //----------------------------------------------------------------------------- function BuildColumn(var pV: PWorldVertex; x, y, z: Single; width: Single): HRESULT; var w: Single; begin w := width / 2; SetTextureCoords(pV, 1.0, 2.0); pV.p := D3DXVector3(x - w, y, z - w); Inc(pV); pV.p := D3DXVector3(x + w, y, z - w); Inc(pV); pV.p := D3DXVector3(x + w, 0.0, z - w); Inc(pV); pV.p := D3DXVector3(x - w, 0.0, z - w); Inc(pV); SetTextureCoords(pV, 1.0, 2.0); pV.p := D3DXVector3(x + w, y, z - w); Inc(pV); pV.p := D3DXVector3(x + w, y, z + w); Inc(pV); pV.p := D3DXVector3(x + w, 0.0, z + w); Inc(pV); pV.p := D3DXVector3(x + w, 0.0, z - w); Inc(pV); SetTextureCoords(pV, 1.0, 2.0); pV.p := D3DXVector3(x + w, y, z + w); Inc(pV); pV.p := D3DXVector3(x - w, y, z + w); Inc(pV); pV.p := D3DXVector3(x - w, 0.0, z + w); Inc(pV); pV.p := D3DXVector3(x + w, 0.0, z + w); Inc(pV); SetTextureCoords(pV, 1.0, 2.0); pV.p := D3DXVector3(x - w, y, z + w); Inc(pV); pV.p := D3DXVector3(x - w, y, z - w); Inc(pV); pV.p := D3DXVector3(x - w, 0.0, z - w); Inc(pV); pV.p := D3DXVector3(x - w, 0.0, z + w); Inc(pV); Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: SetTextureCoords() // Desc: Helper function for BuildWorldMesh to set texture coordinates // for vertices //----------------------------------------------------------------------------- procedure SetTextureCoords(pVertex: PWorldVertex; u, v: Single); begin pVertex.t := D3DXVector2(0.0, 0.0); Inc(pVertex); pVertex.t := D3DXVector2(u, 0.0); Inc(pVertex); pVertex.t := D3DXVector2(u, v ); Inc(pVertex); pVertex.t := D3DXVector2(0.0, v ); // Inc(pVertex); end; //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var avLightViewPosition: array[0..NUM_LIGHTS-1] of TD3DXVector4; iLight: Integer; mView: TD3DXMatrix; begin // Update the camera's position based on user input g_Camera.FrameMove(fElapsedTime); // Set the flag to refresh the user's simulated adaption level. // Frame move is not called when the scene is paused or single-stepped. // If the scene is paused, the user's adaptation level needs to remain // unchanged. g_bAdaptationInvalid := True; // Calculate the position of the lights in view space for iLight:=0 to NUM_LIGHTS - 1 do begin mView := g_Camera.GetViewMatrix^; D3DXVec4Transform(avLightViewPosition[iLight], g_avLightPosition[iLight], mView); end; // Set frame shader constants g_pEffect.SetBool('g_bEnableToneMap', g_bToneMap); g_pEffect.SetBool('g_bEnableBlueShift', g_bBlueShift); g_pEffect.SetValue('g_avLightPositionView', @avLightViewPosition, SizeOf(TD3DXVECTOR4) * NUM_LIGHTS); g_pEffect.SetValue('g_avLightIntensity', @g_avLightIntensity, SizeOf(TD3DXVECTOR4) * NUM_LIGHTS); end; //-------------------------------------------------------------------------------------- // This callback function will be called at the end of every frame to perform all the // rendering calls for the scene, and it will also be called if the window needs to be // repainted. After this function has returned, DXUT will call // IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain //-------------------------------------------------------------------------------------- procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var pSurfLDR: IDirect3DSurface9; // Low dynamic range surface for final output pSurfDS: IDirect3DSurface9; // Low dynamic range depth stencil surface pSurfHDR: IDirect3DSurface9; // High dynamic range surface to store // intermediate floating point color values uiPassCount: LongWord; iPass: Integer; begin // If the settings dialog is being shown, then // render it instead of rendering the app's scene if g_SettingsDlg.Active then begin g_SettingsDlg.OnRender(fElapsedTime); Exit; end; // Store the old render target V(g_pd3dDevice.GetRenderTarget(0, pSurfLDR)); V(g_pd3dDevice.GetDepthStencilSurface(pSurfDS)); // Setup HDR render target V(g_pTexScene.GetSurfaceLevel(0, pSurfHDR)); if g_bUseMultiSampleFloat16 then begin V(g_pd3dDevice.SetRenderTarget(0, g_pFloatMSRT)); V(g_pd3dDevice.SetDepthStencilSurface( g_pFloatMSDS)); end else begin V(g_pd3dDevice.SetRenderTarget(0, pSurfHDR)); end; // Clear the viewport V(g_pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0, 0, 0, 0), 1.0, 0)); // Render the scene if SUCCEEDED(pd3dDevice.BeginScene) then begin // Render the HDR Scene DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Scene'); RenderScene; DXUT_EndPerfEvent; // If using floating point multi sampling, stretchrect to the rendertarget if g_bUseMultiSampleFloat16 then begin V(g_pd3dDevice.StretchRect(g_pFloatMSRT, nil, pSurfHDR, nil, D3DTEXF_NONE)); V(g_pd3dDevice.SetRenderTarget(0, pSurfHDR)); V(g_pd3dDevice.SetDepthStencilSurface(pSurfDS)); end; // Create a scaled copy of the scene Scene_To_SceneScaled; // Setup tone mapping technique if g_bToneMap then MeasureLuminance; // If FrameMove has been called, the user's adaptation level has also changed // and should be updated if g_bAdaptationInvalid then begin // Clear the update flag g_bAdaptationInvalid := False; // Calculate the current luminance adaptation level CalculateAdaptation; end; // Now that luminance information has been gathered, the scene can be bright-pass filtered // to remove everything except bright lights and reflections. SceneScaled_To_BrightPass; // Blur the bright-pass filtered image to create the source texture for the star effect BrightPass_To_StarSource; // Scale-down the source texture for the star effect to create the source texture // for the bloom effect StarSource_To_BloomSource; // Render post-process lighting effects begin DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Bloom'); RenderBloom; DXUT_EndPerfEvent; end; begin DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Star'); RenderStar; DXUT_EndPerfEvent; end; // Draw the high dynamic range scene texture to the low dynamic range // back buffer. As part of this final pass, the scene will be tone-mapped // using the user's current adapted luminance, blue shift will occur // if the scene is determined to be very dark, and the post-process lighting // effect textures will be added to the scene. V(g_pEffect.SetTechnique('FinalScenePass')); V(g_pEffect.SetFloat('g_fMiddleGray', g_fKeyValue)); V(g_pd3dDevice.SetRenderTarget(0, pSurfLDR)); V(g_pd3dDevice.SetTexture(0, g_pTexScene)); V(g_pd3dDevice.SetTexture(1, g_apTexBloom[0])); V(g_pd3dDevice.SetTexture(2, g_apTexStar[0])); V(g_pd3dDevice.SetTexture(3, g_pTexAdaptedLuminanceCur)); V(g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT)); V(g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT)); V(g_pd3dDevice.SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR)); V(g_pd3dDevice.SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR)); V(g_pd3dDevice.SetSamplerState(2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR)); V(g_pd3dDevice.SetSamplerState(2, D3DSAMP_MINFILTER, D3DTEXF_LINEAR)); V(g_pd3dDevice.SetSamplerState(3, D3DSAMP_MAGFILTER, D3DTEXF_POINT)); V(g_pd3dDevice.SetSamplerState(3, D3DSAMP_MINFILTER, D3DTEXF_POINT)); V(g_pEffect._Begin(@uiPassCount, 0)); begin DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Final Scene Pass'); for iPass := 0 to uiPassCount - 1 do begin V(g_pEffect.BeginPass(iPass)); DrawFullScreenQuad(0.0, 0.0, 1.0, 1.0); V(g_pEffect.EndPass); end; DXUT_EndPerfEvent; end; V(g_pEffect._End); V(g_pd3dDevice.SetTexture(1, nil)); V(g_pd3dDevice.SetTexture(2, nil)); V(g_pd3dDevice.SetTexture(3, nil)); begin DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'HUD / Stats'); RenderText; V(g_HUD.OnRender(fElapsedTime)); V(g_SampleUI.OnRender(fElapsedTime)); DXUT_EndPerfEvent; end; V(pd3dDevice.EndScene); end; // Release surfaces SAFE_RELEASE(pSurfHDR); SAFE_RELEASE(pSurfLDR); SAFE_RELEASE(pSurfDS); end; //----------------------------------------------------------------------------- // Name: RenderScene() // Desc: Render the world objects and lights //----------------------------------------------------------------------------- function RenderScene: HRESULT; var iPassCount: Integer; iPass: Integer; mWorld: TD3DXMatrixA16; mObjectToView: TD3DXMatrixA16; mView: TD3DXMatrix; iLight: Integer; mScale: TD3DXMatrixA16; vEmissive: TD3DXVector4; begin g_pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); g_pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); mView := g_Camera.GetViewMatrix^; g_pEffect.SetTechnique('RenderScene'); g_pEffect.SetMatrix('g_mObjectToView', mView); Result := g_pEffect._Begin(@iPassCount, 0); if FAILED(Result) then Exit; for iPass := 0 to iPassCount - 1 do begin g_pEffect.BeginPass(iPass); // Turn off emissive lighting g_pEffect.SetVector('g_vEmissive', D3DXVector4Zero); // Enable texture g_pEffect.SetBool('g_bEnableTexture', True); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); // Render walls and columns g_pEffect.SetFloat('g_fPhongExponent', 5.0); g_pEffect.SetFloat('g_fPhongCoefficient', 1.0); g_pEffect.SetFloat('g_fDiffuseCoefficient', 0.5); g_pd3dDevice.SetTexture(0, g_pTexWall); g_pEffect.CommitChanges; g_pWorldMesh.DrawSubset(0); // Render floor g_pEffect.SetFloat('g_fPhongExponent', 50.0); g_pEffect.SetFloat('g_fPhongCoefficient', 3.0); g_pEffect.SetFloat('g_fDiffuseCoefficient', 1.0); g_pd3dDevice.SetTexture(0, g_pTexFloor); g_pEffect.CommitChanges; g_pWorldMesh.DrawSubset(1); // Render ceiling g_pEffect.SetFloat('g_fPhongExponent', 5.0); g_pEffect.SetFloat('g_fPhongCoefficient', 0.3); g_pEffect.SetFloat('g_fDiffuseCoefficient', 0.3); g_pd3dDevice.SetTexture(0, g_pTexCeiling); g_pEffect.CommitChanges; g_pWorldMesh.DrawSubset(2); // Render paintings g_pEffect.SetFloat('g_fPhongExponent', 5.0); g_pEffect.SetFloat('g_fPhongCoefficient', 0.3); g_pEffect.SetFloat('g_fDiffuseCoefficient', 1.0); g_pd3dDevice.SetTexture(0, g_pTexPainting); g_pEffect.CommitChanges; g_pWorldMesh.DrawSubset(3); // Draw the light spheres. g_pEffect.SetFloat('g_fPhongExponent', 5.0); g_pEffect.SetFloat('g_fPhongCoefficient', 1.0); g_pEffect.SetFloat('g_fDiffuseCoefficient', 1.0); g_pEffect.SetBool('g_bEnableTexture', False); for iLight := 0 to NUM_LIGHTS - 1 do begin // Just position the point light -- no need to orient it D3DXMatrixScaling(mScale, 0.05, 0.05, 0.05); mView := g_Camera.GetViewMatrix^; D3DXMatrixTranslation(mWorld, g_avLightPosition[iLight].x, g_avLightPosition[iLight].y, g_avLightPosition[iLight].z); // mWorld := mScale * mWorld; D3DXMatrixMultiply(mWorld, mScale, mWorld); // mObjectToView := mWorld * mView; D3DXMatrixMultiply(mObjectToView, mWorld, mView); g_pEffect.SetMatrix('g_mObjectToView', mObjectToView); // A light which illuminates objects at 80 lum/sr should be drawn // at 3183 lumens/meter^2/steradian, which equates to a multiplier // of 39.78 per lumen. // vEmissive := EMISSIVE_COEFFICIENT * g_avLightIntensity[iLight]; D3DXVec4Scale(vEmissive, g_avLightIntensity[iLight], EMISSIVE_COEFFICIENT); g_pEffect.SetVector('g_vEmissive', vEmissive); g_pEffect.CommitChanges; g_pmeshSphere.DrawSubset(0); end; g_pEffect.EndPass; end; g_pEffect._End; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: MeasureLuminance() // Desc: Measure the average log luminance in the scene. //----------------------------------------------------------------------------- function MeasureLuminance: HRESULT; var iPassCount, iPass: Integer; i, x, y, index: Integer; avSampleOffsets: array[0..MAX_SAMPLES-1] of TD3DXVector2; dwCurTexture: DWORD; // Sample log average luminance apSurfToneMap: array[0..NUM_TONEMAP_TEXTURES-1] of IDirect3DSurface9; desc: TD3DSurfaceDesc; tU, tV: Single; begin dwCurTexture := NUM_TONEMAP_TEXTURES-1; // Retrieve the tonemap surfaces for i:= 0 to NUM_TONEMAP_TEXTURES - 1 do begin Result := g_apTexToneMap[i].GetSurfaceLevel(0, apSurfToneMap[i]); if FAILED(Result) then Exit; end; g_apTexToneMap[dwCurTexture].GetLevelDesc(0, desc); // Initialize the sample offsets for the initial luminance pass. tU := 1.0 / (3.0 * desc.Width); tV := 1.0 / (3.0 * desc.Height); index := 0; for x := -1 to 1 do begin for y := -1 to 1 do begin avSampleOffsets[index].x := x * tU; avSampleOffsets[index].y := y * tV; Inc(index); end; end; // After this pass, the g_apTexToneMap[NUM_TONEMAP_TEXTURES-1] texture will contain // a scaled, grayscale copy of the HDR scene. Individual texels contain the log // of average luminance values for points sampled on the HDR texture. g_pEffect.SetTechnique('SampleAvgLum'); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pd3dDevice.SetRenderTarget(0, apSurfToneMap[dwCurTexture]); g_pd3dDevice.SetTexture(0, g_pTexSceneScaled); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); g_pd3dDevice.SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); g_pd3dDevice.SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); Result := g_pEffect._Begin(@iPassCount, 0); if FAILED(Result) then Exit; for iPass := 0 to iPassCount - 1 do begin g_pEffect.BeginPass(iPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(0.0, 0.0, 1.0, 1.0); g_pEffect.EndPass; end; g_pEffect._End; Dec(dwCurTexture); // Initialize the sample offsets for the iterative luminance passes while (dwCurTexture > 0) do begin g_apTexToneMap[dwCurTexture+1].GetLevelDesc(0, desc); GetSampleOffsets_DownScale4x4(desc.Width, desc.Height, avSampleOffsets); // Each of these passes continue to scale down the log of average // luminance texture created above, storing intermediate results in // g_apTexToneMap[1] through g_apTexToneMap[NUM_TONEMAP_TEXTURES-1]. g_pEffect.SetTechnique('ResampleAvgLum'); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pd3dDevice.SetRenderTarget(0, apSurfToneMap[dwCurTexture]); g_pd3dDevice.SetTexture(0, g_apTexToneMap[dwCurTexture+1]); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); Result := g_pEffect._Begin(@iPassCount, 0); if FAILED(Result) then Exit; for iPass := 0 to iPassCount - 1 do begin g_pEffect.BeginPass(iPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(0.0, 0.0, 1.0, 1.0); g_pEffect.EndPass; end; g_pEffect._End; Dec(dwCurTexture); end; // Downsample to 1x1 g_apTexToneMap[1].GetLevelDesc(0, desc); GetSampleOffsets_DownScale4x4(desc.Width, desc.Height, avSampleOffsets); // Perform the final pass of the average luminance calculation. This pass // scales the 4x4 log of average luminance texture from above and performs // an exp() operation to return a single texel cooresponding to the average // luminance of the scene in g_apTexToneMap[0]. g_pEffect.SetTechnique('ResampleAvgLumExp'); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pd3dDevice.SetRenderTarget(0, apSurfToneMap[0]); g_pd3dDevice.SetTexture(0, g_apTexToneMap[1]); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); Result := g_pEffect._Begin(@iPassCount, 0); if FAILED(Result) then Exit; for iPass := 0 to iPassCount - 1 do begin g_pEffect.BeginPass(iPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(0.0, 0.0, 1.0, 1.0); g_pEffect.EndPass; end; g_pEffect._End; Result := S_OK; end; //----------------------------------------------------------------------------- // Name: CalculateAdaptation() // Desc: Increment the user's adapted luminance //----------------------------------------------------------------------------- function CalculateAdaptation: HRESULT; var uiPass, uiPassCount: Integer; pTexSwap: IDirect3DTexture9; pSurfAdaptedLum: IDirect3DSurface9; begin // Swap current & last luminance pTexSwap := g_pTexAdaptedLuminanceLast; g_pTexAdaptedLuminanceLast := g_pTexAdaptedLuminanceCur; g_pTexAdaptedLuminanceCur := pTexSwap; V(g_pTexAdaptedLuminanceCur.GetSurfaceLevel(0, pSurfAdaptedLum)); // This simulates the light adaptation that occurs when moving from a // dark area to a bright area, or vice versa. The g_pTexAdaptedLuminance // texture stores a single texel cooresponding to the user's adapted // level. g_pEffect.SetTechnique('CalculateAdaptedLum'); g_pEffect.SetFloat('g_fElapsedTime', DXUTGetElapsedTime); g_pd3dDevice.SetRenderTarget(0, pSurfAdaptedLum); g_pd3dDevice.SetTexture(0, g_pTexAdaptedLuminanceLast); g_pd3dDevice.SetTexture(1, g_apTexToneMap[0]); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_POINT); V(g_pEffect._Begin(@uiPassCount, 0)); for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(0.0, 0.0, 1.0, 1.0); g_pEffect.EndPass; end; g_pEffect._End; Result:= S_OK; end; const s_maxPasses = 3; var s_aaColor: array[0..s_maxPasses-1, 0..7] of TD3DXVector4; //----------------------------------------------------------------------------- // Name: RenderStar() // Desc: Render the blooming effect //----------------------------------------------------------------------------- function RenderStar: HRESULT; var uiPassCount, uiPass: Integer; i, d, p, s: Integer; // Loop variables pSurfStar: IDirect3DSurface9; // Initialize the constants used during the effect starDef: CStarDef; fTanFoV: Single; // = ArcTan(D3DX_PI/8); const vWhite: TD3DXVector4 = (x: 1.0; y: 1.0; z: 1.0; w: 1.0); nSamples = 8; const s_colorWhite: TD3DXColor = (r: 0.63; g: 0.63; b: 0.63; a: 0.0); var avSampleWeights: array[0..MAX_SAMPLES-1] of TD3DXVector4; avSampleOffsets: array[0..MAX_SAMPLES-1] of TD3DXVector2; pSurfSource: IDirect3DSurface9; pSurfDest: IDirect3DSurface9; apSurfStar: array[0..NUM_STAR_TEXTURES-1] of IDirect3DSurface9; desc: TD3DSurfaceDesc; srcW, srcH: Single; ratio: Single; chromaticAberrColor: TD3DXColor; radOffset: Single; pTexSource: IDirect3DTexture9; starLine: PStarLine; rad: Single; sn, cs: Single; vtStepUV: TD3DXVector2; attnPowScale: Single; iWorkTexture: Integer; lum: Single; strTechnique: AnsiString; begin Result := g_apTexStar[0].GetSurfaceLevel(0, pSurfStar); if FAILED(Result) then Exit; // Clear the star texture g_pd3dDevice.ColorFill(pSurfStar, nil, D3DCOLOR_ARGB(0, 0, 0, 0)); SAFE_RELEASE(pSurfStar); // Avoid rendering the star if it's not being used in the current glare if (g_GlareDef.m_fGlareLuminance <= 0.0) or (g_GlareDef.m_fStarLuminance <= 0.0) then begin Result:= S_OK; Exit; end; // Initialize the constants used during the effect starDef := g_GlareDef.m_starDef; fTanFoV := ArcTan(D3DX_PI/8); g_pd3dDevice.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); g_pd3dDevice.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); // Set aside all the star texture surfaces as a convenience for i:= 0 to NUM_STAR_TEXTURES - 1 do begin Result := g_apTexStar[i].GetSurfaceLevel(0, apSurfStar[i]); if FAILED(Result) then Exit; end; // Get the source texture dimensions Result := g_pTexStarSource.GetSurfaceLevel(0, pSurfSource); if FAILED(Result) then Exit; Result := pSurfSource.GetDesc(desc); if FAILED(Result) then Exit; SAFE_RELEASE(pSurfSource); srcW := desc.Width; srcH:= desc.Height; for p := 0 to s_maxPasses - 1 do begin ratio := (p + 1) / s_maxPasses; for s := 0 to nSamples - 1 do begin D3DXColorLerp(chromaticAberrColor, CStarDef.GetChromaticAberrationColor(s)^, s_colorWhite, ratio); D3DXColorLerp(PD3DXColor(@s_aaColor[p][s])^, s_colorWhite, chromaticAberrColor, g_GlareDef.m_fChromaticAberration); end; end; radOffset := g_GlareDef.m_fStarInclination + starDef.m_fInclination; // Direction loop for d := 0 to starDef.m_nStarLines - 1 do begin starLine := @starDef.m_pStarLine[d]; pTexSource := g_pTexStarSource; rad := radOffset + starLine.fInclination; sn := sin(rad); cs := cos(rad); vtStepUV.x := sn / srcW * starLine.fSampleLength; vtStepUV.y := cs / srcH * starLine.fSampleLength; attnPowScale := (fTanFoV + 0.1) * 1.0 * (160.0 + 120.0) / (srcW + srcH) * 1.2; // 1 direction expansion loop g_pd3dDevice.SetRenderState(D3DRS_ALPHABLENDENABLE, iFalse); iWorkTexture := 1; for p := 0 to starLine.nPasses - 1 do begin if (p = starLine.nPasses - 1) then begin // Last pass move to other work buffer pSurfDest := apSurfStar[d+4]; end else begin pSurfDest := apSurfStar[iWorkTexture]; end; // Sampling configration for each stage for i := 0 to nSamples -1 do begin lum := Power(starLine.fAttenuation, attnPowScale * i); // avSampleWeights[i] := s_aaColor[starLine.nPasses - 1 - p][i] * lum * (p+1.0) * 0.5; D3DXVec4Scale(avSampleWeights[i], s_aaColor[starLine.nPasses - 1 - p][i], lum * (p+1.0) * 0.5); // Offset of sampling coordinate avSampleOffsets[i].x := vtStepUV.x * i; avSampleOffsets[i].y := vtStepUV.y * i; if (abs(avSampleOffsets[i].x) >= 0.9) or (abs(avSampleOffsets[i].y) >= 0.9) then begin avSampleOffsets[i].x := 0.0; avSampleOffsets[i].y := 0.0; // avSampleWeights[i] := avSampleWeights[i] * 0.0; end; end; g_pEffect.SetTechnique('Star'); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pEffect.SetVectorArray('g_avSampleWeights', @avSampleWeights, nSamples); g_pd3dDevice.SetRenderTarget(0, pSurfDest); g_pd3dDevice.SetTexture(0, pTexSource); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); Result := g_pEffect._Begin(@uiPassCount, 0); if FAILED(Result) then Exit; for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(0.0, 0.0, 1.0, 1.0); g_pEffect.EndPass; end; g_pEffect._End; // Setup next expansion D3DXVec2Scale(vtStepUV, vtStepUV, nSamples); attnPowScale := attnPowScale * nSamples; // Set the work drawn just before to next texture source. pTexSource := g_apTexStar[iWorkTexture]; Inc(iWorkTexture, 1); if (iWorkTexture > 2) then iWorkTexture := 1; end; end; pSurfDest := apSurfStar[0]; for i:= 0 to starDef.m_nStarLines - 1 do begin g_pd3dDevice.SetTexture( i, g_apTexStar[i+4]); g_pd3dDevice.SetSamplerState( i, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); g_pd3dDevice.SetSamplerState( i, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); D3DXVec4Scale(avSampleWeights[i], vWhite, 1.0 / starDef.m_nStarLines); end; strTechnique := Format('MergeTextures_%d', [starDef.m_nStarLines]); g_pEffect.SetTechnique(TD3DXHandle(strTechnique)); g_pEffect.SetVectorArray('g_avSampleWeights', @avSampleWeights, starDef.m_nStarLines); g_pd3dDevice.SetRenderTarget(0, pSurfDest); Result := g_pEffect._Begin(@uiPassCount, 0); if FAILED(Result) then Exit; for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(0.0, 0.0, 1.0, 1.0); g_pEffect.EndPass; end; g_pEffect._End; for i:= 0 to starDef.m_nStarLines - 1 do g_pd3dDevice.SetTexture(i, nil); Result := S_OK; end; //----------------------------------------------------------------------------- // Name: RenderBloom() // Desc: Render the blooming effect //----------------------------------------------------------------------------- function RenderBloom: HRESULT; var uiPassCount, uiPass: Integer; i: Integer; avSampleOffsets: array[0..MAX_SAMPLES-1] of TD3DXVector2; afSampleOffsets: array[0..MAX_SAMPLES-1] of Single; avSampleWeights: array[0..MAX_SAMPLES-1] of TD3DXVector4; pSurfScaledHDR: IDirect3DSurface9; pSurfBloom: IDirect3DSurface9; pSurfHDR: IDirect3DSurface9; pSurfTempBloom: IDirect3DSurface9; pSurfBloomSource: IDirect3DSurface9; rectSrc: TRect; rectDest: TRect; coords: TCoordRect; desc: TD3DSurfaceDesc; begin g_pTexSceneScaled.GetSurfaceLevel(0, pSurfScaledHDR); g_apTexBloom[0].GetSurfaceLevel(0, pSurfBloom); g_pTexScene.GetSurfaceLevel(0, pSurfHDR); g_apTexBloom[1].GetSurfaceLevel(0, pSurfTempBloom); g_apTexBloom[2].GetSurfaceLevel(0, pSurfBloomSource); // Clear the bloom texture g_pd3dDevice.ColorFill(pSurfBloom, nil, D3DCOLOR_ARGB(0, 0, 0, 0)); GetTextureRect(g_pTexBloomSource, rectSrc); InflateRect(rectSrc, -1, -1); GetTextureRect(g_apTexBloom[2], rectDest); InflateRect(rectDest, -1, -1); GetTextureCoords(g_pTexBloomSource, @rectSrc, g_apTexBloom[2], @rectDest, coords); Result := g_pTexBloomSource.GetLevelDesc(0, desc); if FAILED(Result) then Exit; g_pEffect.SetTechnique('GaussBlur5x5'); Result := GetSampleOffsets_GaussBlur5x5(desc.Width, desc.Height, avSampleOffsets, avSampleWeights, 1.0); if FAILED(Result) then Exit; g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pEffect.SetValue('g_avSampleWeights', @avSampleWeights, SizeOf(avSampleWeights)); g_pd3dDevice.SetRenderTarget(0, pSurfBloomSource); g_pd3dDevice.SetTexture(0, g_pTexBloomSource); g_pd3dDevice.SetScissorRect(@rectDest); g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iTrue); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); Result := g_pEffect._Begin(@uiPassCount, 0); if FAILED(Result) then Exit; for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(coords); g_pEffect.EndPass; end; g_pEffect._End; g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iFalse); Result := g_apTexBloom[2].GetLevelDesc(0, desc); if FAILED(Result) then Exit; {Result := }GetSampleOffsets_Bloom(desc.Width, afSampleOffsets, avSampleWeights, 3.0, 2.0); for i := 0 to MAX_SAMPLES - 1 do begin avSampleOffsets[i] := D3DXVector2(afSampleOffsets[i], 0.0); end; g_pEffect.SetTechnique('Bloom'); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pEffect.SetValue('g_avSampleWeights', @avSampleWeights, SizeOf(avSampleWeights)); g_pd3dDevice.SetRenderTarget(0, pSurfTempBloom); g_pd3dDevice.SetTexture(0, g_apTexBloom[2]); g_pd3dDevice.SetScissorRect(@rectDest); g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iTrue); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); g_pEffect._Begin(@uiPassCount, 0); for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(coords); g_pEffect.EndPass; end; g_pEffect._End; g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iFalse); Result := g_apTexBloom[1].GetLevelDesc(0, desc); if FAILED(Result) then Exit; {Result := }GetSampleOffsets_Bloom(desc.Height, afSampleOffsets, avSampleWeights, 3.0, 2.0); for i := 0 to MAX_SAMPLES - 1 do begin avSampleOffsets[i] := D3DXVector2(0.0, afSampleOffsets[i]); end; GetTextureRect(g_apTexBloom[1], rectSrc); InflateRect(rectSrc, -1, -1); GetTextureCoords(g_apTexBloom[1], @rectSrc, g_apTexBloom[0], nil, coords); g_pEffect.SetTechnique('Bloom'); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pEffect.SetValue('g_avSampleWeights', @avSampleWeights, SizeOf(avSampleWeights)); g_pd3dDevice.SetRenderTarget(0, pSurfBloom); g_pd3dDevice.SetTexture(0, g_apTexBloom[1]); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); Result := g_pEffect._Begin(@uiPassCount, 0); if FAILED(Result) then Exit; for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(coords); g_pEffect.EndPass; end; g_pEffect._End; Result := S_OK; end; //----------------------------------------------------------------------------- // Name: DrawFullScreenQuad // Desc: Draw a properly aligned quad covering the entire render target //----------------------------------------------------------------------------- procedure DrawFullScreenQuad(const c: TCoordRect); overload; begin DrawFullScreenQuad(c.fLeftU, c.fTopV, c.fRightU, c.fBottomV); end; procedure DrawFullScreenQuad(fLeftU, fTopV, fRightU, fBottomV: Single); overload; var dtdsdRT: TD3DSurfaceDesc; pSurfRT: IDirect3DSurface9; fWidth5, fHeight5: Single; svQuad: array[0..3] of TScreenVertex; begin // Acquire render target width and height g_pd3dDevice.GetRenderTarget(0, pSurfRT); pSurfRT.GetDesc(dtdsdRT); pSurfRT := nil; // Ensure that we're directly mapping texels to pixels by offset by 0.5 // For more info see the doc page titled "Directly Mapping Texels to Pixels" fWidth5 := dtdsdRT.Width - 0.5; fHeight5 := dtdsdRT.Height - 0.5; // Draw the quad svQuad[0].p := D3DXVector4(-0.5, -0.5, 0.5, 1.0); svQuad[0].t := D3DXVector2(fLeftU, fTopV); svQuad[1].p := D3DXVector4(fWidth5, -0.5, 0.5, 1.0); svQuad[1].t := D3DXVector2(fRightU, fTopV); svQuad[2].p := D3DXVector4(-0.5, fHeight5, 0.5, 1.0); svQuad[2].t := D3DXVector2(fLeftU, fBottomV); svQuad[3].p := D3DXVector4(fWidth5, fHeight5, 0.5, 1.0); svQuad[3].t := D3DXVector2(fRightU, fBottomV); g_pd3dDevice.SetRenderState(D3DRS_ZENABLE, iFalse); g_pd3dDevice.SetFVF(TScreenVertex_FVF); g_pd3dDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, svQuad, SizeOf(TScreenVertex)); g_pd3dDevice.SetRenderState(D3DRS_ZENABLE, iTrue); end; //----------------------------------------------------------------------------- // Name: GetTextureRect() // Desc: Get the dimensions of the texture //----------------------------------------------------------------------------- function GetTextureRect(const pTexture: IDirect3DTexture9; out pRect: TRect): HRESULT; var desc: TD3DSurfaceDesc; begin if (pTexture = nil) then begin Result:= E_INVALIDARG; Exit; end; Result := pTexture.GetLevelDesc(0, desc); if FAILED(Result) then Exit; pRect.left := 0; pRect.top := 0; pRect.right := desc.Width; pRect.bottom := desc.Height; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: GetTextureCoords() // Desc: Get the texture coordinates to use when rendering into the destination // texture, given the source and destination rectangles //----------------------------------------------------------------------------- function GetTextureCoords(const pTexSrc: IDirect3DTexture9; pRectSrc: PRect; pTexDest: IDirect3DTexture9; pRectDest: PRect; var pCoords: TCoordRect): HRESULT; var desc: TD3DSurfaceDesc; tU, tV: Single; begin // Validate arguments if (pTexSrc = nil) or (pTexDest = nil) then begin Result:= E_INVALIDARG; Exit; end; // Start with a default mapping of the complete source surface to complete // destination surface pCoords.fLeftU := 0.0; pCoords.fTopV := 0.0; pCoords.fRightU := 1.0; pCoords.fBottomV := 1.0; // If not using the complete source surface, adjust the coordinates if (pRectSrc <> nil) then begin // Get destination texture description Result := pTexSrc.GetLevelDesc(0, desc); if FAILED(Result) then Exit; // These delta values are the distance between source texel centers in // texture address space tU := 1.0 / desc.Width; tV := 1.0 / desc.Height; pCoords.fLeftU := pCoords.fLeftU + pRectSrc.left * tU; pCoords.fTopV := pCoords.fTopV + pRectSrc.top * tV; pCoords.fRightU := pCoords.fRightU - (Integer(desc.Width) - pRectSrc.right) * tU; pCoords.fBottomV := pCoords.fBottomV - (Integer(desc.Height) - pRectSrc.bottom) * tV; end; // If not drawing to the complete destination surface, adjust the coordinates if (pRectDest <> nil) then begin // Get source texture description Result := pTexDest.GetLevelDesc(0, desc); if FAILED(Result) then Exit; // These delta values are the distance between source texel centers in // texture address space tU := 1.0 / desc.Width; tV := 1.0 / desc.Height; pCoords.fLeftU := pCoords.fLeftU - pRectDest.left * tU; pCoords.fTopV := pCoords.fTopV - pRectDest.top * tV; pCoords.fRightU := pCoords.fRightU + (Integer(desc.Width) - pRectDest.right) * tU; pCoords.fBottomV := pCoords.fBottomV + (Integer(desc.Height) - pRectDest.bottom) * tV; end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: Scene_To_SceneScaled() // Desc: Scale down g_pTexScene by 1/4 x 1/4 and place the result in // g_pTexSceneScaled //----------------------------------------------------------------------------- function Scene_To_SceneScaled: HRESULT; var avSampleOffsets: array[0..MAX_SAMPLES-1] of TD3DXVector2; pSurfScaledScene: IDirect3DSurface9; pBackBufferDesc: PD3DSurfaceDesc; rectSrc: TRect; coords: TCoordRect; uiPassCount, uiPass: Integer; begin // Get the new render target surface Result := g_pTexSceneScaled.GetSurfaceLevel(0, pSurfScaledScene); if FAILED(Result) then Exit; pBackBufferDesc := DXUTGetBackBufferSurfaceDesc; // Create a 1/4 x 1/4 scale copy of the HDR texture. Since bloom textures // are 1/8 x 1/8 scale, border texels of the HDR texture will be discarded // to keep the dimensions evenly divisible by 8; this allows for precise // control over sampling inside pixel shaders. g_pEffect.SetTechnique('DownScale4x4'); // Place the rectangle in the center of the back buffer surface rectSrc.left := (pBackBufferDesc.Width - g_dwCropWidth) div 2; rectSrc.top := (pBackBufferDesc.Height - g_dwCropHeight) div 2; rectSrc.right := rectSrc.left + Integer(g_dwCropWidth); rectSrc.bottom := rectSrc.top + Integer(g_dwCropHeight); // Get the texture coordinates for the render target GetTextureCoords(g_pTexScene, @rectSrc, g_pTexSceneScaled, nil, coords); // Get the sample offsets used within the pixel shader GetSampleOffsets_DownScale4x4(pBackBufferDesc.Width, pBackBufferDesc.Height, avSampleOffsets); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pd3dDevice.SetRenderTarget(0, pSurfScaledScene); g_pd3dDevice.SetTexture(0, g_pTexScene); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); g_pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); Result := g_pEffect._Begin(@uiPassCount, 0); if FAILED(Result) then Exit; for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad DrawFullScreenQuad(coords); g_pEffect.EndPass; end; g_pEffect._End; Result := S_OK; end; //----------------------------------------------------------------------------- // Name: SceneScaled_To_BrightPass // Desc: Run the bright-pass filter on g_pTexSceneScaled and place the result // in g_pTexBrightPass //----------------------------------------------------------------------------- function SceneScaled_To_BrightPass: HRESULT; var pSurfBrightPass: IDirect3DSurface9; desc: TD3DSurfaceDesc; rectSrc: TRect; rectDest: TRect; coords: TCoordRect; uiPass, uiPassCount: Integer; begin // Get the new render target surface Result := g_pTexBrightPass.GetSurfaceLevel(0, pSurfBrightPass); if FAILED(Result) then Exit; g_pTexSceneScaled.GetLevelDesc(0, desc); // Get the rectangle describing the sampled portion of the source texture. // Decrease the rectangle to adjust for the single pixel black border. GetTextureRect(g_pTexSceneScaled, rectSrc); InflateRect(rectSrc, -1, -1); // Get the destination rectangle. // Decrease the rectangle to adjust for the single pixel black border. GetTextureRect(g_pTexBrightPass, rectDest); InflateRect(rectDest, -1, -1); // Get the correct texture coordinates to apply to the rendered quad in order // to sample from the source rectangle and render into the destination rectangle GetTextureCoords(g_pTexSceneScaled, @rectSrc, g_pTexBrightPass, @rectDest, coords); // The bright-pass filter removes everything from the scene except lights and // bright reflections g_pEffect.SetTechnique('BrightPassFilter'); g_pd3dDevice.SetRenderTarget(0, pSurfBrightPass); g_pd3dDevice.SetTexture(0, g_pTexSceneScaled); g_pd3dDevice.SetTexture(1, g_pTexAdaptedLuminanceCur); g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iTrue); g_pd3dDevice.SetScissorRect(@rectDest); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_POINT); Result := g_pEffect._Begin(@uiPassCount, 0); if FAILED(Result) then Exit; for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad(coords); g_pEffect.EndPass; end; g_pEffect._End; g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iFalse); Result := S_OK; end; //----------------------------------------------------------------------------- // Name: BrightPass_To_StarSource // Desc: Perform a 5x5 gaussian blur on g_pTexBrightPass and place the result // in g_pTexStarSource. The bright-pass filtered image is blurred before // being used for star operations to avoid aliasing artifacts. //----------------------------------------------------------------------------- function BrightPass_To_StarSource: HRESULT; var avSampleOffsets: array[0..MAX_SAMPLES-1] of TD3DXVector2; avSampleWeights: array[0..MAX_SAMPLES-1] of TD3DXVector4; pSurfStarSource: IDirect3DSurface9; rectDest: TRect; coords: TCoordRect; desc: TD3DSurfaceDesc; uiPassCount, uiPass: Integer; begin // Get the new render target surface Result := g_pTexStarSource.GetSurfaceLevel(0, pSurfStarSource); if FAILED(Result) then Exit; // Get the destination rectangle. // Decrease the rectangle to adjust for the single pixel black border. GetTextureRect(g_pTexStarSource, rectDest); InflateRect(rectDest, -1, -1); // Get the correct texture coordinates to apply to the rendered quad in order // to sample from the source rectangle and render into the destination rectangle GetTextureCoords(g_pTexBrightPass, nil, g_pTexStarSource, @rectDest, coords); // Get the sample offsets used within the pixel shader Result := g_pTexBrightPass.GetLevelDesc(0, desc); if FAILED(Result) then Exit; GetSampleOffsets_GaussBlur5x5(desc.Width, desc.Height, avSampleOffsets, avSampleWeights); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pEffect.SetValue('g_avSampleWeights', @avSampleWeights, SizeOf(avSampleWeights)); // The gaussian blur smooths out rough edges to avoid aliasing effects // when the star effect is run g_pEffect.SetTechnique('GaussBlur5x5'); g_pd3dDevice.SetRenderTarget(0, pSurfStarSource); g_pd3dDevice.SetTexture(0, g_pTexBrightPass); g_pd3dDevice.SetScissorRect(@rectDest); g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iTrue); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); g_pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); Result := g_pEffect._Begin(@uiPassCount, 0); if FAILED(Result) then Exit; for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad DrawFullScreenQuad(coords); g_pEffect.EndPass; end; g_pEffect._End; g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iFalse); Result := S_OK; end; //----------------------------------------------------------------------------- // Name: StarSource_To_BloomSource // Desc: Scale down g_pTexStarSource by 1/2 x 1/2 and place the result in // g_pTexBloomSource //----------------------------------------------------------------------------- function StarSource_To_BloomSource: HRESULT; var avSampleOffsets: array[0..MAX_SAMPLES-1] of TD3DXVector2; pSurfBloomSource: IDirect3DSurface9; rectSrc: TRect; rectDest: TRect; coords: TCoordRect; desc: TD3DSurfaceDesc; uiPassCount, uiPass: Integer; begin // Get the new render target surface Result := g_pTexBloomSource.GetSurfaceLevel(0, pSurfBloomSource); if FAILED(Result) then Exit; // Get the rectangle describing the sampled portion of the source texture. // Decrease the rectangle to adjust for the single pixel black border. GetTextureRect(g_pTexStarSource, rectSrc); InflateRect(rectSrc, -1, -1); // Get the destination rectangle. // Decrease the rectangle to adjust for the single pixel black border. GetTextureRect(g_pTexBloomSource, rectDest); InflateRect(rectDest, -1, -1); // Get the correct texture coordinates to apply to the rendered quad in order // to sample from the source rectangle and render into the destination rectangle GetTextureCoords(g_pTexStarSource, @rectSrc, g_pTexBloomSource, @rectDest, coords); // Get the sample offsets used within the pixel shader Result := g_pTexBrightPass.GetLevelDesc(0, desc); if FAILED(Result) then Exit; GetSampleOffsets_DownScale2x2(desc.Width, desc.Height, avSampleOffsets); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); // Create an exact 1/2 x 1/2 copy of the source texture g_pEffect.SetTechnique('DownScale2x2'); g_pd3dDevice.SetRenderTarget(0, pSurfBloomSource); g_pd3dDevice.SetTexture(0, g_pTexStarSource); g_pd3dDevice.SetScissorRect(@rectDest); g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iTrue); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); g_pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); Result := g_pEffect._Begin(@uiPassCount, 0); if FAILED(Result) then Exit; for uiPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(uiPass); // Draw a fullscreen quad DrawFullScreenQuad(coords); g_pEffect.EndPass; end; g_pEffect._End; g_pd3dDevice.SetRenderState(D3DRS_SCISSORTESTENABLE, iFalse); Result := S_OK; end; //----------------------------------------------------------------------------- // Name: GetSampleOffsets_DownScale4x4 // Desc: Get the texture coordinate offsets to be used inside the DownScale4x4 // pixel shader. //----------------------------------------------------------------------------- function GetSampleOffsets_DownScale4x4(dwWidth, dwHeight: DWORD; var avSampleOffsets: array of TD3DXVector2): HRESULT; var tU, tV: Single; index: Integer; x, y: Integer; begin { if( NULL == avSampleOffsets ) return E_INVALIDARG; } tU := 1.0 / dwWidth; tV := 1.0 / dwHeight; // Sample from the 16 surrounding points. Since the center point will be in // the exact center of 16 texels, a 0.5f offset is needed to specify a texel // center. index := 0; for y := 0 to 3 do for x := 0 to 3 do begin avSampleOffsets[index].x := (x - 1.5) * tU; avSampleOffsets[index].y := (y - 1.5) * tV; Inc(index); end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: GetSampleOffsets_DownScale2x2 // Desc: Get the texture coordinate offsets to be used inside the DownScale2x2 // pixel shader. //----------------------------------------------------------------------------- function GetSampleOffsets_DownScale2x2(dwWidth, dwHeight: DWORD; var avSampleOffsets: array of TD3DXVector2): HRESULT; var tU, tV: Single; index: Integer; x, y: Integer; begin { if( NULL == avSampleOffsets ) return E_INVALIDARG; } tU := 1.0 / dwWidth; tV := 1.0 / dwHeight; // Sample from the 4 surrounding points. Since the center point will be in // the exact center of 4 texels, a 0.5f offset is needed to specify a texel // center. index := 0; for y := 0 to 1 do for x := 0 to 1 do begin avSampleOffsets[index].x := (x - 0.5) * tU; avSampleOffsets[index].y := (y - 0.5) * tV; Inc(index); end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: GetSampleOffsets_GaussBlur5x5 // Desc: Get the texture coordinate offsets to be used inside the GaussBlur5x5 // pixel shader. //----------------------------------------------------------------------------- function GetSampleOffsets_GaussBlur5x5(dwD3DTexWidth, dwD3DTexHeight: DWORD; var avTexCoordOffset: array of TD3DXVector2; var avSampleWeight: array of TD3DXVector4; fMultiplier: Single = 1.0): HRESULT; var tu, tv: Single; vWhite: TD3DXVector4; totalWeight: Single; index: Integer; i, x, y: Integer; begin tu := 1.0 / dwD3DTexWidth; tv := 1.0 / dwD3DTexHeight; vWhite := D3DXVector4(1.0, 1.0, 1.0, 1.0); totalWeight := 0.0; index := 0; for x := -2 to 2 do for y := -2 to 2 do begin // Exclude pixels with a block distance greater than 2. This will // create a kernel which approximates a 5x5 kernel using only 13 // sample points instead of 25; this is necessary since 2.0 shaders // only support 16 texture grabs. if (abs(x) + abs(y) > 2) then Continue; // Get the unscaled Gaussian intensity for this offset avTexCoordOffset[index] := D3DXVector2(x * tu, y * tv); // avSampleWeight[index] := vWhite * GaussianDistribution(x, y, 1.0); D3DXVec4Scale(avSampleWeight[index], vWhite, GaussianDistribution(x, y, 1.0)); totalWeight := totalWeight + avSampleWeight[index].x; Inc(index); end; // Divide the current weight by the total weight of all the samples; Gaussian // blur kernels add to 1.0f to ensure that the intensity of the image isn't // changed when the blur occurs. An optional multiplier variable is used to // add or remove image intensity during the blur. for i := 0 to index - 1 do begin D3DXVec4Scale(avSampleWeight[i], avSampleWeight[i], fMultiplier / totalWeight); end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: GetSampleOffsets_Bloom // Desc: Get the texture coordinate offsets to be used inside the Bloom // pixel shader. //----------------------------------------------------------------------------- function GetSampleOffsets_Bloom(dwD3DTexSize: DWORD; var afTexCoordOffset: array of Single; var avColorWeight: array of TD3DXVector4; fDeviation: Single; fMultiplier: Single = 1.0): HRESULT; var i: Integer; tu: Single; weight: Single; begin tu := 1.0 / dwD3DTexSize; // Fill the center texel weight := fMultiplier * GaussianDistribution(0, 0, fDeviation); avColorWeight[0] := D3DXVector4(weight, weight, weight, 1.0); afTexCoordOffset[0] := 0.0; // Fill the first half for i := 1 to 7 do begin // Get the Gaussian intensity for this offset weight := fMultiplier * GaussianDistribution(i, 0, fDeviation); afTexCoordOffset[i] := i * tu; avColorWeight[i] := D3DXVector4(weight, weight, weight, 1.0); end; // Mirror to the second half for i:= 8 to 14 do begin avColorWeight[i] := avColorWeight[i-7]; afTexCoordOffset[i] := -afTexCoordOffset[i-7]; end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: GetSampleOffsets_Bloom // Desc: Get the texture coordinate offsets to be used inside the Bloom // pixel shader. //----------------------------------------------------------------------------- function GetSampleOffsets_Star(dwD3DTexSize: DWORD; var afTexCoordOffset: array {[15]} of Single; var avColorWeight: array of TD3DXVector4; fDeviation: Single): HRESULT; var i: Integer; tu: Single; weight: Single; begin tu := 1.0 / dwD3DTexSize; // Fill the center texel weight := 1.0 * GaussianDistribution(0, 0, fDeviation); avColorWeight[0] := D3DXVector4(weight, weight, weight, 1.0); afTexCoordOffset[0] := 0.0; // Fill the first half for i := 1 to 7 do begin // Get the Gaussian intensity for this offset weight := 1.0 * GaussianDistribution(i, 0, fDeviation); afTexCoordOffset[i] := i * tu; avColorWeight[i] := D3DXVector4(weight, weight, weight, 1.0); end; // Mirror to the second half for i := 8 to 14 do begin avColorWeight[i] := avColorWeight[i-7]; afTexCoordOffset[i] := -afTexCoordOffset[i-7]; end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: GaussianDistribution // Desc: Helper function for GetSampleOffsets function to compute the // 2 parameter Gaussian distrubution using the given standard deviation // rho //----------------------------------------------------------------------------- function GaussianDistribution(x, y, rho: Single): Single;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF} var g: Single; begin g := 1.0 / sqrt( 2.0 * D3DX_PI * rho * rho); g := g * exp( -(x*x + y*y)/(2*rho*rho)); Result:= g; end; //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- procedure RenderText; var txtHelper: CDXUTTextHelper; pd3dsdBackBuffer: PD3DSurfaceDesc; begin // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( g_pSprite, strMsg, -1, &rc, DT_NOCLIP, g_clr ); // If NULL is passed in as the sprite object, then it will work however the // pFont->DrawText() will not be batched together. Batching calls will improves performance. txtHelper:= CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15); // Output statistics txtHelper._Begin; txtHelper.SetInsertionPos(5, 5); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0)); txtHelper.DrawTextLine(DXUTGetFrameStats); txtHelper.DrawTextLine(DXUTGetDeviceStats); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawFormattedTextLine('Glare type: %s', [g_GlareDef.m_strGlareName]); if g_bUseMultiSampleFloat16 then begin txtHelper.DrawTextLine('Using MultiSample Render Target'); txtHelper.DrawFormattedTextLine('Number of Samples: %d', [Integer(g_MaxMultiSampleType)]); txtHelper.DrawFormattedTextLine('Quality: %d', [g_dwMultiSampleQuality]); end; // Draw help if g_bShowHelp then begin pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc; txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*6); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0)); txtHelper.DrawTextLine('Controls (F1 to hide):'); txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*5); txtHelper.DrawTextLine('Look: Left drag mouse'#10+ 'Move: A,W,S,D or Arrow Keys'#10+ 'Quit: ESC'); end else begin txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('Press F1 for help'); end; txtHelper._End; txtHelper.Free; end; //-------------------------------------------------------------------------------------- // Before handling window messages, DXUT passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then DXUT will not process this message. //-------------------------------------------------------------------------------------- function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; begin Result:= 0; // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; if g_SettingsDlg.IsActive then begin g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); Exit; end; // Give the dialogs a chance to handle the message first pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam); end; //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; begin if bKeyDown then begin case nChar of VK_F1: g_bShowHelp := not g_bShowHelp; end; end; end; //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; var pStatic: CDXUTStatic; pComboBox: CDXUTComboBox; pSlider: CDXUTSlider; pCheckBox: CDXUTCheckBox; strBuffer: WideString; iLight: Integer; begin case nControlID of IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen; IDC_TOGGLEREF: DXUTToggleREF; IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active; IDC_RESET: ResetOptions; IDC_TONEMAP: begin pCheckBox := CDXUTCheckBox(pControl); g_bToneMap := pCheckBox.Checked; end; IDC_BLUESHIFT: begin pCheckBox := CDXUTCheckBox(pControl); g_bBlueShift := pCheckBox.Checked; end; IDC_GLARETYPE: begin pComboBox := CDXUTComboBox(pControl); g_eGlareType := TEGlareLibType(INT_PTR(pComboBox.GetSelectedData)); g_GlareDef.Initialize(g_eGlareType); end; IDC_KEYVALUE: begin pSlider := CDXUTSlider(pControl); g_fKeyValue := pSlider.Value / 100.0; strBuffer := Format('Key Value: %.2f', [g_fKeyValue]); pStatic := g_SampleUI.GetStatic(IDC_KEYVALUE_LABEL); pStatic.Text := PWideChar(strBuffer); end; IDC_LIGHT0, IDC_LIGHT1: begin if (nControlID = IDC_LIGHT0) then iLight := 0 else iLight := 1; pSlider := CDXUTSlider(pControl); g_nLightMantissa[iLight] := 1 + pSlider.Value mod 9; g_nLightLogIntensity[iLight] := -4 + pSlider.Value div 9; RefreshLights; end; end; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // entered a lost state and before IDirect3DDevice9::Reset is called. Resources created // in the OnResetDevice callback should be released here, which generally includes all // D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for // information about lost devices. //-------------------------------------------------------------------------------------- procedure OnLostDevice; stdcall; var i: Integer; begin g_DialogResourceManager.OnLostDevice; g_SettingsDlg.OnLostDevice; if (g_pFont <> nil) then g_pFont.OnLostDevice; if (g_pEffect <> nil) then g_pEffect.OnLostDevice; SAFE_RELEASE(g_pTextSprite); SAFE_RELEASE(g_pWorldMesh); SAFE_RELEASE(g_pmeshSphere); SAFE_RELEASE(g_pFloatMSRT); SAFE_RELEASE(g_pFloatMSDS); SAFE_RELEASE(g_pTexScene); SAFE_RELEASE(g_pTexSceneScaled); SAFE_RELEASE(g_pTexWall); SAFE_RELEASE(g_pTexFloor); SAFE_RELEASE(g_pTexCeiling); SAFE_RELEASE(g_pTexPainting); SAFE_RELEASE(g_pTexAdaptedLuminanceCur); SAFE_RELEASE(g_pTexAdaptedLuminanceLast); SAFE_RELEASE(g_pTexBrightPass); SAFE_RELEASE(g_pTexBloomSource); SAFE_RELEASE(g_pTexStarSource); for i:= 0 to NUM_TONEMAP_TEXTURES - 1 do SAFE_RELEASE(g_apTexToneMap[i]); for i:= 0 to NUM_STAR_TEXTURES - 1 do SAFE_RELEASE(g_apTexStar[i]); for i:= 0 to NUM_BLOOM_TEXTURES - 1 do SAFE_RELEASE(g_apTexBloom[i]); end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnCreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- procedure OnDestroyDevice; stdcall; begin g_DialogResourceManager.OnDestroyDevice; g_SettingsDlg.OnDestroyDevice; SAFE_RELEASE(g_pEffect); SAFE_RELEASE(g_pFont); g_pd3dDevice:= nil; end; procedure CreateCustomDXUTobjects; begin g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog g_Camera:= CFirstPersonCamera.Create; g_HUD:= CDXUTDialog.Create; g_SampleUI:= CDXUTDialog.Create; g_GlareDef:= CGlareDef.Create; end; procedure DestroyCustomDXUTobjects; begin FreeAndNil(g_DialogResourceManager); FreeAndNil(g_SettingsDlg); FreeAndNil(g_Camera); FreeAndNil(g_HUD); FreeAndNil(g_SampleUI); FreeAndNil(g_GlareDef); end; end.
unit kiwi.s3.objectinfo; interface uses kiwi.s3.interfaces; type tkiwiS3ObjectInfo = class(tinterfacedobject, ikiwiS3ObjectInfo) private { private declarations } fname: string; flastModifield: tdateTime; feTag: string; fsize: integer; fownerID: string; fdate: tdatetime; procedure setname(const value: string); procedure setlastModifield(const value: tdateTime); procedure seteTag(const value: string); procedure setsize(const value: integer); procedure setownerID(const value: string); procedure setdate(const value: tdatetime); function getname: string; function getlastModifield: tdateTime; function geteTag: string; function getsize: integer; function getownerID: string; function getdate: tdateTime; public { public declarations } constructor create(pname: string = ''; plastModifield: tdatetime = 0; peTag: string = ''; psize: integer = 0; pownerID: string = ''; pdate: tdatetime = 0); destructor destroy; class function new(pname: string = ''; plastModifield: tdatetime = 0; peTag: string = ''; psize: integer = 0; pownerID: string = ''; pdate: tdatetime = 0): tkiwiS3ObjectInfo; property name: string read getname write setname; property lastModifield: tdateTime read getlastModifield write setlastModifield; property eTag: string read geteTag write seteTag; property size: integer read getsize write setsize; property ownerID: string read getownerID write setownerID; property date: tdatetime read getdate write setdate; end; implementation { tKiwiFile } constructor tkiwiS3ObjectInfo.create(pname: string; plastModifield: tdatetime; peTag: string; psize: integer; pownerID: string; pdate: tdatetime); begin fname := pname; flastModifield := plastModifield; feTag := peTag; fsize := psize; fownerID := pownerID; fdate := pdate; end; destructor tkiwiS3ObjectInfo.destroy; begin fname := ''; flastModifield := 0; feTag := ''; fsize := 0; fownerID := ''; fdate := 0; end; function tkiwiS3ObjectInfo.getdate: tdateTime; begin result := fdate; end; function tkiwiS3ObjectInfo.geteTag: string; begin result := feTag; end; function tkiwiS3ObjectInfo.getlastModifield: tdateTime; begin result := flastModifield; end; function tkiwiS3ObjectInfo.getname: string; begin result := fname; end; function tkiwiS3ObjectInfo.getownerID: string; begin result := fownerID; end; function tkiwiS3ObjectInfo.getsize: integer; begin result := fsize; end; class function tkiwiS3ObjectInfo.new(pname: string; plastModifield: tdatetime; peTag: string; psize: integer; pownerID: string; pdate: tdatetime): tkiwiS3ObjectInfo; begin result := self.create(pname, plastModifield, peTag, psize, pownerID, pdate); end; procedure tkiwiS3ObjectInfo.setdate(const value: tdatetime); begin fdate := value; end; procedure tkiwiS3ObjectInfo.seteTag(const value: string); begin feTag := value; end; procedure tkiwiS3ObjectInfo.setlastModifield(const value: tdateTime); begin flastModifield := value; end; procedure tkiwiS3ObjectInfo.setname(const value: string); begin fname := value; end; procedure tkiwiS3ObjectInfo.setownerID(const value: string); begin fownerID := value; end; procedure tkiwiS3ObjectInfo.setsize(const value: integer); begin fsize := value; end; end.
unit Test_Data; interface uses Windows, SysUtils, Classes, ctsTypesDef, ctsPointerInterface; type TTestObj = class(TObject) public FStr: TStrings; Name: string; constructor Create; destructor Destroy; override; function CompareI(AData1, AData2 : Pointer): LongInt; function CompareII(AData1, AData2 : string): LongInt; procedure Observer(AValue: Pointer; ANotifyAction: TctsNotifyAction); end; type IIntfMyObject = interface ['{BA33CBCC-9CB2-4672-BF54-F52C2A0BEFFE}'] function GetInt: Integer; function GetStr: string; procedure SetInt(Value: Integer); procedure SetStr(const Value: string); property Int: Integer read GetInt write SetInt; property Str: string read GetStr write SetStr; end; TIntfMyObject = class(TInterfacedObject, IIntfMyObject) private FInt: Integer; FStr: string; protected { IIntfMyObject } function GetInt: Integer; function GetStr: string; procedure SetInt(Value: Integer); procedure SetStr(const Value: string); public property Int: Integer read GetInt write SetInt; property Str: string read GetStr write SetStr; end; var ActionNames: array[TctsNotifyAction] of string = ('naAdded', 'naDeleting', 'naForEach'); BooleanNames: array[Boolean] of string = ('False', 'True'); implementation constructor TTestObj.Create; begin inherited; FStr := TStringList.Create; end; destructor TTestObj.Destroy; begin FStr.SaveToFile(Name + '.txt'); FStr.Free; inherited; end; function TTestObj.CompareI(AData1, AData2 : Pointer): LongInt; begin Result := Integer(AData1) - Integer(AData2); end; function TTestObj.CompareII(AData1, AData2 : string): LongInt; begin Result := CompareStr(AData1, AData2); end; procedure TTestObj.Observer(AValue: Pointer; ANotifyAction: TctsNotifyAction); var S: string; begin S := Name + ': ' + IntToStr(Integer(AValue)) + ':' + ActionNames[ANotifyAction]; FStr.Add(S); end; { TIntfMyObject } function TIntfMyObject.GetInt: Integer; begin Result := FInt; end; function TIntfMyObject.GetStr: string; begin Result := FStr; end; procedure TIntfMyObject.SetInt(Value: Integer); begin FInt := Value; end; procedure TIntfMyObject.SetStr(const Value: string); begin FStr := Value; end; end.
unit frmTip; interface uses buttons,comctrls,Windows,Messages,SysUtils,Classes,Graphics,Controls, Forms,Dialogs,StdCtrls,ExtCtrls; type TformGETip = class(TForm) bClose: TBitBtn; bNextTip : TBitBtn; bRandomTip: TBitBtn; cbxShowTips: TCheckBox; Image: TImage; lblTitle: TLabel; mbTip: TMemo; pnlBottom: TPanel; pnlTip: TPanel; pnlTipDetails: TPanel; status: TStatusBar; bPreviousTip: TBitBtn; procedure bNextTipClick(Sender:TObject); procedure bRandomTipClick(Sender:TObject); procedure FormClose(Sender:TObject; var Action:TCloseAction); procedure FormCreate(Sender:TObject); procedure FormShow(Sender:TObject); procedure bCloseClick(Sender: TObject); procedure bPreviousTipClick(Sender: TObject); private procedure GetATip; procedure UpdateStatus; public numtip:word; FormTips:TStringList; procedure LoadTipFile(aFile: string); end; implementation {$R *.DFM} // ------ TformGETip.FormClose ------------------------------------------------- procedure TformGETip.FormClose(Sender: TObject; var Action: TCloseAction); begin FormTips.Free; end; // ------ TformGETip.FormCreate ------------------------------------------------ procedure TformGETip.FormCreate(Sender: TObject); begin FormTips := TStringList.Create; end; // ------ TformGETip.FormShow -------------------------------------------------- procedure TformGETip.FormShow(Sender: TObject); begin if FormTips.Count = 0 then FormTips.Add('No tips found!'); if FormTips.Count = 1 then begin bPreviousTip.Enabled := false; bNextTip.Enabled := false; end; if (NumTip<= (FormTips.Count-1)) then UpdateStatus else GetATip; {** for out of bounds} end; // ------ TformGETip.bNextTipClick --------------------------------------------- procedure TformGETip.bNextTipClick(Sender: TObject); begin if (NumTip>=(FormTips.Count-1)) then NumTip := 0 else NumTip := NumTip+1; UpdateStatus; end; // ------ TformGETip.bPreviousTipClick --------------------------------------------- procedure TformGETip.bPreviousTipClick(Sender: TObject); begin if (NumTip<=0) then NumTip := (FormTips.Count-1) else NumTip := NumTip-1; UpdateStatus; end; // ------ TformGETip.bRandomTipClick ------------------------------------------- procedure TformGETip.bRandomTipClick(Sender: TObject); begin GetATip; end; // ------ TformGETip.GetATip --------------------------------------------------- procedure TformGETip.GetATip; begin Randomize; NumTip := Random(FormTips.Count); UpdateStatus; end; // ------ TformGETip.UpdateStatus ---------------------------------------------- procedure TformGETip.UpdateStatus; begin mbTip.Clear; mbTip.Text := FormTips.Strings[NumTip]; status.SimpleText := 'This is tip ' + IntToStr(NumTip+1) + ' of ' + IntToStr(FormTips.Count); pnlBottom.SetFocus; end; // ------ TformGETip.bCloseClick ---------------------------------------------- procedure TformGETip.bCloseClick(Sender: TObject); begin Close; end; // ------ TformGETip.LoadTipFile ---------------------------------------------- procedure TformGETip.LoadTipFile(aFile: string); begin if (aFile <> '') then begin if FileExists(aFile) then FormTips.LoadFromFile(aFile); end; end; // ============================================================================= end.
unit acSelectSkin; {$I sDefs.inc} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, sListBox, StdCtrls, Buttons, sBitBtn, sSkinProvider, ExtCtrls, sPanel, ComCtrls, Mask, sMaskEdit, sSkinManager, sCustomComboEdit, sTooledit, sTrackBar, sLabel; {$IFNDEF NOTFORHELP} type TFormSkinSelect = class(TForm) sListBox1: TsListBox; sBitBtn1: TsBitBtn; sBitBtn2: TsBitBtn; sPanel1: TsPanel; sSkinProvider1: TsSkinProvider; sDirectoryEdit1: TsDirectoryEdit; sStickyLabel1: TsStickyLabel; sTrackBar1: TsTrackBar; sTrackBar2: TsTrackBar; sStickyLabel2: TsStickyLabel; procedure sListBox1Click(Sender: TObject); procedure sDirectoryEdit1Change(Sender: TObject); procedure FormShow(Sender: TObject); procedure sListBox1DblClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure sTrackBar1Change(Sender: TObject); procedure sTrackBar2Change(Sender: TObject); public sName : string; SkinTypes : TacSkinTypes; SkinPlaces : TacSkinPlaces; SkinManager : TsSkinManager; sSkinSaturation, sSkinHUE: integer; private end; var FormSkinSelect: TFormSkinSelect; {$ENDIF} function SelectSkin(var SkinName : string; var SkinDir : string; var SkinSaturation: integer; var SkinHUE: integer; SkinTypes : TacSkinTypes = stAllSkins) : boolean; overload; function SelectSkin(NameList : TStringList; var SkinDir : string; SkinTypes : TacSkinTypes = stAllSkins) : boolean; overload; function SelectSkin(SkinManager : TsSkinManager; SkinPlaces : TacSkinPlaces = spAllPlaces) : boolean; overload; implementation uses UnitStrings, acntUtils, acSkinPreview{$IFDEF TNTUNICODE}{$IFNDEF D2006}, TntWideStrings{$ELSE}, WideStrings{$ENDIF}{$ENDIF}; {$R *.dfm} function SelectSkin(SkinManager : TsSkinManager; SkinPlaces : TacSkinPlaces = spAllPlaces) : boolean; begin Result := False; FormSkinSelect := TFormSkinSelect.Create(Application); FormSkinSelect.SkinTypes := stAllSkins; FormSkinSelect.SkinPlaces := SkinPlaces;//spAllPlaces; FormSkinSelect.sDirectoryEdit1.Text := SkinManager.SkinDirectory; FormSkinSelect.sName := SkinManager.SkinName; FormSkinSelect.SkinManager := SkinManager; if FormSkinSelect.ShowModal = mrOk then begin SkinManager.SkinDirectory := FormSkinSelect.sDirectoryEdit1.Text; SkinManager.SkinName := FormSkinSelect.sListBox1.Items[FormSkinSelect.sListBox1.ItemIndex]; Result := True; end; FreeAndNil(FormSkinSelect); end; function SelectSkin(var SkinName : string; var SkinDir : string; var SkinSaturation: integer; var SkinHUE: integer; SkinTypes : TacSkinTypes = stAllSkins) : boolean; begin Result := False; FormSkinSelect := TFormSkinSelect.Create(Application); FormSkinSelect.SkinTypes := SkinTypes; FormSkinSelect.SkinPlaces := spExternal; FormSkinSelect.sDirectoryEdit1.Text := SkinDir; FormSkinSelect.sName := SkinName; FormSkinSelect.sSkinSaturation := SkinSaturation; FormSkinSelect.sSkinHUE := SkinHUE; FormSkinSelect.SkinManager := nil; if FormSkinSelect.ShowModal = mrOk then begin SkinName := FormSkinSelect.sListBox1.Items[FormSkinSelect.sListBox1.ItemIndex]; SkinDir := FormSkinSelect.sDirectoryEdit1.Text; SkinSaturation := FormSkinSelect.sTrackBar1.Position; SkinHUE := FormSkinSelect.sTrackBar2.Position; Result := True; end; FreeAndNil(FormSkinSelect); end; function SelectSkin(NameList : TStringList; var SkinDir : string; SkinTypes : TacSkinTypes = stAllSkins) : boolean; overload; var i : integer; begin Result := False; if NameList = nil then Exit; FormSkinSelect := TFormSkinSelect.Create(Application); FormSkinSelect.SkinTypes := SkinTypes; FormSkinSelect.SkinPlaces := spExternal; FormSkinSelect.sDirectoryEdit1.Text := SkinDir; if NameList.Count > 0 then FormSkinSelect.sName := NameList[0] else FormSkinSelect.sName := ''; FormSkinSelect.SkinManager := nil; if FormSkinSelect.ShowModal = mrOk then begin NameList.Clear; for I := 0 to FormSkinSelect.sListBox1.Items.Count - 1 do if FormSkinSelect.sListBox1.Selected[I] then NameList.Add(FormSkinSelect.sListBox1.Items[i]); SkinDir := FormSkinSelect.sDirectoryEdit1.Text; Result := True; end; FreeAndNil(FormSkinSelect); end; procedure TFormSkinSelect.sListBox1Click(Sender: TObject); begin if (FormSkinSelect.sListBox1.ItemIndex > -1) and (FormSkinSelect.sListBox1.ItemIndex < FormSkinSelect.sListBox1.Items.Count) then begin FormSkinPreview.PreviewManager.SkinName := FormSkinSelect.sListBox1.Items[FormSkinSelect.sListBox1.ItemIndex]; FormSkinPreview.PreviewManager.Active := True; sBitBtn1.Enabled := True; end else sBitBtn1.Enabled := False; FormSkinPreview.Visible := sBitBtn1.Enabled; end; procedure TFormSkinSelect.sDirectoryEdit1Change(Sender: TObject); var i : integer; begin if Assigned(FormSkinPreview) and Assigned(FormSkinPreview.PreviewManager) then begin FormSkinPreview.PreviewManager.SkinDirectory := sDirectoryEdit1.Text; if SkinManager <> nil then begin FormSkinPreview.PreviewManager.InternalSkins.Clear; for i := 0 to SkinManager.InternalSkins.Count - 1 do with FormSkinPreview.PreviewManager.InternalSkins.Add do Assign(SkinManager.InternalSkins[i]); end; sListBox1.Items.BeginUpdate; sListBox1.Items.Clear; case SkinPlaces of spAllPlaces : begin {$IFDEF TNTUNICODE} FormSkinPreview.PreviewManager.GetSkinNames(TWideStrings(sListBox1.Items), SkinTypes); {$ELSE} FormSkinPreview.PreviewManager.GetSkinNames(sListBox1.Items, SkinTypes); {$ENDIF} end; spExternal : begin {$IFDEF TNTUNICODE} FormSkinPreview.PreviewManager.GetExternalSkinNames(TWideStrings(sListBox1.Items), SkinTypes); {$ELSE} FormSkinPreview.PreviewManager.GetExternalSkinNames(sListBox1.Items, SkinTypes); {$ENDIF} end; spInternal : if FormSkinPreview.PreviewManager.InternalSkins.Count > 0 then for i := 0 to FormSkinPreview.PreviewManager.InternalSkins.Count - 1 do sListBox1.Items.Add(FormSkinPreview.PreviewManager.InternalSkins[i].Name); end; sListBox1.Items.EndUpdate; if not sBitBtn1.Enabled and (sName <> '') then begin i := sListBox1.Items.IndexOf(sName); if i > -1 then sListBox1.ItemIndex := i; end; sBitBtn1.Enabled := sListBox1.ItemIndex > -1; if not sBitBtn1.Enabled then begin FormSkinPreview.Visible := False; FormSkinPreview.PreviewManager.Active := False; end else sListBox1.OnClick(sListBox1); end; end; procedure TFormSkinSelect.FormDestroy(Sender: TObject); begin if FormSkinPreview <> nil then FreeAndNil(FormSkinPreview); end; procedure TFormSkinSelect.FormShow(Sender: TObject); begin Caption := Traduzidos[148]; sPanel1.Caption := Traduzidos[147]; sBitBtn2.Caption := Traduzidos[120]; sDirectoryEdit1.BoundLabel.Caption := Traduzidos[149] + ':'; if FormSkinPreview = nil then begin FormSkinPreview := TFormSkinPreview.Create(Application); FormSkinPreview.Visible := False; FormSkinPreview.Align := alClient; sTrackBar1.Position := sSkinSaturation; sTrackBar2.Position := sSkinHUE; if FormSkinSelect.SkinPlaces = spInternal then sDirectoryEdit1.Visible := False end; sStickyLabel1.Caption := ' ' + Traduzidos[150] + ': ' + IntToStr(sTrackBar1.Position); sStickyLabel2.Caption := ' HUE: ' + IntToStr(sTrackBar2.Position); FormSkinPreview.Parent := sPanel1; sDirectoryEdit1.OnChange(sDirectoryEdit1); end; procedure TFormSkinSelect.sListBox1DblClick(Sender: TObject); begin sBitBtn1.Click end; procedure TFormSkinSelect.sTrackBar1Change(Sender: TObject); begin FormSkinPreview.PreviewManager.BeginUpdate; FormSkinPreview.PreviewManager.Saturation := sTrackBar1.Position; sStickyLabel1.Caption := ' ' + Traduzidos[150] + ': ' + IntToStr(sTrackBar1.Position); FormSkinPreview.PreviewManager.EndUpdate(True, False); end; procedure TFormSkinSelect.sTrackBar2Change(Sender: TObject); begin FormSkinPreview.PreviewManager.BeginUpdate; FormSkinPreview.PreviewManager.HueOffset := sTrackBar2.Position; sStickyLabel2.Caption := ' HUE: ' + IntToStr(sTrackBar2.Position); FormSkinPreview.PreviewManager.EndUpdate(True, False); end; end.
unit OrderedWeightList; // Muniz Binary Tree v1.0 // Created by Banshee // A somewhat ballanced binary tree. It is an ion cannon made to kill an ant, basically. // It codifies an ordered list that allows you to browse it as a linked list and a // binary tree at the same time. You can also browse the whole binary tree starting // from a leaf. // Operations such as Add, Find and Delete happens on O(log(n)) in most of the // situations, using a fixed RAM size. If you set a low size to this structure, // the Add operation may take O(n), as it will try to allocate the new element // in the place of an element that was removed before. // Feel free to use it in your program, as long as I'm credited. interface uses BasicDataTypes; type TCompareValueFunction = function (_Value1, _Value2 : single): boolean of object; TAddValueMethod = procedure (_Value: integer) of object; TDeleteValueMethod = procedure of object; COrderedWeightList = class private Root,First,Last,NumElements,NextID: integer; IsHigher: TCompareValueFunction; // These vectors are what make this structure be expensive. FLeft, FRight, FFather, FPrevious, FNext: aint32; FWeight: afloat; // Comparisons function IsHigherAscendent(_Value1, _Value2: single): boolean; function IsHigherDescendent(_Value1, _Value2: single): boolean; // Gets function GetLeft(_value: integer): integer; function GetRight(_value: integer): integer; function GetFather(_value: integer): integer; function GetWeight(_value: integer): single; function GetNext(_value: integer): integer; function GetPrevious(_value: integer): integer; public // Constructors and Destructors constructor Create; destructor Destroy; override; // Add function Add (_Value : single): integer; procedure Delete(_ID: integer); // Delete procedure Reset; procedure Clear; procedure ClearBuffers; // Sets procedure SetRAMSize(_Value: integer); procedure SetAscendentOrder; procedure SetDecendentOrder; // Gets function GetValue (var _Weight : single): integer; // Misc function GetFirstElement: integer; function GetLastElement: integer; // Data should be browsable by public. property Left[_Value: integer]: integer read GetLeft; property Right[_Value: integer]: integer read GetRight; property Father[_Value: integer]: integer read GetFather; property Weight[_Value: integer]: single read GetWeight; property Next[_Value: integer]: integer read GetNext; property Previous[_Value: integer]: integer read GetPrevious; end; implementation constructor COrderedWeightList.Create; begin Clear; SetAscendentOrder; end; destructor COrderedWeightList.Destroy; begin Clear; inherited Destroy; end; procedure COrderedWeightList.Reset; begin Root := -1; First := -1; Last := -1; NumElements := 0; NextID := 0; end; // Add function COrderedWeightList.Add (_Value : single): integer; var i,Daddy,Grandpa,GrandGrandPa: integer; goLeft: boolean; begin // Find out next writable element. Result := -1; i := 0; // Find out a potential destination for this new element. if NextID <= High(FLeft) then begin // Quickly assign a destination. Result := NextID; end else begin // Try to find as destination a previously deleted element. while (i <= High(FLeft)) and (Result = -1) do begin if (FLeft[i] = -1) and (FRight[i] = -1) and (FFather[i] = -1) and (FWeight[i] = -1) then begin Result := i; end; inc(i); end; end; // Can we add this element? if Result <> -1 then begin // Let's add it then. inc(NumElements); FLeft[Result] := -1; FRight[Result] := -1; FWeight[Result] := _Value; i := Root; // Is it the first element? if i <> -1 then begin // This is not the first element. Let's search its position there. while i <> -1 do begin Daddy := i; if isHigher(FWeight[i],_Value) then begin i := FLeft[i]; goLeft := true; end else begin i := FRight[i]; goLeft := false; end; end; // Now we have an idea of the location of this element in the binary tree. // First, let's try to make it look more ballanced. if Daddy <> Root then begin Grandpa := FFather[Daddy]; if Grandpa <> -1 then begin GrandGrandPa := FFather[GrandPa]; if goLeft then begin if FRight[Daddy] = -1 then begin if FRight[Grandpa] = -1 then begin if GrandGrandPa <> -1 then begin if FLeft[GrandGrandPa] = GrandPa then FLeft[GrandGrandPa] := Daddy else FRight[GrandGrandPa] := Daddy; end else begin Root := Daddy end; FRight[Daddy] := GrandPa; FLeft[Daddy] := Result; if FPrevious[Daddy] <> -1 then FNext[FPrevious[Daddy]] := Result; FNext[Result] := Daddy; FPrevious[Result] := FPrevious[Daddy]; FPrevious[Daddy] := Result; FLeft[GrandPa] := -1; FFather[Daddy] := GrandGrandPa; FFather[GrandPa] := Daddy; FFather[Result] := Daddy; end else if FLeft[Grandpa] = -1 then begin if GrandGrandPa <> -1 then begin if FLeft[GrandGrandPa] = GrandPa then FLeft[GrandGrandPa] := Result else FRight[GrandGrandPa] := Result; end else begin Root := Result; end; FRight[Daddy] := -1; FLeft[Daddy] := -1; FLeft[GrandPa] := -1; FRight[GrandPa] := -1; FLeft[Result] := GrandPa; FRight[Result] := Daddy; if FPrevious[Daddy] <> -1 then FNext[FPrevious[Daddy]] := Result; FNext[Result] := Daddy; FPrevious[Result] := FPrevious[Daddy]; FPrevious[Daddy] := Result; FFather[Result] := GrandGrandPa; FFather[Daddy] := Result; FFather[GrandPa] := Result; end else begin FLeft[Daddy] := Result; FFather[Result] := Daddy; if FPrevious[Daddy] <> -1 then FNext[FPrevious[Daddy]] := Result; FNext[Result] := Daddy; FPrevious[Result] := FPrevious[Daddy]; FPrevious[Daddy] := Result; end; end else begin FLeft[Daddy] := Result; FFather[Result] := Daddy; if FPrevious[Daddy] <> -1 then FNext[FPrevious[Daddy]] := Result; FNext[Result] := Daddy; FPrevious[Result] := FPrevious[Daddy]; FPrevious[Daddy] := Result; end; end else // goRight begin if FLeft[Daddy] = -1 then begin if FRight[Grandpa] = -1 then begin if GrandGrandPa <> -1 then begin if FLeft[GrandGrandPa] = GrandPa then FLeft[GrandGrandPa] := Result else FRight[GrandGrandPa] := Result; end else begin Root := Result; end; FRight[Daddy] := -1; FLeft[Daddy] := -1; FLeft[GrandPa] := -1; FRight[GrandPa] := -1; FLeft[Result] := Daddy; FRight[Result] := GrandPa; if FPrevious[GrandPa] <> -1 then FNext[FPrevious[GrandPa]] := Result; FNext[Result] := GrandPa; FPrevious[Result] := FPrevious[GrandPa]; FPrevious[GrandPa] := Result; FFather[Result] := GrandGrandPa; FFather[GrandPa] := Result; FFather[Daddy] := Result; end else if FLeft[Grandpa] = -1 then begin if GrandGrandPa <> -1 then begin if FLeft[GrandGrandPa] = GrandPa then FLeft[GrandGrandPa] := Daddy else FRight[GrandGrandPa] := Daddy; end else begin Root := Daddy; end; FRight[Daddy] := Result; if FNext[Daddy] <> -1 then FPrevious[FNext[Daddy]] := Result; FPrevious[Result] := Daddy; FNext[Result] := FNext[Daddy]; FNext[Daddy] := Result; FLeft[Daddy] := GrandPa; FRight[GrandPa] := -1; FFather[Daddy] := GrandGrandPa; FFather[Result] := Daddy; FFather[GrandPa] := Daddy; end else begin FRight[Daddy] := Result; FFather[Result] := Daddy; if FNext[Daddy] <> -1 then FPrevious[FNext[Daddy]] := Result; FPrevious[Result] := Daddy; FNext[Result] := FNext[Daddy]; FNext[Daddy] := Result; end; end else begin FRight[Daddy] := Result; FFather[Result] := Daddy; if FNext[Daddy] <> -1 then FPrevious[FNext[Daddy]] := Result; FPrevious[Result] := Daddy; FNext[Result] := FNext[Daddy]; FNext[Daddy] := Result; end; end; end else begin if goLeft then begin FLeft[Daddy] := Result; FNext[Result] := Daddy; if FPrevious[Daddy] <> -1 then FNext[FPrevious[Daddy]] := Result; FPrevious[Result] := FPrevious[Daddy]; FPrevious[Daddy] := Result; end else begin FRight[Daddy] := Result; FPrevious[Result] := Daddy; if FNext[Daddy] <> -1 then FPrevious[FNext[Daddy]] := Result; FNext[Result] := FNext[Daddy]; FNext[Daddy] := Result; end; FFather[Result] := Daddy; end; end else begin if goLeft then begin FLeft[Daddy] := Result; FNext[Result] := Daddy; if FPrevious[Daddy] <> -1 then FNext[FPrevious[Daddy]] := Result; FPrevious[Result] := FPrevious[Daddy]; FPrevious[Daddy] := Result; end else begin FRight[Daddy] := Result; FPrevious[Result] := Daddy; if FNext[Daddy] <> -1 then FPrevious[FNext[Daddy]] := Result; FNext[Result] := FNext[Daddy]; FNext[Daddy] := Result; end; FFather[Result] := Daddy; end; if goLeft then begin if IsHigher(FWeight[First],FWeight[Result]) then begin First := Result; end; end else begin if IsHigher(FWeight[Result], FWeight[Last]) then begin Last := Result; end; end; end else // this is the first element. begin Root := Result; First := Result; Last := Result; FFather[Result] := -1; FNext[Result] := -1; FPrevious[Result] := -1; end; inc(NextID); end; // else, the element cannot be added and it will return -1. end; // Delete procedure COrderedWeightList.Delete(_ID : integer); var Brother,Daddy,NewDaddy,GrandPa,GrandGrandPa : integer; IsLeftSon: boolean; begin if (_ID >= 0) and (_ID <= High(FLeft)) then begin // If it is a leaf, it's just a quick deletion. Daddy := FFather[_ID]; if (FLeft[_ID] = -1) and (FRight[_ID] = -1) then begin if Daddy <> -1 then begin // disconnect it from the binary tree. if FLeft[Daddy] = _ID then begin FLeft[Daddy] := -1; IsLeftSon := true; Brother := FRight[Daddy]; end else begin FRight[Daddy] := -1; IsLeftSon := false; Brother := FLeft[Daddy]; end; // Reballance the binary tree if possible. if Brother <> -1 then begin GrandPa := FFather[Daddy]; if GrandPa <> -1 then begin GrandGrandPa := FFather[GrandPa]; if FLeft[GrandPa] <> -1 then begin if FRight[GrandPa] = -1 then begin if IsLeftSon then begin if GrandGrandPa <> -1 then begin if FLeft[GrandGrandPa] = GrandPa then begin FLeft[GrandGrandPa] := Brother; end else begin FRight[GrandGrandPa] := Brother; end; FFather[Brother] := GrandGrandPa; end else begin Root := Brother; FFather[Brother] := -1; end; FRight[Daddy] := FLeft[Brother]; FLeft[GrandPa] := FRight[Brother]; FLeft[Brother] := Daddy; FRight[Brother] := GrandPa; FFather[Daddy] := Brother; FFather[GrandPa] := Brother; end else begin if GrandGrandPa <> -1 then begin if FLeft[GrandGrandPa] = GrandPa then begin FLeft[GrandGrandPa] := Daddy; end else begin FRight[GrandGrandPa] := Daddy; end; FFather[Daddy] := GrandGrandPa; end else begin Root := Daddy; FFather[Daddy] := -1; end; FRight[Daddy] := GrandPa; FFather[GrandPa] := Daddy; FLeft[GrandPa] := -1; FRight[GrandPa] := -1; end; end; end else if FRight[GrandPa] <> -1 then begin if IsLeftSon then begin if GrandGrandPa <> -1 then begin if FLeft[GrandGrandPa] = GrandPa then begin FLeft[GrandGrandPa] := Daddy; end else begin FRight[GrandGrandPa] := Daddy; end; FFather[Daddy] := GrandGrandPa; end else begin Root := Daddy; FFather[Daddy] := -1; end; FLeft[Daddy] := GrandPa; FFather[GrandPa] := Daddy; FLeft[GrandPa] := -1; FRight[GrandPa] := -1; end else begin if GrandGrandPa <> -1 then begin if FLeft[GrandGrandPa] = GrandPa then begin FLeft[GrandGrandPa] := Brother; end else begin FRight[GrandGrandPa] := Brother; end; FFather[Brother] := GrandGrandPa; end else begin Root := Brother; FFather[Brother] := -1; end; FLeft[Daddy] := FRight[Brother]; FRight[GrandPa] := FLeft[Brother]; FLeft[Brother] := GrandPa; FRight[Brother] := Daddy; FFather[GrandPa] := Brother; FFather[Daddy] := Brother; if Last = _ID then Last := Daddy; end; end; end; end; end else // this was the only element of the binary tree. begin Root := -1; First := -1; Last := -1; end; end else // this is not a leaf. begin if (FLeft[_ID] <> -1) and (FRight[_ID] = -1) then begin if Daddy <> -1 then begin if FLeft[Daddy] = _ID then begin FLeft[Daddy] := FLeft[_ID]; end else begin FRight[Daddy] := FLeft[_ID]; end; FFather[FLeft[_ID]] := Daddy; end else begin Root := FLeft[_ID]; FFather[Root] := -1; end; end else if (FRight[_ID] <> -1) and (FLeft[_ID] = -1) then begin if Daddy <> -1 then begin if FLeft[Daddy] = _ID then begin FLeft[Daddy] := FRight[_ID]; end else begin FRight[Daddy] := FRight[_ID]; end; FFather[FRight[_ID]] := Daddy; end else begin Root := FRight[_ID]; FFather[Root] := -1; end; end else begin if Daddy <> -1 then begin NewDaddy := FNext[_ID]; if FLeft[Daddy] = _ID then begin FLeft[Daddy] := NewDaddy; end else begin FRight[Daddy] := NewDaddy; end; if FLeft[FFather[NewDaddy]] = NewDaddy then begin FLeft[FFather[NewDaddy]] := -1; end else begin FRight[FFather[NewDaddy]] := -1; end; FFather[NewDaddy] := Daddy; if FLeft[_ID] <> NewDaddy then begin FLeft[NewDaddy] := FLeft[_ID]; FFather[FLeft[_ID]] := NewDaddy; end else begin FLeft[NewDaddy] := -1; end; if FRight[_ID] <> NewDaddy then begin FRight[NewDaddy] := FRight[_ID]; FFather[FRight[_ID]] := NewDaddy; end else begin FRight[NewDaddy] := -1; end; end else begin Root := FNext[_ID]; if FLeft[FFather[Root]] = Root then begin FLeft[FFather[Root]] := -1; end else begin FRight[FFather[Root]] := -1; end; FFather[Root] := -1; if FLeft[_ID] <> Root then begin FLeft[Root] := FLeft[_ID]; FFather[FLeft[_ID]] := Root; end else begin FLeft[Root] := -1; end; if FRight[_ID] <> Root then begin FRight[Root] := FRight[_ID]; FFather[FRight[_ID]] := Root; end else begin FRight[Root] := -1; end; end; end; end; if First = _ID then begin First := FNext[_ID]; end; if Last = _ID then begin Last := FPrevious[_ID]; end; FLeft[_ID] := -1; FRight[_ID] := -1; FFather[_ID] := -1; FWeight[_ID] := -1; if FPrevious[_ID] <> -1 then FNext[FPrevious[_ID]] := FNext[_ID]; if FNext[_ID] <> -1 then FPrevious[FNext[_ID]] := FPrevious[_ID]; FPrevious[_ID] := -1; FNext[_ID] := -1; dec(NumElements); end; end; procedure COrderedWeightList.Clear; begin SetRAMSize(0); Reset; end; procedure COrderedWeightList.ClearBuffers; var i: integer; begin for i := Low(FLeft) to High(FLeft) do begin FLeft[i] := -1; FRight[i] := -1; FFather[i] := -1; FNext[i] := -1; FPrevious[i] := -1; end; end; // Sets procedure COrderedWeightList.SetRAMSize(_Value: integer); begin if (_Value >= 0) then begin SetLength(FLeft, _Value); SetLength(FRight, _Value); SetLength(FFather, _Value); SetLength(FWeight, _Value); SetLength(FNext, _Value); SetLength(FPrevious, _Value); ClearBuffers; end; end; procedure COrderedWeightList.SetAscendentOrder; begin IsHigher := IsHigherAscendent; end; procedure COrderedWeightList.SetDecendentOrder; begin IsHigher := IsHigherDescendent; end; // Gets function COrderedWeightList.GetValue (var _Weight : single): integer; begin Result := Root; while Result <> -1 do begin if FWeight[Result] = _Weight then begin exit; end; if isHigher(FWeight[Result],_Weight) then begin Result := FLeft[Result]; end else begin Result := FRight[Result]; end; end; end; function COrderedWeightList.GetLeft(_value: integer): integer; begin Result := FLeft[_Value]; end; function COrderedWeightList.GetRight(_value: integer): integer; begin Result := FRight[_Value]; end; function COrderedWeightList.GetFather(_value: integer): integer; begin Result := FFather[_Value]; end; function COrderedWeightList.GetWeight(_value: integer): single; begin Result := FWeight[_Value]; end; function COrderedWeightList.GetNext(_value: integer): integer; begin Result := FNext[_Value]; end; function COrderedWeightList.GetPrevious(_value: integer): integer; begin Result := FPrevious[_Value]; end; // Comparisons function COrderedWeightList.IsHigherAscendent(_value1, _value2: single): boolean; begin Result := _Value1 >= _Value2; end; function COrderedWeightList.IsHigherDescendent(_value1, _value2: single): boolean; begin Result := _Value2 >= _Value1; end; // Misc function COrderedWeightList.GetFirstElement: integer; begin Result := First; end; function COrderedWeightList.GetLastElement: integer; begin Result := Last; end; end.
unit DBManagers; interface uses stmObj, stmPG, stmDataBase2, Ncdef2, DBRecord1, DBQueryBuilder, DBModels, DBObjects, DBQuerySets, Classes, SysUtils, ZDbcIntfs; type TDBManager = class(typeUO) private _model:TDBModel; _qset:TDBQuerySet; _qbuilder:TQueryBuilder; public constructor Create(model:TDBModel); destructor Destroy;override; procedure initManager(model:TDBModel); function get(where:String):TDBObject; function all(order:String):TDBQuerySet; function filter(where,order:String):TDBQuerySet; function search(join,where,order:String):TDBQuerySet; function insert(var item:TDBObject;commit:boolean=True;break:boolean=False):TDBObject;overload; property model:TDBModel read _model; class function stmClassName:string;override; procedure processMessage(id:integer;source:typeUO;p:pointer);override; end; procedure proTDBManager_Create(var model:TDBModel;var pu:typeUO);pascal; procedure proTDBManager_get(where:String;var dbobject:TDBObject;var pu:typeUO);pascal; procedure proTDBManager_all(order:String;var qset:TDBQuerySet;var pu:typeUO);pascal; procedure proTDBManager_filter(where,order:String;var qset:TDBQuerySet;var pu:typeUO);pascal; procedure proTDBManager_search(join,where,order:String;var qset:TDBQuerySet;var pu:typeUO);pascal; procedure proTDBManager_insert(var dbobject:TDBObject;commit:Boolean;var pu:typeUO);pascal; implementation uses DBCache; constructor TDBManager.Create(model:TDBModel); begin inherited Create; notPublished := True; initManager(model); end; destructor TDBManager.Destroy; begin _qbuilder.Free; _qset.Free; derefObjet(typeUO(_model)); inherited Destroy; end; procedure TDBManager.processMessage(id:integer;source:typeUO;p:pointer); begin inherited processMessage(id,source,p); case id of UOmsg_destroy : begin _model := nil; derefObjet(source); end; end; end; procedure TDBManager.initManager(model:TDBModel); begin derefObjet(typeUO(_model)); _model := model; refObjet(typeUO(_model)); _qbuilder := TQueryBuilder.Create(_model); _qset := TDBQuerySet.Create(model); end; function TDBManager.get(where:String):TDBObject; var statement:IZStatement; resultset:IZResultSet; instance:TDBObject; query:String; begin if _model = nil then raise Exception.Create('model undefined'); statement := _model.connection.CreateStatement; _qbuilder.resetParameters; _qbuilder.where := where; query := _qbuilder.select; resultset := statement.ExecuteQuery(query); if resultset.First then begin {instance := getObject(_model); instance.finalizeObject(_model,resultset);} instance := TDBObject.Create(_model,resultset); instance.created := False; Result := instance; if resultset.Next then raise Exception.Create('too many objects for the get function, please find a where clause that ensure the uniqueness of the object'); end else raise Exception.Create('The requested ' + _model.application_table + ' object does not exist.'); end; function TDBManager.all(order:String):TDBQuerySet; var query:String; qset:TDBQuerySet; begin if _model = nil then raise Exception.Create('model undefined'); _qbuilder.resetParameters; _qbuilder.order := order; query := _qbuilder.select; {_qset.finalizeQuerySet(query);} qset := TDBQuerySet.Create(query,_model); Result := qset; end; function TDBManager.filter(where,order:String):TDBQuerySet; var query:String; qset:TDBQuerySet; begin if _model = nil then raise Exception.Create('model undefined'); _qbuilder.resetParameters; _qbuilder.order := order; _qbuilder.where := where; query := _qbuilder.select; {_qset.clear; _qset.finalizeQuerySet(query);} qset := TDBQuerySet.Create(query,_model); Result := qset; end; function TDBManager.search(join,where,order:String):TDBQuerySet; var query:String; qset:TDBQuerySet; begin if _model = nil then raise Exception.Create('model undefined'); _qbuilder.resetParameters; _qbuilder.join := join; _qbuilder.where := where; _qbuilder.order := order; query := _qbuilder.select; {_qset.finalizeQuerySet(query);} qset := TDBQuerySet.Create(query,_model); Result := qset; end; function TDBManager.insert(var item:TDBObject;commit:boolean=True;break:boolean=False):TDBObject;{tested} var statement:IZStatement; resultset:IZResultSet; tmp_object,tmp_pot,tmp_io,instance,anType,analysis,io,potential,subpotential,input,output:TDBObject; ios:TDBQuerySet; query,coding,cls,condition,pinname,pintype:String; builder:TQueryBuilder; {anTypeModel,ioModel,anModel,potModel,subpotModel,inModel,outModel,boolModel,intModel,floatModel,strModel}{:TDBModel;} {anTypeManager,ioManager,}{anManager,}{,potManager,subpotManager,inManager,outManager,boolManager,intManager,floatManager,strManager,}delegateManager:TDBManager; pins:TDBQuerySet; i,id,index:Integer; test:boolean; begin if _model = nil then raise Exception.Create('model undefined (manager.insert)'); if (_model.application_table <> 'analysis_analysis') or (break = True) then begin statement := _model.connection.CreateStatement; builder := TQueryBuilder.Create(_model,True); query := builder.insert(item); resultset := statement.ExecuteQuery(query); resultset.First; instance := TDBObject.Create(_model,resultset); if commit then begin instance.created := True; instance.existing := True; _model.connection.commit; end; Result := instance; builder.Free; end else begin if item.fields.IndexOf('component')<0 then raise Exception.Create('please specify component field'); if item.fields.IndexOf('id')<0 then raise Exception.Create('please specify id field'); {creation instance de analysis_analysis} {anModel.initModel('analysis_analysis');} analysis := TDBObject.Create(anModel); analysis.AddField('id',gvString); analysis.VString[0] := item.getValue('id').VString; if item.fields.IndexOf('comments')>=0 then begin analysis.AddField('comments',gvString); analysis.VString[1] := item.getValue('comments').VString; analysis.AddField('component',gvString); analysis.VString[2] := item.getValue('component').VString; end else begin analysis.AddField('component',gvString); analysis.VString[1] := item.getValue('component').VString; end; tmp_object := anManager.insert(analysis,False,True); tmp_object.Free; {init ios and io} {ioModel.initModel('analysis_pin',_model.connection);} {io := TDBObject(TDBRecord.Create);} pins := ioManager.filter('component = ''' + item.value['component'].VString + '''','id'); {init potential and subpotential} potential := TDBObject(TDBRecord.Create); {potModel.initModel('analysis_potential',_model.connection);} subpotential := TDBObject(TDBRecord.Create); { subpotModel_str.initModel('analysis_potential_string',_model.connection); subpotModel_int.initModel('analysis_potential_integer',_model.connection); subpotModel_bool.initModel('analysis_potential_boolean',_model.connection); subpotModel_float.initModel('analysis_potential_float',_model.connection); } {init inputs} {inputModel.initModel('analysis_analysis_inputs',_model.connection);} input:= TDBObject(TDBRecord.Create); input.AddField('analysis_id',gvString); input.AddField('potential_id',gvInteger); {init outputs} {outputModel.initModel('analysis_analysis_outputs',_model.connection);} output:= TDBObject(TDBRecord.Create); output.AddField('analysis_id',gvString); output.AddField('potential_id',gvInteger); for i:=1 to pins.count do begin pinname := pins.objects[i-1].value['name'].VString; index := item.fields.IndexOf(pinname); if index >= 0 then begin {find the right input and insert its relative potential, if it is not found the get function raise an exception} condition := 'name = ''' + item.fields[index] + ''' AND component = ''' + analysis.value['component'].Vstring + ''''; io := ioManager.get(condition); id := io.value['id'].VInteger; potential.clearFields; potential.AddField('pin',gvInteger); potential.VInteger[0] := id; tmp_pot := potManager.insert(potential,False); id := tmp_pot.value['id'].VInteger; {detect the potential subclass and insert a new subpotential from the codingtype} subpotential.AddField('potential_ptr_id',gvInteger); subpotential.VInteger[0] := id; coding := io.value['codingtype'].VString; if coding = 'bool' then begin cls:='boolean'; subpotential.AddField('value',gvBoolean); subpotential.VBoolean[1] := item.value[item.fields[index]].VBoolean; delegateManager := subpotManager_bool; end; if coding = 'int' then begin cls:='integer'; subpotential.AddField('value',gvInteger); subpotential.VInteger[1] := item.value[item.fields[index]].VInteger; delegateManager := subpotManager_int; end; if coding = 'float' then begin cls:='float'; subpotential.AddField('value',gvFloat); subpotential.VFloat[1] := item.value[item.fields[index]].VFloat; delegateManager := subpotManager_float; end; if (coding = 'str') or (coding = 'file') then begin cls:='string'; subpotential.AddField('value',gvString); subpotential.VString[1] := item.value[item.fields[index]].VString; delegateManager := subpotManager_str; end; tmp_object := delegateManager.insert(subpotential,False); tmp_object.Free; {add the potential to the list of inputs} pintype := io.value['pintype'].VString; if (pintype = 'Input') or (pintype = 'Parameter') then begin input.VString[0] := analysis.value['id'].VString; input.VInteger[1] := tmp_pot.value['id'].VInteger; tmp_object := inputManager.insert(input,False); end; {add the potential to the list of outputs} if pintype = 'Output' then begin output.VString[0] := analysis.value['id'].VString; output.VInteger[1] := tmp_pot.value['id'].VInteger; tmp_object := outputManager.insert(output,False); end; tmp_object.Free; io.Free; tmp_pot.Free; end; end; {commit all new created data}; if commit then begin _model.connection.commit; analysis.created := True; analysis.existing := True; end; input.Free; output.Free; subpotential.Free; potential.Free; pins.Free; Result := analysis; end; end; class function TDBManager.stmClassName:string; begin result:='DBManager'; end; procedure proTDBManager_Create(var model:TDBModel;var pu:typeUO);pascal; begin createPgObject('',pu,TDBManager); TDBManager(pu).initManager(model); end; procedure proTDBManager_get(where:String;var dbobject:TDBObject;var pu:typeUO);pascal; var statement:IZStatement; resultset:IZResultSet; query:String; begin if TDBManager(pu)._model = nil then raise Exception.Create('model undefined'); statement := TDBManager(pu)._model.connection.CreateStatement; TDBManager(pu)._qbuilder.resetParameters; TDBManager(pu)._qbuilder.where := where; query := TDBManager(pu)._qbuilder.select; resultset := statement.ExecuteQuery(query); if resultset.First then begin if not assigned(dbobject) then createPgObject('',typeUO(dbobject),TDBObject); dbobject.initObject; dbobject.finalizeObject(TDBManager(pu)._model,resultset); dbobject.created := False; if resultset.Next then raise Exception.Create('too many objects for the get function, please find a where clause that ensure the uniqueness of the object'); end else raise Exception.Create('The requested ' + TDBManager(pu)._model.application_table + ' object does not exist.'); end; { var tmp_object:TDBObject; begin verifierObjet(pu); if not assigned(dbobject) then dbobject := TDBObject.Create; tmp_object := TDBManager(pu).get(where); dbobject.assign(tmp_object); dbobject.Free; end; } procedure proTDBManager_all(order:String;var qset:TDBQuerySet;var pu:typeUO);pascal; var query:String; begin if TDBManager(pu)._model = nil then raise Exception.Create('model undefined'); verifierObjet(pu); if not assigned(qset) then createPgObject('',typeUO(qset),TDBQuerySet); qset.initQuerySet(TDBManager(pu)._model); TDBManager(pu)._qbuilder.resetParameters; TDBManager(pu)._qbuilder.order := order; query := TDBManager(pu)._qbuilder.select; qset.finalizeQuerySet(query); end; {var tmp_qset:TDBQuerySet; st:String; i:Integer; begin verifierObjet(pu); if not assigned(qset) then createPgObject('',typeUO(qset),TDBQuerySet); qset.initQuerySet; tmp_qset := TDBManager(pu).all(order); qset.assign(tmp_qset); tmp_qset.Free; i := qset.count; st := TDBObject(qset[0]).value['id'].VString; qset.count; end;} procedure proTDBManager_filter(where,order:String;var qset:TDBQuerySet;var pu:typeUO);pascal; var query:String; begin if TDBManager(pu)._model = nil then raise Exception.Create('model undefined'); verifierObjet(pu); if not assigned(qset) then createPgObject('',typeUO(qset),TDBQuerySet); qset.initQuerySet(TDBManager(pu)._model); TDBManager(pu)._qbuilder.resetParameters; TDBManager(pu)._qbuilder.order := order; TDBManager(pu)._qbuilder.where := where; query := TDBManager(pu)._qbuilder.select; qset.finalizeQuerySet(query); end; { var tmp_qset:TDBQuerySet; begin verifierObjet(pu); if not assigned(qset) then qset := TDBQuerySet.Create; tmp_qset := TDBManager(pu).filter(where,order); qset.assign(tmp_qset); tmp_qset.Free; end; } procedure proTDBManager_search(join,where,order:String;var qset:TDBQuerySet;var pu:typeUO);pascal; var query:String; begin if TDBManager(pu)._model = nil then raise Exception.Create('model undefined'); verifierObjet(pu); if not assigned(qset) then createPgObject('',typeUO(qset),TDBQuerySet); qset.initQuerySet(TDBManager(pu)._model); TDBManager(pu)._qbuilder.resetParameters; TDBManager(pu)._qbuilder.join := join; TDBManager(pu)._qbuilder.where := where; TDBManager(pu)._qbuilder.order := order; query := TDBManager(pu)._qbuilder.select; qset.finalizeQuerySet(query); end; { var tmp_qset:TDBQuerySet; model:TDBModel; begin verifierObjet(pu); if not assigned(qset) then qset := TDBQuerySet.Create; model := TDBManager(pu)._model; tmp_qset := TDBManager(pu).search(join,where,order); qset.assign(tmp_qset); tmp_qset.Free; end; } procedure proTDBManager_insert(var dbobject:TDBObject;commit:Boolean;var pu:typeUO);pascal; var tmp_object:TDBObject; begin if TDBManager(pu)._model = nil then raise Exception.Create('model undefined'); verifierObjet(pu); if not assigned(dbobject) then createPgObject('',typeUO(dbobject),TDBObject); {dbobject := TDBObject.Create;} tmp_object := TDBManager(pu).insert(dbobject,commit); dbobject.assign(tmp_object); tmp_object.Free; end; initialization registerObject(TDBManager,sys); end.
unit uRepConnectionFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, siComp, ExtCtrls, StdCtrls, IniFiles; const CON_DCOM = 0; CON_SOCKET = 1; CON_WEB = 2; type TRepConnectionFrm = class(TForm) Panel1: TPanel; BNext: TButton; BClose: TButton; bvBottom: TBevel; Label1: TLabel; cbxConnectionType: TComboBox; lbHost: TLabel; edtHost: TEdit; lbPort: TLabel; edtPort: TEdit; Label2: TLabel; edtClientID: TEdit; procedure cbxConnectionTypeChange(Sender: TObject); procedure BNextClick(Sender: TObject); procedure BCloseClick(Sender: TObject); private procedure GetConfigFile; procedure SetConfigFile; procedure RefreshConType; public procedure Start; end; implementation uses uDMGlobalNTier, uDMReport; {$R *.dfm} { TFrmServerConnection } procedure TRepConnectionFrm.Start; begin GetConfigFile; ShowModal; end; procedure TRepConnectionFrm.cbxConnectionTypeChange(Sender: TObject); begin inherited; RefreshConType; end; procedure TRepConnectionFrm.GetConfigFile; var sConType : String; begin sConType := DMReport.GetAppProperty('Connection', 'Type'); if sConType = CON_TYPE_SOCKET then cbxConnectionType.ItemIndex := CON_SOCKET else if sConType = CON_TYPE_DCOM then cbxConnectionType.ItemIndex := CON_DCOM else if sConType = CON_TYPE_WEB then cbxConnectionType.ItemIndex := CON_WEB; RefreshConType; edtClientID.Text := DMReport.GetAppProperty('Connection', 'ClientID'); edtHost.Text := DMReport.GetAppProperty('Connection', 'Host'); edtPort.Text := DMReport.GetAppProperty('Connection', 'Port'); end; procedure TRepConnectionFrm.SetConfigFile; begin with DMReport do begin case cbxConnectionType.ItemIndex of CON_SOCKET: SetAppProperty('Connection', 'Type', CON_TYPE_SOCKET); CON_DCOM : SetAppProperty('Connection', 'Type', CON_TYPE_DCOM); CON_WEB : SetAppProperty('Connection', 'Type', CON_TYPE_WEB); end; SetAppProperty('Connection', 'ClientID', edtClientID.Text); SetAppProperty('Connection', 'Host', edtHost.Text); SetAppProperty('Connection', 'Port', edtPort.Text); SetConnectionProperties; end; end; procedure TRepConnectionFrm.BNextClick(Sender: TObject); begin SetConfigFile; Close; end; procedure TRepConnectionFrm.BCloseClick(Sender: TObject); begin Close; end; procedure TRepConnectionFrm.RefreshConType; var fPort: Boolean; begin inherited; case cbxConnectionType.ItemIndex of CON_DCOM : fPort := False; CON_SOCKET: fPort := True; CON_WEB : fPort := False; else fPort := False; end; lbPort.Visible := fPort; edtPort.Visible := fPort; end; end.
unit Invoice.Model.Order; interface uses DB, Classes, SysUtils, Generics.Collections, /// orm Invoice.Model.Customer, ormbr.types.blob, ormbr.types.lazy, ormbr.types.mapping, ormbr.types.nullable, ormbr.mapping.classes, ormbr.mapping.register, ormbr.mapping.attributes; type [Entity] [Table('Order', '')] [PrimaryKey('idOrder', NotInc, NoSort, False, 'Chave primária')] TOrder = class private { Private declarations } FidOrder: Integer; FdataOrder: TDateTime; FidCustomer: Integer; FCustomer_0: TCustomer; public { Public declarations } constructor Create; destructor Destroy; override; [Restrictions([NotNull])] [Column('idOrder', ftInteger)] [Dictionary('idOrder', 'Mensagem de validação', '', '', '', taCenter)] property idOrder: Integer Index 0 read FidOrder write FidOrder; [Restrictions([NotNull])] [Column('dataOrder', ftDateTime)] [Dictionary('dataOrder', 'Mensagem de validação', 'Now', '', '!##/##/####;1;_', taCenter)] property dataOrder: TDateTime Index 1 read FdataOrder write FdataOrder; [Restrictions([NotNull])] [Column('idCustomer', ftInteger)] [ForeignKey('Customer', 'idCustomer', SetNull, SetNull)] [Dictionary('idCustomer', 'Mensagem de validação', '', '', '', taCenter)] property idCustomer: Integer Index 2 read FidCustomer write FidCustomer; [Association(OneToOne,'idCustomer','idCustomer')] property Customer: TCustomer read FCustomer_0 write FCustomer_0; end; implementation constructor TOrder.Create; begin FCustomer_0 := TCustomer.Create; end; destructor TOrder.Destroy; begin FCustomer_0.Free; inherited; end; initialization TRegisterClass.RegisterEntity(TOrder) end.
unit UpOrderAddItem; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, FIBDataSet, pFIBDataSet, ActnList, uMemoControl, StdCtrls, Buttons, uFormControl, uInvisControl, uCharControl, uIntControl, qFTools, uFControl, uLabeledFControl, uSpravControl, ExtCtrls, AccMgmt; type TUpOrderAddItemForm = class(TForm) TopPanel: TPanel; ItemType: TqFSpravControl; qFIC_NumItem: TqFIntControl; qFIC_NumSubItem: TqFIntControl; ActionList: TActionList; Cancel: TAction; Ok: TAction; pFIBDS_GetNums: TpFIBDataSet; OkButton: TBitBtn; CancelButton: TBitBtn; BplName: TqFCharControl; procedure OkButtonClick(Sender: TObject); procedure OkExecute(Sender: TObject); procedure CancelExecute(Sender: TObject); procedure ItemTypeOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); private public Id_Order: Int64; constructor Create(aOwner: TComponent; aFMode: TFormMode; aId_Order: Int64); reintroduce; end; implementation {$R *.dfm} uses RxMemDS, uUnivSprav, uCommonSP, ClipBrd, UpOrderList, HSDialogs, UpKernelUnit; constructor TUpOrderAddItemForm.Create(aOwner: TComponent; aFMode: TFormMode; aId_Order: Int64); begin inherited Create(aOwner); Id_Order := aId_Order; //Загрузка из реестра последнего выбранного типа приказа AutoLoadFromRegistry(Self, nil); //Получение информации об номере пункта/подпункта по умолчанию Caption := 'Створення нового пункту'; pFIBDS_GetNums.Database := TUpOrderListForm(owner.owner).WorkDatabase; pFIBDS_GetNums.Transaction := TUpOrderListForm(owner.owner).WriteTransaction; TUpOrderListForm(owner.owner).WriteTransaction.StartTransaction; pFIBDS_GetNums.ParamByName('id_order').AsInt64 := aId_Order; pFIBDS_GetNums.Open; qFIC_NumItem.Value := pFIBDS_GetNums['num_item']; qFIC_NumSubItem.Value := pFIBDS_GetNums['num_sub_item']; pFIBDS_GetNums.Close; TUpOrderListForm(owner.owner).WriteTransaction.Commit; end; procedure TUpOrderAddItemForm.OkButtonClick(Sender: TObject); begin AutoSaveIntoRegistry(Self, nil); if VarIsNull(ItemType.Value) then begin HSDialogs.HSShowWarning('Треба вибрати тип пункту!', ItemType, ItemType.Interval, 0); exit; end; if VarIsNull(qFIC_NumItem.Value) then begin HSDialogs.HSShowWarning('Треба ввести номер пункту!', qFIC_NumItem, qFIC_NumItem.Interval, 0); qFIC_NumItem.SetFocus; exit; end; if VarIsNull(qFIC_NumSubItem.Value) then begin HSDialogs.HSShowWarning('Треба ввести номер підпункту!', qFIC_NumSubItem, qFIC_NumSubItem.Interval, 0); qFIC_NumSubItem.SetFocus; exit; end; ModalResult := mrOk; end; procedure TUpOrderAddItemForm.OkExecute(Sender: TObject); begin OkButton.Click; end; procedure TUpOrderAddItemForm.CancelExecute(Sender: TObject); begin CancelButton.Click; end; procedure TUpOrderAddItemForm.ItemTypeOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); var Params: TUnivParams; OutPut: TRxMemoryData; begin Params.FormCaption := 'Довідник типів наказів'; Params.ShowMode := fsmSelect; Params.ShowButtons := [fbExit]; Params.TableName := 'UP_DT_ORDER_TYPE_SEL(' + IntToStr(GetUserId) + ')'; Params.Fields := 'id_type,type_name,bpl_name'; Params.FieldsName := 'Тип,Назва'; Params.KeyField := 'id_type'; Params.ReturnFields := 'id_type,type_name,bpl_name'; Params.DBHandle := Integer(TUpOrderListForm(owner.owner).WorkDatabase.Handle); OutPut := TRxMemoryData.Create(self); if GetUnivSprav(Params, OutPut) then begin value := output['id_type']; DisplayText := VarToStr(output['type_name']); BplName.Value := output['bpl_name']; end; end; end.
unit UEntradaEstoque; interface uses UEntidade ,UProduto ,UDeposito ; type TENTRADAESTOQUE = CLASS (TENTIDADE) public DATAEMISSAO : TDateTime; DATAENTRADA : TDateTime; NUMERODOCUMENTO : Integer; PRODUTO : TPRODUTO; QUANTIDADE : Integer; CUSTOUNITARIO : Double; VALORTOTAL : Double; DEPOSITO : TDEPOSITO; LOTE : Integer; LOTEVALIDADE : TDateTime; constructor Create; override; destructor Destroy; override; end; const TBL_ENTRADA_ESTOQUE = 'ENTRADAESTOQUE'; FLD_ENTRADA_ESTOQUE_ID = 'ID'; FLD_ENTRADA_ESTOQUE_DATAEMISSAO = 'DATAEMISSAO'; FLD_ENTRADA_ESTOQUE_DATAENTRADA = 'DATAENTRADA'; FLD_ENTRADA_ESTOQUE_NUMERODOCUMENTO = 'NUMERODOCUMENTO'; FLD_ENTRADA_ESTOQUE_PRODUTO = 'ID_PRODUTO'; FLD_ENTRADA_ESTOQUE_QUANTIDADE = 'QUANTIDADE'; FLD_ENTRADA_ESTOQUE_CUSTOUNITARIO = 'CUSTOUNITARIO'; FLD_ENTRADA_ESTOQUE_VALORTOTAL = 'VALORTOTAL'; FLD_ENTRADA_ESTOQUE_DEPOSITO = 'ID_DEPOSITO'; FLD_ENTRADA_ESTOQUE_LOTE = 'LOTE'; FLD_ENTRADA_ESTOQUE_LOTEVALIDADE = 'LOTEVALIDADE'; VW_ENTRADA_ESTOQUE = 'VW_ESTRADA_ESTOQUE'; VW_ENTRADA_ESTOQUE_ID = 'COD'; VW_ENTRADA_ESTOQUE_PRODUTO = 'PRODUTO'; VW_ENTRADA_ESTOQUE_DEPOSITO = 'DEPOSITO'; resourcestring STR_ENTRADAESTOQUE = 'Movimentação Entrada Estoque'; implementation uses Sysutils ,Dialogs ; { ENTRADA ESTOQUE } constructor TENTRADAESTOQUE.Create; begin inherited; PRODUTO := TPRODUTO.Create; DEPOSITO := TDEPOSITO.Create; end; destructor TENTRADAESTOQUE.Destroy; begin freeAndNil(PRODUTO); freeAndNil(DEPOSITO); inherited; end; end.
{ @abstract(TSynUniSyn classes source) @authors(Fantasist [walking_in_the_sky@yahoo.com], Vit [nevzorov@yahoo.com], Vitalik [2vitalik@gmail.com], Quadr0 [quadr02005@gmail.com]) @created(2004) @lastmod(2006-07-19) } {$IFNDEF QSYNUNICLASSES} unit SynUniClasses; {$ENDIF} {$I SynUniHighlighter.inc} interface uses {$IFDEF SYN_CLX} Qt, Types, QGraphics, QSynEditTypes, QSynEditHighlighter, QSynEditStrConst, {$ELSE} Windows, Graphics, SynEditTypes, SynEditHighlighter, SynEditStrConst, {$ENDIF} Classes, SysUtils; type TCharSet = set of Char; TSynInfo = class; TSynToken = class; TTokenNode = class; TTokenNodeList = class; TAuthorInfo = record Name: string; Email: string; Web: string; Copyright: string; Company: string; Remark: string; end; TGeneralInfo = record Name: string; Extensions: string; FileType: string; Version: Integer; Revision: Integer; History: string; Sample: string; end; TSynInfo = class public Author: TAuthorInfo; General: TGeneralInfo; procedure Clear; procedure LoadFromFile(AFileName: string); procedure LoadFromStream(AStream: TStream); procedure SaveToFile(AFileName: string); procedure SaveToStream(AStream: TStream); end; TStartType = (stUnspecified, stAny, stTerm); TBreakType = (btUnspecified, btAny, btTerm); TStartLine = (slNotFirst, slFirst, slFirstNonSpace); TSynAttributes = class(TSynHighlighterAttributes) public ParentForeground: Boolean; ParentBackground: Boolean; constructor Create(AName: string); destructor Destroy(); override; procedure AssignColorAndStyle(AStyle: TSynAttributes); overload; //property Name: string read fName write fName; end; TEditorProperties = class public ActiveLineColor: TColor; SelectedForeground: TColor; SelectedBackground: TColor; constructor Create(); destructor Destroy(); procedure Clear(); end; TAbstractRule = class; TAbstractSynToken = class public Attributes: TSynHighlighterAttributes; BreakType: TBreakType; FinishOnEol: Boolean; fIsRegexp: Boolean; //new fOpenRule: TAbstractRule; StartLine: TStartLine; StartType: TStartType; constructor Create(); reintroduce; overload; constructor Create(Attribs: TSynHighlighterAttributes); reintroduce; overload; constructor Create(ASynToken: TAbstractSynToken); reintroduce; overload; destructor Destroy(); override; procedure Clear; end; TSynMultiToken = class(TAbstractSynToken) private fSymbols: TStringList; function GetSymbol(Index: Integer): string; procedure SetSymbol(Index: Integer; ASymbol: string); public constructor Create(); reintroduce; overload; constructor Create(Attribs: TSynHighlighterAttributes); reintroduce; overload; constructor Create(ASynMultiToken: TSynMultiToken); reintroduce; overload; destructor Destroy(); override; function AddSymbol(ASymbol: string): Integer; function SymbolCount(): Integer; procedure Clear(); procedure DeleteSymbol(Index: Integer); //property SymbolList: TStringList read fSymbols write fSymbols; property Symbols[Index: Integer]: string read GetSymbol write SetSymbol; //нужно index добавить и туда #0 end; TSynToken = class(TAbstractSynToken) private fSymbol: string; function GetSymbol: string; public ClosingToken: TSynToken; Temporary: Boolean; constructor Create(); overload; constructor Create(Attribs: TSynHighlighterAttributes); overload; constructor Create(ASynToken: TSynToken); overload; constructor Create(ASynMultiToken: TSynMultiToken; Index: Integer); overload; destructor Destroy(); override; procedure Clear(); property Symbol: string read GetSymbol write fSymbol; end; //TODO: возможно стоит его сделать наследником TAbstractSynSymbol TTokenNode = class //was: TSymbolNode private fChar: Char; public BreakType: TBreakType; StartType: TStartType; NextNodes: TTokenNodeList; SynToken: TSynToken; constructor Create(AChar: Char; ASynToken: TSynToken; ABreakType: TBreakType); overload; //virtual; constructor Create(AChar: Char); overload; destructor Destroy(); override; property Char: Char read fChar write fChar; end; TTokenNodeList = class //was: TSymbolList NodeList: TList; constructor Create(); //virtual; destructor Destroy(); override; function FindNode(AChar: Char): TTokenNode; function GetCount: Integer; function GetNode(Index: Integer): TTokenNode; procedure AddNode(Node: TTokenNode); procedure SetNode(Index: Integer; Value: TTokenNode); property Count: Integer read GetCount; property Nodes[index: Integer]: TTokenNode read GetNode write SetNode; end; { Color scheme } TSynScheme = class private fName: string; fStyleList: TList; function GetCount: Integer; function GetStyle(Index: Integer): TSynAttributes; procedure SetStyle(Index: Integer; Value: TSynAttributes); public EditorProperties: TEditorProperties; constructor Create(const AName: string); virtual; destructor Destroy(); override; function AddStyle(AName: string; Foreground, Background: TColor; FontStyle: TFontStyles): TSynAttributes; overload; function GetStyleDefault(const AName: string; const Default: TSynAttributes): TSynAttributes; function GetStyleName(const AName: string): TSynAttributes; function IndexOf(const AName: string): Integer; procedure AddStyle(AStyle: TSynAttributes); overload; procedure Clear(); procedure Delete(const Index: Integer); property Count: Integer read GetCount; property Name: string read fName write fName; property Styles[index: Integer]: TSynAttributes read GetStyle write SetStyle; end; TSynUniSchemes = class protected fSchemesList: TList; function GetCount(): Integer; function GetScheme(Index: Integer): TSynScheme; procedure SetScheme(Index: Integer; Value: TSynScheme); public constructor Create(); virtual; destructor Destroy(); override; function AddScheme(const AName: string): TSynScheme; overload; function GetSchemeName(const AName: string): TSynScheme; function IndexOf(AScheme: TSynScheme): Integer; procedure AddScheme(const AScheme: TSynScheme); overload; procedure Clear(); procedure Delete(AScheme: TSynScheme); overload; procedure Delete(const Index: Integer); overload; procedure ListStyleNames(AList: TStrings); procedure LoadFromFile(AFileName: string); procedure LoadFromStream(AStream: TStream); procedure SaveToFile(AFileName: string); procedure SaveToStream(AStream: TStream); property Count: Integer read GetCount; property Schemes[index: Integer]: TSynScheme read GetScheme write SetScheme; end; TAbstractRule = class private fEnabled: Boolean; procedure SetEnabled(Value: Boolean); public constructor Create(); destructor Destroy(); override; property Enabled: Boolean read fEnabled write SetEnabled default True; end; function FontStyleToStr(AFontStyle: TFontStyles): string; function StrToFontStyle(AString: string): TFontStyles; function SetToStr(ACharSet: TCharSet): string; function StrToSet(AString: string): TCharSet; function StartLineToStr(AStartLine: TStartLine): string; function StrToStartLine(AString: string): TStartLine; function StartTypeToStr(AStartType: TStartType): string; function StrToStartType(AString: string): TStartType; function BreakTypeToStr(ABreakType: TBreakType): string; function StrToBreakType(AString: string): TBreakType; procedure ClearList(var List: TList); procedure FreeList(var List: TList); const { Symbols that are always delimiters } AbsoluteDelimiters: TCharSet = [#0, #9, #10, #13, #32]; { End of line identifier } EOL = #13#10; implementation uses SynUniFormatNativeXml20, {$IFDEF SYN_CLX} QSynUniRules; {$ELSE} SynUniRules; {$ENDIF} //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * * INTERFACE * * * * * * * * * * * * * * * * * * * } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- function FontStyleToStr(AFontStyle: TFontStyles): string; begin Result := ''; if fsBold in AFontStyle then Result := Result + 'B'; if fsItalic in AFontStyle then Result := Result + 'I'; if fsUnderline in AFontStyle then Result := Result + 'U'; if fsStrikeOut in AFontStyle then Result := Result + 'S'; end; //---------------------------------------------------------------------------- function SetToStr(ACharSet: TCharSet): string; var b: byte; begin Result := ''; for b := 1 to 255 do if (chr(b) in ACharSet) and (not (chr(b) in AbsoluteDelimiters)) then Result := Result + chr(b); end; //---------------------------------------------------------------------------- function StrToFontStyle(AString: string): TFontStyles; begin Result := []; if Pos('B', AString) > 0 then Include(Result, fsBold); if Pos('I', AString) > 0 then Include(Result, fsItalic); if Pos('U', AString) > 0 then Include(Result, fsUnderline); if Pos('S', AString) > 0 then Include(Result, fsStrikeOut); end; //---------------------------------------------------------------------------- function StrToSet(AString: string): TCharSet; var i: Integer; begin Result := []; for i := 1 to Length(AString) do Result := Result + [AString[i]]; end; //---------------------------------------------------------------------------- function StartLineToStr(AStartLine: TStartLine): string; begin if AStartLine = slFirst then Result := 'True' else if AStartLine = slFirstNonSpace then Result := 'NonSpace' else Result := ''; end; //---------------------------------------------------------------------------- function StrToStartLine(AString: string): TStartLine; begin Result := slNotFirst; if (AString = 'True') or (AString = 'First') then Result := slFirst else if AString = 'NonSpace' then Result := slFirstNonSpace else if (AString = 'False') or (AString = '') then Result := slNotFirst else //raise Exception.Create('Unknown StartLine identifier'); end; //---------------------------------------------------------------------------- function StartTypeToStr(AStartType: TStartType): string; begin end; //---------------------------------------------------------------------------- function StrToStartType(AString: string): TStartType; begin if (AString = 'True') or (AString = 'Left') or (AString = '') then Result := stAny else if (AString = 'Right') or (AString = 'False') then Result := stTerm else Result := stUnspecified//raise Exception.Create('Unknown start types identifier'); end; //---------------------------------------------------------------------------- function BreakTypeToStr(ABreakType: TBreakType): string; begin end; //---------------------------------------------------------------------------- function StrToBreakType(AString: string): TBreakType; begin if (AString = 'True') or (AString = 'Right') or (AString = '') then Result := btAny else if (AString = 'Left') or (AString = 'False') then Result := btTerm else Result := btUnspecified;//raise Exception.Create('Unknown break types identifier'); end; //---------------------------------------------------------------------------- procedure ClearList(var List: TList); var i: Integer; begin if not Assigned(List) then Exit; for i := 0 to List.Count-1 do TObject(List[i]).Free(); List.Clear(); end; //---------------------------------------------------------------------------- procedure FreeList(var List: TList); var i: Integer; begin if not Assigned(List) then Exit; for i := 0 to List.Count - 1 do TObject(List[i]).Free(); FreeAndNil(List); end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * * TSynInfo * * * * * * * * * * * * * * * * * * * *} //---------------------------------------------------------------------------- procedure TSynInfo.Clear; begin General.Name := ''; General.Extensions := ''; General.Version := 0; General.Revision := 0; General.Sample := ''; Author.Name := ''; Author.Email := ''; Author.Web := ''; Author.Copyright := ''; Author.Company := ''; end; //---------------------------------------------------------------------------- procedure TSynInfo.LoadFromStream(AStream: TStream); begin TSynUniFormatNativeXml20.ImportFromStream(Self, AStream); end; //---------------------------------------------------------------------------- procedure TSynInfo.LoadFromFile(AFileName: string); begin TSynUniFormatNativeXml20.ImportFromFile(Self, AFileName); end; //---------------------------------------------------------------------------- procedure TSynInfo.SaveToStream(AStream: TStream); begin TSynUniFormatNativeXml20.ExportToStream(Self, AStream); end; //---------------------------------------------------------------------------- procedure TSynInfo.SaveToFile(AFileName: string); begin TSynUniFormatNativeXml20.ExportToFile(Self, AFileName); end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * TEditorProperties * * * * * * * * * * * * * * * * * } //---------------------------------------------------------------------------- constructor TEditorProperties.Create(); begin inherited; Clear; end; //---------------------------------------------------------------------------- destructor TEditorProperties.Destroy(); begin inherited; end; //---------------------------------------------------------------------------- procedure TEditorProperties.Clear; begin ActiveLineColor := clNone; SelectedForeground := clHighlightText; SelectedBackground := clHighlight; end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * TSynAttributes * * * * * * * * * * * * * * * * * *} //---------------------------------------------------------------------------- constructor TSynAttributes.Create(AName: String); begin // inherited Create(Name); //!!EK inherited Create(AName); //!!EK //#fName := AName; end; //---------------------------------------------------------------------------- destructor TSynAttributes.Destroy(); begin //#fName := ''; inherited; end; //---------------------------------------------------------------------------- procedure TSynAttributes.AssignColorAndStyle(AStyle: TSynAttributes); begin inherited AssignColorAndStyle(AStyle); ParentForeground := AStyle.ParentForeground; ParentBackground := AStyle.ParentBackground; end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * TAbstractSynSymbol * * * * * * * * * * * * * * * *} //---------------------------------------------------------------------------- constructor TAbstractSynToken.Create(); begin inherited; Attributes := nil; fIsRegexp := False; fOpenRule := nil; StartLine := slNotFirst; StartType := stUnspecified; BreakType := btUnspecified; end; //---------------------------------------------------------------------------- constructor TAbstractSynToken.Create(Attribs: TSynHighlighterAttributes); begin Create(); Attributes := Attribs; end; //---------------------------------------------------------------------------- constructor TAbstractSynToken.Create(ASynToken: TAbstractSynToken); begin inherited Create(); Attributes := ASynToken.Attributes; //# fOpenRule := ASynSymbol.fOpenRule; //TODO: Над этим надо подумать... (см. SafeInsertToken) StartLine := ASynToken.StartLine; StartType := ASynToken.StartType; BreakType := ASynToken.BreakType; end; //---------------------------------------------------------------------------- destructor TAbstractSynToken.Destroy(); begin {if Assigned(Attributes) then FreeAndNil(Attributes);} inherited; end; {//---------------------------------------------------------------------------- procedure TAbstractSynSymbol.SetFinishOnEol(Value: Boolean); begin fFinishOnEol := Value; end;} //---------------------------------------------------------------------------- procedure TAbstractSynToken.Clear; begin StartType := stAny; BreakType := btAny; end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * * * TSynToken * * * * * * * * * * * * * * * * * *} //---------------------------------------------------------------------------- constructor TSynToken.Create(); begin inherited; Symbol := ''; Temporary := False; end; //---------------------------------------------------------------------------- constructor TSynToken.Create(Attribs: TSynHighlighterAttributes); begin inherited; Symbol := ''; end; //---------------------------------------------------------------------------- constructor TSynToken.Create(ASynToken: TSynToken); begin inherited Create(ASynToken as TAbstractSynToken); Symbol := ASynToken.Symbol; end; constructor TSynToken.Create(ASynMultiToken: TSynMultiToken; Index: Integer); begin inherited Create(ASynMultiToken as TAbstractSynToken); Symbol := ASynMultiToken.Symbols[Index]; end; //---------------------------------------------------------------------------- destructor TSynToken.Destroy(); begin {if Assigned(ClosingToken) then FreeAndNil(ClosingToken);} inherited; end; //---------------------------------------------------------------------------- function TSynToken.GetSymbol: string; begin if FinishOnEol then Result := fSymbol + #0 else Result := fSymbol; end; //---------------------------------------------------------------------------- procedure TSynToken.Clear(); begin Symbol := ''; end; (* //---------------------------------------------------------------------------- procedure TSynToken.SetFinishOnEol(Value: Boolean); begin inherited; { if fSymbol[Length(fSymbol)] = #0 then begin if not fFinishOnEol then Delete(fSymbol, Length(fSymbol), 1); end else begin if fFinishOnEol then fSymbol := fSymbol + #0; end} end; *) //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * * TSynMultiToken * * * * * * * * * * * * * * * * } //---------------------------------------------------------------------------- constructor TSynMultiToken.Create(); begin inherited; fSymbols := TStringList.Create(); //fSymbols.Add(''); StartType := stAny; BreakType := btAny; end; //---------------------------------------------------------------------------- constructor TSynMultiToken.Create(Attribs: TSynHighlighterAttributes); begin inherited; Create(); end; //---------------------------------------------------------------------------- constructor TSynMultiToken.Create(ASynMultiToken: TSynMultiToken); begin inherited Create(ASynMultiToken as TAbstractSynToken); Create(); //Symbol := ASynToken.Symbol; end; //---------------------------------------------------------------------------- destructor TSynMultiToken.Destroy(); begin FreeAndNil(fSymbols); inherited; end; //---------------------------------------------------------------------------- function TSynMultiToken.AddSymbol(ASymbol: string): Integer; begin //if (fSymbols.Count = 1) and Result := fSymbols.Add(ASymbol); end; //---------------------------------------------------------------------------- procedure TSynMultiToken.Clear(); begin fSymbols.Clear(); //fSymbols.Add(''); end; //---------------------------------------------------------------------------- procedure TSynMultiToken.DeleteSymbol(Index: Integer); begin if (Index > -1) and (Index < fSymbols.Count) then fSymbols.Delete(Index) else raise Exception.Create(ClassName + '.DelteSymbol: Index out of bounds'); end; { //---------------------------------------------------------------------------- procedure TSynMultiToken.SetFinishOnEol(Value: Boolean); var i: Integer; Current: string; begin inherited; for i := 0 to fSymbols.Count-1 do begin Current := fSymbols[i]; if Current[Length(Current)] = #0 then begin if not FinishOnEol then Delete(Current, Length(Current), 1); end else begin if fFinishOnEol then Current := Current + #0; end; fSymbols[i] := Current; end; end; } //---------------------------------------------------------------------------- function TSynMultiToken.GetSymbol(Index: Integer): string; begin if (Index > -1) and (Index < fSymbols.Count) then Result := fSymbols[Index] else raise Exception.Create(ClassName + '.GetSymbol: Index out of bounds'); end; //---------------------------------------------------------------------------- procedure TSynMultiToken.SetSymbol(Index: Integer; ASymbol: string); begin if (Index > -1) and (Index < fSymbols.Count) then fSymbols[Index] := ASymbol else raise Exception.Create(ClassName + '.SetSymbol: Index out of bounds'); end; //---------------------------------------------------------------------------- function TSynMultiToken.SymbolCount: Integer; begin Result := fSymbols.Count; end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * * * TTokenNode * * * * * * * * * * * * * * * * * } //---------------------------------------------------------------------------- constructor TTokenNode.Create(AChar: Char); begin inherited Create(); fChar := AChar; NextNodes := TTokenNodeList.Create(); SynToken := nil; end; //---------------------------------------------------------------------------- constructor TTokenNode.Create(AChar: Char; ASynToken: TSynToken; ABreakType: TBreakType); begin Create(AChar); BreakType := ABreakType; StartType := ASynToken.StartType; SynToken := ASynToken; end; //---------------------------------------------------------------------------- destructor TTokenNode.Destroy(); begin FreeAndNil(NextNodes); inherited; end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * * TTokenNodeList * * * * * * * * * * * * * * * * *} //---------------------------------------------------------------------------- constructor TTokenNodeList.Create(); begin inherited; NodeList := TList.Create(); end; //---------------------------------------------------------------------------- destructor TTokenNodeList.Destroy(); begin FreeList(NodeList); inherited; end; //---------------------------------------------------------------------------- procedure TTokenNodeList.AddNode(Node: TTokenNode); begin NodeList.Add(Node); end; //---------------------------------------------------------------------------- function TTokenNodeList.FindNode(AChar: Char): TTokenNode; var i: Integer; begin Result := nil; for i := 0 to NodeList.Count-1 do if TTokenNode(NodeList[i]).fChar = AChar then begin Result := TTokenNode(NodeList[i]); Break; end; end; //---------------------------------------------------------------------------- // Return Node count in SymbolList //---------------------------------------------------------------------------- function TTokenNodeList.GetCount: Integer; begin Result := NodeList.Count; end; //---------------------------------------------------------------------------- // Return Node in SymbolList by index //---------------------------------------------------------------------------- function TTokenNodeList.GetNode(Index: Integer): TTokenNode; begin Result := TTokenNode(NodeList[index]); end; //---------------------------------------------------------------------------- procedure TTokenNodeList.SetNode(Index: Integer; Value: TTokenNode); begin if Index < NodeList.Count then TTokenNode(NodeList[index]).Free; NodeList[index] := Value; end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * * * TAbstractRule * * * * * * * * * * * * * * * * } //---------------------------------------------------------------------------- constructor TAbstractRule.Create(); begin inherited; Enabled := True; end; //---------------------------------------------------------------------------- destructor TAbstractRule.Destroy(); begin inherited; end; //---------------------------------------------------------------------------- procedure TAbstractRule.SetEnabled(Value: Boolean); begin fEnabled := Value; end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * TSynScheme * * * * * * * * * * * * * * * * * * * *} //---------------------------------------------------------------------------- constructor TSynScheme.Create(const AName: string); begin inherited Create(); fName := AName; fStyleList := TList.Create(); EditorProperties := TEditorProperties.Create(); end; //---------------------------------------------------------------------------- destructor TSynScheme.Destroy(); begin Clear; FreeList(fStyleList); FreeAndNil(EditorProperties); inherited; end; //---------------------------------------------------------------------------- function TSynScheme.AddStyle(AName: string; Foreground, Background: TColor; FontStyle: TFontStyles): TSynAttributes; begin {$IFDEF WRITABLE_ATTRIBUTE_NAME} Result := TSynAttributes.Create(Name); Result.Name := AName; {$ELSE} Result := TSynAttributes.Create(AName); {$ENDIF} Result.ParentForeground := False; Result.ParentBackground := False; Result.Foreground := Foreground; Result.Background := Background; Result.Style := FontStyle; fStyleList.Add(Result); end; //---------------------------------------------------------------------------- procedure TSynScheme.AddStyle(AStyle: TSynAttributes); begin fStyleList.Add(AStyle); end; //---------------------------------------------------------------------------- procedure TSynScheme.Clear; begin ClearList(fStyleList); end; //---------------------------------------------------------------------------- procedure TSynScheme.Delete(const Index: Integer); begin TSynAttributes(fStyleList.Items[Index]).Free; fStyleList.Remove(fStyleList.Items[Index]); end; //---------------------------------------------------------------------------- function TSynScheme.GetCount: Integer; begin Result := fStyleList.Count; end; //---------------------------------------------------------------------------- function TSynScheme.GetStyle(Index: Integer): TSynAttributes; begin Result := TSynAttributes(fStyleList.Items[Index]); end; //---------------------------------------------------------------------------- function TSynScheme.GetStyleDefault(const AName: string; const Default: TSynAttributes): TSynAttributes; var i: Integer; begin Result := Default; try //??? В Designer 2.0 выскакивает AV if fStyleList = nil then Exit; except Exit; end; for i := 0 to {fStyleList.}Count - 1 do if TSynAttributes(fStyleList[i]).{f}Name = AName then begin Result := TSynAttributes(fStyleList[i]); Break; end; end; //---------------------------------------------------------------------------- function TSynScheme.GetStyleName(const AName: string): TSynAttributes; begin Result := GetStyleDefault(AName, nil); end; //---------------------------------------------------------------------------- function TSynScheme.IndexOf(const AName: string): Integer; var i: Integer; begin Result := -1; for i := 0 to fStyleList.Count - 1 do if TSynAttributes(fStyleList[i]).{f}Name = AName then begin Result := i; Break; end; end; //---------------------------------------------------------------------------- procedure TSynScheme.SetStyle(Index: Integer; Value: TSynAttributes); begin fStyleList.Items[Index] := Value; end; //---------------------------------------------------------------------------- {* * * * * * * * * * * * * * TSynUniSchemes * * * * * * * * * * * * * * * * * *} //---------------------------------------------------------------------------- constructor TSynUniSchemes.Create(); var NewScheme: TSynScheme; begin inherited; fSchemesList := TList.Create(); NewScheme := TSynScheme.Create('Default'); fSchemesList.Add(NewScheme); end; //---------------------------------------------------------------------------- destructor TSynUniSchemes.Destroy(); begin Clear; FreeList(fSchemesList); inherited; end; //---------------------------------------------------------------------------- function TSynUniSchemes.GetCount(): Integer; begin Result := fSchemesList.Count; end; //---------------------------------------------------------------------------- function TSynUniSchemes.GetScheme(Index: Integer): TSynScheme; begin Result := TSynScheme(fSchemesList[Index]); end; //---------------------------------------------------------------------------- function TSynUniSchemes.IndexOf(AScheme: TSynScheme): Integer; begin Result := fSchemesList.IndexOf(AScheme); end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.Delete(const Index: Integer); begin TSynScheme(fSchemesList.Items[Index]).Free; fSchemesList.Remove(fSchemesList.Items[Index]); end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.Delete(AScheme: TSynScheme); begin fSchemesList.Remove(AScheme); FreeAndNil(AScheme); end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.LoadFromStream(AStream: TStream); begin TSynUniFormatNativeXml20.ImportFromStream(Self, AStream); end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.LoadFromFile(AFileName: string); begin TSynUniFormatNativeXml20.ImportFromFile(Self, AFileName); end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.SaveToStream(AStream: TStream); begin TSynUniFormatNativeXml20.ExportToStream(Self, AStream); end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.SaveToFile(AFileName: string); begin TSynUniFormatNativeXml20.ExportToFile(Self, AFileName); end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.SetScheme(Index: Integer; Value: TSynScheme); begin fSchemesList[Index] := Value; end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.Clear; begin ClearList(fSchemesList); end; //---------------------------------------------------------------------------- function TSynUniSchemes.GetSchemeName(const AName: string): TSynScheme; var i: Integer; begin Result := nil; for i := 0 to fSchemesList.Count - 1 do if TSynScheme(fSchemesList[i]).Name = AName then begin Result := TSynScheme(fSchemesList[i]); Break; end; end; //---------------------------------------------------------------------------- function TSynUniSchemes.AddScheme(const AName: string): TSynScheme; begin Result := TSynScheme.Create(AName); fSchemesList.Add(Result); end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.AddScheme(const AScheme: TSynScheme); begin fSchemesList.Add(AScheme); end; //---------------------------------------------------------------------------- procedure TSynUniSchemes.ListStyleNames(AList: TStrings); var i: Integer; begin AList.BeginUpdate; try AList.Clear; for i := 0 to fSchemesList.Count - 1 do AList.Add(TSynScheme(fSchemesList[i]).Name); finally AList.EndUpdate; end; end; end.
{ NAME: Gąsienica; VERSION: 1.4; AUTHOR: Przemysław Wiecheć; CONTACT: os.Orła Białego 52/11 61-251 Poznań Poland; COMPILER: Delphi 2.0; STATUS: Freeware; DATE: 08.XI.2001-09.II.2002 Copyright © Przemysław Wiecheć } unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Menus, ComCtrls, INIFiles, StdCtrls, MMSystem; type TForm1 = class(TForm) MainMenu1: TMainMenu; Plik1: TMenuItem; NowaGra1: TMenuItem; Pauza1: TMenuItem; Wyjcie1: TMenuItem; Timer1: TTimer; HighScores1: TMenuItem; Panel1: TPanel; Image2: TImage; Label1: TLabel; Poziom1: TMenuItem; atwy1: TMenuItem; Normalny1: TMenuItem; Trudny1: TMenuItem; Label4: TLabel; Pomoc1: TMenuItem; Informacje1: TMenuItem; OProgramie1: TMenuItem; Podzikowania1: TMenuItem; Timer2: TTimer; Ustawienia1: TMenuItem; OdtwarzajDwiki1: TMenuItem; Sciany1: TMenuItem; Zakocz1: TMenuItem; OstatniWidok1: TMenuItem; N2: TMenuItem; N1: TMenuItem; GraDwuosobowa1: TMenuItem; Na2planszach1: TMenuItem; Na1planszy1: TMenuItem; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Wyjcie1Click(Sender: TObject); procedure OProgramie1Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure Obliczenia(Sender: TObject); procedure FormPaint(Sender: TObject); procedure Zjedzone(Sender: TObject); procedure NowaGra(Sender: TObject); procedure HighScores1Click(Sender: TObject); procedure Koniec(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Pauza1Click(Sender: TObject); procedure Credits1Click(Sender: TObject); procedure atwy1Click(Sender: TObject); procedure Normalny1Click(Sender: TObject); procedure Trudny1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Informacje1Click(Sender: TObject); procedure Timer2Timer(Sender: TObject); procedure OdtwarzajDwiki1Click(Sender: TObject); procedure Sciany1Click(Sender: TObject); procedure Zakocz1Click(Sender: TObject); procedure OstatniWidok1Click(Sender: TObject); procedure Na2planszach1Click(Sender: TObject); procedure Na1planszy1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; X,Y,Kierunek,Kulki,Za,Zb,Poziom,Bek,Sound,Wall: Byte; Punkty: Integer; Kon,Zje: Boolean; Tab: array[1..225] of Integer = (-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,-2,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1); TabA: array[1..225] of Integer; TabB: array[1..15,1..15] of Integer; Wynik1: array[0..10] of String; Wynik2: array[0..10] of Integer; Wynik3: array[0..10] of String; Wynik4: array[0..10] of Integer; Tab1: array[1..225] of Word = (10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290, 10,30,50,70,90,110,130,150,170,190,210,230,250,270,290); Tab2: array[1..225] of Word = (10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 30,30,30,30,30,30,30,30,30,30,30,30,30,30,30, 50,50,50,50,50,50,50,50,50,50,50,50,50,50,50, 70,70,70,70,70,70,70,70,70,70,70,70,70,70,70, 90,90,90,90,90,90,90,90,90,90,90,90,90,90,90, 110,110,110,110,110,110,110,110,110,110,110,110,110,110,110, 130,130,130,130,130,130,130,130,130,130,130,130,130,130,130, 150,150,150,150,150,150,150,150,150,150,150,150,150,150,150, 170,170,170,170,170,170,170,170,170,170,170,170,170,170,170, 190,190,190,190,190,190,190,190,190,190,190,190,190,190,190, 210,210,210,210,210,210,210,210,210,210,210,210,210,210,210, 230,230,230,230,230,230,230,230,230,230,230,230,230,230,230, 250,250,250,250,250,250,250,250,250,250,250,250,250,250,250, 270,270,270,270,270,270,270,270,270,270,270,270,270,270,270, 290,290,290,290,290,290,290,290,290,290,290,290,290,290,290); const title='Gąsienica 1.4 - Freeware '; implementation uses Unit2, Unit3, Unit4, Unit5, Unit6, Unit7, Unit8; {$R *.DFM} procedure TForm1.Koniec(Sender: TObject); var I,J: Byte; Rect1, Rect2: TRect; begin Rect1 := Rect(10,10,310,310); Rect2 := Rect(0,0,300,300); Form6.Image1.Canvas.CopyRect(Rect2, Form1.Canvas, Rect1); Form6.Image1.Picture.SaveToFile(ExtractFilePath(ParamStr(0))+'widok.bmp'); OstatniWidok1.Enabled:=True; Timer1.Enabled:=False; Timer2.Enabled:=False; Poziom1.Enabled:=True; Kon:=True; Bek:=0; for I:=1 to 10 do for J:=1 to 10 do if Wynik2[I]>Wynik2[J] then begin Wynik1[0]:=Wynik1[i]; Wynik1[i]:=Wynik1[j]; Wynik1[j]:=Wynik1[0]; Wynik2[0]:=Wynik2[i]; Wynik2[i]:=Wynik2[j]; Wynik2[j]:=Wynik2[0]; Wynik3[0]:=Wynik3[i]; Wynik3[i]:=Wynik3[j]; Wynik3[j]:=Wynik3[0]; Wynik4[0]:=Wynik4[i]; Wynik4[i]:=Wynik4[j]; Wynik4[j]:=Wynik4[0]; end; if Sound=1 then begin PlaySound(PChar(ExtractFilePath(ParamStr(0))+'nie'),0,snd_ASync);end; FormPaint(Sender); if Punkty>Wynik2[10] then begin Form4.ShowModal; Form3.ShowModal; end; end; procedure TForm1.NowaGra(Sender: TObject); var I,J,Z: Byte; Ciag: String; Bitmapa: TBitmap; MyRect,MyOther: TRect; begin Label1.Caption:=''; Label4.Caption:=''; if Sound=1 then begin PlaySound(PChar(ExtractFilePath(ParamStr(0))+'dobry'),0,snd_ASync);end; OstatniWidok1.Enabled:=False; Form1.Caption:=title; Poziom1.Enabled:=False; Canvas.Brush.Style:=bsSolid; Canvas.Brush.Color:=clBlack; Form1.Canvas.Rectangle(91,92,222,184); Kon:=False; X:=8; Y:=8; Kulki:=0; Punkty:=0; Kierunek:=(Random(4))+1; for I:=1 to 225 do begin TabA[I]:=Tab[I]; end; Z:=1; for I:=1 to 15 do begin for J:=1 to 15 do begin TabB[I,J]:=TabA[Z]; Inc(Z); end; end; repeat Za:=(Random(12))+1; Zb:=(Random(12))+1; if TabB[Za,Zb]=0 then TabB[Za,Zb]:=-3; until TabB[Za,Zb]=-3; FormPaint(Sender); SetCursorPos(0,0); Sleep(500); Timer1.Enabled:=True; Timer2.Enabled:=True; end; procedure TForm1.Zjedzone(Sender: TObject); var I,J: Byte; begin Timer1.Enabled:=False; Zje:=False; for I:=1 to 15 do begin for J:=1 to 15 do begin if TabB[I,J]>0 then Inc(TabB[I,J]); end; end; repeat Za:=(Random(12))+1; Zb:=(Random(12))+1; if TabB[Za,Zb]=0 then begin TabB[Za,Zb]:=-3; Zje:=True; end; until Zje=True; if Zje=True then begin Inc(Kulki); if Wall=0 then begin if bek<9 then begin Punkty:=Punkty+Poziom; Bek:=0; if Sound=1 then begin PlaySound(PChar(ExtractFilePath(ParamStr(0))+'mlask'),0,snd_ASync);end; end else if bek=9 then begin Punkty:=Punkty-1; bek:=0; if Sound=1 then begin PlaySound(PChar(ExtractFilePath(ParamStr(0))+'bek'),0,snd_ASync);end; Timer2.Enabled:=True; end; end else if Wall=1 then begin if bek<9 then begin Punkty:=Punkty+2; Bek:=0; if Sound=1 then begin PlaySound(PChar(ExtractFilePath(ParamStr(0))+'mlask'),0,snd_ASync);end; end else if bek=9 then begin Punkty:=Punkty-1; bek:=0; if Sound=1 then begin PlaySound(PChar(ExtractFilePath(ParamStr(0))+'bek'),0,snd_ASync);end; Timer2.Enabled:=True; end; end; Label1.Caption:=IntToStr(Punkty); Label4.Caption:=IntToStr(Kulki); Obliczenia(Sender); Timer1.Enabled:=True; end else Zjedzone(Sender); end; procedure TForm1.Obliczenia(Sender: TObject); var I,J,A,B,C: Byte; begin C:= 1; for I:=1 to 15 do begin for J:=1 to 15 do begin if TabB[I,J]>0 then TabB[I,J]:=(TabB[I,J])-1 else if TabB[I,J]=-2 then TabB[I,J]:=Kulki; end; end; TabB[Y,X]:=-2; for A:=1 to 15 do begin for B:=1 to 15 do begin TabA[C]:=TabB[A,B]; Inc(C); end; end; FormPaint(Sender); end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if kierunek=1 then begin if (Key=VK_RIGHT) and (Kulki=0) then begin Kierunek:=2; end; if (Key=VK_UP) {and (Kulki=0) }then begin Kierunek:=3; end; if (Key=VK_DOWN) {and (Kulki=0)} then begin Kierunek:=4; end; end; if Kierunek=2 then begin if (Key=VK_LEFT) and (Kulki=0) then begin Kierunek:=1; end; if (Key=VK_UP) {and (Kulki=0) }then begin Kierunek:=3; end; if (Key=VK_DOWN) {and (Kulki=0)} then begin Kierunek:=4; end; end; if kierunek=3 then begin if (Key=VK_LEFT) {and (Kulki=0)} then begin Kierunek:=1; end; if (Key=VK_RIGHT) {and (Kulki=0) }then begin Kierunek:=2; end; if (Key=VK_DOWN) and (Kulki=0) then begin Kierunek:=4; end; end; if kierunek=4 then begin if (Key=VK_LEFT) {and (Kulki=0)} then begin Kierunek:=1; end; if (Key=VK_RIGHT) {and (Kulki=0) }then begin Kierunek:=2; end; if (Key=VK_UP) and (Kulki=0) then begin Kierunek:=3; end; end; end; procedure TForm1.Wyjcie1Click(Sender: TObject); begin Form1.Close; end; procedure TForm1.OProgramie1Click(Sender: TObject); begin if Timer1.Enabled=True then begin Pauza1Click(Sender); end; Form2.ShowModal; end; procedure TForm1.Timer1Timer(Sender: TObject); begin if Kierunek=1 then if Wall=0 then BEGIN begin if (TabB[Y,X-1]=0) or (TabB[Y,X-1]=1) then begin X:=X-1; Obliczenia(Sender); end else if TabB[Y,X-1]<=-3 then begin X:=X-1; Zjedzone(Sender); end else if (TabB[Y,X-1]>1) or (TabB[Y,X-1]=-1) then Koniec(Sender); end; END ELSE if Wall=1 then BEGIN if (TabB[Y,X-1]=0) or (TabB[Y,X-1]=1) then begin X:=X-1; Obliczenia(Sender); end else if (TabB[Y,X-1]<=-3) then begin X:=X-1; Zjedzone(Sender); end else if (TabB[Y,X-1]=-1) and (TabB[Y,X+12]<=-3) then begin X:=x+12; Zjedzone(Sender); end else if (TabB[Y,X-1]>1) or (TabB[Y,X+12]>1) then Koniec(Sender) else if TabB[Y,X-1]=-1 then begin x:=x+12; Obliczenia(Sender); end; END; if Kierunek=2 then if Wall=0 then BEGIN begin if (TabB[Y,X+1]=0) or (TabB[Y,X+1]=1) then begin X:=X+1; Obliczenia(Sender); end else if TabB[Y,X+1]<=-3 then begin X:=X+1; Zjedzone(Sender); end else if (TabB[Y,X+1]>1) or (TabB[Y,X+1]=-1) then Koniec(Sender); end; END ELSE if Wall=1 then BEGIN if (TabB[Y,X+1]=0) or (TabB[Y,X+1]=1) then begin X:=X+1; Obliczenia(Sender); end else if TabB[Y,X+1]<=-3 then begin X:=X+1; Zjedzone(Sender); end else if (TabB[Y,X+1]=-1) and (TabB[Y,X-12]<=-3) then begin X:=x-12; Zjedzone(Sender); end else if (TabB[Y,X+1]>1) or (TabB[Y,X-12]>1) then Koniec(Sender) else if TabB[Y,X+1]=-1 then begin x:=x-12; Obliczenia(Sender); end; END; if Kierunek=3 then if Wall=0 then BEGIN begin if (TabB[Y-1,X]=0) or (TabB[Y-1,X]=1) then begin Y:=Y-1; Obliczenia(Sender); end else if TabB[Y-1,X]<=-3 then begin Y:=Y-1; Zjedzone(Sender); end else if (TabB[Y-1,X]>1) or (TabB[Y-1,X]=-1) then Koniec(Sender); end; END ELSE if Wall=1 then BEGIN if (TabB[Y-1,X]=0) or (TabB[Y-1,X]=1) then begin Y:=Y-1; Obliczenia(Sender); end else if TabB[Y-1,X]<=-3 then begin Y:=Y-1; Zjedzone(Sender); end else if (TabB[Y-1,X]=-1) and (TabB[Y+12,X]<=-3) then begin y:=y+12; Zjedzone(Sender); end else if (TabB[Y-1,X]>1) or (TabB[Y+12,X]>1) then Koniec(Sender) else if TabB[Y-1,X]=-1 then begin Y:=Y+12; Obliczenia(Sender); end; END; if Kierunek=4 then if Wall=0 then BEGIN begin if (TabB[Y+1,X]=0) or (TabB[Y+1,X]=1) then begin Y:=Y+1; Obliczenia(Sender); end else if TabB[Y+1,X]<=-3 then begin Y:=Y+1; Zjedzone(Sender); end else if (TabB[Y+1,X]>1) or (TabB[Y+1,X]=-1) then Koniec(Sender); end; END ELSE if Wall=1 then BEGIN if (TabB[Y+1,X]=0) or (TabB[Y+1,X]=1) then begin Y:=Y+1; Obliczenia(Sender); end else if TabB[Y+1,X]<=-3 then begin Y:=Y+1; Zjedzone(Sender); end else if (TabB[Y-1,X]=-1) and (TabB[Y-13,X]<=-3) then begin y:=y+12; Zjedzone(Sender); end else if (TabB[Y+1,X]=-1) and (TabB[Y-12,X]<=-3) then begin y:=y-12; Zjedzone(Sender); end else if (TabB[Y+1,X]>1) or (TabB[Y-12,X]>1) then Koniec(Sender) else if TabB[Y+1,X]=-1 then begin Y:=Y-12; Obliczenia(Sender); end; END; end; procedure TForm1.FormPaint(Sender: TObject); var I:integer; MyRect,MyRect2,MyRect3,MyRect4,MyRect5,MyOther: TRect; Bitmapa: TBitmap; begin MyRect:=Rect(43,1,63,21); MyRect2:=Rect(1,1,21,21); MyRect3:=Rect(22,1,42,21); MyRect4:=Rect(64,1,84,21); MyRect5:=Rect(22,22,42,42); Bitmapa:=TBitmap.Create; Bitmapa.LoadFromFile(ExtractFilePath(ParamStr(0))+'grafika'); if Kon=True then begin Canvas.Pen.Color:=clBlack; Canvas.Brush.Style:=bsSolid; Canvas.Brush.Color:=clBlack; Form1.Canvas.Rectangle(0,0,Form1.Width,Form1.Height); MyRect:=Rect(85,1,216,93); MyOther:=Rect(94,92,225,184); Form1.Canvas.CopyRect(MyOther,Bitmapa.Canvas,MyRect); end else for I:=1 to 225 do begin MyOther := Rect(Tab1[I],Tab2[I],Tab1[I]+20,Tab2[I]+20); if TabA[I]=-1 then Form1.Canvas.CopyRect(MyOther,Bitmapa.Canvas,MyRect) else if TabA[I]=-2 then Form1.Canvas.CopyRect(MyOther,Bitmapa.Canvas,MyRect4) else if TabA[I]=-3 then Form1.Canvas.Copyrect(MyOther,Bitmapa.Canvas,MyRect3) else if TabA[I]=-4 then Form1.Canvas.CopyRect(MyOther,Bitmapa.Canvas,MyRect5) else if TabA[I]>0 then Form1.Canvas.CopyRect(MyOther,Bitmapa.Canvas,MyRect2); if TabA[i]=0 then begin Canvas.Pen.Color:=clBlack; Canvas.Brush.Color:=clBlack; Canvas.Brush.Style:=bsSolid; Form1.Canvas.Rectangle(Tab1[I],Tab2[I],Tab1[I]+20,Tab2[I]+20); end; end; Bitmapa.Free; end; procedure TForm1.HighScores1Click(Sender: TObject); begin if Timer1.Enabled=True then begin Pauza1Click(Sender); end; Form3.ShowModal; end; procedure TForm1.FormCreate(Sender: TObject); var Plik: TINIFile; I: Byte; MyRect,MyOther: TRect; Bitmapa: TBitmap; begin Bitmapa:=TBitmap.Create; Bitmapa.LoadFromFile(ExtractFilePath(ParamStr(0))+'grafika'); MyRect:=Rect(1,199,319,249); MyOther:=Rect(0,0,Image2.Width,Image2.Height); Image2.Canvas.CopyRect(MyOther,Bitmapa.Canvas,MyRect); try Plik:=TINIFile.Create(ExtractFilePath(ParamStr(0))+'ustawienia'); for I:=1 to 10 do begin Wynik1[I]:=Plik.ReadString('WYNIKI',IntToStr(I),''); Wynik2[I]:=Plik.ReadInteger('WYNIKI',IntToStr(I)+'a',0); Wynik3[I]:=Plik.ReadString('WYNIKI',IntToStr(I)+'b',''); Wynik4[I]:=Plik.ReadInteger('WYNIKI',IntToStr(I)+'c',0); end; case Plik.ReadInteger('POZIOM','w',0) of 0: Wall:=0; 1: Wall:=1; end; Sciany1.Checked:=Plik.ReadBool('POZIOM','c',FALSE); Sciany1.Enabled:=Plik.ReadBool('POZIOM','e',FALSE); case Plik.ReadInteger('POZIOM','p',2) of 1: begin atwy1.Checked:=True; Poziom:=1; Timer1.Interval:=150; end; 2: begin Normalny1.Checked:=True; Poziom:=2; Timer1.Interval:=100; end; 3: begin Trudny1.Checked:=True; Poziom:=3; Timer1.Interval:=50; end; end; case Plik.ReadInteger('SOUND','s',1) of 0: begin OdtwarzajDwiki1.Checked:=False; Sound:=0; end; 1: begin OdtwarzajDwiki1.Checked:=True; Sound:=1; end; end; finally Plik.Free; end; Bitmapa.Free; end; procedure TForm1.Pauza1Click(Sender: TObject); begin If Pauza1.Caption='Pauza' then begin Pauza1.Caption:='Start'; Timer1.Enabled:=False; Timer2.Enabled:=False; Form1.Caption:=title+'Pauza'; end else begin Pauza1.Caption:='Pauza'; Timer1.Enabled:=True; Timer2.Enabled:=True; Form1.Caption:=title; SetCursorPos(0,0); end; end; procedure TForm1.Credits1Click(Sender: TObject); var P: PChar; begin if Timer1.Enabled=True then begin Pauza1Click(Sender); end; P:=PChar('Beta-Testy i Pomysły:'+#13+'Tasak - bekanie, gra dwuosobowa na 1 planszy, nagrywanie dźwięków'+#13+ 'Piękny - przechodzenie przez ściany, kupa w grze dwuosobowej na 1 planszy'+#13+ 'Piela - gra dwuosobowa na 2 planszach'+#13+#13+ 'TDFWLightEdites'+#13+'(c) Erol S. Uzuner'+#13+'Version: 1.0, 26.03.99'+#13+ 'sarcon@tzi.de'+#13+#13+'TStringAlignGrid'+#13+'(c) Andreas Hörstemeier'+#13+ 'Version 2.0 2000-02-12'); Application.MessageBox(P,'Podziękowania...',MB_OK); end; procedure TForm1.atwy1Click(Sender: TObject); begin Normalny1.Checked:=False; Trudny1.Checked:=False; atwy1.Checked:=True; Poziom:=1; Timer1.Interval:=150; Sciany1.Enabled:=False; Wall:=0; end; procedure TForm1.Normalny1Click(Sender: TObject); begin Normalny1.Checked:=True; Trudny1.Checked:=False; atwy1.Checked:=False; Poziom:=2; Timer1.Interval:=100; Sciany1.Enabled:=False; Wall:=0; end; procedure TForm1.Trudny1Click(Sender: TObject); begin Normalny1.Checked:=False; Trudny1.Checked:=True; atwy1.Checked:=False; Poziom:=3; Timer1.Interval:=50; Sciany1.Enabled:=True; if Sciany1.Checked=True then Wall:=1 else Wall:=0; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); var Plik: TINIFile; begin Plik:=TINIFile.Create(ExtractFilePath(ParamStr(0))+'ustawienia'); Plik.WriteInteger('POZIOM','p',Poziom); Plik.WriteInteger('SOUND','s',Sound); Plik.WriteInteger('POZIOM','w',Wall); Plik.WriteBool('POZIOM','c',Sciany1.Checked); Plik.WriteBool('POZIOM','e',Sciany1.Enabled); Plik.Free; end; procedure TForm1.Informacje1Click(Sender: TObject); begin if Timer1.Enabled=True then begin Pauza1Click(Sender); end; Form5.ShowModal; end; procedure TForm1.Timer2Timer(Sender: TObject); begin Inc(Bek); if Bek=9 then begin TabB[Za,Zb]:=-4; Timer2.Enabled:=False; end; end; procedure TForm1.OdtwarzajDwiki1Click(Sender: TObject); begin If OdtwarzajDwiki1.Checked=True then begin OdtwarzajDwiki1.Checked:=False; Sound:=0; end else begin OdtwarzajDwiki1.Checked:=True; Sound:=1; end; end; procedure TForm1.Sciany1Click(Sender: TObject); begin If Sciany1.Checked=True then begin Sciany1.Checked:=False; Wall:=0; end else begin Sciany1.Checked:=True; Wall:=1; end; end; procedure TForm1.Zakocz1Click(Sender: TObject); begin Koniec(Sender); end; procedure TForm1.OstatniWidok1Click(Sender: TObject); begin Form6.ShowModal; end; procedure TForm1.Na2planszach1Click(Sender: TObject); begin Timer1.Enabled:=False; Timer2.Enabled:=False; Poziom1.Enabled:=True; Kon:=True; Bek:=0; FormPaint(Sender); Form7.ShowModal; end; procedure TForm1.Na1planszy1Click(Sender: TObject); begin Timer1.Enabled:=False; Timer2.Enabled:=False; Poziom1.Enabled:=True; Kon:=True; Bek:=0; FormPaint(Sender); Form8.Showmodal; end; end.
unit uDM; interface uses SysUtils, Classes, IniFiles, Forms, DB, DBClient, Graphics, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, ExtCtrls, uInvoicePollDisplay, uThreadConnectMRPDS; const SCREEN_CONF = 'Screen'; SCREEN_CONF_MOVING_TEXT = 'MovingText'; SCREEN_CONF_TEXT_SPEED = 'TextSpeed'; SCREEN_CONFIG_TEXT_SIZE = 'TextSize'; SCREEN_CONFIG_TEXT_COLOR = 'TextColor'; SCREEN_CONF_RECEIPT_POS = 'ReceiptPos'; SCREEN_CONF_RECEIPT_LOGO = 'Logo'; SCREEN_CONF_VIDEO_TOP = 'VideoTop'; SCREEN_CONF_VIDEO_LEFT = 'VideoLeft'; SCREEN_CONF_VIDEO_RIGHT = 'VideoRight'; SCREEN_CONF_VIDEO_BOTTOM = 'VideoBottom'; SCREEN_CONF_COMPUTER_IP = 'PollDisplayIP'; SCREEN_CONF_COMPUTER_PORT= 'PollDisplayPort'; SCREEN_CONF_STORE_ADD1 = 'StoreAddress1'; SCREEN_CONF_STORE_ADD2 = 'StoreAddress2'; SCREEN_CONF_STORE_ADD3 = 'StoreAddress3'; SCREEN_CONF_RECEIPT_BACKCOLOR = 'ReceiptBackColor'; SCREEN_CONF_RECEIPT_TEXTCOLOR = 'ReceiptTextColor'; SCREEN_CONF_LEFT = 'ScreenLeft'; SCREEN_CONF_TOP = 'ScreenTop'; SCREEN_CONF_HEIGHT = 'ScreenHeight'; SCREEN_CONF_WIDTH = 'ScreenWidth'; SCREEN_SVR_STATION = 'Svr_Station'; SCREEN_SVR_IP = 'Svr_IP'; SCREEN_SVR_PORT = 'Svr_Port'; SCREEN_IDLANGUAGE = 'IDLang'; SCREEN_RESIZE_ADV = 'ResizeAdv'; ADV_BITMAP = 0; ADV_JPG = 1; ADV_VIDEO = 2; ADV_FLASH = 3; ADV_WEB = 4; ADV_BITMAP_EXT = 'Bitmap|*.bmp'; ADV_JPG_EXT = 'JPG|*.jpg'; ADV_VIDEO_EXT = 'Video|*.mpg|all|*.*'; ADV_FLASH_EXT = 'Flash File|*.swf'; ADV_WEB_EXT = 'HTML|*.html|ASP|*.asp'; type TScreenConfig = class FMovingText : WideString; FTextSpeed : Integer; FTextSize : Integer; FReceiptPos : Integer; FIDLanguage : Integer; FLogo : String; FVideoLeft : Integer; FVideoTop : Integer; FVideoRight : Integer; FVideoBottom: Integer; FComputerIP : String; FCompPort : Integer; FStoreAdd1 : String; FStoreAdd2 : String; FStoreAdd3 : String; FReceiptBackColor : TColor; FReceiptTextColor : TColor; FTextColor : TColor; FStationName : String; FServerIP : String; FServerPort : Integer; FAutoResizeAdv : Boolean; end; TDM = class(TDataModule) cdsAdvertising: TClientDataSet; IdTCPClient: TIdTCPClient; tmrSyncAdv: TTimer; cdsAdvertisingDescription: TStringField; cdsAdvertisingFileName: TStringField; cdsAdvertisingStartDate: TDateTimeField; cdsAdvertisingEndDate: TDateTimeField; cdsAdvertisingDaysOfWeek: TStringField; cdsAdvertisingDaysOfWeekString: TStringField; cdsAdvertisingType: TIntegerField; cdsAdvertisingTypeString: TStringField; cdsAdvertisingDuration: TIntegerField; cdsAdvertisingVideoControl: TBooleanField; cdsAdvertisingDisplayDescription: TBooleanField; cdsAdvertisingHours: TStringField; cdsSaleSuggestion: TClientDataSet; cdsSaleSuggestionFileName: TStringField; cdsSaleSuggestionFileType: TIntegerField; cdsSaleSuggestionDuration: TIntegerField; cdsCrossSaleItem: TClientDataSet; cdsCrossSaleItemID: TIntegerField; cdsCrossSaleItemModelNum: TStringField; cdsCrossSaleItemModelCategory: TStringField; cdsCrossSaleItemModelSubCategory: TStringField; cdsCrossSaleItemModelGroup: TStringField; cdsCrossSaleItemFileName: TStringField; cdsCrossSaleItemFileType: TIntegerField; cdsCrossSaleItemDuration: TIntegerField; cdsCrossSaleItemCrossDescription: TStringField; cdsCrossSaleItemCrossSalePrice: TCurrencyField; cdsAdvertisingID: TIntegerField; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure cdsAdvertisingCalcFields(DataSet: TDataSet); procedure tmrSyncAdvTimer(Sender: TObject); private FLocalPath : String; FIP : String; FPort : Integer; FThreadConnectMRPDS: TThreadConnectMRPDS; procedure CloseAdvertising; procedure OpenAdvertising; procedure LoadAdvertising; procedure CloseCrossSale; procedure OpenCrossSale; procedure LoadCrossSale; procedure AddCrossSaleItem(AFile : String; AType, ATimer : Integer); procedure SaveCrossSaleItemHistory(AModelNum, ARegister : String; ADate : TDateTime); procedure SynchMRPDS; procedure ThreadConnectMRPDSTerminate(Sender: TObject); procedure AfterSynchAdvertising; procedure AfterSynchCrossSaleItem; public FScreenConfig : TScreenConfig; FConfigFile: TIniFile; procedure RefreshScreenConfig; procedure RefreshAdvertising; procedure SaveAdvertising; procedure RefreshCrossSale; procedure SetServerConn(AIP : String; APort : Integer); function GetCrossSaleItems(AModelNum, ARegister : String): Boolean; property LocalPath : String read FLocalPath; procedure ClearCrossSale; end; var DM: TDM; implementation uses uPoleDisplay, uInvoicePollDisplayConst, uParamFunctions, uDateTimeFunctions, uDMGlobal; {$R *.dfm} procedure TDM.CloseAdvertising; begin with cdsAdvertising do if Active then Close; end; procedure TDM.DataModuleCreate(Sender: TObject); begin FLocalPath := ExtractFilePath(Application.ExeName); if not FileExists(ChangeFileExt( Application.ExeName, '.ini')) then FileCreate(ChangeFileExt( Application.ExeName, '.ini')); FConfigFile := TIniFile.Create(ChangeFileExt( Application.ExeName, '.ini')); FScreenConfig := TScreenConfig.Create; tmrSyncAdv.Enabled := True; RefreshScreenConfig; DMGlobal.IDLanguage := FScreenConfig.FIDLanguage; SynchMRPDS; OpenAdvertising; OpenCrossSale; end; procedure TDM.DataModuleDestroy(Sender: TObject); begin if IdTCPClient.Connected then begin IdTCPClient.DisconnectSocket; IdTCPClient.Disconnect; end; FreeAndNil(FConfigFile); FreeAndNil(FScreenConfig); CloseAdvertising; CloseCrossSale; end; procedure TDM.SaveAdvertising; begin try cdsAdvertising.SaveToFile(FLocalPath + 'Advertising.xml', dfXMLUTF8); except end; end; procedure TDM.LoadAdvertising; begin if FileExists(FLocalPath + 'Advertising.xml') then cdsAdvertising.LoadFromFile(FLocalPath + 'Advertising.xml'); end; procedure TDM.OpenAdvertising; begin with cdsAdvertising do if not Active then begin CreateDataSet; LoadAdvertising; end; end; procedure TDM.RefreshAdvertising; begin CloseAdvertising; OpenAdvertising; end; procedure TDM.RefreshCrossSale; begin CloseCrossSale; OpenCrossSale; end; procedure TDM.RefreshScreenConfig; begin FScreenConfig.FMovingText := FConfigFile.ReadString(SCREEN_CONF, SCREEN_CONF_MOVING_TEXT, ''); FScreenConfig.FTextSpeed := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_CONF_TEXT_SPEED, 1000); FScreenConfig.FTextSize := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_CONFIG_TEXT_SIZE, 0); FScreenConfig.FReceiptPos := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_CONF_RECEIPT_POS, 0); FScreenConfig.FLogo := FConfigFile.ReadString(SCREEN_CONF, SCREEN_CONF_RECEIPT_LOGO, ''); FScreenConfig.FVideoLeft := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_CONF_VIDEO_LEFT, 50); FScreenConfig.FVideoTop := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_CONF_VIDEO_TOP, 50); FScreenConfig.FVideoRight := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_CONF_VIDEO_RIGHT, 300); FScreenConfig.FVideoBottom := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_CONF_VIDEO_BOTTOM, 300); FScreenConfig.FComputerIP := FConfigFile.ReadString(SCREEN_CONF, SCREEN_CONF_COMPUTER_IP, ''); FScreenConfig.FCompPort := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_CONF_COMPUTER_PORT, 9091); FScreenConfig.FStoreAdd1 := FConfigFile.ReadString(SCREEN_CONF, SCREEN_CONF_STORE_ADD1, ''); FScreenConfig.FStoreAdd2 := FConfigFile.ReadString(SCREEN_CONF, SCREEN_CONF_STORE_ADD2, ''); FScreenConfig.FStoreAdd3 := FConfigFile.ReadString(SCREEN_CONF, SCREEN_CONF_STORE_ADD3, ''); FScreenConfig.FReceiptBackColor := StringToColor(FConfigFile.ReadString(SCREEN_CONF, SCREEN_CONF_RECEIPT_BACKCOLOR, '$00F2E3D0')); FScreenConfig.FTextColor := StringToColor(FConfigFile.ReadString(SCREEN_CONF, SCREEN_CONFIG_TEXT_COLOR, 'clYellow')); FScreenConfig.FReceiptTextColor := StringToColor(FConfigFile.ReadString(SCREEN_CONF, SCREEN_CONF_RECEIPT_TEXTCOLOR, 'clBlack')); FScreenConfig.FStationName := FConfigFile.ReadString(SCREEN_CONF, SCREEN_SVR_STATION, ''); FScreenConfig.FServerIP := FConfigFile.ReadString(SCREEN_CONF, SCREEN_SVR_IP, ''); FScreenConfig.FServerPort := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_SVR_PORT, 7887); FScreenConfig.FIDLanguage := FConfigFile.ReadInteger(SCREEN_CONF, SCREEN_IDLANGUAGE, 1); FScreenConfig.FAutoResizeAdv := FConfigFile.ReadBool(SCREEN_CONF, SCREEN_RESIZE_ADV, False); SetServerConn(FScreenConfig.FServerIP, FScreenConfig.FServerPort); end; procedure TDM.cdsAdvertisingCalcFields(DataSet: TDataSet); var FWeekDays : String; begin FWeekDays := ''; if Pos('1,', cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Monday; '; if Pos('2,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Tuesday; '; if Pos('3,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Wednesday; '; if Pos('4,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Thursday; '; if Pos('5,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Friday; '; if Pos('6,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Saturday; '; if Pos('7,' ,cdsAdvertisingDaysOfWeek.AsString) > 0 then FWeekDays := FWeekDays + 'Sunday; '; cdsAdvertisingDaysOfWeekString.AsString := FWeekDays; case cdsAdvertisingType.AsInteger of ADV_BITMAP : cdsAdvertisingTypeString.AsString := 'Bitmap'; ADV_JPG : cdsAdvertisingTypeString.AsString := 'JPG'; ADV_VIDEO : cdsAdvertisingTypeString.AsString := 'Video'; ADV_FLASH : cdsAdvertisingTypeString.AsString := 'Flash'; ADV_WEB : cdsAdvertisingTypeString.AsString := 'Website'; end; end; procedure TDM.SetServerConn(AIP: String; APort: Integer); begin if (AIP <> '') then begin { if IdTCPClient.Connected then IdTCPClient.Disconnect; IdTCPClient.Host := AIP; IdTCPClient.Port := APort; } FIP := AIP; FPort := APort; end; end; (* function TDM.GetCrossSaleItems(AModelNum, ARegister: String): String; begin Result := ''; try if not IdTCPClient.Connected then IdTCPClient.Connect(5); if IdTCPClient.Connected then begin IdTCPClient.WriteLn(FormatModelNum(AModelNum, ARegister)); Result := IdTCPClient.ReadLn(); end; except end; end; *) function TDM.GetCrossSaleItems(AModelNum, ARegister: String): Boolean; begin Result := False; with cdsCrossSaleItem do if Locate('ModelNum', AModelNum, []) then try //Save Model to history SaveCrossSaleItemHistory(AModelNum, ARegister, Now); Filtered := False; Filter := 'ModelNum = ' + QuotedStr(AModelNum); Filtered := True; //Loop Return Item advertising First; While not EOF do begin AddCrossSaleItem(FieldByName('FileName').AsString, FieldByName('FileType').AsInteger, FieldByName('Duration').AsInteger); Next; end; Result := True; finally Filter := ''; Filtered := False; end; end; procedure TDM.CloseCrossSale; begin with cdsCrossSaleItem do if Active then Close; with cdsSaleSuggestion do if Active then Close; end; procedure TDM.LoadCrossSale; begin if FileExists(FLocalPath + 'CrossSaleItem.xml') then cdsCrossSaleItem.LoadFromFile(FLocalPath + 'CrossSaleItem.xml'); end; procedure TDM.OpenCrossSale; begin with cdsCrossSaleItem do if not Active then begin CreateDataSet; LoadCrossSale; end; with cdsSaleSuggestion do if not Active then CreateDataSet; end; procedure TDM.AddCrossSaleItem(AFile: String; AType, ATimer: Integer); begin OpenCrossSale; with cdsSaleSuggestion do if not Locate('FileName', AFile, []) then begin Append; FieldByName('FileName').AsString := AFile; FieldByName('FileType').AsInteger := AType; FieldByName('Duration').AsInteger := ATimer; Post; end; end; procedure TDM.tmrSyncAdvTimer(Sender: TObject); begin tmrSyncAdv.Enabled := False; try SynchMRPDS; finally //tmrSyncAdv.Enabled := True; end; end; procedure TDM.SynchMRPDS; begin if FThreadConnectMRPDS <> nil then if FThreadConnectMRPDS.Terminated then Exit else FreeAndNil(FThreadConnectMRPDS); FThreadConnectMRPDS := TThreadConnectMRPDS.Create(True); FThreadConnectMRPDS.IP := FIP; FThreadConnectMRPDS.Port := FPort; FThreadConnectMRPDS.FreeOnTerminate := True; FThreadConnectMRPDS.OnTerminate := ThreadConnectMRPDSTerminate; FThreadConnectMRPDS.AfterSynchAdvertising := AfterSynchAdvertising; FThreadConnectMRPDS.AfterSynchCrossSaleItem := AfterSynchCrossSaleItem; FThreadConnectMRPDS.Resume; end; procedure TDM.ThreadConnectMRPDSTerminate(Sender: TObject); begin FThreadConnectMRPDS := nil; end; procedure TDM.ClearCrossSale; begin OpenCrossSale; with cdsSaleSuggestion do begin First; while not EOF do begin Edit; Delete; end; end; end; procedure TDM.SaveCrossSaleItemHistory(AModelNum, ARegister: String; ADate: TDateTime); begin // end; procedure TDM.AfterSynchAdvertising; begin end; procedure TDM.AfterSynchCrossSaleItem; begin end; end.
unit uPaymentGiftCard; interface uses uPayment, ADODB; type TPaymentGiftCard = class(TPayment) private // Antonio, August 09, 2013 FIsMercuryGiftCard: Boolean; FIDGiftCard: Integer; FAmountGiftCard: Currency; FCardNumber: String; procedure setMercuryGiftCard(value: Boolean); procedure SetCardNumber(const Value: String); procedure InsertGiftCardMov; procedure DeleteGiftCardMov; procedure UpdateGiftCardBalance(ACredit: Boolean); function GetNewIDGiftCardMov: Integer; protected procedure OnProcessPayment; override; procedure BeforeDeletePayment; override; procedure FillParameters(FCmdPayment: TADOCommand); override; procedure SetProperties(ADSPayment: TADODataSet); override; function GetSQLFields: String; override; function GetAutoProcess: Boolean; override; function ValidatePayment: Boolean; override; procedure BeforeProcessPayment; override; public function GetPaymentType: Integer; override; property IsMercuryGiftCard: Boolean write setMercuryGiftCard; property CardNumber: String read FCardNumber write SetCardNumber; end; implementation uses uSystemConst, DB, SysUtils, uMsgConstant, Math, uDocumentInfo; { TPaymentGiftCard } procedure TPaymentGiftCard.BeforeDeletePayment; begin FTraceControl.TraceIn(Self.ClassName + '.BeforeDeletePayment'); DeleteGiftCardMov; UpdateGiftCardBalance(True); FTraceControl.TraceOut; end; procedure TPaymentGiftCard.DeleteGiftCardMov; begin FTraceControl.TraceIn(Self.ClassName + '.DeleteGiftCardMov'); with TADOCommand.Create(nil) do try Connection := FADOConnection; CommandText := 'DELETE Sal_AccountCardMov WHERE IDLancamento = :IDLancamento'; Parameters.ParamByName('IDLancamento').Value := FIDPayment; Execute; finally Free; end; FTraceControl.TraceOut; end; procedure TPaymentGiftCard.FillParameters(FCmdPayment: TADOCommand); begin inherited; FCmdPayment.Parameters.ParamByName('NumMeioQuitPrevisto').Value := FCardNumber; end; function TPaymentGiftCard.GetAutoProcess: Boolean; begin Result := True; end; function TPaymentGiftCard.GetNewIDGiftCardMov: Integer; begin FTraceControl.TraceIn(Self.ClassName + '.GetNewIDGiftCardMov'); Result := 0; with TADOStoredProc.Create(nil) do try Connection := FADOConnection; ProcedureName := 'sp_Sis_GetNextCode;1'; Parameters.Refresh; Parameters.ParamByName('@Tabela').Value := 'Sal_AccountCardMov.IDAccountCardMov'; ExecProc; Result := Parameters.ParamByName('@NovoCodigo').Value; finally Free; end; FTraceControl.TraceOut; end; function TPaymentGiftCard.GetPaymentType: Integer; begin Result := PAYMENT_TYPE_GIFTCARD; end; function TPaymentGiftCard.GetSQLFields: String; begin Result := (inherited GetSQLFields) + ',NumMeioQuitPrevisto'; end; procedure TPaymentGiftCard.InsertGiftCardMov; begin FTraceControl.TraceIn(Self.ClassName, '.InsertGiftCardMov'); case DocumentType of dtInvoice: with TADOCommand.Create(nil) do try Connection := FADOConnection; CommandText := 'INSERT Sal_AccountCardMov(IDAccountCardMov,DateMov,Value,Credit,IDPreSale,IDLancamento,IDUser,IDAccountCard)' + 'VALUES(:IDAccountCardMov,GetDate(),:Amount,0,:IDPreSale,:IDLancamento,:IDUser,:IDAccountCard)'; Parameters.ParamByName('IDAccountCardMov').Value := GetNewIDGiftCardMov; Parameters.ParamByName('Amount').Value := FPaymentValue; Parameters.ParamByName('IDPreSale').Value := FIDPreSale; Parameters.ParamByName('IDLancamento').Value := FIDPayment; Parameters.ParamByName('IDUser').Value := FIDUser; Parameters.ParamByName('IDAccountCard').Value := FIDGiftCard; Execute; finally Free; end; dtServiceOrder:; end; FTraceControl.TraceOut; end; procedure TPaymentGiftCard.BeforeProcessPayment; begin inherited; if (FAmountGiftCard <> 0) and (FPaymentValue > FAmountGiftCard) then FPaymentValue := FAmountGiftCard; end; procedure TPaymentGiftCard.OnProcessPayment; begin inherited; FTraceControl.TraceIn(Self.ClassName, '.OnProcessPayment'); InsertGiftCardMov; UpdateGiftCardBalance(False); FTraceControl.TraceOut; end; procedure TPaymentGiftCard.SetCardNumber(const Value: String); begin FTraceControl.TraceIn(Self.ClassName + '.GetIDGiftCard'); FCardNumber := Value; with TADODataSet.Create(nil) do try Connection := FADOConnection; CommandText := 'SELECT A.IDAccountCard, A.Amount ' + 'FROM Sal_AccountCard A ' + 'WHERE A.CardNumber = :CardNumber '; Parameters.ParamByName('CardNumber').Value := FCardNumber; Open; FIDGiftCard := FieldByName('IDAccountCard').AsInteger; FAmountGiftCard := FieldByName('Amount').AsCurrency; finally Free; end; FTraceControl.TraceOut; end; procedure TPaymentGiftCard.SetProperties(ADSPayment: TADODataSet); begin inherited; CardNumber := ADSPayment.FieldByName('NumMeioQuitPrevisto').AsString; end; procedure TPaymentGiftCard.UpdateGiftCardBalance(ACredit: Boolean); begin FTraceControl.TraceIn(Self.ClassName, '.InsertGiftCardMov'); with TADOCommand.Create(nil) do try Connection := FADOConnection; CommandText := 'UPDATE Sal_AccountCard ' + 'SET Amount = Amount + :Amount ' + 'WHERE IDAccountCard = :IDAccountCard'; Parameters.ParamByName('Amount').Value := IfThen(ACredit, FPaymentValue, FPaymentValue*-1); Parameters.ParamByName('IDAccountCard').Value := FIDGiftCard; Execute; finally Free; end; FTraceControl.TraceOut; end; function TPaymentGiftCard.ValidatePayment: Boolean; begin FTraceControl.TraceIn(Self.ClassName, '.ValidatePayment'); Result := inherited ValidatePayment; // Antonio, August 09, 2013 - Mercury will be loaded by swiped event (card reader) if ( FIsMercuryGiftCard ) then begin result := true; exit; end; if FIDGiftCard = 0 then begin Result := False; FErrorMsg := Format(MSG_CRT_NO_GIFT_ACCOUNT, [FCardNumber]); raise Exception.Create(FErrorMsg); end; case DocumentType of dtInvoice: with TADODataSet.Create(nil) do try Connection := FADOConnection; CommandText := 'SELECT L.IDLancamento ' + 'FROM Fin_Lancamento L ' + 'WHERE L.NumMeioQuitPrevisto = :CardNumber '+ 'AND L.IDPreSale = :IDPreSale'; Parameters.ParamByName('CardNumber').Value := FCardNumber; Parameters.ParamByName('IDPreSale').Value := FIDPreSale; Open; Result := IsEmpty; if not Result then begin FErrorMsg := Format('Card %S has already been entered on this sale', [FCardNumber]); raise Exception.Create(FErrorMsg); end; finally Close; Free; end; dtServiceOrder:; end; if FAmountGiftCard <= 0 then begin Result := False; FErrorMsg := 'Gift Card balance is 0'; raise Exception.Create(FErrorMsg); end; FTraceControl.TraceOut; end; procedure TPaymentGiftCard.setMercuryGiftCard(value: Boolean); begin FIsMercuryGiftCard := value; end; end.
unit CMoveOldFilesAgent; interface uses CDBMiddleEngine, VMoveOldFileParamsForms; type TMoveOldFilesAgent = class( TObject ) private FDialogParamsForm: TMoveOldFilesParamsForm; FParams: TMoveRecFilesParams; procedure copyParamsToForm; procedure copyFormToParams; procedure doMoveOldRecs; public constructor Create; virtual; destructor Destroy; override; procedure Execute; end; implementation uses Controls, UGlobalData; // ^^^^^^^^^^^^^^^^ // MÉTODOS PRIVADOS // ^^^^^^^^^^^^^^^^ procedure TMoveOldFilesAgent.copyParamsToForm; begin if assigned( FDialogParamsForm ) then begin FDialogParamsForm.fechaCorteEdit.Date := FParams.fechaCorte; FDialogParamsForm.borrarOLDCheckBox.Checked := FParams.borrarOldFiles; FDialogParamsForm.borrarDELCheckBox.Checked := FParams.borrarDelFiles; FDialogParamsForm.Refresh(); end end; procedure TMoveOldFilesAgent.copyFormToParams; begin FParams.fechaCorte := FDialogParamsForm.fechaCorteEdit.Date; FParams.borrarOldFiles := FDialogParamsForm.borrarOLDCheckBox.Checked; FParams.borrarDelFiles := FDialogParamsForm.borrarDELCheckBox.Checked; end; procedure TMoveOldFilesAgent.doMoveOldRecs; begin TheDBMiddleEngine.lockGlobalRecords(getStationID()); try finally TheDBMiddleEngine.unlockGlobalRecords() end end; // ^^^^^^^^^^^^^^^^ // MÉTODOS PÚBLICOS // ^^^^^^^^^^^^^^^^ // CONSTRUCTORES Y DESTRUCTORES constructor TMoveOldFIlesAgent.Create; begin inherited; FParams := TMoveRecFilesParams.Create(); FDialogParamsForm := TMoveOldFilesParamsForm.Create(nil); end; destructor TMoveOldFilesAgent.Destroy; begin FDialogParamsForm.free(); FParams.Free(); inherited; end; // OTROS procedure TMoveOldFilesAgent.Execute; begin copyParamsToForm(); if FDialogParamsForm.ShowModal() = mrOK then begin copyFormToParams(); // ya tenemos los parámetros para mover los registros viejos doMoveOldRecs(); end; end; end.
unit frmMainUI; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin, OoMisc, AdPort, AdWnPort; type TformMainUI = class(TForm) memoLog: TMemo; btnLeft: TButton; btnRight: TButton; SpinEdit1: TSpinEdit; Label1: TLabel; COM: TApdComPort; btnConnect: TButton; btnDisconnect: TButton; procedure btnSideClick(Sender: TObject); procedure btnConnectClick(Sender: TObject); procedure btnDisconnectClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private fData: String; procedure updateStatus; procedure readData; public end; var formMainUI: TformMainUI; implementation {$R *.dfm} procedure TformMainUI.FormCreate(Sender: TObject); begin updateStatus; end; procedure TformMainUI.FormClose(Sender: TObject; var Action: TCloseAction); begin COM.FlushInBuffer; COM.FlushOutBuffer; COM.Open := false; end; procedure TformMainUI.btnDisconnectClick(Sender: TObject); begin try memoLog.Lines.Add('Disconnect....'); COM.Open := false; memoLog.Lines.Add('Disconnected!'); except on e: exception do begin memoLog.Lines.Add('Disconnecting Error : ' + e.Message); end; end; updateStatus; end; procedure TformMainUI.btnSideClick(Sender: TObject); var data: string; idx: integer; begin try COM.FlushInBuffer; COM.FlushOutBuffer; if Sender = btnLeft then COM.PutChar('L') else if Sender = btnRight then COM.PutChar('R'); sleep(250); except on e: exception do begin showmessage('Serial Error : ' + e.Message); end; end; readData; updateStatus; end; procedure TformMainUI.btnConnectClick(Sender: TObject); begin try memoLog.Lines.Add('Connecting....'); COM.ComNumber := SpinEdit1.Value; COM.Baud := 115200; COM.Open := TRUE; sleep(250); readData; memoLog.Lines.Add('Connected!'); except on e: exception do begin memoLog.Lines.Add('Connecting Error : ' + e.Message); end; end; updateStatus; end; procedure TformMainUI.updateStatus; begin btnConnect.Enabled := not COM.Open; btnDisconnect.Enabled := COM.Open; btnLeft.Enabled := COM.Open; btnRight.Enabled := COM.Open; end; procedure TformMainUI.readData; begin try if not COM.Open then exit; sleep(500); while COM.CharReady do fData := fData + COM.GetChar; finally if pos(#13, fData) > 0 then begin memoLog.Lines.Add(fData); fData := ''; end; end; end; end.
unit UCommon; interface const // Reference // http://theroadtodelphi.wordpress.com/2010/08/07/using-the-google-maps-api-v3-from-delphi-part-i-basic-functionality/ // // Geocoding // https://developers.google.com/maps/documentation/geocoding/?hl=ja MapHTMLStr: AnsiString = '<!DOCTYPE html>' + '<html> ' + '<head> ' + '<meta name="viewport" content="initial-scale=1.0, user-scalable=yes" /> ' + '<meta charset="utf-8">'+ ' <style type="text/css">'+ ' html, body, #map-canvas {'+ ' height: 100%;'+ ' margin: 0px;'+ ' padding: 0px;'+ ' }'+ ' </style>'+ '<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> '+ '<script type="text/javascript"> ' + '' + '' + ' var geocoder; ' + ' var map; ' + ' var trafficLayer;' + ' var bikeLayer;' + ' var markersArray = [];' + '' + '' + ' function initialize() { ' + ' geocoder = new google.maps.Geocoder();' + ' var latlng = new google.maps.LatLng(35.650222,139.44818680000003); ' +// @keiou ' var myOptions = { ' + ' zoom: 13, ' + ' center: latlng, ' + ' mapTypeId: google.maps.MapTypeId.ROADMAP ' + // ' scaleControl: true'+ ' }; ' + ' map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); ' + ' trafficLayer = new google.maps.TrafficLayer();' + ' bikeLayer = new google.maps.BicyclingLayer();' + ' map.set("streetViewControl", true);' + ' } ' + '' + '' + ' function showAddress(address,infoWinTitle,infoWinHTML) { ' + ' if (geocoder) {' + ' geocoder.geocode( { address: address}, function(results, status) { ' + ' if (status == google.maps.GeocoderStatus.OK) {' + ' map.setCenter(results[0].geometry.location);' + // ' PutMarker(results[0].geometry.location.lat(), results[0].geometry.location.lng(), results[0].geometry.location.lat()+","+results[0].geometry.location.lng());' + ' PutMarker(results[0].geometry.location.lat(), results[0].geometry.location.lng(), infoWinTitle,infoWinHTML);' + ' } else {' + //' alert("Geocode error: " + status);' + ' }' + ' });' + ' }' + ' }' + '' + '' + ' function GotoLatLng(Lat, Lang) { ' + ' var latlng = new google.maps.LatLng(Lat,Lang);' + ' map.setCenter(latlng);' + ' PutMarker(Lat, Lang, Lat+","+Lang,"");' + ' }' + '' + '' + 'function ClearMarkers() { ' + ' if (markersArray) { ' + ' for (i in markersArray) { ' + ' markersArray[i].setMap(null); ' + ' } ' + ' } ' + '} ' + '' + ' function PutMarker(Lat, Lang, Msg, Body) { ' + ' var latlng = new google.maps.LatLng(Lat,Lang);' + ' var marker = new google.maps.Marker({' + ' position: latlng, ' + ' map: map,' + ' title: Msg+" ("+Lat+","+Lang+")"' + ' });' + // added ' var infowindow = new google.maps.InfoWindow({' + 'content: Body' + // here ' });' + ' google.maps.event.addListener(marker, "click", function() {' + ' infowindow.open(map,marker);' + ' });' + // ' markersArray.push(marker); ' + ' }' + '' + '' + ' function TrafficOn() { trafficLayer.setMap(map); }' + '' + ' function TrafficOff() { trafficLayer.setMap(null); }' + '' + '' + ' function BicyclingOn() { bikeLayer.setMap(map); }' + '' + ' function BicyclingOff(){ bikeLayer.setMap(null); }' + '' + ' function StreetViewOn() { map.set("streetViewControl", true); }' + '' + ' function StreetViewOff() { map.set("streetViewControl", false); }' + '' + '' + '</script> ' + '</head> ' + '<body onload="initialize()"> ' + ' <div id="map_canvas" style="width:100%; height:100%"></div> ' + '</body> ' + '</html> '; implementation end.
unit FHIRProfileUtilities; interface uses SysUtils, Classes, StringSupport, AdvObjects, AdvGenerics, FHIRBase, FHIRResources, FHIRTypes, FHIRUtilities, FHIRConstants; Const DERIVATION_EQUALS = 'derivation.equals'; IS_DERIVED = 'derived.fact'; type TValidationResult = class (TAdvObject) private FSeverity : TFhirIssueSeverity; FMessage : String; public constructor Create(Severity : TFhirIssueSeverity; Message : String); virtual; Property Severity : TFhirIssueSeverity read FSeverity write FSeverity; Property Message : String read FMessage write FMessage; function isOk : boolean; end; TValidatorServiceProvider = {abstract} class (TAdvObject) public function fetchResource(t : TFhirResourceType; url : String) : TFhirResource; virtual; abstract; function expand(vs : TFhirValueSet) : TFHIRValueSet; virtual; abstract; function supportsSystem(system : string) : boolean; virtual; abstract; function validateCode(system, code, display : String) : TValidationResult; overload; virtual; abstract; function validateCode(system, code, version : String; vs : TFhirValueSet) : TValidationResult; overload; virtual; abstract; function validateCode(code : TFHIRCoding; vs : TFhirValueSet) : TValidationResult; overload; virtual; abstract; function validateCode(code : TFHIRCodeableConcept; vs : TFhirValueSet) : TValidationResult; overload; virtual; abstract; end; { for when we add table generation } // TExtensionContext = class (TAdvObject) // private // FDefinition : TFhirStructureDefinition; // FElement : TFhirElementDefinition; // // public // Constructor Create(definition : TFhirStructureDefinition; element : TFhirElementDefinition); // Destructor Destroy; override; // // Property Element : TFhirElementDefinition read FElement; // Property Definition : TFhirStructureDefinition read FDefinition; // end; TProfileUtilities = class (TAdvObject) private context : TValidatorServiceProvider; messages : TFhirOperationOutcomeIssueList; procedure log(message : String); function fixedPath(contextPath, pathSimple : String) : String; function getDiffMatches(context : TFhirStructureDefinitionDifferential; path : String; istart, iend : integer; profileName : String) : TAdvList<TFhirElementDefinition>; function updateURLs(url : String; element : TFhirElementDefinition) : TFhirElementDefinition; procedure updateFromBase(derived, base : TFhirElementDefinition); procedure markDerived(outcome : TFhirElementDefinition); procedure updateFromDefinition(dest, source : TFhirElementDefinition; pn : String; trimDifferential : boolean; purl : String); function isDataType(value : String) : boolean; overload; function isDataType(types : TFhirElementDefinitionTypeList) : boolean; overload; function typeCode(types : TFhirElementDefinitionTypeList) : String; function pathStartsWith(p1, p2 : String) : boolean; function getProfileForDataType(type_ : TFhirElementDefinitionType) : TFHIRStructureDefinition; function unbounded(definition : TFhirElementDefinition) : boolean; function isSlicedToOneOnly(definition : TFhirElementDefinition) : boolean; function isExtension(definition : TFhirElementDefinition) : boolean; function makeExtensionSlicing : TFhirElementDefinitionSlicing; function findEndOfElement(context : TFhirStructureDefinitionDifferential; cursor : integer) : integer; overload; function findEndOfElement(context : TFhirStructureDefinitionSnapshot; cursor : integer) : integer; overload; function orderMatches(diff, base : TFHIRBoolean) : boolean; function discriiminatorMatches(diff, base : TFhirStringList) : boolean; function ruleMatches(diff, base : TFhirResourceSlicingRules) : boolean; function summariseSlicing(slice : TFhirElementDefinitionSlicing) : String; procedure updateFromSlicing(dst, src : TFhirElementDefinitionSlicing); function getSiblings(list : TFhirElementDefinitionList; current : TFhirElementDefinition) : TAdvList<TFhirElementDefinition>; procedure processPaths(result, base : TFhirStructureDefinitionSnapshot; differential: TFhirStructureDefinitionDifferential; baseCursor, diffCursor, baseLimit, diffLimit : integer; url, profileName, contextPath : String; trimDifferential : boolean; contextName, resultPathBase : String; slicingHandled : boolean); public Constructor create(context : TValidatorServiceProvider; messages : TFhirOperationOutcomeIssueList); { * Given a base (snapshot) profile structure, and a differential profile, generate a snapshot profile * * @param base - the base structure on which the differential will be applied * @param differential - the differential to apply to the base * @param url - where the base has relative urls for profile references, these need to be converted to absolutes by prepending this URL * @return * @throws Exception } procedure generateSnapshot(base, derived : TFHIRStructureDefinition; url, profileName : String); end; function uncapitalize(s : String) : string; function capitalize(s : String) : string; implementation { TProfileUtilities } constructor TProfileUtilities.create(context : TValidatorServiceProvider; messages : TFhirOperationOutcomeIssueList); begin inherited Create; self.context := context; self.messages := messages; end; procedure TProfileUtilities.generateSnapshot(base, derived : TFHIRStructureDefinition; url, profileName : String); var baseCursor, diffCursor: Integer; begin if (base = nil) then raise Exception.create('no base profile provided'); if (derived = nil) then raise Exception.create('no derived structure provided'); derived.Snapshot := TFhirStructureDefinitionSnapshot.create(); // so we have two lists - the base list, and the differential list // the differential list is only allowed to include things that are in the base list, but // is allowed to include them multiple times - thereby slicing them // our approach is to walk through the base list, and see whether the differential // says anything about them. baseCursor := 0; diffCursor := 0; // we need a diff cursor because we can only look ahead, in the bound scoped by longer paths // we actually delegate the work to a subroutine so we can re-enter it with a different cursors processPaths(derived.Snapshot, base.Snapshot, derived.Differential, baseCursor, diffCursor, base.Snapshot.elementList.Count-1, derived.differential.elementList.Count-1, url, derived.Id, '', false, base.Url, '', false); end; function pathTail(d : TFHIRElementDefinition) : String; var s : String; begin if d.Path.contains('.') then s := d.Path.substring(d.Path.lastIndexOf('.')+1) else s := d.Path; if (d.type_List.Count > 0) and (d.type_List[0].profileList.Count > 0) then result := '.' + s else result := '.' + s + '['+d.type_List[0].profileList[0].value+']'; end; procedure TProfileUtilities.processPaths(result, base : TFhirStructureDefinitionSnapshot; differential: TFhirStructureDefinitionDifferential; baseCursor, diffCursor, baseLimit, diffLimit : integer; url, profileName, contextPath : String; trimDifferential : boolean; contextName, resultPathBase : String; slicingHandled : boolean); var currentBase : TFhirElementDefinition; cpath, path, p : String; diffMatches : TAdvList<TFhirElementDefinition>; outcome, original, baseItem, diffItem, template : TFhirElementDefinition; dt, sd : TFHIRStructureDefinition; nbl, ndc, ndl, start, i, diffpos : integer; closed, isExt : boolean; dSlice, bSlice : TFhirElementDefinitionSlicing; baseMatches : TAdvList<TFhirElementDefinition>; begin // just repeat processing entries until we run out of our allowed scope (1st entry, the allowed scope is all the entries) while (baseCursor <= baseLimit) do begin // get the current focus of the base, and decide what to do currentBase := base.elementList[baseCursor]; cpath := fixedPath(contextPath, currentBase.path); diffMatches := getDiffMatches(differential, cpath, diffCursor, diffLimit, profileName); // get a list of matching elements in scope // in the simple case, source is not sliced. if (currentBase.slicing = nil) then begin if (diffMatches.count = 0) then begin // the differential doesn't say anything about this item log(cpath+': no match in the differential'); // so we just copy it in outcome := updateURLs(url, currentBase.Clone()); outcome.path := fixedPath(contextPath, outcome.path); updateFromBase(outcome, currentBase); markDerived(outcome); if (resultPathBase = '') then resultPathBase := outcome.path else if (not outcome.path.startsWith(resultPathBase)) then raise Exception.create('Adding wrong path'); result.elementList.add(outcome); inc(baseCursor); end else if (diffMatches.Count = 1) and (slicingHandled or (diffMatches[0].slicing = nil)) then begin // one matching element in the differential log(cpath+': single match in the differential at '+inttostr(diffCursor)); template := nil; if (diffMatches[0].type_List.Count = 1) and (diffMatches[0].type_List[0].profileList.count > 0) and (diffMatches[0].type_List[0].Code <> 'Reference') then begin p := diffMatches[0].type_List[0].profileList[0].value; sd := context.fetchResource(frtStructureDefinition, p) as TFhirStructureDefinition; if (sd <> nil) then begin template := sd.Snapshot.elementList[0].Clone; template.Path := currentBase.path; if (diffMatches[0].type_List[0].Code <> 'Extension') then begin template.min := currentBase.min; template.max := currentBase.max; end; end; end; if (template = nil) then template := currentBase.Clone; outcome := updateURLs(url, template); outcome.path := fixedPath(contextPath, outcome.path); updateFromBase(outcome, currentBase); outcome.name := diffMatches[0].Name; outcome.slicing := nil; updateFromDefinition(outcome, diffMatches[0], profileName, trimDifferential, url); if (outcome.path.endsWith('[x]')) and (outcome.type_List.Count = 1 ) and (outcome.type_List[0].code <> '*') then // if the base profile allows multiple types, but the profile only allows one, rename it outcome.path := outcome.path.substring(0, outcome.path.length-3)+ capitalize(outcome.type_List[0].code); if (resultPathBase = '') then resultPathBase := outcome.path else if (not outcome.path.startsWith(resultPathBase)) then raise Exception.create('Adding wrong path'); result.elementList.add(outcome); inc(baseCursor); diffCursor := differential.elementList.indexOf(diffMatches[0])+1; if (differential.elementList.Count > diffCursor ) and ( outcome.path.contains('.') ) and ( isDataType(outcome.type_List)) then begin // don't want to do this for the root, since that's base, and we're already processing it if (pathStartsWith(differential.elementList[diffCursor].path, fixedPath(contextPath, diffMatches[0].path+'.'))) then begin if (outcome.type_List.Count > 1) then raise Exception.create(diffMatches[0].path+' has children ('+differential.elementList[diffCursor].path+') and multiple types ('+typeCode(outcome.type_List)+') in profile '+profileName); dt := getProfileForDataType(outcome.type_List[0]); if (dt = nil) then raise Exception.create(diffMatches[0].path+' has children ('+differential.elementList[diffCursor].path+') for type '+typeCode(outcome.type_List)+' in profile '+profileName+', but can''t find type'); log(cpath+': now walk into the profile '+dt.url); contextName := dt.url; start := diffCursor; while (differential.elementList.Count > diffCursor ) and ( pathStartsWith(differential.elementList[diffCursor].path, diffMatches[0].path+'.')) do inc(diffCursor); processPaths(result, dt.snapshot, differential, 1 { starting again on the data type, but skip the root }, start-1, dt.Snapshot.elementList.Count-1, diffCursor - 1, url, profileName+pathTail(diffMatches[0]), diffMatches[0].path, trimDifferential, contextName, resultPathBase, false); end; end; end else begin log(cpath+': differential slices this'); // ok, the differential slices the item. Let's check our pre-conditions to ensure that this is correct if (not unbounded(currentBase)) and (not isSlicedToOneOnly(diffMatches[0])) then // you can only slice an element that doesn't repeat if the sum total of your slices is limited to 1 // (but you might do that in order to split up constraints by type) raise Exception.create('Attempt to a slice an element that does not repeat: '+currentBase.path+'/'+currentBase.name+' from '+contextName); if (diffMatches[0].slicing = nil) and (not isExtension(currentBase)) then // well, the diff has set up a slice, but hasn't defined it. this is an error raise Exception.create('differential does not have a slice: '+currentBase.path); // well, if it passed those preconditions then we slice the dest. // we're just going to accept the differential slicing at face value outcome := updateURLs(url, currentBase.clone()); outcome.path := fixedPath(contextPath, outcome.path); updateFromBase(outcome, currentBase); if (diffMatches[0].slicing = nil) then outcome.slicing := makeExtensionSlicing() else outcome.slicing := diffMatches[0].slicing.clone(); if (not outcome.path.startsWith(resultPathBase)) then raise Exception.create('Adding wrong path'); result.elementList.add(outcome); // differential - if the first one in the list has a name, we'll process it. Else we'll treat it as the base definition of the slice. start := 0; if (diffMatches[0].name = '') then begin updateFromDefinition(outcome, diffMatches[0], profileName, trimDifferential, url); if (outcome.type_List.Count = 0) then raise Exception.create('not done yet'); start := 1; end; // now, for each entry in the diff matches, we're going to process the base item // our processing scope for base is all the children of the current path nbl := findEndOfElement(base, baseCursor); ndc := diffCursor; ndl := diffCursor; for i := start to diffMatches.Count-1 do begin // our processing scope for the differential is the item in the list, and all the items before the next one in the list ndc := differential.elementList.indexOf(diffMatches[i]); ndl := findEndOfElement(differential, ndc); // now we process the base scope repeatedly for each instance of the item in the differential list processPaths(result, base, differential, baseCursor, ndc, nbl, ndl, url, profileName+pathTail(diffMatches[i]), contextPath, trimDifferential, contextName, resultPathBase, true); end; // ok, done with that - next in the base list baseCursor := nbl+1; diffCursor := ndl+1; end; end else begin // the item is already sliced in the base profile. // here's the rules // 1. irrespective of whether the slicing is ordered or not, the definition order must be maintained // 2. slice element names have to match. // 3. TFHIR.createslices must be introduced at the end // corallory: you can't re-slice existing slices. is that ok? // we're going to need this: path := currentBase.path; original := currentBase; if (diffMatches.count = 0) then begin // the differential doesn't say anything about this item // copy across the currentbase, and all of it's children and siblings while (baseCursor < base.elementList.Count ) and ( base.elementList[baseCursor].path.startsWith(path)) do begin outcome := updateURLs(url, base.elementList[baseCursor].clone()); if (not outcome.path.startsWith(resultPathBase)) then raise Exception.create('Adding wrong path'); result.elementList.add(outcome); // so we just copy it in inc(baseCursor); end; end else begin // first - check that the slicing is ok closed := currentBase.slicing.rules = ResourceSlicingRulesClosed; diffpos := 0; isExt := cpath.endsWith('.extension') or cpath.endsWith('.modifierExtension'); if (diffMatches[0].slicing <> nil) then begin // it might be nil if the differential doesn't want to say anything about slicing if (not isExt) then inc(diffpos); // if there's a slice on the first, we'll ignore any content it has dSlice := diffMatches[0].slicing; bSlice := currentBase.slicing; if (not orderMatches(dSlice.orderedElement, bSlice.orderedElement)) then raise Exception.create('Slicing rules on differential ('+summariseSlicing(dSlice)+') do not match those on base ('+summariseSlicing(bSlice)+') - order @ '+path+' ('+contextName+')'); if (not discriiminatorMatches(dSlice.discriminatorList, bSlice.discriminatorList)) then raise Exception.create('Slicing rules on differential ('+summariseSlicing(dSlice)+') do not match those on base ('+summariseSlicing(bSlice)+') - disciminator @ '+path+' ('+contextName+')'); if (not ruleMatches(dSlice.rules, bSlice.rules)) then raise Exception.create('Slicing rules on differential ('+summariseSlicing(dSlice)+') do not match those on base ('+summariseSlicing(bSlice)+') - rule @ '+path+' ('+contextName+')'); end; outcome := updateURLs(url, currentBase.clone()); outcome.path := fixedPath(contextPath, outcome.path); updateFromBase(outcome, currentBase); if (diffMatches[0].slicing <> nil) and (not isExt) then begin updateFromSlicing(outcome.slicing, diffMatches[0].slicing); updateFromDefinition(outcome, diffMatches[0], profileName, closed, url); // if there's no slice, we don't want to update the unsliced description end; result.elementList.add(outcome); // now, we have two lists, base and diff. we're going to work through base, looking for matches in diff. baseMatches := getSiblings(base.elementList, currentBase); for baseItem in baseMatches do begin baseCursor := base.elementList.indexOf(baseItem); outcome := updateURLs(url, baseItem.clone()); updateFromBase(outcome, currentBase); outcome.path := fixedPath(contextPath, outcome.path); outcome.slicing := nil; if (not outcome.path.startsWith(resultPathBase)) then raise Exception.create('Adding wrong path'); if (diffMatches[diffpos].name = '') and (diffMatches[diffpos].slicing <> nil) then begin inc(diffpos); // todo: check slicing details match end; if (diffpos < diffMatches.Count) and (diffMatches[diffpos].name = outcome.name) then begin // if there's a diff, we update the outcome with diff // no? updateFromDefinition(outcome, diffMatches.get(diffpos), profileName, pkp, closed, url); //then process any children nbl := findEndOfElement(base, baseCursor); ndc := differential.elementList.indexOf(diffMatches[diffpos]); ndl := findEndOfElement(differential, ndc); // now we process the base scope repeatedly for each instance of the item in the differential list processPaths(result, base, differential, baseCursor, ndc, nbl, ndl, url, profileName+pathTail(diffMatches[diffpos]), contextPath, closed, contextName, resultPathBase, true); // ok, done with that - now set the cursors for if this is the end baseCursor := nbl+1; diffCursor := ndl+1; inc(diffpos); end else begin result.elementList.add(outcome); inc(baseCursor); // just copy any children on the base while (baseCursor < base.elementList.Count) and (base.elementList[baseCursor].path.startsWith(path)) and (base.elementList[baseCursor].path <> path) do begin outcome := updateURLs(url, currentBase.clone()); outcome.path := fixedPath(contextPath, outcome.path); if (not outcome.path.startsWith(resultPathBase)) then raise Exception.create('Adding wrong path'); result.elementList.add(outcome); inc(baseCursor); end; end; end; // finally, we process any remaining entries in diff, which are TFHIR.create(and which are only allowed if the base wasn't closed if (closed) and (diffpos < diffMatches.Count) then raise Exception.create('The base snapshot marks a slicing as closed, but the differential tries to extend it in '+profileName+' at '+path+' ('+cpath+')'); while (diffpos < diffMatches.Count) do begin diffItem := diffMatches[diffpos]; for baseItem in baseMatches do if (baseItem.name = diffItem.name) then raise Exception.create('Named items are out of order in the slice'); outcome := updateURLs(url, original.clone()); outcome.path := fixedPath(contextPath, outcome.path); updateFromBase(outcome, currentBase); outcome.slicing := nil; if (not outcome.path.startsWith(resultPathBase)) then raise Exception.create('Adding wrong path'); result.elementList.add(outcome); updateFromDefinition(outcome, diffItem, profileName, trimDifferential, url); inc(diffpos); end; end; end; end; end; procedure TProfileUtilities.markDerived(outcome : TFhirElementDefinition); //var // inv : TFhirElementDefinitionConstraint; begin // for inv in outcome.conditionList do // inv.Tags[IS_DERIVED] := true; end; function TProfileUtilities.summariseSlicing(slice : TFhirElementDefinitionSlicing) : String; var b : TStringBuilder; first : boolean; d : TFhirString; begin b := TStringBuilder.Create; try first := true; for d in slice.discriminatorList do begin if (first) then first := false else b.append(', '); b.append(d); end; b.append('('); if (slice.orderedElement <> nil) then b.append(slice.OrderedElement.StringValue); b.append('/'); if (slice.rulesElement <> nil) then b.append(slice.rulesElement.StringValue); b.append(')'); if (slice.description <> '') then begin b.append('"'); b.append(slice.description); b.append('"'); end; result := b.toString(); finally b.Free; end; end; procedure TProfileUtilities.updateFromBase(derived, base : TFhirElementDefinition); begin if (base.base <> nil) then begin derived.base := TFhirElementDefinitionBase.Create; derived.base.path := base.base.path; derived.base.Min := base.base.min; derived.base.Max := base.base.Max; end else begin derived.base := TFhirElementDefinitionBase.Create; derived.base.path := base.path; derived.base.Min := base.Min; derived.base.Max := base.Max; end; end; function TProfileUtilities.pathStartsWith(p1, p2 : String) : boolean; begin result := p1.startsWith(p2); end; function pathMatches(p1, p2 : string) : boolean; begin result := (p1 = p2) or (p2.endsWith('[x]')) and (p1.startsWith(p2.substring(0, p2.length-3))) and (not p1.substring(p2.length-3).contains('.')); end; function TProfileUtilities.fixedPath(contextPath, pathSimple : String) : String; begin if (contextPath = '') then result := pathSimple else result := contextPath+'.'+pathSimple.substring(pathSimple.indexOf('.')+1); end; function TProfileUtilities.getProfileForDataType(type_ : TFhirElementDefinitionType) : TFHIRStructureDefinition; begin result := nil; if (type_.profileList.Count > 0) then result := context.fetchResource(frtStructureDefinition, type_.profileList[0].StringValue) as TFhirStructureDefinition; if (result = nil) then result := context.fetchResource(frtStructureDefinition, 'http://hl7.org/fhir/StructureDefinition/'+type_.code) as TFhirStructureDefinition; if (result = nil) then writeln('XX: failed to find profle for type: ' + type_.code); // debug GJM end; function TProfileUtilities.typeCode(types : TFhirElementDefinitionTypeList) : String; var b : TStringBuilder; first : boolean; type_ : TFHIRElementDefinitionType; begin b := TStringBuilder.Create; try first := true; for type_ in types do begin if (first) then first := false else b.append(', '); b.append(type_.code); if (type_.profileList.count > 1) then b.append('{'+type_.profileList[0].StringValue+'}'); end; result := b.toString(); finally b.Free; end; end; function TProfileUtilities.isDataType(value : String) : boolean; begin result := StringArrayExistsSensitive(['Identifier', 'HumanName', 'Address', 'ContactPoint', 'Timing', 'SimpleQuantity', 'Quantity', 'Attachment', 'Range', 'Period', 'Ratio', 'CodeableConcept', 'Coding', 'SampledData', 'Age', 'Distance', 'Duration', 'Count', 'Money'], value); end; function isPrimitive(value : String) : boolean; begin result := (value = '') or StringArrayExistsInSensitive(['boolean', 'integer', 'decimal', 'base64Binary', 'instant', 'string', 'date', 'dateTime', 'code', 'oid', 'uuid', 'id', 'uri'], value); end; function TProfileUtilities.isDataType(types : TFhirElementDefinitionTypeList) : boolean; var type_ : TFHIRElementDefinitionType; t : String; begin if (types.count = 0) then result := false else begin result := true; for type_ in types do begin t := type_.code; if (not isDataType(t)) and (t <> 'Reference') and (t <> 'Narrative') and (t <> 'Extension') and (t <> 'ElementDefinition') and not isPrimitive(t) then result := false; end; end; end; { * Finds internal references in an Element's Binding and StructureDefinition references (in TypeRef) and bases them on the given url * @param url - the base url to use to turn internal references into absolute references * @param element - the Element to update * @return - the updated Element } function TProfileUtilities.updateURLs(url : String; element : TFhirElementDefinition) : TFhirElementDefinition; var defn : TFhirElementDefinition; t : TFhirElementDefinitionType; tp : TFhirUri; begin if (element <> nil) then begin defn := element; if (defn.binding <> nil) and (defn.binding.valueSet is TFHIRReference) and (TFHIRReference(defn.binding.valueSet).reference.startsWith('#')) then TFHIRReference(defn.binding.valueSet).reference := url+TFHIRReference(defn.binding.valueSet).reference; for t in defn.type_List do begin for tp in t.profileList do begin if (tp.value.startsWith('#')) then tp.value := url+tp.value; end; end; end; result := element; end; function TProfileUtilities.getSiblings(list : TFhirElementDefinitionList; current : TFhirElementDefinition) : TAdvList<TFhirElementDefinition>; var path : String; cursor : integer; begin result := TAdvList<TFhirElementDefinition>.create; path := current.path; cursor := list.indexOf(current)+1; while (cursor < list.Count) and (list[cursor].path.length >= path.length) do begin if (pathMatches(list[cursor].path, path)) then result.add(list[cursor].Link); inc(cursor); end; end; procedure TProfileUtilities.updateFromSlicing(dst, src : TFhirElementDefinitionSlicing); begin if (src.orderedElement <> nil) then dst.orderedElement := src.orderedElement.clone(); if (src.discriminatorList.Count > 0) then dst.discriminatorList.addAll(src.discriminatorList); if (src.rulesElement <> nil) then dst.rulesElement := src.rulesElement.clone(); end; function TProfileUtilities.orderMatches(diff, base : TFHIRBoolean) : boolean; begin result := (diff = nil) or (base = nil) or (diff.value = base.value); end; function TProfileUtilities.discriiminatorMatches(diff, base : TFhirStringList) : boolean; var i : integer; begin if (diff.count = 0) or (base.count = 0) then result := true else if (diff.Count <> base.Count) then result := false else begin result := true; for i := 0 to diff.Count - 1 do if (diff[i].value <> base[i].value) then result := false; end; end; function TProfileUtilities.ruleMatches(diff, base : TFhirResourceSlicingRules) : boolean; begin result := (diff = ResourceSlicingRulesNull) or (base = ResourceSlicingRulesNull) or (diff = base) or (diff = ResourceSlicingRulesOPEN) or ((diff = ResourceSlicingRulesOPENATEND) and (base = ResourceSlicingRulesCLOSED)); end; function TProfileUtilities.isSlicedToOneOnly(definition : TFhirElementDefinition) : boolean; begin result := (definition.slicing <> nil) and (definition.MaxElement <> Nil) and (definition.max = '1'); end; procedure TProfileUtilities.log(message: String); begin end; function TProfileUtilities.makeExtensionSlicing : TFhirElementDefinitionSlicing; begin result := TFhirElementDefinitionSlicing.create; result.discriminatorList.Add(TFHIRString.create('url')); result.ordered := false; result.rules := ResourceSlicingRulesOpen; end; function TProfileUtilities.isExtension(definition : TFhirElementDefinition) : boolean; begin result := definition.path.endsWith('.extension') or definition.path.endsWith('.modifierExtension'); end; function TProfileUtilities.getDiffMatches(context : TFhirStructureDefinitionDifferential; path : String; istart, iend : integer; profileName : String) : TAdvList<TFhirElementDefinition>; var i : integer; statedPath : String; begin result := TAdvList<TFhirElementDefinition>.create; for i := istart to iend do begin statedPath := context.elementList[i].path; if (statedPath = path) or (path.endsWith('[x]') and (statedPath.length > path.length - 2) and (statedPath.substring(0, path.length-3) = path.substring(0, path.length-3))) and (not statedPath.substring(path.length).contains('.')) then result.add(context.elementList[i].Link) else if (result.count = 0) then begin // writeln('ignoring '+statedPath+' in differential of '+profileName); end; end; end; function TProfileUtilities.findEndOfElement(context : TFhirStructureDefinitionDifferential; cursor : integer) : integer; var path : String; begin result := cursor; path := context.elementList[cursor].path+'.'; while (result < context.elementList.Count- 1) and (context.elementList[result+1].path.startsWith(path)) do inc(result); end; function TProfileUtilities.findEndOfElement(context : TFhirStructureDefinitionSnapshot; cursor : integer) : integer; var path : String; begin result := cursor; path := context.elementList[cursor].path+'.'; while (result < context.elementList.Count- 1) and (context.elementList[result+1].path.startsWith(path)) do inc(result); end; function TProfileUtilities.unbounded(definition : TFhirElementDefinition) : boolean; var max : String; begin max := definition.max; if (max = '') then result := false // this is not valid else if (max = '1') then result := false else if (max = '0') then result := false else result := true; end; function isLargerMax(derived, base : String) : boolean; begin if ('*' = base) then result := false else if ('*' = derived) then result := true else result := StrToInt(derived) > StrToInt(base); end; function inExpansion(cc : TFHIRValueSetExpansionContains; contains : TFhirValueSetExpansionContainsList) : boolean; var cc1 : TFhirValueSetExpansionContains; begin result := false; for cc1 in contains do begin if (cc.system = cc1.system) and (cc.code = cc1.code) then result := true; if inExpansion(cc, cc1.containsList) then result := true; end; end; function codesInExpansion(contains : TFhirValueSetExpansionContainsList; expansion : TFHIRValueSetExpansion) : boolean; var cc : TFhirValueSetExpansionContains; begin result := true; for cc in contains do begin if not inExpansion(cc, expansion.containsList) then result := false; if not codesInExpansion(cc.containsList, expansion) then result := false; end; end; function isResource(s : String) : boolean; begin result := StringArrayExistsSensitive(CODES_TFHIRResourceType, s); end; function isSubset(expBase, expDerived : TFhirValueSet) : boolean; begin result := codesInExpansion(expDerived.expansion.containsList, expBase.expansion); end; procedure TProfileUtilities.updateFromDefinition(dest, source : TFhirElementDefinition; pn : String; trimDifferential : boolean; purl : String); var base, derived : TFhirElementDefinition; isExtension, ok : boolean; s : TFHIRString; expBase, expDerived: TFHIRValueSet; ts, td : TFhirElementDefinitionType; b : TStringList; ms, md : TFhirElementDefinitionMapping; cs : TFhirElementDefinitionConstraint; begin // we start with a clone of the base profile ('dest') and we copy from the profile ('source') // over the top for anything the source has base := dest; derived := source; // derived.Tags[DERIVATION_POINTER] := base; if (derived <> nil) then begin // see task 3970. For an extension, there's no point copying across all the underlying definitional stuff isExtension := (base.path = 'Extension') or base.path.endsWith('.extension') or base.path.endsWith('.modifierExtension'); if (isExtension) then begin base.Definition := 'An Extension'; base.Short := 'Extension'; base.comments := ''; base.requirements := ''; base.aliasList.clear(); base.mappingList.clear(); end; if (derived.shortElement <> nil) then begin if not compareDeep(derived.shortElement, base.shortElement, false) then base.shortElement := derived.shortElement.clone() else if (trimDifferential) then derived.shortElement := nil else derived.shortElement.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.DefinitionElement <> nil) then begin if (derived.definition.startsWith('...')) then base.definition := base.definition+#13#10+derived.definition.substring(3) else if not compareDeep(derived.definitionElement, base.definitionElement, false) then base.definitionElement := derived.DefinitionElement.clone() else if (trimDifferential) then derived.DefinitionElement := nil else derived.DefinitionElement.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.CommentsElement <> nil) then begin if (derived.comments.startsWith('...')) then base.comments := base.comments+#13#10+derived.comments.substring(3) else if not compareDeep(derived.commentsElement, base.commentsElement, false) then base.CommentsElement := derived.CommentsElement.clone() else if (trimDifferential) then derived.CommentsElement := nil else derived.CommentsElement.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.RequirementsElement <> nil) then begin if (derived.requirements.startsWith('...')) then base.requirements := base.requirements+#13#10+derived.requirements.substring(3) else if not compareDeep(derived.requirementsElement, base.requirementsElement, false) then base.RequirementsElement := derived.requirementsElement.clone() else if (trimDifferential) then derived.RequirementsElement := nil else derived.requirementsElement.Tags[DERIVATION_EQUALS] := 'true'; end; // sdf-9 if (derived.requirements <> '') and (not base.path.contains('.')) then derived.requirements := ''; if (base.requirements <> '') and (not base.path.contains('.')) then base.requirements := ''; if (derived.aliasList.Count > 0) then begin if not compareDeep(derived.aliasList, base.aliasList, false) then for s in derived.aliasList do begin if not base.aliasList.hasValue(s.value) then base.aliasList.add(s.Clone); end else if (trimDifferential) then derived.aliasList.clear() else for s in derived.aliasList do s.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.MinElement <> nil) then begin if (not compareDeep(derived.minElement, base.minElement, false)) then begin if (derived.min < base.min) then messages.add(TFhirOperationOutcomeIssue.create(IssueSeverityERROR, IssueTypeBUSINESSRULE, pn+'.'+derived.path, 'Derived min ('+derived.min+') cannot be less than base min ('+base.min+')')); base.MinElement := derived.MinElement.clone(); end else if (trimDifferential) then derived.minElement := nil else derived.minElement.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.MaxElement <> nil) then begin if (not compareDeep(derived.maxElement, base.maxElement, false)) then begin if isLargerMax(derived.max, base.max) then messages.add(TFhirOperationOutcomeIssue.create(IssueSeverityERROR, IssueTypeBUSINESSRULE, pn+'.'+derived.path, 'Derived max ('+derived.max+') cannot be greater than base max ('+base.max+')')); base.maxElement := derived.maxElement.clone(); end else if (trimDifferential) then derived.maxElement := nil else derived.maxElement.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.Fixed <> nil) then begin if not compareDeep(derived.fixed, base.fixed, true) then base.fixed := derived.fixed.clone() else if (trimDifferential) then derived.fixed := nil else derived.fixed.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.Pattern <> nil) then begin if not compareDeep(derived.pattern, base.pattern, false) then base.pattern := derived.pattern.clone() else if (trimDifferential) then derived.Pattern := nil else derived.pattern.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.Example <> nil) then begin if (not compareDeep(derived.example, base.example, false)) then base.example := derived.example.clone() else if (trimDifferential) then derived.example := nil else derived.example.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.MaxLengthElement <> nil) then begin if (not compareDeep(derived.maxLengthElement, base.maxLengthElement, false)) then base.maxLengthElement := derived.maxLengthElement.clone() else if (trimDifferential) then derived.maxLengthElement := nil else derived.maxLengthElement.Tags[DERIVATION_EQUALS] := 'true'; end; // todo: what to do about conditions? // condition : id 0..* if (derived.MustSupportElement <> nil) then begin if (not compareDeep(derived.mustSupportElement, base.mustSupportElement, false)) then base.mustSupportElement := derived.mustSupportElement.clone() else if (trimDifferential) then derived.mustSupportElement := nil else derived.mustSupportElement.Tags[DERIVATION_EQUALS] := 'true'; end; // profiles cannot change : isModifier, defaultValue, meaningWhenMissing // but extensions can change isModifier if (isExtension) then begin if (not compareDeep(derived.isModifierElement, base.isModifierElement, false)) then base.isModifierElement := derived.isModifierElement.clone() else if (trimDifferential) then derived.isModifierElement := nil else derived.isModifierElement.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.Binding <> nil) then begin if (not compareDeep(derived.binding, base.binding, false)) then begin if (base.binding <> nil ) and ( base.binding.strength = BindingStrengthREQUIRED ) and ( derived.binding.strength <> BindingStrengthREQUIRED) then messages.add(TFhirOperationOutcomeIssue.create(IssueSeverityERROR, IssueTypeBUSINESSRULE, pn+'.'+derived.path, 'illegal attempt to change a binding from '+CODES_TFhirBindingStrength[base.binding.strength]+' to '+CODES_TFhirBindingStrength[derived.binding.strength])) // raise Exception.create('StructureDefinition '+pn+' at '+derived.path+': illegal attempt to change a binding from '+base.binding.strength.toCode()+' to '+derived.binding.strength.toCode()); else if (base.binding <> nil) and (derived.binding <> nil) and (base.binding.strength = BindingStrengthREQUIRED) then begin expBase := context.expand(context.fetchResource(frtValueSet, (base.binding.valueSet as TFhirReference).reference) as TFhirValueSet); expDerived := context.expand(context.fetchResource(frtValueSet, (base.binding.valueSet as TFhirReference).reference) as TFhirValueSet); if (expBase = nil) then messages.add(TFhirOperationOutcomeIssue.create(IssueSeverityWARNING, IssueTypeBUSINESSRULE, pn+'.'+base.path, 'Binding '+(base.binding.valueSet as TFhirReference).reference+' could not be expanded')) else if (expDerived = nil) then messages.add(TFhirOperationOutcomeIssue.create(IssueSeverityWARNING, IssueTypeBUSINESSRULE, pn+'.'+derived.path, 'Binding '+(derived.binding.valueSet as TFhirReference).reference+' could not be expanded')) else if not isSubset(expBase, expDerived) then messages.add(TFhirOperationOutcomeIssue.create(IssueSeverityERROR, IssueTypeBUSINESSRULE, pn+'.'+derived.path, 'Binding '+(derived.binding.valueSet as TFhirReference).reference+' is not a subset of binding '+(base.binding.valueSet as TFhirReference).reference)); end; base.binding := derived.binding.clone(); end else if (trimDifferential) then derived.binding := nil else derived.binding.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.IsSummaryElement <> nil) then begin if (not compareDeep(derived.isSummaryElement, base.isSummaryElement, false)) then base.isSummaryElement := derived.isSummaryElement.clone() else if (trimDifferential) then derived.isSummaryElement := nil else derived.isSummaryElement.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.type_List.Count > 0) then begin if not compareDeep(derived.type_List, base.type_List, false) then begin if (base.type_List.Count > 0) then begin for ts in derived.type_List do begin ok := false; b := TStringList.Create; try for td in base.type_List do begin b.add(td.code); if (td.code= ts.code) or (td.code = 'Extension') or (td.code = 'Element') or (td.code = '*') or (((td.code = 'Resource') or (td.code = 'DomainResource')) and isResource(ts.code)) then ok := true; end; if (not ok) then raise Exception.create('StructureDefinition '+pn+' at '+derived.path+': illegal constrained type '+ts.code+' from '+b.CommaText); finally b.Free; end; end; end; base.type_List.clear(); for ts in derived.type_List do begin td := ts.clone(); // tt.Tags[DERIVATION_EQUALS] := 'true'; base.type_List.add(td); end; end else if (trimDifferential) then derived.type_List.clear() else for ts in derived.type_List do ts.Tags[DERIVATION_EQUALS] := 'true'; end; if (derived.mappingList.Count > 0) then begin // todo: mappings are not cumulative - one replaces another if (not compareDeep(derived.mappingList, base.mappingList, false)) then begin for ms in derived.mappingList do begin ok := false; for md in base.mappingList do ok := ok or (md.identity = ms.identity) and (md.map = ms.map); if (not ok) then base.mappingList.add(ms.Clone); end; end else if (trimDifferential) then derived.mappingList.clear() else for ms in derived.mappingList do ms.Tags[DERIVATION_EQUALS] := 'true'; end; // todo: constraints are cumulative. there is no replacing for cs in base.constraintList do cs.Tags[IS_DERIVED] := 'true'; if derived.constraintList.Count > 0 then for cs in derived.constraintList do base.constraintList.add(cs.clone()); end; end; function uncapitalize(s : String) : string; begin result := Lowercase(s[1])+s.Substring(1); end; function capitalize(s : String) : string; begin result := UpperCase(s[1])+s.Substring(1); end; { TValidationResult } constructor TValidationResult.Create(Severity: TFhirIssueSeverity; Message: String); begin inherited create; FSeverity := Severity; FMessage := Message; end; function TValidationResult.isOk: boolean; begin result := message = ''; end; //{ TExtensionContext } // //constructor TExtensionContext.Create(definition: TFhirStructureDefinition; // element: TFhirElementDefinition); //begin // FDefinition := definition; // FElement := element; //end; // //destructor TExtensionContext.Destroy; //begin // FDefinition.Free; // FElement.Free; // inherited; //end; end.
unit myShellAPI; interface uses Windows,ShellApi,Classes,SysUtils; function FindFiles (folderName,mask:string;aSL:TSTRINGList):integer; function RecycleBinDelete(strFileName: string): boolean; function DirectoryCopy(sFrom, sTo: string; Protect: boolean;Silent:boolean): boolean; procedure MakeDir(Dir: String); // recursive enable procedure ExecNewProcess(ProgramName: string); implementation procedure ExecNewProcess(ProgramName: string); var StartInfo: TStartupInfo; ProcInfo: TProcessInformation; CreateOK: Boolean; begin { fill with known state } FillChar(StartInfo, SizeOf(TStartupInfo), #0); FillChar(ProcInfo, SizeOf(TProcessInformation), #0); StartInfo.cb := SizeOf(TStartupInfo); StartInfo.dwFlags:=STARTF_USESHOWWINDOW; StartInfo.wShowWindow:=SW_HIDE; CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False, CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, nil, StartInfo, ProcInfo); { check to see if successful } if CreateOK then //may or may not be needed. Usually wait for child processes WaitForSingleObject(ProcInfo.hProcess, 15000); //INFINITE end; function FindFiles (folderName,mask:string;aSL:TSTRINGList):integer; var sr: TSearchRec; i, FileAttrs: Integer; SL: TStringList; begin FileAttrs := 0; FileAttrs := FileAttrs + faAnyFile; i:=0; if FindFirst(foldername + '\' + mask, FileAttrs, sr) = 0 then begin repeat if (sr.Name<>'.') and (sr.Name<>'..') then begin inc(i); aSL.Add(foldername + '\' + sr.Name); end; until FindNext(sr) <> 0; FindClose(sr); end; result:=i; end; function RecycleBinDelete(strFileName: string): boolean; var recFileOpStruct: TSHFileOpStruct; begin // clear the structure FillChar(recFileOpStruct, SizeOf(TSHFileOpStruct), 0); with recFileOpStruct do begin wFunc := FO_DELETE; pFrom := PChar(strFileName); fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_SILENT; end; // set the return with sucess of the operation result := (0 = ShFileOperation(recFileOpStruct)); end; function DirectoryCopy(sFrom, sTo: string; Protect: boolean;Silent:boolean): boolean; { Copies files or directory to another directory. } var F: TShFileOpStruct; ResultVal: integer; tmp1, tmp2: string; begin FillChar(F, SizeOf(F), #0); try F.Wnd := 0; F.wFunc := FO_COPY; { Add an extra null char } tmp1 := sFrom + #0; tmp2 := sTo + #0; F.pFrom := PChar(tmp1); F.pTo := PChar(tmp2); if Protect then F.fFlags := FOF_RENAMEONCOLLISION or FOF_SIMPLEPROGRESS else if Silent then begin F.fFlags := FOF_SILENT or FOF_NOCONFIRMATION; end else F.fFlags := FOF_SIMPLEPROGRESS; F.fAnyOperationsAborted := False; F.hNameMappings := nil; Resultval := ShFileOperation(F); Result := (ResultVal = 0) and (F.fAnyOperationsAborted=false); finally end; end; procedure MakeDir(Dir: String); function Last(What: String; Where: String): Integer; var Ind : Integer; begin Result := 0; for Ind := (Length(Where)-Length(What)+1) downto 1 do if Copy(Where, Ind, Length(What)) = What then begin Result := Ind; Break; end; end; var PrevDir : String; Ind : Integer; begin { if Copy(Dir,2,1) <> ':' then if Copy(Dir,3,1) <> '\' then if Copy(Dir,1,1) = '\' then Dir := 'C:'+Dir else Dir := 'C:\'+Dir else Dir := 'C:'+Dir; } if not DirectoryExists(Dir) then begin // if directory don't exist, get name of the previous directory Ind := Last('\', Dir); // Position of the last '\' PrevDir := Copy(Dir, 1, Ind-1); // Previous directory // if previous directoy don't exist, // it's passed to this procedure - this is recursively... if not DirectoryExists(PrevDir) then MakeDir(PrevDir); // In thats point, the previous directory must be exist. // So, the actual directory (in "Dir" variable) will be created. CreateDir(Dir); end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 12/2/2004 9:26:44 PM JPMugaas Bug fix. Rev 1.4 11/11/2004 10:25:24 PM JPMugaas Added OpenProxy and CloseProxy so you can do RecvFrom and SendTo functions from the UDP client with SOCKS. You must call OpenProxy before using RecvFrom or SendTo. When you are finished, you must use CloseProxy to close any connection to the Proxy. Connect and disconnect also call OpenProxy and CloseProxy. Rev 1.3 11/11/2004 3:42:52 AM JPMugaas Moved strings into RS. Socks will now raise an exception if you attempt to use SOCKS4 and SOCKS4A with UDP. Those protocol versions do not support UDP at all. Rev 1.2 2004.05.20 11:39:12 AM czhower IdStreamVCL Rev 1.1 6/4/2004 5:13:26 PM SGrobety EIdMaxCaptureLineExceeded message string Rev 1.0 2004.02.03 4:19:50 PM czhower Rename Rev 1.15 10/24/2003 4:21:56 PM DSiders Addes resource string for stream read exception. Rev 1.14 2003.10.16 11:25:22 AM czhower Added missing ; Rev 1.13 10/15/2003 11:11:06 PM DSiders Added resource srting for exception raised in TIdTCPServer.SetScheduler. Rev 1.12 10/15/2003 11:03:00 PM DSiders Added resource string for circular links from transparent proxy. Corrected spelling errors. Rev 1.11 10/15/2003 10:41:34 PM DSiders Added resource strings for TIdStream and TIdStreamProxy exceptions. Rev 1.10 10/15/2003 8:48:56 PM DSiders Added resource strings for exceptions raised when setting thread component properties. Rev 1.9 10/15/2003 8:35:28 PM DSiders Added resource string for exception raised in TIdSchedulerOfThread.NewYarn. Rev 1.8 10/15/2003 8:04:26 PM DSiders Added resource strings for exceptions raised in TIdLogFile, TIdReply, and TIdIOHandler. Rev 1.7 10/15/2003 1:03:42 PM DSiders Created resource strings for TIdBuffer.Find exceptions. Rev 1.6 2003.10.14 1:26:44 PM czhower Uupdates + Intercept support Rev 1.5 10/1/2003 10:49:02 PM GGrieve Rework buffer for Octane Compability Rev 1.4 7/1/2003 8:32:32 PM BGooijen Added RSFibersNotSupported Rev 1.3 7/1/2003 02:31:34 PM JPMugaas Message for invalid IP address. Rev 1.2 5/14/2003 6:40:22 PM BGooijen RS for transparent proxy Rev 1.1 1/17/2003 05:06:04 PM JPMugaas Exceptions for scheduler string. Rev 1.0 11/13/2002 08:42:02 AM JPMugaas } unit IdResourceStringsCore; interface {$i IdCompilerDefines.inc} resourcestring RSNoBindingsSpecified = 'Keine Bindungen angegeben.'; RSCannotAllocateSocket = 'Socket kann nicht zugewiesen werden.'; RSSocksUDPNotSupported = 'UDP wird in dieser SOCKS-Version nicht unterstützt.'; RSSocksRequestFailed = 'Anforderung zurückgewiesen oder fehlgeschlagen.'; RSSocksRequestServerFailed = 'Anforderung zurückgewiesen, weil der SOCKS-Server keine Verbindung herstellen kann.'; RSSocksRequestIdentFailed = 'Anforderung zurückgewiesen, weil das Client-Programm und der Identd verschiedene Benutzer-IDs melden.'; RSSocksUnknownError = 'Unbekannter Socks-Fehler.'; RSSocksServerRespondError = 'Socks-Server hat nicht geantwortet.'; RSSocksAuthMethodError = 'Ungültige Authentifizierungsmethode für Socks.'; RSSocksAuthError = 'Authentifizierungsfehler beim Socks-Server.'; RSSocksServerGeneralError = 'Allgemeiner SOCKS-Server-Fehler.'; RSSocksServerPermissionError = 'Verbindung von Regelmenge nicht zugelassen.'; RSSocksServerNetUnreachableError = 'Netzwerk nicht erreichbar.'; RSSocksServerHostUnreachableError = 'Host nicht erreichbar.'; RSSocksServerConnectionRefusedError = 'Verbindung abgelehnt.'; RSSocksServerTTLExpiredError = 'TTL abgelaufen.'; RSSocksServerCommandError = 'Anweisung nicht unterstützt.'; RSSocksServerAddressError = 'Adresstyp nicht unterstützt.'; RSInvalidIPAddress = 'Ungültige IP-Adresse'; RSInterceptCircularLink = '%s: Zirkuläre Verknüpfungen sind nicht zulässig'; RSNotEnoughDataInBuffer = 'Nicht genügend Daten im Puffer. (%d/%d)'; RSTooMuchDataInBuffer = 'Zu viele Daten im Puffer.'; RSCapacityTooSmall = 'Die Kapazität darf nicht kleiner als die Größe sein.'; RSBufferIsEmpty = 'Keine Bytes im Puffer.'; RSBufferRangeError = 'Index außerhalb des Bereichs.'; RSFileNotFound = 'Datei "%s" nicht gefunden'; RSNotConnected = 'Nicht verbunden'; RSObjectTypeNotSupported = 'Objekttyp nicht unterstützt.'; RSIdNoDataToRead = 'Keine Daten für den Lesezugriff.'; RSReadTimeout = 'Zeitüberschreitung beim Lesen.'; RSReadLnWaitMaxAttemptsExceeded = 'Max. Zeilenleseversuche überschritten.'; RSAcceptTimeout = 'Zeitüberschreitung bei der Annahme.'; RSReadLnMaxLineLengthExceeded = 'Max. Zeilenlänge überschritten.'; RSRequiresLargeStream = 'Setzen Sie LargeStream auf True, um Streams, die größer als 2 GB sind, zu senden'; RSDataTooLarge = 'Daten sind für den Stream zu groß'; RSConnectTimeout = 'Zeitüberschreitung der Verbindung.'; RSICMPNotEnoughtBytes = 'Nicht genug Bytes erhalten'; RSICMPNonEchoResponse = 'Antwort vom Typ Non-Echo erhalten'; RSThreadTerminateAndWaitFor = 'Aufruf von TerminateAndWaitFor für FreeAndTerminate-Threads nicht möglich'; RSAlreadyConnected = 'Verbindung besteht bereits.'; RSTerminateThreadTimeout = 'Zeitüberschreitung bei Thread-Beendigung'; RSNoExecuteSpecified = 'Keine Ausführungsbehandlungsroutine gefunden.'; RSNoCommandHandlerFound = 'Keine Befehlsbehandlungsroutine gefunden.'; RSCannotPerformTaskWhileServerIsActive = 'Task kann nicht ausgeführt werden, solange der Server aktiv ist.'; RSThreadClassNotSpecified = 'Thread-Klasse nicht angegeben.'; RSMaximumNumberOfCaptureLineExceeded = 'Maximal zulässige Zeilenanzahl überschritten'; // S.G. 6/4/2004: IdIOHandler.DoCapture RSNoCreateListeningThread = 'Empfangs-Thread kann nicht erstellt werden.'; RSInterceptIsDifferent = 'Dem IOHandler wurde bereits ein anderes Intercept zugewiesen'; //scheduler RSchedMaxThreadEx = 'Die maximale Thread-Anzahl für diesen Scheduler ist überschritten.'; //transparent proxy RSTransparentProxyCannotBind = 'Transparenter Proxy kann nicht binden.'; RSTransparentProxyCanNotSupportUDP = 'UDP wird von diesem Proxy nicht unterstützt.'; //Fibers RSFibersNotSupported = 'Fasern werden auf diesem System nicht unterstützt.'; // TIdICMPCast RSIPMCastInvalidMulticastAddress = 'Die übermittelte IP-Adresse ist keine gültige Multicast-Adresse [224.0.0.0 bis 239.255.255.255].'; RSIPMCastNotSupportedOnWin32 = 'Diese Funktion wird unter Win32 nicht unterstützt.'; RSIPMCastReceiveError0 = 'IP-Broadcast-Empfangsfehler = 0.'; // Log strings RSLogConnected = 'Verbunden.'; RSLogDisconnected = 'Verbindung getrennt.'; RSLogEOL = '<EOL>'; // End of Line RSLogCR = '<CR>'; // Carriage Return RSLogLF = '<LF>'; // Line feed RSLogRecv = 'Erh '; // Receive RSLogSent = 'Ges '; // Send RSLogStat = 'Stat '; // Status RSLogFileAlreadyOpen = 'Dateiname kann bei geöffneter Protokolldatei nicht festgelegt werden.'; RSBufferMissingTerminator = 'Pufferbegrenzer muss angegeben werden.'; RSBufferInvalidStartPos = 'Pufferstartposition ist ungültig.'; RSIOHandlerCannotChange = 'Verbundener IOHandler kann nicht geändert werden.'; RSIOHandlerTypeNotInstalled = 'Kein IOHandler des Typs %s installiert.'; RSReplyInvalidCode = 'Antwortcode ist ungültig: %s'; RSReplyCodeAlreadyExists = 'Antwortcode bereits vorhanden: %s'; RSThreadSchedulerThreadRequired = 'Thread muss für den Scheduler angegeben werden.'; RSNoOnExecute = 'OnExecute-Ereignis muss vorhanden sein.'; RSThreadComponentLoopAlreadyRunning = 'Loop-Eigenschaft kann bei ausgeführtem Thread nicht gesetzt werden.'; RSThreadComponentThreadNameAlreadyRunning = 'ThreadName kann bei ausgeführtem Thread nicht gesetzt werden.'; RSStreamProxyNoStack = 'Für die Konvertierung des Datentyps wurde ein Stack erstellt.'; RSTransparentProxyCyclic = 'Zyklischer Fehler bei transparentem Proxy.'; RSTCPServerSchedulerAlreadyActive = 'Scheduler kann nicht geändert werden, solange der Server aktiv ist.'; RSUDPMustUseProxyOpen = 'proxyOpen muss verwendet werden'; //ICMP stuff RSICMPTimeout = 'Zeitüberschreitung'; //Destination Address -3 RSICMPNetUnreachable = 'Netz nicht erreichbar;'; RSICMPHostUnreachable = 'Host nicht erreichbar;'; RSICMPProtUnreachable = 'Protokoll nicht erreichbar;'; RSICMPPortUnreachable = 'Port nicht erreichbar'; RSICMPFragmentNeeded = 'Fragmentierung erforderlich und "Nicht fragmentieren" wurde festgelegt'; RSICMPSourceRouteFailed = 'Quellroute fehlgeschlagen'; RSICMPDestNetUnknown = 'Ziel-Netzwerk unbekannt'; RSICMPDestHostUnknown = 'Ziel-Host unbekannt'; RSICMPSourceIsolated = 'Quell-Host isoliert'; RSICMPDestNetProhibitted = 'Kommunikation mit Ziel-Netzwerk wurde vom Administrator gesperrt'; RSICMPDestHostProhibitted = 'Kommunikation mit Ziel-Host wurde vom Administrator gesperrt'; RSICMPTOSNetUnreach = 'Ziel-Netzwerk für Type-of-Service nicht erreichbar'; RSICMPTOSHostUnreach = 'Ziel-Host für Type-of-Service nicht erreichbar'; RSICMPAdminProhibitted = 'Kommunikation vom Administrator gesperrt'; RSICMPHostPrecViolation = 'Verletzung der Host-Rangfolge'; RSICMPPrecedenceCutoffInEffect = 'Rangfolgenobergrenze aktiv'; //for IPv6 RSICMPNoRouteToDest = 'Keine Route zum Ziel'; RSICMPAAdminDestProhibitted = 'Kommunikation mit Ziel vom Administrator gesperrt'; RSICMPSourceFilterFailed = 'Quelladresse entspricht nicht der Eintritts-/Austrittsrichtlinie'; RSICMPRejectRoutToDest = 'Route zum Ziel ablehnen'; // Destination Address - 11 RSICMPTTLExceeded = 'Time-to-Live überschritten'; RSICMPHopLimitExceeded = 'Hop-Obergrenze überschritten'; RSICMPFragAsmExceeded = 'Zeit für die erneute Fragment-Zusammensetzung überschritten.'; //Parameter Problem - 12 RSICMPParamError = 'Parameterproblem (Offset %d)'; //IPv6 RSICMPParamHeader = 'fehlerhaftes Header-Feld vorhanden (Offset %d)'; RSICMPParamNextHeader = 'nicht erkannter nächster Header-Typ vorhanden (Offset %d)'; RSICMPUnrecognizedOpt = 'nicht erkannte IPv6-Option vorhanden (Offset %d)'; //Source Quench Message -4 RSICMPSourceQuenchMsg = 'Meldung "Überlastung durch den Sender"'; //Redirect Message RSICMPRedirNet = 'Datagramme für das Netzwerk umleiten.'; RSICMPRedirHost = 'Datagramme für den Host umleiten.'; RSICMPRedirTOSNet = 'Datagramme für Type-of-Service und Netzwerk umleiten.'; RSICMPRedirTOSHost = 'Datagramme für Type-of-Service und Host umleiten.'; //echo RSICMPEcho = 'Echo'; //timestamp RSICMPTimeStamp = 'Zeitstempel'; //information request RSICMPInfoRequest = 'Informationsanforderung'; //mask request RSICMPMaskRequest = 'Adressmaskenanforderung'; // Traceroute RSICMPTracePacketForwarded = 'Ausgehendes Paket erfolgreich weitergeleitet'; RSICMPTraceNoRoute = 'Keine Route für ausgehendes Paket; Paket verworfen'; //conversion errors RSICMPConvUnknownUnspecError = 'Unbekannter/unspezifischer Fehler'; RSICMPConvDontConvOptPresent = 'Option "Nicht konvertieren" ist vorhanden'; RSICMPConvUnknownMandOptPresent = 'Unbekannte Option vorhanden'; RSICMPConvKnownUnsupportedOptionPresent = 'Bekannte nicht unterstützte Option vorhanden'; RSICMPConvUnsupportedTransportProtocol = 'Nicht unterstütztes Transportprotokoll'; RSICMPConvOverallLengthExceeded = 'Gesamtlänge überschritten'; RSICMPConvIPHeaderLengthExceeded = 'IP-Header-Länge überschritten'; RSICMPConvTransportProtocol_255 = 'Transportprotokoll &gt; 255'; RSICMPConvPortConversionOutOfRange = 'Port-Konvertierung außerhalb des Bereichs'; RSICMPConvTransportHeaderLengthExceeded = 'Transport-Header-Länge überschritten'; RSICMPConv32BitRolloverMissingAndACKSet = '32 Bit Rollover fehlt und ACK gesetzt'; RSICMPConvUnknownMandatoryTransportOptionPresent = 'Unbekannte Transportoption vorhanden'; //mobile host redirect RSICMPMobileHostRedirect = 'Mobile Host-Umleitung'; //IPv6 - Where are you RSICMPIPv6WhereAreYou = 'IPv6 Where-Are-You'; //IPv6 - I am here RSICMPIPv6IAmHere = 'IPv6 I-Am-Here'; // Mobile Regestration request RSICMPMobReg = 'Mobile Registrierungsanforderung'; //Skip RSICMPSKIP = 'SKIP'; //Security RSICMPSecBadSPI = 'Schlechte SPI'; RSICMPSecAuthenticationFailed = 'Authentifizierung fehlgeschlagen'; RSICMPSecDecompressionFailed = 'Dekomprimierung fehlgeschlagen'; RSICMPSecDecryptionFailed = 'Entschlüsselung fehlgeschlagen'; RSICMPSecNeedAuthentication = 'Authentifizierung erforderlich'; RSICMPSecNeedAuthorization = 'Autorisierung erforderlich'; //IPv6 Packet Too Big RSICMPPacketTooBig = 'Paket zu groß (MTU = %d)'; { TIdCustomIcmpClient } // TIdSimpleServer RSCannotUseNonSocketIOHandler = 'Ein Nicht-Socket-IOHandler kann nicht verwendet werden'; implementation end.
{------------------------------------------------------------------------------- Copyright 2012 Ethea S.r.l. 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 Kitto.Ext.MainFormUnit; {$I Kitto.Defines.inc} interface uses {$IF RTLVersion >= 23.0}Themes, Styles,{$IFEND} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, Kitto.Ext.Application, ActnList, Kitto.Config, StdCtrls, Buttons, ExtCtrls, ImgList, EF.Logger, Actions, Vcl.Tabs, Vcl.Grids; type TKExtLogEvent = procedure (const AString: string) of object; TKExtMainFormLogEndpoint = class(TEFLogEndpoint) private FOnLog: TKExtLogEvent; protected procedure DoLog(const AString: string); override; public property OnLog: TKExtLogEvent read FOnLog write FOnLog; end; TKExtMainForm = class(TForm) ActionList: TActionList; StartAction: TAction; StopAction: TAction; PageControl: TPageControl; HomeTabSheet: TTabSheet; SessionCountLabel: TLabel; RestartAction: TAction; ConfigFileNameComboBox: TComboBox; ConfigLinkLabel: TLabel; StartSpeedButton: TSpeedButton; StopSpeedButton: TSpeedButton; ImageList: TImageList; LogMemo: TMemo; ControlPanel: TPanel; AppTitleLabel: TLabel; OpenConfigDialog: TOpenDialog; SpeedButton1: TSpeedButton; HomeURLLabel: TLabel; AppIcon: TImage; MainTabSet: TTabSet; SessionPanel: TPanel; SessionToolPanel: TPanel; Button1: TButton; SessionListView: TListView; procedure StartActionUpdate(Sender: TObject); procedure StopActionUpdate(Sender: TObject); procedure StartActionExecute(Sender: TObject); procedure StopActionExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure RestartActionUpdate(Sender: TObject); procedure RestartActionExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure ConfigFileNameComboBoxChange(Sender: TObject); procedure ConfigLinkLabelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure HomeURLLabelClick(Sender: TObject); procedure MainTabSetChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); procedure Button1Click(Sender: TObject); procedure SessionListViewEdited(Sender: TObject; Item: TListItem; var S: string); procedure SessionListViewInfoTip(Sender: TObject; Item: TListItem; var InfoTip: string); private FAppThread: TKExtAppThread; FRestart: Boolean; FLogEndPoint: TKExtMainFormLogEndpoint; procedure ShowTabGUI(const AIndex: Integer); procedure UpdateSessionInfo; const TAB_LOG = 0; TAB_SESSIONS = 1; function IsStarted: Boolean; function GetAppThread: TKExtAppThread; procedure AppThreadTerminated(Sender: TObject); procedure UpdateSessionCountlabel; function GetSessionCount: Integer; procedure FillConfigFileNameCombo; procedure SelectConfigFile; procedure DisplayHomeURL(const AHomeURL: string); property AppThread: TKExtAppThread read GetAppThread; function HasConfigFileName: Boolean; procedure DoLog(const AString: string); public procedure SetConfig(const AFileName: string); end; var KExtMainForm: TKExtMainForm; implementation {$R *.dfm} uses Math, SyncObjs, EF.SysUtils, EF.Shell, EF.Localization, FCGIApp, Kitto.Ext.Session; procedure TKExtMainForm.AppThreadTerminated(Sender: TObject); begin FAppThread := nil; DoLog(_('Listener stopped')); SessionCountLabel.Visible := False; end; procedure TKExtMainForm.Button1Click(Sender: TObject); begin UpdateSessionInfo; end; procedure TKExtMainForm.ConfigLinkLabelClick(Sender: TObject); begin SelectConfigFile; end; procedure TKExtMainForm.SelectConfigFile; begin OpenConfigDialog.InitialDir := TKConfig.AppHomePath; if OpenConfigDialog.Execute then begin // The Home is the parent directory of the Metadata directory. TKConfig.AppHomePath := ExtractFilePath(OpenConfigDialog.FileName) + '..'; Caption := TKConfig.AppHomePath; FillConfigFileNameCombo; SetConfig(ExtractFileName(OpenConfigDialog.FileName)); end; end; procedure TKExtMainForm.SessionListViewEdited(Sender: TObject; Item: TListItem; var S: string); begin if TObject(Item.Data) is TKExtSession then TKExtSession(Item.Data).DisplayName := S; end; procedure TKExtMainForm.SessionListViewInfoTip(Sender: TObject; Item: TListItem; var InfoTip: string); begin if Assigned(Item) and (TObject(Item.Data) is TKExtSession) then begin InfoTip := 'HTTP_USER_AGENT: ' + TKExtSession(Item.Data).RequestHeader['HTTP_USER_AGENT'] + sLineBreak + 'SERVER_SOFTWARE: ' + TKExtSession(Item.Data).RequestHeader['SERVER_SOFTWARE']; end; end; procedure TKExtMainForm.DoLog(const AString: string); begin LogMemo.Lines.Add(FormatDateTime('[yyyy-mm-dd hh:nn:ss.zzz] ', Now()) + AString); end; procedure TKExtMainForm.StopActionExecute(Sender: TObject); begin if IsStarted then begin DoLog(_('Stopping listener...')); FAppThread.Terminate; HomeURLLabel.Visible := False; while IsStarted do Forms.Application.ProcessMessages; if FRestart then begin FRestart := False; StartAction.Execute; end; end; UpdateSessionInfo; end; procedure TKExtMainForm.StopActionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := IsStarted; end; procedure TKExtMainForm.MainTabSetChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); begin ShowTabGUI(NewTab); end; procedure TKExtMainForm.ShowTabGUI(const AIndex: Integer); begin case AIndex of TAB_LOG: LogMemo.BringToFront; TAB_SESSIONS: begin UpdateSessionInfo; SessionPanel.BringToFront; end; end; end; procedure TKExtMainForm.RestartActionExecute(Sender: TObject); begin FRestart := True; StopAction.Execute; end; procedure TKExtMainForm.RestartActionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := IsStarted; end; procedure TKExtMainForm.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin UpdateSessionCountlabel; end; procedure TKExtMainForm.UpdateSessionCountlabel; begin SessionCountLabel.Caption := Format('Active Sessions: %d', [GetSessionCount]); end; procedure TKExtMainForm.UpdateSessionInfo; procedure AddItem(const AThreadData: TFCGIThreadData); var LItem: TListItem; LSession: TKExtSession; begin LItem := SessionListView.Items.Add; if Assigned(AThreadData.Session) and (AThreadData.Session is TKExtSession) then begin LSession := TKExtSession(AThreadData.Session); LItem.Data := LSession; LItem.Caption := LSession.DisplayName; // Start Time. LItem.SubItems.Add(DateTimeToStr(LSession.CreationDateTime)); // Last Req. LItem.SubItems.Add(DateTimeToStr(LSession.LastRequestDateTime)); // User. LItem.SubItems.Add(LSession.GetLoggedInUserName); // Origin. LItem.SubItems.Add(LSession.GetOrigin); end else begin LItem.Caption := _('None'); end; end; var I: Integer; LThreadData: TFCGIThreadData; begin SessionListView.Clear; if Assigned(FCGIApp.Application) then begin FCGIApp.Application.AccessThreads.Enter; try if FCGIApp.Application.ThreadsCount <= 0 then begin LThreadData.Session := nil; AddItem(LThreadData); end else begin for I := 0 to FCGIApp.Application.ThreadsCount - 1 do begin LThreadData := FCGIApp.Application.GetThreadData(I); AddItem(LThreadData); end; end; finally FCGIApp.Application.AccessThreads.Leave; end; end else begin LThreadData.Session := nil; AddItem(LThreadData); end; end; function TKExtMainForm.GetSessionCount: Integer; begin if Assigned(FCGIApp.Application) then Result := Max(0, FCGIApp.Application.ThreadsCount) else Result := 0; end; function TKExtMainForm.HasConfigFileName: Boolean; begin Result := ConfigFileNameComboBox.Text <> ''; end; procedure TKExtMainForm.HomeURLLabelClick(Sender: TObject); begin OpenDocument(HomeURLLabel.Caption); end; function TKExtMainForm.IsStarted: Boolean; begin Result := Assigned(FAppThread); end; procedure TKExtMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin StopAction.Execute; Sleep(100); // Apparently avoids a finalization problem in DBXCommon. end; procedure TKExtMainForm.FormCreate(Sender: TObject); begin FLogEndPoint := TKExtMainFormLogEndpoint.Create; FLogEndPoint.OnLog := DoLog; end; procedure TKExtMainForm.FormDestroy(Sender: TObject); begin FreeAndNil(FLogEndPoint); end; procedure TKExtMainForm.FormShow(Sender: TObject); begin ShowTabGUI(TAB_LOG); Caption := TKConfig.AppHomePath {$IFDEF DEBUG}+' - Debug'{$ENDIF}; DoLog(Format(_('Build date: %s'), [DateTimeToStr(GetFileDateTime(ParamStr(0)))])); FillConfigFileNameCombo; if HasConfigFileName then StartAction.Execute else SelectConfigFile; end; procedure TKExtMainForm.ConfigFileNameComboBoxChange(Sender: TObject); begin SetConfig(ConfigFileNameComboBox.Text); end; procedure TKExtMainForm.SetConfig(const AFileName: string); var LConfig: TKConfig; LWasStarted: Boolean; LAppIconFileName: string; begin LWasStarted := IsStarted; if LWasStarted then StopAction.Execute; ConfigFileNameComboBox.ItemIndex := ConfigFileNameComboBox.Items.IndexOf(AFileName); TKConfig.BaseConfigFileName := AFileName; LConfig := TKConfig.Create; try AppTitleLabel.Caption := Format(_('Application: %s'), [_(LConfig.AppTitle)]); LAppIconFileName := LConfig.FindResourcePathName(LConfig.AppIcon+'.png'); if FileExists(LAppIconFileName) then AppIcon.Picture.LoadFromFile(LAppIconFileName) else AppIcon.Picture.Bitmap := nil; finally FreeAndNil(LConfig); end; StartAction.Update; if LWasStarted then StartAction.Execute; end; procedure TKExtMainForm.DisplayHomeURL(const AHomeURL: string); begin DoLog(Format(_('Home URL: %s'), [AHomeURL])); HomeURLLabel.Caption := AHomeURL; HomeURLLabel.Visible := True; end; procedure TKExtMainForm.FillConfigFileNameCombo; var LDefaultConfig: string; LConfigIndex: Integer; begin FindAllFiles('yaml', TKConfig.GetMetadataPath, ConfigFileNameComboBox.Items, False, False); if ConfigFileNameComboBox.Items.Count > 0 then begin //Read command line param -config with default of TKConfig.BaseConfigFileName LDefaultConfig := ChangeFileExt(GetCmdLineParamValue('Config', TKConfig.BaseConfigFileName),'.yaml'); LConfigIndex := ConfigFileNameComboBox.Items.IndexOf(LDefaultConfig); if LConfigIndex <> -1 then begin ConfigFileNameComboBox.ItemIndex := LConfigIndex; ConfigFileNameComboBoxChange(ConfigFileNameComboBox); end else begin //Read command line param -config with default 'Config.yaml' LDefaultConfig := ChangeFileExt(GetCmdLineParamValue('Config', 'Config.yaml'),'.yaml'); LConfigIndex := ConfigFileNameComboBox.Items.IndexOf(LDefaultConfig); if LConfigIndex <> -1 then begin ConfigFileNameComboBox.ItemIndex := LConfigIndex; ConfigFileNameComboBoxChange(ConfigFileNameComboBox); end else begin //Read config file LDefaultConfig := TKConfig.BaseConfigFileName; LConfigIndex := ConfigFileNameComboBox.Items.IndexOf(LDefaultConfig); if LConfigIndex <> -1 then begin ConfigFileNameComboBox.ItemIndex := LConfigIndex; ConfigFileNameComboBoxChange(ConfigFileNameComboBox); end else begin //Use first Config file found ConfigFileNameComboBox.ItemIndex := 0; ConfigFileNameComboBoxChange(ConfigFileNameComboBox); end; end; end; end; end; function TKExtMainForm.GetAppThread: TKExtAppThread; begin if not Assigned(FAppThread) then begin FAppThread := TKExtAppThread.Create(True); FAppThread.FreeOnTerminate := True; FAppThread.OnTerminate := AppThreadTerminated; FAppThread.Configure; end; Result := FAppThread; end; procedure TKExtMainForm.StartActionExecute(Sender: TObject); var LConfig: TKConfig; begin AppThread.Start; SessionCountLabel.Visible := True; DoLog(_('Listener started')); LConfig := TKConfig.Create; try DisplayHomeURL(LConfig.GetHomeURL); finally FreeAndNil(LConfig); end; end; procedure TKExtMainForm.StartActionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := HasConfigFileName and not IsStarted; end; { TKExtMainFormLogEndpoint } procedure TKExtMainFormLogEndpoint.DoLog(const AString: string); begin if Assigned(FOnLog) then FOnLog(AString); end; end.
unit fDerivativeOptions; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, OpenGLTokens, GLVectorGeometry, uGlobal, uParser, fGridOptions; type TDerivativesForm = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label8: TLabel; zCountLabel: TLabel; GridValues: TSpeedButton; PlotValues: TSpeedButton; EditMinX: TEdit; EditMaxX: TEdit; EditdX: TEdit; EditMinY: TEdit; EditMaxY: TEdit; EditdY: TEdit; EditMinZ: TEdit; EditMaxZ: TEdit; zLimitCB: TCheckBox; ModeComboBox: TComboBox; StyleComboBox: TComboBox; zCapCB: TCheckBox; ApplyBtn: TBitBtn; CloseBtn: TBitBtn; DerivXRB: TRadioButton; DerivYRB: TRadioButton; VolumeRB: TRadioButton; Label7: TLabel; EditAddLineWidth: TEdit; ColorButton: TSpeedButton; ColorDialog: TColorDialog; VolumeLabel: TLabel; PosVolLabel: TLabel; NegVolLabel: TLabel; TotalLabel: TLabel; procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FloatKeyPress(Sender: TObject; var Key: Char); procedure IncKeyPress(Sender: TObject; var Key: Char); procedure EditMinXKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditMaxXKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditdXKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditMinYKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditMaxYKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditdYKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditMinZKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditMaxZKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure zLimitCBClick(Sender: TObject); procedure zCapCBClick(Sender: TObject); procedure ApplyBtnClick(Sender: TObject); procedure CloseBtnClick(Sender: TObject); procedure GridValuesClick(Sender: TObject); procedure PlotValuesClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure StyleComboBoxChange(Sender: TObject); procedure ModeComboBoxChange(Sender: TObject); procedure DerivXRBClick(Sender: TObject); procedure DerivYRBClick(Sender: TObject); procedure VolumeRBClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure EditAddLineWidthKeyPress(Sender: TObject; var Key: Char); procedure EditAddLineWidthKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ColorButtonClick(Sender: TObject); procedure PlotValuesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GridValuesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private TooManyPoints: Boolean; procedure CountzPoints; public { Public declarations } end; var DerivativesForm: TDerivativesForm; //========================================================================== implementation //========================================================================== {$R *.dfm} uses fMain, fAddPlotColors, fEvaluate; procedure TDerivativesForm.EditdXKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var x: TGlFloat; begin try x := StrToFloat(EditdX.Text); except x := 1.0; end; AddedData.xInc := x; //ApplyBtn.Visible := AddedData.AddedAs > AddNone; DerivativeAltered := True; CountzPoints; end; procedure TDerivativesForm.EditdYKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var y: TGLFloat; begin try y := StrToFloat(EditdY.Text); except y := 1.0; end; AddedData.yInc := y; //ApplyBtn.Visible := AddedData.AddedAs > AddNone; DerivativeAltered := True; CountzPoints; end; procedure TDerivativesForm.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin //if (Key = VK_DELETE) or (Key = VK_BACK) //then ApplyBtn.Visible := AddedData.AddedAs > AddNone; end; procedure TDerivativesForm.EditAddLineWidthKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do if not CharInSet(Key, ['0'..'9', #8]) then Key := #0 end; procedure TDerivativesForm.EditAddLineWidthKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var w: integer; begin try w := StrToInt(EditAddLineWidth.Text); except w := 3; end; AddedData.AddLineWidth := w; ViewForm.AddXLine.LineWidth := w; ViewForm.AddYLine.LineWidth := w; ViewForm.AddZLine.LineWidth := w; DerivativeAltered := True; //ApplyBtn.Visible := AddedData.AddedAs = AddVolume; end; procedure TDerivativesForm.EditMaxXKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var x: TGLFloat; begin try x := StrToFloat(EditMaxX.Text); except x := 1.0; end; AddedData.xMax := x; //ApplyBtn.Visible := AddedData.AddedAs > AddNone; DerivativeAltered := True; CountzPoints; end; procedure TDerivativesForm.EditMaxYKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var y: TGLFloat; begin try y := StrToFloat(EditMaxY.Text); except y := 1.0; end; AddedData.yMax := y; //ApplyBtn.Visible := AddedData.AddedAs > AddNone; DerivativeAltered := True; CountzPoints; end; procedure TDerivativesForm.EditMaxZKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var z: TGLFloat; begin try z := StrToFloat(EditMaxZ.Text); except z := 1.0; end; AddedData.zMax := z; //ApplyBtn.Visible := AddedData.AddedAs > AddNone; DerivativeAltered := True; CountzPoints; end; procedure TDerivativesForm.EditMinXKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var x: TGLFloat; begin try x := StrToFloat(EditMinX.Text); except x := -1.0; end; AddedData.xMin := x; //ApplyBtn.Visible := AddedData.AddedAs > AddNone; DerivativeAltered := True; CountzPoints; end; procedure TDerivativesForm.EditMinYKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var y: TGLFloat; begin try y := StrToFloat(EditMinY.Text); except y := -1.0; end; AddedData.yMin := y; //ApplyBtn.Visible := AddedData.AddedAs > AddNone; DerivativeAltered := True; CountzPoints; end; procedure TDerivativesForm.EditMinZKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var z: TGLFloat; begin try z := StrToFloat(EditMinZ.Text); except z := -1.0; end; AddedData.zMin := z; //ApplyBtn.Visible := AddedData.AddedAs > AddNone; DerivativeAltered := True; CountzPoints; end; procedure TDerivativesForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin AddedData.AddedAs := AddNone; ViewForm.ClearAddedField; ViewForm.ClearAddedLines; ViewForm.AddXLine.Visible := False; ViewForm.AddYLine.Visible := False; ViewForm.AddZLine.Visible := False; ViewForm.PlotColours1.Enabled := True; ViewForm.DerivativePlotColours1.Enabled := False; if AddPlotColorsForm.Visible then AddPlotColorsForm.Close; Altered := Altered or DerivativeAltered; end; procedure TDerivativesForm.FormShow(Sender: TObject); begin Caption := GraphFName; with AddedData do begin EditMinX.Text := FloatToStrF(xMin, ffGeneral, 7, 4); EditMaxX.Text := FloatToStrF(xMax, ffGeneral, 7, 4); Editdx.Text := FloatToStrF(xInc, ffGeneral, 7, 4); EditMinY.Text := FloatToStrF(yMin, ffGeneral, 7, 4); EditMaxY.Text := FloatToStrF(yMax, ffGeneral, 7, 4); Editdy.Text := FloatToStrF(yInc, ffGeneral, 7, 4); EditMinZ.Text := FloatToStrF(zMin, ffGeneral, 7, 4); EditMaxZ.Text := FloatToStrF(zMax, ffGeneral, 7, 4); zLimitCB.Checked := zLim; zCapCB.Checked := zCap; ModeComboBox.ItemIndex := Ord(ViewMode); StyleComboBox.ItemIndex := Ord(fxyMode); if AddLineWidth < 1 then AddLineWidth := 1; EditAddLineWidth.Text := IntToStr(AddLineWidth); ModeComboBox.ItemIndex := Ord(ViewMode); StyleComboBox.ItemIndex := Ord(fxyMode); end; AddPlotColorsForm.ShowPlotColorData; //ApplyBtn.Visible := VolumeRB.Checked; if DerivXRB.Checked or DerivyRB.Checked then ApplyBtnClick(Sender); DerivativeAltered := False; CountzPoints; end; procedure TDerivativesForm.GridValuesClick(Sender: TObject); begin with ViewData.xyGrid.xRange do begin EditMinX.Text := FloatToStrF(Minimum, ffGeneral, 7, 4); AddedData.xMin := Minimum; EditMaxX.Text := FloatToStrF(Maximum, ffGeneral, 7, 4); AddedData.xMax := Maximum; EditdX.Text := FloatToStrF(Step, ffGeneral, 7, 4); AddedData.xInc := Step; end; with ViewData.xyGrid.yRange do begin EditMinY.Text := FloatToStrF(Minimum, ffGeneral, 7, 4); AddedData.yMin := Minimum; EditMaxY.Text := FloatToStrF(Maximum, ffGeneral, 7, 4); AddedData.yMax := Maximum; EditdY.Text := FloatToStrF(Step, ffGeneral, 7, 4); AddedData.yInc := Step; end; with ViewData.xzGrid.zRange do begin EditMinZ.Text := FloatToStrF(Minimum, ffGeneral, 7, 4); AddedData.zMin := Minimum; EditMaxZ.Text := FloatToStrF(Maximum, ffGeneral, 7, 4); AddedData.zMax := Maximum; end; DerivativeAltered := True; CountzPoints; end; procedure TDerivativesForm.GridValuesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin //ApplyBtn.Visible := AddedData.AddedAs > AddNone; end; procedure TDerivativesForm.IncKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do if not CharInSet(Key, PosFloat) then Key := #0; end; procedure TDerivativesForm.ModeComboBoxChange(Sender: TObject); begin AddedData.ViewMode := TViewMode(ModeComboBox.ItemIndex); //ApplyBtn.Visible := AddedData.AddedAs > AddNone; ApplyBtnClick(Sender); end; procedure TDerivativesForm.FloatKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do if not CharInSet(Key, AnyFloat) then Key := #0; end; procedure TDerivativesForm.PlotValuesClick(Sender: TObject); begin EditMinx.Text := FloatToStrF(PlotData.xMin, ffGeneral, 7, 4); AddedData.xMin := PlotData.xMin; EditMaxx.Text := FloatToStrF(PlotData.xMax, ffGeneral, 7, 4); AddedData.xMax := PlotData.xMax; EditdX.Text := FloatToStrF(PlotData.xInc, ffGeneral, 7, 4); AddedData.xInc := PlotData.xInc; EditMiny.Text := FloatToStrF(PlotData.yMin, ffGeneral, 7, 4); AddedData.yMin := PlotData.yMin; EditMaxy.Text := FloatToStrF(PlotData.yMax, ffGeneral, 7, 4); AddedData.yMax := PlotData.yMax; EditdY.Text := FloatToStrF(PlotData.yInc, ffGeneral, 7, 4); AddedData.yInc := PlotData.yInc; EditMinz.Text := FloatToStrF(PlotData.zMin, ffGeneral, 7, 4); AddedData.zMin := PlotData.zMin; EditMaxz.Text := FloatToStrF(PlotData.zMax, ffGeneral, 7, 4); AddedData.zMax := PlotData.zMax; zLimitCB.Checked := PlotData.zLim; AddedData.zLim := PlotData.zLim; zCapCB.Checked := PlotData.zCap; AddedData.zCap := PlotData.zCap; CountzPoints; end; procedure TDerivativesForm.PlotValuesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin //ApplyBtn.Visible := AddedData.AddedAs > AddNone; end; procedure TDerivativesForm.StyleComboBoxChange(Sender: TObject); begin AddedData.fxyMode := TfxyMode(StyleComboBox.ItemIndex); //ApplyBtn.Visible := AddedData.AddedAs > AddNone; ApplyBtnClick(Sender); end; procedure TDerivativesForm.VolumeRBClick(Sender: TObject); begin AddedData.AddedAs := AddVolume; //ApplyBtn.Visible := not TooManyPoints; ApplyBtnClick(Sender); end; procedure TDerivativesForm.DerivXRBClick(Sender: TObject); begin ViewForm.ClearAddedLines; AddedData.AddedAs := AddDerivX; DerivXRB.Checked := False; ApplyBtnClick(Sender); end; procedure TDerivativesForm.DerivYRBClick(Sender: TObject); begin ViewForm.ClearAddedLines; AddedData.AddedAs := AddDerivY; DerivYRB.Checked := False; ApplyBtnClick(Sender); end; procedure TDerivativesForm.zCapCBClick(Sender: TObject); begin ViewForm.ClearAddedLines; AddedData.zCap := zCapCB.Checked; //ApplyBtn.Visible := AddedData.AddedAs = AddVolume; end; procedure TDerivativesForm.zLimitCBClick(Sender: TObject); begin AddedData.zLim := zLimitCB.Checked; //ApplyBtn.Visible := AddedData.AddedAs = AddVolume; end; procedure TDerivativesForm.ApplyBtnClick(Sender: TObject); var v: TGLFloat; s: string; begin if TooManyPoints then Exit; Screen.Cursor := crHourGlass; with AddedData do begin if xMin > xMax then { swap } begin v := xMin; xMin := xMax; xMax := v; s := EditMinX.Text; EditMinX.Text := EditMaxX.Text; EditMaxX.Text := s; end; if yMin > yMax then { swap } begin v := yMin; yMin := yMax; yMax := v; s := EditMinY.Text; EditMinY.Text := EditMaxY.Text; EditMaxY.Text := s; end; if zMin > zMax then { swap } begin v := zMin; zMin := zMax; zMax := v; s := EditMinZ.Text; EditMinZ.Text := EditMaxZ.Text; EditMaxZ.Text := s; end; if DerivXRB.Checked then AddedAs := AddDerivX else if DerivYRB.Checked then AddedAs := AddDerivY else if VolumeRB.Checked then AddedAs := AddVolume; end; PosVolLabel.Caption := ''; NegVolLabel.Caption := ''; TotalLabel.Caption := ''; VolumeLabel.Caption := ''; ViewForm.ClearAddedField; ViewForm.ClearAddedLines; ViewForm.UpdateAdded; EvaluateForm.UpdateEvaluate; ApplyBtn.Visible := False; Screen.Cursor := crDefault; end; procedure TDerivativesForm.CloseBtnClick(Sender: TObject); begin Close; end; procedure TDerivativesForm.ColorButtonClick(Sender: TObject); begin ColorDialog.Color := AddedData.AddLineColor; if ColorDialog.Execute then begin AddedData.AddLineColor := ColorDialog.Color; with ViewForm do begin with AddXLine do LineColor.AsWinColor := AddedData.AddLineColor; with AddYLine do LineColor.AsWinColor := AddedData.AddLineColor; with AddZLine do LineColor.AsWinColor := AddedData.AddLineColor; end; DerivativeAltered := True; ApplyBtnClick(Sender); end; end; procedure TDerivativesForm.CountzPoints; var n, c: integer; begin with AddedData do n := round((xMax - xMin)/xInc +1)*round((yMax - yMin)/yInc +1); c := round(Log10(n)); case c of 0..1:ZCountLabel.Font.Color := clLime; 2:ZCountLabel.Font.Color := clTeal; 3:ZCountLabel.Font.Color := clGreen; 4:ZCountLabel.Font.Color := clBlue; else ZCountLabel.Font.Color := clRed; end; TooManyPoints := c > 4; if TooManyPoints then ZCountLabel.Caption := 'Too many Points: ' + FloatToStrF(n, ffnumber, 8, 0)+' !' else ZCountLabel.Caption := 'N° Points = ' + FloatToStrF(n, ffnumber, 8, 0); end; end.
unit Objekt.DHLReceiver; interface uses SysUtils, Classes, geschaeftskundenversand_api_2, Objekt.DHLReceiverNativeAddress, Objekt.DHLCommunication; type TDHLReceiver = class private fReceiverTypeAPI: ReceiverType; fName1: string; fAddress: TDHLReceiverNativeAddress; fCommunication: TDHLCommunication; procedure setName1(const Value: string); public constructor Create; destructor Destroy; override; function ReceiverTypeAPI: ReceiverType; property Name1: string read fName1 write setName1; property Address: TDHLReceiverNativeAddress read fAddress write fAddress; property Communication: TDHLCommunication read fCommunication write fCommunication; end; implementation { TDHLReceiver } constructor TDHLReceiver.Create; begin fAddress := TDHLReceiverNativeAddress.Create; fCommunication := TDHLCommunication.Create; fReceiverTypeAPI := ReceiverType.Create; fReceiverTypeAPI.Address := fAddress.ReceiverNativeAddressTypeAPI; fReceiverTypeAPI.Communication := fCommunication.CommunicationTypeAPI; end; destructor TDHLReceiver.Destroy; begin FreeAndNil(fAddress); FreeAndNil(fCommunication); FreeAndNil(fReceiverTypeAPI); inherited; end; function TDHLReceiver.ReceiverTypeAPI: ReceiverType; begin Result := fReceiverTypeAPI; end; procedure TDHLReceiver.setName1(const Value: string); begin fName1 := Value; fReceiverTypeAPI.name1 := Value; end; end.
unit uDemoViewFrameTipo2; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, uInterfaces, uAtributos, uDemoInterfaces, uDemoViewModels, uTypes, uView, FMX.ScrollBox, FMX.Memo; type [ViewForVM(IMyViewModel2, TMyViewModel2)] TFrame2 = class(TFrameView<IMyViewModel2, TMyViewModel2>) Label1: TLabel; Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } function GetVM_AsInterface: IMyViewModel2; override; function GetVM_AsObject: TMyViewModel2; override; end; implementation {$R *.fmx} procedure TFrame2.Button1Click(Sender: TObject); begin Memo1.Lines.Add(GetVM_AsInterface.Hello2); end; function TFrame2.GetVM_AsInterface: IMyViewModel2; begin Result := FViewModel as IMyViewModel2 end; function TFrame2.GetVM_AsObject: TMyViewModel2; begin Result := FViewModel as TMyViewModel2; end; end.
Program pi(output); Uses sysutils; { Use am Int64 for numsteps because we want to use big numbers of steps. } Var step, x, sum, mypi, time, start, stop : Double; i, numsteps : Int64; Begin numsteps := 1000000000; { Get numsteps from command line args. } if ParamCount > 0 then numsteps := StrToInt64(ParamStr(1)); Writeln('Calculating PI using:'); Writeln(' ', numsteps, ' slices'); { Initialise time counter and sum. Set step size. } start := TimeStampToMSecs(DateTimeToTimeStamp(Now)); sum := 0.0; step := 1.0/Double(numsteps); For i := 1 To numsteps Do Begin x := (Double(i) - 0.5) * step; sum := sum + 4.0/(1.0 + x*x); End; { Calculate pi from final value and stop clock. } mypi := sum * step; stop := TimeStampToMSecs(DateTimeToTimeStamp(Now)); { Note: Highest resolution of this method is milliseconds.} time := (stop - start)/1000; Writeln('Obtained value of PI: ', FloatToStrf(mypi, fffixed, 2, 8)); Writeln('Time taken: ', FloatToStrf(time, fffixed, 4, 4), ' seconds'); End.
unit TpForm; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThTag, ThForm, TpControls; type TTpForm = class(TThForm) private FOnGenerate: TTpEvent; FOnSubmit: TTpEvent; protected function GetInputsHtml: string; override; protected procedure Tag(inTag: TThTag); override; published property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; property OnSubmit: TTpEvent read FOnSubmit write FOnSubmit; end; implementation { TTpForm } function TTpForm.GetInputsHtml: string; const SHiddenInput = '<input type="hidden" name="%s" value="%s" tpName="%0:s" tpClass="TTpInput" />'; var i: Integer; begin //Result := Format('<input type="hidden" name="%s" value="%s" />', // [ Name + '_s', 'submit' ]); Result := Format(SHiddenInput, [ 'tpsubmit', Name ]); for i := 0 to Pred(Inputs.Count) do with Inputs[i] do Result := Result + Format(SHiddenInput, [ WebName, WebValue ]); end; procedure TTpForm.Tag(inTag: TThTag); begin inherited; with inTag do begin Add(tpClass, 'TTpForm'); Add('tpName', Name); if DefaultButton <> nil then Add('tpDefaultButton', DefaultButton.Name); Add('tpOnGenerate', OnGenerate); Add('tpOnSubmit', OnSubmit); end; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Repository.Interfaces; interface uses Spring.Collections, VSoft.Awaitable, DPM.Core.Types, DPM.Core.Sources.Types, DPM.Core.Dependency.Version, DPM.Core.Options.Search, DPM.Core.Options.Push, DPM.Core.Configuration.Interfaces, DPM.Core.Package.Interfaces; type // IPackageSearchResult = interface // ['{39B253DC-4BC5-4E72-918A-2FACC3EB5AC5}'] // function GetPackages : IList<IPackageIdentity>; // property Packages : IList<IPackageIdentity> read GetPackages; // end; //bear in mind that there will be a remote repository implemented with http //so need to keep that in mind with these interfaces. IPackageRepository = interface ['{0B495C12-4BDF-4C1C-9BD6-B008F0BA7F18}'] function GetRepositoryType : TSourceType; function GetName : string; function GetSource : string; procedure Configure(const source : ISourceConfig); function GetEnabled : boolean; procedure SetEnabled(const value : boolean); //above implemented in base class /// Used by the PackageInstaller /// function FindLatestVersion(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const version : TPackageVersion; const platform : TDPMPlatform; const includePrerelease : boolean) : IPackageIdentity; function DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : boolean; function GetPackageVersions(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const preRelease : boolean) : IList<TPackageVersion>; overload; function GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const versionRange : TVersionRange; const preRelease : boolean) : IList<IPackageInfo>; function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo; function GetPackageMetaData(const cancellationToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResultItem; function GetPackageIcon(const cancellationToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon; function GetPackageFeed(const cancellationToken : ICancellationToken; const options : TSearchOptions; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult; function GetPackageFeedByIds(const cancellationToken : ICancellationToken; const ids : IList<IPackageId>; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult; //commands function Push(const cancellationToken : ICancellationToken; const pushOptions : TPushOptions) : Boolean; function List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageListItem>; overload; property Enabled : boolean read GetEnabled write SetEnabled; property Name : string read GetName; property Source : string read GetSource; property RepositoryType : TSourceType read GetRepositoryType; end; IPackageRepositoryFactory = interface ['{67014BE3-AA4C-45ED-A043-68262E57B89A}'] function CreateRepository(const repoType : TSourceType) : IPackageRepository; end; IPackageRepositoryManager = interface ['{86DEB23D-7229-4F1C-949C-0A5CFB421152}'] function Initialize(const configuration : IConfiguration) : boolean; function HasSources : boolean; //commands function List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageListItem>; function Push(const cancellationToken : ICancellationToken; const pushOptions : TPushOptions) : Boolean; //used by the package installer when no version specified - also for the cache command function FindLatestVersion(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const version : TPackageVersion; const platform : TDPMPlatform; const includePrerelease : boolean; const sources : string) : IPackageIdentity; function DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : boolean; //downloads the dspec function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo; function GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const packageId : string; const versionRange : TVersionRange; const includePrerelease : boolean) : IList<IPackageInfo>; function GetPackageVersions(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const packageId : string; const includePrerelease : boolean) : IList<TPackageVersion>; overload; //ui specific stuff function GetPackageMetaData(const cancellationToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResultItem; function GetPackageFeed(const cancellationToken : ICancellationToken; const options : TSearchOptions; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult; function GetPackageIcon(const cancellationToken : ICancellationToken; const source : string; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon; function GetInstalledPackageFeed(const cancellationToken : ICancellationToken; const options : TSearchOptions; const installedPackages : IList<IPackageId>) : IList<IPackageSearchResultItem>; end; implementation end.
unit Related; { a modal dialog used for displaying and deleting all questions related to a question } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DB, DBTables, Grids, DBGrids, Buttons, ExtCtrls, ComCtrls; type TfrmRelated = class(TForm) panHeader: TPanel; btnGoTo: TSpeedButton; btnRefresh: TSpeedButton; btnDelete: TSpeedButton; btnClose: TSpeedButton; btnPrint: TSpeedButton; dgrRecode: TDBGrid; dgrFollow: TDBGrid; dgrPreced: TDBGrid; srcFollow: TDataSource; srcProced: TDataSource; srcRecode: TDataSource; btnContinue: TSpeedButton; qryRecode: TQuery; qryPreced: TQuery; qryFollow: TQuery; staRelated: TStatusBar; updRecode: TUpdateSQL; qryPrecedCore: TIntegerField; qryPrecedDescription: TStringField; qryPrecedShort: TStringField; qryFollowCore: TIntegerField; qryFollowDescription: TStringField; qryFollowShort: TStringField; qryRecodeCore: TIntegerField; qryRecodeDescription: TStringField; qryRecodeShort: TStringField; procedure FormShow(Sender: TObject); procedure CloseClick(Sender: TObject); procedure RefreshClick(Sender: TObject); procedure PrintClick(Sender: TObject); procedure GoToClick(Sender: TObject); procedure DeleteClick(Sender: TObject); procedure ContinueClick(Sender: TObject); procedure UpdateRelated; function GetRecordCount( vQuery : TQuery ) : Integer; private { Private declarations } public vDelete : Boolean; end; const cItemHeight = 19; // height of each entry in a grid cMinFormHeight = 79; // smallest the dialog can be cMargin = 5; // distance to maintain from the edge of the screen cTopDefault = 100; // top if the dialog is not tall enough to hang off the screen var frmRelated: TfrmRelated; implementation uses Data, Common, RRelated, Lookup; {$R *.DFM} { ACTIVATION } procedure TfrmRelated.FormShow(Sender: TObject); begin Left := Screen.Width - ( Width + cMargin ); UpdateRelated; end; { recalculates and displays the number of related questions: 1. calls GetRelatedCount (common unit) 2. displays count and sets button states 3. calculates height of each grid to display number of questions } procedure TfrmRelated.UpdateRelated; var vCount : Word; vGrid : TDBGrid; begin vCount := GetRelatedCount( modLibrary.wtblQuestionCore.Value, False, modLookup.tblRecode, modLookup.tblQuestion ); staRelated.SimpleText := 'Number of Related Questions: ' + IntToStr( vCount ); btnPrint.Enabled := ( vCount > 0 ); btnDelete.Enabled := ( vCount > 0 ); btnGoTo.Enabled := ( vCount > 0 ); btnContinue.Enabled := ( vCount > 0 ); if vCount > 0 then begin if GetRecordCount( qryPreced ) > 0 then begin dgrPreced.Visible := True; dgrPreced.Height := Succ( qryPreced.RecordCount ) * cItemHeight; end else begin dgrPreced.Visible := False; dgrPreced.Height := 0; end; if GetRecordCount( qryFollow ) > 0 then begin dgrFollow.Visible := True; dgrFollow.Height := Succ( qryFollow.RecordCount ) * cItemHeight; end else begin dgrFollow.Visible := False; dgrFollow.Height := 0; end; if GetRecordCount( qryRecode ) > 0 then begin dgrRecode.Visible := True; dgrRecode.Height := Succ( qryRecode.RecordCount ) * cItemHeight; end else begin dgrRecode.Visible := False; dgrRecode.Height := 0; end; Height := cMinFormHeight + dgrPreced.Height + dgrFollow.Height + dgrRecode.Height; while ( Height + cMargin * 2 ) > Screen.Height do begin if dgrPreced.Height > dgrFollow.Height then vGrid := dgrPreced else vGrid := dgrFollow; if dgrRecode.Height > vGrid.Height then vGrid := dgrRecode; vGrid.Height := vGrid.Height - cItemHeight; end; end else begin dgrPreced.Height := 0; dgrFollow.Height := 0; dgrRecode.Height := 0; dgrPreced.Visible := False; dgrFollow.Visible := False; dgrRecode.Visible := False; Height := cMinFormHeight; end; if ( Height + cTopDefault + cMargin ) < Screen.Height then Top := cTopDefault else Top := ( Screen.Height - Height ) div 2; end; { GENERAL METHODS } { executes a query based on question core value and returns the resulting record number } function TfrmRelated.GetRecordCount( vQuery : TQuery ) : Integer; begin if vQuery.Active then vQuery.Close; vQuery.Params[ 0 ].AsInteger := modLibrary.wtblQuestionCore.Value; vQuery.Open; Result := vQuery.RecordCount; end; { BUTTON METHODS } procedure TfrmRelated.CloseClick(Sender: TObject); begin Close; end; procedure TfrmRelated.RefreshClick(Sender: TObject); begin UpdateRelated; end; { prints a list of related questions } procedure TfrmRelated.PrintClick(Sender: TObject); begin qryPreced.DisableControls; qryFollow.DisableControls; qryRecode.DisableControls; try rptRelated := TrptRelated.Create( Application ); rptRelated.qrRelated.Print; rptRelated.Release; finally qryPreced.EnableControls; qryFollow.EnableControls; qryRecode.EnableControls; end; end; procedure TfrmRelated.GoToClick(Sender: TObject); begin modLibrary.wtblQuestion.Locate( 'Core', ( ActiveControl as TDBGrid ).DataSource.DataSet.FieldByName( 'Core' ).Value, [ ] ); end; { deletes (recode) or removes (preced or follow) the related question: 1. if recode, uses an UpdateSQL component to delete record 2. otherwise, clears the referencing field } procedure TfrmRelated.DeleteClick(Sender: TObject); var vControl : string; begin vControl := ActiveControl.Name; if vControl = 'dgrRecode' then updRecode.Apply( ukDelete ) else with ( ActiveControl as TDBGrid ).DataSource.DataSet do begin Edit; if vControl = 'dgrPreced' then FieldByName( 'PrecededBy' ).Clear else FieldByName( 'FollowedBy' ).Clear; Post; end; UpdateRelated; end; { deletes all related questions (calls GetRelatedCount, passes in true for delete) } procedure TfrmRelated.ContinueClick(Sender: TObject); begin GetRelatedCount( modLibrary.wtblQuestionCore.Value, True, modLookup.tblRecode, modLookup.tblQuestion ); Close; end; end.
{* FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn Cryptograpical code from OpenSSL Project *} unit sshdh; interface uses Classes, sysutils, sshbn; type DH_STRUCT = record pad, version: integer; p, g: BIGNUM; length: integer; pub_key, priv_key: BIGNUM; flags: integer; seed: PChar; seedlen: integer; counter: BIGNUM; refrences: integer; // actually, there are 2 fields here, but i don't want them end; DH = ^DH_STRUCT; function DH_new: DH; cdecl; external 'libeay32.dll'; procedure DH_free(dh: DH); cdecl; external 'libeay32.dll'; function DH_generate_key(dh: DH): integer; cdecl; external 'libeay32.dll'; function DH_size(dh: DH): integer; cdecl; external 'libeay32.dll'; function DH_compute_key(Key: PChar; f: BIGNUM; dh: DH): integer; cdecl; external 'libeay32.dll'; type TSSHDH = class public dh: DH; // tobe moved into private part; function PubkeyValid(pub: BIGNUM): boolean; constructor Create(Owner: TObject); destructor Destroy; override; procedure NewGroupAsc(generator, group: string); procedure GenKey(needbits: integer); function FindK(f: BIGNUM): BIGNUM; end; EDHError = class(Exception); implementation uses sshutil; { TSSHDH } const Group1Str1: string = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437'; Group1Str2: string = '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; constructor TSSHDH.Create(Owner: TObject); begin NewGroupAsc('2', Group1Str1 + Group1Str2); end; destructor TSSHDH.Destroy; begin if dh <> nil then DH_free(dh); inherited; end; function TSSHDH.FindK(f: BIGNUM): BIGNUM; var p: pointer; len: integer; begin if not PubkeyValid(f) then begin BN_free(f); raise ESSHError.Create('Bad server pub key'); end; GetMem(p, DH_size(dh)); len := DH_compute_key(p, f, dh); Result := BN_new; BN_bin2bn(p, len, Result); FreeMem(p); end; procedure TSSHDH.GenKey(needbits: integer); var tries: integer; begin // bits_set := 0; tries := 0; if dh.p = nil then raise EDHError.Create('p is not valid'); if needbits * 2 >= BN_num_bits(dh.p) then raise EDHError.Create('group too small'); repeat if dh.priv_key <> nil then BN_free(dh.priv_key); dh.priv_key := BN_new; BN_rand(dh.priv_key, 2 * needbits, 0, 0); DH_generate_key(dh); // bits_set :=0; // for i:=0 to BN_num_bits(dh.priv_key) do // if (BN Inc(tries); if tries > 10 then raise EDHError.Create('Too many tries generating key'); until PubkeyValid(dh.pub_key); end; procedure TSSHDH.NewGroupAsc(generator, group: string); begin dh := DH_new; if dh = nil then raise EDHError.Create('new DH failed!'); if BN_hex2bn(@dh.p, PChar(group)) = 0 then raise EDHError.Create('hex2bn failed!'); if BN_hex2bn(@dh.g, PChar(generator)) = 0 then raise EDHError.Create('hex2bn failed!'); end; function TSSHDH.PubkeyValid(pub: BIGNUM): boolean; var i, n, bits_set: integer; begin bits_set := 0; n := BN_num_bits(pub); Result := False; if pub.neg <> 0 then exit; for i := 0 to n do if BN_is_bit_set(pub, i) then Inc(bits_set); if (bits_set > 1) and (BN_cmp(pub, dh.p) = -1) then Result := True; end; end.
unit vwuFoodsReport; interface uses System.SysUtils, System.Classes, Variants, vwuCommon, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, fruDateTimeFilter; type TvwFoodsReport = class(TvwCommon) FCheckNum: TIntegerField; FTableName: TWideStringField; FSumMoney: TFloatField; FPaidSum: TFloatField; FCardCode: TWideStringField; FCustomerName: TWideStringField; FOpenTable: TSQLTimeStampField; FCloseTable: TSQLTimeStampField; FDiscountSum: TFloatField; FVisit: TIntegerField; FLogicDate: TSQLTimeStampField; FDiscountName: TWideStringField; FCurrencyName: TWideStringField; FNetName: TWideStringField; FRestaurantName: TWideStringField; FMidServer: TIntegerField; FIdentInVisit: TIntegerField; private FDateFilter: TfrDateTimeFilter; FCustomerFilter: Variant; FCardNumFilter: Variant; function GetSqlDateFilter(): String; function GetSqlCustomerFilter(): String; function GetSqlCardNumFilter(): String; public constructor Create(Owner: TComponent); override; property DateFilter: TfrDateTimeFilter read FDateFilter write FDateFilter; property CustomerFilter: Variant read FCustomerFilter write FCustomerFilter; property CardNumFilter: Variant read FCardNumFilter write FCardNumFilter; {наименования вью} class function ViewName(): String; override; {получить текст базового запроса} function GetViewText(aFilter: String): String; override; end; implementation uses uServiceUtils; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TvwFoodsReport } constructor TvwFoodsReport.Create(Owner: TComponent); begin inherited; end; function TvwFoodsReport.GetSqlCardNumFilter: String; begin Result:= ''; if FCardNumFilter <> Null then Result:= ' AND (DishDiscounts.CardCode = N' + QuotedStr(FCardNumFilter) + ')'; end; function TvwFoodsReport.GetSqlCustomerFilter: String; begin Result:= ''; if FCustomerFilter <> Null then Result:= ' AND (DishDiscounts.Holder = N' + QuotedStr(FCustomerFilter) + ')'; end; function TvwFoodsReport.GetSqlDateFilter: String; begin Result:= ''; if Assigned(FDateFilter) then Result:= FDateFilter.GetSqlFilter('Orders.EndService', 'GlobalShifts.ShiftDate'); end; function TvwFoodsReport.GetViewText(aFilter: String): String; const NewLine = #13#10; var List: TStringList; begin Result:= ' SELECT ' + NewLine + ' CAST(ROW_NUMBER() OVER(ORDER BY Orders.Visit) as INT) as ID, ' + NewLine + ' GlobalShifts.ShiftDate as LogicDate, ' + NewLine + ' Orders.Visit as Visit, ' + NewLine + ' Orders.StartService as OpenTable, ' + NewLine + ' Orders.EndService as CloseTable, ' + NewLine + ' Orders.MidServer as MidServer, ' + NewLine + ' Orders.IdentInVisit as IdentInVisit, ' + NewLine + ' Orders.TableName as TableName, ' + NewLine + ' PrintChecks.CheckNum as CheckNum, ' + NewLine + ' DishDiscounts.CardCode as CardCode, ' + NewLine + ' Discounts.Name as DiscountName, ' + NewLine + ' DishDiscounts.Holder as CustomerName, ' + NewLine + ' Orders.PriceListSum as SumMoney, ' + NewLine + ' SUM(DiscParts.Sum) as DiscountSum, ' + NewLine + ' SUM(PayBindings.Paysum) as PaidSum, ' + NewLine + ' Currencies.Name as CurrencyName, ' + NewLine + ' CashGroups.Netname as NetName, ' + NewLine + ' Restaurants.Name as RestaurantName ' + NewLine + // CASHES.Name as CashName {информация о сменах работы ресторана} ' FROM GlobalShifts ' + NewLine + {информацию о кассовых серверах} ' INNER JOIN CashGroups ON (CashGroups.SIFR = GlobalShifts.Midserver) ' + NewLine + {Информация о заказе, состоит из пакетов} ' INNER JOIN Orders ON (GlobalShifts.MidServer = Orders.MidServer) ' + NewLine + ' AND (GlobalShifts.ShiftNum = Orders.iCommonShift) ' + NewLine + GetSqlDateFilter() + NewLine + {Содержит информацию о скидках} ' INNER JOIN Discparts ON (Orders.Visit = DiscParts.Visit) ' + ' AND (Orders.MidServer = DiscParts.MidServer) ' + NewLine + ' AND (Orders.IdentInVisit = DiscParts.OrderIdent) ' + NewLine + {Содержит информацию о скидках/наценках} ' INNER JOIN DishDiscounts ON (DishDiscounts.Visit = DiscParts.Visit) ' + NewLine + ' AND (DishDiscounts.MidServer = DiscParts.MidServer) ' + NewLine + ' AND (DishDiscounts.UNI = DiscParts.DiscLineUNI) ' + NewLine + ' AND (DishDiscounts.CardCode <> '''') ' + NewLine + ' AND (DishDiscounts.ChargeSource = 5) ' + NewLine + GetSqlCardNumFilter() + NewLine + GetSqlCustomerFilter() + NewLine + {платежи} ' INNER JOIN PayBindings ON (PayBindings.Visit = DiscParts.Visit) ' + NewLine + ' AND (PayBindings.MidServer = DiscParts.MidServer) ' + NewLine + ' AND (PayBindings.UNI = DiscParts.BindingUNI) ' + NewLine + {Содержит информацию о платежи с учетом валюты} ' INNER JOIN CurrLines ON (CurrLines.Visit = PayBindings.Visit) ' + NewLine + ' AND (CurrLines.MidServer = PayBindings.MidServer) ' + NewLine + ' AND (CurrLines.UNI = PayBindings.CurrUNI) ' + NewLine + {информацию о чеках} ' INNER JOIN PrintChecks ON (PrintChecks.Visit = CurrLines.Visit) ' + NewLine + ' AND (PrintChecks.MidServer = CurrLines.MidServer) ' + NewLine + ' AND (PrintChecks.UNI = CurrLines.CheckUNI) ' + NewLine + ' AND ((PrintChecks.State = 6) OR (PrintChecks.State = 7)) ' + NewLine + ' AND (PrintChecks.Deleted = 0) ' + NewLine + {информация о кассе закрытия чека} //INNER JOIN CASHES ON (CASHES.SIFR = PrintChecks.ICLOSESTATION) {Содержит информацию о скидках/наценках} ' LEFT JOIN Discounts ON (Discounts.SIFR = DishDiscounts.Sifr) ' + NewLine + {информацию о валюте} ' LEFT JOIN Currencies ON Currencies.SIFR = CurrLines.SIFR ' + NewLine + {информацию о ресторане} ' LEFT JOIN Restaurants ON (Restaurants.SIFR = CashGroups.Restaurant) ' + NewLine + ' GROUP BY ' + NewLine + ' GlobalShifts.ShiftDate, ' + NewLine + ' Orders.MidServer, ' + NewLine + ' Orders.Visit, ' + NewLine + ' Orders.StartService, ' + NewLine + ' Orders.EndService, ' + NewLine + ' Orders.TableName, ' + NewLine + ' Orders.PriceListSum, ' + NewLine + ' Orders.IdentInVisit, ' + NewLine + ' DishDiscounts.CardCode, ' + NewLine + ' DishDiscounts.Holder, ' + NewLine + ' PrintChecks.CheckNum, ' + NewLine + ' Discounts.Name, ' + NewLine + ' Currencies.Name, ' + NewLine + ' CashGroups.NetName, ' + NewLine + ' Restaurants.Name '; // CASHES.Name List := TStringList.Create; try List.Add(Result); List.SaveToFile('d:\sql.text'); finally List.Free; end; end; class function TvwFoodsReport.ViewName: String; begin Result:= 'VW_FOODS_REPORT'; end; end.
// design a program to get 100 values, //find the average of the values //and find the number of values greater than the average. // the program should display the average, //and a count of the numbers greater than the average. Program avg_count; var sum, avg:real; count, j:integer; value: array [1..5] of real; begin sum:=0; count:=0; FOR j:= 1 to 5 DO begin writeln ('Please enter a value'); readln (value[j]); sum:= sum + value[j]; end; avg := sum/5 ; FOR j:= 1 to 5 DO begin IF value[j] > avg THEN begin count := count + 1; end; end; writeln('The average is ',avg:3:2); writeln ('The amount of numbers greater than the average is ',count); readln(); end.
program bubble_sort; const N = 10; // Max number of array elements type array1d = Array[1..N] of Integer; { Start pf procedure switchElements } procedure switchElements(var el1, el2 : Integer); var temp : Integer; begin temp := el1; el1 := el2; el2 := temp; end; { End of procedure switchElements } { Start of procedure fillArray } procedure fillArray(var arrFill : array1d); var i : Integer; begin WriteLn('Filling array elements...'); Randomize; for i := 1 to N do begin arrFill[i] := Random(1000); end; WriteLn(); end; { End of procedure fillArray } { Start of procedure listArray } procedure listArray(arr : array1d); var i : Integer; begin WriteLn('Array elements:'); for i := 1 to N do begin Write(arr[i], ' '); end; WriteLn(); WriteLn(); end; { End of procedure listArray } { Start of procedure bubbleSort } procedure bubbleSort(var sortArray : array1d); var i, j, temp : Integer; begin WriteLn('Sorting array...'); for i := 1 to N do begin for j := 1 to N-1 do begin if sortArray[j] > sortArray[j+1] then begin switchElements(sortArray[j], sortArray[j+1]); end; end; end; WriteLn('Done sorting array!'); WriteLn(); end; { End of procedure bubbleSort } var array_of_elements : array1d; begin fillArray(array_of_elements); listArray(array_of_elements); bubbleSort(array_of_elements); listArray(array_of_elements); Write('Press <Enter> to close the program...'); ReadLn(); end.
unit KrDnceGraphTypes; interface uses System.Types, System.UITypes, FMX.Graphics, FMX.ImgList; function ImageListAdd(AImgList: TImageList; ABitmap: TBitmap): Integer; procedure ImageListReplace(AImgList: TImageList; AIndex: Integer; ABitmap: TBitmap); implementation uses FMX.MultiResBitmap; function ImageListAdd(AImgList: TImageList; ABitmap: TBitmap): Integer; const SCALE = 1; var vSource: TCustomSourceItem; vBitmapItem: TCustomBitmapItem; vDest: TCustomDestinationItem; vLayer: TLayer; begin Result := -1; if (ABitmap.Width = 0) or (ABitmap.Height = 0) then Exit; // add source bitmap vSource:= AImgList.Source.Add; vSource.MultiResBitmap.TransparentColor:= TColorRec.Fuchsia; vSource.MultiResBitmap.SizeKind:= TSizeKind.Source; vSource.MultiResBitmap.Width:= Round(ABitmap.Width / SCALE); vSource.MultiResBitmap.Height:= Round(ABitmap.Height / SCALE); vBitmapItem := vSource.MultiResBitmap.ItemByScale(SCALE, True, True); if vBitmapItem = nil then begin vBitmapItem:= vSource.MultiResBitmap.Add; vBitmapItem.Scale:= Scale; end; vBitmapItem.Bitmap.Assign(ABitmap); vDest:= AImgList.Destination.Add; vLayer:= vDest.Layers.Add; vLayer.SourceRect.Rect:= TRectF.Create(TPoint.Zero, vSource.MultiResBitmap.Width, vSource.MultiResBitmap.Height); vLayer.Name:= vSource.Name; Result:= vDest.Index; end; procedure ImageListReplace(AImgList: TImageList; AIndex: Integer; ABitmap: TBitmap); const SCALE = 1; var vSource: TCustomSourceItem; vBitmapItem: TCustomBitmapItem; vDest: TCustomDestinationItem; vLayer: TLayer; begin if (ABitmap.Width = 0) or (ABitmap.Height = 0) then Exit; // replace source bitmap vSource:= AImgList.Source.Items[AIndex]; vBitmapItem := vSource.MultiResBitmap.ItemByScale(SCALE, True, True); if vBitmapItem = nil then begin vBitmapItem:= vSource.MultiResBitmap.Add; vBitmapItem.Scale:= Scale; end; vBitmapItem.Bitmap.Assign(ABitmap); vDest:= AImgList.Destination.Items[AIndex]; vLayer:= vDest.Layers.Items[0]; vLayer.SourceRect.Rect:= TRectF.Create(TPoint.Zero, vSource.MultiResBitmap.Width, vSource.MultiResBitmap.Height); vLayer.Name:= vSource.Name; end; end.
unit Antlr.Runtime.Collections.Tests; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Antlr.Runtime.Collections, Generics.Collections, Antlr.Runtime.Tools; type // Test methods for class IHashList TestIHashList = class(TTestCase) strict private FIHashList: IHashList<Integer, String>; public procedure SetUp; override; procedure TearDown; override; published procedure TestInsertionOrder; procedure TestRemove; end; // Test methods for class IStackList TestIStackList = class(TTestCase) strict private FIStackList: IStackList<String>; public procedure SetUp; override; procedure TearDown; override; published procedure TestPushPop; procedure TestPeek; end; implementation uses SysUtils; const Values: array [0..9] of Integer = (50, 1, 33, 76, -22, 22, 34, 2, 88, 12); procedure TestIHashList.SetUp; var I: Integer; begin FIHashList := THashList<Integer, String>.Create; for I in Values do FIHashList.Add(I,'Value' + IntToStr(I)); end; procedure TestIHashList.TearDown; begin FIHashList := nil; end; procedure TestIHashList.TestInsertionOrder; var I: Integer; P: TPair<Integer, String>; begin I := 0; for P in FIHashList do begin CheckEquals(P.Key, Values[I]); CheckEquals(P.Value, 'Value' + IntToStr(Values[I])); Inc(I); end; end; procedure TestIHashList.TestRemove; var I: Integer; P: TPair<Integer, String>; begin FIHashList.Remove(34); I := 0; for P in FIHashList do begin if (Values[I] = 34) then Inc(I); CheckEquals(P.Key, Values[I]); CheckEquals(P.Value, 'Value' + IntToStr(Values[I])); Inc(I); end; end; procedure TestIStackList.SetUp; begin FIStackList := TStackList<String>.Create; end; procedure TestIStackList.TearDown; begin FIStackList := nil; end; procedure TestIStackList.TestPushPop; var Item: String; begin Item := 'Item 1'; FIStackList.Push(Item); Item := 'Item 2'; FIStackList.Push(Item); CheckEquals(FIStackList.Pop,'Item 2'); CheckEquals(FIStackList.Pop,'Item 1'); end; procedure TestIStackList.TestPeek; begin FIStackList.Push('Item 1'); FIStackList.Push('Item 2'); FIStackList.Push('Item 3'); FIStackList.Pop; CheckEquals(FIStackList.Peek, 'Item 2'); CheckEquals(FIStackList.Pop, 'Item 2'); end; initialization // Register any test cases with the test runner RegisterTest(TestIHashList.Suite); RegisterTest(TestIStackList.Suite); end.
unit uProgressDialog; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, uWorker; type TProgressDialog = class( TForm ) Label0: TLabel; Label1: TLabel; ProgressBar1: TProgressBar; btnCancel: TButton; procedure btnCancelClick( Sender: TObject ); procedure FormCreate( Sender: TObject ); procedure FormCloseQuery( Sender: TObject; var CanClose: Boolean ); private { Private declarations } FWorker: TWorker; procedure SetMax( Max: Integer ); procedure SetMin( Min: Integer ); procedure SetPos( Pos: Integer ); procedure SetTitle( Title: String ); procedure SetText0( Text0: String ); procedure SetText1( Text1: String ); public { Public declarations } constructor Create( AOwner: TComponent; AWorker: TWorker ); reintroduce; { overload; } property Title: String write SetTitle; property Text0: String write SetText0; property Text1: String write SetText1; property Max: Integer write SetMax; property Min: Integer write SetMin; property Pos: Integer write SetPos; end; var ProgressDialog: TProgressDialog; implementation {$R *.dfm} procedure TProgressDialog.btnCancelClick( Sender: TObject ); begin FWorker.TaskCancel( ); end; constructor TProgressDialog.Create( AOwner: TComponent; AWorker: TWorker ); begin inherited Create( AOwner ); FWorker := AWorker; end; procedure TProgressDialog.FormCloseQuery( Sender: TObject; var CanClose: Boolean ); begin btnCancelClick( Self ); end; procedure TProgressDialog.FormCreate( Sender: TObject ); begin FWorker.TaskStart( ); end; procedure TProgressDialog.SetTitle( Title: String ); begin Self.Caption := Title; end; procedure TProgressDialog.SetText0( Text0: String ); begin Label0.Caption := Text0; end; procedure TProgressDialog.SetText1( Text1: String ); begin Label1.Caption := Text1; end; procedure TProgressDialog.SetMax( Max: Integer ); begin ProgressBar1.Max := Max; end; procedure TProgressDialog.SetMin( Min: Integer ); begin ProgressBar1.Min := Min; end; procedure TProgressDialog.SetPos( Pos: Integer ); begin ProgressBar1.Position := Pos; end; end.
{ @abstract Implements @link(TNtTranslator) class that perform runtime language switch. Normally you don't use this unit. Instead you use @link(NtLanguageDlg.TNtLanguageDialog) to perform runtime language switch. If you have your own user interface to select a new language then you use @link(TNtTranslator.SetNew). You can use lower lever routines to select the language and to @link(TNtBase.LoadNew load) a new resource DLL, and to @link(TNtTranslator.TranslateForms translate) all forms into the new language. } unit NtTranslator; {$I NtVer.inc} interface uses Classes, Forms, NtBase, NtBaseTranslator; type { @abstract Class that translates VCL forms, frames and data modules. This class performs runtime language switch by going through each component and property on the host component (form, frame or data module). Call @link(TNtTranslator.TranslateForms) to translate all forms. } TNtTranslator = class(TNtBaseTranslator) protected { Called after a component has been translated. @param component Component that has been translated. } procedure AfterProcessComponent(component: TComponent); override; procedure Translate(component: TComponent); override; public procedure TranslateForm(form: TCustomForm); { Call this function in the initialization section of your main form. @param layout The original layout of the application. } class procedure InitializeApplication(layout: TNtLayout = laLeftToRight); { Flips the form layout if needed. @param form Form to be initialized. } class procedure InitializeForm(form: TCustomForm); { Load a new resource DLL file, initialize the language depend values, and finally translate the forms. @param code Specifies the file extension without period of the new resource DLL. @param options Language change options. @param originalCode Language used in the original application. @param fileName The file to be loaded. If empty then function looks the standard resource file name and location. @return @true if succesful, @false if failed. } class function SetNew( const code: String = ''; options: TNtResourceOptions = []; const originalCode: String = ''; const fileName: String = ''): Boolean; { Translate all created forms, frames and data modules. } class procedure TranslateForms; end; // _T has been moved to NtTranslatorEx.pas implementation uses Windows, Controls, NtLocalization, NtPattern; class function TNtTranslator.SetNew( const code: String; options: TNtResourceOptions; const originalCode: String; const fileName: String): Boolean; var locale: Integer; begin ResourceOptions := options; Result := TNtBase.LoadNew(code, fileName) <> 0; if Result then begin if code = '' then locale := TNtLocale.ExtensionToLocale(originalCode) else locale := TNtLocale.ExtensionToLocale(code); // Updates thred's locale, format settings and bidi mode to match if not (roNoThreadLocale in options) then SetThreadLocale(locale); if not (roNoLocaleVariables in options) then TNtLocale.UpdateFormatSettings(locale); if not (roNoUpdateBidiMode in options) then begin if TNtLocale.IsLocaleBiDi(TNtBase.LocaleToExtension(locale)) then Application.BiDiMode := bdRightToLeft else Application.BiDiMode := bdLeftToRight; end; // Translate forms TranslateForms; end; if roSaveLocale in options then TNtLocaleRegistry.SetCurrentDefaultLocale; end; procedure TNtTranslator.AfterProcessComponent(component: TComponent); begin if component is TControl then TControl(component).Perform(CM_TEXTCHANGED, 0, 0); end; procedure TNtTranslator.Translate(component: TComponent); var i: Integer; begin for i := 0 to component.ComponentCount - 1 do if component.Components[i] is TFrame then Translate(component.Components[i]); inherited; end; procedure TNtTranslator.TranslateForm(form: TCustomForm); begin if (roFlipChildren in ResourceOptions) and TNtLocale.IsPreviousLocaleBidi then form.FlipChildren(True); Translate(form); if (roFlipChildren in ResourceOptions) and TNtLocale.IsActiveLocaleBidi then form.FlipChildren(True); end; class procedure TNtTranslator.TranslateForms; var translator: TNtTranslator; procedure SetNewLayout(value: TNtLayout); begin translator.TranslateLayout := UiLayout <> value; UiLayout := value; end; var i: Integer; begin translator := TNtTranslator.Create; try if TNtLocale.IsActiveLocaleBidi and (UiLayout = laLeftToRight) then SetNewLayout(laRightToLeft) else if not TNtLocale.IsActiveLocaleBidi and (UiLayout = laRightToLeft) then SetNewLayout(laLeftToRight); if NtTranslateDataModules then for i := 0 to Screen.DataModuleCount - 1 do translator.Translate(Screen.DataModules[i]); for i := 0 to Screen.FormCount - 1 do translator.TranslateForm(Screen.Forms[i]); finally translator.Free; end; end; class procedure TNtTranslator.InitializeApplication(layout: TNtLayout); begin // Sets the bidi mode of the application if TNtLocale.IsActiveLocaleBidi then Application.BiDiMode := bdRightToLeft else Application.BiDiMode := bdLeftToRight; // Sets the initial layout of the application if TNtResource.GetActiveLocale = '' then UiLayout := layout else if TNtLocale.IsActiveLocaleBidi then UiLayout := laRightToLeft else UiLayout := laLeftToRight; end; class procedure TNtTranslator.InitializeForm(form: TCustomForm); begin if TNtLocale.IsActiveLocaleBidi then form.FlipChildren(True); end; end.
Program Library (Input,Output); {**************************************************************************** Author: Scott Janousek Username: ScottJ Student ID: 4361106 Program Assignment 3 Instructor: Cris Pedregal MWF 1:25 Due Date: March 31, 1993 Program Description: This program maintains a list of books for a library. The Software design supports four main commands to access a collection of books within a list. These are : InsertBook (Inserts a Book into the list) DeleteBook (Deletes a Book from the list) ListBooksbyKey (Prints Key in alphabetical order for a Book) Quit (Quits the program and gives a Listing) The method of implementation is a linked list, which supports dynamic memory management. Each individual book is represented by one Node, and this appears in all three of the lists (Title, Author, Subject). One book and it's information is stored exactly once within the program, in alphabetical order implemented by the use of pointers. The Library ADT is a Linked List implementation composed of the TITLE, SUBJECT, AUTHOR Lists. ****************************************************************************} CONST MAX = 40; {* Max Value *} TYPE Category = (Title, Subject, Author); {* Possible Catalogs *} KeyType = string [MAX]; PointerType = ^BookNodeType; {* Pointer to Node *} BookListType = PointerType; BookKeyType = RECORD {* Book Key Type *} Key : KeyType; Next : PointerType; END; BookNodeType = RECORD {* The Library List ADT *} Title : BookKeyType; Subject : BookKeyType; Author : BookKeyType; END; {***************************************************************************} VAR TitleList, {** Title List for Library **} SubjectList, {** Subject List for Library **} AuthorList : BookListType; {** Author List for Library **} Menu : integer; {* Menu Key *} {***************************************************************************} FUNCTION AllCaps (Ch : char) : char; BEGIN {* of AllCaps *} IF Ch IN ['a'..'z'] THEN AllCaps := CHR (ORD(Ch) - (ORD('a') - ORD ('A'))) ELSE AllCaps := Ch; END; {* of AllCaps *} {***************************************************************************} PROCEDURE UpperCase (VAR Strings : KeyType); {* Converts a string to UPPER Case for use in Library *} VAR Index : integer; BEGIN {* of UpperCase *} FOR Index := 1 to MAX DO Strings[Index] := AllCaps (Strings[Index]) END; {* of UpperCase *} {***************************************************************************} PROCEDURE CreatetheLists (VAR TitleList, SubjectList, AuthorList : BookListType); PROCEDURE CreateList (VAR List : BookListType); {* Create an empty list. *} BEGIN {* of Create the List *} New (List); {* Allocate Memory for use *} List := NIL; {* Set List to Nil Pointer *} END; {* of Create the List *} BEGIN {** of Create Lists **} CreateList (TitleList); {* Create the Title List *} CreateList (SubjectList); {* Create the Subject List *} CreateList (AuthorList); {* Create the Author List *} Writeln; Writeln('LIBRARY has been CREATED.'); Writeln; END; {** of Create Lists **} {***************************************************************************} PROCEDURE PrinttheLists (TitleList, SubjectList, AuthorList : BookListType); {* Displays the Lists for the User, printing each Separate List *} {* The user must specify which Key he/she wants to see, then the *} {* the procedure will print out the information according to the *} {* appropriate key by: AUTHOR, TITLE, SUBJECT *} VAR Key : char; Cat : Category; PROCEDURE PrintList (TheList : BookListType; Cat : Category); {* Prints out a particular List specified, dealing with the specified Key *} VAR Location : PointerType; (* traversing pointer *) Key : char; Book : integer; PROCEDURE PrintElement (ElementT, ElementS, ElementA : BookKeyType; Book : integer; Cat : Category); (* Print the fields in each single element. *) BEGIN {* of PrintElement *} CASE Cat OF Title : BEGIN Writeln(' BOOK [=',Book:1,'=]'); Writeln; Writeln (' TITLE : ', ElementT.Key); Writeln ('SUBJECT : ', ElementS.Key); Writeln (' AUTHOR : ', ElementA.Key); Writeln; END; Subject : BEGIN Writeln(' BOOK [=',Book:1,'=]'); Writeln; Writeln ('SUBJECT : ', ElementS.Key); Writeln (' TITLE : ', ElementT.Key); Writeln (' AUTHOR : ', ElementA.Key); Writeln; END; Author : BEGIN Writeln(' BOOK [=',Book:1,'=]'); Writeln; Writeln (' AUTHOR : ', ElementA.Key); Writeln (' TITLE : ', ElementT.Key); Writeln ('SUBJECT : ', ElementS.Key); Writeln; END; END; END; {* of PrintElement *} BEGIN {** of Print the List **} Location := TheList; {* Set the List to Start *} IF Location = NIL THEN BEGIN Writeln('The Library is Currently EMPTY.'); Writeln; END ELSE BEGIN {* of Not Empty List *} Book := 1; (* Make sure that the list isn't empty. *) WHILE Location <> NIL DO {* While the List is not empty *} BEGIN {* of Print all the elements in a List. *} PrintElement (Location^.Title, Location^.Subject, Location^.Author, Book, Cat); CASE Cat OF Title : Location := Location^.Title.Next; Subject : Location := Location^.Subject.Next; Author : Location := Location^.Author.Next; END; {* of Print all elements in a List. *} Book := Book + 1; {* Increment Book Number *} END; {* While *} END; {* of Not Empty List *} END; {** of Print the List **} BEGIN {*** of Print the Lists ***} Writeln('[=LIST=] by what Key (T) Title, (S) Subject, (A) Author)'); Writeln; Write('KEY=> '); Readln (Key); {* Key List by *} Writeln; CASE Key OF 'T', 't' : BEGIN Writeln('[=KEY by TITLE=]'); Writeln; Cat := Title; PrintList (TitleList, Cat); {* Print by Title *} END; 'S', 's' : BEGIN Writeln('[=KEY by SUBJECT=]'); Writeln; Cat := Subject; PrintList (SubjectList, Cat); {* Print by Subject *} END; 'A', 'a' : BEGIN Writeln('[=KEY by AUTHOR=]'); Writeln; Cat := Author; PrintList (AuthorList, Cat); {* Print by Author *} END; END; {* Case *} END; {*** Print the Lists ***) {***************************************************************************} PROCEDURE FindElement (List : BookListType; KeyValue : KeyType; Cat : Category; VAR Location : PointerType; VAR PredLoc : PointerType; VAR Found : Boolean); {* Finds a particular Element within the Library of Lists and returns *} {* the Values of Location, PredLocation, and the Boolean Found *} {* This procedure is used by both the Delete and Insert Procedures *} VAR MoretoSearch : Boolean; BEGIN {* of FindElement *} (* Set to defaults for KeyValue > all keys OR empty list. *) Location := List; {* Set List to beginning *} PredLoc := NIL; {* = NIL if List is empty *} MoreToSearch := TRUE; {* There is more to search *} {* IF not a special case (empty list or KeyValue > all keys *} {* in list, THEN search for KeyValue in specified List *} CASE Cat OF Title : BEGIN {* Title Search *} WHILE MoreToSearch AND (Location <> NIL) DO IF Location^.Title.Key[1] < KeyValue[1] THEN BEGIN PredLoc := Location; {* Previous *} Location := Location^.Title.Next; {* Next *} END ELSE MoreToSearch := FALSE; {* End Search *} IF Location <> NIL THEN IF Location^.Title.Key[1] <> KeyValue[1] THEN Location := NIL ELSE IF Location^.Title.Key = KeyValue THEN Found := TRUE; {* Element Found *} END; {* Title Search *} Subject : BEGIN {* Subject Search *} WHILE MoreToSearch AND (Location <> NIL) DO IF Location^.Subject.Key[1] < KeyValue[1] THEN BEGIN PredLoc := Location; Location := Location^.Subject.Next; END ELSE MoreToSearch := FALSE; IF Location <> NIL THEN IF Location^.Subject.Key[1] <> KeyValue[1] THEN Location := NIL END; {* Subject Search *} Author : BEGIN {* Author Search *} WHILE MoreToSearch AND (Location <> NIL) DO IF Location^.Author.Key[1] < KeyValue[1] THEN BEGIN PredLoc := Location; Location := Location^.Author.Next; END ELSE MoreToSearch := False; IF Location <> NIL THEN IF Location^.Author.Key[1] <> KeyValue[1] THEN Location := NIL END; {* Author Search *} END; {* Case *} END; {* of FindElement *} (*************************************************************) PROCEDURE InsertElement (VAR TitleList, SubjectList, AuthorList : BookListType; NewTitleElement : KeyType; NewSubjectElement : KeyType; NewAuthorElement : KeyType); {* Add NewElement (Book) to the Lists, leaving key value-ordered *} {* structure of List intact. NIL represents the end of the List. *} {* Each Element is inserted into the specified List : AUTHOR, *} {* SUBJECT, TITLE *} VAR NewNode, {* pointer to the new node *} TitlePredLoc, {* pointer to Title predecessor *} AuthorPredLoc, {* same for Author *} SubjectPredLoc, {* same for Subject *} Ignore : PointerType; {* N/A to Insertions *} Found : Boolean; {* is Element in the List *} BEGIN {* of InsertElement *} Found := FALSE; {* Element is not Found yet, set to False *} {* Find Insertion places in TITLE, SUBJECT, AUTHOR LISTS *} FindElement (TitleList, NewTitleElement, Title, Ignore, TitlePredLoc, Found); FindElement (SubjectList, NewSubjectElement, Subject, Ignore, SubjectPredLoc, Found); FindElement (AuthorList, NewAuthorElement, Author, Ignore, AuthorPredLoc, Found); IF NOT Found THEN {* If Element not in TITLE List do insertion *} BEGIN {* If not Found *} NEW (NewNode); {* Allocate a new node, and space *} NewNode^.Title.Key := NewTitleElement; {* Put NewElement into NewNode *} NewNode^.Subject.Key := NewSubjectElement; Newnode^.Author.Key := NewAuthorElement; {* Insert the new node into the specified List. *} IF TitlePredLoc = NIL THEN {* We are inserting into an empty list. *} BEGIN NewNode^.Title.Next := TitleList; {* Title points to Next *} TitleList := NewNode; {* Set TitleList to Newnode *} END ELSE BEGIN NewNode^.Title.Next := TitlePredLoc^.Title.Next; TitlePredLoc^.Title.Next := NewNode; END; IF SubjectPredLoc = NIL THEN BEGIN NewNode^.Subject.Next := SubjectList; SubjectList := NewNode; END ELSE BEGIN NewNode^.Subject.Next := SubjectPredLoc^.Subject.Next; SubjectPredLoc^.Subject.Next := NewNode; END; IF AuthorPredLoc = NIL THEN BEGIN NewNode^.Author.Next := AuthorList; AuthorList := NewNode; END ELSE BEGIN NewNode^.Author.Next := AuthorPredLoc^.Author.Next; AuthorPredLoc^.Author.Next := NewNode; END; END; {* If not Found *} IF Found = TRUE THEN {* Element is in TITLE List *} BEGIN Writeln; Writeln ('Sorry, ',NewTitleElement:1,' already exists within Library.'); Writeln('The Book was not inserted.'); Writeln; END ELSE BEGIN Writeln; Writeln; Writeln('The Book, ',NewTitleElement:1, ' has been added to Library.'); Writeln; END; END; {** of InsertElement **} {***************************************************************************} PROCEDURE InsertBook (VAR TitleList, SubjectList, AuthorList : BookListType); {* The Procedure Inserts a Book into the Lists : TITLE, SUBJECT, AUTHOR *} {* Calling upon the InsertElement procedure to handle the cases within *} {* the Lists. Information is then stored in the Library. *} VAR T, A, S: BookKeyType; BEGIN {* OF Inserting a Book *} Writeln('Enter Book Information:'); Writeln; Write(' TITLE: '); Readln(T.Key); UpperCase (T.Key); Write('SUBJECT: '); Readln(S.Key); UpperCase (S.Key); Write(' AUTHOR: '); Readln(A.Key); UpperCase (A.Key); InsertElement (TitleList, SubjectList, AuthorList, T.key, S.key, A.key); END; {* OF Inserting a Book *} {***************************************************************************} PROCEDURE DeleteBook (VAR TitleList, SubjectList, AuthorList : BookListType); {* Finds and Deletes a TITLE from the 3 Lists. *} VAR Delete : KeyType; Location, Ignore : PointerType; Found : Boolean; PROCEDURE DeleteElement (VAR TitleList, SubjectList, AuthorList : BookListType; DeleteVal : KeyType); {* Finds and Deletes a Node from the TITLE, AUTHOR, SUBJECT Lists *} {* If no Element is found corrosponding to the Delete then no Deletion *} {* is made. *} VAR TitleLocation, TitlePredLoc, {* List Locations to Pointer Info *} AuthorLocation, AuthorPredLoc, SubjectLocation, SubjectPredLoc : PointerType; Found : Boolean; Cat : Category; BEGIN {* of DeleteElement *} {* Find location of DeleteVal in the Lists. *} TitleLocation := TitleList; FindElement (TitleList, DeleteVal, Cat, TitleLocation, TitlePredLoc, Found); FindElement (SubjectList, TitleLocation^.Subject.Key, Cat, SubjectLocation, SubjectPredLoc, Found); FindElement (AuthorList, TitleLocation^.Author.Key, Cat, AuthorLocation, AuthorPredLoc, Found); {* Check if this is the only node in the list. *} IF (TitlePredLoc = NIL) THEN TitleList := TitleLocation^.Title.Next {* Set to Next in List *} ELSE {* not the only node in the list *} TitlePredLoc^.Title.Next := TitleLocation^.Title.Next; IF (SubjectPredLoc = NIL) THEN SubjectList := SubjectLocation^.Subject.Next ELSE {* not the only node in the list *} SubjectPredLoc^.Subject.Next := SubjectLocation^.Subject.Next; IF (AuthorPredLoc = NIL) THEN AuthorList := AuthorLocation^.Author.Next ELSE {* not the only node in the list *} AuthorPredLoc^.Author.Next := AuthorLocation^.Author.Next; Dispose (TitleLocation); {* Free the node space *} END; {* of Delete Element *} BEGIN {** of Delete Book **} Writeln('[=DELETE=] Enter the Title of the Book'); Writeln; Write('=> '); Readln(Delete); UpperCase (Delete); {* Find the Element in the TITLE List *} FindElement (TitleList, Delete, Title, Location, Ignore, Found); IF (Location = NIL) OR (Found = FALSE) THEN BEGIN {* Element not Found in List *} Writeln; Writeln ('Sorry ',Delete:1,' was not Found in Library.') END {* Element not Found in List *} ELSE BEGIN {* Element has been deleted *} DeleteElement (TitleList, SubjectList, AuthorList, Delete); Writeln; Writeln(Delete:1,' has been deleted from Library.'); END; {* Element has been deleted *} END; {** of Delete Book **} {***************************************************************************} FUNCTION UserMenu : Integer; {* This Function provides the user to implement the commands from *} {* an abstract view. The implementation and use of the Three Lists *} {* is kept hidden from him/her. Selections are made through the *} {* keyboard and range from [1] List, [2] Delete, [3] List by Key *) {* and [5] Quit the program. *} VAR BookSelect : char; NumBookMenu : integer; BEGIN {** of UserMenu **} REPEAT Writeln; Writeln('[=MENU=] (1) Insert, (2) Delete, (3) List by Key, (4) Quit'); Writeln; Write('=> '); Readln(BookSelect); NumBookMenu := ORD (BookSelect) - ORD ('1') + 1; Writeln; UNTIL (NumBookMenu >= 1) AND (NumBookMenu <= 4); UserMenu := NumBookMenu; END; {** of UserMenu **} {***************************************************************************} BEGIN {**** Main Program ****} Writeln('[=WELCOME TO THE LIBRARY=]'); Writeln; Writeln('Program written by: Scott Janousek.'); Writeln; CreatetheLists (TitleList, SubjectList, AuthorList); REPEAT {** User Access to Library **} Menu := UserMenu; CASE Menu OF 1 : InsertBook (TitleList, SubjectList, AuthorList); 2 : DeleteBook (TitleList, SubjectList, AuthorList); 3 : PrinttheLists (TitleList, SubjectList, AuthorList); END; UNTIL Menu = 4; Writeln ('Quit program.'); Writeln; Writeln ('[=THE LIBRARY EXITED=]'); Writeln; PrinttheLists (TitleList, SubjectList, AuthorList); Writeln; Writeln ('Good Bye'); readln; END. {**** Main Program ****}
unit uNewGroup; interface uses SysUtils, Classes, uTSBaseClass; type TGroup = class(TSBaseClass) private FMerchanUnitID: Integer; FCompanyID: Integer; FDefaultMarkUp: Double; FID: Integer; FKode: string; FKodeRek: string; FMerchanID: Integer; FNama: string; FUnitID: Integer; function FLoadFromDB( aSQL : String ): Boolean; public constructor Create(aOwner : TComponent); override; destructor Destroy; override; procedure ClearProperties; function ExecuteCustomSQLTask: Boolean; function ExecuteCustomSQLTaskPrior: Boolean; function CustomTableName: string; function GenerateInterbaseMetaData: Tstrings; function ExecuteGenerateSQL: Boolean; function GetFieldNameFor_CompanyID: string; dynamic; function GetFieldNameFor_DefaultMarkUp: string; dynamic; function GetFieldNameFor_ID: string; dynamic; function GetFieldNameFor_Kode: string; dynamic; function GetFieldNameFor_KodeRek: string; dynamic; function GetFieldNameFor_MerchanID: string; dynamic; function GetFieldNameFor_MerchanUnitID: string; function GetFieldNameFor_Nama: string; dynamic; function GetFieldNameFor_UnitID: string; dynamic; function GetHeaderFlag: Integer; function LoadByCode(aKode : String; aUnitID, aMerId, aMerUnitID: Integer): Boolean; function LoadByID(aID : Integer; aUnitID : Integer): Boolean; function RemoveFromDB: Boolean; procedure UpdateData(aCompanyID : Integer; aDefaultMarkUp : Double; aID : Integer; aKode : string; aKodeRek : string; aMerchanID : Integer; aMerchanUnitID : integer; aNama : string; aUnitID : Integer); property MerchanUnitID: Integer read FMerchanUnitID write FMerchanUnitID; property CompanyID: Integer read FCompanyID write FCompanyID; property DefaultMarkUp: Double read FDefaultMarkUp write FDefaultMarkUp; property ID: Integer read FID write FID; property Kode: string read FKode write FKode; property KodeRek: string read FKodeRek write FKodeRek; property MerchanID: Integer read FMerchanID write FMerchanID; property Nama: string read FNama write FNama; property UnitID: Integer read FUnitID write FUnitID; end; implementation uses StrUtils, udmMain, FireDAC.Stan.Error; { ************************************ TGroup ************************************ } constructor TGroup.Create(aOwner : TComponent); begin inherited create(aOwner); ClearProperties; end; destructor TGroup.Destroy; begin inherited Destroy; end; procedure TGroup.ClearProperties; begin ID := 0; Kode := ''; Nama := ''; UnitID := 0; //FreeAndNil(); CompanyID := 0; DefaultMarkUp := 0; KodeRek := ''; MerchanID := 0; MerchanUnitID := 0; end; function TGroup.ExecuteCustomSQLTask: Boolean; begin result := True; end; function TGroup.ExecuteCustomSQLTaskPrior: Boolean; begin result := True; end; function TGroup.CustomTableName: string; begin result := 'REF$MERCHANDISE_GRUP'; end; function TGroup.FLoadFromDB( aSQL : String ): Boolean; begin result := false; State := csNone; ClearProperties; with cOpenQuery(aSQL) do Begin if not EOF then begin FCompanyID := FieldByName(GetFieldNameFor_CompanyID).asInteger; FDefaultMarkUp := FieldByName(GetFieldNameFor_DefaultMarkUp).asFloat; //ShowMessage(FieldByName(GetFieldNameFor_ID).AsString); FID := FieldByName(GetFieldNameFor_ID).asInteger; FKode := FieldByName(GetFieldNameFor_Kode).asString; FKodeRek := FieldByName(GetFieldNameFor_KodeRek).asString; FMerchanID := FieldByName(GetFieldNameFor_MerchanID).asInteger; FMerchanUnitID := FieldByName(GetFieldNameFor_MerchanUnitID).asInteger; FNama := FieldByName(GetFieldNameFor_Nama).asString; FUnitID := FieldByName(GetFieldNameFor_UnitID).asInteger; Self.State := csLoaded; Result := True; end; Free; End; end; function TGroup.GenerateInterbaseMetaData: Tstrings; begin result := TstringList.create; result.Append( '' ); result.Append( 'Create Table TGroup ( ' ); result.Append( 'TRMSBaseClass_ID Integer not null, ' ); result.Append( 'CompanyID Integer Not Null , ' ); result.Append( 'DefaultMarkUp double precision Not Null , ' ); result.Append( 'ID Integer Not Null Unique, ' ); result.Append( 'Kode Varchar(30) Not Null , ' ); result.Append( 'KodeRek Varchar(30) Not Null , ' ); result.Append( 'MerchanID Integer Not Null , ' ); result.Append( 'MerchanUnitID Integer Not Null , ' ); result.Append( 'Nama Varchar(30) Not Null , ' ); result.Append( 'UnitID Integer Not Null , ' ); result.Append( 'Stamp TimeStamp ' ); result.Append( ' ); ' ); end; function TGroup.ExecuteGenerateSQL: Boolean; var S: string; //i: Integer; //SS: Tstrings; begin //result := TstringList.create; Result := False; if State = csNone then Begin raise Exception.create('Tidak bisa generate dalam Mode csNone') end; { SS := CustomSQLTaskPrior; if SS <> nil then Begin result.AddStrings(SS); end; //SS := Nil; } if not ExecuteCustomSQLTaskPrior then begin cRollbackTrans; Exit; end else begin If FID <= 0 then begin FID := cGetNextID(GetFieldNameFor_ID, CustomTableName); S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_CompanyID + ', ' + GetFieldNameFor_DefaultMarkUp + ', ' + GetFieldNameFor_ID + ', ' + GetFieldNameFor_Kode + ', ' + GetFieldNameFor_KodeRek + ', ' + GetFieldNameFor_MerchanID + ', ' + GetFieldNameFor_MerchanUnitID + ', ' + GetFieldNameFor_Nama + ', ' + GetFieldNameFor_UnitID + ') values (' + IntToStr( FCompanyID) + ', ' + QuotedStr(FormatFloat(siFrtDec2, FDefaultMarkUp)) + ', ' + IntToStr( FID) + ', ' + QuotedStr(FKode ) + ',' + IfThen(FKodeRek='', 'null,', QuotedStr(FKodeRek ) + ',') + IntToStr( FMerchanID) + ', ' + IntToStr( FMerchanUnitID) + ', ' + QuotedStr(FNama ) + ',' + IntToStr( FUnitID) + ');' end else begin //generate Update SQL S := 'Update ' + CustomTableName + ' set ' + GetFieldNameFor_CompanyID + ' = ' + IntToStr( FCompanyID) + ', ' + GetFieldNameFor_DefaultMarkUp + ' = ' + QuotedStr(FormatFloat(siFrtDec2, FDefaultMarkUp)) + ', ' + GetFieldNameFor_Kode + ' = ' + QuotedStr( FKode ) + ', ' + GetFieldNameFor_KodeRek + ' = ' + IfThen(FKodeRek='', 'null', QuotedStr(FKodeRek)) + ', ' + GetFieldNameFor_MerchanID + ' = ' + IntToStr( FMerchanID) + ', ' + GetFieldNameFor_MerchanUnitID + ' = ' + IntToStr( FMerchanUnitID) + ', ' + GetFieldNameFor_Nama + ' = ' + QuotedStr( FNama ) + ' where ' + GetFieldNameFor_UnitID + ' = ' + IntToStr( FUnitID) + ' and ' + GetFieldNameFor_ID + ' = ' + IntToStr(FID) + ';'; end; end; {result.append( S ); //generating Collections SQL SS := CustomSQLTask; if SS <> nil then Begin result.AddStrings(SS); end;} if not cExecSQL(S, dbtPOS, False) then begin cRollbackTrans; Exit; end else Result := ExecuteCustomSQLTask; end; function TGroup.GetFieldNameFor_CompanyID: string; begin Result := 'MERCHANGRUP_COMP_ID';// <<-- Rubah string ini untuk mapping end; function TGroup.GetFieldNameFor_DefaultMarkUp: string; begin Result := 'MERCHANGRUP_DEF_MARK_UP';// <<-- Rubah string ini untuk mapping end; function TGroup.GetFieldNameFor_ID: string; begin Result := 'MERCHANGRUP_ID';// <<-- Rubah string ini untuk mapping end; function TGroup.GetFieldNameFor_Kode: string; begin Result := 'MERCHANGRUP_CODE';// <<-- Rubah string ini untuk mapping end; function TGroup.GetFieldNameFor_KodeRek: string; begin Result := 'MERCHANGRUP_REK_CODE';// <<-- Rubah string ini untuk mapping end; function TGroup.GetFieldNameFor_MerchanID: string; begin Result := 'MERCHANGRUP_MERCHAN_ID';// <<-- Rubah string ini untuk mapping end; function TGroup.GetFieldNameFor_MerchanUnitID: string; begin // TODO -cMM: TGroup.GetFieldNameFor_MerchanUnitID default body inserted Result := 'MERCHANGRUP_MERCHAN_UNT_ID' ; end; function TGroup.GetFieldNameFor_Nama: string; begin Result := 'MERCHANGRUP_NAME';// <<-- Rubah string ini untuk mapping end; function TGroup.GetFieldNameFor_UnitID: string; begin Result := 'MERCHANGRUP_UNT_ID';// <<-- Rubah string ini untuk mapping end; function TGroup.GetHeaderFlag: Integer; begin result := 120; end; function TGroup.LoadByCode(aKode : String; aUnitID, aMerId, aMerUnitID: Integer): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode) + ' and ' + GetFieldNameFor_UnitID + ' = ' + IntToStr(aUnitID) + ' and ' + GetFieldNameFor_MerchanID + ' = ' + IntToStr(aMerId) + ' and ' + GetFieldNameFor_MerchanUnitID + ' = ' + IntToStr(aMerUnitID) ); end; function TGroup.LoadByID(aID : Integer; aUnitID : Integer): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_ID + ' = ' + IntToStr(aID) + ' and ' + GetFieldNameFor_UnitID + ' = ' + IntToStr(aUnitID)); end; function TGroup.RemoveFromDB: Boolean; var sErr: string; sSQL: String; begin Result := False; sSQL := 'DELETE FROM REF$MERCHANDISE_GRUP ' + ' WHERE ' + GetFieldNameFor_ID + ' = ' + IntToStr(FID) + ' AND ' + GetFieldNameFor_UnitID + ' = ' + IntToStr(FUnitID) + ';'; try if cExecSQL(sSQL, dbtPOS, False) then result := True;//SimpanBlob(sSQL, GetHeaderFlag); except on E: EFDDBEngineException do begin sErr := e.Message; if sErr <> '' then raise Exception.Create(sErr) else raise Exception.Create('Error Code: '+IntToStr(e.ErrorCode)+#13#10+e.SQL); end; end; end; procedure TGroup.UpdateData(aCompanyID : Integer; aDefaultMarkUp : Double; aID : Integer; aKode : string; aKodeRek : string; aMerchanID : Integer; aMerchanUnitID : integer; aNama : string; aUnitID : Integer); begin ClearProperties; FCompanyID := aCompanyID; FDefaultMarkUp := aDefaultMarkUp; FID := aID; FKode := trim(aKode); FKodeRek := trim(aKodeRek); FMerchanID := aMerchanID; FMerchanUnitID := aMerchanUnitID; FNama := trim(aNama); FUnitID := aUnitID; State := csCreated; end; end.
unit typeDefSucc; {Модуль реализации классов.} interface uses SysUtils, Classes, typeDefBase; // Класс Закладка type TAppBookMarks = class(TAppItem) private _url: string; public published property url: string read _url write _url; end; // Класс Журнал type TAppJournal = class(TAppItem) private _date: Integer; public published property date: Integer read _date write _date; end; // Класс считывает и формирует список из файла журнала type TAppFileArrayJrnl = class(TAppFileBase) private procedure CreateList(pArr: TBytes; var pList: TStringList); public constructor Create(str: string); overload; constructor Create(); overload; destructor Destroy; override; procedure CreateFileArray(); override; // - в базовом классе procedure CreateListFromArray(); override; property fileStrList: TStringList read _fileStrList; property fileName: string read _fileName write _fileName; end; type TBookmark = record id: string; name: string; url: string; end; type TBMArray = array of TAppBookMarks; // TBookmark // Класс считывает и формирует список из файла закладок type TAppFileArrayBM = class(TAppFileArrayJrnl) private _bookMarksArr: TBMArray; procedure CreateList(pArr: TBytes; var pList: TStringList); public constructor Create(str: string); overload; constructor Create(); overload; destructor Destroy; override; procedure CreateFileArray(); override; // - в базовом классе procedure CreateListFromArray(); override; // - в базовом классе published property fileStrList: TStringList read _fileStrList; property fileName: string read _fileName write _fileName; property bookMarksArr: TBMArray read _bookMarksArr write _bookMarksArr; end; type TMyFinalArray = array of TAppJournal; implementation uses operations, mainUnit, header; //************** Реализация класса TAppFileArrayJrnl *********** //************************************************************** constructor TAppFileArrayJrnl.Create(str: string); begin _fileName:= str; end; constructor TAppFileArrayJrnl.Create(); begin inherited; _fileName:= ''; end; // Обязательно очищаем объект-поле, иначе получим утечку памяти. destructor TAppFileArrayJrnl.Destroy; begin FreeAndNil(_fileStrList); inherited; end; { Процедура формирует StringList из массива байтов файла. Байты со значением большим 32 считаются значащими символами. Байты со значением 00 и 01 считаются символами окончания строки и заменяются на CR LF. Байты со значением 32 - пробел. } procedure TAppFileArrayJrnl.CreateListFromArray(); var i, j: Integer; tempArr: TBytes; index: Integer; begin index := -1; j := 0; i := 0; while i < Length(_fileArray) do begin if (_fileArray[i] = 0) then begin if index = -1 then begin SetLength(tempArr, j + 2); tempArr[j] := 13; tempArr[j + 1] := 10; Inc(j, 2); index := 1; Inc(i); end else Inc(i); end else if (_fileArray[i] = 32) then begin SetLength(tempArr, j + 1); tempArr[j] := Ord(' '); Inc(j); index := -1; Inc(i); end else if (_fileArray[i] > 32) then begin while (_fileArray[i] <> 0) do begin SetLength(tempArr, j + 1); tempArr[j] := _fileArray[i]; Inc(j); index := -1; Inc(i); end; end else Inc(i); end; _fileStrList := TStringList.Create; CreateList(tempArr, _fileStrList); end; procedure TAppFileArrayJrnl.CreateList(pArr: TBytes; var pList: TStringList); var qqq: TStringStream; qqqNonModified: TStringList; i, j, x: Integer; tempPList: TStringList; str: Ansistring; aa: PAnsiChar; tempInt: Ansistring; urlPos: Integer; begin qqq := TStringStream.Create; qqqNonModified := TStringList.Create; try qqq.Write(pArr[0], Length(pArr)); qqqNonModified.Text := qqq.DataString; pList.Text := Utf8ToAnsi(qqq.DataString); // Utf8ToAnsi WideCharToMultiByte finally qqq.Free; end; for i := 0 to pList.Count - 1 do pList.Strings[i] := TrimLeft(pList.Strings[i]); tempPList := TStringList.Create; i := 0; while i < pList.Count - 2 do begin urlPos:= 0; if IsStringURL(pList.Strings[i], urlPos) then begin tempPList.Add(Copy(pList.Strings[i], urlPos, Length(pList.Strings[i]))); tempPList.Add(Copy(pList.Strings[i+1], 1, Length(pList.Strings[i+1])-4)); tempInt := Ansistring(Copy(qqqNonModified.Strings[i+1], (Length(qqqNonModified.Strings[i+1]) - 3), Length(qqqNonModified.Strings[i+1]))); aa := @tempInt[1]; str := ''; for j := 0 to 3 do begin x := Ord(aa^); if x < 10 then begin x := Ord(aa^); str := str + '0' + IntToHex(x, 1); end else str := str + IntToHex(Ord(aa^), 1); Inc(aa, 1); end; str:= '$' + str; tempPList.Add(DateTimeToStr(UnixToDateTime(StrToInt(str)))); end; Inc(i); end; pList.Text := tempPList.Text; FreeAndNil(tempPList); FreeAndNil(qqqNonModified); end; procedure TAppFileArrayJrnl.CreateFileArray(); begin inherited; end; //************** Реализация класса TAppFileArrayBM ************* //************************************************************** constructor TAppFileArrayBM.Create(str: string); begin inherited; end; constructor TAppFileArrayBM.Create(); begin inherited; end; // Обязательно очищаем объект-поле, иначе получим утечку памяти. destructor TAppFileArrayBM.Destroy; var i: Integer; begin FreeAndNil(_fileStrList); for I := 0 to Length(_bookMarksArr) - 1 do FreeAndNil(_bookMarksArr[i]); inherited; end; procedure TAppFileArrayBM.CreateListFromArray(); var i, j: Integer; tempArr: TBytes; index: Integer; begin index := -1; j := 0; for i := 0 to Length(_fileArray) do begin if _fileArray[i] > 32 then begin SetLength(tempArr, j + 1); tempArr[j] := _fileArray[i]; Inc(j); index := -1; end else if (_fileArray[i] = 0) or (_fileArray[i] = 01) then begin if index = -1 then begin SetLength(tempArr, j + 2); tempArr[j] := 13; tempArr[j + 1] := 10; Inc(j, 2); index := 1; end; end else if (_fileArray[i] = 32) then begin SetLength(tempArr, j + 1); tempArr[j] := Ord(' '); Inc(j); end; end; _fileStrList := TStringList.Create; CreateList(tempArr, _fileStrList); end; procedure TAppFileArrayBM.CreateList(pArr: TBytes; var pList: TStringList); var qqq: TStringStream; i: Integer; tempPList: TStringList; begin qqq := TStringStream.Create; try qqq.Write(pArr[0], Length(pArr)); pList.Text := Utf8ToAnsi(qqq.DataString); // Utf8ToAnsi WideCharToMultiByte finally qqq.Free; end; for i := 0 to pList.Count - 1 do pList.Strings[i] := TrimLeft(pList.Strings[i]); tempPList := TStringList.Create; i := 0; while i < pList.Count - 2 do begin if IsFolder(pList, i) then begin tempPList.Add(pList.Strings[i]); tempPList.Add(pList.Strings[i + 1]); Inc(i, 2); end else if IsBookmark(pList, i) then begin tempPList.Add(pList.Strings[i]); tempPList.Add(pList.Strings[i + 1]); tempPList.Add(pList.Strings[i + 2]); Inc(i, 3); end else if (IsStringID(pList.Strings[i])) then begin tempPList.Add(pList.Strings[i]); Inc(i, 1); Continue; end else Inc(i); end; pList.Text := tempPList.Text; FreeAndNil(tempPList); end; procedure TAppFileArrayBM.CreateFileArray(); begin inherited; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GLCadencer, GLScene, GLObjects, GLWin32Viewer, GLAsyncTimer, GLVectorFileObjects, GLTexture, GLGraph, GLFile3DS, GLVectorGeometry, GLVectorTypes, GLGraphics, GLMaterial, GLCoordinates, GLCrossPlatform, GLBaseClasses, GLVectorLists, Uplasma; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; GLCadencer1: TGLCadencer; AsyncTimer1: TGLAsyncTimer; GLDummyCube1: TGLDummyCube; GLMaterialLibrary1: TGLMaterialLibrary; GLActor1: TGLActor; Lights: TGLDummyCube; GLLightSource1: TGLLightSource; procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure AsyncTimer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private is_mouse_pressed: boolean; procedure UpdatePlasmaImage(B: TBitmap); procedure init_plasma_world; procedure step_plasma_world; public B: TBitmap; f: TForceField; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.AsyncTimer1Timer(Sender: TObject); begin Caption := Inttostr(Round(GLSceneViewer1.FramesPerSecond)) + ' FPS'; GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.FormCreate(Sender: TObject); begin GLActor1.LoadFromFile('plane.3DS'); B := TBitmap.Create; B.LoadFromFile('bitmap.bmp'); B.PixelFormat := pf32bit; f := TForceField.Create; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); var t: Integer; VL: TAffineVectorList; dV: TVector3f; begin step_plasma_world; UpdatePlasmaImage(B); GLMaterialLibrary1.Materials[0].Material.Texture.Image.Assign(B); GLSceneViewer1.Invalidate; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin is_mouse_pressed := true; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if is_mouse_pressed then begin if (X < N * 4) and (Y < N * 4) then begin f.dens_prev[X div 4, Y div 4] := 20; end; end; end; procedure TForm1.GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin is_mouse_pressed := false; end; procedure TForm1.UpdatePlasmaImage(B: TBitmap); var X, Y, C: Integer; Line: PGLPixel32Array; v: Integer; begin // Update the texture. for Y := 0 to N do begin Line := B.ScanLine[Y]; for X := 0 to N do begin // Here the color of the bitmap might be set better than this: Line[X].r := abs(Round(f.u[X, Y] * 100)); Line[X].g := abs(Round(f.dens[X, Y] * 100)); Line[X].B := abs(Round(f.v[X, Y] * 100)); end; end; end; procedure TForm1.step_plasma_world; var X, Y: Integer; l: Integer; diff, visc, dt: real; begin diff := 0.0001; visc := 0.0001; dt := 0.1; // eventually update dens_prev, u_prev, v_prev here: init_plasma_world; f.vel_step(N, f.u, f.v, f.u_prev, f.v_prev, visc, dt); f.dens_step(N, f.dens, f.dens_prev, f.u, f.v, diff, dt, is_mouse_pressed); end; procedure TForm1.init_plasma_world; var X, Y: Integer; tk: real; begin tk := 0.2 * (GettickCount / 360 * 3.14159); // ADD A FORCE EMITTER HERE for X := 10 to 20 do begin for Y := 10 to 20 do begin f.u_prev[X, Y] := sin(tk) * 8; // random*150;//1 f.v_prev[X, Y] := cos(tk) * 8; // random*150;//1 end; end; // ADD A FORCE EMITTER HERE for X := 80 to 90 do begin for Y := 80 to 90 do begin f.u_prev[X, Y] := -random * 5; // 1 f.v_prev[X, Y] := -random * 5; // 1 end; end; // ADD A FORCE EMITTER HERE for X := 30 to 40 do begin for Y := 40 to 50 do begin f.u_prev[X, Y] := sin(tk * 1.23) * 8; // random*150;//1 f.v_prev[X, Y] := cos(tk * 2.32) * 8; // random*150;//1 end; end; end; end.
unit GreaterEqOpTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, uIntXLibTypes, uIntX; type { TTestGreaterEqOp } TTestGreaterEqOp = class(TTestCase) published procedure Simple(); procedure SimpleFail(); procedure Big(); procedure BigFail(); procedure EqualValues(); end; implementation procedure TTestGreaterEqOp.Simple(); var int1, int2: TIntX; begin int1 := TIntX.Create(7); int2 := TIntX.Create(8); AssertTrue(int2 >= int1); end; procedure TTestGreaterEqOp.SimpleFail(); var int1: TIntX; begin int1 := TIntX.Create(8); AssertFalse(7 >= int1); end; procedure TTestGreaterEqOp.Big(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 2; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, True); AssertTrue(int1 >= int2); end; procedure TTestGreaterEqOp.BigFail(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 2; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, True); AssertFalse(int2 >= int1); end; procedure TTestGreaterEqOp.EqualValues(); var temp1, temp2: TIntXLibUInt32Array; int1, int2: TIntX; begin SetLength(temp1, 3); temp1[0] := 1; temp1[1] := 2; temp1[2] := 3; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 2; temp2[2] := 3; int1 := TIntX.Create(temp1, True); int2 := TIntX.Create(temp2, True); AssertTrue(int2 >= int1); end; initialization RegisterTest(TTestGreaterEqOp); end.
unit uReg_Add; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxClasses, cxStyles, cxTL, dxBarExtItems, dxBar, ImgList, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxLookAndFeelPainters, StdCtrls, cxButtons, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxControls, cxGridCustomView, cxGrid, RxMemDS, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, cxRadioGroup, cxGroupBox, cnConsts; type TfrReg_Add = class(TForm) LargeImages: TImageList; DisabledLargeImages: TImageList; PopupImageList: TImageList; BarManager: TdxBarManager; AddButton: TdxBarLargeButton; EditButton: TdxBarLargeButton; DeleteButton: TdxBarLargeButton; RefreshButton: TdxBarLargeButton; ExitButton: TdxBarLargeButton; PrintButton: TdxBarLargeButton; PayButton: TdxBarLargeButton; LgotaButton: TdxBarLargeButton; EntryRestButton: TdxBarLargeButton; HistoryButton: TdxBarLargeButton; FIO_BarContainer: TdxBarControlContainerItem; FilterExecute_Button: TdxBarButton; Dog_Filter_Edit: TdxBarEdit; GlobalFilterButton: TdxBarLargeButton; DsetRecordCount: TdxBarButton; CreditButton: TdxBarLargeButton; Faculty_Footer_Label: TdxBarStatic; Spec_Footer_Label: TdxBarStatic; Gragdanstvo_Footer_Label: TdxBarStatic; FormStudy_Footer_Label: TdxBarStatic; CategoryStudy_Footer_Label: TdxBarStatic; Kurs_Footer_Label: TdxBarStatic; Group_Footer_Label: TdxBarStatic; UpLoad_Button: TdxBarLargeButton; BreakDown_Button: TdxBarLargeButton; PayerData_Button: TdxBarButton; RastorgPri4ina_Button: TdxBarButton; dxBarStatic1: TdxBarStatic; Dodatki_Button: TdxBarSubItem; Log: TdxBarButton; RecoveryBtn: TdxBarButton; OrdersBtn: TdxBarLargeButton; SelectBtn: TdxBarLargeButton; Erased_Btn: TdxBarButton; NoteStatic: TdxBarStatic; ExportDataBtn: TdxBarButton; btnTwain: TdxBarLargeButton; dxBarStatic2: TdxBarStatic; dxBarButton1: TdxBarButton; dxBarButton2: TdxBarButton; dxBarButton3: TdxBarButton; Dog_status_label: TdxBarStatic; dxBarToolbarsListItem1: TdxBarToolbarsListItem; dxBarLargeButton1: TdxBarLargeButton; dxBarLargeButton2: TdxBarLargeButton; Styles: TcxStyleRepository; BackGround: TcxStyle; FocusedRecord: TcxStyle; Header: TcxStyle; DesabledRecord: TcxStyle; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; cxStyle21: TcxStyle; cxStyle22: TcxStyle; cxStyle23: TcxStyle; cxStyle24: TcxStyle; cxStyle25: TcxStyle; cxStyle26: TcxStyle; cxStyle27: TcxStyle; cxStyle28: TcxStyle; cxStyle29: TcxStyle; cxStyle30: TcxStyle; cxStyle31: TcxStyle; cxStyle32: TcxStyle; cxStyle33: TcxStyle; cxStyle34: TcxStyle; cxStyle35: TcxStyle; cxStyle36: TcxStyle; cxStyle37: TcxStyle; cxStyle38: TcxStyle; cxStyle39: TcxStyle; cxStyle40: TcxStyle; cxStyle41: TcxStyle; cxStyle42: TcxStyle; cxStyle43: TcxStyle; cxStyle44: TcxStyle; cxStyle45: TcxStyle; cxStyle46: TcxStyle; cxStyle47: TcxStyle; cxStyle48: TcxStyle; cxStyle49: TcxStyle; cxStyle50: TcxStyle; cxStyle51: TcxStyle; cxStyle52: TcxStyle; cxStyle53: TcxStyle; cxStyle54: TcxStyle; cxStyle55: TcxStyle; cxStyle56: TcxStyle; cxStyle57: TcxStyle; testColorStyle: TcxStyle; TreeListStyleSheetDevExpress: TcxTreeListStyleSheet; MemoryDataNot: TRxMemoryData; DataSource_Not: TDataSource; cxGrid1: TcxGrid; cxGrid1DBTableView1: TcxGridDBTableView; FIO_NOT: TcxGridDBColumn; cxGridNotInReg: TcxGridLevel; cxButtonOneToList: TcxButton; cxButtonAllToList: TcxButton; cxButtonOneInList: TcxButton; cxButtonAllInList: TcxButton; cxGrid2: TcxGrid; cxGrid2DBTableView1: TcxGridDBTableView; FIO_IN: TcxGridDBColumn; cxGridInReg: TcxGridLevel; DataSource_In: TDataSource; MemoryDataIn: TRxMemoryData; NUM_NOT: TcxGridDBColumn; NUM_IN: TcxGridDBColumn; DataSet_update: TpFIBDataSet; MemoryDataNotMrFIO: TStringField; MemoryDataNotMrNUM: TStringField; MemoryDataNotMrID_DOG: TIntegerField; MemoryDataInMrFIO_in: TStringField; MemoryDataInMrNUM_in: TStringField; MemoryDataInMrID_dog_in: TVariantField; cxButtonClose: TcxButton; cxButtonSave: TcxButton; StoredProc: TpFIBStoredProc; Tran_write: TpFIBTransaction; dxBarStatic3: TdxBarStatic; dxBarControlContainerItem1: TdxBarControlContainerItem; Filtration_GroupBox: TcxGroupBox; FiltrByFIO_RadioButton: TcxRadioButton; FiltrByNum_RadioButton: TcxRadioButton; Label1: TLabel; procedure cxButtonOneToListClick(Sender: TObject); procedure cxButtonAllToListClick(Sender: TObject); procedure cxButtonOneInListClick(Sender: TObject); procedure cxButtonAllInListClick(Sender: TObject); procedure cxButtonCloseClick(Sender: TObject); procedure cxButtonSaveClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FilterExecute_ButtonClick(Sender: TObject); private { Private declarations } public id_user:int64; id_reestr:int64; PLanguageIndex: Byte; { Public declarations } end; var frReg_Add: TfrReg_Add; implementation uses uReg, uAdd; {$R *.dfm} procedure TfrReg_Add.cxButtonOneToListClick(Sender: TObject); begin if MemoryDataNot.RecordCount>0 then begin MemoryDataIn.Open; MemoryDataIn.Insert; MemoryDataIn.FieldByName('MrFIO_in').AsString:=MemoryDataNot.FieldByName('MrFIO').AsString; MemoryDataIn.FieldByName('MrNUM_in').AsString:=MemoryDataNot.FieldByName('MrNUM').AsString; MemoryDataIn.FieldByName('MrID_DOG_in').AsVariant:=MemoryDataNot.FieldByName('MrID_DOG').AsVariant; MemoryDataIn.Post; MemoryDataNot.Delete; end; end; procedure TfrReg_Add.cxButtonAllToListClick(Sender: TObject); var i:Integer; begin refresh; cxGrid1DBTableView1.BeginUpdate; // cxGridNotInReg.BeginUpdate; MemoryDataNot.First; for i:=0 to MemoryDataNot.RecordCount-1 do begin cxButtonOneToListClick(self); MemoryDataNot.Next; end; // cxGridNotInReg.EndUpdate; cxGrid1DBTableView1.EndUpdate; end; procedure TfrReg_Add.cxButtonOneInListClick(Sender: TObject); begin if MemoryDataIn.RecordCount>0 then begin MemoryDataNot.Open; MemoryDataNot.Insert; MemoryDataNot.FieldByName('MrFIO').AsString:=MemoryDataIn.FieldByName('MrFIO_in').AsString; MemoryDataNot.FieldByName('MrNUM').AsString:=MemoryDataIn.FieldByName('MrNUM_in').AsString; MemoryDataNot.FieldByName('MrID_DOG').AsVariant:=MemoryDataIn.FieldByName('MrID_DOG_in').AsVariant; MemoryDataNot.Post; MemoryDataIn.Delete; end; end; procedure TfrReg_Add.cxButtonAllInListClick(Sender: TObject); var i:Integer; begin refresh; MemoryDataIn.First; for i:=0 to MemoryDataIn.RecordCount-1 do begin cxButtonOneInListClick(self); MemoryDataIn.Next; end; end; procedure TfrReg_Add.cxButtonCloseClick(Sender: TObject); begin if MessageBox(Handle,PChar('Вы уверены, что хотите закрыть форму?'),'Подтверждение',MB_YESNO or MB_ICONQUESTION)= mrYes then begin close; end; end; procedure TfrReg_Add.cxButtonSaveClick(Sender: TObject); Var i:integer; T:TfrmAdd; id_reestr:int64; begin If MemoryDataIn.RecordCount<1 then Begin ShowMessage('Не выбрано ни одного контракта!'); Exit; End; T:=TfrmAdd.Create(self); T.Caption := 'Информация о реестре'; T.cxButton_ok.Caption := cnConsts.cn_Accept[PLanguageIndex]; T.cxButton_ok.Hint := cnConsts.cn_Accept[PLanguageIndex]; T.cxButton_cancel.Caption := cnConsts.cn_Cancel[PLanguageIndex]; T.cxButton_cancel.hint := cnConsts.cn_Cancel[PLanguageIndex]; T.ShowModal; If (T.ModalResult=mrOk) then Begin Tran_write.StartTransaction; //===================================================== StoredProc.StoredProcName:='CN_DT_DOG_REESTR_INS'; StoredProc.Prepare; StoredProc.ParamByName('NUM_REESTR').AsInteger:=T.Num_Edit.EditValue; StoredProc.ParamByName('DATE_REESTR').AsDate:=t.Date_Edit.EditValue; StoredProc.ParamByName('ID_USER').AsInteger:=id_user; StoredProc.ParamByName('NOTE').AsString:=T.Note_memo.Text; StoredProc.ExecProc; id_reestr:=StoredProc.FldByName['ID_REESTR'].Asint64; //===================================================== MemoryDataIn.First; For i:=0 to MemoryDataIn.RecordCount-1 do Begin StoredProc.StoredProcName:='CN_DT_DOG_UPD'; StoredProc.Prepare; StoredProc.ParamByName('ID_DOG').AsInteger:=MemoryDataIn['MRID_DOG_IN']; StoredProc.ParamByName('ID_REESTR').AsInteger:=Id_reestr; StoredProc.ExecProc; MemoryDataIn.Next; End; //===================================================== try Tran_write.Commit; StoredProc.Close; except Tran_write.Rollback; StoredProc.Close; End; ModalResult:=mrOk; End; T.Free; end; procedure TfrReg_Add.FormShow(Sender: TObject); Var i:integer; begin Dog_Filter_Edit.Caption := cnConsts.cn_SearchBtn_Caption[PLanguageIndex]; FiltrByFIO_RadioButton.Caption := cnConsts.cn_FiltrByFIO[PLanguageIndex]; FiltrByNum_RadioButton.Caption := cnConsts.cn_FiltrByNum[PLanguageIndex]; FilterExecute_Button.Hint := cnConsts.cn_SearchBtn_Caption[PLanguageIndex]; If cxButtonSave.Enabled then begin DataSet_update.Close; DataSet_update.SQLs.SelectSQL.Clear; DataSet_update.SQLs.SelectSQL.add('select first (30)'); DataSet_update.SQLs.SelectSQL.add('dr.num_dog,'); DataSet_update.SQLs.SelectSQL.add('dr.fio,'); DataSet_update.SQLs.SelectSQL.add('d.ID_DOG'); DataSet_update.SQLs.SelectSQL.add('from cn_dt_dog_root dr, cn_dt_dog d'); DataSet_update.SQLs.SelectSQL.add('Where (d.id_reestr is null)'); DataSet_update.SQLs.SelectSQL.add(' and (d.id_dog_root=dr.id_dog_root)'); DataSet_update.SQLs.SelectSQL.add(' and (dr.use_end=''01.01.3050'')'); DataSet_update.Open; DataSet_update.FetchAll; MemoryDataNot.EmptyTable; For i:=0 to DataSet_update.RecordCount-1 do Begin MemoryDataNot.Open; MemoryDataNot.Insert; MemoryDataNot.FieldByName('MrFIO').AsString:=''; MemoryDataNot.FieldByName('MrNum').AsVariant:=0; MemoryDataNot.FieldByName('MrID_DOG').AsVariant:=0; MemoryDataNot.Post; MemoryDataNot.Next; End; MemoryDataNot.First; DataSet_update.First; For i:=0 to DataSet_update.RecordCount-1 do Begin MemoryDataNot.Open; MemoryDataNot.Edit; MemoryDataNot.FieldByName('MrFIO').AsVariant:=DataSet_update.FieldByName('FIO').AsVariant; MemoryDataNot.FieldByName('MrNUM').AsString:=DataSet_update.FieldByName('NUM_DOG').AsString; MemoryDataNot.FieldByName('MrID_DOG').AsVariant:=DataSet_update.FieldByName('ID_DOG').AsVariant; MemoryDataNot.Post; DataSet_update.Next; MemoryDataNot.Next; end; MemoryDataNot.First; End Else Begin DataSet_update.Close; DataSet_update.SQLs.SelectSQL.Clear; DataSet_update.SQLs.SelectSQL.add('select'); DataSet_update.SQLs.SelectSQL.add('dr.num_dog,'); DataSet_update.SQLs.SelectSQL.add('dr.fio,'); DataSet_update.SQLs.SelectSQL.add('d.ID_DOG'); DataSet_update.SQLs.SelectSQL.add('from cn_dt_dog_root dr, cn_dt_dog d'); DataSet_update.SQLs.SelectSQL.add('Where (d.id_reestr ='+IntToStr(ID_REESTR)+')'); DataSet_update.SQLs.SelectSQL.add(' and (d.id_dog_root=dr.id_dog_root)'); DataSet_update.Open; DataSet_update.FetchAll; MemoryDataIn.EmptyTable; For i:=0 to DataSet_update.RecordCount-1 do Begin MemoryDatain.Open; MemoryDatain.Insert; MemoryDatain.FieldByName('MrFIO_in').AsString:=''; MemoryDatain.FieldByName('MrNum_in').AsVariant:=0; MemoryDatain.FieldByName('MrID_DOG_in').AsVariant:=0; MemoryDatain.Post; MemoryDatain.Next; End; MemoryDatain.First; DataSet_update.First; For i:=0 to DataSet_update.RecordCount-1 do Begin MemoryDatain.Open; MemoryDatain.Edit; MemoryDatain.FieldByName('MrFIO_in').AsVariant:=DataSet_update.FieldByName('FIO').AsVariant; MemoryDatain.FieldByName('MrNUM_in').AsString:=DataSet_update.FieldByName('NUM_DOG').AsString; MemoryDatain.FieldByName('MrID_DOG_in').AsVariant:=DataSet_update.FieldByName('ID_DOG').AsVariant; MemoryDatain.Post; DataSet_update.Next; MemoryDatain.Next; end; MemoryDatain.First; End; end; procedure TfrReg_Add.FilterExecute_ButtonClick(Sender: TObject); var i:integer; S:String; begin if Dog_Filter_Edit.text<>'' then Begin DataSet_update.Close; DataSet_update.SQLs.SelectSQL.Clear; DataSet_update.SQLs.SelectSQL.add('select '); DataSet_update.SQLs.SelectSQL.add('dr.num_dog,'); DataSet_update.SQLs.SelectSQL.add('dr.fio,'); DataSet_update.SQLs.SelectSQL.add('d.ID_DOG'); DataSet_update.SQLs.SelectSQL.add('from cn_dt_dog_root dr, cn_dt_dog d'); DataSet_update.SQLs.SelectSQL.add('Where (d.id_reestr is null)'); DataSet_update.SQLs.SelectSQL.add(' and (d.id_dog_root=dr.id_dog_root)'); DataSet_update.SQLs.SelectSQL.add(' and (dr.use_end=''01.01.3050'')'); if FiltrByFIO_RadioButton.Checked then S:='FIO' Else S:='NUM_DOG'; DataSet_update.SQLs.SelectSQL.Add(' and (UPPER(dr.'+S+') LIKE UPPER('''+Dog_Filter_Edit.Text+''')||''%'')'); DataSet_update.Open; DataSet_update.FetchAll; MemoryDataNot.EmptyTable; For i:=0 to DataSet_update.RecordCount-1 do Begin MemoryDataNot.Open; MemoryDataNot.Insert; MemoryDataNot.FieldByName('MrFIO').AsString:=''; MemoryDataNot.FieldByName('MrNum').AsString:=''; MemoryDataNot.FieldByName('MrID_DOG').AsVariant:=0; MemoryDataNot.Post; MemoryDataNot.Next; End; MemoryDataNot.First; DataSet_update.First; For i:=0 to DataSet_update.RecordCount-1 do Begin MemoryDataNot.Open; MemoryDataNot.Edit; MemoryDataNot.FieldByName('MrFIO').AsVariant:=DataSet_update.FieldByName('FIO').AsVariant; MemoryDataNot.FieldByName('MrNUM').AsString:=DataSet_update.FieldByName('NUM_DOG').AsString; MemoryDataNot.FieldByName('MrID_DOG').AsVariant:=DataSet_update.FieldByName('ID_DOG').AsVariant; MemoryDataNot.Post; DataSet_update.Next; MemoryDataNot.Next; end; MemoryDataNot.First; End; end; end.
unit AddOpTest; {$mode objfpc}{$H+} interface uses SysUtils, fpcunit, testregistry, uIntX, uConstants, uIntXLibTypes; type { TTestAddOp } TTestAddOp = class(TTestCase) published procedure Add2IntX(); procedure Add2IntXNeg(); procedure AddIntIntX(); procedure AddIntXInt(); procedure CallAddNullIntX(); procedure Add0IntX(); procedure Add0IntXNeg(); procedure Add2BigIntX(); procedure Add2BigIntXC(); procedure Add2BigIntXC2(); procedure Add2BigIntXC3(); procedure Add2BigIntXC4(); procedure Fibon(); procedure AddSub(); private procedure AddNullIntX(); end; implementation { TTestAddOp } procedure TTestAddOp.Add2IntX(); var int1, int2: TIntX; begin int1 := TIntX.Create(3); int2 := TIntX.Create(5); AssertTrue(int1 + int2 = 8); end; procedure TTestAddOp.Add2IntXNeg(); var int1, int2: TIntX; begin int1 := TIntX.Create(-3); int2 := TIntX.Create(-5); AssertTrue(int1 + int2 = -8); end; procedure TTestAddOp.AddIntIntX(); var IntX: TIntX; begin IntX := TIntX.Create(3); AssertTrue(IntX + 5 = 8); end; procedure TTestAddOp.AddIntXInt(); var IntX: TIntX; begin IntX := TIntX.Create(3); AssertTrue(5 + IntX = 8); end; procedure TTestAddOp.AddNullIntX(); var int1: TIntX; begin int1 := TIntX.Create(3); int1 := int1 + Default(TIntX); end; procedure TTestAddOp.CallAddNullIntX(); var TempMethod: TRunMethod; begin TempMethod := @AddNullIntX; AssertException(EArgumentNilException, TempMethod); end; procedure TTestAddOp.Add0IntX(); var int1: TIntX; begin int1 := TIntX.Create(3); AssertTrue(int1 + 0 = 3); AssertTrue(int1 + TIntX.Create(0) = 3); end; procedure TTestAddOp.Add0IntXNeg(); var int1, tempIntX: TIntX; begin int1 := TIntX.Create(-3); AssertTrue(int1 + 0 = -3); AssertTrue(int1 + TIntX.Create(0) = -3); tempIntX := TIntX.Create(-1); AssertTrue((TIntX.Create(0) + tempIntX) = -1); AssertTrue(TIntX.Create(0) + 0 = 0); end; procedure TTestAddOp.Add2BigIntX(); var temp1, temp2, temp3: TIntXLibUInt32Array; int1, int2, int3: TIntX; begin SetLength(temp1, 3); temp1[0] := 1; temp1[1] := 2; temp1[2] := 3; SetLength(temp2, 3); temp2[0] := 3; temp2[1] := 4; temp2[2] := 5; SetLength(temp3, 3); temp3[0] := 4; temp3[1] := 6; temp3[2] := 8; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, False); int3 := TIntX.Create(temp3, False); AssertTrue(int1 + int2 = int3); end; procedure TTestAddOp.Add2BigIntXC(); var temp1, temp2, temp3: TIntXLibUInt32Array; int1, int2, int3: TIntX; begin SetLength(temp1, 2); temp1[0] := TConstants.MaxUInt32Value; temp1[1] := TConstants.MaxUInt32Value - 1; SetLength(temp2, 2); temp2[0] := 1; temp2[1] := 1; SetLength(temp3, 3); temp3[0] := 0; temp3[1] := 0; temp3[2] := 1; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, False); int3 := TIntX.Create(temp3, False); AssertTrue(int1 + int2 = int3); end; procedure TTestAddOp.Add2BigIntXC2(); var temp1, temp2, temp3: TIntXLibUInt32Array; int1, int2, int3: TIntX; begin SetLength(temp1, 2); temp1[0] := TConstants.MaxUInt32Value - 1; temp1[1] := TConstants.MaxUInt32Value - 1; SetLength(temp2, 2); temp2[0] := 1; temp2[1] := 1; SetLength(temp3, 2); temp3[0] := TConstants.MaxUInt32Value; temp3[1] := TConstants.MaxUInt32Value; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, False); int3 := TIntX.Create(temp3, False); AssertTrue(int1 + int2 = int3); end; procedure TTestAddOp.Add2BigIntXC3(); var temp1, temp2, temp3: TIntXLibUInt32Array; int1, int2, int3: TIntX; begin SetLength(temp1, 2); temp1[0] := TConstants.MaxUInt32Value; temp1[1] := TConstants.MaxUInt32Value; SetLength(temp2, 2); temp2[0] := 1; temp2[1] := 1; SetLength(temp3, 3); temp3[0] := 0; temp3[1] := 1; temp3[2] := 1; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, False); int3 := TIntX.Create(temp3, False); AssertTrue(int1 + int2 = int3); end; procedure TTestAddOp.Add2BigIntXC4(); var temp1, temp2, temp3: TIntXLibUInt32Array; int1, int2, int3: TIntX; begin SetLength(temp1, 4); temp1[0] := TConstants.MaxUInt32Value; temp1[1] := TConstants.MaxUInt32Value; temp1[2] := 1; temp1[3] := 1; SetLength(temp2, 2); temp2[0] := 1; temp2[1] := 1; SetLength(temp3, 4); temp3[0] := 0; temp3[1] := 1; temp3[2] := 2; temp3[3] := 1; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, False); int3 := TIntX.Create(temp3, False); AssertTrue(int1 + int2 = int3); end; procedure TTestAddOp.Fibon(); var int1, int2, int3: TIntX; i: integer; begin int1 := TIntX.Create(1); int2 := int1; int3 := Default(TIntX); i := 0; while i <= Pred(10000) do begin int3 := int1 + int2; int1 := int2; int2 := int3; Inc(i); end; end; procedure TTestAddOp.AddSub(); var int1, int2: TIntX; begin int1 := TIntX.Create(2); int2 := TIntX.Create(-2); AssertTrue(int1 + int2 = 0); end; initialization RegisterTest(TTestAddOp); end.
//------------------------------------------------------------------------------ //Mob UNIT //------------------------------------------------------------------------------ // What it does- // A mob that uses TMobAI to take control of everything. // // Changes - // [2008/12/?] Aeomin - Created (actually created long ago). // //------------------------------------------------------------------------------ unit Mob; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Types, AIBeing, AI ; type TSummonType = (stREPEAT,stONELIFE); TMob = class(TAIBeing) protected public SpriteName : String; Defense : Word; MDEF : Word; Race : Byte; Scale : Byte; TamingItem : LongWord; FoodItem : LongWord; InitPosition : TPoint; RadiusX : Word; RadiusY : Word; SummonType : TSummonType; procedure CalcMaxHP; override; procedure CalcMaxSP; override; procedure AddToList; procedure Initiate; constructor Create; destructor Destroy; override; end; implementation uses Main, MobAI, AreaLoopEvents, MapTypes ; procedure TMob.CalcMaxHP; begin MaxHP := HP; end; procedure TMob.CalcMaxSP; begin MaxHP := HP; end; procedure TMob.AddToList; begin MainProc.ZoneServer.MobList.Add(Self); MapInfo.MobList.Add(Self); end; //------------------------------------------------------------------------------ //Initiate PROCEDURE //------------------------------------------------------------------------------ // What it does- // Initiate mob, call this procedure after place into map. // This routine should initiate mob AI and all that good stuffs // // Changes- // [2008/12/13] Aeomin - Create. //------------------------------------------------------------------------------ procedure TMob.Initiate; var Pass : Boolean; Trials:Byte; function RandomRadiusCell:Boolean; var NewPosition : TPoint; begin NewPosition.X := InitPosition.X + (Random($FFFF) mod (RadiusX*2) - RadiusX); NewPosition.Y := InitPosition.Y + (Random($FFFF) mod (RadiusY*2) - RadiusY); Position := NewPosition; Result := MapInfo.PointInRange(Position) AND NOT MapInfo.IsBlocked(Position); end; begin if MapInfo.State = LOADED then begin if SummonType = stREPEAT then begin if (InitPosition.X = 0) AND (InitPosition.Y = 0) then begin Position := MapInfo.RandomCell; end else begin Pass := False; for Trials := 1 to 100 do begin if RandomRadiusCell then begin Pass:=True; Break; end; end; if NOT Pass then begin WriteLN('Position failed'); Exit; end; end; end; MapInfo.Cell[Position.X, Position.Y].Beings.AddObject(ID,Self); AreaLoop(SpawnMob); {Let's see what we have around here...} AI.Initiate; end; end;{Initiate} //------------------------------------------------------------------------------ constructor TMob.Create; begin inherited; AI := TMobAI.Create(Self); end; destructor TMob.Destroy; begin AI.Free; end; end.
unit Fun; interface uses Registry,Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; implementation procedure SaveParam(Left,Top,Width,Height:integer); var Reg:TRegistry; begin Reg:=TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\LenaSoft\Dogovor', True) then begin Reg.WriteInteger('Left',Left); Reg.WriteInteger('Top',Top); Reg.WriteInteger('Width',Width); Reg.WriteInteger('Height',Height); Reg.CloseKey; end; finally Reg.Free; end; end; /////////////////////////////////////////////////////////////////////////// procedure LoadParam(var Left,Top,Width,Height:integer); var Reg:TRegistry; a:integer; begin Reg:=TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\LenaSoft\Dogovor', True) then begin a:=Reg.ReadInteger('Left'); if(a>0)then Left:=a; a:=Reg.ReadInteger('Top'); if(a>0)then Top:=a; a:=Reg.ReadInteger('Width'); if(a>0)then Width:=a; a:=Reg.ReadInteger('Height'); if(a>0)then Height:=a; Reg.CloseKey; end; finally Reg.Free; end; end; end.
unit St_sp_Category_Class_Form; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, ToolWin, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, FIBQuery, pFIBQuery, pFIBStoredProc, ActnList, FIBDataSet, pFIBDataSet, cxContainer, cxLabel, ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, Menus, FIBDatabase, pFIBDatabase, IBase, St_Proc, dxStatusBar, st_ConstUnit; type TClassCategoryForm = class(TForm) ToolBar1: TToolBar; AddButton: TToolButton; EditButton: TToolButton; DeleteButton: TToolButton; RefreshButton: TToolButton; SelectButton: TToolButton; ExitButton: TToolButton; ImageListOfCategory: TImageList; cxGrid1: TcxGrid; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1DBTableView1DBColumn1: TcxGridDBColumn; cxGrid1DBTableView1ID_CATEGORY_CLASS: TcxGridDBColumn; cxGrid1DBTableView1NAME_CATEGORY_CLASS: TcxGridDBColumn; cxGrid1DBTableView1PEOPLE: TcxGridDBColumn; cxGrid1DBTableView1PLACES: TcxGridDBColumn; cxGrid1Level1: TcxGridLevel; Panel1: TPanel; cxLabel1: TcxLabel; PeopleLabel: TcxLabel; cxLabel2: TcxLabel; PlaceLabel: TcxLabel; DataSource: TDataSource; WriteProc: TpFIBStoredProc; ActionList1: TActionList; AddAction: TAction; EditAction: TAction; DeleteAction: TAction; RefreshAction: TAction; ExitAction: TAction; cxStyleRepository1: TcxStyleRepository; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; PopupMenu1: TPopupMenu; N1: TMenuItem; N2: TMenuItem; DeleteAction1: TMenuItem; RefreshAction1: TMenuItem; SearchButton_Naim: TToolButton; N3: TMenuItem; DB: TpFIBDatabase; WriteTransaction: TpFIBTransaction; ReadTransaction: TpFIBTransaction; DataSet: TpFIBDataSet; ReadDataSet: TpFIBDataSet; PopupImageList: TImageList; HotKey_StatusBar: TdxStatusBar; SelectAction: TAction; procedure ExitButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure DataSetAfterScroll(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure DataSetAfterOpen(DataSet: TDataSet); procedure SelectButtonClick(Sender: TObject); procedure cxGrid1DBTableView1DblClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure SearchButton_NaimClick(Sender: TObject); private PLanguageIndex : byte; procedure FormIniLanguage(); public KeyField : string; constructor Create (AOwner: TComponent; DB_Handle:TISC_DB_HANDLE;IsChild: boolean; AllowMultiSelect: boolean);reintroduce; procedure SelectAll; end; function View_st_Class_Category(AOwner : TComponent;DB:TISC_DB_HANDLE; ShowModal: boolean; MultiSelect: boolean; ID : int64):variant;stdcall; exports View_st_Class_Category; var ClassCategoryForm: TClassCategoryForm; res:Variant; implementation uses St_sp_Category_Class_Form_Add, Search_LgotUnit, Search_Unit; {$R *.dfm} procedure TClassCategoryForm.FormIniLanguage(); begin // индекс языка (1-укр, 2 - рус) PLanguageIndex:= St_Proc.cnLanguageIndex; Caption := st_ConstUnit.st_CatClassSprav[PLanguageIndex]; //названия кнопок ExitButton.Caption := st_ConstUnit.st_ExitBtn_Caption[PLanguageIndex]; ExitButton.Hint := st_ConstUnit.st_ExitBtn_Caption[PLanguageIndex]; AddButton.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex]; AddButton.Hint := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex]; EditButton.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex]; EditButton.Hint := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex]; DeleteButton.Caption := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex]; DeleteButton.Hint := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex]; RefreshButton.Caption := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex]; RefreshButton.Hint := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex]; SelectButton.Caption := st_ConstUnit.st_Select_Caption[PLanguageIndex]; SelectButton.Hint := st_ConstUnit.st_Select_Caption[PLanguageIndex]; SearchButton_Naim.Caption := st_ConstUnit.st_ZaName[PLanguageIndex]; SearchButton_Naim.Hint := st_ConstUnit.st_ZaName[PLanguageIndex]; HotKey_StatusBar.Panels[0].Text:= st_ConstUnit.st_InsertBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex]; HotKey_StatusBar.Panels[1].Text:= st_ConstUnit.st_EditBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_EditBtn_Caption[PLanguageIndex]; HotKey_StatusBar.Panels[2].Text:= st_ConstUnit.st_DeleteBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex]; HotKey_StatusBar.Panels[3].Text:= st_ConstUnit.st_RefreshBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex]; HotKey_StatusBar.Panels[4].Text:= st_ConstUnit.st_Select_Caption[PLanguageIndex] + st_ConstUnit.st_EnterBtn_ShortCut[PLanguageIndex]; HotKey_StatusBar.Panels[5].Text:= st_ConstUnit.st_ExitBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_ExitBtn_Caption[PLanguageIndex]; HotKey_StatusBar.Hint := st_ConstUnit.st_HotKeys[PLanguageIndex]; // кол-во людей cxLabel1.Caption := st_ConstUnit.st_KolvoLudey[PLanguageIndex]; // кол-во мест cxLabel2.Caption := st_ConstUnit.st_KolvoMest[PLanguageIndex]; // пошел грид cxGrid1DBTableView1NAME_CATEGORY_CLASS.Caption := st_ConstUnit.st_NameLable[PLanguageIndex]; N1.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex]; N2.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex]; DeleteAction1.Caption := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex]; RefreshAction1.Caption := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex]; N3.Caption := st_ConstUnit.st_KontextPoisk[PLanguageIndex]; N1.Hint := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex]; N2.Hint := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex]; DeleteAction1.Hint := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex]; RefreshAction1.Hint := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex]; N3.Caption := st_ConstUnit.st_KontextPoisk[PLanguageIndex]; end; constructor TClassCategoryForm.Create(AOwner: TComponent; DB_Handle:TISC_DB_HANDLE; IsChild: boolean; AllowMultiSelect: boolean); begin inherited Create(AOwner); Screen.Cursor:= crHourGlass; DB.Handle:=DB_Handle; if IsChild then begin Formstyle:=fsMDIChild; SelectButton.Enabled:=false; end else begin if AllowMultiSelect then begin Formstyle:=fsNormal; cxGrid1DBTableView1.Columns[0].Visible := true; SelectButton.Enabled:=true; cxGrid1DBTableView1.OptionsSelection.MultiSelect:=true; SearchButton_Naim.Enabled:=true; end else begin Formstyle:=fsNormal; SelectButton.Enabled:=true; SearchButton_Naim.Enabled:=true; cxGrid1DBTableView1.OptionsSelection.MultiSelect:=false; end; end; Screen.Cursor:= crDefault; end; function View_st_Class_Category(AOwner : TComponent;DB:TISC_DB_HANDLE; ShowModal: boolean; MultiSelect: boolean; ID : int64):variant;stdcall; var ViewForm:TClassCategoryForm; begin if not IsMDIChildFormShow(TClassCategoryForm) then if ShowModal=false then begin ViewForm:=TClassCategoryForm.Create(AOwner,DB, true, false); ViewForm.selectall; View_st_Class_Category:=res; end else begin if (not MultiSelect) then begin ViewForm:=TClassCategoryForm.Create(AOwner,DB, false, false); ViewForm.selectall; if (ID <> -2) then ViewForm.DataSet.Locate('ID_CATEGORY_CLASS', ID, []); ViewForm.ShowModal; View_st_Class_Category:=res; end else begin ViewForm:=TClassCategoryForm.Create(AOwner,DB, false, true); ViewForm.selectall; ViewForm.ShowModal; View_st_Class_Category:=res; end; end; end; procedure TClassCategoryForm.SelectAll; begin DataSet.Close; DataSet.Open; end; procedure TClassCategoryForm.ExitButtonClick(Sender: TObject); begin res:=null; close; end; procedure TClassCategoryForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TClassCategoryForm.DataSetAfterScroll(DataSet: TDataSet); begin if DataSet.RecordCount = 0 then exit; PeopleLabel.Caption := IntToStr(DataSet['PEOPLES']); PlaceLabel.Caption := FloatToStr(DataSet['PLACES']); end; procedure TClassCategoryForm.FormCreate(Sender: TObject); begin KeyField := 'ID_CATEGORY_CLASS'; PLanguageIndex:= St_Proc.cnLanguageIndex; end; procedure TClassCategoryForm.FormShow(Sender: TObject); begin // cxGrid1DBTableView1.Items[0].DataBinding.ValueTypeClass := TcxIntegerValueType; FormIniLanguage(); if not DataSet.Active then SelectAll; end; procedure TClassCategoryForm.DataSetAfterOpen(DataSet: TDataSet); begin if DataSet.RecordCount = 0 then begin EditButton.Enabled := false; DeleteButton.Enabled := false; SelectButton.Enabled := false; end else begin EditButton.Enabled := true; DeleteButton.Enabled := true; // SelectButton.Enabled := true; end; end; procedure TClassCategoryForm.SelectButtonClick(Sender: TObject); var i : integer; RecMultiSelected : integer; begin if cxGrid1DBTableView1.OptionsSelection.MultiSelect=true then begin RecMultiSelected:=cxGrid1DBTableView1.DataController.GetSelectedCount; res:=VarArrayCreate([0,RecMultiSelected-1],varVariant); for i:=0 to cxGrid1DBTableView1.DataController.GetSelectedCount-1 do begin res[i]:=cxGrid1DBTableView1.Controller.SelectedRecords[i].Values[1]; end; end; if cxGrid1DBTableView1.OptionsSelection.MultiSelect=false then begin res:=VarArrayCreate([0,1],varVariant); res[0]:=DataSet['ID_CATEGORY_CLASS']; res[1]:=DataSet['NAME_CATEGORY_CLASS']; end; ModalResult := mrOK; end; procedure TClassCategoryForm.cxGrid1DBTableView1DblClick(Sender: TObject); var i : integer; RecMultiSelected : integer; begin if cxGrid1DBTableView1.OptionsSelection.MultiSelect=true then begin RecMultiSelected:=cxGrid1DBTableView1.DataController.GetSelectedCount; res:=VarArrayCreate([0,RecMultiSelected-1],varVariant); for i:=0 to cxGrid1DBTableView1.DataController.GetSelectedCount-1 do begin res[i]:=cxGrid1DBTableView1.Controller.SelectedRecords[i].Values[1]; end; end; if cxGrid1DBTableView1.OptionsSelection.MultiSelect=false then begin res:=VarArrayCreate([0,1],varVariant); res[0]:=DataSet['ID_CATEGORY_CLASS']; res[1]:=DataSet['NAME_CATEGORY_CLASS']; end; if FormStyle = fsMDIChild then EditButtonClick(Sender); ModalResult := mrOK; end; procedure TClassCategoryForm.AddButtonClick(Sender: TObject); var new_id : integer; begin ClassCategoryFormAdd := TClassCategoryFormAdd.Create(Self); ClassCategoryFormAdd.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex]; ClassCategoryFormAdd.PLanguageIndex := PLanguageIndex; if ClassCategoryFormAdd.ShowModal = mrOK then begin WriteProc.StoredProcName := 'ST_INI_CATEGORY_CLASS_INSERT'; WriteProc.Transaction.StartTransaction; WriteProc.Prepare; WriteProc.ParamByName('NAME_CATEGORY_CLASS').AsString := ClassCategoryFormAdd.NameEdit.Text; WriteProc.ParamByName('PEOPLES').AsInteger := StrToInt(ClassCategoryFormAdd.PeopleEdit.Text); WriteProc.ParamByName('PLACES').AsFloat := StrToFloat(ClassCategoryFormAdd.PlaceEdit.Text); WriteProc.ExecProc; new_id := WriteProc[KeyField].AsInteger; try WriteProc.Transaction.Commit; WriteProc.Close; except WriteProc.Transaction.Rollback; WriteProc.Close; raise; end; SelectAll; DataSet.Locate(KeyField, new_id, []); end; ClassCategoryFormAdd.Free; end; procedure TClassCategoryForm.EditButtonClick(Sender: TObject); var id : integer; begin id := DataSet[KeyField]; ClassCategoryFormAdd := TClassCategoryFormAdd.Create(Self); ClassCategoryFormAdd.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex]; ClassCategoryFormAdd.PLanguageIndex := PLanguageIndex; ClassCategoryFormAdd.NameEdit.Text := DataSet['NAME_CATEGORY_CLASS']; ClassCategoryFormAdd.PeopleEdit.Text := IntToStr(DataSet['PEOPLES']); ClassCategoryFormAdd.PlaceEdit.Text := FloatToStr(DataSet['PLACES']); if ClassCategoryFormAdd.ShowModal = mrOK then begin WriteProc.StoredProcName := 'ST_INI_CATEGORY_CLASS_UPDATE'; WriteProc.Transaction.StartTransaction; WriteProc.Prepare; WriteProc.ParamByName(KeyField).AsInteger := id; WriteProc.ParamByName('NAME_CATEGORY_CLASS').AsString := ClassCategoryFormAdd.NameEdit.Text; WriteProc.ParamByName('PEOPLES').AsInteger := StrToInt(ClassCategoryFormAdd.PeopleEdit.Text); WriteProc.ParamByName('PLACES').AsFloat := StrToFloat(ClassCategoryFormAdd.PlaceEdit.Text); WriteProc.ExecProc; try WriteProc.Transaction.Commit; WriteProc.Close; except WriteProc.Transaction.Rollback; WriteProc.Close; raise; end; SelectAll; DataSet.Locate(KeyField, id, []); end; ClassCategoryFormAdd.Free; end; procedure TClassCategoryForm.DeleteButtonClick(Sender: TObject); var selected : integer; begin Screen.Cursor:=crHourGlass; ReadDataSet.Close; ReadDataSet.SelectSQL.Clear; ReadDataSet.SelectSQL.Text:='select CAN from ST_INI_CATEGORY_CLASS_CAN_DELET('+ inttostr(DataSet[KeyField])+')'; ReadDataSet.Open; if ReadDataSet['Can']=0 then begin Screen.Cursor:=crDefault; ShowMessage(PChar(st_ConstUnit.st_mess_NoItemDelete[PLanguageIndex])); ReadDataSet.Close; exit; end; ReadDataSet.Close; Screen.Cursor:=crDefault; if MessageBox(Handle,PChar(st_ConstUnit.st_DeletePromt[PLanguageIndex]),PChar(st_ConstUnit.st_Confirmation_Caption[PLanguageIndex]),MB_YESNO or MB_ICONQUESTION)= mrNo then exit; WriteProc.StoredProcName := 'ST_INI_CATEGORY_CLASS_DELETE'; WriteProc.Transaction.StartTransaction; WriteProc.Prepare; WriteProc.ParamByName(KeyField).AsInteger := DataSet[KeyField]; WriteProc.ExecProc; try WriteProc.Transaction.Commit; WriteProc.Close; except WriteProc.Transaction.Rollback; WriteProc.Close; raise; end; selected := cxGrid1DBTableView1.DataController.FocusedRowIndex-1; SelectAll; cxGrid1DBTableView1.DataController.FocusedRowIndex := selected; end; procedure TClassCategoryForm.RefreshButtonClick(Sender: TObject); var selected : integer; begin Screen.Cursor:=crHourGlass; selected := -1; if DataSet.RecordCount <> 0 then selected := DataSet[KeyField]; SelectAll; DataSet.Locate(KeyField, selected, []); Screen.Cursor:=crDefault; end; procedure TClassCategoryForm.SearchButton_NaimClick(Sender: TObject); begin if PopupMenu1.Items[4].Checked= true then begin Search_LgotForm := TSearch_LgotForm.Create(Self); Search_LgotForm.PLanguageIndex := PLanguageIndex; while Search_LgotForm.FindFlag = false do begin if Search_LgotForm.FindClosed = true then begin Search_LgotForm.Free; exit; end; if Search_LgotForm.ShowModal = mrOk then begin if Search_LgotForm.FindFlag = true then begin cxGrid1DBTableView1NAME_CATEGORY_CLASS.SortOrder:=soAscending; DataSet.Locate('NAME_CATEGORY_CLASS', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]); Search_LgotForm.Free; exit; end else begin cxGrid1DBTableView1NAME_CATEGORY_CLASS.SortOrder:=soAscending; DataSet.Locate('NAME_CATEGORY_CLASS', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]); Search_LgotForm.showModal; end; end; end; if Search_LgotForm.FindFlag = true then begin cxGrid1DBTableView1NAME_CATEGORY_CLASS.SortOrder:=soAscending; DataSet.Locate('NAME_CATEGORY_CLASS', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]); Search_LgotForm.Free; end; end else begin Search_Form:= TSearch_Form.create(self); Search_Form.PLanguageIndex := PLanguageIndex; if Search_Form.ShowModal = mrOk then begin DataSet.Locate('NAME_CATEGORY_CLASS', Search_Form.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]); end; end; end; end.
unit nsLogFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, nsGlobals, nsTypes, nsUtils, ShellAPI, ShlObj, Printers, ComCtrls, Vcl.ActnMan, Vcl.ActnCtrls, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ToolWin; type TfrmLogView = class(TForm) PrintDialog: TPrintDialog; SaveDialog: TSaveDialog; SynMemo1: TMemo; acLogView: TActionManager; acClose: TAction; acSaveAs: TAction; acPrint: TAction; acHelp: TAction; acView: TAction; cbViewMode: TComboBox; sbStatus: TStatusBar; ProgressBar1: TProgressBar; clbr1: TCoolBar; tlbLogView: TToolBar; btnacClose: TToolButton; btnacSaveAs: TToolButton; btnacPrint: TToolButton; btnacHelp: TToolButton; btn5: TToolButton; btn6: TToolButton; btn1: TToolButton; pnlLocalCaption: TPanel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnPrintClick(Sender: TObject); procedure btnSaveAsClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure FormHide(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure cbViewModeChange(Sender: TObject; const Text: string); procedure acViewExecute(Sender: TObject); private FProject: TNSProject; FStrings: TStrings; FStrings2: TStrings; procedure GetSettings(const AProject: TNSProject; const AFileName: string = ''); end; procedure DisplayLogDlg(const AProject: TNSProject; const AFileName: string = ''; const AShowFilter: Boolean = True); implementation {$R *.dfm} procedure DisplayLogDlg(const AProject: TNSProject; const AFileName: string = ''; const AShowFilter: Boolean = True); begin with TfrmLogView.Create(Application) do try Caption := Format(sLogCaption, [AProject.DisplayName]); sbStatus.Visible := AShowFilter; GetSettings(AProject, AFileName); ShowModal; finally Free; end; end; procedure TfrmLogView.FormCreate(Sender: TObject); begin FStrings := TStringList.Create; FStrings2 := TStringList.Create; end; procedure TfrmLogView.FormDestroy(Sender: TObject); begin FStrings.Free; FStrings2.Free; if cbViewMode.Visible then g_ViewLogMode := TViewLogMode(cbViewMode.ItemIndex); end; procedure TfrmLogView.btnPrintClick(Sender: TObject); var Line: integer; PrintText: TextFile; {declares a file variable} begin if PrintDialog.Execute then begin AssignPrn(PrintText); {assigns PrintText to the printer} Rewrite(PrintText); {creates and opens the output file} Printer.Canvas.Font := SynMemo1.Font; {assigns Font settings to the canvas} for Line := 0 to SynMemo1.Lines.Count - 1 do Writeln(PrintText, SynMemo1.Lines[Line]); {writes the contents of the Memo1 to the printer object} CloseFile(PrintText); {Closes the printer variable} end; end; procedure TfrmLogView.btnSaveAsClick(Sender: TObject); begin SaveDialog.FileName := FormatDateTime('"AceBackup Report "yyyy"_"mm"_"dd"_"hh"_"nn".log"', Now); if SaveDialog.Execute then begin if SaveDialog.FilterIndex = 1 then SaveDialog.FileName := ChangeFileExt(SaveDialog.FileName, sLog); SynMemo1.Lines.SaveToFile(SaveDialog.FileName); end; end; procedure TfrmLogView.btnHelpClick(Sender: TObject); begin Application.HelpSystem.ShowContextHelp(HelpContext, Application.HelpFile); end; procedure TfrmLogView.GetSettings(const AProject: TNSProject; const AFileName: string = ''); begin FProject := AProject; if AFileName <> EmptyStr then FStrings.LoadFromFile(AFileName) else FStrings.Assign(FProject.GetLog); cbViewMode.ItemIndex := Ord(g_ViewLogMode); cbViewModeChange(Self, cbViewMode.Items[cbViewMode.ItemIndex]); end; procedure TfrmLogView.FormHide(Sender: TObject); begin SaveFormSettings(Self); end; procedure TfrmLogView.FormShow(Sender: TObject); begin RestoreFormSettings(Self); UpdateVistaFonts(Self); end; procedure TfrmLogView.cbViewModeChange(Sender: TObject; const Text: string); var Index: integer; S: string; begin FStrings2.Clear; ProgressBar1.Position := 0; ProgressBar1.Max := FStrings.Count - 1; ProgressBar1.Visible := True; try SynMemo1.Lines.Clear; if cbViewMode.Visible and (TViewLogMode(cbViewMode.ItemIndex) = vlFailed) then begin if FStrings.Count = 0 then Exit; for Index := 0 to FStrings.Count - 1 do begin ProgressBar1.Position := ProgressBar1.Position + 1; Application.ProcessMessages; S := FStrings[Index]; if S = EmptyStr then Continue; if S[1] = #1 then Continue; FStrings2.Add(Trim(S)); end; end else begin for Index := 0 to FStrings.Count - 1 do begin ProgressBar1.Position := ProgressBar1.Position + 1; Application.ProcessMessages; S := FStrings[Index]; FStrings2.Add(Trim(S)); end; end; SynMemo1.Lines.Assign(FStrings2); finally ProgressBar1.Visible := False; end; end; procedure TfrmLogView.acViewExecute(Sender: TObject); begin // nothing to do here end; procedure TfrmLogView.btnCloseClick(Sender: TObject); begin ModalResult := mrOk; end; end.
Unit GraphObjects; Interface uses Graphics, Classes; var ColrBlack: TColor; type TViz = class(TObject) ColrLine: TColor; Canvas: TCanvas; x,y,r: word; procedure Ris; virtual; abstract; procedure Draw(bl:boolean); procedure Show; procedure Hide; procedure MovTo(dx,dy,dr:integer); end; TKrug = class(TViz) x1,y1,x2,y2: word; constructor Create(x0,y0,r0: word; colrLine0: TColor; canvas0: TCanvas); procedure Ris; override; end; TKvad = class(TKrug) procedure Ris; override; end; TRectan = class(TViz) x1,y1,x2,y2: word; constructor Create(xs,ys,xe,ye: word; colrLine0: TColor; canvas0: TCanvas); procedure Ris; override; end; TCar = class(TRectan) lights_on, doors_open: boolean; constructor Create(xs,ys,xe,ye: word; colrLine0: TColor; canvas0: TCanvas); procedure Ris; override; procedure Lights(turnon:boolean); procedure Doors(open:boolean); procedure MovTo(dx,dy:integer); end; implementation //TViz procedure Tviz.Draw; begin with Canvas do begin if bl then begin pen.color:=colrLine; brush.color:=colrLine end else begin pen.color:=colrBlack; brush.color:=colrBlack end; Ris; end; end; procedure Tviz.Show; begin Draw(true); end; procedure Tviz.Hide; begin Draw(false); end; procedure Tviz.MovTo; begin Hide; x:=x+dx; y:=y+dy; r:=r+dr; Show; end; //TKrug constructor TKrug.Create; begin colrLine:=colrLine0; canvas:=canvas0; x:=x0; y:=y0; r:=r0; end; procedure Tkrug.Ris; begin x1:=x-r; x2:=x+r; y1:=y-r; y2:=y+r; Canvas.Ellipse(x1,y1,x2,y2); end; //TKvad procedure Tkvad.ris; begin x1:=x-r; x2:=x+r; y1:=y-r; y2:=y+r; Canvas.Rectangle(x1,y1,x2,y2); end; //TRectan [Rectangle] constructor TRectan.Create; begin colrLine:=colrLine0; canvas:=canvas0; x1:=xs; y1:=ys; x2:=xe; y2:=ye; end; procedure TRectan.ris; begin Canvas.Rectangle(x1,y1,x2,y2); end; //TCar constructor TCar.Create; begin lights_on:=false; doors_open:=false; inherited Create(xs,ys,xe,ye,colrLine0,canvas0); end; procedure TCar.ris; begin Canvas.Brush.color:=clWhite; Canvas.Ellipse(round(x1+(x2-x1)/10),round(y2-(x2-x1)/10),round(x1+(x2-x1)/10*3),round(y2+(x2-x1)/10)); Canvas.Ellipse(round(x1+(x2-x1)/10*7),round(y2-(x2-x1)/10),round(x1+(x2-x1)/10*9),round(y2+(x2-x1)/10)); inherited ris; Canvas.MoveTo(round(x1+(x2-x1)/5),y1); Canvas.LineTo(round(x1+(x2-x1)/10*3),y1-(y2-y1)); Canvas.LineTo(round(x1+(x2-x1)/10*7),y1-(y2-y1)); Canvas.LineTo(round(x1+(x2-x1)/5*4),y1); Canvas.MoveTo(round(x1+(x2-x1)/20*11),y1-(y2-y1)); Canvas.LineTo(round(x1+(x2-x1)/20*11),y2); Canvas.MoveTo(round(x1+(x2-x1)/10*3),y1-(y2-y1)); Canvas.LineTo(round(x1+(x2-x1)/10*3),y2); Canvas.MoveTo(round(x1+(x2-x1)/5*4),y1); Canvas.LineTo(round(x1+(x2-x1)/5*4),y2); Canvas.MoveTo(round(x1+(x2-x1)/20*19),y1); Canvas.LineTo(round(x1+(x2-x1)/20*19),round(y1+(y2-y1)/2)); Canvas.LineTo(x2,round(y1+(y2-y1)/2)); end; procedure TCar.Lights; begin lights_on:=turnon; if turnon then begin Canvas.Brush.Color:=clYellow; Canvas.FillRect(Rect(round(x1+(x2-x1)/20*19)+1,y1+1,x2-1,round(y1+(y2-y1)/2))); end else begin Canvas.Brush.Color:=ColrBlack; Canvas.FillRect(Rect(round(x1+(x2-x1)/20*19)+1,y1+1,x2-1,round(y1+(y2-y1)/2))); end; Canvas.Brush.Color:=ColrBlack; end; procedure TCar.Doors; begin doors_open:=open; if open then begin Canvas.Pen.Color:=ColrBlack; Canvas.MoveTo(round(x1+(x2-x1)/20*11),y1); Canvas.LineTo(round(x1+(x2-x1)/5*4),y1); Canvas.Pen.Color:=ColrLine; Canvas.MoveTo(round(x1+(x2-x1)/5*4),y1); Canvas.LineTo(round(x1+(x2-x1)/4*3),round(y1-(y2-y1))); Canvas.LineTo(round(x1+(x2-x1)/5*3),round(y1-(y2-y1)/2)); Canvas.LineTo(round(x1+(x2-x1)/5*3),round(y2+(y2-y1)/2)); Canvas.LineTo(round(x1+(x2-x1)/5*4),y2); Canvas.MoveTo(round(x1+(x2-x1)/5*4),y1); Canvas.LineTo(round(x1+(x2-x1)/5*3),round(y1+(y2-y1)/2)); end else begin Canvas.Pen.Color:=ColrBlack; Canvas.MoveTo(round(x1+(x2-x1)/5*4),y1); Canvas.LineTo(round(x1+(x2-x1)/4*3),round(y1-(y2-y1))); Canvas.LineTo(round(x1+(x2-x1)/5*3),round(y1-(y2-y1)/2)); Canvas.LineTo(round(x1+(x2-x1)/5*3),round(y2+(y2-y1)/2)); Canvas.LineTo(round(x1+(x2-x1)/5*4),y2); Canvas.MoveTo(round(x1+(x2-x1)/5*4),y1); Canvas.LineTo(round(x1+(x2-x1)/5*3),round(y1+(y2-y1)/2)); Canvas.Pen.Color:=ColrLine; Canvas.MoveTo(round(x1+(x2-x1)/20*11),y1); Canvas.LineTo(round(x1+(x2-x1)/5*4),y1); Canvas.Pie(round(x1+(x2-x1)/10*7),round(y2-(x2-x1)/10),round(x1+(x2-x1)/10*9),round(y2+(x2-x1)/10),x1,y2,x2,y2); Canvas.MoveTo(x1,y2-1); Canvas.LineTo(x2,y2-1); Canvas.MoveTo(round(x1+(x2-x1)/5*4),y1); Canvas.LineTo(round(x1+(x2-x1)/10*7),y1-(y2-y1)); end; end; procedure TCar.MovTo; var l,d:boolean; begin l:=lights_on; d:=doors_open; Lights(false); Doors(false); Hide; x1:=x1+dx; y1:=y1+dy; x2:=x2+dx; y2:=y2+dy; Show; Lights(l); Doors(d); end; end.
// Pascal Coding Reference.pas
PROGRAM PrimFac; TYPE {* Needed for the return type of GetPrimesOfNumber since Arrays can't be a return type for functions. *} ArrayOfInteger = ARRAY OF INTEGER; {* IsPrime function from Uebung 2 WS 2018 *} FUNCTION IsPrime(number: INTEGER): BOOLEAN; VAR i: INTEGER; BEGIN IF number = 2 THEN IsPrime := true ELSE IF (number mod 2 = 0) OR (number <= 1) THEN IsPrime := false ELSE BEGIN IsPrime := true; i := 3; WHILE i <= number-1 DO BEGIN IF number mod i = 0 THEN BEGIN IsPrime := false; END; i := i + 2 END END END; {* returns array with all prime numbers below the target *} FUNCTION GetPrimesOfNumber(target: INTEGER): ArrayOfInteger; VAR i, j: INTEGER; result: ARRAY OF INTEGER; BEGIN j := 0; SetLength(result, j); FOR i := 0 TO target DO IF (IsPrime(i)) THEN BEGIN SetLength(result, j+1); {* re-adjust array length "dynamicly" *} result[j] := i; j := j + 1; END; GetPrimesOfNumber := result; END; PROCEDURE PrimeFactors(x: INTEGER; VAR factors: ARRAY OF INTEGER; VAR count: INTEGER); VAR i, j: INTEGER; primes: ARRAY OF INTEGER; outOfRange: BOOLEAN; BEGIN i := 0; j := 0; count := 0; outOfRange := false; IF IsPrime(x) or (x < 2) THEN BEGIN {* value x is already prime or below 0 *} factors[0] := x; count := 1 END ELSE BEGIN primes := GetPrimesOfNumber(x); while (i < Length(primes)) AND (x >= 1) and (not outOfRange) DO BEGIN {* check if prime can divide x without rest *} IF (x mod primes[i]) = 0 THEN BEGIN IF j >= Length(factors) THEN BEGIN {* factors length is to small for the primefactors. all collected primefactors stay in the array *} outOfRange := true; count := 0; END ELSE BEGIN {* primefactor found, add it to factors *} factors[j] := primes[i]; j := j + 1; count := count + 1; {* calculate the new x *} x := x DIV primes[i]; {* IMPORTANT! don't increase counter i since the found factor maybe works again for the new x *} END; END ELSE BEGIN {* current prime is no primefactor. Inrease counter i and try next in array *} i := i + 1; END; END; END; END; FUNCTION Number(factors: ARRAY OF INTEGER; count: INTEGER): INTEGER; VAR erg, i: INTEGER; BEGIN {* first primefactor has to be mapped to erg before the loop starts otherwise erg could have a random money from the memory or 0. *} erg := factors[0]; FOR i := 1 TO count-1 DO BEGIN erg := erg * factors[i]; END; Number := erg; END; PROCEDURE Intersect(a, b: ARRAY OF INTEGER; countA, countB: INTEGER; VAR result: ARRAY OF INTEGER; VAR countResult: INTEGER); VAR i, j: INTEGER; BEGIN i := 0; j := 0; countResult := 0; WHILE (i < countA) and (j < countB) DO BEGIN IF a[i] = b[j] THEN BEGIN {* shared primefactor found, save it *} result[countResult] := a[i]; countResult := countResult + 1; {* both count variables have to be increased, to ensure there are duplicates in result *} i := i + 1; j := j + 1; END ELSE BEGIN {* always increase the count variable of the array * with the smaller value. *} IF a[i] < b[j] THEN i := i + 1 ELSE j := j + 1; END; END; {* if there are no shared primefactors the ggt is 1 *} if countResult = 0 THEN result[0] := 1; END; PROCEDURE Union(a, b: ARRAY OF INTEGER; countA, countB: INTEGER; VAR result: ARRAY OF INTEGER; VAR countResult: INTEGER); VAR i, j: INTEGER; BEGIN i := 0; j := 0; countResult := 0; WHILE (i < countA) and (j < countB) DO BEGIN IF a[i] < b[j] THEN BEGIN {* The smaller value will be saved. Also the arrays counter increases *} result[countResult] := a[i]; countResult := countResult + 1; i := i + 1; END ELSE IF b[j] < a[i] THEN BEGIN {* The smaller value will be saved. Also the arrays counter increases *} result[countResult] := b[j]; countResult := countResult + 1; j := j + 1 END ELSE IF a[i] = b [j] THEN BEGIN {* If both values are equal, just one will be saved in result. *} result[countResult] := a[i]; countResult := countResult + 1; i := i + 1; {* Both counters have to be increased to avoid duplicates *} j := j + 1 END; END; {* if there are values that were not compared yet since one of the arrays was shorter than the other one the remaining values should just be added to result. *} IF i < countA THEN BEGIN WHILE (i < countA) DO BEGIN result[countResult] := a[i]; countResult := countResult + 1; i := i + 1; END; END; IF j < countB THEN BEGIN WHILE (j < countB) DO BEGIN result[countResult] := b[j]; countResult := countResult + 1; j := j + 1; END; END; END; FUNCTION AssertPrimeFactors(n, arrLength, expectedCount: INTEGER): BOOLEAN; VAR arr: ARRAY OF INTEGER; count, retNumber: INTEGER; BEGIN {* Check if primefactors of given n fit inside arr of with lenght arrLenght. Found PrimeFactors must be true, if retNumber equals n *} SetLength(arr, arrLength); PrimeFactors(n, arr, count); retNumber := Number(arr, count); AssertPrimeFactors := (retNumber = n) and (expectedCount = count) END; FUNCTION AssertPrimeFactorsOnlyCountCheck(n, arrLength, expectedCount: INTEGER): BOOLEAN; VAR arr: ARRAY OF INTEGER; count: INTEGER; BEGIN SetLength(arr, arrLength); PrimeFactors(n, arr, count); AssertPrimeFactorsOnlyCountCheck := (expectedCount = count) END; {* The operation of checking if two arrays are equal is used more often *} FUNCTION AssertEqualArrays(arr1, arr2: ARRAY OF INTEGER; count: INTEGER): BOOLEAN; VAR i: INTEGER; BEGIN AssertEqualArrays := true; {* if at one point the values are not equal the array are considered to not be equal *} FOR i := 0 TO count-1 DO BEGIN IF arr1[i] <> arr2[i] THEN AssertEqualArrays := false; END; END; FUNCTION AssertIntersection(arr1, arr2, expectedResult: ARRAY OF INTEGER; count1, count2, expectedCount: INTEGER): BOOLEAN; VAR result: ARRAY OF INTEGER; countResult: INTEGER; BEGIN SetLength(result, expectedCount); {* set the array length for result *} Intersect(arr1, arr2, count1, count2, result, countResult); AssertIntersection := AssertEqualArrays(result, expectedResult, countResult) and (expectedCount = countResult); END; FUNCTION AssertUnion(arr1, arr2, expectedResult: ARRAY OF INTEGER; count1, count2, expectedCount: INTEGER): BOOLEAN; VAR result: ARRAY OF INTEGER; countResult: INTEGER; BEGIN SetLength(result, expectedCount); {* set the array length for result *} Union(arr1, arr2, count1, count2, result, countResult); AssertUnion := AssertEqualArrays(result, expectedResult, countResult) and (expectedCount = countResult); END; FUNCTION AssertNumber(arr: ARRAY OF INTEGER; count, expectedResult: INTEGER): BOOLEAN; VAR n: INTEGER; BEGIN n := Number(arr, count); AssertNumber := (n = expectedResult) END; BEGIN //AssertPrimeFactors(n, arrLength, expectedCount: INTEGER): BOOLEAN; WriteLn('AssertPrimeFactors(number, arrLength, expectedCount: INTEGER): BOOLEAN'); WriteLn('1. AssertPrimeFactors(333, 3, 3) -> ', AssertPrimeFactors(333, 3, 3)); WriteLn('2. AssertPrimeFactors(333, 2, 0) -> ', AssertPrimeFactors(333, 2, 0)); // Array ist zu klein, Auflösung durch Number funktioniert nicht WriteLn('3. AssertPrimeFactors(-32768, 1, 1) -> ', AssertPrimeFactors(-32768, 1, 1)); // Noch im Range, Negative Zahl liefert sich selbst zurück WriteLn('4. AssertPrimeFactors(0, 1, 1) -> ', AssertPrimeFactors(0, 1, 1)); WriteLn('5. AssertPrimeFactors(1, 1, 1) -> ', AssertPrimeFactors(1, 1, 1)); WriteLn('6. AssertPrimeFactors(9, 10, 2) -> ', AssertPrimeFactors(9, 10, 2)); // zu großes Array ist kein Problem WriteLn('7. AssertPrimeFactors(9, 1, 0) -> ', AssertPrimeFactors(9, 1, 0)); // False weil Number sich nicht auflösen lässt, out of Range WriteLn('8. AssertPrimeFactors(17, 1, 1) -> ', AssertPrimeFactors(17, 1, 1)); WriteLn('9. AssertPrimeFactorsOnlyCountCheck(9, 1, 0) -> ', AssertPrimeFactorsOnlyCountCheck(9, 1, 0)); // WriteLn('AssertPrimeFactors(32676, 100) -> ', AssertPrimeFactors(32768, 100, 100)); // Overflow WriteLn(); //AssertNumber(arr: ARRAY OF INTEGER; count, expectedResult: INTEGER): BOOLEAN; WriteLn('2) AssertNumber'); WriteLn('1. AssertNumber([2, 2, 5, 5], 4, 100) -> ', AssertNumber([2, 2, 5, 5], 4, 100)); WriteLn('2. AssertNumber([2, 2, 5, 5, 0], 4, 100) -> ', AssertNumber([2, 2, 5, 5, 0], 4, 100)); // Größeres Array kein Problem wenn Count stimmt WriteLn('3. AssertNumber([1], 1, 1) -> ', AssertNumber([1], 1, 1)); WriteLn('4. AssertNumber([-3], 1, -3) -> ', AssertNumber([-3], 1, -3)); WriteLn('5. AssertNumber([-3, -3], 2, 9) -> ', AssertNumber([-3, -3], 2, 9)); // - * - gibt + WriteLn('6. AssertNumber([0, 1, 2], 3, 0) -> ', AssertNumber([0, 1, 2], 3, 0)); WriteLn('7. AssertNumber([], 0, 0) -> ', AssertNumber([], 0, 0)); // Produziert irgendeine Nummer die gerade am Speicher abgelegt ist WriteLn(); //AssertIntersection(arr1, arr2, expectedResult: ARRAY OF INTEGER; count1, count2, expectedCount: INTEGER): BOOLEAN; WriteLn('3) AssertIntersection'); WriteLn('1. AssertIntersection([2, 2, 5, 5], [2, 5, 5], [2, 5, 5], 4, 3, 3) -> ', AssertIntersection([2, 2, 5, 5], [2, 5, 5], [2, 5, 5], 4, 3, 3)); // WriteLn('AssertIntersection([], [], [], 0, 0, 0) -> ', AssertIntersection([], [], [], 0, 0, 0)); // Laufzeit Fehler // WriteLn('AssertIntersection([2, 2, 5, 5], [], [], 4, 0, 0) -> ', AssertIntersection([2, 2, 5, 5], [], [], 4, 0, 0)); //LaufzeitFehler // WriteLn('AssertIntersection([2, 2, 5, 5], [2, 5, 5], [2, 5, 5], 4, 3, 3) -> ', AssertIntersection([2, 2, 5, 5], [3, 3, 37], [2, 5, 5], 3, 4, 4)); WriteLn('2. AssertIntersection([-2, 2, 5, 5], [-2, 5, 5], [-2, 5, 5], 4, 3, 3) -> ', AssertIntersection([-2, 2, 5, 5], [-2, 5, 5], [-2, 5, 5], 4, 3, 3)); // gibt false aus aufgrund von rechenfehlern WriteLn(); //FUNCTION AssertUnion(arr1, arr2, expectedResult: ARRAY OF INTEGER; count1, count2, expectedCount: INTEGER): BOOLEAN; WriteLn('4) AssertUnion'); WriteLn('1. AssertUnion([2, 2, 5, 5], [2, 5, 5], [2, 2, 5, 5], 4, 3, 4) -> ', AssertUnion([2, 2, 5, 5], [2, 5, 5], [2, 2, 5, 5], 4, 3, 4)); WriteLn('2. AssertUnion([17], [23], [17, 23], 1, 1, 2) -> ', AssertUnion([17], [23], [17, 23], 1, 1, 2)); WriteLn('3. AssertUnion([2, 2, 3, 3, 7], [3, 3, 37], [2, 2, 3, 3, 7, 37], 5, 3, 6) -> ', AssertUnion([2, 2, 3, 3, 7], [3, 3, 37], [2, 2, 3, 3, 7, 37], 5, 3, 6)); WriteLn('4. AssertUnion([2, -2, 5, 5], [-2, 5, 5], [2, -2, 5, 5], 4, 3, 4) -> ', AssertUnion([-2, 2, 5, 5], [-2, 5, 5], [-2, 2, 5, 5], 4, 3, 4)); // WriteLn('AssertUnion([2, 2, 5, 5], [], [], 4, 0, 0) -> ', AssertUnion([2, 2, 5, 5], [0], [0], 4, 0, 0)); // Laufzeitfehler //WriteLn('AssertUnion([], [], [], 0, 0, 0) -> ', AssertUnion([], [], [], 0, 0, 0)); // Leere Arrays führen zu einem Laufzeitfehler WriteLn(); END.
unit Auth; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.OleCtrls, SHDocVw, System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent, System.JSON, Vcl.Buttons, ActiveX; type TAuthForm = class(TForm) BottomPanel: TPanel; BrowserAuth: TWebBrowser; LogMemo: TMemo; PropertiesPanel: TPanel; AuthGB: TGroupBox; Splitter1: TSplitter; Label1: TLabel; PropertiesGB: TGroupBox; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; StatusEdit: TEdit; Access_TokenEdit: TEdit; NicknameEdit: TEdit; Account_IdEdit: TEdit; Expires_AtEdit: TEdit; NetClient: TNetHTTPClient; NetRequest: TNetHTTPRequest; AuthBtn: TBitBtn; SaveLogBtn: TBitBtn; OpenLogBtn: TBitBtn; ClearLogBtn: TBitBtn; procedure BrowserAuthBeforeNavigate2(ASender: TObject; const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); procedure BrowserAuthNavigateComplete2(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); procedure NetRequestRequestError(const Sender: TObject; const AError: string); procedure AuthBtnClick(Sender: TObject); procedure NetRequestRequestCompleted(const Sender: TObject; const AResponse: IHTTPResponse); private FCodeErr: string; FMessageErr: string; FStatusErr: string; Fnickname: string; Fexpires_at: string; FStatus: string; FSuccessRedirectURL: string; Faccess_token: String; FlocationRedirect: string; Faccount_id: string; { Private declarations } procedure ParseAuth(strJSON: string); procedure GetPropertiesAuth(strAuth: string; CountSymb: integer); procedure Setaccess_token(const Value: String); procedure Setaccount_id(const Value: string); procedure SetCodeErr(const Value: string); procedure Setexpires_at(const Value: string); procedure SetlocationRedirect(const Value: string); procedure SetMessageErr(const Value: string); procedure Setnickname(const Value: string); procedure SetStatus(const Value: string); procedure SetStatusErr(const Value: string); procedure SetSuccessRedirectURL(const Value: string); function SaveHTML(Strings:TStrings; WB: TWebBrowser):boolean; public { Public declarations } published // Параметры redirect_uri при успешной аутентификации property Status: string read FStatus write SetStatus; property access_token: String read Faccess_token write Setaccess_token; property expires_at: string read Fexpires_at write Setexpires_at; property account_id: string read Faccount_id write Setaccount_id; property nickname: string read Fnickname write Setnickname; // Параметры redirect_uri при ошибке аутентификации property StatusErr: string read FStatusErr write SetStatusErr; property CodeErr: string read FCodeErr write SetCodeErr; property MessageErr: string read FMessageErr write SetMessageErr; property locationRedirect: string read FlocationRedirect write SetlocationRedirect; property SuccessRedirectURL: string read FSuccessRedirectURL write SetSuccessRedirectURL; end; var AuthForm: TAuthForm; implementation {$R *.dfm} uses Globals, SConsts, BrowserEmulationAdjuster; procedure TAuthForm.AuthBtnClick(Sender: TObject); var strReq: string; begin try LogMemo.Lines.Add('Попытка авторизации'); strReq := Format(AuthURL, [AppKey, DisplayApp, Expires_at, Nofollow]); NetRequest.MethodString := 'GET'; NetRequest.URL := strReq; NetRequest.Execute(); finally LogMemo.Lines.Add(strReq); end; end; procedure TAuthForm.BrowserAuthBeforeNavigate2(ASender: TObject; const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); begin LogMemo.Lines.Add(URL); end; procedure TAuthForm.BrowserAuthNavigateComplete2(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); begin try SuccessRedirectURL := URL; GetPropertiesAuth(SuccessRedirectURL, Length(SuccessRedirectURL)); LogMemo.Lines.Add(URL); finally LogMemo.Lines.Add('Строка успешной авторизации получена!'); end; end; procedure TAuthForm.GetPropertiesAuth(strAuth: string; CountSymb: integer); begin if CountSymb > 0 then try Status := Copy(strAuth, Pos('&status=', strAuth) + Length('&status='), Pos('&access_token=', strAuth) - (Pos('&status=', strAuth) + Length('&status='))); access_token := Copy(strAuth, Pos('&access_token=', strAuth) + Length('&access_token='), Pos('&nickname=', strAuth) - (Pos('&access_token=', strAuth) + Length('&access_token='))); nickname := Copy(strAuth, Pos('&nickname=', strAuth) + Length('&nickname='), Pos('&account_id=', strAuth) - (Pos('&nickname=', strAuth) + Length('&nickname='))); account_id := Copy(strAuth, Pos('&account_id=', strAuth) + Length('&account_id='), Pos('&expires_at=', strAuth) - (Pos('&account_id=', strAuth) + Length('&account_id='))); expires_at := Copy(strAuth, Pos('&expires_at=', strAuth) + Length('&expires_at='), CountSymb - Pos('&expires_at=', strAuth)); finally LogMemo.Lines.Add('Получение параметров завершено!'); StatusEdit.Text := Status; Access_TokenEdit.Text := access_token; Expires_AtEdit.Text := expires_at; Account_IdEdit.Text := account_id; NicknameEdit.Text := nickname; SetAuthParams(Status, access_token, expires_at, account_id, nickname); // Передача данных в глобальную запись (record) end; end; procedure TAuthForm.NetRequestRequestCompleted(const Sender: TObject; const AResponse: IHTTPResponse); begin LogMemo.Lines.Add(AResponse.ContentAsString()); ParseAuth(AResponse.ContentAsString()); BrowserAuth.Navigate2(locationRedirect); end; procedure TAuthForm.NetRequestRequestError(const Sender: TObject; const AError: string); begin LogMemo.Lines.Add('-------------------------------------------------------------------------'); LogMemo.Lines.Add('При попытке открыть ссылку произошла ошибка: ' + AError); end; procedure TAuthForm.ParseAuth(strJSON: string); var JSON: TJSONObject; begin JSON := JSON.ParseJSONValue(strJSON) as TJSONObject; try locationRedirect := ((JSON.Get('data').JsonValue as TJSONObject).Get('location')).JsonValue.Value; finally LogMemo.Lines.Add('-------------------------------------------------------------------------'); LogMemo.Lines.Add(locationRedirect); FreeAndNil(JSON); end; end; function TAuthForm.SaveHTML(Strings: TStrings; WB: TWebBrowser): boolean; var PersistStream: IPersistStreamInit; MS: TMemoryStream; Stream: IStream; SaveResult: HRESULT; begin PersistStream := WB.Document as IPersistStreamInit; MS := TMemoryStream.Create; Result:=false; try Stream := TStreamAdapter.Create(MS, soReference) as IStream; SaveResult := PersistStream.Save(Stream, True); if FAILED(SaveResult) then exit; Result:=true; MS.position:=0; Strings.LoadFromStream(MS); finally MS.Free; end; end; procedure TAuthForm.Setaccess_token(const Value: String); begin Faccess_token := Value; end; procedure TAuthForm.Setaccount_id(const Value: string); begin Faccount_id := Value; end; procedure TAuthForm.SetCodeErr(const Value: string); begin FCodeErr := Value; end; procedure TAuthForm.Setexpires_at(const Value: string); begin Fexpires_at := Value; end; procedure TAuthForm.SetlocationRedirect(const Value: string); begin FlocationRedirect := Value; end; procedure TAuthForm.SetMessageErr(const Value: string); begin FMessageErr := Value; end; procedure TAuthForm.Setnickname(const Value: string); begin Fnickname := Value; end; procedure TAuthForm.SetStatus(const Value: string); begin FStatus := Value; end; procedure TAuthForm.SetStatusErr(const Value: string); begin FStatusErr := Value; end; procedure TAuthForm.SetSuccessRedirectURL(const Value: string); begin FSuccessRedirectURL := Value; end; end.
{$I-,Q-,R-,S-} {Problema 12: Marcas RADAR [Tradicional, 2006] GJ ha estado marcando las vacas con un número serial. Están de moda las marcas `RADAR`, llamadas así porque ellas se leen igual hacia delante y hacia atrás: ellas son palíndromos. Todas las vacas quieren que sus hijas sean marcadas con el nuevo estilo. Cada madre quiere que la marca de su hija sea derivada de su propia marca no-RADAR sumando la marca de la madre y su reversa. Algunas veces (por ejemplo, 12 + 21 = 33) esto da directamente un palíndromo. Algunas veces el proceso debe ser repetido varias veces hasta que aparezca la marca RADAR. Considere la marca '87' que requiere cuatro pasos para convertirse en una marca RADAR: Marca Reverso Suma Paso 1: 87 + 78 = 165 Paso 2: 165 + 561 = 726 Paso 3: 726 + 627 = 1353 Paso 4: 1353 + 3531 = 4884 Dada la marca de la madre (un entero positivo), determine el número de pasos y la marca RADAR que resulte de aplicar el procedimiento descrito. Ninguna respuesta será mayor que dos billones. NOMBRE DEL PROBLEMA: radar FORMATO DE ENTRADA: * Línea 1: Un solo entero, la marca de la madre no palíndromo. ENTRADA EJEMPLO (archivo radar.in): 87 FORMATO DE SALIDA: * Línea 1: Dos enteros separados por espacio, que son respectivamente: el número de pasos para encontrar la marca RADAR y la marca RADAR encontrada. SALIDA EJEMPLO (archivo radar.out): 4 4884 } var fe,fs : text; n,m,sol : longint; st,t : string; c : integer; procedure open; begin assign(fe,'radar.in'); reset(fe); assign(fs,'radar.out'); rewrite(fs); readln(fe,n); close(fe); end; function palin(x : string) : boolean; var i,j : longint; begin j:=length(x); for i:=1 to (j div 2) do if (x[i] <> x[j-i+1]) then begin palin:=false; exit; end; palin:=true; end; procedure work; var i,j,k,x,y : longint; begin sol:=0; str(n,st); while (not palin(st)) do begin inc(sol); k:=length(st); t:=''; for i:=k downto 1 do begin t:=t + st[i]; end; val(st,x,c); val(t,y,c); j:=x + y; str(j,st); end; end; procedure closer; begin writeln(fs,sol,' ',st); close(fs); end; begin open; work; closer; end.
//+------------------------------------------------------------------------- // Microsoft Windows // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------- unit CMC.Inspectable; {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses Windows, Classes, SysUtils, CMC.HString; const IID_IInspectable: TGUID = '{AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90}'; type IInspectable = interface; PIInspectable = ^IInspectable; TTrustLevel = ( BaseTrust = 0, PartialTrust = (BaseTrust + 1), FullTrust = (PartialTrust + 1) ); IInspectable = interface(IUnknown) ['{AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90}'] function GetIids(out iidCount: ULONG; out iids: PGUID): HResult; stdcall; function GetRuntimeClassName(out ClassName: HSTRING): HResult; stdcall; function GetTrustLevel(out trustLevel: TTrustLevel): HResult; stdcall; end; implementation end.
{ ****************************************************************************** } { * cadencer imp library written by QQ 600585@qq.com * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit Cadencer; {$INCLUDE zDefine.inc} interface uses CoreClasses; type { Progression event for time-base animations/simulations. deltaTime is the time delta since last progress and newTime is the new time after the progress event is completed. } TCadencerProgressMethod = procedure(Sender: TObject; const deltaTime, newTime: Double) of object; TCadencerProgressCall = procedure(Sender: TObject; const deltaTime, newTime: Double); {$IFDEF FPC} TCadencerProgressProc = procedure(Sender: TObject; const deltaTime, newTime: Double) is nested; {$ELSE FPC} TCadencerProgressProc = reference to procedure(Sender: TObject; const deltaTime, newTime: Double); {$ENDIF FPC} ICadencerProgressInterface = interface procedure CadencerProgress(const deltaTime, newTime: Double); end; { This component allows auto-progression of animation. Basicly dropping this component and linking it to your app will send it real-time progression events (time will be measured in seconds) while keeping the CPU 100% busy if possible (ie. if things change in your app). The progression time (the one you'll see in you progression events) is calculated using (CurrentTime-OriginTime)*TimeMultiplier, CurrentTime being either manually or automatically updated using TimeReference (setting CurrentTime does NOT trigger progression). } TCadencer = class(TCoreClassObject) private { Private Declarations } FTimeMultiplier: Double; LastTime, DownTime, LastMultiplier: Double; FLastDeltaTime: Double; FEnabled: Boolean; FSleepLength: Integer; FCurrentTime: Double; FOriginTime: Double; FMaxDeltaTime, FMinDeltaTime, FFixedDeltaTime: Double; FOnProgress: TCadencerProgressMethod; FOnProgressCall: TCadencerProgressCall; FOnProgressProc: TCadencerProgressProc; FProgressing: Integer; FProgressIntf: ICadencerProgressInterface; protected function StoreTimeMultiplier: Boolean; procedure SetEnabled(const val_: Boolean); procedure SetTimeMultiplier(const val_: Double); procedure SetCurrentTime(const Value: Double); { Returns raw ref time (no multiplier, no offset) } function GetRawReferenceTime: Double; public constructor Create; destructor Destroy; override; { Allows to manually trigger a progression. Time stuff is handled automatically. If cadencer is disabled, this functions does nothing. } procedure Progress; { Adjusts CurrentTime if necessary, then returns its value. } function UpdateCurrentTime: Double; { Returns True if a "Progress" is underway. } function IsBusy: Boolean; { Reset the time parameters and returns to zero. } procedure Reset; { Value soustracted to current time to obtain progression time. } property OriginTime: Double read FOriginTime write FOriginTime; { Current time (manually or automatically set, see TimeReference). } property CurrentTime: Double read FCurrentTime write SetCurrentTime; { Enables/Disables cadencing. Disabling won't cause a jump when restarting, it is working like a play/pause (ie. may modify OriginTime to keep things smooth). } property Enabled: Boolean read FEnabled write SetEnabled default True; { Multiplier applied to the time reference. } property TimeMultiplier: Double read FTimeMultiplier write SetTimeMultiplier stored StoreTimeMultiplier; { Maximum value for deltaTime in progression events. If null or negative, no max deltaTime is defined, otherwise, whenever an event whose actual deltaTime would be superior to MaxDeltaTime occurs, deltaTime is clamped to this max, and the extra time is hidden by the cadencer (it isn't visible in CurrentTime either). This option allows to limit progression rate in simulations where high values would result in errors/random behaviour. } property MaxDeltaTime: Double read FMaxDeltaTime write FMaxDeltaTime; { Minimum value for deltaTime in progression events. If superior to zero, this value specifies the minimum time step between two progression events. This option allows to limit progression rate in simulations where low values would result in errors/random behaviour. } property MinDeltaTime: Double read FMinDeltaTime write FMinDeltaTime; { Fixed time-step value for progression events. If superior to zero, progression steps will happen with that fixed delta time. The progression remains time based, so zero to N events may be fired depending on the actual deltaTime (if deltaTime is inferior to FixedDeltaTime, no event will be fired, if it is superior to two times FixedDeltaTime, two events will be fired, etc.). This option allows to use fixed time steps in simulations (while the animation and rendering itself may happen at a lower or higher framerate). } property FixedDeltaTime: Double read FFixedDeltaTime write FFixedDeltaTime; { Allows relinquishing time to other threads/processes. A "sleep" is issued BEFORE each progress if SleepLength>=0 (see help for the "sleep" procedure in delphi for details). } property SleepLength: Integer read FSleepLength write FSleepLength default -1; { LastDeltaTime from progress. } property LastDeltaTime: Double read FLastDeltaTime; { backcall } property OnProgress: TCadencerProgressMethod read FOnProgress write FOnProgress; property OnProgressCall: TCadencerProgressCall read FOnProgressCall write FOnProgressCall; property OnProgressProc: TCadencerProgressProc read FOnProgressProc write FOnProgressProc; { interface } property ProgressInterface: ICadencerProgressInterface read FProgressIntf write FProgressIntf; property OnProgressInterface: ICadencerProgressInterface read FProgressIntf write FProgressIntf; end; implementation function TCadencer.StoreTimeMultiplier: Boolean; begin Result := (FTimeMultiplier <> 1); end; procedure TCadencer.SetEnabled(const val_: Boolean); begin if FEnabled <> val_ then begin FEnabled := val_; if Enabled then FOriginTime := FOriginTime + GetRawReferenceTime - DownTime else DownTime := GetRawReferenceTime; end; end; procedure TCadencer.SetTimeMultiplier(const val_: Double); var rawRef: Double; begin if val_ <> FTimeMultiplier then begin if val_ = 0 then begin LastMultiplier := FTimeMultiplier; Enabled := False; end else begin rawRef := GetRawReferenceTime; if FTimeMultiplier = 0 then begin Enabled := True; FOriginTime := rawRef - (rawRef - FOriginTime) * LastMultiplier / val_; end else FOriginTime := rawRef - (rawRef - FOriginTime) * FTimeMultiplier / val_; end; FTimeMultiplier := val_; end; end; procedure TCadencer.SetCurrentTime(const Value: Double); begin LastTime := Value - (FCurrentTime - LastTime); FOriginTime := FOriginTime + (FCurrentTime - Value); FCurrentTime := Value; end; function TCadencer.GetRawReferenceTime: Double; begin Result := GetTimeTick * 0.001; end; constructor TCadencer.Create; begin inherited Create; DownTime := GetRawReferenceTime; FOriginTime := DownTime; FTimeMultiplier := 1; LastTime := 0; LastMultiplier := 0; FLastDeltaTime := 0; FSleepLength := -1; Enabled := True; FOnProgress := nil; FOnProgressCall := nil; FOnProgressProc := nil; FProgressIntf := nil; end; destructor TCadencer.Destroy; begin while FProgressing > 0 do TCompute.Sleep(1); inherited Destroy; end; procedure TCadencer.Progress; var deltaTime, newTime, totalDelta: Double; begin { basic protection against infinite loops, } { shall never happen, unless there is a bug in user code } if FProgressing < 0 then Exit; if Enabled then begin { avoid stalling everything else... } if SleepLength >= 0 then TCoreClassThread.Sleep(SleepLength); end; AtomInc(FProgressing); try if Enabled then begin { One of the processed messages might have disabled us } if Enabled then begin { ...and progress ! } newTime := UpdateCurrentTime; deltaTime := newTime - LastTime; if (deltaTime >= MinDeltaTime) and (deltaTime >= FixedDeltaTime) then begin if FMaxDeltaTime > 0 then begin if deltaTime > FMaxDeltaTime then begin FOriginTime := FOriginTime + (deltaTime - FMaxDeltaTime) / FTimeMultiplier; deltaTime := FMaxDeltaTime; newTime := LastTime + deltaTime; end; end; totalDelta := deltaTime; if FixedDeltaTime > 0 then deltaTime := FixedDeltaTime; while totalDelta >= deltaTime do begin LastTime := LastTime + deltaTime; FLastDeltaTime := deltaTime; try if Assigned(FOnProgress) then FOnProgress(Self, deltaTime, newTime); if Assigned(FOnProgressCall) then FOnProgressCall(Self, deltaTime, newTime); if Assigned(FOnProgressProc) then FOnProgressProc(Self, deltaTime, newTime); if Assigned(FProgressIntf) then FProgressIntf.CadencerProgress(deltaTime, newTime); except end; if deltaTime <= 0 then Break; totalDelta := totalDelta - deltaTime; end; end; end; end; finally AtomDec(FProgressing); end; end; function TCadencer.UpdateCurrentTime: Double; begin Result := (GetRawReferenceTime - FOriginTime) * FTimeMultiplier; FCurrentTime := Result; end; function TCadencer.IsBusy: Boolean; begin Result := (FProgressing > 0); end; procedure TCadencer.Reset; begin LastTime := 0; DownTime := GetRawReferenceTime; FOriginTime := DownTime; end; initialization finalization end.
{==============================================================================| | Project : Ararat Synapse | 001.003.001 | |==============================================================================| | Content: Utils for FreePascal compatibility | |==============================================================================| | Copyright (c)1999-2013, Lukas Gebauer | | 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 Lukas Gebauer 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 REGENTS 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. | |==============================================================================| | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).| | Portions created by Lukas Gebauer are Copyright (c)2003-2013. | | All Rights Reserved. | |==============================================================================| | Contributor(s): | | Tomas Hajny (OS2 support) | |==============================================================================| | History: see HISTORY.HTM from distribution package | | (Found at URL: http://www.ararat.cz/synapse/) | |==============================================================================} {:@exclude} {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$H+} //old Delphi does not have MSWINDOWS define. {$IFDEF WIN32} {$IFNDEF MSWINDOWS} {$DEFINE MSWINDOWS} {$ENDIF} {$ENDIF} unit synafpc; interface uses {$IFDEF FPC} dynlibs, sysutils; {$ELSE} {$IFDEF MSWINDOWS} Windows; {$ELSE} SysUtils; {$ENDIF} {$ENDIF} {$IFDEF FPC} type TLibHandle = dynlibs.TLibHandle; function LoadLibrary(ModuleName: PChar): TLibHandle; function FreeLibrary(Module: TLibHandle): LongBool; function GetProcAddress(Module: TLibHandle; Proc: PChar): Pointer; function GetModuleFileName(Module: TLibHandle; Buffer: PChar; BufLen: Integer): Integer; {$ELSE} //not FPC type {$IFDEF CIL} TLibHandle = Integer; PtrInt = Integer; {$ELSE} TLibHandle = HModule; {$IFDEF WIN64} PtrInt = NativeInt; {$ELSE} PtrInt = Integer; {$ENDIF} {$ENDIF} {$IFDEF VER100} LongWord = DWord; {$ENDIF} {$ENDIF} procedure Sleep(milliseconds: Cardinal); implementation {==============================================================================} {$IFDEF FPC} function LoadLibrary(ModuleName: PChar): TLibHandle; begin Result := dynlibs.LoadLibrary(Modulename); end; function FreeLibrary(Module: TLibHandle): LongBool; begin Result := dynlibs.UnloadLibrary(Module); end; function GetProcAddress(Module: TLibHandle; Proc: PChar): Pointer; begin {$IFDEF OS2GCC} Result := dynlibs.GetProcedureAddress(Module, '_' + Proc); {$ELSE OS2GCC} Result := dynlibs.GetProcedureAddress(Module, Proc); {$ENDIF OS2GCC} end; function GetModuleFileName(Module: TLibHandle; Buffer: PChar; BufLen: Integer): Integer; begin Result := 0; end; {$ELSE} {$ENDIF} procedure Sleep(milliseconds: Cardinal); begin {$IFDEF MSWINDOWS} {$IFDEF FPC} sysutils.sleep(milliseconds); {$ELSE} windows.sleep(milliseconds); {$ENDIF} {$ELSE} sysutils.sleep(milliseconds); {$ENDIF} end; end.
unit fre_http_srvhandler; { (§LIC) (c) Autor,Copyright Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch FirmOS Business Solutions GmbH www.openfirmos.org New Style BSD Licence (OSI) Copyright (c) 2001-2013, FirmOS Business Solutions GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <FirmOS Business Solutions GmbH> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (§LIC_END) } //TODO: CASE SENSITIVE !! not rfc compliant {$mode objfpc}{$H+} {$INTERFACES CORBA} interface uses Classes, SysUtils,fos_strutils,FRE_DB_INTERFACE,FRE_APS_INTERFACE,FOS_FCOM_TYPES,FOS_TOOL_INTERFACES,FRE_HTTP_TOOLS,zstream; type { TFRE_HTTP_METAENTRY } TFRE_HTTP_METAENTRY = packed class ETag : String[64]; ModificationDate : TFRE_DB_DateTime64; ModFileDate : NativeUint; Size : NativeUint; ZippedSize : NativeUint; AccessOrder : NativeUint; ZipRatio : double; Cached : Boolean; ZippedExist : Boolean; HasZippedCache : Boolean; HasUnZippedCache : Boolean; InMemoryOnly : Boolean; FileExtension : String[12]; Filename : String; MimeType : String; ContentUnZipped : TMemoryStream; ContentZipped : TMemoryStream; procedure CalcRatio; procedure SetUnzippedContentFromString(const data:string); procedure PopulateZippedCacheFromUnzipped; end; IFRE_HTTP_BASESERVER=interface procedure DispatchHttpRequest (const connection_object:TObject;const uri:string ; const method: TFRE_HTTP_PARSER_REQUEST_METHOD); function FetchMetaEntry (file_path:String;var metae : TFRE_HTTP_METAENTRY):boolean; function FetchStreamDBO (const enc_sessionid, enc_uid: string; var end_field: TFRE_DB_NameTypeRL; var lcontent: TFRE_DB_RawByteString; var stored_ct: TFRE_DB_String; var stored_etag: TFRE_DB_String): boolean; function GetETag (const filename: string; const filesize: NativeUint;const moddate: TFRE_DB_DateTime64):String; end; { TFRE_HTTP_CONNECTION_HANDLER } TFRE_HTTP_PARSER_REQ_STATE = (rprs_PARSEREQ_LINE,rprs_PARSE_HEADERS,rprs_PARSEBODY,rprs_DISPATCHREQUEST); TFRE_HTTP_PARSER_ERROR = (rpe_OK,rpe_CONTINUE,rpe_INVALID_REQ_LINE,rpe_INVALID_REQUEST); TFRE_HTTP_ResponseHeaders = (rh_AcceptRanges,rh_Age,rh_ETag,rh_Location,rh_ProxyAuth,rh_ReryAfter,rh_Server,rh_Vary,rh_WWWAuth,rh_contentDisposition); TFRE_HTTP_ResponseEntityHeaders = (reh_Allow,reh_ContentEncoding,reh_ContentLanguage,reh_ContentLength,reh_ContentMD5,reh_ContentRange,reh_ContentType,reh_Origin, reh_Expires,reh_LastModified,reh_Connection,reh_CacheControl,reh_SetCookie,reh_Upgrade,reh_SecWebSocketAccept,reh_SecWebSocketProtocol,reh_SecWebSocketVersion, reh_old_SecWebSocketOrigin,reh_old_SecWebSocketLocation); const CFRE_HTTP_ResponseHeaders : Array [TFRE_HTTP_ResponseHeaders] of String = ('Accept-Ranges','Age','ETag','Location','Proxy-Authenticate','Retry-After','Server','Vary','WWW-Authenticate','Content-Disposition'); CFRE_HTTP_ResponseEntityHeaders : Array [TFRE_HTTP_ResponseEntityHEaders] of String = ('Allow','Content-Encoding','Content-Language','Content-Length','Content-MD5', 'Content-Range','Content-Type','Origin','Expires','Last-Modified','Connection','Cache-Control','Set-Cookie','Upgrade','Sec-WebSocket-Accept','Sec-WebSocket-Protocol','Sec-WebSocket-Version', 'Sec-WebSocket-Origin','Sec-WebSocket-Location'); type TFRE_HTTP_CONNECTION_HANDLER=class private FInternalState : TFRE_HTTP_PARSER_REQ_STATE; FRequest : String; FRequestURIPos : integer; FRequestURILen : integer; FRequestVersionPos : integer; FRequestVersionLen : integer; FHeaderPos : integer; FHeaderLen : integer; FContentLenght : integer; FHost : string; FContentStart : integer; FHasContent : boolean; FResponse : String; FSSL_Enabled : boolean; FResponseHeaders : Array[TFRE_HTTP_ResponseHeaders] of String; FResponseEntityHeaders : Array[TFRE_HTTP_ResponseEntityHEaders] of String; FHttpBase : IFRE_HTTP_BASESERVER; FReqErrorState : TFRE_HTTP_PARSER_ERROR; function GetResponseEntityHeader(idx: TFRE_HTTP_ResponseEntityHeaders): String; function GetResponseHeader(idx: TFRE_HTTP_ResponseHeaders): String; procedure SetResponseEntityHeader(idx: TFRE_HTTP_ResponseEntityHeaders; const AValue: String); procedure SetResponseHeader(idx: TFRE_HTTP_ResponseHeaders; const AValue: String); protected FChannel : IFRE_APSC_CHANNEL; function GetContent : String; function GetRequestHeaders : string; function GetRequestUri : string; function GetRequestVersion : string; function GetHeaderField (const fieldname:String):string; procedure NotFound ; procedure Unsupported ; procedure InitForNewRequest ; procedure SetResponseStatusLine (const StatusCode:integer; const ReasonPhrase:String); procedure SetResponseHeaders ; procedure SetEntityHeaders ; procedure SetETagandLastModified (const filename:string; const filesize:NativeUint; const moddate:TFRE_DB_DateTime64); procedure SetBody (const data:string); procedure SendResponse ; procedure HttpRequest (const method:TFRE_HTTP_PARSER_REQUEST_METHOD); procedure DispatchRequest (const uri:string ; const method: TFRE_HTTP_PARSER_REQUEST_METHOD); virtual; public FRequestMethod : TFRE_HTTP_PARSER_REQUEST_METHOD; public function HttpBaseServer :IFRE_HTTP_BASESERVER; function Response : string; constructor Create (const channel:IFRE_APSC_CHANNEL ; const http_server : IFRE_HTTP_BASESERVER;const ssl_enabled : Boolean=false); procedure ReadChannelData (const channel:IFRE_APSC_CHANNEL);virtual; procedure DisconnectChannel (const channel:IFRE_APSC_CHANNEL);virtual; function RawRequest :String; function FindOldWS_HickseyContent : String; property RequestUri :string read GetRequestUri; property RequestVersion :string read GetRequestVersion; property RequestHeaders :string read GetRequestHeaders; property RequestContent :String read GetContent; property RequestHost :string read FHost; property ResponseHeader [idx:TFRE_HTTP_ResponseHeaders] : String read GetResponseHeader write SetResponseHeader; property ResponseEntityHeader [idx:TFRE_HTTP_ResponseEntityHeaders] : String read GetResponseEntityHeader write SetResponseEntityHeader; end; implementation { TFRE_HTTP_METAENTRY } procedure TFRE_HTTP_METAENTRY.CalcRatio; begin if ZippedSize=0 then ZipRatio:=0 else ZipRatio := 100-GFRE_BT.RatioPercent(ZippedSize,Size); end; procedure TFRE_HTTP_METAENTRY.SetUnzippedContentFromString(const data: string); begin ContentUnZipped := TMemoryStream.Create; ContentUnZipped.SetSize(Length(data)); Move(data[1],ContentUnZipped.Memory^,ContentUnZipped.Size); HasUnZippedCache := true; end; procedure TFRE_HTTP_METAENTRY.PopulateZippedCacheFromUnzipped; var zstream : Tcompressionstream; begin ContentZipped.Free; ContentZipped := TMemoryStream.Create; zstream := Tcompressionstream.Create(cldefault,ContentZipped); try zstream.CopyFrom(ContentUnZipped,0); zstream.free; ZippedSize := ContentZipped.Size; HasZippedCache := true; finally // zstream.free; end; end; { TOffloadWriteObject } { TFRE_HTTP_CONNECTION_HANDLER } function TFRE_HTTP_CONNECTION_HANDLER.GetRequestUri: string; begin result := Copy(FRequest,FRequestURIPos,FRequestURILen); end; function TFRE_HTTP_CONNECTION_HANDLER.GetResponseHeader(idx: TFRE_HTTP_ResponseHeaders): String; begin result := FResponseHeaders[idx]; end; function TFRE_HTTP_CONNECTION_HANDLER.GetResponseEntityHeader(idx: TFRE_HTTP_ResponseEntityHeaders): String; begin result := FResponseEntityHeaders[idx]; end; procedure TFRE_HTTP_CONNECTION_HANDLER.SetResponseEntityHeader(idx: TFRE_HTTP_ResponseEntityHeaders; const AValue: String); begin FResponseEntityHeaders[idx] := AValue; end; procedure TFRE_HTTP_CONNECTION_HANDLER.SetResponseHeader(idx: TFRE_HTTP_ResponseHeaders; const AValue: String); begin FResponseHeaders[idx] := AValue; end; function TFRE_HTTP_CONNECTION_HANDLER.GetContent: String; begin if FHasContent then begin result := Copy(FRequest,FContentStart,FContentLenght); end; end; function TFRE_HTTP_CONNECTION_HANDLER.GetRequestHeaders: string; begin result := Copy(FRequest,FHeaderPos,FHeaderLen); end; function TFRE_HTTP_CONNECTION_HANDLER.GetRequestVersion: string; begin result := Copy(FRequest,FRequestVersionPos,FRequestVersionLen); end; function TFRE_HTTP_CONNECTION_HANDLER.GetHeaderField(const fieldname: String): string; var lStart,lEnd,lNamelen:integer; begin result:=''; lStart := fos_posEx(fieldname+':',FRequest,FHeaderPos); if lStart>0 then begin lNamelen := Length(fieldname)+1; lStart := lStart+lNamelen; lEnd := fos_posEx(#13#10,FRequest,lStart); //TODO -> FOLDED HEADER FIELDS (LWS) result := trim(Copy(FRequest,lStart,lEnd-lStart)); end; end; procedure TFRE_HTTP_CONNECTION_HANDLER.Unsupported; begin SetResponseStatusLine(500,'FOS SRV UNSUPPORTED REQUEST'); ResponseEntityHeader[reh_ContentLength]:='0'; ResponseEntityHeader[reh_ContentType]:=''; SetResponseHeaders; SetEntityHeaders; SetBody(''); SendResponse; end; procedure TFRE_HTTP_CONNECTION_HANDLER.NotFound; begin SetResponseStatusLine(404,'FOS SRV OBJECT NOT FOUND'); ResponseEntityHeader[reh_ContentLength]:='0'; ResponseEntityHeader[reh_ContentType]:=''; SetResponseHeaders; SetEntityHeaders; SetBody(''); SendResponse; end; procedure TFRE_HTTP_CONNECTION_HANDLER.InitForNewRequest; begin FInternalState := rprs_PARSEREQ_LINE; FContentLenght := -1; FHeaderPos := -1; FHeaderLen := -1; FContentStart := -1; FRequest := ''; FHasContent := false; FRequestURIPos := -1; FRequestURILen := -1; FResponse := ''; end; procedure TFRE_HTTP_CONNECTION_HANDLER.SetResponseStatusLine(const StatusCode: integer; const ReasonPhrase: String); begin FResponse:='HTTP/1.1 '+Inttostr(StatusCode)+' '+ReasonPhrase+#13#10; end; procedure TFRE_HTTP_CONNECTION_HANDLER.SetResponseHeaders; var i : TFRE_HTTP_ResponseHeaders; begin for i in TFRE_HTTP_ResponseHeaders do begin if FResponseHeaders[i]<>'' then begin FResponse:=Fresponse+CFRE_HTTP_ResponseHeaders[i]+': '+FResponseHeaders[i]+#13#10; end; end; end; procedure TFRE_HTTP_CONNECTION_HANDLER.SetEntityHeaders; var i : TFRE_HTTP_ResponseEntityHeaders; begin for i in TFRE_HTTP_ResponseEntityHeaders do begin if FResponseEntityHeaders[i]<>'' then begin if i=reh_ContentType then begin FResponse:=Fresponse+CFRE_HTTP_ResponseEntityHeaders[i]+': '+FResponseEntityHeaders[i]+'; charset=utf-8'+#13#10; end else begin FResponse:=Fresponse+CFRE_HTTP_ResponseEntityHeaders[i]+': '+FResponseEntityHeaders[i]+#13#10; end; end; end; end; procedure TFRE_HTTP_CONNECTION_HANDLER.SetETagandLastModified(const filename: string; const filesize: NativeUint;const moddate: TFRE_DB_DateTime64); begin ResponseEntityHeader[reh_LastModified] := GFRE_DT.ToStrHTTP(moddate); ResponseHeader[rh_ETag] := HttpBaseServer.GetETag(filename,filesize,moddate); end; procedure TFRE_HTTP_CONNECTION_HANDLER.SetBody(const data: string); begin FResponse:=FResponse+#13#10+data; end; procedure TFRE_HTTP_CONNECTION_HANDLER.SendResponse; var i : TFRE_HTTP_ResponseEntityHeaders; lResponse:string; lPos:integer; begin GFRE_DBI.LogInfo(dblc_HTTP_RES,'< [%s] [%s] [Answerlen: %d]',[GFRE_BT.SepLeft(FResponse,#13#10),FChannel.ch_GetVerboseDesc,Length(FResponse)]); //GFRE_DBI.LogDebug(dblc_HTTP_RES,FResponse); FChannel.CH_WriteString(FResponse); end; procedure TFRE_HTTP_CONNECTION_HANDLER.HttpRequest(const method: TFRE_HTTP_PARSER_REQUEST_METHOD); begin try if not assigned(HttpBaseServer) then begin DispatchRequest(RequestHost+RequestUri,method); end else begin HttpBaseServer.DispatchHttpRequest(self, RequestHost+RequestUri,method); end; except on E:Exception do begin writeln('HTTP: ERROR : 500 ERROR ON DISPATCH REQUEST '+e.Message); SetResponseStatusLine(500,'ERROR ON DISPATCH REQUEST '+e.Message); ResponseEntityHeader[reh_ContentLength]:='0'; ResponseEntityHeader[reh_ContentType]:=''; SetResponseHeaders; SetEntityHeaders; SetBody(''); SendResponse; end; end; end; procedure TFRE_HTTP_CONNECTION_HANDLER.DispatchRequest(const uri: string; const method: TFRE_HTTP_PARSER_REQUEST_METHOD); begin abort; end; function TFRE_HTTP_CONNECTION_HANDLER.HttpBaseServer: IFRE_HTTP_BASESERVER; begin result := FHttpBase; end; function TFRE_HTTP_CONNECTION_HANDLER.Response: string; begin result := FResponse; end; constructor TFRE_HTTP_CONNECTION_HANDLER.Create(const channel: IFRE_APSC_CHANNEL; const http_server: IFRE_HTTP_BASESERVER; const ssl_enabled: Boolean); begin FChannel := channel; FSSL_Enabled := ssl_enabled; InitForNewRequest; FResponseHeaders [rh_Server]:='FirmOS FRE HTTP Engine'; FResponseEntityHeaders [reh_ContentLength]:='0'; FHttpBase := http_server; end; procedure TFRE_HTTP_CONNECTION_HANDLER.ReadChannelData(const channel: IFRE_APSC_CHANNEL); var data : string; lContinue : boolean; lActualPos : integer; lReqLineLen : integer; label cont; procedure _ParseReqLine; var lLineend : integer; lSpacePos : integer; function _RestCheck(const position,needed : integer):boolean; begin result := position+needed <= lReqLineLen; end; begin lLineend := pos(#13#10,FRequest); if lLineend=0 then exit; //stay in state lActualPos := 1 ; if fos_posEx('GET',FRequest,lActualPos)=1 then begin FRequestMethod := rprm_GET; inc(lActualPos,4); end else if fos_posEx('POST',FRequest,lActualPos)=1 then begin FRequestMethod := rprm_POST; inc(lActualPos,5); end else if fos_posEx('PUT',FRequest,lActualPos)=1 then begin FRequestMethod := rprm_PUT; inc(lActualPos,4); end else if fos_posEx('OPTIONS',FRequest,lActualPos)=1 then begin FRequestMethod := rprm_OPTIONS; inc(lActualPos,8); end else if fos_posEx('DELETE',FRequest,lActualPos)=1 then begin FRequestMethod := rprm_DELETE; inc(lActualPos,7); end else if fos_posEx('HEAD',FRequest,lActualPos)=1 then begin FRequestMethod := rprm_HEAD; inc(lActualPos,5); end else if fos_posEx('TRACE',FRequest,lActualPos)=1 then begin FRequestMethod := rprm_TRACE; inc(lActualPos,6); end else if fos_posEx('CONNECT',FRequest,lActualPos)=1 then begin FRequestMethod := rprm_CONNECT; inc(lActualPos,8); end else begin FReqErrorState := rpe_INVALID_REQUEST; exit; end; //writeln('REQUEST MODE - ',FRequestMethod); lSpacePos:=fos_posEx(' ',FRequest,lActualPos); if lSpacePos>1 then begin FRequestURIPos := lActualPos; FRequestURILen := lSpacePos-lActualPos; //writeln('REQUEST URI : ',RequestUri); inc(lActualPos,FRequestURILen+1); end else begin FReqErrorState := rpe_INVALID_REQUEST; exit; end; lSpacePos:=fos_posEx(#13#10,FRequest,lActualPos); if lSpacePos>1 then begin FRequestVersionPos := lActualPos; FRequestVersionLen := lSpacePos-lActualPos; //writeln('REQUEST VERSION : ',RequestVersion); inc(lActualPos,FRequestVersionLen+2); end else begin FReqErrorState := rpe_INVALID_REQUEST; exit; end; //writeln(lActualPos,'/',lReqLineLen); FInternalState := rprs_PARSE_HEADERS; FHeaderPos := lActualPos; lContinue := lActualPos<lReqLineLen; end; procedure _ParseHeaders; var lHeaderEndPos:integer; procedure _EvaluateHeaders; begin FContentLenght := StrToIntDef(GetHeaderField('Content-Length'),-1); FHost := GetHeaderField('Host'); end; begin // writeln('>>PARSEHEADERS ',FHeaderPos); if FHeaderPos=-1 then begin FHeaderPos:=fos_posEx(#13#10,FRequest)+2; if FHeaderPos<=1 then GFRE_BT.CriticalAbort('LOGIC FAILURE'); end; lActualPos := FHeaderPos; lHeaderEndPos := fos_posEx(#13#10#13#10,FRequest,lActualPos); if lHeaderEndPos > 1 then begin FHeaderLen := lHeaderEndPos-lActualPos; FContentStart := lHeaderEndPos+4; // Theoretical Content Start //writeln('HEADERS'); //writeln(RequestHeaders); _EvaluateHeaders; //writeln('CLEN ',FContentLenght); end; lContinue := lReqLineLen>=(lHeaderEndPos+3); FInternalState := rprs_PARSEBODY; //writeln('>>PARSEHEADERS ',lContinue,' ',lReqLineLen,' ',lHeaderEndPos,' ',lHeaderEndPos+3); end; procedure _ParseBody; begin //writeln('--- PARSEBODY ---'); if FContentLenght<>-1 then begin if lReqLineLen+1-(FContentStart+FContentLenght)>=0 then begin FHasContent:=true; end else begin FReqErrorState := rpe_CONTINUE; exit; end; end else begin FHasContent := false; end; FInternalState := rprs_DISPATCHREQUEST; lContinue := True; end; procedure _DispatchRequest; begin //FMyCookie.CookieString:=GetHeaderField('Cookie'); GFRE_DBI.LogInfo(dblc_HTTP_REQ,'> %s [%s]',[GFRE_BT.SepLeft(FRequest,#13#10),FChannel.ch_GetVerboseDesc]); GFRE_DBI.LogDebug(dblc_HTTP_REQ,'%s',[GFRE_BT.SepLeft(FRequest,#13#10#13#10)]); HttpRequest(FRequestMethod); InitForNewRequest; FInternalState:=rprs_PARSEREQ_LINE; end; begin FReqErrorState := rpe_OK; FRequest := FRequest + channel.CH_ReadString; lReqLineLen := Length(FRequest); //writeln('REQ::: '); //writeln(FRequest); //if datalen=0 then GFRE_BT.CriticalAbort('DATA LEN 0'); cont: lContinue := false; case FInternalState of rprs_PARSEREQ_LINE : _ParseReqline; rprs_PARSE_HEADERS : _ParseHeaders; rprs_PARSEBODY : _ParseBody; rprs_DISPATCHREQUEST : _DispatchRequest; else begin writeln('LOGIC STATE FAILURE ',FInternalState,' ',NativeUint(self)); abort; end; end; if lContinue then begin // writeln('Continuing... ',FInternalState); goto cont; end; //writeln('ERRORSTATE : ',Result); end; procedure TFRE_HTTP_CONNECTION_HANDLER.DisconnectChannel(const channel: IFRE_APSC_CHANNEL); begin end; function TFRE_HTTP_CONNECTION_HANDLER.RawRequest: String; begin result := FRequest; end; function TFRE_HTTP_CONNECTION_HANDLER.FindOldWS_HickseyContent: String; var lpos:integer; begin lpos := Pos(#13#10#13#10,FRequest); if lpos >0 then begin result := Copy(FRequest,lpos+4,maxint); end; end; end.
unit Unit2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,COMObj, KompasAPI7_TLB,Kompas6Constants_TLB,Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.jpeg, Vcl.ExtCtrls; type TForm2 = class(TForm) Button1: TButton; Image1: TImage; Label1: TLabel; Label2: TLabel; Label3: TLabel; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; d2,da2,df2,Lcm2, Dcm2,Dd2, q1,q2,b2,m,z,Dv2,h: extended; tolTable : ITable; txt : ITextLine; cell : ITableCell; procedure Kompas(d2,da2,df2,Lcm2, Dcm2,Dd2, q1,q2,b2,m,z,Dv2,h: extended); procedure SponkaCalc(out W, H: Extended); implementation {$R *.dfm} procedure SetToleranceText( tolPar : IToleranceParam ); var tolTable : ITable; txt : ITextLine; cell : ITableCell; begin if ( tolPar <> nil ) then begin // Получить интерфейс таблицы с текстом допуска формы tolTable := tolPar.Table; if ( tolTable <> nil ) then begin // Добавить 3 столбца (1 уже есть) //tolTable.AddColumn( -1, TRUE {справа} ); // tolTable.AddColumn( -1, TRUE {справа} ); // tolTable.AddColumn( -1, TRUE {справа} ); // Записать текст в 1-ю ячейку cell := tolTable.Cell[ 0, 0 ]; if ( cell <> nil ) then begin txt:= cell.Text As ITextLine; if ( txt <> nil ) then txt.Str := 'A'; end; // Записать текст во 2-ю ячейку cell := tolTable.Cell[ 0, 1 ]; if ( cell <> nil ) then begin txt := cell.Text As ITextLine; if ( txt <> nil ) then txt.Str := '@27~'; end; // Записать текст в 3-ю ячейку cell := tolTable.Cell[ 0, 2 ]; if ( cell <> nil ) then begin txt := cell.Text As ITextLine; if ( txt <> nil ) then txt.Str := '@26~'; end; // Записать текст в 4-ю ячейку cell := tolTable.Cell[ 0, 3 ]; if ( cell <> nil ) then begin txt := cell.Text As ITextLine; if ( txt <> nil ) then txt.Str := '@25~'; end; end; end; end; function AddLine(LSS: ILineSegments; X1, Y1, X2, Y2: extended): ILineSegment; var LS: ILineSegment; begin LS := LSS.Add; LS.X1 := X1; LS.Y1 := Y1; LS.X2 := X2; LS.Y2 := Y2; LS.Style := ksCSNormal; LS.Update; Result := LS; end; function AddLine2(LSS: ILineSegments; X1, Y1, X2, Y2: extended): ILineSegment; var LS: ILineSegment; begin LS := LSS.Add; LS.X1 := X1; LS.Y1 := Y1; LS.X2 := X2; LS.Y2 := Y2; LS.Style := ksCSAxial; LS.Update; Result := LS; end; function AddLineAxial(LSS: ILineSegments; X1, Y1, X2, Y2: extended) : ILineSegment; var LS: ILineSegment; begin LS := LSS.Add; LS.X1 := X1; LS.Y1 := Y1; LS.X2 := X2; LS.Y2 := Y2; LS.Style := ksCSThin; LS.Update; Result := LS; end; function AddLineAxial2(LSS: ILineSegments; X1, Y1, X2, Y2: extended) : ILineSegment; var LS: ILineSegment; begin LS := LSS.Add; LS.X1 := X1; LS.Y1 := Y1; LS.X2 := X2; LS.Y2 := Y2; LS.Style := ksCSAxial; LS.Update; Result := LS; end; function AddArc(Arcs: IArcs; Xc, Yc, R: extended): IArc; var Arc: IArc; begin Arc := Arcs.Add; Arc.Xc := Xc; Arc.Yc := Yc; Arc.Radius := R; Arc.Angle1 := 0; Arc.Angle2 := 360; Arc.Style := ksCSNormal; Arc.Update; Result := Arc; end; function AddArc1(Arcs: IArcs; Xc, Yc, R: extended): IArc; var Arc: IArc; begin Arc := Arcs.Add; Arc.Xc := Xc; Arc.Yc := Yc; Arc.Radius := R; Arc.Angle1 := 0; Arc.Angle2 := 360; Arc.Style := ksCSAxial; Arc.Update; Result := Arc; end; function AddLine1(LSS: ILineDimensions; X1, Y1, X2, Y2, X3, Y3: extended): ILineDimension; var LS2: ILineDimension; begin LS2 := LSS.Add; LS2.X1 := X1; LS2.Y1 := Y1; LS2.X2 := X2; LS2.Y2 := Y2; LS2.X3 := X3; LS2.Y3 := Y3; LS2.Update; Result := LS2; end; function AddArcAxial(Arcs: IArcs; X1, Y1, X2, Y2, X3, Y3: extended): IArc; var Arc: IArc; begin Arc := Arcs.Add; Arc.X1 := X1; Arc.Y1 := Y1; Arc.X2 := X2; Arc.Y2 := Y2; Arc.X3 := X3; Arc.Y3 := Y3; Arc.Style := ksCSNormal; Arc.Update; Result := Arc; end; function Addarv(LSS: IDiametralDimensions; X1, Y1, X2: extended) : IDiametralDimension; var LS2: IDiametralDimension; begin LS2 := LSS.Add; LS2.Xc := X1; LS2.Yc := Y1; LS2.DimensionType := False; LS2.Radius := X2; LS2.Angle := 80; LS2.Update; Result := LS2; end; procedure SponkaCalc(out W, H: Extended); begin if (dv2 > 12) and (dv2 <= 17) then begin W:=5; H:=2.3; end else if (dv2 > 17) and (dv2 <= 22) then begin W:=6; H:=2.8; end else if (dv2 > 22) and (dv2 <= 30) then begin W:=8; H:=3.3; end else if (dv2 > 30) and (dv2 <= 38) then begin W:=10; H:=3.3; end else if (dv2 > 38) and (dv2 <= 44) then begin W:=12; H:=3.3; end else if (dv2 > 44) and (dv2 <= 50) then begin W:=14; H:=3.8; end else if (dv2 > 50) and (dv2 <= 58) then begin W:=16; H:=4.3; end else if (dv2 > 58) and (dv2 <= 65) then begin W:=18; H:=4.4; end else if (dv2 > 65) and (dv2 <= 75) then begin W:=20; H:=4.9; end else if (dv2 > 75) and (dv2 <= 85) then begin W:=22; H:=5.4; end else if (dv2 > 85) and (dv2 <= 95) then begin W:=25; H:=5.4; end else ShowMessage('Невозможно подобрать параметры шпоночного паза'); end; procedure Kompas; var j, G, x0, y0, Y2, X2, X3, Y3, Ab, Bc, X1, Y1, De, Fg,D5,t1,t2: extended; KP: IApplication; KD: IKompasDocument; DP: IDispatch; LSS: ILineSegments; Arcs: IArcs; AW: IView; es: ICircles; Fd: IDiametralDimensions; Fd2: IRadialDimensions; Skk: ILineDimensions; dimText: IDimensionText; dimParam: IDimensionParams; LineSeg: array [0 .. 45] of ILineSegment; LineSeg2: array [0 .. 30] of ILineDimension; ArcSeg: array [0 .. 20] of IArc; Fds: array [0 .. 20] of IDiametralDimension; branchs: IBranchs; baseLeader: IBaseLeader; leader: Ileader; tx1,tx2,tx3: IText; rounghs:IRoughs ; roughPar : IRoughParams; symbCont: ISymbols2DContainer; leadersCol: ILeaders; lead: Ileader; bLeader: IBaseLeader; center: ICentreMarkers ; hat:IHatch; hatpar:IHatchParam; hats:IHatches; toler: ITolerance; tolers: ITolerances; tolerpar: IToleranceParam; begin x0 := 130; y0 := 170; KP := Co_Application.Create; KP.Visible := true; KD := KP.Documents.Add(ksDocumentDrawing, true); KD := KP.ActiveDocument; KD.LayoutSheets.Item[0].Format.Format := ksFormatUser; KD.LayoutSheets.Item[0].Format.FormatWidth := 420; KD.LayoutSheets.Item[0].Format.FormatHeight := 297; KD.LayoutSheets.Item[0].Update; AW := (KD as IDrawingDocument).ViewsAndLayersManager.Views.ActiveView; LSS := ((KD as IDrawingDocument).ViewsAndLayersManager.Views.ActiveView as IDrawingContainer).LineSegments; Skk := (AW as ISymbols2DContainer).LineDimensions; Fd := (AW as ISymbols2DContainer).DiametralDimensions; Arcs := ((KD as IDrawingDocument).ViewsAndLayersManager.Views.ActiveView as IDrawingContainer).Arcs; rounghs:=(AW as ISymbols2DContainer).Roughs; center:= (AW as ISymbols2DContainer).CentreMarkers; hats:=((KD as IDrawingDocument).ViewsAndLayersManager.Views.ActiveView as IDrawingContainer).Hatches as IHatches; tolers:= (AW as ISymbols2DContainer).Tolerances; ArcSeg[1] := AddArc(Arcs, x0, y0, dv2/2); ArcSeg[2] := AddArc(Arcs, x0, y0, dcm2/2); // окружность ArcSeg[3] := AddArc(Arcs, x0, y0, (df2-q1)/2); ArcSeg[4] := AddArc(Arcs, x0, y0, df2/2); ArcSeg[5] := AddArc1(Arcs, x0, y0, d2/2); // осевая окружность ArcSeg[6] := AddArc(Arcs, x0, y0, da2/2); LineSeg2[2] := AddLine1(Skk, x0 + da2 / 2+30+Lcm2/2+b2/2, y0 + da2/2, x0 + da2 / 2+30+Lcm2/2+b2/2, y0 - da2/2, x0 + da2 / 2+80+Lcm2+b2/2, y0 ); dimText:=LineSeg2[2] as Idimensiontext; dimText.Prefix.Str:='@2~' ; LineSeg2[2].Update; LineSeg[3] := AddLine2(LSS, x0 + da2 / 2 + 20, y0, x0 + da2 / 2 +Lcm2+ 40, y0);//осевая прямая линия LineSeg[4] := AddLine(LSS, x0 + da2 / 2+30, y0 + dv2 / 2, x0 + da2 / 2+30, y0 +Dcm2/2); LineSeg[5] := AddLine(LSS, x0 + da2 / 2+30, y0 +Dcm2/2, x0 + da2 / 2+30+(Lcm2-q2)/2, y0 +Dcm2/2); LineSeg[6] := AddLine(LSS, x0 + da2 / 2+30+(Lcm2-q2)/2, y0 +Dcm2/2, x0 + da2 / 2+30+(Lcm2-q2)/2, y0 +df2/2-q1); LineSeg[7] := AddLine(LSS, x0 + da2 / 2+30+(Lcm2-q2)/2, y0 +df2/2-q1, x0 + da2 / 2+30+(Lcm2-b2)/2, y0 +df2/2-q1); LineSeg[8] := AddLine(LSS, x0 + da2 / 2+30+(Lcm2-b2)/2, y0 +df2/2-q1, x0 + da2 / 2+30+(Lcm2-b2)/2, y0 +da2/2); LineSeg[9] := AddLine(LSS, x0 + da2 / 2+30+(Lcm2-b2)/2, y0 +da2/2, x0 + da2 / 2+30+b2+(Lcm2-b2)/2, y0 +da2/2); LineSeg[10] := AddLine(LSS, x0 + da2 / 2+30+b2+(Lcm2-b2)/2, y0 +da2/2, x0 + da2 / 2+30+b2+(Lcm2-b2)/2, y0 + df2/2-q1); LineSeg[11] := AddLine(LSS, x0 + da2 / 2+30+b2+(Lcm2-b2)/2, y0 +df2/2-q1, x0 + da2 / 2+30+(Lcm2-q2)/2+q2, y0+df2/2-q1); LineSeg[12] := AddLine(LSS, x0 + da2 / 2+30+(Lcm2-q2)/2+q2, y0 +df2/2-q1, x0 + da2 / 2+30+(Lcm2-q2)/2+q2, y0 +Dcm2/2); LineSeg[13] := AddLine(LSS, x0 + da2 / 2+30+(Lcm2-q2)/2+q2, y0 +Dcm2/2, x0 + da2 / 2+30+Lcm2, y0 +Dcm2/2); LineSeg[14] := AddLine(LSS, x0 + da2 / 2+30+Lcm2, y0 +Dcm2/2, x0 + da2 / 2+30+Lcm2, y0 +dv2/2); LineSeg[15] := AddLine(LSS, x0 + da2 / 2+30+Lcm2, y0 +dv2/2, x0 + da2 / 2+30, y0 + dv2 / 2); LineSeg[16] := AddLine(LSS, x0 + da2 / 2+30+(Lcm2-b2)/2, y0 + df2/2, x0 + da2 / 2+30+(Lcm2-b2)/2+b2, y0 + df2/2); LineSeg[17] := AddLine2(LSS, x0 + da2 / 2+30+(Lcm2-b2)/2, y0+d2/2, x0 + da2 / 2+30+(Lcm2-b2)/2+b2, y0+d2/2); LineSeg2[18] := AddLine1(Skk, x0 + da2 / 2+30+Lcm2/2+b2/2, y0 + d2/2, x0 + da2 / 2+30+Lcm2/2+b2/2, y0 - d2/2, x0 + da2 / 2+70+Lcm2+b2/2, y0 ); dimText:=LineSeg2[18] as Idimensiontext; dimText.Prefix.Str:='@2~' ; LineSeg2[18].Update; LineSeg2[19] := AddLine1(Skk, x0 + da2 / 2+30+Lcm2, y0 +dv2/2, x0 + da2 / 2+30, y0 + dv2 / 2, x0 + da2 / 2+30+Lcm2/2, y0 -dcm2/2); LineSeg2[20] := AddLine1(Skk, x0 + da2 / 2+30+(Lcm2-q2)/2, y0 +Dcm2/2, x0 + da2 / 2+30+(Lcm2-q2)/2+q2, y0 +Dcm2/2, x0 + da2 / 2+30+Lcm2/2+q2, y0 +Dcm2/2+3); LineSeg2[21] := AddLine1(Skk, x0 + da2 / 2+30+Lcm2, y0 +dv2/2, x0 + da2 / 2+30+Lcm2, y0 -Dv2/2, x0 + da2 / 2+45+Lcm2, y0 ); dimText:=LineSeg2[21] as Idimensiontext; dimText.Prefix.Str:='@2~' ; LineSeg2[21].Update; LineSeg2[22] := AddLine1(Skk, x0 + da2 / 2+30+Lcm2, y0 +dcm2/2, x0 + da2 / 2+30+Lcm2, y0 -Dcm2/2, x0 + da2 / 2+55+Lcm2, y0 ); dimText:=LineSeg2[22] as Idimensiontext; dimText.Prefix.Str:='@2~' ; LineSeg2[22].Update; LineSeg2[23] := AddLine1(Skk, x0 + da2 / 2+30+(Lcm2-b2)/2+b2, y0 + df2/2, x0 + da2 / 2+30+(Lcm2-b2)/2+b2, y0 - df2/2, x0 + da2 / 2+65+Lcm2, y0 ); dimText:=LineSeg2[23] as Idimensiontext; dimText.Prefix.Str:='@2~' ; LineSeg2[23].Update; LineSeg2[24] := AddLine1(Skk, x0 + da2 / 2+30+(Lcm2-b2)/2+b2, y0 + df2/2, x0 + da2 / 2+30+b2+(Lcm2-b2)/2, y0 +df2/2-q1, x0 + da2 / 2+40, (y0 + df2/2-y0 -(df2-q1)/2)/2+y0 +(df2-q1)/2 ); LineSeg[25] := AddLine2(LSS, x0 + da2 / 2 + 10, y0, x0 - da2 / 2 - 10, y0); //осевые у окружности LineSeg[26] := AddLine2(LSS, x0 , y0+ da2 / 2 + 10, x0, y0 - da2 / 2 - 10); SponkaCalc(T1,T2); LineSeg[27] := AddLine(LSS, x0 -t1/2, y0 + dv2 / 2-t2/2, x0 - t1/2, y0 +dv2 / 2+t2/2); LineSeg[28] := AddLine(LSS, x0 - t1/2, y0 +dv2 / 2+t2/2, x0 + t1/2, y0 +dv2 / 2+t2/2); LineSeg[29] := AddLine(LSS, x0 + t1/2, y0 +dv2 / 2+t2/2, x0 +t1/2, y0 + dv2 / 2-t2/2); LineSeg[30] := AddLine(LSS, x0 - t1/2, y0 +dv2 / 2-t2/2, x0 + t1/2, y0 +dv2 / 2-t2/2); LineSeg[31] := AddLine(LSS, x0 + da2 / 2+30, y0 +dv2 / 2+t2/2, x0 + da2 / 2+30+Lcm2, y0 +dv2 / 2+t2/2); rounghs.Add; //шероховатость rounghs.Rough[0].X0:=x0+200; rounghs.Rough[0].Y0:=y0+100; roughPar := rounghs.Rough[0] As IRoughParams; roughPar.ProcessingByContour:=false; roughPar.ArrowInside:=true; tx1:=roughPar.RoughParamText; if ( tx1 <> nil ) then begin tx1.Str := '3,2 ( @78~ '+ ' )'; end; rounghs.Rough[0].Update; rounghs.Add; //шероховатость rounghs.Rough[1].X0:=x0+da2/2+30; rounghs.Rough[1].Y0:=y0+Dv2/4; roughPar := rounghs.Rough[1] As IRoughParams; roughPar.ShelfDirection:= ksLSolderingSign;// Изменение положения шероховатости в вертикальность roughPar.ArrowType:=0; tx3:=roughPar.RoughParamText; if ( tx3 <> nil ) then tx3.Str := '1,6'; rounghs.Rough[1].Update; Toler:=Tolers.Add; if ( toler <> nil ) then begin // Получить интерфейс ответвления branchs := toler As IBranchs; if ( branchs <> nil ) then begin branchs.X0 := x0+da2/2+lcm2/2+30; // Задать точку привязки branchs.Y0 := y0-dv2/6; branchs.AddBranchByPoint( 1, x0+da2/2+lcm2/2+30, y0+dv2/2); // Добавить ответвление end; // Получить интерфейс параметров допуска формы TolerPar := toler As IToleranceParam; if ( TolerPar <> nil ) then begin if ( tolerpar <> nil ) then begin // Получить интерфейс таблицы с текстом допуска формы tolTable := tolerpar.Table; if ( tolTable <> nil ) then begin cell := tolTable.Cell[ 0, 0 ]; if ( cell <> nil ) then begin txt:= cell.Text As ITextLine; if ( txt <> nil ) then txt.Str := 'A'; end; end; end; // Положение базовой точки относительно таблицы - внизу посередине TolerPar.BasePointPos := ksTPUpCenter; end; // Тип стрелки 1-го ответвления - треугольник toler.Set_ArrowType( 0, FALSE ); // Положение 1-го ответвления относительно таблицы - внизу посередине Toler.Set_BranchPos( 0, ksTPUpCenter ); toler.Update(); end; Toler:=Tolers.Add; if ( toler <> nil ) then begin // Получить интерфейс ответвления branchs := toler As IBranchs; if ( branchs <> nil ) then begin // Задать точку привязки branchs.X0 := x0+da2/2+30+Lcm2/2; branchs.Y0 := y0+da2/2+15; // Добавить 2 ответвления branchs.AddBranchByPoint( 1, x0+da2/2+30+Lcm2/2, y0+da2/2 ); end; // Получить интерфейс параметров допуска формы TolerPar := toler As IToleranceParam; if ( TolerPar <> nil ) then begin if ( tolerpar <> nil ) then begin // Получить интерфейс таблицы с текстом допуска формы tolTable := tolerpar.Table; if ( tolTable <> nil ) then begin // Добавить 3 столбца {справа} tolTable.AddColumn( -1, TRUE ); tolTable.AddColumn( -1, TRUE ); cell := tolTable.Cell[ 0, 0 ]; // Записать текст в 1-ю ячейку if ( cell <> nil ) then begin txt:= cell.Text As ITextLine; if ( txt <> nil ) then txt.Str := '@28~'; end; // Записать текст во 2-ю ячейку cell := tolTable.Cell[ 0, 1 ]; if ( cell <> nil ) then begin txt := cell.Text As ITextLine; if ( txt <> nil ) then txt.Str := '0,002'; end; // Записать текст в 3-ю ячейку cell := tolTable.Cell[ 0, 2 ]; if ( cell <> nil ) then begin txt := cell.Text As ITextLine; if ( txt <> nil ) then txt.Str := 'A'; end; end; end; // Положение базовой точки относительно таблицы TolerPar.BasePointPos := ksTPLeftCenter; end; // Тип стрелки 1-го ответвления - треугольник toler.Set_ArrowType( 1, FALSE ); // Положение 1-го ответвления относительно таблицы Toler.Set_BranchPos( 0, ksTPLeftUp ); toler.Update(); end; end; procedure TForm2.Button1Click(Sender: TObject); begin if (Edit1.Text='') or (Edit2.Text='') or (Edit3.Text='') then begin ShowMessage('Заполните все поля!'); exit; end; m:=StrToFloat(Edit1.Text); z:=StrToFloat(Edit2.Text); d2:=m*z; Dv2:=StrToFloat(Edit3.Text); da2:=d2+2*m; df2:=d2-2.5*m; Lcm2:=1.5*Dv2; Dcm2:=1.6*Dv2; Dd2:=1.2*Dv2; q1:=2.25*m; if q1<8 then q1:=8; b2:=7*m; q2:=0.4*b2; h:=da2-df2; kompas(d2,da2,df2,Lcm2, Dcm2,Dd2, q1,q2,b2,m,z,Dv2,h); end; end.
unit DSA.Tree.Heap; interface uses System.SysUtils, DSA.List_Stack_Queue.ArrayList, DSA.Interfaces.DataStructure, DSA.Interfaces.Comparer, DSA.Utils; type THeapkind = (Min, Max); THeap<T> = class private type TArr_T = TArray<T>; TArrayList_T = TArrayList<T>; TComparer_T = TComparer<T>; var __data: TArrayList<T>; __comparer: IComparer<T>; __heapKind: THeapkind; /// <summary> 返回完全二叉树的数组表示中,一个索引所表示的元素的父亲节点的索引 </summary> function __parent(index: Integer): Integer; /// <summary> 返回完全二叉树的数组表示中,一个索引所表示的元素的左孩子节点的索引 </summary> function __leftChild(index: Integer): Integer; /// <summary> 返回完全二叉树的数组表示中,一个索引所表示的元素的右孩子节点的索引 </summary> function __rightChild(index: Integer): Integer; /// <summary> 交换索引为 i , j 的节点元素 </summary> procedure __swap(i: Integer; j: Integer); /// <summary> 元素上浮过程 </summary> procedure __shiftUp(k: Integer); /// <summary> 元素下沉过程 </summary> procedure __shiftDown(k: Integer); public constructor Create(capacity: Integer = 10; heapKind: THeapkind = THeapkind.Min); overload; constructor Create(const arr: TArr_T; heapKind: THeapkind = THeapkind.Min); overload; constructor Create(const arr: TArr_T; cmp: IComparer<T>; heapKind: THeapkind = THeapkind.Min); overload; destructor Destroy; override; /// <summary> 返回堆中元素个数 </summary> function Size: Integer; /// <summary> 返回天所布尔值,表示堆中是否为空 </summary> function IsEmpty: Boolean; /// <summary> 向堆中添加元素 </summary> procedure Add(e: T); /// <summary> 返回堆中的第一个元素的值 </summary> function FindFirst: T; /// <summary> 取出堆中第一个元素 </summary> function ExtractFirst: T; /// <summary> 设置比较器 </summary> procedure SetComparer(c: IComparer<T>); end; procedure Main; implementation type THeap_int = THeap<Integer>; procedure Main; var n: Integer; maxHeap, minHeap: THeap_int; i: Integer; arr: TArray_int; begin n := 10; Randomize; maxHeap := THeap_int.Create(n, THeapkind.Max); //maxHeap.SetComparer(TComparer<Integer>.Default); for i := 0 to n - 1 do maxHeap.Add(Random(1000)); SetLength(arr, n); for i := 0 to n - 1 do arr[i] := maxHeap.ExtractFirst; for i := 1 to n - 1 do if (arr[i - 1] < arr[i]) then raise Exception.Create('Error'); Writeln('Test MaxHeap completed.'); TDSAUtils.DrawLine; minHeap := THeap_int.Create(n, THeapkind.Min); for i := 0 to n - 1 do minHeap.Add(Random(1000)); SetLength(arr, n); for i := 0 to n - 1 do arr[i] := minHeap.ExtractFirst; for i := 1 to n - 1 do if (arr[i - 1] > arr[i]) then raise Exception.Create('Error'); Writeln('Test MinHeap completed.'); end; { THeap<T> } constructor THeap<T>.Create(capacity: Integer; heapKind: THeapkind); begin __comparer := TComparer_T.Default; __data := TArrayList_T.Create(capacity); __heapKind := heapKind; end; procedure THeap<T>.Add(e: T); begin __data.AddLast(e); __shiftUp(__data.GetSize - 1); end; constructor THeap<T>.Create(const arr: TArr_T; heapKind: THeapkind = THeapkind.Min); begin Self.Create(arr, TComparer_T.Default, heapKind); end; constructor THeap<T>.Create(const arr: TArr_T; cmp: IComparer<T>; heapKind: THeapkind); var i: Integer; begin __comparer := cmp; __data := TArrayList_T.Create(arr); __heapKind := heapKind; for i := __parent(__data.GetSize - 1) downto 0 do begin __shiftDown(i); end; end; destructor THeap<T>.Destroy; begin FreeAndNil(__comparer); FreeAndNil(__data); inherited; end; function THeap<T>.ExtractFirst: T; var ret: T; begin ret := FindFirst; __swap(0, __data.GetSize - 1); __data.RemoveLast; __shiftDown(0); Result := ret; end; function THeap<T>.FindFirst: T; begin if __data.GetSize = 0 then raise Exception.Create('Can not FindFirst when heap is empty.'); Result := __data.Get(0); end; function THeap<T>.IsEmpty: Boolean; begin Result := __data.IsEmpty; end; procedure THeap<T>.SetComparer(c: IComparer<T>); begin __comparer := c; end; function THeap<T>.Size: Integer; begin Result := __data.GetSize; end; function THeap<T>.__leftChild(index: Integer): Integer; begin Result := index * 2 + 1; end; function THeap<T>.__parent(index: Integer): Integer; begin if index = 0 then raise Exception.Create('index-0 doesn''t have parent.'); Result := (index - 1) div 2; end; function THeap<T>.__rightChild(index: Integer): Integer; begin Result := index * 2 + 2; end; procedure THeap<T>.__shiftDown(k: Integer); var j: Integer; begin case __heapKind of Min: while __leftChild(k) < __data.GetSize do begin j := __leftChild(k); if ((j + 1) < __data.GetSize) and (__comparer.Compare(__data.Get(j + 1), __data.Get(j)) < 0) then j := __rightChild(k); // __data[j] 是 leftChild 和 rightChild 中的最小值 if __comparer.Compare(__data[k], __data[j]) <= 0 then Break; __swap(k, j); k := j; end; Max: while __leftChild(k) < __data.GetSize do begin j := __leftChild(k); if ((j + 1) < __data.GetSize) and (__comparer.Compare(__data.Get(j + 1), __data.Get(j)) > 0) then j := __rightChild(k); // __data[j] 是 leftChild 和 rightChild 中的最大值 if __comparer.Compare(__data[k], __data[j]) >= 0 then Break; __swap(k, j); k := j; end; end; end; procedure THeap<T>.__shiftUp(k: Integer); begin case __heapKind of Min: while (k > 0) and (__comparer.Compare(__data.Get(__parent(k)), __data.Get(k)) > 0) do begin __swap(k, __parent(k)); k := __parent(k); end; Max: while (k > 0) and (__comparer.Compare(__data.Get(__parent(k)), __data.Get(k)) < 0) do begin __swap(k, __parent(k)); k := __parent(k); end; end; end; procedure THeap<T>.__swap(i, j: Integer); var temp: T; begin if (i < 0) or (i >= Size) or (j < 0) or (j >= Size) then raise Exception.Create('index is illegal.'); temp := __data[i]; __data[i] := __data[j]; __data[j] := temp; end; end.
{ This sample shows how to make a single file deployment. } unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Label1: TLabel; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} {$IFOPT D+} {$R 'Resources.res' 'Resources.rc'} {$ENDIF} uses NtBase, NtBaseTranslator, NtLanguageDlg; procedure TForm1.Button1Click(Sender: TObject); begin TNtLanguageDialog.Select('en'); end; initialization NtEnabledProperties := STRING_TYPES; // Extract resource DLL files from resources into external files so VCL can // use them. TNtBase.ExtractFiles; end.
unit uInfo; interface uses SysUtils, Windows; function GetBuildInfo(var Version: string; AFileName: string = ''): boolean; implementation function GetBuildInfo(var Version: string; AFileName: string = ''): boolean; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; V1, V2, V3, V4: word; begin Result := True; if AFileName = '' then AFileName := ParamStr(0); VerInfoSize := GetFileVersionInfoSize(PChar(AFileName), Dummy); if VerInfoSize = 0 then begin Result := False; Exit; end; GetMem(VerInfo, VerInfoSize); try GetFileVersionInfo(PChar(AFileName), 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin V1 := dwFileVersionMS shr 16; V2 := dwFileVersionMS and $FFFF; V3 := dwFileVersionLS shr 16; V4 := dwFileVersionLS and $FFFF; end; Version := IntToStr(V1) + '.' + IntToStr(V2) + '.' + IntToStr(V3) + '.' + IntToStr(V4); finally FreeMem(VerInfo, VerInfoSize); end; end; end.
unit UHeatExchanger; interface uses UFlow; type HeatExchanger = class d_in := 0.2; d_out := 0.5; length := 3.0; k := 4900; function calculate(hot, cold: Flow; h: real := 0.01): array of Flow; end; implementation function HeatExchanger.calculate(hot, cold: Flow; h: real): array of Flow; begin var v_c := cold.volume_flow_rate / (3.14 * d_in ** 2 / 4 * length); var v_h := hot.volume_flow_rate / (3.14 * d_out ** 2 / 4 * length - 3.14 * d_in ** 2 / 4 * length); var hot_ := new Flow(hot.mass_flow_rate, hot.mass_fractions, hot.temperature); var cold_ := new Flow(cold.mass_flow_rate, cold.mass_fractions, cold.temperature); var len := 0.0; while len <= length do begin hot_.temperature -= k * 3.14 * d_out / (v_h * hot_.density * 1e3 * hot_.cp) * (hot_.temperature - cold_.temperature) * h; cold_.temperature += k * 3.14 * d_in / (v_c * cold_.density * 1e3 * cold_.cp) * (hot_.temperature - cold_.temperature) * h; len += h end; result := |hot_, cold_| end; end.
namespace RegExpression; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Effects, FMX.Edit, FMX.Memo, FMX.ListBox, FMX.Layouts, System.RegularExpressions, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo.Types; type TForm1 = class(TForm) published lbRegExp: TListBox; MemoRegEx: TMemo; EditText: TEdit; lbType: TLabel; SEResult: TShadowEffect; method FormCreate(Sender: TObject); method lbRegExpChange(Sender: TObject); method EditTextChangeTracking(Sender: TObject); end; var Form1: TForm1; implementation method TForm1.EditTextChangeTracking(Sender: TObject); begin if TRegEx.IsMatch(EditText.Text, MemoRegEx.Text) then SEResult.ShadowColor := TAlphaColors.Green else SEResult.ShadowColor := TAlphaColors.Palevioletred; end; method TForm1.FormCreate(Sender: TObject); begin lbRegExpChange(lbRegExp); end; method TForm1.lbRegExpChange(Sender: TObject); begin if not assigned(lbType) then exit; case lbRegExp.ItemIndex of 0: begin lbType.Text := 'E-mail for validation'; MemoRegEx.Text := '^((?>[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+\x20*' + '|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\' + 'x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!' + '#$%&''*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])' + '[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\' + '-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)' + '(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\' + 'd\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|' + '\\[\x01-\x7f])+)\])(?(angle)>)$'; end; 1: begin // Accept IP address between 0..255 lbType.Text := 'IP address for validation (0..255)'; MemoRegEx.Text := '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\' + '.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' + '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'; end; 2: begin // Data interval format mm-dd-yyyy lbType.Text := 'Date in mm-dd-yyyy format from between 01-01-1900 and 12-31-2099'; MemoRegEx.Text := '^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[' + '01])[- /.](19|20)\d\d$'; end; 3: begin // Data interval format mm-dd-yyyy lbType.Text := 'Date in dd-mm-yyyy format from between 01-01-1900 and 31-12-2099'; MemoRegEx.Text := '^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[01' + '2])[- /.](19|20)\d\d$'; end; end; EditTextChangeTracking(EditText); end; end.
namespace WindowsApplication2; interface uses System.Windows.Forms, System.Drawing; type /// <summary> /// Summary description for MainForm. /// </summary> MainForm = partial class(System.Windows.Forms.Form) private protected method Dispose(aDisposing: boolean); override; public constructor; end; implementation {$REGION Construction and Disposition} constructor MainForm; begin // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // end; method MainForm.Dispose(aDisposing: boolean); begin if aDisposing then begin if assigned(components) then components.Dispose(); // // TODO: Add custom disposition code here // end; inherited Dispose(aDisposing); end; {$ENDREGION} end.
unit Validador.Data.FDdbChange; interface uses Data.DB, FireDac.Comp.Client; type TFDDbChange = class(TFDMemTable) private FTemPos: TField; FVersao: TField; FDescricao: TField; FExisteNaPasta: TField; FValue: TField; FZDescricao: TField; FOrdemOriginal: TField; FImportar: TField; FNome: TField; FRepetido: TField; procedure CarregarCampos; procedure CriarCampos; protected procedure DoAfterOpen; override; procedure DoMarcarRepetidos(const ANome: string); procedure DoOnNewRecord; override; public procedure MarcarRepetidos; procedure CreateDataSet; override; property OrdemOriginal: TField read FOrdemOriginal; property Repetido: TField read FRepetido; property Importar: TField read FImportar; property ExisteNaPasta: TField read FExisteNaPasta; property Nome: TField read FNome; property Versao: TField read FVersao; property ZDescricao: TField read FZDescricao; property Descricao: TField read FDescricao; property TemPos: TField read FTemPos; property Value: TField read FValue; end; implementation uses System.SysUtils; procedure TFDDbChange.CreateDataSet; begin CriarCampos; inherited; end; procedure TFDDbChange.CriarCampos; begin FieldDefs.Clear; FieldDefs.Add('OrdemOriginal', ftInteger); FieldDefs.Add('Repetido', ftBoolean); FieldDefs.Add('Importar', ftBoolean); FieldDefs.Add('ExisteNaPasta', ftBoolean); FieldDefs.Add('Nome', ftString, 50); FieldDefs.Add('Versao', ftString, 30); FieldDefs.Add('ZDescricao', ftString, 250); FieldDefs.Add('Descricao', ftString, 250); FieldDefs.Add('TemPos', ftBoolean); FieldDefs.Add('Value', ftString, 50); end; procedure TFDDbChange.DoAfterOpen; begin CarregarCampos; inherited; end; procedure TFDDbChange.CarregarCampos; begin FOrdemOriginal := FindField('OrdemOriginal'); FRepetido := FindField('Repetido'); FImportar := FindField('Importar'); FExisteNaPasta := FindField('ExisteNaPasta'); FNome := FindField('Nome'); FVersao := FindField('Versao'); FZDescricao := FindField('ZDescricao'); FDescricao := FindField('Descricao'); FTemPos := FindField('TemPos'); FValue := FindField('Value'); end; procedure TFDDbChange.DoMarcarRepetidos(const ANome: string); var _registroRepetido: boolean; begin Next; if Eof then Exit; _registroRepetido := Nome.AsString.Equals(ANome) or Value.AsString.Equals(ANome); Edit; Repetido.AsBoolean := _registroRepetido; Importar.AsBoolean := not _registroRepetido; Post; if Repetido.AsBoolean then begin Prior; Edit; Repetido.AsBoolean := Nome.AsString.Equals(ANome); Post; Next; end; DoMarcarRepetidos(Nome.AsString); end; procedure TFDDbChange.DoOnNewRecord; begin Repetido.AsBoolean := False; Importar.AsBoolean := True; ExisteNaPasta.AsBoolean := True; inherited; end; procedure TFDDbChange.MarcarRepetidos; var _indexFieldNames: string; begin _indexFieldNames := IndexFieldNames; DisableControls; try IndexFieldNames := 'Nome'; First; DoMarcarRepetidos(Nome.AsString); finally IndexFieldNames := _indexFieldNames; EnableControls; end; end; end.
unit NfeTransporte; {$mode objfpc}{$H+} interface uses HTTPDefs, BrookRESTActions, BrookUtils, FPJson, SysUtils, BrookHTTPConsts; type TNfeTransporteOptions = class(TBrookOptionsAction) end; TNfeTransporteRetrieve = class(TBrookRetrieveAction) procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override; end; TNfeTransporteShow = class(TBrookShowAction) end; TNfeTransporteCreate = class(TBrookCreateAction) end; TNfeTransporteUpdate = class(TBrookUpdateAction) end; TNfeTransporteDestroy = class(TBrookDestroyAction) end; implementation procedure TNfeTransporteRetrieve.Request(ARequest: TRequest; AResponse: TResponse); var VRow: TJSONObject; Campo: String; Filtro: String; begin Campo := Values['campo'].AsString; Filtro := Values['filtro'].AsString; Values.Clear; Table.Where(Campo + ' = "' + Filtro + '"'); 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; //inherited Request(ARequest, AResponse); end; initialization TNfeTransporteOptions.Register('nfe_transporte', '/nfe_transporte'); TNfeTransporteRetrieve.Register('nfe_transporte', '/nfe_transporte/:campo/:filtro/'); TNfeTransporteShow.Register('nfe_transporte', '/nfe_transporte/:id'); TNfeTransporteCreate.Register('nfe_transporte', '/nfe_transporte'); TNfeTransporteUpdate.Register('nfe_transporte', '/nfe_transporte/:id'); TNfeTransporteDestroy.Register('nfe_transporte', '/nfe_transporte/:id'); end.
unit glIterator; interface type TglIterator = class private FValue, FDefault: Integer; public property DefaultValue: Integer read FDefault write FDefault; property Value: Integer read FValue; constructor Create; overload; constructor Create(StartValue: Integer); overload; constructor Create(StartValue, DefaultValue: Integer); overload; procedure Up; procedure Down; procedure New; end; implementation { TglIterator } constructor TglIterator.Create; begin FDefault := 0; New; end; constructor TglIterator.Create(StartValue: Integer); begin FDefault := 0; FValue := StartValue; end; constructor TglIterator.Create(StartValue, DefaultValue: Integer); begin FDefault := DefaultValue; FValue := StartValue; end; procedure TglIterator.Down; begin Dec(FValue); end; procedure TglIterator.New; begin FValue := FDefault; end; procedure TglIterator.Up; begin Inc(FValue); end; end.
unit MeshOptimization2009Command; interface uses ControllerDataTypes, ActorActionCommandBase, Actor; {$INCLUDE source/Global_Conditionals.inc} type TMeshOptmization2009Command = class (TActorActionCommandBase) protected FIgnoreColours: boolean; FAngle: single; public constructor Create(var _Actor: TActor; var _Params: TCommandParams); override; procedure Execute; override; end; implementation uses StopWatch, MeshOptimization2009, GlobalVars, SysUtils; constructor TMeshOptmization2009Command.Create(var _Actor: TActor; var _Params: TCommandParams); begin FCommandName := 'Mesh Optimization 2009 Method'; ReadAttributes1Bool1Single(_Params, FIgnoreColours, FAngle, false, 1); inherited Create(_Actor,_Params); end; procedure TMeshOptmization2009Command.Execute; var MeshOptimization : TMeshOptimization2009; {$ifdef SPEED_TEST} StopWatch : TStopWatch; {$endif} begin {$ifdef SPEED_TEST} StopWatch := TStopWatch.Create(true); {$endif} MeshOptimization := TMeshOptimization2009.Create(FActor.Models[0]^.LOD[FActor.Models[0]^.CurrentLOD]); MeshOptimization.IgnoreColors := FIgnoreColours; MeshOptimization.Angle := FAngle; MeshOptimization.Execute; MeshOptimization.Free; {$ifdef SPEED_TEST} StopWatch.Stop; GlobalVars.SpeedFile.Add('Mesh optimization (2009) for LOD takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.'); StopWatch.Free; {$endif} end; end.
//------------------------------------------------------------------------------ //Server UNIT //------------------------------------------------------------------------------ // What it does- // Base class of all servers // // Changes - // January 26th, 2008 - RaX - Created // //------------------------------------------------------------------------------ unit Server; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} SysUtils, {Project} Database, {3rd Party} IdTCPServer, IdContext ; type TServer = class protected fPort : Word; TCPServer : TIdTCPServer; Procedure OnExecute(AConnection: TIdContext);virtual;abstract; Procedure OnConnect(AConnection: TIdContext);virtual;abstract; Procedure OnDisconnect(AConnection: TIdContext);virtual;abstract; Procedure OnException(AConnection: TIdContext; AException: Exception);virtual;abstract; Procedure SetPort(Value : Word); Function GetStarted : Boolean; public WANIP : string; LANIP : string; Database : TDatabase; property Started : Boolean read GetStarted; property Port : Word read fPort write SetPort; Constructor Create; Destructor Destroy;Override; Procedure Start();virtual; Procedure Stop();virtual; end; implementation //------------------------------------------------------------------------------ //Create () CONSTRUCTOR //------------------------------------------------------------------------------ // What it does- // Initializes our server // // Changes - // //------------------------------------------------------------------------------ Constructor TServer.Create; begin inherited; TCPServer := TIdTCPServer.Create(); TCPServer.OnConnect := OnConnect; TCPServer.OnDisconnect := OnDisconnect; TCPServer.OnExecute := OnExecute; TCPServer.OnException := OnException; fPort := 0; Database := TDatabase.Create(); end;{Create} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Destroy() DESTRUCTOR //------------------------------------------------------------------------------ // What it does- // Destroys our server // // Changes - // //------------------------------------------------------------------------------ Destructor TServer.Destroy; Begin TCPServer.Free; Database.Disconnect(); Database.Free; inherited; End; (* Dest TZoneServer.Destroy *-----------------------------------------------------------------------------*) //------------------------------------------------------------------------------ //GetStarted FUNCTION //------------------------------------------------------------------------------ // What it does- // Checks to see if the internal TCP server is active, if it is it returns // true. // // Changes - // //------------------------------------------------------------------------------ Function TServer.GetStarted() : Boolean; begin Result := TCPServer.Active; end;{GetStarted} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetPort PROCEDURE //------------------------------------------------------------------------------ // What it does- // // Changes - // //------------------------------------------------------------------------------ Procedure TServer.SetPort(Value : Word); begin fPort := Value; TCPServer.DefaultPort := fPort; end;{GetStarted} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Start PROCEDURE //------------------------------------------------------------------------------ // What it does- // // Changes - // //------------------------------------------------------------------------------ Procedure TServer.Start(); begin Database.Connect(); end;{Start} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Stop PROCEDURE //------------------------------------------------------------------------------ // What it does- // // Changes - // //------------------------------------------------------------------------------ Procedure TServer.Stop(); begin Database.Disconnect(); end;{Stop} //------------------------------------------------------------------------------ end.
//------------------------------------------------------------------------------ // // getTraj.pas // //------------------------------------------------------------------------------ // // Contains procedures for generating trajectories for the robot. Trajectories // are saved to a TTrajectory object passed as reference. // //------------------------------------------------------------------------------ unit genTraj; {$mode objfpc}{$H+} interface uses Classes, SysUtils, obsavoid, Utils, Math; type //Save circular trajectory definitions TTrajectoryCircle = record x_center, y_center, radius, length: double; end; procedure calcDistance(var traj : TTrajectory); procedure saveTrajToFile(var traj:TTrajectory; fileName:string); //Procedures for trajectory generation procedure generateTrajectoryCircle(var traj: TTrajectory; x_center, y_center, radius, length : double); procedure generateTrajectory90DegCorner(var traj: TTrajectory; x_start, y_start, L1, L2 : double; varTeta : boolean); procedure generateTrajectory8(var traj: TTrajectory; width, height,x_center,y_center : double); procedure generateTrajectory90Deg4Corners(var traj: TTrajectory; x_start, y_start, L1, L2, L3, L4, L5 : double; varTeta : boolean); procedure generateTrajectoryLoadFromFile(var traj: TTrajectory; fileName : string); procedure generateTrajectoryHook(var traj: TTrajectory; x_i,y_i,x_f,y_f,circleRadius,circleLength,currAngle,v_ini,v_fin : double); //Variables var TrajectoryCircle : TTrajectoryCircle; const //distance between points in the trajectory trajStep = 0.2; implementation //************************************************************* // generateTrajectory8 // // Generate a trajectory in 8 shape //------------------------------------------------------------- procedure generateTrajectory8(var traj: TTrajectory; width, height,x_center,y_center : double); var i : integer; step, teta_inc : double; begin traj.count:=MaxTrajectoryCount; traj.static := true; traj.index:=0; step := 2*pi/(traj.count-1); teta_inc := 0; //Generate circular trajectory starting in (x_center + radius, y_center) //and going counter-clockwise; for i := 0 to (MaxTrajectoryCount-1) do begin with traj.pts[i] do begin x := x_center+width*cos(teta_inc)/(1+sin(teta_inc)*sin(teta_inc)); y := y_center+1.35*height*width*sin(teta_inc)*cos(teta_inc)/(1+sin(teta_inc)*sin(teta_inc)); teta := 0; teta_power:= 1; teta_inc += step; end; end; //calculate size calcDistance(traj); end; //************************************************************* // generateTrajectory90Deg4Corners // // Generates a pulse trajectory //------------------------------------------------------------- procedure generateTrajectory90Deg4Corners(var traj: TTrajectory; x_start, y_start, L1, L2, L3, L4, L5 : double; varTeta : boolean); var i,cornerPoint : integer; cornerPoint1, cornerPoint2, cornerPoint3, cornerPoint4, cornerPoint5 : integer; tetaRef : array[0 .. 5] of double; begin if varTeta then begin //define teta for teta changes tetaRef[0] := 0; tetaRef[1] := pi/2; tetaRef[2] := 0; tetaRef[3] := -pi/2; tetaRef[4] := 0; end else begin tetaRef[0] := 0; tetaRef[1] := 0; tetaRef[2] := 0; tetaRef[3] := 0; tetaRef[4] := 0; end; traj.count:=MaxTrajectoryCount; traj.static := true; traj.index:=0; cornerPoint1 := round(abs(L1)/trajStep); cornerPoint2 := cornerPoint1 + round(abs(L2)/trajStep); cornerPoint3 := cornerPoint2 + round(abs(L3)/trajStep); cornerPoint4 := cornerPoint3 + round(abs(L4)/trajStep); cornerPoint5 := cornerPoint4 + round(abs(L5)/trajStep); traj.pts[0].x := x_start; traj.pts[0].y := y_start; for i:= 1 to cornerPoint1 do begin if (i <= MaxTrajectoryCount-1) then begin with traj.pts[i] do begin x := traj.pts[i-1].x + Sign(L1)*trajStep; y := y_start; teta := tetaRef[0]; teta_power:= 1; end; end else begin calcDistance(traj); exit; end; end; for i:= cornerPoint1+1 to cornerPoint2 do begin if (i <= MaxTrajectoryCount-1) then begin with traj.pts[i] do begin x := traj.pts[i-1].x; y := traj.pts[i-1].y + Sign(L2)*trajStep; teta := tetaRef[1]; teta_power:= 1; end; end else begin calcDistance(traj); exit; end; end; for i:= cornerPoint2+1 to cornerPoint3 do begin if (i <= MaxTrajectoryCount-1) then begin with traj.pts[i] do begin x := traj.pts[i-1].x + Sign(L3)*trajStep; y := traj.pts[i-1].y; teta := tetaRef[2]; teta_power:= 1; end; end else begin calcDistance(traj); exit; end; end; for i:= cornerPoint3+1 to cornerPoint4 do begin if (i <= MaxTrajectoryCount-1) then begin with traj.pts[i] do begin x := traj.pts[i-1].x; y := traj.pts[i-1].y + Sign(L4)*trajStep; teta := tetaRef[3]; teta_power:= 1; end; end else begin calcDistance(traj); exit; end; end; for i:= cornerPoint4+1 to cornerPoint5 do begin if (i <= MaxTrajectoryCount-1) then begin with traj.pts[i] do begin x := traj.pts[i-1].x + Sign(L5)*trajStep; y := traj.pts[i-1].y; teta := tetaRef[4]; teta_power:= 1; end; end else begin calcDistance(traj); exit; end; end; traj.count:=cornerPoint5 + 1; calcDistance(traj); end; //************************************************************* // generateTrajectoryL // // Generates a L trajectory //------------------------------------------------------------- procedure generateTrajectory90DegCorner(var traj: TTrajectory; x_start, y_start, L1, L2 : double; varTeta : boolean); var i,cornerPoint,cornerPoint2 : integer; tetaRef : array[0 .. 2] of double; tetaInc : array[0 .. 1] of double; begin if varTeta then begin //define teta for teta changes tetaRef[0] := 0; tetaRef[1] := pi/2; tetaRef[2] := 0; end else begin tetaRef[0] := 0; tetaRef[1] := 0; tetaRef[2] := 0; end; if L1 > 0 then tetaInc[0] := (tetaRef[1]-tetaRef[0])/(round(abs(L1)/trajStep)); if L2 > 0 then tetaInc[1] := (tetaRef[2]-tetaRef[1])/(round(abs(L2)/trajStep)); traj.count:=MaxTrajectoryCount; traj.static := true; traj.index:=0; traj.predIndex :=0; cornerPoint := round(abs(L1)/trajStep); cornerPoint2 := cornerPoint + round(abs(L2)/trajStep); traj.pts[0].x := x_start; traj.pts[0].y := y_start; traj.pts[0].teta := tetaRef[0]; for i:= 1 to cornerPoint do begin if (i <= MaxTrajectoryCount-1) then begin with traj.pts[i] do begin x := x_start; y := traj.pts[i-1].y + Sign(L1)*trajStep; teta := traj.pts[i-1].teta + tetaInc[0]; teta_power:= 1; end; end else begin calcDistance(traj); exit; end; end; for i:= cornerPoint+1 to cornerPoint2 do begin if (i <= MaxTrajectoryCount-1) then begin with traj.pts[i] do begin x := traj.pts[i-1].x + Sign(L2)*trajStep; y := traj.pts[i-1].y; teta := traj.pts[i-1].teta + tetaInc[1]; teta_power:= 1; end; end else begin calcDistance(traj); exit; end; end; traj.count:=cornerPoint2 + 1; calcDistance(traj); end; //************************************************************* // generateTrajectoryCircle // // Generates a circular trajectory //------------------------------------------------------------- procedure generateTrajectoryCircle(var traj: TTrajectory; x_center, y_center, radius, length : double); var i : integer; step, teta_inc : double; begin traj.count:=MaxTrajectoryCount; traj.static := true; traj.index:=0; step := trajStep/radius; teta_inc := 0; //Generate circular trajectory starting in (x_center + radius, y_center) //and going counter-clockwise; for i := 0 to (MaxTrajectoryCount-1) do begin if (i <= MaxTrajectoryCount-1) and (teta_inc <= 2*pi*length) then begin with traj.pts[i] do begin x := x_center + radius*cos(teta_inc); y := y_center + radius*sin(teta_inc); teta := teta_inc; teta_power:= 1; teta_inc += step; end; end else begin traj.count := i; calcDistance(traj); exit; end; end; //calculate size calcDistance(traj); end; //************************************************************* // generateTrajectoryHook // // Generates a trajectory in hook //------------------------------------------------------------- procedure generateTrajectoryHook(var traj: TTrajectory; x_i,y_i,x_f,y_f,circleRadius,circleLength,currAngle,v_ini,v_fin : double); var i : integer; i_limit, i_limit_circle : integer; circleStep, teta_inc, teta_init : double; length, angle : double; lineAngleStep : double; x_c,y_c : double; v_step : double; begin traj.static := true; traj.index:=0; //calc stuff length := sqrt(power((x_i-x_f),2)+power((y_i-y_f),2)); i_limit := round(length/trajStep); angle := atan2(y_f-y_i,x_f-x_i); lineAngleStep := (angle + pi -currAngle)/i_limit; v_step:=(v_ini-v_fin)/i_limit; //fill line for i:= 0 to i_limit do begin with traj.pts[i] do begin x := x_i + trajStep*i*cos(angle); y := y_i + trajStep*i*sin(angle); teta := currAngle + i*lineAngleStep; teta_power:= 1; vRef:=v_ini; end; end; //add circle x_c := traj.pts[i].x + circleRadius*cos(angle + pi/2); y_c := traj.pts[i].y + circleRadius*sin(angle + pi/2); circleStep := (trajStep/10)/circleRadius; teta_init := angle - pi/2; teta_inc := teta_init; i+=1; while teta_inc <= teta_init+(2*pi*circleLength) do begin with traj.pts[i] do begin x := x_c + circleRadius*cos(teta_inc); y := y_c + circleRadius*sin(teta_inc); teta := angle + pi; teta_power:= 1; vRef:=v_fin; end; teta_inc += circleStep; i+=1; end; { //Generate circular trajectory starting in (x_center + radius, y_center) //and going counter-clockwise; for i := 0 to (MaxTrajectoryCount-1) do begin if (i <= MaxTrajectoryCount-1) and (teta_inc <= 2*pi*length) then begin with traj.pts[i] do begin x := x_center + radius*cos(teta_inc); y := y_center + radius*sin(teta_inc); teta := teta_inc; teta_power:= 1; teta_inc += step; end; end else begin traj.count := i; calcDistance(traj); exit; end; end; } //calculate size traj.count:=i-1; calcDistance(traj); end; //************************************************************* // saveTrajToFile // // saves trajectory to text file //------------------------------------------------------------- procedure saveTrajToFile(var traj:TTrajectory; fileName:string); var trajFile : TextFile; trajText: string; index: integer; begin AssignFile(trajFile,fileName); Rewrite(trajFile); //WriteLn(trajFile,format('Count: %d',[traj.count])); for index := 0 to traj.count-1 do begin trajText := format('%.5f %.5f %.5f',[traj.pts[index].x,traj.pts[index].y,traj.pts[index].teta]); WriteLn(trajFile,trajText); end; CloseFile(trajFile); end; //************************************************************* // generateTrajectoryLoadFromFile // // Loads trajectory from textfile //------------------------------------------------------------- procedure generateTrajectoryLoadFromFile(var traj: TTrajectory; fileName : string); var i: integer; line: string; trajFile : TextFile; sl : TStringList; x,y,teta:double; begin i:= 0; //Load file if FileExists(fileName) then begin Assign(trajFile,fileName); Reset(trajFile); end; //Load it into trajectory try while not EOF(trajFile) do BEGIN ReadLn(trajFile,x,y,teta); traj.pts[i].x:=x; traj.pts[i].y:=y; traj.pts[i].teta:=teta; i:=i+1; end; except end; traj.count:=i; traj.static:=true; traj.index :=0; traj.currentPoint:=0; calcDistance(traj); end; //************************************************************* // calcDistance // // calculates distance of currentPoint to end of trajectory // saves it onto traj.distance //------------------------------------------------------------- procedure calcDistance(var traj : TTrajectory); var i : integer; begin if traj.static then begin traj.distance := 0; for i := traj.currentPoint to traj.count-2 do traj.distance += dist(traj.pts[i+1].x-traj.pts[i].x,traj.pts[i+1].y-traj.pts[i].y); end; end; end.
unit MODFLOW_SwtWriterUnit; interface uses CustomModflowWriterUnit, ModflowPackageSelectionUnit, IntListUnit, PhastModelUnit, Classes; type TModflowSWT_Writer = class(TCustomSubWriter) private FSwtPackage: TSwtPackageSelection; FNameOfFile: string; // model layer assignments for each system of no-delay interbeds FLNWT: TIntegerList; FTHICK_List: TList; FSse_List: TList; FSsv_List: TList; FCr_List: TList; FCc_List: TList; FVOID_List: TList; FSUB_List: TList; procedure RetrieveArrays; procedure WriteDataSet1; procedure WriteDataSet2; procedure WriteDataSet3; procedure WriteDataSet4; procedure WriteDataSet5; procedure WriteDataSet6; procedure WriteDataSets7to13; procedure WriteDataSet14; procedure WriteDataSet15; procedure WriteDataSet16; procedure WriteDataSet17; protected function Package: TModflowPackageSelection; override; class function Extension: string; override; public procedure WriteFile(const AFileName: string); Constructor Create(Model: TCustomModel; EvaluationType: TEvaluationType); override; Destructor Destroy; override; end; implementation uses ModflowUnitNumbers, frmProgressUnit, LayerStructureUnit, ModflowSubsidenceDefUnit, DataSetUnit, frmErrorsAndWarningsUnit, SysUtils, Forms, GoPhastTypes; resourcestring StrNoSWTLayersDefine = 'No SWT layers defined'; StrInTheSWTPackage = 'In the SWT package, no systems of interbeds have bee' + 'n defined in the MODFLOW Layer Groups dialog box.'; StrWritingSWTPackage = 'Writing SWT Package input.'; // StrWritingDataSet1 = ' Writing Data Set 1.'; // StrWritingDataSet2 = ' Writing Data Set 2.'; // StrWritingDataSet3 = ' Writing Data Set 3.'; // StrWritingDataSet4 = ' Writing Data Set 4.'; // StrWritingDataSet5 = ' Writing Data Set 5.'; // StrWritingDataSet6 = ' Writing Data Set 6.'; StrWritingDataSets7to13 = ' Writing Data Sets 7 to 13.'; // StrWritingDataSet14 = ' Writing Data Set 14.'; // StrWritingDataSet15 = ' Writing Data Set 15.'; // StrWritingDataSet16 = ' Writing Data Set 16.'; // StrWritingDataSet17 = ' Writing Data Set 17.'; { TModflowSWT_Writer } constructor TModflowSWT_Writer.Create(Model: TCustomModel; EvaluationType: TEvaluationType); begin inherited; FLNWT := TIntegerList.Create; FTHICK_List := TList.Create; FSse_List := TList.Create; FSsv_List := TList.Create; FCr_List := TList.Create; FCc_List := TList.Create; FVOID_List := TList.Create; FSUB_List := TList.Create; end; destructor TModflowSWT_Writer.Destroy; begin FSUB_List.Free; FVOID_List.Free; FCc_List.Free; FCr_List.Free; FSsv_List.Free; FSse_List.Free; FTHICK_List.Free; FLNWT.Free; inherited; end; class function TModflowSWT_Writer.Extension: string; begin result := '.swt'; end; function TModflowSWT_Writer.Package: TModflowPackageSelection; begin result := Model.ModflowPackages.SwtPackage; end; procedure TModflowSWT_Writer.RetrieveArrays; var Layers: TLayerStructure; MFLayer_Group: Integer; GroupIndex: Integer; Group: TLayerGroup; SubsidenceIndex: Integer; WT_Item: TSwtWaterTableItem; CompressibleThicknessDataArray: TDataArray; InitialElasticSkeletalSpecificStorageDataArray: TDataArray; InitialInelasticSkeletalSpecificStorageDataArray: TDataArray; RecompressionIndexDataArray: TDataArray; CompressionIndexDataArray: TDataArray; InitialVoidRatioDataArray: TDataArray; InitialCompactionDataArray: TDataArray; LayerIndex: Integer; begin Layers := Model.LayerStructure; MFLayer_Group := 0; for GroupIndex := 1 to Layers.Count - 1 do begin Group := Layers.LayerGroups[GroupIndex]; if Group.RunTimeSimulated then begin for SubsidenceIndex := 0 to Group.WaterTableLayers.Count - 1 do begin WT_Item := Group.WaterTableLayers[SubsidenceIndex]; CompressibleThicknessDataArray := Model.DataArrayManager.GetDataSetByName( WT_Item.WaterTableCompressibleThicknessDataArrayName); Assert(CompressibleThicknessDataArray <> nil); InitialElasticSkeletalSpecificStorageDataArray := Model.DataArrayManager.GetDataSetByName( WT_Item.WaterTableInitialElasticSkeletalSpecificStorageDataArrayName); if FSwtPackage.CompressionSource = csSpecificStorage then begin Assert(InitialElasticSkeletalSpecificStorageDataArray <> nil); end; InitialInelasticSkeletalSpecificStorageDataArray := Model.DataArrayManager.GetDataSetByName( WT_Item.WaterTableInitialInelasticSkeletalSpecificStorageDataArrayName); if FSwtPackage.CompressionSource = csSpecificStorage then begin Assert(InitialInelasticSkeletalSpecificStorageDataArray <> nil); end; RecompressionIndexDataArray := Model.DataArrayManager.GetDataSetByName( WT_Item.WaterTableRecompressionIndexDataArrayName); if FSwtPackage.CompressionSource = csCompressionReComp then begin Assert(RecompressionIndexDataArray <> nil); end; CompressionIndexDataArray := Model.DataArrayManager.GetDataSetByName( WT_Item.WaterTableCompressionIndexDataArrayName); if FSwtPackage.CompressionSource = csCompressionReComp then begin Assert(CompressionIndexDataArray <> nil); end; InitialVoidRatioDataArray := Model.DataArrayManager.GetDataSetByName( WT_Item.WaterTableInitialVoidRatioDataArrayName); Assert(InitialVoidRatioDataArray <> nil); InitialCompactionDataArray := Model.DataArrayManager.GetDataSetByName( WT_Item.WaterTableInitialCompactionDataArrayName); Assert(InitialCompactionDataArray <> nil); if Group.LayerCount = 1 then begin FLNWT.Add(MFLayer_Group+1); FTHICK_List.Add(CompressibleThicknessDataArray); FSse_List.Add(InitialElasticSkeletalSpecificStorageDataArray); FSsv_List.Add(InitialInelasticSkeletalSpecificStorageDataArray); FCr_List.Add(RecompressionIndexDataArray); FCc_List.Add(CompressionIndexDataArray); FVOID_List.Add(InitialVoidRatioDataArray); FSUB_List.Add(InitialCompactionDataArray); end else begin if WT_Item.UseInAllLayers then begin for LayerIndex := 1 to Group.LayerCount do begin FLNWT.Add(MFLayer_Group+LayerIndex); FTHICK_List.Add(CompressibleThicknessDataArray); FSse_List.Add(InitialElasticSkeletalSpecificStorageDataArray); FSsv_List.Add(InitialInelasticSkeletalSpecificStorageDataArray); FCr_List.Add(RecompressionIndexDataArray); FCc_List.Add(CompressionIndexDataArray); FVOID_List.Add(InitialVoidRatioDataArray); FSUB_List.Add(InitialCompactionDataArray); end; end else begin for LayerIndex := 1 to Group.LayerCount do begin if WT_Item.UsedLayers.GetItemByLayerNumber(LayerIndex) <> nil then begin FLNWT.Add(MFLayer_Group+LayerIndex); FTHICK_List.Add(CompressibleThicknessDataArray); FSse_List.Add(InitialElasticSkeletalSpecificStorageDataArray); FSsv_List.Add(InitialInelasticSkeletalSpecificStorageDataArray); FCr_List.Add(RecompressionIndexDataArray); FCc_List.Add(CompressionIndexDataArray); FVOID_List.Add(InitialVoidRatioDataArray); FSUB_List.Add(InitialCompactionDataArray); end; end; end; end; end; Inc(MFLayer_Group,Group.LayerCount); end; end; Assert(FLNWT.Count = FTHICK_List.Count); Assert(FLNWT.Count = FSse_List.Count); Assert(FLNWT.Count = FSsv_List.Count); Assert(FLNWT.Count = FCr_List.Count); Assert(FLNWT.Count = FCc_List.Count); Assert(FLNWT.Count = FVOID_List.Count); Assert(FLNWT.Count = FSUB_List.Count); end; procedure TModflowSWT_Writer.WriteDataSet1; var ISWTCB, ISWTOC, NSYSTM, ITHK, IVOID, ISTPCS, ICRCC: integer; begin GetFlowUnitNumber(ISWTCB); ISWTOC := FSwtPackage.PrintChoices.Count; NSYSTM := Model.LayerStructure.WaterTableCount; ITHK := Ord(FSwtPackage.ThickResponse); IVOID := Ord(FSwtPackage.VoidRatioResponse); ISTPCS := Ord(FSwtPackage.PreconsolidationSource); ICRCC := Ord(FSwtPackage.CompressionSource); WriteInteger(ISWTCB); WriteInteger(ISWTOC); WriteInteger(NSYSTM); WriteInteger(ITHK); WriteInteger(IVOID); WriteInteger(ISTPCS); WriteInteger(ICRCC); WriteString(' # Data Set 1: ISWTCB ISWTOC NSYSTM ITHK IVOID ISTPCS ICRCC'); NewLine; end; procedure TModflowSWT_Writer.WriteDataSet14; var DataArray: TDataArray; MFLayerIndex: Integer; // GroupIndex: Integer; // Group: TLayerGroup; LayerIndex: Integer; ArrayIndex: Integer; begin DataArray := Model.DataArrayManager.GetDataSetByName(StrInitialPreOffsets); MFLayerIndex := 0; for LayerIndex := 0 to Model.LayerCount - 1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; if Model.IsLayerSimulated(LayerIndex) then begin Inc(MFLayerIndex); ArrayIndex := Model. ModflowLayerToDataSetLayer(MFLayerIndex); WriteArray(DataArray, ArrayIndex, 'Data Set 14: PCSOFF, Layer ' + IntToStr(MFLayerIndex), StrNoValueAssigned, 'PCSOFF'); end; end; { for GroupIndex := 1 to Model.LayerStructure.Count -1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; Group := Model.LayerStructure.LayerGroups[GroupIndex]; if Group.Simulated then begin for LayerIndex := 0 to Group.ModflowLayerCount -1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; Inc(MFLayerIndex); ArrayIndex := Model. ModflowLayerToDataSetLayer(MFLayerIndex); WriteArray(DataArray, ArrayIndex, 'Data Set 14: PCSOFF, Layer ' + IntToStr(MFLayerIndex)); end; end; end; } Model.DataArrayManager.AddDataSetToCache(DataArray); Model.DataArrayManager.CacheDataArrays; end; procedure TModflowSWT_Writer.WriteDataSet15; var DataArray: TDataArray; MFLayerIndex: Integer; // GroupIndex: Integer; // Group: TLayerGroup; LayerIndex: Integer; ArrayIndex: Integer; begin DataArray := Model.DataArrayManager.GetDataSetByName(StrInitialPreconsolida); MFLayerIndex := 0; for LayerIndex := 0 to Model.LayerCount - 1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; if Model.IsLayerSimulated(LayerIndex) then begin Inc(MFLayerIndex); ArrayIndex := Model. ModflowLayerToDataSetLayer(MFLayerIndex); WriteArray(DataArray, ArrayIndex, 'Data Set 15: PCS, Layer ' + IntToStr(MFLayerIndex), StrNoValueAssigned, 'PCS'); end; end; { for GroupIndex := 1 to Model.LayerStructure.Count -1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; Group := Model.LayerStructure.LayerGroups[GroupIndex]; if Group.Simulated then begin for LayerIndex := 0 to Group.ModflowLayerCount -1 do begin Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; Inc(MFLayerIndex); ArrayIndex := Model. ModflowLayerToDataSetLayer(MFLayerIndex); WriteArray(DataArray, ArrayIndex, 'Data Set 15: PCS, Layer ' + IntToStr(MFLayerIndex)); end; end; end; } Model.DataArrayManager.AddDataSetToCache(DataArray); Model.DataArrayManager.CacheDataArrays; end; procedure TModflowSWT_Writer.WriteDataSet16; var PrintFormats: TSwtPrintFormats; Ifm1: Integer; Ifm2: Integer; Ifm3: Integer; Ifm4: Integer; Ifm5: Integer; Ifm6: Integer; Ifm7: Integer; Ifm8: Integer; Ifm9: Integer; Ifm10: Integer; Ifm11: Integer; Ifm12: Integer; Ifm13: Integer; Save1: Boolean; Save2: Boolean; Save3: Boolean; Save4: Boolean; Save5: Boolean; Save6: Boolean; Save7: Boolean; Save8: Boolean; Save9: Boolean; Save10: Boolean; Save11: Boolean; Save12: Boolean; Save13: Boolean; Index: Integer; PrintChoice: TSwtPrintItem; Iun1: Integer; SwtFileName: string; // AFileName: string; Iun2: Integer; Iun3: Integer; Iun4: Integer; Iun5: Integer; Iun6: Integer; Iun7: Integer; Iun8: Integer; Iun9: Integer; Iun10: Integer; Iun11: Integer; Iun12: Integer; Iun13: Integer; function GetCombinedUnitNumber: integer; begin result := Model.UnitNumbers.UnitNumber(StrSwtSUB_Out); if SwtFileName = '' then begin SwtFileName := ExtractFileName(ChangeFileExt(FNameOfFile, StrSwtOut)); WriteToNameFile(StrDATABINARY, result, SwtFileName, foOutput, Model); end; end; function HandleUnitNumber(Save: boolean; const Key, Extension: string): integer; var AFileName: string; begin result := 0; if Save then begin case FSwtPackage.BinaryOutputChoice of sbocSingleFile: begin result := GetCombinedUnitNumber; end; sbocMultipleFiles: begin result := Model.UnitNumbers.UnitNumber(Key); AFileName := ExtractFileName(ChangeFileExt(FNameOfFile, Extension)); WriteToNameFile(StrDATABINARY, result, AFileName, foOutput, Model); end else Assert(False); end; end; end; begin SwtFileName := ''; PrintFormats := FSwtPackage.PrintFormats; Ifm1 := PrintFormats.SubsidenceFormat+1; Ifm2 := PrintFormats.CompactionByModelLayerFormat+1; Ifm3 := PrintFormats.CompactionByInterbedSystemFormat+1; Ifm4 := PrintFormats.VerticalDisplacementFormat+1; Ifm5 := PrintFormats.PreconsolidationStress+1; Ifm6 := PrintFormats.DeltaPreconsolidationStress+1; Ifm7 := PrintFormats.GeostaticStress+1; Ifm8 := PrintFormats.DeltaGeostaticStress+1; Ifm9 := PrintFormats.EffectiveStress+1; Ifm10 := PrintFormats.DeltaEffectiveStress+1; Ifm11 := PrintFormats.VoidRatio+1; Ifm12 := PrintFormats.ThicknessCompressibleSediments+1; Ifm13 := PrintFormats.LayerCenterElevation+1; Save1 := False; Save2 := False; Save3 := False; Save4 := False; Save5 := False; Save6 := False; Save7 := False; Save8 := False; Save9 := False; Save10 := False; Save11 := False; Save12 := False; Save13 := False; for Index := 0 to FSwtPackage.PrintChoices.Count - 1 do begin PrintChoice := FSwtPackage.PrintChoices[Index]; Save1 := Save1 or PrintChoice.SaveSubsidence; Save2 := Save2 or PrintChoice.SaveCompactionByModelLayer; Save3 := Save3 or PrintChoice.SaveCompactionByInterbedSystem; Save4 := Save4 or PrintChoice.SaveVerticalDisplacement; Save5 := Save5 or PrintChoice.SavePreconsolidationStress; Save6 := Save6 or PrintChoice.SaveDeltaPreconsolidationStress; Save7 := Save7 or PrintChoice.SaveGeostaticStress; Save8 := Save8 or PrintChoice.SaveDeltaGeostaticStress; Save9 := Save9 or PrintChoice.SaveEffectiveStress; Save10 := Save10 or PrintChoice.SaveDeltaEffectiveStress; Save11 := Save11 or PrintChoice.SaveVoidRatio; Save12 := Save12 or PrintChoice.SaveThicknessCompressibleSediments; Save13 := Save13 or PrintChoice.SaveLayerCenterElevation; if Save1 and Save2 and Save3 and Save4 and Save5 and Save6 and Save6 and Save8 and Save9 and Save10 and Save11 and Save12 and Save13 then begin break; end; end; Iun1 := HandleUnitNumber(Save1, StrSwtSUB_Out, StrSwtSubOut); Iun2 := HandleUnitNumber(Save2, StrSwtComML_Out, StrSwtComMLOut); Iun3 := HandleUnitNumber(Save3, StrSwtCOM_IS_Out, StrSwtComIsOut); Iun4 := HandleUnitNumber(Save4, StrSwt_VD_Out, StrSwtVDOut); Iun5 := HandleUnitNumber(Save5, StrSwt_PreCon_Out, StrSwtPreConStrOut); Iun6 := HandleUnitNumber(Save6, StrSwt_DeltaPreCon_Out, StrSwtDeltaPreConStrOu); Iun7 := HandleUnitNumber(Save7, StrSwt_GeoStat_Out, StrSwtGeoStatOut); Iun8 := HandleUnitNumber(Save8, StrSwt_DeltaGeoStat_Out, StrSwtDeltaGeoStatOut); Iun9 := HandleUnitNumber(Save9, StrSwt_EffStress_Out, StrSwtEffStressOut); Iun10 := HandleUnitNumber(Save10, StrSwt_DeltaEffStress_Out, StrSwtDeltaEffStressOu); Iun11 := HandleUnitNumber(Save11, StrSwt_VoidRatio_Out, StrSwtVoidRatioOut); Iun12 := HandleUnitNumber(Save12, StrSwt_ThickCompSed_Out, StrSwtThickCompSedOut); Iun13 := HandleUnitNumber(Save13, StrSwt_LayerCentElev_Out, StrSwtLayerCentElevOut); WriteInteger(Ifm1 ); WriteInteger(Iun1 ); WriteInteger(Ifm2 ); WriteInteger(Iun2 ); WriteInteger(Ifm3 ); WriteInteger(Iun3 ); WriteInteger(Ifm4 ); WriteInteger(Iun4 ); WriteInteger(Ifm5 ); WriteInteger(Iun5 ); WriteInteger(Ifm6 ); WriteInteger(Iun6 ); WriteInteger(Ifm7 ); WriteInteger(Iun7 ); WriteInteger(Ifm8 ); WriteInteger(Iun8 ); WriteInteger(Ifm9 ); WriteInteger(Iun9 ); WriteInteger(Ifm10); WriteInteger(Iun10); WriteInteger(Ifm11); WriteInteger(Iun11); WriteInteger(Ifm12); WriteInteger(Iun12); WriteInteger(Ifm13); WriteInteger(Iun13); WriteString(' # Data Set 16: Ifm1 Iun1 Ifm2 Iun2 Ifm3 Iun3 ... Ifm13 Iun13'); NewLine; end; procedure TModflowSWT_Writer.WriteDataSet17; var PrintChoiceIndex: Integer; PrintChoice: TSwtPrintItem; ISP1: Integer; ITS1: Integer; ISP2: Integer; ITS2: Integer; Ifl1: Integer; Ifl2: Integer; Ifl3: Integer; Ifl4: Integer; Ifl5: Integer; Ifl6: Integer; Ifl7: Integer; Ifl8: Integer; Ifl9: Integer; Ifl10: Integer; Ifl11: Integer; Ifl12: Integer; Ifl13: Integer; Ifl14: Integer; Ifl15: Integer; Ifl16: Integer; Ifl17: Integer; Ifl18: Integer; Ifl19: Integer; Ifl20: Integer; Ifl21: Integer; Ifl22: Integer; Ifl23: Integer; Ifl24: Integer; Ifl25: Integer; Ifl26: Integer; begin FSwtPackage.PrintChoices.ReportErrors; for PrintChoiceIndex := 0 to FSwtPackage.PrintChoices.Count -1 do begin PrintChoice := FSwtPackage.PrintChoices[PrintChoiceIndex]; if PrintChoice.StartTime <= PrintChoice.EndTime then begin GetStartAndEndTimeSteps(ITS2, ISP2, ITS1, ISP1, PrintChoice); Ifl1 := Ord(PrintChoice.PrintSubsidence); Ifl2 := Ord(PrintChoice.SaveSubsidence); Ifl3 := Ord(PrintChoice.PrintCompactionByModelLayer); Ifl4 := Ord(PrintChoice.SaveCompactionByModelLayer); Ifl5 := Ord(PrintChoice.PrintCompactionByInterbedSystem); Ifl6 := Ord(PrintChoice.SaveCompactionByInterbedSystem); Ifl7 := Ord(PrintChoice.PrintVerticalDisplacement); Ifl8 := Ord(PrintChoice.SaveVerticalDisplacement); Ifl9 := Ord(PrintChoice.PrintPreconsolidationStress); Ifl10 := Ord(PrintChoice.SavePreconsolidationStress); Ifl11 := Ord(PrintChoice.PrintDeltaPreconsolidationStress); Ifl12 := Ord(PrintChoice.SaveDeltaPreconsolidationStress); Ifl13 := Ord(PrintChoice.PrintGeostaticStress); Ifl14 := Ord(PrintChoice.SaveGeostaticStress); Ifl15 := Ord(PrintChoice.PrintDeltaGeostaticStress); Ifl16 := Ord(PrintChoice.SaveDeltaGeostaticStress); Ifl17 := Ord(PrintChoice.PrintEffectiveStress); Ifl18 := Ord(PrintChoice.SaveEffectiveStress); Ifl19 := Ord(PrintChoice.PrintDeltaEffectiveStress); Ifl20 := Ord(PrintChoice.SaveDeltaEffectiveStress); Ifl21 := Ord(PrintChoice.PrintVoidRatio); Ifl22 := Ord(PrintChoice.SaveVoidRatio); Ifl23 := Ord(PrintChoice.PrintThicknessCompressibleSediments); Ifl24 := Ord(PrintChoice.SaveThicknessCompressibleSediments); Ifl25 := Ord(PrintChoice.PrintLayerCenterElevation); Ifl26 := Ord(PrintChoice.SaveLayerCenterElevation); WriteInteger(ISP1); WriteInteger(ISP2); WriteInteger(ITS1); WriteInteger(ITS2); WriteInteger(Ifl1); WriteInteger(Ifl2); WriteInteger(Ifl3); WriteInteger(Ifl4); WriteInteger(Ifl5); WriteInteger(Ifl6); WriteInteger(Ifl7); WriteInteger(Ifl8); WriteInteger(Ifl9); WriteInteger(Ifl10); WriteInteger(Ifl11); WriteInteger(Ifl12); WriteInteger(Ifl13); WriteInteger(Ifl14); WriteInteger(Ifl15); WriteInteger(Ifl16); WriteInteger(Ifl17); WriteInteger(Ifl18); WriteInteger(Ifl19); WriteInteger(Ifl20); WriteInteger(Ifl21); WriteInteger(Ifl22); WriteInteger(Ifl23); WriteInteger(Ifl24); WriteInteger(Ifl25); WriteInteger(Ifl26); WriteString(' # Data Set 17: ISP1 ISP2 ITS1 ITS2 Ifl1 Ifl2 Ifl3 ... Ifl26'); NewLine; end; end; end; procedure TModflowSWT_Writer.WriteDataSet2; var Index: Integer; begin frmErrorsAndWarnings.RemoveErrorGroup(Model, StrNoSWTLayersDefine); if FLNWT.Count = 0 then begin frmErrorsAndWarnings.AddError(Model, StrNoSWTLayersDefine, StrInTheSWTPackage); Exit; end; for Index := 0 to FLNWT.Count - 1 do begin WriteInteger(FLNWT[Index]); end; WriteString(' # Data Set 2: LNWT'); NewLine; end; procedure TModflowSWT_Writer.WriteDataSet3; var // IZCFL IZCFM IGLFL IGLFM IESTFL IESTFM IPCSFL IPCSFM ISTFL ISTFM: integer; IZCFL, IZCFM, IGLFL, IGLFM, IESTFL, IESTFM, IPCSFL, IPCSFM, ISTFL, ISTFM: integer; InitialPrint: TSwtInitialPrint; begin InitialPrint := FSwtPackage.InitialPrint; IZCFL := Ord(InitialPrint.PrintInitialLayerCenterElevations); IZCFM := InitialPrint.InitialLayerCenterElevationFormat+1; IGLFL := Ord(InitialPrint.PrintInitialGeostaticStress); IGLFM := InitialPrint.InitialGeostaticStressFormat+1; IESTFL := Ord(InitialPrint.PrintInitialEffectiveStress); IESTFM := InitialPrint.InitialEffectiveStressFormat+1; IPCSFL := Ord(InitialPrint.PrintInitialPreconsolidationStress); IPCSFM := InitialPrint.InitialPreconsolidationStressFormat+1; ISTFL := Ord(InitialPrint.PrintInitialEquivalentStorageProperties); ISTFM := InitialPrint.InitialEquivalentStoragePropertiesFormat+1; WriteInteger(IZCFL); WriteInteger(IZCFM); WriteInteger(IGLFL); WriteInteger(IGLFM); WriteInteger(IESTFL); WriteInteger(IESTFM); WriteInteger(IPCSFL); WriteInteger(IPCSFM); WriteInteger(ISTFL); WriteInteger(ISTFM); WriteString(' # Data Set 3: IZCFL IZCFM IGLFL IGLFM IESTFL IESTFM IPCSFL IPCSFM ISTFL ISTFM'); NewLine; end; procedure TModflowSWT_Writer.WriteDataSet4; var DataArray: TDataArray; begin DataArray := Model.DataArrayManager.GetDataSetByName(StrGeostaticStress); WriteArray(DataArray, 0, 'Data Set 4: GL0', StrNoValueAssigned, 'GL0'); Model.DataArrayManager.AddDataSetToCache(DataArray); Model.DataArrayManager.CacheDataArrays; end; procedure TModflowSWT_Writer.WriteDataSet5; var DataArray: TDataArray; begin DataArray := Model.DataArrayManager.GetDataSetByName(StrSpecificGravityUns); WriteArray(DataArray, 0, 'Data Set 5: SGM', StrNoValueAssigned, 'SGM'); Model.DataArrayManager.AddDataSetToCache(DataArray); Model.DataArrayManager.CacheDataArrays; end; procedure TModflowSWT_Writer.WriteDataSet6; var DataArray: TDataArray; begin DataArray := Model.DataArrayManager.GetDataSetByName(StrSpecificGravitySat); WriteArray(DataArray, 0, 'Data Set 6: SGS', StrNoValueAssigned, 'SGS'); Model.DataArrayManager.AddDataSetToCache(DataArray); Model.DataArrayManager.CacheDataArrays; end; procedure TModflowSWT_Writer.WriteDataSets7to13; var Index: Integer; DataArray: TDataArray; begin for Index := 0 to FTHICK_List.Count - 1 do begin DataArray := FTHICK_List[Index]; WriteArray(DataArray, 0, 'Data set 7: THICK', StrNoValueAssigned, 'THICK'); Model.DataArrayManager.AddDataSetToCache(DataArray); if FSwtPackage.CompressionSource = csSpecificStorage then begin DataArray := FSse_List[Index]; WriteArray(DataArray, 0, 'Data set 8: Sse', StrNoValueAssigned, 'Sse'); Model.DataArrayManager.AddDataSetToCache(DataArray); DataArray := FSsv_List[Index]; WriteArray(DataArray, 0, 'Data set 9: Ssv', StrNoValueAssigned, 'Ssv'); Model.DataArrayManager.AddDataSetToCache(DataArray); end; if FSwtPackage.CompressionSource = csCompressionReComp then begin DataArray := FCr_List[Index]; WriteArray(DataArray, 0, 'Data set 10: Cr', StrNoValueAssigned, 'Cr'); Model.DataArrayManager.AddDataSetToCache(DataArray); DataArray := FCc_List[Index]; WriteArray(DataArray, 0, 'Data set 11: Cc', StrNoValueAssigned, 'Cc'); Model.DataArrayManager.AddDataSetToCache(DataArray); end; DataArray := FVOID_List[Index]; WriteArray(DataArray, 0, 'Data set 12: VOID', StrNoValueAssigned, 'VOID'); Model.DataArrayManager.AddDataSetToCache(DataArray); DataArray := FSUB_List[Index]; WriteArray(DataArray, 0, 'Data set 13: SUB', StrNoValueAssigned, 'SUB'); Model.DataArrayManager.AddDataSetToCache(DataArray); end; Model.DataArrayManager.CacheDataArrays; end; procedure TModflowSWT_Writer.WriteFile(const AFileName: string); begin FSwtPackage := Package as TSwtPackageSelection; if not FSwtPackage.IsSelected then begin Exit end; if Model.PackageGeneratedExternally(StrSWT) then begin Exit; end; frmErrorsAndWarnings.BeginUpdate; try FNameOfFile := FileName(AFileName); WriteToNameFile(StrSWT, Model.UnitNumbers.UnitNumber(StrSWT), FNameOfFile, foInput, Model); RetrieveArrays; OpenFile(FNameOfFile); try frmProgressMM.AddMessage(StrWritingSWTPackage); WriteDataSet0; frmProgressMM.AddMessage(StrWritingDataSet1); WriteDataSet1; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet2); WriteDataSet2; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet3); WriteDataSet3; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet4); WriteDataSet4; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet5); WriteDataSet5; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet6); WriteDataSet6; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSets7to13); WriteDataSets7to13; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; if FSwtPackage.PreconsolidationSource = pcOffsets then begin frmProgressMM.AddMessage(StrWritingDataSet14); WriteDataSet14; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; end; if FSwtPackage.PreconsolidationSource = pcSpecified then begin frmProgressMM.AddMessage(StrWritingDataSet15); WriteDataSet15; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; end; if FSwtPackage.PrintChoices.Count > 0 then begin frmProgressMM.AddMessage(StrWritingDataSet16); WriteDataSet16; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet17); WriteDataSet17; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; end; finally CloseFile; end; finally frmErrorsAndWarnings.EndUpdate; end; end; end.
unit PCL0; { Gère les objets photon en utilisant les mêmes principes que dans dtf0 ou tbe0 } interface uses util1, dtf0; { TPCLrecord est la structure d'un photon dans un fichier PCL Les nombres sont stockés en Big Endian format Convert rétablit l'ordre des octets . Quand TPCLrecord est utilisé en interne, on oublie la conversion } type TPCLrecord = object time:double; X,Y,Z:smallint; procedure convert; end; tabPCLrecord = array[0..0] of TPCLrecord; PtabPCLrecord=^tabPCLrecord; // Type générique TypeDataPhotonB= class indiceMin,indiceMax:integer; function getPhoton(i:integer): TPCLrecord; virtual;abstract; property Photon[i:integer]: TPCLrecord read GetPhoton; function getDataVtime: typeDataB;virtual;abstract; function getDataVx: typeDataB;virtual;abstract; function getDataVy: typeDataB;virtual;abstract; function getDataVz: typeDataB;virtual;abstract; end; // Les photons sont dans un tableau en mémoire de TPCLrecord TypeDataPhoton= class (TypeDataPhotonB) p0: PtabPCLrecord; constructor create(p: pointer;i1, i2: integer); function getPhoton(i:integer): TPCLrecord; override; function getDataVtime: typeDataB;override; function getDataVx: typeDataB;override; function getDataVy: typeDataB;override; function getDataVz: typeDataB;override; end; // Les photons sont dans un tableau tournant de TPCLrecord // p indique le début du buffer considéré comme un tableau indicé de 0 à Nmax-1 // indice1 est le début du segment de données utiles dans ce buffer // imin et imax sont les indices utilisateurs de début et de fin de ce segment // GetPhoton = p0^[(indice1+i) mod Nmax]; TypeDataPhotonT= class (TypeDataPhotonB) indice1: integer; Nmax:integer; p0: PtabPCLrecord; constructor create(p: pointer; N1, i1,imin,imax: integer); function getPhoton(i:integer): TPCLrecord; override; function getDataVtime: typeDataB;override; function getDataVx: typeDataB;override; function getDataVy: typeDataB;override; function getDataVz: typeDataB;override; end; implementation { TPCLrecord } function swap(x:smallint):smallint;assembler; asm mov ax, x xchg ah,al end; procedure swapDouble(var x:double); var x1: array[0..7] of byte absolute x; y: double; y1: array[0..7] of byte absolute y; i:integer; begin for i:=0 to 7 do y1[i]:=x1[7-i]; x:=y; end; procedure TPCLrecord.convert; begin swapDouble(time); x:=swap(x); y:=swap(y); z:=swap(z); end; { TypeDataPhoton } constructor TypeDataPhoton.create(p: pointer; i1, i2: integer); begin p0:=p; indicemin:=i1; indicemax:=i2; end; function TypeDataPhoton.getDataVtime: typeDataB; begin result:= typeDataD.createStep(@p0^[0].time,sizeof(TPCLrecord),0,indicemin, indicemax); end; function TypeDataPhoton.getDataVx: typeDataB; begin result:= typeDataI.createStep(@p0^[0].x,sizeof(TPCLrecord),0,indicemin,indicemax); end; function TypeDataPhoton.getDataVy: typeDataB; begin result:= typeDataI.createStep(@p0^[0].y,sizeof(TPCLrecord),0,indicemin,indicemax); end; function TypeDataPhoton.getDataVz: typeDataB; begin result:= typeDataI.createStep(@p0^[0].z,sizeof(TPCLrecord),0,indicemin,indicemax); end; function TypeDataPhoton.getPhoton(i: integer): TPCLrecord; begin result:=p0^[i-indicemin]; // result:=p0^[i+indice1]; end; { TypeDataPhotonT } constructor TypeDataPhotonT.create(p: pointer; N1,i1,imin,imax: integer); begin p0:=p; indice1:=i1; indicemin:=imin; indicemax:=imax; Nmax:=N1; end; function TypeDataPhotonT.getDataVtime: typeDataB; begin result:= typeDataDT.createStep(@p0^[0].time,sizeof(TPCLrecord),Nmax,indice1,indicemin, indicemax); end; function TypeDataPhotonT.getDataVx: typeDataB; begin result:= typeDataIT.createStep(@p0^[0].x,sizeof(TPCLrecord),Nmax,indice1,indicemin, indicemax); end; function TypeDataPhotonT.getDataVy: typeDataB; begin result:= typeDataIT.createStep(@p0^[0].y,sizeof(TPCLrecord),Nmax,indice1,indicemin, indicemax); end; function TypeDataPhotonT.getDataVz: typeDataB; begin result:= typeDataIT.createStep(@p0^[0].z,sizeof(TPCLrecord),Nmax,indice1,indicemin, indicemax); end; function TypeDataPhotonT.getPhoton(i: integer): TPCLrecord; begin result:=p0^[(indice1+i) mod Nmax]; end; end.
program HowToCollideTwoSprites; uses SwinGame, sgTypes; procedure Main(); var earth: Sprite; asteroid: Sprite; begin OpenGraphicsWindow('Colliding Sprites', 800, 600); ClearScreen(ColorWhite); LoadBitmapNamed('earth', 'earth.png'); LoadBitmapNamed('asteroid', 'asteroid.png'); earth := CreateSprite(BitmapNamed('earth')); SpriteSetX(earth, 700); SpriteSetY(earth, 100); SpriteSetVelocity(earth, VectorTo(-0.8, 0.6)); asteroid := CreateSprite(BitmapNamed('asteroid')); SpriteSetX(asteroid, 100); SpriteSetY(asteroid, 500); SpriteSetVelocity(asteroid, VectorTo(1, -0.6)); repeat ProcessEvents(); ClearScreen(ColorWhite); DrawSprite(earth); UpdateSprite(earth); DrawSprite(asteroid); UpdateSprite(asteroid); if SpriteCollision(earth, asteroid) then CollideCircles(asteroid, earth); RefreshScreen(); until WindowCloseRequested(); FreeSprite(earth); FreeSprite(asteroid); ReleaseAllResources(); end; begin Main(); end.
(* Copyright 2016, MARS-Curiosity library Home: https://github.com/andrea-magni/MARS *) unit MARS.Client.Client; {$I MARS.inc} interface uses SysUtils, Classes , MARS.Core.JSON , MARS.Client.Utils, MARS.Core.Utils ; type TMARSAuthEndorsement = (Cookie, AuthorizationBearer); TMARSHttpVerb = (Get, Put, Post, Head, Delete, Patch); TMARSClientErrorEvent = procedure ( AResource: TObject; AException: Exception; AVerb: TMARSHttpVerb; const AAfterExecute: TMARSClientResponseProc; var AHandled: Boolean) of object; TMARSCustomClient = class; // fwd TMARSCustomClientClass = class of TMARSCustomClient; {$ifdef DelphiXE2_UP} [ComponentPlatformsAttribute( pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice {$ifdef DelphiXE8_UP} or pidiOSDevice32 or pidiOSDevice64 {$endif} or pidAndroid)] {$endif} TMARSCustomClient = class(TComponent) private FMARSEngineURL: string; FOnError: TMARSClientErrorEvent; FAuthEndorsement: TMARSAuthEndorsement; protected procedure AssignTo(Dest: TPersistent); override; function GetConnectTimeout: Integer; virtual; function GetReadTimeout: Integer; virtual; procedure SetConnectTimeout(const Value: Integer); virtual; procedure SetReadTimeout(const Value: Integer); virtual; procedure SetAuthEndorsement(const Value: TMARSAuthEndorsement); procedure EndorseAuthorization(const AAuthToken: string); virtual; procedure AuthEndorsementChanged; virtual; public constructor Create(AOwner: TComponent); override; procedure DoError(const AResource: TObject; const AException: Exception; const AVerb: TMARSHttpVerb; const AAfterExecute: TMARSClientResponseProc); virtual; procedure Delete(const AURL: string; AContent, AResponse: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); virtual; procedure Get(const AURL: string; AResponseContent: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); virtual; procedure Post(const AURL: string; AContent, AResponse: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); overload; virtual; procedure Post(const AURL: string; const AFormData: TArray<TFormParam>; const AResponse: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); overload; virtual; procedure Put(const AURL: string; AContent, AResponse: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); overload; virtual; procedure Put(const AURL: string; const AFormData: TArray<TFormParam>; const AResponse: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); overload; virtual; function LastCmdSuccess: Boolean; virtual; function ResponseStatusCode: Integer; virtual; function ResponseText: string; virtual; // shortcuts class function GetJSON<T: TJSONValue>(const AEngineURL, AAppName, AResourceName: string; const AToken: string = ''): T; overload; class function GetJSON<T: TJSONValue>(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AToken: string = ''; const AIgnoreResult: Boolean = False): T; overload; {$ifdef DelphiXE7_UP} class procedure GetJSONAsync<T: TJSONValue>(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const ACompletionHandler: TProc<T>{$ifdef DelphiXE2_UP} = nil{$endif}; const AOnException: TMARSClientExecptionProc{$ifdef DelphiXE2_UP} = nil{$endif}; const AToken: string = ''; const ASynchronize: Boolean = True); overload; {$endif} class function GetAsString(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AToken: string = ''): string; overload; class function PostJSON(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AContent: TJSONValue; const ACompletionHandler: TProc<TJSONValue>{$ifdef DelphiXE2_UP} = nil{$endif}; const AToken: string = '' ): Boolean; {$ifdef DelphiXE7_UP} class procedure PostJSONAsync(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AContent: TJSONValue; const ACompletionHandler: TProc<TJSONValue>{$ifdef DelphiXE2_UP} = nil{$endif}; const AOnException: TMARSClientExecptionProc{$ifdef DelphiXE2_UP} = nil{$endif}; const AToken: string = ''; const ASynchronize: Boolean = True); {$endif} class function GetStream(const AEngineURL, AAppName, AResourceName: string; const AToken: string = ''): TStream; overload; class function GetStream(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AToken: string = ''): TStream; overload; class function PostStream(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AContent: TStream; const AToken: string = ''): Boolean; published property MARSEngineURL: string read FMARSEngineURL write FMARSEngineURL; property ConnectTimeout: Integer read GetConnectTimeout write SetConnectTimeout; property ReadTimeout: Integer read GetReadTimeout write SetReadTimeout; property OnError: TMARSClientErrorEvent read FOnError write FOnError; property AuthEndorsement: TMARSAuthEndorsement read FAuthEndorsement write SetAuthEndorsement default TMARSAuthEndorsement.Cookie; end; function TMARSHttpVerbToString(const AVerb: TMARSHttpVerb): string; implementation uses Rtti, TypInfo , MARS.Client.CustomResource , MARS.Client.Resource , MARS.Client.Resource.JSON , MARS.Client.Resource.Stream , MARS.Client.Application ; function TMARSHttpVerbToString(const AVerb: TMARSHttpVerb): string; begin {$ifdef DelphiXE7_UP} Result := TRttiEnumerationType.GetName<TMARSHttpVerb>(AVerb); {$else} Result := GetEnumName(TypeInfo(TMARSHttpVerb), Integer(AVerb)); {$endif} end; { TMARSCustomClient } procedure TMARSCustomClient.AssignTo(Dest: TPersistent); var LDestClient: TMARSCustomClient; begin // inherited; LDestClient := Dest as TMARSCustomClient; if Assigned(LDestClient) then begin LDestClient.AuthEndorsement := AuthEndorsement; LDestClient.MARSEngineURL := MARSEngineURL; LDestClient.ConnectTimeout := ConnectTimeout; LDestClient.ReadTimeout := ReadTimeout; LDestClient.OnError := OnError; end; end; procedure TMARSCustomClient.AuthEndorsementChanged; begin end; constructor TMARSCustomClient.Create(AOwner: TComponent); begin inherited; FAuthEndorsement := Cookie; FMARSEngineURL := 'http://localhost:8080/rest'; end; procedure TMARSCustomClient.Delete(const AURL: string; AContent, AResponse: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); begin EndorseAuthorization(AAuthToken); end; procedure TMARSCustomClient.DoError(const AResource: TObject; const AException: Exception; const AVerb: TMARSHttpVerb; const AAfterExecute: TMARSClientResponseProc); var LHandled: Boolean; begin LHandled := False; if Assigned(FOnError) then FOnError(AResource, AException, AVerb, AAfterExecute, LHandled); if not LHandled then raise EMARSClientException.Create(AException.Message) end; procedure TMARSCustomClient.EndorseAuthorization(const AAuthToken: string); begin end; procedure TMARSCustomClient.Get(const AURL: string; AResponseContent: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); begin EndorseAuthorization(AAuthToken); end; function TMARSCustomClient.GetConnectTimeout: Integer; begin Result := -1; end; function TMARSCustomClient.GetReadTimeout: Integer; begin Result := -1; end; //function TMARSCustomClient.GetRequest: TIdHTTPRequest; //begin // Result := FHttpClient.Request; //end; //function TMARSCustomClient.GetResponse: TIdHTTPResponse; //begin // Result := FHttpClient.Response; //end; function TMARSCustomClient.LastCmdSuccess: Boolean; begin Result := False; end; procedure TMARSCustomClient.Post(const AURL: string; AContent, AResponse: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); begin EndorseAuthorization(AAuthToken); end; procedure TMARSCustomClient.Put(const AURL: string; AContent, AResponse: TStream; const AAuthToken: string; const AAccept: string; const AContentType: string); begin EndorseAuthorization(AAuthToken); end; function TMARSCustomClient.ResponseStatusCode: Integer; begin Result := -1; end; function TMARSCustomClient.ResponseText: string; begin Result := ''; end; procedure TMARSCustomClient.SetAuthEndorsement( const Value: TMARSAuthEndorsement); begin if FAuthEndorsement <> Value then begin FAuthEndorsement := Value; AuthEndorsementChanged; end; end; procedure TMARSCustomClient.SetConnectTimeout(const Value: Integer); begin end; procedure TMARSCustomClient.SetReadTimeout(const Value: Integer); begin end; class function TMARSCustomClient.GetAsString(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AToken: string): string; var LClient: TMARSCustomClient; LResource: TMARSClientResource; LApp: TMARSClientApplication; LIndex: Integer; LFinalURL: string; begin LClient := Create(nil); try LClient.AuthEndorsement := AuthorizationBearer; LClient.MARSEngineURL := AEngineURL; LApp := TMARSClientApplication.Create(nil); try LApp.Client := LClient; LApp.AppName := AAppName; LResource := TMARSClientResource.Create(nil); try LResource.Application := LApp; LResource.Resource := AResourceName; LResource.PathParamsValues.Clear; for LIndex := 0 to Length(APathParams)-1 do LResource.PathParamsValues.Add(APathParams[LIndex]); if Assigned(AQueryParams) then LResource.QueryParams.Assign(AQueryParams); LFinalURL := LResource.URL; LResource.SpecificToken := AToken; Result := LResource.GETAsString(); finally LResource.Free; end; finally LApp.Free; end; finally LClient.Free; end; end; class function TMARSCustomClient.GetJSON<T>(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AToken: string; const AIgnoreResult: Boolean): T; var LClient: TMARSCustomClient; LResource: TMARSClientResourceJSON; LApp: TMARSClientApplication; LIndex: Integer; LFinalURL: string; begin Result := nil; LClient := Create(nil); try LClient.AuthEndorsement := AuthorizationBearer; LClient.MARSEngineURL := AEngineURL; LApp := TMARSClientApplication.Create(nil); try LApp.Client := LClient; LApp.AppName := AAppName; LResource := TMARSClientResourceJSON.Create(nil); try LResource.Application := LApp; LResource.Resource := AResourceName; LResource.PathParamsValues.Clear; for LIndex := 0 to Length(APathParams)-1 do LResource.PathParamsValues.Add(APathParams[LIndex]); if Assigned(AQueryParams) then LResource.QueryParams.Assign(AQueryParams); LFinalURL := LResource.URL; LResource.SpecificToken := AToken; LResource.GET(nil, nil, nil); Result := nil; if not AIgnoreResult then Result := LResource.Response.Clone as T; finally LResource.Free; end; finally LApp.Free; end; finally LClient.Free; end; end; {$ifdef DelphiXE7_UP} class procedure TMARSCustomClient.GetJSONAsync<T>(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const ACompletionHandler: TProc<T>; const AOnException: TMARSClientExecptionProc; const AToken: string; const ASynchronize: Boolean); var LClient: TMARSCustomClient; LResource: TMARSClientResourceJSON; LApp: TMARSClientApplication; LIndex: Integer; LFinalURL: string; begin LClient := Create(nil); try LClient.AuthEndorsement := AuthorizationBearer; LClient.MARSEngineURL := AEngineURL; LApp := TMARSClientApplication.Create(nil); try LApp.Client := LClient; LApp.AppName := AAppName; LResource := TMARSClientResourceJSON.Create(nil); try LResource.Application := LApp; LResource.Resource := AResourceName; LResource.PathParamsValues.Clear; for LIndex := 0 to Length(APathParams)-1 do LResource.PathParamsValues.Add(APathParams[LIndex]); if Assigned(AQueryParams) then LResource.QueryParams.Assign(AQueryParams); LFinalURL := LResource.URL; LResource.SpecificToken := AToken; LResource.GETAsync( procedure (AResource: TMARSClientCustomResource) begin try if Assigned(ACompletionHandler) then ACompletionHandler((AResource as TMARSClientResourceJSON).Response as T); finally LResource.Free; LApp.Free; LClient.Free; end; end , AOnException , ASynchronize ); except LResource.Free; raise; end; except LApp.Free; raise; end; except LClient.Free; raise; end; end; {$endif} class function TMARSCustomClient.GetStream(const AEngineURL, AAppName, AResourceName: string; const AToken: string): TStream; begin Result := GetStream(AEngineURL, AAppName, AResourceName, nil, nil, AToken); end; class function TMARSCustomClient.GetJSON<T>(const AEngineURL, AAppName, AResourceName: string; const AToken: string): T; begin Result := GetJSON<T>(AEngineURL, AAppName, AResourceName, nil, nil, AToken); end; class function TMARSCustomClient.GetStream(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AToken: string): TStream; var LClient: TMARSCustomClient; LResource: TMARSClientResourceStream; LApp: TMARSClientApplication; LIndex: Integer; begin LClient := Create(nil); try LClient.AuthEndorsement := AuthorizationBearer; LClient.MARSEngineURL := AEngineURL; LApp := TMARSClientApplication.Create(nil); try LApp.Client := LClient; LApp.AppName := AAppName; LResource := TMARSClientResourceStream.Create(nil); try LResource.Application := LApp; LResource.Resource := AResourceName; LResource.PathParamsValues.Clear; for LIndex := 0 to Length(APathParams)-1 do LResource.PathParamsValues.Add(APathParams[LIndex]); if Assigned(AQueryParams) then LResource.QueryParams.Assign(AQueryParams); LResource.SpecificToken := AToken; LResource.GET(nil, nil, nil); Result := TMemoryStream.Create; try Result.CopyFrom(LResource.Response, LResource.Response.Size); except Result.Free; raise; end; finally LResource.Free; end; finally LApp.Free; end; finally LClient.Free; end; end; procedure TMARSCustomClient.Post(const AURL: string; const AFormData: TArray<TFormParam>; const AResponse: TStream; const AAuthToken, AAccept: string; const AContentType: string); begin EndorseAuthorization(AAuthToken); end; class function TMARSCustomClient.PostJSON(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AContent: TJSONValue; const ACompletionHandler: TProc<TJSONValue>; const AToken: string ): Boolean; var LClient: TMARSCustomClient; LResource: TMARSClientResourceJSON; LApp: TMARSClientApplication; LIndex: Integer; begin LClient := Create(nil); try LClient.AuthEndorsement := AuthorizationBearer; LClient.MARSEngineURL := AEngineURL; LApp := TMARSClientApplication.Create(nil); try LApp.Client := LClient; LApp.AppName := AAppName; LResource := TMARSClientResourceJSON.Create(nil); try LResource.Application := LApp; LResource.Resource := AResourceName; LResource.PathParamsValues.Clear; for LIndex := 0 to Length(APathParams)-1 do LResource.PathParamsValues.Add(APathParams[LIndex]); if Assigned(AQueryParams) then LResource.QueryParams.Assign(AQueryParams); LResource.SpecificToken := AToken; LResource.POST( procedure (AStream: TMemoryStream) var LWriter: TStreamWriter; begin if Assigned(AContent) then begin LWriter := TStreamWriter.Create(AStream); try LWriter.Write(AContent.ToJSON); finally LWriter.Free; end; end; end , procedure (AStream: TStream) begin if Assigned(ACompletionHandler) then ACompletionHandler(LResource.Response); end , nil ); Result := LClient.LastCmdSuccess; finally LResource.Free; end; finally LApp.Free; end; finally LClient.Free; end; end; {$ifdef DelphiXE7_UP} class procedure TMARSCustomClient.PostJSONAsync(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AContent: TJSONValue; const ACompletionHandler: TProc<TJSONValue>; const AOnException: TMARSClientExecptionProc; const AToken: string; const ASynchronize: Boolean); var LClient: TMARSCustomClient; LResource: TMARSClientResourceJSON; LApp: TMARSClientApplication; LIndex: Integer; begin LClient := Create(nil); try LClient.AuthEndorsement := AuthorizationBearer; LClient.MARSEngineURL := AEngineURL; LApp := TMARSClientApplication.Create(nil); try LApp.Client := LClient; LApp.AppName := AAppName; LResource := TMARSClientResourceJSON.Create(nil); try LResource.Application := LApp; LResource.Resource := AResourceName; LResource.PathParamsValues.Clear; for LIndex := 0 to Length(APathParams)-1 do LResource.PathParamsValues.Add(APathParams[LIndex]); if Assigned(AQueryParams) then LResource.QueryParams.Assign(AQueryParams); LResource.SpecificToken := AToken; LResource.POSTAsync( procedure (AStream: TMemoryStream) var LWriter: TStreamWriter; begin if Assigned(AContent) then begin LWriter := TStreamWriter.Create(AStream); try LWriter.Write(AContent.ToJSON); finally LWriter.Free; end; end; end , procedure (AResource: TMARSClientCustomResource) begin try if Assigned(ACompletionHandler) then ACompletionHandler((AResource as TMARSClientResourceJSON).Response); finally LResource.Free; LApp.Free; LClient.Free; end; end , AOnException , ASynchronize ); except LResource.Free; raise; end; except LApp.Free; raise; end; except LClient.Free; raise; end; end; {$endif} class function TMARSCustomClient.PostStream(const AEngineURL, AAppName, AResourceName: string; const APathParams: TArray<string>; const AQueryParams: TStrings; const AContent: TStream; const AToken: string ): Boolean; var LClient: TMARSCustomClient; LResource: TMARSClientResourceStream; LApp: TMARSClientApplication; LIndex: Integer; begin LClient := Create(nil); try LClient.AuthEndorsement := AuthorizationBearer; LClient.MARSEngineURL := AEngineURL; LApp := TMARSClientApplication.Create(nil); try LApp.Client := LClient; LApp.AppName := AAppName; LResource := TMARSClientResourceStream.Create(nil); try LResource.Application := LApp; LResource.Resource := AResourceName; LResource.PathParamsValues.Clear; for LIndex := 0 to Length(APathParams)-1 do LResource.PathParamsValues.Add(APathParams[LIndex]); if Assigned(AQueryParams) then LResource.QueryParams.Assign(AQueryParams); LResource.SpecificToken := AToken; LResource.POST( procedure (AStream: TMemoryStream) begin if Assigned(AContent) then begin AStream.Size := 0; // reset AContent.Position := 0; AStream.CopyFrom(AContent, AContent.Size); end; end , nil, nil ); Result := LClient.LastCmdSuccess; finally LResource.Free; end; finally LApp.Free; end; finally LClient.Free; end; end; procedure TMARSCustomClient.Put(const AURL: string; const AFormData: TArray<TFormParam>; const AResponse: TStream; const AAuthToken, AAccept: string; const AContentType: string); begin EndorseAuthorization(AAuthToken); end; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK August 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: BackgroundThread.pas,v 1.3 2006/10/23 22:30:52 clootie Exp $ *----------------------------------------------------------------------------*) //-------------------------------------------------------------------------------------- // File: BackgroundThread.cpp // // Sample showing how to use D3D9Ex advanced features. // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- unit BackgroundThread; {$I DirectX.inc} interface uses Windows, Direct3D9, D3DX9, DXUTcore; //----------------------------------------------------------------------------- // structures //----------------------------------------------------------------------------- type TBackgroundVertex = record x, y, z: Single; // The untransformed position for the vertex dwColor: DWORD; // Color end; const D3DFVF_BACKGROUNDVERTEX = (D3DFVF_XYZ or D3DFVF_DIFFUSE); //-------------------------------------------------------------------------------------- // Function Prototypes and Externs //-------------------------------------------------------------------------------------- function BackgroundThreadProc(lpParam: Pointer): DWORD; stdcall; function CreateCube(const pDev: IDirect3DDevice9Ex): HRESULT; function CreateSharedRenderTexture(const pDev: IDirect3DDevice9Ex): HRESULT; procedure RenderBackground(const pDev: IDirect3DDevice9Ex); procedure CleanupBackground; //-------------------------------------------------------------------------------------- // Exported //-------------------------------------------------------------------------------------- function CreateBackgroundThread(const pD3D9: IDirect3D9Ex): THandle; procedure KillBackgroundThread; { g_bEndThread = true; } function GetSharedTextureHandle: THandle; { return g_SharedHandle; } function IncreaseCubeCount: Integer; function DecreaseCubeCount: Integer; function GetFPS: Single; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- var g_RTWidth: LongWord = 1024; g_RTHeight: LongWord = 1024; implementation uses D3D9ExUnit; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- var g_bEndThread: Boolean = False; g_pRenderTarget: IDirect3DTexture9; g_pSharedTexture: IDirect3DTexture9; g_pCubeVB: IDirect3DVertexBuffer9; g_pCubeIB: IDirect3DIndexBuffer9; g_SharedHandle: THandle = 0; g_CubeCubes: Integer = 3; g_BoxRad: Single = 30.0; g_CSCubes: TRTLCriticalSection; g_fBackLastFrameTime: Single = 0.000001; g_liBackLastTimerUpdate: Int64 = 0; g_liBackTimerFrequency: Int64 = 0; // main background thread proc function BackgroundThreadProc(lpParam: Pointer): DWORD; stdcall; var pDevBackground: IDirect3DDevice9Ex; pD3D9: IDirect3D9Ex; d3dpp: TD3DPresentParameters; begin // Create a critsec InitializeCriticalSection(g_CSCubes); // Create a d3d9V device pD3D9 := IDirect3D9Ex(lpParam); FillChar(d3dpp, SizeOf(d3dpp), 0); d3dpp.Windowed := True; d3dpp.SwapEffect := D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat := D3DFMT_UNKNOWN; d3dpp.PresentationInterval := D3DPRESENT_INTERVAL_DEFAULT; if FAILED(CreateD3D9VDevice(pD3D9, pDevBackground, d3dpp, 0)) then begin Result:= 1; Exit; end; if FAILED(CreateCube(pDevBackground)) then begin Result:= 2; Exit; end; if FAILED(CreateSharedRenderTexture(pDevBackground)) then begin Result:= 3; Exit; end; // Set the GPU thread priority pDevBackground.SetGPUThreadPriority(-7); SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_LOWEST); // Get Timer Frequency QueryPerformanceFrequency(g_liBackTimerFrequency); QueryPerformanceCounter(g_liBackLastTimerUpdate); while (not g_bEndThread) do begin RenderBackground(pDevBackground); // Uncomment next line to throttle rendering to no more then the refresh rate of the monitor. // pDevBackground->WaitForVBlank(0); end; // Cleanup DeleteCriticalSection(g_CSCubes); CleanupBackground; pDevBackground := nil; Result:= 0; end; function CreateBackgroundThread(const pD3D9: IDirect3D9Ex): THandle; var dwThreadID: DWORD; hBackgroundThread: THandle; begin // create the thread dwThreadID := 0; hBackgroundThread := CreateThread(nil, 0, @BackgroundThreadProc, Pointer(pD3D9), CREATE_SUSPENDED, dwThreadID); if (hBackgroundThread <> 0) then begin // set the priority // resume the thread ResumeThread(hBackgroundThread); end; Result:= hBackgroundThread; end; const vertices: array[0..7] of TBackgroundVertex = ( (x: -1.0; y: 1.0; z: -1.0; dwColor: $000066), (x: 1.0; y: 1.0; z: -1.0; dwColor: $006600), (x: 1.0; y: 1.0; z: 1.0; dwColor: $006666), (x: -1.0; y: 1.0; z: 1.0; dwColor: $660000), (x: -1.0; y: -1.0; z: -1.0; dwColor: $660066), (x: 1.0; y: -1.0; z: -1.0; dwColor: $666600), (x: 1.0; y: -1.0; z: 1.0; dwColor: $666666), (x: -1.0; y: -1.0; z: 1.0; dwColor: $000000) ); indices: array[0..12*3-1] of Word = ( 3,1,0, 2,1,3, 0,5,4, 1,5,0, 3,4,7, 0,4,3, 1,6,5, 2,6,1, 2,7,6, 3,7,2, 6,4,5, 7,4,6 ); function CreateCube(const pDev: IDirect3DDevice9Ex): HRESULT; var pVertices: Pointer; pIndices: Pointer; begin Result:= E_FAIL; // create the vb if FAILED(pDev.CreateVertexBuffer(8*SizeOf(TBackgroundVertex), 0, D3DFVF_BACKGROUNDVERTEX, D3DPOOL_DEFAULT, g_pCubeVB, nil)) then Exit; if FAILED(g_pCubeVB.Lock(0, SizeOf(vertices), pVertices, 0)) then Exit; CopyMemory(pVertices, @vertices, SizeOf(vertices)); g_pCubeVB.Unlock; if FAILED(pDev.CreateIndexBuffer(36*SizeOf(WORD), 0, D3DFMT_INDEX16, D3DPOOL_DEFAULT, g_pCubeIB, nil)) then Exit; if FAILED(g_pCubeIB.Lock(0, SizeOf(indices), pIndices, 0)) then Exit; CopyMemory(pIndices, @indices, SizeOf(indices)); g_pCubeIB.Unlock; Result:= S_OK; end; function CreateSharedRenderTexture(const pDev: IDirect3DDevice9Ex): HRESULT; var pRTSurf: IDirect3DSurface9; vp: TD3DViewport9; begin Result:= E_FAIL; if FAILED(pDev.CreateTexture(g_RTWidth, g_RTHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, g_pSharedTexture, @g_SharedHandle)) then Exit; if (g_SharedHandle = 0) then Exit; // create a render target if FAILED(pDev.CreateTexture(g_RTWidth, g_RTHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, g_pRenderTarget, nil)) then Exit; if FAILED(g_pRenderTarget.GetSurfaceLevel(0, pRTSurf)) then Exit; if FAILED(pDev.SetRenderTarget(0, pRTSurf)) then Exit; pRTSurf := nil; // viewport vp.X := 0; vp.Y := 0; vp.Width := g_RTWidth; vp.Height := g_RTHeight; vp.MinZ := 0.0; vp.MaxZ := 1.0; pDev.SetViewport(vp); Result:= S_OK; end; var fRot: Single = 0.0; procedure RenderBackground(const pDev: IDirect3DDevice9Ex); var mWorld: TD3DXMatrix; mView: TD3DXMatrix; mProj: TD3DXMatrix; eye, at, up: TD3DXVector3; //hr: HRESULT; fStep, fStart, fStop: Single; x, y, z: Single; mPos: TD3DXMatrix; pSurfSrc: IDirect3DSurface9; pSurfDest: IDirect3DSurface9; liCurrentTime: Int64; begin fRot := fRot + g_fBackLastFrameTime*60.0*(D3DX_PI/180.0); // setup the matrices D3DXMatrixRotationY(mWorld, fRot); eye := D3DXVector3(0, 2.0, g_BoxRad*3.5); at := D3DXVector3Zero; up := D3DXVector3(0, 1, 0); D3DXMatrixLookAtLH(mView, eye, at, up); D3DXMatrixPerspectiveFovLH(mProj, D3DX_PI/4.0, 1.0, 0.1, 1000.0); pDev.SetTransform(D3DTS_VIEW, mView); pDev.SetTransform(D3DTS_PROJECTION, mProj); // clear // hr := S_OK; pDev.Clear(0, nil, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0, 0); // Begin the scene if SUCCEEDED(pDev.BeginScene) then begin // set the texture stage states pDev.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); pDev.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE); // disable lighting pDev.SetRenderState(D3DRS_LIGHTING, iFalse); // stream sources pDev.SetStreamSource(0, g_pCubeVB, 0, SizeOf(TBackgroundVertex)); pDev.SetIndices(g_pCubeIB); pDev.SetFVF(D3DFVF_BACKGROUNDVERTEX); // draw if (g_CubeCubes <> 0) then fStep := (g_BoxRad*2) / g_CubeCubes else fStep := 0; fStart := -g_BoxRad + fStep/2.0; fStop := fStart + fStep*g_CubeCubes; EnterCriticalSection(g_CSCubes); z := fStart; // for float z:=fStart; z<fStop; z:= _ +fStep ) while (z<fStop) do begin y := fStart; // for( float y=fStart; y<fStop; y+=fStep ) while (y<fStop) do begin x := fStart; // for( float x=fStart; x<fStop; x+=fStep ) while (x<fStop) do begin D3DXMatrixTranslation(mPos, x,y,z); // mPos := mWorld*mPos; D3DXMatrixMultiply(mPos, mWorld, mPos); pDev.SetTransform(D3DTS_WORLD, mPos); {hr := }pDev.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8, 0, 12); x := x + fStep; end; y:= y + fStep; end; z:= z + fStep; end; LeaveCriticalSection(g_CSCubes); // End the scene pDev.EndScene; end; // Stretch rect to our shared texture g_pRenderTarget.GetSurfaceLevel(0, pSurfSrc); g_pSharedTexture.GetSurfaceLevel(0, pSurfDest); {hr := }pDev.StretchRect(pSurfSrc, nil, pSurfDest, nil, D3DTEXF_POINT); SAFE_RELEASE(pSurfSrc); SAFE_RELEASE(pSurfDest); // Get the time QueryPerformanceCounter(liCurrentTime); g_fBackLastFrameTime := (liCurrentTime - g_liBackLastTimerUpdate) / g_liBackTimerFrequency; g_liBackLastTimerUpdate := liCurrentTime; end; procedure CleanupBackground; begin SAFE_RELEASE(g_pRenderTarget); SAFE_RELEASE(g_pSharedTexture); SAFE_RELEASE(g_pCubeVB); SAFE_RELEASE(g_pCubeIB); end; procedure KillBackgroundThread; begin g_bEndThread := True; end; function GetSharedTextureHandle: THandle; begin Result:= g_SharedHandle; end; function IncreaseCubeCount: Integer; begin EnterCriticalSection(g_CSCubes); Inc(g_CubeCubes); if (g_CubeCubes > 100) then g_CubeCubes := 100; LeaveCriticalSection(g_CSCubes); Result:= g_CubeCubes; end; function DecreaseCubeCount: Integer; begin EnterCriticalSection(g_CSCubes); Dec(g_CubeCubes); if (g_CubeCubes < 0) then g_CubeCubes := 0; LeaveCriticalSection(g_CSCubes); Result:= g_CubeCubes; end; function GetFPS: Single; begin Result:= 1.0 / g_fBackLastFrameTime; end; end.
unit NfeNumero; {$mode objfpc}{$H+} interface uses HTTPDefs, BrookRESTActions, BrookUtils; type TNfeNumeroOptions = class(TBrookOptionsAction) end; TNfeNumeroRetrieve = class(TBrookRetrieveAction) procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override; end; TNfeNumeroShow = class(TBrookShowAction) end; TNfeNumeroCreate = class(TBrookCreateAction) end; TNfeNumeroUpdate = class(TBrookUpdateAction) end; TNfeNumeroDestroy = class(TBrookDestroyAction) end; implementation procedure TNfeNumeroRetrieve.Request(ARequest: TRequest; AResponse: TResponse); var Campo: String; Filtro: String; begin Campo := Values['campo'].AsString; Filtro := Values['filtro'].AsString; Values.Clear; Table.Where(Campo + ' LIKE "%' + Filtro + '%"'); inherited Request(ARequest, AResponse); end; initialization TNfeNumeroOptions.Register('nfe_numero', '/nfe_numero'); TNfeNumeroRetrieve.Register('nfe_numero', '/nfe_numero/:campo/:filtro/'); TNfeNumeroShow.Register('nfe_numero', '/nfe_numero/:id'); TNfeNumeroCreate.Register('nfe_numero', '/nfe_numero'); TNfeNumeroUpdate.Register('nfe_numero', '/nfe_numero/:id'); TNfeNumeroDestroy.Register('nfe_numero', '/nfe_numero/:id'); end.
//------------------------------------------------------------------------------ //CharAccountInfo UNIT //------------------------------------------------------------------------------ // What it does- // This class used by Char server to handle each account data in list // // Changes - // April 12th, 2007 - Aeomin - Created Header // //------------------------------------------------------------------------------ unit CharAccountInfo; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses IdContext; type TCharAccountInfo = class public //Acc id AccountID : LongWord; //Char id CharacterID : LongWord; //Which zone currently on? ZoneServerID : Word; //Is the account in game? InGame : Boolean; //Transfering back to char server select? Transfering : Boolean; //The socket of client ClientInfo : TIdContext; Constructor Create(AID : LongWord); end; implementation Constructor TCharAccountInfo.Create(AID : LongWord); begin inherited Create; AccountID := AID; Ingame := False; Transfering := False; end; end.
{$i deltics.inc} unit Test.InterfacedObjectList; interface uses Deltics.Smoketest; type TInterfacedObjectListTests = class(TTest) procedure InterfacedObjectAddedToListIsRemovedWhenDestroyed; procedure AddingItemsViaObjectReferenceIsAnInvalidOperation; procedure AddingItemsViaInterfaceReferenceIsSuccessful; end; implementation uses Deltics.Exceptions, Deltics.InterfacedObjects; type TInterfacedObjectListSubClassExposingAddMethod = class(TInterfacedObjectList); { TTestInterfacedObjectList } procedure TInterfacedObjectListTests.AddingItemsViaInterfaceReferenceIsSuccessful; var sut: IInterfacedObjectList; io: TInterfacedObject; begin sut := TInterfacedObjectList.Create; io := TInterfacedObject.Create; try sut.Add(io); Test('Count').Assert(sut.Count).Equals(1); finally io.Free; end; end; procedure TInterfacedObjectListTests.AddingItemsViaObjectReferenceIsAnInvalidOperation; var sut: TInterfacedObjectListSubClassExposingAddMethod; io: TInterfacedObject; begin Test.RaisesException(EInvalidOperation); sut := TInterfacedObjectListSubClassExposingAddMethod.Create; try io := TInterfacedObject.Create; try sut.Add(io); finally io.Free; end; finally // Call the TObject.Free implementation on SUT (to bypass the reintroduced Free // which raises an exception when trying to Free a COM interfaced object) otherwise // the test will leak SUT. TObject(sut).Free; end; end; procedure TInterfacedObjectListTests.InterfacedObjectAddedToListIsRemovedWhenDestroyed; var sut: IInterfacedObjectList; io: TInterfacedObject; begin sut := TInterfacedObjectList.Create; io := TInterfacedObject.Create; Test('Count').Assert(sut.Count).Equals(0); sut.Add(io); Test('Count').Assert(sut.Count).Equals(1); io.Free; Test('Count').Assert(sut.Count).Equals(0); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses // Embedded_GUI_SubArch_List, Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, EditBtn, Buttons, FileUtil, SynEdit, SynHighlighterPas, IniFiles; type { TForm1 } TForm1 = class(TForm) Close_Btn: TBitBtn; Generate_BitBtn: TBitBtn; DirectoryEdit1: TDirectoryEdit; SynEdit1: TSynEdit; SynPasSyn1: TSynPasSyn; procedure Generate_BitBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); private function FindText(s: string; var ofs: integer): string; function Comma(sl: TStringList): string; function ControllerDataType(s: string): string; function AddSubArch(sl: TStrings; cpu: string): TStringList; function AddNewCommaText(sl: TStrings): string; procedure AddCPUData(sl, SubArchList: TStrings; cpu: string); procedure AddControllerDataList(sl: TStrings; cpu: string); public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.FormCreate(Sender: TObject); var ini: TIniFile; begin ini := TIniFile.Create('config.ini'); Left := ini.ReadInteger('pos', 'Left', 100); Width := ini.ReadInteger('pos', 'Width', 500); Top := ini.ReadInteger('pos', 'Top', 50); Height := ini.ReadInteger('pos', 'Height', 400); DirectoryEdit1.Directory := ini.ReadString('options', 'path', '/home/tux/fpc.src/fpc'); ini.Free; SynEdit1.ScrollBars := ssAutoBoth; end; procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction); var ini: TIniFile; begin ini := TIniFile.Create('config.ini'); ini.WriteInteger('pos', 'Left', Left); ini.WriteInteger('pos', 'Width', Width); ini.WriteInteger('pos', 'Top', Top); ini.WriteInteger('pos', 'Height', Height); ini.WriteString('options', 'path', DirectoryEdit1.Directory); ini.Free; end; function TForm1.Comma(sl: TStringList): string; begin Result := sl.CommaText; Result := StringReplace(Result, ',', #39', '#39, [rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result, 'cpu_', '', [rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result, 'fpu_', '', [rfReplaceAll, rfIgnoreCase]); end; function TForm1.FindText(s: string; var ofs: integer): string; begin while not (s[ofs] in ['0'..'9', 'a'..'z', 'A'..'Z', '_', '$']) do begin Inc(ofs); end; Result := ''; repeat Result += s[ofs]; Inc(ofs); until not (s[ofs] in ['0'..'9', 'a'..'z', 'A'..'Z', '_', '$']); end; function TForm1.ControllerDataType(s: string): string; var ofs: integer; s1: string; begin ofs := Pos('tcontrollerdatatype', s); Inc(ofs, 19); FindText(s, ofs); s1 := FindText(s, ofs); Result := s1; repeat while not (s[ofs] in [';', ',']) do begin Inc(ofs); end; s1 := FindText(s, ofs); if s1 <> 'end' then begin Result += #39', '#39 + s1; end; until s1 = 'end'; end; function TForm1.AddSubArch(sl: TStrings; cpu: string): TStringList; var source_SL: TStringList; p: integer; s, s1: string; sa: TStringArray; begin Result := TStringList.Create; if Pos('generic', cpu) > 0 then begin Exit; end; source_SL := TStringList.Create; source_SL.LoadFromFile(cpu); s := source_SL.Text; source_SL.Free; p := Pos('cputypestr', s); if p > 0 then begin while s[p] <> ')' do begin Inc(p); if s[p] = #39 then begin Inc(p); if s[p] <> #39 then begin s1 := ''; repeat s1 += s[p]; Inc(p); until s[p] = #39; Result.Add(s1); end; end; end; sa := cpu.Split('/'); if Length(sa) >= 2 then begin sl.Add('const'); sl.Add(' ' + sa[Length(sa) - 2] + '_SubArch_List = '); sl.Add(' '#39 + Result.CommaText + #39 + ';'); end; end; end; function TForm1.AddNewCommaText(sl: TStrings): string; var i: integer; begin if sl.Count = 0 then begin Result := ' '#39#39','; end else begin Result := ' ' + #39; for i := 0 to sl.Count - 1 do begin Result := Result + sl[i] + ','; if (i <> sl.Count - 1) and (i mod 4 = 3) then begin Result += #39 + ' +' + LineEnding + ' ' + #39; end; end; Delete(Result, Length(Result), 1); Result := Result + #39 + ','; end; end; procedure TForm1.AddCPUData(sl, SubArchList: TStrings; cpu: string); var source_SL: TStringList; SubArchData: array of TStringList; ofs, i: integer; s, s1, s2: string; sa: TStringArray; begin if Pos('generic', cpu) > 0 then begin Exit; end; source_SL := TStringList.Create; source_SL.LoadFromFile(cpu); s := source_SL.Text; source_SL.Free; SetLength(SubArchData, SubArchList.Count); for i := 0 to Length(SubArchData) - 1 do begin SubArchData[i] := TStringList.Create; end; ofs := 1; ofs := Pos('embedded_controllers', s, ofs); if ofs > 0 then begin while ofs > 0 do begin ofs := Pos('controllertypestr', s, ofs); if ofs > 0 then begin s1 := ''; s2 := ''; ofs := Pos(#39, s, ofs); Inc(ofs); if s[ofs] <> #39 then begin repeat s1 += s[ofs]; Inc(ofs); until s[ofs] = #39; ofs := Pos('cpu_', s, ofs); Inc(ofs, 4); repeat s2 += s[ofs]; Inc(ofs); until not (s[ofs] in ['0'..'9', 'a'..'z', 'A'..'Z', '_']); i := 0; while UpCase(s2) <> UpCase(SubArchList[i]) do begin Inc(i); end; SubArchData[i].Add(s1); end; end; end; sa := cpu.Split('/'); if Length(sa) >= 2 then begin sl.Add(''); sl.Add(' ' + sa[Length(sa) - 2] + '_List: array of string = ('); end; for i := 0 to Length(SubArchData) - 1 do begin sl.Add(''); sl.Add(' // ' + SubArchList[i]); sl.Add(AddNewCommaText(SubArchData[i])); end; s := sl[sl.Count - 1]; Delete(s, Length(s), 1); sl[sl.Count - 1] := s + ');'; sl.Add(''); end; for i := 0 to Length(SubArchData) - 1 do begin SubArchData[i].Free; end; end; procedure TForm1.AddControllerDataList(sl: TStrings; cpu: string); var source_SL, sl1: TStringList; ofs: integer; s, s1: string; sa: TStringArray; begin if Pos('generic', cpu) > 0 then begin Exit; end; source_SL := TStringList.Create; sl1 := TStringList.Create; source_SL.LoadFromFile(cpu); s := source_SL.Text; source_SL.Free; sa := cpu.Split('/'); if Length(sa) >= 2 then begin sl.Add(''); s1 := sa[Length(sa) - 2]; sl.Add('type'); sl.Add(' T' + s1 + '_ControllerDataList = array of array of String;'); sl.Add(''); sl.Add('const'); sl.Add(' ' + s1 + '_ControllerDataList : T' + s1 + '_ControllerDataList = ('); end; ofs := Pos('embedded_controllers', s); sl.Add(' ('#39 + ControllerDataType(s) + #39'),'); if ofs > 0 then begin while (ofs > 0) do begin ofs := Pos('(', s, ofs); ofs := Pos('(', s, ofs); repeat FindText(s, ofs); while not (s[ofs] in [';', ')']) do begin Inc(ofs); end; until s[ofs] = ')'; repeat Inc(ofs); until s[ofs] in [',', ')']; if s[ofs] = ',' then begin repeat repeat ofs := Pos(':', s, ofs); sl1.Add(FindText(s, ofs)); while not (s[ofs] in [';', ')']) do begin Inc(ofs); end; while not (s[ofs] in ['0'..'9', 'a'..'z', 'A'..'Z', '_', '+', '-', '*', '/', '$', ')']) do begin Inc(ofs); end; until s[ofs] = ')'; sl.Add(' ('#39 + Comma(sl1) + #39'),'); sl1.Clear; repeat Inc(ofs); until s[ofs] in [',', ')']; until s[ofs] = ')'; end; ofs := Pos('embedded_controllers', s, ofs); end; s := sl[sl.Count - 1]; Delete(s, Length(s), 1); sl[sl.Count - 1] := s + ');'; end; sl1.Free; end; procedure TForm1.Generate_BitBtnClick(Sender: TObject); const UName = 'Embedded_GUI_Embedded_List_Const'; var i: integer; CPU_SL, SubArchList: TStringList; begin CPU_SL := TStringList.Create; FindAllFiles(CPU_SL, DirectoryEdit1.Directory, 'cpuinfo.pas', True); SynEdit1.Clear; SynEdit1.Lines.Add(''); SynEdit1.Lines.Add('// Diese Unit wird automatisch durch das Tool "./Tool/Embedded_List_to_const" erzeugt.'); SynEdit1.Lines.Add('// Die Arrays werden aus "./fpc.src/fpc/compiler/avr/cpuinfo.pas" und'); SynEdit1.Lines.Add('// "./fpc.src/fpc/compiler/arm/cpuinfo.pas" importiert.'); SynEdit1.Lines.Add(''); SynEdit1.Lines.Add('unit ' + UName + ';'); SynEdit1.Lines.Add(''); SynEdit1.Lines.Add('interface'); SynEdit1.Lines.Add(''); for i := 0 to CPU_SL.Count - 1 do begin SubArchList := AddSubArch(SynEdit1.Lines, CPU_SL[i]); AddCPUData(SynEdit1.Lines, SubArchList, CPU_SL[i]); SubArchList.Free; end; for i := 0 to CPU_SL.Count - 1 do begin AddControllerDataList(SynEdit1.Lines, CPU_SL[i]); end; SynEdit1.Lines.Add(''); SynEdit1.Lines.Add('implementation'); SynEdit1.Lines.Add(''); SynEdit1.Lines.Add('begin'); SynEdit1.Lines.Add('end.'); SynEdit1.Lines.SaveToFile('../../Lazarus_Arduino_AVR_GUI_Package/' + LowerCase(UName) + '.pas'); CPU_SL.Free; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { A GLSL shader that applies bump mapping. Notes: 1) Alpha is a synthetic property, in real life your should set each color's Alpha individualy 2) TVXSLMLBumpShader takes all Light parameters directly from OpenGL (that includes TVXLightSource's) TODO: 1) Implement IGLShaderDescription in all shaders. } unit VXS.GLSLBumpShader; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.OpenGL, VXS.Texture, VXS.Scene, VXS.VectorGeometry, VXS.VectorTypes, VXS.Cadencer, VXS.Strings, VXS.CustomShader, VXS.Color, VXS.RenderContextInfo, VXS.Material, VXS.GLSLShader; type EGLSLBumpShaderException = class(EGLSLShaderException); // An abstract class. TVXBaseCustomGLSLBumpShader = class(TVXCustomGLSLShader, IVXMaterialLibrarySupported) private FBumpHeight: Single; FBumpSmoothness: Integer; FSpecularPower: Single; FSpecularSpread: Single; FLightPower: Single; FMaterialLibrary: TVXMaterialLibrary; FNormalTexture: TVXTexture; FSpecularTexture: TVXTexture; FNormalTextureName: TVXLibMaterialName; FSpecularTextureName: TVXLibMaterialName; function GetNormalTextureName: TVXLibMaterialName; function GetSpecularTextureName: TVXLibMaterialName; procedure SetNormalTextureName(const Value: TVXLibMaterialName); procedure SetSpecularTextureName(const Value: TVXLibMaterialName); procedure SetSpecularTexture(const Value: TVXTexture); procedure SetNormalTexture(const Value: TVXTexture); // Implementing IGLMaterialLibrarySupported. function GetMaterialLibrary: TVXAbstractMaterialLibrary; protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override; procedure SetMaterialLibrary(const Value: TVXMaterialLibrary); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner : TComponent); override; property BumpHeight: Single read FBumpHeight write FBumpHeight; property BumpSmoothness: Integer read FBumpSmoothness write FBumpSmoothness; property SpecularPower: Single read FSpecularPower write FSpecularPower; property SpecularSpread: Single read FSpecularSpread write FSpecularSpread; property LightPower: Single read FLightPower write FLightPower; property NormalTexture: TVXTexture read FNormalTexture write SetNormalTexture; property SpecularTexture: TVXTexture read FSpecularTexture write SetSpecularTexture; property NormalTextureName: TVXLibMaterialName read GetNormalTextureName write SetNormalTextureName; property SpecularTextureName: TVXLibMaterialName read GetSpecularTextureName write SetSpecularTextureName; property MaterialLibrary: TVXMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; end; // An abstract class. TVXBaseCustomGLSLBumpShaderMT = class(TVXBaseCustomGLSLBumpShader) private FMainTexture: TVXTexture; FMainTextureName: TVXLibMaterialName; function GetMainTextureName: string; procedure SetMainTextureName(const Value: string); protected procedure SetMaterialLibrary(const Value: TVXMaterialLibrary); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public property MainTexture: TVXTexture read FMainTexture write FMainTexture; property MainTextureName: TVXLibMaterialName read GetMainTextureName write SetMainTextureName; end; // One Light shaders. TVXCustomGLSLBumpShaderAM = class(TVXBaseCustomGLSLBumpShaderMT) private FAmbientColor: TVXColor; FDiffuseColor: TVXColor; FSpecularColor: TVXColor; function GetAlpha: Single; procedure SetAlpha(const Value: Single); protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; property AmbientColor: TVXColor read FAmbientColor; property DiffuseColor: TVXColor read FDiffuseColor; property SpecularColor: TVXColor read FSpecularColor; property Alpha: Single read GetAlpha write SetAlpha; end; TVXCustomGLSLBumpShaderMT = class(TVXBaseCustomGLSLBumpShaderMT) protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); override; end; TVXCustomGLSLBumpShader = class(TVXBaseCustomGLSLBumpShader, IGLShaderDescription) private // Implementing IGLShaderDescription. procedure SetShaderTextures(const Textures: array of TVXTexture); procedure GetShaderTextures(var Textures: array of TVXTexture); procedure SetShaderColorParams(const AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); procedure GetShaderColorParams(var AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); procedure SetShaderMiscParameters(const ACadencer: TVXCadencer; const AMatLib: TVXMaterialLibrary; const ALightSources: TVXLightSourceSet); procedure GetShaderMiscParameters(var ACadencer: TVXCadencer; var AMatLib: TVXMaterialLibrary; var ALightSources: TVXLightSourceSet); function GetShaderAlpha: Single; procedure SetShaderAlpha(const Value: Single); function GetShaderDescription: string; protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); override; end; // MultiLight shaders. TVXCustomGLSLMLBumpShader = class(TVXBaseCustomGLSLBumpShader, IGLShaderDescription) private FLightSources: TVXLightSourceSet; FLightCompensation: Single; procedure SetLightSources(const Value: TVXLightSourceSet); procedure SetLightCompensation(const Value: Single); // Implementing IGLShaderDescription. procedure SetShaderTextures(const Textures: array of TVXTexture); procedure GetShaderTextures(var Textures: array of TVXTexture); procedure SetShaderColorParams(const AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); procedure GetShaderColorParams(var AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); procedure SetShaderMiscParameters(const ACadencer: TVXCadencer; const AMatLib: TVXMaterialLibrary; const ALightSources: TVXLightSourceSet); procedure GetShaderMiscParameters(var ACadencer: TVXCadencer; var AMatLib: TVXMaterialLibrary; var ALightSources: TVXLightSourceSet); function GetShaderAlpha: Single; procedure SetShaderAlpha(const Value: Single); function GetShaderDescription: string; protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); override; public constructor Create(AOwner : TComponent); override; property LightSources: TVXLightSourceSet read FLightSources write SetLightSources default [1]; { Setting LightCompensation to a value less than 1 decreeses individual light intensity when using multiple lights } property LightCompensation: Single read FLightCompensation write SetLightCompensation; end; TVXCustomGLSLMLBumpShaderMT = class(TVXBaseCustomGLSLBumpShaderMT) private FLightSources: TVXLightSourceSet; FLightCompensation: Single; procedure SetLightSources(const Value: TVXLightSourceSet); procedure SetLightCompensation(const Value: Single); protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); override; public constructor Create(AOwner : TComponent); override; property LightSources: TVXLightSourceSet read FLightSources write SetLightSources default [1]; { Setting LightCompensation to a value less than 1 decreeses individual light intensity when using multiple lights } property LightCompensation: Single read FLightCompensation write SetLightCompensation; end; {************** Published **************} // One light shaders. TVXSLBumpShaderMT = class(TVXCustomGLSLBumpShaderMT) published property MainTextureName; property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; end; TVXSLBumpShader = class(TVXCustomGLSLBumpShader) published property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; end; TVXSLBumpShaderAM = class(TVXCustomGLSLBumpShaderAM) published property AmbientColor; property DiffuseColor; property SpecularColor; property Alpha stored False; property MainTextureName; property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; end; // Multi light shaders. TVXSLMLBumpShader = class(TVXCustomGLSLMLBumpShader) published property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; property LightSources; property LightCompensation; end; TVXSLMLBumpShaderMT = class(TVXCustomGLSLMLBumpShaderMT) published property MainTextureName; property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; property LightSources; property LightCompensation; end; //----------------------------------------------------------------------------- implementation //----------------------------------------------------------------------------- procedure GetVertexProgramCode(const Code: TStrings); begin with Code do begin Clear; Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add('varying vec3 LightDirection; '); Add(' '); Add('void main( void ) '); Add('{ '); Add(' gl_Position = ftransform(); '); Add(' Texcoord = gl_MultiTexCoord0.xy; '); Add(' '); Add(' vec3 fvViewDirection = (gl_ModelViewMatrix * gl_Vertex).xyz; '); Add(' vec3 fvLightDirection = gl_LightSource[0].position.xyz - fvViewDirection; '); Add(' '); Add(' vec3 fvNormal = gl_NormalMatrix * gl_Normal; '); Add(' vec3 fvBinormal = gl_NormalMatrix * gl_MultiTexCoord2.xyz; '); Add(' vec3 fvTangent = gl_NormalMatrix * gl_MultiTexCoord1.xyz; '); Add(' '); Add(' ViewDirection.x = dot( fvTangent, fvViewDirection ); '); Add(' ViewDirection.y = dot( fvBinormal, fvViewDirection ); '); Add(' ViewDirection.z = dot( fvNormal, fvViewDirection ); '); Add(' '); Add(' LightDirection.x = dot( fvTangent, fvLightDirection ); '); Add(' LightDirection.y = dot( fvBinormal, fvLightDirection ); '); Add(' LightDirection.z = dot( fvNormal, fvLightDirection ); '); Add(' '); Add(' LightDirection = normalize(LightDirection); '); Add(' ViewDirection = normalize(ViewDirection); '); Add('} '); end; end; procedure GetFragmentProgramCodeMP(const Code: TStrings; const UseSpecularMap: Boolean; const UseNormalMap: Boolean); begin with Code do begin Clear; Add('uniform vec4 fvAmbient; '); Add('uniform vec4 fvSpecular; '); Add('uniform vec4 fvDiffuse; '); Add(' '); Add('uniform float fLightPower; '); Add('uniform float fSpecularPower; '); Add('uniform float fSpecularSpread; '); if UseNormalMap then begin Add('uniform sampler2D bumpMap; '); Add('uniform float fBumpHeight; '); Add('uniform float fBumpSmoothness; '); end; Add(' '); Add('uniform sampler2D baseMap; '); if UseSpecularMap then Add('uniform sampler2D specMap; '); Add(' '); Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add('varying vec3 LightDirection; '); Add(' '); Add('void main( void ) '); Add('{ '); if UseNormalMap then Add(' vec3 fvNormal = normalize( ( texture2D( bumpMap, Texcoord ).xyz * fBumpSmoothness) - fBumpHeight * fBumpSmoothness); ') else Add(' vec3 fvNormal = vec3(0.0, 0.0, 1);'); Add(' '); Add(' float fNDotL = dot( fvNormal, LightDirection ); '); Add(' vec3 fvReflection = normalize( ( (fSpecularSpread * fvNormal ) * fNDotL ) - LightDirection ); '); Add(' '); Add(' float fRDotV = max( dot( fvReflection, -ViewDirection ), 0.0 ); '); Add(' '); Add(' vec4 fvBaseColor = texture2D( baseMap, Texcoord ); '); if UseSpecularMap then Add(' vec4 fvSpecColor = texture2D( specMap, Texcoord ) * fvSpecular; ') else Add(' vec4 fvSpecColor = fvSpecular; '); Add(' '); Add(' vec4 fvTotalDiffuse = clamp(fvDiffuse * fNDotL, 0.0, 1.0); '); Add(' '); Add(' // (fvTotalDiffuse + 0.2) / 1.2 is used for removing artefacts on the non-lit side '); Add(' vec4 fvTotalSpecular = clamp((pow(fRDotV, fSpecularPower ) ) * (fvTotalDiffuse + 0.2) / 1.2 * fvSpecColor, 0.0, 1.0); '); Add(' '); Add(' gl_FragColor = fLightPower * (fvBaseColor * ( fvAmbient + fvTotalDiffuse ) + fvTotalSpecular); '); Add('} '); end; end; procedure GetFragmentProgramCode(const Code: TStrings; const UseSpecularMap: Boolean; const UseNormalMap: Boolean); begin with Code do begin Clear; Add('uniform float fLightPower; '); Add('uniform float fSpecularPower; '); Add('uniform float fSpecularSpread; '); if UseNormalMap then begin Add('uniform sampler2D bumpMap; '); Add('uniform float fBumpHeight; '); Add('uniform float fBumpSmoothness; '); end; Add(' '); Add('uniform sampler2D baseMap; '); if UseSpecularMap then Add('uniform sampler2D specMap; '); Add(' '); Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add('varying vec3 LightDirection; '); Add(' '); Add('void main( void ) '); Add('{ '); if UseNormalMap then Add(' vec3 fvNormal = normalize( ( texture2D( bumpMap, Texcoord ).xyz * fBumpSmoothness) - fBumpHeight * fBumpSmoothness); ') else Add(' vec3 fvNormal = vec3(0.0, 0.0, 1.0);'); Add(' '); Add(' float fNDotL = dot( fvNormal, LightDirection ); '); Add(' vec3 fvReflection = normalize( ( (fSpecularSpread * fvNormal ) * fNDotL ) - LightDirection ); '); Add(' '); Add(' float fRDotV = max(dot( fvReflection, -ViewDirection ), 0.0); '); Add(' '); Add(' vec4 fvBaseColor = texture2D( baseMap, Texcoord ); '); if UseSpecularMap then Add(' vec4 fvSpecColor = texture2D( specMap, Texcoord ) * gl_LightSource[0].specular; ') else Add(' vec4 fvSpecColor = gl_LightSource[0].specular; '); Add(' '); Add(' vec4 fvTotalDiffuse = clamp(gl_LightSource[0].diffuse * fNDotL, 0.0, 1.0); '); Add(' '); Add(' // (fvTotalDiffuse + 0.2) / 1.2 is used for removing artefacts on the non-lit side '); Add(' vec4 fvTotalSpecular = clamp((pow(fRDotV, fSpecularPower ) ) * (fvTotalDiffuse + 0.2) / 1.2 * fvSpecColor, 0.0, 1.0); '); Add(' '); Add(' gl_FragColor = fLightPower * (fvBaseColor * ( gl_LightSource[0].ambient + fvTotalDiffuse ) + fvTotalSpecular); '); Add('} '); end; end; procedure GetMLVertexProgramCode(const Code: TStrings); begin with Code do begin Clear; Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add(' '); Add('varying vec3 fvViewDirection; '); Add('varying vec3 fvNormal; '); Add('varying vec3 fvBinormal; '); Add('varying vec3 fvTangent; '); Add(' '); Add('void main( void ) '); Add('{ '); Add(' gl_Position = ftransform(); '); Add(' Texcoord = gl_MultiTexCoord0.xy; '); Add(' '); Add(' fvViewDirection = (gl_ModelViewMatrix * gl_Vertex).xyz; '); Add(' '); Add(' fvNormal = gl_NormalMatrix * gl_Normal; '); Add(' fvBinormal = gl_NormalMatrix * gl_MultiTexCoord2.xyz; '); Add(' fvTangent = gl_NormalMatrix * gl_MultiTexCoord1.xyz; '); Add(' '); Add(' ViewDirection.x = dot( fvTangent, fvViewDirection ); '); Add(' ViewDirection.y = dot( fvBinormal, fvViewDirection ); '); Add(' ViewDirection.z = dot( fvNormal, fvViewDirection ); '); Add(' '); Add(' ViewDirection = normalize(ViewDirection); '); Add('} '); end; end; procedure GetMLFragmentProgramCodeBeg(const Code: TStrings; const UseSpecularMap: Boolean; const UseNormalMap: Boolean); begin with Code do begin Clear; Add('uniform float fLightPower; '); Add('uniform float fSpecularPower; '); Add('uniform float fSpecularSpread; '); if UseNormalMap then begin Add('uniform sampler2D bumpMap; '); Add('uniform float fBumpHeight; '); Add('uniform float fBumpSmoothness; '); end; Add(' '); Add('uniform sampler2D baseMap; '); if UseSpecularMap then Add('uniform sampler2D specMap; '); Add(' '); Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add(' '); Add('varying vec3 fvViewDirection; '); Add('varying vec3 fvNormal; '); Add('varying vec3 fvBinormal; '); Add('varying vec3 fvTangent; '); Add(' '); Add('void main( void ) '); Add('{ '); Add(' vec3 LightDirection;'); Add(' vec3 fvLightDirection; '); Add(' '); if UseNormalMap then Add(' vec3 fvBumpNormal = normalize( ( texture2D( bumpMap, Texcoord ).xyz * fBumpSmoothness) - fBumpHeight * fBumpSmoothness); ') else Add(' vec3 fvBumpNormal = vec3(0.0, 0.0, 1);'); Add(' '); Add(' float fNDotL ; '); Add(' vec3 fvReflection ; '); Add(' float fRDotV ; '); Add(' vec4 fvBaseColor = texture2D( baseMap, Texcoord ); '); if UseSpecularMap then Add(' vec4 fvSpecColor = texture2D( specMap, Texcoord ); ') else Add(' vec4 fvSpecColor = vec4(1.0, 1.0, 1.0, 1.0); '); Add(' vec4 fvNewDiffuse ; '); Add(' vec4 fvTotalDiffuse = vec4(0, 0, 0, 0); '); Add(' vec4 fvTotalAmbient = vec4(0, 0, 0, 0); '); Add(' vec4 fvTotalSpecular = vec4(0, 0, 0, 0); '); end; end; procedure GetMLFragmentProgramCodeMid(const Code: TStrings; const CurrentLight: Integer); begin with Code do begin Add(' fvLightDirection = gl_LightSource[' + IntToStr(CurrentLight) + '].position.xyz - fvViewDirection; '); Add(' '); Add(' LightDirection.x = dot( fvTangent, fvLightDirection ); '); Add(' LightDirection.y = dot( fvBinormal, fvLightDirection ); '); Add(' LightDirection.z = dot( fvNormal, fvLightDirection ); '); Add(' LightDirection = normalize(LightDirection); '); Add(' '); Add(' fNDotL = dot( fvBumpNormal, LightDirection ); '); Add(' fvReflection = normalize( ( (fSpecularSpread * fvBumpNormal ) * fNDotL ) - LightDirection ); '); Add(' fRDotV = max( dot( fvReflection, -ViewDirection ), 0.0 ); '); Add(' fvNewDiffuse = clamp(gl_LightSource[' + IntToStr(CurrentLight) + '].diffuse * fNDotL, 0.0, 1.0); '); Add(' fvTotalDiffuse = min(fvTotalDiffuse + fvNewDiffuse, 1.0); '); Add(' fvTotalSpecular = min(fvTotalSpecular + clamp((pow(fRDotV, fSpecularPower ) ) * (fvNewDiffuse + 0.2) / 1.2 * (fvSpecColor * gl_LightSource[' + IntToStr(CurrentLight) + '].specular), 0.0, 1.0), 1.0); '); Add(' fvTotalAmbient = fvTotalAmbient + gl_LightSource[' + IntToStr(CurrentLight) + '].ambient; '); end; end; procedure GetMLFragmentProgramCodeEnd(const Code: TStrings; const FLightCount: Integer; const FLightCompensation: Single); var Temp: AnsiString; begin with Code do begin Str((1 + (FLightCount - 1) * FLightCompensation) / FLightCount :1 :1, Temp); if (FLightCount = 1) or (FLightCompensation = 1) then Add(' gl_FragColor = fLightPower * (fvBaseColor * ( fvTotalAmbient + fvTotalDiffuse ) + fvTotalSpecular); ') else Add(' gl_FragColor = fLightPower * (fvBaseColor * ( fvTotalAmbient + fvTotalDiffuse ) + fvTotalSpecular) * ' + string(Temp) + '; '); Add('} '); end; end; { TVXBaseCustomGLSLBumpShader } constructor TVXBaseCustomGLSLBumpShader.Create(AOwner: TComponent); begin inherited; FSpecularPower := 6; FSpecularSpread := 1.5; FLightPower := 1; FBumpHeight := 0.5; FBumpSmoothness := 300; TStringList(VertexProgram.Code).OnChange := nil; TStringList(FragmentProgram.Code).OnChange := nil; VertexProgram.Enabled := True; FragmentProgram.Enabled := True; end; procedure TVXBaseCustomGLSLBumpShader.DoApply( var rci: TVXRenderContextInfo; Sender: TObject); begin // Don't inherit not to call the event. GetGLSLProg.UseProgramObject; Param['fSpecularPower'].AsVector1f := FSpecularPower; Param['fSpecularSpread'].AsVector1f := FSpecularSpread; Param['fLightPower'].AsVector1f := FLightPower; if FSpecularTexture <> nil then Param['specMap'].AsTexture2D[2] := FSpecularTexture; {$IFNDEF VXS_OPTIMIZATIONS} if FNormalTexture <> nil then {$ENDIF} begin Param['bumpMap'].AsTexture2D[1] := FNormalTexture; Param['fBumpHeight'].AsVector1f := FBumpHeight; Param['fBumpSmoothness'].AsVector1f := FBumpSmoothness; end; end; function TVXBaseCustomGLSLBumpShader.DoUnApply( var rci: TVXRenderContextInfo): Boolean; begin //don't inherit not to call the event Result := False; GetGLSLProg.EndUseProgramObject; end; function TVXBaseCustomGLSLBumpShader.GetMaterialLibrary: TVXAbstractMaterialLibrary; begin Result := FMaterialLibrary; end; function TVXBaseCustomGLSLBumpShader.GetNormalTextureName: TVXLibMaterialName; begin Result := FMaterialLibrary.GetNameOfTexture(FNormalTexture); if Result = '' then Result := FNormalTextureName; end; function TVXBaseCustomGLSLBumpShader.GetSpecularTextureName: TVXLibMaterialName; begin Result := FMaterialLibrary.GetNameOfTexture(FSpecularTexture); if Result = '' then Result := FSpecularTextureName; end; procedure TVXBaseCustomGLSLBumpShader.Notification( AComponent: TComponent; Operation: TOperation); var Index: Integer; begin inherited; if Operation = opRemove then if AComponent = FMaterialLibrary then if FMaterialLibrary <> nil then begin // Need to nil the textures that were ownned by it. if FNormalTexture <> nil then begin Index := FMaterialLibrary.Materials.GetTextureIndex(FNormalTexture); if Index <> -1 then SetNormalTexture(nil); end; if FSpecularTexture <> nil then begin Index := FMaterialLibrary.Materials.GetTextureIndex(FSpecularTexture); if Index <> -1 then SetSpecularTexture(nil); end; FMaterialLibrary := nil; end; end; procedure TVXBaseCustomGLSLBumpShader.SetMaterialLibrary( const Value: TVXMaterialLibrary); begin if FMaterialLibrary <> nil then FMaterialLibrary.RemoveFreeNotification(Self); FMaterialLibrary := Value; if FMaterialLibrary <> nil then begin FMaterialLibrary.FreeNotification(Self); if FNormalTextureName <> '' then SetNormalTextureName(FNormalTextureName); if FSpecularTextureName <> '' then SetSpecularTextureName(FSpecularTextureName); end else begin FNormalTextureName := ''; FSpecularTextureName := ''; end; end; procedure TVXBaseCustomGLSLBumpShader.SetNormalTexture( const Value: TVXTexture); begin FNormalTexture := Value; FinalizeShader; end; procedure TVXBaseCustomGLSLBumpShader.SetNormalTextureName( const Value: TVXLibMaterialName); begin if FMaterialLibrary = nil then begin FNormalTextureName := Value; if not (csLoading in ComponentState) then raise EGLSLBumpShaderException.Create(strErrorEx + strMatLibNotDefined); end else begin SetNormalTexture(FMaterialLibrary.TextureByName(Value)); FNormalTextureName := ''; end; end; procedure TVXBaseCustomGLSLBumpShader.SetSpecularTexture( const Value: TVXTexture); begin FSpecularTexture := Value; FinalizeShader; end; procedure TVXBaseCustomGLSLBumpShader.SetSpecularTextureName( const Value: TVXLibMaterialName); begin if FMaterialLibrary = nil then begin FSpecularTextureName := Value; if not (csLoading in ComponentState) then raise EGLSLBumpShaderException.Create(strErrorEx + strMatLibNotDefined); end else begin SetSpecularTexture(FMaterialLibrary.TextureByName(Value)); FSpecularTextureName := ''; end; end; { TVXBaseCustomGLSLBumpShaderMT } function TVXBaseCustomGLSLBumpShaderMT.GetMainTextureName: TVXLibMaterialName; begin Result := FMaterialLibrary.GetNameOfTexture(FMainTexture); if Result = '' then Result := FMainTextureName; end; procedure TVXBaseCustomGLSLBumpShaderMT.Notification( AComponent: TComponent; Operation: TOperation); var Index: Integer; begin if Operation = opRemove then if AComponent = FMaterialLibrary then if FMaterialLibrary <> nil then begin //need to nil the textures that were ownned by it if FMainTexture <> nil then begin Index := FMaterialLibrary.Materials.GetTextureIndex(FMainTexture); if Index <> -1 then FMainTexture := nil; end; end; inherited; end; procedure TVXBaseCustomGLSLBumpShaderMT.SetMainTextureName( const Value: TVXLibMaterialName); begin if FMaterialLibrary = nil then begin FMainTextureName := Value; if not (csLoading in ComponentState) then raise EGLSLBumpShaderException.Create(strErrorEx + strMatLibNotDefined); end else begin FMainTexture := FMaterialLibrary.TextureByName(Value); FMainTextureName := ''; end; end; procedure TVXBaseCustomGLSLBumpShaderMT.SetMaterialLibrary( const Value: TVXMaterialLibrary); begin inherited; if FMaterialLibrary <> nil then begin if FMainTextureName <> '' then SetMainTextureName(FMainTextureName); end else FMainTextureName := ''; end; { TVXCustomGLSLBumpShaderAM } constructor TVXCustomGLSLBumpShaderAM.Create(AOwner: TComponent); begin inherited; FAmbientColor := TVXColor.Create(Self); FDiffuseColor := TVXColor.Create(Self); FSpecularColor := TVXColor.Create(Self); // Setup initial parameters. FAmbientColor.SetColor(0.15, 0.15, 0.15, 1); FDiffuseColor.SetColor(1, 1, 1, 1); FSpecularColor.SetColor(1, 1, 1, 1); end; destructor TVXCustomGLSLBumpShaderAM.Destroy; begin FAmbientColor.Destroy; FDiffuseColor.Destroy; FSpecularColor.Destroy; inherited; end; procedure TVXCustomGLSLBumpShaderAM.DoApply(var rci: TVXRenderContextInfo; Sender: TObject); begin inherited; Param['fvAmbient'].AsVector4f := FAmbientColor.Color; Param['fvDiffuse'].AsVector4f := FDiffuseColor.Color; Param['fvSpecular'].AsVector4f := FSpecularColor.Color; Param['baseMap'].AsTexture2D[0] := FMainTexture; end; procedure TVXCustomGLSLBumpShaderAM.DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); begin GetVertexProgramCode(VertexProgram.Code); GetFragmentProgramCodeMP(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; function TVXCustomGLSLBumpShaderAM.GetAlpha: Single; begin Result := (FAmbientColor.Alpha + FDiffuseColor.Alpha + FSpecularColor.Alpha) / 3; end; procedure TVXCustomGLSLBumpShaderAM.SetAlpha(const Value: Single); begin FAmbientColor.Alpha := Value; FDiffuseColor.Alpha := Value; FSpecularColor.Alpha := Value; end; { TVXCustomGLSLMLBumpShaderMT } constructor TVXCustomGLSLMLBumpShaderMT.Create(AOwner: TComponent); begin inherited; FLightSources := [1]; FLightCompensation := 1; end; procedure TVXCustomGLSLMLBumpShaderMT.DoApply(var rci: TVXRenderContextInfo; Sender: TObject); begin inherited; Param['baseMap'].AsTexture2D[0] := FMainTexture; end; procedure TVXCustomGLSLMLBumpShaderMT.DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); var I: Integer; lLightCount: Integer; begin GetMLVertexProgramCode(VertexProgram.Code); with FragmentProgram.Code do begin GetMLFragmentProgramCodeBeg(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); lLightCount := 0; // Repeat for all lights. for I := 0 to vxsShaderMaxLightSources - 1 do if I + 1 in FLightSources then begin GetMLFragmentProgramCodeMid(FragmentProgram.Code, I); Inc(lLightCount); end; GetMLFragmentProgramCodeEnd(FragmentProgram.Code, lLightCount, FLightCompensation); end; VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; procedure TVXCustomGLSLMLBumpShaderMT.SetLightCompensation( const Value: Single); begin FLightCompensation := Value; FinalizeShader; end; procedure TVXCustomGLSLMLBumpShaderMT.SetLightSources( const Value: TVXLightSourceSet); begin Assert(Value <> [], strErrorEx + strShaderNeedsAtLeastOneLightSource); FLightSources := Value; FinalizeShader; end; { TVXCustomGLSLBumpShaderMT } procedure TVXCustomGLSLBumpShaderMT.DoApply( var rci: TVXRenderContextInfo; Sender: TObject); begin inherited; Param['baseMap'].AsTexture2D[0] := FMainTexture; end; procedure TVXCustomGLSLBumpShaderMT.DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); begin GetVertexProgramCode(VertexProgram.Code); GetFragmentProgramCode(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); inherited; end; { TVXCustomGLSLBumpShader } procedure TVXCustomGLSLBumpShader.DoApply(var rci: TVXRenderContextInfo; Sender: TObject); begin inherited; Param['baseMap'].AsVector1i := 0; // Use the current texture. end; procedure TVXCustomGLSLBumpShader.DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); begin GetVertexProgramCode(VertexProgram.Code); GetFragmentProgramCode(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; function TVXCustomGLSLBumpShader.GetShaderAlpha: Single; begin //ignore Result := -1; end; procedure TVXCustomGLSLBumpShader.GetShaderColorParams(var AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); begin //ignore AAmbientColor := NullHmgVector; ADiffuseColor := NullHmgVector; ASpecularcolor := NullHmgVector; end; procedure TVXCustomGLSLBumpShader.GetShaderTextures( var Textures: array of TVXTexture); begin Textures[0] := FNormalTexture; Textures[1] := FSpecularTexture; end; procedure TVXCustomGLSLBumpShader.GetShaderMiscParameters(var ACadencer: TVXCadencer; var AMatLib: TVXMaterialLibrary; var ALightSources: TVXLightSourceSet); begin ACadencer := nil; AMatLib := FMaterialLibrary; ALightSources := [0]; end; procedure TVXCustomGLSLBumpShader.SetShaderAlpha(const Value: Single); begin //ignore end; procedure TVXCustomGLSLBumpShader.SetShaderColorParams(const AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); begin //ignore end; procedure TVXCustomGLSLBumpShader.SetShaderMiscParameters( const ACadencer: TVXCadencer; const AMatLib: TVXMaterialLibrary; const ALightSources: TVXLightSourceSet); begin SetMaterialLibrary(AMatLib); end; procedure TVXCustomGLSLBumpShader.SetShaderTextures( const Textures: array of TVXTexture); begin SetNormalTexture(Textures[0]); SetSpecularTexture(Textures[1]); end; function TVXCustomGLSLBumpShader.GetShaderDescription: string; begin Result := 'ShaderTexture1 is NormalMap, ShaderTexture2 is SpecularMap' end; { TVXCustomGLSLMLBumpShader } constructor TVXCustomGLSLMLBumpShader.Create(AOwner: TComponent); begin inherited; FLightSources := [1]; FLightCompensation := 1; end; procedure TVXCustomGLSLMLBumpShader.DoApply(var rci: TVXRenderContextInfo; Sender: TObject); begin inherited; Param['baseMap'].AsVector1i := 0; // Use the current texture. end; procedure TVXCustomGLSLMLBumpShader.DoInitialize(var rci : TVXRenderContextInfo; Sender : TObject); var I: Integer; lLightCount: Integer; begin GetMLVertexProgramCode(VertexProgram.Code); with FragmentProgram.Code do begin GetMLFragmentProgramCodeBeg(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); lLightCount := 0; // Repeat for all lights. for I := 0 to vxsShaderMaxLightSources - 1 do if I + 1 in FLightSources then begin GetMLFragmentProgramCodeMid(FragmentProgram.Code, I); Inc(lLightCount); end; GetMLFragmentProgramCodeEnd(FragmentProgram.Code, lLightCount, FLightCompensation); end; VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; procedure TVXCustomGLSLMLBumpShader.SetLightCompensation( const Value: Single); begin FLightCompensation := Value; FinalizeShader; end; procedure TVXCustomGLSLMLBumpShader.SetLightSources( const Value: TVXLightSourceSet); begin Assert(Value <> [], strErrorEx + strShaderNeedsAtLeastOneLightSource); FLightSources := Value; FinalizeShader; end; function TVXCustomGLSLMLBumpShader.GetShaderAlpha: Single; begin //ignore Result := -1; end; procedure TVXCustomGLSLMLBumpShader.GetShaderColorParams(var AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); begin //ignore AAmbientColor := NullHmgVector; ADiffuseColor := NullHmgVector; ASpecularcolor := NullHmgVector; end; function TVXCustomGLSLMLBumpShader.GetShaderDescription: string; begin Result := 'ShaderTexture1 is NormalMap, ShaderTexture2 is SpecularMap'; end; procedure TVXCustomGLSLMLBumpShader.GetShaderMiscParameters( var ACadencer: TVXCadencer; var AMatLib: TVXMaterialLibrary; var ALightSources: TVXLightSourceSet); begin ACadencer := nil; AMatLib := FMaterialLibrary; ALightSources := FLightSources; end; procedure TVXCustomGLSLMLBumpShader.GetShaderTextures( var Textures: array of TVXTexture); begin Textures[0] := FNormalTexture; Textures[1] := FSpecularTexture; end; procedure TVXCustomGLSLMLBumpShader.SetShaderAlpha(const Value: Single); begin //ignore end; procedure TVXCustomGLSLMLBumpShader.SetShaderColorParams(const AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); begin //ignore end; procedure TVXCustomGLSLMLBumpShader.SetShaderMiscParameters( const ACadencer: TVXCadencer; const AMatLib: TVXMaterialLibrary; const ALightSources: TVXLightSourceSet); begin SetMaterialLibrary(AMatLib); SetLightSources(ALightSources); end; procedure TVXCustomGLSLMLBumpShader.SetShaderTextures( const Textures: array of TVXTexture); begin SetNormalTexture(Textures[0]); SetSpecularTexture(Textures[1]); end; initialization RegisterClasses([TVXSLBumpShaderMT, TVXSLBumpShader, TVXSLBumpShaderAM, TVXSLMLBumpShader, TVXSLMLBumpShaderMT]); end.
unit storage; {$mode objfpc}{$H+} {$codepage UTF8} interface uses Classes, SysUtils, Contnrs, lazutf8; // Юнит для хранения узлов, предоставляет основные структуры хранения данных и первоначальную инфраструктуру доступа // Ядро type TCore=record Name: String; // Имя системы Value: String; // Значение системы Nature: Integer; // Простая/сложная система 0/1 // 2 - закрытая часть системы // 3 - система-функция // 4 - закрытая система-функция AType: String; // Тип системы FuncLink: Integer; // Ссылка на тело функции end; ////////////////////////////////////////////////////////////////////////// // Система type TSystem=class private procedure InitCore(); // Инициализация ядра системы public Core: TCore; // Ядро системы constructor Create; // Конструктор procedure Init(); // Инициализатор destructor Destroy(); override; // Деструктор end; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Параметры учета систем в хранилище type TParams=record Divider: String; // Символ-разделитель в сцепленном ключе Hide_marker: String; // Символ-маркер скрытого раздела системы end; ////////////////////////////////////////////////////////////////////////// // Список систем type TStorage=class private data: TObjectList; // Список систем Param: TParams; // Параметры хранения систем Progs: Array of TConstruct; // Описание функций систем // Служебные методы function InsertedIndex(Name: String; Parent: Integer): Integer; // Индекс для добавления системы в хранилище function FindSystem(Name: String; StartPos: Integer): Integer; // Поиск системы в хранилище procedure InitParams(); // Инициализация параметров хранения систем procedure AddRoot(); // Добавление корневой системы function AddSystem(Name, Value, AType: String; Nature, Index: Integer): Integer; // Добавление системы function GetLastNode(Line: String): String; // Извлечние последнего узла в пути function Spacer(Count: Integer; Line: String): String; // Забивает пробелами указанное количество символов function NewNamer(OldKey, Node, NewKey: String): String; // Генератор путей для переноса подсистем function Move(Index1, Index2: Integer; ANewName: String): Integer; // Перемещение системы и всех ее подсистем function CheckRename(OldKey, NewKey: String): Boolean; // Проверка, является ли новый путь переименованием системы function DivideKey(var Key: String): String; // Разделение ключа на путь и имя procedure CopySystem(Source, Dest: Integer); // Копирование системы procedure InitSystem(Index: Integer); // Инициализация системы public // Служебные constructor Create; // Конструктор destructor Destroy; override; // Деструктор procedure Init(); // Инициализатор // Пользовательские - полный доступ function AddSystem(Name, SuperSystem: String; Part: Boolean): Integer; // Добавляем систему function AddSystem(Name, Value, SuperSystem: String; Part: Boolean): Integer; // Добавляем простую систему function EraseSystem(Key: String): Integer; // Удаление подсистемы function RemoveSystem(OldKey, NewKey: String): Integer; // Перемещение/переменование системы function AddSystem2(OldKey, NewKey: String): Integer; // Добавляет систему на основе уже существующей function CopySystem(Source, Dest: String): Integer; // Копирует систему на место другой системы function InitSystem(Sys: String): Integer; // Инициализация системы // Пользовательские - свойства и индикаторы системы function CheckSystem(Sys: String): Boolean; // Проверка существования системы по указанному ключу function GetValueSystem(Sys: String; var Rez: String): Boolean; // Чтение текстового значения системы function GetNatureSystem(Sys: String; var Rez: Integer): Boolean; // Чтение внутреннего представления системы function GetTypeSystem(Sys: String; var Rez: String): Boolean; // Чтение типа системы function GetFunckLink(Sys: String; var Rez: Integer): Boolean; // Чтение ссылки на функцию function CheckSubSystem(Sys: String): Integer; // Проверка существования подситем function GetCountHideSystem(Sys: String): Integer; // Количество скрытых подсистем function CheckNesting(OldKey, NewKey: String): Boolean; // Определяет вложенность ключей function SetValue(Sys, NewValue: String): Integer; // Изменение текстового значения функции function SetTypeSystem(Sys, NewType: String): Integer; // Изменение типа системы // Работа с кодом function GetCountBlock(): Integer; // Общее количество блоков кода в системе // Пользовательские - открытая часть // Отчеты procedure Report_Keys(var rep: TStringList); // Все пути procedure ReportRoot(var rep: TStringList; detail: Boolean); // Полное дерево хранилища end; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Ядро инструкции type TInstruction=record Start: Integer; // Местоположение в исходном коде Id: Integer; // Идентификатор конструкции/блока Link: Integer; // Ссылка на внешний блок Param: Array [1..4] of TString; // Параметры конструкции end; ////////////////////////////////////////////////////////////////////////// // Полная блок-инструкция type TConstruct=record Core: TInstruction // Ядро инструкции Link1: Integer; // Ссылка на другой блок/конструкцию Link2: Integer; // Ссылка на другой блок/конструкцию Codes: Array of TInstruction; // Инструкции, содержащиеся в блоке end; ////////////////////////////////////////////////////////////////////////// implementation // Общее количество блоков кода в системе function TStorage.GetCountBlock(): Integer; begin // Обертка Result:=Length(Progs); end; ////////////////////////////////////////////////////////////////////////// // Изменение типа системы // Sys - ключ системы // NewType - новый тип системы // -1 - система не найдена // 0 - операция прошла успешно function TStorage.SetTypeSystem(Sys, NewType: String): Integer; var Index: Integer; begin // Инциализация Result:=-1; Sys:='1'+Param.Divider+Sys; // Найдем систему Index:=FindSystem(Sys, 0); // Система существует? If Index<0 then Exit; // Пишем результат TSystem(data[Index]).Core.AType:=NewType; // Операция прошла успешно Result:=0; end; ////////////////////////////////////////////////////////////////////////// // Изменение текстового значения функции // Sys - ключ системы // NewValue - новое текстовое значение системы // -1 - система не найдена // 0 - операция прошла успешно function TStorage.SetValue(Sys, NewValue: String): Integer; var Index: Integer; begin // Инциализация Result:=-1; Sys:='1'+Param.Divider+Sys; // Найдем систему Index:=FindSystem(Sys, 0); // Система существует? If Index<0 then Exit; // Пишем результат TSystem(data[Index]).Core.Value:=NewValue; // Операция прошла успешно Result:=0; end; ////////////////////////////////////////////////////////////////////////// // Количество скрытых подсистем (включая вложенные!!!!) // Sys - ключ системы // -1 - система не найдена // 0 - система не имеет подсистем // другое число - количество подсистем function TStorage.GetCountHideSystem(Sys: String): Integer; var Index, SubIndex, Nature: Integer; begin // Инцииализация Result:=-1; Sys:='1'+Param.Divider+Sys; // Найдем систему Index:=FindSystem(Sys, 0); // Система существует? If Index<0 then Exit; // Индекс предполагаемой подсистемы SubIndex:=Index+1; // Граница хранилища? Result:=0; If SubIndex=data.Count Then begin // Это последняя система в хранилище и у нее нет подсистем Exit; end; // Сканирование систем While Pos(TSystem(data[Index]).Core.Name+Param.Divider, TSystem(data[SubIndex]).Core.Name)=1 do begin // Тип подсистемы Nature:=TSystem(data[SubIndex]).Core.Nature; // Скрытая подсистема? if ((Nature=2) or (Nature=4)) then Inc(Result); // Следующий индекс Inc(SubIndex); // Проверка выхода за нижнюю границу хранилище If SubIndex=data.Count Then Exit; end; end; ////////////////////////////////////////////////////////////////////////// // Проверка существования подситем (включая скрытые). Подсчет ведется и по вложенынм подсистемам!!! // Sys - ключ системы // -1 - система не найдена // 0 - система не имеет подсистем // другое число - количество подсистем function TStorage.CheckSubSystem(Sys: String): Integer; var Index, SubIndex: Integer; begin // Инцииализация Result:=-1; Sys:='1'+Param.Divider+Sys; // Найдем систему Index:=FindSystem(Sys, 0); // Система существует? If Index<0 then Exit; // Индекс предполагаемой подсистемы SubIndex:=Index+1; // Граница хранилища? Result:=0; If SubIndex=data.Count Then begin // Это последняя система в хранилище и у нее нет подсистем Exit; end; // Сканирование систем While Pos(TSystem(data[Index]).Core.Name+Param.Divider, TSystem(data[SubIndex]).Core.Name)=1 do begin // Количество подсистем Inc(Result); // Следующий индекс Inc(SubIndex); // Проверка выхода за нижнюю границу хранилище If SubIndex=data.Count Then Exit; end; end; ////////////////////////////////////////////////////////////////////////// // Чтение ссылки на функцию // Sys - ключ системы // Rez - результат работы // False - система не найдена function TStorage.GetFunckLink(Sys: String; var Rez: Integer): Boolean; var Index: Integer; begin // Инциализация Result:=False; Sys:='1'+Param.Divider+Sys; Rez:=-1; // Найдем систему Index:=FindSystem(Sys, 0); // Система существует? If Index<0 then Exit; // Пишем результат Rez:=TSystem(data[Index]).Core.FuncLink; // Операция прошла успешно Result:=True; end; ////////////////////////////////////////////////////////////////////////// // Чтение типа системы // Sys - ключ системы // Rez - результат работы // False - система не найдена function TStorage.GetTypeSystem(Sys: String; var Rez: String): Boolean; var Index: Integer; begin // Инциализация Result:=False; Sys:='1'+Param.Divider+Sys; Rez:=''; // Найдем систему Index:=FindSystem(Sys, 0); // Система существует? If Index<0 then Exit; // Пишем результат Rez:=TSystem(data[Index]).Core.AType; // Операция прошла успешно Result:=True; end; ////////////////////////////////////////////////////////////////////////// // Чтение внутреннего представления системы // Sys - ключ системы // Rez - результат работы // False - система не найдена function TStorage.GetNatureSystem(Sys: String; var Rez: Integer): Boolean; var Index: Integer; begin // Инциализация Result:=False; Sys:='1'+Param.Divider+Sys; Rez:=-1; // Найдем систему Index:=FindSystem(Sys, 0); // Система существует? If Index<0 then Exit; // Пишем результат Rez:=TSystem(data[Index]).Core.Nature; // Операция прошла успешно Result:=True; end; ////////////////////////////////////////////////////////////////////////// // Чтение текстового значения системы // Sys - ключ системы // Rez - результат работы // False - система не найдена function TStorage.GetValueSystem(Sys: String; var Rez: String): Boolean; var Index: Integer; begin // Инциализация Result:=False; Sys:='1'+Param.Divider+Sys; Rez:=''; // Найдем систему Index:=FindSystem(Sys, 0); // Система существует? If Index<0 then Exit; // Пишем результат Rez:=TSystem(data[Index]).Core.Value; // Операция прошла успешно Result:=True; end; ////////////////////////////////////////////////////////////////////////// // Проверка существования системы по указанному ключу // Sys - ключ системы // True - система существует function TStorage.CheckSystem(Sys: String): Boolean; var Index: Integer; begin // Инициализация Result:=False; Sys:='1'+Param.Divider+Sys; // Поиск Index:=FindSystem(Sys, 0); // Проверка существования If Index>-1 then Result:=True; end; ////////////////////////////////////////////////////////////////////////// // Инициализация системы // 0 - операция прошла успешно // -1 - система не найдена function TStorage.InitSystem(Sys: String): Integer; var Index: Integer; begin // Инициализация Result:=-1; Sys:='1'+Param.Divider+Sys; // Найдем систему в хранилище Index:=FindSystem(Sys, 0); // Найдена? If Index<0 Then Exit; // Инициализация системы InitSystem(Index); // Операция прошла успешно Result:=0; end; ////////////////////////////////////////////////////////////////////////// // Копирует систему на место другой системы // Source - что копировать // Dest - куда копировать // 0 - Операция прошла успешно // -1 - Source не найден // -2 - Dest не найден // -3 - Копирование основной ветви в дочернуюю function TStorage.CopySystem(Source, Dest: String): Integer; var Index1, Index2: Integer; begin // Инциализация Result:=-1; Source:='1'+Param.Divider+Source; Dest:='1'+Param.Divider+Dest; // Индекс источника Index1:=FindSystem(Source, 0); // Система существует? If Index1<0 Then Exit; // Индекс приемника Index2:=FindSystem(Dest, 0); // Система существует? If Index2<0 Then begin // Сообщим об ошибке Result:=-2; Exit; end; // Системы вложены? If CheckNesting(Source, Dest)=True then begin // Сообщим о проблеме Result:=-3; Exit; end; // Инциализируем приемник InitSystem(Index2); // Копирование системы CopySystem(Index1, Index2); // Операция прошла успешно Result:=0; end; ////////////////////////////////////////////////////////////////////////// // Инициализация системы // Index - индекс инициализируемой системы в хранилище procedure TStorage.InitSystem(Index: Integer); var Index2: Integer; begin // Обнуляем все данные системы (за исключением имени) TSystem(data[Index]).Core.AType:=''; TSystem(data[Index]).Core.FuncLink:=-1; TSystem(data[Index]).Core.Nature:=0; TSystem(data[Index]).Core.Value:=''; // Подсистемы If Index=data.Count-1 Then exit; Index2:=Index+1; // Каждая подсистема данной системы while Pos(TSystem(data[Index]).Core.Name+Param.Divider, TSystem(data[Index2]).Core.Name)=1 do begin // Нужно удалить данную подсистему data.Delete(Index2); // Анализ границы If Index=data.Count-1 Then Exit; end; end; ////////////////////////////////////////////////////////////////////////// // Добавляет систему на основе уже существующей // OldKey - система которая будет копироваться под новым именем // NewKey - новый ключ для создаваемой системы (последний элемент - новое имя) // 0 - Операция прошла успешно // -1 - OldKey не найдена // -2 - NewKey уже существует // -3 - Путь до NewKey не найден // -4 - Самокопирование (когда NewKey это дочерняя ветка OldKey) function TStorage.AddSystem2(OldKey, NewKey: String): Integer; var index1, Index2: Integer; Last: String; begin // Инициализация Result:=-1; OldKey:='1'+Param.Divider+OldKey; NewKey:='1'+Param.Divider+NewKey; // Найдем адрес системы в хранилище Index1:=FindSystem(OldKey, 0); // Нашли? If Index1<0 then Exit; // Проверим существование системы по новому ключу Index2:=FindSystem(NewKey, 0); // Нашли? If Index2>-1 then begin // Система с таким именем уже существует Result:=-2; Exit; end; // Вложенное копирование If CheckNesting(OldKey, NewKey)=True Then begin // Сообщим об ошибке Result:=-4; Exit; end; // Разделим ключ на путь и конечное имя Last:=DivideKey(NewKey); // Проверим существование приемника копируемой системы Index2:=FindSystem(NewKey, 0); // Нашли? If Index2<0 then begin // Приемник не найден Result:=-3; Exit; end; // Создаем систему AddSystem(Last, '', '', 0, Index2); // Индекс системы Index2:=FindSystem(NewKey+Param.Divider+Last, Index2); Index1:=FindSystem(OldKey, 0); // Копирование системы и ее подсистем CopySystem(Index1, Index2); // Операция прошла успешно Result:=0; end; ////////////////////////////////////////////////////////////////////////// // Копирование системы и всех ее подсистем // Source - индекс копируемой системы // Dest - индекс системы в которую будет скопирована Source // Имя системы НЕ ИЗМЕНЯЕТСЯ!!!! procedure TStorage.CopySystem(Source, Dest: Integer); var SubSource, Index, len: Integer; Name, SourceName, CopyName: String; begin // Перенос полей SourceName:=TSystem(data[Source]).Core.Name; CopyName:=TSystem(data[Dest]).Core.Name; TSystem(data[Dest]).Core.AType :=TSystem(data[Source]).Core.AType; TSystem(data[Dest]).Core.FuncLink :=TSystem(data[Source]).Core.FuncLink; TSystem(data[Dest]).Core.Nature :=TSystem(data[Source]).Core.Nature; TSystem(data[Dest]).Core.Value :=TSystem(data[Source]).Core.Value; // Есть что добавлять? SubSource:=Source+1; If SubSource>data.Count-1 Then Exit; // Добавляем каждую систему while UTF8pos(TSystem(data[Source]).Core.Name+Param.Divider, TSystem(data[SubSource]).Core.Name)=1 do begin // Генерируем новое имя Name:=TSystem(data[SubSource]).Core.Name; len:=Utf8Length(TSystem(data[Source]).Core.Name); Name:=Utf8Copy(Name, len+2, (UTF8Length(Name)-len-1)); // Вставляем новую систему AddSystem(Name, '', '', 0, Dest); // Ключ новой системы Name:=TSystem(data[Dest]).Core.Name+Param.Divider+Name; // Индекс новой системы Index:=FindSystem(Name, Dest); // Коррекция индексов из-за добавления новой системы If Dest<=Source Then begin // Смещене Inc(SubSource); Inc(Source); end; // Копирование len:=TSystem(data[SubSource]).Core.Nature; SourceName:=TSystem(data[SubSource]).Core.Name; CopyName:=TSystem(data[Index]).Core.Name; TSystem(data[Index]).Core.AType :=TSystem(data[SubSource]).Core.AType; TSystem(data[Index]).Core.FuncLink :=TSystem(data[SubSource]).Core.FuncLink; TSystem(data[Index]).Core.Nature :=TSystem(data[SubSource]).Core.Nature; TSystem(data[Index]).Core.Value :=TSystem(data[SubSource]).Core.Value; // Следующий шаг Inc(SubSource); end; end; ////////////////////////////////////////////////////////////////////////// // Разделение ключа на путь и имя // Key - ключ (туда же будет возвращен путь до системы) // Возвращает имя системы function TStorage.DivideKey(var Key: String): String; begin // Имя системы Result:=GetLastNode(Key); // Получим сам путь Key:=UTF8Copy(Key, 1, UTF8Length(Key)-1-Utf8Length(Result)); end; ////////////////////////////////////////////////////////////////////////// // Перемещение/переменование системы // OldKey - текущий путь до системы // NewKey - новый путь до системы // 0 - Операция прошла успешно // -1 - Система по OldKey не найдена // -2 - NewKey не существует // -3 - Нельзя копировать родителя в потомка // -4 - Система с таким именем уже существует в NewKey function TStorage.RemoveSystem(OldKey, NewKey: String): Integer; var Index, Index2: Integer; Name: String; begin // Инциализация Result:=-3; OldKey:='1'+Param.Divider+OldKey; NewKey:='1'+Param.Divider+NewKey; // Найдем переносимую систему Index:=FindSystem(OldKey, 0); // Система указана корректно? If Index<0 then begin // Сообщим об ошибке Result:=-1; Exit; end; // Проверим вложенность систем If CheckNesting(OldKey, NewKey)=True Then Exit; // Проверим существование приемника Index2:=FindSystem(NewKey, 0); If Index2<0 then begin // Сообщим об ошибке Result:=-2; Exit; end; // Мы пытаемся переименовать систему? Name:=''; If CheckRename(OldKey, NewKey)=True then begin // Получим имя для переименования Name:=GetLastNode(NewKey); // Ключ для передачи NewKey:=Utf8Copy(NewKey, 1, UTF8Length(NewKey)-1-UTF8Length(Name)); end; // Проверим существование приемника Index2:=FindSystem(NewKey, 0); If Index2<0 then begin // Сообщим об ошибке Result:=-2; Exit; end; // Перенос системы Result:=Move(Index, Index2, Name); end; ////////////////////////////////////////////////////////////////////////// // Проверка, является ли новый путь переименованием системы // OldKey - Текущий ключ системы // NewKey - Новый ключ системы // TRUE - новый путь переименование - системы function TStorage.CheckRename(OldKey, NewKey: String): Boolean; var OldLast, NewLast, OldRoot, NewRoot: String; len1, len2: Integer; begin // Инициализация Result:=False; // Получим последние элементы OldLast:=GetLastNode(OldKey); NewLast:=GetLastNode(NewKey); // Получим родителя старого ключа len1:=UTF8Length(OldLast); len1:=UTF8Length(OldKey)-len1; OldRoot:=Utf8Copy(OldKey, 1, len1); // Получим родителя нового ключа len2:=UTF8Length(NewLast); len2:=UTF8Length(NewKey)-len2; NewRoot:=Utf8Copy(NewKey, 1, len2); // Анализ if OldRoot=NewRoot Then Result:=True; end; ////////////////////////////////////////////////////////////////////////// // Перемещение системы и всех ее подсистем // Index1 - что переносим // Index2 - куда переносим // 0 - Операция прошла успешно // -4 - система с таким именем уже существует в приемнике function TStorage.Move(Index1, Index2: Integer; ANewName: String): Integer; var NewName, Last, Name, str1: String; Index: Integer; begin // Инцииализация Result:=-4; // Генерируем новое имя Name:=TSystem(data[Index1]).Core.Name; // Имя передали? If ANewName<>'' Then begin // Просто используем переданное имя Last:=ANewName; end Else begin // Получим имя из ключа Last:=GetLastNode(Name); end; NewName:=TSystem(data[Index2]).Core.Name+Param.Divider+Last; // Место свободно? If FindSystem(NewName, Index2)>-1 then Exit; // Индекс для перемещения Index:=InsertedIndex(NewName, Index2); // Корректор индекса If Index>=data.Count Then Index:=data.Count-1; // Восстановим первоначальынй индекс If (Index>Index2) and (Index1<Index2) Then Dec(Index2); If (Index>Index2) and (Index1<Index2) Then Dec(Index); // Перенос data.Move(Index1, Index); // Новое имя элемента TSystem(data[Index]).Core.Name:=NewName; // Шаг приращения If Index1>=Index Then Inc(Index1); If Index1=data.Count then Exit; // Апргрейд имени для подсистем Str1:=TSystem(data[Index2]).Core.Name+Param.Divider+Last; // Цикл переноса подсистем while Utf8Pos(Name+Param.Divider, TSystem(data[Index1]).Core.Name)=1 do begin // Генерируем новое имя NewName:=NewNamer(Name, TSystem(data[Index1]).Core.Name, str1); // Новый индекс Index:=InsertedIndex(NewName, Index2); // Корректор индекса If Index>=data.Count Then Index:=data.Count-1; // Восстановим первоначальынй индекс If (Index>Index2) and (Index1<Index2) Then Dec(Index2); If (Index>Index2) and (Index1<Index2) Then Dec(Index); // Перенос data.Move(Index1, Index); // Новое имя TSystem(data[Index]).Core.Name:=NewName; // Шаг приращения If Index1>=Index Then Inc(Index1); If Index1=data.Count then Exit; end; // Операция прошла успешно Result:=0; end; ////////////////////////////////////////////////////////////////////////// // Генератор путей для переноса подсистем // OldKey - источник, надсистема // Node - ключ переносимой подсистемы // NewKey - адрес куда требуется перенести подсистему // Системы уже должны содержать корневой элемент '1' function TStorage.NewNamer(OldKey, Node, NewKey: String): String; var len: Integer; begin // Вычитаем старый путь из переносимой системы len:=UTF8Length(OldKey)+1; Node:=UTF8copy(Node, len+1, UTF8Length(Node)-len); Node:=NewKey+Param.Divider+Node; // Результат Result:=Node; end; ////////////////////////////////////////////////////////////////////////// // Определяет вложенность ключей // Осуществляет проверку того, что NewKey является частью OldKey, т.е. что NewKey более высокого уровня // True - да, False - нет function TStorage.CheckNesting(OldKey, NewKey: String): Boolean; begin // Инициализация Result:=False; If UTF8Pos(NewKey+Param.Divider, OldKey)=1 Then Result:=True; end; ////////////////////////////////////////////////////////////////////////// // Удаление подсистемы // Name - имя удаляемой подсистемы // SuperSystem - система в которой нужно провести удаление // 0 - операция прошла успешно // -1 - Удаляемая система не найдена function TStorage.EraseSystem(Key: String): Integer; var Index: Integer; begin // Инциализация Result:=-1; // Индекс надсистемы Key:='1'+Param.Divider+Key; Index:=FindSystem(Key, 0); // Найдена? If Index<0 then Exit; // Удалим данную систему data.Delete(Index); if Index>data.Count-1 Then begin // Больше нечего удалять Result:=0; Exit; end; // Удаление подсистем while UTF8Pos(key+Param.Divider, TSystem(data[Index]).Core.Name)=1 do begin data.Delete(Index); if Index>data.Count-1 Then begin // Больше нечего удалять Result:=0; Exit; end; end; // Операция завершена Result:=0; end; ////////////////////////////////////////////////////////////////////////// // Полное дерево хранилища // rep - список для отчета // Предыдущая информация сохраняется // detail - Нужен ли подробный вывод - TRUE - да procedure TStorage.ReportRoot(var rep: TStringList; detail: Boolean); var i, count, s: Integer; Node, Last: String; begin // Количество систем в хранилище count:=data.Count-1; // Отображаем данные по узлам for i:=0 to count do begin // Имя узла Node:=TSystem(data[i]).Core.Name; // Последний элемент в систе Last:=GetLastNode(Node); // Забиваем путь s:=UTF8Length(Node)-UTF8Length(Last); Node:=Spacer(s, Last); // Закрытая система? If (TSystem(data[i]).Core.Nature=2) or (TSystem(data[i]).Core.Nature=2) Then begin Node:=Node+'<!>'; end; // Отобразим результат rep.Add(Node); If detail=True then begin // Тип Node:=Spacer(Length(Node), Node); Last:=Node+'<Тип: '+TSystem(data[i]).Core.AType+'>'; rep.Add(Last); // Значение Last:=Node+'<Значение: '+TSystem(data[i]).Core.Value+'>'; rep.Add(Last); end; end; end; ////////////////////////////////////////////////////////////////////////// // Забивает проблеами указанное количество символов // Count - количество символов, которые нужно добавить перед function TStorage.Spacer(Count: Integer; Line: String): String; var i: Integer; begin // Забиваем символы Result:=''; for i:=1 to Count do begin Result:=Result+' '; end; // Результат Result:=Result+Line; end; ////////////////////////////////////////////////////////////////////////// // Извлечние последнего узла в пути function TStorage.GetLastNode(Line: String): String; var i, count: Integer; begin // Инициализация Result:=Line; // Количество элементов в строке count:=UTF8Length(Line); // Сканируем в обратном порядке for i:=count downto 1 do begin // Сверим с разделителем узлов if UTF8Copy(Line, i, 1)=Param.Divider then begin // Остаток Result:=UTF8copy(Line, i+1, count-i); Exit; end; end; end; ///////////////////////////////////////////////////////////////////////// // Добавляем простую систему // Name - добавляемой системы // Value - значение системы // SuperSystem - путь до родителя // Part - в какую часть надсистемы добавлять подсистему // False - открытая часть // True - закрытая часть // 0 - Операция прошла успешно // -1 - Система уже существует // -2 - Родитель не найден // -3 - Имя системы не задано function TStorage.AddSystem(Name, Value, SuperSystem: String; Part: Boolean): Integer; var Index: Integer; begin // Инициализация Result:=-2; // Найдем индекс родителя if SuperSystem='' then begin // Адрес по умолчанию SuperSystem:='1'; end Else begin // Глобальное имя SuperSystem:='1'+Param.Divider+SuperSystem; end; Index:=FindSystem(SuperSystem, 0); // Добавляем систему If Part=True then begin // Пометка, что нужна закрытая часть системы Result:=AddSystem(Name, Value, '', 2, Index); end Else begin // Обычная система Result:=AddSystem(Name, Value, '', 1, Index); end; end; ////////////////////////////////////////////////////////////////////////// // Все пути // Собирает и выводит все пути в хранилище // rep - список для отчета // Предыдущая информация не удаляется procedure TStorage.Report_Keys(var rep: TStringList); var i, count: Integer; begin // Количество элементов в системе count:=data.Count; // Просматриваем хранилище for i:=0 to count-1 do begin // Добавляем пути rep.Add(TSystem(data[i]).Core.Name); end; end; ////////////////////////////////////////////////////////////////////////// // Добавление корневой системы // Корневая система создается в нулевом индексе // Если система уже есть, она не будет создаваться procedure TStorage.AddRoot(); var count: Integer; begin // Проверим существует ли корневой узел count:=data.Count; // Уже есть? If count>0 then Exit; // Создаем узел data.Add(TSystem.Create); // Имя узла TSystem(data[0]).Core.Name:='1'; end; ////////////////////////////////////////////////////////////////////////// // Добавляем систему // Name - добавляемой системы // SuperSystem - путь до родителя // Part - в какую часть надсистемы добавлять подсистему // False - открытая часть // True - закрытая часть // 0 - Операция прошла успешно // -1 - Система уже существует // -2 - Родитель не найден // -3 - Имя системы не задано function TStorage.AddSystem(Name, SuperSystem: String; Part: Boolean): Integer; var Index: Integer; begin // Инициализация Result:=-2; // Найдем индекс родителя if SuperSystem='' then begin // Адрес по умолчанию SuperSystem:='1'; end Else begin // Глобальное имя SuperSystem:='1'+Param.Divider+SuperSystem; end; Index:=FindSystem(SuperSystem, 0); // Добавляем систему if Part=True then begin // Закрытая система Result:=AddSystem(Name, '', '', 2, Index); end Else begin // Открытая система Result:=AddSystem(Name, '', '', 1, Index); end; end; ////////////////////////////////////////////////////////////////////////// // Добавление системы // Name - добавляемой системы // Index - индекс родителя в хранилище // 0 - Операция прошла успешно // -1 - Система уже существует // -2 - Родитель не найден // -3 - Имя системы не задано function TStorage.AddSystem(Name, Value, AType: String; Nature, Index: Integer): Integer; var FullKey: String; begin // Инициализация Result:=-2; // Родитель указан корректно? If Index<0 then Exit; // Имя системы указано? If Name='' then begin // Сообщим об ошибке Result:=-3; Exit; end; // Сцепленный ключ FullKey:=TSystem(data[Index]).Core.Name+Param.Divider+Name; // Найдем индекс для вставки нового элемента Index:=InsertedIndex(FullKey, Index); // Система уже существует? If index<0 then begin // Сообщим о проблеме Result:=-1; Exit; end; // Вставляем новую систему data.Insert(Index, TSystem.Create); // Имя новой системе TSystem(data[Index]).Core.Name:=FullKey; // Значение новой системе TSystem(data[Index]).Core.Value:=Value; // Природа системы TSystem(data[Index]).Core.Nature:=Nature; // Тип системы TSystem(data[Index]).Core.AType:=AType; // Операция прошла успешно Result:=0; end; ////////////////////////////////////////////////////////////////////////// // Поиск системы в хранилище // Name -Имя/путь до системы // Parent - Родитель // Возвращает идентификатор системы в хранилище // -1 Если система не найдена function TStorage.FindSystem(Name: String; StartPos: Integer): Integer; var start,finish, ex: Integer; s: String; begin // Инициализация Result:=-1; finish:=data.Count-1; start:=StartPos; // Частный случай If Name='' Then Exit; // Сканируем хранилище половинным делением интервала while finish>=start do begin // Новая точка для анализа ex:=start+((finish-start) div 2); // Совпадение s:=TSystem(data[ex]).Core.Name; If s=Name Then begin // Передаем индекс Result:=ex; Exit; end; // Корректировка интервала поиска If s>Name Then begin // Подтягиваем нижнюю границу finish:=ex-1; end Else begin // Подтягиваем верхнуюю границу диапазона start:=ex+1; end; end; end; ////////////////////////////////////////////////////////////////////////// // Индекс для добавления системы в хранилище // Name - Полное имя для добавления в хранилище // -1 - Система с таким именем уже существует function TStorage.InsertedIndex(Name: String; Parent: Integer): Integer; var ex, start, finish: Integer; begin // Инициализация result:=-1; start:=Parent; finish:=data.Count-1; // Частный случай if finish<0 then begin // Сообщим о первом индексе Result:=0; Exit; end; // Сканируем имена половинным делением интервала while start<=finish do begin // Получим интервал ex:=start+((finish-start) div 2); // Совпало? if Name=TSystem(data[ex]).Core.Name then begin // Сообщим о существовании системы Exit; end; // Нижняя граница if Name>TSystem(data[ex]).Core.Name then begin // Подтягиваем нижнюю границу start:=ex+1; end Else begin // Подтягиваем верхнюю границу finish:=ex-1; end; end; // Передаем индекс Result:=start; end; ////////////////////////////////////////////////////////////////////////// // Конструктор constructor TStorage.Create; begin // Предок Inherited Create; // Хранилище data:=TObjectList.Create(); // Параметры InitParams(); // Суперсистема AddRoot(); end; ////////////////////////////////////////////////////////////////////////// // Деструктор destructor TStorage.Destroy; begin // Инициализация Init(); // Хранилище data.Free; // Предок Inherited Destroy; end; ////////////////////////////////////////////////////////////////////////// // Инициализатор procedure TStorage.Init(); begin // Количество доступных систем data.OwnsObjects:=true; data.Clear; // Параметры InitParams(); // Корневой узел AddRoot(); end; ////////////////////////////////////////////////////////////////////////// // Инициализация параметров хранения систем procedure TStorage.InitParams(); begin // Установки по умолчанию Param.Divider:='.'; Param.Hide_marker:='?'; end; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Деструктор destructor TSystem.Destroy(); begin // Инициализация Init(); // Предок Inherited Destroy; end; ////////////////////////////////////////////////////////////////////////// // Инициализатор procedure TSystem.Init(); begin // Ядро InitCore(); end; ////////////////////////////////////////////////////////////////////////// // Инициализация ядра системы procedure TSystem.InitCore(); begin // Обнулей полей Core.AType:=''; Core.Name:=''; Core.Nature:=0; Core.Value:=''; end; ////////////////////////////////////////////////////////////////////////// // Конструктор constructor TSystem.Create; begin // Предок Inherited Create; end; ////////////////////////////////////////////////////////////////////////// end.
unit Objekt.DHLStatusinformationList; interface uses System.SysUtils, System.Classes, Objekt.DHLStatusinformation, Objekt.DHLBaseList, System.Contnrs; type TDHLStatusinformationList = class(TDHLBaseList) private fStatusinformation : TDHLStatusinformation; function getDHLStatusinformation(Index: Integer): TDHLStatusinformation; public constructor Create; override; destructor Destroy; override; property Item[Index: Integer]: TDHLStatusinformation read getDHLStatusinformation; function Add: TDHLStatusinformation; end; implementation { TDHLStatusinformationList } constructor TDHLStatusinformationList.Create; begin inherited; end; destructor TDHLStatusinformationList.Destroy; begin inherited; end; function TDHLStatusinformationList.getDHLStatusinformation(Index: Integer): TDHLStatusinformation; begin Result := nil; if Index > fList.Count -1 then exit; Result := TDHLStatusinformation(fList[Index]); end; function TDHLStatusinformationList.Add: TDHLStatusinformation; begin fStatusinformation := TDHLStatusinformation.Create; fList.Add(fStatusinformation); Result := fStatusinformation; end; end.
unit ufrmExportToMDB; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMaster, StdCtrls, ComCtrls, ExtCtrls, uTSCommonDlg, uTSINIFile, uConstanta, Types, OleCtrls, DateUtils; type TfrmExportToMDB = class(TfrmMaster) Panel1: TPanel; Label1: TLabel; btnExport: TButton; dtTanggal: TDateTimePicker; mmoExport: TMemo; dtLastExport: TDateTimePicker; Label2: TLabel; procedure btnExportClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); private FCompID: Integer; FPosCode: string; FMDBPath, FMDBPass: String; FUnitID: Integer; FUserID: Integer; function cZipFile(AFileName, APassword: string): Boolean; function GetExportFileName: string; function IsExportSuccess: Boolean; function IsParameterValid: Boolean; procedure LoadConfig; procedure SetMDBPass(const Value: string); procedure SetMDBPath(const Value: string); public property CompID: Integer read FCompID write FCompID; property PosCode: string read FPosCode write FPosCode; property UnitID: Integer read FUnitID write FUnitID; property UserID: Integer read FUserID write FUserID; published property MDBPass: string read FMDBPass write SetMDBPass; property MDBPath: string read FMDBPath write SetMDBPath; end; var frmExportToMDB: TfrmExportToMDB; implementation uses uAppUtils; {$R *.dfm} procedure TfrmExportToMDB.btnExportClick(Sender: TObject); begin inherited; if IsParameterValid then begin mmoExport.Clear; if IsExportSuccess then CommonDlg.ShowMessage('Export Data Sukses') else CommonDlg.ShowError('Export Data Gagal'); end; end; function TfrmExportToMDB.cZipFile(AFileName, APassword: string): Boolean; //var // AbZipp: TZipMaster; // NamaZip: string; begin // Result := False; // AbZipp.Create(Self); try // AbZipp := TZipMaster.create(Self); // NamaZip := ChangeFileExt(AFileName,'.zip'); // // AbZipp.FSpecArgs.Add(AFileName); // AbZipp.Verbose := False; // AbZipp.Trace := False; // AbZipp.ZipFileName := ExtractFileName(NamaZip); // AbZipp.Add; // // if AbZipp.SuccessCnt >0 then Result := True; finally // AbZipp.Free; end; end; procedure TfrmExportToMDB.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_ESCAPE then Close; end; procedure TfrmExportToMDB.FormShow(Sender: TObject); var // lQ: TIBQuery; sSQL: string; begin inherited; // ClearByTag(Self, [0]); // dtTanggal.DateTime := cGetServerTime; dtLastExport.DateTime := 0; LoadConfig; sSQL := 'select LOG_DATEBYUSER from TLOGEXIMMDB ' + ' where LOG_ISEXPORT = 1 order by LOG_DATE desc rows 1'; { lQ := cOpenQuery(sSQL); try if not lQ.Eof then begin dtLastExport.DateTime := lQ.Fields[0].AsDateTime; end; finally lQ.Free; end; } end; function TfrmExportToMDB.GetExportFileName: string; //var // lUnit: TUnit; begin //Get Kode Cabang { lUnit := TUnit.Create(Self); try if lUnit.LoadByID(UnitID) then Result := lUnit.Kode; finally lUnit.Free; end; } //Get kode POS Result := Result + PosCode; //Get Date Result := Result + FormatDateTime('YYYYMMDD', dtTanggal.DateTime); // Result := Result + '.MDB'; end; function TfrmExportToMDB.IsExportSuccess: Boolean; var aListAll: TStrings; FSaveDlg: TSaveDialog; sErrorCreateDB: string; SS: TStrings; sSQL: String; begin Result := False; aListAll := TStringList.Create; try FSaveDlg := TSaveDialog.Create(Self); FSaveDlg.FileName := GetExportFileName; if not FSaveDlg.Execute then Exit; if FileExists(FSaveDlg.FileName) then begin ShowMessage('File dengan nama tersebut sudah ada'); Exit; end; FMDBPath := FSaveDlg.FileName; // sErrorCreateDB := cAdoCreateDB(FMDBPath, FMDBPass); if sErrorCreateDB <> '' then ShowMessage(sErrorCreateDB); { if cAdoConnect(FMDBPath, FMDBPass) then begin mmoExport.Lines.Add('0. Create Table for Export ...'); aListALL.Add(SQL_CREATE_TABLE_TRANSAKSI); aListALL.Add(SQL_CREATE_TABLE_TRANSAKSI_PENDING); aListALL.Add(SQL_CREATE_TABLE_TRANSAKSI_DETIL); aListALL.Add(SQL_CREATE_TABLE_TRANSAKSI_CARD); aListALL.Add(SQL_CREATE_TABLE_VOUCHER_LAIN_LAIN); aListALL.Add(SQL_CREATE_TABLE_SETUPPOS); aListALL.Add(SQL_CREATE_TABLE_BEGINNING_BALANCE); aListALL.Add(SQL_CREATE_TABLE_SHIFT); aListALL.Add(SQL_CREATE_TABLE_FINAL_PAYMENT); aListALL.Add(SQL_CREATE_TABLE_TRANSAKSI_RETUR_NOTA); aListALL.Add(SQL_CREATE_TABLE_CASH_DROPPING); if not cAdoExecSQLs(aListAll, FMDBPath, FMDBPass) then begin DeleteFile(FMDBPath); mmoExport.Lines.Add(' Gagal Create DB ...'); Exit; end; aListAll.Clear; mmoExport.Lines.Add('1. Preparing Data Transaksi ...'); SS := GetDataTransaksi(UnitID, dtTanggal.DateTime); aListALL.AddStrings(SS); SS.Free; mmoExport.Lines.Add('2. Preparing Data TransaksiPending ...'); SS := GetDataTransaksiPending(UnitID, dtTanggal.DateTime); aListALL.AddStrings(SS); SS.Free; mmoExport.Lines.Add('3. Preparing Data TransaksiDetil ...'); SS := GetDataTransaksiDetail(UnitID, dtTanggal.DateTime); aListAll.AddStrings(SS); SS.Free; mmoExport.Lines.Add('4. Preparing Data TransaksiCard ...'); SS := GetDataTransaksiCard(UnitID, dtTanggal.DateTime); aListAll.AddStrings(SS); SS.Free; mmoExport.Lines.Add('5. Preparing Data TransaksiVoucher ...'); SS := GetDataTransaksiVoucher(UnitID, dtTanggal.DateTime); aListAll.AddStrings(SS); SS.Free; mmoExport.Lines.Add('6. Preparing Data TransaksiRetur ...'); SS := GetDataTransaksiRetur(UnitID, dtTanggal.DateTime); aListAll.AddStrings(SS); SS.Free; mmoExport.Lines.Add('7. Preparing Data SetupPOS ...'); SS := GetDataSetupPOS(UnitID, dtTanggal.DateTime); aListAll.AddStrings(SS); SS.Free; mmoExport.Lines.Add('8. Preparing Data BeginningBalance ...'); SS := GetDataBeginningBalance(UnitID, dtTanggal.DateTime); aListAll.AddStrings(SS); SS.Free; mmoExport.Lines.Add('9. Preparing Data Shift ...'); SS := GetDataShift(UnitID, dtTanggal.DateTime); aListAll.AddStrings(SS); SS.Free; mmoExport.Lines.Add('10. Preparing Data Final Payment ...'); SS := GetDataFinalPayment(UnitID, dtTanggal.DateTime); aListAll.AddStrings(SS); SS.Free; // Disable by request user (TSN) // mmoExport.Lines.Add('11. Preparing Data Cash Dropping ...'); // SS := GetDataCashDropping(UnitID, dtTanggal.DateTime); // aListAll.AddStrings(SS); // SS.Free; // SS := GetDataTransaksiVoucherAssalam(UnitID, dtTanggal.DateTime); // aListAll.AddStrings(SS); // SS.Free; mmoExport.Lines.Add('11. Exporting Data ...'); aListAll.SaveToFile(cGetAppPath + FormatDateTime('YYYYMMDDhhmmss', cGetServerTime) + '.txt'); if cAdoExecSQLs(aListAll, FMDBPath, FMDBPass) then begin // if cZipFile(FMDBPath, FMDBPass) then // begin mmoExport.Lines.Add('12.Insert LOG ...'); sSQL := 'insert into TLOGEXIMMDB ( ' + ' LOG_DATE, LOG_DATEBYUSER, LOG_UNIT, LOG_POSCODE, LOG_ISEXPORT ' + ' ) values( ' + Quot(FormatDateTime('MM-DD-YYYY hh:mm:ss', cGetServerTime)) + ', ' + QuotDT(dtTanggal.DateTime) + ', ' + IntToStr(UnitID) + ', ' + Quot(POSCode) + ', 1 );'; cExecSQL(sSQL); cCommitTrans; mmoExport.Lines.Add(' Sukses Export Data ...'); dtLastExport.DateTime := dtTanggal.DateTime; Result := True; // end // else // begin // mmoExport.Lines.Add(' Gagal Compress Data ...'); // end; end else begin DeleteFile(FMDBPath); mmoExport.Lines.Add(' Gagal Export Data ...'); end; end; } finally // cRollbackTrans; aListAll.Free; end; end; function TfrmExportToMDB.IsParameterValid: Boolean; begin Result := False; if CompID <= 0 then CommonDlg.ShowMessage('Company belum dipilih') else if UnitID <= 0 then CommonDlg.ShowMessage('Unit belum dipilih') else if UserID <= 0 then CommonDlg.ShowMessage('User tidak valid') else Result := True; end; procedure TfrmExportToMDB.LoadConfig; begin FMDBPath := _INIReadString(CONFIG_FILE, DB_POS, 'MDBPath'); FPOSCode := _INIReadString(CONFIG_FILE, DB_POS, 'POSCode'); FMDBPass := TAppUtils._Decrypt(TAppUtils._MakeOriginal(_INIReadString(CONFIG_FILE,DB_POS,'MDBPass')),START_KEY,MULTI_KEY,ADD_KEY); end; procedure TfrmExportToMDB.SetMDBPass(const Value: string); begin FMDBPass := Value; end; procedure TfrmExportToMDB.SetMDBPath(const Value: string); begin FMDBPath := Value; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Spec.TemplateBase; interface uses Spring.Collections, JsonDataObjects, DPM.Core.TargetPlatform, DPM.Core.Types, DPM.Core.Logging, DPM.Core.Spec.Interfaces, DPM.Core.Spec.Node; type TSpecTemplateBase = class(TSpecNode, ISpecTemplateBase) protected FDependencies : IList<ISpecDependency>; FDesignFiles : IList<ISpecBPLEntry>; FFiles : IList<ISpecFileEntry>; FLibFiles : IList<ISpecFileEntry>; FRuntimeFiles : IList<ISpecBPLEntry>; FSourceFiles : IList<ISpecFileEntry>; FSearchPaths : IList<ISpecSearchPath>; FBuildEntries : IList<ISpecBuildEntry>; protected function IsTemplate : boolean; virtual; function AllowDependencyGroups : boolean; virtual; function AllowSearchPathGroups : boolean; virtual; function GetDependencies : IList<ISpecDependency>; function GetDesignFiles : IList<ISpecBPLEntry>; function GetFiles : IList<ISpecFileEntry>; function GetLibFiles : IList<ISpecFileEntry>; function GetRuntimeFiles : IList<ISpecBPLEntry>; function GetSourceFiles : IList<ISpecFileEntry>; function GetSearchPaths : IList<ISpecSearchPath>; function GetBuildEntries : IList<ISpecBuildEntry>; function FindDependencyById(const id : string) : ISpecDependency; function FindDependencyGroupByTargetPlatform(const targetPlatform : TTargetPlatform) : ISpecDependencyGroup; function FindSearchPathByPath(const path : string) : ISpecSearchPath; function FindRuntimeBplBySrc(const src : string) : ISpecBPLEntry; function FindDesignBplBySrc(const src : string) : ISpecBPLEntry; function FindLibFileBySrc(const src : string) : ISpecFileEntry; function FindSourceFileBySrc(const src : string) : ISpecFileEntry; function FindOtherFileBySrc(const src : string) : ISpecFileEntry; function FindBuildEntryById(const id : string) : ISpecBuildEntry; // function LoadCollection(const rootElement : IXMLDOMElement; const collectionPath : string; const nodeClass : TSpecNodeClass; const action : TConstProc<ISpecNode>) : boolean; function LoadDependenciesFromJson(const dependenciesArray : TJsonArray) : Boolean; function LoadLibraryFromJson(const libArray : TJsonArray) : Boolean; function LoadSourceFromJson(const sourceArray : TJsonArray) : Boolean; function LoadRuntimeFromJson(const runtimeArray : TJsonArray) : Boolean; function LoadDesignFromJson(const designArray : TJsonArray) : Boolean; function LoadFilesFromJson(const filesArray : TJsonArray) : Boolean; function LoadSearchPathsFromJson(const searchPathsArray : TJsonArray) : Boolean; function LoadBuildEntriesFromJson(const buildArray : TJsonArray) : Boolean; function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override; constructor CreateClone(const logger : ILogger; const deps : IList<ISpecDependency>; const design, runtime : IList<ISpecBPLEntry>; const source, lib, files : IList<ISpecFileEntry>; const search : IList<ISpecSearchPath>); public constructor Create(const logger : ILogger); override; end; implementation uses System.SysUtils, DPM.Core.Spec.FileEntry, DPM.Core.Spec.BPLEntry, DPM.Core.Spec.Dependency, DPM.Core.Spec.DependencyGroup, DPM.Core.Spec.SearchPath, DPM.Core.Spec.SearchPathGroup, DPM.Core.Spec.BuildEntry; { TSpecTemplateBase } function TSpecTemplateBase.AllowDependencyGroups : boolean; begin result := false; end; function TSpecTemplateBase.AllowSearchPathGroups : boolean; begin result := false; end; constructor TSpecTemplateBase.Create(const logger : ILogger); begin inherited Create(Logger); FDependencies := TCollections.CreateList<ISpecDependency>; FDesignFiles := TCollections.CreateList<ISpecBPLEntry>; FFiles := TCollections.CreateList<ISpecFileEntry>; FLibFiles := TCollections.CreateList<ISpecFileEntry>; FRuntimeFiles := TCollections.CreateList<ISpecBPLEntry>; FSourceFiles := TCollections.CreateList<ISpecFileEntry>; FSearchPaths := TCollections.CreateList<ISpecSearchPath>; FBuildEntries := TCollections.CreateList<ISpecBuildEntry>; end; constructor TSpecTemplateBase.CreateClone(const logger : ILogger; const deps : IList<ISpecDependency>; const design, runtime : IList<ISpecBPLEntry>; const source, lib, files : IList<ISpecFileEntry>; const search : IList<ISpecSearchPath>); begin Create(logger); FDependencies.AddRange(deps); FDesignFiles.AddRange(design); FFiles.AddRange(files); FLibFiles.AddRange(lib); FRuntimeFiles.AddRange(runtime); FSourceFiles.AddRange(source); FSearchPaths.AddRange(search); end; function TSpecTemplateBase.FindBuildEntryById(const id : string) : ISpecBuildEntry; begin result := FBuildEntries.FirstOrDefault( function(const item : ISpecBuildEntry) : boolean begin result := SameText(item.Id, id); end); end; function TSpecTemplateBase.FindDependencyById(const id : string) : ISpecDependency; begin result := FDependencies.FirstOrDefault( function(const item : ISpecDependency) : boolean begin result := SameText(item.Id, id); end); end; function TSpecTemplateBase.FindDependencyGroupByTargetPlatform(const targetPlatform : TTargetPlatform) : ISpecDependencyGroup; begin result := FDependencies.FirstOrDefault( function(const item : ISpecDependency) : boolean begin result := false; if item.IsGroup then result := (item as ISpecDependencyGroup).TargetPlatform = targetPlatform; end) as ISpecDependencyGroup; end; function TSpecTemplateBase.FindDesignBplBySrc(const src : string) : ISpecBPLEntry; begin result := FDesignFiles.FirstOrDefault( function(const item : ISpecBPLEntry) : boolean begin result := SameText(item.Source, src); end); end; function TSpecTemplateBase.FindLibFileBySrc(const src : string) : ISpecFileEntry; begin result := FLibFiles.FirstOrDefault( function(const item : ISpecFileEntry) : boolean begin result := SameText(item.Source, src); end); end; function TSpecTemplateBase.FindOtherFileBySrc(const src : string) : ISpecFileEntry; begin result := FFiles.FirstOrDefault( function(const item : ISpecFileEntry) : boolean begin result := SameText(item.Source, src); end); end; function TSpecTemplateBase.FindRuntimeBplBySrc(const src : string) : ISpecBPLEntry; begin result := FRuntimeFiles.FirstOrDefault( function(const item : ISpecBPLEntry) : boolean begin result := SameText(item.Source, src); end); end; function TSpecTemplateBase.FindSearchPathByPath(const path : string) : ISpecSearchPath; begin result := FSearchPaths.FirstOrDefault( function(const item : ISpecSearchPath) : boolean begin result := SameText(item.Path, path); end); end; function TSpecTemplateBase.FindSourceFileBySrc(const src : string) : ISpecFileEntry; begin result := FSourceFiles.FirstOrDefault( function(const item : ISpecFileEntry) : boolean begin result := SameText(item.Source, src); end); end; function TSpecTemplateBase.GetBuildEntries : IList<ISpecBuildEntry>; begin result := FBuildEntries; end; function TSpecTemplateBase.GetDependencies : IList<ISpecDependency>; begin result := FDependencies; end; function TSpecTemplateBase.GetDesignFiles : IList<ISpecBPLEntry>; begin result := FDesignFiles; end; function TSpecTemplateBase.GetFiles : IList<ISpecFileEntry>; begin result := FFiles; end; function TSpecTemplateBase.GetLibFiles : IList<ISpecFileEntry>; begin result := FLibFiles; end; function TSpecTemplateBase.GetRuntimeFiles : IList<ISpecBPLEntry>; begin result := FRuntimeFiles; end; function TSpecTemplateBase.GetSearchPaths : IList<ISpecSearchPath>; begin result := FSearchPaths; end; function TSpecTemplateBase.GetSourceFiles : IList<ISpecFileEntry>; begin result := FSourceFiles; end; function TSpecTemplateBase.IsTemplate : boolean; begin result := false; end; function TSpecTemplateBase.LoadBuildEntriesFromJson(const buildArray : TJsonArray) : Boolean; begin result := LoadJsonCollection(buildArray, TSpecBuildEntry, procedure(const value : IInterface) begin FBuildEntries.Add(value as ISpecBuildEntry); end); end; function TSpecTemplateBase.LoadDependenciesFromJson(const dependenciesArray : TJsonArray) : Boolean; var i : integer; dependencyObj : TJsonObject; dependency : ISpecDependency; begin result := true; if dependenciesArray.Count = 0 then exit; for i := 0 to dependenciesArray.Count - 1 do begin dependencyObj := dependenciesArray[i]; if dependencyObj.Contains('targetPlatform') then begin if not IsTemplate then begin result := false; Logger.Error('Dependency groups not valid in targetPlatform, for use in templates only'); continue; end; dependency := TSpecDependencyGroup.Create(Logger); end else dependency := TSpecDependency.Create(Logger); FDependencies.Add(dependency); result := dependency.LoadFromJson(dependencyObj) and result; end; end; function TSpecTemplateBase.LoadDesignFromJson(const designArray : TJsonArray) : Boolean; begin result := LoadJsonCollection(designArray, TSpecBPLEntry, procedure(const value : IInterface) begin FDesignFiles.Add(value as ISpecBPLEntry); end); end; function TSpecTemplateBase.LoadFilesFromJson(const filesArray : TJsonArray) : Boolean; begin result := LoadJsonCollection(filesArray, TSpecFileEntry, procedure(const value : IInterface) begin FFiles.Add(value as ISpecFileEntry); end); end; function TSpecTemplateBase.LoadLibraryFromJson(const libArray : TJsonArray) : Boolean; begin result := LoadJsonCollection(libArray, TSpecFileEntry, procedure(const value : IInterface) begin FLibFiles.Add(value as ISpecFileEntry); end); end; function TSpecTemplateBase.LoadRuntimeFromJson(const runtimeArray : TJsonArray) : Boolean; begin result := LoadJsonCollection(runtimeArray, TSpecBPLEntry, procedure(const value : IInterface) begin FRuntimeFiles.Add(value as ISpecBPLEntry); end); end; function TSpecTemplateBase.LoadSearchPathsFromJson(const searchPathsArray : TJsonArray) : Boolean; var i : integer; searchPath : ISpecSearchPath; searchPathGroup : ISpecSearchPathGroup; searchPathObj : TJsonObject; begin result := true; if searchPathsArray.Count = 0 then exit; for i := 0 to searchPathsArray.Count - 1 do begin searchPathObj := searchPathsArray.O[i]; //detect if it's a group or not. if searchPathObj.Contains('targetPlatform') then begin if not IsTemplate then begin result := false; Logger.Error('searchPath groups not valid in targetPlatform, for use in templates only'); continue; end; searchPath := TSpecSearchPathGroup.Create(Logger) end else searchPath := TSpecSearchPath.Create(Logger); FSearchPaths.Add(searchPath); result := searchPath.LoadFromJson(searchPathObj) and result; if searchPath.IsGroup then begin searchPathGroup := searchPath as ISpecSearchPathGroup; if not searchPathGroup.SearchPaths.Any then begin result := false; Logger.Error('Empty searchPath/group not allowed [' + searchPathGroup.TargetPlatform.ToString + ']'); end; end; end; if not FSearchPaths.Any then begin Logger.Error('No searchPaths were specified'); result := false; end; end; function TSpecTemplateBase.LoadSourceFromJson(const sourceArray : TJsonArray) : Boolean; begin result := LoadJsonCollection(sourceArray, TSpecFileEntry, procedure(const value : IInterface) begin FSourceFiles.Add(value as ISpecFileEntry); end); end; function TSpecTemplateBase.LoadFromJson(const jsonObject : TJsonObject) : Boolean; var hasChildren : boolean; sValue : string; collectionObj : TJsonArray; begin result := true; if IsTemplate then begin if jsonObject.Contains('template') then begin result := false; Logger.Error('template property not valid in a template!'); exit; end; hasChildren := jsonObject.Count > 1; //name + if not hasChildren then begin if jsonObject.Contains('name') then sValue := jsonObject.S['name'] else sValue := 'unamed'; result := false; Logger.Error('Empty template [' + sValue + ']'); exit; end; end else begin //TODO : Rethink this validation, doesn't look all that comprehensive. //if we point to a template and have props other than compiler + platforms then fail if jsonObject.Contains('template') then begin if jsonObject.Count > 4 then //compiler + platforms + template + variables begin Logger.Error('targetPlatform cannot specify a template and it''s own definition, pick one'); result := false; end; // if it's 4 props, then variables must be one of them if jsonObject.Count > 3 then //compiler + platforms + template if not jsonObject.Contains('variables') then begin Logger.Error('targetPlatform cannot specify a template and it''s own definition, pick one'); result := false; end; exit; end; end; collectionObj := jsonObject.A['dependencies']; if collectionObj.Count > 0 then result := LoadDependenciesFromJson(collectionObj) and result; collectionObj := jsonObject.A['lib']; if collectionObj.Count > 0 then result := LoadLibraryFromJson(collectionObj) and result; collectionObj := jsonObject.A['source']; if collectionObj.Count > 0 then result := LoadSourceFromJson(collectionObj) and result; collectionObj := jsonObject.A['runtime']; if collectionObj.Count > 0 then result := LoadRuntimeFromJson(collectionObj) and result; collectionObj := jsonObject.A['design']; if collectionObj.Count > 0 then result := LoadDesignFromJson(collectionObj) and result; collectionObj := jsonObject.A['files']; if collectionObj.Count > 0 then result := LoadFilesFromJson(collectionObj) and result; collectionObj := jsonObject.A['searchPaths']; if collectionObj.Count > 0 then result := LoadSearchPathsFromJson(collectionObj) and result else begin result := false; Logger.Error('Required field [searchPaths] not found'); end; collectionObj := jsonObject.A['build']; if collectionObj.Count > 0 then result := LoadBuildEntriesFromJson(collectionObj) and result; end; end.
// XD Pascal - a 32-bit compiler for Windows // Copyright (c) 2009-2010, 2019-2020, Vasiliy Tereshkov {$I-} {$H-} unit CodeGen; interface uses Common; const MAXCODESIZE = 1 * 1024 * 1024; var Code: array [0..MAXCODESIZE - 1] of Byte; procedure InitializeCodeGen; function GetCodeSize: LongInt; procedure PushConst(Value: LongInt); procedure PushRealConst(Value: Double); procedure PushRelocConst(Value: LongInt; RelocType: TRelocType); procedure Relocate(CodeDeltaAddr, InitDataDeltaAddr, UninitDataDeltaAddr, ImportDeltaAddr: Integer); procedure PushFunctionResult(ResultType: Integer); procedure MoveFunctionResultFromFPUToEDXEAX(DataType: Integer); procedure MoveFunctionResultFromEDXEAXToFPU(DataType: Integer); procedure PushVarPtr(Addr: Integer; Scope: TScope; DeltaNesting: Byte; RelocType: TRelocType); procedure DerefPtr(DataType: Integer); procedure GetArrayElementPtr(ArrType: Integer); procedure GetFieldPtr(Offset: Integer); procedure GetCharAsTempString(Depth: Integer); procedure SaveStackTopToEAX; procedure RestoreStackTopFromEAX; procedure SaveStackTopToEDX; procedure RestoreStackTopFromEDX; procedure RaiseStackTop(NumItems: Byte); procedure DiscardStackTop(NumItems: Byte); procedure DuplicateStackTop; procedure SaveCodePos; procedure GenerateIncDec(proc: TPredefProc; Size: Byte; BaseTypeSize: Integer = 0); procedure GenerateRound(TruncMode: Boolean); procedure GenerateDoubleFromInteger(Depth: Byte); procedure GenerateDoubleFromSingle; procedure GenerateSingleFromDouble; procedure GenerateMathFunction(func: TPredefProc; ResultType: Integer); procedure GenerateUnaryOperator(op: TTokenKind; ResultType: Integer); procedure GenerateBinaryOperator(op: TTokenKind; ResultType: Integer); procedure GenerateRelation(rel: TTokenKind; ValType: Integer); procedure GenerateAssignment(DesignatorType: Integer); procedure GenerateForAssignmentAndNumberOfIterations(CounterType: Integer; Down: Boolean); procedure GenerateStructuredAssignment(DesignatorType: Integer); procedure GenerateInterfaceFieldAssignment(Offset: Integer; PopValueFromStack: Boolean; Value: LongInt; RelocType: TRelocType); procedure InitializeCStack; procedure PushToCStack(SourceStackDepth: Integer; DataType: Integer; PushByValue: Boolean); procedure ConvertSmallStructureToPointer(Addr: LongInt; Size: LongInt); procedure ConvertPointerToSmallStructure(Size: LongInt); procedure GenerateImportFuncStub(EntryPoint: LongInt); procedure GenerateCall(EntryPoint: LongInt; CallerNesting, CalleeNesting: Integer); procedure GenerateIndirectCall(CallAddressDepth: Integer); procedure GenerateReturn(TotalParamsSize, Nesting: Integer); procedure GenerateForwardReference; procedure GenerateForwardResolution(CodePos: Integer); procedure GenerateIfCondition; procedure GenerateIfProlog; procedure GenerateElseProlog; procedure GenerateIfElseEpilog; procedure GenerateCaseProlog; procedure GenerateCaseEpilog(NumCaseStatements: Integer); procedure GenerateCaseEqualityCheck(Value: LongInt); procedure GenerateCaseRangeCheck(Value1, Value2: LongInt); procedure GenerateCaseStatementProlog; procedure GenerateCaseStatementEpilog; procedure GenerateWhileCondition; procedure GenerateWhileProlog; procedure GenerateWhileEpilog; procedure GenerateRepeatCondition; procedure GenerateRepeatProlog; procedure GenerateRepeatEpilog; procedure GenerateForCondition; procedure GenerateForProlog; procedure GenerateForEpilog(CounterType: Integer; Down: Boolean); procedure GenerateGotoProlog; procedure GenerateGoto(LabelIndex: Integer); procedure GenerateGotoEpilog; procedure GenerateShortCircuitProlog(op: TTokenKind); procedure GenerateShortCircuitEpilog; procedure GenerateNestedProcsProlog; procedure GenerateNestedProcsEpilog; procedure GenerateFPUInit; procedure GenerateStackFrameProlog(PreserveRegs: Boolean); procedure GenerateStackFrameEpilog(TotalStackStorageSize: LongInt; PreserveRegs: Boolean); procedure GenerateBreakProlog(LoopNesting: Integer); procedure GenerateBreakCall(LoopNesting: Integer); procedure GenerateBreakEpilog(LoopNesting: Integer); procedure GenerateContinueProlog(LoopNesting: Integer); procedure GenerateContinueCall(LoopNesting: Integer); procedure GenerateContinueEpilog(LoopNesting: Integer); procedure GenerateExitProlog; procedure GenerateExitCall; procedure GenerateExitEpilog; implementation const MAXINSTRSIZE = 15; MAXPREVCODESIZES = 10; MAXRELOCS = 20000; MAXGOTOS = 100; MAXLOOPNESTING = 20; MAXBREAKCALLS = 100; type TRelocatable = record RelocType: TRelocType; Pos: LongInt; Value: LongInt; end; TGoto = record Pos: LongInt; LabelIndex: Integer; ForLoopNesting: Integer; end; TBreakContinueExitCallList = record NumCalls: Integer; Pos: array [1..MAXBREAKCALLS] of LongInt; end; TRegister = (EAX, ECX, EDX, ESI, EDI, EBP); var CodePosStack: array [0..1023] of Integer; CodeSize, CodePosStackTop: Integer; PrevCodeSizes: array [1..MAXPREVCODESIZES] of Integer; NumPrevCodeSizes: Integer; Reloc: array [1..MAXRELOCS] of TRelocatable; NumRelocs: Integer; Gotos: array [1..MAXGOTOS] of TGoto; NumGotos: Integer; BreakCall, ContinueCall: array [1..MAXLOOPNESTING] of TBreakContinueExitCallList; ExitCall: TBreakContinueExitCallList; procedure InitializeCodeGen; begin CodeSize := 0; CodePosStackTop := 0; NumPrevCodeSizes := 0; NumRelocs := 0; NumGotos := 0; end; function GetCodeSize: LongInt; begin Result := CodeSize; NumPrevCodeSizes := 0; end; procedure Gen(b: Byte); begin Code[CodeSize] := b; Inc(CodeSize); end; procedure GenNew(b: Byte); var i: Integer; begin if CodeSize + MAXINSTRSIZE >= MAXCODESIZE then Error('Maximum code size exceeded'); if NumPrevCodeSizes < MAXPREVCODESIZES then Inc(NumPrevCodeSizes) else for i := 1 to MAXPREVCODESIZES - 1 do PrevCodeSizes[i] := PrevCodeSizes[i + 1]; PrevCodeSizes[NumPrevCodeSizes] := CodeSize; Gen(b); end; procedure GenAt(Pos: LongInt; b: Byte); begin Code[Pos] := b; end; procedure GenWord(w: Integer); var i: Integer; begin for i := 1 to 2 do begin Gen(Byte(w and $FF)); w := w shr 8; end; end; procedure GenWordAt(Pos: LongInt; w: Integer); var i: Integer; begin for i := 0 to 1 do begin GenAt(Pos + i, Byte(w and $FF)); w := w shr 8; end; end; procedure GenDWord(dw: LongInt); var i: Integer; begin for i := 1 to 4 do begin Gen(Byte(dw and $FF)); dw := dw shr 8; end; end; procedure GenDWordAt(Pos: LongInt; dw: LongInt); var i: Integer; begin for i := 0 to 3 do begin GenAt(Pos + i, Byte(dw and $FF)); dw := dw shr 8; end; end; procedure GenRelocDWord(dw: LongInt; RelocType: TRelocType); begin Inc(NumRelocs); if NumRelocs > MAXRELOCS then Error('Maximum number of relocations exceeded'); Reloc[NumRelocs].RelocType := RelocType; Reloc[NumRelocs].Pos := CodeSize; Reloc[NumRelocs].Value := dw; GenDWord(dw); end; function PrevInstrByte(Depth, Offset: Integer): Byte; begin Result := 0; // The last generated instruction starts at Depth = 0, Offset = 0 if Depth < NumPrevCodeSizes then Result := Code[PrevCodeSizes[NumPrevCodeSizes - Depth] + Offset]; end; function PrevInstrDWord(Depth, Offset: Integer): LongInt; begin Result := 0; // The last generated instruction starts at Depth = 0, Offset = 0 if Depth < NumPrevCodeSizes then Result := PLongInt(@Code[PrevCodeSizes[NumPrevCodeSizes - Depth] + Offset])^; end; function PrevInstrRelocDWordIndex(Depth, Offset: Integer): Integer; var i: Integer; Pos: LongInt; begin Result := 0; // The last generated instruction starts at Depth = 0, Offset = 0 if Depth < NumPrevCodeSizes then begin Pos := PrevCodeSizes[NumPrevCodeSizes - Depth] + Offset; for i := NumRelocs downto 1 do if Reloc[i].Pos = Pos then begin Result := i; Exit; end; end; end; procedure RemovePrevInstr(Depth: Integer); begin if Depth >= NumPrevCodeSizes then Error('Internal fault: previous instruction not found'); CodeSize := PrevCodeSizes[NumPrevCodeSizes - Depth]; NumPrevCodeSizes := NumPrevCodeSizes - Depth - 1; end; procedure PushConst(Value: LongInt); begin GenNew($68); GenDWord(Value); // push Value end; procedure PushRealConst(Value: Double); type TIntegerArray = array [0..1] of LongInt; PIntegerArray = ^TIntegerArray; var IntegerArray: PIntegerArray; begin IntegerArray := PIntegerArray(@Value); PushConst(IntegerArray^[1]); PushConst(IntegerArray^[0]); end; procedure PushRelocConst(Value: LongInt; RelocType: TRelocType); begin GenNew($68); GenRelocDWord(Value, RelocType); // push Value ; relocatable end; procedure Relocate(CodeDeltaAddr, InitDataDeltaAddr, UninitDataDeltaAddr, ImportDeltaAddr: Integer); var i, DeltaAddr: Integer; begin DeltaAddr := 0; for i := 1 to NumRelocs do begin case Reloc[i].RelocType of CODERELOC: DeltaAddr := CodeDeltaAddr; INITDATARELOC: DeltaAddr := InitDataDeltaAddr; UNINITDATARELOC: DeltaAddr := UninitDataDeltaAddr; IMPORTRELOC: DeltaAddr := ImportDeltaAddr else Error('Internal fault: Illegal relocation type'); end; GenDWordAt(Reloc[i].Pos, Reloc[i].Value + DeltaAddr); end; end; procedure GenPushReg(Reg: TRegister); begin case Reg of EAX: GenNew($50); // push eax ECX: GenNew($51); // push ecx EDX: GenNew($52); // push edx ESI: GenNew($56); // push esi EDI: GenNew($57); // push edi EBP: GenNew($55) // push ebp else Error('Internal fault: Illegal register'); end; end; procedure GenPopReg(Reg: TRegister); function OptimizePopReg: Boolean; var HasPushRegPrefix: Boolean; Value, Addr: LongInt; ValueRelocIndex: Integer; PrevOpCode: Byte; begin Result := FALSE; PrevOpCode := PrevInstrByte(0, 0); // Optimization: (push Reg) + (pop Reg) -> 0 if ((Reg = EAX) and (PrevOpCode = $50)) or // Previous: push eax ((Reg = ECX) and (PrevOpCode = $51)) or // Previous: push ecx ((Reg = EDX) and (PrevOpCode = $52)) or // Previous: push edx ((Reg = ESI) and (PrevOpCode = $56)) or // Previous: push esi ((Reg = EDI) and (PrevOpCode = $57)) or // Previous: push edi ((Reg = EBP) and (PrevOpCode = $55)) // Previous: push ebp then begin RemovePrevInstr(0); // Remove: push Reg Result := TRUE; Exit; end // Optimization: (push eax) + (pop ecx) -> (mov ecx, eax) else if (Reg = ECX) and (PrevOpCode = $50) then // Previous: push eax begin RemovePrevInstr(0); // Remove: push eax GenNew($89); Gen($C1); // mov ecx, eax Result := TRUE; Exit; end // Optimization: (push eax) + (pop esi) -> (mov esi, eax) else if (Reg = ESI) and (PrevOpCode = $50) then // Previous: push esi begin RemovePrevInstr(0); // Remove: push eax // Special case: (mov eax, [epb + Addr]) + (push eax) + (pop esi) -> (mov esi, [epb + Addr]) if (PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $85) then // Previous: mov eax, [epb + Addr] begin Addr := PrevInstrDWord(0, 2); RemovePrevInstr(0); // Remove: mov eax, [epb + Addr] GenNew($8B); Gen($B5); GenDWord(Addr); // mov esi, [epb + Addr] end else begin GenNew($89); Gen($C6); // mov esi, eax end; Result := TRUE; Exit; end // Optimization: (push esi) + (pop eax) -> (mov eax, esi) else if (Reg = EAX) and (PrevOpCode = $56) then // Previous: push esi begin RemovePrevInstr(0); // Remove: push esi GenNew($89); Gen($F0); // mov eax, esi Result := TRUE; Exit; end // Optimization: (push Value) + (pop eax) -> (mov eax, Value) else if (Reg = EAX) and (PrevOpCode = $68) then // Previous: push Value begin Value := PrevInstrDWord(0, 1); ValueRelocIndex := PrevInstrRelocDWordIndex(0, 1); // Special case: (push esi) + (push Value) + (pop eax) -> (mov eax, Value) + (push esi) HasPushRegPrefix := PrevInstrByte(1, 0) = $56; // Previous: push esi RemovePrevInstr(0); // Remove: push Value if HasPushRegPrefix then RemovePrevInstr(0); // Remove: push esi GenNew($B8); GenDWord(Value); // mov eax, Value if HasPushRegPrefix then begin if ValueRelocIndex <> 0 then Dec(Reloc[ValueRelocIndex].Pos); // Relocate Value if necessary GenPushReg(ESI); // push esi end; Result := TRUE; Exit; end // Optimization: (push [esi]) + (pop eax) -> (mov eax, [esi]) else if (Reg = EAX) and (PrevInstrByte(0, 0) = $FF) and (PrevInstrByte(0, 1) = $36) then // Previous: push [esi] begin RemovePrevInstr(0); // Remove: push [esi] GenNew($8B); Gen($06); // mov eax, [esi] Result := TRUE; Exit; end // Optimization: (push [esi + 4]) + (mov eax, [esi]) + (pop edx) -> (mov eax, [esi]) + (mov edx, [esi + 4]) else if (Reg = EDX) and (PrevInstrByte(1, 0) = $FF) and (PrevInstrByte(1, 1) = $76) and (PrevInstrByte(1, 2) = $04) // Previous: push [esi + 4] and (PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $06) // Previous: mov eax, [esi] then begin RemovePrevInstr(1); // Remove: push [esi + 4], mov eax, [esi] GenNew($8B); Gen($06); // mov eax, [esi] GenNew($8B); Gen($56); Gen($04); // mov edx, [esi + 4] Result := TRUE; Exit; end // Optimization: (push Value) + (pop ecx) -> (mov ecx, Value) else if (Reg = ECX) and (PrevOpCode = $68) then // Previous: push Value begin Value := PrevInstrDWord(0, 1); ValueRelocIndex := PrevInstrRelocDWordIndex(0, 1); // Special case: (push eax) + (push Value) + (pop ecx) -> (mov ecx, Value) + (push eax) HasPushRegPrefix := PrevInstrByte(1, 0) = $50; // Previous: push eax RemovePrevInstr(0); // Remove: push Value if HasPushRegPrefix then RemovePrevInstr(0); // Remove: push eax / push [ebp + Addr] GenNew($B9); GenDWord(Value); // mov ecx, Value if HasPushRegPrefix then begin if ValueRelocIndex <> 0 then Dec(Reloc[ValueRelocIndex].Pos); // Relocate Value if necessary GenPushReg(EAX); // push eax end; Result := TRUE; Exit; end // Optimization: (push Value) + (pop esi) -> (mov esi, Value) else if (Reg = ESI) and (PrevOpCode = $68) then // Previous: push Value begin Value := PrevInstrDWord(0, 1); RemovePrevInstr(0); // Remove: push Value GenNew($BE); GenDWord(Value); // mov esi, Value Result := TRUE; Exit; end // Optimization: (push Value) + (mov eax, [Addr]) + (pop esi) -> (mov esi, Value) + (mov eax, [Addr]) else if (Reg = ESI) and (PrevInstrByte(1, 0) = $68) and (PrevInstrByte(0, 0) = $A1) then // Previous: push Value, mov eax, [Addr] begin Value := PrevInstrDWord(1, 1); Addr := PrevInstrDWord(0, 1); RemovePrevInstr(1); // Remove: push Value, mov eax, [Addr] GenNew($BE); GenDWord(Value); // mov esi, Value GenNew($A1); GenDWord(Addr); // mov eax, [Addr] Result := TRUE; Exit; end // Optimization: (push esi) + (mov eax, [ebp + Value]) + (pop esi) -> (mov eax, [ebp + Value]) else if (Reg = ESI) and (PrevInstrByte(1, 0) = $56) // Previous: push esi and (PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $85) // Previous: mov eax, [ebp + Value] then begin Value := PrevInstrDWord(0, 2); RemovePrevInstr(1); // Remove: push esi, mov eax, [ebp + Value] GenNew($8B); Gen($85); GenDWord(Value); // mov eax, [ebp + Value] Result := TRUE; Exit; end // Optimization: (push dword ptr [esp]) + (pop esi) -> (mov esi, [esp]) else if (Reg = ESI) and (PrevInstrByte(0, 0) = $FF) and (PrevInstrByte(0, 1) = $34) and (PrevInstrByte(0, 2) = $24) // Previous: push dword ptr [esp] then begin RemovePrevInstr(0); // Remove: push dword ptr [esp] GenNew($8B); Gen($34); Gen($24); // mov esi, [esp] Result := TRUE; Exit; end end; begin // GenPopReg if not OptimizePopReg then case Reg of EAX: GenNew($58); // pop eax ECX: GenNew($59); // pop ecx EDX: GenNew($5A); // pop edx ESI: GenNew($5E); // pop esi EDI: GenNew($5F); // pop edi EBP: GenNew($5D) // pop ebp else Error('Internal fault: Illegal register'); end; end; procedure GenPushToFPU; function OptimizeGenPushToFPU: Boolean; begin Result := FALSE; // Optimization: (fstp qword ptr [esp]) + (fld qword ptr [esp]) -> (fst qword ptr [esp]) if (PrevInstrByte(0, 0) = $DD) and (PrevInstrByte(0, 1) = $1C) and (PrevInstrByte(0, 2) = $24) then // Previous: fstp dword ptr [esp] begin RemovePrevInstr(0); // Remove: fstp dword ptr [esp] GenNew($DD); Gen($14); Gen($24); // fst qword ptr [esp] Result := TRUE; end // Optimization: (push [esi + 4]) + (push [esi]) + (fld qword ptr [esp]) -> (fld qword ptr [esi]) + (sub esp, 8) else if (PrevInstrByte(1, 0) = $FF) and (PrevInstrByte(1, 1) = $76) and (PrevInstrByte(1, 2) = $04) and // Previous: push [esi + 4] (PrevInstrByte(0, 0) = $FF) and (PrevInstrByte(0, 1) = $36) // Previous: push [esi] then begin RemovePrevInstr(1); // Remove: push [esi + 4], push [esi] GenNew($DD); Gen($06); // fld qword ptr [esi] RaiseStackTop(2); // sub esp, 8 Result := TRUE; end; end; begin if not OptimizeGenPushToFPU then begin GenNew($DD); Gen($04); Gen($24); // fld qword ptr [esp] end; end; procedure GenPopFromFPU; begin GenNew($DD); Gen($1C); Gen($24); // fstp qword ptr [esp] end; procedure PushFunctionResult(ResultType: Integer); begin if Types[ResultType].Kind = REALTYPE then GenPushReg(EDX) // push edx else if Types[ResultType].Kind = BOOLEANTYPE then begin GenNew($83); Gen($E0); Gen($01); // and eax, 1 end else case TypeSize(ResultType) of 1: if Types[ResultType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B6); Gen($C0); // movzx eax, al end else begin GenNew($0F); Gen($BE); Gen($C0); // movsx eax, al end; 2: if Types[ResultType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B7); Gen($C0); // movzx eax, ax end else begin GenNew($0F); Gen($BF); Gen($C0); // movsx eax, ax end; end; // case GenPushReg(EAX); // push eax end; procedure MoveFunctionResultFromFPUToEDXEAX(DataType: Integer); begin if Types[DataType].Kind = REALTYPE then begin RaiseStackTop(2); // sub esp, 8 ; expand stack GenPopFromFPU; // fstp qword ptr [esp] ; [esp] := st; pop GenNew($8B); Gen($04); Gen($24); // mov eax, [esp] GenNew($8B); Gen($54); Gen($24); Gen($04); // mov edx, [esp + 4] DiscardStackTop(2); // add esp, 8 ; shrink stack end else if Types[DataType].Kind = SINGLETYPE then begin RaiseStackTop(1); // sub esp, 4 ; expand stack GenNew($D9); Gen($1C); Gen($24); // fstp dword ptr [esp] ; [esp] := single(st); pop GenNew($8B); Gen($04); Gen($24); // mov eax, [esp] DiscardStackTop(1); // add esp, 4 ; shrink stack end else Error('Internal fault: Illegal type'); end; procedure MoveFunctionResultFromEDXEAXToFPU(DataType: Integer); begin if Types[DataType].Kind = REALTYPE then begin GenPushReg(EDX); // push edx GenPushReg(EAX); // push eax GenPushToFPU; // fld qword ptr [esp] DiscardStackTop(2); // add esp, 8 ; shrink stack end else if Types[DataType].Kind = SINGLETYPE then begin GenPushReg(EAX); // push eax GenNew($D9); Gen($04); Gen($24); // fld dword ptr [esp] DiscardStackTop(1); // add esp, 4 ; shrink stack end else Error('Internal fault: Illegal type'); end; procedure PushVarPtr(Addr: Integer; Scope: TScope; DeltaNesting: Byte; RelocType: TRelocType); const StaticLinkAddr = 2 * 4; var i: Integer; begin // EAX must be preserved case Scope of GLOBAL: // Global variable PushRelocConst(Addr, RelocType); LOCAL: begin if DeltaNesting = 0 then // Strictly local variable begin GenNew($8D); Gen($B5); GenDWord(Addr); // lea esi, [ebp + Addr] end else // Intermediate level variable begin GenNew($8B); Gen($75); Gen(StaticLinkAddr); // mov esi, [ebp + StaticLinkAddr] for i := 1 to DeltaNesting - 1 do begin GenNew($8B); Gen($76); Gen(StaticLinkAddr); // mov esi, [esi + StaticLinkAddr] end; GenNew($8D); Gen($B6); GenDWord(Addr); // lea esi, [esi + Addr] end; GenPushReg(ESI); // push esi end; end; // case end; procedure DerefPtr(DataType: Integer); function OptimizeDerefPtr: Boolean; var Addr, Offset: LongInt; AddrRelocIndex: Integer; begin Result := FALSE; // Global variable loading // Optimization: (mov esi, Addr) + (mov... eax, ... ptr [esi]) -> (mov... eax, ... ptr [Addr]) ; relocatable if PrevInstrByte(0, 0) = $BE then // Previous: mov esi, Addr begin Addr := PrevInstrDWord(0, 1); AddrRelocIndex := PrevInstrRelocDWordIndex(0, 1); RemovePrevInstr(0); // Remove: mov esi, Addr case TypeSize(DataType) of 1: if Types[DataType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B6); Gen($05); // movzx eax, byte ptr ... end else begin GenNew($0F); Gen($BE); Gen($05); // movsx eax, byte ptr ... end; 2: if Types[DataType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B7); Gen($05); // movzx eax, word ptr ... end else begin GenNew($0F); Gen($BF); Gen($05); // movsx eax, word ptr ... end; 4: begin GenNew($A1); // mov eax, dword ptr ... end else Error('Internal fault: Illegal designator size'); end; GenDWord(Addr); // ... [Addr] // Relocate Addr if necessary if (AddrRelocIndex <> 0) and (TypeSize(DataType) <> 4) then with Reloc[AddrRelocIndex] do Pos := Pos + 2; Result := TRUE; Exit; end // Local variable loading // Optimization: (lea esi, [ebp + Addr]) + (mov... eax, ... ptr [esi]) -> (mov... eax, ... ptr [ebp + Addr]) else if (PrevInstrByte(0, 0) = $8D) and (PrevInstrByte(0, 1) = $B5) then // Previous: lea esi, [ebp + Addr] begin Addr := PrevInstrDWord(0, 2); RemovePrevInstr(0); // Remove: lea esi, [ebp + Addr] case TypeSize(DataType) of 1: if Types[DataType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B6); Gen($85); // movzx eax, byte ptr [ebp + ... end else begin GenNew($0F); Gen($BE); Gen($85); // movsx eax, byte ptr [ebp + ... end; 2: if Types[DataType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B7); Gen($85); // movzx eax, word ptr [ebp + ... end else begin GenNew($0F); Gen($BF); Gen($85); // movsx eax, word ptr [ebp + ... end; 4: begin GenNew($8B); Gen($85); // mov eax, dword ptr [ebp + ... end else Error('Internal fault: Illegal designator size'); end; GenDWord(Addr); // ... + Addr] Result := TRUE; Exit; end // Record field loading // Optimization: (add esi, Offset) + (mov... eax, ... ptr [esi]) -> (mov... eax, ... ptr [esi + Offset]) else if (PrevInstrByte(0, 0) = $81) and (PrevInstrByte(0, 1) = $C6) then // Previous: add esi, Offset begin Offset := PrevInstrDWord(0, 2); RemovePrevInstr(0); // Remove: add esi, Offset case TypeSize(DataType) of 1: if Types[DataType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B6); Gen($86); // movzx eax, byte ptr [esi + ... end else begin GenNew($0F); Gen($BE); Gen($86); // movsx eax, byte ptr [esi + ... end; 2: if Types[DataType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B7); Gen($86); // movzx eax, word ptr [esi + ... end else begin GenNew($0F); Gen($BF); Gen($86); // movsx eax, word ptr [esi + ... end; 4: begin GenNew($8B); Gen($86); // mov eax, dword ptr [esi + ... end else Error('Internal fault: Illegal designator size'); end; GenDWord(Offset); // ... + Offset] Result := TRUE; Exit; end; end; begin // DerefPtr GenPopReg(ESI); // pop esi if Types[DataType].Kind = REALTYPE then // Special case: Double begin GenNew($FF); Gen($76); Gen($04); // push [esi + 4] GenNew($FF); Gen($36); // push [esi] end else // General rule begin if not OptimizeDerefPtr then case TypeSize(DataType) of 1: if Types[DataType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B6); Gen($06); // movzx eax, byte ptr [esi] end else begin GenNew($0F); Gen($BE); Gen($06); // movsx eax, byte ptr [esi] end; 2: if Types[DataType].Kind in UnsignedTypes then begin GenNew($0F); Gen($B7); Gen($06); // movzx eax, word ptr [esi] end else begin GenNew($0F); Gen($BF); Gen($06); // movsx eax, word ptr [esi] end; 4: begin GenNew($8B); Gen($06); // mov eax, dword ptr [esi] end else Error('Internal fault: Illegal designator size'); end; GenPushReg(EAX); // push eax end; end; procedure GetArrayElementPtr(ArrType: Integer); function OptimizeGetArrayElementPtr: Boolean; var BaseAddr, IndexAddr: LongInt; Index: Integer; begin Result := FALSE; // Global arrays // Optimization: (push BaseAddr) + (mov eax, [ebp + IndexAddr]) + (pop esi) -> (mov esi, BaseAddr) + (mov eax, [ebp + IndexAddr]) if (PrevInstrByte(1, 0) = $68) and (PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $85) then // Previous: push BaseAddr, mov eax, [ebp + IndexAddr] begin BaseAddr := PrevInstrDWord(1, 1); IndexAddr := PrevInstrDWord(0, 2); RemovePrevInstr(1); // Remove: push BaseAddr, mov eax, [ebp + IndexAddr] GenNew($BE); GenDWord(BaseAddr); // mov esi, BaseAddr ; suilable for relocatable addresses (instruction length is the same as for push BaseAddr) GenNew($8B); Gen($85); GenDWord(IndexAddr); // mov eax, [ebp + IndexAddr] Result := TRUE; end // Optimization: (push BaseAddr) + (mov eax, Index) + (pop esi) -> (mov esi, BaseAddr) + (mov eax, Index) else if (PrevInstrByte(1, 0) = $68) and (PrevInstrByte(0, 0) = $B8) then // Previous: push BaseAddr, mov eax, Index begin BaseAddr := PrevInstrDWord(1, 1); Index := PrevInstrDWord(0, 1); RemovePrevInstr(1); // Remove: push BaseAddr, mov eax, Index GenNew($BE); GenDWord(BaseAddr); // mov esi, BaseAddr ; suitable for relocatable addresses (instruction length is the same as for push BaseAddr) GenNew($B8); GenDWord(Index); // mov eax, Index Result := TRUE; end // Local arrays // Optimization: (mov eax, [ebp + BaseAddr]) + (push eax) + (mov eax, [ebp + IndexAddr]) + (pop esi) -> (mov esi, [ebp + BaseAddr]) + (mov eax, [ebp + IndexAddr]) else if (PrevInstrByte(2, 0) = $8B) and (PrevInstrByte(2, 1) = $85) and // Previous: mov eax, [ebp + BaseAddr] (PrevInstrByte(1, 0) = $50) and // Previous: push eax (PrevInstrByte(0, 0) = $8B) and (PrevInstrByte(0, 1) = $85) // Previous: mov eax, [ebp + IndexAddr] then begin BaseAddr := PrevInstrDWord(2, 2); IndexAddr := PrevInstrDWord(0, 2); RemovePrevInstr(2); // Remove: mov eax, [ebp + BaseAddr], push eax, mov eax, [ebp + IndexAddr] GenNew($8B); Gen($B5); GenDWord(BaseAddr); // mov esi, [ebp + BaseAddr] GenNew($8B); Gen($85); GenDWord(IndexAddr); // mov eax, [ebp + IndexAddr] Result := TRUE; end // Optimization: (mov eax, [ebp + BaseAddr]) + (push eax) + (mov eax, Index) + (pop esi) -> (mov esi, [ebp + BaseAddr]) + (mov eax, Index) else if (PrevInstrByte(2, 0) = $8B) and (PrevInstrByte(2, 1) = $85) and // Previous: mov eax, [ebp + BaseAddr] (PrevInstrByte(1, 0) = $50) and // Previous: push eax (PrevInstrByte(0, 0) = $B8) // Previous: mov eax, Index then begin BaseAddr := PrevInstrDWord(2, 2); Index := PrevInstrDWord(0, 1); RemovePrevInstr(2); // Remove: mov eax, [ebp + BaseAddr], push eax, mov eax, Index GenNew($8B); Gen($B5); GenDWord(BaseAddr); // mov esi, [ebp + BaseAddr] GenNew($B8); GenDWord(Index); // mov eax, Index Result := TRUE; end end; function Log2(x: LongInt): ShortInt; var i: Integer; begin for i := 0 to 31 do if x = 1 shl i then begin Result := i; Exit; end; Result := -1; end; var BaseTypeSize, IndexLowBound: Integer; Log2BaseTypeSize: ShortInt; begin GenPopReg(EAX); // pop eax ; Array index if not OptimizeGetArrayElementPtr then GenPopReg(ESI); // pop esi ; Array base offset BaseTypeSize := TypeSize(Types[ArrType].BaseType); IndexLowBound := LowBound(Types[ArrType].IndexType); if IndexLowBound = 1 then GenNew($48) // dec eax else if IndexLowBound <> 0 then begin GenNew($2D); GenDWord(IndexLowBound); // sub eax, IndexLowBound end; if (BaseTypeSize <> 1) and (BaseTypeSize <> 2) and (BaseTypeSize <> 4) and (BaseTypeSize <> 8) then begin Log2BaseTypeSize := Log2(BaseTypeSize); if Log2BaseTypeSize > 0 then begin GenNew($C1); Gen($E0); Gen(Log2BaseTypeSize); // shl eax, Log2BaseTypeSize end else begin GenNew($69); Gen($C0); GenDWord(BaseTypeSize); // imul eax, BaseTypeSize end; end; // if GenNew($8D); Gen($34); // lea esi, [esi + eax * ... case BaseTypeSize of 1: Gen($06); // ... * 1] 2: Gen($46); // ... * 2] 4: Gen($86); // ... * 4] 8: Gen($C6) // ... * 8] else Gen($06) // ... * 1] ; already multiplied above end; GenPushReg(ESI); // push esi end; procedure GetFieldPtr(Offset: Integer); function OptimizeGetFieldPtr: Boolean; var Addr: LongInt; BaseTypeSizeCode: Byte; begin Result := FALSE; // Optimization: (lea esi, [ebp + Addr]) + (add esi, Offset) -> (lea esi, [ebp + Addr + Offset]) if (PrevInstrByte(0, 0) = $8D) and (PrevInstrByte(0, 1) = $B5) then // Previous: lea esi, [ebp + Addr] begin Addr := PrevInstrDWord(0, 2); RemovePrevInstr(0); // Remove: lea esi, [ebp + Addr] GenNew($8D); Gen($B5); GenDWord(Addr + Offset); // lea esi, [ebp + Addr + Offset] Result := TRUE; end // Optimization: (lea esi, [esi + eax * BaseTypeSize]) + (add esi, Offset) -> (lea esi, [esi + eax * BaseTypeSize + Offset]) else if (PrevInstrByte(0, 0) = $8D) and (PrevInstrByte(0, 1) = $34) then // Previous: lea esi, [esi + eax * BaseTypeSize] begin BaseTypeSizeCode := PrevInstrDWord(0, 2); RemovePrevInstr(0); // Remove: lea esi, [esi + eax * BaseTypeSize] GenNew($8D); Gen($B4); Gen(BaseTypeSizeCode); GenDWord(Offset); // lea esi, [esi + eax * BaseTypeSize + Offset] Result := TRUE; end; end; begin // GetFieldPtr if Offset <> 0 then begin GenPopReg(ESI); // pop esi if not OptimizeGetFieldPtr then begin GenNew($81); Gen($C6); GenDWord(Offset); // add esi, Offset end; GenPushReg(ESI); // push esi end; end; procedure GetCharAsTempString(Depth: Integer); begin if (Depth <> 0) and (Depth <> SizeOf(LongInt)) then Error('Internal fault: Illegal depth'); GenPopReg(ESI); // pop esi ; Temporary string address if Depth = SizeOf(LongInt) then GenPopReg(ECX); // pop ecx ; Some other string address GenPopReg(EAX); // pop eax ; Character GenNew($88); Gen($06); // mov byte ptr [esi], al GenNew($C6); Gen($46); Gen($01); Gen($00); // mov byte ptr [esi + 1], 0 GenPushReg(ESI); // push esi if Depth = SizeOf(LongInt) then GenPushReg(ECX); // push ecx ; Some other string address end; procedure SaveStackTopToEAX; begin GenPopReg(EAX); // pop eax end; procedure RestoreStackTopFromEAX; begin GenPushReg(EAX); // push eax end; procedure SaveStackTopToEDX; begin GenPopReg(EDX); // pop edx end; procedure RestoreStackTopFromEDX; begin GenPushReg(EDX); // push edx end; procedure RaiseStackTop(NumItems: Byte); begin GenNew($81); Gen($EC); GenDWord(SizeOf(LongInt) * NumItems); // sub esp, 4 * NumItems end; procedure DiscardStackTop(NumItems: Byte); function OptimizeDiscardStackTop: Boolean; var Value: LongInt; begin Result := FALSE; // Optimization: (push Reg) + (add esp, 4 * NumItems) -> (add esp, 4 * (NumItems - 1)) if PrevInstrByte(0, 0) in [$50, $51, $52, $56, $57, $55] then // Previous: push Reg begin RemovePrevInstr(0); // Remove: push Reg if NumItems > 1 then begin GenNew($81); Gen($C4); GenDWord(SizeOf(LongInt) * (NumItems - 1)); // add esp, 4 * (NumItems - 1) end; Result := TRUE; end // Optimization: (sub esp, Value) + (add esp, 4 * NumItems) -> (add esp, 4 * NumItems - Value) else if (PrevInstrByte(0, 0) = $81) and (PrevInstrByte(0, 1) = $EC) then // Previous: sub esp, Value begin Value := PrevInstrDWord(0, 2); RemovePrevInstr(0); // Remove: sub esp, Value if SizeOf(LongInt) * NumItems <> Value then begin GenNew($81); Gen($C4); GenDWord(SizeOf(LongInt) * NumItems - Value); // add esp, 4 * NumItems - Value end; Result := TRUE; end end; begin // DiscardStackTop if not OptimizeDiscardStackTop then begin GenNew($81); Gen($C4); GenDWord(SizeOf(LongInt) * NumItems); // add esp, 4 * NumItems end end; procedure DiscardStackTopAt(Pos: LongInt; NumItems: Byte); begin GenAt(Pos, $81); GenAt(Pos + 1, $C4); GenDWordAt(Pos + 2, SizeOf(LongInt) * NumItems); // add esp, 4 * NumItems end; procedure DuplicateStackTop; begin GenNew($FF); Gen($34); Gen($24); // push dword ptr [esp] end; procedure SaveCodePos; begin Inc(CodePosStackTop); CodePosStack[CodePosStackTop] := GetCodeSize; end; function RestoreCodePos: LongInt; begin Result := CodePosStack[CodePosStackTop]; Dec(CodePosStackTop); end; procedure GenerateIncDec(proc: TPredefProc; Size: Byte; BaseTypeSize: Integer = 0); begin GenPopReg(ESI); // pop esi if BaseTypeSize <> 0 then // Special case: typed pointer begin GenNew($81); // ... dword ptr ... case proc of INCPROC: Gen($06); // add ... [esi], ... DECPROC: Gen($2E); // sub ... [esi], ... end; GenDWord(BaseTypeSize); // ... BaseTypeSize end else // General rule begin case Size of 1: begin GenNew($FE); // ... byte ptr ... end; 2: begin GenNew($66); Gen($FF); // ... word ptr ... end; 4: begin GenNew($FF); // ... dword ptr ... end; end; case proc of INCPROC: Gen($06); // inc ... [esi] DECPROC: Gen($0E); // dec ... [esi] end; end; end; procedure GenerateRound(TruncMode: Boolean); begin GenPushToFPU; // fld qword ptr [esp] ; st = operand DiscardStackTop(1); // add esp, 4 ; shrink stack if TruncMode then begin GenNew($66); Gen($C7); Gen($44); Gen($24); Gen(Byte(-4)); GenWord($0F7F); // mov word ptr [esp - 4], 0F7Fh GenNew($D9); Gen($6C); Gen($24); Gen(Byte(-4)); // fldcw word ptr [esp - 4] end; GenNew($DB); Gen($1C); Gen($24); // fistp dword ptr [esp] ; [esp] := round(st); pop if TruncMode then begin GenNew($66); Gen($C7); Gen($44); Gen($24); Gen(Byte(-4)); GenWord($037F); // mov word ptr [esp - 4], 037Fh GenNew($D9); Gen($6C); Gen($24); Gen(Byte(-4)); // fldcw word ptr [esp - 4] end; end;// GenerateRound procedure GenerateDoubleFromInteger(Depth: Byte); begin if Depth = 0 then begin GenNew($DB); Gen($04); Gen($24); // fild dword ptr [esp] ; st := double(operand) RaiseStackTop(1); // sub esp, 4 ; expand stack GenPopFromFPU; // fstp qword ptr [esp] ; [esp] := st; pop end else if Depth = SizeOf(Double) then begin GenPushToFPU; // fld qword ptr [esp] ; st := operand2 GenNew($DB); Gen($44); Gen($24); Gen(Depth); // fild dword ptr [esp + Depth] ; st := double(operand), st(1) = operand2 RaiseStackTop(1); // sub esp, 4 ; expand stack GenNew($DD); Gen($5C); Gen($24); Gen(Depth); // fstp qword ptr [esp + Depth] ; [esp + Depth] := operand; pop GenPopFromFPU; // fstp qword ptr [esp] ; [esp] := operand2; pop end else Error('Internal fault: Illegal stack depth'); end;// GenerateDoubleFromInteger procedure GenerateDoubleFromSingle; begin GenNew($D9); Gen($04); Gen($24); // fld dword ptr [esp] ; st := double(operand) RaiseStackTop(1); // sub esp, 4 ; expand stack GenPopFromFPU; // fstp qword ptr [esp] ; [esp] := st; pop end; // GenerateDoubleFromSingle procedure GenerateSingleFromDouble; begin GenPushToFPU; // fld qword ptr [esp] ; st := operand DiscardStackTop(1); // add esp, 4 ; shrink stack GenNew($D9); Gen($1C); Gen($24); // fstp dword ptr [esp] ; [esp] := single(st); pop end; // GenerateDoubleFromSingle procedure GenerateMathFunction(func: TPredefProc; ResultType: Integer); begin if Types[ResultType].Kind = REALTYPE then // Real type begin GenPushToFPU; // fld qword ptr [esp] ; st = operand case func of ABSFUNC: begin GenNew($D9); Gen($E1); // fabs end; SQRFUNC: begin GenNew($DC); Gen($C8); // fmul st, st end; SINFUNC: begin GenNew($D9); Gen($FE); // fsin end; COSFUNC: begin GenNew($D9); Gen($FF); // fcos end; ARCTANFUNC: begin GenNew($D9); Gen($E8); // fld1 GenNew($D9); Gen($F3); // fpatan ; st := arctan(x / 1.0) end; EXPFUNC: begin GenNew($D9); Gen($EA); // fldl2e GenNew($DE); Gen($C9); // fmul GenNew($D9); Gen($C0); // fld st GenNew($D9); Gen($FC); // frndint GenNew($DD); Gen($D2); // fst st(2) ; st(2) := round(x * log2(e)) GenNew($DE); Gen($E9); // fsub GenNew($D9); Gen($F0); // f2xm1 ; st := 2 ^ frac(x * log2(e)) - 1 GenNew($D9); Gen($E8); // fld1 GenNew($DE); Gen($C1); // fadd GenNew($D9); Gen($FD); // fscale ; st := 2 ^ frac(x * log2(e)) * 2 ^ round(x * log2(e)) = exp(x) end; LNFUNC: begin GenNew($D9); Gen($ED); // fldln2 GenNew($D9); Gen($C9); // fxch GenNew($D9); Gen($F1); // fyl2x ; st := ln(2) * log2(x) = ln(x) end; SQRTFUNC: begin GenNew($D9); Gen($FA); // fsqrt end; end;// case GenPopFromFPU; // fstp qword ptr [esp] ; [esp] := st; pop end else // Ordinal types case func of ABSFUNC: begin GenPopReg(EAX); // pop eax GenNew($83); Gen($F8); Gen($00); // cmp eax, 0 GenNew($7D); Gen($02); // jge +2 GenNew($F7); Gen($D8); // neg eax GenPushReg(EAX); // push eax end; SQRFUNC: begin GenPopReg(EAX); // pop eax GenNew($F7); Gen($E8); // imul eax GenPushReg(EAX); // push eax end; end;// case end;// GenerateMathFunction procedure GenerateUnaryOperator(op: TTokenKind; ResultType: Integer); begin if Types[ResultType].Kind = REALTYPE then // Real type begin if op = MINUSTOK then begin GenPushToFPU; // fld qword ptr [esp] ; st = operand GenNew($D9); Gen($E0); // fchs GenPopFromFPU; // fstp qword ptr [esp] ; [esp] := st; pop end; end else // Ordinal types begin GenPopReg(EAX); // pop eax case op of MINUSTOK: begin GenNew($F7); Gen($D8); // neg eax end; NOTTOK: begin GenNew($F7); Gen($D0); // not eax end; end;// case if Types[ResultType].Kind = BOOLEANTYPE then begin GenNew($83); Gen($E0); Gen($01); // and eax, 1 end; GenPushReg(EAX); // push eax end;// else end; procedure GenerateBinaryOperator(op: TTokenKind; ResultType: Integer); begin if Types[ResultType].Kind = REALTYPE then // Real type begin GenPushToFPU; // fld qword ptr [esp] ; st = operand2 DiscardStackTop(2); // add esp, 8 GenPushToFPU; // fld qword ptr [esp] ; st(1) = operand2; st = operand1 case op of PLUSTOK: begin GenNew($DE); Gen($C1); // fadd ; st(1) := st(1) + st; pop end; MINUSTOK: begin GenNew($DE); Gen($E1); // fsubr ; st(1) := st - st(1); pop end; MULTOK: begin GenNew($DE); Gen($C9); // fmul ; st(1) := st(1) * st; pop end; DIVTOK: begin GenNew($DE); Gen($F1); // fdivr ; st(1) := st / st(1); pop end; end;// case GenPopFromFPU; // fstp dword ptr [esp] ; [esp] := st; pop end // if else // Ordinal types begin // For commutative operators, use reverse operand order for better optimization if (op = PLUSTOK) or (op = ANDTOK) or (op = ORTOK) or (op = XORTOK) then begin GenPopReg(EAX); // pop eax GenPopReg(ECX); // pop ecx end else begin GenPopReg(ECX); // pop ecx GenPopReg(EAX); // pop eax end; case op of PLUSTOK: begin GenNew($03); Gen($C1); // add eax, ecx end; MINUSTOK: begin GenNew($2B); Gen($C1); // sub eax, ecx end; MULTOK: begin GenNew($F7); Gen($E9); // imul ecx end; IDIVTOK, MODTOK: begin GenNew($99); // cdq GenNew($F7); Gen($F9); // idiv ecx if op = MODTOK then begin GenNew($8B); Gen($C2); // mov eax, edx ; save remainder end; end; SHLTOK: begin GenNew($D3); Gen($E0); // shl eax, cl end; SHRTOK: begin GenNew($D3); Gen($E8); // shr eax, cl end; ANDTOK: begin GenNew($23); Gen($C1); // and eax, ecx end; ORTOK: begin GenNew($0B); Gen($C1); // or eax, ecx end; XORTOK: begin GenNew($33); Gen($C1); // xor eax, ecx end; end;// case if Types[ResultType].Kind = BOOLEANTYPE then begin GenNew($83); Gen($E0); Gen($01); // and eax, 1 end; GenPushReg(EAX); // push eax end;// else end; procedure GenerateRelation(rel: TTokenKind; ValType: Integer); function OptimizeGenerateRelation: Boolean; var Value: LongInt; begin Result := FALSE; // Optimization: (mov ecx, Value) + (cmp eax, ecx) -> (cmp eax, Value) if PrevInstrByte(0, 0) = $B9 then // Previous: mov ecx, Value begin Value := PrevInstrDWord(0, 1); RemovePrevInstr(0); // Remove: mov ecx, Value GenNew($3D); GenDWord(Value); // cmp eax, Value Result := TRUE; end; end; begin if Types[ValType].Kind = REALTYPE then // Real type begin GenPushToFPU; // fld dword ptr [esp] ; st = operand2 DiscardStackTop(2); // add esp, 8 GenPushToFPU; // fld dword ptr [esp] ; st(1) = operand2; st = operand1 DiscardStackTop(2); // add esp, 8 GenNew($DE); Gen($D9); // fcompp ; test st - st(1) GenNew($DF); Gen($E0); // fnstsw ax GenNew($9E); // sahf GenNew($B8); GenDWord(1); // mov eax, 1 ; TRUE case rel of EQTOK: GenNew($74); // je ... NETOK: GenNew($75); // jne ... GTTOK: GenNew($77); // ja ... GETOK: GenNew($73); // jae ... LTTOK: GenNew($72); // jb ... LETOK: GenNew($76); // jbe ... end;// case end else // Ordinal types begin GenPopReg(ECX); // pop ecx GenPopReg(EAX); // pop eax if not OptimizeGenerateRelation then begin GenNew($39); Gen($C8); // cmp eax, ecx end; GenNew($B8); GenDWord(1); // mov eax, 1 ; TRUE case rel of EQTOK: GenNew($74); // je ... NETOK: GenNew($75); // jne ... GTTOK: GenNew($7F); // jg ... GETOK: GenNew($7D); // jge ... LTTOK: GenNew($7C); // jl ... LETOK: GenNew($7E); // jle ... end;// case end;// else Gen($02); // ... +2 GenNew($31); Gen($C0); // xor eax, eax ; FALSE GenPushReg(EAX); // push eax end; procedure GenerateAssignment(DesignatorType: Integer); function OptimizeGenerateRealAssignment: Boolean; begin Result := FALSE; // Optimization: (fstp qword ptr [esp]) + (pop eax) + (pop edx) + (pop esi) + (mov [esi], eax) + (mov [esi + 4], edx) -> (add esp, 8) + (pop esi) + (fstp qword ptr [esi]) if (PrevInstrByte(0, 0) = $DD) and (PrevInstrByte(0, 1) = $1C) and (PrevInstrByte(0, 2) = $24) then // Previous: fstp dword ptr [esp] begin RemovePrevInstr(0); // Remove: fstp dword ptr [esp] DiscardStackTop(2); // add esp, 8 GenPopReg(ESI); // pop esi GenNew($DD); Gen($1E); // fstp qword ptr [esi] Result := TRUE; end; end; function OptimizeGenerateAssignment: Boolean; var IsMov, IsMovPush: Boolean; Value: LongInt; ValueRelocIndex: Integer; begin Result := FALSE; IsMov := PrevInstrByte(0, 0) = $B8; // Previous: mov eax, Value IsMovPush := (PrevInstrByte(1, 0) = $B8) and (PrevInstrByte(0, 0) = $56); // Previous: mov eax, Value, push esi if IsMov then begin Value := PrevInstrDWord(0, 1); ValueRelocIndex := PrevInstrRelocDWordIndex(0, 1); end else begin Value := PrevInstrDWord(1, 1); ValueRelocIndex := PrevInstrRelocDWordIndex(1, 1); end; // Optimization: (mov eax, Value) + [(push esi) + (pop esi)] + (mov [esi], al/ax/eax) -> (mov byte/word/dword ptr [esi], Value) if (IsMov or IsMovPush) and (ValueRelocIndex = 0) then // Non-relocatable Value only begin if IsMovPush then GenPopReg(ESI); // pop esi ; destination address RemovePrevInstr(0); // Remove: mov eax, Value if IsMov then GenPopReg(ESI); // pop esi ; destination address case TypeSize(DesignatorType) of 1: begin GenNew($C6); Gen($06); Gen(Byte(Value)); // mov byte ptr [esi], Value end; 2: begin GenNew($66); Gen($C7); Gen($06); GenWord(Word(Value)); // mov word ptr [esi], Value end; 4: begin GenNew($C7); Gen($06); GenDWord(Value); // mov dword ptr [esi], Value end else Error('Internal fault: Illegal designator size'); end; // case Result := TRUE; end; end; begin if Types[DesignatorType].Kind = REALTYPE then // Special case: 64-bit real type begin if not OptimizeGenerateRealAssignment then begin GenPopReg(EAX); // pop eax ; source value GenPopReg(EDX); // pop edx ; source value GenPopReg(ESI); // pop esi ; destination address GenNew($89); Gen($06); // mov [esi], eax GenNew($89); Gen($56); Gen($04); // mov [esi + 4], edx end end else // General rule: 8, 16, 32-bit types begin if not OptimizeGenerateAssignment then begin GenPopReg(EAX); // pop eax ; source value GenPopReg(ESI); // pop esi ; destination address case TypeSize(DesignatorType) of 1: begin GenNew($88); Gen($06); // mov [esi], al end; 2: begin GenNew($66); Gen($89); Gen($06); // mov [esi], ax end; 4: begin GenNew($89); Gen($06); // mov [esi], eax end else Error('Internal fault: Illegal designator size'); end; // case end; end; end; procedure GenerateForAssignmentAndNumberOfIterations(CounterType: Integer; Down: Boolean); function OptimizeGenerateForAssignmentAndNumberOfIterations: Boolean; var InitialValue, FinalValue: LongInt; InitialValueRelocIndex, FinalValueRelocIndex: LongInt; begin Result := FALSE; // Optimization: (push InitialValue) + (push FinalValue) + ... -> ... (constant initial and final values) if (PrevInstrByte(1, 0) = $68) and (PrevInstrByte(0, 0) = $68) then // Previous: push InitialValue, push FinalValue begin InitialValue := PrevInstrDWord(1, 1); InitialValueRelocIndex := PrevInstrRelocDWordIndex(1, 1); FinalValue := PrevInstrDWord(0, 1); FinalValueRelocIndex := PrevInstrRelocDWordIndex(0, 1); if (InitialValueRelocIndex = 0) and (FinalValueRelocIndex = 0) then // Non-relocatable values only begin RemovePrevInstr(1); // Remove: push InitialValue, push FinalValue GenPopReg(ESI); // pop esi ; counter address case TypeSize(CounterType) of 1: begin GenNew($C6); Gen($06); Gen(Byte(InitialValue)); // mov byte ptr [esi], InitialValue end; 2: begin GenNew($66); Gen($C7); Gen($06); GenWord(Word(InitialValue)); // mov word ptr [esi], InitialValue end; 4: begin GenNew($C7); Gen($06); GenDWord(InitialValue); // mov dword ptr [esi], InitialValue end else Error('Internal fault: Illegal designator size'); end; // case // Number of iterations if Down then PushConst(InitialValue - FinalValue + 1) else PushConst(FinalValue - InitialValue + 1); Result := TRUE; end; end; end; begin if not OptimizeGenerateForAssignmentAndNumberOfIterations then begin GenPopReg(EAX); // pop eax ; final value GenPopReg(ECX); // pop ecx ; initial value GenPopReg(ESI); // pop esi ; counter address case TypeSize(CounterType) of 1: begin GenNew($88); Gen($0E); // mov [esi], cl end; 2: begin GenNew($66); Gen($89); Gen($0E); // mov [esi], cx end; 4: begin GenNew($89); Gen($0E); // mov [esi], ecx end else Error('Internal fault: Illegal designator size'); end; // case // Number of iterations if Down then begin GenNew($29); Gen($C1); // sub ecx, eax GenNew($41); // inc ecx GenPushReg(ECX); // push ecx end else begin GenNew($2B); Gen($C1); // sub eax, ecx GenNew($40); // inc eax GenPushReg(EAX); // push eax end; end; end; procedure GenerateStructuredAssignment(DesignatorType: Integer); begin // ECX should be preserved GenPopReg(ESI); // pop esi ; source address GenPopReg(EDI); // pop edi ; destination address // Copy source to destination GenPushReg(ECX); // push ecx GenNew($B9); GenDWord(TypeSize(DesignatorType)); // mov ecx, TypeSize(DesignatorType) GenNew($FC); // cld ; increment esi, edi after each step GenNew($F3); Gen($A4); // rep movsb GenPopReg(ECX); // pop ecx end; procedure GenerateInterfaceFieldAssignment(Offset: Integer; PopValueFromStack: Boolean; Value: LongInt; RelocType: TRelocType); begin if PopValueFromStack then begin GenPopReg(ESI); // pop esi GenNew($89); Gen($B5); GenDWord(Offset); // mov dword ptr [ebp + Offset], esi GenPushReg(ESI); // push esi end else begin GenNew($C7); Gen($85); GenDWord(Offset); GenRelocDWord(Value, RelocType); // mov dword ptr [ebp + Offset], Value end; end; procedure InitializeCStack; begin GenNew($89); Gen($E1); // mov ecx, esp end; procedure PushToCStack(SourceStackDepth: Integer; DataType: Integer; PushByValue: Boolean); var ActualSize: Integer; begin if PushByValue and (Types[DataType].Kind in StructuredTypes) then begin ActualSize := Align(TypeSize(DataType), SizeOf(LongInt)); // Copy structure to the C stack RaiseStackTop(ActualSize div SizeOf(LongInt)); // sub esp, ActualSize GenNew($8B); Gen($B1); GenDWord(SourceStackDepth); // mov esi, [ecx + SourceStackDepth] GenNew($89); Gen($E7); // mov edi, esp GenPushReg(EDI); // push edi ; destination address GenPushReg(ESI); // push esi ; source address GenerateStructuredAssignment(DataType); end else if PushByValue and (Types[DataType].Kind = REALTYPE) then begin GenNew($FF); Gen($B1); GenDWord(SourceStackDepth + SizeOf(LongInt)); // push [ecx + SourceStackDepth + 4] GenNew($FF); Gen($B1); GenDWord(SourceStackDepth); // push [ecx + SourceStackDepth] end else begin GenNew($FF); Gen($B1); GenDWord(SourceStackDepth); // push [ecx + SourceStackDepth] end; end; procedure ConvertSmallStructureToPointer(Addr: LongInt; Size: LongInt); begin // Converts a small structure in EDX:EAX into a pointer in EAX if Size <= SizeOf(LongInt) then begin GenNew($89); Gen($85); GenDWord(Addr); // mov [ebp + Addr], eax end else if Size <= 2 * SizeOf(LongInt) then begin GenNew($89); Gen($85); GenDWord(Addr); // mov [ebp + Addr], eax GenNew($89); Gen($95); GenDWord(Addr + SizeOf(LongInt)); // mov [ebp + Addr + 4], edx end else Error('Internal fault: Structure is too large to return in EDX:EAX'); GenNew($8D); Gen($85); GenDWord(Addr); // lea eax, [ebp + Addr] end; procedure ConvertPointerToSmallStructure(Size: LongInt); begin // Converts a pointer in EAX into a small structure in EDX:EAX if Size <= SizeOf(LongInt) then begin GenNew($8B); Gen($00); // mov eax, [eax] end else if Size <= 2 * SizeOf(LongInt) then begin GenNew($8B); Gen($50); Gen(Byte(SizeOf(LongInt))); // mov edx, [eax + 4] GenNew($8B); Gen($00); // mov eax, [eax] end else Error('Internal fault: Structure is too large to return in EDX:EAX'); end; procedure GenerateImportFuncStub(EntryPoint: LongInt); begin GenNew($FF); Gen($25); GenRelocDWord(EntryPoint, IMPORTRELOC); // jmp ds:EntryPoint ; relocatable end; procedure GenerateCall(EntryPoint: LongInt; CallerNesting, CalleeNesting: Integer); const StaticLinkAddr = 2 * 4; var CodePos: Integer; i: Integer; begin if (CallerNesting < 0) or (CalleeNesting < 1) or (CallerNesting - CalleeNesting < -1) then Error('Internal fault: Illegal nesting level'); if CalleeNesting > 1 then // If a nested routine is called, push static link as the last hidden parameter if CallerNesting - CalleeNesting = -1 then // The caller and the callee's enclosing routine are at the same nesting level begin GenPushReg(EBP); // push ebp end else // The caller is deeper begin GenNew($8B); Gen($75); Gen(StaticLinkAddr); // mov esi, [ebp + StaticLinkAddr] for i := 1 to CallerNesting - CalleeNesting do begin GenNew($8B); Gen($76); Gen(StaticLinkAddr); // mov esi, [esi + StaticLinkAddr] end; GenPushReg(ESI); // push esi end; // Call the routine CodePos := GetCodeSize; GenNew($E8); GenDWord(EntryPoint - (CodePos + 5)); // call EntryPoint end; procedure GenerateIndirectCall(CallAddressDepth: Integer); begin GenNew($8B); Gen($B4); Gen($24); GenDWord(CallAddressDepth); // mov esi, dword ptr [esp + CallAddressDepth] GenNew($FF); Gen($16); // call [esi] end; procedure GenerateReturn(TotalParamsSize, Nesting: Integer); begin GenNew($C2); // ret ... if Nesting = 1 then GenWord(TotalParamsSize) // ... TotalParamsSize else GenWord(TotalParamsSize + 4); // ... TotalParamsSize + 4 ; + 4 is for static link end; procedure GenerateForwardReference; begin GenNew($90); // nop ; jump to the procedure entry point will be inserted here GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop end; procedure GenerateForwardResolution(CodePos: Integer); begin GenAt(CodePos, $E9); GenDWordAt(CodePos + 1, GetCodeSize - (CodePos + 5)); // jmp GetCodeSize end; procedure GenerateForwardResolutionToDestination(CodePos, DestPos: Integer); begin GenAt(CodePos, $E9); GenDWordAt(CodePos + 1, DestPos - (CodePos + 5)); // jmp DestPos end; procedure GenerateIfCondition; function OptimizeGenerateIfCondition: Boolean; var JumpOpCode: Byte; begin Result := FALSE; JumpOpCode := PrevInstrByte(1, 0); // Optimization: (mov eax, 1) + (jxx +2) + (xor eax, eax) + (test eax, eax) + (jne +5) -> (jxx +5) if (PrevInstrByte(2, 0) = $B8) and (PrevInstrDWord(2, 1) = 1) and // Previous: mov eax, 1 (JumpOpCode in [$74, $75, $77, $73, $72, $76, $7F, $7D, $7C, $7E]) and (PrevInstrByte(1, 1) = $02) and // Previous: jxx +2 (PrevInstrByte(0, 0) = $31) and (PrevInstrByte(0, 1) = $C0) // Previous: xor eax, eax then begin RemovePrevInstr(2); // Remove: mov eax, 1, jxx +2, xor eax, eax GenNew(JumpOpCode); Gen($05); // jxx +5 Result := TRUE; end; end; begin GenPopReg(EAX); // pop eax if not OptimizeGenerateIfCondition then begin GenNew($85); Gen($C0); // test eax, eax GenNew($75); Gen($05); // jne +5 end; end; procedure GenerateIfProlog; begin SaveCodePos; GenNew($90); // nop ; jump to the IF block end will be inserted here GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop end; procedure GenerateElseProlog; var CodePos: Integer; begin CodePos := RestoreCodePos; GenAt(CodePos, $E9); GenDWordAt(CodePos + 1, GetCodeSize - (CodePos + 5) + 5); // jmp (IF..THEN block end) GenerateIfProlog; end; procedure GenerateIfElseEpilog; var CodePos: Integer; begin CodePos := RestoreCodePos; GenAt(CodePos, $E9); GenDWordAt(CodePos + 1, GetCodeSize - (CodePos + 5)); // jmp (IF..THEN block end) end; procedure GenerateCaseProlog; begin GenPopReg(ECX); // pop ecx ; CASE switch value GenNew($B0); Gen($00); // mov al, 00h ; initial flag mask end; procedure GenerateCaseEpilog(NumCaseStatements: Integer); var i: Integer; begin for i := 1 to NumCaseStatements do GenerateIfElseEpilog; end; procedure GenerateCaseEqualityCheck(Value: LongInt); begin GenNew($81); Gen($F9); GenDWord(Value); // cmp ecx, Value GenNew($9F); // lahf GenNew($0A); Gen($C4); // or al, ah end; procedure GenerateCaseRangeCheck(Value1, Value2: LongInt); begin GenNew($81); Gen($F9); GenDWord(Value1); // cmp ecx, Value1 GenNew($7C); Gen($0A); // jl +10 GenNew($81); Gen($F9); GenDWord(Value2); // cmp ecx, Value2 GenNew($7F); Gen($02); // jg +2 GenNew($0C); Gen($40); // or al, 40h ; set zero flag on success end; procedure GenerateCaseStatementProlog; begin GenNew($24); Gen($40); // and al, 40h ; test zero flag GenNew($75); Gen($05); // jnz +5 ; if set, jump to the case statement GenerateIfProlog; end; procedure GenerateCaseStatementEpilog; var StoredCodeSize: LongInt; begin StoredCodeSize := GetCodeSize; GenNew($90); // nop ; jump to the CASE block end will be inserted here GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop GenerateIfElseEpilog; Inc(CodePosStackTop); CodePosStack[CodePosStackTop] := StoredCodeSize; end; procedure GenerateWhileCondition; begin GenerateIfCondition; end; procedure GenerateWhileProlog; begin GenerateIfProlog; end; procedure GenerateWhileEpilog; var CodePos, CurPos, ReturnPos: Integer; begin CodePos := RestoreCodePos; GenAt(CodePos, $E9); GenDWordAt(CodePos + 1, GetCodeSize - (CodePos + 5) + 5); // jmp (WHILE..DO block end) ReturnPos := RestoreCodePos; CurPos := GetCodeSize; GenNew($E9); GenDWord(ReturnPos - (CurPos + 5)); // jmp ReturnPos end; procedure GenerateRepeatCondition; begin GenerateIfCondition; end; procedure GenerateRepeatProlog; begin SaveCodePos; end; procedure GenerateRepeatEpilog; var CurPos, ReturnPos: Integer; begin ReturnPos := RestoreCodePos; CurPos := GetCodeSize; GenNew($E9); GenDWord(ReturnPos - (CurPos + 5)); // jmp ReturnPos end; procedure GenerateForCondition; begin // Check remaining number of iterations GenNew($83); Gen($3C); Gen($24); Gen($00); // cmp dword ptr [esp], 0 GenNew($7F); Gen($05); // jg +5 end; procedure GenerateForProlog; begin Inc(ForLoopNesting); GenerateIfProlog; end; procedure GenerateForEpilog(CounterType: Integer; Down: Boolean); begin // Increment/decrement counter variable if Down then GenerateIncDec(DECPROC, TypeSize(CounterType)) else GenerateIncDec(INCPROC, TypeSize(CounterType)); // Decrement remaining number of iterations GenNew($FF); Gen($0C); Gen($24); // dec dword ptr [esp] GenerateWhileEpilog; Dec(ForLoopNesting); end; procedure GenerateGotoProlog; begin NumGotos := 0; end; procedure GenerateGoto(LabelIndex: Integer); begin Inc(NumGotos); Gotos[NumGotos].Pos := GetCodeSize; Gotos[NumGotos].LabelIndex := LabelIndex; Gotos[NumGotos].ForLoopNesting := ForLoopNesting; GenNew($90); // nop ; the remaining numbers of iterations of all nested FOR loops will be removed from stack here GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop GenerateForwardReference; end; procedure GenerateGotoEpilog; var CodePos: LongInt; i: Integer; begin for i := 1 to NumGotos do begin CodePos := Gotos[i].Pos; DiscardStackTopAt(CodePos, Gotos[i].ForLoopNesting - Ident[Gotos[i].LabelIndex].ForLoopNesting); // Remove the remaining numbers of iterations of all nested FOR loops GenerateForwardResolutionToDestination(CodePos + 6, Ident[Gotos[i].LabelIndex].Address); end; end; procedure GenerateShortCircuitProlog(op: TTokenKind); begin GenPopReg(EAX); // pop eax GenNew($85); Gen($C0); // test eax, eax case op of ANDTOK: GenNew($75); // jne ... ORTOK: GenNew($74); // je ... end; Gen($05); // ... +5 GenerateIfProlog; end; procedure GenerateShortCircuitEpilog; begin GenPopReg(EAX); // pop eax GenerateIfElseEpilog; GenPushReg(EAX); // push eax end; procedure GenerateNestedProcsProlog; begin GenerateIfProlog; end; procedure GenerateNestedProcsEpilog; begin GenerateIfElseEpilog; end; procedure GenerateFPUInit; begin GenNew($DB); Gen($E3); // fninit end; procedure GenerateStackFrameProlog(PreserveRegs: Boolean); begin GenPushReg(EBP); // push ebp GenNew($8B); Gen($EC); // mov ebp, esp SaveCodePos; GenNew($90); // nop ; actual stack storage size will be inserted here GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop GenNew($90); // nop if PreserveRegs then begin GenPushReg(ESI); // push esi GenPushReg(EDI); // push edi end; end; procedure GenerateStackFrameEpilog(TotalStackStorageSize: LongInt; PreserveRegs: Boolean); var CodePos: Integer; begin CodePos := RestoreCodePos; GenAt(CodePos, $81); GenAt(CodePos + 1, $EC); GenDWordAt(CodePos + 2, TotalStackStorageSize); // sub esp, TotalStackStorageSize if PreserveRegs then begin GenPopReg(EDI); // pop edi GenPopReg(ESI); // pop esi end; GenNew($8B); Gen($E5); // mov esp, ebp GenPopReg(EBP); // pop ebp end; procedure GenerateBreakProlog(LoopNesting: Integer); begin BreakCall[LoopNesting].NumCalls := 0; end; procedure GenerateBreakCall(LoopNesting: Integer); begin Inc(BreakCall[LoopNesting].NumCalls); BreakCall[LoopNesting].Pos[BreakCall[LoopNesting].NumCalls] := GetCodeSize; GenerateForwardReference; end; procedure GenerateBreakEpilog(LoopNesting: Integer); var i: Integer; begin for i := 1 to BreakCall[LoopNesting].NumCalls do GenerateForwardResolution(BreakCall[LoopNesting].Pos[i]); end; procedure GenerateContinueProlog(LoopNesting: Integer); begin ContinueCall[LoopNesting].NumCalls := 0; end; procedure GenerateContinueCall(LoopNesting: Integer); begin Inc(ContinueCall[LoopNesting].NumCalls); ContinueCall[LoopNesting].Pos[ContinueCall[LoopNesting].NumCalls] := GetCodeSize; GenerateForwardReference; end; procedure GenerateContinueEpilog(LoopNesting: Integer); var i: Integer; begin for i := 1 to ContinueCall[LoopNesting].NumCalls do GenerateForwardResolution(ContinueCall[LoopNesting].Pos[i]); end; procedure GenerateExitProlog; begin ExitCall.NumCalls := 0; end; procedure GenerateExitCall; begin DiscardStackTop(ForLoopNesting); // Remove the remaining numbers of iterations of all nested FOR loops Inc(ExitCall.NumCalls); ExitCall.Pos[ExitCall.NumCalls] := GetCodeSize; GenerateForwardReference; end; procedure GenerateExitEpilog; var i: Integer; begin for i := 1 to ExitCall.NumCalls do GenerateForwardResolution(ExitCall.Pos[i]); end; end.
{$I-,Q-,R-,S-} {Problema 13: Compre Uno Obtenga Uno Gratis [Jeffrey Wang, 2007] El Granjero Juan ha descubierto que el Internet está comprando fardos de heno en línea cuando él ha descubierto una oferta especial. ¡Por cada fardo de heno de tamaño A (1 <= A <= 1,000,000) que el compre, él puede obtener un fardo de heno de tamaño B (1 <= B < A) gratis! La oferta, sin embargo, tiene sus restricciones: el fardo más grande debe ser de alta calidad y el más chico debe ser de baja calidad. GJ, siempre un tipo frugal y económico, no se preocupa: cualquier calidad de heno le sirve en tanto él ahorre algún dinero. Dada una lista de los tamaños de N (1 <= N <= 10,000) fardos de alta calidad y M(1 <= M <= 10,000) fardos de baja calidad, encuentre el número máximo de fardos que el Granjero Juan puede comprar. El puede comprar fardos de alta calidad sin obtener los fardos gratis de baja calidad, pero él no puede comparar fardos de baja calidad (esto es, él debe obtenerlos gratis en la oferta). NOMBRE DEL PROBLEMA: buyfree FORMATO DE ENTRADA: * Línea 1: Dos enteros separados por espacio: N y M * Líneas 2..N+1: La línea i+1 contiene un solo entero el cual es el tamaño del i-ésimo fardo de alta calidad. * Líneas 2..N+M+1: La línea i+N+1 contiene un solo entero el cual es el tamaño del i-ésimo fardo de baja calidad. Entrada Ejemplo (archivo buyfree.in): 3 4 6 1 3 1 5 3 4 DETALLES DE LA ENTRADA: Hay 3 fardos de calidad alta, con tamaños 6, 1, y 3, y 4 fardos de baja calidad, con tamaños 1, 5, 3, y 4. FORMATO DE SALIDA: * Línea 1: El número total máximo de fardos que el Granjero Juan puede obtener. ARCHIVO EJEMPLO (archivo buyfree.out): 5 DETALLES DE LA SALIDA: Obviamente, el Granjero Juan puede comprar todos los fardos de alta calidad. Cuando él compra el fardo de alta calidad de tamaño 6, él puede obtener cualquier fardo de baja calidad gratis (por decir, el fardo de tamaño 3). Cuando él compra el fardo de alta calidad de tamaño 3, él puede obtener el fardo de tamaño 1 de baja calidad. Cuando él compra el fardo de alta calidad de tamaño 1, sin embargo, él no puede obtener gratis ningún fardo de baja calidad (desde que el tamaño debe ser estrictamente menor). El total, no importando cuan inteligente es GJ, viene a ser 5 fardos. } type max = array[1..10000] of longint; var fe,fs : text; n,m,sol : longint; tab : array[1..2] of ^max; be : array[1..64000] of byte; procedure open; var i : longint; begin assign(fe,'buyfree.in'); reset(fe); assign(fs,'buyfree.out'); rewrite(fs); settextbuf(fe,be); readln(fe,n,m); new(tab[1]); fillchar(tab[1]^,sizeof(tab[1]^),0); new(tab[2]); fillchar(tab[2]^,sizeof(tab[2]^),0); for i:=1 to n do readln(fe,tab[1]^[i]); for i:=1 to m do readln(fe,tab[2]^[i]); close(fe); end; procedure qsort(ini,fin : longint; p : byte); var i,j,k,t : longint; begin i:=ini; j:=fin; k:=tab[p]^[random(j-i+1)+i]; repeat while tab[p]^[i] < k do inc(i); while tab[p]^[j] > k do dec(j); if i<=j then begin t:=tab[p]^[i]; tab[p]^[i]:=tab[p]^[j]; tab[p]^[j]:=t; inc(i); dec(j); end; until i>j; if i < fin then qsort(i,fin,p); if j > ini then qsort(ini,j,p); end; procedure work; var i,j : longint; begin randomize; qsort(1,n,1); qsort(1,m,2); sol:=n; j:=1; for i:=1 to m do begin while (j <= n) and (tab[2]^[i] >= tab[1]^[j]) do inc(j); if j<=n then begin inc(sol); inc(j); end; end; end; procedure closer; begin writeln(fs,sol); close(fs); end; begin release(heaporg); open; work; closer; end.
namespace TestApplication; interface uses proholz.xsdparser, RemObjects.Elements.EUnit; type TestBaseClass = public class(Test) private //const testfile : String = 'test.xsd'; protected var elements : List<XsdElement> ; var schemas : List<XsdSchema>; var parser : XsdParser; method gettestParser(const testfile : String) : XsdParser; public end; implementation method TestBaseClass.gettestParser(const testfile : String): XsdParser; begin var fullname := Path.Combine('../../resources', Path.ChangeExtension(testfile,'.xsd')); if File.Exists(fullname) then begin parser := new XsdParser(fullname); schemas := parser.getResultXsdSchemas().toList(); elements := parser.getResultXsdElements().toList(); exit parser; end else Assert.Fail($'Testfile {testfile} not Found'); end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller relacionado à tabela [R02] 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 R02Controller; interface uses Classes, SysUtils, Windows, Forms, Controller, md5, VO, R02VO, R03VO, Biblioteca; type TR02Controller = class(TController) private public class function ConsultaLista(pFiltro: String): TListaR02VO; class function ConsultaObjeto(pFiltro: String): TR02VO; class procedure Insere(pObjeto: TR02VO); class function Altera(pObjeto: TR02VO): Boolean; class function Exclui(pId: Integer): Boolean; end; implementation uses T2TiORM; var ObjetoLocal: TR02VO; class function TR02Controller.ConsultaLista(pFiltro: String): TListaR02VO; begin try ObjetoLocal := TR02VO.Create; Result := TListaR02VO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TR02Controller.ConsultaObjeto(pFiltro: String): TR02VO; var Filtro: String; begin try Result := TR02VO.Create; Result := TR02VO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); if Assigned(Result) then begin //Exercício: crie o método para popular esses objetos automaticamente no T2TiORM Filtro := 'ID_R02 = ' + IntToStr(Result.Id); Result.ListaR03VO := TListaR03VO(TT2TiORM.Consultar(TR03VO.Create, Filtro, True)); end; finally end; end; class procedure TR02Controller.Insere(pObjeto: TR02VO); var I, UltimoID: Integer; begin try FormatSettings.DecimalSeparator := '.'; pObjeto.HashRegistro := '0'; pObjeto.HashRegistro := MD5Print(MD5String(pObjeto.ToJSONString)); UltimoID := TT2TiORM.Inserir(pObjeto); // Detalhes for I := 0 to pObjeto.ListaR03VO.Count - 1 do begin pObjeto.ListaR03VO[I].SerieEcf := Sessao.Configuracao.EcfImpressoraVO.Serie; pObjeto.ListaR03VO[I].IdR02 := UltimoID; pObjeto.ListaR03VO[I].HashRegistro := '0'; pObjeto.ListaR03VO[I].HashRegistro := MD5Print(MD5String(pObjeto.ListaR03VO[I].ToJSONString)); TT2TiORM.Inserir(pObjeto.ListaR03VO[I]); end; finally FormatSettings.DecimalSeparator := ','; end; end; class function TR02Controller.Altera(pObjeto: TR02VO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TR02Controller.Exclui(pId: Integer): Boolean; begin try ObjetoLocal := TR02VO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal); end; end; end.
{ Double Commander ------------------------------------------------------------------------- General icons loaded at launch based on screen resolution Copyright (C) 2009-2020 Alexander Koblov (alexx2000@mail.ru) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit dmCommonData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Dialogs; type { TdmComData } TdmComData = class(TDataModule) ilEditorImages: TImageList; ilViewerImages: TImageList; ImageList: TImageList; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; procedure DataModuleCreate(Sender: TObject); private procedure LoadImages(Images: TImageList; const ANames: array of String); public { public declarations } end; var dmComData: TdmComData; implementation uses LCLVersion, Graphics, uPixMapManager; {$R *.lfm} const ViewerNames: array[0..26] of String = ( 'view-refresh', 'go-previous', 'go-next', 'edit-copy', 'edit-cut', 'edit-delete', 'zoom-in', 'zoom-out', 'object-rotate-left', 'object-rotate-right', 'object-flip-horizontal', 'media-playback-pause', 'media-playback-start', 'media-skip-backward', 'media-skip-forward', 'image-crop', 'image-red-eye', 'draw-freehand', 'draw-rectangle', 'draw-ellipse', 'edit-undo', 'document-edit', 'view-fullscreen', 'draw-path', 'document-page-setup', 'view-restore', 'camera-photo' ); EditorNames: array[0..44] of String = ( 'document-new', 'document-open', 'document-save', 'document-save-as', 'document-properties', 'edit-cut', 'edit-copy', 'edit-paste', 'edit-undo', 'edit-redo', 'edit-find', 'edit-find-replace', 'application-exit', 'help-about', 'edit-delete', 'edit-select-all', 'go-jump', 'view-refresh', 'mr-config', 'mr-editor', 'mr-filename', 'mr-extension', 'mr-counter', 'mr-date', 'mr-time', 'mr-plugin', 'view-file', 'mr-pathtools', 'mr-rename', 'mr-clearfield', 'mr-presets', 'mr-savepreset', 'mr-deletepreset', 'mr-droppresets', 'document-save-alt', 'document-save-as-alt', 'go-next', 'go-bottom', 'go-down', 'go-up', 'go-top', 'process-stop', 'copy-right-to-left', 'copy-left-to-right', 'choose-encoding' ); { TdmComData } procedure TdmComData.DataModuleCreate(Sender: TObject); begin if Assigned(PixMapManager) then begin LoadImages(ilViewerImages, ViewerNames); LoadImages(ilEditorImages, EditorNames); end; end; procedure TdmComData.LoadImages(Images: TImageList; const ANames: array of String); var AName: String; ASize16, ASize24, ASize32: Integer; ABitmap16, ABitmap24, ABitmap32: TBitmap; begin Images.Clear; ASize16:= 16; // AdjustIconSize(16, 96); ASize24:= 24; // AdjustIconSize(24, 96); ASize32:= 32; // AdjustIconSize(32, 96); Images.RegisterResolutions([ASize16, ASize24, ASize32]); for AName in ANames do begin ABitmap16:= PixMapManager.GetThemeIcon(AName, ASize16); if (ABitmap16 = nil) then ABitmap16:= TBitmap.Create; ABitmap24:= PixMapManager.GetThemeIcon(AName, ASize24); if (ABitmap24 = nil) then ABitmap24:= TBitmap.Create; ABitmap32:= PixMapManager.GetThemeIcon(AName, ASize32); if (ABitmap32 = nil) then ABitmap32:= TBitmap.Create; Images.AddMultipleResolutions([ABitmap16, ABitmap24, ABitmap32]); ABitmap16.Free; ABitmap24.Free; ABitmap32.Free; end; end; end.
unit n_WebArmProcedures; // процедуры для WebArm interface uses Windows, Classes, SysUtils, Math, Forms, DateUtils, Contnrs, IBDatabase, IBSQL, n_free_functions, v_constants, v_DataTrans, v_Server_Common, n_LogThreads, n_DataCacheInMemory, n_constants, n_DataSetsManager, n_server_common, n_DataCacheAddition, n_TD_functions, n_xml_functions, n_DataCacheObjects; // работа с клиентами procedure prWebArmGetRegionalFirms(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список контрагентов регионала procedure prWebArmGetFirmUsers(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список юзеров контрагента procedure prWebArmResetUserPassword(Stream: TBoBMemoryStream; ThreadData: TThreadData); // сброс пароля procedure prWebArmSetFirmMainUser(Stream: TBoBMemoryStream; ThreadData: TThreadData); // назначить главного пользователя procedure prUnblockWebUser(Stream: TBoBMemoryStream; ThreadData: TThreadData); // разблокировка клиента // работа со счетами procedure prWebArmGetFirmInfo(Stream: TBoBMemoryStream; ThreadData: TThreadData); // передать реквизиты к/а //procedure prWebArmGetFirmAccountList(Stream: TBoBMemoryStream; ThreadData: TThreadData); // передать список незакрытых счетов к/а procedure prWebArmShowAccount(Stream: TBoBMemoryStream; ThreadData: TThreadData); // показать счет (если нет - создать новый) procedure prWebArmShowFirmWareRests(Stream: TBoBMemoryStream; ThreadData: TThreadData); // показать остатки по товару и складам фирмы procedure prWebArmEditAccountHeader(Stream: TBoBMemoryStream; ThreadData: TThreadData); // редактирование заголовка счета procedure prWebArmEditAccountLine(Stream: TBoBMemoryStream; ThreadData: TThreadData); // добавление/редактирование/удаление строки счета function fnGetStrSummByDoubleCurr(sum: Double; MainCurr: Integer): String; // строка с суммой в 2-х валютах procedure prWebArmGetFilteredAccountList(Stream: TBoBMemoryStream; ThreadData: TThreadData); // передать список счетов с учетом фильтра procedure prWebArmMakeSecondAccount(Stream: TBoBMemoryStream; ThreadData: TThreadData); // формирование счета на недостающие procedure prWebArmMakeInvoiceFromAccount(Stream: TBoBMemoryStream; ThreadData: TThreadData); // формирование накладной из счета procedure prWebArmGetTransInvoicesList(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список накладных передачи (счета WebArm) procedure prWebArmGetTransInvoice(Stream: TBoBMemoryStream; ThreadData: TThreadData); // просмотр накладной передачи (счета WebArm) procedure prWebArmAddWaresFromAccToTransInv(Stream: TBoBMemoryStream; ThreadData: TThreadData); // добавление товаров из счета в накладную передачи (счета WebArm) // работа с заявками на регистрацию procedure prWebArmGetOrdersToRegister(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список заявок procedure prWebArmAnnulateOrderToRegister(Stream: TBoBMemoryStream; ThreadData: TThreadData); // аннулировать заявку procedure prWebArmRegisterOrderToRegister(Stream: TBoBMemoryStream; ThreadData: TThreadData); // принять заявку // статистика по заказам и счетам //procedure prGetWebArmSystemStatistic(Stream: TBoBMemoryStream; ThreadData: TThreadData); // работа с регионами procedure prWebArmGetRegionalZones(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список регионов procedure prWebArmInsertRegionalZone(Stream: TBoBMemoryStream; ThreadData: TThreadData); // добавление региона procedure prWebArmDeleteRegionalZone(Stream: TBoBMemoryStream; ThreadData: TThreadData); // удаление региона procedure prWebArmUpdateRegionalZone(Stream: TBoBMemoryStream; ThreadData: TThreadData); // изменение региона //****************************************************************************** // Бренды procedure prGetBrandsTD(Stream: TBoBMemoryStream; ThreadData: TThreadData); // (Web) Список брендов TecDoc // Производители procedure prGetManufacturerList(Stream: TBoBMemoryStream; ThreadData: TThreadData); // (+ Web) Список производителей procedure prManufacturerAdd(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Добавить производителя procedure prManufacturerDel(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Удалить производителя procedure prManufacturerEdit(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Изменить производителя // Модельный ряд procedure prGetModelLineList(Stream: TBoBMemoryStream; ThreadData: TThreadData); // (+ Web) Список модельных рядов производителя procedure prModelLineAdd(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Добавить модельный ряд procedure prModelLineDel(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Удалить модельный ряд procedure prModelLineEdit(Stream: TBoBMemoryStream; ThreadData: TThreadData); // изменить модельный ряд // Модель procedure prGetModelLineModels(Stream: TBoBMemoryStream; ThreadData: TThreadData); // (+ Web) Список моделей модельного ряда procedure prGetModelTree(Stream: TBoBMemoryStream; ThreadData: TThreadData); // (+ Web) Дерево узлов модели procedure prModelAddToModelLine(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Добавить модель в модельный ряд procedure prModelDel(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Удалить модель procedure prModelEdit(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Изменить модель procedure prModelSetVisible(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Изменить видимость модели // Товары, атрибуты procedure prGetListAttrGroupNames(Stream: TBoBMemoryStream; ThreadData: TThreadData); // (+ Web) Список групп атрибутов системы procedure prGetListGroupAttrs(Stream: TBoBMemoryStream; ThreadData: TThreadData); // (+ Web) Список атрибутов группы procedure prGetWareInfoView(Stream: TBoBMemoryStream; ThreadData: TThreadData); // параметры товара для просмотра procedure prGetCompareWaresInfo(Stream: TBoBMemoryStream; ThreadData: TThreadData); // параметры товаров для сравнения procedure prGetWareSatellites(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список сопутствующих товаров (Web & WebArm) procedure prGetWareAnalogs(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список аналогов (Web & WebArm) procedure prCommonWareSearch(Stream: TBoBMemoryStream; ThreadData: TThreadData); // поиск товаров (Web & WebArm) procedure prCommonGetRestsOfWares(Stream: TBoBMemoryStream; ThreadData: TThreadData); // вывод семафоров наличия товаров (Web & WebArm) procedure prCommonGetNodeWares(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список товаров по узлу (Web & WebArm) procedure prCommonSearchWaresByAttr(Stream: TBoBMemoryStream; ThreadData: TThreadData); // поиск товаров по значениям атрибутов (Web & WebArm) procedure prCommonGetWaresByOE(Stream: TBoBMemoryStream; ThreadData: TThreadData); // поиск товаров по оригин.номеру (Web & WebArm) procedure prWebArmGetWaresDescrView(Stream: TBoBMemoryStream; ThreadData: TThreadData); // описания товаров для просмотра (счета WebArm) procedure prWebarmGetDeliveries(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список доставок как результат поиска (WebArm) procedure prGetWareTypesTree(Stream: TBoBMemoryStream; ThreadData: TThreadData); // дерево типов товаров (сортировка по наименованию) // Дерево узлов procedure prTNAGet(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Дерево узлов procedure prTNANodeAdd(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Добавить узел в дерево procedure prTNANodeDel(Stream: TBoBMemoryStream; ThreadData: TThreadData); // Удалить узел из дерева procedure prTNANodeEdit(Stream: TBoBMemoryStream; ThreadData: TThreadData); // редактировать узел в дереве // Двигатель procedure prGetEngineTree(Stream: TBoBMemoryStream; ThreadData: TThreadData); // (+ Web) Дерево узлов двигателя //****************************************************************************** // импорт из TDT, отчеты //procedure prTestFileExt(pFileExt: string; RepKind: integer); // проверяем расширение файла procedure prFormRepFileName(pFilePath: string; var fname: string; RepKind: integer; flSet: Boolean=False); // формируем имя файла отчета procedure prFormRepMailParams(var Subj, ContentType: string; // параметры письма с отчетом var BodyMail: TStringList; RepKind: integer; flSet: Boolean=False); procedure prGetAutoDataFromTDT(ReportKind, UserID: integer; // поиск новых данных авто в TDT var BodyMail: TStringList; var pFileName, Subj, ContentType: string; ThreadData: TThreadData=nil; filter_data: String=''); procedure prSetAutoDataFromTDT(ReportKind, UserID: integer; // загрузка / изменение данных авто из TDT var BodyMail: TStringList; var pFileName, Subj, ContentType: string; ThreadData: TThreadData=nil); procedure prGetFirmClones(pUserID: Integer; pFileName: String; ThreadData: TThreadData=nil); // 53-stamp - переброска к/а Гроссби // разное procedure prSaveStrListWithIDToStream(const pLst: TStringList; Stream: TBoBMemoryStream); // Запись TStringList с ID в Objects в поток procedure prWebArmGetNotificationsParams(Stream: TBoBMemoryStream; ThreadData: TThreadData); // список уведомлений (WebArm) implementation //****************************************************************************** uses n_IBCntsPool, v_Functions, t_ImportChecking;// импорт из TDT (*//=================================================== проверяем расширение файла procedure prTestFileExt(pFileExt: string; RepKind: integer); var rightExt: String; flWrongExt: Boolean; begin case RepKind of 13, 14, 36, 53: begin rightExt:= '.csv'; flWrongExt:= pFileExt<>rightExt; end; 15: begin rightExt:= '.xls'; flWrongExt:= pFileExt<>rightExt; end; 25, 34, 39: begin rightExt:= '.xls или .xlsx'; flWrongExt:= not ((pFileExt='.xls') or (pFileExt='.xlsx')); end; 24: // администрирование баз case GetIniParamInt(nmIniFileBOB, 'reports', 'get24', 0) of 1: begin // загрузка альтернативных значений инфо-текстов TecDoc из файла Excel rightExt:= '.xls или .xlsx'; flWrongExt:= not ((pFileExt='.xls') or (pFileExt='.xlsx')); end; { 2: begin // поиск новых узлов авто из TDT rightExt:= '.xls или .xlsx'; flWrongExt:= not ((pFileExt='.xls') or (pFileExt='.xlsx')); end; } else begin // def - пакетная загрузка связок, критериев, текстов, файлов и ОН товаров из TDT rightExt:= '.xls'; flWrongExt:= pFileExt<>rightExt; end; end; else begin rightExt:= ''; flWrongExt:= True; end; end; if flWrongExt then raise EBOBError.Create('Неверный формат файла - '+pFileExt+', нужен '+rightExt); end; *) //=================================================== формируем имя файла отчета procedure prFormRepFileName(pFilePath: string; var fname: string; RepKind: integer; flSet: Boolean=False); var pFileExt{, MidName}: String; begin if flSet then begin // импорт из файла в базу fname:= pFilePath+fnFormRepFileName(IntToStr(RepKind), fname, constOpImport); end else begin // отчет о необходимых изменениях pFileExt:= ''; case RepKind of 13, 14, 36, 53: pFileExt:= '.csv'; 15, 25, 34, 39, 40: pFileExt:= '.xml'; 24: // администрирование баз // case GetIniParamInt(nmIniFileBOB, 'reports', 'get24', 0) of // def - пакетная загрузка связок, критериев, текстов, файлов и ОН товаров из TDT // else pFileExt:= '.txt'; // end; end; fname:= pFilePath+fnFormRepFileName(IntToStr(RepKind), pFileExt, constOpExport); end; if FileExists(fname) and not SysUtils.DeleteFile(fname) then raise EBOBError.Create(MessText(mtkNotDelPrevFile)); end; //=================================================== параметры письма с отчетом procedure prFormRepMailParams(var Subj, ContentType: string; var BodyMail: TStringList; RepKind: integer; flSet: Boolean=False); //-------------------------------- function GetRepNameTD(s: string): string; begin if flSet then Result:= 'Отчет о загрузке '+s+' легк.авто из TecDoc' else Result:= 'Отчет о проверке '+s+' легк.авто по TecDoc'; end; //-------------------------------- begin case RepKind of 13 : Subj:= GetRepNameTD('производителей'); 14 : Subj:= GetRepNameTD('модельных рядов'); 15 : Subj:= GetRepNameTD('моделей'); 25 : Subj:= GetRepNameTD('произв.+м.р.+мод.'); 34 : Subj:= GetRepNameTD('узлов'); 36 : Subj:= 'Отчет об артикулах TecDoc для инфо-групп Гроссби'; 39 : Subj:= 'Замены инфо-текстов TecDoc'; 40: Subj:= 'Отчет о проверке привязок товаров к артикулам TecDoc'; 53 : Subj:= 'Отчет о клонировании к/а'; 24: // администрирование баз if flSet then begin // case GetIniParamInt(nmIniFileBOB, 'reports', 'set24', 0) of // else Subj:= 'Отчет об удалении моделей'; // end; end else begin // case GetIniParamInt(nmIniFileBOB, 'reports', 'get24', 0) of // else Subj:= 'Отчет о пакетной загрузке'; // end; end; end; if not Assigned(BodyMail) then BodyMail:= TStringList.Create; BodyMail.Add(Subj+' от '+FormatDateTime(cDateTimeFormatY2S, Now())); end; //======================================== отчет - поиск новых данных авто в TDT procedure prGetAutoDataFromTDT(ReportKind, UserID: integer; var BodyMail: TStringList; var pFileName, Subj, ContentType: string; ThreadData: TThreadData=nil; filter_data: String=''); const nmProc = 'prGetAutoDataFromTDT'; // имя процедуры/функции var pFilePath, errmess: String; lst: TStringList; begin lst:= nil; pFilePath:= ''; errmess:= ''; if not GetEmplTmpFilePath(UserID, pFilePath, errmess) then raise EBOBError.Create(errmess); // if CheckNotValidModelManage(UserID, constIsAuto, errmess) then raise EBOBError.Create(errmess); try prFormRepFileName(pFilePath, pFileName, ReportKind, False); // формируем имя файла отчета case ReportKind of (* 13: begin // 13-stamp - поиск новых производителей авто из TDT lst:= fnGetNewAutoManufFromTDT(UserID, ThreadData); SaveListToFile(lst, pFileName); // csv ContentType:= CSVFileContentType; end; 14: begin // 14-stamp - поиск новых мод.рядов авто из TDT lst:= fnGetNewAutoModelLineFromTDT(UserID, ThreadData); SaveListToFile(lst, pFileName); // csv ContentType:= CSVFileContentType; end; 15: begin // 15-stamp - поиск новых моделей авто из TDT lst:= fnGetNewAutoModelFromTDT(UserID, ThreadData); SaveListToFile(lst, pFileName); // xml ContentType:= XMLContentType; end; *) 25: begin // 25-stamp - поиск новых производителей, м.р., моделей авто из TDT lst:= fnGetNewAutoMfMlModFromTDT(UserID, ThreadData); SaveListToFile(lst, pFileName); // xml ContentType:= XMLContentType; end; 34: begin // 34-stamp - поиск новых узлов авто из TDT lst:= fnGetNewTreeNodesFromTDT(UserID, ThreadData); SaveListToFile(lst, pFileName); // xml ContentType:= XMLContentType; end; 36: begin // 36-stamp - поиск артикулов TDT для инфо-групп Гроссби prGetArticlesINFOgrFromTDT(UserID, pFileName, ThreadData); ContentType:= CSVFileContentType; end; 39: begin // 39-stamp - Отчет по инфо-текстам TecDoc lst:= fnGetInfoTextsForTranslate(UserID, ThreadData); SaveListToFile(lst, pFileName); // xml ContentType:= XMLContentType; end; 40: begin // 40-stamp - Отчет о проверке привязок товаров к артикулам lst:= fnGetCheckWareTDTArticles(UserID, ThreadData); SaveListToFile(lst, pFileName); // xml ContentType:= XMLContentType; end; 53: begin // 53-stamp - переброска к/а Гроссби prGetFirmClones(UserID, pFileName, ThreadData); ContentType:= CSVFileContentType; end; 24: begin // // 24-stamp - пакетная загрузка связок, критериев, текстов, файлов и ОН товаров из TDT case GetIniParamInt(nmIniFileBOB, 'reports', 'get24', 0) of 3: begin // простановка контрактов в db_ORD lst:= SetClientContractsToORD(UserID, ThreadData); SaveListToFile(lst, pFileName); // txt ContentType:= FileContentType; // raise EBOBError.Create('отчет '+IntToStr(ReportKind)+'(3) недоступен'); end; else begin // def 24-stamp - пакетная загрузка связок, критериев, текстов, файлов и ОН товаров из TDT if (Cache.LongProcessFlag=cdlpLoadData) then raise EBOBError.Create('Загрузка уже запущена'); if not SetLongProcessFlag(cdlpLoadData) then raise EBOBError.Create('Не могу запустить загрузку - идет процесс: '+cdlpNames[Cache.LongProcessFlag]); try lst:= AddLoadWaresInfoFromTDT(UserID, ThreadData, filter_data); SaveListToFile(lst, pFileName); // txt ContentType:= FileContentType; finally SetNotLongProcessFlag(cdlpLoadData); end; end; end; end; else raise EBOBError.Create('Неизвестный вид отчета - '+IntToStr(ReportKind)); end; prFormRepMailParams(Subj, ContentType, BodyMail, ReportKind); // параметры письма с отчетом finally prFree(lst); end; end; //====================================== загрузка / изменение данных авто из TDT procedure prSetAutoDataFromTDT(ReportKind, UserID: integer; var BodyMail: TStringList; var pFileName, Subj, ContentType: string; ThreadData: TThreadData=nil); const nmProc = 'prSetAutoDataFromTDT'; // имя процедуры/функции var errmess, pFilePath, pFileName1: String; lst: TStringList; begin lst:= nil; pFilePath:= ''; if not FileExists(pFileName) then raise EBOBError.Create('Не найден файл загрузки.'); if not GetEmplTmpFilePath(UserID, pFilePath, errmess) then raise EBOBError.Create(errmess); // if CheckNotValidModelManage(UserID, constIsAuto, errmess) then raise EBOBError.Create(errmess); try case ReportKind of (* 13: begin // 13-imp - загрузка / изменение производителей авто из TDT prTestFileExt(ExtractFileExt(pFileName), ReportKind); // проверяем расширение файла lst:= fnSetNewAutoManufFromTDT(UserID, pFileName, ThreadData); // отчет для выгрузки в файл CSV prFormRepFileName(pFilePath, pFileName, ReportKind, True); // формируем имя файла отчета fnStringsLogToFile(lst, pFileName); ContentType:= CSVFileContentType; prFormRepMailParams(Subj, ContentType, BodyMail, ReportKind, True); // параметры письма с отчетом end; 14: begin // 14-imp - загрузка / изменение мод.рядов авто из TDT prTestFileExt(ExtractFileExt(pFileName), ReportKind); // проверяем расширение файла lst:= fnSetNewAutoModelLineFromTDT(UserID, pFileName, ThreadData); // отчет для выгрузки в файл CSV prFormRepFileName(pFilePath, pFileName, ReportKind, True); // формируем имя файла отчета fnStringsLogToFile(lst, pFileName); ContentType:= CSVFileContentType; prFormRepMailParams(Subj, ContentType, BodyMail, ReportKind, True); // параметры письма с отчетом end; 15: begin // 15-imp - загрузка / изменение моделей авто из TDT pFileName1:= pFileName; // запоминаем имя исходного файла prFormRepFileName(pFilePath, pFileName, ReportKind, True); // формируем имя файла отчета CopyFile(PChar(pFileName1), PChar(pFileName), False); // копируем исходный файл в отчет if FileExists(pFileName) then DeleteFile(pFileName1); prSetNewAutoModelFromTDT(UserID, pFileName, ThreadData); // обрабатываем файл и в него же пишем отчет ContentType:= FileContentType; // ??? prFormRepMailParams(Subj, ContentType, BodyMail, ReportKind, True); // параметры письма с отчетом end; *) 25: begin // 25-imp - загрузка новых производителей, м.р., моделей авто из TDT pFileName1:= pFileName; // запоминаем имя исходного файла prFormRepFileName(pFilePath, pFileName, ReportKind, True); // формируем имя файла отчета CopyFile(PChar(pFileName1), PChar(pFileName), False); // копируем исходный файл в отчет if FileExists(pFileName) then DeleteFile(pFileName1); prSetNewAutoMfMlModFromTDT(UserID, pFileName, ThreadData); // обрабатываем файл и в него же пишем отчет ContentType:= FileContentType; // ??? prFormRepMailParams(Subj, ContentType, BodyMail, ReportKind, True); // параметры письма с отчетом end; 34: begin // 34-imp - загрузка / корректировка узлов авто из Excel pFileName1:= pFileName; // запоминаем имя исходного файла prFormRepFileName(pFilePath, pFileName, ReportKind, True); // формируем имя файла отчета CopyFile(PChar(pFileName1), PChar(pFileName), False); // копируем исходный файл в отчет if FileExists(pFileName) then DeleteFile(pFileName1); prSetNewTreeNodesFromTDT(UserID, pFileName, ThreadData); // обрабатываем файл и в него же пишем отчет ContentType:= FileContentType; // ??? prFormRepMailParams(Subj, ContentType, BodyMail, ReportKind, True); // параметры письма с отчетом end; 39: begin // 39-imp - загрузка альтернативных значений инфо-текстов TecDoc из файла Excel pFileName1:= pFileName; // запоминаем имя исходного файла prFormRepFileName(pFilePath, pFileName, ReportKind, True); // формируем имя файла отчета CopyFile(PChar(pFileName1), PChar(pFileName), False); // копируем исходный файл в отчет if FileExists(pFileName) then DeleteFile(pFileName1); prSetAlternativeInfoTexts(UserID, pFileName, ThreadData); // обрабатываем файл и в него же пишем отчет ContentType:= FileContentType; // ??? prFormRepMailParams(Subj, ContentType, BodyMail, ReportKind, True); // параметры письма с отчетом end; 24: begin // 24-imp - удаление моделей и их связок из ORD // case GetIniParamInt(nmIniFileBOB, 'reports', 'set24', 0) of // else begin // pFileName1:= pFileName; // запоминаем имя исходного файла prFormRepFileName(pFilePath, pFileName, ReportKind, True); // формируем имя файла отчета CopyFile(PChar(pFileName1), PChar(pFileName), False); // копируем исходный файл в отчет if FileExists(pFileName) then DeleteFile(pFileName1); prDeleteAutoModels(UserID, pFileName, ThreadData); // обрабатываем файл и в него же пишем отчет ContentType:= FileContentType; // ??? prFormRepMailParams(Subj, ContentType, BodyMail, ReportKind, True); // параметры письма с отчетом // end; // end; end; 36, 40, 53: // 36-imp, 40-imp, 53-imp - нет raise EBOBError.Create('Импорт ('+IntToStr(ReportKind)+') не предусмотрен'); else raise EBOBError.Create('Неизвестный вид импорта - '+IntToStr(ReportKind)); end; finally prFree(lst); end; end; //****************************************************************************** //================================================ список контрагентов регионала procedure prWebArmGetRegionalFirms(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetRegionalFirms'; // имя процедуры/функции var EmplId, FirmID, i, j: integer; Codes: Tai; Template, errmess: string; empl: TEmplInfoItem; flManageSprav: Boolean; begin Stream.Position:= 0; SetLength(Codes, 0); EmplId:= Stream.ReadInt; // код регионала (0-все) Template:= trim(Stream.ReadStr); // фильтр наименования контрагента prSetThLogParams(ThreadData, 0, EmplId, 0, 'Template='+Template); // логирование try if CheckNotValidUser(EmplId, isWe, errmess) then raise EBOBError.Create(errmess); empl:= Cache.arEmplInfo[EmplId]; // проверяем право пользователя flManageSprav:= empl.UserRoleExists(rolManageSprav); if not (flManageSprav or empl.UserRoleExists(rolRegional) or empl.UserRoleExists(rolUiK)) then // vc raise EBOBError.Create(MessText(mtkNotRightExists)); j:= fnIfint(flManageSprav or empl.UserRoleExists(rolUiK), 0, EmplID); // vc Codes:= Cache.GetRegFirmCodes(j, Template); // список кодов неархивных контрагентов j:= length(Codes); if (j<1) then raise EBOBError.Create(MessText(mtkNotFoundData)); Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteInt(j); for i:= 0 to j-1 do begin FirmID:= Codes[i]; Stream.WriteInt(FirmID); with Cache.arFirmInfo[FirmID] do begin Stream.WriteStr(UPPERSHORTNAME); Stream.WriteStr(Name); Stream.WriteStr(NUMPREFIX); end; end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; SetLength(Codes, 0); Stream.Position:= 0; end; //==================================================== список юзеров контрагента procedure prWebArmGetFirmUsers(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetFirmUsers'; // имя процедуры/функции var EmplId, FirmID, i, j, ii: integer; Users: Tai; flManageSprav: Boolean; firm: TFirmInfo; empl: TEmplInfoItem; begin Stream.Position:= 0; try EmplId:= Stream.ReadInt; FirmId:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, EmplId, 0, 'FirmID='+IntToStr(FirmID)); // логирование if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); Cache.TestFirms(FirmID, True, False, True); // проверяем частично фирму if not Cache.FirmExist(FirmId) then raise EBOBError.Create(MessText(mtkNotFirmExists)); firm:= Cache.arFirmInfo[FirmId]; empl:= Cache.arEmplInfo[EmplId]; flManageSprav:= empl.UserRoleExists(rolManageSprav); if not (flManageSprav or empl.UserRoleExists(rolUiK) or // vc (empl.UserRoleExists(rolRegional) and firm.CheckFirmManager(emplID))) then raise EBOBError.Create(MessText(mtkNotRightExists)); Cache.TestClients(firm.SUPERVISOR, True, False, True); // проверяем частично должн.лиц контрагента SetLength(Users, Length(firm.FirmClients)); // получаем список должн.лиц контрагента ii:= 0; // счетчик должн.лиц for i:= Low(firm.FirmClients) to High(firm.FirmClients) do begin j:= firm.FirmClients[i]; if not Cache.ClientExist(j) then Continue; Users[ii]:= j; inc(ii); end; if ii<1 then raise EBOBError.Create('Сотрудники контрагента не найдены.'); Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteInt(ii); // кол-во должн.лиц for i:= 0 to ii-1 do begin j:= Users[i]; Stream.WriteInt(j); // код // Stream.WriteBool(firm.SUPERVISOR=j); // признак Главного пользователя // vc with Cache.arClientInfo[j] do begin Stream.WriteStr(Name); // ФИО Stream.WriteStr(Post); // должность Stream.WriteStr(Phone); // телефоны Stream.WriteStr(Mail); // vc Stream.WriteStr(Login); // логин // Stream.WriteBool(Blocked); // признак блокированности // vc Stream.WriteByte(byte(Blocked)+2*fnIfInt(flManageSprav, 1, 0)+fnIfInt((firm.SUPERVISOR=j), 4, 0)); // признак блокированности + признак суперпупера // vc end; end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; SetLength(Users, 0); Stream.Position:= 0; end; //================================================================= сброс пароля procedure prWebArmResetUserPassword(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmResetUserPassword'; // имя процедуры/функции var OrdIBD: TIBDatabase; OrdIBS: TIBSQL; EmplId, UserId, FirmID: integer; newpass, UserCode, errmess: string; Client: TClientInfo; empl: TEmplInfoItem; begin OrdIBS:= nil; OrdIBD:= nil; Stream.Position:= 0; try EmplId:= Stream.ReadInt; FirmId:= Stream.ReadInt; UserCode:= Stream.ReadStr; UserId:= StrToIntDef(UserCode, 0); prSetThLogParams(ThreadData, 0, EmplId, 0, 'FirmID='+IntToStr(FirmID)+#13#10'UserId='+UserCode); // логирование if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); Client:= Cache.arClientInfo[UserId]; if (Client.Login='') then raise EBOBError.Create(MessText(mtkNotClientExist)); empl:= Cache.arEmplInfo[EmplId]; // проверяем право пользователя if not (empl.UserRoleExists(rolRegional) and Cache.arFirmInfo[FirmId].CheckFirmManager(emplID)) then raise EBOBError.Create(MessText(mtkNotRightExists)); OrdIBD:= cntsORD.GetFreeCnt; OrdIBS:= fnCreateNewIBSQL(OrdIBD, 'OrdIBS_'+nmProc, ThreadData.ID, tpWrite, true); OrdIBS.SQL.Text:= 'select rPassword, rErrText from SetUserPassword('+UserCode+', :p, 1, 0)'; OrdIBS.ParamByName('p').AsString:= ''; OrdIBS.ExecQuery; if (OrdIBS.Bof and OrdIBS.Eof) then raise Exception.Create(MessText(mtkNotValidParam)); if OrdIBS.FieldByName('rErrText').AsString<>'' then raise EBOBError.Create(OrdIBS.FieldByName('rErrText').AsString); newpass:= OrdIBS.FieldByName('rPassword').AsString; OrdIBS.Transaction.Commit; OrdIBS.Close; Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteStr(newpass); Client.Password:= newpass; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; prFreeIBSQL(OrdIBS); cntsORD.SetFreeCnt(OrdIBD); Stream.Position:= 0; end; //============================================== назначить главного пользователя procedure prWebArmSetFirmMainUser(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmSetFirmMainUser'; // имя процедуры/функции var IBS: TIBSQL; IBD: TIBDatabase; EmplId, UserId, FirmID: integer; newpass, UserCode, UserLogin, errmess: string; flNewUser: boolean; Client: TClientInfo; firma: TFirmInfo; Strings: TStringList; begin newpass:= ''; Stream.Position:= 0; IBS:= nil; IBD:= nil; try EmplId:= Stream.ReadInt; FirmId:= Stream.ReadInt; UserCode:= Stream.ReadStr; UserLogin:= Stream.ReadStr; UserId:= StrToIntDef(UserCode, 0); prSetThLogParams(ThreadData, 0, EmplId, 0, 'FirmID='+IntToStr(FirmID)+ #13#10'UserId='+UserCode+#13#10'UserLogin='+UserLogin); // логирование if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); Client:= Cache.arClientInfo[UserId]; if (Client.Mail='') then raise EBOBError.Create('Нельзя делать главным пользователя без email'); // vc flNewUser:= (Client.Login=''); if flNewUser then begin if (Client.Post='') then raise EBOBError.Create(MessText(mtkNotClientExist)); if (UserLogin='') then raise EBOBError.Create(MessText(mtkNotSetLogin)); end; firma:= Cache.arFirmInfo[FirmId]; if not ((Cache.arEmplInfo[EmplId].UserRoleExists(rolRegional) // проверяем право пользователя // vc and firma.CheckFirmManager(emplID)) or Cache.arEmplInfo[EmplId].UserRoleExists(rolUiK)) then // vc raise EBOBError.Create(MessText(mtkNotRightExists)); if flNewUser and not fnCheckOrderWebLogin(UserLogin) then raise EBOBError.Create(MessText(mtkNotValidLogin)); if flNewUser and not fnNotLockingLogin(UserLogin) then // проверяем, не относится ли логин к запрещенным raise EBOBError.Create(MessText(mtkLockingLogin, UserLogin)); // уникальность логина в базе проверяется при добавлении пользователя if flNewUser or (firma.SUPERVISOR<>UserId) then try IBD:= cntsORD.GetFreeCnt; IBS:= fnCreateNewIBSQL(IBD, 'IBS_'+nmProc, ThreadData.ID, tpWrite, true); IBS.SQL.Text:= 'select rPassw,rErrText from SetFirmMainUser('+ UserCode+', '+IntToStr(FirmID)+', :login, '+IntToStr(EmplId)+', 0)'; // vc IBS.ParamByName('login').AsString:= UserLogin; IBS.ExecQuery; if (IBS.Bof and IBS.Eof) then raise Exception.Create(MessText(mtkNotValidParam)); if IBS.FieldByName('rErrText').AsString<>'' then raise EBOBError.Create(IBS.FieldByName('rErrText').AsString); if flNewUser then begin // если новый пользователь if (IBS.FieldByName('rPassw').AsString='') then raise EBOBError.Create(MessText(mtkErrFormTmpPass)); newpass:= IBS.FieldByName('rPassw').AsString; Client.Login:= UserLogin; Client.Password:= newpass; end; IBS.Transaction.Commit; IBS.Close; firma.SUPERVISOR:= UserId; finally prFreeIBSQL(IBS); cntsORD.SetFreeCnt(IBD); end; if flNewUser then try // если новый клиент - пишем логин в Grossbee IBD:= cntsGRB.GetFreeCnt; IBS:= fnCreateNewIBSQL(IBD, 'IBS_'+nmProc, ThreadData.ID, tpWrite, true); IBS.SQL.Text:= 'UPDATE PERSONS SET PRSNLOGIN=:login WHERE PRSNCODE='+UserCode; IBS.ParamByName('login').AsString:= UserLogin; IBS.ExecQuery; if IBS.Transaction.InTransaction then IBS.Transaction.Commit; IBS.Close; // vc +++ Strings:=TStringList.Create; Strings.Add('Здравствуйте'); Strings.Add('Для Вас, как клиента Компании "Владислав", создана учетная запись на сайте http://order.vladislav.ua.'); Strings.Add('Логин: '+Client.Login); Strings.Add('Пароль: '+Client.Password); Strings.Add(''); errmess:= n_SysMailSend(Client.Mail, 'Для Вас создана учетная запись на сайте order.vladislav.ua', Strings, nil, '', '', true); prSaveCommonError(Stream, ThreadData, nmProc, errmess, '', True); if errmess<>'' then raise EBOBError.Create('Учетная запись создана успешно, но при отправке письма клиенту произошла ошибка.' +' Сообщите клиенту его логин и предложите получить пароль для входа через систему восстановления пароля'); // vc --- finally prFreeIBSQL(IBS); cntsGRB.SetFreeCnt(IBD); end; Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteStr(newpass); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; prFree(Strings); // vc end; //****************************************************************************** // работа с заявками на регистрацию //****************************************************************************** //================================================================ список заявок procedure prWebArmGetOrdersToRegister(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetOrdersToRegister'; // имя процедуры/функции var IBS: TIBSQL; IBD: TIBDatabase; s, s1: string; i, Count, EmplId, sPos: integer; DateStart, DateFinish: TDateTime; flDirector: boolean; empl: TEmplInfoItem; begin Stream.Position:= 0; IBS:= nil; IBD:= nil; empl:= nil; DateStart:= 0; DateFinish:= 0; i:= 0; flDirector:= False; try EmplId:= Stream.ReadInt; try if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); empl:= Cache.arEmplInfo[EmplId]; flDirector:= empl.UserRoleExists(rolSaleDirector); if not (flDirector or empl.UserRoleExists(rolUiK) or empl.UserRoleExists(rolRegional) // vc or empl.UserRoleExists(rolSuperRegional)) then raise EBOBError.Create(MessText(mtkNotRightExists)); s:= ''; // если не указ.фильтр - все if boolean(Stream.ReadByte) then s:= 'OREGSTATE=0'; if boolean(Stream.ReadByte) then s:= s+fnIfStr(s='','',' or ')+'OREGSTATE=1'; if boolean(Stream.ReadByte) then s:= s+fnIfStr(s='','',' or ')+'OREGSTATE=2'; if s<>'' then s:= '('+s+')'; DateStart:= Stream.ReadDouble; DateFinish:= Stream.ReadDouble; s1:= Stream.ReadStr; i:= Stream.ReadInt; // dprtcode finally prSetThLogParams(ThreadData, 0, EmplId, 0, 'DateStart='+ fnIfStr(DateStart>0, FormatDateTime(cDateFormatY2, DateStart), '')+ #13#10'DateFinish='+fnIfStr(DateFinish>0, FormatDateTime(cDateFormatY2, DateFinish), '')+ #13#10'OREGFIRMNAME LIKE='+s1+#13#10'OREGDPRTCODE='+IntToStr(i)+#13#10+s); // логирование end; if (DateStart>0) then s:= s+fnIfStr(s='', '', ' and ')+'OREGCREATETIME>=:DateStart'; if (DateFinish>0) then s:= s+fnIfStr(s='', '', ' and ')+'OREGCREATETIME<=:DateFinish'; if (s1<>'') then s:= s+fnIfStr(s='','',' and ')+'OREGFIRMNAME LIKE ''%'+s1+'%'''; if not flDirector then i:= empl.EmplDprtID; if (i>-1) then s:= s+fnIfStr(s='', '', ' and ')+'OREGDPRTCODE ='+IntToStr(i); IBD:= cntsORD.GetFreeCnt; IBS:= fnCreateNewIBSQL(IBD, 'IBS_'+nmProc, ThreadData.ID, tpRead, True); IBS.SQL.Text:= 'select * from ORDERTOREGISTER '+ ' left join REGIONALZONES on RGZNCODE=OREGREGION'+fnIfStr(s='','',' where '+s); if DateStart>0 then IBS.ParamByName('DateStart').AsDateTime:= Round(DateStart); if DateFinish>0 then IBS.ParamByName('DateFinish').AsDateTime:= Round(DateFinish); Stream.Clear; Stream.WriteInt(aeSuccess); // сначала знак того, что запрос обработан корректно Count:= 0; sPos:= Stream.Position; Stream.WriteInt(Count); IBS.ExecQuery; // trim ??? while not IBS.EOF do begin Stream.WriteInt(IBS.FieldByName('OREGCODE').AsInteger); Stream.WriteStr(IBS.FieldByName('OREGFIRMNAME').AsString); Stream.WriteStr(IBS.FieldByName('RGZNNAME').AsString); Stream.WriteStr(IBS.FieldByName('OREGMAINUSERFIO').AsString); Stream.WriteStr(IBS.FieldByName('OREGMAINUSERPOST').AsString); Stream.WriteStr(IBS.FieldByName('OREGLOGIN').AsString); Stream.WriteBool(GetBoolGB(IBS, 'OREGCLIENT')); Stream.WriteStr(IBS.FieldByName('OREGADDRESS').AsString); Stream.WriteStr(IBS.FieldByName('OREGPHONES').AsString); Stream.WriteStr(IBS.FieldByName('OREGEMAIL').AsString); Stream.WriteInt(IBS.FieldByName('OREGTYPE').AsInteger); Stream.WriteInt(IBS.FieldByName('OREGSTATE').AsInteger); Stream.WriteDouble(IBS.FieldByName('OREGPROCESSINGTIME').AsDateTime); Stream.WriteStr(IBS.FieldByName('OREGCOMMENT').AsString); Stream.WriteInt(IBS.FieldByName('OREGDPRTCODE').AsInteger); Stream.WriteInt(IBS.FieldByName('OREGUSERCODE').AsInteger); Stream.WriteStr(IBS.FieldByName('OREGUSERNAME').AsString); Stream.WriteDouble(IBS.FieldByName('OREGCREATETIME').AsDateTime); TestCssStopException; IBS.Next; Inc(Count); end; if Count<1 then raise EBOBError.Create('Заявки по заданным критериям не найдены.'); Stream.Position:= sPos; Stream.WriteInt(Count); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; prFreeIBSQL(IBS); cntsORD.SetFreeCnt(IBD); Stream.Position:= 0; end; //========================================================== аннулировать заявку procedure prWebArmAnnulateOrderToRegister(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmAnnulateOrderToRegister'; // имя процедуры/функции var IBS: TIBSQL; IBD: TIBDatabase; OREGCODE,EmplId: integer; OREGCOMMENT: String; empl: TEmplInfoItem; begin Stream.Position:= 0; IBS:= nil; IBD:= nil; try // тут всякие проверки EmplId:= Stream.ReadInt; OREGCODE:= Stream.ReadInt; OREGCOMMENT:= Stream.ReadStr; prSetThLogParams(ThreadData, 0, EmplId, 0, 'OREGCODE='+IntToStr(OREGCODE)+#13#10'OREGCOMMENT='+OREGCOMMENT); // логирование if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); empl:= Cache.arEmplInfo[EmplId]; if not (empl.UserRoleExists(rolRegional) or empl.UserRoleExists(rolSuperRegional)) then raise EBOBError.Create(MessText(mtkNotRightExists)); if OREGCOMMENT='' then raise EBOBError.Create('Не указана причина аннулирования заявки.'); IBD:= cntsORD.GetFreeCnt; IBS:= fnCreateNewIBSQL(IBD, 'IBS_'+nmProc, ThreadData.ID, tpRead, True); IBS.SQL.Text:= 'SELECT OREGSTATE, OREGDPRTCODE FROM ORDERTOREGISTER WHERE OREGCODE='+IntToStr(OREGCODE); IBS.ExecQuery; if IBS.Bof and IBS.Eof then raise EBOBError.Create(MessText(mtkNotFoundRegOrd)); if IBS.FieldByName('OREGSTATE').AsInteger>0 then raise EBOBError.Create(MessText(mtkRegOrdAddOrAnn)); if (empl.EmplDprtID<>IBS.FieldByName('OREGDPRTCODE').AsInteger) then raise EBOBError.Create(MessText(mtkRegOrdNotYourFil)); IBS.Close; // все проверки пройдены, аннулируем fnSetTransParams(IBS.Transaction, tpWrite, True); IBS.SQL.Text:= 'update ORDERTOREGISTER set OREGSTATE=2,'+ // признак отклоненной заявки ' OREGPROCESSINGTIME=:OREGPROCESSINGTIME, OREGCOMMENT=:OREGCOMMENT,'+ ' OREGUSERNAME=:OREGUSERNAME WHERE OREGCODE='+IntToStr(OREGCODE); IBS.ParamByName('OREGPROCESSINGTIME').AsdateTime:= now(); IBS.ParamByName('OREGCOMMENT').AsString:= OREGCOMMENT; IBS.ParamByName('OREGUSERNAME').AsString:= empl.EmplShortName; IBS.ExecQuery; IBS.Transaction.Commit; IBS.Close; Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; prFreeIBSQL(IBS); cntsORD.SetFreeCnt(IBD); Stream.Position:= 0; end; //=============================================================== принять заявку procedure prWebArmRegisterOrderToRegister(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmRegisterOrderToRegister'; // имя процедуры/функции var IBS: TIBSQL; IBD: TIBDatabase; OREGCODE, EmplId, UserID, FirmID, i: integer; UserLogin, UserCode, FirmCode, newpass, comment, errmess: String; flNewUser, flNewFirm: Boolean; empl: TEmplInfoItem; Client: TClientInfo; // vc begin Stream.Position:= 0; IBS:= nil; IBD:= nil; try // тут всякие проверки EmplId:= Stream.ReadInt; OREGCODE:= Stream.ReadInt; UserLogin:= Stream.ReadStr; UserID:= Stream.ReadInt; FirmID:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, EmplId, 0, 'OREGCODE='+IntToStr(OREGCODE)+ #13#10'UserLogin='+UserLogin+#13#10'UserID='+UserCode+#13#10'FirmID='+FirmCode); // логирование UserCode:= IntToStr(UserID); FirmCode:= IntToStr(FirmID); if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); empl:= Cache.arEmplInfo[EmplId]; if not (empl.UserRoleExists(rolRegional) or empl.UserRoleExists(rolUiK)) then // vc raise EBOBError.Create(MessText(mtkNotRightExists)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); with Cache.arFirmInfo[FirmID] do begin if empl.UserRoleExists(rolRegional) and not CheckFirmManager(emplID) then // проверяем право пользователя // vc raise EBOBError.Create(MessText(mtkNotRightExists)); flNewFirm:= StrToIntDef(NUMPREFIX, 0)<1; // новая Web-фирма flNewUser:= True; if not flNewFirm then // если Web-фирма есть for i:= Low(FirmClients) to High(FirmClients) do if Cache.ClientExist(FirmClients[i]) and (Cache.arClientInfo[FirmClients[i]].Login<>'') then begin flNewUser:= False; // если есть хоть один Web-клиент break; end; end; // with Cache.arFirmInfo[FirmID] Client:= Cache.arClientInfo[UserId]; // vc if (Client.Mail='') then raise EBOBError.Create('Нельзя делать главным пользователя без email'); // vc flNewUser:= (Client.Login=''); if flNewUser then begin // если новый Web-клиент if (Client.Post='') then raise EBOBError.Create(MessText(mtkNotClientExist)); // vc // if (Cache.arClientInfo[UserID].Post='') then // vc // raise EBOBError.Create('У клиента нет должности.'); // ??? // vc if (UserLogin='') then raise EBOBError.Create(MessText(mtkNotSetLogin)); end; try IBD:= cntsORD.GetFreeCnt; IBS:= fnCreateNewIBSQL(IBD, 'IBS_'+nmProc, ThreadData.ID, tpRead, True); IBS.SQL.Text:= 'SELECT OREGSTATE, OREGDPRTCODE FROM ORDERTOREGISTER WHERE OREGCODE='+IntToStr(OREGCODE); IBS.ExecQuery; if IBS.Bof and IBS.Eof then raise EBOBError.Create(MessText(mtkNotFoundRegOrd)); if IBS.FieldByName('OREGSTATE').AsInteger>0 then raise EBOBError.Create(MessText(mtkRegOrdAddOrAnn)); if (empl.EmplDprtID<>IBS.FieldByName('OREGDPRTCODE').AsInteger) then raise EBOBError.Create(MessText(mtkRegOrdNotYourFil)); IBS.Close; fnSetTransParams(IBS.Transaction, tpWrite); // готовимся писать if flNewUser then begin // если новый клиент if not fnCheckOrderWebLogin(UserLogin) then raise EBOBError.Create(MessText(mtkNotValidLogin)); if not fnNotLockingLogin(UserLogin) then // проверяем, не относится ли логин к запрещенным raise EBOBError.Create(MessText(mtkLockingLogin, UserLogin)); // уникальность логина в базе проверяется при добавлении пользователя with ibs.Transaction do if not InTransaction then StartTransaction; IBS.SQL.Text:= 'select rPassw,rErrText from SetFirmMainUser('+ UserCode+', '+IntToStr(FirmID)+', :login, '+IntToStr(EmplId)+', 0)'; // vc IBS.ParamByName('login').AsString:= UserLogin; IBS.ExecQuery; if (IBS.Bof and IBS.Eof) then raise Exception.Create(MessText(mtkNotValidParam)); if IBS.FieldByName('rErrText').AsString<>'' then raise EBOBError.Create(IBS.FieldByName('rErrText').AsString); if (IBS.FieldByName('rPassw').AsString='') then raise EBOBError.Create(MessText(mtkErrFormTmpPass)); newpass:= IBS.FieldByName('rPassw').AsString; IBS.Transaction.Commit; IBS.Close; comment:= 'Заявка оформлена на клиента с логином '+UserLogin; end else begin newpass:= 'Заявка закрыта по контрагенту'; // сообщение юзеру comment:= newpass+' '+Cache.arFirmInfo[FirmID].Name; end; comment:= comment+' пользователем '+empl.EmplShortName; // все проверки пройдены, регистрируем with ibs.Transaction do if not InTransaction then StartTransaction; IBS.SQL.Text:= 'update ORDERTOREGISTER set OREGSTATE=1,'+ // признак принятой заявки ' OREGPROCESSINGTIME=:OREGPROCESSINGTIME, OREGCOMMENT=:OREGCOMMENT,'+ ' OREGUSERNAME=:OREGUSERNAME WHERE OREGCODE='+IntToStr(OREGCODE); IBS.ParamByName('OREGPROCESSINGTIME').AsdateTime:= now(); IBS.ParamByName('OREGCOMMENT').AsString:= comment; IBS.ParamByName('OREGUSERNAME').AsString:= empl.EmplShortName; IBS.ExecQuery; IBS.Transaction.Commit; IBS.Close; finally prFreeIBSQL(IBS); cntsORD.SetFreeCnt(IBD); end; if flNewUser then try // если новый клиент - пишем логин в Grossbee IBD:= cntsGRB.GetFreeCnt; IBS:= fnCreateNewIBSQL(IBD, 'IBS_'+nmProc, ThreadData.ID, tpWrite, true); IBS.SQL.Text:= 'UPDATE PERSONS SET PRSNLOGIN=:login WHERE PRSNCODE='+UserCode; IBS.ParamByName('login').AsString:= UserLogin; IBS.ExecQuery; if IBS.Transaction.InTransaction then IBS.Transaction.Commit; IBS.Close; finally prFreeIBSQL(IBS); cntsGRB.SetFreeCnt(IBD); end; if flNewUser then Cache.TestClients(UserID, true, false, true); // обновляем параметры клиента и фирмы в кэше Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteBool(flNewUser); // признак нового пользователя Stream.WriteStr(newpass); // временный пароль или сообщение except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //****************************************************************************** // работа с регионами //****************************************************************************** //============================================================== список регионов procedure prWebArmGetRegionalZones(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetRegionalZones'; // имя процедуры/функции var ibs: TIBSQL; IBD: TIBDatabase; Count, EmplId, sPos: integer; begin Stream.Position:= 0; ibs:= nil; IBD:= nil; try EmplId:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, EmplId, 0, ''); // логирование if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); if not Cache.arEmplInfo[EmplId].UserRoleExists(rolSaleDirector) then raise EBOBError.Create(MessText(mtkNotRightExists)); IBD:= cntsORD.GetFreeCnt; ibs:= fnCreateNewIBSQL(IBD, 'ibs_'+nmProc, ThreadData.ID, tpRead, True); ibs.SQL.Text:= 'select * from REGIONALZONES order by RGZNNAME'; ibs.ExecQuery; if (IBS.Bof and IBS.Eof) then raise Exception.Create(MessText(mtkNotValidParam)); Stream.Clear; Stream.WriteInt(aeSuccess); // сначала знак того, что запрос обработан корректно sPos:= Stream.Position; Count:= 0; Stream.WriteInt(Count); while not ibs.EOF do begin Stream.WriteInt(ibs.FieldByName('RGZNCODE').AsInteger); Stream.WriteStr(ibs.FieldByName('RGZNNAME').AsString); Stream.WriteStr(ibs.FieldByName('RGZNEMAIL').AsString); Stream.WriteInt(ibs.FieldByName('RGZNFILIALLINK').AsInteger); TestCssStopException; ibs.Next; Inc(Count); end; if Count<1 then raise EBOBError.Create(MessText(mtkNotFoundData)); Stream.Position:= sPos; Stream.WriteInt(Count); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; prFreeIBSQL(ibs); cntsORD.SetFreeCnt(IBD); Stream.Position:= 0; end; //=========================================================== добавление региона procedure prWebArmInsertRegionalZone(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmInsertRegionalZone'; // имя процедуры/функции var ibs: TIBSQL; IBD: TIBDatabase; email, ZoneName, s: string; idprt, EmplId, i: integer; begin ibs:= nil; IBD:= nil; try Stream.Position:= 0; EmplId:= Stream.ReadInt; ZoneName:= trim(Stream.ReadStr); email:= trim(Stream.ReadStr); idprt:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, EmplId, 0, 'email='+email+ #13#10'ZoneName='+ZoneName+#13#10'idprt='+IntToStr(idprt)); // логирование if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); if not Cache.arEmplInfo[EmplId].UserRoleExists(rolSaleDirector) then raise EBOBError.Create(MessText(mtkNotRightExists)); if (ZoneName='') then raise EBOBError.Create(MessText(mtkEmptyName)); if (email='') then raise EBOBError.Create('Не задан Email.'); if (idprt<1) then raise EBOBError.Create('Не задано подразделение.'); IBD:= cntsORD.GetFreeCnt; ibs:= fnCreateNewIBSQL(IBD, 'ibs_'+nmProc, ThreadData.ID, tpRead, True); // обрезаем текстовые значения по размерам полей ibs.SQL.Text:= 'select f.RDB$FIELD_NAME fname, ff.RDB$FIELD_LENGTH fsize'+ ' from rdb$relation_fields f, rdb$fields ff'+ ' where ff.RDB$FIELD_NAME=f.RDB$FIELD_SOURCE and f.RDB$RELATION_NAME=:table'; ibs.ParamByName('table').AsString:= 'REGIONALZONES'; ibs.ExecQuery; while not ibs.Eof do begin s:= trim(ibs.FieldByName('fname').AsString); i:= ibs.FieldByName('fsize').AsInteger; if (s='RGZNNAME') and (length(ZoneName)>i) then ZoneName:= trim(Copy(ZoneName, 1, i)) else if (s='RGZNEMAIL') and (length(email)>i) then email:= trim(Copy(email, 1, i)); ibs.Next; end; ibs.Close; fnSetTransParams(ibs.Transaction, tpWrite, True); ibs.SQL.Text:= 'insert into REGIONALZONES (RGZNNAME, RGZNEMAIL, RGZNFILIALLINK)'+ ' values (:RGZNNAME, :RGZNEMAIL, :RGZNFILIALLINK)'; ibs.ParamByName('RGZNNAME').AsString:= ZoneName; ibs.ParamByName('RGZNEMAIL').AsString:= email; ibs.ParamByName('RGZNFILIALLINK').AsInteger:= idprt; ibs.ExecQuery; ibs.Transaction.Commit; ibs.Close; Stream.Clear; Stream.WriteInt(aeSuccess); // сначала знак того, что запрос обработан корректно except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; prFreeIBSQL(ibs); cntsORD.SetFreeCnt(IBD); Stream.Position:= 0; end; //============================================================= удаление региона procedure prWebArmDeleteRegionalZone(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmDeleteRegionalZone'; // имя процедуры/функции var ibs: TIBSQL; IBD: TIBDatabase; zcode, EmplId: integer; begin ibs:= nil; IBD:= nil; try Stream.Position:= 0; EmplId:= Stream.ReadInt; zcode:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, EmplId, 0, 'zcode='+IntToStr(zcode)); // логирование if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); if not Cache.arEmplInfo[EmplId].UserRoleExists(rolSaleDirector) then raise EBOBError.Create(MessText(mtkNotRightExists)); if (zcode<1) then raise EBOBError.Create(MessText(mtkNotSetRegion)); IBD:= cntsORD.GetFreeCnt; ibs:= fnCreateNewIBSQL(IBD, 'ibs_'+nmProc, ThreadData.ID, tpWrite, true); ibs.SQL.Text:= 'delete from REGIONALZONES where RGZNCODE='+IntToStr(zcode); ibs.ExecQuery; ibs.Transaction.Commit; ibs.Close; Stream.Clear; Stream.WriteInt(aeSuccess); // сначала знак того, что запрос обработан корректно except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; prFreeIBSQL(ibs); cntsORD.SetFreeCnt(IBD); end; //============================================================ изменение региона procedure prWebArmUpdateRegionalZone(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmUpdateRegionalZone'; // имя процедуры/функции var ibs: TIBSQL; IBD: TIBDatabase; email, ZoneName, s, ss: string; idprt, EmplId, zcode, i: integer; begin ibs:= nil; IBD:= nil; Stream.Position:= 0; try EmplId:= Stream.ReadInt; zcode:= Stream.ReadInt; ZoneName:= trim(Stream.ReadStr); email:= trim(Stream.ReadStr); idprt:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, EmplId, 0, 'zcode='+IntToStr(zcode)+ #13#10'email='+email+#13#10'ZoneName='+ZoneName+#13#10'idprt='+IntToStr(idprt)); // логирование if not Cache.EmplExist(EmplId) then raise EBOBError.Create(MessText(mtkNotEmplExist)); if not Cache.arEmplInfo[EmplId].UserRoleExists(rolSaleDirector) then raise EBOBError.Create(MessText(mtkNotRightExists)); if (zcode<1) then raise EBOBError.Create(MessText(mtkNotSetRegion)); if (ZoneName='') and (email='') and (idprt<1) then raise EBOBError.Create(MessText(mtkNotParams)); s:= ''; if (ZoneName<>'') then s:= s+'RGZNNAME=:RGZNNAME'; if (email<>'') then s:= s+fnIfStr(s='','',',')+'RGZNEMAIL=:RGZNEMAIL'; if (idprt>0) then s:= s+fnIfStr(s='','',',')+'RGZNFILIALLINK=:RGZNFILIALLINK'; IBD:= cntsORD.GetFreeCnt; ibs:= fnCreateNewIBSQL(IBD, 'ibs_'+nmProc, ThreadData.ID, tpRead, True); // обрезаем текстовые значения по размерам полей ibs.SQL.Text:= 'select f.RDB$FIELD_NAME fname, ff.RDB$FIELD_LENGTH fsize'+ ' from rdb$relation_fields f, rdb$fields ff'+ ' where ff.RDB$FIELD_NAME=f.RDB$FIELD_SOURCE and f.RDB$RELATION_NAME=:table'; ibs.ParamByName('table').AsString:= 'REGIONALZONES'; ibs.ExecQuery; while not ibs.Eof do begin ss:= trim(ibs.FieldByName('fname').AsString); i:= ibs.FieldByName('fsize').AsInteger; if (ss='RGZNNAME') and (length(ZoneName)>i) then ZoneName:= trim(Copy(ZoneName, 1, i)) else if (ss='RGZNEMAIL') and (length(email)>i) then email:= trim(Copy(email, 1, i)); ibs.Next; end; ibs.Close; fnSetTransParams(ibs.Transaction, tpWrite, True); ibs.SQL.Text:= 'update REGIONALZONES set '+s+' where RGZNCODE='+IntToStr(zcode); if (ZoneName<>'') then ibs.ParamByName('RGZNNAME').AsString:= ZoneName; if (email<>'') then ibs.ParamByName('RGZNEMAIL').AsString:= email; if (idprt>0) then ibs.ParamByName('RGZNFILIALLINK').AsInteger:= idprt; ibs.ExecQuery; ibs.Transaction.Commit; ibs.Close; Stream.Clear; Stream.WriteInt(aeSuccess); // сначала знак того, что запрос обработан корректно except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; prFreeIBSQL(ibs); cntsORD.SetFreeCnt(IBD); end; //****************************************************************************** // подбор запчастей //****************************************************************************** //****************************************************************************** // Товары, атрибуты //****************************************************************************** //======================================= (+ Web) Список групп атрибутов системы procedure prGetListAttrGroupNames(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetListAttrGroupNames'; // имя процедуры/функции var UserID, FirmID, SysID, i: Integer; errmess: String; lst: TStringList; begin Stream.Position:= 0; try FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; SysID:= Stream.ReadInt; // код системы prSetThLogParams(ThreadData, 0, UserId, FirmID, 'SysID='+IntToStr(SysID)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); if CheckNotValidFirmSys(FirmID, SysID, errmess) then raise EBOBError.Create(errmess); // Web lst:= Cache.AttrGroups.GetListAttrGroups(SysID); // Список групп атрибутов (TStringList) not Free !!! if not Assigned(lst) or (lst.Count<1) then raise EBOBError.Create(MessText(mtkNotFoundData)); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteInt(lst.Count); // кол-во групп for i:= 0 to lst.Count-1 do begin Stream.WriteInt(Integer(lst.Objects[i])); // код Stream.WriteStr(lst[i]); // название end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //============================================== (+ Web) Список атрибутов группы procedure prGetListGroupAttrs(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetListGroupAttrs'; // имя процедуры/функции var UserID, FirmID, SysID, grpID, i, ii: Integer; errmess: String; AttrGroup: TAttrGroupItem; begin Stream.Position:= 0; try FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; grpID:= Stream.ReadInt; // код группы атрибутов prSetThLogParams(ThreadData, 0, UserId, FirmID, 'grpID='+IntToStr(grpID)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); if not Cache.AttrGroups.ItemExists(grpID) then raise EBOBError.Create(MessText(mtkNotFoundAttGr, IntToStr(grpID))); AttrGroup:= Cache.AttrGroups.GetAttrGroup(grpID); // группа атрибутов SysID:= AttrGroup.TypeSys; if CheckNotValidFirmSys(FirmID, SysID, errmess) then raise EBOBError.Create(errmess); // Web with AttrGroup.GetListGroupAttrs do try // Список атрибутов группы (TList) if (Count<1) then raise EBOBError.Create(MessText(mtkNotFoundData)); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteInt(Count); // кол-во атрибутов for i:= 0 to Count-1 do with TAttributeItem(Items[i]) do begin Stream.WriteInt(ID); // код Stream.WriteStr(Name); // название Stream.WriteByte(TypeAttr); // Тип with ListValues do begin // значения атрибутов Stream.WriteInt(Count); // Количество for ii:= 0 to Count-1 do begin Stream.WriteInt(Integer(Objects[ii])); // код значения Stream.WriteStr(Strings[ii]); // само значение end; end; end; finally Free; end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //=============================================== параметры товара для просмотра procedure prGetWareInfoView(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetWareInfoView'; // имя процедуры/функции var UserID, FirmID, WareID, i, Count1, sPos, j, ModelID, NodeID: Integer; s, sFilters: string; // txt1, txt2, DelimBr, DelimColor, TitleBegin: string; Files: TarWareFileOpts; isEngine: boolean; List: TStringList; aiWares: Tai; // node: TAutoTreeNode; Engine: TEngine; Model: TModelAuto; begin List:= nil; Stream.Position:= 0; try FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; WareID:= Stream.ReadInt; // код товара ModelID:= Stream.ReadInt; NodeID:= Stream.ReadInt; isEngine:= Stream.ReadBool; sFilters:= Stream.ReadStr; prSetThLogParams(ThreadData, 0, UserId, FirmID, 'WareID='+IntToStr(WareID)+ #13#10+fnIfStr(isEngine, 'EngineID=', 'ModelID=')+IntToStr(ModelID)+ #13#10'NodeID='+IntToStr(NodeID)+#13#10'sFilters='+sFilters); // if CheckNotValidUser(UserID, FirmID, s) then raise EBOBError.Create(s); if not Cache.WareExist(WareID) then raise EBOBError.Create(MessText(mtkNotFoundWare, IntToStr(WareID))); With Cache.GetWare(WareID) do begin if IsArchive then raise EBOBError.Create(MessText(mtkNotFoundWare, IntToStr(WareID))); Stream.Clear; Stream.WriteInt(aeSuccess); // Передаем параметры товара Stream.WriteStr(Name); // наименование Stream.WriteBool(IsSale); // признак распродажи Stream.WriteBool(IsNonReturn); // признак невозврата Stream.WriteBool(IsCutPrice); // признак уценки Stream.WriteStr(BrandNameWWW); // бренд для файла логотипа Stream.WriteStr(BrandAdrWWW); // адрес ссылки на сайт бренда Stream.WriteStr(WareBrandName); // бренд Stream.WriteDouble(divis); // кратность Stream.WriteStr(MeasName); // ед.изм. Stream.WriteStr(Comment); // описание with GetWareAttrValuesView do try // список названий и значений атрибутов товара (TStringList) Stream.WriteInt(Count); // кол-во атрибутов for i:= 0 to Count-1 do begin Stream.WriteStr(Names[i]); // название атрибута Stream.WriteStr(ExtractParametr(Strings[i])); // значение атрибута end; finally Free; end; // DelimBr:= fnCodeBracketsForWeb('</b>'); // DelimColor:= fnCodeBracketsForWeb('<b style="color: blue;">'); // TitleBegin:= 'Условия применимости товара '; // txt1:= ''; with Cache.FDCA do try try if (ModelId<1) or (NodeID<1) then raise EBOBError.Create(''); SetLength(aiWares, 1); aiWares[0]:= WareID; if IsEngine then begin // --------------------------- двигатель if not Engines.ItemExists(ModelId) then raise EBOBError.Create('Неверно указан двигатель'); Engine:= Engines.GetEngine(ModelId); if not AutoTreeNodesSys[constIsAuto].NodeExists(NodeID) then raise EBOBError.Create('Неверно указан узел'); List:= Engine.GetEngNodeWareUsesView(NodeID, aiWares, sFilters); if (List.Count<1) then EBOBError.Create('Нет условий'); { node:= AutoTreeNodesSys[constIsAuto][NodeID]; if node.IsEnding then begin txt1:= ' к узлу '+DelimColor+node.Name+DelimBr; txt2:= ' двигателя '; end else txt2:= ' к двигателю '; Stream.WriteStr(TitleBegin+DelimColor+Name+DelimBr+txt1+txt2+ DelimColor+Engine.WebName+DelimBr); } // Stream.WriteStr(''); end else begin // --------------------------- модель if not Models.ModelExists(ModelId) then raise EBOBError.Create('Неверно указана модель'); Model:= Models[ModelId]; if not AutoTreeNodesSys[Model.TypeSys].NodeExists(NodeID) then raise EBOBError.Create('Неверно указан узел'); List:= Cache.GetWaresModelNodeUsesAndTextsView(ModelID, NodeID, aiWares, sFilters); if (List.Count<1) then raise EBOBError.Create('Нет условий'); { node:= AutoTreeNodesSys[Model.TypeSys][NodeID]; if not node.IsEnding then begin txt1:= ' к узлу '+DelimColor+node.Name+DelimBr; txt2:= ' модели '; end else txt2:= ' к модели '; Stream.WriteStr(TitleBegin+DelimColor+Name+DelimBr+txt1+txt2+ DelimColor+Model.WebName+DelimBr); } // Stream.WriteStr(''); end; Stream.WriteStr(List.Text); except on E: Exception do begin // Stream.WriteStr(''); Stream.WriteStr(''); end; end; // with Cache.FDCA finally prFree(List); SetLength(aiWares, 0); end; s:= ''; with GetWareCriValuesView do try if Count>0 then s:= Text; finally Free; end; Stream.WriteStr(s); Files:= GetWareFiles; Count1:= Length(Files)-1; j:= -1; sPos:= Stream.Position; Stream.WriteInt(j); for i:= 0 to Count1 do with Files[i] do if LinkURL then begin Stream.WriteStr(FileName); Stream.WriteInt(SupID); Stream.WriteStr(HeadName); Inc(j); end; Stream.Position:= sPos; Stream.WriteInt(j); Stream.Position:= Stream.Size; // если будем еще добавлять инфо по товару end; // With Cache.GetWare(WareID) except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; SetLength(Files, 0); end; //============================================== параметры товаров для сравнения procedure prGetCompareWaresInfo(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetCompareWaresInfo'; // имя процедуры/функции var UserID, FirmID, CurrID, WareID, agID, i, j, WareCount, contID: Integer; errmess: String; Ware: TWareInfo; WaresList: TStringList; attCodes: Tai; pRetail, pSelling: double; begin Stream.Position:= 0; setLength(attCodes, 0); agID:= 0; WaresList:= nil; try UserID:= Stream.ReadInt; FirmID:= Stream.ReadInt; ContID:= Stream.ReadInt; // для контрактов WareCount:= Stream.ReadInt; // входное кол-во товаров prSetThLogParams(ThreadData, 0, UserId, FirmID, 'WareCount='+IntToStr(WareCount)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); if FirmID=isWe then CurrID:= cDefCurrency else CurrID:= Cache.arClientInfo[UserID].SearchCurrencyID; // код валюты сравнения // else CurrID:= Cache.arFirmInfo[FirmID].GetContract(contID).ContCurrency; WaresList:= fnCreateStringList(True, dupIgnore, WareCount); // список с проверкой на дубликаты кодов товаров ??? for i:= 0 to WareCount-1 do begin // принимаем коды товаров WareID:= Stream.ReadInt; if Cache.WareExist(WareID) then begin // проверка существования товара Ware:= Cache.GetWare(WareID); if not Ware.IsArchive then begin if agID<1 then agID:= Ware.AttrGroupID; // определяем код группы атрибутов if (agID>0) and (agID=Ware.AttrGroupID) then // потом берем только с этой группой WaresList.AddObject(Ware.Name, Ware); // в Object - ссылка на товар end; end; end; if (agID<1) or (WaresList.Count<1) then raise EBOBError.Create(MessText(mtkNotParams)); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteStr(Cache.GetCurrName(CurrID)); // наименование валюты сравнения with Cache.AttrGroups.GetAttrGroup(agID).GetListGroupAttrs do try // список атрибутов группы (TList) Stream.WriteInt(Count); // кол-во атрибутов группы setLength(attCodes, Count); // порядок кодов атрибутов for j:= 0 to Count-1 do with TAttributeItem(Items[j]) do begin attCodes[j]:= ID; // запоминаем порядок кодов атрибутов Stream.WriteStr(Name); // передаем название атрибута end; finally Free; end; Stream.WriteInt(WaresList.Count); // исходящее кол-во товаров for i:= 0 to WaresList.Count-1 do with TWareInfo(WaresList.Objects[i]) do begin // передаем параметры товара Stream.WriteInt(ID); // код товара Stream.WriteStr(Name); // наименование Stream.WriteBool(IsSale); // признак распродажи Stream.WriteBool(IsNonReturn); // признак невозврата Stream.WriteBool(IsCutPrice); // признак уценки Stream.WriteStr(BrandNameWWW); // бренд для файла логотипа Stream.WriteStr(BrandAdrWWW); // адрес ссылки на сайт бренда Stream.WriteStr(WareBrandName); // бренд Stream.WriteDouble(divis); // кратность Stream.WriteStr(MeasName); // ед.изм. Stream.WriteStr(Comment); // описание CalcFirmPrices(pRetail, pSelling, FirmID, CurrID, contID); // розничная и продажная цены товара для фирмы Stream.WriteDouble(pRetail); // цена розницы if FirmID<>isWe then Stream.WriteDouble(pSelling); // цена клиента (Web) with GetWareAttrValuesByCodes(AttCodes) do try // значения атрибутов в нужном порядке (TStringList) for j:= 0 to Count-1 do Stream.WriteStr(Strings[j]); finally Free; end; end; // for i:= 0 to WaresList.Count-1 except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; prFree(WaresList); setLength(attCodes, 0); Stream.Position:= 0; end; //****************************************************************************** // модельный ряд //****************************************************************************** //====================================== (+ Web) Получить список модельных рядов procedure prGetModelLineList(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetModelLineList'; // имя процедуры/функции var UserID, FirmID, SysID, ManufID, i, sPos, iCount: Integer; isTops, OnlyVisible, OnlyWithWares: Boolean; errmess: String; Manuf: TManufacturer; begin Stream.Position:= 0; try FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; SysID:= Stream.ReadInt; ManufID:= Stream.ReadInt; isTops:= Stream.ReadBool; // Топы вверх OnlyVisible:= Stream.ReadBool; // False - все, True - только видимые OnlyWithWares:= OnlyVisible; // False - все, True - только с товарами prSetThLogParams(ThreadData, 0, UserId, FirmID, 'ManufID='+IntToStr(ManufID)); if CheckNotValidManuf(ManufID, SysID, Manuf, errmess) then raise EBOBError.Create(errmess); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); // if (FirmID=isWe) and CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); if CheckNotValidFirmSys(FirmID, SysID, errmess) then raise EBOBError.Create(errmess); // Web Stream.Clear; Stream.WriteInt(aeSuccess); // Запись списка модельных рядов в поток with Manuf.GetModelLinesList(SysID, isTops) do begin sPos:= Stream.Position; iCount:= 0; // счетчик - если передаем только видимые Stream.WriteInt(iCount); for i:= 0 to Count-1 do with Cache.FDCA.ModelLines[Integer(Objects[i])] do begin if (OnlyVisible and not (IsVisible and HasVisModels)) then Continue; if (OnlyWithWares and not MLHasWares) then Continue; // если нет товаров Stream.WriteInt(ID); // Код модельного ряда Stream.WriteStr(Name); // Наименование Stream.WriteBool(IsVisible); // Признак видимости модельного ряда Stream.WriteBool(IsTop); // Топ Stream.WriteInt(YStart); // Год начала выпуска Stream.WriteInt(MStart); // Месяц Stream.WriteInt(YEnd); // Год окончание выпуска Stream.WriteInt(MEnd); // Месяц Stream.WriteInt(ModelsCount); // Наличие моделей в ряду Inc(iCount); end; Stream.Position:= sPos; Stream.WriteInt(iCount); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //======================================================= Добавить модельный ряд procedure prModelLineAdd(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prModelLineAdd'; // имя процедуры/функции var UserID, SysID, ManufID, fMS, fYS, fME, fYE, iCode: Integer; MLName, errmess: String; isTop, isVis: boolean; Manuf: TManufacturer; begin Stream.Position:= 0; try UserID:= Stream.ReadInt; SysID:= Stream.ReadInt; ManufID:= Stream.ReadInt; // Код производителя авто MLName:= Stream.ReadStr; // Наименование модельного ряда isTop:= Stream.ReadBool; fMS:= Stream.ReadInt; // Месяц начала выпуска fYS:= Stream.ReadInt; // Год начала fME:= Stream.ReadInt; // Месяц окончания fYE:= Stream.ReadInt; // Год окончания isVis:= Stream.ReadBool; // Признак видимости prSetThLogParams(ThreadData, 0, UserId, 0, 'ManufID='+IntToStr(ManufID)+', MLName='+MLName); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); if MLName='' then raise EBOBError.Create(MessText(mtkEmptyName)); if CheckNotValidManuf(ManufID, SysID, Manuf, errmess) then raise EBOBError.Create(errmess); errmess:= Manuf.ModelLineAdd(iCode, MLName, SysID, fYS, fMS, fYE, fME, UserID, isTop, isVis); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteInt(iCode); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //======================================================== Удалить модельный ряд procedure prModelLineDel(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prModelLineDel'; // имя процедуры/функции var UserID, ModelLineID, ManufID, SysID: Integer; errmess: String; ModelLine: TModelLine; Manuf: TManufacturer; begin Stream.Position:= 0; try UserID:= Stream.ReadInt; ModelLineID:= Stream.ReadInt; // Код модельного ряда prSetThLogParams(ThreadData, 0, UserId, 0, 'ModelLineID='+IntToStr(ModelLineID)); if CheckNotValidModelLine(ModelLineID, SysID, ModelLine, errmess) then raise EBOBError.Create(errmess); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); ManufID:= ModelLine.MFAID; if CheckNotValidManuf(ManufID, SysID, Manuf, errmess) then raise EBOBError.Create(errmess); errmess:= Manuf.ModelLineDel(ModelLineID); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //======================================================= Изменить модельный ряд procedure prModelLineEdit(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prModelLineEdit'; // имя процедуры/функции var UserID, ModelLineID, ManufID, SysID, fMS, fYS, fME, fYE: Integer; MLName, errmess: String; isTop, isVis: Boolean; ModelLine: TModelLine; Manuf: TManufacturer; begin Stream.Position:= 0; try UserID:= Stream.ReadInt; ModelLineID:= Stream.ReadInt; // Код модельного ряда MLName:= Stream.ReadStr; // Наименование модельного ряда isTop:= Stream.ReadBool; fYS:= Stream.ReadInt; // Год начала fMS:= Stream.ReadInt; // Месяц начала выпуска fYE:= Stream.ReadInt; // Год окончания fME:= Stream.ReadInt; // Месяц окончания isVis:= Stream.ReadBool; //Признак видимости prSetThLogParams(ThreadData, 0, UserId, 0, 'ModelLineID='+IntToStr(ModelLineID)+', MLName='+MLName); if CheckNotValidModelLine(ModelLineID, SysID, ModelLine, errmess) then raise EBOBError.Create(errmess); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); ManufID:= ModelLine.MFAID; if CheckNotValidManuf(ManufID, SysID, Manuf, errmess) then raise EBOBError.Create(errmess); errmess:= Manuf.ModelLineEdit(ModelLineID, fYS, fMS, fYE, fME, UserID, isTop, isVis, MLName); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //****************************************************************************** // модель //****************************************************************************** //============================== (+ Web) Получить список моделей модельного ряда procedure prGetModelLineModels(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetModelLineModels'; // имя процедуры/функции var UserID, FirmID, ModelLineID, SysID, i, sPos, iCount: Integer; TopsUp, OnlyVisible, OnlyWithWares: Boolean; ModelLine: TModelLine; errmess, s: String; begin Stream.Position:= 0; try FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; ModelLineID:= Stream.ReadInt; // Код модельного ряда TopsUp:= Stream.ReadBool; // Топы вверх OnlyVisible:= Stream.ReadBool; // False - все, True - только видимые OnlyWithWares:= OnlyVisible; // False - все, True - только с товарами prSetThLogParams(ThreadData, 0, UserId, FirmID, 'ModelLineID='+IntToStr(ModelLineID)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); if CheckNotValidModelLine(ModelLineID, SysID, ModelLine, errmess) then raise EBOBError.Create(errmess); // if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); // if (FirmID=isWe) and CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); if CheckNotValidFirmSys(FirmID, SysID, errmess) then raise EBOBError.Create(errmess); // Web Stream.Clear; // Запись моделей модельного ряда в поток Stream.WriteInt(aeSuccess); sPos:= Stream.Position; iCount:= 0; // счетчик - если передаем только видимые Stream.WriteInt(iCount); with ModelLine.GetListModels(TopsUp) do if (Count>0) then begin for i:= 0 to Count-1 do with Cache.FDCA.Models[Integer(Objects[i])] do begin if (OnlyVisible and not IsVisible) then Continue; if (OnlyWithWares and not ModelHasWares) then Continue; // если нет товаров Stream.WriteInt(ID); // Код модели s:= ''; if OnlyWithWares then begin s:= MarksCommaText; if s<>'' then s:= '('+s+')'; if (Params.pHP>0) then s:= IntToStr(Params.pHP)+', '+s; end; if s<>'' then s:= '||'+s; Stream.WriteStr(Name+s); // Название модели + доп.данные Stream.WriteBool(IsVisible); // Видимость модели Stream.WriteBool(IsTop); // Топ модель Stream.WriteInt(Params.pYStart); // Год начала выпуска Stream.WriteInt(Params.pMStart); // Месяц начала выпуска Stream.WriteInt(Params.pYEnd); // Год окончания выпуска Stream.WriteInt(Params.pMEnd); // Месяц окончания выпуска Stream.WriteInt(ModelOrderNum); // Порядковый номер Stream.WriteInt(SubCode); // Номер TecDoc (авто) / код для сайта (мото) Inc(iCount); end; Stream.Position:= sPos; Stream.WriteInt(iCount); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //========================================= (+ Web) Получить дерево узлов модели procedure prGetModelTree(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetModelTree'; // имя процедуры/функции var UserID, FirmID, ModelID, SysID, i, j, spos: Integer; flNodesWithoutWares, flHideNodesWithOneChild, flHideOnlySameName, flHideOnlyOneLevel, flFromBase: boolean; errmess: String; Model: TModelAuto; Node: TAutoTreeNode; link: TSecondLink; listParCodes, listNodes: TList; begin Stream.Position:= 0; listParCodes:= nil; listNodes:= nil; try // if not Cache.WareLinksUnLocked then // raise EBOBError.Create(MessText(mtkFuncNotEnable)); FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; ModelID:= Stream.ReadInt; // код модели flNodesWithoutWares:= Stream.ReadBool; // признак - передавать ноды без товаров flHideNodesWithOneChild:= not flNodesWithoutWares; // сворачивать ноды с 1 ребенком flHideOnlyOneLevel:= flHideNodesWithOneChild and Cache.HideOnlyOneLevel; // сворачивать только 1 уровень flHideOnlySameName:= flHideNodesWithOneChild and Cache.HideOnlySameName; // сворачивать только при совпадении имен prSetThLogParams(ThreadData, 0, UserId, FirmID, 'ModelID='+IntToStr(ModelID)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); if CheckNotValidModel(ModelID, SysID, Model, errmess) then raise EBOBError.Create(errmess); // if (FirmID=isWe) and CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); if CheckNotValidFirmSys(FirmID, SysID, errmess) then raise EBOBError.Create(errmess); // Web flFromBase:= not Cache.WareLinksUnLocked; // пока кеш связок не заполнен - берем из базы try // список связок с видимыми нодами модели listNodes:= Model.GetModelNodesList(True, flFromBase); if not flNodesWithoutWares then // чистим ноды без товаров for i:= listNodes.Count-1 downto 0 do begin link:= listNodes[i]; if not link.NodeHasWares then listNodes.Delete(i); end; if listNodes.Count<1 then raise EBOBError.Create(MessText(mtkNotFoundNodes)); listParCodes:= TList.Create; listParCodes.Capacity:= listNodes.Count; for i:= 0 to listNodes.Count-1 do begin // список кодов родителей link:= listNodes[i]; Node:= link.LinkPtr; listParCodes.Add(Pointer(Node.ParentID)); end; if flHideNodesWithOneChild then // сворачиваем ноды с 1-м ребенком prHideTreeNodes(listNodes, listParCodes, flHideOnlySameName, flHideOnlyOneLevel); if listNodes.Count<1 then raise EBOBError.Create(MessText(mtkNotFoundNodes)); Stream.Clear; Stream.WriteInt(aeSuccess); // Запись дерева модели в поток Stream.WriteStr(Model.WebName); // Запись названия модели в поток j:= 0; // счетчик строк spos:= Stream.Position; Stream.WriteInt(j); for i:= 0 to listNodes.Count-1 do if Assigned(listNodes[i]) then begin link:= listNodes[i]; Node:= link.LinkPtr; Stream.WriteInt(Node.ID); Stream.WriteInt(Integer(listParCodes[i])); Stream.WriteStr(Node.Name); Stream.WriteBool(link.IsLinkNode); if link.IsLinkNode then begin Stream.WriteDouble(link.Qty); Stream.WriteStr(Cache.GetMeasName(Node.MeasID)); Stream.WriteBool(link.NodeHasFilters); // признак наличия фильтров в узле модели end; inc(j); end; Stream.Position:= spos; Stream.WriteInt(j); // кол-во переданных элементов finally if flFromBase then for i:= 0 to listNodes.Count-1 do if Assigned(listNodes[i]) then TObject(listNodes[i]).Free; prFree(listNodes); prFree(listParCodes); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //=========================================== считать параметры модели из потока procedure ReadModelParams(Stream: TBoBMemoryStream; mps: TModelParams); begin mps.pYStart:= Stream.ReadInt; // Год начала выпуска mps.pMStart:= Stream.ReadInt; // Месяц начала выпуска mps.pYEnd := Stream.ReadInt; // Год окончания выпуска mps.pMEnd := Stream.ReadInt; // Месяц окончания выпуска try // если не все данные были записаны в Stream mps.pKW := Stream.ReadInt; // Мощность кВт mps.pHP := Stream.ReadInt; // Мощность ЛС mps.pCCM := Stream.ReadInt; // Тех. обьем куб.см. mps.pCylinders := Stream.ReadInt; // Количество цилиндров mps.pValves := Stream.ReadInt; // Количество клапанов на одну камеру сгорания mps.pBodyID := Stream.ReadInt; // Код, тип кузова mps.pDriveID := Stream.ReadInt; // Код, тип привода mps.pEngTypeID := Stream.ReadInt; // Код, тип двигателя mps.pFuelID := Stream.ReadInt; // Код, тип топлива mps.pFuelSupID := Stream.ReadInt; // Код, система впрыска mps.pBrakeID := Stream.ReadInt; // Код, тип тормозной системы mps.pBrakeSysID:= Stream.ReadInt; // Код, Тормозная система mps.pCatalID := Stream.ReadInt; // Код, Тип катализатора mps.pTransID := Stream.ReadInt; // Код, Вид коробки передач except end; end; //============================================== Добавить модель в модельный ряд procedure prModelAddToModelLine(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prModelAddToModelLine'; // имя процедуры/функции var UserID, MLineID, pModelID, SysID, pOrdNum, pTDcode: Integer; Top, isVis: Boolean; pName, errmess: String; ModelLine: TModelLine; mps: TModelParams; begin Stream.Position:= 0; mps:= TModelParams.Create; try UserID:= Stream.ReadInt; MLineID:= Stream.ReadInt; // Код модельного ряда pName:= Stream.ReadStr; // Название модели prSetThLogParams(ThreadData, 0, UserId, 0, ' MLineID='+IntToStr(MLineID)+' pName='+pName); if (pName='') then raise EBOBError.Create(MessText(mtkEmptyName)); if CheckNotValidModelLine(MLineID, SysID, ModelLine, errmess) then raise EBOBError.Create(errmess); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); Top := Stream.ReadBool; // Топ isVis := Stream.ReadBool; // видимость ReadModelParams(Stream, mps); try pOrdNum:= Stream.ReadInt; // порядковый № except pOrdNum:= -1; end; try pTDcode:= Stream.ReadInt; // Номер TecDoc (авто) / код для сайта (мото) except pTDcode:= -1; end; errmess:= Cache.FDCA.Models.ModelAdd(pModelID, pName, isVis, Top, UserID, MLineID, mps, pOrdNum, pTDcode); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteInt(pModelID); // Код модели except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; prFree(mps); end; //============================================================== Изменить модель procedure prModelEdit(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prModelEdit'; // имя процедуры/функции var UserID, ModelID, SysID, pOrdNum, pTDcode: Integer; Top, Visible: Boolean; pName, errmess: String; Model: TModelAuto; mps: TModelParams; begin Stream.Position:= 0; mps:= TModelParams.Create; try UserID:= Stream.ReadInt; ModelID:= Stream.ReadInt; // Код модели pName:= Stream.ReadStr; // Название модели prSetThLogParams(ThreadData, 0, UserId, 0, 'ModelID='+IntToStr(ModelID)+', pName='+pName); if (pName='') then raise EBOBError.Create(MessText(mtkEmptyName)); if CheckNotValidModel(ModelID, SysID, Model, errmess) then raise EBOBError.Create(errmess); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); Top := Stream.ReadBool; // Топ Visible := Stream.ReadBool; // видимость ReadModelParams(Stream, mps); try pOrdNum:= Stream.ReadInt; // порядковый № except pOrdNum:= -1; end; try pTDcode:= Stream.ReadInt; // Номер TecDoc (авто) / код для сайта (мото) except pTDcode:= -1; end; errmess:= Model.ModelEdit(pName, Visible, Top, UserID, mps, pOrdNum, pTDcode); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; prFree(mps); end; //=============================================================== Удалить модель procedure prModelDel(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prModelDel'; // имя процедуры/функции var UserID, ModelID, SysID: Integer; errmess: String; Model: TModelAuto; // для проверки begin Stream.Position:= 0; try UserID:= Stream.ReadInt; ModelID:= Stream.ReadInt; // Код модели prSetThLogParams(ThreadData, 0, UserId, 0, 'ModelID='+IntToStr(ModelID)); if CheckNotValidModel(ModelID, SysID, Model, errmess) then raise EBOBError.Create(errmess); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); errmess:= Cache.FDCA.Models.ModelDel(ModelID); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //==================================================== Изменить видимость модели procedure prModelSetVisible(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prModelSetVisible'; // имя процедуры/функции var UserID, ModelID, SysID: Integer; Visible: Boolean; Model: TModelAuto; errmess: string; begin Stream.Position:= 0; try UserID:= Stream.ReadInt; ModelID:= Stream.ReadInt; // Код модели Visible:= Stream.ReadBool; prSetThLogParams(ThreadData, 0, UserId, 0, 'ModelID='+IntToStr(ModelID)); if CheckNotValidModel(ModelID, SysID, Model, errmess) then raise EBOBError.Create(errmess); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); errmess:= Model.SetModelVisible(Visible); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //****************************************************************************** // Бренды //****************************************************************************** //=============================================== Получить список брендов TecDoc procedure prGetBrandsTD(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetBrandsTD'; // имя процедуры/функции var UserID: Integer; lstBrand: TStringList; begin Stream.Position:= 0; with Cache do try UserID:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, UserId); if not EmplExist(UserID) then raise EBOBError.Create(MessText(mtkNotEmplExist)); if not arEmplInfo[UserId].UserRoleExists(rolManageBrands) then raise EBOBError.Create(MessText(mtkNotRightExists)); lstBrand:= BrandTDList; if lstBrand.Count<1 then raise EBOBError.Create('Список брендов TecDoc пуст!'); Stream.Clear; Stream.WriteInt(aeSuccess); prSaveStrListWithIDToStream(lstBrand, Stream); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //****************************************************************************** // Производители //****************************************************************************** //========================== (+ Web) Получить список производителей авто/брендов procedure prGetManufacturerList(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetManufacturerList'; // имя процедуры/функции var UserID, FirmID, SysID: Integer; errmess: String; OnlyVisible, OnlyWithWares: Boolean; lst: TStringList; //---------------------------------------- procedure prSaveManufListToStream(pLst: TStringList; pTypeSys: Integer); var i, spos, icount: Integer; begin icount:= 0; spos:= Stream.Position; Stream.WriteInt(icount); for i:= 0 to pLst.Count-1 do with TManufacturer(pLst.Objects[i]) do begin if (OnlyVisible and not // если нет видимых моделей (CheckIsVisible(pTypeSys) and HasVisMLModels(pTypeSys))) then Continue; if (OnlyWithWares and not ManufHasWares) then Continue; // если нет товаров Stream.WriteInt(ID); // Код Stream.WriteStr(Name); // Наименование Stream.WriteBool(CheckIsTop(pTypeSys)); // Топ Stream.WriteBool(CheckHasModelLines(pTypeSys)); // Наличие модельных рядов по данной системе Stream.WriteBool(CheckIsTypeSys(pTypeSys)); Stream.WriteBool(CheckIsVisible(pTypeSys)); inc(icount); end; Stream.Position:= spos; Stream.WriteInt(icount); Stream.Position:= Stream.Size; end; //---------------------------------------- SysID: begin lst:= nil; // 0 - получить весь список производителей Stream.Position:= 0; // 1 - производителей авто OnlyVisible:= False; // 2 - производителей мото try // 11 - производители авто, топовые позиции вверху FirmID:= Stream.ReadInt; // 12 - производители мото, топовые позиции вверху UserID:= Stream.ReadInt; // 21 - производители с ориг.номерами SysID:= Stream.ReadInt; // 31 - производители с двигателями OnlyVisible:= Stream.ReadBool; // False - все, True - только видимые OnlyWithWares:= OnlyVisible; // False - все, True - только с товарами prSetThLogParams(ThreadData, 0, UserId, FirmID, 'SysID='+IntToStr(SysID)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); // if CheckNotValidFirmSys(FirmID, SysID, errmess) then raise EBOBError.Create(errmess); // Web ??? Stream.Clear; Stream.WriteInt(aeSuccess); with Cache.FDCA.Manufacturers do case SysID of constIsAuto, constIsMoto: prSaveManufListToStream(GetSortedList(SysID), SysID); constIsAuto+10, constIsMoto+10: prSaveManufListToStream(GetSortedListWithTops(SysID-10), SysID-10); constIsAuto+20: begin lst:= Cache.FDCA.Manufacturers.GetOEManufList; // сортированный список производителей с ОН; prSaveStrListWithIDToStream(lst, Stream); end; constIsAuto+30: begin lst:= Cache.FDCA.Manufacturers.GetEngManufList; prSaveStrListWithIDToStream(lst, Stream); end; else prSaveManufListToStream(GetSortedList(SysID), 0); end; // case except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; prFree(lst); end; //======================================================= Добавить производителя procedure prManufacturerAdd(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prManufacturerAdd'; // имя процедуры/функции var UserID, SysID, iCode: Integer; ManufName, errmess: String; isTop, isVis: boolean; begin Stream.Position:= 0; iCode:= 0; try UserID:= Stream.ReadInt; SysID:= Stream.ReadInt; ManufName:= Stream.ReadStr; // Наименование производителя isTop := Stream.ReadBool; // Топ производитель isVis := Stream.ReadBool; // видимость prSetThLogParams(ThreadData, 0, UserId, 0, 'SysID='+IntToStr(SysID)+', ManufName= '+ManufName); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); if (ManufName='') then raise EBOBError.Create(MessText(mtkEmptyName)); if not CheckTypeSys(SysID) then errmess:= MessText(mtkNotFoundTypeSys, IntToStr(SysID)); errmess:= Cache.FDCA.Manufacturers.ManufAdd(iCode, ManufName, SysID, UserID, isTop, isVis); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteInt(iCode); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //======================================================== Удалить производителя procedure prManufacturerDel(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prManufacturerDel'; // имя процедуры/функции var UserID, SysID, ManufID: Integer; errmess: String; begin Stream.Position:= 0; try UserID:= Stream.ReadInt; SysID:= Stream.ReadInt; ManufID:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, UserId, 0, 'ManufID= '+IntToStr(ManufID)); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); errmess:= Cache.FDCA.Manufacturers.ManufDel(ManufID, SysID); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteInt(ManufID); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //======================================================= Изменить производителя procedure prManufacturerEdit(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prManufacturerEdit'; // имя процедуры/функции var UserID, SysID, ManufID: Integer; ManufName, errmess: String; isTop, isVis: boolean; begin Stream.Position:= 0; try UserID:= Stream.ReadInt; ManufID:= Stream.ReadInt;; SysID:= Stream.ReadInt; ManufName:= Stream.ReadStr; // Наименование производителя isTop := Stream.ReadBool; // Топ производитель isVis := Stream.ReadBool; // Доступен пользователям prSetThLogParams(ThreadData, 0, UserId, 0, 'ManufID= '+IntToStr(ManufID)+', ManufName='+ManufName); if CheckNotValidModelManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); errmess:= Cache.FDCA.Manufacturers.ManufEdit(ManufID, SysID, UserID, isTop, isVis, ManufName); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //****************************************************************************** // Дерево узлов //****************************************************************************** //======================================================== Получить дерево узлов procedure prTNAGet(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prTNAGet'; // имя процедуры/функции var UserID, SysID, FirmID, i: Integer; errmess: String; Node: TAutoTreeNode; begin Stream.Position:= 0; try FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; SysID := Stream.ReadInt; prSetThLogParams(ThreadData, 0, UserId, FirmID); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); // if (FirmID=isWe) and CheckNotValidTNAManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); // if CheckNotValidFirmSys(FirmID, SysID, errmess) then raise EBOBError.Create(errmess); // Web Stream.Clear; Stream.WriteInt(aeSuccess); with Cache.FDCA.AutoTreeNodesSys[SysID].NodesList do begin // Запись дерева в поток Stream.WriteInt(Count); for i:= 0 to Count-1 do begin Node:= TAutoTreeNode(Objects[i]); Stream.WriteInt(Node.ID); Stream.WriteInt(Node.ParentID); Stream.WriteStr(Node.Name); Stream.WriteStr(Node.NameSys); Stream.WriteBool(Node.Visible); Stream.WriteInt(Node.MainCode); Stream.WriteBool(Node.IsEnding); end; end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //======================================================= Добавить узел в дерево procedure prTNANodeAdd(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prTNANoteAdd'; // имя процедуры/функции var UserID, ParentID, NodeID, SysID, Vis, NodeMain: Integer; NodeName, NodeNameSys, errmess: String; begin Stream.Position:= 0; try UserID:= Stream.ReadInt; SysID:= Stream.ReadInt; ParentID:= Stream.ReadInt; // Код родителя NodeName:= Trim(Stream.ReadStr); // Наименование узла NodeNameSys:= Trim(Stream.ReadStr); // Системное наименование узла Vis:= Stream.ReadInt; NodeMain:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, UserId, 0, 'NodeName= '+NodeName+ ', NodeNameSys= '+NodeNameSys+', ParentID= '+IntToStr(ParentID)); if CheckNotValidTNAManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); NodeID:= -1; errmess:= Cache.FDCA.TreeNodeAdd(SysID, ParentID, NodeMain, NodeName, NodeNameSys, UserID, NodeID, Vis=1); // Добавление узла if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteInt(NodeID); Stream.WriteStr(AnsiUpperCase(NodeNameSys)); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //================================================== редактировать узел в дереве procedure prTNANodeEdit(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prTNANodeEdit'; // имя процедуры/функции var UserID, NodeID, SysID, Vis, NodeMain: Integer; NodeName, NodeNameSys, errmess: String; Nodes: TAutoTreeNodes; begin Stream.Position:= 0; try UserID:= Stream.ReadInt; SysID:= Stream.ReadInt; NodeID:= Stream.ReadInt; NodeName:= Trim(Stream.ReadStr); NodeNameSys:= Trim(Stream.ReadStr); Vis:= Stream.ReadInt; NodeMain:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, UserId); if not CheckTypeSys(SysID) then raise EBOBError.Create(MessText(mtkNotFoundTypeSys, IntToStr(SysID))); if CheckNotValidTNAManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); Nodes:= Cache.FDCA.AutoTreeNodesSys[SysID]; errmess:= Nodes.NodeEdit(NodeID, NodeMain, Vis, UserID, NodeName, NodeNameSys); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteStr(Nodes[NodeID].NameSys); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //======================================================= Удалить узел из дерева procedure prTNANodeDel(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prTNANodeDel'; // имя процедуры/функции var UserID, NodeID, SysID: Integer; errmess: String; begin Stream.Position:= 0; try UserID:= Stream.ReadInt; SysID:= Stream.ReadInt; NodeID:= Stream.ReadInt; prSetThLogParams(ThreadData, 0, UserId); if CheckNotValidTNAManage(UserID, SysID, errmess) then raise EBOBError.Create(errmess); if not CheckTypeSys(SysID) then raise EBOBError.Create(MessText(mtkNotFoundTypeSys, IntToStr(SysID))); errmess:= Cache.FDCA.AutoTreeNodesSys[SysID].NodeDel(NodeID); if errmess<>'' then raise EBOBError.Create(errmess); Stream.Clear; Stream.WriteInt(aeSuccess); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //=================================================== Запись TStringList в поток procedure prSaveStrListWithIDToStream(const pLst: TStringList; Stream: TBoBMemoryStream); var i: Integer; begin if not Assigned(pLst) then Exit; Stream.WriteInt(pLst.Count); for i:= 0 to pLst.Count-1 do begin Stream.WriteInt(Integer(pLst.Objects[i])); Stream.WriteStr(pLst[i]); end; end; //****************************************************************************** // Двигатель //****************************************************************************** //=============================================== (+ Web) Дерево узлов двигателя procedure prGetEngineTree(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetEngineTree'; // имя процедуры/функции var UserID, FirmID, EngID, SysID, i, j, spos: Integer; flNodesWithoutWares, flHideNodesWithOneChild, flHideOnlySameName, flHideOnlyOneLevel: boolean; errmess: String; Eng: TEngine; Node: TAutoTreeNode; link: TSecondLink; listParCodes, listNodes: TList; nlinks: TLinks; begin Stream.Position:= 0; listParCodes:= nil; listNodes:= nil; nlinks:= nil; try try FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; EngID:= Stream.ReadInt; // код двигателя flNodesWithoutWares:= Stream.ReadBool; // признак - передавать ноды без товаров flHideNodesWithOneChild:= not flNodesWithoutWares; // сворачивать ноды с 1 ребенком flHideOnlyOneLevel:= flHideNodesWithOneChild and Cache.HideOnlyOneLevel; // сворачивать только 1 уровень flHideOnlySameName:= flHideNodesWithOneChild and Cache.HideOnlySameName; // сворачивать только при совпадении имен prSetThLogParams(ThreadData, 0, UserId, FirmID, 'EngID='+IntToStr(EngID)); if CheckNotValidUser(UserID, FirmID, errmess) then raise EBOBError.Create(errmess); SysID:= constIsAuto; if CheckNotValidFirmSys(FirmID, SysID, errmess) then raise EBOBError.Create(errmess); // Web if not Cache.FDCA.Engines.ItemExists(EngID) then raise EBOBError.Create(MessText(mtkNotFoundEngine, IntToStr(EngID))); Eng:= Cache.FDCA.Engines.GetEngine(EngID); if not Assigned(Eng) then raise EBOBError.Create(MessText(mtkNotFoundEngine, IntToStr(EngID))); nlinks:= Eng.GetNodesLinks; if nlinks.LinkCount<1 then raise EBOBError.Create(MessText(mtkNotFoundNodes)); listNodes:= TList.Create; // список линков для обработки listNodes.Capacity:= nlinks.LinkCount; for i:= 0 to nlinks.LinkCount-1 do listNodes.Add(nlinks.ListLinks[i]); if not flNodesWithoutWares then // чистим ноды без товаров for i:= listNodes.Count-1 downto 0 do begin link:= listNodes[i]; if not link.NodeHasWares then listNodes.Delete(i); end; if listNodes.Count<1 then raise EBOBError.Create(MessText(mtkNotFoundNodes)); listParCodes:= TList.Create; listParCodes.Capacity:= listNodes.Count; for i:= 0 to listNodes.Count-1 do begin // список кодов родителей link:= listNodes[i]; Node:= link.LinkPtr; listParCodes.Add(Pointer(Node.ParentID)); end; if flHideNodesWithOneChild then // сворачиваем ноды с 1-м ребенком prHideTreeNodes(listNodes, listParCodes, flHideOnlySameName, flHideOnlyOneLevel); if listNodes.Count<1 then raise EBOBError.Create(MessText(mtkNotFoundNodes)); Stream.Clear; Stream.WriteInt(aeSuccess); // Запись дерева двигателя в поток Stream.WriteStr(Eng.WebName); // Запись названия двигателя в поток j:= 0; // счетчик строк spos:= Stream.Position; Stream.WriteInt(j); for i:= 0 to listNodes.Count-1 do if Assigned(listNodes[i]) then begin link:= listNodes[i]; Node:= link.LinkPtr; Stream.WriteInt(Node.ID); Stream.WriteInt(Integer(listParCodes[i])); Stream.WriteStr(Node.Name); Stream.WriteBool(link.IsLinkNode); if link.IsLinkNode then begin Stream.WriteDouble(link.Qty); Stream.WriteStr(Cache.GetMeasName(Node.MeasID)); Stream.WriteBool(link.NodeHasFilters); // признак наличия фильтров в узле двигателя end; inc(j); end; Stream.Position:= spos; Stream.WriteInt(j); // кол-во переданных элементов except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; finally prFree(listNodes); prFree(listParCodes); prFree(nlinks); end; Stream.Position:= 0; end; //======================================================== разблокировка клиента procedure prUnblockWebUser(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prUnblockWebUser'; // имя процедуры/функции var EmplID, FirmID, UserID, i: integer; errmess, s, regMail, sParam: String; WebUser: TClientInfo; Body: TStringList; Empl: TEmplInfoItem; BlockTime: TDateTime; begin Stream.Position:= 0; WebUser:= nil; Empl:= nil; try FirmID:= isWe; EmplID:= Stream.ReadInt; UserID:= Stream.ReadInt; sParam:= 'WebUserID='+IntToStr(UserID); try if CheckNotValidUser(EmplID, FirmID, errmess) then raise EBOBError.Create(errmess); if not Cache.ClientExist(UserID) then raise EBOBError.Create(MessText(mtkNotClientExist)); WebUser:= Cache.arClientInfo[UserID]; FirmID:= WebUser.FirmID; if not Cache.FirmExist(FirmID) then raise EBOBError.Create(MessText(mtkNotFirmExists)); empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolManageSprav) then // только админы raise EBOBError.Create(MessText(mtkNotRightExists)); if not WebUser.Blocked then raise EBOBError.Create('пользователь не блокирован'); if not SaveClientBlockType(cbUnBlockedByEmpl, UserID, BlockTime, EmplID) then // разблокировка клиента в базе raise EBOBError.Create('ошибка разблокировки клиента'); // ключевой текст разблокировки (для GetUserSearchCount) ??? sParam:= sParam+#13#10'WebUser '+IntToStr(UserID)+' unblocked'; finally prSetThLogParams(ThreadData, 0, EmplID, 0, sParam); end; with WebUser do try // в кеше CS_client.Enter; Blocked:= False; CountSearch:= 0; CountQty:= 0; CountConnect:= 0; finally CS_client.Leave; end; //------------------------------------------ рассылаем извещения о разблокировке Body:= TStringList.Create; with Cache do try //---------------------------------- по списку рассылки regMail:= ''; Body.Add(FormatDateTime(cDateTimeFormatY4S, Now())+' разблокирована'); Body.Add(' сотрудником '+empl.EmplShortName); Body.Add(' учетная запись в системе заказов'); Body.Add('пользователя с логином <'+WebUser.Login+'> (код '+IntToStr(WebUser.ID)+')'); Body.Add(' контрагент '+WebUser.FirmName); if FirmExist(FirmID) then begin s:= arFirmInfo[FirmID].GetFirmManagersString([fmpName, fmpShort, fmpPref]); if (s<>'') then Body.Add(' '+s); end; regMail:= Cache.GetConstEmails(pcEmpl_list_UnBlock, errmess, FirmID); if regMail='' then // в s запоминаем строку в письмо контролю s:= 'Сообщение о разблокировке клиента не отправлено - не найдены адреса рассылки' else begin s:= n_SysMailSend(regMail, 'Разблокировка учетной записи пользователя', Body, nil, '', '', True); if (s<>'') and (Pos(MessText(mtkErrMailToFile), s)>0) then begin // если не записалось в файл fnWriteToLog(ThreadData, lgmsSysError, nmProc+'(send mail to empls)', 'ошибка рассылки', s, ''); s:= 'Ошибка отправки сообщения о разблокировке клиента на Email: '+regMail; end else s:= 'Сообщение о разблокировке клиента отправлено на Email: '+regMail; end; //-------------------------- контролю (Щербакову) if s<>'' then Body.Add(#10+s); if errmess<>'' then Body.Add(#10+errmess); // сообщение о ненайденных адресах regMail:= Cache.GetConstEmails(pcBlockMonitoringEmpl, errmess, FirmID); if errmess<>'' then Body.Add(errmess); if regMail='' then regMail:= GetSysTypeMail(constIsAuto); // Щербакову (на всяк.случай) if regMail<>'' then begin s:= n_SysMailSend(regMail, 'Разблокировка учетной записи пользователя', Body, nil, '', '', True); if (s<>'') and (Pos(MessText(mtkErrMailToFile), s)>0) then prMessageLOGS(nmProc+'(send mail to Monitoring): '+s); end; prMessageLOGS(nmProc+': разблокировка клиента'); // пишем в лог for i:= 0 to Body.Count-1 do if trim(Body[i])<>'' then prMessageLOGS(StringReplace(Body[i], #10, '', [rfReplaceAll])); except on E: Exception do fnWriteToLog(ThreadData, lgmsSysError, nmProc, 'ошибка рассылки', E.Message, ''); end; prFree(Body); Stream.Clear; Stream.WriteInt(aeSuccess); except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //================================== список сопутствующих товаров (Web & WebArm) procedure prGetWareSatellites(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetWareSatellites'; // имя процедуры/функции var UserID, FirmID, WareID, currID, ForFirmID, Sys, j, arlen, contID: integer; wCodes: Tai; PriceInUah: boolean; begin Sys:= 0; Stream.Position:= 0; SetLength(wCodes, 0); try UserID:= Stream.ReadInt; FirmID:= Stream.ReadInt; WareID:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; ContID:= Stream.ReadInt; // для контрактов PriceInUah:= Stream.ReadBool; prSetThLogParams(ThreadData, 0, UserID, FirmID, 'WareID='+IntToStr(WareID)+ #13#10'ForFirmID='+IntToStr(ForFirmID)); // логирование if not Cache.WareExist(WareID) then raise EBOBError.Create(MessText(mtkNotFoundWare, IntToStr(WareID))); // проверить UserID, FirmID, ForFirmID и получить систему, валюту prCheckUserForFirmAndGetSysCurr(UserID, FirmID, ForFirmID, Sys, CurrID, PriceInUah, contID); wCodes:= Cache.GetWare(WareID).GetSatellites(Sys); arlen:= Length(wCodes); Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteInt(arlen); // кол-во строк товаров for j:= 0 to High(wCodes) do prSaveShortWareInfoToStream(Stream, wCodes[j], FirmID, UserID, 0, currID, ForFirmID, 0, contID); PriceInUah:= ((FirmID<>IsWe) or (ForFirmID>0)) and (arlen>0) // здесь PriceInUah использ.как флаг and (arlen<=Cache.GetConstItem(pcOrderWareSemaforLimit).IntValue); Stream.WriteBool(PriceInUah); // нужно ли запрашивать остатки // блок отправки инфы о наличии привязанных моделей +++ prSaveWaresModelsExists(Stream, Sys, wCodes); // блок отправки инфы о наличии привязанных моделей --- except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; SetLength(wCodes, 0); end; //=============================================== список аналогов (Web & WebArm) procedure prGetWareAnalogs(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetWareAnalogs'; // имя процедуры/функции var i, arlen, UserId, WareID, WhatShow, FirmID, currID, ForFirmID, Sys, contID: integer; wCodes: Tai; PriceInUah: boolean; begin Sys:= 0; Stream.Position:= 0; SetLength(wCodes, 0); try UserID:= Stream.ReadInt; FirmID:= Stream.ReadInt; WareID:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; ContID:= Stream.ReadInt; // для контрактов PriceInUah:= Stream.ReadBool; WhatShow:= Stream.ReadByte; prSetThLogParams(ThreadData, 0, UserId, FirmID, 'WareID='+IntToStr(WareID)+#13#10+ #13#10'ForFirmID='+IntToStr(ForFirmID)+'WhatShow='+IntToStr(WhatShow)); // логирование // проверить UserID, FirmID, ForFirmID и получить систему, валюту prCheckUserForFirmAndGetSysCurr(UserID, FirmID, ForFirmID, Sys, CurrID, PriceInUah, contID); if WhatShow=constThisIsOrNum then begin if not Cache.FDCA.OrigNumExist(WareID) then raise EBOBError.Create(MessText(mtkNotFoundOrNum)); wCodes:= Cache.FDCA.arOriginalNumInfo[WareID].arAnalogs; if (Sys>0) then for i:= High(wCodes) downto 0 do // отсев по системе if not Cache.WareExist(wCodes[i]) or not Cache.GetWare(wCodes[i]).CheckWareTypeSys(Sys) then prDelItemFromArray(i, wCodes); end else begin if not Cache.WareExist(WareID) then raise EBOBError.Create(MessText(mtkNotFoundWare, IntToStr(WareID))); wCodes:= fnGetAllAnalogs(WareID, -1, Sys); end; Stream.Clear; Stream.WriteInt(aeSuccess); arlen:= Length(wCodes); Stream.WriteInt(arlen); // кол-во аналогов; for i:= 0 to High(wCodes) do prSaveShortWareInfoToStream(Stream, wCodes[i], FirmID, UserId, 0, currID, ForFirmID, 0, contID); PriceInUah:= ((FirmID<>IsWe) or (ForFirmID>0)) and (arlen>0) // здесь PriceInUah использ.как флаг and (arlen<=Cache.GetConstItem(pcOrderWareSemaforLimit).IntValue); Stream.WriteBool(PriceInUah); // нужно ли запрашивать остатки // блок отправки инфы о наличии привязанных моделей +++ prSaveWaresModelsExists(Stream, Sys, wCodes); // блок отправки инфы о наличии привязанных моделей --- except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; SetLength(wCodes, 0); end; //================================================= поиск товаров (Web & WebArm) procedure prCommonWareSearch(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prCommonWareSearch'; // имя процедуры/функции var Template, s, InnerErrorPos, ss, sParam: string; UserId, FirmID, currID, ForFirmID, FirmSys, i, j, arlen, arlen1, CountAll, CountWares, CountON, contID: integer; IgnoreSpec: byte; ShowAnalogs, NeedGroups, NotWasGroups, PriceInUah, flAUTO, flMOTO, flSale, flCutPrice, flLamp, flSpecSearch: boolean; aiOrNums, aiWareByON, TypesI, arTotalWares: Tai; // TypesS: Tas; OrigNum: TOriginalNumInfo; OList, WList: TObjectList; WareAndAnalogs: TWareAndAnalogs; begin Stream.Position:= 0; WList:= nil; SetLength(aiOrNums, 0); SetLength(TypesI, 0); SetLength(arTotalWares, 0); SetLength(aiWareByON, 0); OList:= TObjectList.Create; FirmSys:= 0; flSale:= False; flCutPrice:= False; CountON:= 0; try InnerErrorPos:='0'; UserId:= Stream.ReadInt; FirmId:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; ContID:= Stream.ReadInt; // для контрактов Template:= Stream.ReadStr; IgnoreSpec:= Stream.ReadByte; PriceInUah:= Stream.ReadBool; Template:= trim(Template); if Length(Template)<1 then raise EBOBError.Create('Не задан шаблон поиска'); // логирование в ib_css - формат НЕ ТРОГАТЬ, обрабатывается в базе !!! sParam:= 'Template='+Template+#13#10+'IgnoreSpec='+IntToStr(IgnoreSpec); try //------------------------------------------------------------- спец.виды поиска flLamp:= (IgnoreSpec=coLampBaseIgnoreSpec); // подбор по лампам if flLamp then IgnoreSpec:= 0 // обнуляем признак ламп else begin s:= AnsiUpperCase(Template); flSale := (s=cTemplateSale); // РАСПРОДАЖА flCutPrice:= (s=cTemplateCutPrice); // УЦЕНКА if not (IgnoreSpec in [1, 2]) then IgnoreSpec:= 0; // пока IgnoreSpec=3 не работает end; flSpecSearch:= (flSale or flCutPrice or flLamp); // признак спец.поиска //------------------------------------------------------------- InnerErrorPos:='1'; if flLamp then // добавляем в перечень типы товара ЛАМПА и т.п. s:= Cache.GetConstItem(pcWareTypeLampCodes).StrValue else s:= Stream.ReadStr; // получаем перечень типов товаров, выбранных пользователем if (s<>'') then for ss in fnSplitString(S, ',') do begin j:= StrToIntDef(ss, -1); if j>-1 then prAddItemToIntArray(j, TypesI); end; InnerErrorPos:='2'; // проверить UserID, FirmID, ForFirmID и получить систему, валюту prCheckUserForFirmAndGetSysCurr(UserID, FirmID, ForFirmID, FirmSys, CurrID, PriceInUah, contID); flAUTO:= (FirmSys in [0, constIsAuto]); flMOTO:= (FirmSys in [0, constIsMoto]); NotWasGroups:= (Length(TypesI)=0); // запоминаем, передавались ли группы, т.к. массив переопределится WList:= SearchWaresTypesAnalogs(Template, TypesI, IgnoreSpec, -1, flAUTO, flMOTO, false, true, flSale, flCutPrice, flLamp); CountWares:= WList.Count; if NotWasGroups then begin for i:= 0 to High(TypesI) do prAddWareType(OList, TypesI[i]); SetLength(TypesI, 0); end; InnerErrorPos:='3'; if flAUTO and not flSpecSearch then begin // только для АВТО и обычного поиска aiOrNums:= Cache.FDCA.SearchWareOrigNums(Template, IgnoreSpec, True, TypesI); CountON:= Length(aiOrNums); end; CountAll:= CountON+CountWares; if (CountAll<1) then begin s:= 'Не найдены '; if flSale then s:= s+'товары распродажи' // поиск по распродаже else if flCutPrice then s:= s+'уцененные товары' // поиск по уценке else if flLamp then s:= s+'лампы с параметрами '+Template // поиск по лампам else s:= s+'товары/оригинальные номера по шаблону '+Template; // поиск по шаблону raise EBOBError.Create(s); end; InnerErrorPos:='4'; NeedGroups:= NotWasGroups and (CountAll>Cache.GetConstItem(pcSearchCountTypeAsk).IntValue); if NeedGroups then for i:= 0 to length(TypesI)-1 do prAddWareType(OList, TypesI[i]); NeedGroups:= NeedGroups and (OList.Count>1); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteBool(NeedGroups); if NeedGroups then begin //------------------------------- если нужны группы InnerErrorPos:='5'; OList.Sort(@CompareTypeNamesForTwoCodes); Stream.WriteInt(CountAll); Stream.WriteInt(OList.Count); for I:= 0 to OList.Count-1 do begin j:= TTwoCodes(OList[i]).ID1; Stream.WriteInt(j); Stream.WriteStr(Cache.GetWareTypeName(j)); end; end else begin //----------------------------------------- если нужны товары InnerErrorPos:='6'; Stream.WriteStr(Cache.GetCurrName(currID)); ShowAnalogs:= (FirmID<>IsWe) and (CountAll<Cache.arClientInfo[UserID].MaxRowShowAnalogs); Stream.WriteBool(ShowAnalogs); Stream.WriteInt(CountWares); // Передаем товары for i:= 0 to CountWares-1 do begin InnerErrorPos:='7-'+IntToStr(i); WareAndAnalogs:= TWareAndAnalogs(WList[i]); arlen:= Length(WareAndAnalogs.arAnalogs); arlen1:= Length(WareAndAnalogs.arSatells); prSaveShortWareInfoToStream(Stream, WareAndAnalogs.WareID, FirmId, UserId, arlen, currID, ForFirmID, arlen1, contID); prAddItemToIntArray(WareAndAnalogs.WareID, arTotalWares); if ShowAnalogs then for j:= 0 to High(WareAndAnalogs.arAnalogs) do begin prSaveShortWareInfoToStream(Stream, WareAndAnalogs.arAnalogs[j], FirmId, UserId, 0, currID, ForFirmID, 0, contID); prAddItemToIntArray(WareAndAnalogs.arAnalogs[j], arTotalWares); end; end; Stream.WriteInt(CountON); // Передаем оригинальные номера for i:= 0 to High(aiOrNums) do begin InnerErrorPos:='8-'+IntToStr(i); OrigNum:= Cache.FDCA.arOriginalNumInfo[aiOrNums[i]]; Stream.WriteInt(OrigNum.ID); Stream.WriteInt(OrigNum.MfAutoID); Stream.WriteStr(OrigNum.ManufName); Stream.WriteStr(OrigNum.OriginalNum); Stream.WriteStr(OrigNum.CommentWWW); if ShowAnalogs then begin SetLength(aiWareByON, 0); aiWareByON:= OrigNum.arAnalogs; Stream.WriteInt(Length(aiWareByON)); // кол-во аналогов for j:= 0 to High(aiWareByON) do begin prSaveShortWareInfoToStream(Stream, aiWareByON[j], FirmId, UserId, 0, currID, ForFirmID, 0, contID); prAddItemToIntArray(aiWareByON[j], arTotalWares); end; SetLength(aiWareByON, 0); end; end; CountAll:= Length(arTotalWares); PriceInUah:= ((FirmID<>IsWe) or (ForFirmID>0)) and (CountAll>0) // здесь PriceInUah использ.как флаг and (CountAll<=Cache.GetConstItem(pcOrderWareSemaforLimit).IntValue); Stream.WriteBool(PriceInUah); // нужно ли запрашивать остатки InnerErrorPos:='9-1'; // блок отправки инфы о наличии привязанных моделей +++ prSaveWaresModelsExists(Stream, FirmSys, arTotalWares); // блок отправки инфы о наличии привязанных моделей --- end; sParam:= sParam+#13#10'WareQty='+IntToStr(CountWares)+#13#10'OEQty='+IntToStr(CountON); finally prSetThLogParams(ThreadData, 0, UserID, FirmID, sParam); // логирование end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, 'InnerErrorPos='+InnerErrorPos, False); end; Stream.Position:= 0; SetLength(aiOrNums, 0); SetLength(aiWareByON, 0); SetLength(arTotalWares, 0); SetLength(TypesI, 0); // SetLength(TypesS, 0); prFree(OList); prFree(WList); end; //=============================== вывод семафоров наличия товаров (Web & WebArm) procedure prCommonGetRestsOfWares(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prCommonGetRestsOfWares'; // имя процедуры/функции var UserId, FirmID, NodeID, ModelID, WareCode, iCount, i, j, iSem, ForFirmID, iPos, FirmSys, CurrID, ContID: integer; WareCodes: string; First: Tas; Second, StorageCodes: Tai; Ware: TWareInfo; Firm: TFirmInfo; Contract: TContract; flAdd: boolean; OList: TObjectList; begin Stream.Position:= 0; SetLength(First, 0); SetLength(StorageCodes, 0); OList:= nil; try UserId:= Stream.ReadInt; FirmId:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; ContID:= Stream.ReadInt; // для контрактов ModelID:= Stream.ReadInt; NodeID:= Stream.ReadInt; WareCodes:= Stream.ReadStr; prSetThLogParams(ThreadData, 0, UserID, FirmID, 'WareCodes='+WareCodes+ // логирование ' ModelID='+IntToStr(ModelID)+' NodeID='+IntToStr(NodeID)+' ForFirmID='+IntToStr(ForFirmID)); if WareCodes='' then Exit; iCount:= 0; Stream.Clear; Stream.WriteInt(aeSuccess); iPos:= Stream.Position; Stream.WriteInt(iCount); if (FirmID<>IsWe) then ForFirmID:= FirmID else if (ForFirmID<1) then Exit; // не надо передавать при ForFirmID<1 First:= fnSplitString(WareCodes, ','); if Length(First)>Cache.GetConstItem(pcOrderWareSemaforLimit).IntValue then raise EBOBError.Create('Слишком много товаров для проверки наличия'); Firm:= Cache.arFirmInfo[ForFirmID]; Contract:= Firm.GetContract(ContID); flAdd:= flClientStoragesView_add and Contract.HasAddVis; // проверить UserID, FirmID, ForFirmID и получить систему, валюту prCheckUserForFirmAndGetSysCurr(UserID, FirmID, ForFirmID, FirmSys, CurrID, False, ContID); SetLength(Second, 0); for i:= 0 to High(First) do begin WareCode:= StrToIntDef(trim(First[i]), 0); if (WareCode>0) and Cache.WareExist(WareCode) then begin Ware:= Cache.GetWare(WareCode); if Ware.IsMarketWare(ForFirmID, contID) then prAddItemToIntArray(WareCode, Second); end; end; if (Length(Second)>0) then begin for i:= 0 to High(Contract.ContStorages) do with Contract.ContStorages[i] do if IsVisible or (flAdd and IsAddVis) then prAddItemToIntArray(DprtId, StorageCodes); for i:= 0 to High(Second) do begin iSem:= 0; OList:= Cache.GetWareRestsByStores(Second[i]); try for j:= 0 to OList.Count-1 do with TCodeAndQty(OList[j]) do if ((fnInIntArray(ID, StorageCodes)>-1) and (Qty>constDeltaZero)) then begin iSem:= 2; break; end; finally prFree(OList); end; Stream.Writeint(Second[i]); Stream.Writeint(iSem); Inc(iCount); end; end; if iCount>0 then begin Stream.Position:= iPos; Stream.Writeint(iCount); end; except on E: Exception do begin Stream.Clear; Stream.WriteInt(aeSuccess); // просто ничего не красим Stream.WriteInt(0); end; end; Stream.Position:= 0; SetLength(First, 0); SetLength(Second, 0); SetLength(StorageCodes, 0); end; //======================================== список товаров по узлу (Web & WebArm) procedure prCommonGetNodeWares(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prCommonGetNodeWares'; // имя процедуры/функции var UserId, NodeId, ModelId, FirmId, Position, i, j, WareCount, aCount, sCount, ForFirmID, Sys, CurrID, WareID, contID: integer; ShowChildWares, IsEngine, flag, PriceInUAH, flWebarm, ShowAnalogs: boolean; aiWares, aar, aar1, arTotalWares: Tai; Model: TModelAuto; StrPos, filter, NodeName: string; List: TStringList; Engine: TEngine; empl: TEmplInfoItem; begin Stream.Position:= 0; Engine:= nil; Model:= nil; List:= nil; empl:= nil; SetLength(arTotalWares, 0); try FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; NodeID:= Stream.ReadInt; ModelID:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; ContID:= Stream.ReadInt; // для контрактов ShowChildWares:= Stream.ReadBool; IsEngine:= Stream.ReadBool; PriceInUAH:= Stream.ReadBool; filter:= Stream.ReadStr; StrPos:='0'; prSetThLogParams(ThreadData, 0, UserID, FirmID, 'Node='+IntToStr(NodeID)+ // логирование #13#10'Model='+IntToStr(ModelID)+#13#10'Filter='+(Filter)+ #13#10'IsEngine='+fnIfStr(IsEngine, '1', '0')+#13#10'ForFirmID='+IntToStr(ForFirmID)); StrPos:='1'; // проверить UserID, FirmID, ForFirmID и получить систему, валюту prCheckUserForFirmAndGetSysCurr(UserID, FirmID, ForFirmID, Sys, CurrID, PriceInUah, contID); StrPos:='2'; // if not Cache.WareLinksUnLocked then // raise EBOBError.Create(MessText(mtkFuncNotEnable)); if IsEngine then begin //--------- двигатель if (Sys=0) then Sys:= constIsAuto; if Sys<>constIsAuto then raise EBOBError.Create(MessText(mtkNotFoundWares)); if not Cache.FDCA.Engines.ItemExists(ModelID) then raise EBOBError.Create(MessText(mtkNotFoundEngine)); Engine:= Cache.FDCA.Engines[ModelID]; end else begin //--------- модель if not Cache.FDCA.Models.ModelExists(ModelID) then raise EBOBError.Create(MessText(mtkNotFoundModel)); Model:= Cache.FDCA.Models.GetModel(ModelID); if Sys<>Model.TypeSys then Sys:= Model.TypeSys; end; if not Cache.FDCA.AutoTreeNodesSys[Sys].NodeExists(NodeID) then raise EBOBError.Create(MessText(mtkNotFoundNode)); flWebArm:= (FirmId=IsWe); if flWebArm then empl:= Cache.arEmplInfo[UserId]; StrPos:='3'; Stream.Clear; Stream.WriteInt(aeSuccess); if IsEngine then begin //--------- двигатель Stream.WriteInt(31); Stream.WriteStr(Engine.WebName); // Признак того, что пользователь WebArm может удалять товар из связки 3 flag:= flWebArm and empl.UserRoleExists(rolTNAManageAuto); StrPos:='4-1'; List:= Engine.GetEngNodeWaresWithUsesByFilters(NodeID, ShowChildWares, Filter); end else begin //--------- модель Stream.WriteInt(Sys); Stream.WriteStr(Model.WebName); // Признак того, что пользователь WebArm может удалять товар из связки 3 flag:= flWebArm and Cache.WareLinksUnLocked and Model.GetModelNodeIsSecondLink(NodeID) and (((Sys=constIsMoto) and empl.UserRoleExists(rolTNAManageMoto)) or ((Sys=constIsAuto) and empl.UserRoleExists(rolTNAManageAuto))); StrPos:='4-2'; List:= Cache.GetModelNodeWaresWithUsesByFilters(ModelID, NodeID, ShowChildWares, Filter); end; WareCount:= List.Count; if (WareCount<1) then raise EBOBError.Create(MessText(mtkNotFoundWares)); StrPos:='4-3'; NodeName:= Cache.FDCA.AutoTreeNodesSys[Sys][NodeID].Name; SetLength(aiWares, WareCount); for i:= 0 to WareCount-1 do aiWares[i]:= integer(List.Objects[i]); StrPos:='5'; Stream.WriteBool(flag); Stream.WriteStr(NodeName); Stream.WriteStr(Filter); Stream.WriteStr(Cache.GetCurrName(CurrID)); ShowAnalogs:= not flWebarm and (WareCount<Cache.arClientInfo[UserID].MaxRowShowAnalogs); Stream.WriteBool(ShowAnalogs); Stream.WriteInt(WareCount); for i:= 0 to WareCount-1 do try // Передаем товары WareID:= aiWares[i]; aar:= fnGetAllAnalogs(WareID, -1, Sys); aCount:= Length(aar); // кол-во аналогов aar1:= Cache.GetWare(WareID).GetSatellites(Sys); sCount:= Length(aar1); // кол-во сопут.товаров prSaveShortWareInfoToStream(Stream, WareID, FirmId, UserId, aCount, CurrID, ForFirmID, sCount, contID); prAddItemToIntArray(WareID, arTotalWares); if ShowAnalogs then for j:= 0 to High(aar) do begin prSaveShortWareInfoToStream(Stream, aar[j], FirmId, UserId, 0, currID, ForFirmID, 0, contID); prAddItemToIntArray(aar[j], arTotalWares); end; finally SetLength(aar, 0); SetLength(aar1, 0); end; StrPos:='10'; //------------------------------------------------------------------------ aCount:= 0; // Доп.инфо о применимости товаров к моделям Position:= Stream.Position; Stream.WriteInt(aCount); for i:= 0 to List.Count-1 do if (List.Strings[i]<>'') then begin Stream.WriteInt(Integer(List.Objects[i])); Stream.WriteStr(List.Strings[i]); Inc(aCount); end; Stream.Position:= Position; Stream.WriteInt(aCount); Stream.Position:= Stream.Size; PriceInUah:= (not flWebarm or (ForFirmID>0)) and (WareCount>0) // здесь PriceInUah использ.как флаг and (WareCount<=Cache.GetConstItem(pcOrderWareSemaforLimit).IntValue); Stream.WriteBool(PriceInUah); // нужно ли запрашивать остатки StrPos:='15'; // блок отправки инфы о наличии привязанных моделей +++ prSaveWaresModelsExists(Stream, Sys, arTotalWares); // блок отправки инфы о наличии привязанных моделей --- except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, 'StrPos='+StrPos, True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, 'StrPos='+StrPos, False); end; Stream.Position:= 0; SetLength(aiWares, 0); SetLength(arTotalWares, 0); prFree(List); end; //========================== поиск товаров по значениям атрибутов (Web & WebArm) procedure prCommonSearchWaresByAttr(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prCommonSearchWaresByAttr'; // имя процедуры/функции var UserID, FirmID, pCount, i, j, ForFirmID, FirmSys, CurrID, sCount, contID: Integer; attCodes, valCodes, aar: Tai; PriceInUAH: boolean; begin Stream.Position:= 0; currID:= 0; try FirmID:= Stream.ReadInt; UserID:= Stream.ReadInt; pCount:= Stream.ReadInt; // кол-во атрибутов prSetThLogParams(ThreadData, 0, UserId, FirmID, 'pCount='+IntToStr(pCount)); if pCount<1 then raise EBOBError.Create(MessText(mtkNotParams)); SetLength(attCodes, pCount); SetLength(valCodes, pCount); for i:= 0 to pCount-1 do begin attCodes[i]:= Stream.ReadInt; valCodes[i]:= Stream.ReadInt; end; PriceInUAH:= Stream.ReadBool; ForFirmID:= Stream.ReadInt; // new !!! ContID:= Stream.ReadInt; // для контрактов // проверить UserID, FirmID, ForFirmID и получить систему, валюту prCheckUserForFirmAndGetSysCurr(UserID, FirmID, ForFirmID, FirmSys, CurrID, PriceInUah, contID); attCodes:= Cache.SearchWaresByAttrValues(attCodes, valCodes); if (FirmSys>0) then for i:= High(attCodes) downto 0 do // отсев по системе if not Cache.GetWare(attCodes[i]).CheckWareTypeSys(FirmSys) then prDelItemFromArray(i, attCodes); j:= Length(attCodes); if j<1 then raise EBOBError.Create(MessText(mtkNotFoundWares)); Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteStr(Cache.GetCurrName(currID)); Stream.WriteBool(false); // Чисто для совместимости Stream.WriteInt(j); // Передаем товары for i:= 0 to j-1 do try aar:= Cache.GetWare(attCodes[i]).GetSatellites(FirmSys); sCount:= Length(aar); // кол-во сопут.товаров prSaveShortWareInfoToStream(Stream, attCodes[i], FirmID, UserID, 0, currID, ForFirmID, sCount, contID); finally SetLength(aar, 0); end; PriceInUah:= ((FirmId<>IsWe) or (ForFirmID>0)) and (j>0) // здесь PriceInUah использ.как флаг and (j<=Cache.GetConstItem(pcOrderWareSemaforLimit).IntValue); Stream.WriteBool(PriceInUah); // нужно ли запрашивать остатки //--------------------- блок отправки инфы о наличии привязанных моделей +++ prSaveWaresModelsExists(Stream, FirmSys, attCodes); //--------------------- блок отправки инфы о наличии привязанных моделей --- except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; SetLength(attCodes, 0); SetLength(valCodes, 0); SetLength(aar, 0); Stream.Position:= 0; end; //================================ поиск товаров по оригин.номеру (Web & WebArm) procedure prCommonGetWaresByOE(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prCommonGetWaresByOE'; // имя процедуры/функции var UserId, FirmId, i, j, ManufID, arlen, arlen1, ForFirmID, Sys, CurrID, wareID, iCount, contID: integer; Manuf, OE: string; ErrorPos: string; aiWareByON, aiAnalogs, aiSatells, arTotalWares: Tai; PriceInUah, ShowAnalogs: boolean; begin Stream.Position:= 0; SetLength(aiWareByON, 0); SetLength(arTotalWares, 0); try UserID:= Stream.ReadInt; FirmID:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; // new !!! ContID:= Stream.ReadInt; // для контрактов PriceInUah:= Stream.ReadBool; Manuf:= AnsiUpperCase(Stream.ReadStr); OE:= Stream.ReadStr; ErrorPos:='00'; prSetThLogParams(ThreadData, 0, UserId, FirmID, ''); // проверить UserID, FirmID, ForFirmID и получить систему, валюту prCheckUserForFirmAndGetSysCurr(UserID, FirmID, ForFirmID, Sys, CurrID, PriceInUah, contID); ErrorPos:='05'; if not Cache.FDCA.Manufacturers.ManufExistsByName(Manuf, ManufID) then raise EBOBError.Create(MessText(mtkNotFoundManuf, Manuf)); if (Sys>0) and not Cache.FDCA.Manufacturers[ManufID].CheckIsTypeSys(Sys) then raise EBOBError.Create(MessText(mtkNotSysManuf, intToStr(Sys))); ErrorPos:='10'; i:= Cache.FDCA.SearchOriginalNum(ManufID, fnDelSpcAndSumb(OE)); if i=-1 then raise EBOBError.Create(MessText(mtkNotFoundOrNum)+' "'+OE+'"'); aiWareByON:= Cache.FDCA.arOriginalNumInfo[i].arAnalogs; // товары к ОН if (Sys>0) then for i:= High(aiWareByON) downto 0 do // отсев по системе if not Cache.GetWare(aiWareByON[i]).CheckWareTypeSys(Sys) then prDelItemFromArray(i, aiWareByON); iCount:= Length(aiWareByON); if (iCount<1) then raise EBOBError.Create(MessText(mtkNotFoundWares)+ ' с оригинальным номером "'+OE+'"'); ErrorPos:='15'; Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteStr(Cache.GetCurrName(CurrID)); ShowAnalogs:= (FirmID<>IsWe) and (iCount<=Cache.arClientInfo[UserID].MaxRowShowAnalogs); Stream.WriteBool(ShowAnalogs); Stream.WriteInt(iCount); // кол-во аналогов for i:= 0 to High(aiWareByON) do try wareID:= aiWareByON[i]; aiAnalogs:= fnGetAllAnalogs(wareID, -1, Sys); arlen:= Length(aiAnalogs); aiSatells:= Cache.GetWare(wareID).GetSatellites(Sys); arlen1:= Length(aiSatells); // кол-во сопут.товаров prSaveShortWareInfoToStream(Stream, wareID, FirmID, UserID, arlen, CurrID, ForFirmID, arlen1, contID); prAddItemToIntArray(wareID, arTotalWares); if ShowAnalogs then for j:= 0 to High(aiAnalogs) do begin prSaveShortWareInfoToStream(Stream, aiAnalogs[j], FirmID, UserID, 0, CurrID, ForFirmID, 0, contID); prAddItemToIntArray(wareID, arTotalWares); end; finally SetLength(aiAnalogs, 0); SetLength(aiSatells, 0); end; j:= length(arTotalWares); PriceInUah:= ((FirmId<>IsWe) or (ForFirmID>0)) and (j>0) // здесь PriceInUah использ.как флаг and (j<=Cache.GetConstItem(pcOrderWareSemaforLimit).IntValue); Stream.WriteBool(PriceInUah); // нужно ли запрашивать остатки ErrorPos:='20'; //--------------------- блок отправки инфы о наличии привязанных моделей +++ prSaveWaresModelsExists(Stream, Sys, arTotalWares); //--------------------- блок отправки инфы о наличии привязанных моделей --- except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; SetLength(aiWareByON, 0); SetLength(arTotalWares, 0); end; //======================================================= передать реквизиты к/а procedure prWebArmGetFirmInfo(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetFirmInfo'; // имя процедуры/функции var EmplID, ForFirmID, LineCount, sPos, k, i, ContID: integer; errmess: string; firm: TFirmInfo; Contract: TContract; begin Stream.Position:= 0; ContID:= 0; try EmplID:= Stream.ReadInt; // код юзера ForFirmID:= Stream.ReadInt; // код контрагента // ContID:= Stream.ReadInt; // для контрактов - функция уходит prSetThLogParams(ThreadData, 0, EmplID, 0, 'FirmID='+IntToStr(ForFirmID)); // логирование if CheckNotValidUser(EmplID, isWe, errmess) then raise EBOBError.Create(errmess); if not Cache.CheckEmplVisFirm(EmplID, ForFirmID) then raise EBOBError.Create(MessText(mtkNotFirmExists)); Cache.TestFirms(ForFirmID, True, True, False); if not Cache.FirmExist(ForFirmID) then raise EBOBError.Create(MessText(mtkNotFirmExists)); firm:= Cache.arFirmInfo[ForFirmID]; Contract:= firm.GetContract(contID); Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteStr(firm.Name); // наименование фирмы Stream.WriteDouble(Contract.CredLimit); Stream.WriteDouble(Contract.DebtSum); Stream.WriteDouble(Contract.OrderSum); Stream.WriteDouble(Contract.PlanOutSum); Stream.WriteInt(Contract.CredCurrency); Stream.WriteStr(Cache.GetCurrName(Contract.CredCurrency)); Stream.WriteStr(Contract.WarnMessage); Stream.WriteBool(Contract.SaleBlocked); Stream.WriteInt(Contract.CredDelay); if not Contract.SaleBlocked then Stream.WriteInt(Contract.WhenBlocked); // если отгрузка не блокирована //-------------- передаем все склады резервирования контракта фирмы LineCount:= 0; // счетчик sPos:= Stream.Position; Stream.WriteInt(0); // место под кол-во складов for i:= 0 to High(Contract.ContStorages) do if Contract.ContStorages[i].IsReserve then begin k:= Contract.ContStorages[i].DprtID; if not Cache.CheckEmplVisStore(EmplID, ForFirmID) then Continue; // проверка видимости склада сотруднику Stream.WriteInt(k); // код склада Stream.WriteStr(Cache.GetDprtMainName(k)); // наименование склада inc(LineCount); end; if (LineCount>0) then begin Stream.Position:= sPos; Stream.WriteInt(LineCount); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //=================================== показать остатки по товару и складам фирмы procedure prWebArmShowFirmWareRests(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmShowFirmWareRests'; // имя процедуры/функции var EmplID, ForFirmID, WareID, spos, LineCount, k, i, ContID: integer; s: string; Ware: TWareInfo; firm: TFirmInfo; Rest: Double; link: TQtyLink; Contract: TContract; begin Stream.Position:= 0; ContID:= 0; try EmplID:= Stream.ReadInt; WareID:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; ContID:= Stream.ReadInt; // для контрактов prSetThLogParams(ThreadData, 0, EmplID, 0, 'ForFirmID='+IntToStr(ForFirmID)+' WareID='+IntToStr(WareID)); // логирование if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера if not Cache.arEmplInfo[EmplID].UserRoleExists(rolOPRSK) then // проверяем право пользователя ??? raise EBOBError.Create(MessText(mtkNotRightExists)); if not Cache.FirmExist(ForFirmID) // проверка фирмы or not Cache.CheckEmplVisFirm(EmplID, ForFirmID) then raise EBOBError.Create(MessText(mtkNotFirmExists)); Ware:= Cache.GetWare(WareID, True); if not Assigned(Ware) or (Ware=NoWare) or Ware.IsArchive then raise EBOBError.Create(MessText(mtkNotFoundWare, IntToStr(WareID))); firm:= Cache.arFirmInfo[ForFirmID]; Contract:= firm.GetContract(contID); Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteStr(Ware.Name); // наименование товара //----------------------------------- передаем остатки по всем складам фирмы LineCount:= 0; // счетчик sPos:= Stream.Position; Stream.WriteInt(0); // место под кол-во складов for i:= 0 to High(Contract.ContStorages) do with Contract.ContStorages[i] do if IsVisible or (flClientStoragesView_add and IsAddVis) then begin k:= DprtID; Rest:= 0; if Assigned(ware.RestLinks) then begin link:= ware.RestLinks[k]; if Assigned(link) then Rest:= link.Qty; end; Stream.WriteStr(Cache.GetDprtMainName(k)); // наименование склада Stream.WriteStr(IntToStr(round(Rest))); // кол-во inc(LineCount); end; if (LineCount>0) then begin Stream.Position:= sPos; Stream.WriteInt(LineCount); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; {//======================================== передать список незакрытых счетов к/а procedure prWebArmGetFirmAccountList(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetFirmAccountList'; // имя процедуры/функции var EmplID, ForFirmID, j, sPos: integer; s: string; GBIBD: TIBDatabase; GBIBS: TIBSQL; empl: TEmplInfoItem; begin Stream.Position:= 0; GBIBS:= nil; try EmplID:= Stream.ReadInt; // код юзера ForFirmID:= Stream.ReadInt; // код контрагента prSetThLogParams(ThreadData, 0, EmplId, 0, 'ForFirmID='+IntToStr(ForFirmID)); // логирование if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя ??? raise EBOBError.Create(MessText(mtkNotRightExists)); if not Cache.CheckEmplVisFirm(EmplID, ForFirmID) then // проверка фирмы raise EBOBError.Create(MessText(mtkNotFirmExists)); GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно sPos:= Stream.Position; Stream.WriteInt(0); // место под кол-во счетов try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpRead, True); GBIBS.SQL.Text:= 'select PInvCode, PInvNumber, PInvDate, PInvSumm,'+ ' PINVPROCESSED, PInvLocked, PINVCLIENTCOMMENT, PInvCrncCode, u.uslsusername,'+ ' PINVSHIPMENTMETHODCODE, PINVSHIPMENTDATE, PINVSHIPMENTTIMECODE'+ // отгрузка ' from PayInvoiceReestr'+ ' left join SUBCONTRACT on SbCnDocmCode=PInvCode and SbCnDocmType=99'+ ' left join INVOICEREESTR on INVCSUBCONTRACT=SbCnCode'+ ' left join PROTOCOL pp on pp.ProtObjectCode=pinvcode'+ ' and pp.ProtObjectType=55 and pp.ProtOperType=1'+ // создатель счета ' left join userlist u on u.UsLsUserID=pp.ProtUserID'+ ' WHERE PInvRecipientCode='+IntToStr(ForFirmID)+' and PINVANNULKEY="F"'+ ' and PInvDate>DATEADD(DAY, -EXTRACT(DAY FROM CURRENT_TIMESTAMP)-30, CURRENT_TIMESTAMP)'+ ' and (SbCnCode is null or INVCCODE is null) ORDER BY PInvNumber'; GBIBS.ExecQuery; j:= 0; while not GBIBS.EOF do begin Stream.WriteBool(GetBoolGB(GBibs, 'PInvLocked')); // признак блокировки счета Stream.WriteInt(GBIBS.FieldByName('PInvCode').AsInteger); Stream.WriteStr(FormatDateTime(cDateFormatY2, GBIBS.FieldByName('PInvDate').AsDateTime)); Stream.WriteBool(GetBoolGB(GBibs, 'PINVPROCESSED')); Stream.WriteStr(GBIBS.FieldByName('PInvNumber').AsString); Stream.WriteStr(GBIBS.FieldByname('PINVCLIENTCOMMENT').AsString); Stream.WriteDouble(GBIBS.FieldByName('PInvSumm').AsFloat); Stream.WriteStr(Cache.GetCurrName(GBIBS.FieldByName('PInvCrncCode').AsInteger)); // TestCssStopException; GBIBS.Next; Inc(j); end; GBIBS.Close; Stream.Position:= sPos; Stream.WriteInt(j); // передаем кол-во finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; } //====================================== передать список счетов с учетом фильтра procedure prWebArmGetFilteredAccountList(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetFilteredAccountList'; // имя процедуры/функции var EmplID, j, sPos, filtCurrency, filtStorage, filtShipMethod, filtForFirmID, filtContractID, filtShipTimeID, filtProcessed, filtWebAccount, filtBlocked, fid, sid: integer; s: string; GBIBD: TIBDatabase; GBIBS: TIBSQL; empl: TEmplInfoItem; filtFromDate, filtToDate, filtShipDate: TDate; filtExecuted, filtAnnulated, flSkip: Boolean; begin Stream.Position:= 0; GBIBS:= nil; try EmplID := Stream.ReadInt; // код сотрудника filtFromDate := Stream.ReadDouble; // дата от, 0 - не задана filtToDate := Stream.ReadDouble; // дата до, 0 - не задана filtCurrency := Stream.ReadInt; // код валюты, <1 - все filtStorage := Stream.ReadInt; // код склада, <1 - все filtShipMethod:= Stream.ReadInt; // код метода отгрузки, <1 - все filtShipDate := Stream.ReadDouble; // дата отгрузки, 0 - не задана filtShipTimeID:= Stream.ReadInt; // код времени отгрузки, <1 - все filtExecuted := Stream.ReadBool; // исполненные: False - не показывать, True - показывать filtAnnulated := Stream.ReadBool; // аннулированые: False - не показывать, True - показывать filtProcessed := Stream.ReadInt; // -1 - все, 0 - необработанные, 1 - обработанные filtWebAccount:= Stream.ReadInt; // -1 - все, 0 - не Web-счета, 1 - Web-счета filtBlocked := Stream.ReadInt; // -1 - все, 0 - не блокированные, 1 - блокированные filtForFirmID := Stream.ReadInt; // код контрагента, <1 - все filtContractID:= Stream.ReadInt; // код контракта, <1 - все prSetThLogParams(ThreadData, 0, EmplID, 0, 'filtForFirmID='+IntToStr(filtForFirmID)); // логирование if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя ??? raise EBOBError.Create(MessText(mtkNotRightExists)); s:= ''; // формируем строку условий фильтра if (filtForFirmID>0) then begin // если задана фирма - проверка видимости if not Cache.FirmExist(filtForFirmID) or not Cache.CheckEmplVisFirm(EmplID, filtForFirmID) then raise EBOBError.Create(MessText(mtkNotFirmExists)); s:= s+fnIfStr(s='', '', ' and ')+' PInvRecipientCode='+IntToStr(filtForFirmID); end; if (filtContractID>0) then begin if not Cache.Contracts.ItemExists(filtContractID) then raise EBOBError.Create(MessText(mtkNotFoundCont)); s:= s+fnIfStr(s='', '', ' and ')+' PINVCONTRACTCODE='+IntToStr(filtContractID); end; if (filtStorage>0) then begin // если задан склад - проверка видимости if not Cache.DprtExist(filtStorage) or not Cache.CheckEmplVisStore(EmplID, filtStorage) then raise EBOBError.Create(MessText(mtkNotDprtExists)); s:= s+fnIfStr(s='', '', ' and ')+' PInvSupplyDprtCode='+IntToStr(filtStorage); end else s:= s+fnIfStr(s='', '', ' and ')+' not PInvSupplyDprtCode is null'; if Cache.DocmMinDate>filtFromDate then filtFromDate:= Cache.DocmMinDate; if (filtFromDate>0) then // дата от s:= s+fnIfStr(s='', '', ' and ')+' PInvDate>=:filtFromDate'; if (filtToDate>0) then begin // если задана дата до if (Cache.DocmMinDate>filtToDate) then filtToDate:= Cache.DocmMinDate; s:= s+fnIfStr(s='', '', ' and ')+' PInvDate<=:filtToDate'; end; // if (filtFromDate<1) and (filtToDate<1) then // если от/до не заданы - за месяц ??? // s:= s+fnIfStr(s='', '', ' and ')+' PInvDate>DATEADD(DAY, -EXTRACT(DAY FROM CURRENT_TIMESTAMP)-30, CURRENT_TIMESTAMP)'; if (filtCurrency>0) then begin // если задана валюта if not Cache.CurrExists(filtCurrency) then raise EBOBError.Create('Не найдена валюта'); s:= s+fnIfStr(s='', '', ' and ')+' PInvCrncCode='+IntToStr(filtCurrency); end; if not filtExecuted then // исполненные не показывать s:= s+fnIfStr(s='', '', ' and ')+' (SbCnCode is null or INVCCODE is null)'; if not filtAnnulated then // аннулированые не показывать s:= s+fnIfStr(s='', '', ' and ')+' PINVANNULKEY="F"'; if (filtProcessed>-1) then // необработанные/обработанные if (filtProcessed=0) then s:= s+fnIfStr(s='', '', ' and ')+' PINVPROCESSED="F"' else if (filtProcessed=1) then s:= s+fnIfStr(s='', '', ' and ')+' PINVPROCESSED="T"'; if (filtBlocked>-1) then // не блокированные/блокированные if (filtBlocked=0) then s:= s+fnIfStr(s='', '', ' and ')+' PInvLocked="F"' else if (filtBlocked=1) then s:= s+fnIfStr(s='', '', ' and ')+' PInvLocked="T"'; if (filtWebAccount>-1) then // не Web-счета/Web-счета if (filtWebAccount=0) then s:= s+fnIfStr(s='', '', ' and ')+' (PINVWEBCOMMENT is null or PINVWEBCOMMENT="")' else if (filtWebAccount=1) then s:= s+fnIfStr(s='', '', ' and ')+' (not PINVWEBCOMMENT is null and PINVWEBCOMMENT>"")'; if (filtShipDate>0) then // если задана дата отгрузки s:= s+fnIfStr(s='', '', ' and ')+' PINVSHIPMENTDATE=:filtShipDate'; if (filtShipMethod>0) then begin // если задан метод отгрузки if not Cache.ShipMethods.ItemExists(filtShipMethod) then raise EBOBError.Create('Не найден метод отгрузки'); if (filtShipTimeID>0) and Cache.GetShipMethodNotTime(filtShipMethod) then raise EBOBError.Create('Этот метод отгрузки - без указания времени'); s:= s+fnIfStr(s='', '', ' and ')+' PINVSHIPMENTMETHODCODE='+IntToStr(filtShipMethod); end; if (filtShipTimeID>0) then begin // если задано время отгрузки if not Cache.ShipTimes.ItemExists(filtShipTimeID) then raise EBOBError.Create('Не найдено время отгрузки'); s:= s+fnIfStr(s='', '', ' and ')+' PINVSHIPMENTTIMECODE='+IntToStr(filtShipTimeID); end; GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpRead, True); GBIBS.SQL.Text:= 'select PInvCode, PInvNumber, PInvDate, PInvSumm,'+ ' PINVPROCESSED, PInvLocked, PINVCLIENTCOMMENT, PInvCrncCode, u.uslsusername,'+ ' PINVSHIPMENTMETHODCODE, PINVSHIPMENTDATE, PINVSHIPMENTTIMECODE,'+ // отгрузка ' PInvRecipientCode, PInvSupplyDprtCode, PINVANNULKEY, PINVCOMMENT,'+ ' c.contnumber, c.contbeginingdate, c.CONTBUSINESSTYPECODE, PINVCONTRACTCODE, '+ ' iif(SbCnCode is null or INVCCODE is null, "F", "T") as pExecuted'+ // ??? ' from PayInvoiceReestr'+ ' left join SUBCONTRACT on SbCnDocmCode=PInvCode and SbCnDocmType=99'+ ' left join INVOICEREESTR on INVCSUBCONTRACT=SbCnCode'+ ' left join CONTRACT c on c.contcode=PINVCONTRACTCODE'+ ' left join PROTOCOL pp on pp.ProtObjectCode=pinvcode'+ ' and pp.ProtObjectType=55 and pp.ProtOperType=1'+ // создатель счета ' left join userlist u on u.UsLsUserID=pp.ProtUserID'+ ' WHERE '+s+' ORDER BY PInvNumber'; if (filtFromDate>0) then GBIBS.ParamByName('filtFromDate').AsDateTime:= filtFromDate; if (filtToDate>0) then GBIBS.ParamByName('filtToDate').AsDateTime := filtToDate; if (filtShipDate>0) then GBIBS.ParamByName('filtShipDate').AsDateTime:= filtShipDate; GBIBS.ExecQuery; Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно sPos:= Stream.Position; Stream.WriteInt(0); // место под кол-во счетов j:= 0; while not GBIBS.EOF do begin sid:= GBIBS.FieldByName('PInvSupplyDprtCode').AsInteger; // проверяем склад flSkip:= False; if (filtStorage<>sid) then begin flSkip:= not Cache.DprtExist(sid) or not Cache.CheckEmplVisStore(EmplID, sid); if not flSkip then with Cache.arDprtInfo[sid] do flSkip:= not (IsStoreHouse or IsStoreRoad); end; if flSkip then begin GBIBS.Next; Continue; end; fid:= GBIBS.FieldByName('PInvRecipientCode').AsInteger; // проверяем к/а flSkip:= False; if (filtForFirmID<>fid) then with Cache do flSkip:= not FirmExist(fid) or not CheckEmplVisFirm(EmplID, fid); if flSkip then begin GBIBS.Next; Continue; end; Stream.WriteBool(GetBoolGB(GBibs, 'PInvLocked')); // признак блокировки счета Stream.WriteInt(GBIBS.FieldByName('PInvCode').AsInteger); Stream.WriteBool(GetBoolGB(GBibs, 'PINVPROCESSED')); // обработан Stream.WriteBool(GetBoolGB(GBibs, 'PINVANNULKEY')); // аннулирован Stream.WriteBool(GetBoolGB(GBibs, 'pExecuted')); // исполнен Stream.WriteBool(CheckShipmentDateTime(GBIBS.FieldByName('PINVSHIPMENTDATE').AsDate, GBIBS.FieldByName('PINVSHIPMENTTIMECODE').AsInteger)); // просрочена доставка Stream.WriteStr(GBIBS.FieldByName('PInvNumber').AsString); Stream.WriteStr(FormatDateTime(cDateFormatY2, GBIBS.FieldByName('PInvDate').AsDateTime)); Stream.WriteInt(fid); // код к/а Stream.WriteStr(Cache.arFirmInfo[fid].Name); // наименование к/а Stream.WriteInt(GBIBS.FieldByName('PINVCONTRACTCODE').AsInteger); Stream.WriteBool(GBIBS.FieldByName('CONTBUSINESSTYPECODE').AsInteger=2); // is moto Stream.WriteStr(GBIBS.FieldByName('CONTNUMBER').AsString+'-'+ FormatDateTime('yy', GBIBS.FieldByName('CONTBEGININGDATE').AsDateTime)); Stream.WriteInt(sid); // склад Stream.WriteDouble(GBIBS.FieldByName('PInvSumm').AsFloat); Stream.WriteStr(Cache.GetCurrName(GBIBS.FieldByName('PInvCrncCode').AsInteger)); Stream.WriteInt(GBIBS.FieldByName('PINVSHIPMENTMETHODCODE').AsInteger); // метод отгрузки Stream.WriteDouble(GBIBS.FieldByName('PINVSHIPMENTDATE').AsDate); // дата отгрузки Stream.WriteInt(GBIBS.FieldByName('PINVSHIPMENTTIMECODE').AsInteger); // время отгрузки Stream.WriteStr(GBIBS.FieldByName('uslsusername').AsString); // создатель счета Stream.WriteStr(GBIBS.FieldByname('PINVCOMMENT').AsString); Stream.WriteStr(GBIBS.FieldByname('PINVCLIENTCOMMENT').AsString); // TestCssStopException; GBIBS.Next; Inc(j); end; GBIBS.Close; if (j>0) then begin Stream.Position:= sPos; Stream.WriteInt(j); // передаем кол-во end; finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //===================================== показать счет (если нет - создать новый) procedure prWebArmShowAccount(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmShowAccount'; // имя процедуры/функции var GBIBD: TIBDatabase; GBIBS: TIBSQL; EmplID, ForFirmID, AccountID, spos, LineCount, k, curr, i, iStore, ContID: integer; AccountCode, FirmCode, s, sh: string; Ware: TWareInfo; empl: TEmplInfoItem; firm: TFirmInfo; sum: Double; Success: boolean; Contract: TContract; //----------------------------------------- проверка фирмы procedure CheckFirm(firmID: Integer); begin if (firmID<1) or Assigned(Firm) then Exit; if (not Cache.FirmExist(firmID) or not Cache.CheckEmplVisFirm(EmplID, firmID)) then raise EBOBError.Create(MessText(mtkNotFirmExists)); Cache.TestFirms(firmID, True, True, False); if ForFirmID<>firmID then ForFirmID:= firmID; FirmCode:= IntToStr(ForFirmID); firm:= Cache.arFirmInfo[ForFirmID]; Contract:= firm.GetContract(contID); end; //----------------------------------------- begin Stream.Position:= 0; GBIBS:= nil; firm:= nil; contID:= 0; try EmplID:= Stream.ReadInt; AccountID:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; // ContID:= Stream.ReadInt; // для контрактов - здесь не нужен AccountCode:= IntToStr(AccountID); FirmCode:= IntToStr(ForFirmID); prSetThLogParams(ThreadData, 0, EmplID, 0, 'ForFirmID='+FirmCode+' AccountID='+AccountCode); // логирование if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя ??? raise EBOBError.Create(MessText(mtkNotRightExists)); if (ForFirmID>0) then CheckFirm(ForFirmID); // проверка фирмы (если задан ForFirmID) GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpRead); //------------------------------ новый счет ------------------------------------ if (AccountID=-1) and Assigned(Firm) then begin k:= Contract.MainStorage; // склад по умолчанию fnSetTransParams(GBIBS.Transaction, tpWrite, True); // curr:= Contract.ContCurrency; curr:= Contract.CredCurrency; GBIBS.SQL.Text:= 'Select NewAccCode, NewDprtCode'+ // получаем код нового счета ' from Vlad_CSS_AddAccHeaderC('+FirmCode+', '+IntToStr(ContID)+', '+ IntToStr(k)+', '+IntToStr(curr)+', "")'; Success:= false; for i:= 1 to RepeatCount do try GBIBS.Close; with GBIBS.Transaction do if not InTransaction then StartTransaction; GBIBS.ExecQuery; if GBIBS.Bof and GBIBS.Eof then raise EBOBError.Create('Ошибка создания счета'); if GBIBS.FieldByName('NewDprtCode').AsInteger<>k then // проверка замены склада (на всяк.случай) raise EBOBError.Create('Ошибка создания счета по складу '+Cache.GetDprtMainName(k)); AccountID:= GBIBS.FieldByName('NewAccCode').AsInteger; AccountCode:= IntToStr(AccountID); GBIBS.Close; GBIBS.SQL.Text:= 'update PayInvoiceReestr set'+ // пишем комментарий сотрудникам ' PINVCOMMENT=:comm where PInvCode='+AccountCode; GBIBS.ParamByName('comm').AsString:= cWebArmComment; GBIBS.ExecQuery; GBIBS.Transaction.Commit; GBIBS.Close; Success:= true; break; except on E: EBOBError do raise EBOBError.Create(E.Message); on E: Exception do if (Pos('lock', E.Message)>0) and (i<RepeatCount) then begin with GBIBS.Transaction do if InTransaction then RollbackRetaining; GBIBS.Close; sleep(RepeatSaveInterval); end else raise Exception.Create(E.Message); end; GBIBS.Close; if not Success then raise EBOBError.Create('Ошибка создания счета'); fnSetTransParams(GBIBS.Transaction, tpRead); end; //------------------------------- создали новый счет --------------------------- with GBIBS.Transaction do if not InTransaction then StartTransaction; GBIBS.SQL.Text:= 'SELECT p1.PInvNumber, p1.PInvDate, p1.PInvProcessed, p1.PInvSumm,'+ ' p1.PInvCrncCode, p1.PInvSupplyDprtCode, p1.PINVCOMMENT, p1.PINVWEBCOMMENT,'+ ' p1.PINVCLIENTCOMMENT, p1.PInvLocked, p1.PINVWARELINECOUNT, p1.PINVANNULKEY,'+ ' p2.PInvNumber AcntNumber, p2.PInvDate AcntDate, INVCCODE, u.uslsusername,'+ ' p1.PINVSHIPMENTMETHODCODE, p1.PINVSHIPMENTDATE, p1.PINVSHIPMENTTIMECODE,'+ // отгрузка ' p1.PInvRecipientCode, p2.PInvCode AcntCode, p1.PINVLABELCODE, p1.PINVCONTRACTCODE'+ ' from PayInvoiceReestr p1 left join PROTOCOL pp on pp.ProtObjectCode=p1.pinvcode'+ ' and pp.ProtObjectType=55 and pp.ProtOperType=1'+ // создатель счета ' left join userlist u on u.UsLsUserID=pp.ProtUserID'+ ' left join PayInvoiceReestr p2 on p2.PInvCode=p1.PINVSOURCEACNTCODE'+ ' left join SUBCONTRACT on SbCnDocmCode=p1.PInvCode and SbCnDocmType=99'+ ' left join INVOICEREESTR on INVCSUBCONTRACT=SbCnCode'+ ' where p1.PInvCode='+AccountCode; GBIBS.ExecQuery; if GBIBS.Bof and GBIBS.Eof then raise EBOBError.Create('Не найден счет с id='+AccountCode); s:= 'Счет '+GBIBS.FieldByName('PInvNumber').AsString; //-------------------- запреты на просмотр счета ------------------------------- ??? // if GetBoolGB(GBibs, 'PInvLocked') then raise EBOBError.Create(s+' блокирован'); // if GetBoolGB(GBibs, 'PINVANNULKEY') then raise EBOBError.Create(s+' аннулирован'); // if GBIBS.FieldByName('INVCCODE').AsInteger>0 then raise EBOBError.Create(s+' недоступен'); //-------------------- запреты на просмотр счета ------------------------------- // проверка фирмы (если не задан ForFirmID) if (ForFirmID<1) then CheckFirm(GBIBS.FieldByName('PInvRecipientCode').AsInteger); Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteBool(GetBoolGB(GBibs, 'PInvLocked')); Stream.WriteBool(GetBoolGB(GBibs, 'PINVANNULKEY')); Stream.WriteBool(GBIBS.FieldByName('INVCCODE').AsInteger>0); //-------------------- передаем заголовок счета -------------------------------- Stream.WriteInt(ForFirmID); // код получателя Stream.WriteStr(firm.UPPERSHORTNAME); // краткое наим. получателя Stream.WriteStr(firm.Name); // наим. получателя i:= GBIBS.FieldByName('PINVCONTRACTCODE').AsInteger; contID:= i; if (Contract.ID<>contID) then Contract:= firm.GetContract(contID); if (i<>ContID) then raise EBOBError.Create(MessText(mtkNotFoundCont, IntToStr(i))); Stream.WriteInt(contID); // код контракта Stream.WriteStr(Contract.Name); // наименование контракта Stream.WriteInt(Firm.FirmContracts.Count); // кол-во контрактов Stream.WriteBool(Contract.SysID=constIsAuto); // Является ли автоконтрактом iStore:= GBIBS.FieldByName('PInvSupplyDprtCode').AsInteger; Stream.WriteInt(iStore); // код склада счета curr:= GBIBS.FieldByName('PInvCrncCode').AsInteger; Stream.WriteInt(curr); // код валюты счета Stream.WriteInt(AccountID); // код счета Stream.WriteStr(GBIBS.FieldByName('PInvNumber').AsString); // номер счета Stream.WriteDouble(GBIBS.FieldByName('PInvDate').AsDateTime); // дата Stream.WriteBool(GetBoolGB(GBIBS, 'PInvProcessed')); // признак обработки // Stream.WriteBool(GetBoolGB(GBIBS, 'PInvLocked')); // признак блокировки ??? sum:= GBIBS.FieldByName('PInvSumm').AsFloat; // сумма счета s:= fnGetStrSummByDoubleCurr(sum, curr); // строка с суммой в 2-х валютах Stream.WriteStr(s); Stream.WriteStr(GBIBS.FieldByName('PINVCOMMENT').AsString); // комментарий сотрудникам Stream.WriteStr(GBIBS.FieldByName('PINVWEBCOMMENT').AsString); // комментарий WEB Stream.WriteStr(GBIBS.FieldByName('PINVCLIENTCOMMENT').AsString); // комментарий клиенту Stream.WriteInt(GBIBS.FieldByName('AcntCode').AsInteger); // код родительского счета s:= GBIBS.FieldByName('AcntNumber').AsString; // номер и дата родительского счета if s<>'' then s:= s+' от '+ FormatDateTime(cDateFormatY2, GBIBS.FieldByName('AcntDate').AsDateTime); Stream.WriteStr(s); Stream.WriteStr(GBIBS.FieldByName('uslsusername').AsString); // создатель счета (оператор) with Cache.GetShipMethodsList(iStore) do try // список методов отгрузки по складу Stream.WriteInt(Count); for i:= 0 to Count-1 do begin Stream.WriteInt(Integer(Objects[i])); Stream.WriteStr(Strings[i]); end; finally Free; end; i:= GBIBS.FieldByName('PINVSHIPMENTMETHODCODE').AsInteger; Stream.WriteInt(i); // код метода отгрузки if Cache.GetShipMethodNotTime(i) then k:= -1 else k:= GBIBS.FieldByName('PINVSHIPMENTTIMECODE').AsInteger; Stream.WriteInt(k); // код времени отгрузки Stream.WriteDouble(GBIBS.FieldByName('PINVSHIPMENTDATE').AsDateTime); // дата отгрузки if Cache.GetShipMethodNotLabel(i) then k:= -1 else k:= GBIBS.FieldByName('PINVLABELCODE').AsInteger; Stream.WriteInt(k); // код наклейки LineCount:= GBIBS.FieldByName('PINVWARELINECOUNT').AsInteger; // кол-во строк товаров в счете GBIBS.Close; sh:= IntToStr(Cache.arFirmInfo[ForFirmID].HostCode); // список наклеек клиента GBIBS.SQL.Text:= 'select FRLBCODE, FRLBNAME, FRLBFACENAME, FRLBPHONE,'+ ' "" as FRLBCARRIER, FRLBDELIVERYTIME, FRLBCOMMENT from FIRMLABELREESTR'+ // поле FRLBCARRIER убрали ' where FRLBSUBJCODE='+sh+' and FRLBSUBJTYPE=1 and (FRLBARCHIVE="F" or FRLBCODE='+intToStr(k)+') '; sPos:= Stream.Position; k:= 0; Stream.WriteInt(0); // место под кол-во наклеек GBIBS.ExecQuery; while not GBIBS.EOF do begin Inc(k); Stream.WriteInt(GBIBS.FieldByName('FRLBCODE').AsInteger); // код наклейки Stream.WriteStr(GBIBS.FieldByName('FRLBNAME').AsString); // Stream.WriteStr(GBIBS.FieldByName('FRLBFACENAME').AsString); // Stream.WriteStr(GBIBS.FieldByName('FRLBPHONE').AsString); // Stream.WriteStr(GBIBS.FieldByName('FRLBCARRIER').AsString); // Stream.WriteStr(GBIBS.FieldByName('FRLBDELIVERYTIME').AsString); // Stream.WriteStr(GBIBS.FieldByName('FRLBCOMMENT').AsString); // GBIBS.Next; end; GBIBS.Close; if k>0 then begin Stream.Position:= sPos; Stream.WriteInt(k); Stream.Position:= Stream.Size; end; //-------------------- передали заголовок счета -------------------------------- sPos:= Stream.Position; Stream.WriteInt(0); // место под кол-во строк if LineCount>0 then begin //-------------------- передаем товары счета ----------------------------------- LineCount:= 0; // счетчик - кол-во строк GBIBS.SQL.Text:= 'select PInvLnCode, PInvLnWareCode, PInvLnOrder, PInvLnCount, PInvLnPrice'+ ' from PayInvoiceLines where PInvLnDocmCode='+AccountCode; GBIBS.ExecQuery; while not GBIBS.EOF do begin k:= GBIBS.FieldByName('PInvLnWareCode').AsInteger; Ware:= Cache.GetWare(k, True); if not Assigned(Ware) or (Ware=NoWare) or Ware.IsArchive then raise EBOBError.Create(MessText(mtkNotFoundWare, IntToStr(k))); Stream.WriteInt(GBIBS.FieldByName('PInvLnCode').AsInteger); // код строки Stream.WriteInt(k); // код товара Stream.WriteStr(Ware.Name); // наименование товара Stream.WriteStr(GBIBS.FieldByName('PInvLnOrder').AsString); // заказ Stream.WriteStr(GBIBS.FieldByName('PInvLnCount').AsString); // факт Stream.WriteStr(Ware.MeasName); // наименование ед.изм. sum:= GBIBS.FieldByName('PInvLnPrice').AsFloat; s:= fnGetStrSummByDoubleCurr(sum, curr); // цена в 2-х валютах Stream.WriteStr(s); if GBIBS.FieldByName('PInvLnCount').AsFloat=1 then Stream.WriteStr(s) else begin sum:= RoundToHalfDown(sum*GBIBS.FieldByName('PInvLnCount').AsFloat); s:= fnGetStrSummByDoubleCurr(sum, curr); Stream.WriteStr(s); // сумма по строке в 2-х валютах end; Stream.WriteStr(Ware.Comment); // комментарий inc(LineCount); // TestCssStopException; GBIBS.Next; end; if LineCount>0 then begin Stream.Position:= sPos; Stream.WriteInt(LineCount); end; //-------------------- передали товары счета ----------------------------------- end; finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; end; //=============================================== редактирование заголовка счета procedure prWebArmEditAccountHeader(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmEditAccountHeader'; // имя процедуры/функции sNot = 'Нет изменений'; type RLineWareAndQties = record Ware: TWareInfo; OldQty, NewQty, DeltaQty: Double; end; var GBIBD: TIBDatabase; GBIBS: TIBSQL; EmplID, ForFirmID, AccountID, ParamID, k, kk, i, LineCount, ContID, SysID: integer; AccountCode, FirmCode, s1, sWhere, ParamStr, ParamStr2, sf: string; empl: TEmplInfoItem; firm: TFirmInfo; dd: TDate; fl: Boolean; arLineWareAndQties: array of RLineWareAndQties; Contract: TContract; //----------------------------------------- проверка фирмы procedure CheckFirm(firmID: Integer); begin if not Cache.FirmExist(firmID) or not Cache.CheckEmplVisFirm(EmplID, firmID) then raise EBOBError.Create(MessText(mtkNotFirmExists)); if ForFirmID<>firmID then ForFirmID:= firmID; FirmCode:= IntToStr(ForFirmID); firm:= Cache.arFirmInfo[ForFirmID]; Contract:= firm.GetContract(contID); end; //----------------------------------------- проверка склада фирмы procedure CheckForFirmStore(StoreID: Integer); var i: Integer; begin i:= Contract.GetСontStoreIndex(StoreID); if (i<0) then raise EBOBError.Create('Не найден склад резервирования'); if not Contract.ContStorages[i].IsReserve then raise EBOBError.Create('Склад недоступен для резервирования'); end; //----------------------------------------- begin Stream.Position:= 0; GBIBS:= nil; firm:= nil; dd:= 0; k:= 0; ForFirmID:= 0; contID:= 0; SetLength(arLineWareAndQties, 0); try EmplID:= Stream.ReadInt; AccountID:= Stream.ReadInt; ParamID:= Stream.ReadInt; // вид параметра ParamStr:= Stream.ReadStr; // значение параметра if (ParamID=ceahAnnulateInvoice) then ParamStr2:= Stream.ReadStr; // значение параметра2 AccountCode:= IntToStr(AccountID); prSetThLogParams(ThreadData, 0, EmplID, 0, ' AccountID='+AccountCode+ ' ParamID='+IntToStr(ParamID)+' ParamStr='+ParamStr); // логирование if CheckNotValidUser(EmplID, isWe, s1) then raise EBOBError.Create(s1); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя raise EBOBError.Create(MessText(mtkNotRightExists)); GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpRead, True); sWhere:= ' where PInvCode='+AccountCode; //------------------------------ имя проверяемого поля ------------------------- case ParamID of ceahChangeCurrency, ceahRecalcPrices : sf:= 'PInvCrncCode'; ceahChangeRecipient, ceahRecalcCounts: sf:= 'PInvSupplyDprtCode'; ceahChangeStorage : sf:= 'PInvSupplyDprtCode, PINVSHIPMENTMETHODCODE'; ceahChangeProcessed : sf:= 'PInvProcessed'; ceahChangeEmplComm : sf:= 'PINVCOMMENT'; ceahChangeClientComm: sf:= 'PINVCLIENTCOMMENT'; ceahChangeShipMethod: sf:= 'PINVSHIPMENTMETHODCODE, PINVSHIPMENTTIMECODE, PINVLABELCODE'; ceahChangeShipTime : sf:= 'PINVSHIPMENTMETHODCODE, PINVSHIPMENTTIMECODE'; ceahChangeShipDate : sf:= 'PINVSHIPMENTDATE'; ceahChangeDocmDate : sf:= 'PInvDate'; ceahChangeLabel : sf:= 'PINVLABELCODE, PINVSHIPMENTMETHODCODE'; ceahAnnulateInvoice : sf:= 'PINVANNULKEY'; // , PINVUSEINREPORT ceahChangeContract : sf:= 'PInvSupplyDprtCode, PINVCONTRACTCODE'; end; GBIBS.SQL.Text:= 'select PInvNumber, PINVANNULKEY, PInvLocked, INVCCODE, PINVWARELINECOUNT,'+ ' PInvRecipientCode, PINVCONTRACTCODE'+fnIfStr(sf='', '', ', ')+sf+' from PayInvoiceReestr'+ ' left join SUBCONTRACT on SbCnDocmCode=PInvCode and SbCnDocmType=99'+ ' left join INVOICEREESTR on INVCSUBCONTRACT=SbCnCode'+sWhere; GBIBS.ExecQuery; if GBIBS.Bof and GBIBS.Eof then raise EBOBError.Create('Не найден счет с id='+AccountCode); s1:= 'Счет '+GBIBS.FieldByName('PInvNumber').AsString; //-------------------- запреты на изменение счета ------------------------------ ??? if GetBoolGB(GBibs, 'PInvLocked') then raise EBOBError.Create(s1+' блокирован'); if ((ParamID<>ceahAnnulateInvoice) or (ParamStr<>'F')) and GetBoolGB(GBibs, 'PINVANNULKEY') then raise EBOBError.Create(s1+' аннулирован'); // if GetBoolGB(GBibs, 'PINVANNULKEY') then raise EBOBError.Create(s1+' аннулирован'); if GBIBS.FieldByName('INVCCODE').AsInteger>0 then raise EBOBError.Create(s1+' недоступен'); //-------------------- запреты на изменение счета ------------------------------ LineCount:= GBIBS.FieldByName('PINVWARELINECOUNT').AsInteger; // проверка, есть ли товары в счете ??? ForFirmID:= GBIBS.FieldByName('PInvRecipientCode').AsInteger; contID:= GBIBS.FieldByName('PINVCONTRACTCODE').AsInteger; kk:= contID; CheckFirm(ForFirmID); // проверка фирмы //------------------- подготовка, проверка корректности значений --------------- case ParamID of ceahChangeContract: begin //------------------------------------- контракт k:= StrToIntDef(ParamStr, 0); sf:= 'PINVCONTRACTCODE'; if kk=k then raise EBOBError.Create(sNot); if not Cache.Contracts.ItemExists(k) then raise EBOBError.Create(MessText(mtkNotFoundCont)); // если есть товары - запоминаем бизнес-направление прежнего контракта if (LineCount>0) then SysID:= Contract.SysID else SysID:= 0; contID:= k; Contract:= firm.GetContract(contID); if (contID<>k) then raise EBOBError.Create(MessText(mtkNotFoundCont)); if (SysID>0) and (SysID<>Contract.SysID) then raise EBOBError.Create('Контракт не соответствует бизнес-направлению'); kk:= GBIBS.FieldByName('PInvSupplyDprtCode').AsInteger; CheckForFirmStore(kk); // проверка соответствия склада новому контракту фирмы end; ceahChangeStorage: begin //----------------------------------------- склад k:= StrToIntDef(ParamStr, 0); sf:= 'PInvSupplyDprtCode'; if GBIBS.FieldByName(sf).AsInteger=k then raise EBOBError.Create(sNot); if not Cache.DprtExist(k) then raise EBOBError.Create('Не найден склад'); CheckForFirmStore(k); // проверка склада контракта фирмы kk:= GBIBS.FieldByName('PINVSHIPMENTMETHODCODE').AsInteger; // проверяем доступность метода отгрузки новому складу if (kk>0) and Cache.ShipMethods.ItemExists(kk) then begin with Cache.GetShipMethodsList(k) do try // список методов отгрузки по новому складу fl:= False; for i:= 0 to Count-1 do begin fl:= (Integer(Objects[i])=kk); if fl then break; end; finally Free; end; if not fl then raise EBOBError.Create('Метод отгрузки недоступен для склада'); end; end; ceahChangeCurrency: begin //--------------------------------------- валюта k:= StrToIntDef(ParamStr, 0); if GBIBS.FieldByName(sf).AsInteger=k then raise EBOBError.Create(sNot); if not Cache.CurrExists(k) or Cache.arCurrArhived[k] then raise EBOBError.Create('Не найдена валюта'); end; ceahChangeProcessed: begin //--------------------------- признак обработки k:= StrToIntDef(ParamStr, 0); if fnIfInt(GBIBS.FieldByName(sf).AsString='T', 1, 0)=k then raise EBOBError.Create(sNot); ParamStr:= fnIfStr(k=1, '"T"', '"F"'); end; ceahChangeEmplComm, //---------- комментарий сотрудникам (м.б.пусто) ceahChangeClientComm: begin //------------ комментарий клиенту (м.б.пусто) if GBIBS.FieldByName(sf).AsString=ParamStr then raise EBOBError.Create(sNot); k:= Length(ParamStr); if k>cCommentLength then raise EBOBError.Create('Слишком длинный комментарий'); end; ceahChangeShipMethod: begin //------------ код метода отгрузки (м.б.пусто) k:= StrToIntDef(ParamStr, 0); sf:= 'PINVSHIPMENTMETHODCODE'; if (k>0) then begin if GBIBS.FieldByName(sf).AsInteger=k then raise EBOBError.Create(sNot); if not Cache.ShipMethods.ItemExists(k) then raise EBOBError.Create('Не найден метод отгрузки'); if (GBIBS.FieldByName('PINVSHIPMENTTIMECODE').AsInteger>0) // сброс времени отгрузки and Cache.GetShipMethodNotTime(k) then ParamStr:= ParamStr+', PINVSHIPMENTTIMECODE=null'; if (GBIBS.FieldByName('PINVLABELCODE').AsInteger>0) // сброс наклейки and Cache.GetShipMethodNotLabel(k) then ParamStr:= ParamStr+', PINVLABELCODE=null'; end else ParamStr:= 'null'; end; ceahChangeShipTime: begin //------------- код времени отгрузки (м.б.пусто) k:= StrToIntDef(ParamStr, 0); sf:= 'PINVSHIPMENTTIMECODE'; if GBIBS.FieldByName(sf).AsInteger=k then raise EBOBError.Create(sNot); if (k>0) then begin if not Cache.ShipTimes.ItemExists(k) then raise EBOBError.Create('Не найдено время отгрузки'); kk:= GBIBS.FieldByName('PINVSHIPMENTMETHODCODE').AsInteger; if (kk>0) and Cache.GetShipMethodNotTime(kk) then raise EBOBError.Create('Этот метод отгрузки - без указания времени'); end else ParamStr:= 'null'; end; ceahChangeLabel: begin //---------------------- код наклейки (м.б.пусто) k:= StrToIntDef(ParamStr, 0); sf:= 'PINVLABELCODE'; if GBIBS.FieldByName(sf).AsInteger=k then raise EBOBError.Create(sNot); if (k>0) then begin kk:= GBIBS.FieldByName('PINVSHIPMENTMETHODCODE').AsInteger; if (kk>0) and Cache.GetShipMethodNotLabel(kk) then raise EBOBError.Create('Этот метод отгрузки - без указания наклейки'); end else ParamStr:= 'null'; end; ceahChangeShipDate: begin //-------------------- дата отгрузки (м.б.пусто) if (ParamStr='') then begin if GBIBS.FieldByName(sf).IsNull then raise EBOBError.Create(sNot); dd:= 0; end else try dd:= StrToDate(ParamStr); if GBIBS.FieldByName(sf).AsDate=dd then raise EBOBError.Create(sNot); if dd<Date then raise EBOBError.Create('Старая дата'); // ??? except on E: EBOBError do raise EBOBError.Create(E.Message); on E: Exception do raise EBOBError.Create('Некорректное значение даты'); end; end; ceahChangeDocmDate: begin //---------------------------------- дата док-та try dd:= StrToDate(ParamStr); if GBIBS.FieldByName(sf).AsDate=dd then raise EBOBError.Create(sNot); if dd<Date then raise EBOBError.Create('Старая дата'); // ??? except on E: EBOBError do raise EBOBError.Create(E.Message); on E: Exception do raise EBOBError.Create('Некорректное значение даты'); end; end; ceahChangeRecipient: begin //---------------------------------- получатель ForFirmID:= StrToIntDef(ParamStr, 0); // если есть товары - запоминаем бизнес-направление прежнего контракта if (LineCount>0) then SysID:= Contract.SysID else SysID:= 0; CheckFirm(ForFirmID); // проверка фирмы if (SysID>0) and (SysID<>Contract.SysID) then begin k:= contID; // ищем контракт нужного бизнес-направления for i:= 0 to firm.FirmContracts.Count-1 do begin contID:= firm.FirmContracts[i]; if (contID=k) then Continue; // пропускаем тот, что уже был Contract:= firm.GetContract(contID); if (Contract.SysID=SysID) and not Contract.IsEnding then break; end; if (k=contID) then // если другой подходящий не нашли raise EBOBError.Create('Контракт не соответствует бизнес-направлению'); end; k:= GBIBS.FieldByName(sf).AsInteger; // код склада sf:= 'PInvRecipientCode'; if GBIBS.FieldByName(sf).AsInteger=ForFirmID then raise EBOBError.Create(sNot); CheckForFirmStore(k); // проверка склада фирмы end; ceahRecalcPrices: begin //--------------------------------- пересчет цен if (LineCount<1) then raise EBOBError.Create('Нет товаров'); ParamStr:= GBIBS.FieldByName(sf).AsString; end; ceahRecalcCounts: begin //------------------------------- пересчет факта if (LineCount<1) then raise EBOBError.Create('Нет товаров'); k:= GBIBS.FieldByName(sf).AsInteger; // код склада if not Cache.DprtExist(k) then raise EBOBError.Create('Не найден склад'); CheckForFirmStore(k); // проверка склада фирмы // ParamStr:= ''; end; ceahAnnulateInvoice: begin if (ParamStr<>'T') and (ParamStr<>'F') then EBOBError.Create('Неверный параметр аннуляции - "'+ParamStr+'"'); if (ParamStr2<>'T') and (ParamStr2<>'F') then EBOBError.Create('Неверный параметр аннуляции - "'+ParamStr2+'"'); ParamStr:= '"'+ParamStr+'", PINVUSEINREPORT="'+ParamStr2+'"'; end; end; GBIBS.Close; //------------------------- запись изменений ----------------------------------- fnSetTransParams(GBIBS.Transaction, tpWrite, True); // готовимся к записи s1:= 'update PayInvoiceReestr set '+sf+'='; case ParamID of // формируем строку SQL ceahChangeProcessed, //--------------------- признак обработки ceahChangeShipMethod, //------------------------ метод отгрузки ceahChangeShipTime, //------------------------ время отгрузки ceahAnnulateInvoice, //--- аннулирование/деаннулирование счета ceahChangeLabel, //-------------------------- код наклейки ceahChangeContract: //------------------------------ контракт GBIBS.SQL.Text:= s1+ParamStr+sWhere; ceahChangeEmplComm, //--------------- комментарий сотрудникам ceahChangeClientComm: //------------------- комментарий клиенту if (ParamStr<>'') then begin GBIBS.SQL.Text:= s1+':comm'+sWhere; GBIBS.ParamByName('comm').AsString:= ParamStr; end else GBIBS.SQL.Text:= s1+'null'+sWhere; ceahChangeShipDate: //------------------------- дата отгрузки if (dd>0) then begin GBIBS.SQL.Text:= s1+':dd'+sWhere; GBIBS.ParamByName('dd').AsDate:= dd; end else GBIBS.SQL.Text:= s1+'null'+sWhere; ceahChangeDocmDate: begin //--------------------------- дата док-та GBIBS.SQL.Text:= s1+':dd'+sWhere; GBIBS.ParamByName('dd').AsDate:= dd; end; ceahChangeRecipient: //---------------------------- получатель GBIBS.SQL.Text:= s1+FirmCode+', pinvcontractcode='+IntToStr(ContID)+sWhere; ceahChangeStorage: //--------------------------------- склад GBIBS.SQL.Text:= 'execute procedure Vlad_CSS_ChangeAccDprtC('+AccountCode+', '+ParamStr+')'; ceahChangeCurrency, //-------------------------------- валюта ceahRecalcPrices: //--------------------------------- пересчет цен GBIBS.SQL.Text:= 'execute procedure Vlad_CSS_RecalcAccSummC('+AccountCode+', '+ParamStr+')'; ceahRecalcCounts: //-- пересчет факта (возвр. стар. и нов.факт для кеша) GBIBS.SQL.Text:= 'select rWareCode, rOldCount, rNewCount'+ ' from Vlad_CSS_RecalcAccFactC('+AccountCode+')'; else raise EBOBError.Create(MessText(mtkNotValidParam)); end; // case for i:= 0 to RepeatCount do with GBIBS.Transaction do try Application.ProcessMessages; GBIBS.Close; if not InTransaction then StartTransaction; GBIBS.ExecQuery; if ParamID=ceahRecalcCounts then begin // запоминаем разницу факта SetLength(arLineWareAndQties, LineCount); LineCount:= 0; while not GBIBS.Eof do begin kk:= GBIBS.FieldByName('rWareCode').AsInteger; if Cache.WareExist(kk) then begin arLineWareAndQties[LineCount].Ware:= Cache.GetWare(kk); arLineWareAndQties[LineCount].DeltaQty:= GBIBS.FieldByName('rNewCount').AsFloat-GBIBS.FieldByName('rOldCount').AsFloat; inc(LineCount); end; GBIBS.Next; end; if LineCount<>Length(arLineWareAndQties) then SetLength(arLineWareAndQties, LineCount); end; // if ParamID=ceahRecalcCounts Commit; break; except on E: Exception do begin RollbackRetaining; if (i<RepeatCount) then sleep(RepeatSaveInterval) else raise Exception.Create(E.Message); end; end; if ParamID=ceahRecalcCounts then // снимаем разницу факта с остатков в кеше for kk:= 0 to High(arLineWareAndQties) do with arLineWareAndQties[kk] do Cache.CheckWareRest(Ware.RestLinks, k, DeltaQty, True); finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; //--------------------------- передаем ответ ----------------------------------- Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False, True); end; SetLength(arLineWareAndQties, 0); Stream.Position:= 0; end; //============================== добавление/редактирование/удаление строки счета procedure prWebArmEditAccountLine(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmEditAccountLine'; // имя процедуры/функции var GBIBD: TIBDatabase; GBIBS: TIBSQL; EmplID, ForFirmID, AccountID, Option, LineID, dprt, WareID, curr, iLine, i: integer; AccountCode, FirmCode, s, meas, WarnMess: string; empl: TEmplInfoItem; Ware: TWareInfo; cliQty, oldQty, sum: Double; begin Stream.Position:= 0; GBIBS:= nil; meas:= ''; WarnMess:= ''; try EmplID:= Stream.ReadInt; AccountID:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; Option:= Stream.ReadInt; // операция - constOpAdd, constOpEdit, constOpDel, constOpEditFact LineID:= Stream.ReadInt; // код строки WareID:= Stream.ReadInt; // код товара cliQty:= Stream.ReadDouble; // новый заказ / факт // oldQty:= Stream.ReadDouble; // старый факт cliQty:= abs(cliQty); AccountCode:= IntToStr(AccountID); FirmCode:= IntToStr(ForFirmID); prSetThLogParams(ThreadData, 0, EmplID, 0, 'ForFirmID='+FirmCode+' AccountID='+AccountCode+ ' Option='+IntToStr(Option)+' LineID='+IntToStr(LineID)+' cliQty='+FloatToStr(cliQty)); // логирование if not (Option in [constOpAdd, constOpEdit, constOpDel, constOpEditFact]) then raise EBOBError.Create(MessText(mtkNotValidParam)+' операции'); if (Option<>constOpAdd) and (LineID<1) then raise EBOBError.Create(MessText(mtkNotValidParam)+' номера строки'); if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя raise EBOBError.Create(MessText(mtkNotRightExists)); if not Cache.FirmExist(ForFirmID) // проверка фирмы or not Cache.CheckEmplVisFirm(EmplID, ForFirmID) then raise EBOBError.Create(MessText(mtkNotFirmExists)); if not Cache.WareExist(WareID) then raise EBOBError.Create(MessText(mtkNotFoundWare, IntToStr(WareID))); Ware:= Cache.GetWare(WareID); GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpRead, True); GBIBS.SQL.Text:= 'select PInvNumber, PINVANNULKEY, PInvSupplyDprtCode,'+ // , PINVWARELINECOUNT ??? ' PInvLocked, INVCCODE, PInvLnCount, PInvLnCode from PayInvoiceReestr'+ // ' left join SUBCONTRACT on SbCnDocmCode=PInvCode and SbCnDocmType=99'+ ' left join INVOICEREESTR on INVCSUBCONTRACT=SbCnCode'+ ' left join PayInvoiceLines on PInvLnDocmCode=PInvCode and PInvLnCode='+IntToStr(LineID)+ ' where PInvCode='+AccountCode+' and PInvRecipientCode='+FirmCode; GBIBS.ExecQuery; if GBIBS.Bof and GBIBS.Eof then raise EBOBError.Create('Не найден счет с id='+AccountCode); s:= 'Счет '+GBIBS.FieldByName('PInvNumber').AsString; //-------------------- запреты на изменение счета ------------------------------ ??? if GetBoolGB(GBibs, 'PInvLocked') then raise EBOBError.Create(s+' блокирован'); if GetBoolGB(GBibs, 'PINVANNULKEY') then raise EBOBError.Create(s+' аннулирован'); if GBIBS.FieldByName('INVCCODE').AsInteger>0 then raise EBOBError.Create(s+' недоступен'); //-------------------- запреты на изменение счета ------------------------------ if (Option=constOpAdd) then begin oldQty:= 0; LineID:= 0; end else begin oldQty:= GBIBS.FieldByName('PInvLnCount').AsFloat; // старый факт LineID:= GBIBS.FieldByName('PInvLnCode').AsInteger; if LineID<1 then raise EBOBError.Create(MessText(mtkNotValidParam)+' - код строки'); end; dprt:= GBIBS.FieldByName('PInvSupplyDprtCode').AsInteger; // склад GBIBS.Close; fnSetTransParams(GBIBS.Transaction, tpWrite, True); case Option of // формируем строку SQL constOpAdd: begin //----------------------------------------- добавить if cliQty<1 then raise EBOBError.Create(MessText(mtkNotValidParam)+' количества'); GBIBS.SQL.Text:= 'select NewLineCode, WarnMess from Vlad_CSS_AddAccLineWC('+ AccountCode+', '+IntToStr(dprt)+', '+IntToStr(WareID)+', :CLIENTQTY)'; GBIBS.ParamByName('CLIENTQTY').AsFloat:= cliQty; for i:= 0 to RepeatCount do with GBIBS.Transaction do try Application.ProcessMessages; GBIBS.Close; if not InTransaction then StartTransaction; GBIBS.ExecQuery; if GBIBS.Bof and GBIBS.Eof then raise Exception.Create(MessText(mtkErrAddRecord)); LineID:= GBIBS.FieldByName('NewLineCode').AsInteger; // код новой строки WarnMess:= GBIBS.FieldByName('WarnMess').AsString; oldQty:= 0; // обнуляем старый факт Commit; break; except on E: Exception do begin RollbackRetaining; if (i<RepeatCount) then sleep(RepeatSaveInterval) else raise Exception.Create(E.Message); end; end; end; // constOpAdd constOpEdit, constOpEditFact: begin //-------------- изменить заказ / факт if (Option=constOpEditFact) then iLine:= -LineID else iLine:= LineID; // iLine<0 - корректировка факта GBIBS.SQL.Text:= 'select WarnMess from Vlad_CSS_EditAccLineC('+IntToStr(iLine)+', :CLIENTQTY)'; GBIBS.ParamByName('CLIENTQTY').AsFloat:= cliQty; for i:= 0 to RepeatCount do with GBIBS.Transaction do try Application.ProcessMessages; GBIBS.Close; if not InTransaction then StartTransaction; GBIBS.ExecQuery; if GBIBS.Bof and GBIBS.Eof then raise Exception.Create(MessText(mtkErrEditRecord)); WarnMess:= GBIBS.FieldByName('WarnMess').AsString; Commit; break; except on E: Exception do begin RollbackRetaining; if (i<RepeatCount) then sleep(RepeatSaveInterval) else raise Exception.Create(E.Message); end; end; end; // constOpEdit, constOpEditFact constOpDel: begin //----------------------------------------- удалить GBIBS.SQL.Text:= 'delete from PayInvoiceLines where PInvLnCode='+IntToStr(LineID); for i:= 0 to RepeatCount do with GBIBS.Transaction do try Application.ProcessMessages; GBIBS.Close; if not InTransaction then StartTransaction; GBIBS.ExecQuery; if (GBIBS.RowsAffected<1) then raise Exception.Create(MessText(mtkErrDelRecord)); LineID:= 0; // обнуляем код строки Commit; break; except on E: Exception do begin RollbackRetaining; if (i<RepeatCount) then sleep(RepeatSaveInterval) else raise Exception.Create(E.Message); end; end; end; // constOpDel else raise EBOBError.Create(MessText(mtkNotValidParam)); end; // case // GBIBS.Transaction.Commit; GBIBS.Close; fnSetTransParams(GBIBS.Transaction, tpRead, True); Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно //-------------------------- новая сумма счета GBIBS.SQL.Text:= 'SELECT PInvProcessed, PInvCrncCode, PInvSupplyDprtCode, PInvSumm'+ ' from PayInvoiceReestr where PInvCode='+AccountCode+' and PInvRecipientCode='+FirmCode; GBIBS.ExecQuery; Stream.WriteBool(GetBoolGB(GBIBS, 'PInvProcessed')); // признак обработки s:= FormatFloat('# ##0.00', GBIBS.FieldByName('PInvSumm').AsFloat); curr:= GBIBS.FieldByName('PInvCrncCode').AsInteger; // валюта счета dprt:= GBIBS.FieldByName('PInvSupplyDprtCode').AsInteger; // склад sum:= GBIBS.FieldByName('PInvSumm').AsFloat; // сумма счета GBIBS.Close; s:= fnGetStrSummByDoubleCurr(sum, curr); // строка с суммой в 2-х валютах Stream.WriteStr(s); Stream.WriteInt(LineID); // код строки (constOpDel - 0) if LineID>0 then begin //-------------------- новое состояниее строки GBIBS.SQL.Text:= 'select PInvLnOrder, PInvLnCount, PInvLnPrice'+ ' from PayInvoiceLines where PInvLnCode='+IntToStr(LineID); GBIBS.ExecQuery; Stream.WriteInt(WareID); // код товара Stream.WriteStr(Ware.Name); // наименование товара Stream.WriteStr(GBIBS.FieldByName('PInvLnOrder').AsString); // заказ Stream.WriteStr(GBIBS.FieldByName('PInvLnCount').AsString); // факт Stream.WriteStr(Ware.MeasName); // наименование ед.изм. cliQty:= GBIBS.FieldByName('PInvLnCount').AsFloat; // новый факт sum:= GBIBS.FieldByName('PInvLnPrice').AsFloat; // цена GBIBS.Close; s:= fnGetStrSummByDoubleCurr(sum, curr); // строка с ценой в 2-х валютах Stream.WriteStr(s); if cliQty=1 then Stream.WriteStr(s) // сумма по строке else begin sum:= RoundToHalfDown(sum*cliQty); s:= fnGetStrSummByDoubleCurr(sum, curr); // строка с суммой в 2-х валютах Stream.WriteStr(s); end; Stream.WriteStr(Ware.Comment); // комментарий end else cliQty:= 0; // обнуляем новый факт для удаленной строки Stream.WriteStr(WarnMess); // предупреждение о пересчете по кратности и т.п. Cache.CheckWareRest(Ware.RestLinks, dprt, cliQty-oldQty, True); // снимаем разницу факта с остатка в кеше finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False, True); end; Stream.Position:= 0; end; //================================================ строка с суммой в 2-х валютах function fnGetStrSummByDoubleCurr(sum: Double; MainCurr: Integer): String; var k: Integer; begin Result:= ''; if not Cache.CurrExists(MainCurr) then Exit; Result:= FormatFloat('# ##0.00', sum)+' '+Cache.GetCurrName(MainCurr); if not (MainCurr in [1, cDefCurrency]) then Exit; // пока только грн и евро if MainCurr=cDefCurrency then begin k:= 1; sum:= sum*Cache.CURRENCYRATE; end else {if (MainCurr=1) then} begin k:= cDefCurrency; sum:= sum/Cache.CURRENCYRATE; end; Result:= Result+' ('+FormatFloat('# ##0.00', sum)+' '+Cache.GetCurrName(k)+')'; end; //================================ описания товаров для просмотра (счета WebArm) procedure prWebArmGetWaresDescrView(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetWaresDescrView'; // имя процедуры/функции var EmplID, ForFirmID, WareID, i, ii, sPos, j, SysID, iCri, iNode, contID: Integer; s, sView, sWareCodes, ss, CriName: string; Codes: Tas; empl: TEmplInfoItem; ware: TWareInfo; ORD_IBS, ORD_IBS1: TIBSQL; ORD_IBD: TIBDatabase; Contract: TContract; begin ORD_IBS:= nil; ORD_IBS1:= nil; Stream.Position:= 0; SetLength(Codes, 0); contID:= 0; try EmplID:= Stream.ReadInt; ForFirmID:= Stream.ReadInt; ContID:= Stream.ReadInt; // для контрактов sWareCodes:= Stream.ReadStr; // коды товаров prSetThLogParams(ThreadData, 0, EmplID, 0, 'ForFirmID='+IntToStr(ForFirmID)+ #13#10'sWareCodes='+sWareCodes); Stream.Clear; Stream.WriteInt(aeSuccess); sPos:= Stream.Position; Stream.WriteInt(0); // место под кол-во товаров Codes:= fnSplitString(sWareCodes, ','); if Length(Codes)<1 then Exit; // товаров нет - выходим // if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера if CheckNotValidUser(EmplID, isWe, s) then Exit; // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then Exit; // проверяем право пользователя // raise EBOBError.Create(MessText(mtkNotRightExists)); if not Cache.FirmExist(ForFirmID) // проверка фирмы or not Cache.CheckEmplVisFirm(EmplID, ForFirmID) then Exit; // raise EBOBError.Create(MessText(mtkNotFirmExists)); Contract:= Cache.arFirmInfo[ForFirmID].GetContract(contID); SysID:= Contract.SysID; ORD_IBD:= cntsOrd.GetFreeCnt; try ORD_IBS:= fnCreateNewIBSQL(ORD_IBD, 'ORD_IBS_'+nmProc); ORD_IBS1:= fnCreateNewIBSQL(ORD_IBD, 'ORD_IBS1_'+nmProc, -1, tpRead, true); //----------------------------------------------------- значения критериев ORD_IBS.SQL.Text:= 'select WCRICODE, WCRIDESCR, WCVSVALUE'+ ' from (select LWCVWCVSCODE from LINKWARECRIVALUES'+ ' where LWCVWARECODE=:WareID and LWCVWRONG="F")'+ ' left join WARECRIVALUES on WCVSCODE=LWCVWCVSCODE'+ ' left join WARECRITERIES on WCRICODE=WCVSWCRICODE'+ ' order by WCRIORDNUM nulls last, WCRICODE, WCVSVALUE'; ORD_IBS.Prepare; //------------------------------------------- тексты к связке товар - нода ORD_IBS1.SQL.Text:= 'select LWNTnodeID, LWNTinfotype, DITMNAME, TRNANAME,'+ ' iif(ITATEXT is null, ITTEXT, ITATEXT) text'+ // new txt ' from (select LWNTnodeID, LWNTinfotype, LWNTWIT'+ ' from LinkWareNodeText where LWNTwareID=:WareID and LWNTWRONG="F")'+ ' left join DIRINFOTYPEMODEL on DITMCODE = LWNTinfotype'+ ' left join TREENODESAUTO on TRNACODE=LWNTnodeID'+ ' left join WareInfoTexts on WITCODE=LWNTWIT'+ ' left join INFOTEXTS on ITCODE=WITTEXTCODE'+ // new txt ' left join INFOTEXTSaltern on ITACODE=ITALTERN'+ // new txt ' where TRNADTSYCODE='+IntToStr(SysID)+ ' order by LWNTnodeID, LWNTinfotype, text'; ORD_IBS1.Prepare; j:= 0; // счетчик товаров for i:= 0 to High(Codes) do begin WareID:= StrToIntDef(Codes[i], 0); if not Cache.WareExist(WareID) then Continue; ware:= Cache.GetWare(WareID); if ware.IsArchive or not ware.IsWare or not ware.CheckWareTypeSys(SysID) then Continue; Stream.WriteInt(WareID); // Передаем код товара inc(j); sView:= ''; with ware.GetWareAttrValuesView do try // список названий и значений атрибутов товара (TStringList) for ii:= 0 to Count-1 do sView:= sView+fnIfStr(sView='', '', '; ')+Names[ii]+': '+ // название атрибута ExtractParametr(Strings[ii]); // значение атрибута finally Free; end; Stream.WriteStr(sView); // Передаем строку атрибутов sView:= ''; //--------------------------------------- значения критериев ORD_IBS.ParamByName('WareID').AsInteger:= WareID; ORD_IBS.ExecQuery; while not ORD_IBS.Eof do begin iCri:= ORD_IBS.FieldByName('WCRICODE').AsInteger; CriName:= ORD_IBS.FieldByName('WCRIDESCR').AsString; s:= ''; while not ORD_IBS.Eof and (iCri=ORD_IBS.FieldByName('WCRICODE').AsInteger) do begin ss:= ORD_IBS.FieldByName('WCVSVALUE').AsString; if ss<>'' then s:= s+fnIfStr(s='', '', ', ')+ss; cntsORD.TestSuspendException; ORD_IBS.Next; end; sView:= sView+fnIfStr(sView='', '', '; ')+CriName+fnIfStr(s='', '', ': '+s); // строка по 1-му критерию end; ORD_IBS.Close; Stream.WriteStr(sView); // Передаем строку критериев sView:= ''; //----------------------------- тексты к связке товар - нода ORD_IBS1.ParamByName('WareID').AsInteger:= WareID; ORD_IBS1.ExecQuery; while not ORD_IBS1.Eof do begin iNode:= ORD_IBS1.FieldByName('LWNTnodeID').AsInteger; sView:= sView+fnIfStr(sView='', '', #13#10)+'Узел '+ORD_IBS1.FieldByName('TRNANAME').AsString+': '; while not ORD_IBS1.Eof and (iNode=ORD_IBS1.FieldByName('LWNTnodeID').AsInteger) do begin iCri:= ORD_IBS1.FieldByName('LWNTinfotype').AsInteger; CriName:= ORD_IBS1.FieldByName('DITMNAME').AsString; s:= ''; while not ORD_IBS1.Eof and (iNode=ORD_IBS1.FieldByName('LWNTnodeID').AsInteger) and (iCri=ORD_IBS1.FieldByName('LWNTinfotype').AsInteger) do begin ss:= ORD_IBS1.FieldByName('text').AsString; if ss<>'' then s:= s+fnIfStr(s='', '', ', ')+ss; cntsORD.TestSuspendException; ORD_IBS1.Next; end; // while ... and (iNode= ... and (iCri= end; // while ... and (iNode= // sView:= sView+fnIfStr(sView='', '', '; ')+CriName+fnIfStr(s='', '', ': '+s); // строка по 1-му типу текста sView:= sView+fnIfStr(sView='', '', '; ')+CriName+fnIfStr(s='', '', ': '+s); // строка по 1-му типу текста end; ORD_IBS1.Close; Stream.WriteStr(sView); // Передаем строку текстов end; // for finally prFreeIBSQL(ORD_IBS); prFreeIBSQL(ORD_IBS1); cntsOrd.SetFreeCnt(ORD_IBD); end; if j>0 then begin Stream.Position:= sPos; Stream.WriteInt(j); // Stream.Position:= Stream.Size; // если будем еще добавлять инфо по товару end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False); end; Stream.Position:= 0; SetLength(Codes, 0); end; //================================ список доставок как результат поиска (WebArm) procedure prWebarmGetDeliveries(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebarmGetDeliveries'; // имя процедуры/функции var InnerErrorPos: string; UserId, FirmID, currID, ForFirmID, FirmSys, i, CountDeliv, wareID, contID: integer; ShowAnalogs, PriceInUah: boolean; ar: Tai; begin Stream.Position:= 0; SetLength(ar, 0); FirmSys:= 0; ForFirmID:= 0; contID:= 0; FirmId:= isWe; ShowAnalogs:= False; try InnerErrorPos:='0'; UserId:= Stream.ReadInt; PriceInUah:= Stream.ReadBool; InnerErrorPos:='1'; // проверить UserID, FirmID, ForFirmID и получить систему, валюту prCheckUserForFirmAndGetSysCurr(UserID, FirmID, ForFirmID, FirmSys, CurrID, PriceInUah, contID); InnerErrorPos:='2'; CountDeliv:= Cache.DeliveriesList.Count; InnerErrorPos:='3'; prSetThLogParams(ThreadData, 0, UserID, FirmID, 'DelivQty='+IntToStr(CountDeliv)); // логирование InnerErrorPos:='4'; if CountDeliv<1 then raise EBOBError.Create('Не найдены доставки'); Stream.Clear; Stream.WriteInt(aeSuccess); InnerErrorPos:='6'; Stream.WriteStr(Cache.GetCurrName(currID)); Stream.WriteBool(ShowAnalogs); Stream.WriteInt(CountDeliv); // Передаем доставки for i:= 0 to CountDeliv-1 do begin InnerErrorPos:='7-'+IntToStr(i); wareID:= Integer(Cache.DeliveriesList.Objects[i]); prSaveShortWareInfoToStream(Stream, wareID, FirmId, UserId, 0, currID, ForFirmID, 0, contID); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, 'InnerErrorPos='+InnerErrorPos, False); end; Stream.Position:= 0; SetLength(ar, 0); end; //============================================ формирование счета на недостающие procedure prWebArmMakeSecondAccount(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmMakeSecondAccount'; // имя процедуры/функции errmess = 'Ошибка создания счета'; var GBIBD: TIBDatabase; GBIBS: TIBSQL; EmplID, AccountID, i: integer; AccountCode, s: string; empl: TEmplInfoItem; Success: boolean; begin Stream.Position:= 0; GBIBS:= nil; try EmplID:= Stream.ReadInt; // код сотрудника AccountID:= Stream.ReadInt; // код счета AccountCode:= IntToStr(AccountID); prSetThLogParams(ThreadData, 0, EmplID, 0, 'AccountID='+AccountCode); // логирование if (AccountID<1) then raise EBOBError.Create('Неверный код исходного счета'); if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя ??? raise EBOBError.Create(MessText(mtkNotRightExists)); GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpWrite, True); //------------------------- код и номер нового счета --------------------------- GBIBS.SQL.Text:= 'select RAccCode, Rnumber from Vlad_CSS_MakeSecondAcc('+AccountCode+')'; AccountCode:= ''; Success:= false; for i:= 1 to RepeatCount do try GBIBS.Close; with GBIBS.Transaction do if not InTransaction then StartTransaction; GBIBS.ExecQuery; if (GBIBS.Bof and GBIBS.Eof) then raise EBOBError.Create(errmess); AccountID:= GBIBS.FieldByName('RAccCode').AsInteger; if (AccountID<1) then raise EBOBError.Create(errmess); AccountCode:= GBIBS.FieldByName('Rnumber').AsString; if (AccountCode='') then raise EBOBError.Create(errmess); GBIBS.Transaction.Commit; GBIBS.Close; Success:= true; break; except on E: EBOBError do raise EBOBError.Create(E.Message); on E: Exception do if (Pos('lock', E.Message)>0) and (i<RepeatCount) then begin with GBIBS.Transaction do if InTransaction then RollbackRetaining; GBIBS.Close; sleep(RepeatSaveInterval); end else raise Exception.Create(E.Message); end; GBIBS.Close; if not Success then raise EBOBError.Create(errmess); //------------------------------- создали новый счет --------------------------- Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteInt(AccountID); // код нового счета Stream.WriteStr(AccountCode); // номер нового счета finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False, True); end; Stream.Position:= 0; end; //============================================== формирование накладной из счета procedure prWebArmMakeInvoiceFromAccount(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmMakeInvoiceFromAccount'; // имя процедуры/функции errmess = 'Ошибка формирования накладной из счета'; var GBIBD: TIBDatabase; GBIBS: TIBSQL; EmplID, AccountID, i, ForFirmID, ContID: integer; AccountCode, s: string; empl: TEmplInfoItem; Success: boolean; Contract: TContract; begin Stream.Position:= 0; GBIBS:= nil; ContID:= 0; try EmplID:= Stream.ReadInt; // код сотрудника AccountID:= Stream.ReadInt; // код счета ForFirmID:= Stream.ReadInt; // код к/а // ContID:= Stream.ReadInt; // для контрактов - здесь не нужен AccountCode:= IntToStr(AccountID); prSetThLogParams(ThreadData, 0, EmplID, 0, 'AccountID='+AccountCode+ ', ForFirmID='+IntToStr(ForFirmID)); // логирование if (AccountID<1) then raise EBOBError.Create('Неверный код счета'); if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя ??? raise EBOBError.Create(MessText(mtkNotRightExists)); if not Cache.CheckEmplVisFirm(EmplID, ForFirmID) then // проверка фирмы raise EBOBError.Create(MessText(mtkNotFirmExists)); Cache.TestFirms(ForFirmID, True, True, False); if not Cache.FirmExist(ForFirmID) then raise EBOBError.Create(MessText(mtkNotFirmExists)); GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpRead, True); GBIBS.SQL.Text:= 'select PINVCONTRACTCODE from PayInvoiceReestr'+ ' where PInvCode='+AccountCode; GBIBS.ExecQuery; if (GBIBS.Bof and GBIBS.Eof) then raise EBOBError.Create('Не найден счет код='+AccountCode); i:= GBIBS.FieldByName('PINVCONTRACTCODE').AsInteger; GBIBS.Close; contID:= i; Contract:= Cache.arFirmInfo[ForFirmID].GetContract(contID); if (contID<>i) then raise EBOBError.Create(MessText(mtkNotFoundCont, IntToStr(i))); if Contract.SaleBlocked then // проверка доступности отгрузки ??? raise EBOBError.Create('Отгрузка запрещена'); s:= FormatDateTime(cDateFormatY4, Date); i:= HourOf(Now); //------------------------- код и номер накладной ------------------------------ fnSetTransParams(GBIBS.Transaction, tpWrite, True); GBIBS.SQL.Text:= 'select InvcCode, InvcNumber from DCMAKEINVOICEFROMACCOUNTFOR35('+ AccountCode+', "'+s+'", '+IntToStr(i)+', 0, "") m'+ ' left join INVOICEREESTR on InvcCode=m.RINVCCODE'; AccountCode:= ''; Success:= false; for i:= 1 to RepeatCount do try GBIBS.Close; with GBIBS.Transaction do if not InTransaction then StartTransaction; GBIBS.ExecQuery; if (GBIBS.Bof and GBIBS.Eof) then raise EBOBError.Create(errmess); AccountID:= GBIBS.FieldByName('InvcCode').AsInteger; if (AccountID<1) then raise EBOBError.Create(errmess); AccountCode:= GBIBS.FieldByName('InvcNumber').AsString; if (AccountCode='') then raise EBOBError.Create(errmess); GBIBS.Transaction.Commit; GBIBS.Close; Success:= true; break; except on E: EBOBError do raise EBOBError.Create(E.Message); on E: Exception do if (Pos('lock', E.Message)>0) and (i<RepeatCount) then begin with GBIBS.Transaction do if InTransaction then RollbackRetaining; GBIBS.Close; sleep(RepeatSaveInterval); end else raise Exception.Create(E.Message); end; GBIBS.Close; if not Success then raise EBOBError.Create(errmess); //------------------------------- создали накладную --------------------------- Stream.Clear; Stream.WriteInt(aeSuccess); // знак того, что запрос обработан корректно Stream.WriteInt(AccountID); // код накладной Stream.WriteStr(AccountCode); // номер накладной finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False, True); end; Stream.Position:= 0; end; //===================================== список накладных передачи (счета WebArm) procedure prWebArmGetTransInvoicesList(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetTransInvoicesList'; // имя процедуры/функции var EmplID, i, sPos, j, DprtFrom, DprtTo: Integer; s: string; empl: TEmplInfoItem; GBIBS: TIBSQL; GBIBD: TIBDatabase; dd, ddFrom: Double; flOpened: Boolean; begin GBIBS:= nil; Stream.Position:= 0; try EmplID := Stream.ReadInt; // код сотрудника ddFrom := Stream.ReadDouble; // начиная с даты док-та DprtFrom:= Stream.ReadInt; // подр.отгрузки DprtTo := Stream.ReadInt; // подр.приема flOpened:= Stream.ReadBool; // только открытые prSetThLogParams(ThreadData, 0, EmplID, 0, 'ddFrom='+DateToStr(ddFrom)+' DprtFrom='+ IntToStr(DprtFrom)+' DprtTo='+IntToStr(DprtTo)+' flOpened='+BoolToStr(flOpened)); // логирование if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя ??? raise EBOBError.Create(MessText(mtkNotRightExists)); dd:= IncDay(Date, -7); // ограничиваем начальную дату - не более 7 дней if (ddFrom<dd) then ddFrom:= dd; // формируем условия по фильтрам s:= ' and TRINPRINTLOCK="F" and TRINBYNORMKEY="F"'; // неблокированные не по нормам if (DprtFrom>0) then s:= s+' and TRINSORCDPRTCODE='+IntToStr(DprtFrom); // подр.отгрузки if (DprtTo>0) then s:= s+' and TRINDESTDPRTCODE='+IntToStr(DprtTo); // подр.отгрузки if flOpened then s:= s+' and TRINEXECUTED="F"'+ // неисполненные открытые ' and (otwhcode is null and inwhcode is null)'; // Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteDouble(ddFrom); // начальная дата (могла измениться) sPos:= Stream.Position; Stream.WriteInt(0); // место под кол-во GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpRead, True); GBIBS.SQL.Text:= 'select TRINCODE, TRINNUMBER, TRINDATE, TRINSORCDPRTCODE,'+ ' TRINDESTDPRTCODE, TRINSHIPMENTMETHODCODE, TRINSHIPMENTDATE, TRINBYNORMKEY,'+ ' TRINSHIPMENTTIMECODE, TRINCOMMENTS, TRINPRINTLOCK, TRINEXECUTED,'+ ' iif(otwhcode is null and inwhcode is null, 0, 1) hcode from TRANSFERINVOICEREESTR'+ ' left join AdditionalCheckMainWMSDocm(97, TrInCode, "T") io on 1=1'+ ' left join AdditionalCheckMainWMSDocm(97, TrInCode, "F") ii on 1=1'+ ' left join OUTWAREHOUSEREESTR ow on OTWHCODE=TrInWMSDocmCode'+ ' and io.RCorrect="T" and OtWhMainDocmType=97'+ ' left join inwarehousereestr iw on inwhcode=TrInWMSDocmCode'+ ' and ii.RCorrect="T" and inwhmaindocmtype=97'+ ' where TRINSUBFIRMCODE=1 and TRINDATE>=:dd'+s; // начиная с даты док-та GBIBS.ParamByName('dd').AsDateTime:= dd; GBIBS.ExecQuery; j:= 0; // счетчик строк while not GBIBS.Eof do begin i:= GBIBS.FieldByName('TRINCODE').AsInteger; Stream.WriteInt(i); // код док-та s:= GBIBS.FieldByName('TRINNUMBER').AsString; Stream.WriteStr(s); // номер док-та dd:= GBIBS.FieldByName('TRINDATE').AsDateTime; Stream.WriteDouble(dd); // дата док-та i:= GBIBS.FieldByName('TRINSORCDPRTCODE').AsInteger; Stream.WriteInt(i); // код подр. отгрузки i:= GBIBS.FieldByName('TRINDESTDPRTCODE').AsInteger; Stream.WriteInt(i); // код подр. приема i:= GBIBS.FieldByName('TRINSHIPMENTMETHODCODE').AsInteger; Stream.WriteInt(i); // код способа отгрузки dd:= GBIBS.FieldByName('TRINSHIPMENTDATE').AsDateTime; Stream.WriteDouble(dd); // дата отгрузки i:= GBIBS.FieldByName('TRINSHIPMENTTIMECODE').AsInteger; Stream.WriteInt(i); // код времени отгрузки s:= GBIBS.FieldByName('TRINCOMMENTS').AsString; Stream.WriteStr(s); // комментарий if (GBIBS.FieldByName('TRINEXECUTED').AsString='T') then s:= 'Исполнен' else if (GBIBS.FieldByName('hcode').AsInteger>0) then s:= 'Обработка' else s:= 'Открыт'; Stream.WriteStr(s); // статус // fl:= GBIBS.FieldByName('TRINPRINTLOCK').AsString='T'; // Stream.WriteBool(fl); // блокировка после печати // fl:= GBIBS.FieldByName('TRINBYNORMKEY').AsString='T'; // Stream.WriteBool(fl); // по нормам // fl:= False; // заглушка // Stream.WriteBool(fl); // Необходимость подтверждения inc(j); GBIBS.Next; end; finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; if j>0 then begin Stream.Position:= sPos; Stream.WriteInt(j); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False, True); end; Stream.Position:= 0; end; //=================================== просмотр накладной передачи (счета WebArm) procedure prWebArmGetTransInvoice(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetTransInvoice'; // имя процедуры/функции var EmplID, InvID, i, sPos, j: Integer; s, InvCode: string; empl: TEmplInfoItem; GBIBS: TIBSQL; GBIBD: TIBDatabase; dd: Double; begin GBIBS:= nil; Stream.Position:= 0; try EmplID:= Stream.ReadInt; // код сотрудника InvID := Stream.ReadInt; // код накл.передачи InvCode:= IntToStr(InvID); prSetThLogParams(ThreadData, 0, EmplID, 0, 'InvID='+InvCode); // логирование if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя ??? raise EBOBError.Create(MessText(mtkNotRightExists)); Stream.Clear; Stream.WriteInt(aeSuccess); GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); j:= 0; // счетчик строк товаров try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpRead, True); GBIBS.SQL.Text:= 'select TRINNUMBER, TRINDATE, TRINSORCDPRTCODE,'+ ' TRINDESTDPRTCODE, TRINSHIPMENTMETHODCODE, TRINSHIPMENTDATE, TRINBYNORMKEY,'+ ' TRINSHIPMENTTIMECODE, TRINCOMMENTS, TRINPRINTLOCK, TRINEXECUTED,'+ ' iif(otwhcode is null and inwhcode is null, 0, 1) hcode from TRANSFERINVOICEREESTR'+ ' left join AdditionalCheckMainWMSDocm(97, TrInCode, "T") io on 1=1'+ ' left join AdditionalCheckMainWMSDocm(97, TrInCode, "F") ii on 1=1'+ ' left join OUTWAREHOUSEREESTR ow on OTWHCODE=TrInWMSDocmCode'+ ' and io.RCorrect="T" and OtWhMainDocmType=97'+ ' left join inwarehousereestr iw on inwhcode=TrInWMSDocmCode'+ ' and ii.RCorrect="T" and inwhmaindocmtype=97'+ ' where TRINCODE='+InvCode; GBIBS.ExecQuery; if (GBIBS.Bof and GBIBS.Eof) then raise EBOBError.Create('Не найдена накладная'); Stream.WriteInt(InvID); // код док-та s:= GBIBS.FieldByName('TRINNUMBER').AsString; Stream.WriteStr(s); // номер док-та dd:= GBIBS.FieldByName('TRINDATE').AsDateTime; Stream.WriteDouble(dd); // дата док-та i:= GBIBS.FieldByName('TRINSORCDPRTCODE').AsInteger; Stream.WriteInt(i); // код подр. отгрузки s:= Cache.GetDprtMainName(i); Stream.WriteStr(s); // наимен. подр. отгрузки i:= GBIBS.FieldByName('TRINDESTDPRTCODE').AsInteger; Stream.WriteInt(i); // код подр. приема s:= Cache.GetDprtMainName(i); Stream.WriteStr(s); // наимен. подр. приема i:= GBIBS.FieldByName('TRINSHIPMENTMETHODCODE').AsInteger; Stream.WriteInt(i); // код способа отгрузки with Cache.ShipMethods do if ItemExists(i) then s:= GetItemName(i) else s:= ''; Stream.WriteStr(s); // наимен. способа отгрузки dd:= GBIBS.FieldByName('TRINSHIPMENTDATE').AsDateTime; Stream.WriteDouble(dd); // дата отгрузки i:= GBIBS.FieldByName('TRINSHIPMENTTIMECODE').AsInteger; Stream.WriteInt(i); // код времени отгрузки with Cache.ShipTimes do if ItemExists(i) then s:= GetItemName(i) else s:= ''; Stream.WriteStr(s); // значение времени отгрузки s:= GBIBS.FieldByName('TRINCOMMENTS').AsString; Stream.WriteStr(s); // комментарий if (GBIBS.FieldByName('TRINEXECUTED').AsString='T') then s:= 'Исполнен' else if (GBIBS.FieldByName('hcode').AsInteger>0) then s:= 'Обработка' else s:= 'Открыт'; Stream.WriteStr(s); // статус GBIBS.Close; sPos:= Stream.Position; Stream.WriteInt(0); // место под кол-во GBIBS.SQL.Text:= 'select TrInLnWareCode, TrInLnPlanCount, TrInLnCount, TrInLnUnitCode'+ ' from TransferInvoiceLines where TrInLnDocmCode='+InvCode; GBIBS.ExecQuery; while not GBIBS.Eof do begin i:= GBIBS.FieldByName('TrInLnWareCode').AsInteger; Stream.WriteInt(i); // код товара if Cache.WareExist(i) then s:= Cache.GetWare(i).Name else s:= ''; Stream.WriteStr(s); // наимен. товара dd:= GBIBS.FieldByName('TrInLnPlanCount').AsFloat; Stream.WriteDouble(dd); // план dd:= GBIBS.FieldByName('TrInLnCount').AsFloat; Stream.WriteDouble(dd); // кол-во i:= GBIBS.FieldByName('TrInLnUnitCode').AsInteger; Stream.WriteInt(i); // код ед.изм. s:= Cache.GetMeasName(i); Stream.WriteStr(s); // наимен. ед.изм. inc(j); GBIBS.Next; end; if j>0 then begin Stream.Position:= sPos; Stream.WriteInt(j); end; finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False, True); end; Stream.Position:= 0; end; //============== добавление товаров из счета в накладную передачи (счета WebArm) procedure prWebArmAddWaresFromAccToTransInv(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmAddWaresFromAccToTransInv'; // имя процедуры/функции var EmplID, InvID, AccID, i, DprtFrom, DprtTo, TimeID, ii: Integer; s, InvCode, AccCode, sLineCodes, Comment, InvNumber: string; empl: TEmplInfoItem; GBIBS: TIBSQL; GBIBD: TIBDatabase; ddShip: Double; arLineCodes: Tas; lst: TStringList; begin GBIBS:= nil; Stream.Position:= 0; SetLength(arLineCodes, 0); lst:= TStringList.Create; try EmplID:= Stream.ReadInt; // код сотрудника AccID:= Stream.ReadInt; // код счета sLineCodes:= Stream.ReadStr; // коды строк счета для обработки InvID:= Stream.ReadInt; // код накл.передачи (<1 - создавать новую) if (InvID<1) then begin // новая накладная DprtFrom:= Stream.ReadInt; // склад отгрузки DprtTo:= Stream.ReadInt; // склад приема ddShip:= Stream.ReadDouble; // дата отгрузки TimeID:= Stream.ReadInt; // код времени отгрузки Comment:= Stream.ReadStr; // комментарий end else begin DprtFrom:= 0; DprtTo:= 0; ddShip:= 0; TimeID:= 0; Comment:= ''; end; AccCode:= IntToStr(AccID); InvCode:= IntToStr(InvID); prSetThLogParams(ThreadData, 0, EmplID, 0, 'AccID='+AccCode+', InvID='+InvCode+', InvID='); // логирование if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера empl:= Cache.arEmplInfo[EmplID]; if not empl.UserRoleExists(rolOPRSK) then // проверяем право пользователя ??? raise EBOBError.Create(MessText(mtkNotRightExists)); arLineCodes:= fnSplitString(sLineCodes, ','); if length(arLineCodes)<1 then raise EBOBError.Create('Нет строк для обработки'); if (InvID<1) then begin // новая накладная if not Cache.DprtExist(DprtFrom) then raise EBOBError.Create('Не найдено п/р отгрузки'); if not Cache.DprtExist(DprtTo) then raise EBOBError.Create('Не найдено п/р приема'); if (TimeID>0) and not Cache.ShipTimes.ItemExists(TimeID) then raise EBOBError.Create('Не найдено время отгрузки'); end; GBIBD:= CntsGRB.GetFreeCnt(empl.GBLogin, cDefPassword, cDefGBrole); try GBIBS:= fnCreateNewIBSQL(GBIBD, 'GBIBS_'+nmProc, ThreadData.ID, tpWrite, True); if (InvID>0) then begin //-------- проверяем статус существующей накладной GBIBS.SQL.Text:= 'select iif(otwhcode is null and inwhcode is null, 0, 1) hcode,'+ ' TRINNUMBER, TRINEXECUTED, TRINSORCDPRTCODE, TRINDESTDPRTCODE from TRANSFERINVOICEREESTR'+ ' left join AdditionalCheckMainWMSDocm(97, TrInCode, "T") io on 1=1'+ ' left join AdditionalCheckMainWMSDocm(97, TrInCode, "F") ii on 1=1'+ ' left join OUTWAREHOUSEREESTR ow on OTWHCODE=TrInWMSDocmCode'+ ' and io.RCorrect="T" and OtWhMainDocmType=97'+ ' left join inwarehousereestr iw on inwhcode=TrInWMSDocmCode'+ ' and ii.RCorrect="T" and inwhmaindocmtype=97'+ ' where TRINCODE='+InvCode; GBIBS.ExecQuery; if (GBIBS.Bof and GBIBS.Eof) then raise EBOBError.Create('Не найдена накладная передачи'); if (GBIBS.FieldByName('TRINEXECUTED').AsString='T') then s:= 'Исполнен' else if (GBIBS.FieldByName('hcode').AsInteger>0) then s:= 'Обработка' else s:= ''; InvNumber:= GBIBS.FieldByName('TRINNUMBER').AsString; DprtFrom:= GBIBS.FieldByName('TRINSORCDPRTCODE').AsInteger; DprtTo:= GBIBS.FieldByName('TRINDESTDPRTCODE').AsInteger; GBIBS.Close; if (s<>'') then raise EBOBError.Create('Накладная передачи '+InvNumber+' имеет статус '+s); end; if (InvID<1) then begin //-------------------------------- новая накладная GBIBS.SQL.Text:= 'insert into TRANSFERINVOICEREESTR (TRINNUMBER, TRINDATE,'+ ' TRINHOUR, TRINSUBFIRMCODE, TRINSORCDPRTCODE, TRINDESTDPRTCODE,'+ ' TRINSHIPMENTDATE, TRINSHIPMENTTIMECODE, TRINCOMMENTS) values '+ '("< АВТО >", "TODAY", EXTRACT(HOUR FROM CURRENT_TIMESTAMP), 1,'+ IntToStr(DprtFrom)+', '+IntToStr(DprtTo)+', '+ fnIfStr(ddShip>DateNull, ':ddShip', 'null')+', '+ fnIfStr(TimeID>0, IntToStr(TimeID), 'null')+', '+ fnIfStr(Comment<>'', ':comm', 'null')+') returning TRINCODE, TRINNUMBER'; if (ddShip>DateNull) then GBIBS.ParamByName('ddShip').AsDateTime:= ddShip; if (Comment<>'') then GBIBS.ParamByName('comm').AsString:= Comment; s:= 'Ошибка создания накладной передачи'; GBIBS.ExecQuery; if (GBIBS.Bof and GBIBS.Eof) then raise EBOBError.Create(s); InvID:= GBIBS.FieldByName('TRINCODE').AsInteger; if (InvID<1) then raise EBOBError.Create(s); InvCode:= IntToStr(InvID); InvNumber:= GBIBS.FieldByName('TRINNUMBER').AsString; GBIBS.Close; end; //---------------- пишем строки в накладную GBIBS.SQL.Text:= 'select rWareCode, rTransfer, rUnitCode'+ ' from Vlad_CSS_WaresFromAccToTrInv('+AccCode+', :aAccLineCode, '+InvCode+')'; GBIBS.Prepare; for i:= 0 to High(arLineCodes) do try GBIBS.ParamByName('aAccLineCode').AsString:= arLineCodes[i]; GBIBS.ExecQuery; if (GBIBS.Bof and GBIBS.Eof) then Continue; ii:= GBIBS.FieldByName('rWareCode').AsInteger; // код товара if not Cache.WareExist(ii) then Continue; if (GBIBS.FieldByName('rTransfer').AsInteger<1) then Continue; s:= fnMakeAddCharStr(GBIBS.FieldByName('rTransfer').AsString, 10)+ // кол-во ' '+Cache.GetMeasName(GBIBS.FieldByName('rUnitCode').AsInteger); // ед.изм. s:= Cache.GetWare(ii).Name+cSpecDelim+s; lst.Add(s); // наимен.товара|||кол-во ед.изм. finally GBIBS.Close; end; if (lst.Count<1) then raise EBOBError.Create('Нет записанных строк'); GBIBS.Transaction.Commit; finally prFreeIBSQL(GBIBS); cntsGRB.SetFreeCnt(GBIBD); end; Stream.Clear; Stream.WriteInt(aeSuccess); Stream.WriteInt(lst.Count+2); s:= 'Добавлены товары в накладную передачи '+InvNumber; // заголовок - 2 строки Stream.WriteStr(s); s:= '('+Cache.GetDprtMainName(DprtFrom)+' - '+Cache.GetDprtMainName(DprtTo)+')'; Stream.WriteStr(s); for i:= 0 to lst.Count-1 do Stream.WriteStr(lst[i]); //------ строки товаров except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False, True); end; Stream.Position:= 0; SetLength(arLineCodes, 0); prFree(lst); end; //================================================== список уведомлений (WebArm) procedure prWebArmGetNotificationsParams(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prWebArmGetNotificationsParams'; // имя процедуры/функции var EmplID, noteID, FirmID, LineCount, FirmCount, pos, j: Integer; s: string; // empl: TEmplInfoItem; IBS: TIBSQL; IBD: TIBDatabase; Filials, Classes, Types, Firms: TIntegerList; flAdd, flAuto, flMoto: Boolean; begin IBS:= nil; Stream.Position:= 0; Filials:= TIntegerList.Create; Classes:= TIntegerList.Create; Types := TIntegerList.Create; Firms := TIntegerList.Create; try EmplID:= Stream.ReadInt; // код сотрудника noteID:= Stream.ReadInt; // код уведомления (<1 - все) prSetThLogParams(ThreadData, 0, EmplID, 0, 'noteID='+IntToStr(noteID)); // логирование if CheckNotValidUser(EmplID, isWe, s) then raise EBOBError.Create(s); // проверка юзера // empl:= Cache.arEmplInfo[EmplID]; if not Cache.arEmplInfo[EmplID].UserRoleExists(rolNewsManage) then // проверяем право пользователя raise EBOBError.Create(MessText(mtkNotRightExists)); Stream.Clear; Stream.WriteInt(aeSuccess); pos:= Stream.Position; Stream.WriteInt(0); LineCount:= 0; IBD:= CntsORD.GetFreeCnt; try IBS:= fnCreateNewIBSQL(IBD, 'IBS_'+nmProc, ThreadData.ID, tpRead, True); IBS.SQL.Text:= 'select NoteCODE, NoteBegDate, NoteEndDate, NoteText,'+ ' NoteFilials, NoteClasses, NoteTypes, NoteFirms, NoteUpdTime,'+ ' NOTEUSERID, NOTEFIRMSADDFLAG, NOTEauto, NOTEmoto, c.rCliCount, c.rFirmCount'+ ' from Notifications left join GetNotifiedCounts(NoteCODE) c on 1=1'+ ' where NoteArchived="F"'+fnIfStr(noteID>0, ' and NoteCODE='+IntToStr(noteID), '')+ ' order by NoteBegDate, NoteEndDate'; IBS.ExecQuery; while not IBS.Eof do begin Stream.WriteInt(IBS.FieldByName('NoteCODE').AsInteger); // код уведомления Stream.WriteDouble(IBS.FieldByName('NoteBegDate').AsDate); // дата начала Stream.WriteDouble(IBS.FieldByName('NoteEndDate').AsDate); // дата окончания Stream.WriteStr(IBS.FieldByName('NoteText').AsString); // текст уведомления //------------------------------------------------------ последняя корректировка EmplID:= IBS.FieldByName('NOTEUSERID').AsInteger; // код юзера if Cache.EmplExist(EmplID) then s:= Cache.arEmplInfo[EmplID].EmplShortName else s:= ''; Stream.WriteStr(s); // ФИО юзера Stream.WriteDouble(IBS.FieldByName('NoteUpdTime').AsDateTime); // дата и время //---------------------------------- вычисляем к-во к/а, охваченных уведомлением Filials.Clear; // коды филиалов к/а for j in fnArrOfCodesFromString(IBS.FieldByName('NoteFilials').AsString) do Filials.Add(j); Classes.Clear; // коды категорий к/а for j in fnArrOfCodesFromString(IBS.FieldByName('NoteClasses').AsString) do Classes.Add(j); Types.Clear; // коды типов к/а for j in fnArrOfCodesFromString(IBS.FieldByName('NoteTypes').AsString) do Types.Add(j); Firms.Clear; // коды к/а for j in fnArrOfCodesFromString(IBS.FieldByName('NoteFirms').AsString) do Firms.Add(j); flAdd := GetBoolGB(ibs, 'NOTEFIRMSADDFLAG'); // флаг - добавлять/исключать коды Firms flAuto:= GetBoolGB(ibs, 'NOTEauto'); // флаг рассылки к/а с авто-контрактами flMoto:= GetBoolGB(ibs, 'NOTEmoto'); // флаг рассылки к/а с мото-контрактами FirmCount:= 0; for FirmID:= 1 to High(Cache.arFirmInfo) do // проверка соответствия к/а условиям фильтрации if CheckFirmFilterConditions(FirmID, flAdd, flAuto, flMoto, Filials, Classes, Types, Firms) then inc(FirmCount); Stream.WriteInt(FirmCount); //------------------------------------------------------------------------------ Stream.WriteInt(IBS.FieldByName('rFirmCount').AsInteger); // к-во ознакомленных к/а Stream.WriteInt(IBS.FieldByName('rCliCount').AsInteger); // к-во ознакомленных пользователей inc(LineCount); IBS.Next; end; finally prFreeIBSQL(IBS); cntsORD.SetFreeCnt(IBD); end; if LineCount>0 then begin Stream.Position:= pos; Stream.WriteInt(LineCount); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False, True); end; Stream.Position:= 0; prFree(Filials); prFree(Classes); prFree(Types); prFree(Firms); end; //============================ дерево типов товаров (сортировка по наименованию) procedure prGetWareTypesTree(Stream: TBoBMemoryStream; ThreadData: TThreadData); const nmProc = 'prGetWareTypesTree'; // имя процедуры/функции var pos, LineCount: Integer; // UserID, FirmID: Integer; IBS: TIBSQL; IBD: TIBDatabase; s: String; begin IBS:= nil; Stream.Position:= 0; try s:= Cache.GetConstItem(pcWareTypeRootCode).StrValue; if (s='') then raise EBOBError.Create(MessText(mtkNotValidParam)); // FirmID:= Stream.ReadInt; // UserID:= Stream.ReadInt; Stream.ReadInt; Stream.ReadInt; IBD:= CntsGRB.GetFreeCnt; LineCount:= 0; Stream.Clear; Stream.WriteInt(aeSuccess); pos:= Stream.Position; Stream.WriteInt(LineCount); try IBS:= fnCreateNewIBSQL(IBD, 'IBS_'+nmProc, ThreadData.ID, tpRead, True); IBS.ParamCheck:= False; IBS.SQL.Add('execute block returns (Rmaster integer, Rcode integer, Rname varchar(100))'); IBS.SQL.Add('as declare variable xMasterCode integer='+s+';'); IBS.SQL.Add('declare variable xChild integer; begin'); IBS.SQL.Add(' if (exists(select * from WARES where WAREMASTERCODE=:xMasterCode)) then begin'); IBS.SQL.Add(' for select WARECODE, WAREOFFICIALNAME, WARECHILDCOUNT from WARES'); IBS.SQL.Add(' where WAREMASTERCODE=:xMasterCode order by WAREOFFICIALNAME'); IBS.SQL.Add(' into :Rmaster, :Rname, :xChild do begin Rcode=Rmaster; suspend;'); IBS.SQL.Add(' if (xChild>0) then for select WARECODE, WAREOFFICIALNAME'); IBS.SQL.Add(' from WARES where WAREMASTERCODE = :Rmaster order by WAREOFFICIALNAME'); IBS.SQL.Add(' into :Rcode, :Rname do suspend; end end end'); IBS.ExecQuery; while not IBS.Eof do begin Stream.WriteInt(IBS.FieldByName('Rmaster').AsInteger); Stream.WriteInt(IBS.FieldByName('Rcode').AsInteger); Stream.WriteStr(IBS.FieldByName('Rname').AsString); inc(LineCount); IBS.Next; end; finally prFreeIBSQL(IBS); CntsGRB.SetFreeCnt(IBD); end; if LineCount>0 then begin Stream.Position:= pos; Stream.WriteInt(LineCount); end; except on E: EBOBError do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', True); on E: Exception do prSaveCommonError(Stream, ThreadData, nmProc, E.Message, '', False, True); end; Stream.Position:= 0; end; //============================================ 53-stamp - переброска к/а Гроссби procedure prGetFirmClones(pUserID: Integer; pFileName: String; ThreadData: TThreadData=nil); const nmProc = 'prGetFirmClones'; // имя процедуры/функции var ordIBD, gbIBD, gbIBDw: TIBDatabase; ordIBS, gbIBS, gbIBSw: TIBSQL; lstSQL, lstSQL1: TStringList; Firm1, Cont1, fil, dprt, i: Integer; s, ss, sf1, sFirm: String; Percent: real; begin ordIBS:= nil; gbIBS:= nil; gbIBSw:= nil; // gbIBDw:= nil; // ordIBD:= nil; lstSQL:= fnCreateStringList(False, 10); // список строк SQL для изменения логинов и признаков обработки к/а lstSQL1:= fnCreateStringList(False, 10); // список строк SQL для изменения архивных логинов Percent:= 1; SetExecutePercent(pUserID, ThreadData, Percent); try gbIBD:= cntsGRB.GetFreeCnt('', '', '', True); gbIBDw:= cntsGRB.GetFreeCnt('', '', '', True); ordIBD:= cntsORD.GetFreeCnt('', '', '', True); try gbIBS:= fnCreateNewIBSQL(gbIBD, 'gbIBS_'+nmProc, -1, tpRead, true); gbIBS.SQL.Text:= 'select count(*) from firms where FirmCloneSource="T"'; gbIBS.ExecQuery; fil:= gbIBS.Fields[0].AsInteger; // кол-во фирм для обработки gbIBS.Close; if (fil>0) then Percent:= 90/fil else raise EBOBError.Create('Не найдены к/а для клонирования'); SetExecutePercent(pUserID, ThreadData, Percent); prMessageLOGn('к/а-источник;контракт;к/а-приемник;контракт;результат', pFileName); ordIBS:= fnCreateNewIBSQL(ordIBD, 'ordIBS_'+nmProc, -1, tpWrite, true); s:= IntToStr(pUserID); ordIBS.SQL.Text:= 'select rClientOld, rArhLogin from CloneFirm(:FirmFrom,'+ ' :ContFrom, :FirmTo, :ContTo, :FilialTo, :DprtTo, '+s+', :Clients)'; gbIBSw:= fnCreateNewIBSQL(gbIBDw, 'gbIBSw_'+nmProc, -1, tpWrite, true); gbIBS.SQL.Text:= 'select f.firmcode as firm1, f1.firmcode as Firm2,'+ ' c.contcode as Cont1, c1.contcode as Cont2, h.ctshlkdprtcode as dprt,'+ ' f.firmmainname as fname1, f1.firmmainname as fname2,'+ ' c.contnumber||"-"||RIGHT(cast(EXTRACT(YEAR FROM c.contbeginingdate) as varchar(4)), 2) as cNum1,'+ ' c1.contnumber||"-"||RIGHT(cast(EXTRACT(YEAR FROM c1.contbeginingdate) as varchar(4)), 2) as cNum2,'+ ' p.prsnlogin as login1, p.prsncode as CliCode1,'+ ' p1.prsnlogin as login2, p1.prsncode as CliCode2 from firms f'+ ' left join contract c on c.contsecondparty=f.firmcode'+ ' left join contract c1 on c1.contclonecontsource=c.contcode'+ ' left join contractstorehouselink h on h.ctshlkcontcode=c1.contcode and h.ctshlkdefault="T"'+ ' left join firms f1 on f1.firmcode=c1.contsecondparty'+ ' left join persons p on p.prsnfirmcode=f.firmcode and p.prsnlogin is not null'+ ' left join persons p1 on p1.prsnfirmcode=f1.firmcode and p1.prsnlogin=p.prsnlogin'+ ' where f.FirmCloneSource="T" and c1.contcode>0 order by Firm1, Cont1'; // ' where f.FirmCloneSource="T" and p.prsncode<>p1.prsncode order by Firm1, Cont1'; gbIBS.ExecQuery; while not gbIBS.Eof do begin Firm1:= gbIBS.FieldByName('firm1').AsInteger; sFirm:= gbIBS.FieldByName('firm1').AsString; lstSQL.Clear; lstSQL.Add('execute block as begin'); sf1:= gbIBS.FieldByName('fname1').AsString+'('+sFirm+');'; while not gbIBS.Eof and (Firm1=gbIBS.FieldByName('firm1').AsInteger) do begin Cont1:= gbIBS.FieldByName('Cont1').AsInteger; ss:= sf1+gbIBS.FieldByName('cNum1').AsString+';'+ gbIBS.FieldByName('fname2').AsString+'('+gbIBS.FieldByName('firm2').AsString+');'+ gbIBS.FieldByName('cNum2').AsString+';'; if (Firm1=gbIBS.FieldByName('firm2').AsInteger) then begin ss:= ss+'контракты одного к/а в СВК не клонируются'; prMessageLOGn(ss, pFileName); prMessageLOGS(nmProc+': '+ss, 'import_test', False); // логирование while not gbIBS.Eof and (Cont1=gbIBS.FieldByName('Cont1').AsInteger) do gbIBS.Next; Continue; end; { ss:= gbIBS.FieldByName('fname1').AsString+'('+gbIBS.FieldByName('firm1').AsString+');'+ gbIBS.FieldByName('cNum1').AsString+';'; s:= ''; if (gbIBS.FieldByName('Firm2').AsInteger<1) then begin s:= 'не найден к/а-приемник'; ss:= ss+';'; end else ss:= ss+gbIBS.FieldByName('fname2').AsString+'('+gbIBS.FieldByName('firm2').AsString+');'; if (gbIBS.FieldByName('Cont2').AsInteger<1) then begin s:= 'не найден контракт-приемник'; ss:= ss+';'; end else ss:= ss+gbIBS.FieldByName('cNum2').AsString+';'; if (s<>'') then begin // если не нашли, куда переносить ss:= ss+s; prMessageLOGn(ss, pFileName); prMessageLOGS(nmProc+': '+ss, 'import_test', False); // логирование while not gbIBS.Eof and (Cont1=gbIBS.FieldByName('Cont1').AsInteger) do gbIBS.Next; Continue; end; } with ordIBS.Transaction do if not InTransaction then StartTransaction; ordIBS.ParamByName('FirmFrom').AsInteger:= Firm1; ordIBS.ParamByName('ContFrom').AsInteger:= Cont1; ordIBS.ParamByName('FirmTo').AsInteger:= gbIBS.FieldByName('Firm2').AsInteger; ordIBS.ParamByName('ContTo').AsInteger:= gbIBS.FieldByName('Cont2').AsInteger; dprt:= gbIBS.FieldByName('dprt').AsInteger; ordIBS.ParamByName('DprtTo').AsInteger:= dprt; if Cache.DprtExist(dprt) then fil:= Cache.arDprtInfo[dprt].FilialID else fil:= 0; ordIBS.ParamByName('FilialTo').AsInteger:= fil; s:= ''; // собираем строку с логинами и кодами клиентов while not gbIBS.Eof and (Cont1=gbIBS.FieldByName('Cont1').AsInteger) do begin if (gbIBS.FieldByName('CliCode1').AsInteger<>gbIBS.FieldByName('CliCode2').AsInteger) and (gbIBS.FieldByName('login1').AsString=gbIBS.FieldByName('login2').AsString) then s:= s+fnIfStr(s='', '', ';')+gbIBS.FieldByName('login2').AsString+'='+gbIBS.FieldByName('CliCode2').AsString; gbIBS.Next; end; if (s='') then begin ss:= ss+'нет данных о сотрудниках с логинами для клонирования в СВК'; prMessageLOGn(ss, pFileName); prMessageLOGS(nmProc+': '+ss, 'import_test', False); // логирование while not gbIBS.Eof and (Cont1=gbIBS.FieldByName('Cont1').AsInteger) do gbIBS.Next; Continue; end; ordIBS.ParamByName('Clients').AsString:= s; try ordIBS.ExecQuery; //------------------------- клонируем к/а в db_ORD s:= ''; while not ordIBS.Eof do begin if (ordIBS.FieldByName('rClientOld').AsInteger<0) then // аннулировано/перенесено заказов - в лог s:= s+' '+ordIBS.FieldByName('rArhLogin').AsString else if (ordIBS.FieldByName('rClientOld').AsInteger>0) then lstSQL.Add('update persons set prsnlogin="'+ordIBS.FieldByName('rArhLogin').AsString+ '" where prsncode='+ordIBS.FieldByName('rClientOld').AsString+';'); ordIBS.Next; end; ordIBS.Transaction.Commit; ss:= ss+'клонирован в СВК'; prMessageLOGS(nmProc+': '+ss+#13#10+s, 'import_test', False); // логирование переноса заказов except on E: Exception do begin with ordIBS.Transaction do if InTransaction then Rollback; ss:= ss+'ошибка клонирования в СВК'; prMessageLOGS(nmProc+': '+ss+#13#10+CutEMess(E.Message), 'import'); end; end; ordIBS.Close; prMessageLOGn(ss, pFileName); end; // while ... (Firm1= lstSQL1.Add(sFirm); // здесь собираем коды символьные к/а // отключение признака клонирования к/а в Grossbee и замена логинов на старых кодах клиентов lstSQL.Add(' update firms set FirmCloneSource="F" where firmcode='+sFirm+';'); lstSQL.Add('end'); with gbIBSw.Transaction do if not InTransaction then StartTransaction; gbIBSw.SQL.Clear; gbIBSw.SQL.AddStrings(lstSQL); try gbIBSw.ExecQuery; gbIBSw.Transaction.Commit; ss:= sf1+';;;отключен признак клонирования в Grossbee'; except on E: Exception do begin with gbIBSw.Transaction do if InTransaction then Rollback; ss:= sf1+';;;!!! ошибка отключения признака клонирования в Grossbee'; prMessageLOGS(nmProc+': '+ss+#13#10+CutEMess(E.Message), 'import'); end; end; gbIBSw.Close; prMessageLOGn(ss, pFileName); SetExecutePercent(pUserID, ThreadData, Percent); CheckStopExecute(pUserID, ThreadData); // проверка остановки процесса или системы end; // while not gbIBS.Eof gbIBS.Close; //-------------------------------------------- архивные логины клонированных к/а ss:= ''; sf1:= ''; if (lstSQL1.Count>0) then begin // ищем lstSQL1.Delimiter:= ','; lstSQL1.QuoteChar:= ' '; lstSQL.Clear; gbIBSw.SQL.Clear; gbIBSw.ParamCheck:= False; with gbIBSw.Transaction do if not InTransaction then StartTransaction; gbIBSw.SQL.Add('execute block returns(rCli integer, rLog varchar(20))'+ ' as declare variable xArh char(1); begin'); for i:= 0 to lstSQL1.Count-1 do begin gbIBSw.SQL.Add(' for select prsncode, prsnlogin, prsnarchivedkey from persons'+ ' where prsnfirmcode='+lstSQL1[i]+' and prsnlogin is not null'+ ' and left(prsnlogin, 1)<>"_" into :rCli, :rLog, :xArh do if (rCli>0) then begin'+ ' if (xArh="T") then begin rLog=left("_"||rLog, 20);'+ ' update persons p set p.prsnlogin=:rLog where p.prsncode=:rCli; end suspend; end'); end; gbIBSw.SQL.Add('end'); try gbIBSw.ExecQuery; while not gbIBSw.Eof do begin s:= gbIBSw.FieldByName('rLog').AsString; sFirm:= gbIBSw.FieldByName('rCli').AsString; if (copy(s, 1, 1)<>'_') then sf1:= sf1+' "'+s+'"('+sFirm+')' // не перенесенные логины else lstSQL.Add('update WEBORDERCLIENTS set WOCLLOGIN="'+s+'" where WOCLCODE='+sFirm+';'); gbIBSw.Next; end; gbIBSw.Transaction.Commit; if (lstSQL.Count>0) then ss:= ss+' найдены/заменены в Grossbee' else ss:= ss+' не найдены в Grossbee'; except on E: Exception do begin with gbIBSw.Transaction do if InTransaction then Rollback; ss:= ss+' !!! ошибка поиска в Grossbee по к/а '+lstSQL1.DelimitedText+#13#10+CutEMess(E.Message); lstSQL.Clear; end; end; gbIBSw.Close; if (lstSQL.Count>0) then begin lstSQL.Insert(0, 'execute block as begin'); lstSQL.Add('end'); ordIBS.SQL.Clear; ordIBS.SQL.AddStrings(lstSQL); with ordIBS.Transaction do if not InTransaction then StartTransaction; try ordIBS.ExecQuery; //------------------------- клонируем к/а в db_ORD ordIBS.Transaction.Commit; ss:= ss+' заменены в ORD'; except on E: Exception do begin with ordIBS.Transaction do if InTransaction then Rollback; ss:= ss+' !!! ошибка замены в ORD'#13#10+CutEMess(E.Message); end; end; ordIBS.Close; end; end; // if (lstSQL1.Count>0) if (ss<>'') then prMessageLOGS(nmProc+': ----------- архивные логины клонир.к/а '+ss, 'import_test', False); // логирование if (sf1<>'') then prMessageLOGS(nmProc+': ----------- не перенесены логины клонир.к/а в Grossbee '+sf1, 'import_test', False); // логирование finally prFreeIBSQL(ordIBS); cntsORD.SetFreeCnt(ordIBD, True); prFreeIBSQL(gbIBS); cntsGRB.SetFreeCnt(gbIBD, True); prFreeIBSQL(gbIBSw); cntsGRB.SetFreeCnt(gbIBDw, True); prFree(lstSQL); prFree(lstSQL1); end; except on E: EBOBError do raise EBOBError.Create(E.Message); on E: Exception do begin E.Message:= nmProc+': '+E.Message; prMessageLOGS(E.Message, 'import'); raise Exception.Create(E.Message); end; end; end; end.
unit DelphiFeedsIOSClientForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, FMX.Layouts, FMX.Memo, Xml.XMLIntf, FMX.ListBox, Xml.adomxmldom, Xml.XMLDoc, Xml.xmldom, FMX.TabControl; type TRSSFeedSource = (fsDelphiFeeds, fsEmbarcaderoBlogs); type THeaderFooterForm = class(TForm) Header: TToolBar; Footer: TToolBar; HeaderLabel: TLabel; XMLDocument1: TXMLDocument; ListBoxDelphi: TListBox; LabelStatusD: TLabel; TabControlMain: TTabControl; TabDelphiFeeds: TTabItem; TabEmbarcadero: TTabItem; Header2: TToolBar; HeaderLabel2: TLabel; ListBoxEmbt: TListBox; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; ToolBar1: TToolBar; LabelStatusE: TLabel; IdHTTP1: TIdHTTP; procedure DelphiFeedsUpdate(Sender: TObject); procedure ListBoxDelphiItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); procedure EmbtBlogsUpdate(Sender: TObject); procedure ListBoxEmbtItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); private procedure RefreshFeeds (fSource: TRSSFeedSource); public { Public declarations } end; var HeaderFooterForm: THeaderFooterForm; implementation {$R *.fmx} procedure THeaderFooterForm.DelphiFeedsUpdate(Sender: TObject); begin RefreshFeeds (fsDelphiFeeds); end; procedure THeaderFooterForm.RefreshFeeds (fSource: TRSSFeedSource); var strUrl: string; strXml: string; title, author, pubDate, url: string; I: Integer; ChannelNode, ItemNode: IXMLNode; ListBoxItem: TListBoxItem; TargetList: TListBox; LabelStatus: Tlabel; begin case fSource of fsDelphiFeeds: begin strUrl := 'http://feeds.delphifeeds.com/delphifeeds'; TargetList := ListBoxDelphi; LabelStatus := LabelStatusD; end; fsEmbarcaderoBlogs: begin strUrl := 'http://blogs.embarcadero.com/feeds/wpmu-feed/'; TargetList := ListBoxEmbt; LabelStatus := LabelStatuse; end; end; //ShowMessage ('About to get data from ' + strUrl); try strXml := IdHTTP1.Get (strUrl); except on E: Exception do begin ShowMessage ('Error: ' + E.Message); Exit; end; end; //ShowMessage ('Processing XML'); XMLDocument1.LoadFromXML(strXml); XMLDocument1.Active := True; LabelStatus.Text := 'Processing RSS'; LabelStatus.Repaint; TargetList.BeginUpdate; try TargetList.Clear; ChannelNode := XMLDocument1.DocumentElement.ChildNodes.FindNode ('channel'); for I := 0 to ChannelNode.ChildNodes.Count - 1 do begin ItemNode := ChannelNode.ChildNodes[I]; if ItemNode.NodeName = 'item' then begin LabelStatus.Text := 'Processing Node ' + I.ToString; title := ItemNode.ChildValues ['title']; pubDate := ItemNode.ChildValues ['pubDate']; case fSource of fsDelphiFeeds: author := ItemNode.ChildValues ['author']; fsEmbarcaderoBlogs: author := ItemNode.ChildValues ['creator']; end; url := ItemNode.ChildValues ['link']; ListBoxItem := TListBoxItem.Create(TargetList); ListBoxItem.Text := title; ListBoxItem.ItemData.Detail := author + ' - ' + Copy(pubDate, 1, 11); ListBoxItem.TagString := url; TargetList.AddObject(ListBoxItem); end; end; finally TargetList.EndUpdate; end; LabelStatus.Text := 'RSS Processed'; end; procedure THeaderFooterForm.EmbtBlogsUpdate(Sender: TObject); begin RefreshFeeds (fsEmbarcaderoBlogs); end; procedure THeaderFooterForm.ListBoxDelphiItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); begin LabelStatusD.Text := Item.TagString; end; procedure THeaderFooterForm.ListBoxEmbtItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); begin LabelStatusE.Text := Item.TagString; end; end.
unit Odontologia.Vistas.Agenda; interface uses Data.DB, System.Variants, System.Classes, System.ImageList, Winapi.Windows, Winapi.Messages, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.WinXPanels, Vcl.ExtCtrls, Vcl.ImgList, Vcl.DBCtrls, Vcl.WinXCalendars, Vcl.ComCtrls, Odontologia.Controlador, Odontologia.Controlador.Agenda.Interfaces, Odontologia.Controlador.Estado.Cita.Interfaces, Odontologia.Controlador.Interfaces, Odontologia.Controlador.Medico.Interfaces, Odontologia.Controlador.Paciente.Interfaces, Odontologia.Vistas.Main, Odontologia.Vista.Estilos; type TPagAgenda = class(TForm) DataSource1: TDataSource; DataSource2: TDataSource; DataSource3: TDataSource; ImageList1: TImageList; CardPanel1: TCardPanel; Card1: TCard; Card2: TCard; DBGrid1: TDBGrid; CalendarView1: TCalendarView; PnlPrincipal: TPanel; PnlCabecera: TPanel; PnlCabeceraTitulo: TPanel; PnlCentralGrid: TPanel; PnlCentralGridLinea: TPanel; PnlCentralFiltro: TPanel; PnlCentralFormulario: TPanel; PnlPieBotonAccion: TPanel; PnlPieBotonPagina: TPanel; PnlPieBotonEdicion: TPanel; PnlSubTitulo: TPanel; btnActualizar: TSpeedButton; btnNuevo: TSpeedButton; btnGuardar: TSpeedButton; btnCancelar: TSpeedButton; btnCerrar: TSpeedButton; btnBorrar: TSpeedButton; btnPrior: TSpeedButton; btnNext: TSpeedButton; btnBuscarPaciente: TSpeedButton; lblTitulo: TLabel; lblTitulo2: TLabel; LblMedico: TLabel; LblPaciente: TLabel; LblEstado: TLabel; lblPagina: TLabel; lblCodigoConsulta: TLabel; lblCodigoPaciente: TLabel; lblFecha: TLabel; lblMedicoRegistro: TLabel; lblEstadoConsulta: TLabel; lblNombrePaciente: TLabel; EdtMedico: TEdit; EdtPaciente: TEdit; edtCodigoConsulta: TEdit; edtCodigoPaciente: TEdit; edtNombrePaciente: TEdit; cmbRegMedico: TDBLookupComboBox; cmbRegEstado: TDBLookupComboBox; fechaReg: TDateTimePicker; DataSource4: TDataSource; horaReg: TDateTimePicker; lblHora: TLabel; RadioButton1: TRadioButton; RadioButton2: TRadioButton; RadioButton3: TRadioButton; RadioButton4: TRadioButton; procedure btnNuevoClick(Sender: TObject); procedure btnActualizarClick(Sender: TObject); procedure btnCerrarClick(Sender: TObject); procedure btnGuardarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnBorrarClick(Sender: TObject); procedure RadioButton1Click(Sender: TObject); procedure RadioButton2Click(Sender: TObject); procedure RadioButton3Click(Sender: TObject); procedure RadioButton4Click(Sender: TObject); procedure CalendarView1Change(Sender: TObject); procedure EdtMedicoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EdtPacienteKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); private { Private declarations } FController : iController; FAgenda : iControllerAgenda; FMedico : iControllerMedico; FPaciente : iControllerPaciente; FEstadoCita : iControllerEstadoCita; procedure prc_estado_inicial; procedure prc_buscar_por_parametros; public { Public declarations } end; var PagAgenda : TPagAgenda; Insercion : Boolean; estado : string; implementation uses System.SysUtils; {$R *.dfm} procedure TPagAgenda.btnActualizarClick(Sender: TObject); begin FAgenda.Buscar; modoEdicion := False; end; procedure TPagAgenda.btnBorrarClick(Sender: TObject); var ShouldClose: Boolean; begin inherited; if MessageDlg('Realmente desea eliminar este registro?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin FAgenda.Entidad.AGe_CODIGO := StrToInt(edtCodigoConsulta.Text); FAgenda.Eliminar; FAgenda.Buscar; prc_estado_inicial; end else begin edtNombrePaciente.SetFocus; end; end; procedure TPagAgenda.btnCancelarClick(Sender: TObject); begin modoEdicion := False; prc_estado_inicial; end; procedure TPagAgenda.btnCerrarClick(Sender: TObject); begin if MessageDlg('Está seguro de cerrar la ventana?', mtConfirmation, [mbOk, mbCancel], 0) = mrOk then close; end; procedure TPagAgenda.btnGuardarClick(Sender: TObject); begin inherited; modoEdicion := False; if Insercion then begin FAgenda.Entidad.AGE_FECHA := FormatDateTime('yyyy/mm/dd', fechaReg.Date); FAgenda.Entidad.AGE_HORA := horaReg.Time; FAgenda.Entidad.AGE_PACIENTE := StrToInt(edtCodigoPaciente.Text); FAgenda.Entidad.AGE_MEDICO := cmbRegMedico.KeyValue; FAgenda.Entidad.AGE_COD_ESTADO_CITA := cmbRegEstado.KeyValue; FAgenda.Insertar; end else begin FAgenda.Entidad.AGE_CODIGO := StrToInt(edtCodigoConsulta.Text); FAgenda.Entidad.AGE_FECHA := FormatDateTime('yyyy/mm/dd', fechaReg.Date); FAgenda.Entidad.AGE_HORA := horaReg.DateTime; FAgenda.Entidad.AGE_PACIENTE := StrToInt(edtCodigoPaciente.Text); FAgenda.Entidad.AGE_MEDICO := cmbRegMedico.KeyValue; FAgenda.Entidad.AGE_COD_ESTADO_CITA := cmbRegEstado.KeyValue; FAgenda.Modificar; end; prc_estado_inicial; end; procedure TPagAgenda.btnNuevoClick(Sender: TObject); begin Insercion := True; modoEdicion := True; CardPanel1.ActiveCard := Card2; lblTitulo2.Caption := 'Agregar nuevo registro'; cmbRegMedico.KeyValue := 1; cmbRegEstado.KeyValue := 1; edtCodigoPaciente.SetFocus; end; procedure TPagAgenda.CalendarView1Change(Sender: TObject); begin prc_buscar_por_parametros; end; procedure TPagAgenda.EdtMedicoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin prc_buscar_por_parametros; end; procedure TPagAgenda.EdtPacienteKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin prc_buscar_por_parametros; end; procedure TPagAgenda.FormCreate(Sender: TObject); begin Self.Font.Color := FONT_COLOR; Self.Font.Size := FONT_H7; lblTitulo.Caption := 'Agendamiento de citas y consultas'; CardPanel1.ActiveCard := Card1; CardPanel1.Color := COLOR_BACKGROUND; PnlPrincipal.Color := COLOR_BACKGROUND; PnlCabecera.Color := COLOR_BACKGROUND; PnlCabeceraTitulo.Color := COLOR_BACKGROUND; PnlCentralGridLinea.Color := COLOR_BACKGROUND_DESTAK; PnlCentralGrid.Color := COLOR_BACKGROUND; PnlCentralFiltro.Color := COLOR_BACKGROUND; PnlPieBotonAccion.Color := COLOR_BACKGROUND; PnlPieBotonPagina.Color := COLOR_BACKGROUND; PnlCentralFormulario.Color := COLOR_BACKGROUND; PnlPieBotonEdicion.Color := COLOR_BACKGROUND; PnlSubTitulo.Color := COLOR_BACKGROUND; lblTitulo.Font.Color := FONT_COLOR3; lblTitulo.Font.Size := FONT_H5; lblTitulo2.Font.Color := FONT_COLOR3; lblTitulo2.Font.Size := FONT_H5; FController := TController.New; FAgenda := FController.Agenda.DataSource(DataSource1); FMedico := FController.Medico.DataSource(DataSource2); FPaciente := FController.Paciente.DataSource(DataSource3); FEstadoCita := FController.EstadoCita.DataSource(DataSource4); prc_estado_inicial; end; procedure TPagAgenda.FormShow(Sender: TObject); begin CalendarView1.Date := now; end; procedure TPagAgenda.prc_buscar_por_parametros; var fecha, medico, paciente : String; begin fecha := FormatDateTime('yyyy/mm/dd', CalendarView1.Date); medico := EdtMedico.Text; paciente := EdtPaciente.Text; Fagenda.Buscar(fecha, '%'+medico+'%', '%'+paciente+'%', '%'+estado+'%'); end; procedure TPagAgenda.prc_estado_inicial; begin CardPanel1.ActiveCard := Card1; RadioButton1.Checked; EdtMedico.Text := ''; EdtPaciente.Text := ''; prc_buscar_por_parametros; FMedico.Buscar; Fpaciente.buscar; FEstadoCita.Buscar; end; procedure TPagAgenda.RadioButton1Click(Sender: TObject); begin estado := ''; prc_buscar_por_parametros; end; procedure TPagAgenda.RadioButton2Click(Sender: TObject); begin estado := 'AGENDADA'; prc_buscar_por_parametros; end; procedure TPagAgenda.RadioButton3Click(Sender: TObject); begin estado := 'REALIZADA'; prc_buscar_por_parametros; end; procedure TPagAgenda.RadioButton4Click(Sender: TObject); begin estado := 'CANCELADA'; prc_buscar_por_parametros; end; end.