text
stringlengths
14
6.51M
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC Oracle metadata } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.OracleMeta; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator; type TFDPhysOraMetadata = class (TFDPhysConnectionMetadata) protected function GetKind: TFDRDBMSKind; override; function GetTxSavepoints: Boolean; override; function GetEventSupported: Boolean; override; function GetEventKinds: String; override; function GetGeneratorSupported: Boolean; override; function GetIdentitySupported: Boolean; override; function GetIdentityInsertSupported: Boolean; override; function GetIdentityInWhere: Boolean; override; function GetParamNameMaxLength: Integer; override; function GetNameParts: TFDPhysNameParts; override; function GetNameCaseSensParts: TFDPhysNameParts; override; function GetNameDefLowCaseParts: TFDPhysNameParts; override; function GetInsertHBlobMode: TFDPhysInsertHBlobMode; override; function GetNamedParamMark: TFDPhysParamMark; override; function GetInlineRefresh: Boolean; override; function GetSelectOptions: TFDPhysSelectOptions; override; function GetAsyncAbortSupported: Boolean; override; function GetLockNoWait: Boolean; override; function GetDefValuesSupported: TFDPhysDefaultValues; override; function GetLineSeparator: TFDTextEndOfLine; override; function GetLimitOptions: TFDPhysLimitOptions; override; function GetNullLocations: TFDPhysNullLocations; override; function GetColumnOriginProvided: Boolean; override; function InternalEscapeBoolean(const AStr: String): String; override; function InternalEscapeDate(const AStr: String): String; override; function InternalEscapeDateTime(const AStr: String): String; override; function InternalEscapeFloat(const AStr: String): String; override; function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override; function InternalEscapeTime(const AStr: String): String; override; function InternalEscapeInto(const AStr: String): String; override; function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override; public constructor Create(const AConnection: TFDPhysConnection; AServerVersion, AClientVersion: TFDVersion; AIsUnicode: Boolean); end; TFDPhysOraCommandGenerator = class(TFDPhysCommandGenerator) private FUseDBAViews: Boolean; protected function GetInlineRefresh(const AStmt: String; ARequest: TFDUpdateRequest): String; override; function GetPessimisticLock: String; override; function GetSavepoint(const AName: String): String; override; function GetRollbackToSavepoint(const AName: String): String; override; function GetReadGenerator(const AName, AAlias: String; ANextValue, AFullSelect: Boolean): String; override; function GetSingleRowTable: String; override; function GetRowId(var AAlias: String): String; override; function GetCall(const AName: String): String; override; function GetStoredProcCall(const ACatalog, ASchema, APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String; override; function GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind; const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String; AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds; AOverload: Word): String; override; function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String; override; function GetColumnType(AColumn: TFDDatSColumn): String; override; function GetCreateGenerator(const AName: String): String; override; function GetDropGenerator(const AName: String): String; override; function GetCreateIdentityTrigger: String; override; public constructor Create(const ACommand: IFDPhysCommand; AUseDBAViews: Boolean); overload; constructor Create(const AConnection: IFDPhysConnection; AUseDBAViews: Boolean); overload; end; implementation uses System.SysUtils, Data.DB, FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Param; {-------------------------------------------------------------------------------} { TFDPhysOraMetadata } {-------------------------------------------------------------------------------} constructor TFDPhysOraMetadata.Create(const AConnection: TFDPhysConnection; AServerVersion, AClientVersion: TFDVersion; AIsUnicode: Boolean); begin inherited Create(AConnection, AServerVersion, AClientVersion, AIsUnicode); FKeywords.CommaText := // Oracle 10g reserved words 'ACCESS,ELSE,MODIFY,START,' + 'ADD,EXCLUSIVE,NOAUDIT,SELECT,' + 'ALL,EXISTS,NOCOMPRESS,SESSION,' + 'ALTER,FILE,NOT,SET,' + 'AND,FLOAT,NOTFOUND,SHARE,' + 'ANY,FOR,NOWAIT,SIZE,' + 'ARRAYLEN,FROM,NULL,SMALLINT,' + 'AS,GRANT,NUMBER,SQLBUF,' + 'ASC,GROUP,OF,SUCCESSFUL,' + 'AUDIT,HAVING,OFFLINE,SYNONYM,' + 'BETWEEN,IDENTIFIED,ON,SYSDATE,' + 'BY,IMMEDIATE,ONLINE,TABLE,' + 'CHAR,IN,OPTION,THEN,' + 'CHECK,INCREMENT,OR,TO,' + 'CLUSTER,INDEX,ORDER,TRIGGER,' + 'COLUMN,INITIAL,PCTFREE,UID,' + 'COMMENT,INSERT,PRIOR,UNION,' + 'COMPRESS,INTEGER,PRIVILEGES,UNIQUE,' + 'CONNECT,INTERSECT,PUBLIC,UPDATE,' + 'CREATE,INTO,RAW,USER,' + 'CURRENT,IS,RENAME,VALIDATE,' + 'DATE,LEVEL,RESOURCE,VALUES,' + 'DECIMAL,LIKE,REVOKE,VARCHAR,' + 'DEFAULT,LOCK,ROW,VARCHAR2,' + 'DELETE,LONG,ROWID,VIEW,' + 'DESC,MAXEXTENTS,ROWLABEL,WHENEVER,' + 'DISTINCT,MINUS,ROWNUM,WHERE,' + 'DROP,MODE,ROWS,WITH,' + // Oracle 10g key words 'ADMIN,CURSOR,FOUND,MOUNT,' + 'AFTER,CYCLE,FUNCTION,NEXT,' + 'ALLOCATE,DATABASE,GO,NEW,' + 'ANALYZE,DATAFILE,GOTO,NOARCHIVELOG,' + 'ARCHIVE,DBA,GROUPS,NOCACHE,' + 'ARCHIVELOG,DEC,INCLUDING,NOCYCLE,' + 'AUTHORIZATION,DECLARE,INDICATOR,NOMAXVALUE,' + 'AVG,DISABLE,INITRANS,NOMINVALUE,' + 'BACKUP,DISMOUNT,INSTANCE,NONE,' + 'BEGIN,DOUBLE,INT,NOORDER,' + 'BECOME,DUMP,KEY,NORESETLOGS,' + 'BEFORE,EACH,LANGUAGE,NORMAL,' + 'BLOCK,ENABLE,LAYER,NOSORT,' + 'BODY,END,LINK,NUMERIC,' + 'CACHE,ESCAPE,LISTS,OFF,' + 'CANCEL,EVENTS,LOGFILE,OLD,' + 'CASCADE,EXCEPT,MANAGE,ONLY,' + 'CHANGE,EXCEPTIONS,MANUAL,OPEN,' + 'CHARACTER,EXEC,MAX,OPTIMAL,' + 'CHECKPOINT,EXPLAIN,MAXDATAFILES,OWN,' + 'CLOSE,EXECUTE,MAXINSTANCES,PACKAGE,' + 'COBOL,EXTENT,MAXLOGFILES,PARALLEL,' + 'COMMIT,EXTERNALLY,MAXLOGHISTORY,PCTINCREASE ,' + 'COMPILE,FETCH,MAXLOGMEMBERS,PCTUSED ,' + 'CONSTRAINT,FLUSH,MAXTRANS,PLAN ,' + 'CONSTRAINTS,FREELIST,MAXVALUE,PLI ,' + 'CONTENTS,FREELISTS,MIN,PRECISION ,' + 'CONTINUE,FORCE,MINEXTENTS,PRIMARY ,' + 'CONTROLFILE,FOREIGN,MINVALUE,PRIVATE ,' + 'COUNT,FORTRAN,MODULE,PROCEDURE ,' + 'PROFILE,SAVEPOINT,SQLSTATE,TRACING ,' + 'QUOTA,SCHEMA,STATEMENT_ID,TRANSACTION ,' + 'READ,SCN,STATISTICS,TRIGGERS ,' + 'REAL,SECTION,STOP,TRUNCATE ,' + 'RECOVER,SEGMENT,STORAGE,UNDER ,' + 'REFERENCES,SEQUENCE,SUM,UNLIMITED ,' + 'REFERENCING,SHARED,SWITCH,UNTIL ,' + 'RESETLOGS,SNAPSHOT,SYSTEM,USE ,' + 'RESTRICTED,SOME,TABLES,USING ,' + 'REUSE,SORT,TABLESPACE,WHEN ,' + 'ROLE,SQL,TEMPORARY,WRITE ,' + 'ROLES,SQLCODE,THREAD,WORK,' + 'ROLLBACK,SQLERROR,TIME ,' + // Oracle 10g PL/SQL reserved words 'ABORT,BETWEEN,CRASH,DIGITS,' + 'ACCEPT,BINARY_INTEGER,CREATE,DISPOSE,' + 'ACCESS,BODY,CURRENT,DISTINCT,' + 'ADD,BOOLEAN,CURRVAL,DO,' + 'ALL,BY,CURSOR,DROP,' + 'ALTER,CASE,DATABASE,ELSE,' + 'AND,CHAR,DATA_BASE,ELSIF,' + 'ANY,CHAR_BASE,DATE,END,' + 'ARRAY,CHECK,DBA,ENTRY,' + 'ARRAYLEN,CLOSE,DEBUGOFF,EXCEPTION,' + 'AS,CLUSTER,DEBUGON,EXCEPTION_INIT,' + 'ASC,CLUSTERS,DECLARE,EXISTS,' + 'ASSERT,COLAUTH,DECIMAL,EXIT,' + 'ASSIGN,COLUMNS,DEFAULT,FALSE,' + 'AT,COMMIT,DEFINITION,FETCH,' + 'AUTHORIZATION,COMPRESS,DELAY,FLOAT,' + 'AVG,CONNECT,DELETE,FOR,' + 'BASE_TABLE,CONSTANT,DELTA,FORM,' + 'BEGIN,COUNT,DESC,FROM,' + 'FUNCTION,NEW,RELEASE,SUM ,' + 'GENERIC,NEXTVAL,REMR,TABAUTH ,' + 'GOTO,NOCOMPRESS,RENAME,TABLE ,' + 'GRANT,NOT,RESOURCE,TABLES ,' + 'GROUP,NULL,RETURN,TASK ,' + 'HAVING,NUMBER,REVERSE,TERMINATE ,' + 'IDENTIFIED,NUMBER_BASE,REVOKE,THEN,' + 'IF,OF,ROLLBACK,TO,' + 'IN,ON,ROWID,TRUE,' + 'INDEX,OPEN,ROWLABEL,TYPE,' + 'INDEXES,OPTION,ROWNUM,UNION,' + 'INDICATOR,OR,ROWTYPE,UNIQUE,' + 'INSERT,ORDER,RUN,UPDATE,' + 'INTEGER,OTHERS,SAVEPOINT,USE,' + 'INTERSECT,OUT,SCHEMA,VALUES,' + 'INTO,PACKAGE,SELECT,VARCHAR,' + 'IS,PARTITION,SEPARATE,VARCHAR2,' + 'LEVEL,PCTFREE,SET,VARIANCE,' + 'LIKE,POSITIVE,SIZE,VIEW,' + 'LIMITED,PRAGMA,SMALLINT,VIEWS,' + 'LOOP,PRIOR,SPACE,WHEN,' + 'MAX,PRIVATE,SQL,WHERE,' + 'MIN,PROCEDURE,SQLCODE,WHILE,' + 'MINUS,PUBLIC,SQLERRM,WITH,' + 'MLSLABEL,RAISE,START,WORK,' + 'MOD,RANGE,STATEMENT,XOR,' + 'MODE,REAL,STDDEV,' + 'NATURAL,RECORD,SUBTYPE'; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetKind: TFDRDBMSKind; begin Result := TFDRDBMSKinds.Oracle; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetNameCaseSensParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetNameDefLowCaseParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetParamNameMaxLength: Integer; begin Result := 30; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetNameParts: TFDPhysNameParts; begin Result := [npSchema, npDBLink, npBaseObject, npObject]; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetNamedParamMark: TFDPhysParamMark; begin Result := prName; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetTxSavepoints: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetEventSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetEventKinds: String; begin Result := S_FD_EventKind_Oracle_DBMS_ALERT + ';' + S_FD_EventKind_Oracle_DBMS_PIPE; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetGeneratorSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetIdentitySupported: Boolean; begin Result := (GetServerVersion >= cvOracle120000) and (GetClientVersion >= cvOracle120000); end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetIdentityInsertSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetIdentityInWhere: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetInsertHBlobMode: TFDPhysInsertHBlobMode; begin if (GetClientVersion >= cvOracle81000) or (GetClientVersion < cvOracle80000) then Result := hmInInsert else Result := hmSetAfterReturning; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetInlineRefresh: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetSelectOptions: TFDPhysSelectOptions; begin Result := [soInlineView]; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetLockNoWait: Boolean; begin Result := True; end; { ----------------------------------------------------------------------------- } function TFDPhysOraMetadata.GetAsyncAbortSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetDefValuesSupported: TFDPhysDefaultValues; begin if GetServerVersion >= cvOracle90000 then Result := dvDef else Result := dvNone; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetLineSeparator: TFDTextEndOfLine; begin Result := elPosix; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetLimitOptions: TFDPhysLimitOptions; begin Result := [loSkip, loRows]; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetNullLocations: TFDPhysNullLocations; begin Result := [nlAscLast, nlDescFirst]; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.GetColumnOriginProvided: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.InternalEscapeBoolean( const AStr: String): String; begin if CompareText(AStr, S_FD_True) = 0 then Result := '1' else Result := '0'; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.InternalEscapeDate(const AStr: String): String; begin Result := 'TO_DATE(' + AnsiQuotedStr(AStr, '''') + ', ''YYYY-MM-DD'')'; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.InternalEscapeDateTime(const AStr: String): String; begin Result := 'TO_DATE(' + AnsiQuotedStr(AStr, '''') + ', ''YYYY-MM-DD HH24:MI:SS'')'; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.InternalEscapeTime(const AStr: String): String; begin Result := 'TO_DATE(' + AnsiQuotedStr('1900-01-01' + AStr, '''') + ', ''YYYY-MM-DD HH24:MI:SS'')'; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.InternalEscapeFloat(const AStr: String): String; begin Result := 'TO_NUMBER(' + AnsiQuotedStr(AStr, '''') + ')'; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.InternalEscapeInto(const AStr: String): String; begin Result := 'INTO ' + AStr; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; var sName: String; A1, A2, A3, A4: String; rSeq: TFDPhysEscapeData; function AddArgs: string; begin if Length(ASeq.FArgs) > 0 then Result := '(' + AddEscapeSequenceArgs(ASeq) + ')'; end; begin sName := ASeq.FName; if Length(ASeq.FArgs) >= 1 then begin A1 := ASeq.FArgs[0]; if Length(ASeq.FArgs) >= 2 then begin A2 := ASeq.FArgs[1]; if Length(ASeq.FArgs) >= 3 then begin A3 := ASeq.FArgs[2]; if Length(ASeq.FArgs) >= 4 then A4 := ASeq.FArgs[3]; end; end; end; case ASeq.FFunc of // the same efASCII, efLTRIM, efREPLACE, efRTRIM, efABS, efACOS, efASIN, efATAN, efCOS, efEXP, efFLOOR, efMOD, efPOWER, efROUND, efSIGN, efSIN, efSQRT, efTAN, efDECODE: Result := sName + AddArgs; // character efBIT_LENGTH: Result := '(LENGTHB(' + A1 + ') * 8)'; efCHAR: Result := 'CHR' + AddArgs; efCHAR_LENGTH: Result := 'LENGTH' + AddArgs; efCONCAT: Result := '(' + A1 + ' || ' + A2 + ')'; efINSERT: Result := '(SUBSTR(' + A1 + ', 1, (' + A2 + ') - 1) || ' + A4 + ' || SUBSTR(' + A1 + ', (' + A2 + ' + ' + A3 + ')))'; efLCASE: Result := 'LOWER' + AddArgs; efLEFT: Result := 'SUBSTR(' + A1 + ', 1, ' + A2 + ')'; efLENGTH: Result := 'LENGTH(RTRIM(' + A1 + '))'; efLOCATE: begin Result := 'INSTR(' + A2 + ', ' + A1; if Length(ASeq.FArgs) = 3 then Result := Result + ', ' + A3; Result := Result + ')' end; efOCTET_LENGTH:Result := 'LENGTHB' + AddArgs; efPOSITION: Result := 'INSTR(' + A2 + ', ' + A1 + ')'; efREPEAT: Result := 'RPAD(' + A1 + ', (' + A2 + ') * LENGTH(' + A1 + '), ' + A1 + ')'; efRIGHT: Result := 'SUBSTR(' + A1 + ', LENGTH(' + A1 + ') + 1 - (' + A2 + '))'; efSPACE: Result := 'RPAD('' '', ' + A1 + ')'; efSUBSTRING: Result := 'SUBSTR' + AddArgs; efUCASE: Result := 'UPPER' + AddArgs; // numeric efCEILING: Result := 'CEIL' + AddArgs; efDEGREES: Result := '(180 * (' + A1 + ') / ' + S_FD_Pi + ')'; efLOG: Result := 'LN' + AddArgs; efLOG10: Result := 'LOG(10, ' + A1 + ')'; efPI: Result := S_FD_Pi; efRADIANS: Result := '((' + A1 + ') / 180 * ' + S_FD_Pi + ')'; efRANDOM: if GetServerVersion >= cvOracle90000 then Result := 'DBMS_RANDOM.VALUE' else Result := 'MOD(TRUNC((SYSDATE - TRUNC(SYSDATE)) * 60 * 60 * 24), 1000)'; efTRUNCATE: Result := 'TRUNC' + AddArgs; // date and time efCURDATE: Result := 'TRUNC(SYSDATE)'; efCURTIME: Result := '(TO_DATE(''1900-01-01'', ''YYYY-MM-DD'') + (SYSDATE - TRUNC(SYSDATE)))'; efNOW: Result := 'SYSDATE'; efDAYNAME: Result := 'RTRIM(TO_CHAR(' + A1 + ', ''DAY''))'; efDAYOFMONTH: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''DD''))'; efDAYOFWEEK: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''D''))'; efDAYOFYEAR: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''DDD''))'; efEXTRACT: begin rSeq.FKind := eskFunction; if A1[1] = '''' then A1 := Copy(A1, 2, Length(A1) - 2); A1 := UpperCase(A1); if A1 = 'DAY' then A1 := 'DAYOFMONTH'; rSeq.FName := A1; SetLength(rSeq.FArgs, 1); rSeq.FArgs[0] := ASeq.FArgs[1]; EscapeFuncToID(rSeq); Result := InternalEscapeFunction(rSeq); end; efHOUR: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''HH24''))'; efMINUTE: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''MI''))'; efMONTH: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''MM''))'; efMONTHNAME: Result := 'RTRIM(TO_CHAR(' + A1 + ', ''MONTH''))'; efQUARTER: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''Q''))'; efSECOND: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''SS''))'; efTIMESTAMPADD: begin A1 := UpperCase(FDUnquote(Trim(A1), '''')); if A1 = 'YEAR' then Result := 'ADD_MONTHS(' + A3 + ', 12 * (' + A2 + '))' else if A1 = 'MONTH' then Result := 'ADD_MONTHS(' + A3 + ', ' + A2 + ')' else if A1 = 'WEEK' then Result := '(' + A3 + ' + 7 * (' + A2 + '))' else if A1 = 'DAY' then Result := '(' + A3 + ' + ' + A2 + ')' else if A1 = 'HOUR' then Result := '(' + A3 + ' + (' + A2 + ') / 24.0)' else if A1 = 'MINUTE' then Result := '(' + A3 + ' + (' + A2 + ') / (24.0 * 60.0))' else if A1 = 'SECOND' then Result := '(' + A3 + ' + (' + A2 + ') / (24.0 * 60.0 * 60.0))' else if A1 = 'FRAC_SECOND' then Result := '(' + A3 + ' + (' + A2 + ') / (24.0 * 60.0 * 60.0 * 1000000))' else UnsupportedEscape(ASeq); end; efTIMESTAMPDIFF: begin A1 := UpperCase(FDUnquote(Trim(A1), '''')); if A1 = 'YEAR' then Result := 'TRUNC(MONTHS_BETWEEN(' + A3 + ', ' + A2 + ') / 12)' else if A1 = 'MONTH' then Result := 'MONTHS_BETWEEN(' + A3 + ', ' + A2 + ')' else if A1 = 'WEEK' then Result := 'TRUNC(((' + A3 + ') - (' + A2 + ')) / 7)' else if A1 = 'DAY' then Result := '((' + A3 + ') - (' + A2 + '))' else if A1 = 'HOUR' then Result := 'TRUNC(((' + A3 + ') - (' + A2 + ')) * 24.0)' else if A1 = 'MINUTE' then Result := 'TRUNC(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0))' else if A1 = 'SECOND' then Result := 'TRUNC(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0 * 60.0))' else if A1 = 'FRAC_SECOND' then Result := 'ROUND(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0 * 60.0 * 1000000.0))' else UnsupportedEscape(ASeq); end; efWEEK: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''WW''))'; efYEAR: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''YYYY''))'; // system efCATALOG: Result := ''''''; efSCHEMA: if GetServerVersion < cvOracle81500 then Result := 'USER' else Result := 'SYS_CONTEXT(''USERENV'', ''CURRENT_SCHEMA'')'; efIFNULL: Result := 'NVL' + AddArgs; efIF: if GetServerVersion >= cvOracle90000 then Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END' else UnsupportedEscape(ASeq); // convert efCONVERT: begin A2 := UpperCase(FDUnquote(Trim(A2), '''')); if (A2 = 'CHAR') or (A2 = 'LONGVARCHAR') or (A2 = 'VARCHAR') then Result := 'TO_CHAR(' + A1 + ')' else if (A2 = 'WCHAR') or (A2 = 'WLONGVARCHAR') or (A2 = 'WVARCHAR') then Result := 'TO_NCHAR(' + A1 + ')' else if (A2 = 'DATE') then if GetServerVersion >= cvOracle90000 then Result := 'TRUNC(CAST(' + A1 + ' AS DATE))' else Result := 'TRUNC(TO_DATE(' + A1 + '))' else if (A2 = 'DATETIME') then if GetServerVersion >= cvOracle90000 then Result := 'CAST(' + A1 + ' AS DATE)' else Result := 'TO_DATE(' + A1 + ')' else if (A2 = 'TIME') then if GetServerVersion >= cvOracle90000 then Result := '(TO_DATE(''1900-01-01'', ''YYYY-MM-DD'') + (CAST(' + A1 + ' AS DATE) - TRUNC(CAST(' + A1 + ' AS DATE))))' else Result := '(TO_DATE(''1900-01-01'', ''YYYY-MM-DD'') + (TO_DATE(' + A1 + ') - TRUNC(TO_DATE(' + A1 + '))))' else if (A2 = 'DECIMAL') or (A2 = 'DOUBLE') or (A2 = 'FLOAT') or (A2 = 'NUMERIC') or (A2 = 'REAL') then Result := 'TO_NUMBER(' + A1 + ')' else if (A2 = 'INTEGER') or (A2 = 'SMALLINT') or (A2 = 'TINYINT') or (A2 = 'BIGINT') then Result := 'TRUNC(TO_NUMBER(' + A1 + '))' else UnsupportedEscape(ASeq); end; else // unsupported ATAN2, COT UnsupportedEscape(ASeq); end; end; {-------------------------------------------------------------------------------} function TFDPhysOraMetadata.InternalGetSQLCommandKind( const ATokens: TStrings): TFDPhysCommandKind; var sToken: String; begin sToken := ATokens[0]; if sToken = 'ALTER' then if (ATokens.Count = 1) or (ATokens.Count = 2) and (ATokens[1] = 'SESSION') or (ATokens.Count = 3) and (ATokens[2] = 'SET') then Result := skNotResolved else if (ATokens.Count = 4) and (ATokens[3] = 'CURRENT_SCHEMA') then Result := skSetSchema else Result := skAlter else if (sToken = 'DECLARE') or (sToken = 'BEGIN') then Result := skExecute else if sToken = 'SET' then if ATokens.Count = 1 then Result := skNotResolved else if ATokens[1] = 'TRANSACTION' then Result := skStartTransaction else Result := inherited InternalGetSQLCommandKind(ATokens) else if sToken = 'PURGE' then Result := skDrop else Result := inherited InternalGetSQLCommandKind(ATokens); end; {-------------------------------------------------------------------------------} { TFDPhysOraCommandGenerator } {-------------------------------------------------------------------------------} constructor TFDPhysOraCommandGenerator.Create(const ACommand: IFDPhysCommand; AUseDBAViews: Boolean); begin inherited Create(ACommand); FUseDBAViews := AUseDBAViews; end; {-------------------------------------------------------------------------------} constructor TFDPhysOraCommandGenerator.Create( const AConnection: IFDPhysConnection; AUseDBAViews: Boolean); begin inherited Create(AConnection); FUseDBAViews := AUseDBAViews; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetInlineRefresh(const AStmt: String; ARequest: TFDUpdateRequest): String; begin Result := AStmt + GetReturning(ARequest, True); end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetPessimisticLock: String; var lNeedFrom: Boolean; begin Result := 'SELECT ' + GetSelectList(True, False, lNeedFrom) + BRK + 'FROM ' + GetFrom + BRK + 'WHERE ' + GetWhere(False, True, False) + BRK + 'FOR UPDATE'; FCommandKind := skSelectForLock; ASSERT(lNeedFrom); if not FOptions.UpdateOptions.LockWait then Result := Result + ' NOWAIT'; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetSavepoint(const AName: String): String; begin Result := 'SAVEPOINT ' + AName; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetRollbackToSavepoint(const AName: String): String; begin Result := 'ROLLBACK TO SAVEPOINT ' + AName; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetReadGenerator(const AName, AAlias: String; ANextValue, AFullSelect: Boolean): String; begin Result := AName; if ANextValue then Result := Result + '.NEXTVAL' else Result := Result + '.CURRVAL'; if AAlias <> '' then Result := Result + ' ' + AAlias; if AFullSelect then Result := 'SELECT ' + Result + BRK + 'FROM ' + GetSingleRowTable; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetSingleRowTable: String; begin Result := 'SYS.DUAL'; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetRowId(var AAlias: String): String; begin Result := 'ROWID'; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetCall(const AName: String): String; begin Result := 'BEGIN ' + AName; if Result[Length(Result)] <> ';' then Result := Result + ';'; Result := Result + ' END;'; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetStoredProcCall(const ACatalog, ASchema, APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String; var i: Integer; oParam: TFDParam; rName: TFDPhysParsedName; lWasParam: Boolean; function BuildParamStr(AParam: TFDParam): String; var sName: String; begin sName := AParam.SQLName; if (FParams.BindMode = pbByName) and (AParam.ParamType <> ptResult) then Result := sName + ' => ' else Result := ''; Result := Result + ':' + sName; end; begin Result := 'BEGIN '; for i := 0 to FParams.Count - 1 do if FParams[i].ParamType = ptResult then begin Result := Result + BuildParamStr(FParams[i]) + ' := '; Break; end; rName.FCatalog := ACatalog; rName.FSchema := ASchema; rName.FBaseObject := APackage; rName.FObject := AProc; Result := Result + FConnMeta.EncodeObjName(rName, FCommand, [eoQuote, eoNormalize]); lWasParam := False; for i := 0 to FParams.Count - 1 do begin case FParams.BindMode of pbByName: oParam := FParams[i]; pbByNumber: oParam := FParams.FindParam(i + 1); else oParam := nil; end; if (oParam = nil) or (oParam.ParamType <> ptResult) then begin if lWasParam then Result := Result + ', ' else begin Result := Result + '('; lWasParam := True; end; if oParam = nil then Result := Result + 'NULL' else Result := Result + BuildParamStr(oParam); end; end; if lWasParam then Result := Result + ')'; Result := Result + '; END;'; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind; const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String; AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds; AOverload: Word): String; var sKinds, sViewPrefix, sUserFunc: String; sCharLen, sUniCharLen, sUniVarCharLen: String; sIndexName, sOwnerName, sToChar: String; sIndexName2, sOwnerName2, sToChar2: String; lWasWhere: Boolean; oPar: TFDParam; procedure AddWhere(const ACond: String; const AParam: String = ''); var oPar: TFDParam; begin if lWasWhere then Result := Result + ' AND ' + ACond else begin Result := Result + ' WHERE ' + ACond; lWasWhere := True; end; if AParam <> '' then begin oPar := GetParams.Add; oPar.Name := AParam; oPar.DataType := ftString; oPar.Size := 50; end; end; procedure AddTopScope(AOwnerName: String); var sScope: String; begin if ASchema <> '' then AddWhere(AOwnerName + ' = ''' + ASchema + '''') else if AObjectScopes <> [osMy, osSystem, osOther] then begin sScope := ''; if osMy in AObjectScopes then sScope := sScope + AOwnerName + ' = ' + sUserFunc + ' OR '; if osSystem in AObjectScopes then sScope := sScope + AOwnerName + ' IN (''SYS'', ''SYSTEM'', ''INFORMATION_SCHEMA'') OR '; if osOther in AObjectScopes then sScope := sScope + AOwnerName + ' NOT IN (''SYS'', ''SYSTEM'', ''INFORMATION_SCHEMA'', ' + sUserFunc + ') OR '; if sScope <> '' then AddWhere('(' + Copy(sScope, 1, Length(sScope) - 4) + ')'); end; end; function EncodeDataType(const AFieldName: String): String; function DT2Str(AType: TFDDataType): String; begin Result := IntToStr(Integer(AType)); end; begin Result := 'DECODE(' + AFieldName + ', ' + '''CHAR'', ' + DT2Str(dtAnsiString) + ', ' + '''VARCHAR'', ' + DT2Str(dtAnsiString) + ', ' + '''VARCHAR2'', ' + DT2Str(dtAnsiString) + ', ' + '''NCHAR'', ' + DT2Str(dtWideString) + ', ' + '''NCHAR VARYING'', ' + DT2Str(dtWideString) + ', ' + '''NVARCHAR2'', ' + DT2Str(dtWideString) + ', ' + '''NUMBER'', ' + DT2Str(dtFmtBCD) + ', ' + '''FLOAT'', ' + DT2Str(dtDouble) + ', ' + '''DATE'', ' + DT2Str(dtDateTime) + ', ' + '''RAW'', ' + DT2Str(dtByteString) + ', ' + '''LONG'', ' + DT2Str(dtMemo) + ', ' + '''LONG RAW'', ' + DT2Str(dtBlob) + ', ' + '''ROWID'', ' + DT2Str(dtAnsiString) + ', ' + '''UROWID'', ' + DT2Str(dtAnsiString) + ', ' + '''NCLOB'', ' + DT2Str(dtWideHMemo) + ', ' + '''CLOB'', ' + DT2Str(dtHMemo) + ', ' + '''BLOB'', ' + DT2Str(dtHBlob) + ', ' + '''BFILE'', ' + DT2Str(dtHBFile) + ', ' + '''CFILE'', ' + DT2Str(dtHBFile) + ', ' + '''NATIVE INTEGER'', ' + DT2Str(dtInt32) + ', ' + '''BINARY_INTEGER'', ' + DT2Str(dtInt32) + ', ' + '''REF CURSOR'', ' + DT2Str(dtCursorRef) + ', ' + '''PL/SQL BOOLEAN'', ' + DT2Str(dtBoolean) + ', ' + '''TIME'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIME WITH TIME ZONE'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP(1)'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP(2)'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP(3)'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP(4)'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP(5)'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP(6)'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP(7)'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP(8)'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP(9)'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP WITH TIME ZONE'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''TIMESTAMP WITH LOCAL TIME ZONE'', ' + DT2Str(dtDateTimeStamp) + ', ' + '''INTERVAL YEAR TO MONTH'', ' + DT2Str(dtTimeIntervalYM) + ', ' + '''INTERVAL DAY TO SECOND'', ' + DT2Str(dtTimeIntervalDS) + ', ' + '''BINARY_FLOAT'', ' + DT2Str(dtSingle) + ', ' + '''BINARY_DOUBLE'', ' + DT2Str(dtDouble) + ', ' + DT2Str(dtUnknown) + ')'; end; function EncodeAttrs(const ATypeFieldName, ANullableFieldName, ADefaultLengthFieldName, AIdentityFieldName: String): String; function Attrs2Str(AAttrs: TFDDataAttributes): String; begin if AKind <> mkTableFields then Exclude(AAttrs, caBase); Result := IntToStr(PWord(@AAttrs)^); end; begin Result := 'DECODE(' + ATypeFieldName + ', ' + '''CHAR'', ' + Attrs2Str([caBase, caFixedLen, caSearchable]) + ', ' + '''VARCHAR'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''VARCHAR2'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''NCHAR'', ' + Attrs2Str([caBase, caFixedLen, caSearchable]) + ', ' + '''NCHAR VARYING'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''NVARCHAR2'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''NUMBER'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''FLOAT'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''DATE'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''RAW'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''LONG'', ' + Attrs2Str([caBase, caBlobData]) + ', ' + '''LONG RAW'', ' + Attrs2Str([caBase, caBlobData]) + ', ' + '''ROWID'', ' + Attrs2Str([caBase, caAllowNull, caFixedLen, caSearchable, caROWID]) + ', ' + '''UROWID'', ' + Attrs2Str([caBase, caAllowNull, caSearchable, caROWID]) + ', ' + '''NCLOB'', ' + Attrs2Str([caBase, caBlobData]) + ', ' + '''CLOB'', ' + Attrs2Str([caBase, caBlobData]) + ', ' + '''BLOB'', ' + Attrs2Str([caBase, caBlobData]) + ', ' + '''BFILE'', ' + Attrs2Str([caBase, caBlobData, caVolatile]) + ', ' + '''CFILE'', ' + Attrs2Str([caBase, caBlobData, caVolatile]) + ', ' + '''NATIVE INTEGER'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''BINARY_INTEGER'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''REF CURSOR'', ' + Attrs2Str([caAllowNull]) + ', ' + '''PL/SQL BOOLEAN'', ' + Attrs2Str([]) + ', ' + '''TIME'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''TIME WITH TIME ZONE'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''TIMESTAMP'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''TIMESTAMP WITH TIME ZONE'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''TIMESTAMP WITH LOCAL TIME ZONE'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''INTERVAL YEAR TO MONTH'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''INTERVAL DAY TO SECOND'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''BINARY_FLOAT'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + '''BINARY_DOUBLE'', ' + Attrs2Str([caBase, caSearchable]) + ', ' + Attrs2Str([caBase]) + ') + '; if ANullableFieldName <> '' then Result := Result + 'DECODE(' + ANullableFieldName + ', ''Y'', ' + Attrs2Str([caAllowNull]) + ', ' + Attrs2Str([]) + ')' else Result := Result + Attrs2Str([caAllowNull]); if ADefaultLengthFieldName <> '' then Result := Result + ' + DECODE(' + ADefaultLengthFieldName + ', NULL, ' + Attrs2Str([]) + ', ' + Attrs2Str([caDefault]) + ')'; if (FConnMeta.ServerVersion >= cvOracle120000) and (AIdentityFieldName <> '') then Result := Result + ' + DECODE(' + AIdentityFieldName + ', ''YES'', ' + Attrs2Str([caAutoInc]) + ', 0)'; end; function EncodeScope(const AOwnerFieldName: String): String; begin Result := 'DECODE(' + AOwnerFieldName + ', ' + sUserFunc + ', ' + IntToStr(Integer(osMy)) + ', ' + '''SYS'', ' + IntToStr(Integer(osSystem)) + ', ' + '''SYSTEM'', ' + IntToStr(Integer(osSystem)) + ', ' + '''INFORMATION_SCHEMA'', ' + IntToStr(Integer(osSystem)) + ', ' + IntToStr(Integer(osOther)) + ')'; end; procedure GetLengthExpressions(var ACharLen, AUniCharLen, AUniVarCharLen: String); begin if FConnMeta.ServerVersion >= cvOracle90000 then begin ACharLen := 'CHAR_LENGTH'; AUniCharLen := 'CHAR_LENGTH'; AUniVarCharLen := 'CHAR_LENGTH'; end else begin ACharLen := 'DATA_LENGTH'; AUniCharLen := 'DATA_LENGTH'; AUniVarCharLen := AUniCharLen; end; end; procedure GetIndexExpressions(var AIndexName, AOwnerName, AToChar: String; const AAlias: String); begin if FConnMeta.ServerVersion >= cvOracle90000 then begin AIndexName := AAlias + '.INDEX_NAME'; AOwnerName := 'NVL(' + AAlias + '.INDEX_OWNER, ' + AAlias + '.OWNER)'; AToChar := 'TO_CHAR('; end else begin AIndexName := AAlias + '.CONSTRAINT_NAME'; AOwnerName := AAlias + '.OWNER'; AToChar := '('; end; end; function GetOwner: String; begin if ASchema <> '' then Result := QuotedStr(ASchema) else Result := sUserFunc; end; begin if FUseDBAViews then sViewPrefix := 'SYS.DBA' else sViewPrefix := 'SYS.ALL'; if FConnMeta.ServerVersion < cvOracle81500 then sUserFunc := 'USER' else sUserFunc := 'SYS_CONTEXT(''USERENV'', ''CURRENT_SCHEMA'')'; lWasWhere := False; case AKind of mkCatalogs: Result := ''; mkSchemas: begin Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'USERNAME AS SCHEMA_NAME FROM ' + sViewPrefix + '_USERS'; if AWildcard <> '' then AddWhere('USERNAME LIKE :WIL', 'WIL'); Result := Result + ' ORDER BY 3'; end; mkTables: begin sKinds := ''; if (tkTable in ATableKinds) or (tkTempTable in ATableKinds) then sKinds := sKinds + '''TABLE'', '; if tkView in ATableKinds then sKinds := sKinds + '''VIEW'', ''MATERIALIZED VIEW'', '; if tkSynonym in ATableKinds then sKinds := sKinds + '''SYNONYM'', '; Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'OWNER AS SCHEMA_NAME, OBJECT_NAME AS TABLE_NAME, ' + 'DECODE(TEMPORARY, ' + '''Y'', ' + InttoStr(Integer(tkTempTable)) + ', ' + 'DECODE(OBJECT_TYPE, ' + '''TABLE'', ' + IntToStr(Integer(tkTable)) + ', ' + '''SYNONYM'', ' + IntToStr(Integer(tkSynonym)) + ', ' + IntToStr(Integer(tkView)) + ')) AS TABLE_TYPE, ' + EncodeScope('OWNER') + ' AS TABLE_SCOPE ' + 'FROM ' + sViewPrefix + '_OBJECTS'; if sKinds <> '' then AddWhere('OBJECT_TYPE IN (' + Copy(sKinds, 1, Length(sKinds) - 2) + ')') else AddWhere('0 = 1'); if AWildcard <> '' then AddWhere('OBJECT_NAME LIKE :WIL', 'WIL'); AddTopScope('OWNER'); if FConnMeta.ServerVersion >= cvOracle81500 then if not (tkTempTable in ATableKinds) then AddWhere('TEMPORARY = ''N''') else if ATableKinds = [tkTempTable] then AddWhere('TEMPORARY = ''Y'''); if FConnMeta.ServerVersion >= cvOracle100000 then AddWhere('OBJECT_NAME NOT LIKE ''BIN$%'''); Result := Result + ' ORDER BY 3, 4'; end; mkTableFields: begin sCharLen := ''; sUniCharLen := ''; sUniVarCharLen := ''; GetLengthExpressions(sCharLen, sUniCharLen, sUniVarCharLen); Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'OWNER AS SCHEMA_NAME, TABLE_NAME, COLUMN_NAME, ' + 'COLUMN_ID AS COLUMN_POSITION, ' + EncodeDataType('DATA_TYPE') + ' AS COLUMN_DATATYPE, ' + 'DECODE(DATA_TYPE_OWNER, NULL, DATA_TYPE, ''"'' || DATA_TYPE_OWNER || ''"."'' || DATA_TYPE || ''"'') AS COLUMN_TYPENAME, ' + EncodeAttrs('DATA_TYPE', 'NULLABLE', 'DEFAULT_LENGTH', 'IDENTITY_COLUMN') + ' AS COLUMN_ATTRIBUTES, ' + 'LEAST(DATA_PRECISION, 38) AS COLUMN_PRECISION, GREATEST(DATA_SCALE, 0) AS COLUMN_SCALE, ' + 'DECODE(DATA_TYPE, ''CHAR'', ' + sCharLen + ', ''VARCHAR'', ' + sCharLen + ', ' + '''VARCHAR2'', ' + sCharLen + ', ''NCHAR'', ' + sUniCharLen + ', ' + '''NCHAR VARYING'', ' + sUniVarCharLen + ', ''NVARCHAR2'', ' + sUniVarCharLen + ', ' + '''RAW'', DATA_LENGTH, ''ROWID'', 18, NULL) AS COLUMN_LENGTH ' + 'FROM ' + sViewPrefix + '_TAB_COLUMNS'; AddWhere('OWNER = ' + GetOwner); AddWhere('TABLE_NAME = :OBJ', 'OBJ'); if AWildcard <> '' then AddWhere('COLUMN_NAME LIKE :WIL', 'WIL'); Result := Result + ' ORDER BY 6'; end; mkIndexes: begin sIndexName := ''; sOwnerName := ''; sToChar := ''; GetIndexExpressions(sIndexName, sOwnerName, sToChar, 'C'); Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'I.OWNER AS SCHEMA_NAME, I.TABLE_NAME, I.INDEX_NAME, '; if FConnMeta.ServerVersion >= cvOracle81000 then Result := Result + sToChar + '(' + 'SELECT C.CONSTRAINT_NAME ' + 'FROM ' + sViewPrefix + '_CONSTRAINTS C ' + 'WHERE ' + sOwnerName + ' = I.OWNER AND C.TABLE_NAME = I.TABLE_NAME AND ' + sIndexName + ' = I.INDEX_NAME' + ')) AS CONSTRAINT_NAME, ' + 'DECODE(UNIQUENESS, ' + '''NONUNIQUE'', ' + IntToStr(Integer(ikNonUnique)) + ', ' + '''UNIQUE'', ' + 'NVL((SELECT DECODE(CONSTRAINT_TYPE, ' + '''P'', ' + IntToStr(Integer(ikPrimaryKey)) + ', ' + IntToStr(Integer(ikUnique)) + ') ' + 'FROM ' + sViewPrefix + '_CONSTRAINTS C ' + 'WHERE ' + sOwnerName + ' = I.OWNER AND C.TABLE_NAME = I.TABLE_NAME AND ' + sIndexName + ' = I.INDEX_NAME AND C.CONSTRAINT_TYPE = ''P''' + '), ' + IntToStr(Integer(ikUnique)) + ')) INDEX_TYPE ' else Result := Result + 'C.CONSTRAINT_NAME, ' + 'DECODE(I.UNIQUENESS, ' + '''NONUNIQUE'', ' + IntToStr(Integer(ikNonUnique)) + ', ' + '''UNIQUE'', ' + 'NVL(DECODE(C.CONSTRAINT_TYPE, ' + '''P'', ' + IntToStr(Integer(ikPrimaryKey)) + ', ' + IntToStr(Integer(ikUnique)) + '), ' + IntToStr(Integer(ikUnique)) + ')) INDEX_TYPE '; Result := Result + 'FROM ' + sViewPrefix + '_INDEXES I'; if FConnMeta.ServerVersion < cvOracle81000 then Result := Result + ', ' + sViewPrefix + '_CONSTRAINTS C'; AddWhere('I.TABLE_OWNER = ' + GetOwner); AddWhere('I.TABLE_NAME = :OBJ', 'OBJ'); if FConnMeta.ServerVersion < cvOracle81000 then begin AddWhere('I.OWNER = C.OWNER (+)'); AddWhere('I.INDEX_NAME = C.CONSTRAINT_NAME (+)'); end; AddWhere('I.INDEX_TYPE <> ''LOB'''); if AWildcard <> '' then AddWhere('I.INDEX_NAME LIKE :WIL', 'WIL'); Result := Result + ' ORDER BY 7 DESC, 5 ASC'; end; mkIndexFields: begin Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'C.INDEX_OWNER AS SCHEMA_NAME, C.TABLE_NAME, C.INDEX_NAME, ' + 'SUBSTR(C.COLUMN_NAME, 1, 30) AS COLUMN_NAME, C.COLUMN_POSITION, '; if FConnMeta.ServerVersion >= cvOracle81500 then Result := Result + 'DECODE(C.DESCEND, ''ASC'', ''A'', ''D'') AS SORT_ORDER, ' else Result := Result + '''A'' AS SORT_ORDER, '; Result := Result + 'TO_CHAR(NULL) AS FILTER, '; if FConnMeta.ServerVersion >= cvOracle81500 then Result := Result + 'E.COLUMN_EXPRESSION ' else Result := Result + 'NULL AS COLUMN_EXPRESSION '; Result := Result + 'FROM ' + sViewPrefix + '_IND_COLUMNS C'; if FConnMeta.ServerVersion >= cvOracle81500 then Result := Result + ', ' + sViewPrefix + '_IND_EXPRESSIONS E'; AddWhere('C.TABLE_OWNER = ' + GetOwner); AddWhere('C.TABLE_NAME = :BAS', 'BAS'); AddWhere('C.INDEX_NAME = :OBJ', 'OBJ'); if FConnMeta.ServerVersion >= cvOracle81500 then begin AddWhere('C.TABLE_OWNER = E.TABLE_OWNER (+)'); AddWhere('C.TABLE_NAME = E.TABLE_NAME (+)'); AddWhere('C.INDEX_OWNER = E.INDEX_OWNER (+)'); AddWhere('C.INDEX_NAME = E.INDEX_NAME (+)'); AddWhere('C.COLUMN_POSITION = E.COLUMN_POSITION (+)'); end; if AWildcard <> '' then AddWhere('C.COLUMN_NAME LIKE :WIL', 'WIL'); Result := Result + ' ORDER BY 7'; end; mkPrimaryKey: begin sIndexName := ''; sOwnerName := ''; sToChar := ''; GetIndexExpressions(sIndexName, sOwnerName, sToChar, 'C'); Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + sOwnerName + ' AS SCHEMA_NAME, C.TABLE_NAME, ' + sIndexName + ', C.CONSTRAINT_NAME, ' + IntToStr(Integer(ikPrimaryKey)) + ' AS INDEX_TYPE ' + 'FROM ' + sViewPrefix + '_CONSTRAINTS C'; AddWhere('C.CONSTRAINT_TYPE = ''P'''); AddWhere(sOwnerName + ' = ' + GetOwner); AddWhere('C.TABLE_NAME = :OBJ', 'OBJ'); if AWildcard <> '' then AddWhere('C.CONSTRAINT_NAME LIKE :WIL', 'WIL'); Result := Result + ' ORDER BY 5'; end; mkPrimaryKeyFields: begin sIndexName := ''; sOwnerName := ''; sToChar := ''; GetIndexExpressions(sIndexName, sOwnerName, sToChar, 'C'); Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'INDEX_OWNER AS SCHEMA_NAME, TABLE_NAME, INDEX_NAME, SUBSTR(COLUMN_NAME, 1, 30) AS COLUMN_NAME, ' + 'COLUMN_POSITION, '; if FConnMeta.ServerVersion >= cvOracle81500 then Result := Result + 'DECODE(DESCEND, ''ASC'', ''A'', ''D'') AS SORT_ORDER, ' else Result := Result + '''A'' AS SORT_ORDER, '; Result := Result + 'TO_CHAR(NULL) AS FILTER ' + 'FROM ' + sViewPrefix + '_IND_COLUMNS ' + 'WHERE (INDEX_OWNER, INDEX_NAME, TABLE_OWNER, TABLE_NAME) = (' + 'SELECT ' + sOwnerName + ', ' + sIndexName + ', ' + sOwnerName + ', C.TABLE_NAME ' + 'FROM ' + sViewPrefix + '_CONSTRAINTS C'; AddWhere('C.CONSTRAINT_TYPE = ''P'''); AddWhere(sOwnerName + ' = ' + GetOwner); AddWhere('C.TABLE_NAME = :BAS)', 'BAS'); if AWildcard <> '' then begin lWasWhere := False; AddWhere('COLUMN_NAME LIKE :WIL', 'WIL'); end; Result := Result + ' ORDER BY 7'; end; mkForeignKeys: begin sIndexName := ''; sOwnerName := ''; sToChar := ''; GetIndexExpressions(sIndexName, sOwnerName, sToChar, 'C'); sIndexName2 := ''; sOwnerName2 := ''; sToChar2 := ''; GetIndexExpressions(sIndexName2, sOwnerName2, sToChar2, 'C2'); Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + sOwnerName + ' AS SCHEMA_NAME, C.TABLE_NAME, C.CONSTRAINT_NAME AS FKEY_NAME, ' + 'TO_CHAR(NULL) AS PKEY_CATALOG_NAME, ' + sOwnerName2 + ' AS PKEY_SCHEMA_NAME, ' + 'C2.TABLE_NAME AS PKEY_TABLE_NAME, '+ 'DECODE(C.DELETE_RULE, ''CASCADE'', ' + IntToStr(Integer(ckCascade)) + ', ''SET NULL'', ' + IntToStr(Integer(ckSetNull)) + ', ' + IntToStr(Integer(ckRestrict)) + ') AS DELETE_RULE, ' + IntToStr(Integer(ckRestrict)) + ' AS UPDATE_RULE ' + 'FROM ' + sViewPrefix + '_CONSTRAINTS C, ' + sViewPrefix + '_CONSTRAINTS C2'; AddWhere('C.R_OWNER = C2.OWNER'); AddWhere('C.R_CONSTRAINT_NAME = C2.CONSTRAINT_NAME'); AddWhere('C.CONSTRAINT_TYPE = ''R'''); AddWhere('C.OWNER = ' + GetOwner); AddWhere('C.TABLE_NAME = :OBJ', 'OBJ'); if AWildcard <> '' then AddWhere('C.CONSTRAINT_NAME LIKE :WIL', 'WIL'); Result := Result + ' ORDER BY 5'; end; mkForeignKeyFields: begin sIndexName := ''; sOwnerName := ''; sToChar := ''; GetIndexExpressions(sIndexName, sOwnerName, sToChar, 'C'); sIndexName2 := ''; sOwnerName2 := ''; sToChar2 := ''; GetIndexExpressions(sIndexName2, sOwnerName2, sToChar2, 'C2'); Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + sOwnerName + ' AS SCHEMA_NAME, C.TABLE_NAME, C.CONSTRAINT_NAME AS FKEY_NAME, '+ 'L.COLUMN_NAME, L2.COLUMN_NAME AS PKEY_COLUMN_NAME, NVL(L.POSITION, 1) AS COLUMN_POSITION ' + 'FROM ' + sViewPrefix + '_CONSTRAINTS C, ' + sViewPrefix + '_CONSTRAINTS C2, ' + sViewPrefix + '_CONS_COLUMNS L, ' + sViewPrefix + '_CONS_COLUMNS L2'; AddWhere('C.R_OWNER = C2.OWNER'); AddWhere('C.R_CONSTRAINT_NAME = C2.CONSTRAINT_NAME'); AddWhere('C.CONSTRAINT_TYPE = ''R'''); AddWhere('C.OWNER = L.OWNER'); AddWhere('C.TABLE_NAME = L.TABLE_NAME'); AddWhere('C.CONSTRAINT_NAME = L.CONSTRAINT_NAME'); AddWhere('C2.OWNER = L2.OWNER'); AddWhere('C2.TABLE_NAME = L2.TABLE_NAME'); AddWhere('C2.CONSTRAINT_NAME = L2.CONSTRAINT_NAME'); AddWhere('NVL(L.POSITION, 1) = NVL(L2.POSITION, 1)'); AddWhere(sOwnerName + ' = ' + GetOwner); AddWhere('C.TABLE_NAME = :BAS', 'BAS'); AddWhere('C.CONSTRAINT_NAME = :OBJ', 'OBJ'); if AWildcard <> '' then AddWhere('C.COLUMN_NAME LIKE :WIL', 'WIL'); Result := Result + ' ORDER BY 8'; end; mkPackages: begin Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'OWNER AS SCHEMA_NAME, OBJECT_NAME AS PACKAGE_NAME, ' + EncodeScope('OWNER') + ' AS PACKAGE_SCOPE ' + 'FROM ' + sViewPrefix + '_OBJECTS'; AddWhere('OBJECT_TYPE = ''PACKAGE'''); AddTopScope('OWNER'); if AWildcard <> '' then AddWhere('OBJECT_NAME LIKE :WIL', 'WIL'); Result := Result + ' ORDER BY 3, 4'; end; mkProcs: begin if ABaseObject = '' then begin Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'OWNER AS SCHEMA_NAME, TO_CHAR(NULL) AS PACK_NAME, OBJECT_NAME AS PROC_NAME, ' + 'TO_NUMBER(NULL) AS OVERLOAD, DECODE(OBJECT_TYPE, ' + '''FUNCTION'', ' + IntToStr(Integer(pkFunction)) + ', ' + '''PROCEDURE'', ' + IntToStr(Integer(pkProcedure)) + ') AS PROC_TYPE, ' + EncodeScope('OWNER') + ' AS PROC_SCOPE, TO_NUMBER(NULL) AS IN_PARAMS, ' + 'TO_NUMBER(NULL) AS OUT_PARAMS ' + 'FROM ' + sViewPrefix + '_OBJECTS'; AddWhere('OBJECT_TYPE IN (''PROCEDURE'', ''FUNCTION'')'); AddTopScope('OWNER'); if AWildcard <> '' then AddWhere('OBJECT_NAME LIKE :WIL', 'WIL'); Result := Result + ' ORDER BY 3, 5'; end else begin Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, A.* ' + 'FROM ( ' + 'SELECT OWNER AS SCHEMA_NAME, PACKAGE_NAME AS PACK_NAME, OBJECT_NAME AS PROC_NAME, ' + 'TO_NUMBER(OVERLOAD) AS OVERLOAD, DECODE(COUNT(DECODE(ARGUMENT_NAME, NULL, 1, NULL)), ' + '1, ' + IntToStr(Integer(pkFunction)) + ', ' + IntToStr(Integer(pkProcedure)) + ') AS PROC_TYPE, ' + EncodeScope('OWNER') + ' AS PROC_SCOPE, ' + 'COUNT(DECODE(IN_OUT, ''IN'', DECODE(DATA_TYPE, NULL, NULL, 1), ''IN/OUT'', 1, NULL)) AS IN_PARAMS, ' + 'COUNT(DECODE(IN_OUT, ''OUT'', 1, ''IN/OUT'', 1, NULL)) AS OUT_PARAMS ' + 'FROM ALL_ARGUMENTS'; AddWhere('PACKAGE_NAME = :BAS', 'BAS'); AddWhere('OWNER = ' + GetOwner); if AWildcard <> '' then AddWhere('OBJECT_NAME LIKE :WIL', 'WIL'); AddWhere('DATA_LEVEL = 0'); Result := Result + ' GROUP BY OWNER, PACKAGE_NAME, OBJECT_NAME, OVERLOAD ' + ') A ORDER BY 3, 4, 5, 6'; end; end; mkProcArgs: begin sCharLen := ''; sUniCharLen := ''; sUniVarCharLen := ''; GetLengthExpressions(sCharLen, sUniCharLen, sUniVarCharLen); Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'OWNER AS SCHEMA_NAME, PACKAGE_NAME AS PACK_NAME, ' + 'OBJECT_NAME AS PROC_NAME, OVERLOAD, NVL(ARGUMENT_NAME, ''Result'') AS PARAM_NAME, ' + 'POSITION AS PARAM_POSITION, ' + 'DECODE(IN_OUT, ''IN'', 1, ''IN/OUT'', 3, ''OUT'', DECODE(ARGUMENT_NAME, NULL, 4, 2)) AS PARAM_TYPE, ' + EncodeDataType('DATA_TYPE') + ' AS PARAM_DATATYPE, ' + 'DECODE(DATA_TYPE, ''UNDEFINED'', ''"'' || TYPE_OWNER || ''"."'' || TYPE_NAME || ' + 'DECODE(TYPE_SUBNAME, NULL, '''', ''."'' || TYPE_SUBNAME || ''"''), DATA_TYPE) AS PARAM_TYPENAME, ' + EncodeAttrs('DATA_TYPE', '', '', '') + ' AS PARAM_ATTRIBUTES, ' + 'LEAST(DATA_PRECISION, 38) AS PARAM_PRECISION, GREATEST(DATA_SCALE, 0) AS PARAM_SCALE, ' + 'DECODE(DATA_TYPE, ''CHAR'', ' + sCharLen + ', ''VARCHAR'', ' + sCharLen + ', ' + '''VARCHAR2'', ' + sCharLen + ', ''NCHAR'', ' + sUniCharLen + ', ' + '''NCHAR VARYING'', ' + sUniVarCharLen + ', ''NVARCHAR2'', ' + sUniVarCharLen + ', ' + '''RAW'', DATA_LENGTH, ''ROWID'', 18, NULL) AS PARAM_LENGTH ' + 'FROM ALL_ARGUMENTS'; if ABaseObject <> '' then AddWhere('PACKAGE_NAME = :BAS', 'BAS') else AddWhere('PACKAGE_NAME IS NULL'); AddWhere('OWNER = ' + GetOwner); AddWhere('OBJECT_NAME = :OBJ', 'OBJ'); if AWildcard <> '' then AddWhere('ARGUMENT_NAME LIKE :WIL', 'WIL'); if AOverload <> 0 then begin AddWhere('OVERLOAD = :OVE', 'OVE'); oPar := GetParams[GetParams.Count - 1]; oPar.DataType := ftInteger; oPar.Size := 0; end else AddWhere('OVERLOAD IS NULL'); AddWhere('DATA_LEVEL = 0'); AddWhere('DATA_TYPE IS NOT NULL'); Result := Result + ' ORDER BY 8'; end; mkGenerators: begin Result := 'SELECT TO_NUMBER(NULL) AS RECNO, TO_CHAR(NULL) AS CATALOG_NAME, ' + 'SEQUENCE_OWNER AS SCHEMA_NAME, SEQUENCE_NAME AS GENERATOR_NAME, ' + EncodeScope('SEQUENCE_OWNER') + ' AS GENERATOR_SCOPE ' + 'FROM ' + sViewPrefix + '_SEQUENCES'; if AWildcard <> '' then AddWhere('SEQUENCE_NAME LIKE :WIL', 'WIL'); AddTopScope('SEQUENCE_OWNER'); Result := Result + ' ORDER BY 3, 4'; end; mkResultSetFields, mkTableTypeFields: Result := ''; end; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetLimitSelect(const ASQL: String; ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String; var sSQL: String; begin sSQL := UpperCase(ASQL); // Without that ORA-2287 (Sequence number is not allowed here) will be raised // on fetching a generator from the DApt manager. if (Pos('NEXTVAL', sSQL) = 0) and (Pos('CURRVAL', sSQL) = 0) then if FConnMeta.ServerVersion >= cvOracle121000 then if (ASkip > 0) and (ARows + ASkip <> MAXINT) then Result := ASQL + BRK + 'OFFSET ' + IntToStr(ASkip) + ' ROWS FETCH FIRST ' + IntToStr(ARows) + ' ROWS ONLY' else if ASkip > 0 then Result := ASQL + BRK + 'OFFSET ' + IntToStr(ASkip) + ' ROWS' else if ARows >= 0 then Result := ASQL + BRK + 'FETCH FIRST ' + IntToStr(ARows) + ' ROWS ONLY' else begin Result := ASQL; AOptions := []; end else if (ASkip > 0) and (ARows + ASkip <> MAXINT) then Result := 'SELECT T.* FROM (SELECT T.*, ROWNUM ' + C_FD_SysColumnPrefix + 'rn FROM (' + ASQL + ') T WHERE ROWNUM <= ' + IntToStr(ASkip + ARows) + ') T WHERE T.' + C_FD_SysColumnPrefix + 'rn > ' + IntToStr(ASkip) else if ASkip > 0 then Result := 'SELECT T.* FROM (SELECT T.*, ROWNUM ' + C_FD_SysColumnPrefix + 'rn FROM (' + ASQL + ') T) T WHERE T.' + C_FD_SysColumnPrefix + 'rn > ' + IntToStr(ASkip) else if ARows >= 0 then Result := 'SELECT * FROM (' + BRK + ASQL + BRK + ') WHERE ROWNUM <= ' + IntToStr(ARows) else begin Result := ASQL; AOptions := []; end else begin Result := ASQL; AOptions := []; end; end; {-------------------------------------------------------------------------------} // http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm function TFDPhysOraCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String; var eAttrs: TFDDataAttributes; begin eAttrs := AColumn.ActualAttributes; if caROWID in eAttrs then begin Result := 'ROWID'; Exit; end; case AColumn.DataType of dtBoolean: Result := 'NUMBER(1, 0)'; dtSByte: Result := 'NUMBER(3, 0)'; dtInt16: Result := 'NUMBER(5, 0)'; dtInt32: Result := 'NUMBER(10, 0)'; dtInt64: Result := 'NUMBER(19, 0)'; dtByte: Result := 'NUMBER(3, 0)'; dtUInt16: Result := 'NUMBER(5, 0)'; dtUInt32: Result := 'NUMBER(10, 0)'; dtUInt64: Result := 'NUMBER(20, 0)'; dtSingle: if FConnMeta.ServerVersion < cvOracle100000 then Result := 'NUMBER(*, 8)' else Result := 'BINARY_FLOAT'; dtDouble, dtExtended: if FConnMeta.ServerVersion < cvOracle100000 then Result := 'NUMBER(*, 16)' else Result := 'BINARY_DOUBLE'; dtCurrency: Result := 'NUMBER' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, 18, 4); dtBCD, dtFmtBCD: Result := 'NUMBER' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, FOptions.FormatOptions.MaxBcdPrecision, 0); dtDateTime, dtTime, dtDate: Result := 'DATE'; dtDateTimeStamp: Result := 'TIMESTAMP'; dtTimeIntervalYM: Result := 'INTERVAL YEAR TO MONTH'; dtTimeIntervalFull, dtTimeIntervalDS: Result := 'INTERVAL DAY TO SECOND'; dtAnsiString: begin if (caFixedLen in AColumn.ActualAttributes) and (AColumn.Size <= 2000) then Result := 'CHAR' else Result := 'VARCHAR'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtWideString: begin if (caFixedLen in AColumn.ActualAttributes) and (AColumn.Size <= 2000) then Result := 'NCHAR' else Result := 'NVARCHAR'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtByteString: Result := 'RAW'; dtBlob: Result := 'LONG RAW'; dtMemo: Result := 'LONG'; dtWideMemo: Result := 'NCLOB'; dtXML: Result := 'XML'; dtHBlob: Result := 'BLOB'; dtHMemo: Result := 'CBLOB'; dtWideHMemo: Result := 'NCBLOB'; dtHBFile: Result := 'BLOB'; dtGUID: Result := 'CHAR(38)'; dtUnknown, dtRowSetRef, dtCursorRef, dtRowRef, dtArrayRef, dtParentRowRef, dtObject: Result := ''; end; if Result <> '' then if caAutoInc in AColumn.ActualAttributes then if FConnMeta.ServerVersion >= cvOracle120000 then Result := Result + ' GENERATED BY DEFAULT AS IDENTITY' else FFlags := FFlags + [gfCreateIdentityTrigger, gfCreateIdentityGenerator] else if caExpr in AColumn.ActualAttributes then if FConnMeta.ServerVersion >= cvOracle110000 then Result := Result + ' GENERATED ALWAYS AS (' + AColumn.Expression + ') VIRTUAL'; end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetCreateGenerator(const AName: String): String; var rName: TFDPhysParsedName; begin rName.FCatalog := ''; rName.FSchema := ''; rName.FBaseObject := ''; rName.FObject := AName; Result := 'CREATE SEQUENCE ' + FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]); end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetDropGenerator(const AName: String): String; var rName: TFDPhysParsedName; begin rName.FCatalog := ''; rName.FSchema := ''; rName.FBaseObject := ''; rName.FObject := AName; Result := 'DROP SEQUENCE ' + FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]); end; {-------------------------------------------------------------------------------} function TFDPhysOraCommandGenerator.GetCreateIdentityTrigger: String; var i: Integer; oCols: TFDDatSColumnList; oCol: TFDDatSColumn; sGen, sCol, sTab: String; rName: TFDPhysParsedName; begin oCols := FTable.Columns; for i := 0 to oCols.Count - 1 do begin oCol := oCols[i]; if ColumnStorable(oCol) and (caAutoInc in oCol.ActualAttributes) then begin sGen := ColumnGenerator(oCol); if sGen <> '' then begin rName.FCatalog := ''; rName.FSchema := ''; rName.FBaseObject := ''; rName.FObject := sGen; sGen := FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]); sCol := GetColumn('', -1, oCol); Result := IND + 'IF :NEW.' + sCol + ' IS NULL THEN' + BRK + IND + IND + 'SELECT ' + sGen + '.NEXTVAL INTO :NEW.' + sCol + ' FROM SYS.DUAL;' + BRK + IND + 'END IF;' + BRK; end; end; end; if Result <> '' then begin sTab := GetFrom; FConnMeta.DecodeObjName(sTab, rName, nil, [doUnquote]); rName.FObject := 'TR_' + rName.FObject + '_BI'; Result := 'CREATE TRIGGER ' + FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]) + BRK + 'BEFORE INSERT ON ' + sTab + ' FOR EACH ROW ' + BRK + 'BEGIN' + BRK + Result + 'END;' + BRK; end; end; {-------------------------------------------------------------------------------} initialization FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.Oracle, S_FD_Ora_RDBMS); end.
unit AContatosCliente; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, ExtCtrls, PainelGradiente, Localizacao, StdCtrls, Componentes1, Buttons, Grids, CGrades, UnDados, UnClientes, Mask; type TFContatosCliente = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; SpeedButton1: TSpeedButton; Label1: TLabel; Label2: TLabel; ECliente: TEditLocaliza; ConsultaPadrao1: TConsultaPadrao; PanelColor2: TPanelColor; Grade: TRBStringGridColor; PanelColor3: TPanelColor; BGravar: TBitBtn; BCancelar: TBitBtn; BFechar: TBitBtn; EProfissao: TEditLocaliza; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure BCancelarClick(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GradeNovaLinha(Sender: TObject); procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure EProfissaoRetorno(Retorno1, Retorno2: String); procedure GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EProfissaoCadastrar(Sender: TObject); procedure GradeKeyPress(Sender: TObject; var Key: Char); private VprAcao: Boolean; VprEmail : string; VprCodCliente: Integer; VprDContato: TRBDContatoCliente; VprContatos: TList; procedure CarTitulosGrade; procedure CarDContatoClasse; function ExisteProfissao : boolean; public { Public declarations } function CadastraContatos(VpaCodCliente: Integer): Boolean; end; var FContatosCliente: TFContatosCliente; implementation uses APrincipal, FunObjeto, ConstMsg, Constantes, FunData, AProfissoes; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFContatosCliente.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprAcao:= False; VprContatos:= TList.Create; Grade.ADados:= VprContatos; Grade.CarregaGrade; CarTitulosGrade; end; { ******************* Quando o formulario e fechado ************************** } procedure TFContatosCliente.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FreeTObjectsList(VprContatos); VprContatos.Free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFContatosCliente.CarTitulosGrade; begin Grade.Cells[1,0]:= 'Nome Contato'; Grade.Cells[2,0]:= 'Dt. Nascimento'; Grade.Cells[3,0]:= 'Telefone'; Grade.Cells[4,0]:= 'Celular'; Grade.Cells[5,0]:= 'E-Mail'; Grade.Cells[6,0]:= 'Código'; Grade.Cells[7,0]:= 'Profissão'; Grade.Cells[8,0]:= 'Observações'; Grade.Cells[9,0]:= 'Marketing'; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Eventos )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFContatosCliente.BFecharClick(Sender: TObject); begin Self.Close; end; {******************************************************************************} procedure TFContatosCliente.BCancelarClick(Sender: TObject); begin Self.Close; end; {******************************************************************************} procedure TFContatosCliente.BGravarClick(Sender: TObject); var VpfResultado: String; begin VpfResultado:= FunClientes.GravaDContatos(VprCodCliente,VprContatos); if VpfResultado = '' then begin VprAcao:= True; Self.Close; end else Aviso(VpfResultado); end; {******************************************************************************} procedure TFContatosCliente.GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDContato:= TRBDContatoCliente(VprContatos.Items[VpaLinha-1]); Grade.Cells[1,VpaLinha]:= VprDContato.NomContato; if VprDContato.DatNascimento > MontaData(1,1,1900) then Grade.Cells[2,VpaLinha]:= FormatDateTime('DD/MM/YYYY',VprDContato.DatNascimento) else Grade.Cells[2,VpaLinha]:= ''; Grade.Cells[3,VpaLinha]:= VprDContato.DesTelefone; Grade.Cells[4,VpaLinha]:= VprDContato.DesCelular; Grade.Cells[5,VpaLinha]:= VprDContato.DesEMail; if VprDContato.CodProfissao <> 0 then Grade.Cells[6,VpaLinha]:= IntToStr(VprDContato.CodProfissao) else Grade.Cells[6,VpaLinha]:= ''; Grade.Cells[7,VpaLinha]:= VprDContato.NomProfissao; Grade.Cells[8,VpaLinha]:= VprDContato.DesObservacao; Grade.Cells[9,VpaLinha]:= VprDContato.AceitaEMarketing; end; {******************************************************************************} procedure TFContatosCliente.GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos:= True; if Grade.Cells[1,Grade.ALinha] = '' then begin Aviso('NOME DO CONTATO NÃO PREENCHIDO!!!'#13'É necessário preencher o nome do contato.'); VpaValidos:= False; Grade.Col:= 1; end else if not ExisteProfissao then begin Aviso('PROFISSÃO INVÁLIDA!!!'#13'A profissão digitada não é válida.'); VpaValidos:= False; Grade.Col:= 6; end else if Grade.Cells[9,Grade.ALinha] = '' then begin Aviso('EMARKETING NÃO PREENCHIDO!!!'#13'É necessário preencher se o cliente aceita telemarketing.'); VpaValidos:= False; Grade.Col:= 1; end; if VpaValidos then CarDContatoClasse; end; {******************************************************************************} procedure TFContatosCliente.CarDContatoClasse; begin VprDContato.NomContato:= Grade.Cells[1,Grade.ALinha]; try StrToDate(Grade.Cells[2,Grade.ALinha]); VprDContato.DatNascimento:= StrToDate(Grade.Cells[2,Grade.ALinha]); except VprDContato.DatNascimento:= MontaData(1,1,1900); end; VprDContato.DesTelefone:= Grade.Cells[3,Grade.ALinha]; VprDContato.DesCelular:= Grade.Cells[4,Grade.ALinha]; VprDContato.DesEMail:= LowerCase(Grade.Cells[5,Grade.ALinha]); if Grade.Cells[6,Grade.ALinha] <> '' then VprDContato.CodProfissao:= StrToInt(Grade.Cells[6,Grade.ALinha]) else VprDContato.CodProfissao:= 0; VprDContato.NomProfissao:= Grade.Cells[7,Grade.ALinha]; VprDContato.DesObservacao:= Grade.Cells[8,Grade.ALinha]; VprDContato.AceitaEMarketing:= Grade.Cells[9,Grade.ALinha]; if Grade.AEstadoGrade in [egEdicao] then begin if VprDContato.DesEMail <> VprEmail then VprDContato.IndExportadoEficacia := false; end; VprDContato.CodUsuario:= Varia.CodigoUsuario; end; {******************************************************************************} function TFContatosCliente.ExisteProfissao : boolean; begin result := true; if Grade.Cells[6,Grade.ALinha] <> '' then begin result := FunClientes.ExisteProfissao(StrToInt(Grade.Cells[6,Grade.ALinha])); if result then begin EProfissao.Text := Grade.Cells[6,Grade.ALinha]; EProfissao.Atualiza; end; end; end; {******************************************************************************} procedure TFContatosCliente.GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); begin case ACol of 2: Value:= '!99\/99\/0000;1; '; 3, 4: Value:= '!\(00\)>#000-0000;1; '; 6: Value:= '00000;0; '; end; end; {******************************************************************************} procedure TFContatosCliente.GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprContatos.Count > 0 then begin VprDContato:= TRBDContatoCliente(VprContatos.Items[VpaLinhaAtual - 1]); VprEmail := VprDContato.DesEMail; end; end; {******************************************************************************} procedure TFContatosCliente.GradeNovaLinha(Sender: TObject); begin VprDContato:= TRBDContatoCliente.cria; VprContatos.Add(VprDContato); VprDContato.AceitaEMarketing:= 'S'; Grade.Cells[9,Grade.ALinha]:= 'S'; end; {******************************************************************************} procedure TFContatosCliente.GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if Grade.AEstadoGrade in [egEdicao, egInsercao] then begin if Grade.AColuna <> ACol then begin case Grade.AColuna of 6: if not ExisteProfissao then EProfissao.AAbreLocalizacao end; end; end; end; {******************************************************************************} procedure TFContatosCliente.EProfissaoRetorno(Retorno1, Retorno2: String); begin Grade.Cells[6,Grade.ALinha]:= Retorno1; Grade.Cells[7,Grade.ALinha]:= Retorno2; end; {******************************************************************************} procedure TFContatosCliente.GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of 114 : begin case Grade.AColuna of 6: EProfissao.AAbreLocalizacao; end; end; end; end; {******************************************************************************} function TFContatosCliente.CadastraContatos( VpaCodCliente: Integer): Boolean; begin VprCodCliente := VpaCodCliente; ECliente.AInteiro := VpaCodCliente; ECliente.Atualiza; FunClientes.CarDContatoCliente(VpaCodCliente,VprContatos); Grade.CarregaGrade; Showmodal; result := VprAcao; end; procedure TFContatosCliente.EProfissaoCadastrar(Sender: TObject); begin FProfissoes :=TFProfissoes.CriarSDI(self,'',FPrincipal.VerificaPermisao('FProfissoes')); FProfissoes.BotaoCadastrar1.Click; FProfissoes.showmodal; FProfissoes.free; ConsultaPadrao1.AtualizaConsulta; end; {******************************************************************************} procedure TFContatosCliente.GradeKeyPress(Sender: TObject; var Key: Char); begin case Grade.Col of 5 : begin if key in [' ',',','/',';','ç','\','ã',':'] then key := #0; end; 9 : begin if not (Key in ['s','S','n','N',#8]) then Key:= #0 else if Key = 's' Then Key:= 'S' else if key = 'n' Then Key:= 'N'; end; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFContatosCliente]); end.
unit UDbfCursor; interface uses classes,db, UDbfPagedFile,UDbfCommon; type TOnBracketStr = procedure(First,Last:PChar;NoFirst,NoLast:boolean;var Accept: Boolean) of object; TOnBracketNum = procedure(First,Last:double;NoFirst,NoLast:boolean;var Accept: Boolean) of object; //==================================================================== TVirtualCursor = class private _file:TPagedFile; public property PagedFile:TPagedFile read _file; constructor Create(pFile:TPagedFile); destructor destroy; override; function RecordSize : Integer; function Next:boolean; virtual; abstract; function Prev:boolean; virtual; abstract; procedure First; virtual; abstract; procedure Last; virtual; abstract; function GetPhysicalRecno:integer; virtual; abstract; procedure SetPhysicalRecno(Recno:integer); virtual; abstract; function GetSequentialRecordCount:integer; virtual; abstract; function GetSequentialRecno:integer; virtual; abstract; procedure SetSequentialRecno(Recno:integer); virtual; abstract; function GetBookMark:rBookmarkData; virtual; abstract; procedure GotoBookmark(Bookmark:rBookmarkData); virtual; abstract; procedure Insert(Recno:integer; Buffer:PChar); virtual; abstract; procedure Update(Recno: integer; PrevBuffer,NewBuffer: PChar); virtual; abstract; end; implementation function TVirtualCursor.RecordSize : Integer; begin if _file = nil then result:=0 else result:=_file.recordsize; end; constructor TVirtualCursor.Create(pFile:TPagedFile); begin _File:=pFile; end; destructor TVirtualCursor.destroy; {override;} begin end; end.
unit testinverseupdateunit; interface uses Math, Sysutils, Ap, inverseupdate; function TestInverseUpdate(Silent : Boolean):Boolean; function testinverseupdateunit_test_silent():Boolean; function testinverseupdateunit_test():Boolean; implementation procedure MakeACopy(const A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var B : TReal2DArray);forward; procedure MatLU(var A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray);forward; procedure GenerateRandomOrthogonalMatrix(var A0 : TReal2DArray; N : AlglibInteger);forward; procedure GenerateRandomMatrixCond(var A0 : TReal2DArray; N : AlglibInteger; C : Double);forward; function InvMatTR(var A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean; IsunitTriangular : Boolean):Boolean;forward; function InvMatLU(var A : TReal2DArray; const Pivots : TInteger1DArray; N : AlglibInteger):Boolean;forward; function InvMat(var A : TReal2DArray; N : AlglibInteger):Boolean;forward; function MatrixDiff(const A : TReal2DArray; const B : TReal2DArray; M : AlglibInteger; N : AlglibInteger):Double;forward; function UpdAndInv(var A : TReal2DArray; const U : TReal1DArray; const V : TReal1DArray; N : AlglibInteger):Boolean;forward; function TestInverseUpdate(Silent : Boolean):Boolean; var A : TReal2DArray; InvA : TReal2DArray; B1 : TReal2DArray; B2 : TReal2DArray; U : TReal1DArray; V : TReal1DArray; N : AlglibInteger; MaxN : AlglibInteger; I : AlglibInteger; J : AlglibInteger; UpdRow : AlglibInteger; UpdCol : AlglibInteger; Val : Double; Pass : AlglibInteger; PassCount : AlglibInteger; WasErrors : Boolean; Threshold : Double; C : Double; begin WasErrors := False; MaxN := 10; PassCount := 100; Threshold := 1.0E-6; // // process // N:=1; while N<=MaxN do begin SetLength(A, N-1+1, N-1+1); SetLength(B1, N-1+1, N-1+1); SetLength(B2, N-1+1, N-1+1); SetLength(U, N-1+1); SetLength(V, N-1+1); Pass:=1; while Pass<=PassCount do begin C := Exp(RandomReal*Ln(10)); GenerateRandomMatrixCond(A, N, C); MakeACopy(A, N, N, InvA); if not InvMat(InvA, N) then begin WasErrors := True; Break; end; // // Test simple update // UpdRow := RandomInteger(N); UpdCol := RandomInteger(N); Val := 0.1*(2*RandomReal-1); I:=0; while I<=N-1 do begin if I=UpdRow then begin U[I] := Val; end else begin U[I] := 0; end; if I=UpdCol then begin V[I] := 1; end else begin V[I] := 0; end; Inc(I); end; MakeACopy(A, N, N, B1); if not UpdAndInv(B1, U, V, N) then begin WasErrors := True; Break; end; MakeACopy(InvA, N, N, B2); RMatrixInvUpdateSimple(B2, N, UpdRow, UpdCol, Val); WasErrors := WasErrors or AP_FP_Greater(MatrixDiff(B1, B2, N, N),Threshold); // // Test row update // UpdRow := RandomInteger(N); I:=0; while I<=N-1 do begin if I=UpdRow then begin U[I] := 1; end else begin U[I] := 0; end; V[I] := 0.1*(2*RandomReal-1); Inc(I); end; MakeACopy(A, N, N, B1); if not UpdAndInv(B1, U, V, N) then begin WasErrors := True; Break; end; MakeACopy(InvA, N, N, B2); RMatrixInvUpdateRow(B2, N, UpdRow, V); WasErrors := WasErrors or AP_FP_Greater(MatrixDiff(B1, B2, N, N),Threshold); // // Test column update // UpdCol := RandomInteger(N); I:=0; while I<=N-1 do begin if I=UpdCol then begin V[I] := 1; end else begin V[I] := 0; end; U[I] := 0.1*(2*RandomReal-1); Inc(I); end; MakeACopy(A, N, N, B1); if not UpdAndInv(B1, U, V, N) then begin WasErrors := True; Break; end; MakeACopy(InvA, N, N, B2); RMatrixInvUpdateColumn(B2, N, UpdCol, U); WasErrors := WasErrors or AP_FP_Greater(MatrixDiff(B1, B2, N, N),Threshold); // // Test full update // I:=0; while I<=N-1 do begin V[I] := 0.1*(2*RandomReal-1); U[I] := 0.1*(2*RandomReal-1); Inc(I); end; MakeACopy(A, N, N, B1); if not UpdAndInv(B1, U, V, N) then begin WasErrors := True; Break; end; MakeACopy(InvA, N, N, B2); RMatrixInvUpdateUV(B2, N, U, V); WasErrors := WasErrors or AP_FP_Greater(MatrixDiff(B1, B2, N, N),Threshold); Inc(Pass); end; Inc(N); end; // // report // if not Silent then begin Write(Format('TESTING INVERSE UPDATE (REAL)'#13#10'',[])); if WasErrors then begin Write(Format('TEST FAILED'#13#10'',[])); end else begin Write(Format('TEST PASSED'#13#10'',[])); end; Write(Format(''#13#10''#13#10'',[])); end; Result := not WasErrors; end; (************************************************************************* Copy *************************************************************************) procedure MakeACopy(const A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var B : TReal2DArray); var I : AlglibInteger; J : AlglibInteger; begin SetLength(B, M-1+1, N-1+1); I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin B[I,J] := A[I,J]; Inc(J); end; Inc(I); end; end; (************************************************************************* LU decomposition *************************************************************************) procedure MatLU(var A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); var I : AlglibInteger; J : AlglibInteger; JP : AlglibInteger; T1 : TReal1DArray; s : Double; i_ : AlglibInteger; begin SetLength(Pivots, Min(M-1, N-1)+1); SetLength(T1, Max(M-1, N-1)+1); Assert((M>=0) and (N>=0), 'Error in LUDecomposition: incorrect function arguments'); // // Quick return if possible // if (M=0) or (N=0) then begin Exit; end; J:=0; while J<=Min(M-1, N-1) do begin // // Find pivot and test for singularity. // JP := J; I:=J+1; while I<=M-1 do begin if AP_FP_Greater(AbsReal(A[I,J]),AbsReal(A[JP,J])) then begin JP := I; end; Inc(I); end; Pivots[J] := JP; if AP_FP_Neq(A[JP,J],0) then begin // //Apply the interchange to rows // if JP<>J then begin APVMove(@T1[0], 0, N-1, @A[J][0], 0, N-1); APVMove(@A[J][0], 0, N-1, @A[JP][0], 0, N-1); APVMove(@A[JP][0], 0, N-1, @T1[0], 0, N-1); end; // //Compute elements J+1:M of J-th column. // if J<M then begin JP := J+1; S := 1/A[J,J]; for i_ := JP to M-1 do begin A[i_,J] := S*A[i_,J]; end; end; end; if J<Min(M, N)-1 then begin // //Update trailing submatrix. // JP := J+1; I:=J+1; while I<=M-1 do begin S := A[I,J]; APVSub(@A[I][0], JP, N-1, @A[J][0], JP, N-1, S); Inc(I); end; end; Inc(J); end; end; (************************************************************************* Generate matrix with given condition number C (2-norm) *************************************************************************) procedure GenerateRandomOrthogonalMatrix(var A0 : TReal2DArray; N : AlglibInteger); var T : Double; Lambda : Double; S : AlglibInteger; I : AlglibInteger; J : AlglibInteger; U1 : Double; U2 : Double; W : TReal1DArray; V : TReal1DArray; A : TReal2DArray; SM : Double; begin if N<=0 then begin Exit; end; SetLength(W, N+1); SetLength(V, N+1); SetLength(A, N+1, N+1); SetLength(A0, N-1+1, N-1+1); // // Prepare A // I:=1; while I<=N do begin J:=1; while J<=N do begin if I=J then begin A[I,J] := 1; end else begin A[I,J] := 0; end; Inc(J); end; Inc(I); end; // // Calculate A using Stewart algorithm // S:=2; while S<=N do begin // // Prepare v and Lambda = v'*v // repeat I := 1; while i<=S do begin U1 := 2*RandomReal-1; U2 := 2*RandomReal-1; SM := U1*U1+U2*U2; if AP_FP_Eq(SM,0) or AP_FP_Greater(SM,1) then begin Continue; end; SM := Sqrt(-2*Ln(SM)/SM); V[I] := U1*SM; if I+1<=S then begin V[I+1] := U2*SM; end; I := I+2; end; Lambda := APVDotProduct(@V[0], 1, S, @V[0], 1, S); until AP_FP_Neq(Lambda,0); Lambda := 2/Lambda; // // A * (I - 2 vv'/v'v ) = // = A - (2/v'v) * A * v * v' = // = A - (2/v'v) * w * v' // where w = Av // I:=1; while I<=S do begin T := APVDotProduct(@A[I][0], 1, S, @V[0], 1, S); W[I] := T; Inc(I); end; I:=1; while I<=S do begin T := W[I]*Lambda; APVSub(@A[I][0], 1, S, @V[0], 1, S, T); Inc(I); end; Inc(S); end; // // // I:=1; while I<=N do begin J:=1; while J<=N do begin A0[I-1,J-1] := A[I,J]; Inc(J); end; Inc(I); end; end; procedure GenerateRandomMatrixCond(var A0 : TReal2DArray; N : AlglibInteger; C : Double); var L1 : Double; L2 : Double; Q1 : TReal2DArray; Q2 : TReal2DArray; CC : TReal1DArray; I : AlglibInteger; J : AlglibInteger; K : AlglibInteger; begin GenerateRandomOrthogonalMatrix(Q1, N); GenerateRandomOrthogonalMatrix(Q2, N); SetLength(CC, N-1+1); L1 := 0; L2 := Ln(1/C); CC[0] := Exp(L1); I:=1; while I<=N-2 do begin CC[I] := Exp(RandomReal*(L2-L1)+L1); Inc(I); end; CC[N-1] := Exp(L2); SetLength(A0, N-1+1, N-1+1); I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin A0[I,J] := 0; K:=0; while K<=N-1 do begin A0[I,J] := A0[I,J]+Q1[I,K]*CC[K]*Q2[J,K]; Inc(K); end; Inc(J); end; Inc(I); end; end; (************************************************************************* triangular inverse *************************************************************************) function InvMatTR(var A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean; IsunitTriangular : Boolean):Boolean; var NOunit : Boolean; I : AlglibInteger; J : AlglibInteger; V : Double; AJJ : Double; T : TReal1DArray; i_ : AlglibInteger; begin Result := True; SetLength(T, N-1+1); // // Test the input parameters. // NOunit := not IsunitTriangular; if IsUpper then begin // // Compute inverse of upper triangular matrix. // J:=0; while J<=N-1 do begin if NOunit then begin if AP_FP_Eq(A[J,J],0) then begin Result := False; Exit; end; A[J,J] := 1/A[J,J]; AJJ := -A[J,J]; end else begin AJJ := -1; end; // // Compute elements 1:j-1 of j-th column. // if J>0 then begin for i_ := 0 to J-1 do begin T[i_] := A[i_,J]; end; I:=0; while I<=J-1 do begin if I<J-1 then begin V := APVDotProduct(@A[I][0], I+1, J-1, @T[0], I+1, J-1); end else begin V := 0; end; if NOunit then begin A[I,J] := V+A[I,I]*T[I]; end else begin A[I,J] := V+T[I]; end; Inc(I); end; for i_ := 0 to J-1 do begin A[i_,J] := AJJ*A[i_,J]; end; end; Inc(J); end; end else begin // // Compute inverse of lower triangular matrix. // J:=N-1; while J>=0 do begin if NOunit then begin if AP_FP_Eq(A[J,J],0) then begin Result := False; Exit; end; A[J,J] := 1/A[J,J]; AJJ := -A[J,J]; end else begin AJJ := -1; end; if J<N-1 then begin // // Compute elements j+1:n of j-th column. // for i_ := J+1 to N-1 do begin T[i_] := A[i_,J]; end; I:=J+1; while I<=N-1 do begin if I>J+1 then begin V := APVDotProduct(@A[I][0], J+1, I-1, @T[0], J+1, I-1); end else begin V := 0; end; if NOunit then begin A[I,J] := V+A[I,I]*T[I]; end else begin A[I,J] := V+T[I]; end; Inc(I); end; for i_ := J+1 to N-1 do begin A[i_,J] := AJJ*A[i_,J]; end; end; Dec(J); end; end; end; (************************************************************************* LU inverse *************************************************************************) function InvMatLU(var A : TReal2DArray; const Pivots : TInteger1DArray; N : AlglibInteger):Boolean; var WORK : TReal1DArray; I : AlglibInteger; IWS : AlglibInteger; J : AlglibInteger; JB : AlglibInteger; JJ : AlglibInteger; JP : AlglibInteger; V : Double; i_ : AlglibInteger; begin Result := True; // // Quick return if possible // if N=0 then begin Exit; end; SetLength(WORK, N-1+1); // // Form inv(U) // if not InvMatTR(A, N, True, False) then begin Result := False; Exit; end; // // Solve the equation inv(A)*L = inv(U) for inv(A). // J:=N-1; while J>=0 do begin // // Copy current column of L to WORK and replace with zeros. // I:=J+1; while I<=N-1 do begin WORK[I] := A[I,J]; A[I,J] := 0; Inc(I); end; // // Compute current column of inv(A). // if J<N-1 then begin I:=0; while I<=N-1 do begin V := APVDotProduct(@A[I][0], J+1, N-1, @WORK[0], J+1, N-1); A[I,J] := A[I,J]-V; Inc(I); end; end; Dec(J); end; // // Apply column interchanges. // J:=N-2; while J>=0 do begin JP := Pivots[J]; if JP<>J then begin for i_ := 0 to N-1 do begin WORK[i_] := A[i_,J]; end; for i_ := 0 to N-1 do begin A[i_,J] := A[i_,JP]; end; for i_ := 0 to N-1 do begin A[i_,JP] := WORK[i_]; end; end; Dec(J); end; end; (************************************************************************* Matrix inverse *************************************************************************) function InvMat(var A : TReal2DArray; N : AlglibInteger):Boolean; var Pivots : TInteger1DArray; begin MatLU(A, N, N, Pivots); Result := InvMatLU(A, Pivots, N); end; (************************************************************************* Diff *************************************************************************) function MatrixDiff(const A : TReal2DArray; const B : TReal2DArray; M : AlglibInteger; N : AlglibInteger):Double; var I : AlglibInteger; J : AlglibInteger; begin Result := 0; I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin Result := Max(Result, AbsReal(B[I,J]-A[I,J])); Inc(J); end; Inc(I); end; end; (************************************************************************* Update and inverse *************************************************************************) function UpdAndInv(var A : TReal2DArray; const U : TReal1DArray; const V : TReal1DArray; N : AlglibInteger):Boolean; var Pivots : TInteger1DArray; I : AlglibInteger; R : Double; begin I:=0; while I<=N-1 do begin R := U[I]; APVAdd(@A[I][0], 0, N-1, @V[0], 0, N-1, R); Inc(I); end; MatLU(A, N, N, Pivots); Result := InvMatLU(A, Pivots, N); end; (************************************************************************* Silent unit test *************************************************************************) function testinverseupdateunit_test_silent():Boolean; begin Result := TestInverseUpdate(True); end; (************************************************************************* Unit test *************************************************************************) function testinverseupdateunit_test():Boolean; begin Result := TestInverseUpdate(False); end; end.
{ Copyright (c) 2013-2017, RealThinClient components - http://www.realthinclient.com Copyright (c) Independent JPEG group - http://www.ijg.org 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 OWNER 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. @exclude } unit rtcXJPEGConst; {$INCLUDE rtcDefs.inc} interface uses rtcTypes; const MAXDATALEN = $6FFFFFFF; type JPEG_Float = single; colorRGB24 = packed record R, G, B: byte; end; colorBGR24 = packed record B, G, R: byte; end; colorRGB32 = packed record R, G, B, A: byte; end; colorBGR32 = packed record B, G, R, A: byte; end; PColorRGB24 = ^colorRGB24; PColorBGR24 = ^colorBGR24; PColorRGB32 = ^colorRGB32; PColorBGR32 = ^colorBGR32; colorRGB24x8 = packed record R1, G1, B1: byte; R2, G2, B2: byte; R3, G3, B3: byte; R4, G4, B4: byte; R5, G5, B5: byte; R6, G6, B6: byte; R7, G7, B7: byte; R8, G8, B8: byte; end; colorBGR24x8 = packed record B1, G1, R1: byte; B2, G2, R2: byte; B3, G3, R3: byte; B4, G4, R4: byte; B5, G5, R5: byte; B6, G6, R6: byte; B7, G7, R7: byte; B8, G8, R8: byte; end; colorRGB32x8 = packed record R1, G1, B1, A1: byte; R2, G2, B2, A2: byte; R3, G3, B3, A3: byte; R4, G4, B4, A4: byte; R5, G5, B5, A5: byte; R6, G6, B6, A6: byte; R7, G7, B7, A7: byte; R8, G8, B8, A8: byte; end; colorBGR32x8 = packed record B1, G1, R1, A1: byte; B2, G2, R2, A2: byte; B3, G3, R3, A3: byte; B4, G4, R4, A4: byte; B5, G5, R5, A5: byte; B6, G6, R6, A6: byte; B7, G7, R7, A7: byte; B8, G8, R8, A8: byte; end; colorAll24x8 = packed record Bits1: longword; Bits2: longword; Bits3: longword; Bits4: longword; Bits5: longword; Bits6: longword; end; colorAll32x8 = packed record RGBA1: longword; RGBA2: longword; RGBA3: longword; RGBA4: longword; RGBA5: longword; RGBA6: longword; RGBA7: longword; RGBA8: longword; end; TRGB24_buffer = array[0..(MAXDATALEN div SizeOf(colorRGB24))] of colorRGB24; TRGB32_buffer = array[0..(MAXDATALEN div SizeOf(colorRGB32))] of colorRGB32; TBGR24_buffer = array[0..(MAXDATALEN div SizeOf(colorBGR24))] of colorBGR24; TBGR32_buffer = array[0..(MAXDATALEN div SizeOf(colorBGR32))] of colorBGR32; PRGB24_buffer =^TRGB24_buffer; PRGB32_buffer =^TRGB32_buffer; PBGR24_buffer =^TBGR24_buffer; PBGR32_buffer =^TBGR32_buffer; TRGB24x8_buffer = array[0..(MAXDATALEN div SizeOf(colorRGB24x8))] of colorRGB24x8; TRGB32x8_buffer = array[0..(MAXDATALEN div SizeOf(colorRGB32x8))] of colorRGB32x8; TBGR24x8_buffer = array[0..(MAXDATALEN div SizeOf(colorBGR24x8))] of colorBGR24x8; TBGR32x8_buffer = array[0..(MAXDATALEN div SizeOf(colorBGR32x8))] of colorBGR32x8; TAll24x8_buffer = array[0..(MAXDATALEN div SizeOf(colorAll24x8))] of colorAll24x8; TAll32x8_buffer = array[0..(MAXDATALEN div SizeOf(colorAll32x8))] of colorAll32x8; PRGB24x8_buffer =^TRGB24x8_buffer; PRGB32x8_buffer =^TRGB32x8_buffer; PBGR24x8_buffer =^TBGR24x8_buffer; PBGR32x8_buffer =^TBGR32x8_buffer; PAll24x8_buffer =^TAll24x8_buffer; PAll32x8_buffer =^TAll32x8_buffer; bitstring = packed record length: byte; value: longword; // word end; // { BYTE length; WORD value;} bitstring; ByteArr64 = array [0 .. 63] of byte; ByteArr17 = array [0 .. 16] of byte; ByteArr12 = array [0 .. 11] of byte; ByteArr162 = array [0 .. 161] of byte; BitString12 = array [0 .. 11] of bitstring; BitString256 = array [0 .. 255] of bitstring; SmallIntArr64 = array [0 .. 63] of smallint; ShortIntArr64 = array [0 .. 63] of shortint; LongIntArr64 = array [0 .. 63] of longint; FloatArr64 = array [0 .. 63] of JPEG_Float; FloatArr8 = array [0 .. 7] of JPEG_Float; WordArr256 = array [0 .. 255] of word; PByte = ^byte; PJPEG_LongInt = ^LongInt; PJPEG_Float = ^JPEG_Float; PByteArr64 = ^ByteArr64; const zigzag: ByteArr64 = (0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63); (* These are the sample quantization tables given in JPEG spec section K.1. The spec says that the values given produce "good" quality, and when divided by 2, "very good" quality. *) txt_luminance_qt: ByteArr64 = (4, 2, 2, 4, 6, 10, 12, 15, 3, 3, 3, 4, 6, 14, 15, 13, 3, 3, 4, 6, 10, 14, 17, 14, 3, 4, 5, 7, 12, 21, 20, 15, 4, 5, 9, 14, 17, 27, 25, 19, 6, 8, 13, 16, 20, 26, 28, 23, 12, 16, 19, 21, 25, 30, 30, 25, 18, 23, 23, 24, 28, 25, 25, 24); txt_chrominance_qt: ByteArr64 = (4, 4, 6, 11, 24, 24, 24, 24, 4, 5, 6, 16, 24, 24, 24, 24, 6, 6, 14, 24, 24, 24, 24, 24, 11, 16, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24); img_luminance_qt: ByteArr64 = (16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99); img_chrominance_qt: ByteArr64 = (17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99); // Standard Huffman tables (cf. JPEG standard section K.3) */ std_dc_luminance_nrcodes: ByteArr17 = (0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0); std_dc_luminance_values: ByteArr12 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); std_dc_chrominance_nrcodes: ByteArr17 = (0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0); std_dc_chrominance_values: ByteArr12 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); std_ac_luminance_nrcodes: ByteArr17 = (0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, $7D); std_ac_luminance_values: ByteArr162 = ($01, $02, $03, $00, $04, $11, $05, $12, $21, $31, $41, $06, $13, $51, $61, $07, $22, $71, $14, $32, $81, $91, $A1, $08, $23, $42, $B1, $C1, $15, $52, $D1, $F0, $24, $33, $62, $72, $82, $09, $0A, $16, $17, $18, $19, $1A, $25, $26, $27, $28, $29, $2A, $34, $35, $36, $37, $38, $39, $3A, $43, $44, $45, $46, $47, $48, $49, $4A, $53, $54, $55, $56, $57, $58, $59, $5A, $63, $64, $65, $66, $67, $68, $69, $6A, $73, $74, $75, $76, $77, $78, $79, $7A, $83, $84, $85, $86, $87, $88, $89, $8A, $92, $93, $94, $95, $96, $97, $98, $99, $9A, $A2, $A3, $A4, $A5, $A6, $A7, $A8, $A9, $AA, $B2, $B3, $B4, $B5, $B6, $B7, $B8, $B9, $BA, $C2, $C3, $C4, $C5, $C6, $C7, $C8, $C9, $CA, $D2, $D3, $D4, $D5, $D6, $D7, $D8, $D9, $DA, $E1, $E2, $E3, $E4, $E5, $E6, $E7, $E8, $E9, $EA, $F1, $F2, $F3, $F4, $F5, $F6, $F7, $F8, $F9, $FA); std_ac_chrominance_nrcodes: ByteArr17 = (0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, $77); std_ac_chrominance_values: ByteArr162 = ($00, $01, $02, $03, $11, $04, $05, $21, $31, $06, $12, $41, $51, $07, $61, $71, $13, $22, $32, $81, $08, $14, $42, $91, $A1, $B1, $C1, $09, $23, $33, $52, $F0, $15, $62, $72, $D1, $0A, $16, $24, $34, $E1, $25, $F1, $17, $18, $19, $1A, $26, $27, $28, $29, $2A, $35, $36, $37, $38, $39, $3A, $43, $44, $45, $46, $47, $48, $49, $4A, $53, $54, $55, $56, $57, $58, $59, $5A, $63, $64, $65, $66, $67, $68, $69, $6A, $73, $74, $75, $76, $77, $78, $79, $7A, $82, $83, $84, $85, $86, $87, $88, $89, $8A, $92, $93, $94, $95, $96, $97, $98, $99, $9A, $A2, $A3, $A4, $A5, $A6, $A7, $A8, $A9, $AA, $B2, $B3, $B4, $B5, $B6, $B7, $B8, $B9, $BA, $C2, $C3, $C4, $C5, $C6, $C7, $C8, $C9, $CA, $D2, $D3, $D4, $D5, $D6, $D7, $D8, $D9, $DA, $E2, $E3, $E4, $E5, $E6, $E7, $E8, $E9, $EA, $F2, $F3, $F4, $F5, $F6, $F7, $F8, $F9, $FA); mask: array [0 .. 15] of word = (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768); implementation end.
{ **********************************************************} { } { DeskMetrics - Delphi Dynamic Unit } { Copyright (c) 2010-2011 } { } { http://deskmetrics.com } { support@deskmetrics.com } { } { Author: Stuart Clennett (GNU GPL v3) } { } { **********************************************************} unit DeskMetrics; interface uses SysUtils; type TDMStart = function(FApplicationID: PWideChar; FApplicationVersion: PWideChar): Boolean; stdcall; TDMStartA = function(FApplicationID: PAnsiChar; FApplicationVersion: PAnsiChar): Boolean; stdcall; TDMStop = function: Boolean; stdcall; TDMTrackEvent = procedure(FEventCategory, FEventName: PWideChar); stdcall; TDMTrackEventA = procedure(FEventCategory, FEventName: PAnsiChar); stdcall; TDMTrackEventValue = procedure(FEventCategory, FEventName, FEventValue: PWideChar); stdcall; TDMTrackEventValueA = procedure(FEventCategory, FEventName, FEventValue: PAnsiChar); stdcall; TDMTrackEventPeriod = procedure(FEventCategory, FEventName: PWideChar; FEventTime: Integer; FEventCompleted: Boolean); stdcall; TDMTrackEventPeriodA = procedure(FEventCategory, FEventName: PAnsiChar; FEventTime: Integer; FEventCompleted: Boolean); stdcall; TDMTrackLog = procedure(FMessage: PWideChar); stdcall; TDMTrackLogA = procedure(FMessage: PAnsiChar); stdcall; TDMTrackCustomData = procedure(FName, FValue: PWideChar); stdcall; TDMTrackCustomDataA = procedure(FName, FValue: PAnsiChar); stdcall; TDMTrackCustomDataR = function(FName: PWideChar; FValue: PWideChar): Integer; stdcall; TDMTrackCustomDataRA = function(FName: PAnsiChar; FValue: PAnsiChar): Integer; stdcall; TDMTrackException = procedure(FExpectionObject: Exception); stdcall; TDMSetProxy = function(FHostIP: PWideChar; FPort: Integer; FUserName, FPassword: PWideChar): Boolean; stdcall; TDMSetProxyA = function(FHostIP: PAnsiChar; FPort: Integer; FUserName, FPassword: PAnsiChar): Boolean; stdcall; TDMGetProxy = function(var FHostIP: PWideChar; var FPort: Integer): Boolean; stdcall; TDMGetProxyA = function(var FHostIP: PAnsiChar; var FPort: Integer): Boolean; stdcall; TDMSetUserID = function(FID: PWideChar): Boolean; stdcall; TDMSetUserIDA = function(FID: PAnsiChar): Boolean; stdcall; TDMGetPostServer = function:PWideChar; stdcall; TDMGetPostServerA = function:PAnsiChar; stdcall; TDMSetPostServer = function(FServer: PWideChar): Boolean; stdcall; TDMSetPostServerA = function(FServer: PAnsiChar): Boolean; stdcall; TDMGetPostPort = function:Integer; stdcall; TDMSetPostPort = function(FPort: Integer): Boolean; stdcall; TDMGetPostTimeOut = function:Integer; stdcall; TDMSetPostTimeOut = function(FTimeOut: Integer): Boolean; stdcall; TDMGetPostWaitResponse = function:Boolean; stdcall; TDMSetPostWaitResponse = function(FEnabled: Boolean): Boolean; stdcall; TDMGetJSON = function:PWideChar; stdcall; TDMGetJSONA = function:PAnsiChar; stdcall; TDMSetEnabled = function(FValue: Boolean): Boolean; stdcall; TDMGetEnabled = function:Boolean; stdcall; TDMSendData = function:Boolean; stdcall; TDMGetDebugMode = function:Boolean; stdcall; TDMSetDebugMode = function(FEnabled: Boolean): Boolean; stdcall; TDMGetDebugFile = function:Boolean; stdcall; function DeskMetricsStart(FApplicationID: PWideChar; FApplicationVersion: PWideChar): Boolean; function DeskMetricsStartA(FApplicationID: PAnsiChar; FApplicationVersion: PAnsiChar): Boolean; function DeskMetricsStop: Boolean; procedure DeskMetricsTrackEvent(FEventCategory, FEventName: PWideChar); procedure DeskMetricsTrackEventA(FEventCategory, FEventName: PAnsiChar); procedure DeskMetricsTrackEventValue(FEventCategory, FEventName, FEventValue: PWideChar); procedure DeskMetricsTrackEventValueA(FEventCategory, FEventName, FEventValue: PAnsiChar); procedure DeskMetricsTrackEventPeriod(FEventCategory, FEventName: PWideChar; FEventTime: Integer; FEventCanceled: Boolean); procedure DeskMetricsTrackEventPeriodA(FEventCategory, FEventName: PAnsiChar; FEventTime: Integer; FEventCanceled: Boolean); procedure DeskMetricsTrackLog(FMessage: PWideChar); procedure DeskMetricsTrackLogA(FMessage: PAnsiChar); procedure DeskMetricsTrackCustomData(FName, FValue: PWideChar); procedure DeskMetricsTrackCustomDataA(FName, FValue: PAnsiChar); function DeskMetricsTrackCustomDataR(FName: PWideChar; FValue: PWideChar): Integer; function DeskMetricsTrackCustomDataRA(FName: PAnsiChar; FValue: PAnsiChar): Integer; procedure DeskMetricsTrackException(FExpectionObject: Exception); function DeskMetricsSetProxy(FHostIP: PWideChar; FPort: Integer; FUserName, FPassword: PWideChar): Boolean; function DeskMetricsSetProxyA(FHostIP: PAnsiChar; FPort: Integer; FUserName, FPassword: PAnsiChar): Boolean; function DeskMetricsGetProxy(var FHostIP: PWideChar; var FPort: Integer): Boolean; function DeskMetricsGetProxyA(var FHostIP: PAnsiChar; var FPort: Integer): Boolean; function DeskMetricsSetUserID(FID: PWideChar): Boolean; function DeskMetricsSetUserIDA(FID: PAnsiChar): Boolean; function DeskMetricsGetPostServer: PWideChar; function DeskMetricsGetPostServerA: PAnsiChar; function DeskMetricsSetPostServer(FServer: PWideChar): Boolean; function DeskMetricsSetPostServerA(FServer: PAnsiChar): Boolean; function DeskMetricsGetPostPort: Integer; function DeskMetricsSetPostPort(FPort: Integer): Boolean; function DeskMetricsGetPostTimeOut: Integer; function DeskMetricsSetPostTimeOut(FTimeOut: Integer): Boolean; function DeskMetricsGetPostWaitResponse: Boolean; function DeskMetricsSetPostWaitResponse(FEnabled: Boolean): Boolean; function DeskMetricsGetJSON: PWideChar; function DeskMetricsGetJSONA: PAnsiChar; function DeskMetricsSetEnabled(FValue: Boolean): Boolean; function DeskMetricsGetEnabled: Boolean; function DeskMetricsSendData: Boolean; function DeskMetricsGetDebugMode: Boolean; function DeskMetricsSetDebugMode(FEnabled: Boolean): Boolean; function DeskMetricsGetDebugFile: Boolean; function DeskMetricsDllLoaded: Boolean; function Load_DLL: Boolean; function Unload_DLL: Boolean; const EMPTY_STRING = ''; NO_INTEGER_VALUE = 0; implementation uses Windows; var hModule : THandle; const DESKMETRICS_DLL = 'DeskMetrics.dll'; PROC_DeskMetricsStart = 'DeskMetricsStart'; PROC_DeskMetricsStartA = 'DeskMetricsStartA'; PROC_DeskMetricsStop = 'DeskMetricsStop'; PROC_DeskMetricsTrackEvent = 'DeskMetricsTrackEvent'; PROC_DeskMetricsTrackEventA = 'DeskMetricsTrackEventA'; PROC_DeskMetricsTrackEventValue = 'DeskMetricsTrackEventValue'; PROC_DeskMetricsTrackEventValueA = 'DeskMetricsTrackEventValueA'; PROC_DeskMetricsTrackEventPeriod = 'DeskMetricsTrackEventPeriod'; PROC_DeskMetricsTrackEventPeriodA = 'DeskMetricsTrackEventPeriodA'; PROC_DeskMetricsTrackLog = 'DeskMetricsTrackLog'; PROC_DeskMetricsTrackLogA = 'DeskMetricsTrackLogA'; PROC_DeskMetricsTrackCustomData = 'DeskMetricsTrackCustomData'; PROC_DeskMetricsTrackCustomDataA = 'DeskMetricsTrackCustomDataA'; PROC_DeskMetricsTrackCustomDataR = 'DeskMetricsTrackCustomDataR'; PROC_DeskMetricsTrackCustomDataRA = 'DeskMetricsTrackCustomDataRA'; PROC_DeskMetricsTrackException = 'DeskMetricsTrackException'; PROC_DeskMetricsSetProxy = 'DeskMetricsSetProxy'; PROC_DeskMetricsSetProxyA = 'DeskMetricsSetProxyA'; PROC_DeskMetricsGetProxy = 'DeskMetricsGetProxy'; PROC_DeskMetricsGetProxyA = 'DeskMetricsGetProxyA'; PROC_DeskMetricsSetUserID = 'DeskMetricsSetUserID'; PROC_DeskMetricsSetUserIDA = 'DeskMetricsSetUserIDA'; PROC_DeskMetricsGetPostServer = 'DeskMetricsGetPostServer'; PROC_DeskMetricsGetPostServerA = 'DeskMetricsGetPostServerA'; PROC_DeskMetricsSetPostServer = 'DeskMetricsSetPostServer'; PROC_DeskMetricsSetPostServerA = 'DeskMetricsSetPostServerA'; PROC_DeskMetricsGetPostPort = 'DeskMetricsGetPostPort'; PROC_DeskMetricsSetPostPort = 'DeskMetricsSetPostPort'; PROC_DeskMetricsGetPostTimeOut = 'DeskMetricsGetPostTimeOut'; PROC_DeskMetricsSetPostTimeOut = 'DeskMetricsSetPostTimeOut'; PROC_DeskMetricsGetPostWaitResponse = 'DeskMetricsGetPostWaitResponse'; PROC_DeskMetricsSetPostWaitResponse = 'DeskMetricsSetPostWaitResponse'; PROC_DeskMetricsGetJSON = 'DeskMetricsGetJSON'; PROC_DeskMetricsGetJSONA = 'DeskMetricsGetJSONA'; PROC_DeskMetricsSetEnabled = 'DeskMetricsSetEnabled'; PROC_DeskMetricsGetEnabled = 'DeskMetricsGetEnabled'; PROC_DeskMetricsSendData = 'DeskMetricsSendData'; PROC_DeskMetricsGetDebugMode = 'DeskMetricsGetDebugMode'; PROC_DeskMetricsSetDebugMode = 'DeskMetricsSetDebugMode'; PROC_DeskMetricsGetDebugFile = 'DeskMetricsGetDebugFile'; function GetAppPath : string; begin try Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); except Result := ''; end; end; function CheckLoadDLL : Boolean; begin try if hModule < HINSTANCE_ERROR then begin hModule := LoadLibrary(PChar(GetAppPath + DESKMETRICS_DLL)); Result := not(hModule < HINSTANCE_ERROR); end else Result := True; except Result := False; end; end; function DeskMetricsDllLoaded : Boolean; begin try Result := not (hModule < HINSTANCE_ERROR); except Result := False; end; end; function Load_DLL : boolean; begin try Result := CheckLoadDLL; except Result := False; end; end; function Unload_DLL : boolean; begin try Result := False; if not (hModule < HINSTANCE_ERROR) then Result := FreeLibrary(hModule); except Result := False; end; end; function DeskMetricsStart(FApplicationID: PWideChar; FApplicationVersion: PWideChar): Boolean; const DMStart : TDMStart = nil; begin Result := False; try if CheckLoadDLL then begin @DMStart := GetProcAddress(hModule, PROC_DeskMetricsStart); if Assigned(DMStart) then Result := DMStart(FApplicationID, FApplicationVersion); end; except Result := False; end; end; function DeskMetricsStartA(FApplicationID: PAnsiChar; FApplicationVersion: PAnsiChar): Boolean; const DMStartA : TDMStartA = nil; begin Result := False; try if CheckLoadDLL then begin @DMStartA := GetProcAddress(hModule, PROC_DeskMetricsStartA); if Assigned(DMStartA) then Result := DMStartA(FApplicationID, FApplicationVersion); end; except Result := False; end; end; function DeskMetricsStop: Boolean; const DMStop : TDMStop = nil; begin Result := False; try if CheckLoadDLL then begin @DMStop := GetProcAddress(hModule, PROC_DeskMetricsStop); if Assigned(DMStop) then Result := DMStop; end; except Result := False; end; end; procedure DeskMetricsTrackEvent(FEventCategory, FEventName: PWideChar); const DMTrackEvent : TDMTrackEvent = nil; begin try if CheckLoadDLL then begin @DMTrackEvent := GetProcAddress(hModule, PROC_DeskMetricsTrackEvent); if Assigned(DMTrackEvent) then DMTrackEvent(FEventCategory, fEventName); end; except end; end; procedure DeskMetricsTrackEventA(FEventCategory, FEventName: PAnsiChar); const DMTrackEventA : TDMTrackEventA = nil; begin try if CheckLoadDLL then begin @DMTrackEventA := GetProcAddress(hModule, PROC_DeskMetricsTrackEventA); if Assigned(DMTrackEventA) then DMTrackEventA(FEventCategory, fEventName); end; except end; end; procedure DeskMetricsTrackEventValue(FEventCategory, FEventName, FEventValue: PWideChar); const DMTrackEventValue : TDMTrackEventValue = nil; begin try if CheckLoadDLL then begin @DMTrackEventValue := GetProcAddress(hModule, PROC_DeskMetricsTrackEventValue); if Assigned(DMTrackEventValue) then DMTrackEventValue(FEventCategory, fEventName, fEventValue); end; except end; end; procedure DeskMetricsTrackEventValueA(FEventCategory, FEventName, FEventValue: PAnsiChar); const DMTrackEventValuea : TDMTrackEventValueA = nil; begin try if CheckLoadDLL then begin @DMTrackEventValueA := GetProcAddress(hModule, PROC_DeskMetricsTrackEventValueA); if Assigned(DMTrackEventValueA) then DMTrackEventValueA(FEventCategory, fEventName, fEventValue); end; except end; end; procedure DeskMetricsTrackEventPeriod(FEventCategory, FEventName: PWideChar; FEventTime: Integer; FEventCanceled: Boolean); const DMTrackEventPeriod : TDMTrackEventPeriod = nil; begin try if CheckLoadDLL then begin @DMTrackEventPeriod := GetProcAddress(hModule, PROC_DeskMetricsTrackEventPeriod); if Assigned(DMTrackEventPeriod) then DMTrackEventPeriod(FEventCategory, FEventName, FEventTime, FEventCanceled); end; except end; end; procedure DeskMetricsTrackEventPeriodA(FEventCategory, FEventName: PAnsiChar; FEventTime: Integer; FEventCanceled: Boolean); const DMTrackEventPeriodA : TDMTrackEventPeriodA = nil; begin try if CheckLoadDLL then begin @DMTrackEventPeriodA := GetProcAddress(hModule, PROC_DeskMetricsTrackEventPeriodA); if Assigned(DMTrackEventPeriodA) then DMTrackEventPeriodA(FEventCategory, FEventName, FEventTime, FEventCanceled); end; except end; end; procedure DeskMetricsTrackLog(FMessage: PWideChar); const DMTrackLog : TDMTrackLog = nil; begin try if CheckLoadDLL then begin @DMTrackLog := GetProcAddress(hModule, PROC_DeskMetricsTrackLog); if Assigned(DMTrackLog) then DMTrackLog(FMessage); end; except end; end; procedure DeskMetricsTrackLogA(FMessage: PAnsiChar); const DMTrackLogA : TDMTrackLogA = nil; begin try if CheckLoadDLL then begin @DMTrackLogA := GetProcAddress(hModule, PROC_DeskMetricsTrackLogA); if Assigned(DMTrackLogA) then DMTrackLogA(FMessage); end; except end; end; procedure DeskMetricsTrackCustomData(FName, FValue: PWideChar); const DMTrackCustomData : TDMTrackCustomData = nil; begin try if CheckLoadDLL then begin @DMTrackCustomData := GetProcAddress(hModule, PROC_DeskMetricsTrackCustomData); if Assigned(DMTrackCustomData) then DMTrackCustomData(FName, FValue); end; except end; end; procedure DeskMetricsTrackCustomDataA(FName, FValue: PAnsiChar); const DMTrackCustomDataA : TDMTrackCustomDataA = nil; begin try if CheckLoadDLL then begin @DMTrackCustomDataA := GetProcAddress(hModule, PROC_DeskMetricsTrackCustomDataA); if Assigned(DMTrackCustomDataA) then DMTrackCustomDataA(FName, FValue); end; except end; end; function DeskMetricsTrackCustomDataR(FName: PWideChar; FValue: PWideChar): Integer; const DMTrackCustomDataR : TDMTrackCustomDataR = nil; begin Result := NO_INTEGER_VALUE; try if CheckLoadDLL then begin @DMTrackCustomDataR := GetProcAddress(hModule, PROC_DeskMetricsTrackCustomDataR); if Assigned(DMTrackCustomDataR) then Result := DMTrackCustomDataR(FName, FValue); end; except Result := NO_INTEGER_VALUE; end; end; function DeskMetricsTrackCustomDataRA(FName: PAnsiChar; FValue: PAnsiChar): Integer; const DMTrackCustomDataRA : TDMTrackCustomDataRA = nil; begin Result := NO_INTEGER_VALUE; try if CheckLoadDLL then begin @DMTrackCustomDataRA := GetProcAddress(hModule, PROC_DeskMetricsTrackCustomDataRA); if Assigned(DMTrackCustomDataRA) then Result := DMTrackCustomDataRA(FName, FValue); end; except Result := NO_INTEGER_VALUE; end; end; procedure DeskMetricsTrackException(FExpectionObject: Exception); const DMTrackException : TDMTrackException = nil; begin try if CheckLoadDLL then begin @DMTrackException := GetProcAddress(hModule, PROC_DeskMetricsTrackException); if Assigned(DMTrackException) then DMTrackException(FExpectionObject); end; except end; end; function DeskMetricsSetProxy(FHostIP: PWideChar; FPort: Integer; FUserName, FPassword: PWideChar): Boolean; const DMSetProxy : TDMSetProxy = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetProxy := GetProcAddress(hModule, PROC_DeskMetricsSetProxy); if Assigned(DMSetProxy) then Result := DMSetProxy(FHostIP, FPort, FUserName, fPassword); end; except Result := False; end; end; function DeskMetricsSetProxyA(FHostIP: PAnsiChar; FPort: Integer; FUserName, FPassword: PAnsiChar): Boolean; const DMSetProxyA : TDMSetProxyA = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetProxyA := GetProcAddress(hModule, PROC_DeskMetricsSetProxyA); if Assigned(DMSetProxyA) then Result := DMSetProxyA(FHostIP, FPort, FUserName, fPassword); end; except Result := False; end; end; function DeskMetricsGetProxy(var FHostIP: PWideChar; var FPort: Integer): Boolean; const DMGetProxy : TDMGetProxy = nil; begin Result := False; try if CheckLoadDLL then begin @DMGetProxy := GetProcAddress(hModule, PROC_DeskMetricsGetProxy); if Assigned(DMGetProxy) then Result := DMGetProxy(FHostIP, FPort); end; except Result := False; end; end; function DeskMetricsGetProxyA(var FHostIP: PAnsiChar; var FPort: Integer): Boolean; const DMGetProxyA : TDMGetProxyA = nil; begin Result := False; try if CheckLoadDLL then begin @DMGetProxyA := GetProcAddress(hModule, PROC_DeskMetricsGetProxyA); if Assigned(DMGetProxyA) then Result := DMGetProxyA(FHostIP, FPort); end; except Result := False; end; end; function DeskMetricsSetUserID(FID: PWideChar): Boolean; const DMSetUserID : TDMSetUserID = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetUserID := GetProcAddress(hModule, PROC_DeskMetricsSetUserID); if Assigned(DMSetUserID) then Result := DMSetUserID(FID); end; except Result := False; end; end; function DeskMetricsSetUserIDA(FID: PAnsiChar): Boolean; const DMSetUserIDA : TDMSetUserIDA = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetUserIDA := GetProcAddress(hModule, PROC_DeskMetricsSetUserIDA); if Assigned(DMSetUserIDA) then Result := DMSetUserIDA(FID); end; except Result := False; end; end; function DeskMetricsGetPostServer: PWideChar; const DMGetPostServer : TDMGetPostServer = nil; begin Result := EMPTY_STRING; try if CheckLoadDLL then begin @DMGetPostServer := GetProcAddress(hModule, PROC_DeskMetricsGetPostServer); if Assigned(DMGetPostServer) then Result := DMGetPostServer; end; except Result := EMPTY_STRING; end; end; function DeskMetricsGetPostServerA: PAnsiChar; const DMGetPostServerA : TDMGetPostServerA = nil; begin Result := EMPTY_STRING; try if CheckLoadDLL then begin @DMGetPostServerA := GetProcAddress(hModule, PROC_DeskMetricsGetPostServerA); if Assigned(DMGetPostServerA) then Result := DMGetPostServerA; end; except Result := EMPTY_STRING; end; end; function DeskMetricsSetPostServer(FServer: PWideChar): Boolean; const DMSetPostServer : TDMSetPostServer = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetPostServer := GetProcAddress(hModule, PROC_DeskMetricsSetPostServer); if Assigned(DMSetPostServer) then Result := DMSetPostServer(FServer); end; except Result := False; end; end; function DeskMetricsSetPostServerA(FServer: PAnsiChar): Boolean; const DMSetPostServerA : TDMSetPostServerA = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetPostServerA := GetProcAddress(hModule, PROC_DeskMetricsSetPostServerA); if Assigned(DMSetPostServerA) then Result := DMSetPostServerA(FServer); end; except Result := False; end; end; function DeskMetricsGetPostPort: Integer; const DMGetPostPort : TDMGetPostPort = nil; begin Result := NO_INTEGER_VALUE; try if CheckLoadDLL then begin @DMGetPostPort := GetProcAddress(hModule, PROC_DeskMetricsGetPostPort); if Assigned(DMGetPostPort) then Result := DMGetPostPort; end; except Result := NO_INTEGER_VALUE; end; end; function DeskMetricsSetPostPort(FPort: Integer): Boolean; const DMSetPostPort : TDMSetPostPort = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetPostPort := GetProcAddress(hModule, PROC_DeskMetricsSetPostPort); if Assigned(DMSetPostPort) then Result := DMSetPostPort(FPort); end; except Result := False; end; end; function DeskMetricsGetPostTimeOut: Integer; const DMGetPostTimeOut : TDMGetPostTimeOut = nil; begin Result := NO_INTEGER_VALUE; try if CheckLoadDLL then begin @DMGetPostTimeOut := GetProcAddress(hModule, PROC_DeskMetricsGetPostTimeOut); if Assigned(DMGetPostTimeOut) then Result := DMGetPostTimeOut; end; except Result := NO_INTEGER_VALUE; end; end; function DeskMetricsSetPostTimeOut(FTimeOut: Integer): Boolean; const DMSetPostTimeOut : TDMSetPostTimeOut = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetPostTimeOut := GetProcAddress(hModule, PROC_DeskMetricsSetPostTimeOut); if Assigned(DMSetPostTimeOut) then Result := DMSetPostTimeOut(FTimeOut); end; except Result := False; end; end; function DeskMetricsGetPostWaitResponse: Boolean; const DMGetPostWaitResponse : TDMGetPostWaitResponse = nil; begin Result := False; try if CheckLoadDLL then begin @DMGetPostWaitResponse := GetProcAddress(hModule, PROC_DeskMetricsGetPostWaitResponse); if Assigned(DMGetPostWaitResponse) then Result := DMGetPostWaitResponse; end; except Result := False; end; end; function DeskMetricsSetPostWaitResponse(FEnabled: Boolean): Boolean; const DMSetPostWaitResponse : TDMSetPostWaitResponse = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetPostWaitResponse := GetProcAddress(hModule, PROC_DeskMetricsSetPostWaitResponse); if Assigned(DMSetPostWaitResponse) then Result := DMSetPostWaitResponse(FEnabled); end; except Result := False; end; end; function DeskMetricsGetJSON: PWideChar; const DMGetJSON : TDMGetJSON = nil; begin Result := EMPTY_STRING; try if CheckLoadDLL then begin @DMGetJSON := GetProcAddress(hModule, PROC_DeskMetricsGetJSON); if Assigned(DMGetJSON) then Result := DMGetJSON; end; except Result := EMPTY_STRING; end; end; function DeskMetricsGetJSONA: PAnsiChar; const DMGetJSONA : TDMGetJSONA = nil; begin Result := EMPTY_STRING; try if CheckLoadDLL then begin @DMGetJSONA := GetProcAddress(hModule, PROC_DeskMetricsGetJSONA); if Assigned(DMGetJSONA) then Result := DMGetJSONA; end; except Result := EMPTY_STRING; end; end; function DeskMetricsSetEnabled(FValue: Boolean): Boolean; const DMSetEnabled : TDMSetEnabled = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetEnabled := GetProcAddress(hModule, PROC_DeskMetricsSetEnabled); if Assigned(DMSetEnabled) then Result := DMSetEnabled(FValue); end; except Result := False; end; end; function DeskMetricsGetEnabled: Boolean; const DMGetEnabled : TDMGetEnabled = nil; begin Result := False; try if CheckLoadDLL then begin @DMGetEnabled := GetProcAddress(hModule, PROC_DeskMetricsGetEnabled); if Assigned(DMGetEnabled) then Result := DMGetEnabled; end; except Result := False; end; end; function DeskMetricsSendData: Boolean; const DMSendData : TDMSendData = nil; begin Result := False; try if CheckLoadDLL then begin @DMSendData := GetProcAddress(hModule, PROC_DeskMetricsSendData); if Assigned(DMSendData) then Result := DMSendData; end; except Result := False; end; end; function DeskMetricsGetDebugMode: Boolean; const DMGetDebugMode : TDMGetDebugMode = nil; begin Result := False; try if CheckLoadDLL then begin @DMGetDebugMode := GetProcAddress(hModule, PROC_DeskMetricsGetDebugMode); if Assigned(DMGetDebugMode) then Result := DMGetDebugMode; end; except Result := False; end; end; function DeskMetricsSetDebugMode(FEnabled: Boolean): Boolean; const DMSetDebugMode : TDMSetDebugMode = nil; begin Result := False; try if CheckLoadDLL then begin @DMSetDebugMode := GetProcAddress(hModule, PROC_DeskMetricsSetDebugMode); if Assigned(DMSetDebugMode) then Result := DMSetDebugMode(FEnabled); end; except Result := False; end; end; function DeskMetricsGetDebugFile: Boolean; const DMGetDebugFile : TDMGetDebugFile = nil; begin Result := False; try if CheckLoadDLL then begin @DMGetDebugFile := GetProcAddress(hModule, PROC_DeskMetricsGetDebugFile); if Assigned(DMGetDebugFile) then Result := DMGetDebugFile; end; except Result := False; end; end; initialization hModule := 0; finalization if not(hModule < HINSTANCE_ERROR) then FreeLibrary(hModule); end.
unit ncTotCaixa; interface uses ncClassesBase, SysUtils, nxdb; function TotalizaCaixa(DB: TnxDatabase; Num, CaixaI, CaixaF: Integer; var AcessoFat, AcessoDebitado, AcessoDebPago, AcessoPago, VendaFat, VendaDebitado, VendaDebPago, VendaPago, Suprimento, Sangria, Descontos, TempoAcesso, TempoManut : Extended; var QuantAcesso, QuantVenda : Integer): Boolean; implementation function TotalizaCaixa(DB: TnxDatabase; Num, CaixaI, CaixaF: Integer; var AcessoFat, AcessoDebitado, AcessoDebPago, AcessoPago, VendaFat, VendaDebitado, VendaDebPago, VendaPago, Suprimento, Sangria, Descontos, TempoAcesso, TempoManut : Extended; var QuantAcesso, QuantVenda : Integer): Boolean; var Q : TnxQuery; begin Q := TnxQuery.Create(nil); try Q.Database := DB; Q.Active := False; Q.SQL.Clear; Q.SQL.Add('SELECT ' + ' Cancelado, TipoTran, TipoItem, ' + ' Count(*) as Quant, ' + ' Sum(Total) as Total, ' + ' Sum(Desconto) as Desconto, ' + ' Sum(Pago) as Pago, ' + ' Sum(Debito) as Debito, ' + ' Sum(Cast(Tempo as FLOAT)) as Tempo ' + 'FROM ' + ' ITran '); if Num>0 then Q.SQL.Add('WHERE ' + ' ((CaixaP='+IntToStr(Num)+') AND (StatusPagto=2)) OR'+ ' ((CaixaF='+IntToStr(Num)+') AND (StatusPagto=3)) ') else Q.SQL.Add('WHERE ' + ' (CaixaF>='+IntToStr(CaixaI)+') AND (CaixaF<='+IntTOStr(CaixaF)+')'); Q.SQL.Add('GROUP BY ' + ' Tipo, StatusPagto'); Q.Open; Acesso := 0; AcessoNaoPago := 0; AcessoDebPago := 0; Venda := 0; VendaNaoPago := 0; VendaDebPago := 0; Suprimento := 0; Sangria := 0; Descontos := 0; TempoAcesso := 0; TempoManut := 0; QuantAcesso := 0; QuantVenda := 0; Q.First; while not Q.Eof do begin case Q.FieldByName('Tipo').AsInteger of ttAcesso, ttAcessoVenda, ttEstVenda : begin Acesso := Acesso + Q.FieldByName('Acesso').AsFloat; Venda := Venda + Q.FieldByName('Produtos').AsFloat - Q.FieldByName('DescProd').AsFloat; if Q.FieldByName('StatusPagto').AsInteger=spDebitado then begin AcessoNaoPago := AcessoNaoPago + Q.FieldByName('Acesso').AsFloat; VendaNaoPago := VendaNaoPago + Q.FieldByName('Produtos').AsFloat - Q.FieldByName('DescProd').AsFloat; end; Descontos := Descontos + Q.FieldByName('DescAcesso').AsFloat + Q.FieldByName('DescProd').AsFloat; if Q.FieldByName('Tipo').AsInteger <> ttEstVenda then begin TempoAcesso := TempoAcesso + Q.FieldByName('Tempo').AsFloat; QuantAcesso := QuantAcesso + Q.FieldByName('Quant').AsInteger; end; if Q.FieldByName('Tipo').AsInteger <> ttAcesso then QuantVenda := QuantVenda + Q.FieldByName('Quant').AsInteger; end; ttSinal, ttVendaPacote, ttVendaPassaporte, ttCreditoTempo : begin Acesso := Acesso + Q.FieldByName('Valor').AsFloat - Q.FieldByName('DescAcesso').AsFloat; if Q.FieldByName('StatusPagto').AsInteger=spDebitado then AcessoNaoPago := AcessoNaoPago + Q.FieldByName('Valor').AsFloat - Q.FieldByName('DescAcesso').AsFloat; Descontos := Descontos + Q.FieldByName('DescAcesso').AsFloat; end; ttManutencao : TempoManut := TempoManut + Q.FieldByName('Tempo').AsFloat; ttPagtoDebito : begin VendaDebPago := VendaDebPago + Q.FieldByName('Produtos').AsFloat - Q.FieldByName('DescProd').AsFloat; AcessoDebPago := AcessoDebPago + Q.FieldByName('Acesso').AsFloat; Descontos := Descontos + Q.FieldByName('DescAcesso').AsFloat + Q.FieldByName('DescProd').AsFloat; end; ttSuprimentoCaixa : Suprimento := Suprimento + Q.FieldByName('Valor').AsFloat; ttSangriaCaixa : Sangria := Sangria + Q.FieldByName('Valor').AsFloat; end; Q.Next; end; Q.Close; TempoAcesso := TempoAcesso * 24; TempoManut := TempoManut * 24; finally Q.Free; end; } end; end.
unit IdTelnetServer; interface uses Classes, IdException, IdGlobal, IdTCPServer; const GLoginAttempts = 3; type TTelnetData = class(TObject) public Username, Password: string; HUserToken: cardinal; end; TIdTelnetNegotiateEvent = procedure(AThread: TIdPeerThread) of object; TAuthenticationEvent = procedure(AThread: TIdPeerThread; const AUsername, APassword: string; var AAuthenticated: Boolean) of object; TIdTelnetServer = class(TIdTCPServer) protected FLoginAttempts: Integer; FOnAuthentication: TAuthenticationEvent; FLoginMessage: string; FOnNegotiate: TIdTelnetNegotiateEvent; public constructor Create(AOwner: TComponent); override; function DoAuthenticate(AThread: TIdPeerThread; const AUsername, APassword: string) : boolean; virtual; procedure DoNegotiate(AThread: TIdPeerThread); virtual; procedure DoConnect(AThread: TIdPeerThread); override; published property DefaultPort default IdPORT_TELNET; property LoginAttempts: Integer read FLoginAttempts write FLoginAttempts default GLoginAttempts; property LoginMessage: string read FLoginMessage write FLoginMessage; property OnAuthentication: TAuthenticationEvent read FOnAuthentication write FOnAuthentication; property OnNegotiate: TIdTelnetNegotiateEvent read FOnNegotiate write FOnNegotiate; end; EIdTelnetServerException = class(EIdException); EIdNoOnAuthentication = class(EIdTelnetServerException); EIdLoginException = class(EIdTelnetServerException); EIdMaxLoginAttempt = class(EIdLoginException); implementation uses SysUtils, IdResourceStrings; constructor TIdTelnetServer.Create(AOwner: TComponent); begin inherited; LoginAttempts := GLoginAttempts; LoginMessage := RSTELNETSRVWelcomeString; DefaultPort := IdPORT_TELNET; end; function TIdTelnetServer.DoAuthenticate; begin if not assigned(OnAuthentication) then begin raise EIdNoOnAuthentication.Create(RSTELNETSRVNoAuthHandler); end; result := False; OnAuthentication(AThread, AUsername, APassword, result); end; procedure TIdTelnetServer.DoConnect(AThread: TIdPeerThread); var Data: TTelnetData; i: integer; begin try inherited; if AThread.Data = nil then begin AThread.Data := TTelnetData.Create; end; Data := AThread.Data as TTelnetData; DoNegotiate(AThread); if length(LoginMessage) > 0 then begin AThread.Connection.WriteLn(LoginMessage); AThread.Connection.WriteLn(''); end; if assigned(OnAuthentication) then begin for i := 1 to LoginAttempts do begin AThread.Connection.Write(RSTELNETSRVUsernamePrompt); Data.Username := AThread.Connection.InputLn; AThread.Connection.Write(RSTELNETSRVPasswordPrompt); Data.Password := AThread.Connection.InputLn('*'); AThread.Connection.WriteLn; if DoAuthenticate(AThread, Data.Username, Data.Password) then begin Break; end else begin AThread.Connection.WriteLn(RSTELNETSRVInvalidLogin); // translate if i = FLoginAttempts then begin raise EIdMaxLoginAttempt.Create(RSTELNETSRVMaxloginAttempt); // translate end; end; end; end; except on E: Exception do begin AThread.Connection.WriteLn(E.Message); AThread.Connection.Disconnect; end; end; end; procedure TIdTelnetServer.DoNegotiate(AThread: TIdPeerThread); begin if assigned(FOnNegotiate) then begin FOnNegotiate(AThread); end; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; BitBtn1: TBitBtn; OpenDialog1: TOpenDialog; Label1: TLabel; procedure BitBtn1Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} function SD_GetVerifiedPublisher(FileName: WideString; var Publisher: WideString): LONG; stdcall; external 'VerifyTrust.dll'; function GetCompanyName(FileName: WideString): WideString; var Handle, Len, Size: Cardinal; Translation: WideString; Data: PWideChar; Buffer: Pointer; begin try Size := GetFileVersionInfoSizeW(PWideChar(FileName), Handle); if Size > 0 then begin GetMem(Data, Size); try if GetFileVersionInfoW(PWideChar(FileName), Handle, Size, Data) then begin if VerQueryValueW(Data, '\VarFileInfo\Translation', Buffer, Len) then begin Translation := IntToHex(PDWORD(Buffer)^, 8); Translation := Copy(Translation, 5, 4) + Copy(Translation, 1, 4); end; if VerQueryValueW(Data, PWideChar('\StringFileInfo\' + Translation + '\CompanyName'), Buffer, Len) then Result := PWideChar(Buffer); end; finally FreeMem(Data); end; end; except end; end; procedure TForm1.BitBtn1Click(Sender: TObject); begin if OpenDialog1.Execute then begin Edit1.Text := OpenDialog1.FileName; Button1.Click; end; end; procedure TForm1.Button1Click(Sender: TObject); var Publisher: WideString; VerifiedStatus: LONG; begin VerifiedStatus := SD_GetVerifiedPublisher(Edit1.Text, Publisher); MessageBeep(0); // Только в случае возврата 0 подпись считается действительной if VerifiedStatus = 0 then begin // Файл подписан, подпись действительна MessageBoxW(0, PWideChar('Издатель: ' + Publisher + #13#10 + #13#10 + 'Цифровая подпись действительна'), 'Результат проверки', 0); end else begin if Publisher = '' then begin // Файл не подписан, пробуем получить имя компании из FileVersionInfo Publisher := GetCompanyName(Edit1.Text); if Publisher <> '' then MessageBoxW(0, PWideChar('Издатель: ' + Publisher + #13#10 + #13#10 + 'Цифровая подпись отсутствует'), 'Результат проверки', 0) else MessageBoxW(0, PWideChar('Издатель: ' + 'Неизвестен' + #13#10 + #13#10 + 'Цифровая подпись отсутствует'), 'Результат проверки', 0) end else begin // Файл подписан, но подпись не действительна MessageBoxW(0, PWideChar('Издатель: ' + Publisher + #13#10 + #13#10 + 'Цифровая подпись не действительна'), 'Результат проверки', 0); end; end; end; procedure TForm1.FormCreate(Sender: TObject); begin Edit1.Text := Application.ExeName; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Datasnap.DSHTTPWebBroker; interface uses Web.AutoDisp, System.Classes, Datasnap.DSHTTPCommon, Web.HTTPApp, System.Masks, System.SysUtils; type { Webbroker component that dispatches DataSnap requests } TDSHTTPWebDispatcher = class(TDSHTTPServerTransport, IWebDispatch) private FWebDispatch: TWebDispatch; procedure SetWebDispatch(const Value: TWebDispatch); protected function CreateHttpServer: TDSHTTPServer; override; function DispatchEnabled: Boolean; function DispatchMask: TMask; function DispatchMethodType: TMethodType; function DispatchRequest(Sender: TObject; Request: TWebRequest; Response: TWebResponse): Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Start; override; procedure Stop; override; published /// <summary>Dispatch criteria. Indicate the types of requests that will be processed by this dispatcher. /// </summary> property WebDispatch: TWebDispatch read FWebDispatch write SetWebDispatch; end; TDSHTTPContextWebBroker = class(TDSHTTPContext) public function Connected: Boolean; override; end; TDSHTTPRequestWebBroker = class(TDSHTTPRequest) strict private FRequestInfo: TWebRequest; FPostStream: TMemoryStream; FParams: TStrings; FAuthUserName: AnsiString; FAuthPassword: AnsiString; FHaveAuth: Boolean; procedure UpdateAuthStrings; protected function GetCommand: string; override; function GetCommandType: TDSHTTPCommandType; override; function GetDocument: string; override; function GetParams: TStrings; override; function GetPostStream: TStream; override; function GetAuthUserName: string; override; function GetAuthPassword: string; override; function GetURI: string; override; function GetPragma: string; override; function GetAccept: string; override; function GetRemoteIP: string; override; function GetUserAgent: string; override; function GetProtocolVersion: string; override; public constructor Create(ARequestInfo: TWebRequest); destructor Destroy; override; /// <summary>WebBroker Request. Provided so that event handlers can get to WebBroker specific properties. /// </summary> property WebRequest: TWebRequest read FRequestInfo; end; TDSHTTPResponseWebBroker = class(TDSHTTPResponse) strict private FResponseInfo: TWebResponse; FCloseConnection: Boolean; strict protected function GetContentStream: TStream; override; function GetResponseNo: Integer; override; function GetResponseText: String; override; procedure SetContentStream(const Value: TStream); override; procedure SetResponseNo(const Value: Integer); override; procedure SetResponseText(const Value: String); override; function GetContentText: string; override; procedure SetContentText(const Value: string); override; function GetContentLength: Int64; override; procedure SetContentLength(const Value: Int64); override; function GetCloseConnection: Boolean; override; procedure SetCloseConnection(const Value: Boolean); override; function GetPragma: string; override; procedure SetPragma(const Value: string); override; function GetContentType: string; override; procedure SetContentType(const Value: string); override; function GetFreeContentStream: Boolean; override; procedure SetFreeContentStream(const Value: Boolean); override; public constructor Create(AResponseInfo: TWebResponse); procedure SetHeaderAuthentication(const Value: String; const Realm: String); override; /// <summary>WebBroker Response. Provided so that event handlers can get to WebBroker specific properties. /// </summary> property WebResponse: TWebResponse read FResponseInfo; end; /// <summary>Get the Web Module currently processing a DataSnap HTTP request. /// </summary> function GetDataSnapWebModule: TWebModule; implementation uses Data.DBXClientResStrs; type TDSHTTPServerWebBroker = class(TDSHTTPServer) protected function Decode(Data: string): string; override; public procedure DispatchDataSnap(ARequest: TWebRequest; AResponse: TWebResponse); end; threadvar DataSnapWebModule: TWebModule; function GetDataSnapWebModule: TWebModule; begin Result := DataSnapWebModule; end; { TDSHTTPWebDispatcher } constructor TDSHTTPWebDispatcher.Create(AOwner: TComponent); begin inherited Create(AOwner); FWebDispatch := TWebDispatch.Create(Self); FWebDispatch.PathInfo := 'datasnap*'; { do not localize } end; function TDSHTTPWebDispatcher.CreateHttpServer: TDSHTTPServer; begin Result := TDSHTTPServerWebBroker.Create; end; destructor TDSHTTPWebDispatcher.Destroy; begin FWebDispatch.Free; inherited Destroy; end; procedure TDSHTTPWebDispatcher.Start; begin // Do nothing end; procedure TDSHTTPWebDispatcher.Stop; begin // Do nothing end; procedure TDSHTTPWebDispatcher.SetWebDispatch(const Value: TWebDispatch); begin FWebDispatch.Assign(Value); end; function TDSHTTPWebDispatcher.DispatchEnabled: Boolean; begin Result := True; end; function TDSHTTPWebDispatcher.DispatchMask: TMask; begin Result := FWebDispatch.Mask; end; function TDSHTTPWebDispatcher.DispatchMethodType: TMethodType; begin Result := FWebDispatch.MethodType; end; function TDSHTTPWebDispatcher.DispatchRequest(Sender: TObject; Request: TWebRequest; Response: TWebResponse): Boolean; begin try if Owner is TWebModule then DataSnapWebModule := TWebModule(Owner); try try RequiresServer; TDSHTTPServerWebBroker(Self.FHttpServer).DispatchDataSnap(Request, Response); Result := True; except on E: Exception do begin { Default to 500, like web services. } Response.StatusCode := 500; Result := True; end; end; except { Swallow any unexpected exception, it will bring down some web servers } Result := False; end; finally { Reset current DataSnapWebModule } DataSnapWebModule := nil; end; end; { TDSHTTPServerWebBroker } function TDSHTTPServerWebBroker.Decode(Data: string): string; begin Result := Data; end; procedure TDSHTTPServerWebBroker.DispatchDataSnap(ARequest: TWebRequest; AResponse: TWebResponse); var LRequestInfo: TDSHTTPRequest; LResponseInfo: TDSHTTPResponse; LContext: TDSHTTPContext; begin LRequestInfo := TDSHTTPRequestWebBroker.Create(ARequest); LResponseInfo := TDSHTTPResponseWebBroker.Create(AResponse); LContext := TDSHTTPContextWebBroker.Create(); try DoCommand(LContext, LRequestInfo, LResponseInfo); finally LRequestInfo.Free; LResponseInfo.Free; LContext.Free; end; end; { TDSHTTPResponseWebBroker } constructor TDSHTTPResponseWebBroker.Create(AResponseInfo: TWebResponse); begin FResponseInfo := AResponseInfo; end; function TDSHTTPResponseWebBroker.GetCloseConnection: Boolean; begin Result := FCloseConnection; end; function TDSHTTPResponseWebBroker.GetContentLength: Int64; begin Result := FResponseInfo.ContentLength; end; function TDSHTTPResponseWebBroker.GetContentStream: TStream; begin Result := FResponseInfo.ContentStream; end; function TDSHTTPResponseWebBroker.GetContentText: string; begin Result := FResponseInfo.Content; end; function TDSHTTPResponseWebBroker.GetContentType: string; begin Result := FResponseInfo.GetCustomHeader('Content-Type'); end; function TDSHTTPResponseWebBroker.GetFreeContentStream: Boolean; begin Result := FResponseInfo.FreeContentStream; end; function TDSHTTPResponseWebBroker.GetPragma: string; begin Result := FResponseInfo.GetCustomHeader('Pragma'); end; function TDSHTTPResponseWebBroker.GetResponseNo: Integer; begin Result := FResponseInfo.StatusCode; end; function TDSHTTPResponseWebBroker.GetResponseText: String; begin // Expect reason string to be 8 bit characters only Result := string(FResponseInfo.ReasonString); end; procedure TDSHTTPResponseWebBroker.SetCloseConnection(const Value: Boolean); begin FCloseConnection := Value; end; procedure TDSHTTPResponseWebBroker.SetContentLength(const Value: Int64); begin FResponseInfo.ContentLength := Value; end; procedure TDSHTTPResponseWebBroker.SetContentStream(const Value: TStream); begin FResponseInfo.ContentStream := Value; end; procedure TDSHTTPResponseWebBroker.SetContentText(const Value: string); begin FResponseInfo.Content := Value; end; procedure TDSHTTPResponseWebBroker.SetContentType(const Value: string); begin FResponseInfo.SetCustomHeader('Content-Type', Value); end; procedure TDSHTTPResponseWebBroker.SetFreeContentStream(const Value: Boolean); begin FResponseInfo.FreeContentStream := Value; end; procedure TDSHTTPResponseWebBroker.SetPragma(const Value: string); begin FResponseInfo.SetCustomHeader('Pragma', Value); end; procedure TDSHTTPResponseWebBroker.SetHeaderAuthentication(const Value, Realm: String); begin FResponseInfo.WWWAuthenticate := AnsiString(Value); FResponseInfo.Realm := AnsiString(Realm); end; procedure TDSHTTPResponseWebBroker.SetResponseNo(const Value: Integer); begin FResponseInfo.StatusCode := Value; end; procedure TDSHTTPResponseWebBroker.SetResponseText(const Value: String); begin // Expect reason phrase to 8 bit characters only. FResponseInfo.ReasonString := AnsiString(Value); end; constructor TDSHTTPRequestWebBroker.Create(ARequestInfo: TWebRequest); begin FRequestInfo := ARequestInfo; end; destructor TDSHTTPRequestWebBroker.Destroy; begin FPostStream.Free; FParams.Free; inherited; end; procedure Base64DecodeToStream(const S: AnsiString; AStream: TStream); const cPaddingChar: AnsiChar = '='; LDecodeMap: array[AnsiChar] of Byte = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); var LLength: Integer; LPaddingCount: Integer; P, PLast: PAnsiChar; LBuffer: array[0..2] of Byte; begin LLength := Length(S); LPaddingCount := 0; if LLength = 1 then begin if S[1] = cPaddingChar then LPaddingCount := 1 end else if LLength > 1 then begin if S[LLength] = cPaddingChar then if S[LLength-1] = cPaddingChar then LPaddingCount := 2 else LPaddingCount := 1; end; P := PAnsiChar(S); PLast := P + LLength - 1 - LPaddingCount; while P <= PLast do begin case PLast - P + 1 of 2: begin LBuffer[0] := (LDecodeMap[P[0]] shl 2) or ((LDecodeMap[P[1]] shr 4) and 3); AStream.WriteBuffer(LBuffer[0], 1); break; end; 3: begin LBuffer[0] := (LDecodeMap[P[0]] shl 2) or ((LDecodeMap[P[1]] shr 4) and 3); LBuffer[1] := ((LDecodeMap[P[1]] and 15) shl 4) or ((LDecodeMap[P[2]] shr 2) and 15); AStream.WriteBuffer(LBuffer[0], 2); break; end; else begin LBuffer[0] := (LDecodeMap[P[0]] shl 2) or ((LDecodeMap[P[1]] shr 4) and 3); LBuffer[1] := ((LDecodeMap[P[1]] and 15) shl 4) or ((LDecodeMap[P[2]] shr 2) and 15); LBuffer[2] := ((LDecodeMap[P[2]] and 3) shl 6) or (LDecodeMap[P[3]] and 63); AStream.WriteBuffer(LBuffer[0], 3); P := P + 4; end end end; end; function Base64DecodeToString(const S: AnsiString): AnsiString; var LStream: TStream; begin LStream := TMemoryStream.Create; try Base64DecodeToStream(S, LStream); LStream.Seek(0, TSeekOrigin.soBeginning); SetLength(Result, LStream.Size); LStream.Read(Result[1], LStream.Size); finally LStream.Free; end; end; procedure TDSHTTPRequestWebBroker.UpdateAuthStrings; function Trim(const S: AnsiString): AnsiString; var I, L: Integer; begin L := Length(S); I := 1; while (I <= L) and (S[I] <= ' ') do Inc(I); if I > L then Result := '' else begin while S[L] <= ' ' do Dec(L); Result := Copy(S, I, L - I + 1); end; end; var LAuthorization: AnsiString; LDecodedAuthorization: AnsiString; LPos: NativeInt; P: PAnsiChar; begin if not FHaveAuth then begin FHaveAuth := True; LAuthorization := (FRequestInfo.Authorization); if AnsiStrComp(PAnsiChar(Copy(LAuthorization, 1, 5)), 'Basic') = 0 then begin LDecodedAuthorization := Base64DecodeToString(Trim(Copy(LAuthorization, 6, MaxInt))); P := AnsiStrScan(PAnsiChar(LDecodedAuthorization), ':'); if P <> nil then begin LPos := P - PAnsiChar(LDecodedAuthorization); FAuthUserName := Copy(LDecodedAuthorization, 1, LPos); FAuthPassword := Copy(LDecodedAuthorization, LPos+2, MaxInt); end; end; end; end; function TDSHTTPRequestWebBroker.GetAuthPassword: string; begin UpdateAuthStrings; Result := string(FAuthPassword); end; function TDSHTTPRequestWebBroker.GetAuthUserName: string; begin UpdateAuthStrings; Result := string(FAuthUserName); end; function TDSHTTPRequestWebBroker.GetCommand: string; begin Result := string(FRequestInfo.Method); end; function TDSHTTPRequestWebBroker.GetCommandType: TDSHTTPCommandType; begin if AnsiStrComp(PAnsiChar(FRequestInfo.Method), 'DELETE') = 0 then { do not localize } // WebBroker doesn't have code for delete Result := TDSHTTPCommandType.hcDELETE else case FRequestInfo.MethodType of TMethodType.mtAny: Result := TDSHTTPCommandType.hcUnknown; TMethodType.mtHead: Result := TDSHTTPCommandType.hcOther; TMethodType.mtGet: Result := TDSHTTPCommandType.hcGET; TMethodType.mtPost: Result := TDSHTTPCommandType.hcPOST; TMethodType.mtPut: Result := TDSHTTPCommandType.hcPUT; else raise Exception.Create(sUnknownCommandType); end; end; function TDSHTTPRequestWebBroker.GetDocument: string; begin Result := string(FRequestInfo.InternalPathInfo); end; function TDSHTTPRequestWebBroker.GetParams: TStrings; begin if FParams = nil then begin FParams := TStringList.Create; FParams.AddStrings(FRequestInfo.QueryFields); if FRequestInfo.MethodType = mtPost then FParams.AddStrings(FRequestInfo.ContentFields); end; Result := FParams; end; function TDSHTTPRequestWebBroker.GetPostStream: TStream; begin if FPostStream = nil then begin FPostStream := TMemoryStream.Create; if Length(FRequestInfo.RawContent) > 0 then begin FPostStream.Write(FRequestInfo.RawContent[1], Length(FRequestInfo.RawContent)); FPostStream.Seek(0, TSeekOrigin.soBeginning); end; end; Result := FPostStream; end; function TDSHTTPRequestWebBroker.GetPragma: string; begin Result := String(FRequestInfo.GetFieldByName('Pragma')); end; function TDSHTTPRequestWebBroker.GetRemoteIP: string; begin Result := String(FRequestInfo.RemoteIP); end; function TDSHTTPRequestWebBroker.GetAccept: string; begin Result := String(FRequestInfo.GetFieldByName('Accept')); end; function TDSHTTPRequestWebBroker.GetURI: string; begin Result := String(FRequestInfo.RawPathInfo); end; function TDSHTTPRequestWebBroker.GetUserAgent: string; begin Result := String(FRequestInfo.UserAgent); end; function TDSHTTPRequestWebBroker.GetProtocolVersion: string; begin Result := String(FRequestInfo.ProtocolVersion); end; { TDSHTTPContextWebBroker } function TDSHTTPContextWebBroker.Connected: Boolean; begin Result := True; end; end.
(** This module contains code for installing a splash screen in the RAD Studio IDE. @Author David Hoyle @Version 1.0 @Date 03 Jan 2018 **) Unit ITHelper.SplashScreen; Interface {$INCLUDE CompilerDefinitions.Inc} Procedure InstallSplashScreen; Implementation Uses ToolsAPI, SysUtils, Windows, Forms, ITHelper.CommonFunctions, ITHelper.Constants, ITHelper.ResourceStrings; (** This procedure installs the splash screen entry into the RAD Studio IDE. @precon None. @postcon The splash screen entry is installed. **) Procedure InstallSplashScreen; Const {$IFDEF D2007} strITHelperSplashScreen = 'ITHelperSplashScreen24x24'; {$ELSE} strITHelperSplashScreen = 'ITHelperSplashScreen48x48'; {$ENDIF} Var bmSplashScreen : HBITMAP; iMajor, iMinor, iBugFix, iBuild : Integer; SS : IOTASplashScreenServices; strModuleName: String; iSize: Cardinal; Begin bmSplashScreen := LoadBitmap(hInstance, strITHelperSplashScreen); SetLength(strModuleName, MAX_PATH); iSize := GetModuleFileName(hInstance, PChar(strModuleName), MAX_PATH); SetLength(strModuleName, iSize); BuildNumber(strModuleName, iMajor, iMinor, iBugFix, iBuild); If Supports(SplashScreenServices, IOTASplashScreenServices, SS) Then Begin SS.AddPluginBitmap( Format(strSplashScreenName, [iMajor, iMinor, Copy(strRevisions, iBugFix + 1, 1), Application.Title]), bmSplashScreen, {$IFDEF DEBUG} True {$ELSE} False {$ENDIF}, Format(strSplashScreenBuild, [iMajor, iMinor, iBugfix, iBuild])); End; End; End.
{*********************************************} { TeeBI Software Library } { WorkflowItem Editor Dialog } { Copyright (c) 2015-2016 by Steema Software } { All Rights Reserved } {*********************************************} unit VCLBI.Editor.WorkflowItem; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, BI.Workflow, BI.DataItem, Vcl.ExtCtrls, VCLBI.Editor.Needs; type TWorkflowItemEditor = class(TForm) PageControl1: TPageControl; TabRename: TTabSheet; ItemNames: TComboBox; ENewName: TEdit; TabDelete: TTabSheet; DeleteItemNames: TComboBox; TabAdd: TTabSheet; EAdd: TEdit; CBKind: TComboBox; TabQuery: TTabSheet; MemoSQL: TMemo; TabFilter: TTabSheet; BEditFilter: TButton; TabSingleRow: TTabSheet; Label1: TLabel; ERow: TEdit; UDRow: TUpDown; TBRow: TTrackBar; Panel1: TPanel; BEditQuery: TButton; LError: TLabel; TabNeeds: TTabSheet; procedure CBKindChange(Sender: TObject); procedure ENewNameChange(Sender: TObject); procedure EAddChange(Sender: TObject); procedure MemoSQLChange(Sender: TObject); procedure ItemNamesChange(Sender: TObject); procedure BEditQueryClick(Sender: TObject); procedure BEditFilterClick(Sender: TObject); procedure ERowChange(Sender: TObject); procedure TBRowChange(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } IChanging : Boolean; INeeds : TProviderNeedsEditor; FItem : TWorkflowItem; function AnyTabVisible:Boolean; class function ProviderOf(const AItem:TWorkflowItem):TDataProvider; static; procedure SetAddProperties(const AData:TDataItem); procedure SetDeleteProperties(const AData:TDataItem); function SetErrorLabel(const Sender:TObject; const Error:String):Boolean; procedure SetQueryProperties(const AData:TDataItem); procedure SetRenameProperties(const AData:TDataItem); procedure SetSingleRowProperties(const AData:TDataItem); procedure ShowHideTabs(const AItem:TWorkflowItem); public { Public declarations } class function Embedd(const AOwner:TComponent; const AParent:TWinControl):TWorkflowItemEditor; static; function HasContent:Boolean; procedure Refresh(const AItem:TWorkflowItem); end; implementation
{**********************************************} { TImagePointSeries and TDeltaPointSeries } { Copyright (c) 1997-2004 by David Berneda } {**********************************************} unit ImaPoint; {$I TeeDefs.inc} interface Uses {$IFNDEF LINUX} Windows, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, Types, {$ELSE} Graphics, {$ENDIF} TeEngine, Chart, Series, TeCanvas; { This unit contains two Series components: TImagePointSeries -- A point Series displaying images TDeltaPointSeries -- An ImagePoint Series displaying a different image depending the previous point value. } Type TCustomImagePointSeries=class; TGetImageEvent=Procedure( Sender:TCustomImagePointSeries; ValueIndex:Integer; Picture:TPicture) of object; TCustomImagePointSeries=class(TPointSeries) private FImagePoint : TPicture; FImageTransp : Boolean; FOnGetImage : TGetImageEvent; procedure SetImagePoint(Const Value:TPicture); procedure SetImageTransp(Const Value:Boolean); protected procedure DrawValue(ValueIndex:Integer); override; Procedure PrepareForGallery(IsEnabled:Boolean); override; public Constructor Create(AOwner:TComponent); override; Destructor Destroy; override; property ImagePoint:TPicture read FImagePoint write SetImagePoint; property ImageTransparent:Boolean read FImageTransp write SetImageTransp default False; property OnGetImage:TGetImageEvent read FOnGetImage write FOnGetImage; end; TImagePointSeries=class(TCustomImagePointSeries) public Constructor Create(AOwner:TComponent); override; published property ImagePoint; property ImageTransparent default True; property OnGetImage; end; TDeltaImageStyle=(disSmiles, disHands); TDeltaPointSeries=class(TCustomImagePointSeries) private FEqualImage : TPicture; FGreaterImage : TPicture; FImageStyle : TDeltaImageStyle; FLowerImage : TPicture; procedure SetEqualImage(Const Value:TPicture); procedure SetGreaterImage(Const Value:TPicture); procedure SetImageStyle(Const Value:TDeltaImageStyle); procedure SetLowerImage(Const Value:TPicture); protected procedure DrawValue(ValueIndex:Integer); override; public Constructor Create(AOwner:TComponent); override; Destructor Destroy; override; published property EqualImage:TPicture read FEqualImage write SetEqualImage; property GreaterImage:TPicture read FGreaterImage write SetGreaterImage; property ImageStyle:TDeltaImageStyle read FImageStyle write SetImageStyle default disSmiles; property ImageTransparent; property LowerImage:TPicture read FLowerImage write SetLowerImage; { inherited from TCustomImagePointSeries } property OnGetImage; end; implementation Uses ImageBar, TeeProCo; {$IFDEF CLR} {$R 'TeeEqualSmile.bmp'} {$R 'TeeLowerSmile.bmp'} {$R 'TeeGreaterSmile.bmp'} {$R 'TeeDefaultImage.bmp'} {$R 'TeeEqualHand.bmp'} {$R 'TeeGreaterHand.bmp'} {$R 'TeeLowerHand.bmp'} {$ELSE} {$R TeeImaPo.res} {$ENDIF} { TCustomImagePointSeries } Constructor TCustomImagePointSeries.Create(AOwner:TComponent); begin inherited; FImagePoint:=TPicture.Create; FImagePoint.OnChange:=CanvasChanged; end; Destructor TCustomImagePointSeries.Destroy; begin FImagePoint.Free; inherited; end; { overrided DrawValue to draw an Image for each point } procedure TCustomImagePointSeries.DrawValue(ValueIndex:Integer); var R : TRect; begin if FImagePoint.Graphic=nil then inherited else With ParentChart,Canvas do begin { trigger the OnGetImage event if assigned... } if Assigned(FOnGetImage) then OnGetImage(Self,ValueIndex,FImagePoint); { draw the image... } With R do begin Left:=CalcXPos(ValueIndex)-(Pointer.HorizSize div 2); Right:=Left+Pointer.HorizSize; Top:=CalcYPos(ValueIndex)-(Pointer.VertSize div 2); Bottom:=Top+Pointer.VertSize; end; FImagePoint.Graphic.Transparent:=FImageTransp; With ParentChart.Canvas do begin R:=CalcRect3D(R,StartZ); if ((R.Right-R.Left)=FImagePoint.Graphic.Width) and ((R.Bottom-R.Top)=FImagePoint.Graphic.Height) then Draw(R.Left,R.Top,FImagePoint.Graphic) else StretchDraw(R,FImagePoint.Graphic); end; end; end; procedure TCustomImagePointSeries.SetImagePoint(Const Value:TPicture); begin FImagePoint.Assign(Value); { <-- set new property values } if Assigned(Value) then begin if Value.Width>0 then Pointer.HorizSize:=Value.Width; if Value.Height>0 then Pointer.VertSize:=Value.Height; end; end; procedure TCustomImagePointSeries.SetImageTransp(Const Value:Boolean); begin SetBooleanProperty(FImageTransp,Value); end; Procedure TCustomImagePointSeries.PrepareForGallery(IsEnabled:Boolean); begin inherited; ParentChart.View3DOptions.Orthogonal:=True; end; type TPointerAccess=class(TSeriesPointer); { TImagePointSeries } Constructor TImagePointSeries.Create(AOwner:TComponent); begin inherited; LoadBitmapFromResourceName(FImagePoint.Bitmap,'TeeDefaultImage'); FImageTransp:=True; TPointerAccess(Pointer).ChangeHorizSize(FImagePoint.Width); TPointerAccess(Pointer).ChangeVertSize(FImagePoint.Height); end; { TDeltaPointSeries } Constructor TDeltaPointSeries.Create(AOwner:TComponent); begin inherited; FEqualImage:=TPicture.Create; FEqualImage.OnChange:=CanvasChanged; FGreaterImage:=TPicture.Create; FGreaterImage.OnChange:=CanvasChanged; FLowerImage:=TPicture.Create; FLowerImage.OnChange:=CanvasChanged; ImageStyle:=disSmiles; end; Destructor TDeltaPointSeries.Destroy; begin FEqualImage.Free; FLowerImage.Free; FGreaterImage.Free; inherited; end; { overrided DrawValue to draw an Image for each point } procedure TDeltaPointSeries.DrawValue(ValueIndex:Integer); Var tmp : Double; tmpPrevious : Double; begin if ValueIndex=0 then FImagePoint.Assign(FEqualImage) else begin tmpPrevious:=MandatoryValueList.Value[ValueIndex-1]; tmp:=MandatoryValueList.Value[ValueIndex]; if tmp>tmpPrevious then FImagePoint.Assign(FGreaterImage) else if tmp<tmpPrevious then FImagePoint.Assign(FLowerImage) else FImagePoint.Assign(FEqualImage); end; if FImagePoint.Width>0 then TPointerAccess(Pointer).ChangeHorizSize(FImagePoint.Width); if FImagePoint.Height>0 then TPointerAccess(Pointer).ChangeVertSize(FImagePoint.Height); inherited; end; procedure TDeltaPointSeries.SetEqualImage(Const Value:TPicture); begin FEqualImage.Assign(Value); end; procedure TDeltaPointSeries.SetGreaterImage(Const Value:TPicture); begin FGreaterImage.Assign(Value); end; procedure TDeltaPointSeries.SetLowerImage(Const Value:TPicture); begin FLowerImage.Assign(Value); end; procedure TDeltaPointSeries.SetImageStyle(Const Value:TDeltaImageStyle); begin FImageStyle:=Value; if Value=disHands then begin LoadBitmapFromResourceName(FEqualImage.Bitmap,'TeeEqualHand'); LoadBitmapFromResourceName(FGreaterImage.Bitmap,'TeeGreaterHand'); LoadBitmapFromResourceName(FLowerImage.Bitmap,'TeeLowerHand'); end else begin LoadBitmapFromResourceName(FEqualImage.Bitmap,'TeeEqualSmile'); LoadBitmapFromResourceName(FGreaterImage.Bitmap,'TeeGreaterSmile'); LoadBitmapFromResourceName(FLowerImage.Bitmap,'TeeLowerSmile'); end; end; initialization RegisterTeeSeries( TImagePointSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_ImagePointSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySamples, 1 ); RegisterTeeSeries( TDeltaPointSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_DeltaPointSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySamples, 1 ); finalization UnRegisterTeeSeries([ TImagePointSeries,TDeltaPointSeries ]); end.
unit vr_WinAPI; {$mode delphi}{$H+} {$I vrode.inc} interface {$IFDEF WINDOWS} uses Windows, SysUtils, Classes, vr_types, Math, vr_WideStrings, LazUTF8 {$IFDEF IGNORE_SHELL_COMPAT} , ShellApi, shlobj{$ENDIF}; function UTF8ToOEM(const S: string): string; function OEMToUTF8(const S: string): string; const WIN_VER_10 = 10.0; WIN_VER_8_1 = 6.3; WIN_VER_8 = 6.2; WIN_VER_7 = 6.1; WIN_VER_Server_2008_R2 = 6.1; WIN_VER_Server_2008 = 6.0; WIN_VER_Vista = 6.0; WIN_VER_Server_2003_R2 = 5.2; WIN_VER_Server_2003 = 5.2; WIN_VER_XP_64 = 5.2; WIN_VER_XP = 5.1; WIN_VER_2000 = 5.0; function GetWindowsVersion: string; function GetWindowsVersionNumber: Double;//WIN_VER_* function CompareWindowsVersion(AVersion: Double): Integer; function IsWinNT: Boolean; function IsWin64: Boolean; function GetSysDirW: WideString; function GetSysDir: string; function GetWindowsDirW: WideString; function GetWindowsDir: string; function GetSpecialFolderDirW(CSIDL_: Integer): WideString; function GetSpecialFolderDir(CSIDL_: Integer): string; function GetProgramFilesDirW: WideString; function GetProgramFilesDir: string; function SearchFilePathW(const AFileName: WideString; out APath: WideString): Boolean; function SearchFilePath(const AFileName: string; out APath: string): Boolean; function WinToDosTime(var Wtime : TFileTime; var DTime:longint): longbool; function DosToWinTime(DTime: longint; var Wtime: TFileTime): longbool; function file_ExistsW(const AFileName: WideString): Boolean; function file_ExtractDirW(const AFileName: WideString): WideString; function DuplicateHandle(var AHandle: THandle): Boolean; function ExecuteDocumentW(const APath, AParams: WideString; const ACurrentDirectory: WideString; const AShowError: Boolean = False): Boolean; function ExecuteDocumentExW(const APath, AParams: WideString; const ACurrentDirectory: WideString; const AShowError: Boolean; out AProcessHandle: THandle): Boolean; function ExecuteProgramExW(const AProg, AParams, ACurrentDirectory: WideString; const AFlags: TExecProgramFlags; const AMSecWait: Integer; const AProcessId: PProcessId = nil; const AJobHandle: PHandle = nil; const AProcessHandle: PHandle = nil): Integer; {%Region Registry} function reg_KeyOpenReadW(const ASubKey: WideString; out AResult: HKey; AKey: HKey = HKEY_CURRENT_USER): Boolean; function reg_KeyOpenWriteW(const ASubKey: WideString; out AResult: HKey; AKey: HKey = HKEY_CURRENT_USER): Boolean; function reg_KeyOpenCreateW(const ASubKey: WideString; out AResult: HKey; AKey: HKey = HKEY_CURRENT_USER): Boolean; procedure reg_KeyClose(AKey: HKey); function reg_KeyDeleteW(AKey: HKey; const ASubKey: WideString): Boolean; function reg_KeyDeleteValueW(AKey: HKey; const ASubKey: WideString): Boolean; function reg_KeyExistsW(AKey: HKey; const ASubKey: WideString): Boolean; function reg_KeyValueExistsW(AKey: HKey; const AName: WideString): Boolean; {* If the function succeeds, the return value return will be one of the following: REG_BINARY , REG_DWORD, REG_DWORD_LITTLE_ENDIAN, REG_DWORD_BIG_ENDIAN, REG_EXPAND_SZ, REG_LINK , REG_MULTI_SZ, REG_NONE, REG_RESOURCE_LIST, REG_SZ } function reg_KeyGetValueTypeW(const AKey: HKEY; const AName: WideString): DWORD; function reg_KeyValueSizeW(AKey: HKey; const AName: WideString): Integer; function reg_KeyGetStringW(AKey: HKey; const AName: WideString; const ADefault: WideString = ''): WideString; function reg_KeySetStringW(AKey: HKEY; const AName, AValue: WideString; AsExpand: Boolean = False): Boolean; function reg_KeyGetDWordW(AKey: HKey; const AName: WideString; ADefault: DWORD = 0): DWORD; function reg_KeySetDWordW(AKey: HKey; const AName: WideString; AValue: DWORD): Boolean; function reg_KeyGetBinaryW(AKey: HKey; const AName: WideString; out ABuffer; ACount: Integer): Integer; function reg_KeySetBinaryW(AKey: HKey; const AName: WideString; const ABuffer; ACount: Integer): Boolean; function reg_KeyGetDateTimeW(AKey: HKey; const AName: WideString): TDateTime; function reg_KeySetDateTimeW(AKey: HKey; const AName: WideString; ADateTime: TDateTime): Boolean; //ToDo TWideStringList -> TWideStrings -> vrTypes //function reg_KeyGetSubKeysW(const AKey: HKEY; AList: TWideStringList; AIsClearList: Boolean = True): Boolean; //function reg_KeyGetValueNamesW(const AKey: HKEY; AList: TWideStringList; AIsClearList: Boolean = True): Boolean; function reg_KeyOpenRead(const ASubKey: string; out AResult: HKey; AKey: HKey = HKEY_CURRENT_USER): Boolean; function reg_KeyOpenWrite(const ASubKey: string; out AResult: HKey; AKey: HKey = HKEY_CURRENT_USER): Boolean; function reg_KeyOpenCreate(const ASubKey: string; out AResult: HKey; AKey: HKey = HKEY_CURRENT_USER): Boolean; function reg_KeyDelete(AKey: HKey; const ASubKey: string): Boolean; function reg_KeyDeleteValue(AKey: HKey; const ASubKey: string): Boolean; function reg_KeyExists(AKey: HKey; const ASubKey: string): Boolean; function reg_KeyValueExists(AKey: HKey; const AName: string): Boolean; function reg_KeyGetValueType(const AKey: HKEY; const AName: string): DWORD; function reg_KeyValueSize(AKey: HKey; const AName: string): Integer; function reg_KeyGetString(AKey: HKey; const AName: string; const ADefault: string = ''): string; function reg_KeySetString(AKey: HKEY; const AName, AValue: string; AsExpand: Boolean = False): Boolean; function reg_KeyGetDWord(AKey: HKey; const AName: string; ADefault: DWORD = 0): DWORD; function reg_KeySetDWord(AKey: HKey; const AName: string; AValue: DWORD): Boolean; function reg_KeyGetBinary(AKey: HKey; const AName: string; var ABuffer; ACount: Integer): Integer; function reg_KeySetBinary(AKey: HKey; const AName: string; const ABuffer; ACount: Integer): Boolean; function reg_KeyGetDateTime(AKey: HKey; const AName: string): TDateTime; function reg_KeySetDateTime(AKey: HKey; const AName: string; ADateTime: TDateTime): Boolean; function reg_KeyGetSubKeys(const AKey: HKEY; AList: TStrings; AIsClearList: Boolean = True): Boolean; function reg_KeyGetValueNames(const AKey: HKEY; AList: TStrings; AIsAddValues: Boolean = False; AIsClearList: Boolean = True): Boolean; function RegKeyExistsW(const ASubKey, AName: WideString; AKey: HKey = HKEY_CURRENT_USER): Boolean; function RegKeyValueExistsW(const ASubKey, AName: WideString; AKey: HKey = HKEY_CURRENT_USER): Boolean; function RegReadStringW(const ASubKey, AName: WideString; const ADefault: WideString = ''; AKey: HKey = HKEY_CURRENT_USER): WideString; function RegWriteStringW(const ASubKey, AName, AValue: WideString; AKey: HKey = HKEY_CURRENT_USER): Boolean; function RegReadIntegerW(const ASubKey, AName: WideString; const ADefault: Integer; AKey: Cardinal = HKEY_CURRENT_USER): Integer; function RegWriteIntegerW(const ASubKey, AName: WideString; const AValue: Integer; AKey: Cardinal = HKEY_CURRENT_USER): Boolean; function RegKeyExists(const ASubKey, AName: string; AKey: HKey = HKEY_CURRENT_USER): Boolean; function RegKeyValueExists(const ASubKey, AName: string; AKey: HKey = HKEY_CURRENT_USER): Boolean; function RegReadString(const ASubKey, AName: string; const ADefault: string = ''; AKey: HKey = HKEY_CURRENT_USER): string; function RegWriteString(const ASubKey, AName, AValue: string; AKey: HKey = HKEY_CURRENT_USER): Boolean; function RegReadInteger(const ASubKey, AName: string; const ADefault: Integer; AKey: Cardinal = HKEY_CURRENT_USER): Integer; function RegWriteInteger(const ASubKey, AName: string; const AValue: Integer; AKey: Cardinal = HKEY_CURRENT_USER): Boolean; function RegReadBool(const ASubKey, AName: string; const ADefault: Boolean = False; AKey: Cardinal = HKEY_CURRENT_USER): Boolean; function RegWriteBool(const ASubKey, AName: string; const AValue: Boolean; AKey: Cardinal = HKEY_CURRENT_USER): Boolean; function RegGetSubKeys(const ASubKey: string; AList: TStrings; AKey: HKey = HKEY_CURRENT_USER; AIsClearList: Boolean = True): Boolean; function RegGetValueNames(const ASubKey: string; AList: TStrings; AIsAddValues: Boolean = False; AKey: HKey = HKEY_CURRENT_USER; AIsClearList: Boolean = True): Boolean; {%EndRegion Registry} function GetProcessHandleFromHwnd(wnd: HWND): HANDLE; stdcall; function IsHwndBelongToPID(const AWnd: HWND; const pid: Cardinal): Boolean; function HwndFromPID(pid: Cardinal; out wnd: HWND): Boolean; const GetHwndFromPID: function(pid: Cardinal; out wnd: HWND): Boolean = HwndFromPID; {$IFNDEF IGNORE_SHELL_COMPAT}//ShellApi,shlobj to reduce size const shell32 = 'shell32'; CSIDL_DESKTOP = $0000; // <desktop> CSIDL_INTERNET = $0001; // Internet Explorer (icon on desktop) CSIDL_PROGRAMS = $0002; // Start Menu\Programs CSIDL_CONTROLS = $0003; // My Computer\Control Panel CSIDL_PRINTERS = $0004; // My Computer\Printers CSIDL_PERSONAL = $0005; // My Documents CSIDL_FAVORITES = $0006; // <user name>\Favorites CSIDL_STARTUP = $0007; // Start Menu\Programs\Startup CSIDL_RECENT = $0008; // <user name>\Recent CSIDL_SENDTO = $0009; // <user name>\SendTo CSIDL_BITBUCKET = $000a; // <desktop>\Recycle Bin CSIDL_STARTMENU = $000b; // <user name>\Start Menu CSIDL_MYDOCUMENTS = $000c; // logical "My Documents" desktop icon CSIDL_MYMUSIC = $000d; // "My Music" folder CSIDL_MYVIDEO = $000e; // "My Videos" folder CSIDL_DESKTOPDIRECTORY = $0010; // <user name>\Desktop CSIDL_DRIVES = $0011; // My Computer CSIDL_NETWORK = $0012; // Network Neighborhood (My Network Places) CSIDL_NETHOOD = $0013; // <user name>\nethood CSIDL_FONTS = $0014; // windows\fonts CSIDL_TEMPLATES = $0015; CSIDL_COMMON_STARTMENU = $0016; // All Users\Start Menu CSIDL_COMMON_PROGRAMS = $0017; // All Users\Start Menu\Programs CSIDL_COMMON_STARTUP = $0018; // All Users\Startup CSIDL_COMMON_DESKTOPDIRECTORY = $0019; // All Users\Desktop CSIDL_APPDATA = $001a; // <user name>\Application Data CSIDL_PRINTHOOD = $001b; // <user name>\PrintHood CSIDL_LOCAL_APPDATA = $001c; // <user name>\Local Settings\Applicaiton Data (non roaming) CSIDL_ALTSTARTUP = $001d; // non localized startup CSIDL_COMMON_ALTSTARTUP = $001e; // non localized common startup CSIDL_COMMON_FAVORITES = $001f; CSIDL_INTERNET_CACHE = $0020; CSIDL_COOKIES = $0021; CSIDL_HISTORY = $0022; CSIDL_COMMON_APPDATA = $0023; // All Users\Application Data CSIDL_WINDOWS = $0024; // GetWindowsDirectory() CSIDL_SYSTEM = $0025; // GetSystemDirectory() CSIDL_PROGRAM_FILES = $0026; // C:\Program Files CSIDL_MYPICTURES = $0027; // C:\Program Files\My Pictures CSIDL_PROFILE = $0028; // USERPROFILE CSIDL_SYSTEMX86 = $0029; // x86 system directory on RISC CSIDL_PROGRAM_FILESX86 = $002a; // x86 C:\Program Files on RISC CSIDL_PROGRAM_FILES_COMMON = $002b; // C:\Program Files\Common CSIDL_PROGRAM_FILES_COMMONX86 = $002c; // x86 Program Files\Common on RISC CSIDL_COMMON_TEMPLATES = $002d; // All Users\Templates CSIDL_COMMON_DOCUMENTS = $002e; // All Users\Documents CSIDL_COMMON_ADMINTOOLS = $002f; // All Users\Start Menu\Programs\Administrative Tools CSIDL_ADMINTOOLS = $0030; // <user name>\Start Menu\Programs\Administrative Tools CSIDL_CONNECTIONS = $0031; // Network and Dial-up Connections CSIDL_COMMON_MUSIC = $0035; // All Users\My Music CSIDL_COMMON_PICTURES = $0036; // All Users\My Pictures CSIDL_COMMON_VIDEO = $0037; // All Users\My Video CSIDL_RESOURCES = $0038; // Resource Direcotry CSIDL_RESOURCES_LOCALIZED = $0039; // Localized Resource Direcotry CSIDL_COMMON_OEM_LINKS = $003a; // Links to All Users OEM specific apps CSIDL_CDBURN_AREA = $003b; // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning CSIDL_COMPUTERSNEARME = $003d; // Computers Near Me (computered from Workgroup membership) CSIDL_FLAG_CREATE = $8000; // combine with CSIDL_ value to force folder creation in SHGetFolderPath() CSIDL_FLAG_DONT_VERIFY = $4000; // combine with CSIDL_ value to return an unverified folder path CSIDL_FLAG_NO_ALIAS = $1000; // combine with CSIDL_ value to insure non-alias versions of the pidl CSIDL_FLAG_PER_USER_INIT = $0800; // combine with CSIDL_ value to indicate per-user init (eg. upgrade) CSIDL_FLAG_MASK = $FF00; // mask for all possible flag values SEE_MASK_CLASSNAME = $00000001; SEE_MASK_CLASSKEY = $00000003; { Note INVOKEIDLIST overrides IDLIST } SEE_MASK_IDLIST = $00000004; SEE_MASK_INVOKEIDLIST = $0000000c; SEE_MASK_ICON = $00000010; SEE_MASK_HOTKEY = $00000020; SEE_MASK_NOCLOSEPROCESS = $00000040; SEE_MASK_CONNECTNETDRV = $00000080; SEE_MASK_FLAG_DDEWAIT = $00000100; SEE_MASK_DOENVSUBST = $00000200; SEE_MASK_FLAG_NO_UI = $00000400; SEE_MASK_UNICODE = $00004000; SEE_MASK_NO_CONSOLE = $00008000; SEE_MASK_ASYNCOK = $00100000; SEE_MASK_HMONITOR = $00200000; //if (_WIN32_IE >= 0x0500) SEE_MASK_NOQUERYCLASSSTORE= $01000000; SEE_MASK_WAITFORINPUTIDLE= $02000000; //endif (_WIN32_IE >= 0x500) //if (_WIN32_IE >= 0x0560) SEE_MASK_FLAG_LOG_USAGE = $04000000; type {$IFDEF VER3} STARTUPINFOW = windows.STARTUPINFOW; {$ELSE} STARTUPINFOW = record cb : DWORD; lpReserved : LPWSTR; lpDesktop : LPWSTR; lpTitle : LPWSTR; dwX : DWORD; dwY : DWORD; dwXSize : DWORD; dwYSize : DWORD; dwXCountChars : DWORD; dwYCountChars : DWORD; dwFillAttribute : DWORD; dwFlags : DWORD; wShowWindow : WORD; cbReserved2 : WORD; lpReserved2 : LPBYTE; hStdInput : HANDLE; hStdOutput : HANDLE; hStdError : HANDLE; end; LPSTARTUPINFOW = ^STARTUPINFOW; _STARTUPINFOW = STARTUPINFOW; TSTARTUPINFOW = STARTUPINFOW; PSTARTUPINFOW = ^STARTUPINFOW; {$ENDIF} _SHELLEXECUTEINFOW = record cbSize : DWORD; fMask : ULONG; wnd : HWND; lpVerb : lpcwstr; lpFile : lpcwstr; lpParameters : lpcwstr; lpDirectory : lpcwstr; nShow : longint; hInstApp : HINST; lpIDList : LPVOID; lpClass : LPCWSTR; hkeyClass : HKEY; dwHotKey : DWORD; DUMMYUNIONNAME : record case longint of 0 : ( hIcon : HANDLE ); 1 : ( hMonitor : HANDLE ); end; hProcess : HANDLE; end; SHELLEXECUTEINFOW = _SHELLEXECUTEINFOW; TSHELLEXECUTEINFOW = _SHELLEXECUTEINFOW; LPSHELLEXECUTEINFOW = ^_SHELLEXECUTEINFOW; function SHGetSpecialFolderLocation( hwnd:HWND; csidl:longint;out ppidl: LPITEMIDLIST):HResult;StdCall; external shell32 name 'SHGetSpecialFolderLocation'; function SHGetPathFromIDListW(pidl:LPCITEMIDLIST; pszPath:LPWStr):BOOL;StdCall;external shell32 name 'SHGetPathFromIDListW'; function ShellExecuteW(hwnd: HWND;lpOperation : LPCWSTR ; lpFile : LPCWSTR; lpParameters : LPCWSTR; lpDirectory: LPCWSTR; nShowCmd:LONGINT):HInst; stdcall; external shell32 name 'ShellExecuteW'; Function ShellExecuteExW(lpExecInfo: LPSHELLEXECUTEINFOW):Bool; stdcall; external shell32 name 'ShellExecuteExW'; {$ENDIF} const IID_IShellLinkDataList: TGUID = (D1:$45e2b4ae; D2:$b1c3; D3:$11d0; D4:($b9, $2f, $0, $a0, $c9, $3, $12, $e1)); type IShellLinkDataList = interface ['{45e2b4ae-b1c3-11d0-b92f-00a0c90312e1}'] function AddDataBlock(pDataBlock: Pointer): HRESULT; stdcall; function CopyDataBlock(dwSig: DWORD; ppDataBlock: PPointer): HRESULT; stdcall; function GetFlags(pdwFlags: PDWORD): HRESULT; stdcall; function RemoveDataBlock(dwSig: DWORD): HRESULT; stdcall; function SetFlags(dwFlags: DWORD): HRESULT; stdcall;//dwFlags: SLDF_* in ShellApi.pp end; {$IFNDEF JEDI_WINAPI} {$I jedi.inc} {$ENDIF} {$ENDIF WINDOWS} implementation {$IFDEF WINDOWS} uses vr_utils; function UTF8ToOEM(const S: string): string; var Dst: PChar; ws: WideString; begin ws := UTF8Decode(S); Dst := AllocMem((Length(ws) + 1) * SizeOf(WideChar)); if CharToOemW(PWideChar(ws), Dst) then Result := StrPas(Dst) else Result := S; FreeMem(Dst); end; function OEMToUTF8(const S: string): string; var Dst: PWideChar; ws: WideString; begin Dst := AllocMem((Length(S) + 1) * SizeOf(WideChar)); if OemToCharW(PChar(s), Dst) then begin ws := PWideChar(Dst); Result := UTF8Encode(ws); end else Result := s; FreeMem(Dst); end; function _GetWindowsVersionInfo: OSVERSIONINFOW; begin FillChar(Result{%H-}, SizeOf(Result), 0); Result.dwOSVersionInfoSize := SizeOf(Result); GetVersionExW(@Result); end; function GetWindowsVersion: string; var OSVer: OSVERSIONINFOW; begin OSVer := _GetWindowsVersionInfo; Result := IntToStr(OSVer.dwMajorVersion) + '.' + IntToStr(OSVer.dwMinorVersion) + '.' + IntToStr(OSVer.dwBuildNumber) + ' ' + UTF8Encode(WideString(OSVer.szCSDVersion)); Result := TrimRight(Result); end; function GetWindowsVersionNumber: Double; var OSVer: OSVERSIONINFOW; begin OSVer := _GetWindowsVersionInfo; TryStrToFloat(IntToStr(OSVer.dwMajorVersion) + DefaultFormatSettings.DecimalSeparator + IntToStr(OSVer.dwMinorVersion), Result); end; function CompareWindowsVersion(AVersion: Double): Integer; begin Result := CompareValue(GetWindowsVersionNumber, AVersion, 0.001); end; function IsWinNT: Boolean; var OSVer: OSVERSIONINFOW; begin OSVer := _GetWindowsVersionInfo; Result := OSVer.dwPlatformId = VER_PLATFORM_WIN32_NT; end; function IsWin64: Boolean; var Attr: DWORD; begin Attr := Windows.GetFileAttributesW(PWideChar(GetWindowsDirW + '\SysWOW64\regedit.exe')); if Attr <> INVALID_FILE_ATTRIBUTES then Result := (Attr and FILE_ATTRIBUTE_DIRECTORY) = 0 else Result := False; end; function GetSysDirW: WideString; var I: windows.UINT; begin SetLength(Result, MAX_PATH); I := GetSystemDirectoryW(PWideChar(Result), MAX_PATH); SetLength(Result, I);//Result := PWideChar(Result); end; function GetSysDir: string; begin Result := UTF8Encode(GetSysDirW); end; function GetWindowsDirW: WideString; var I: windows.UINT; begin SetLength(Result, MAX_PATH); I := GetWindowsDirectoryW(PWideChar(Result), MAX_PATH); SetLength(Result, I);//Result := PWideChar(Result); end; function GetWindowsDir: string; begin Result := UTF8Encode(GetWindowsDirW); end; function GetSpecialFolderDirW(CSIDL_: Integer): WideString; var //IDL: ITEMIDLIST; PIDL: PItemIDList; //S: string; //Path: LPSTR; begin //Path := StrAlloc(MAX_PATH); //CSIDL_RECENT = $0008; //Folder := CSIDL_HISTORY {SetLength(Result, MAX_PATH); if SHGetSpecialFolderPath(0, PChar(Result), Folder, True) then Result := PChar(Result) else Result := '';} if Succeeded(SHGetSpecialFolderLocation(0, CSIDL_, PIDL)) then begin SetLength(Result, MAX_PATH); SHGetPathFromIDListW(PIDL, PWideChar(Result)); Result := PWideChar(Result); end; //StrDispose(Path); end; function GetSpecialFolderDir(CSIDL_: Integer): string; begin Result := UTF8Encode(GetSpecialFolderDirW(CSIDL_)); end; function _GetDrive(const APath: WideString): WideString; begin Result := UTF8Decode(ExtractFileDrive(UTF8Encode(APath))); end; function GetProgramFilesDirW: WideString; begin Result := GetSpecialFolderDirW(CSIDL_PROGRAM_FILES); if Length(Result) = 0 then begin Result := GetWindowsDirW; Result := _GetDrive(Result) + '\Program Files'; end; if Result[Length(Result)] = '\' then// WideEndsStr(PathDelim, Result) then System.Delete(Result, Length(Result), 1); end; function GetProgramFilesDir: string; begin Result := UTF8Encode(GetProgramFilesDirW); end; function SearchFilePathW(const AFileName: WideString; out APath: WideString): Boolean; begin SetLength(APath, MAX_PATH); Result := Windows.SearchPathW(nil, PWideChar(AFileName), nil, MAX_PATH, PWideChar(APath), nil) > 0; if Result then APath := PWideChar(APath) else APath := ''; end; function SearchFilePath(const AFileName: string; out APath: string): Boolean; var wsResult: WideString; begin Result := SearchFilePathW(UTF8ToUTF16(AFileName), wsResult); APath := UTF16ToUTF8(wsResult); end; function WinToDosTime(var Wtime: TFileTime; var DTime: longint): longbool; var lft : TFileTime; begin Result := FileTimeToLocalFileTime(WTime,lft{%H-}) and FileTimeToDosDateTime(lft,Longrec(Dtime).Hi,LongRec(DTIME).lo); end; function DosToWinTime(DTime: longint; var Wtime: TFileTime): longbool; var lft : TFileTime; begin Result := DosDateTimeToFileTime(longrec(dtime).hi,longrec(dtime).lo,@lft) and LocalFileTimeToFileTime(lft,Wtime); end; function file_ExistsW(const AFileName: WideString): Boolean; var Attr:Dword; begin Attr:=GetFileAttributesW(PWideChar(AFileName)); if Attr <> $ffffffff then Result := (Attr and FILE_ATTRIBUTE_DIRECTORY) = 0 else Result := False; end; function file_ExtractDirW(const AFileName: WideString): WideString; begin Result := UTF8Decode(ExtractFileDir(UTF8Encode(AFileName))); end; function DuplicateHandle(var AHandle: THandle): Boolean; var oldHandle: THandle; begin oldHandle := AHandle; Result := Windows.DuplicateHandle(GetCurrentProcess(), oldHandle, GetCurrentProcess(), @AHandle, 0, True, DUPLICATE_SAME_ACCESS); if Result then Result := CloseHandle(oldHandle); end; function ExecuteDocumentW(const APath, AParams: WideString; const ACurrentDirectory: WideString; const AShowError: Boolean): Boolean; var h: THandle; begin Result := ExecuteDocumentExW(APath, AParams, ACurrentDirectory, AShowError, h); if Result then CloseHandle(h); end; function ExecuteDocumentExW(const APath, AParams: WideString; const ACurrentDirectory: WideString; const AShowError: Boolean; out AProcessHandle: THandle): Boolean; var CurrDir: WideString; Info: TSHELLEXECUTEINFOW; begin AProcessHandle := 0; if ACurrentDirectory = '' then CurrDir := file_ExtractDirW(APath) else CurrDir := ACurrentDirectory; if AShowError then begin FillChar(Info{%H-}, SizeOf(Info), 0); Info.cbSize := SizeOf(Info); Info.fMask := SEE_MASK_NOCLOSEPROCESS; Info.lpVerb := 'open'; Info.lpFile := PWideChar(APath); Info.lpParameters := PWideChar(AParams); Info.lpDirectory := PWideChar(CurrDir); Info.nShow := SW_NORMAL; Result := ShellExecuteExW(@Info);//show error if Result then AProcessHandle := Info.hProcess; end else begin Result := ShellExecuteW(0, 'open', PWideChar(APath), PWideChar(AParams), PWideChar(CurrDir), SW_NORMAL) > 32; end; end; function ExecuteProgramExW(const AProg, AParams, ACurrentDirectory: WideString; const AFlags: TExecProgramFlags; const AMSecWait: Integer; const AProcessId: PProcessId; const AJobHandle: PHandle; const AProcessHandle: PHandle): Integer; var pi: TProcessInformation; //ARedir: TProcessRedirectThread; function _Execute: Integer; var SI: TStartupInfoW; hProcess: THandle; code: DWord; CommandLine, CurrDir : WideString; Flags: DWORD = 0;//NORMAL_PRIORITY_CLASS; begin Result := EXEC_FAIL; FillChar(SI{%H-}, SizeOf(SI), 0); SI.cb := SizeOf(SI); if epfHidden in AFlags then begin SI.wShowWindow := SW_HIDE; SI.dwFlags := STARTF_USESHOWWINDOW; end else SI.wShowWindow := SW_NORMAL; //new:6.9.5 SI.wShowWindow := IfThen(epfHidden in AFlags, SW_HIDE, SW_NORMAL); //if ARedir <> nil then // begin // flag_Set(SI.dwFlags, STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW); // SI.hStdInput := ARedir.Input; // SI.hStdOutput := ARedir.Output; // SI.hStdError := ARedir.Stderr; // end; if ACurrentDirectory = '' then CurrDir := file_ExtractDirW(AProg) else CurrDir := ACurrentDirectory; CommandLine := AProg + ' ' + AParams + #0; if epfNewConsole in AFlags then flag_Set(Flags, CREATE_NEW_CONSOLE); //if epfSuspended in AFlags then // flag_Set(Flags, CREATE_SUSPENDED); if epfNewGroup in AFlags then flag_Set(Flags, CREATE_NEW_PROCESS_GROUP); if AJobHandle <> nil then flag_Set(Flags, CREATE_SUSPENDED); if not CreateProcessW(nil, PWideChar(CommandLine), nil, nil, epfInheritHandles in AFlags, Flags, nil, PWideChar(CurrDir), @SI, @PI) then begin Exit; end; hProcess := PI.hProcess; if AJobHandle <> nil then begin AJobHandle^ := CreateJobObject(nil, nil); AssignProcessToJobObject(AJobHandle^, hProcess); ResumeThread(PI.hThread); //if ARedir <> nil then // ARedir.JobHandle := AJobHandle^; end; if (epfWait in AFlags) and (AMSecWait > 0) and (WaitForSingleObject(hProcess, DWORD(AMSecWait)) <> WAIT_FAILED) then//dword($ffffffff)) <> $ffffffff) then begin GetExitCodeProcess(hProcess, code{%H-}); Result := code; end else begin //e:=EOSError.CreateFmt(SExecuteProcessFailed,[ACommandLine,GetLastError]); //e.ErrorCode:=GetLastError; if epfKillIfTimeOut in AFlags then begin Result := EXEC_TIME_OUT; TerminateProcess(PI.hProcess, Cardinal(EXEC_TIME_OUT)); end else Result := 0; end; end; begin if AProcessId <> nil then AProcessId^ := 0; if AProcessHandle <> nil then AProcessHandle^ := 0; //if ARedirThread is TProcessRedirectThread then // ARedir := TProcessRedirectThread(ARedirThread) //else // ARedir := nil; Result := _Execute;//(AProg, AParams, ACurrentDirectory, AFlags, AMSecWait, //pi, AJobHandle, ARedir); if Result <> EXEC_FAIL then begin CloseHandle(PI.hThread); if AProcessId <> nil then AProcessId^ := PI.dwProcessId; if AProcessHandle <> nil then begin AProcessHandle^ := PI.hProcess; //if ARedir <> nil then // ARedir.ProcessHandle := PI.hProcess; end else CloseHandle(PI.hProcess); end; end; var _GetProcessHandleFromHwnd: function(wnd: HWND): HANDLE; stdcall; //external 'Oleacc.dll'; _hlibOleacc: windows.HINST; function _GetProcessHandleFromHwndDummy({%H-}wnd: HWND): HANDLE; stdcall; begin Result := HANDLE(0); end; function reg_KeyOpenReadW(const ASubKey: WideString; out AResult: HKey; AKey: HKey = HKEY_CURRENT_USER): Boolean; begin Result := RegOpenKeyExW(AKey, PWideChar(ASubKey), 0, KEY_READ, AResult{%H-}) = ERROR_SUCCESS; end; function reg_KeyOpenWriteW(const ASubKey: WideString; out AResult: HKey; AKey: HKey = HKEY_CURRENT_USER): Boolean; begin Result := RegOpenKeyExW(AKey, PWideChar(ASubKey), 0, KEY_READ or KEY_WRITE, AResult{%H-}) = ERROR_SUCCESS; end; function reg_KeyOpenCreateW(const ASubKey: WideString; out AResult: HKey; AKey: HKey = HKEY_CURRENT_USER): Boolean; var dwDisp: DWord; begin Result := RegCreateKeyExW(AKey, PWideChar(ASubKey), 0, nil, 0, KEY_ALL_ACCESS, nil, AResult{%H-}, @dwDisp) = ERROR_SUCCESS; end; procedure reg_KeyClose(AKey: HKey); begin if AKey <> 0 then RegCloseKey(AKey); end; function reg_KeyDeleteW(AKey: HKey; const ASubKey: WideString): Boolean; begin Result := FALSE; if AKey <> 0 then Result := RegDeleteKeyW(AKey, PWideChar(ASubKey)) = ERROR_SUCCESS; end; function reg_KeyDeleteValueW(AKey: HKey; const ASubKey: WideString): Boolean; begin Result := FALSE; if AKey <> 0 then Result := RegDeleteValueW(AKey, PWideChar(ASubKey)) = ERROR_SUCCESS; end; function reg_KeyExistsW(AKey: HKey; const ASubKey: WideString): Boolean; var K: HKey; begin Result := (AKey <> 0) and reg_KeyOpenReadW(ASubKey, K, AKey); if Result then reg_KeyClose(K); end; function reg_KeyValueExistsW(AKey: HKey; const AName: WideString): Boolean; var dwType, dwSize: DWORD; begin Result := (AKey <> 0) and (RegQueryValueExW(AKey, PWideChar(AName), nil, @dwType, nil, @dwSize ) = ERROR_SUCCESS); end; function reg_KeyGetValueTypeW(const AKey: HKEY; const AName: WideString): DWORD; begin Result := AKey; if (AKey <> 0) and (AName <> '') then RegQueryValueExW(AKey, @AName[1], nil, @Result, nil, nil) end; function reg_KeyValueSizeW(AKey: HKey; const AName: WideString): Integer; begin Result := 0; if AKey = 0 then Exit; RegQueryValueExW(AKey, PWideChar(AName), nil, nil, nil, @DWORD(Result)); end; function reg_KeyGetStringW(AKey: HKey; const AName: WideString; const ADefault: WideString = ''): WideString; var ws: WideString; ok: Boolean; LenWS: DWORD; rType: DWORD; begin Result := ADefault; ok := RegQueryValueExW(AKey, PWideChar(AName), nil, nil, nil, @LenWS) = ERROR_SUCCESS; if ok then begin SetLength(ws, LenWS); ok := RegQueryValueExW(AKey, PWideChar(AName), nil, @rType, @ws[1], @LenWS) = ERROR_SUCCESS; if ok and ((rType = REG_SZ) or (rType = REG_EXPAND_SZ) or (rType = REG_MULTI_SZ)) then begin Result := WideTrimChar(PWideChar(ws), '"'); end; end; end; function reg_KeySetStringW(AKey: HKEY; const AName, AValue: WideString; AsExpand: Boolean): Boolean; var dwType: DWORD; begin if AsExpand then dwType := REG_EXPAND_SZ else dwType := REG_SZ; Result := (AKey <> 0) and (RegSetValueExW(AKey, PWideChar(AName), 0, dwType, PWideChar(AValue), (Length(AValue) + 1) * 2) = ERROR_SUCCESS); end; function reg_KeyGetDWordW(AKey: HKey; const AName: WideString; ADefault: DWORD): DWORD; var dwType, dwSize: DWORD; begin dwSize := Sizeof(DWORD); Result := ADefault; if (AKey = 0) or (RegQueryValueExW(AKey, PWideChar(AName), nil, @dwType, PByte(@Result), @dwSize) <> ERROR_SUCCESS) or (dwType <> REG_DWORD) then Result := ADefault; end; function reg_KeySetDWordW(AKey: HKey; const AName: WideString; AValue: DWORD): Boolean; begin Result := (AKey <> 0) and (RegSetValueExW(AKey, PWideChar(AName), 0, REG_DWORD, @AValue, SizeOf(DWORD)) = ERROR_SUCCESS); end; function reg_KeyGetBinaryW(AKey: HKey; const AName: WideString; out ABuffer; ACount: Integer): Integer; begin Result := 0; if AKey = 0 then Exit; Result := ACount; RegQueryValueExW(AKey, PWideChar(AName), nil, nil, @ABuffer, @Result); end; function reg_KeySetBinaryW(AKey: HKey; const AName: WideString; const ABuffer; ACount: Integer): Boolean; begin Result := (AKey <> 0) and (RegSetValueExW(AKey, PWideChar(AName ), 0, REG_BINARY, @ABuffer, ACount) = ERROR_SUCCESS); end; function reg_KeyGetDateTimeW(AKey: HKey; const AName: WideString): TDateTime; begin reg_KeyGetBinaryW(AKey, AName, Result, Sizeof(Result)); end; function reg_KeySetDateTimeW(AKey: HKey; const AName: WideString; ADateTime: TDateTime): Boolean; begin Result := reg_KeySetBinaryW(AKey, AName, ADateTime, Sizeof(ADateTime)); end; function reg_KeyGetSubKeysW(const AKey: HKEY; AList: TWideStringList; AIsClearList: Boolean = True): Boolean; var i, MaxSubKeyLen, Size: DWORD; Buf: PWideChar; begin Result := False; if AIsClearList then AList.Clear; if RegQueryInfoKeyW(AKey, nil, nil, nil, nil, @MaxSubKeyLen, nil, nil, nil, nil, nil, nil) = ERROR_SUCCESS then begin if MaxSubKeyLen > 0 then begin Size := MaxSubKeyLen + 1; GetMem(Buf, Size * Sizeof(WideChar)); i := 0; while RegEnumKeyExW(AKey, i, buf, Size, nil, nil, nil, nil) <> ERROR_NO_MORE_ITEMS do begin AList.Add(WideString(Buf)); Size := MaxSubKeyLen + 1; inc(i); end; FreeMem(Buf{,MaxSubKeyLen + 1}); end; Result := True; end; end; function reg_KeyGetValueNamesW(const AKey: HKEY; AList: TWideStringList; AIsAddValues: Boolean = False; AIsClearList: Boolean = True): Boolean; var i, MaxValueNameLen, Size: DWORD; Buf: PWideChar; dwType: DWord; sName, sValue: WideString; begin Result := False; if AIsClearList then AList.Clear; if RegQueryInfoKeyW(AKey, nil, nil, nil, nil, nil, nil, nil, @MaxValueNameLen, nil, nil, nil) = ERROR_SUCCESS then begin if MaxValueNameLen > 0 then begin Size := MaxValueNameLen + 1; GetMem(Buf, Size * SizeOf(WideChar)); i := 0; while RegEnumValueW(AKey, i, buf, Size, nil, @dwType, nil, nil) <> ERROR_NO_MORE_ITEMS do begin sName := WideString(Buf); if AIsAddValues then begin case dwType of REG_SZ, REG_EXPAND_SZ: sValue := reg_KeyGetStringW(AKey, sName, ''); else sValue := '' end; sName := sName + '=' + sValue; end; AList.Add(sName); Size := MaxValueNameLen+1; inc(i); end; FreeMem(Buf {,MaxValueNameLen + ... system always knows how long buffer is}); end; Result := True; end; end; function RegKeyExistsW(const ASubKey, AName: WideString; AKey: HKey): Boolean; var hRegKey: HKEY; begin Result := False; if reg_KeyOpenReadW(ASubKey, hRegKey, AKey) then begin Result := reg_KeyExistsW(hRegKey, AName); RegCloseKey(hRegKey); end; end; function RegKeyValueExistsW(const ASubKey, AName: WideString; AKey: HKey ): Boolean; var hRegKey: HKEY; begin Result := False; if reg_KeyOpenReadW(ASubKey, hRegKey, AKey) then begin Result := reg_KeyValueExistsW(hRegKey, AName); RegCloseKey(hRegKey); end; end; function RegReadStringW(const ASubKey, AName: WideString; const ADefault: WideString; AKey: HKey): WideString; var hRegKey: HKEY; begin Result := ADefault; if reg_KeyOpenReadW(ASubKey, hRegKey, AKey) then begin Result := reg_KeyGetStringW(hRegKey, AName, ADefault); RegCloseKey(hRegKey); end; end; function reg_KeyGetSubKeys(const AKey: HKEY; AList: TStrings; AIsClearList: Boolean): Boolean; var strs: TWideStringList; begin strs := TWideStringList.Create; try Result := reg_KeyGetSubKeysW(AKey, strs, AIsClearList); WideStringsToUTF8(strs, AList, AIsClearList); finally strs.Free; end; end; function reg_KeyGetValueNames(const AKey: HKEY; AList: TStrings; AIsAddValues: Boolean; AIsClearList: Boolean): Boolean; var strs: TWideStringList; begin strs := TWideStringList.Create; try Result := reg_KeyGetValueNamesW(AKey, strs, AIsAddValues, AIsClearList); WideStringsToUTF8(strs, AList, AIsClearList); finally strs.Free; end; end; function RegKeyExists(const ASubKey, AName: string; AKey: HKey): Boolean; begin Result := RegKeyExistsW(UTF8Decode(ASubKey), UTF8Decode(AName), AKey); end; function RegKeyValueExists(const ASubKey, AName: string; AKey: HKey): Boolean; begin Result := RegKeyValueExistsW(UTF8Decode(ASubKey), UTF8Decode(AName), AKey); end; function RegReadString(const ASubKey, AName: string; const ADefault: string; AKey: HKey): string; begin Result := UTF8Encode(RegReadStringW(UTF8Decode(ASubKey), UTF8Decode(AName), UTF8Decode(ADefault), AKey)); end; function RegWriteStringW(const ASubKey, AName, AValue: WideString; AKey: HKey): Boolean; var Key: HKey; begin Result := False; if reg_KeyOpenCreateW(ASubKey, Key, AKey) then begin Result := reg_KeySetStringW(Key, AName, AValue, False); reg_KeyClose(Key); end; end; function RegReadIntegerW(const ASubKey, AName: WideString; const ADefault: Integer; AKey: Cardinal): Integer; var Key: HKEY; begin Result := ADefault; if reg_KeyOpenReadW(ASubKey, Key, AKey) then begin Result := reg_KeyGetDWordW(Key, AName, ADefault); RegCloseKey(Key); end; end; function RegWriteIntegerW(const ASubKey, AName: WideString; const AValue: Integer; AKey: Cardinal): Boolean; var Key: HKey; begin Result := False; if reg_KeyOpenCreateW(ASubKey, Key, AKey) then begin Result := reg_KeySetDWord(Key, UTF8Encode(AName), AValue); reg_KeyClose(Key); end; end; function RegWriteString(const ASubKey, AName, AValue: string; AKey: HKey): Boolean; begin Result := RegWriteStringW(UTF8Decode(ASubKey), UTF8Decode(AName), UTF8Decode(AValue), AKey); end; function RegReadInteger(const ASubKey, AName: string; const ADefault: Integer; AKey: Cardinal): Integer; begin Result := RegReadIntegerW(UTF8Decode(ASubKey), UTF8Decode(AName), ADefault, AKey); end; function RegWriteInteger(const ASubKey, AName: string; const AValue: Integer; AKey: Cardinal): Boolean; begin Result := RegWriteIntegerW(UTF8Decode(ASubKey), UTF8Decode(AName), AValue, AKey); end; function RegReadBool(const ASubKey, AName: string; const ADefault: Boolean; AKey: Cardinal): Boolean; begin Result := RegReadIntegerW(UTF8Decode(ASubKey), UTF8Decode(AName), Ord(ADefault), AKey) <> 0; end; function RegWriteBool(const ASubKey, AName: string; const AValue: Boolean; AKey: Cardinal): Boolean; begin Result := RegWriteIntegerW(UTF8Decode(ASubKey), UTF8Decode(AName), Ord(AValue), AKey); end; function reg_KeyOpenRead(const ASubKey: string; out AResult: HKey; AKey: HKey ): Boolean; begin Result := reg_KeyOpenReadW(UTF8ToUTF16(ASubKey), AResult, AKey); end; function reg_KeyOpenWrite(const ASubKey: string; out AResult: HKey; AKey: HKey ): Boolean; begin Result := reg_KeyOpenWriteW(UTF8ToUTF16(ASubKey), AResult, AKey); end; function reg_KeyOpenCreate(const ASubKey: string; out AResult: HKey; AKey: HKey ): Boolean; begin Result := reg_KeyOpenCreateW(UTF8ToUTF16(ASubKey), AResult, AKey); end; function reg_KeyDelete(AKey: HKey; const ASubKey: string): Boolean; begin Result := reg_KeyDeleteW(AKey, UTF8ToUTF16(ASubKey)); end; function reg_KeyDeleteValue(AKey: HKey; const ASubKey: string): Boolean; begin Result := reg_KeyDeleteValueW(AKey, UTF8ToUTF16(ASubKey)); end; function reg_KeyExists(AKey: HKey; const ASubKey: string): Boolean; begin Result := reg_KeyExistsW(AKey, UTF8ToUTF16(ASubKey)); end; function reg_KeyValueExists(AKey: HKey; const AName: string): Boolean; begin Result := reg_KeyValueExistsW(AKey, UTF8ToUTF16(AName)); end; function reg_KeyGetValueType(const AKey: HKEY; const AName: string): DWORD; begin Result := reg_KeyGetValueTypeW(AKey, UTF8ToUTF16(AName)); end; function reg_KeyValueSize(AKey: HKey; const AName: string): Integer; begin Result := reg_KeyValueSizeW(AKey, UTF8ToUTF16(AName)); end; function reg_KeyGetString(AKey: HKey; const AName: string; const ADefault: string): string; begin Result := UTF16ToUTF8(reg_KeyGetStringW(AKey, UTF8ToUTF16(AName), UTF8ToUTF16(ADefault))); end; function reg_KeySetString(AKey: HKEY; const AName, AValue: string; AsExpand: Boolean): Boolean; begin Result := reg_KeySetStringW(AKey, UTF8ToUTF16(AName), UTF8ToUTF16(AValue), AsExpand); end; function reg_KeyGetDWord(AKey: HKey; const AName: string; ADefault: DWORD ): DWORD; begin Result := reg_KeyGetDWordW(AKey, UTF8ToUTF16(AName), ADefault); end; function reg_KeySetDWord(AKey: HKey; const AName: string; AValue: DWORD ): Boolean; begin Result := reg_KeySetDWordW(AKey, UTF8ToUTF16(AName), AValue); end; function reg_KeyGetBinary(AKey: HKey; const AName: string; var ABuffer; ACount: Integer): Integer; begin Result := reg_KeyGetBinaryW(AKey, UTF8ToUTF16(AName), ABuffer, ACount); end; function reg_KeySetBinary(AKey: HKey; const AName: string; const ABuffer; ACount: Integer): Boolean; begin Result := reg_KeySetBinaryW(AKey, UTF8ToUTF16(AName), ABuffer, ACount); end; function reg_KeyGetDateTime(AKey: HKey; const AName: string): TDateTime; begin Result := reg_KeyGetDateTimeW(AKey, UTF8ToUTF16(AName)); end; function reg_KeySetDateTime(AKey: HKey; const AName: string; ADateTime: TDateTime): Boolean; begin Result := reg_KeySetDateTimeW(AKey, UTF8ToUTF16(AName), ADateTime); end; function RegGetSubKeys(const ASubKey: string; AList: TStrings; AKey: HKey; AIsClearList: Boolean): Boolean; var Key: HKey; begin if reg_KeyOpenRead(ASubKey, Key, AKey) then begin Result := reg_KeyGetSubKeys(Key, AList, AIsClearList); reg_KeyClose(Key); end; end; function RegGetValueNames(const ASubKey: string; AList: TStrings; AIsAddValues: Boolean; AKey: HKey; AIsClearList: Boolean): Boolean; var Key: HKey; begin if reg_KeyOpenRead(ASubKey, Key, AKey) then begin Result := reg_KeyGetValueNames(Key, AList, AIsAddValues, AIsClearList); reg_KeyClose(Key); end; end; function GetProcessHandleFromHwnd(wnd: HWND): HANDLE; stdcall; begin if not Assigned(_GetProcessHandleFromHwnd) then begin _hlibOleacc := LoadLibrary('Oleacc.dll'); if _hlibOleacc <> 0 then begin _GetProcessHandleFromHwnd := GetProcAddress(_hlibOleacc, 'GetProcessHandleFromHwnd'); if not Assigned(_GetProcessHandleFromHwnd) then _GetProcessHandleFromHwnd := _GetProcessHandleFromHwndDummy; end; end; Result := _GetProcessHandleFromHwnd(wnd); end; type PHWND = ^HWND; TEnumWinsForPID = record pid: DWORD; wnd: PHWND; wndParam: HWND; end; PEnumWinsForPID = ^TEnumWinsForPID; function __OnEnumChildIsHwndBelongToPID(wnd: HWND; lp: LPARAM): WINBOOL; stdcall; var r: PEnumWinsForPID; begin Result := True; r := {%H-}PEnumWinsForPID(lp); if r^.wndParam = wnd then begin Result := False; r.wnd^ := r.wndParam; end else begin EnumChildWindows(wnd, __OnEnumChildIsHwndBelongToPID, lp); Result := r.wnd^ <> r.wndParam; end; end; function _OnEnumIsHwndBelongToPID(wnd: HWND; lp: LPARAM): WINBOOL; stdcall; var r: PEnumWinsForPID; pid: DWORD; begin Result := True; r := {%H-}PEnumWinsForPID(lp); GetWindowThreadProcessId(wnd, pid{%H-}); if (r^.pid = pid) then if (r^.wndParam = wnd) then begin Result := False; r.wnd^ := r.wndParam; end else begin EnumChildWindows(wnd, @__OnEnumChildIsHwndBelongToPID, lp); Result := r.wnd^ <> r.wndParam; end; end; function IsHwndBelongToPID(const AWnd: HWND; const pid: Cardinal): Boolean; var wnd: HWND; r: TEnumWinsForPID; begin wnd := 0; r.pid := pid; r.wnd := @wnd; r.wndParam := AWnd; EnumWindows(_OnEnumIsHwndBelongToPID, {%H-}LPARAM(@r)); Result := wnd = AWnd; //Result := HwndFromPID_1(wnd, pid); //if not Result then Exit; //Result := wnd = AWnd; //if Result then Exit; //r.pid := 0; //r.wnd := @AWnd; //EnumChildWindows(wnd, @_OnEnumIsHwndBelongToPID, LPARAM(@r)); //Result := (r.pid = 1); end; function _OnEnumWinsForPID(wnd: HWND; lp: LPARAM): WINBOOL; stdcall; var r: PEnumWinsForPID; pid: DWORD; begin Result := True; r := {%H-}PEnumWinsForPID(lp); GetWindowThreadProcessId(wnd, pid{%H-}); if r^.pid = pid then begin Result := False; r.wnd^ := wnd; end; end; function HwndFromPID(pid: Cardinal; out wnd: HWND): Boolean; var r: TEnumWinsForPID; begin wnd := 0; r.pid := pid; r.wnd := @wnd; r.wndParam := 0; EnumWindows(_OnEnumWinsForPID, {%H-}LPARAM(@r)); Result := wnd <> 0; end; {$IFNDEF JEDI_WINAPI} //JwaWinIOctl function CTL_CODE(DeviceType, Func, Method, Access: WORD): DWORD; begin Result := (DeviceType shl 16) or (Access shl 14) or (Func shl 2) or Method; end; {$ENDIF} finalization if _hlibOleacc <> 0 then FreeLibrary(_hlibOleacc); {$ENDIF WINDOWS} end.
unit ncFrmSuporteRem; { ResourceString: Dario 12/03/13 Nada para fazer } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, cxDropDownEdit, cxLabel, ExtCtrls, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxImageComboBox, ncClassesBase, ShellApi, registry, LMDControl, cxLookAndFeels, PngImage, LMDPNGImage; type TFrmSuporte = class(TForm) LMDSimplePanel1: TLMDSimplePanel; LMDSimplePanel2: TLMDSimplePanel; cxLabel1: TcxLabel; cxLabel2: TcxLabel; btnCancelar: TcxButton; btnOk: TcxButton; Image1: TImage; procedure btnOkClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCancelarClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private FRes: Boolean; { Private declarations } public { Public declarations } function ObterSuporte: Boolean; end; procedure ChamaSuporte(Nome, Obs: String; aAutomatize: Boolean = False); var FrmSuporte: TFrmSuporte; const Portas : Array[0..1] of Integer = (1975, 1974); implementation uses ncFrmDownSup; {$R *.dfm} procedure ChamaSuporte(Nome, Obs: String; aAutomatize: Boolean = False); //var R: TRegistry; begin { R := TRegistry.Create; try R.RootKey := HKEY_CURRENT_USER; R.Access := KEY_ALL_ACCESS; R.OpenKey('Software\LogMeInRescueCallingCard', True); try R.WriteString('CField0', Nome); finally R.CloseKey; end; R.OpenKey('Software\LogMeInRescueCallingCard', True); try R.WriteString('CField1', gConfig.CodLoja); finally R.CloseKey; end; R.OpenKey('Software\LogMeInRescueCallingCard', True); try R.WriteString('CField2', Obs); finally R.CloseKey; end; ShellExecute(0, 'open', 'CallingCard.exe', nil, PChar(ExtractFilePath(Application.ExeName)+'suporte\'), SW_SHOW); TdmLogmein.Create(nil); finally R.Free; end; } TFrmDownSup.Create(nil).Baixar(Nome, Obs, aAutomatize); end; { procedure ChamaSuporte(Porta: Integer); var CFG: TStringList; begin // Write simple configuration file for RemoteHost.exe // It is assumed that RemoteHost.exe is located in the same folder // with your application CFG := TStringList.Create; try CFG.Add('[RemoteHost]'); CFG.Add('User='+gConfig.CodLoja); CFG.Add('Address=suporte.nextar.com.br'); CFG.Add('Port='+IntToStr(Porta)); CFG.Add('AllowModify=0'); Cfg.Add('[MainForm]'); Cfg.Add('mnuEndSession.Caption=Finalizar Suporte'); Cfg.Add('cbxPorts.Visible=True'); Cfg.Add('Caption=Assistência Remota'); Cfg.Add('lblHelpDeskPort.Caption=Selecionar Técnico:'); Cfg.Add('lblHelpDeskAddr.Caption=Endereço:'); Cfg.Add('lblUsername.Caption=Loja'); Cfg.Add('btnConnect.Caption=OK'); Cfg.Add('btnCancel.Caption=Cancelar'); Cfg.Add('lblMessage.Left=42'); Cfg.Add('lblMessage.Width=373'); Cfg.Add('lblMessage.Caption=Solicitar Assistência Remota: Clique em OK para se conectar ao serviço de suporte técnico remoto da Nextar. Através dessa opção seu computador será controlado por um técnico que terá acesso total ao seu computador.'); Cfg.Add('[Messages]'); Cfg.Add('UnableToConnect=Não foi possível conectar ao suporte técnico da Nextar!'); CFG.SaveToFile( IncludeTRailingBackslash(ExtractFilePath(Application.ExeName)) + 'RemoteHost.cfg'); finally CFG.Free; end; ShellExecute(0, 'open', 'RemoteHost.exe', pchar('-silent'), PChar(ExtractFilePath(Application.ExeName)), SW_SHOW); end; } procedure TFrmSuporte.btnCancelarClick(Sender: TObject); begin Close; end; procedure TFrmSuporte.btnOkClick(Sender: TObject); begin FRes := True; Close; end; procedure TFrmSuporte.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmSuporte.FormKeyPress(Sender: TObject; var Key: Char); begin if Key=#27 then begin Key := #0; Close; end; end; function TFrmSuporte.ObterSuporte: Boolean; var I: Integer; begin ShowModal; Result := FRes; end; end.
unit uDAO.PessoaContato; interface uses System.SysUtils, System.Classes, FireDAC.Comp.Client, Data.DB, uDAO.Interfaces, uDB, uModel.Interfaces; type TPessoaContatoDAO = class(TInterfacedObject, iPessoaContatoDAO) private FQry: TFDQuery; function IsExist(pId: Integer): Boolean; public constructor Create; destructor Destroy; override; class function New: iPessoaContatoDAO; function Get(pIdPessoa: Integer; pList: iPessoaContatoList = nil): TDataSet; function Delete(pId, pIdPessoa: Integer): Boolean; function Save(pModel: iPessoaContatoModel): Boolean; end; implementation uses uModel.PessoaContato; { TPessoaContatoDAO } constructor TPessoaContatoDAO.Create; begin FQry := TFDQuery.Create(nil); FQry.Connection := TDB.getInstance.Conexao; end; destructor TPessoaContatoDAO.Destroy; begin FQry.Close; FreeAndNil(FQry); inherited; end; class function TPessoaContatoDAO.New: iPessoaContatoDAO; begin Result := Self.Create; end; function TPessoaContatoDAO.Delete(pId, pIdPessoa: Integer): Boolean; var Qry: TFDQuery; begin if (pIdPessoa = 0) and (pIdPessoa = 0) then begin Result := False; raise Exception.Create('Nenhum ID foi passado como parametro'); end; Result := True; Qry := TFDQuery.Create(nil); try Qry.Connection := TDB.getInstance.Conexao; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add('delete from PESSOACONTATO'); if pIdPessoa > 0 then begin Qry.SQL.Add('where ID = :ID'); Qry.ParamByName('ID').AsInteger := pIdPessoa; end; if pId > 0 then begin Qry.SQL.Add('where IDPESSOA = :IDPESSOA'); Qry.ParamByName('IDPESSOA').AsInteger := pId; end; try Qry.ExecSQL; except on E: Exception do begin Result := False; raise Exception.Create(E.Message); end; end; finally FreeAndNil(Qry); end; end; function TPessoaContatoDAO.Get(pIdPessoa: Integer; pList: iPessoaContatoList): TDataSet; begin FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('select * from PESSOACONTATO'); FQry.SQL.Add('where IDPESSOA = :IDPESSOA'); FQry.ParamByName('IDPESSOA').AsInteger := pIdPessoa; try FQry.Open; Result := FQry; if pList <> nil then begin FQry.First; while not FQry.Eof do begin pList.Add(TPessoaContatoModel.New .Id(FQry.FieldByName('ID').AsInteger) .IdPessoa(FQry.FieldByName('IDPESSOA').AsInteger) .Tipo(FQry.FieldByName('TIPO').AsString) .Contato(FQry.FieldByName('CONTATO').AsString) ); FQry.Next; end; end; except on E: Exception do raise Exception.Create(E.Message); end; end; function TPessoaContatoDAO.IsExist(pId: Integer): Boolean; var Qry: TFDQuery; begin Qry := TFDQuery.Create(nil); try Qry.Connection := TDB.getInstance.Conexao; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add('select 1 from PESSOACONTATO'); Qry.SQL.Add('where ID = :ID'); Qry.ParamByName('ID').AsInteger := pId; try Qry.Open; Result := not Qry.IsEmpty; except on E: Exception do raise Exception.Create(E.Message); end; finally FreeAndNil(Qry); end; end; function TPessoaContatoDAO.Save(pModel: iPessoaContatoModel): Boolean; var Qry: TFDQuery; IsInsert: Boolean; begin if (pModel = nil) then begin Result := False; raise Exception.Create('Nenhum contato foi passado como parametro'); end; Result := True; IsInsert := Self.IsExist(pModel.Id); Qry := TFDQuery.Create(nil); try Qry.Connection := TDB.getInstance.Conexao; Qry.Close; Qry.SQL.Clear; if not IsInsert then begin Qry.SQL.Add('insert into PESSOACONTATO ('); Qry.SQL.Add('IDPESSOA, TIPO, CONTATO) values ('); Qry.SQL.Add(':IDPESSOA, :TIPO, :CONTATO)'); Qry.SQL.Add('returns ID'); end else begin Qry.SQL.Add('update PESSOACONTATO set'); Qry.SQL.Add(' IDPESSOA =:IDPESSOA, TIPO =:TIPO, CONTATO =:CONTATO'); Qry.SQL.Add('where ID =:ID'); Qry.ParamByName('ID').AsInteger := pModel.Id; end; Qry.ParamByName('IDPESSOA').AsInteger := pModel.IdPessoa; Qry.ParamByName('TIPO').AsString := pModel.Tipo; Qry.ParamByName('CONTATO').AsString := pModel.Contato; try Qry.ExecSQL; except on E: Exception do begin Result := False; raise Exception.Create(E.Message); end; end; finally FreeAndNil(Qry); end; end; end.
unit ClassFaktury; interface uses Classes, ClassDBF, Typy, Math, Dialogs; type TFaktury = class private DBF1, DBF2, DBF3 : TDBF; Subor1, Subor2, Subor3 : string; function BinarySearch( iCislo : string ) : integer; protected procedure Nacitaj; public Zoznam : TList; SpolocnyText : TStringList; constructor Create( iS1, iS2, iS3 : string ); destructor Destroy; override; end; implementation //============================================================================== //============================================================================== // // Constrcutor // //============================================================================== //============================================================================== constructor TFaktury.Create( iS1, iS2, iS3 : string ); procedure QuickSortFaktury( iLeft, iRight : integer ); var I, J : integer; S : string; P : pointer; begin I := iLeft; J := iRight; S := TFaktura( Zoznam[(I + J) div 2]^ ).Cislo; repeat while TFaktura( Zoznam[I]^ ).Cislo < S do Inc( I ); while TFaktura( Zoznam[J]^ ).Cislo > S do Dec( J ); if I <= J then begin P := Zoznam[I]; Zoznam[I] := Zoznam[J]; Zoznam[J] := P; Inc(I); Dec(J); end; until I > J; if J > iLeft then QuickSortFaktury( iLeft , J ); if I < iRight then QuickSortFaktury( I , iRight ); end; begin inherited Create; SpolocnyText := TStringList.Create; Subor1 := iS1; Subor2 := iS2; Subor3 := iS3; Zoznam := TList.Create; DBF1 := TDBF.Create( Subor1 ); DBF2 := TDBF.Create( Subor2 ); DBF3 := TDBF.Create( Subor3 ); Nacitaj; QuickSortFaktury( 0 , Zoznam.Count-1 ); end; //============================================================================== //============================================================================== // // Destrcutor // //============================================================================== //============================================================================== destructor TFaktury.Destroy; var I, J : integer; begin for I := 0 to Zoznam.Count-1 do begin for J := 0 to TFaktura( Zoznam[I]^ ).Polozky.Count-1 do begin TPolozka( TFaktura( Zoznam[I]^ ).Polozky[J]^ ).Vyrobne.Free; Dispose( PPolozka( TFaktura( Zoznam[I]^ ).Polozky[J] ) ); end; TFaktura( Zoznam[I]^ ).Polozky.Free; TFaktura( Zoznam[I]^ ).Dodavatel.Adresa.Free; TFaktura( Zoznam[I]^ ).Odberatel.Adresa.Free; Dispose( PFaktura( Zoznam[I] ) ); end; Zoznam.Free; DBF1.Free; DBF2.Free; DBF3.Free; SpolocnyText.Free; inherited; end; //============================================================================== //============================================================================== // // Načítanie dát // //============================================================================== //============================================================================== function TFaktury.BinarySearch( iCislo : string ) : integer; var Found : boolean; First, Last : integer; Middle : integer; S : string; begin Middle := 0; Found := False; First := 1; Last := DBF1.Header.Records; while (First <= Last) and (not Found ) do begin Middle := (Last + First) div 2; S := DBF1.Cells( Middle , 2 ); if (iCislo = S) then Found := True else if (iCislo < S) then Last := Middle - 1 else First := Middle + 1; end; if Found then Result := Middle else Result := -1; end; procedure TFaktury.Nacitaj; var I, J, K : integer; PNewFaktura : PFaktura; PNewPolozka : PPolozka; Cislo : string; CisloPolozky : integer; Pole : array[1..10000] of string; begin for I := 1 to DBF3.Header.Records do Pole[I] := DBF3.Cells( I , 5 ); I := 1; while I < Integer( DBF2.Header.Records ) do begin Cislo := DBF2.Cells( I , 1 ); CisloPolozky := BinarySearch( Cislo ); //Alokacie pamate pre novu fakturu a jej inicializacia : New( PNewFaktura ); Zoznam.Add( PNewFaktura ); PNewFaktura^.Cislo := DBF1.Cells( CisloPolozky , 2 ); PNewFaktura^.Polozky := TList.Create; PNewFaktura^.Dodavatel.Adresa := TStringList.Create; PNewFaktura^.Odberatel.Adresa := TStringList.Create; with PNewFaktura^.Dodavatel.Adresa do begin Add( 'PC PROMPT, s. r. o.' ); Add( 'Bajkalská 27' ); Add( '821 01 Bratislava' ); end; PNewFaktura^.Dodavatel.ICO := '35688149'; PNewFaktura^.Odberatel.ICO := DBF1.Cells( CisloPolozky , 13 ); for J := 1 to DBF3.Header.Records do if PNewFaktura^.Odberatel.ICO = Pole[J] then begin K := 1; repeat PNewFaktura^.Odberatel.Adresa.Add( DBF3.Cells( J , K ) ); Inc( K ); until DBF3.Cells( J , K ) = ''; Break; end; //Pridanie poloziek k novej fakture : repeat New( PNewPolozka ); PNewFaktura^.Polozky.Add( PNewPolozka ); PNewPolozka^.Text := DBF2.Cells( I , 3 ); PNewPolozka^.J := DBF2.Cells( I , 4 ); PNewPolozka^.Mnozstvo := DBF2.Cells( I , 6 ); PNewPolozka^.Vyrobne := TStringList.Create; PNewPolozka^.Zaruka := '0'; Inc( I ); until (I > Integer( DBF2.Header.Records )) or (DBF2.Cells( I , 1 ) <> Cislo); end; end; //============================================================================== //============================================================================== // // Interface // //============================================================================== //============================================================================== end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit System.Win.Mtsobj; {$H+,X+} interface uses Winapi.Windows, System.Win.ComObj, Winapi.Mtx; type { TMtsAutoObject } TMtsAutoObject = class(TAutoObject, IObjectControl) private FObjectContext: IObjectContext; FCanBePooled: Boolean; protected { IObjectControl } procedure Activate; safecall; procedure Deactivate; stdcall; function CanBePooled: Bool; virtual; stdcall; procedure OnActivate; virtual; procedure OnDeactivate; virtual; property ObjectContext: IObjectContext read FObjectContext; public procedure SetComplete; procedure SetAbort; procedure EnableCommit; procedure DisableCommit; function IsInTransaction: Bool; function IsSecurityEnabled: Bool; function IsCallerInRole(const Role: WideString): Bool; property Pooled: Boolean read FCanBePooled write FCanBePooled; end; implementation procedure TMtsAutoObject.Activate; begin FObjectContext := GetObjectContext; OnActivate; end; procedure TMtsAutoObject.OnActivate; begin end; procedure TMtsAutoObject.Deactivate; begin OnDeactivate; FObjectContext := nil; end; procedure TMtsAutoObject.OnDeactivate; begin end; function TMtsAutoObject.CanBePooled: Bool; begin Result := FCanBePooled; end; procedure TMtsAutoObject.SetComplete; begin if Assigned(FObjectContext) then FObjectContext.SetComplete; end; procedure TMtsAutoObject.SetAbort; begin if Assigned(FObjectContext) then FObjectContext.SetAbort; end; procedure TMtsAutoObject.EnableCommit; begin if Assigned(FObjectContext) then FObjectContext.EnableCommit; end; procedure TMtsAutoObject.DisableCommit; begin if Assigned(FObjectContext) then FObjectContext.DisableCommit; end; function TMtsAutoObject.IsInTransaction: Bool; begin if Assigned(FObjectContext) then Result := FObjectContext.IsInTransaction else Result := False; end; function TMtsAutoObject.IsSecurityEnabled: Bool; begin if Assigned(FObjectContext) then Result := FObjectContext.IsSecurityEnabled else Result := False; end; function TMtsAutoObject.IsCallerInRole(const Role: WideString): Bool; begin if Assigned(FObjectContext) then Result := FObjectContext.IsCallerInRole(Role) else Result := False; end; end.
unit USubProgr; interface uses SysUtils; function CheckAllowed(const s: string): boolean; function IsValidEmail(const Value: string): boolean; Function russianQuoting(strForQuote:String):String; function CheckINN(const INN: string): Boolean; function CheckSNILS(const SNILS: string): Boolean; function Translit (const Str: string): string; implementation function CheckAllowed(const s: string): boolean; var i: integer; begin Result:= false; for i:= 1 to Length(s) do begin if not (s[i] in ['a'..'z', 'A'..'Z', '0'..'9', '_', '-', '.']) then Exit; end; Result:= true; end; function IsValidEmail(const Value: string): boolean; var i: integer; namePart, serverPart: string; begin Result:= false; i:= Pos('@', Value); if i = 0 then Exit; namePart:= Copy(Value, 1, i - 1); serverPart:= Copy(Value, i + 1, Length(Value)); if (Length(namePart) = 0) or ((Length(serverPart) < 5)) then Exit; i:= Pos('.', serverPart); if (i = 0) or (i > (Length(serverPart) - 2)) then Exit; Result:= CheckAllowed(namePart) and CheckAllowed(serverPart); end; function ReplaceStr(const S, Srch, Replace: string): string; {замена подстроки в строке} var I: Integer; Source: string; begin Source := S; Result := ''; repeat I := Pos(Srch, Source); if I >0 then begin Result := Result + Copy(Source, 1, I - 1) + Replace; Source := Copy(Source, I + Length(Srch), MaxInt); end else Result := Result + Source; until I<= 0; end; Function russianQuoting(strForQuote:string):string; begin //заменим кавычку с пробелом перед ней strForQuote:= ReplaceStr(strForQuote, '('+Chr(34)+Chr(34) , '('+Chr(34)+Chr(171) ); strForQuote:= ReplaceStr(strForQuote, Chr(34)+Chr(34)+')' , Chr(187)+Chr(34)+')' ); strForQuote:= ReplaceStr(strForQuote, ','+Chr(34)+Chr(34) , ','+Chr(34)+Chr(171) ); strForQuote:= ReplaceStr(strForQuote, Chr(34)+Chr(34)+',' , Chr(187)+Chr(34)+',' ); strForQuote:= ReplaceStr(strForQuote, ' '+Chr(34) , ' '+Chr(171) ); strForQuote:= ReplaceStr(strForQuote, Chr(34)+' ' , Chr(187)+' ' ); russianQuoting:= strForQuote; End; function OnlyDigits(const s: string): boolean; var i: integer; begin Result:= false; for i:= 1 to Length(s) do begin if not (s[i] in ['0'..'9']) then Exit; end; Result:= true; end; function CheckINN(const INN: string): Boolean; const factor1: array[0..8] of byte = (2, 4, 10, 3, 5, 9, 4, 6, 8); factor2: array[0..9] of byte = (7, 2, 4, 10, 3, 5, 9, 4, 6, 8); factor3: array[0..10] of byte = (3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8); var i: byte; sum: word; sum2: word; begin Result := False; if not OnlyDigits(INN) then exit; try if Length(INN) = 10 then begin sum := 0; for i := 0 to 8 do sum := sum + StrToInt(INN[i + 1]) * factor1[i]; sum := sum mod 11; sum := sum mod 10; Result := StrToInt(INN[10]) = sum; end else if Length(INN) = 12 then begin sum := 0; for i := 0 to 9 do sum := sum + StrToInt(INN[i + 1]) * factor2[i]; sum := sum mod 11; sum := sum mod 10; sum2 := 0; for i := 0 to 10 do sum2 := sum2 + StrToInt(INN[i + 1]) * factor3[i]; sum2 := sum2 mod 11; sum2 := sum2 mod 10; Result := (StrToInt(INN[11]) = sum) and (StrToInt(INN[12]) = sum2); end; // except Result := False; end; // try end; function CheckSNILS(const SNILS: string): Boolean; var sum: Word; i: Byte; begin Result := False; if not OnlyDigits(SNILS) then exit; sum := 0; if Length(SNILS) <> 11 then Exit; try for i := 1 to 9 do sum := sum + StrToInt(SNILS[i]) * (9 - i + 1); sum := sum mod 101; Result := StrToInt(Copy(SNILS, 10, 2)) = sum; except Result := False; end; // try end; function Translit (const Str: string): string; const RArrayL = 'абвгдеЄжзийклмнопрстуфхцчшщьыъэю€'; RArrayU = 'јЅ¬√ƒ≈®∆«»… ЋћЌќѕ–—“”‘’÷„Ўў№џЏЁёя'; colChar = 33; arr: array[1..2, 1..ColChar] of string = (('a', 'b', 'v', 'g', 'd', 'e', 'yo', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'kh', 'ts', 'ch', 'sh', 'shch', '''', 'y', '''', 'e', 'yu', 'ya'), ('A', 'B', 'V', 'G', 'D', 'E', 'Yo', 'Zh', 'Z', 'I', 'Y', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'Kh', 'Ts', 'Ch', 'Sh', 'Shch', '''', 'Y', '''', 'E', 'Yu', 'Ya')); var i: Integer; LenS: Integer; p: integer; d: byte; begin result := ''; LenS := length(str); for i := 1 to lenS do begin d := 1; p := pos(str[i], RArrayL); if p = 0 then begin p := pos(str[i], RArrayU); d := 2 end; if p <> 0 then result := result + arr[d, p] else result := result + str[i]; //если не русска€ буква, то берем исходную end; end; end.
{*******************************************************} { } { DelphiWebMVC } { } { °æÈ¨ËùÓÐ (C) 2019 ËÕÐËÓ­(PRSoft) } { } {*******************************************************} unit SessionList; interface uses System.SysUtils, System.Classes, System.IniFiles, System.Generics.Collections; type TSessionList = class SessionLs_vlue: TDictionary<string, string>; SessionLs_timerout: TDictionary<string, string>; public function getValueByKey(sessionid: string): string; function getTimeroutByKey(sessionid: string): string; function setValueByKey(sessionid: string; value: string): boolean; function setTimeroutByKey(sessionid: string; timerout: string): boolean; function deleteSession(key:string): boolean; constructor Create(); destructor Destroy; override; end; implementation uses Command; { TSessionList2 } constructor TSessionList.Create(); begin SessionLs_vlue := TDictionary<string, string>.Create; SessionLs_timerout := TDictionary<string, string>.Create; end; function TSessionList.deleteSession(key:string): boolean; begin Result := false; if SessionLs_timerout.Count > 0 then begin try SessionLs_timerout.Remove(key); if SessionLs_vlue.Count > 0 then begin SessionLs_vlue.Remove(key); end; Result := true; except Result := false; end; end; end; destructor TSessionList.Destroy; begin SessionLs_vlue.Clear; SessionLs_timerout.Clear; SessionLs_vlue.Free; SessionLs_timerout.Free; inherited; end; function TSessionList.getTimeroutByKey(sessionid: string): string; var s: string; begin SessionLs_timerout.TryGetValue(sessionid, s); Result := s; end; function TSessionList.getValueByKey(sessionid: string): string; var s: string; begin SessionLs_vlue.TryGetValue(sessionid, s); Result := s; end; function TSessionList.setTimeroutByKey(sessionid, timerout: string): boolean; begin SessionLs_timerout.AddOrSetValue(sessionid, timerout); end; function TSessionList.setValueByKey(sessionid, value: string): boolean; begin SessionLs_vlue.AddOrSetValue(sessionid, value); end; end.
{********************************************} { TeeOpenGL Component Registration } { Copyright (c) 1999-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeeOpenGLReg; {$I TeeDefs.inc} interface procedure Register; implementation Uses Classes, {$IFDEF D6} DesignIntf, DesignEditors, {$ELSE} DsgnIntf, {$ENDIF} TeeGLEditor, TeeOpenGL, TeeConst; type TTeeOpenGLCompEditor=class(TComponentEditor) public procedure ExecuteVerb( Index : Integer ); override; function GetVerbCount : Integer; override; function GetVerb( Index : Integer ) : string; override; end; { TTeeOpenGLCompEditor } procedure TTeeOpenGLCompEditor.ExecuteVerb( Index : Integer ); begin if Index<>0 then inherited ExecuteVerb(Index) else if EditTeeOpenGL(nil,Component as TTeeOpenGL) then Designer.Modified; end; function TTeeOpenGLCompEditor.GetVerbCount : Integer; begin Result := inherited GetVerbCount+1; end; function TTeeOpenGLCompEditor.GetVerb( Index : Integer ) : string; begin if Index=0 then result:=TeeMsg_Edit else result:=inherited GetVerb(Index); end; procedure Register; begin RegisterComponents(TeeMsg_TeeChartPalette,[TTeeOpenGL]); RegisterComponentEditor(TTeeOpenGL,TTeeOpenGLCompEditor); end; end.
unit intensive.Model.Entity.Cliente; interface uses SimpleAttributes; type [Tabela('CLIENTE')] TCliente = class private FId: Integer; FNome: String; FTelefone: String; procedure SetId(const Value: Integer); procedure SetNome(const Value: String); procedure SetTelefone(const Value: String); public [Campo('ID'), PK, AutoInc] property Id : Integer read FId write SetId; [Campo('NOME')] property Nome : String read FNome write SetNome; [Campo('TELEFONE')] property Telefone : String read FTelefone write SetTelefone; end; implementation { TCliente } procedure TCliente.SetId(const Value: Integer); begin FId := Value; end; procedure TCliente.SetNome(const Value: String); begin FNome := Value; end; procedure TCliente.SetTelefone(const Value: String); begin FTelefone := Value; end; end.
{ GS1 interface library for FPC and Lazarus Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit doc_list; {$mode objfpc}{$H+} interface uses Classes, SysUtils, JSONObjects, AbstractSerializationObjects; type { TDocumentDataDto } TDocumentDataDto = class(TJSONSerializationObject) private FDid: string; FEdoRecipient: string; FElr: Integer; FErrors: string; Fk_offset: Integer; Fk_partition: Integer; FOst: string; FReceiptId: TXSDStringArray; FSigningDate: Int64; FSignRecipientFio: string; FT: Integer; FTrn: Integer; procedure SetDid(AValue: string); procedure SetEdoRecipient(AValue: string); procedure SetElr(AValue: Integer); procedure SetErrors(AValue: string); procedure Setk_offset(AValue: Integer); procedure Setk_partition(AValue: Integer); procedure SetOst(AValue: string); procedure SetReceiptId(AValue: TXSDStringArray); procedure SetSigningDate(AValue: Int64); procedure SetSignRecipientFio(AValue: string); procedure SetT(AValue: Integer); procedure SetTrn(AValue: Integer); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public constructor Create; override; destructor Destroy; override; published property Ost:string read FOst write SetOst; property Trn:Integer read FTrn write SetTrn; property Errors:string read FErrors write SetErrors; property SigningDate : Int64 read FSigningDate write SetSigningDate; property SignRecipientFio:string read FSignRecipientFio write SetSignRecipientFio; property EdoRecipient:string read FEdoRecipient write SetEdoRecipient; property Did:string read FDid write SetDid; property T:Integer read FT write SetT; property k_offset:Integer read Fk_offset write Setk_offset; property k_partition:Integer read Fk_partition write Setk_partition; property Elr:Integer read FElr write SetElr; property ReceiptId:TXSDStringArray read FReceiptId write SetReceiptId; end; { TDocItem } TDocItem = class(TJSONSerializationObject) private FAType: string; FBody: string; FcisTotal: Integer; FContent: string; FDocDate: string; FDocErrors: string; FDocumentDataDto: TDocumentDataDto; FDownloadDesc: string; FDownloadStatus: string; FErrors: TXSDStringArray; FInput: Boolean; FInvoiceDate: string; FInvoiceNumber: string; FNumber: string; FPdfFile: string; FReceivedAt: string; FreceiverInn: string; FReceiverName: string; FsenderInn: string; FSenderName: string; FStatus: string; FTotal: Integer; FVat: Integer; function GetDocumentDate: TDateTime; function GetDocumentInvoiceDate: TDateTime; function GetDocumentReceivedAt: TDateTime; procedure SetAType(AValue: string); procedure SetBody(AValue: string); procedure SetcisTotal(AValue: Integer); procedure SetContent(AValue: string); procedure SetDocDate(AValue: string); procedure SetDocErrors(AValue: string); procedure SetDocumentDate(AValue: TDateTime); procedure SetDocumentInvoiceDate(AValue: TDateTime); procedure SetDocumentReceivedAt(AValue: TDateTime); procedure SetDownloadDesc(AValue: string); procedure SetDownloadStatus(AValue: string); procedure SetErrors(AValue: TXSDStringArray); procedure SetInput(AValue: Boolean); procedure SetInvoiceDate(AValue: string); procedure SetInvoiceNumber(AValue: string); procedure SetNumber(AValue: string); procedure SetPdfFile(AValue: string); procedure SetReceivedAt(AValue: string); procedure SetReceiverInn(AValue: string); procedure SetReceiverName(AValue: string); procedure SetSenderInn(AValue: string); procedure SetSenderName(AValue: string); procedure SetStatus(AValue: string); procedure SetTotal(AValue: Integer); procedure SetVat(AValue: Integer); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public destructor Destroy; override; constructor Create; override; property DocumentDate:TDateTime read GetDocumentDate write SetDocumentDate; property DocumentReceivedAt:TDateTime read GetDocumentReceivedAt write SetDocumentReceivedAt; property DocumentInvoiceDate:TDateTime read GetDocumentInvoiceDate write SetDocumentInvoiceDate; published property Number:string read FNumber write SetNumber; property DocDate:string read FDocDate write SetDocDate; property ReceivedAt:string read FReceivedAt write SetReceivedAt; property AType:string read FAType write SetAType; property Status:string read FStatus write SetStatus; //externalId property SenderName:string read FSenderName write SetSenderName; property SenderInn:string read FsenderInn write SetsenderInn; property ReceiverName:string read FReceiverName write SetReceiverName; property ReceiverInn:string read FreceiverInn write SetreceiverInn; property InvoiceNumber:string read FInvoiceNumber write SetInvoiceNumber; property InvoiceDate:string read FInvoiceDate write SetInvoiceDate; property Total:Integer read FTotal write SetTotal; property Vat:Integer read FVat write SetVat; property DownloadStatus:string read FDownloadStatus write SetDownloadStatus; property DownloadDesc:string read FDownloadDesc write SetDownloadDesc; property cisTotal:Integer read FcisTotal write SetcisTotal; property Body:string read FBody write SetBody; property Content:string read FContent write SetContent; property Input:Boolean read FInput write SetInput; property DocErrors:string read FDocErrors write SetDocErrors; property PdfFile:string read FPdfFile write SetPdfFile; property Errors:TXSDStringArray read FErrors write SetErrors; //atk //sender property DocumentDataDto:TDocumentDataDto read FDocumentDataDto; end; TDocItemList = specialize GXMLSerializationObjectList<TDocItem>; { TDocItems } TDocItems = class(TJSONSerializationObject) private FResults: TDocItemList; FTotal: Integer; procedure SetTotal(AValue: Integer); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public constructor Create; override; destructor Destroy; override; published property Results:TDocItemList read FResults; property Total:Integer read FTotal write SetTotal; end; implementation uses sdo_date_utils, DateUtils; { TDocItems } procedure TDocItems.SetTotal(AValue: Integer); begin if FTotal=AValue then Exit; FTotal:=AValue; ModifiedProperty('Total'); end; procedure TDocItems.InternalRegisterPropertys; begin inherited InternalRegisterPropertys; RegisterProperty('Results', 'results', [], '', -1, -1); RegisterProperty('Total', 'total', [], '', -1, -1); end; procedure TDocItems.InternalInitChilds; begin inherited InternalInitChilds; FResults:=TDocItemList.Create; end; constructor TDocItems.Create; begin inherited Create; FIgnoreReadUndefProps:=true; end; destructor TDocItems.Destroy; begin FreeAndNil(FResults); inherited Destroy; end; { TDocItem } procedure TDocItem.SetAType(AValue: string); begin if FAType=AValue then Exit; FAType:=AValue; ModifiedProperty('AType'); end; function TDocItem.GetDocumentDate: TDateTime; var R: TDateTimeRec; begin if xsd_TryStrToDate(FDocDate, R, xdkDateTime) then Result:=NormalizeToUTC(R); end; function TDocItem.GetDocumentInvoiceDate: TDateTime; var R: TDateTimeRec; begin // Result:=UnixToDateTime(FInvoiceDate div 1000); if xsd_TryStrToDate(FDocDate, R, xdkDateTime) then Result:=NormalizeToUTC(R); end; function TDocItem.GetDocumentReceivedAt: TDateTime; var R: TDateTimeRec; begin if xsd_TryStrToDate(FReceivedAt, R, xdkDateTime) then Result:=NormalizeToUTC(R); end; procedure TDocItem.SetBody(AValue: string); begin if FBody=AValue then Exit; FBody:=AValue; ModifiedProperty('Body'); end; procedure TDocItem.SetcisTotal(AValue: Integer); begin if FcisTotal=AValue then Exit; FcisTotal:=AValue; ModifiedProperty('cisTotal'); end; procedure TDocItem.SetContent(AValue: string); begin if FContent=AValue then Exit; FContent:=AValue; ModifiedProperty('Content'); end; procedure TDocItem.SetDocDate(AValue: string); begin if FDocDate=AValue then Exit; FDocDate:=AValue; ModifiedProperty('DocDate'); end; procedure TDocItem.SetDocErrors(AValue: string); begin if FDocErrors=AValue then Exit; FDocErrors:=AValue; ModifiedProperty('DocErrors'); end; procedure TDocItem.SetDocumentDate(AValue: TDateTime); begin // end; procedure TDocItem.SetDocumentInvoiceDate(AValue: TDateTime); begin end; procedure TDocItem.SetDocumentReceivedAt(AValue: TDateTime); begin end; procedure TDocItem.SetDownloadDesc(AValue: string); begin if FDownloadDesc=AValue then Exit; FDownloadDesc:=AValue; ModifiedProperty('DownloadDesc'); end; procedure TDocItem.SetDownloadStatus(AValue: string); begin if FDownloadStatus=AValue then Exit; FDownloadStatus:=AValue; ModifiedProperty('DownloadStatus'); end; procedure TDocItem.SetErrors(AValue: TXSDStringArray); begin if FErrors=AValue then Exit; FErrors:=AValue; ModifiedProperty('Errors'); end; procedure TDocItem.SetInput(AValue: Boolean); begin if FInput=AValue then Exit; FInput:=AValue; ModifiedProperty('Input'); end; procedure TDocItem.SetInvoiceDate(AValue: string); begin if FInvoiceDate=AValue then Exit; FInvoiceDate:=AValue; ModifiedProperty('InvoiceDate'); end; procedure TDocItem.SetInvoiceNumber(AValue: string); begin if FInvoiceNumber=AValue then Exit; FInvoiceNumber:=AValue; ModifiedProperty('InvoiceNumber'); end; procedure TDocItem.SetNumber(AValue: string); begin if FNumber=AValue then Exit; FNumber:=AValue; ModifiedProperty('Number'); end; procedure TDocItem.SetPdfFile(AValue: string); begin if FPdfFile=AValue then Exit; FPdfFile:=AValue; ModifiedProperty('PdfFile'); end; procedure TDocItem.SetReceivedAt(AValue: string); begin if FReceivedAt=AValue then Exit; FReceivedAt:=AValue; ModifiedProperty('ReceivedAt'); end; procedure TDocItem.SetreceiverInn(AValue: string); begin if FreceiverInn=AValue then Exit; FreceiverInn:=AValue; ModifiedProperty('receiverInn'); end; procedure TDocItem.SetReceiverName(AValue: string); begin if FreceiverName=AValue then Exit; FReceiverName:=AValue; ModifiedProperty('ReceiverName'); end; procedure TDocItem.SetSenderInn(AValue: string); begin if FsenderInn=AValue then Exit; FsenderInn:=AValue; ModifiedProperty('SenderInn'); end; procedure TDocItem.SetSenderName(AValue: string); begin if FSenderName=AValue then Exit; FSenderName:=AValue; ModifiedProperty('SenderName'); end; procedure TDocItem.SetStatus(AValue: string); begin if FStatus=AValue then Exit; FStatus:=AValue; ModifiedProperty('Status'); end; procedure TDocItem.SetTotal(AValue: Integer); begin if FTotal=AValue then Exit; FTotal:=AValue; ModifiedProperty('Total'); end; procedure TDocItem.SetVat(AValue: Integer); begin if FVat=AValue then Exit; FVat:=AValue; ModifiedProperty('Vat'); end; procedure TDocItem.InternalRegisterPropertys; begin inherited InternalRegisterPropertys; RegisterProperty('Number', 'number', [], '', -1, -1); RegisterProperty('DocDate', 'docDate', [], '', -1, -1); RegisterProperty('ReceivedAt', 'receivedAt', [], '', -1, -1); RegisterProperty('AType', 'type', [], '', -1, -1); RegisterProperty('Status', 'status', [], '', -1, -1); RegisterProperty('SenderName', 'senderName', [], '', -1, -1); RegisterProperty('SenderInn', 'senderInn', [], '', -1, -1); RegisterProperty('ReceiverInn', 'receiverInn', [], '', -1, -1); RegisterProperty('ReceiverName', 'receiverName', [], '', -1, -1); RegisterProperty('InvoiceNumber', 'invoiceNumber', [], '', -1, -1); RegisterProperty('InvoiceDate', 'invoiceDate', [], '', -1, -1); RegisterProperty('Total', 'total', [], '', -1, -1); RegisterProperty('Vat', 'vat', [], '', -1, -1); RegisterProperty('Body', 'body', [], '', -1, -1); RegisterProperty('DownloadStatus', 'downloadStatus', [], '', -1, -1); RegisterProperty('DownloadDesc', 'downloadDesc', [], '', -1, -1); RegisterProperty('cisTotal', 'cisTotal', [], '', -1, -1); RegisterProperty('Content', 'content', [], '', -1, -1); RegisterProperty('Input', 'input', [], '', -1, -1); RegisterProperty('PdfFile', 'pdfFile', [], '', -1, -1); RegisterProperty('Errors', 'errors', [], '', -1, -1); RegisterProperty('DocErrors', 'docErrors', [], '', -1, -1); RegisterProperty('DocumentDataDto', 'documentDataDto', [], '', -1, -1); end; procedure TDocItem.InternalInitChilds; begin inherited InternalInitChilds; FDocumentDataDto:=TDocumentDataDto.Create; end; destructor TDocItem.Destroy; begin FreeAndNil(FDocumentDataDto); inherited Destroy; end; constructor TDocItem.Create; begin inherited Create; FIgnoreReadUndefProps:=true; end; { TDocumentDataDto } procedure TDocumentDataDto.SetEdoRecipient(AValue: string); begin if FEdoRecipient=AValue then Exit; FEdoRecipient:=AValue; ModifiedProperty('EdoRecipient'); end; procedure TDocumentDataDto.SetElr(AValue: Integer); begin if FElr=AValue then Exit; FElr:=AValue; ModifiedProperty('Elr'); end; procedure TDocumentDataDto.SetDid(AValue: string); begin if FDid=AValue then Exit; FDid:=AValue; ModifiedProperty('Did'); end; procedure TDocumentDataDto.SetErrors(AValue: string); begin if FErrors=AValue then Exit; FErrors:=AValue; ModifiedProperty('Errors'); end; procedure TDocumentDataDto.Setk_offset(AValue: Integer); begin if Fk_offset=AValue then Exit; Fk_offset:=AValue; ModifiedProperty('k_offset'); end; procedure TDocumentDataDto.Setk_partition(AValue: Integer); begin if Fk_partition=AValue then Exit; Fk_partition:=AValue; ModifiedProperty('k_partition'); end; procedure TDocumentDataDto.SetOst(AValue: string); begin if FOst=AValue then Exit; FOst:=AValue; ModifiedProperty('Ost'); end; procedure TDocumentDataDto.SetReceiptId(AValue: TXSDStringArray); begin if FReceiptId=AValue then Exit; FReceiptId:=AValue; ModifiedProperty('ReceiptId'); end; procedure TDocumentDataDto.SetSigningDate(AValue: Int64); begin if FSigningDate=AValue then Exit; FSigningDate:=AValue; ModifiedProperty('SigningDate'); end; procedure TDocumentDataDto.SetSignRecipientFio(AValue: string); begin if FSignRecipientFio=AValue then Exit; FSignRecipientFio:=AValue; ModifiedProperty('SignRecipientFio'); end; procedure TDocumentDataDto.SetT(AValue: Integer); begin if FT=AValue then Exit; FT:=AValue; ModifiedProperty('T'); end; procedure TDocumentDataDto.SetTrn(AValue: Integer); begin if FTrn=AValue then Exit; FTrn:=AValue; ModifiedProperty('Trn'); end; procedure TDocumentDataDto.InternalRegisterPropertys; begin inherited InternalRegisterPropertys; RegisterProperty('Ost', 'ost', [], '', -1, -1); RegisterProperty('Trn', 'trn', [], '', -1, -1); RegisterProperty('Errors', 'errors', [], '', -1, -1); RegisterProperty('SigningDate', 'signingDate', [], '', -1, -1); RegisterProperty('SignRecipientFio', 'signRecipientFio', [], '', -1, -1); RegisterProperty('EdoRecipient', 'edoRecipient', [], '', -1, -1); RegisterProperty('Did', 'did', [], '', -1, -1); RegisterProperty('T', 't', [], '', -1, -1); RegisterProperty('k_offset', 'k_offset', [], '', -1, -1); RegisterProperty('k_partition', 'k_partition', [], '', -1, -1); RegisterProperty('Elr', 'elr', [], '', -1, -1); RegisterProperty('ReceiptId', 'receiptId', [], '', -1, -1); end; procedure TDocumentDataDto.InternalInitChilds; begin inherited InternalInitChilds; end; constructor TDocumentDataDto.Create; begin inherited Create; FIgnoreReadUndefProps:=true; end; destructor TDocumentDataDto.Destroy; begin inherited Destroy; end; end.
unit NvPing; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask; type TPingDialog = class(TForm) btnStart: TButton; btnCancel: TButton; GroupBox: TGroupBox; lblBytes: TLabel; lblNumber: TLabel; lblTimeOut: TLabel; edtBytes: TMaskEdit; edtNumber: TMaskEdit; edtTimeOut: TMaskEdit; chkFragment: TCheckBox; lblResults: TLabel; Memo: TMemo; procedure FormShow(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); private { Private declarations } FComputerName: string; FIpAddress: string; FCancel: Boolean; public { Public declarations } property ComputerName: string read FComputerName write FComputerName; property IpAddress: string read FIpAddress write FIpAddress; end; procedure ShowPingDialog(AOwner: TComponent; const AComputerName, AIpAddress: string); var PingDialog: TPingDialog; implementation uses NvConst, Icmp, WinSock; {$R *.dfm} var IcmpHandle: THandle; procedure ShowPingDialog(AOwner: TComponent; const AComputerName, AIpAddress: string); begin with TPingDialog.Create(AOwner) do try FComputerName := AComputerName; FIpAddress := AIpAddress; ShowModal; finally Free; end; end; procedure TPingDialog.FormShow(Sender: TObject); begin Caption := Format(SPingDlgCaption, [FComputerName]); end; procedure TPingDialog.btnStartClick(Sender: TObject); var BufferSize, TimeOut, EchoCount, RetVal, i: Integer; IpOpt: TIPOptionInformation; PingBuffer: Pointer; pIpe: PIcmpEchoReply; TimeStr: string; begin if IcmpHandle = INVALID_HANDLE_VALUE then begin Memo.Lines.Add(SInitErr); Exit; end; BufferSize := StrToInt(Trim(edtBytes.Text)); if (BufferSize < 1) or (BufferSize > 65500) then begin BufferSize := 32; edtBytes.Text := IntToStr(BufferSize); end; EchoCount := StrToInt(Trim(edtNumber.Text)); if EchoCount < 1 then begin EchoCount := 4; edtNumber.Text := IntToStr(EchoCount); end; TimeOut := StrToInt(Trim(edtTimeOut.Text)); if TimeOut < 1 then begin TimeOut := 1000; edtTimeout.Text := IntToStr(TimeOut); end; with IpOpt do begin Ttl := 32; Tos := 0; if chkFragment.Checked then Flags := IP_FLAG_DF else Flags := 0; OptionsSize := 0; OptionsData := nil; end; GetMem(pIpe, SizeOf(TICMPEchoReply) + BufferSize); GetMem(PingBuffer, BufferSize); try FillChar(PingBuffer^, BufferSize, $AA); pIpe^.Data := PingBuffer; if Memo.Lines.Count > 100 then begin Memo.Lines.BeginUpdate; Memo.Lines.Delete(0); Memo.Lines.EndUpdate; end; Memo.Lines.Add(Format(SPinging, [FComputerName, FIpAddress, BufferSize])); for i := 0 to EchoCount - 1 do begin Application.ProcessMessages; if FCancel then Break; RetVal := IcmpSendEcho(IcmpHandle, inet_addr(PChar(FIpAddress)), PingBuffer, BufferSize, @IpOpt, pIpe, SizeOf(TICMPEchoReply) + BufferSize, TimeOut); if RetVal = 0 then begin RetVal := GetLastError; case RetVal of IP_REQ_TIMED_OUT: Memo.Lines.Add(SReqTimedOut); IP_PACKET_TOO_BIG: Memo.Lines.Add(SPacketTooBig); else Memo.Lines.Add(Format(SErrorCode, [RetVal])); end; Sleep(1000); Continue; end; if pIpe^.RoundTripTime < 1 then TimeStr := '<10' else TimeStr := '=' + IntToStr(pIpe^.RoundTripTime); Memo.Lines.Add(Format(SReply, [inet_ntoa(TInAddr(pIpe^.Address)), pIpe^.DataSize, TimeStr, pIpe^.Options.Ttl])); Sleep(1000); end; Memo.Lines.Add(''); finally FreeMem(pIpe); FreeMem(PingBuffer); end; end; procedure TPingDialog.btnCancelClick(Sender: TObject); begin FCancel := True; end; initialization IcmpHandle := IcmpCreateFile; finalization if IcmpHandle <> INVALID_HANDLE_VALUE then IcmpCloseHandle(IcmpHandle); end.
unit Module.ValueObject.StringVO.Impl; interface uses Module.ValueObject.StringVO; type TStringVO = class(TInterfacedObject, IStringVO) private FString: string; public constructor Create(const AString: string); virtual; function AsString: string; end; implementation function TStringVO.AsString: string; begin Result := FString; end; constructor TStringVO.Create(const AString: string); begin FString := AString; end; end.
unit frm_collection_item; {============================================================================== UnitName = frm_collection_item ============================================================================== } {$mode objfpc}{$H+} interface uses Forms, Classes, Buttons, Controls, ExtCtrls, StdCtrls, LResources, ComCtrls, u_xpl_collection, ActnList, RTTICtrls; type { TfrmCollIItem } TfrmCollIItem = class(TForm) ActionList: TActionList; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; lblVendor: TLabel; lblBuildDate: TLabel; acClose: TAction; tbLaunch: TToolButton; tieDisplayName: TTIEdit; tieValue: TTIEdit; tieComment: TTIEdit; tieCreateTS: TTILabel; tieModifyTs: TTILabel; ToolBar: TToolBar; ToolButton2: TToolButton; procedure acCloseExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); end; procedure ShowFrmCollIItem(aItem : TxPLCollectionItem); implementation // ============================================================== uses SysUtils , Graphics , u_xpl_gui_resource ; var frmCollIItem: TfrmCollIItem; procedure ShowFrmCollIItem(aItem: TxPLCollectionItem); begin if not Assigned(frmCollIItem) then Application.CreateForm(TfrmCollIItem, frmCollIItem); frmCollIItem.tieDisplayName.Link.TIObject := aItem; frmCollIItem.tieDisplayName.Link.TIPropertyName := 'DisplayName'; frmCollIItem.tieValue.Link.TIObject := aItem; frmCollIItem.tieValue.Link.TIPropertyName := 'Value'; frmCollIItem.tieComment.Link.TIObject := aItem; frmCollIItem.tieComment.Link.TIPropertyName := 'Comment'; frmCollIItem.tieCreateTS.Link.TIObject := aItem; frmCollIItem.tieCreateTS.Link.TIPropertyName := 'CreateTS'; frmCollIItem.tieModifyTs.Link.TIObject := aItem; frmCollIItem.tieModifyTs.Link.TIPropertyName := 'ModifyTS'; frmCollIItem.ShowModal; end; // ============================================================================= procedure TfrmCollIItem.FormCreate(Sender: TObject); begin Toolbar.Images := xPLGUIResource.Images; end; procedure TfrmCollIItem.FormShow(Sender: TObject); begin end; procedure TfrmCollIItem.acCloseExecute(Sender: TObject); begin Close; end; initialization // ============================================================== {$I frm_collection_item.lrs} end.
//////////////////////////////////////////// // Класс для разбора и хранения блока данных от приборов Геомер //////////////////////////////////////////// unit GMBlockValues; interface uses Windows, Classes, SysUtils, GMGlobals, DateUtils, GMConst; const GEOMER_WITH_UBZ_BLOCK_LEN = 38; GEOMER_WITH_UBZ_DEVICE_LEN = 18; type TGeomerBlockType = (gbtUnknown, gbtShort, gbtLong, gbtLongUBZ, gbtLongISCO, gbt485); TGMUBZData = record Address: byte; // 0 - адрес УБЗ в сети 485 CommStatus: byte; // 1 – флаги состояния связи с УБЗ Current: Word; // 2 - усредненный фазный ток по 3м фазам Voltage: Word; // 4 – усредненное линейное напряжение по 3м фазам, В Power: double; // 14 – активная мощность, десятки Вт AlarmState: ULONG; // регистры аварий 901 и 902 end; TGeomerBlockValues = class private FTraced: bool; FgmBufRec: ArrayOfByte; function GetDT: TDateTime; function GetDI(i: int): byte; function GetDO(i: int): byte; procedure Trace(buf: array of byte; cnt: int); procedure ReadBaseData(buf: array of byte); function GetBufRecString: AnsiString; function GetLenRec: int; procedure ReadLongDataWithUBZ_ReadUBZData(buf: array of byte; n: int); protected function NeedTrace(): bool; virtual; public gbt: TGeomerBlockType; ReqDetails: TRequestDetails; AllDI: Byte; AllDO: Byte; AI: array [0..3] of double; // анальные нумеруются с 0 // анальный 0 - это температура внутри корпуса прибора DIC: array[1..5] of int; // счетчики с единицы LE: double; // уровень в м, 4 байта: длинное целое младшим байтом вперед, для получения уровня в м разделить на 100 000. VE: double; // - скорость в м/с, 4 байта: длинное целое младшим байтом вперед, для получения скорости в м/c разделить на 10 000. FL: double; // - расход в м3/c, 4 байта: длинное целое младшим байтом вперед, для получения расхода разделить на 1 000 000 VO: double; // - объем в м3, 4 байта: длинное целое младшим байтом вперед, для получения объема разделить на 10. gmTime, iscoTime: UINT; moneyLeft: int; ubzList: array[0..7] of TGMUBZData; ubzCount: int; property gmBufRec: ArrayOfByte read FgmBufRec; property gmLenRec: int read GetLenRec; property DT: TDateTime read GetDT; property DI[i: int]: byte read GetDI; property DOut[i: int]: byte read GetDO; property BufRecString: AnsiString read GetBufRecString; procedure ReadShortData(buf: array of byte); procedure ReadLongData(buf: array of byte); procedure ReadLongDataWithISCO(buf: array of byte); procedure ReadLongDataWithUBZ(buf: array of byte); procedure Read485(const buf: array of byte; cnt: int); constructor Create; overload; procedure SetBufRec(const bufRec: array of byte; cnt: int = -1); overload; procedure SetBufRec(const s: AnsiString); overload; function ToString(): string; override; end; implementation uses Forms, Math, ProgramLogFile; { TGeomerBlockValues } procedure TGeomerBlockValues.Trace(buf: array of byte; cnt: int); var f: TFileStream; path: string; fname: string; n: int; begin if FTraced or (cnt <= 0) or not NeedTrace() then Exit; path := IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName)) + 'trace\'; if not ForceDirectories(path) then Exit; try fname := path + IntToStr(ReqDetails.N_Car) + '_' + IntToStr(gmTime) + '_'; n := 1; while FileExists(fname + IntToStr(n) + '.gbv') do inc(n); fname := fname + IntToStr(n) + '.gbv'; f := nil; try f := TFileStream.Create(fname, fmCreate); f.Write(buf, cnt); except end; if f <> nil then f.Free(); except end; FTraced := true; end; function TGeomerBlockValues.GetDI(i: int): byte; var n: byte; begin Result:=0; if i in [0..7] then begin n:=1 shl i; if (AllDI and n)>0 then Result:=1; end; end; function TGeomerBlockValues.GetDO(i: int): byte; var n: byte; begin Result:=0; if i in [0..7] then begin n:=1 shl i; if (AllDO and n)>0 then Result:=1; end; end; function TGeomerBlockValues.GetDT: TDateTime; begin Result := UTCtoLocal(gmTime); end; function TGeomerBlockValues.GetLenRec: int; begin Result := Length(FgmBufRec); end; procedure TGeomerBlockValues.ReadBaseData(buf: array of byte); begin ReqDetails.N_Car := ReadWord(buf, 2); gmTime := ReadUINT(buf, 4); end; procedure TGeomerBlockValues.ReadShortData(buf: array of byte); begin // общая часть короткого и длинного ответов ReadBaseData(buf); Trace(buf, 24); gbt := gbtShort; AllDI := buf[16]; AllDO := buf[17]; AI[0] := (ReadWord(buf, 18) * 2.5 / 1023.0 - 0.444) / 0.00625; // сразу в градусы AI[1] := ReadWord(buf, 20) * 5 / 1023.0; AI[2] := ReadWord(buf, 22) * 5 / 1023.0; AI[3] := 0; end; procedure TGeomerBlockValues.ReadLongData(buf: array of byte); begin ReadBaseData(buf); Trace(buf, 46); ReadShortData(buf); gbt := gbtLong; // счетчики DIC[1] := ReadWord(buf, 24); DIC[2] := ReadWord(buf, 26); DIC[3] := ReadWord(buf, 28); DIC[4] := ReadWord(buf, 30); // вместо 5го счетчика импульсов - 3й анальный вход AI[3] := ReadWord(buf, 32) * 32 / 1023.0; end; procedure TGeomerBlockValues.ReadLongDataWithISCO(buf: array of byte); begin ReadBaseData(buf); Trace(buf, 90); ReadLongData(buf); gbt := gbtLongISCO; iscoTime := ReadUINT(buf, 50); LE := ReadUINT(buf, 54) / 100000.0; // уровень в м, 4 байта: длинное целое младшим байтом вперед, для получения уровня в м разделить на 100 000. VE := ReadUINT(buf, 58) / 10000.0; // - скорость в м/с, 4 байта: длинное целое младшим байтом вперед, для получения скорости в м/c разделить на 10 000. FL := ReadUINT(buf, 62) / 1000000.0 * 3600; // - расход в м3/c, 4 байта: длинное целое младшим байтом вперед, для получения расхода разделить на 1 000 000 VO := ReadUINT(buf, 66) / 10.0; // - объем в м3, 4 байта: длинное целое младшим байтом вперед, для получения объема разделить на 10. end; procedure TGeomerBlockValues.ReadLongDataWithUBZ_ReadUBZData(buf: array of byte; n: int); var ubzStart: int; begin ubzStart := GEOMER_WITH_UBZ_BLOCK_LEN + GEOMER_WITH_UBZ_DEVICE_LEN * n; ubzList[n].Address := buf[ubzStart]; // 0 - адрес УБЗ в сети 485 ubzList[n].CommStatus := buf[ubzStart + 1]; // 1 – флаги состояния связи с УБЗ ubzList[n].Current := ReadWord(buf, ubzStart + 2); // 2 - усредненный фазный ток по 3м фазам ubzList[n].Voltage := ReadWord(buf, ubzStart + 4); // 4 – усредненное линейное напряжение по 3м фазам, В ubzList[n].Power := ReadUINT(buf, ubzStart + 6) / 100.0; // 6 – активная мощность, десятки Вт, переводим в КВт ubzList[n].AlarmState := ReadWordInv(buf, ubzStart + 14) + (ReadWordInv(buf, ubzStart + 16) shl 16); // 14 - регистры аварий 901 и 902 end; procedure TGeomerBlockValues.ReadLongDataWithUBZ(buf: array of byte); var i: int; begin ReadBaseData(buf); ubzCount := ReadWord(buf, 36); Trace(buf, GEOMER_WITH_UBZ_BLOCK_LEN + ubzCount * GEOMER_WITH_UBZ_DEVICE_LEN); ReadLongData(buf); gbt := gbtLongUBZ; moneyLeft := ReadWord(buf, 34); for i := 0 to ubzCount - 1 do ReadLongDataWithUBZ_ReadUBZData(buf, i); end; procedure TGeomerBlockValues.Read485(const buf: array of byte; cnt: int); var lenRec: int; var i: int; begin if cnt < buf[3] + 4 then Exit; // посылка битая lenRec := buf[3]; Trace(buf, lenRec + 4); gmTime := NowGM(); gbt := gbt485; SetLength(FgmBufRec, lenRec); for i := 0 to lenRec - 1 do FgmBufRec[i] := buf[i + 4]; end; constructor TGeomerBlockValues.Create; var i: int; begin inherited; ReqDetails.Init(); iscoTime := 0; FTraced := false; moneyLeft := 0; ubzCount := 0; for i := 0 to high(ubzList) do ZeroMemory(@(ubzList[i]), SizeOf(TGMUBZData)); end; function TGeomerBlockValues.NeedTrace: bool; begin Result := FindCmdLineSwitch('trace', ['-'], true); end; function TGeomerBlockValues.GetBufRecString: AnsiString; var i: int; begin SetLength(Result, gmLenRec); for i := 1 to gmLenRec do Result[i] := AnsiChar(gmBufRec[i - 1]); end; procedure TGeomerBlockValues.SetBufRec(const bufRec: array of byte; cnt: int = -1); begin if cnt < 0 then cnt := Length(bufRec); SetLength(FgmBufRec, cnt); WriteBuf(FgmBufRec, 0, bufRec, cnt); end; procedure TGeomerBlockValues.SetBufRec(const s: AnsiString); begin SetLength(FgmBufRec, Length(s)); WriteString(FgmBufRec, 0, s); end; function TGeomerBlockValues.ToString: string; begin Result := Format('N_Car %d DevNumber %d rqtp %s ID_Obj %d ID_Device %d ID_DevType %d ID_Prm %d ', [ReqDetails.N_Car, ReqDetails.DevNumber, ReqDetails.rqtp.ToString(), ReqDetails.ID_Obj, ReqDetails.ID_Device, ReqDetails.ID_DevType, ReqDetails.ID_Prm]) + 'buffer ' + ArrayToString(FgmBufRec, GetLenRec, true, true); end; end.
{ SMIX is Copyright 1995 by Ethan Brodsky. All rights reserved. } unit SMix; {Version 1.25} {$X+} {$G+} {$R-} interface const BlockLength = 512; {Size of digitized sound block } LoadChunkSize = 2048; {Chunk size used for loading sounds from disk} Voices = 8; {Number of available voices } SamplingRate = 22025; {Sampling rate for output } type PSound = ^TSound; TSound = record XMSHandle: word; StartOfs: LongInt; SoundSize: LongInt; end; function InitSB(BaseIO: word; IRQ: byte; DMA, DMA16: byte): boolean; {Initializes control parameters, resets DSP, and installs int. handler } { Parameters: (Can be found using GetSettings procedure in Detect) } { BaseIO: Sound card base IO address } { IRQ: Sound card IRQ setting } { DMA: Sound card 8-bit DMA channel } { DMA16: Sound card 16-bit DMA channel (0 if not supported) } { Returns: } { TRUE: Sound card successfully initialized (Maybe) } { FALSE: Sound card could not be initialized } procedure ShutdownSB; {Removes interrupt handler and resets DSP } procedure InitMixing; {Allocates internal buffers and starts digitized sound output } procedure ShutdownMixing; {Deallocates internal buffers and stops digitized sound output } function InitXMS: boolean; {Attempts to intialize extended memory } { Returns: } { TRUE: Extended memory successfully initialized } { FALSE: Extended memory could not be initialized } function GetFreeXMS: word; {Returns amount of free XMS memory (In kilobytes) } procedure InitSharing; {Allocates an EMB that all sounds are stored in. This preserves EMB } {handles, which are a scarce resource. Call this on initialization and} {all sounds will automatically be stored in one EMB. Call LoadSound as} {usual to allocate a sound, but FreeSound only deallocates the sound } {data structure. Call ShutdownSharing before program termination to } {free allocated extended memory. } procedure ShutdownSharing; {Shuts down EMB sharing and frees all allocated extended memory } procedure OpenSoundResourceFile(FileName: string); {Call this to open a resource file for loading sounds. After this has } {been called, the Key parameter in the LoadSound function is used as a } {resource key to locate the sound data in this file. } { Parameters: } { FileName: File name of resource file } procedure CloseSoundResourceFile; {Close sound resource file. If you have called this, the Key parameter} {will act as a filename instead of a resource key. } procedure LoadSound(var Sound: PSound; Key: string); {Allocates an extended memory block and loads a sound from a file } { Parameters: } { Sound: Unallocated pointer to sound data structure } { Key: If a resource file has been opened then key is a resource } { identifier. Use the same ID as you used for SNDLIB. } { If a resource file has not been opened, then key is the } { filename to load the sound data from. } procedure FreeSound(var Sound: PSound); {Deallocates extended memory and destroys sound data structure } { Parameters: } { Sound: Unallocated pointer to sound data structure } procedure StartSound(Sound: PSound; Index: byte; Loop: boolean); {Starts playing a sound } { Parameters: } { Sound: Pointer to sound data structure } { Index: A number to keep track of the sound with (Used to stop it)} { Loop: Indicates whether the sound should be continuously looped } procedure StopSound(Index: byte); {Stops playing sound } { Parameters: } { Index: Index of sound to stop (All with given index are stopped) } function SoundPlaying(Index: byte): boolean; {Checks if a sound is still playing } { Parameters: } { Index: Index used when the sound was started } { Returns: } { TRUE At least oen sound with the specified index is playing } { FALSE No sounds with the specified index are playing } var IntCount : LongInt; {Number of sound interrupts that have occured } DSPVersion : real; {Contains the version of the installed DSP chip } AutoInit : boolean; {Tells Auto-initialized DMA transfers are in use} SixteenBit : boolean; {Tells whether 16-bit sound output is occuring } VoiceCount : byte; {Number of voices currently in use } implementation uses CRT, DOS, XMS; const BufferLength = BlockLength * 2; var ResetPort : word; ReadPort : word; WritePort : word; PollPort : word; AckPort : word; PICRotatePort : word; PICMaskPort : word; DMAMaskPort : word; DMAClrPtrPort : word; DMAModePort : word; DMABaseAddrPort : word; DMACountPort : word; DMAPagePort : word; IRQStartMask : byte; IRQStopMask : byte; IRQIntVector : byte; DMAStartMask : byte; DMAStopMask : byte; DMAMode : byte; DMALength : word; OldIntVector : pointer; OldExitProc : pointer; HandlerInstalled : boolean; procedure WriteDSP(Value: byte); begin repeat until (Port[WritePort] and $80) = 0; Port[WritePort] := Value; end; function ReadDSP: byte; begin repeat until (Port[PollPort] and $80) <> 0; ReadDSP := Port[ReadPort]; end; function ResetDSP: boolean; var i: byte; begin Port[ResetPort] := 1; Delay(1); {One millisecond} Port[ResetPort] := 0; i := 100; while (ReadDSP <> $AA) and (i > 0) do Dec(i); if i > 0 then ResetDSP := true else ResetDSP := false; end; procedure InstallHandler; forward; procedure UninstallHandler; forward; procedure MixExitProc; far; forward; function InitSB(BaseIO: word; IRQ: byte; DMA, DMA16: byte): boolean; begin {Sound card IO ports} ResetPort := BaseIO + $6; ReadPort := BaseIO + $A; WritePort := BaseIO + $C; PollPort := BaseIO + $E; {Reset DSP, get version, and pick output mode} if not(ResetDSP) then begin InitSB := false; Exit; end; WriteDSP($E1); {Get DSP version number} DSPVersion := ReadDSP; DSPVersion := DSPVersion + ReadDSP/100; AutoInit := DSPVersion > 2.0; SixteenBit := (DSPVersion > 4.0) and (DMA16 <> $FF) and (DMA16 > 3); {Compute interrupt ports and parameters} if IRQ <= 7 then begin IRQIntVector := $08+IRQ; PICMaskPort := $21; end else begin IRQIntVector := $70+IRQ-8; PICMaskPort := $A1; end; IRQStopMask := 1 shl (IRQ mod 8); IRQStartMask := not(IRQStopMask); {Compute DMA ports and parameters} if SixteenBit then {Sixteen bit} begin DMAMaskPort := $D4; DMAClrPtrPort := $D8; DMAModePort := $D6; DMABaseAddrPort := $C0 + 4*(DMA16-4); DMACountPort := $C2 + 4*(DMA16-4); case DMA16 of 5: DMAPagePort := $8B; 6: DMAPagePort := $89; 7: DMAPagePort := $8A; end; DMAStopMask := DMA16-4 + $04; {000001xx} DMAStartMask := DMA16-4 + $00; {000000xx} DMAMode := DMA16-4 + $58; {010110xx} AckPort := BaseIO + $F; end else {Eight bit} begin DMAMaskPort := $0A; DMAClrPtrPort := $0C; DMAModePort := $0B; DMABaseAddrPort := $00 + 2*DMA; DMACountPort := $01 + 2*DMA; case DMA of 0: DMAPagePort := $87; 1: DMAPagePort := $83; 2: DMAPagePort := $81; 3: DMAPagePort := $82; end; DMAStopMask := DMA + $04; {000001xx} DMAStartMask := DMA + $00; {000000xx} if AutoInit then DMAMode := DMA + $58 {010110xx} else DMAMode := DMA + $48; {010010xx} AckPort := BaseIO + $E; end; if AutoInit then DMALength := BufferLength else DMALength := BlockLength; InstallHandler; OldExitProc := ExitProc; ExitProc := @MixExitProc; InitSB := true; end; procedure ShutdownSB; begin if HandlerInstalled then UninstallHandler; ResetDSP; end; function InitXMS: boolean; begin InitXMS := true; if not(XMSInstalled) then InitXMS := false else XMSInit; end; function GetFreeXMS: word; begin GetFreeXMS := XMSGetFreeMem; end; {Voice control} type PVoice = ^TVoice; TVoice = record Sound: PSound; Index: byte; CurPos: LongInt; Loop: boolean; end; var VoiceInUse: array[0..Voices-1] of boolean; Voice: array[0..Voices-1] of TVoice; CurBlock: byte; {Sound buffer} var SoundBlock: array[1..BlockLength+1] of ShortInt; {The length of XMS copies under HIMEM.SYS must be a mutiple } {of two. If the sound data ends in mid-block, it may not be } {possible to round up without corrupting memory. Therefore, } {the copy buffer has been extended by one byte to eliminate } {this problem. } {Mixing buffers} type PMixingBlock = ^TMixingBlock; TMixingBlock = array[1..BlockLength] of integer; var MixingBlock : TMixingBlock; {Output buffers} type {8-bit} POut8Block = ^TOut8Block; TOut8Block = array[1..BlockLength] of byte; POut8Buffer = ^TOut8Buffer; TOut8Buffer = array[1..2] of TOut8Block; type {16-bit} POut16Block = ^TOut16Block; TOut16Block = array[1..BlockLength] of integer; POut16Buffer = ^TOut16Buffer; TOut16Buffer = array[1..2] of TOut16Block; var OutMemArea : pointer; Out8Buffer : POut8Buffer; Out16Buffer : POut16Buffer; var BlockPtr : array[1..2] of pointer; CurBlockPtr : pointer; var {For auto-initialized transfers (Whole buffer)} BufferAddr : LongInt; BufferPage : byte; BufferOfs : word; {For single-cycle transfers (One block at a time)} BlockAddr : array[1..2] of LongInt; BlockPage : array[1..2] of byte; BlockOfs : array[1..2] of word; {Clipping for 8-bit output} var Clip8 : array[-128*Voices..128*Voices] of byte; function TimeConstant(Rate: word): byte; begin TimeConstant := 256 - (1000000 div Rate); end; procedure StartDAC; begin Port[DMAMaskPort] := DMAStopMask; Port[DMAClrPtrPort] := $00; Port[DMAModePort] := DMAMode; Port[DMABaseAddrPort] := Lo(BufferOfs); Port[DMABaseAddrPort] := Hi(BufferOfs); Port[DMACountPort] := Lo(DMALength-1); Port[DMACountPort] := Hi(DMALength-1); Port[DMAPagePort] := BufferPage; Port[DMAMaskPort] := DMAStartMask; if SixteenBit then {Sixteen bit: SB16 and up (DSP 4.xx)} begin WriteDSP($41); {Set digitized sound output sampling rate} WriteDSP(Hi(SamplingRate)); WriteDSP(Lo(SamplingRate)); WriteDSP($B6); {16-bit DMA command: D/A, Auto-Init, FIFO} WriteDSP($10); {16-bit DMA mode: Signed Mono } WriteDSP(Lo(BlockLength - 1)); WriteDSP(Hi(BlockLength - 1)); end else {Eight bit} begin WriteDSP($D1); {Turn on speaker } WriteDSP($40); {Set digitized sound time constant } WriteDSP(TimeConstant(SamplingRate)); if AutoInit then {Eight bit auto-initialized: SBPro and up (DSP 2.00+)} begin WriteDSP($48); {Set DSP block transfer size } WriteDSP(Lo(BlockLength - 1)); WriteDSP(Hi(BlockLength - 1)); WriteDSP($1C); {8-bit auto-init DMA mono sound output } end else {Eight bit single-cycle: Sound Blaster (DSP 1.xx+)} begin WriteDSP($14); {8-bit single-cycle DMA sound output } WriteDSP(Lo(BlockLength - 1)); WriteDSP(Hi(BlockLength - 1)); end; end; end; procedure StopDAC; begin if SixteenBit then {Sixteen bit} begin WriteDSP($D5); {Pause 16-bit DMA sound I/O } end else {Eight bit} begin WriteDSP($D0); {Pause 8-bit DMA mode sound I/O } WriteDSP($D3); {Turn off speaker } end; Port[DMAMaskPort] := DMAStopMask; end; {Setup for storing all sounds in one extended memory block (Saves handles)} var SharedEMB : boolean; SharedHandle : word; SharedSize : LongInt; procedure InitSharing; begin SharedEMB := true; SharedSize := 0; XMSAllocate(SharedHandle, SharedSize); end; procedure ShutdownSharing; begin if SharedEMB then XMSFree(SharedHandle); SharedEMB := false; end; {Setup for sound resource files} var ResourceFile : boolean; ResourceFilename : string; procedure OpenSoundResourceFile(FileName: string); begin ResourceFile := true; ResourceFilename := FileName; end; procedure CloseSoundResourceFile; begin ResourceFile := false; ResourceFilename := ''; end; type TKey = array[1..8] of char; var SoundFile : file; SoundSize : LongInt; function MatchingKeys(a, b: TKey): boolean; var i: integer; begin MatchingKeys := true; for i := 1 to 8 do if a <> b then MatchingKeys := false; end; procedure GetSoundFile(Key: string); type Resource = record Key: TKey; Start: LongInt; Size: LongInt; end; var NumSounds: integer; ResKey: TKey; ResHeader: Resource; Index: integer; i: integer; Found: boolean; begin if ResourceFile then begin for i := 1 to 8 do if i <= Length(Key) then ResKey[i] := Key[i] else ResKey[i] := #0; Assign(SoundFile, ResourceFilename); Reset(SoundFile, 1); BlockRead(SoundFile, NumSounds, SizeOf(NumSounds)); Found := false; Index := 0; while not(Found) and (Index < NumSounds) do begin Index := Index + 1; BlockRead(SoundFile, ResHeader, SizeOf(ResHeader)); if MatchingKeys(ResHeader.Key, ResKey) then Found := true; end; if Found then begin Seek(SoundFile, ResHeader.Start); SoundSize := ResHeader.Size; end else Halt(255); end else begin Assign(SoundFile, Key); Reset(SoundFile, 1); SoundSize := FileSize(SoundFile); end; end; function Min(a, b: LongInt): LongInt; begin if a < b then Min := a else Min := b; end; {Loading and freeing sounds} var MoveParams: TMoveParams; {The XMS driver doesn't like this on the stack} procedure LoadSound(var Sound: PSound; Key: string); var Size: LongInt; InBuffer: array[1..LoadChunkSize] of byte; Remaining: LongInt; begin GetSoundFile(Key); New(Sound); Sound^.SoundSize := SoundSize; if not(SharedEMB) then begin Sound^.StartOfs := 0; XMSAllocate(Sound^.XMSHandle, (SoundSize + 1023) div 1024); end else begin Sound^.StartOfs := SharedSize; Sound^.XMSHandle := SharedHandle; SharedSize := SharedSize + SoundSize; XMSReallocate(SharedHandle, (SharedSize + 1023) div 1024); end; MoveParams.SourceHandle := 0; MoveParams.SourceOffset := LongInt(Addr(InBuffer)); MoveParams.DestHandle := Sound^.XMSHandle; MoveParams.DestOffset := Sound^.StartOfs; Remaining := Sound^.SoundSize; repeat MoveParams.Length := Min(Remaining, LoadChunkSize); BlockRead(SoundFile, InBuffer, MoveParams.Length); MoveParams.Length := ((MoveParams.Length+1) div 2) * 2; {XMS copy lengths must be a multiple of two} XMSMove(@MoveParams); Inc(MoveParams.DestOffset, MoveParams.Length); Dec(Remaining, MoveParams.Length); until not(Remaining > 0); Close(SoundFile); end; procedure FreeSound(var Sound: PSound); begin if not(SharedEMB) then XMSFree(Sound^.XMSHandle); Dispose(Sound); Sound := nil; end; {Voice maintainance} procedure DeallocateVoice(VoiceNum: byte); begin VoiceInUse[VoiceNum] := false; with Voice[VoiceNum] do begin Sound := nil; Index := 0; CurPos := 0; Loop := false; end; end; procedure StartSound(Sound: PSound; Index: byte; Loop: boolean); var i, Slot: byte; begin Slot := $FF; i := 0; repeat if not(VoiceInUse[i]) then Slot := i; Inc(i); until ((Slot <> $FF) or (i=Voices)); if Slot <> $FF then begin Inc(VoiceCount); Voice[Slot].Sound := Sound; Voice[Slot].Index := Index; Voice[Slot].CurPos := 0; Voice[Slot].Loop := Loop; VoiceInUse[Slot] := true; end; end; procedure StopSound(Index: byte); var i: byte; begin for i := 0 to Voices-1 do if Voice[i].Index = Index then begin DeallocateVoice(i); Dec(VoiceCount); end; end; function SoundPlaying(Index: byte): boolean; var i: byte; begin SoundPlaying := False; for i := 0 to Voices-1 do if Voice[i].Index = Index then SoundPlaying := True; end; procedure UpdateVoices; var VoiceNum: byte; begin for VoiceNum := 0 to Voices-1 do begin if VoiceInUse[VoiceNum] then if Voice[VoiceNum].CurPos >= Voice[VoiceNum].Sound^.SoundSize then begin DeallocateVoice(VoiceNum); Dec(VoiceCount); end; end; end; {Utility functions} procedure SetCurBlock(BlockNum: byte); begin CurBlock := BlockNum; CurBlockPtr := pointer(BlockPtr[BlockNum]); end; procedure ToggleBlock; begin if CurBlock = 1 then SetCurBlock(2) else SetCurBlock(1); end; procedure SilenceBlock; begin FillChar(MixingBlock, BlockLength*2, 0); {FillChar uses REP STOSW} end; function GetLinearAddr(Ptr: pointer): LongInt; begin GetLinearAddr := LongInt(Seg(Ptr^))*16 + LongInt(Ofs(Ptr^)); end; function NormalizePtr(p: pointer): pointer; var LinearAddr: LongInt; begin LinearAddr := GetLinearAddr(p); NormalizePtr := Ptr(LinearAddr div 16, LinearAddr mod 16); end; procedure InitClip8; var i, Value: integer; begin for i := -128*Voices to 128*Voices do begin Value := i; if (Value < -128) then Value := -128; if (Value > +127) then Value := +127; Clip8[i] := Value + 128; end; end; procedure InitMixing; var i: integer; begin for i := 0 to Voices-1 do DeallocateVoice(i); VoiceCount := 0; if SixteenBit then begin {Find a block of memory that does not cross a page boundary} GetMem(OutMemArea, 4*BufferLength); if ((GetLinearAddr(OutMemArea) div 2) mod 65536)+BufferLength < 65536 then Out16Buffer := OutMemArea else Out16Buffer := NormalizePtr(Ptr(Seg(OutMemArea^), Ofs(OutMemArea^)+2*BufferLength)); for i := 1 to 2 do BlockPtr[i] := NormalizePtr(Addr(Out16Buffer^[i])); {DMA parameters} BufferAddr := GetLinearAddr(pointer(Out16Buffer)); BufferPage := BufferAddr div 65536; BufferOfs := (BufferAddr div 2) mod 65536; for i := 1 to 2 do BlockAddr[i] := GetLinearAddr(pointer(BlockPtr[i])); for i := 1 to 2 do BlockPage[i] := BlockAddr[i] div 65536; for i := 1 to 2 do BlockOfs[i] := (BlockAddr[i] div 2) mod 65536; FillChar(Out16Buffer^, BufferLength*2, $00); {Signed 16-bit} end else begin {Find a block of memory that does not cross a page boundary} GetMem(OutMemArea, 2*BufferLength); if (GetLinearAddr(OutMemArea) mod 65536)+BufferLength < 65536 then Out8Buffer := OutMemArea else Out8Buffer := NormalizePtr(Ptr(Seg(OutMemArea^), Ofs(OutMemArea^)+BufferLength)); for i := 1 to 2 do BlockPtr[i] := NormalizePtr(Addr(Out8Buffer^[i])); {DMA parameters} BufferAddr := GetLinearAddr(pointer(Out8Buffer)); BufferPage := BufferAddr div 65536; BufferOfs := BufferAddr mod 65536; for i := 1 to 2 do BlockAddr[i] := GetLinearAddr(pointer(BlockPtr[i])); for i := 1 to 2 do BlockPage[i] := BlockAddr[i] div 65536; for i := 1 to 2 do BlockOfs[i] := BlockAddr[i] mod 65536; FillChar(Out8Buffer^, BufferLength, $80); {Unsigned 8-bit} InitClip8; end; FillChar(MixingBlock, BlockLength*2, $00); SetCurBlock(1); IntCount := 0; StartDAC; end; procedure ShutdownMixing; begin StopDAC; if SixteenBit then FreeMem(OutMemArea, 4*BufferLength) else FreeMem(OutMemArea, 2*BufferLength); end; var {The XMS driver doesn't like parameter blocks in the stack} IntMoveParams: TMoveParams; {In case LoadSound is interrupted} procedure CopySound(Sound: PSound; var CurPos: LongInt; CopyLength: word; Loop: boolean); var SoundSize: LongInt; DestPtr: pointer; begin SoundSize := Sound^.SoundSize; DestPtr := pointer(@SoundBlock); IntMoveParams.SourceHandle := Sound^.XMSHandle; IntMoveParams.DestHandle := 0; while CopyLength > 0 do begin {Compute max transfer size} if CopyLength < SoundSize-CurPos then IntMoveParams.Length := CopyLength else IntMoveParams.Length := SoundSize-CurPos; {Compute starting dest. offset and update offset for next block} IntMoveParams.SourceOffset := Sound^.StartOfs + CurPos; CurPos := CurPos + IntMoveParams.Length; if Loop then CurPos := CurPos mod SoundSize; {Compute starting source offset and update offset for next block} IntMoveParams.DestOffset := LongInt(DestPtr); DestPtr := NormalizePtr(Ptr(Seg(DestPtr^), Ofs(DestPtr^)+IntMoveParams.Length)); {Update remaining count for next iteration} CopyLength := CopyLength - IntMoveParams.Length; {Move block} IntMoveParams.Length := ((IntMoveParams.Length+1) div 2) * 2; {XMS copy lengths must be a multiple of two} XMSMove(@IntMoveParams); {Luckily, the XMS driver is re-entrant} end; end; procedure MixVoice(VoiceNum: byte); var MixLength: word; begin with Voice[VoiceNum] do if Loop then MixLength := BlockLength else if BlockLength < Sound^.SoundSize-CurPos then MixLength := BlockLength else MixLength := Sound^.SoundSize-CurPos; CopySound(Voice[VoiceNum].Sound, Voice[VoiceNum].CurPos, MixLength, Voice[VoiceNum].Loop); asm lea si, SoundBlock {DS:SI -> Sound data (Source) } mov ax, ds {ES:DI -> Mixing block (Destination) } mov es, ax lea di, MixingBlock mov cx, MixLength {CX = Number of samples to copy } @MixSample: mov al, [si] {Load a sample from the sound block } inc si { increment pointer } cbw {Convert it to a 16-bit signed sample } add es:[di], ax {Add it into the mixing buffer } add di, 2 {Next word in mixing buffer } dec cx {Loop for next sample } jnz @MixSample end; end; procedure MixVoices; var i: word; begin SilenceBlock; for i := 0 to Voices-1 do if VoiceInUse[i] then MixVoice(i); end; procedure CopyData16; assembler; asm lea si, MixingBlock {DS:SI -> 16-bit input block } les di, [CurBlockPtr] {ES:DI -> 16-bit output block } mov cx, BlockLength {CX = Number of samples to copy } @CopySample: mov ax, [si] {Load a sample from the mixing block } add di, 2 {Increment destination pointer } sal ax, 5 {Shift sample left to fill 16-bit range} add si, 2 {Increment source pointer } mov es:[di-2], ax {Store sample in output block } dec cx {Process the next sample } jnz @CopySample end; procedure CopyData8; assembler; asm push bp mov dx, ss {Preserve SS in DX } pushf cli {Disable interrupts } mov ax, ds {Using SS for data } mov ss, ax lea si, Clip8 {DS:SI -> 8-bit clipping buffer } add si, 128*Voices {DS:SI -> Center of clipping buffer } lea bp, MixingBlock {SS:BP -> 16-bit input block } les di, [CurBlockPtr] {ES:DI -> 8-bit output block } mov cx, BlockLength {CX = Number of samples to copy } @CopySample: mov bx, [bp] {BX = Sample from mixing block } inc di {Increment destination pointer (DI) } add bp, 2 {Increment source pointer (BP) } mov al, [si+bx] {AL = Clipped sample } mov es:[di], al {Store sample in output block } dec cx {Process the next sample } jnz @CopySample mov ss, dx {Restore SS } popf {Restore flags } pop bp end; procedure CopyData; begin if SixteenBit then CopyData16 else CopyData8; end; procedure StartBlock_SC; {Starts a single-cycle DMA transfer} begin Port[DMAMaskPort] := DMAStopMask; Port[DMAClrPtrPort] := $00; Port[DMAModePort] := DMAMode; Port[DMABaseAddrPort] := Lo(BlockOfs[CurBlock]); Port[DMABaseAddrPort] := Hi(BlockOfs[CurBlock]); Port[DMACountPort] := Lo(DMALength-1); Port[DMACountPort] := Hi(DMALength-1); Port[DMAPagePort] := BlockPage[CurBlock]; Port[DMAMaskPort] := DMAStartMask; WriteDSP($14); {8-bit single-cycle DMA sound output } WriteDSP(Lo(BlockLength - 1)); WriteDSP(Hi(BlockLength - 1)); end; procedure IntHandler; interrupt; var Temp: byte; begin Inc(IntCount); if not(AutoInit) {Start next block first if not using auto-init DMA} then begin StartBlock_SC; CopyData; ToggleBlock; end; UpdateVoices; MixVoices; if (AutoInit) then begin CopyData; ToggleBlock; end; Temp := Port[AckPort]; Port[$A0] := $20; Port[$20] := $20; end; procedure EnableInterrupts; InLine($FB); {STI} procedure DisableInterrupts; InLine($FA); {CLI} procedure InstallHandler; begin DisableInterrupts; Port[PICMaskPort] := Port[PICMaskPort] or IRQStopMask; GetIntVec(IRQIntVector, OldIntVector); SetIntVec(IRQIntVector, @IntHandler); Port[PICMaskPort] := Port[PICMaskPort] and IRQStartMask; EnableInterrupts; HandlerInstalled := true; end; procedure UninstallHandler; begin DisableInterrupts; Port[PICMaskPort] := Port[PICMaskPort] or IRQStopMask; SetIntVec(IRQIntVector, OldIntVector); EnableInterrupts; HandlerInstalled := false; end; procedure MixExitProc; {Called automatically on program termination} begin ExitProc := OldExitProc; StopDAC; ShutdownSB; end; begin HandlerInstalled := false; SharedEMB := false; ResourceFile := false; end.
unit ncaFrmLeXML; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, kbmMemTable, cxImageComboBox, cxContainer, cxTextEdit, cxMaskEdit, cxButtonEdit, cxLabel, dxLayoutcxEditAdapters, dxLayoutControlAdapters, Vcl.Menus, cxCheckBox, cxDBEdit, cxCurrencyEdit, dxLayoutContainer, Vcl.StdCtrls, cxButtons, dxLayoutControl, LMDBaseControl, LMDBaseGraphicControl, LMDGraphicControl, LMDHTMLLabel, ncDMdanfe_NFCE, ncMyImage, Vcl.ImgList, cxGridInplaceEditForm, dxBar, LMDCustomScrollBox, LMDScrollBox, LMDSplt, nxdb, cxRadioGroup, LMDCustomButton, LMDButton, dxBarBuiltInMenu, cxPC, cxGroupBox, cxSpinEdit, Vcl.ExtCtrls, System.ImageList; type TFrmLeXML = class(TForm) mt: TkbmMemTable; mtDescrXML: TStringField; mtUnidXML: TStringField; mtProduto: TIntegerField; ds: TDataSource; mtitem: TWordField; mtOK: TBooleanField; mtFatorUniv: TBooleanField; mtFator: TFloatField; mtNomeProd: TStringField; mtQuant: TFloatField; mtTotal: TCurrencyField; mtUnidProd: TStringField; mtNCM: TStringField; imgs: TcxImageList; panPri: TLMDSimplePanel; mtCodigo: TStringField; tConvUnid: TnxTable; tProdFor: TnxTable; tProdForUID: TGuidField; tProdForProduto: TLongWordField; tProdForFornecedor: TLongWordField; tProdForRef: TStringField; tProdForPos: TWordField; tConvUnidUID: TGuidField; tConvUnidA: TStringField; tConvUnidB: TStringField; tConvUnidFator: TFloatField; tConvUnidUniversal: TBooleanField; tConvUnidProduto: TLongWordField; tConvUnidMult: TBooleanField; mtProdutoSugerido: TIntegerField; mtNomeProdSug: TStringField; mtStatus: TByteField; pgPri: TcxPageControl; tsProd: TcxTabSheet; tsArq: TcxTabSheet; Splitter: TLMDSplitterPanel; spGrid: TLMDSplitterPane; lbTitItens: TcxLabel; grid: TcxGrid; TV: TcxGridDBTableView; TVStatus: TcxGridDBColumn; TVDescrXML: TcxGridDBColumn; TVRootGroup: TcxGridInplaceEditFormGroup; GL: TcxGridLevel; spLC: TLMDSplitterPane; Paginas: TcxPageControl; tsSugestao: TcxTabSheet; cxGroupBox1: TcxGroupBox; btnPesquisar: TLMDButton; btnNovo: TLMDButton; cxLabel3: TcxLabel; btnAceitarSug: TLMDButton; cxLabel2: TcxLabel; lbProdutoSugerido: TcxLabel; tsSemProd: TcxTabSheet; btnNovo2: TLMDButton; btnPesquisar2: TLMDButton; tsSemUnid: TcxTabSheet; LMDHTMLLabel2: TLMDHTMLLabel; LMDSimplePanel3: TLMDSimplePanel; btnAddUnid: TcxButton; tsConvUnid: TcxTabSheet; lbUnidProd: TLMDHTMLLabel; lbUnidXML: TLMDHTMLLabel; cxLabel4: TcxLabel; cxLabel5: TcxLabel; panRegra: TLMDSimplePanel; LMDSimplePanel5: TLMDSimplePanel; tsOk: TcxTabSheet; LMDSimplePanel1: TLMDSimplePanel; LMDSimplePanel2: TLMDSimplePanel; cxLabel1: TcxLabel; tsFor: TcxTabSheet; lbSelModelo: TcxLabel; panBottom: TLMDSimplePanel; btnAvancar: TcxButton; btnVoltar: TcxButton; LMDSimplePanel6: TLMDSimplePanel; cxLabel6: TcxLabel; edArq: TcxTextEdit; LMDSimplePanel7: TLMDSimplePanel; btnSelArq: TcxButton; cxLabel8: TcxLabel; LMDSimplePanel8: TLMDSimplePanel; edFor: TcxTextEdit; panNewFor: TLMDSimplePanel; btnPesqFor: TcxButton; btnCadFor: TcxButton; OpenXML: TOpenDialog; lbErro: TcxLabel; TVOk: TcxGridDBColumn; lbDe: TcxLabel; edPara: TcxDBCurrencyEdit; lbPara: TcxLabel; lbInverter: TcxLabel; panImg: TLMDSimplePanel; imgStatus: TMyImage; LMDSimplePanel4: TLMDSimplePanel; edProduto: TcxDBButtonEdit; btnEditar: TcxButton; mtNumSeq: TAutoIncField; mtNewFator: TFloatField; mtNewFatorUniv: TBooleanField; lbPend: TcxLabel; mtFatorInvertido: TBooleanField; mtNewFatorInvertido: TBooleanField; cxLabel9: TcxLabel; edUniv: TcxDBCheckBox; tLinkXML: TnxTable; tLinkXMLUID: TGuidField; tLinkXMLProduto: TLongWordField; tLinkXMLFornecedor: TLongWordField; tLinkXMLLink: TStringField; tTran: TnxTable; tTranChaveNFE: TStringField; tTranCancelado: TBooleanField; tTranID: TUnsignedAutoIncField; tTranDataHora: TDateTimeField; tTranCaixa: TLongWordField; tsFrete: TcxTabSheet; cxLabel7: TcxLabel; panFrete: TLMDSimplePanel; edFrete: TcxCurrencyEdit; cxLabel10: TcxLabel; cxLabel11: TcxLabel; cbEntrada: TcxCheckBox; procedure FormCreate(Sender: TObject); procedure edProdutoPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure btnPesquisarClick(Sender: TObject); procedure TVFocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure mtCalcFields(DataSet: TDataSet); procedure btnNovoClick(Sender: TObject); procedure btnAceitarSugClick(Sender: TObject); procedure btnAddUnidClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnPesqForClick(Sender: TObject); procedure pgPriChange(Sender: TObject); procedure btnSelArqClick(Sender: TObject); procedure btnAvancarClick(Sender: TObject); procedure btnVoltarClick(Sender: TObject); procedure btnCadForClick(Sender: TObject); procedure TVDescrXMLCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure btnEditarClick(Sender: TObject); procedure lbInverterClick(Sender: TObject); function TamPara: Integer; procedure edParaEnter(Sender: TObject); procedure edParaPropertiesChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); private dmDanfe : TdmDanfe_NFCE; FFor : Integer; FChave : String; FLoaded : Boolean; FPend : Integer; FOnFornecedor : TNotifyEvent; FOnConcluir : TNotifyEvent; FTotal : Currency; FpercFrete : Double; { Private declarations } procedure LoadProd; procedure LoadDadosProd; procedure LoadConvUnid; procedure Update; procedure forceEdit; procedure PesquisarProd; procedure _SalvaConvUnid; procedure SalvaConvUnid; procedure SalvaProdFor; procedure RefreshPend; procedure Concluir; function LoadFor: Boolean; procedure LoadItens; procedure SetFor(const Value: Integer); public function QuantFator: Double; function Frete: Currency; property Total: Currency read FTotal; property percFrete: Double read FpercFrete; property Chave: String read FChave; property OnFornecedor: TNotifyEvent read FOnFornecedor write FOnFornecedor; property OnConcluir: TNotifyEvent read FOnConcluir write FOnConcluir; property IDFor: Integer read FFor write SetFor; { Public declarations } end; var FrmLeXML: TFrmLeXML; implementation {$R *.dfm} uses ufmImagens, ncaFrmPri, ncaDM, ncaFrmProdPesq2, ncaFrmPesqFor, ncaFrmProduto, ncaFrmCadFornecedor; { TFrmLeXML } const sLabelUnidXML = 'Unidade no XML/NFe = <strong><FONT COLOR="#0080FF">%s</strong>'; sLabelUnidProd = 'Unidade no Cadastro do Produto = <strong><FONT COLOR="#0080FF">%s</strong>'; sUniv = 'A conversão de %s para %s é sempre igual, para TODOS produtos.'; psSugestao = 0; psSemProd = 1; psSemUnid = 2; psConvUnid = 3; psOk = 4; procedure TFrmLeXML.btnAceitarSugClick(Sender: TObject); begin forceEdit; mtProduto.Value := mtProdutoSugerido.Value; LoadDadosProd; LoadConvUnid; Update; while (not mt.Eof) and mtOk.Value do mt.Next; end; procedure TFrmLeXML.btnAddUnidClick(Sender: TObject); begin with Dados do if tbPro.Locate('ID', mtProduto.Value, []) then begin TFrmProduto.Create(Self).Editar(dados.tbPro, True); forceEdit; LoadDadosProd; LoadConvUnid; Update; end; end; procedure TFrmLeXML.btnAvancarClick(Sender: TObject); begin case pgPri.ActivePageIndex of 0 : pgPri.ActivePage := tsFor; 1 : pgPri.ActivePage := tsProd; 2 : pgPri.ActivePage := tsFrete; 3 : Concluir; end; end; procedure TFrmLeXML.btnCadForClick(Sender: TObject); var aID: Integer; begin aID := TFrmCadFornecedor.Create(Self).Novo(Dados.tbCli, nil, dmDanfe); if aID>0 then begin IDFor := aID; pgPri.ActivePage := tsProd; end; end; procedure TFrmLeXML.btnEditarClick(Sender: TObject); begin with Dados do if tbPro.Locate('ID', mtProduto.Value, []) then begin TFrmProduto.Create(Self).Editar(dados.tbPro); forceEdit; LoadDadosProd; LoadConvUnid; Update; end; end; procedure TFrmLeXML.btnNovoClick(Sender: TObject); begin dmDanfe.mtItem.Locate('nItem', mtItem.Value, []); if TFrmProduto.Create(Self).Incluir(dados.tbPro, self.dmDanfe, FFor) then begin forceEdit; mtProduto.Value := dados.tbProID.Value; LoadDadosProd; LoadConvUnid; Update; while (not mt.Eof) and mtOk.Value do mt.Next; end; end; procedure TFrmLeXML.btnPesqForClick(Sender: TObject); var FPesq : TFrmPesqFor; FFidPontos : Double; S: String; begin S := edFor.text; FFidPontos := 0; FPesq := gPesqForList.GetFrm; try if FPesq.Pesquisar(FFor, S, FFidPontos, dmDanfe) then begin IDFor := FFor; if IDFor>0 then pgPri.ActivePage := tsProd; end; finally gPesqForList.ReleaseFrm(FPesq); end; end; procedure TFrmLeXML.btnPesquisarClick(Sender: TObject); var Antes: Boolean; begin Antes := mtOk.Value; PesquisarProd; if not Antes then while (not mt.Eof) and mtOk.Value do mt.Next; end; procedure TFrmLeXML.btnSelArqClick(Sender: TObject); var sl : TStrings; begin if not OpenXML.Execute(Handle) then Exit; FTotal := 0; FpercFrete := 0; lbErro.Visible := False; FLoaded := False; btnAvancar.Enabled := False; edArq.Text := OpenXML.FileName; sl := TStringList.Create; try sl.LoadFromFile(OpenXML.FileName); dmDanfe.LoadXML(sl.Text, 0, '', '', '', '', Dados.tbConfig, '', '', '', False); edFrete.Value := dmDanfe.mtTotalvFrete.Value; lbErro.Visible := (dmDanfe.mtItem.RecordCount=0) or (dmDanfe.mtItem.RecordCount=0); FChave := dmDanfe.mtIDEchNFe.Value; tTran.SetRange([FChave], [FChave]); tTran.First; while not tTran.Eof do begin if not tTranCancelado.Value then raise Exception.Create('Essa NF-e/XML já foi lançada em '+ FormatDateTime('dd/mm/yyyy hh:mm', tTranDataHora.Value) + ' transaçao n.'+tTranID.AsString + ' no caixa '+tTranCaixa.AsString+'.'); tTran.Next; end; LoadFor; LoadItens; btnAvancar.Enabled := not lbErro.Visible; if btnAvancar.Enabled then pgPri.ActivePage := tsFor; finally sl.Free; end; end; procedure TFrmLeXML.btnVoltarClick(Sender: TObject); begin pgPri.ActivePageIndex := pgPri.ActivePageIndex-1; end; procedure TFrmLeXML.Concluir; begin mt.DisableControls; try SalvaConvUnid; SalvaProdFor; FTotal := 0; FpercFrete := 0; mt.First; while not mt.Eof do begin FTotal := FTotal + mtTotal.Value; mt.Next; end; if Frete<0.01 then FpercFrete := 0 else FpercFrete := (Frete/FTotal); mt.First; if Assigned(FOnConcluir) then FOnConcluir(Self); Close; finally mt.EnableControls; end; end; procedure TFrmLeXML.edParaEnter(Sender: TObject); begin edPara.Width := TamPara; end; procedure TFrmLeXML.edParaPropertiesChange(Sender: TObject); var Antes: Boolean; begin edPara.Width := TamPara; if edPara.Focused then begin Antes := mtOk.Value; edPara.PostEditValue; if mtOK.Value then imgStatus.ImageIndex := 4 else imgStatus.ImageIndex := mtStatus.Value; if mtOk.Value<>Antes then RefreshPend; end; end; procedure TFrmLeXML.edProdutoPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var Antes: Boolean; begin Antes := mtOk.Value; PesquisarProd; if not Antes then while (not mt.Eof) and mtOk.Value do mt.Next; end; procedure TFrmLeXML.forceEdit; begin if (mt.State<>dsEdit) then mt.Edit; end; procedure TFrmLeXML.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmLeXML.FormCreate(Sender: TObject); begin FChave := ''; FTotal := 0; FpercFrete := 0; FOnConcluir := nil; FOnFornecedor := nil; FLoaded := False; FPend := 0; dmDanfe := TdmDanfe_NFCE.Create(self); Paginas.Properties.HideTabs := True; FFor := 0; pgPri.Properties.HideTabs := True; pgPri.ActivePageIndex := 0; btnAvancar.Enabled := False; end; procedure TFrmLeXML.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of Key_F3 : if Paginas.ActivePageIndex = 0 then btnAceitarSug.Click; Key_F4 : if Paginas.ActivePageIndex in [0, 1] then btnNovo.Click; Key_F5 : if Paginas.ActivePageIndex in [0, 1] then btnPesquisar.Click; end; end; procedure TFrmLeXML.FormShow(Sender: TObject); begin Update; end; function TFrmLeXML.Frete: Currency; begin Result := edFrete.Value; end; procedure TFrmLeXML.lbInverterClick(Sender: TObject); begin forceEdit; mtnewFatorInvertido.Value := not mtNewFatorInvertido.Value; if (edPara.Value<>0) and (edPara.Value<>1) then edPara.Value := 1 / edPara.Value; mt.Post; Update; end; procedure TFrmLeXML.LoadConvUnid; begin try if (mtProduto.Value=0) or (mtUnidXML.Value=mtUnidProd.Value) then Exit; if tConvUnid.FindKey([mtUnidXMl.Value, mtUnidProd.Value, False, mtProduto.Value]) then begin mtFator.Value := tConvUnidFator.Value; mtFatorUniv.Value := False; mtFatorInvertido.Value := False; mtNewFatorInvertido.Value := False; mtNewFator.Value := mtFator.Value; mtNewFatorUniv.Value := mtFatorUniv.Value; end else if tConvUnid.FindKey([mtUnidProd.Value, mtUnidXML.Value, False, mtProduto.Value]) then begin mtFator.Value := tConvUnidFator.Value; mtFatorUniv.Value := False; mtFatorInvertido.Value := True; mtNewFatorInvertido.Value := True; mtNewFator.Value := mtFator.Value; mtNewFatorUniv.Value := mtFatorUniv.Value; end else if tConvUnid.FindKey([mtUnidXMl.Value, mtUnidProd.Value, True]) then begin mtFator.Value := tConvUnidFator.Value; mtFatorUniv.Value := True; mtFatorInvertido.Value := False; mtNewFatorInvertido.Value := False; mtNewFator.Value := mtFator.Value; mtNewFatorUniv.Value := mtFatorUniv.Value; end else if tConvUnid.FindKey([mtUnidProd.Value, mtUnidXML.Value, True]) then begin mtFator.Value := tConvUnidFator.Value; mtFatorUniv.Value := True; mtFatorInvertido.Value := True; mtNewFatorInvertido.Value := True; mtNewFator.Value := mtFator.Value; mtNewFatorUniv.Value := mtFatorUniv.Value; end else begin mtFatorInvertido.Value := False; mtNewFatorInvertido.Value := False; mtFator.Clear; mtFatorUniv.Value := False; mtNewFator.Clear; mtNewFatorUniv.Value := False; end; finally if FLoaded then RefreshPend; end; end; procedure TFrmLeXML.LoadDadosProd; begin Dados.tbPro.IndexName := 'IID'; if Dados.tbPro.FindKey([mtProduto.Value]) then begin MTUnidProd.Value := Dados.tbProUnid.Value; MTNomeProd.Value := dados.tbProDescricao.Value; end; end; function TFrmLeXML.LoadFor: Boolean; begin with Dados, dmDanfe do begin if tbCli.Locate('cpf', mtEmitCNPJ.Value, []) then IDFor := tbCliID.Value else IDFor := 0; Result := (IDFor>0); end; end; procedure TFrmLeXML.LoadItens; var I: Integer; begin with dmDanfe, dados do begin mt.Active := False; mt.Active := True; dmDanfe.mtItem.First; I := 0; while not dmDanfe.mtItem.Eof do begin mt.Append; Inc(i); self.mtitem.Value := I; mtDescrXML.Value := mtItemxProd.Value; mtCodigo.Value := mtItemCodigo.Value; mtNCM.Value := mtItemNCM.Value; mtQuant.Value := mtItemqCom.Value; mtUnidXML.Value := mtItemuCom.Value; mtOk.Value := False; self.mtTotal.Value := mtItemvProd.Value + mtItemvICMSST.Value + mtItemvIPI.Value - mtItemvDesc.Value; LoadProd; mt.Post; dmDanfe.mtItem.Next; end; mt.First; end; FLoaded := True; RefreshPend; Update; end; procedure TFrmLeXML.LoadProd; begin Dados.tbPro.IndexName := 'IID'; with Dados do if tLinkXML.FindKey([FFor, mtCodigo.Value]) and tbPro.FindKey([tLinkXMLProduto.Value]) then begin MTProduto.Value := Dados.tbProID.Value; MTUnidProd.Value := Dados.tbProUnid.Value; MTNomeProd.Value := dados.tbProDescricao.Value; end else begin tProdFor.IndexName := 'IForRef'; tbPro.IndexName := 'ICodigo'; if (tProdFor.FindKey([FFor, mtCodigo.Value]) and tbPro.Locate('ID', tProdForProduto.Value, [])) or tbPro.FindKey([mtCodigo.Value]) then begin MTProdutoSugerido.Value := Dados.tbProID.Value; MTNomeProdSug.Value := Dados.tbProDescricao.Value; end; end; LoadConvUnid; end; procedure TFrmLeXML.mtCalcFields(DataSet: TDataSet); begin mtOk.Value := (mtProduto.Value>0) and ( SameText(Trim(mtUnidXML.Value), Trim(mtUnidProd.Value)) or (mtNewFator.Value>0)); if mtProduto.Value>0 then begin if Trim(mtUnidProd.Value)='' then mtStatus.Value := psSemUnid else if mtOk.Value then mtStatus.Value := psOk else mtStatus.Value := psConvUnid; end else begin if mtProdutoSugerido.Value=0 then mtStatus.Value := psSemProd else mtStatus.Value := psSugestao; end; mtOk.Value := (mtProduto.Value>0) and ( SameText(Trim(mtUnidXML.Value), Trim(mtUnidProd.Value)) or (mtNewFator.Value>0)); end; procedure TFrmLeXML.PesquisarProd; var FPesq: TFrmProdPesq2; P, PAnt : Cardinal; U, UAnt : String; Ok : Boolean; begin FPesq := gProdPesq2List.GetFrm; with Dados do try P := mtProduto.Value; PAnt := P; UAnt := mtUnidProd.Value; U := UAnt; Ok := FPesq.Pesquisar(P); if Ok then begin tbPro.IndexName := 'IID'; if (P>0) then begin tbPro.FindKey([mtProduto.Value]); U := tbProUnid.Value; end; if (P<>PAnt) or (U<>UAnt) then begin forceEdit; mtProduto.Value := P; LoadDadosProd; LoadConvUnid; Update; end; end; finally gProdPesq2List.ReleaseFrm(FPesq); end; end; procedure TFrmLeXML.pgPriChange(Sender: TObject); begin btnVoltar.Enabled := (pgPri.ActivePageIndex>0); case pgPri.ActivePageIndex of 0 : btnAvancar.Enabled := FLoaded; 1 : btnAvancar.Enabled := (FFor>0); 2 : btnAvancar.Enabled := (FPend=0); 3 : begin btnAvancar.Enabled := (FPend=0); edFrete.SetFocus; end; end; if pgPri.ActivePageIndex=3 then btnAvancar.Caption := 'Concluir!' else btnAvancar.Caption := 'Avançar'; end; function TFrmLeXML.QuantFator: Double; begin if SameText(Trim(mtUnidXML.Value), Trim(mtUnidProd.Value)) then Result := mtQuant.Value else if mtNewFatorInvertido.Value then Result := mtQuant.Value / mtNewFator.Value else Result := mtQuant.Value * mtNewFator.Value; end; procedure TFrmLeXML.RefreshPend; var SaveItem: Integer; begin SaveItem := mtItem.Value; mt.DisableControls; try FPend := mt.RecordCount; mt.First; while not mt.Eof do begin if mtOK.Value then FPend := FPend - 1; mt.Next; end; finally mt.Locate('item', saveitem, []); mt.EnableControls; end; if FPend>0 then begin if FPend>1 then lbPend.Caption := IntToStr(FPend) + ' itens pendentes' else if mt.RecordCount>1 then lbPend.Caption := 'Quase lá! Apenas 1 item pendente :-)' else lbPend.Caption := '1 item pendente'; lbPend.Style.TextColor := clRed; if pgPri.ActivePage=tsProd then btnAvancar.Enabled := False; end else begin lbPend.Caption := 'Parabéns! Agora só falta clicar em concluir.'; lbPend.Style.TextColor := clGreen; if pgPri.ActivePage=tsProd then btnAvancar.Enabled := True; end; end; procedure TFrmLeXML.SalvaConvUnid; begin mt.First; while not mt.Eof do begin if not SameText(Trim(mtUnidXML.Value), Trim(mtUnidProd.Value)) then _SalvaConvUnid; mt.Next; end; end; procedure TFrmLeXML.SalvaProdFor; var P : Integer; begin mt.First; while not mt.Eof do begin if tLinkXML.FindKey([FFor, mtCodigo.Value]) then tLinkXML.Edit else tLinkXML.Append; tLinkXMLProduto.Value := mtProduto.Value; tLinkXMLFornecedor.Value := FFor; tLinkXMLLink.Value := mtCodigo.Value; tLinkXML.Post; tProdFor.IndexName := 'IProdFor'; if not tProdFor.FindKey([mtProduto.Value, FFor]) then begin tProdFor.IndexName := 'IProdPos'; tProdFor.SetRange([mtProduto.Value], [mtProduto.Value]); try tProdFor.Last; P := tProdForPos.Value + 1; tProdFor.Append; tProdForProduto.Value := mtProduto.Value; tProdForFornecedor.Value := FFor; tProdForRef.Value := mtCodigo.Value; tProdForPos.Value := P; tProdFor.Post; finally tProdFor.CancelRange; end; end; mt.Next; end; end; procedure TFrmLeXML.SetFor(const Value: Integer); begin FFor := Value; with Dados do if FFor=0 then begin edFor.Text := ''; panNewFor.Visible := True; end else begin tbCli.Locate('ID', FFor, []); edFor.Text := tbCliNome.Value; panNewFor.Visible := False; end; if pgPri.ActivePage=tsFor then btnAvancar.Enabled := (FFor>0); if Assigned(FOnFornecedor) then FOnFornecedor(Self); end; function TFrmLeXML.TamPara: Integer; begin Result := cxtextWidth(edPara.Style.Font, edPara.EditingText)+20; if Result<50 then Result := 50; end; procedure TFrmLeXML.TVDescrXMLCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); var V: Variant; begin V := AViewInfo.GridRecord.Values[TVOK.Index]; if (not VarIsNull(V)) and (V=True) then begin ACanvas.Font.Name := 'Segoe UI'; ACanvas.Font.Style := []; if not AViewInfo.Selected then ACanvas.Font.Color := clGray; end; end; procedure TFrmLeXML.TVFocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin Update; end; function UnidIgual(S: String): String; begin S := Trim(S); if (S>'') and (S[1] in ['0'..'9']) then Result := S + ' = ' else Result := '1 '+S+' = '; end; procedure TFrmLeXML.Update; begin if not FLoaded then Exit; if mtOK.Value then imgStatus.ImageIndex := 4 else imgStatus.ImageIndex := mtStatus.Value; if mtProduto.Value=0 then begin if mtProdutoSugerido.Value>0 then Paginas.ActivePage := tsSugestao else Paginas.ActivePage := tsSemProd; end else if Trim(mtUnidProd.Value)='' then Paginas.ActivePage := tsSemUnid else if not SameText(Trim(mtUnidXML.Value), Trim(mtUnidProd.Value)) then Paginas.ActivePage := tsConvUnid else Paginas.ActivePage := tsOk; lbProdutoSugerido.Caption := mtNomeProdSug.Value; lbUnidXML.Caption := Format(sLabelUnidXML, [mtUnidXMl.Value]); lbUnidProd.Caption := Format(sLabelUnidProd, [mtUnidProd.Value]); edUniv.Caption := Format(sUniv, [mtUnidXML.Value, mtUnidProd.Value]); btnEditar.visible := (mtProduto.Value>0); if mtNewFatorInvertido.Value then begin lbDe.Caption := UnidIgual(mtUnidProd.Value); lbPara.Caption := mtUnidXML.Value; end else begin lbDe.Caption := UnidIgual(mtUnidXML.Value); lbPara.Caption := mtUnidProd.Value; end; end; procedure TFrmLeXML._SalvaConvUnid; var A, B : String; Achou : Boolean; begin if SameText(Trim(mtUnidXML.Value), Trim(mtUnidProd.Value)) then Exit; if (mtFator.Value=mtNewFator.Value) and (mtFatorInvertido.Value=mtNewFatorInvertido.Value) and (mtFatorUniv.Value=mtNewFatorUniv.Value) then Exit; Achou := False; if not mtFator.IsNull then begin if mtFatorInvertido.Value then begin A := mtUnidProd.Value; B := mtUnidXML.Value; end else begin A := mtUnidXML.Value; B := mtUnidProd.Value; end; if mtFatorUniv.Value then Achou := tConvUnid.FindKey([A, B, True]) else Achou := tConvUnid.FindKey([A, B, False, mtProduto.Value]); end; if Achou then tConvUnid.Edit else tConvUnid.Append; if mtNewFatorInvertido.Value then begin A := mtUnidProd.Value; B := mtUnidXML.Value; end else begin A := mtUnidXML.Value; B := mtUnidProd.Value; end; tConvUnidA.Value := A; tConvUnidB.Value := B; tConvUnidUniversal.Value := mtNewFatorUniv.Value; if mtNewFatorUniv.Value then tConvUnidProduto.Clear else tConvUnidProduto.Value := mtProduto.Value; tConvUnidFator.Value := mtNewFator.Value; tConvUnid.Post; end; end.
unit AnyTest_c; {This file was generated on 27 Oct 2000 17:40:35 GMT by version 03.03.03.C1.06} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file } {C:\Examples\IDL2PA~1\Any\AnyTest.idl. } {Delphi Pascal unit : AnyTest_c } {derived from IDL module : default } interface uses CORBA, AnyTest_i; type TMyTestHelper = class; TMyTestStub = class; TMyTestHelper = class class procedure Insert (var _A: CORBA.Any; const _Value : AnyTest_i.MyTest); class function Extract(var _A: CORBA.Any) : AnyTest_i.MyTest; class function TypeCode : CORBA.TypeCode; class function RepositoryId : string; class function Read (const _Input : CORBA.InputStream) : AnyTest_i.MyTest; class procedure Write(const _Output : CORBA.OutputStream; const _Value : AnyTest_i.MyTest); class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : AnyTest_i.MyTest; class function Bind(const _InstanceName : string = ''; _HostName : string = '') : AnyTest_i.MyTest; overload; class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : AnyTest_i.MyTest; overload; end; TMyTestStub = class(CORBA.TCORBAObject, AnyTest_i.MyTest) public function GetAny : ANY; virtual; end; implementation class procedure TMyTestHelper.Insert(var _A : CORBA.Any; const _Value : AnyTest_i.MyTest); begin _A := Orb.MakeObjectRef( TMyTestHelper.TypeCode, _Value as CORBA.CORBAObject); end; class function TMyTestHelper.Extract(var _A : CORBA.Any): AnyTest_i.MyTest; var _obj : Corba.CorbaObject; begin _obj := Orb.GetObjectRef(_A); Result := TMyTestHelper.Narrow(_obj, True); end; class function TMyTestHelper.TypeCode : CORBA.TypeCode; begin Result := ORB.CreateInterfaceTC(RepositoryId, 'MyTest'); end; class function TMyTestHelper.RepositoryId : string; begin Result := 'IDL:MyTest:1.0'; end; class function TMyTestHelper.Read(const _Input : CORBA.InputStream) : AnyTest_i.MyTest; var _Obj : CORBA.CORBAObject; begin _Input.ReadObject(_Obj); Result := Narrow(_Obj, True) end; class procedure TMyTestHelper.Write(const _Output : CORBA.OutputStream; const _Value : AnyTest_i.MyTest); begin _Output.WriteObject(_Value as CORBA.CORBAObject); end; class function TMyTestHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : AnyTest_i.MyTest; begin Result := nil; if (_Obj = nil) or (_Obj.QueryInterface(AnyTest_i.MyTest, Result) = 0) then exit; if _IsA and _Obj._IsA(RepositoryId) then Result := TMyTestStub.Create(_Obj); end; class function TMyTestHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : AnyTest_i.MyTest; begin Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True); end; class function TMyTestHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : AnyTest_i.MyTest; begin Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True); end; function TMyTestStub.GetAny : ANY; var _Output: CORBA.OutputStream; _Input : CORBA.InputStream; begin inherited _CreateRequest('GetAny',True, _Output); inherited _Invoke(_Output, _Input); _Input.ReadAny(Result); end; initialization end.
unit NtUtils.Threads.Stack; interface uses NtUtils.Exceptions; // Get current address (address of the next instruction to be executed) function RtlxCurrentAddress: Pointer; register; // Get return address (address of the caller of the current function) function RtlxCallersAddress: Pointer; inline; // Get address of the caller's caller function RtlxCallersCallerAddress: Pointer; inline; // Capture a stack trace of the current thread function RtlxCaptureStackTrace(out BackTrace: TArray<Pointer>; FramesToCapture: Cardinal = 32; FramesToSkip: Cardinal = 0): Word; inline; implementation uses Ntapi.ntrtl; function RtlxCurrentAddress: Pointer; register; begin // Return address whitin a non-inline function is the address of the next // instruction after it returns Result := ReturnAddress; end; function RtlxCallersAddress: Pointer; inline; begin // Inlined return address Result := ReturnAddress; end; function RtlxCallersCallerAddress: Pointer; inline; var Dummy: Pointer; begin // The first out param is the return address (use RtlxCallersAddress to // obtain it), the second out param is the second level return address. RtlGetCallersAddress(Dummy, Result); end; function RtlxCaptureStackTrace(out BackTrace: TArray<Pointer>; FramesToCapture: Cardinal; FramesToSkip: Cardinal): Word; inline; begin // Alloc enough space for the requested stack trace SetLength(BackTrace, FramesToCapture); // Get the stack trace. Note that the function is inlined Result := RtlCaptureStackBackTrace(FramesToSkip, FramesToCapture, BackTrace, nil); // Truncare the result SetLength(BackTrace, Result); end; end.
unit IdGlobal; interface {$I IdCompilerDefines.inc} uses Classes, IdException, SysUtils; const IdTimeoutDefault = -1; IdTimeoutInfinite = -2; wsOk = 1; wsErr = 0; IdPORT_ECHO = 7; IdPORT_DISCARD = 9; IdPORT_SYSTAT = 11; IdPORT_DAYTIME = 13; IdPORT_NETSTAT = 15; IdPORT_QOTD = 17; IdPORT_CHARGEN = 19; {UDP Server!} IdPORT_FTP = 21; IdPORT_TELNET = 23; IdPORT_SMTP = 25; IdPORT_TIME = 37; IdPORT_WHOIS = 43; IdPORT_DOMAIN = 53; IdPORT_TFTP = 69; IdPORT_GOPHER = 70; IdPORT_FINGER = 79; IdPORT_HTTP = 80; IdPORT_HOSTNAME = 101; IdPORT_POP2 = 109; IdPORT_POP3 = 110; IdPORT_AUTH = 113; IdPORT_NNTP = 119; IdPORT_SNTP = 123; IdPORT_IMAP4 = 143; IdPORT_SSL = 443; IdPORT_LPD = 515; IdPORT_DICT = 2628; IdPORT_IRC = 6667; gsIdProductName = 'Indy'; { do not localize } gsIdVersion = '8.0.25'; { do not localize } // CHAR0 = #0; BACKSPACE = #8; LF = #10; CR = #13; EOL = CR + LF; TAB = #9; CHAR32 = #32; {$IFDEF Linux} GPathSep = '/'; { do not localize } {$ELSE} GPathSep = '\'; { do not localize } {$ENDIF} type {$IFDEF LINUX} TThreadPriority = (tpIdle, tpLowest, tpLower, tpNormal, tpHigher, tpHighest, pTimeCritical); {$ENDIF} TStringEvent = procedure(ASender: TComponent; const AString: string); TPosProc = function(const Substr, S: string): Integer; TIdMimeTable = class(TObject) protected FMIMEList: TStringList; FFileExt: TStringList; public procedure BuildCache; virtual; function GetFileMIMEType(const fileName: string): string; function getDefaultFileExt(const MIMEType: string): string; constructor Create(Autofill: boolean = true); virtual; destructor Destroy; override; end; TCharSet = (csGB2312, csBig5, csIso2022jp, csEucKR, csIso88591); {$IFDEF LINUX} TIdPID = Integer; {$ELSE} TIdPID = LongWord; {$ENDIF} //This is called whenever there is a failure to retreive the time zone information EIdFailedToRetreiveTimeZoneInfo = class(EIdException); //This usually is a property editor exception EIdCorruptServicesFile = class(EIdException); {$IFNDEF VCL5ORABOVE} function AnsiSameText(const S1, S2: string): Boolean; function IncludeTrailingBackSlash(const APath: string): string; procedure FreeAndNil(var Obj); {$ENDIF} procedure CommaSeperatedToStringList(AList: TStrings; const Value: string); function CopyFileTo(const Source, Destination: string): Boolean; function CurrentProcessId: TIdPID; function DateTimeToGmtOffSetStr(ADateTime: TDateTime; SubGMT: Boolean): string; function DateTimeToInternetStr(const Value: TDateTime): string; procedure DebugOutput(const AText: string); function Fetch(var AInput: string; const ADelim: string = ' '; const ADelete: { do not localize } Boolean = true) : string; function FileSizeByName(sFilename: string): cardinal; function GetMIMETypeFromFile(AFile: TFileName): string; function GetSystemLocale: TCharSet; function GetTickCount: Cardinal; function GmtOffsetStrToDateTime(S: string): TDateTime; function IntToBin(Value: cardinal): string; function IdPorts: TList; function IsCurrentThread(AThread: TThread): boolean; function IsNumeric(c: char): Boolean; function InMainThread: boolean; function Max(AValueOne, AValueTwo: Integer): Integer; function MakeTempFilename: string; function Min(AValueOne, AValueTwo: Integer): Integer; function OffsetFromUTC: TDateTime; procedure ParseURI(URI: string; var Protocol, Host, path, Document, Port, Bookmark: string); function PosInStrArray(SearchStr: string; Contents: array of string; const CaseSensitive: Boolean = True): Integer; function RightStr(st: string; Len: Integer): string; function ROL(val: LongWord; shift: Byte): LongWord; function ROR(val: LongWord; shift: Byte): LongWord; function RPos(const ASub, AIn: string; AStart: Integer = -1): Integer; function SetLocalTime(Value: TDateTime): boolean; procedure SetThreadPriority(AThread: TThread; const APriority: TThreadPriority); procedure Sleep(ATime: cardinal); function StrToCard(AVal: string): Cardinal; function StrInternetToDateTime(Value: string): TDateTime; function StrToDay(const ADay: string): Byte; function StrToMonth(const AMonth: string): Byte; function TimeZoneBias: Double; function UpCaseFirst(S: string): string; function GMTToLocalDateTime(S: string): TDateTime; function URLDecode(psSrc: string): string; function URLEncode(const psSrc: string): string; var IndyPos: TPosProc = nil; {$IFDEF LINUX} GOffsetFromUTC: TDateTime = 0; GSystemLocale: TCharSet = csIso88591; GTimeZoneBias: Double = 0; {$ENDIF} implementation uses {$IFDEF LINUX} Libc, IdStack, {$ELSE} Registry, Windows, {$ENDIF} IdResourceStrings, IdURI; const WhiteSpace = [#0..#12, #14..' ']; {do not localize} var FIdPorts: TList; {$IFNDEF LINUX} ATempPath: string; {$ENDIF} function RawStrInternetToDateTime(var Value: string): TDateTime; var i: Integer; Dt, Mo, Yr, Ho, Min, Sec: Word; sTime: string; begin Result := 0.0; Value := Trim(Value); if length(Value) = 0 then begin Exit; end; try if StrToDay(Copy(Value, 1, 3)) > 0 then begin Fetch(Value); end; Dt := StrToIntDef(Fetch(Value), 1); Value := TrimLeft(Value); Mo := StrToMonth(Fetch(Value)); Value := TrimLeft(Value); Yr := StrToIntDef(Fetch(Value), 1900); if Yr < 80 then begin Inc(Yr, 2000); end else if Yr < 100 then begin Inc(Yr, 1900); end; Result := EncodeDate(Yr, Mo, Dt); Value := TrimLeft(Value); i := IndyPos(':', Value); {do not localize} if i > 0 then begin sTime := fetch(Value, ' '); {do not localize} Ho := StrToIntDef(Fetch(sTime, ':'), 0); {do not localize} Min := StrToIntDef(Fetch(sTime, ':'), 0); {do not localize} Sec := StrToIntDef(Fetch(sTime), 0); Result := Result + EncodeTime(Ho, Min, Sec, 0); end; Value := TrimLeft(Value); except Result := 0.0; end; end; {$IFNDEF VCL5ORABOVE} function AnsiSameText(const S1, S2: string): Boolean; begin Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, PChar(S1) , Length(S1), PChar(S2), Length(S2)) = 2; end; function IncludeTrailingBackSlash(const APath: string): string; begin Result := APath; if not IsPathDelimiter(Result, Length(Result)) then begin Result := Result + '\'; {do not localize} end; end; procedure FreeAndNil(var Obj); var P: TObject; begin P := TObject(Obj); TObject(Obj) := nil; P.Free; end; {$ENDIF} {$IFNDEF LINUX} {$IFNDEF VCL5ORABOVE} function CreateTRegistry: TRegistry; begin Result := TRegistry.Create; end; {$ELSE} function CreateTRegistry: TRegistry; begin Result := TRegistry.Create(KEY_READ); end; {$ENDIF} {$ENDIF} function Max(AValueOne, AValueTwo: Integer): Integer; begin if AValueOne < AValueTwo then begin Result := AValueTwo end else begin Result := AValueOne; end; end; function Min(AValueOne, AValueTwo: Integer): Integer; begin if AValueOne > AValueTwo then begin Result := AValueTwo end else begin Result := AValueOne; end; end; {This should never be localized} function DateTimeToInternetStr(const Value: TDateTime): string; const wdays: array[1..7] of string = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'); { do not localize } monthnames: array[1..12] of string = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', { do not localize } 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); {do not localize} var wDay, wMonth, wYear: Word; begin DecodeDate(Value, wYear, wMonth, wDay); Result := Format('%s, %d %s %d %s %s', {do not localize} [wdays[DayOfWeek(Value)], wDay, monthnames[wMonth], wYear, FormatDateTime('hh:nn:ss', Value), {do not localize} DateTimeToGmtOffSetStr(OffsetFromUTC, False)]); end; function StrInternetToDateTime(Value: string): TDateTime; begin Result := RawStrInternetToDateTime(Value); end; procedure CommaSeperatedToStringList(AList: TStrings; const Value: string); var iStart, iEnd, iQuote, iPos, iLength: integer; sTemp: string; begin iQuote := 0; iPos := 1; iLength := Length(Value); AList.Clear; while (iPos <= iLength) do begin iStart := iPos; iEnd := iStart; while (iPos <= iLength) do begin if Value[iPos] = '"' then {do not localize} begin inc(iQuote); end; if Value[iPos] = ',' then {do not localize} begin if iQuote <> 1 then begin break; end; end; inc(iEnd); inc(iPos); end; sTemp := Trim(Copy(Value, iStart, iEnd - iStart)); if Length(sTemp) > 0 then begin AList.Add(sTemp); end; iPos := iEnd + 1; iQuote := 0; end; end; {$IFDEF LINUX} function CopyFileTo(const Source, Destination: string): Boolean; var SourceStream: TFileStream; begin result := false; if not FileExists(Destination) then begin SourceStream := TFileStream.Create(Source, fmOpenRead); try with TFileStream.Create(Destination, fmCreate) do try CopyFrom(SourceStream, 0); finally free; end; finally SourceStream.free; end; result := true; end; end; {$ELSE} function CopyFileTo(const Source, Destination: string): Boolean; begin Result := CopyFile(PChar(Source), PChar(Destination), true); end; {$ENDIF} {$IFNDEF LINUX} function TempPath: string; var i: integer; begin SetLength(Result, MAX_PATH); i := GetTempPath(Length(Result), PChar(Result)); SetLength(Result, i); IncludeTrailingBackSlash(Result); end; {$ENDIF} function MakeTempFilename: string; begin {$IFDEF LINUX} Result := tempnam(nil, 'Indy'); {do not localize} {$ELSE} SetLength(Result, MAX_PATH + 1); GetTempFileName(PChar(ATempPath), 'Indy', 0, PChar(result)); {do not localize} Result := PChar(Result); {$ENDIF} end; function RPos(const ASub, AIn: string; AStart: Integer = -1): Integer; var i: Integer; LStartPos: Integer; LTokenLen: Integer; begin result := 0; LTokenLen := Length(ASub); if AStart = -1 then begin AStart := Length(AIn); end; if AStart < (Length(AIn) - LTokenLen + 1) then begin LStartPos := AStart; end else begin LStartPos := (Length(AIn) - LTokenLen + 1); end; for i := LStartPos downto 1 do begin if AnsiSameText(Copy(AIn, i, LTokenLen), ASub) then begin result := i; break; end; end; end; function GetSystemLocale: TCharSet; begin {$IFDEF LINUX} Result := GSystemLocale; {$ELSE} case SysLocale.PriLangID of LANG_CHINESE: if SysLocale.SubLangID = SUBLANG_CHINESE_SIMPLIFIED then Result := csGB2312 else Result := csBig5; LANG_JAPANESE: Result := csIso2022jp; LANG_KOREAN: Result := csEucKR; else Result := csIso88591; end; {$ENDIF} end; function FileSizeByName(sFilename: string): cardinal; var sFile: TFileStream; begin sFile := TFileStream.Create(sFilename, fmOpenRead or fmShareDenyNone); try result := sFile.Size; finally sFile.free; end; end; function RightStr(st: string; Len: Integer): string; begin if (Len > Length(st)) or (Len < 0) then begin Result := st; end else begin Result := Copy(St, Length(st) - Len, Len); end; end; {$IFDEF LINUX} function OffsetFromUTC: TDateTime; begin Result := GOffsetFromUTC; end; {$ELSE} function OffsetFromUTC: TDateTime; var iBias: Integer; tmez: TTimeZoneInformation; begin case GetTimeZoneInformation(tmez) of TIME_ZONE_ID_INVALID: raise EIdFailedToRetreiveTimeZoneInfo.Create(RSFailedTimeZoneInfo); TIME_ZONE_ID_UNKNOWN: iBias := tmez.Bias; TIME_ZONE_ID_DAYLIGHT: iBias := tmez.Bias + tmez.DaylightBias; TIME_ZONE_ID_STANDARD: iBias := tmez.Bias + tmez.StandardBias; else raise EIdFailedToRetreiveTimeZoneInfo.Create(RSFailedTimeZoneInfo); end; Result := EncodeTime(Abs(iBias) div 60, Abs(iBias) mod 60, 0, 0); if iBias > 0 then begin Result := 0 - Result; end; end; {$ENDIF} function StrToCard(AVal: string): Cardinal; begin Result := StrToInt64Def(Trim(AVal), 0); end; {$IFDEF LINUX} function TimeZoneBias: Double; begin Result := GTimeZoneBias; end; {$ELSE} function TimeZoneBias: Double; var ATimeZone: TTimeZoneInformation; begin if (GetTimeZoneInformation(ATimeZone) = TIME_ZONE_ID_DAYLIGHT) then begin result := ATimeZone.Bias + ATimeZone.DaylightBias; end else begin result := ATimeZone.Bias + ATimeZone.StandardBias; end; Result := Result / 1440; end; {$ENDIF} function GetTickCount: Cardinal; begin {$IFDEF LINUX} Result := clock div (CLOCKS_PER_SEC div 1000); {$ELSE} Result := Windows.GetTickCount; {$ENDIF} end; {$IFDEF LINUX} function SetLocalTime(Value: TDateTime): boolean; begin result := False; end; {$ELSE} function SetLocalTime(Value: TDateTime): boolean; var SysTimeVar: TSystemTime; begin DateTimeToSystemTime(Value, SysTimeVar); Result := Windows.SetLocalTime(SysTimeVar); end; {$ENDIF} function IdPorts: TList; var sLocation, s: string; idx, i, iPrev, iPosSlash: integer; sl: TStringList; begin if FIdPorts = nil then begin FIdPorts := TList.Create; {$IFDEF LINUX} sLocation := '/etc/'; {do not localize} {$ELSE} SetLength(sLocation, MAX_PATH); SetLength(sLocation, GetWindowsDirectory(pchar(sLocation), MAX_PATH)); sLocation := IncludeTrailingBackslash(sLocation); if Win32Platform = VER_PLATFORM_WIN32_NT then begin sLocation := sLocation + 'system32\drivers\etc\'; {do not localize} end; {$ENDIF} sl := TStringList.Create; try sl.LoadFromFile(sLocation + 'services'); {do not localize} iPrev := 0; for idx := 0 to sl.Count - 1 do begin s := sl[idx]; iPosSlash := IndyPos('/', s); {do not localize} if (iPosSlash > 0) and (not (IndyPos('#', s) in [1..iPosSlash])) then { do not localize } {do not localize} begin i := iPosSlash; repeat dec(i); if i = 0 then begin raise EIdCorruptServicesFile.CreateFmt(RSCorruptServicesFile, [sLocation + 'services']); {do not localize} end; until s[i] in WhiteSpace; i := StrToInt(Copy(s, i + 1, iPosSlash - i - 1)); if i <> iPrev then begin FIdPorts.Add(TObject(i)); end; iPrev := i; end; end; finally sl.Free; end; end; Result := FIdPorts; end; function Fetch(var AInput: string; const ADelim: string = ' '; const ADelete: { do not localize } Boolean = true) : string; var iPos: Integer; begin if ADelim = #0 then begin iPos := Pos(ADelim, AInput); end else begin iPos := IndyPos(ADelim, AInput); end; if iPos = 0 then begin Result := AInput; if ADelete then begin AInput := ''; { do not localize } end; end else begin result := Copy(AInput, 1, iPos - 1); if ADelete then begin Delete(AInput, 1, iPos + Length(ADelim) - 1); end; end; end; function PosInStrArray(SearchStr: string; Contents: array of string; const CaseSensitive: Boolean = True): Integer; begin for Result := Low(Contents) to High(Contents) do begin if CaseSensitive then begin if SearchStr = Contents[Result] then begin Exit; end; end else begin if ANSISameText(SearchStr, Contents[Result]) then begin Exit; end; end; end; Result := -1; end; function IsCurrentThread(AThread: TThread): boolean; begin result := AThread.ThreadID = GetCurrentThreadID; end; function IsNumeric(c: char): Boolean; begin Result := Pos(c, '0123456789') > 0; {do not localize} end; function StrToDay(const ADay: string): Byte; begin Result := Succ(PosInStrArray(Uppercase(ADay), ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'])); {do not localize} end; function StrToMonth(const AMonth: string): Byte; begin Result := Succ(PosInStrArray(Uppercase(AMonth), ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'])); {do not localize} end; function UpCaseFirst(S: string): string; begin Result := LowerCase(S); if Result <> '' then { do not localize } begin Result[1] := UpCase(Result[1]); end; end; function DateTimeToGmtOffSetStr(ADateTime: TDateTime; SubGMT: Boolean): string; var AHour, AMin, ASec, AMSec: Word; begin if (ADateTime = 0.0) and SubGMT then begin Result := 'GMT'; {do not localize} Exit; end; DecodeTime(ADateTime, AHour, AMin, ASec, AMSec); Result := Format(' %0.2d%0.2d', [AHour, AMin]); {do not localize} if ADateTime < 0.0 then begin Result[1] := '-'; {do not localize} end else begin Result[1] := '+'; {do not localize} end; end; function GetMIMETypeFromFile(AFile: TFileName): string; var MIMEMap: TIdMIMETable; begin MIMEMap := TIdMimeTable.Create(true); try result := MIMEMap.GetFileMIMEType(AFile); finally MIMEMap.Free; end; end; procedure ParseURI(URI: string; var Protocol, Host, path, Document, Port, Bookmark: string); begin TIdURI.ParseURI(URI, Protocol, Host, path, Document, Port, Bookmark); end; function GmtOffsetStrToDateTime(S: string): TDateTime; begin Result := 0.0; S := Copy(Trim(s), 1, 5); if Length(S) > 0 then begin if s[1] in ['-', '+'] then {do not localize} begin try Result := EncodeTime(StrToInt(Copy(s, 2, 2)), StrToInt(Copy(s, 4, 2)), 0, 0); if s[1] = '-' then {do not localize} begin Result := -Result; end; except Result := 0.0; end; end; end; end; function GMTToLocalDateTime(S: string): TDateTime; var DateTimeOffset: TDateTime; begin Result := RawStrInternetToDateTime(S); if Length(S) < 5 then begin DateTimeOffset := 0.0 end else begin DateTimeOffset := GmtOffsetStrToDateTime(S); end; if DateTimeOffset < 0.0 then begin Result := Result + Abs(DateTimeOffset); end else begin Result := Result - DateTimeOffset; end; Result := Result + OffSetFromUTC; end; procedure Sleep(ATime: cardinal); begin {$IFDEF LINUX} GStack.WSSelect(nil, nil, nil, ATime) {$ELSE} Windows.Sleep(ATime); {$ENDIF} end; function IntToBin(Value: cardinal): string; var i: Integer; begin SetLength(result, 32); for i := 1 to 32 do begin if ((Value shl (i - 1)) shr 31) = 0 then result[i] := '0' {do not localize} else result[i] := '1'; {do not localize} end; end; function CurrentProcessId: TIdPID; begin {$IFDEF LINUX} Result := getpid; {$ELSE} Result := GetCurrentProcessID; {$ENDIF} end; function ROL(val: LongWord; shift: Byte): LongWord; assembler; asm mov eax, val; mov cl, shift; rol eax, cl; end; function ROR(val: LongWord; shift: Byte): LongWord; assembler; asm mov eax, val; mov cl, shift; ror eax, cl; end; procedure DebugOutput(const AText: string); begin {$IFDEF LINUX} __write(stderr, AText, Length(AText)); __write(stderr, EOL, Length(EOL)); {$ELSE} OutputDebugString(PChar(AText)); {$ENDIF} end; function InMainThread: boolean; begin result := GetCurrentThreadID = MainThreadID; end; {$IFDEF Linux} procedure TIdMimeTable.BuildCache; begin end; {$ELSE} procedure TIdMimeTable.BuildCache; var reg: TRegistry; KeyList: TStringList; i: Integer; begin Reg := CreateTRegistry; try KeyList := TStringList.create; try Reg.RootKey := HKEY_CLASSES_ROOT; Reg.OpenKeyReadOnly('\'); {do not localize} Reg.GetKeyNames(KeyList); reg.Closekey; for i := 0 to KeyList.Count - 1 do begin if Copy(KeyList[i], 1, 1) = '.' then {do not localize} begin reg.OpenKeyReadOnly(KeyList[i]); if Reg.ValueExists('Content Type') then {do not localize} begin FFileExt.Values[KeyList[i]] := Reg.ReadString('Content Type'); { do not localize } {do not localize} end; reg.CloseKey; end; end; Reg.OpenKeyreadOnly('\MIME\Database\Content Type'); {do not localize} KeyList.Clear; Reg.GetKeyNames(KeyList); reg.Closekey; for i := 0 to KeyList.Count - 1 do begin Reg.OpenKeyreadOnly('\MIME\Database\Content Type\' + KeyList[i]); { do not localize } {do not localzie} FMIMEList.Values[reg.ReadString('Extension')] := KeyList[i]; { do not localize } {do not localize} Reg.CloseKey; end; finally KeyList.Free; end; finally reg.free; end; end; {$ENDIF} constructor TIdMimeTable.Create(Autofill: boolean); begin FFileExt := TStringList.Create; FMIMEList := TStringList.Create; if Autofill then BuildCache; end; destructor TIdMimeTable.Destroy; begin FreeAndNil(FMIMEList); FreeAndNil(FFileExt); inherited; end; function TIdMimeTable.getDefaultFileExt(const MIMEType: string): string; begin result := FMIMEList.Values[MIMEType]; if Length(result) = 0 then begin BuildCache; result := FMIMEList.Values[MIMEType]; ; end; end; function TIdMimeTable.GetFileMIMEType(const fileName: string): string; begin result := FFileExt.Values[ExtractFileExt(FileName)]; if Length(result) = 0 then begin BuildCache; result := FMIMEList.Values[ExtractFileExt(FileName)]; if Length(result) = 0 then begin result := 'application/octet-stream'; {do not localize} end; end; end; procedure SetThreadPriority(AThread: TThread; const APriority: TThreadPriority); begin {$IFDEF LINUX} {$ELSE} AThread.Priority := APriority; {$ENDIF} end; function URLDecode(psSrc: string): string; var i: Integer; ESC: string[2]; CharCode: integer; begin Result := ''; { do not localize } psSrc := StringReplace(psSrc, '+', ' ', [rfReplaceAll]); {do not localize} i := 1; while i <= Length(psSrc) do begin if psSrc[i] <> '%' then { do not localize } begin {do not localize} Result := Result + psSrc[i] end else begin Inc(i); ESC := Copy(psSrc, i, 2); Inc(i, 1); try CharCode := StrToInt('$' + ESC); {do not localize} if (CharCode > 0) and (CharCode < 256) then Result := Result + Char(CharCode); except end; end; Inc(i); end; end; function URLEncode(const psSrc: string): string; const UnsafeChars = ' *#%<>'; {do not localize} var i: Integer; begin Result := ''; { do not localize } for i := 1 to Length(psSrc) do begin if (IndyPos(psSrc[i], UnsafeChars) > 0) or (psSrc[i] >= #$80) then begin Result := Result + '%' + IntToHex(Ord(psSrc[i]), 2); {do not localize} end else begin Result := Result + psSrc[i]; end; end; end; function SBPos(const Substr, S: string): Integer; begin Result := Pos(Substr, S); end; initialization {$IFDEF LINUX} {$ELSE} ATempPath := TempPath; {$ENDIF} if LeadBytes = [] then begin IndyPos := SBPos; end else begin IndyPos := AnsiPos; end; finalization FIdPorts.Free; end.
unit JD.Weather.Foreca; interface uses System.Classes, System.SysUtils, System.Generics.Collections, Vcl.Graphics, Vcl.Imaging.Jpeg, Vcl.Imaging.PngImage, Vcl.Imaging.GifImg, JD.Weather, JD.Weather.Intf, SuperObject; type TForecaWeatherThread = class(TJDWeatherThread) public function GetUrl: String; override; function DoAll(Conditions: TWeatherConditions; Forecast: TWeatherForecast; ForecastDaily: TWeatherForecast; ForecastHourly: TWeatherForecast; Alerts: TWeatherAlerts; Maps: TWeatherMaps): Boolean; override; function DoConditions(Conditions: TWeatherConditions): Boolean; override; function DoForecast(Forecast: TWeatherForecast): Boolean; override; function DoForecastHourly(Forecast: TWeatherForecast): Boolean; override; function DoForecastDaily(Forecast: TWeatherForecast): Boolean; override; function DoAlerts(Alerts: TWeatherAlerts): Boolean; override; function DoMaps(Maps: TWeatherMaps): Boolean; override; end; implementation uses DateUtils, StrUtils, Math; { TForecaWeatherThread } function TForecaWeatherThread.GetUrl: String; begin Result:= 'http://apitest.foreca.net/'; Result:= Result + '?key='+Owner.Key; Result:= Result + '&format=json'; //http://apitest.foreca.net/?lon=24.934&lat=60.1755&key=yxDYDu3IIlRJzjBVaoje7jtLa4A&format=json end; function TForecaWeatherThread.DoAll(Conditions: TWeatherConditions; Forecast, ForecastDaily, ForecastHourly: TWeatherForecast; Alerts: TWeatherAlerts; Maps: TWeatherMaps): Boolean; begin Result:= False; end; function TForecaWeatherThread.DoConditions(Conditions: TWeatherConditions): Boolean; begin Result:= False; end; function TForecaWeatherThread.DoForecast(Forecast: TWeatherForecast): Boolean; begin Result:= False; end; function TForecaWeatherThread.DoForecastDaily( Forecast: TWeatherForecast): Boolean; begin Result:= False; end; function TForecaWeatherThread.DoForecastHourly( Forecast: TWeatherForecast): Boolean; begin Result:= False; end; function TForecaWeatherThread.DoAlerts(Alerts: TWeatherAlerts): Boolean; begin Result:= False; end; function TForecaWeatherThread.DoMaps(Maps: TWeatherMaps): Boolean; begin Result:= False; end; end.
unit Unit2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TMyThreadUpdate = reference to procedure (const AUpdateText: string); TMyThread = class(TThread) strict private FOnUpdate: TMyThreadUpdate; procedure DoUpdate; strict protected procedure Execute; override; public constructor Create(const AOnUpdate: TMyThreadUpdate); reintroduce; destructor Destroy; override; end; TForm2 = class(TForm) Edit1: TEdit; Button1: TButton; procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormDestroy(Sender: TObject); strict private FThread: TMyThread; FOnThreadFinished: TNotifyEvent; procedure HandleThreadUpdate(const AUpdateText: string); procedure HandleThreadFinished(Sender: TObject); public property OnThreadFinished: TNotifyEvent write FOnThreadFinished; end; var Form2: TForm2; implementation {$R *.dfm} procedure TForm2.FormShow(Sender: TObject); begin {}FThread := TMyThread.Create({}HandleThreadUpdate); FThread.OnTerminate := HandleThreadFinished; FThread.FreeOnTerminate := True; {}FThread.Start; /////// while not FThread.Started do begin end; FThread.Free; end; procedure TForm2.FormDestroy(Sender: TObject); begin // FThread.Free; end; procedure TForm2.HandleThreadUpdate(const AUpdateText: string); begin Edit1.Text := AUpdateText; end; procedure TForm2.HandleThreadFinished(Sender: TObject); begin if Assigned(FOnThreadFinished) then FOnThreadFinished(nil); end; procedure TForm2.Button1Click(Sender: TObject); begin // if Assigned(FThread) then {}FThread.Terminate; // begin // if TerminateThread(FThread.Handle, 0) then // MessageDlg('Thread terminated successfully.', mtInformation, [mbOK], 0) // else // raise Exception.Create('Failed to terminate thread.'); // end; end; { TMyThread } constructor TMyThread.Create(const AOnUpdate: TMyThreadUpdate); begin {}inherited Create(True); {}FOnUpdate := AOnUpdate; end; destructor TMyThread.Destroy; begin // OnTerminate := nil; // FOnUpdate := nil; inherited Destroy; end; procedure TMyThread.Execute; begin /////// inherited Execute; while {}not {}Terminated do // while True do begin Sleep(1000); {}Synchronize({}DoUpdate); end; end; procedure TMyThread.DoUpdate; begin if Assigned(FOnUpdate) then FOnUpdate(FormatDateTime('ddmmyyyy hh:nn:ss', Now)); end; end.
unit grafo_obj; interface uses ExtCtrls, StdCtrls; const nulo=nil; type tipo_est=0..1; posicion_vertice = ^nodo_vertice; nodo_vertice = record estado:tipo_est; l,t:integer; end; obstaculo = record nombre:string; N1,N2,N3,N4:posicion_vertice; end; posicion_o = ^nodo_obstaculo; nodo_obstaculo = record dato: obstaculo; ante, prox: posicion_o; end; lista_obstaculos = record inicio, final: posicion_o; end; procedure crear_lista_obstaculos(var l: lista_obstaculos); function lista_obstaculos_vacia(var l: lista_obstaculos): boolean; function lista_obstaculos_llena(var l: lista_obstaculos):boolean; procedure eliminar_o(var l:lista_obstaculos; p:posicion_o); function distancia(t1,t2,l1,l2:integer):integer; function buscar(var l:lista_obstaculos; x:string):posicion_o; procedure agregar_o(var l:lista_obstaculos; x:obstaculo); implementation procedure crear_lista_obstaculos(var l: lista_obstaculos); begin l.inicio:= nulo; l.final:= nulo; end; function lista_obstaculos_vacia(var l: lista_obstaculos): boolean; begin lista_obstaculos_vacia := (l.inicio = nulo); end; function lista_obstaculos_llena(var l: lista_obstaculos):boolean; var q: posicion_o; begin new(q); lista_obstaculos_llena := (q=nulo); dispose(q); end; procedure eliminar_o(var l:lista_obstaculos; p:posicion_o); var q:posicion_o; begin if not(lista_obstaculos_vacia(l)) then begin q:=p; if (p=l.inicio) and (p=l.final) then crear_lista_obstaculos(l) else if (p=l.inicio) then begin l.inicio:=l.inicio^.prox; l.inicio^.ante:=nulo; end else if (p=l.final) then begin l.final:=l.final^.ante; l.final^.prox:=nulo; end else begin p^.ante^.prox:=p^.prox; p^.prox^.ante:=p^.ante; end; dispose(q); end; end; function distancia(t1,t2,l1,l2:integer):integer; var aux:integer; begin if t1 > t2 then aux:=t1-t2 else aux:=t2-t1; if l1 > l2 then aux:=l1-l2+aux else aux:=l2-l1+aux; distancia:=aux; end; function buscar(var l:lista_obstaculos; x:string):posicion_o; var q: posicion_o; encontre : boolean; begin buscar := nulo; q := l.inicio; encontre := false; while (q <> nulo) and (not(encontre)) do if q.dato.nombre<>x then q := q^.prox else encontre := true; if encontre then buscar := q; end; procedure agregar_o (var l:lista_obstaculos; x:obstaculo); var q: posicion_o; begin if not(lista_obstaculos_llena(l)) then begin new(q); q^.dato := x; q^.prox := nulo; q^.ante := l.final; if lista_obstaculos_vacia(l) then l.inicio :=q else l.final^.prox := q; l.final := q; end; end; end.
unit LogReaderMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxTextEdit, cxMaskEdit, cxButtonEdit, dxmdaset, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxGroupBox, GMGlobals, cxMemo, cxCalendar, cxLabel; type TLogReaderMainForm = class(TForm) cxGroupBox1: TcxGroupBox; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; mdLog: TdxMemData; mdLogText: TMemoField; mdLogDT: TDateTimeField; mdLogThreadID: TIntegerField; mdLogDirection: TStringField; mdLogSource: TStringField; mdLogLength: TIntegerField; eFileName: TcxButtonEdit; FileOpenDialog1: TFileOpenDialog; DataSource1: TDataSource; cxGrid1DBTableView1RecId: TcxGridDBColumn; cxGrid1DBTableView1DT: TcxGridDBColumn; cxGrid1DBTableView1ThreadID: TcxGridDBColumn; cxGrid1DBTableView1Direction: TcxGridDBColumn; cxGrid1DBTableView1Source: TcxGridDBColumn; cxGrid1DBTableView1Length: TcxGridDBColumn; cxGrid1DBTableView1Text: TcxGridDBColumn; procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxGrid1DBTableView1CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure eFileNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cxGrid1DBTableView1CellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure cxGrid1DBTableView1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FSearchString: string; procedure ProcessFiles; procedure InitGrid; procedure ProcessFile(const fileName: string); procedure ProcessString(const s: string); procedure PostDataSet; procedure SearchNext; procedure AskForSearchString; procedure PreviewXml(const s: string); { Private declarations } public { Public declarations } end; var LogReaderMainForm: TLogReaderMainForm; implementation uses Dateutils, XmlPreview; {$R *.dfm} function SQLStringToDateTime(const str: string): TDateTime; var y, m, d, hh, nn, ss, zz: word; s: string; begin Result := 0; try s := Trim(str); if pos('-', s) > 0 then begin y := StrToInt(Copy(s, 1, 4)); m := StrToInt(Copy(s, 6, 2)); d := StrToInt(Copy(s, 9, 2)); Delete(s, 1, 11); Result := EncodeDate(y, m, d); end; if Length(s) > 0 then begin hh := StrToInt(Copy(s, 1, 2)); nn := StrToInt(Copy(s, 4, 2)); ss := 0; if Length(s) > 6 then ss := StrToInt(Copy(s, 7, 2)); zz := 0; if Length(s) > 9 then zz := StrToInt(Copy(s, 10, 3)); Result := Result + EncodeTime(hh, nn, ss, zz); end; except Result := 0; end; end; procedure TLogReaderMainForm.PreviewXml(const s: string); begin XmlPreviewDlg.SetString(s); XmlPreviewDlg.Show(); end; procedure TLogReaderMainForm.cxGrid1DBTableView1CellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin PreviewXml(ACellViewInfo.RecordViewInfo.GridRecord.Values[cxGrid1DBTableView1Text.Index]); end; procedure TLogReaderMainForm.cxGrid1DBTableView1CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure ApplyColor(color: TColor); begin if not AViewInfo.Selected or AViewInfo.Focused then ACanvas.Font.Color := color; end; var dir: string; begin dir := Trim(AViewInfo.RecordViewInfo.GridRecord.Values[3]); if dir = '<' then ApplyColor(clRed); if dir = '?' then ApplyColor(clBlue); end; procedure TLogReaderMainForm.cxGrid1DBTableView1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Key = Ord('F')) then begin AskForSearchString(); SearchNext(); end; if (Shift = []) and (Key = VK_F3) then SearchNext(); if (Shift = []) and (Key = VK_RETURN) then PreviewXml(cxGrid1DBTableView1.DataController.Values[cxGrid1DBTableView1.DataController.FocusedRecordIndex, cxGrid1DBTableView1Text.Index]); end; procedure TLogReaderMainForm.AskForSearchString(); begin InputQuery('Строка поиска', '', FSearchString); end; procedure TLogReaderMainForm.SearchNext(); var recordIndex, i: int; s: string; begin for i := cxGrid1DBTableView1.DataController.FocusedRowIndex + 1 to cxGrid1DBTableView1.DataController.RowCount - 1 do begin recordIndex := cxGrid1DBTableView1.DataController.DataControllerInfo.GetRowInfo(i).RecordIndex; s := cxGrid1DBTableView1.DataController.Values[recordIndex, cxGrid1DBTableView1Text.Index]; if Pos(FSearchString, s) > 0 then begin cxGrid1DBTableView1.DataController.FocusedRowIndex := i; cxGrid1DBTableView1.DataController.ClearSelection(); cxGrid1DBTableView1.DataController.SelectRows(i, i); Exit; end; end; end; procedure TLogReaderMainForm.eFileNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin ProcessFiles(); Key := 0; end; end; procedure TLogReaderMainForm.FormCreate(Sender: TObject); begin {$ifdef DEBUG} eFileName.Text := 'D:\Programs\Delphi\Geomer\GMIOPSvc_trace1.log'; {$endif} end; procedure TLogReaderMainForm.FormShow(Sender: TObject); var i: int; begin eFileName.Text := ''; for i := 1 to ParamCount() do begin if eFileName.Text <> '' then eFileName.Text := eFileName.Text + ', '; eFileName.Text := eFileName.Text + Paramstr(i); end; ProcessFiles(); end; procedure TLogReaderMainForm.InitGrid(); begin mdLog.DisableControls(); mdLog.Close(); mdLog.Open(); end; procedure TLogReaderMainForm.PostDataSet(); begin mdLog.EnableControls(); end; procedure TLogReaderMainForm.ProcessString(const s: string); var lst: TArray<string>; dt: TDateTime; n: int; begin if Trim(s) = '' then Exit; lst := s.Split([#9]); if Length(lst) < 2 then Exit; dt := SQLStringToDateTime(lst[0]); if CompareDateTime(dt, 0) <= 0 then Exit; mdLog.Append(); mdLog.FieldByName('DT').AsDateTime := dt; if Length(lst) > 1 then mdLog.FieldByName('Text').AsString := lst[High(lst)]; if Length(lst) > 2 then begin n := StrToIntDef(lst[1], -1); if n > 0 then mdLog.FieldByName('ThreadID').AsInteger := n; end; if Length(lst) > 3 then mdLog.FieldByName('Direction').AsString := lst[2]; if Length(lst) > 4 then mdLog.FieldByName('Source').AsString := lst[3]; if Length(lst) > 5 then begin n := StrToIntDef(lst[4], -1); if n > 0 then mdLog.FieldByName('Length').AsInteger := n; end; mdLog.Post(); end; procedure TLogReaderMainForm.ProcessFile(const fileName: string); var f: TSTringList; i: int; begin if not FileExists(fileName) then Exit; f := TSTringList.Create(); try f.LoadFromFile(fileName); for i := 0 to f.Count - 1 do ProcessString(f[i]); finally f.Free(); end; end; procedure TLogReaderMainForm.ProcessFiles(); var sl: TSTringList; i: int; begin InitGrid(); sl := TSTringList.Create(); try sl.CommaText := eFileName.Text; for i := 0 to sl.Count - 1 do begin ProcessFile(sl[i]); end; finally sl.Free(); PostDataSet(); end; end; procedure TLogReaderMainForm.cxButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin if not FileOpenDialog1.Execute() then Exit; eFileName.Text := FileOpenDialog1.Files.CommaText; ProcessFiles(); end; end.
/// <summary> /// Contain Main class with FaceAPI async functions for end-user /// </summary> unit uFunctions.FaceApiAsyncHelper; interface uses { TTask.Create; TProc } System.SysUtils, { TDetectOptions } uFaceApi.FaceDetectOptions, { TBytesStream } System.Classes, { TAccess } uFaceApi.ServersAccess.Types; type /// <summary> /// Type of callback procedure with result for async functions /// </summary> TFaceApiAsyncCallback = procedure(AResult: String) of object; /// <summary> /// Main class with FaceAPI async functions for end-user /// </summary> FaceApiAsyncHelper = class private class procedure RunAsync(AProc: TProc); class procedure CallCallback(ACallbackMethod: TFaceApiAsyncCallback = nil; const AResult: String = ''); public /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Face|IFaceApiFace.DetectURL">interface DetectURL</see> /// </summary> class function DetectURL(AAccess: TAccessServer; const AURL: String; const ADetectOptions: TDetectOptions; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Face|IFaceApiFace.DetectFile">interface DetectFile</see> /// </summary> class function DetectFile(AAccess: TAccessServer; const AFileName: String; const ADetectOptions: TDetectOptions; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Face|IFaceApiFace.DetectStream">interface DetectStream</see> /// </summary> class function DetectStream(AAccess: TAccessServer; AStream: TBytesStream; const ADetectOptions: TDetectOptions; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.PersonGroup|IFaceApiPersonGroup.ListPersonGroups">interface ListPersonGroups</see> /// </summary> class function ListPersonGroups(AAccess: TAccessServer; ACallbackMethod: TFaceApiAsyncCallback = nil; const AStart: String = ''; const ATop: Integer = 1000): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Core|IFaceApiCore.ListPersonsInPersonGroup">interface ListPersonsInPersonGroup</see> /// </summary> class function ListPersonsInPersonGroup(AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Core|IFaceApiCore.AddPersonFaceURL">interface AddPersonFaceURL</see> /// </summary> class function AddPersonFaceURL(AAccess: TAccessServer; const AGroupID, APersonID, AURL, ATargetFace: String; const AUserData: String = ''; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Core|IFaceApiCore.CreatePerson">interface CreatePerson</see> /// </summary> class function CreatePerson(AAccess: TAccessServer; AGroupID: String; APersonName: String; APersonUserData: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.PersonGroup|IFaceApiPersonGroup.GetPersonGroupTrainingStatus">interface GetPersonGroupTrainingStatus</see> /// </summary> class function GetPersonGroupTrainingStatus(AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.PersonGroup|IFaceApiPersonGroup.TrainPersonGroup">interface TrainPersonGroup</see> /// </summary> class function TrainPersonGroup(AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.PersonGroup|IFaceApiPersonGroup.CreatePersonGroup">interface CreatePersonGroup</see> /// </summary> class function CreatePersonGroup(AAccess: TAccessServer; const AGroupID, AGroupName, AGroupUserData: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.PersonGroup|IFaceApiPersonGroup.DeletePersonGroup">interface DeletePersonGroup</see> /// </summary> class function DeletePersonGroup(AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Face|IFaceApiFace.Verify">interface Verify (overload)</see> /// </summary> class function Verify(AAccess: TAccessServer; const AFaceTempID1, AFaceTempID2: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; overload; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Face|IFaceApiFace.Verify">interface Verify (overload)</see> /// </summary> class function Verify(AAccess: TAccessServer; const AFaceTempID, APersonID, AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; overload; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Face|IFaceApiFace.Identify">interface Identify</see> /// </summary> class function Identify(AAccess: TAccessServer; AFaceIDS: TStringList; const AGroupID: String; const AMaxNumOfCandidatesReturned: Integer = 1; const AConfidenceThreshold: Double = 0.5; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.PersonGroup|IFaceApiPersonGroup.UpdatePersonGroup">interface UpdatePersonGroup</see> /// </summary> class function UpdatePersonGroup(AAccess: TAccessServer; const AGroupID: String; const AGroupName: String; const AGroupUserData: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.PersonGroup|IFaceApiPersonGroup.GetPersonGroup">interface GetPersonGroup</see> /// </summary> class function GetPersonGroup(AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Face|IFaceApiFace.FindSimilar">interface FindSimilar (overload)</see> /// </summary> class function FindSimilar(AAccess: TAccessServer; const AFaceID: String; const AListID: String; const AMaxNumOfCandidatesReturned: Integer = 20; AFindMode: String = 'matchPerson'; ACallbackMethod: TFaceApiAsyncCallback = nil): String; overload; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Face|IFaceApiFace.FindSimilar">interface FindSimilar (overload)</see> /// </summary> class function FindSimilar(AAccess: TAccessServer; const AFaceID: String; AFaceIDS: TStringList; const AMaxNumOfCandidatesReturned: Integer = 20; AFindMode: String = 'matchPerson'; ACallbackMethod: TFaceApiAsyncCallback = nil): String; overload; /// <summary> /// Implements asynchronous top layout for /// <see cref="uIFaceApi.Face|IFaceApiFace.Group">interface Group</see> /// </summary> class function Group(AAccess: TAccessServer; AFaceIDS: TStringList; ACallbackMethod: TFaceApiAsyncCallback = nil): String; end; implementation uses { IFaceApiCore } uIFaceApi.Core, { TFaceApiCore } uFaceApi.Core, { IFaceApiFace } uIFaceApi.Face, { ITask } System.Threading, { FaceApiHelper } uFunctions.FaceApiHelper; class procedure FaceApiAsyncHelper.RunAsync(AProc: TProc); var LTask: ITask; begin LTask := TTask.Create( procedure begin AProc; end ); LTask.Start; end; class procedure FaceApiAsyncHelper.CallCallback(ACallbackMethod: TFaceApiAsyncCallback = nil; const AResult: String = ''); begin if Assigned(ACallbackMethod) then ACallbackMethod(AResult); end; class function FaceApiAsyncHelper.AddPersonFaceURL(AAccess: TAccessServer; const AGroupID, APersonID, AURL, ATargetFace, AUserData: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.AddPersonFaceURL(AAccess, AGroupID, APersonID, AURL, ATargetFace, AUserData); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.CreatePerson(AAccess: TAccessServer; AGroupID, APersonName, APersonUserData: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.CreatePerson(AAccess, AGroupID, APersonName, APersonUserData); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.CreatePersonGroup(AAccess: TAccessServer; const AGroupID, AGroupName, AGroupUserData: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.CreatePerson(AAccess, AGroupID, AGroupName, AGroupUserData); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.DeletePersonGroup(AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.DeletePersonGroup(AAccess, AGroupID); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.DetectFile(AAccess: TAccessServer; const AFileName: String; const ADetectOptions: TDetectOptions; ACallbackMethod: TFaceApiAsyncCallback = nil): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.DetectFile(AAccess, AFileName, ADetectOptions); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.DetectStream(AAccess: TAccessServer; AStream: TBytesStream; const ADetectOptions: TDetectOptions; ACallbackMethod: TFaceApiAsyncCallback = nil): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.DetectStream(AAccess, AStream, ADetectOptions); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.DetectURL(AAccess: TAccessServer; const AURL: String; const ADetectOptions: TDetectOptions; ACallbackMethod: TFaceApiAsyncCallback = nil): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.DetectURL(AAccess, AURL, ADetectOptions); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.FindSimilar(AAccess: TAccessServer; const AFaceID, AListID: String; const AMaxNumOfCandidatesReturned: Integer; AFindMode: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.FindSimilar(AAccess, AFaceID, AListID, AMaxNumOfCandidatesReturned, AFindMode); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.FindSimilar(AAccess: TAccessServer; const AFaceID: String; AFaceIDS: TStringList; const AMaxNumOfCandidatesReturned: Integer; AFindMode: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.FindSimilar(AAccess, AFaceID, AFaceIDS, AMaxNumOfCandidatesReturned, AFindMode); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.GetPersonGroup(AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.GetPersonGroup(AAccess, AGroupID); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.GetPersonGroupTrainingStatus( AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.GetPersonGroupTrainingStatus(AAccess, AGroupID); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.Group(AAccess: TAccessServer; AFaceIDS: TStringList; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.Group(AAccess, AFaceIDS); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.Identify(AAccess: TAccessServer; AFaceIDS: TStringList; const AGroupID: String; const AMaxNumOfCandidatesReturned: Integer; const AConfidenceThreshold: Double; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.Identify(AAccess, AFaceIDS, AGroupID, AMaxNumOfCandidatesReturned, AConfidenceThreshold); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.ListPersonGroups(AAccess: TAccessServer; ACallbackMethod: TFaceApiAsyncCallback = nil; const AStart: String = ''; const ATop: Integer = 1000): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.ListPersonGroups(AAccess, AStart, ATop); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.ListPersonsInPersonGroup( AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback = nil): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.ListPersonsInPersonGroup(AAccess, AGroupID); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.TrainPersonGroup(AAccess: TAccessServer; const AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.TrainPersonGroup(AAccess, AGroupID); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.UpdatePersonGroup(AAccess: TAccessServer; const AGroupID, AGroupName, AGroupUserData: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.UpdatePersonGroup(AAccess, AGroupID, AGroupName, AGroupUserData); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.Verify(AAccess: TAccessServer; const AFaceTempID1, AFaceTempID2: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.Verify(AAccess, AFaceTempID1, AFaceTempID2); CallCallback(ACallbackMethod, LResult); end ); end; class function FaceApiAsyncHelper.Verify(AAccess: TAccessServer; const AFaceTempID, APersonID, AGroupID: String; ACallbackMethod: TFaceApiAsyncCallback): String; begin RunAsync( procedure var LResult: String; begin LResult := FaceApiHelper.Verify(AAccess, AFaceTempID, APersonID, AGroupID); CallCallback(ACallbackMethod, LResult); end ); end; end.
unit StringGridExUnit; interface uses System.SysUtils, Winapi.Windows, Winapi.Messages, Vcl.Clipbrd, scisupport, Vcl.Controls, System.Contnrs, Vcl.ComCtrls, Vcl.Forms, Vcl.Dialogs, Vcl.Graphics, Vcl.Grids, Vcl.StdCtrls, System.StrUtils, System.Classes; type TStringGridEx = class(TStringGrid) private function DoKeyUp(var Message: TWMKey): Boolean; procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN; procedure WMSysKeyDown(var Message: TWMSysKeyDown); message WM_SYSKEYDOWN; protected procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; public constructor Create(AOwner: TComponent); override; function CopyToClipboard: boolean; function CopyAllToClipboard: boolean; end; implementation function tabba(const S: string): string; begin if Length(Trim(S))=0 then Result := '' else Result := #9; end; { TStringGridEx } constructor TStringGridEx.Create(AOwner: TComponent); begin inherited Create(AOwner); DefaultColWidth := 10; ScrollBars := ssNone; BorderStyle:= bsNone; FixedColor := clBtnFace; DefaultRowHeight := 18; Options := []; Anchors := [akLeft, akTop]; DoubleBuffered := True; TabStop := false; end; procedure TStringGridEx.DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState); var Hold: Integer; bColor, predColorB, fColor, predColorF: TColor; S: string; begin if UseRightToLeftAlignment then begin ARect.Left := ClientWidth - ARect.Left; ARect.Right := ClientWidth - ARect.Right; Hold := ARect.Left; ARect.Left := ARect.Right; ARect.Right := Hold; ChangeGridOrientation(False); end; with Canvas do begin predColorB := Brush.Color; predColorF := Font.Color; try fColor := clBlack; S := TStringGrid(Self).Cells[ACol, ARow]; bColor := clWhite; if (gdFixed in AState) then Font.Style := Font.Style + [fsBold] else Font.Style := Font.Style - [fsBold]; if gdSelected in AState then begin if (RowCount > 1) and (ColCount > 1) then begin bColor := clHighlight; fColor := clHighlightText; end; end; if gdFixed in AState then begin bColor := clBtnFace; end; Brush.Color := bColor; Font.Color := fColor; FillRect(ARect); TextRect(ARect,ARect.Left+2,ARect.Top+2, S); finally Brush.Color := predColorB; Font.Color := predColorF; end; end; if UseRightToLeftAlignment then ChangeGridOrientation(True); end; procedure TStringGridEx.WMKeyDown(var Message: TWMKeyDown); begin if not DoKeyUp(Message) then inherited; end; procedure TStringGridEx.WMSysKeyDown(var Message: TWMSysKeyDown); begin if not DoKeyUp(Message) then inherited; end; function TStringGridEx.CopyToClipboard: boolean; var i,j: integer; S,S0: string; begin Result := False; if Focused then begin S := ''; for i := Selection.Top to Selection.Bottom do begin S0 := ''; for j := Selection.Left to Selection.Right do S0 := S0 + tabba(S0) + Cells[j,i]; S := S + S0; if Length(S) > 0 then if i < Selection.Bottom then begin j := Length(S); if j > 2 then begin if Copy(S,j-1,MaxInt) <> sLineBreak then S := S + sLineBreak; end else S := S + sLineBreak; end; end; if Length(S)>0 then begin Clipboard.AsText := S; Row := Selection.Top; Result := True; end; Exit; end; end; function TStringGridEx.CopyAllToClipboard: boolean; var i,j: integer; S,S0: string; begin Result := False; if Focused then begin S := ''; for i := 0 to RowCount-1 do begin S0 := ''; for j := 0 to ColCount-1 do S0 := S0 + tabba(S0) + Cells[j,i]; S := S + S0; if Length(S) > 0 then if i < Selection.Bottom then begin j := Length(S); if j > 2 then begin if Copy(S,j-1,MaxInt) <> sLineBreak then S := S + sLineBreak; end else S := S + sLineBreak; end; end; if Length(S)>0 then begin Clipboard.AsText := S; Result := True; end; Exit; end; end; function TStringGridEx.DoKeyUp(var Message: TWMKey): Boolean; var ShiftState: TShiftState; LCharCode: Word; begin Result := True; with Message do begin ShiftState := KeyDataToShiftState(KeyData); if ssCtrl in ShiftState then if not (csNoStdEvents in ControlStyle) then if CharCode = 67 then begin CopyToClipboard; Exit; end; end; Result := False; end; function TStringGridEx.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin Result := False; end; end.
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium Software E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com In this unit I defined design-time editors for TSMDBComboBox and TSMDBFilterComboBox components } unit SMDBCombReg; interface uses SMDBComb; procedure Register; {$I SMVersion.inc} implementation uses Classes, DB, TypInfo, {$IFDEF SMForDelphi6} DesignIntf, DesignEditors {$ELSE} DsgnIntf {$ENDIF}; { TSMFieldProperty } { For TSMDBFilterComboBox component (FieldDisplay/FieldValue properties) } type TSMFieldProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; procedure GetValueList(List: TStrings); virtual; function GetDataSourcePropName: string; virtual; end; function TSMFieldProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paSortList, paMultiSelect]; end; procedure TSMFieldProperty.GetValues(Proc: TGetStrProc); var i: Integer; Values: TStringList; begin Values := TStringList.Create; try GetValueList(Values); for i := 0 to Values.Count - 1 do Proc(Values[I]); finally Values.Free; end; end; function TSMFieldProperty.GetDataSourcePropName: string; begin Result := 'DataSource'; end; procedure TSMFieldProperty.GetValueList(List: TStrings); var Instance: TComponent; PropInfo: PPropInfo; DataSource: TDataSource; begin Instance := TComponent(GetComponent(0)); PropInfo := TypInfo.GetPropInfo(Instance.ClassInfo, GetDataSourcePropName); if (PropInfo <> nil) and (PropInfo^.PropType^.Kind = tkClass) then begin DataSource := TObject(GetOrdProp(Instance, PropInfo)) as TDataSource; if (DataSource <> nil) and (DataSource.DataSet <> nil) then DataSource.DataSet.GetFieldNames(List); end; end; procedure Register; begin RegisterComponents('SMComponents', [TSMDBComboBox, TSMDBFilterComboBox]); RegisterPropertyEditor(TypeInfo(string), TSMDBFilterComboBox, 'FieldDisplay', TSMFieldProperty); RegisterPropertyEditor(TypeInfo(string), TSMDBFilterComboBox, 'FieldValue', TSMFieldProperty); end; end.
unit intensive.Resources.Conexao; interface uses FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteWrapper.Stat, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, Data.DB, FireDAC.Comp.Client, intensive.Resources.Interfaces; type TConexao = class(TInterfacedObject, iConexao) private FConn : TFDConnection; public constructor Create; destructor Destroy; override; class function New : iConexao; function Connect : TCustomConnection; end; implementation function TConexao.Connect: TCustomConnection; begin Result := FConn; end; constructor TConexao.Create; begin FConn := TFDConnection.Create(nil); FConn.Params.Clear; FConn.Params.Add('DriverID=SQLite'); FConn.Params.Add('DataBase=..\..\database\Dados.sdb'); FConn.Params.Add('LockingMode=Normal'); FConn.Connected := True; end; destructor TConexao.Destroy; begin FConn.DisposeOf; inherited; end; class function TConexao.New : iConexao; begin Result := Self.Create; end; end.
unit DelphiUtils.Arrays; interface type TFilterRoutine<T> = function (const Entry: T; Parameter: NativeUInt) : Boolean; TFilterAction = (ftKeep, ftExclude); TConvertRoutine<T1, T2> = function (const Entry: T1; out ConvertedEntry: T2) : Boolean; TTreeNode<T> = record Entry: T; Index: Integer; Parent: ^TTreeNode<T>; Children: TArray<^TTreeNode<T>>; end; TParentChecker<T> = function (const Parent, Child: T): Boolean; TArrayHelper = class // Filter an array on by-element basis class procedure Filter<T>(var Entries: TArray<T>; Matches: TFilterRoutine<T>; Parameter: NativeUInt; Action: TFilterAction = ftKeep); // Convert (map) each array element class procedure Convert<T1, T2>(const Entries: TArray<T1>; out MappedEntries: TArray<T2>; Converter: TConvertRoutine<T1, T2>); // Find all parent-child relationships in an array class function BuildTree<T>(const Entries: TArray<T>; ParentChecker: TParentChecker<T>): TArray<TTreeNode<T>>; end; // Convert a list of zero-terminated strings into an array function ParseMultiSz(Buffer: PWideChar; BufferLength: Cardinal) : TArray<String>; implementation { TArrayHelper } class function TArrayHelper.BuildTree<T>(const Entries: TArray<T>; ParentChecker: TParentChecker<T>): TArray<TTreeNode<T>>; var i, j, k, Count: Integer; begin SetLength(Result, Length(Entries)); // Copy entries for i := 0 to High(Entries) do begin Result[i].Entry := Entries[i]; Result[i].Index := i; end; // Fill parents as references to array elements for i := 0 to High(Entries) do for j := 0 to High(Entries) do if (i <> j) and ParentChecker(Entries[j], Entries[i]) then begin Result[i].Parent := @Result[j]; Break; end; // Fill children, also as references for i := 0 to High(Entries) do begin Count := 0; for j := 0 to High(Entries) do if Result[j].Parent = @Result[i] then Inc(Count); SetLength(Result[i].Children, Count); k := 0; for j := 0 to High(Entries) do if Result[j].Parent = @Result[i] then begin Result[i].Children[k] := @Result[j]; Inc(k); end; end; end; class procedure TArrayHelper.Convert<T1, T2>(const Entries: TArray<T1>; out MappedEntries: TArray<T2>; Converter: TConvertRoutine<T1, T2>); var i, j: Integer; begin Assert(Assigned(Converter)); SetLength(MappedEntries, Length(Entries)); j := 0; for i := 0 to High(Entries) do if Converter(Entries[i], MappedEntries[j]) then Inc(j); SetLength(MappedEntries, j); end; class procedure TArrayHelper.Filter<T>(var Entries: TArray<T>; Matches: TFilterRoutine<T>; Parameter: NativeUInt; Action: TFilterAction); var i, j: Integer; begin Assert(Assigned(Matches)); j := 0; for i := 0 to High(Entries) do if Matches(Entries[i], Parameter) xor (Action = ftExclude) then begin // j grows slower then i, move elements backwards overwriting ones that // don't match if i <> j then Entries[j] := Entries[i]; Inc(j); end; SetLength(Entries, j); end; { Functions } function ParseMultiSz(Buffer: PWideChar; BufferLength: Cardinal) : TArray<String>; var Count, j: Integer; pCurrentChar, pItemStart, pBlockEnd: PWideChar; begin // Save where the buffer ends to make sure we don't pass this point pBlockEnd := Buffer + BufferLength; // Count strings Count := 0; pCurrentChar := Buffer; while (pCurrentChar < pBlockEnd) and (pCurrentChar^ <> #0) do begin // Skip one zero-terminated string while (pCurrentChar < pBlockEnd) and (pCurrentChar^ <> #0) do Inc(pCurrentChar); Inc(Count); Inc(pCurrentChar); end; SetLength(Result, Count); // Save the content j := 0; pCurrentChar := Buffer; while (pCurrentChar < pBlockEnd) and (pCurrentChar^ <> #0) do begin // Parse one string Count := 0; pItemStart := pCurrentChar; while (pCurrentChar < pBlockEnd) and (pCurrentChar^ <> #0) do begin Inc(pCurrentChar); Inc(Count); end; // Save it SetString(Result[j], pItemStart, Count); Inc(j); Inc(pCurrentChar); end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLSCUDAParallelPrimitives<p> <b>History : </b><font size=-1><ul> <li>28/01/10 - Yar - Creation </ul></font> } // ------------------------------------------------------------- // cuDPP -- CUDA Data Parallel Primitives library // ------------------------------------------------------------- // $Revision: 4562 $ // $Date: 2010-01-29 00:21:42 +0300 (Fri, 29 Jan 2010) $ // ------------------------------------------------------------- // This source code is distributed under the terms of license.txt in // the root directory of this source distribution. // ------------------------------------------------------------- unit GLSCUDAParallelPrimitives; interface uses GLSCLPlatform; {$I cuda.inc} const CUDPPDLL = 'cudpp32.dll'; CUDPP_INVALID_HANDLE = $C0DABAD1; type TCUDPPResult = ( CUDPP_SUCCESS, // No error. CUDPP_ERROR_INVALID_HANDLE, // Specified handle (for example, // to a plan) is invalid. CUDPP_ERROR_ILLEGAL_CONFIGURATION, // Specified configuration is // illegal. For example, an // invalid or illogical // combination of options. CUDPP_ERROR_UNKNOWN // Unknown or untraceable error. ); TCUDPPOption = ( CUDPP_OPTION_FORWARD, // Algorithms operate forward: // from start to end of input // array CUDPP_OPTION_BACKWARD, // Algorithms operate backward: // from end to start of array CUDPP_OPTION_EXCLUSIVE, // Exclusive (for scans) - scan // includes all elements up to (but // not including) the current // element CUDPP_OPTION_INCLUSIVE, // Inclusive (for scans) - scan // includes all elements up to and // including the current element CUDPP_OPTION_CTA_LOCAL, // Algorithm performed only on // the CTAs (blocks) with no // communication between blocks. // @todo Currently ignored. CUDPP_OPTION_KEYS_ONLY, // No associated value to a key // (for global radix sort) CUDPP_OPTION_KEY_VALUE_PAIRS // Each key has an associated value ); TCUDPPDatatype = ( CUDPP_CHAR, // Character type (C char) CUDPP_UCHAR, // Unsigned character (byte) type (C unsigned char) CUDPP_INT, // Integer type (C int) CUDPP_UINT, // Unsigned integer type (C unsigned int) CUDPP_FLOAT // Float type (C float) ); TCUDPPOperator = ( CUDPP_ADD, // Addition of two operands CUDPP_MULTIPLY, // Multiplication of two operands CUDPP_MIN, // Minimum of two operands CUDPP_MAX // Maximum of two operands ); TCUDPPAlgorithm = ( CUDPP_SCAN, CUDPP_SEGMENTED_SCAN, CUDPP_COMPACT, CUDPP_REDUCE, CUDPP_SORT_RADIX, CUDPP_SPMVMULT, // Sparse matrix-dense vector multiplication CUDPP_RAND_MD5, // Pseudo Random Number Generator using MD5 hash algorithm CUDPP_ALGORITHM_INVALID // Placeholder at end of enum ); TCUDPPConfiguration = record algorithm: TCUDPPAlgorithm; // The algorithm to be used op: TCUDPPOperator; // The numerical operator to be applied datatype: TCUDPPDatatype; // The datatype of the input arrays options: TCUDPPoption; // Options to configure the algorithm end; TCUDPPHandle = size_t; // Plan allocation (for scan, sort, and compact) function cudppPlan(var planHandle: TCUDPPHandle; config: TCUDPPConfiguration; n: size_t; rows: size_t; rowPitch: size_t): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; function cudppDestroyPlan(plan: TCUDPPHandle): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; // Scan and sort algorithms function cudppScan(planHandle: TCUDPPHandle; var d_out; var d_in, numElements: size_t): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; function cudppMultiScan(planHandle: TCUDPPHandle; var d_out; var d_in; numElements: size_t; numRows: size_t): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; function cudppSegmentedScan(planHandle: TCUDPPHandle; var d_out; var d_idata; const d_iflags: PCardinal; numElements: size_t): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; function cudppCompact(planHandle: TCUDPPHandle; var d_out; var d_numValidElements: size_t; var d_in; const d_isValid: PCardinal; numElements: size_t): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; function cudppSort(planHandle: TCUDPPHandle; var d_keys; var d_values; keybits: Integer; numElements: size_t): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; // Sparse matrix allocation function cudppSparseMatrix(var sparseMatrixHandle: TCUDPPHandle; config: TCUDPPConfiguration; n: size_t; rows: size_t; var A; const h_rowIndices: PCardinal; const h_indices: PCardinal): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; function cudppDestroySparseMatrix(sparseMatrixHandle: TCUDPPHandle): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; // Sparse matrix-vector algorithms function cudppSparseMatrixVectorMultiply(sparseMatrixHandle: TCUDPPHandle; var d_y; var d_x): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; // random number generation algorithms function cudppRand(planHandle: TCUDPPHandle; var d_out; numElements: size_t): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; function cudppRandSeed(const planHandle: TCUDPPHandle; seed: Cardinal): TCUDPPResult; {$IFDEF CUDA_STDCALL}stdcall; {$ENDIF} {$IFDEF CUDA_CDECL}cdecl; {$ENDIF} external CUDPPDLL; implementation end.
unit ubookio; {Berisi fungsi (F05, F06, F07, F09, F10) yang berhubungan dengan keluar masuknya buku di perpustakaan} {REFERENSI : -} interface uses ucsvwrapper, ubook, ubookutils, udate; {PUBLIC FUNCTION, PROCEDURE} procedure borrowBookUtil(pnewBorrow : psingleborrow; ptrborrow: pborrow; ptrbook: pbook); {F05} procedure returnBookUtil(bookid : integer; username : string; ptrreturn : preturn; ptrborrow : pborrow; ptrbook : pbook); {F06} procedure addMissingBookUtil(ptr : psinglemissing; ptrarray: pmissing; ptrbook: pbook); {F07} procedure addNewBookUtil(ptr : psinglebook; ptrarray : pbook); {F09} procedure addBookQtyUtil(id, qty : integer; ptr : pbook); {F10} implementation {FUNGSI dan PROSEDUR} procedure borrowBookUtil(pnewBorrow : psingleborrow; ptrborrow: pborrow; ptrbook: pbook); {DESKRIPSI : (F05) Menerima data buku yang dipinjam dengan menerima data id buku, judul buku, dan tanggal peminjaman.} {I.S : pointer terdefinisi (pointer pada book.csv)} {F.S : data buku dipinjam tersimpan.} {Proses : Menerima input buku yang dipinjam, memeriksa apakah stok buku ada, lalu mengurangi jumlah buku dipinjam dalam data jika stok tersedia.} var idx : integer; {ALGORITMA} begin writeln(); idx := checklocation(pnewBorrow^.id, ptrbook); if (ptrbook^[idx].qty > 0) then begin ptrborrow^[borrowNeff+1] := pnewBorrow^; borrowNeff += 1; ptrbook^[idx].qty -= 1; writeln('Tersisa ', ptrbook^[idx].qty, ' buku ', unwraptext(ptrbook^[idx].title), '.'); writeln('Terima kasih, ', unwraptext(pnewBorrow^.username), ', sudah meminjam buku ', unwraptext(ptrbook^[idx].title), '!'); end else begin writeln('Buku ', unwraptext(ptrbook^[idx].title), ' sedang habis!'); writeln('Coba lain kali.'); end; end; procedure returnBookUtil(bookid : integer; username : string; ptrreturn : preturn; ptrborrow : pborrow; ptrbook : pbook); {DESKRIPSI : (F06) Menerima data buku yang dikembalikan dengan menerima id buku, judul buku, dan tanggal pengembalian.} {I.S : bookid bertipe integer, username bertipe string, dan pointer terdefinisi.} {F.S : data buku yang dikembalikan tersimpan.} {Proses : menerima input buku yang dikembalikan, lalu menambahkan jumlah buku yang dikembalikan dalam data csv.} {KAMUS LOKAL} var newReturn : ReturnHistory; borrowData : BorrowHistory; tmp : string; booktitle : string; idx : integer; selisih : integer; {ALGORITMA} begin borrowData := searchBorrow(bookid, username, ptrborrow); if (borrowData.username <> wraptext('Anonymous')) then begin idx := checklocation(borrowData.id, ptrbook); booktitle := ptrbook^[idx].title; writeln(); writeln('Data peminjaman:'); writeln('Username: ', unwraptext(borrowData.username)); writeln('Judul buku: ', unwraptext(booktitle)); writeln('Tanggal peminjaman: ', DateToStr(borrowData.borrowDate)); writeln('Tanggal pengembalian: ', DateToStr(borrowData.returnDate)); write('Masukkan tanggal hari ini (DD/MM/YYYY): '); readln(tmp); writeln(); newReturn.username := username; newReturn.id := bookid; newReturn.returnDate:= StrToDate(tmp); ptrreturn^[returnNeff+1] := newReturn; returnNeff += 1; idx := checklocation(bookid, ptrbook); ptrbook^[idx].qty += 1; selisih := DateDifference(borrowData.returnDate, newReturn.returnDate); if (selisih < 0) then begin writeln('Terima kasih sudah meminjam.'); end else begin writeln('Anda terlambat ', selisih, ' hari mengembalikan buku.'); writeln('Anda terkena denda Rp2000/hari. Total denda: Rp', selisih * 2000, '.'); writeln('Silakan bayar di loket.'); end; end; end; procedure addMissingBookUtil(ptr : psinglemissing; ptrarray : pmissing; ptrbook: pbook); {DESKRIPSI : (F07) Menerima laporan buku hilang dengan menerima data id buku, judul buku, dan tanggal pelaporan} {I.S : array of book terdefinisi, pointer terdefinisi (pointer pada book.csv)} {F.S : data buku hilang tersimpan } {Proses : menambahkan buku hilang sesuai dengan data buku hilang yang diinput dan mengurangi jumlah buku tsb pada array buku} {KAMUS LOKAL} var idx : integer; {ALGORITMA} begin idx := checkLocation(ptr^.id, ptrbook); ptrbook^[idx].qty -= 1; ptrarray^[missingNeff + 1] := ptr^; missingNeff += 1; writeln('Laporan berhasil diterima.'); end; procedure addNewBookUtil(ptr : psinglebook; ptrarray : pbook); {DESKRIPSI : (F09) Menerima data buku baru dan memasukkannya ke book.csv} {I.S : pointer buku dan array terdefinisi (pointer pada book.csv)} {F.S : data buku baru tersimpan } {Proses : Menerima data buku baru dan memasukkannya ke book.csv, dengan menerima masukkan id buku, judul pengarang,jumlah,tahun terbit,dan kategori} {ALGORITMA} begin ptrarray^[bookNeff+1]:= ptr^; bookNeff += 1; writeln('Buku berhasil ditambahkan ke dalam sistem!'); end; procedure addBookQtyUtil (id,qty : integer; ptr : pbook); {DESKRIPSI : (F10) Menambahkan jumlah buku dengan skema searching pada id yang ingin ditambahkan pada book.csv} {I.S : id dan qty yang bertipe integer dan Ptrbook (pointer pada book.csv)} {F.S : Jumlah buku dari buku dengan ID tertentu berubah } {PROSES : Mencari buku dengan ID tertentu dengan skema searching dan mengubah data qty pada buku ID tersebut} {KAMUS LOKAL} var i,idx : integer; found : boolean; {ALGORITMA} begin {INISIALISASI} i := 1; found := False; {SKEMA SEARCHING} while ((not found) and (i <= bookNeff)) do begin if (id = ptr^[i].id) then begin idx := i; found := True; end; i += 1; end; {TAHAP PENAMBAHAN JUMLAH BUKU} ptr^[idx].qty += qty; writeln(); writeln('Pembaharuan jumlah buku berhasil dilakukan.'); writeln('Total buku ', unwraptext(ptr^[idx].title), ' menjadi ', ptr^[idx].qty); end; end.
{----------------------------------------------------------------------------- Unit Name: uhTariff Author: n0mad Version: 1.1.6.87 Creation: 27.08.2003 Purpose: Tariff helper History: -----------------------------------------------------------------------------} unit uhTariff; interface {$I kinode01.inc} uses Classes, Gauges, Extctrls, Forms, Menus, Controls, Graphics; function Load_All_Tariffs: boolean; function Get_Tariff_Desc(i_Tariff: Integer; var s_Nam, s_Desc, s_Comment: string; var i_Base_Cost: Integer; var b_Freezed: Boolean): Integer; // -------------------------------------------------------------------------- implementation uses Bugger, SysUtils, StrConsts, uTools, udBase, urCommon; const UnitName: string = 'uhTariff'; function Load_All_Tariffs: boolean; const ProcName: string = 'Load_All_Tariffs'; var Time_Start, Time_End: TDateTime; Hour, Min, Sec, MSec: Word; begin Time_Start := Now; // -------------------------------------------------------------------------- // 2.3) Загрузка всех тарифов // -------------------------------------------------------------------------- DEBUGMessEnh(1, UnitName, ProcName, '->'); // -------------------------------------------------------------------------- Result := false; // -------------------------------------------------------------------------- DEBUGMessEnh(-1, UnitName, ProcName, '<-'); // -------------------------------------------------------------------------- // calculating work time // -------------------------------------------------------------------------- Time_End := Now; DecodeTime(Time_End - Time_Start, Hour, Min, Sec, MSec); DEBUGMessEnh(0, UnitName, ProcName, 'Work time - (' + IntToStr(Hour) + ':' + FixFmt(Min, 2, '0') + ':' + FixFmt(Sec, 2, '0') + '.' + FixFmt(MSec, 3, '0') + ')'); end; function Get_Tariff_Desc(i_Tariff: Integer; var s_Nam, s_Desc, s_Comment: string; var i_Base_Cost: Integer; var b_Freezed: Boolean): Integer; const ProcName: string = 'Get_Tariff_Desc'; begin // -------------------------------------------------------------------------- // Загрузка тарифа из запроса // -------------------------------------------------------------------------- DEBUGMessEnh(1, UnitName, ProcName, '->'); // -------------------------------------------------------------------------- s_Nam := '<none>'; s_Desc := '<none>'; s_Comment := '<none>'; i_Base_Cost := 0; b_Freezed := false; Result := 0; with dm_Base.ds_Tariff do begin if (not Active) then begin try Close; Prepare; Open; First; Last; except on E: Exception do begin DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']'); DEBUGMessEnh(0, UnitName, ProcName, 'Reopening for (' + Name + ') is failed.'); end; end; {$IFDEF Debug_Level_6} DEBUGMessEnh(0, UnitName, ProcName, Name + '.Active = ' + BoolYesNo[Active] + ', RecordCount = (' + IntToStr(RecordCount) + ')'); {$ENDIF} end; if Active then begin First; if Assigned(FieldByName(s_TARIFF_KOD)) then begin if Locate(s_TARIFF_KOD, i_Tariff, []) then begin if Assigned(FieldByName(s_TARIFF_NAM)) then s_Nam := FieldByName(s_TARIFF_NAM).AsString; if Assigned(FieldByName(s_TARIFF_DESC)) then s_Desc := FieldByName(s_TARIFF_DESC).AsString; if Assigned(FieldByName(s_TARIFF_COMMENT)) then s_Comment := FieldByName(s_TARIFF_COMMENT).AsString; if Assigned(FieldByName(s_TARIFF_BASE_COST)) then i_Base_Cost := FieldByName(s_TARIFF_BASE_COST).AsInteger; if Assigned(FieldByName(s_TARIFF_FREEZED)) then b_Freezed := (FieldByName(s_TARIFF_FREEZED).AsInteger <> 0); DEBUGMessEnh(0, UnitName, ProcName, 'Found - s_Nam = (' + s_Nam + '), i_Base_Cost = (' + IntToStr(i_Base_Cost) + '), b_Freezed = ' + BoolYesNo[b_Freezed]); Result := 1; end else DEBUGMessEnh(0, UnitName, ProcName, 'Tariff with ID = (' + IntToStr(i_Tariff) + ') not found.'); end else DEBUGMessEnh(0, UnitName, ProcName, s_TARIFF_KOD + ' field not found in dataset.'); end else DEBUGMessEnh(0, UnitName, ProcName, 'Tariff dataset is not active.'); end; // -------------------------------------------------------------------------- DEBUGMessEnh(-1, UnitName, ProcName, '<-'); end; end.
unit uSVD_Type; interface { dimElement : NAME[%s] -- Array of Elements, NAME_%s -- Multiple Elements ---------------------------------------------------------------------------------------------------------------------- A powerfull construct in data structures of the C programming language is the array. An array is a series of data elements of the same type selected via an index. CMSIS-SVD supports arrays of <peripherals>, <cluster> and <register>. derivedFrom : Multiple Instantiation ---------------------------------------------------------------------------------------------------------------------- CMSIS-SVD supports the reuse of whole sections of the description. The attribute derivedFrom for the * peripheral-, register-, and field-section specifies the source of the section to be copied from. Individual tags can be used to redefine specific elements within a copied section. Hierarchies are separated by a dot. For example, <peripheralName>.<registerName>.<fieldName> In case the name of the description source is not unique, the name needs to be qualified hierarchically until the element composite name becomes unique. Descriptions ---------------------------------------------------------------------------------------------------------------------- ** On each level **, the tag description provides verbose information about the respective element. The description field plays an important part in improving the software development productivity as it gives instant access to information that otherwise would need to be looked up in the device documentation. Constants ---------------------------------------------------------------------------------------------------------------------- Number constants shall be entered in hexadecimal, decimal, or binary format. ** The Hexadecimal format is indicated by a leading "0x". ** The Binary format is indicated by a leading "#". ** All other formats are interpreted as decimal numbers. The value tag in enumeratedValue accepts 'do not care' bits represented by "x". Device Level ---------------------------------------------------------------------------------------------------------------------- A device contains one or more peripherals. **** registerPropertiesGroup **** Optional elements like ** size, access, resetValue, and resetMask ** defined on this level are used as default values throughout the device description, unless they get redefined at a lower level. Peripherals Level ---------------------------------------------------------------------------------------------------------------------- derivedFrom : Specifies the name of the register from which to inherit the data. * Elements being specified underneath will override the inherited values. baseAddress : An address block and register addresses are specified relative to the base address of a peripheral. offset : addressBlock, register Starting version 1.3 of the SVD specification arrays of peripherals can be specified. The single peripheral description gets duplicated automatically into an array. The peripheral name needs to be of the format myPeripheral[%s]. The <dim> specifies the number of array elements. The <dimIncrement> specifies the address offset between two peripherals : sizeof(peripheral) The <dimIndex> is ignored. <dim> * <dimIncrement> = sizeof(peripheral[0..dim-1]) If you want to create copies of a peripheral using different names, please use the derivedFrom attribute. alternatePeripheral : USB_OTG_DEVICE, USB_OTG_HOST : the same address blocks ( may be not same registers layout ) All address blocks in the memory space of a device are assigned to a unique peripheral by default. If there are multiple peripherals describing the same address blocks, this needs to be specified explicitly. A peripheral redefining an address block needs to specify the name of the peripheral that is listed first in the description. If no alternate peripheral is specified, then the SVDConv utility will generate errors. Registers Level ---------------------------------------------------------------------------------------------------------------------- derivedFrom : The field is cloned from a previously defined field with a unique name. * When deriving a register, it is mandatory to specify the name, the description, and the addressOffset. * The register's *name*, *detailed description*, and the *address-offset* relative to the peripheral base address are the ****mandatory**** elements. If the *size*, *access*, *reset value*, and *reset mask* have not been specified on the device or peripheral level, or if the default values need to be redefined locally, these fields become ****mandatory****. A register can represent a single value or can be subdivided into individual bit-fields of specific functionality. In schema-terms the *fields* section is ****optional****. alternateRegister : A register could be a redefinition of an already described address. In the case, the register can be either marked alternateRegister and needs to have a unique name. The single register description gets duplicated automatically into an array. The <dim> specifies the number of array elements. The <dimIncrement> specifies the address offset between two registers. The <dimIndex> specific the register names. NAME[%s] -- Array of Elements : The <dimIndex> is ignored. NAME_%s --- Multiple Elements : The <dimIndex> : %s = A,B,C,D : %s = 0-3 : %s = A,C,E By default, the index is a decimal value starting with 0 for the first register. Cluster Level : an optional sub-level within the CMSIS SVD registers level ---------------------------------------------------------------------------------------------------------------------- derivedFrom : Specifies the name of the cluster from which to inherit the data. Elements being specified underneath will override the inherited values. When deriving a cluster, it is mandatory to specify at least the **name, the description, and the addressOffset**. The <dim> specifies the number of elements in an array of clusters The <dimIncrement> specifies the address offset between two neighboring clusters The <dimIndex> specific the register names. A cluster specifies the addressOffset relative to the baseAddress of the peripheral. All register elements within a cluster specify their addressOffset relative to the cluster base address (peripheral:baseAddress + cluster:addressOffset). register address = peripheral:baseAddress + cluster:addressOffset + register:addressOffset Since version 1.3 of the specification the nesting of <cluster> elements is supported. This means, that within a <cluster> section any number of <register> and <cluster> sections may occur. register address = p:baseAddress + c:addressOffset + c:addressOffset + register:addressOffset Fields Level ---------------------------------------------------------------------------------------------------------------------- derivedFrom : The field is cloned from a previously defined field with a unique name. name : A bit-field has a name that is unique within the register. enumeratedValues : A field may define an enumeratedValues in order to make the display more intuitive to read. Enumerated Values Level ---------------------------------------------------------------------------------------------------------------------- derivedFrom : Makes a copy from a previously defined enumeratedValues section. No modifications are allowed. dimElementGroup ---------------------------------------------------------------------------------------------------------------------- The size of the array is specified by the <dim> element. The register names can be composed by the register name and an index-specific substring defined in <dimIndex>. The <dimIncrement> specifies the address offset between two registers. registerPropertiesGroup ---------------------------------------------------------------------------------------------------------------------- Register properties can be set on device, peripheral, and register level. Element values defined on a lower level overwrite element values defined on a more general level. } uses Winapi.Windows, Winapi.Messages, // Windows System.Classes, System.Variants, System.SysUtils, // System Generics.Collections, Generics.Defaults, uMisc, uDynArray; type // ----------------------------------------------------------------------------------------------- // System View description : CMSIS-SVD.xsd, CMSIS-SVD Schema File V1.3.2, 22. January 2016 // ----------------------------------------------------------------------------------------------- TSVD_BitRangeType = ( brOffsetWidth, brLsbMsb, brString ); TSVD_RegisterParent = ( rpCluster, rpRegisters ); TSVD_BitRangeOffsetWidth = record { Value defining the position of the least significant bit of the field within the register it belongs to. } bitOffset: Cardinal; // ---- 28 { Value defining the bit-width of the bitfield within the register it belongs to. } bitWidth: Cardinal; // ----- 4 end; TSVD_BitRangeLsbMsb = record { Value defining the bit position of the least significant bit within the register it belongs to. } lsb: Cardinal; // ---------- 28 { Value defining the bit position of the most significant bit within the register it belongs to. } msb: Cardinal; // ---------- 31 end; PSVD_BitRange = ^TSVD_BitRange; TSVD_BitRange = record bitRangeType: TSVD_BitRangeType; bitRangeLsbMsb: TSVD_BitRangeLsbMsb; bitRangeOffsetWidth: TSVD_BitRangeOffsetWidth; { A String in the format: "[<msb>:<lsb>]" } bitRangeString: String; end; { dimElementGroup specifies a series of elements (dim), the address offset between to consecutive elements and an a comma seperated list of strings being used for identifying each element. A specialized case is an array of elements, where the name is contructed using [%s] and the dimIndex being integers from 0 to n } TSVD_dimElement = record { xs:sequence } { the value defines the number of elements in an array of registers. } dim: Cardinal; { If dim is specified, this element becomes mandatory. The element specifies the address increment in between two neighboring registers of the register array in the address map. } dimIncrement: Cardinal; { Specifies the substrings that replaces the %s placeholder within the register name. By default, the index is a decimal value starting with 0 for the first register. e.g. dim : 3, dimIndex : A,B,C :: name : GPIO_%s :: GPIO_A_CTRL, GPIO_B_CTRL, GPIO_C_CTRL e.g. dim : 3, dimIndex : 3-6 :: name : IRQ%s :: IRQ3, IRQ4, IRQ5, IRQ6 e.g. dim : 4, dimIndex : ??? :: name : DATA[%s] :: DATA[4] } dimIndex: String; { V1.3.2 adding dimIndexArray to peripheral-, cluster- and register-array to describe enumeration of array indices. } dimArrayIndex: String; { xs:sequence } { name of peripheral, cluster and register. } { name : String; } end; { register properties specifies register size, access permission and reset value this is used in multiple locations. Settings are inherited downstream } TSVD_RegisterProperties = record { xs:sequence } size: Cardinal; { Predefined strings can be used to define the allowed access types for this field: read-only, write-only, read-write, writeOnce, and read-writeOnce. Can be omitted if it matches the access permission set for the parent register. ---- overwrite element values defined on the parent register. } access: String; protection: String; resetValue: Cardinal; resetMask: Cardinal; { xs:sequence } end; PSVD_AddressBlock = ^TSVD_AddressBlock; PSVD_Interrupt = ^TSVD_Interrupt; PSVD_CPU = ^TSVD_CPU; PSVD_Device = ^TSVD_Device; PSVD_Peripheral = ^TSVD_Peripheral; PSVD_Cluster = ^TSVD_Cluster; PSVD_Register = ^TSVD_Register; PSVD_Field = ^TSVD_Field; PSVD_EnumeratedValues = ^TSVD_EnumeratedValues; PSVD_EnumeratedValue = ^TSVD_EnumeratedValue; { Specifies an address range uniquely mapped to this peripheral. A peripheral must have at least one address block, but may allocate multiple distinct address ranges. If a peripheral is derived form another peripheral, the addressBlock is not mandatory. addressBlockType specifies the elements to describe an address block } TSVD_AddressBlock = record { Specifies the start address of an address block relative to the peripheral baseAddress. } Offset: Cardinal; { Specifies the number of addressUnitBits being covered by this address block. The end address of an address block results from the sum of baseAddress, offset, and (size - 1). } size: Cardinal; end; { A peripheral can have multiple associated interrupts. This entry allows the debugger to show interrupt names instead of interrupt numbers. } TSVD_Interrupt = record { The String represents the interrupt name. } name: String; description: String; { Is the enumeration index value associated to the interrupt. 0 : vector_address : 0x00000040 } value: Cardinal; end; TSVD_CPU = record name: string; revision: string; endian: string; itcmPresent: string; dtcmPresent: string; icachePresent: string; dcachePresent: string; mpuPresent: string; fpuPresent: string; fpuDP: string; vtorPresent: string; vendorSystickConfig: string; sauNumRegions: Cardinal; nvicPrioBits: Cardinal; deviceNumInterrupts: Cardinal; end; { An enumeratedValue defines a map between an unsigned integer and a human readable String. value name description 0 <-----> disabled -> "the clock source clk0 is turned off" 1 <-----> enabled --> "the clock source clk1 is running" } TSVD_EnumeratedValue = record parent: PSVD_EnumeratedValues; { enumeratedValue derivedFrom=<identifierType> } derivedFrom: String; { name is a ANSI C indentifier representing the value (C Enumeration) } name: String; { description contains the details about the semantics/behavior specified by this value } description: String; { Defines the constant of the bit-field that the name corresponds to. } value: Cardinal; { isDefault specifies the name and description for all values that are not specifically described individually } isDefault: String; end; TSVD_EnumeratedValues = record parent: PSVD_Field; { The field is cloned from a previously defined field with a unique name. } derivedFrom: String; { name specfies a reference to this enumeratedValues section for reuse purposes this name does not appear in the System Viewer nor the Header File. } name: String; { usage specifies whether this enumeration is to be used for read or write or (read and write) accesses } usage: String; enumeratedValueArray: TDynArray< TSVD_EnumeratedValue >; end; { A bit-field has a name that is unique within the register. The position and size within the register is either described by the combination of the least significant bit's position (lsb) and the most significant bit's position (msb), or the lsb and the bit-width of the field. A field may define an enumeratedValue in order to make the display more intuitive to read. } TSVD_Field = record parent: PSVD_Register; { The field is cloned from a previously defined field with a unique name. } derivedFrom: String; dimElement: TSVD_dimElement; { name specifies a field's name. The System Viewer and the device header file will use the name of the field as identifier } name: String; { description contains reference manual level information about the function and options of a field. } description: String; bitRange: TSVD_BitRange; enumeratedValues: TSVD_EnumeratedValues; end; TSVD_Register = record parentPeripheral: PSVD_Peripheral; parentCluster: PSVD_Cluster; derivedFrom: String; { describes a series of consecutive registers } dimElement: TSVD_dimElement; { name specifies the name of the register. The register name is used by System Viewer and device header file generator to represent a register } name: String; { display name specifies a register name without the restritions of an ANSIS C identifier. The use of this tag is discouraged because it does not allow consistency between the System View and the device header file. } displayName: String; { description contains a reference manual level description about the register and it's purpose } description: String; { alternateGroup specifies the identifier of the subgroup a register belongs to. This is useful if a register has a different description per mode but a single name } alternateGroup: String; { V1.1: alternateRegister specifies an alternate register description for an address that is already fully described. In this case the register name must be unique within the peripheral } alternateRegister: String; { addressOffset describes the address of the register relative to the baseOffset of the peripheral } addressOffset: Cardinal; { registerPropertiesGroup elements specify the default values for register size, access permission and reset value. These default values are inherited to all registers contained in this peripheral } registerProperties: TSVD_RegisterProperties; { V1.1: dataType specifies a CMSIS compliant native dataType for a register (i.e. signed, unsigned, pointer) } dataType: String; fieldArray: TDynArray< TSVD_Field >; end; TSVD_Cluster = record parentPeripheral: PSVD_Peripheral; { 1.3: nesting of cluster is supported } parentCluster: PSVD_Cluster; derivedFrom: String; { describes a series of consecutive clusters } dimElement: TSVD_dimElement; name: String; displayName: String; description: String; { V1.1: alternateCluster specifies an alternative description for a cluster address range that is already fully described. In this case the cluster name must be unique within the peripheral } alternateCluster: String; addressOffset: Cardinal; { registerPropertiesGroup elements specify the default values for register size, access permission and reset value. These default values are inherited to all registers contained in this peripheral } registerProperties: TSVD_RegisterProperties; { 1.3: nesting of cluster is supported } clusterArray: TDynArray< TSVD_Cluster >; registerArray: TDynArray< TSVD_Register >; end; TSVD_Peripheral = record { name specifies the name of a peripheral. This name is used for the System View and device header file } name: String; derivedFrom: String; version: String; { description provides a high level functional description of the peripheral } description: String; { V1.1: alternatePeripheral specifies an alternative description for an address range that is already fully by a peripheral described. In this case the peripheral name must be unique within the device description } alternatePeripheral: String; { prependToName specifies a prefix that is placed in front of each register name of this peripheral. The device header file will show the registers in a C-Struct of the peripheral without the prefix. } prependToName: String; { appendToName is a postfix that is appended to each register name of this peripheral. The device header file will sho the registers in a C-Struct of the peripheral without the postfix } appendToName: String; { 1.3: specify uni-dimensional array of peripheral - requires name="<name>[%s]" } dimElement: TSVD_dimElement; { baseAddress specifies the absolute base address of a peripheral. For derived peripherals it is mandatory to specify a baseAddress. } baseAddress: Cardinal; { registerPropertiesGroup elements specify the default values for register size, access permission and reset value. These default values are inherited to all registers contained in this peripheral } registerProperties: TSVD_RegisterProperties; { addressBlock specifies *one or more* address ranges that are assigned exclusively to this peripheral. derived peripherals may have no addressBlock, however none-derived peripherals are required to specify at least one address block } addressBlockArray: TDynArray< TSVD_AddressBlock >; { interrupt specifies can specify one or more interrtupts by name, description and value } interrupt: TSVD_Interrupt; { can have an arbitrary list of cluster and register sections } clusterArray: TDynArray< TSVD_Cluster >; registerArray: TDynArray< TSVD_Register >; end; TSVD_ObjectType = ( otAny, otEnumeratedValues, otField, otRegister, otCluster, otPeripheral ); PSVD_Object = ^TSVD_Object; TSVD_Object = record parent: PSVD_Object; name: String; _type: TSVD_ObjectType; case TSVD_ObjectType of otAny: ( data: Pointer ); otEnumeratedValues: ( enumeratedValues: PSVD_EnumeratedValues ); otField: ( field: PSVD_Field ); otRegister: ( _Register: PSVD_Register ); otCluster: ( cluster: PSVD_Cluster ); otPeripheral: ( peripheral: PSVD_Peripheral ); end; TSVD_ObjectArray = TDynArray< TSVD_Object >; TSVD_Device = record vendor: String; vendorID: String; { The name string is used to identify the device or device series. Device names are required to be unique. } name: string; series: String; { The string defines the version of the file. Silicon vendors maintain the description throughout the life-cycle of the device and ensure that all updated and released copies have a unique version string. Higher numbers indicate a more recent version. } version: string; { String for describing main features of a device (for example CPU, clock frequency, peripheral overview). } description: string; { Defines the number of data bits uniquely selected by each address. The value for Cortex-M based devices is 8 (byte-addressable). } addressUnitBits: Cardinal; { Defines the number of data bit-width of the maximum single data transfer supported by the bus infrastructure. This information is relevant for debuggers when accessing registers, because it might be required to issue multiple accesses for accessing a resource of a bigger size. The expected value for Cortex-M based devices is 32. } width: Cardinal; { registerPropertiesGroup elements specify the default values for register size, access permission and reset value. These default values are inherited to all registers contained in this peripheral } registerProperties: TSVD_RegisterProperties; cpu: TSVD_CPU; peripheralArray: TDynArray< TSVD_Peripheral >; ObjectArray: TSVD_ObjectArray; end; function Str2Int( const S: String ): Cardinal; implementation (* Constants Number constants shall be entered in hexadecimal, decimal, or binary format. The Hexadecimal format is indicated by a leading "0x". The Binary format is indicated by a leading "#". All other formats are interpreted as decimal numbers. The value tag in enumeratedValue accepts 'do not care' bits represented by "x". <xs:simpleType name="scaledNonNegativeInteger"> <xs:restriction base="xs:string"> <xs:pattern value="[+]?(0x|0X|#)?[0-9a-fA-F]+[kmgtKMGT]?"/> </xs:restriction> </xs:simpleType> A scaled integer. It supports any string recognized by java.lang.Long.decode(). It also supports a magnitude scale suffix of upper or lower case K (kilo=2^10), M (mega=2^20), G (giga=2^30) or T (tera=2^40) <enumeratedValue> <name>KEEP</name> <value>#00</value> </enumeratedValue> <!-- enumeratedValue 1 --> <enumeratedValue> <name>INCREMENT</name> <value>#01</value> </enumeratedValue> <!-- enumeratedValue 2, 3 --> <enumeratedValue> <name>DECREMENT</name> <value>#1X</value> or <value>#1x</value> </enumeratedValue> typedef enum { TIMER2_CR_IDR0_VAL_KEEP = 0, TIMER2_CR_IDR0_VAL_INCREMENT = 1, TIMER2_CR_IDR0_VAL_DECREMENT_2 = 2, TIMER2_CR_IDR0_VAL_DECREMENT_3 = 3, } TIMER2_CR_IDR0_VAL_Enum; *) function Str2Int( const S: String ): Cardinal; function BinToInt( value: string ): Cardinal; var i, iValueSize: Cardinal; begin Result := 0; iValueSize := Length( value ); for i := iValueSize downto 1 do if value[ i ] = '1' then Result := Result + ( 1 shl ( iValueSize - i ) ); end; var leadPos: Integer; begin // The Binary format is indicated by a leading "#10101010" leadPos := Pos( '#', S ); if leadPos > 0 then begin // The value tag in enumeratedValue accepts 'do not care' bits represented by "x" or "X". StringReplace( S, 'x', '0', [ rfReplaceAll, rfIgnoreCase ] ); Result := BinToInt( Copy( S, 2, Length( S ) - 1 ) ); Exit; end; // The Hexadecimal format is indicated by a leading "0x". // All other formats are interpreted as decimal numbers. Result := StrToInt( S ); Exit; // The Hexadecimal format is indicated by a leading "0x". leadPos := Pos( '0x', S ); if leadPos > 0 then begin Result := StrToInt( S ); Exit; end; end; end.
unit VA508DelphiCompatibility; interface uses SysUtils, Classes, Controls, Windows, StdCtrls, CheckLst, ExtCtrls, Forms, ValEdit, DBGrids, Calendar, ComCtrls, VA508AccessibilityManager; function GetCheckBoxComponentName(AllowGrayed: boolean): string; function GetCheckBoxInstructionMessage(Checked: boolean): string; function GetCheckBoxStateText(State: TCheckBoxState): String; procedure ListViewIndexQueryProc(Sender: TObject; ItemIndex: integer; var Text: string); type TVA508StaticTextManager = class(TVA508ManagedComponentClass) public constructor Create; override; function GetComponentName(Component: TWinControl): string; override; function GetCaption(Component: TWinControl): string; override; function GetValue(Component: TWinControl): string; override; end; implementation uses Grids, VA508AccessibilityRouter, VA508AccessibilityConst, VA508MSAASupport, VAUtils; type TCheckBox508Manager = class(TVA508ManagedComponentClass) public constructor Create; override; function GetComponentName(Component: TWinControl): string; override; function GetInstructions(Component: TWinControl): string; override; function GetState(Component: TWinControl): string; override; end; TCheckListBox508Manager = class(TVA508ManagedComponentClass) private function GetIndex(Component: TWinControl): integer; public constructor Create; override; function GetComponentName(Component: TWinControl): string; override; function GetState(Component: TWinControl): string; override; function GetItem(Component: TWinControl): TObject; override; function GetItemInstructions(Component: TWinControl): string; override; end; TVA508EditManager = class(TVA508ManagedComponentClass) public constructor Create; override; function GetValue(Component: TWinControl): string; override; end; TVA508ComboManager = class(TVA508ManagedComponentClass) public constructor Create; override; function GetValue(Component: TWinControl): string; override; end; TCustomGrid508Manager = class(TVA508ManagedComponentClass) private public constructor Create; override; function GetComponentName(Component: TWinControl): string; override; function GetInstructions(Component: TWinControl): string; override; function GetValue(Component: TWinControl): string; override; function GetItem(Component: TWinControl): TObject; override; // function GetData(Component: TWinControl; Value: string): string; override; end; TVA508RegistrationScreenReader = class(TVA508ScreenReader); function CustomComboAlternateHandle(Component: TWinControl): HWnd; forward; procedure ListViewIndexQueryProc(Sender: TObject; ItemIndex: integer; var Text: string); var temp, ImgTxt, state, overlay: string; view: TListView; item: TListItem; i: integer; include: boolean; CtrlManager: TVA508AccessibilityManager; ColValue: boolean; function Append(data: array of string): string; overload; var i: integer; begin Result := ''; for i := low(data) to high(data) do begin if data[i] <> '' then begin if result <> '' then Result := Result + ' '; Result := Result + data[i]; end; end; end; procedure Append(txt: string); overload; begin if txt = '' then exit; if text <> '' then text := text + ' '; text := text + txt + ','; end; procedure AppendHeader(txt: string); begin if txt = '' then txt := 'blank header'; Append(txt); end; begin view := TListView(Sender); Text := ''; include := TRUE; CtrlManager := GetComponentManager(view); if (ItemIndex < 0) or (ItemIndex >= view.Items.Count) then exit; item := view.Items.Item[ItemIndex]; if (view.ViewStyle = vsReport) and (view.Columns.Count > 0) then begin //-1 and -2 are valid widths if (view.Columns[0].Width = 0) or (view.Columns[0].Width < -3) then include := FALSE else AppendHeader(view.Columns[0].Caption); end; if include then begin //Load the image ImgTxt := ''; state := ''; overlay := ''; if assigned(view.StateImages) then state := GetImageListText(view, iltStateImages, item.StateIndex); if view.ViewStyle = vsIcon then ImgTxt := GetImageListText(view, iltLargeImages, item.ImageIndex) else ImgTxt := GetImageListText(view, iltSmallImages, item.ImageIndex); if (item.OverlayIndex >= 0) then overlay := GetImageListText(view, iltOverlayImages, item.OverlayIndex); ImgTxt := Append([state, ImgTxt, overlay]); temp := item.Caption; // Added to protect from a/v in case CtrlManager isn't assigned. ColValue := false; if assigned (CtrlManager) then begin if assigned (CtrlManager.AccessColumns[view]) then ColValue := CtrlManager.AccessColumns[view].ColumnValues[0]; end; if (temp = '') and ColValue then temp := 'blank'; temp := Append([ImgTxt, temp]); Append(temp); end; if view.ViewStyle = vsReport then begin for i := 1 to view.Columns.Count - 1 do begin if (view.Columns[i].Width > 0) or (view.Columns[i].Width = -1) or (view.Columns[i].Width = -3) then begin AppendHeader(view.Columns[i].Caption); ImgTxt := ''; //Get subimages if Assigned(View.SmallImages) then ImgTxt := GetImageListText(view, iltSmallImages, item.SubItemImages[I-1]); if (i-1) < item.SubItems.Count then temp := item.SubItems[i-1] else temp := ''; // Added to protect from a/v in case CtrlManager isn't assigned. ColValue := false; if assigned (CtrlManager) then begin if assigned (CtrlManager.AccessColumns[view]) then ColValue := CtrlManager.AccessColumns[view].ColumnValues[0]; end; if (temp = '') and ColValue then begin temp := 'blank'; end; temp := Append([ImgTxt, temp]); Append(temp); end; end; end; end; procedure RegisterStandardDelphiComponents; begin RegisterAlternateHandleComponent(TCustomCombo, CustomComboAlternateHandle); RegisterManagedComponentClass(TCheckBox508Manager.Create); RegisterManagedComponentClass(TCheckListBox508Manager.Create); RegisterManagedComponentClass(TCustomGrid508Manager.Create); RegisterManagedComponentClass(TVA508StaticTextManager.Create); RegisterManagedComponentClass(TVA508EditManager.Create); RegisterManagedComponentClass(TVA508ComboManager.Create); with TVA508RegistrationScreenReader(GetScreenReader) do begin // even though TListView is in Default.JCF, we add it here to clear out previous MSAA setting RegisterCustomClassBehavior(TListView.ClassName, CLASS_BEHAVIOR_LIST_VIEW); RegisterCustomClassBehavior(TVA508StaticText.ClassName, CLASS_BEHAVIOR_STATIC_TEXT); end; RegisterMSAAQueryListClassProc(TListView, ListViewIndexQueryProc); { TODO -oJeremy Merrill -c508 : Add these components as ones that need an alternate handle TColorBox TValueListEditor ?? - may be fixed because it's a TStringGrid TCaptionStringGrid TToolBar (not needed when the tool bar doesn't have focus) TPageScroller add stuff for image processing descendents of TCustomTabControl } { TODO -oJeremy Merrill -c508 :Need to create a fix for the list box stuff here} end; { TCustomCombo Alternate Handle } type TExposedCustomCombo = class(TCustomCombo) public property EditHandle; end; function CustomComboAlternateHandle(Component: TWinControl): HWnd; begin Result := TExposedCustomCombo(Component).EditHandle; end; { Check Box Utils - used by multiple classes } function GetCheckBoxComponentName(AllowGrayed: boolean): string; begin if AllowGrayed then Result := 'Three State Check Box' else Result := 'Check Box'; end; function GetCheckBoxInstructionMessage(Checked: boolean): string; begin if not Checked then // handles clear and gray entries Result := 'to check press space bar' else Result := 'to clear check mark press space bar'; end; function GetCheckBoxStateText(State: TCheckBoxState): String; begin case State of cbUnchecked: Result := 'not checked'; cbChecked: Result := 'checked'; cbGrayed: Result := 'Partially Checked'; else Result := ''; end; end; { TCheckBox508Manager } constructor TCheckBox508Manager.Create; begin inherited Create(TCheckBox, [mtComponentName, mtInstructions, mtState, mtStateChange]); end; function TCheckBox508Manager.GetComponentName(Component: TWinControl): string; begin Result := GetCheckBoxComponentName(TCheckBox(Component).AllowGrayed); end; function TCheckBox508Manager.GetInstructions(Component: TWinControl): string; begin Result := GetCheckBoxInstructionMessage(TCheckBox(Component).Checked); end; function TCheckBox508Manager.GetState(Component: TWinControl): string; begin Result := GetCheckBoxStateText(TCheckBox(Component).State); end; { TCheckListBox508Manager } constructor TCheckListBox508Manager.Create; begin inherited Create(TCheckListBox, [mtComponentName, mtState, mtStateChange, mtItemChange, mtItemInstructions]); end; function TCheckListBox508Manager.GetComponentName( Component: TWinControl): string; var lb : TCheckListBox; begin lb := TCheckListBox(Component); if lb.AllowGrayed then Result := 'Three State Check List Box' else Result := 'Check List Box'; end; function TCheckListBox508Manager.GetItemInstructions( Component: TWinControl): string; var lb : TCheckListBox; idx: integer; begin lb := TCheckListBox(Component); idx := GetIndex(Component); if (idx < 0) then Result := '' else Result := GetCheckBoxInstructionMessage(lb.Checked[idx]); end; function TCheckListBox508Manager.GetIndex(Component: TWinControl): integer; var lb : TCheckListBox; begin lb := TCheckListBox(Component); if (lb.ItemIndex < 0) then begin if lb.Count > 0 then Result := 0 else Result := -1 end else Result := lb.ItemIndex; end; function TCheckListBox508Manager.GetItem(Component: TWinControl): TObject; var lb : TCheckListBox; begin lb := TCheckListBox(Component); Result := TObject((lb.items.Count * 10000) + (lb.ItemIndex + 2)); end; function TCheckListBox508Manager.GetState(Component: TWinControl): string; var lb : TCheckListBox; idx: integer; begin lb := TCheckListBox(Component); idx := GetIndex(Component); if idx < 0 then Result := '' else Result := GetCheckBoxStateText(lb.State[idx]); end; { TCustomForm508Manager } type TAccessGrid = class(TCustomGrid); constructor TCustomGrid508Manager.Create; begin { TODO : Add support for other string grid features - like state changes for editing or selecting cells } // inherited Create(TStringGrid, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE); inherited Create(TCustomGrid, [mtComponentName, mtInstructions, mtValue, mtItemChange], TRUE); // FLastX := -1; // FLastY := -1; end; // Data pieces // 1 = Column header, if any // 2 = Column # // 3 = number of columns // 4 = Row header, if any // 5 = Row # // 6 = number of rows // 7 = Cell # // 8 = total # of cells // 9 = cell contents const DELIM = '^'; function TCustomGrid508Manager.GetComponentName(Component: TWinControl): string; begin Result := ' grid '; // don't use 'grid' - we're abandoning the special code in the JAWS scripts for // grids - it's too messy, and based on the 'grid' component name end; { function TCustomGrid508Manager.GetData(Component: TWinControl; Value: string): string; var grid: TAccessGrid; row, col: integer; cnt, x, y, max, mult: integer; txt: string; procedure Add(txt: integer); overload; begin Result := Result + inttostr(txt) + DELIM; end; procedure Add(txt: string); overload; begin Result := Result + Piece(txt,DELIM,1) + DELIM; end; begin grid := TAccessGrid(Component); row := grid.Row; col := grid.Col; if (row >= 0) and (col >= 0) then begin if grid.FixedRows > 0 then Add(grid.GetEditText(col, 0)) else Add(''); Add(col - grid.FixedCols + 1); Add(grid.ColCount - grid.FixedCols); if grid.FixedCols > 0 then Add(grid.GetEditText(0, row)) else Add(''); Add(row - grid.FixedRows + 1); Add(grid.RowCount - grid.FixedRows); x := grid.ColCount - grid.FixedCols; y := grid.RowCount - grid.FixedRows; max := x * y; x := grid.Col - grid.FixedCols; y := grid.Row - grid.FixedRows; mult := grid.ColCount - grid.FixedCols; if (mult > 0) and (x >= 0) and (x < grid.ColCount) and (y >= 0) and (y < grid.RowCount) then begin cnt := (y * mult) + x + 1; Add(cnt); end else Add(0); Add(max); if Value = '' then txt := grid.GetEditText(col, row) else txt := Value; Add(txt); delete(Result,length(Result),1); // remove trailing delimeter end else Result := ''; end; } function TCustomGrid508Manager.GetInstructions(Component: TWinControl): string; var grid: TAccessGrid; // cnt, x, y, max, mult: integer; begin Result := ''; grid := TAccessGrid(Component); // x := grid.ColCount - grid.FixedCols; // y := grid.RowCount - grid.FixedRows; // max := x * y; // x := grid.Col - grid.FixedCols; // y := grid.Row - grid.FixedRows; // mult := grid.ColCount - grid.FixedCols; // // if (mult > 0) and // (x >= 0) and (x < grid.ColCount) and // (y >= 0) and (y < grid.RowCount) then // begin // cnt := (y * mult) + x + 1; // Result := IntToStr(cnt) + ' of ' + inttostr(max) + ', '; // end; Result := Result + 'To move to items use the arrow '; if goTabs in grid.Options then Result := Result + ' or tab '; Result := Result + 'keys'; end; // if // key //end; (* listbox column 120 row 430 unavailable (text of cell?) read only 20 or 81 listbox column 3 of 10 row 6 of 10 unavailable (text of cell?) read only 20 or 81 with each navigation: column 3 of 10 row 6 of 10 unavailable (text of cell?) read only *) function TCustomGrid508Manager.GetItem(Component: TWinControl): TObject; var grid: TAccessGrid; row, col, maxRow: integer; begin grid := TAccessGrid(Component); row := grid.Row + 2; col := grid.Col + 2; MaxRow := grid.RowCount + 3; if MaxRow < 1000 then MaxRow := 1000; Result := TObject((row * maxRow) + col); end; //function TCustomGrid508Manager.GetValue(Component: TWinControl): string; //var // grid: TAccessGrid; //begin // grid := TAccessGrid(Component); // Result := Piece(grid.GetEditText(grid.Col, grid.Row), DELIM, 1); //end; function TCustomGrid508Manager.GetValue(Component: TWinControl): string; var grid: TAccessGrid; row, col: integer; colHdr, rowHdr, txt: string; begin grid := TAccessGrid(Component); row := grid.Row; col := grid.Col; if (row >= 0) and (col >= 0) then begin // if col <> FLastX then // begin if grid.FixedRows > 0 then colHdr := Piece(grid.GetEditText(col, 0), DELIM, 1) else colHdr := ''; if colHdr = '' then colHdr := inttostr(col+1-grid.FixedCols) + ' of ' + inttostr(grid.ColCount-grid.FixedCols); colHdr := 'column ' + colhdr + ', '; // end // else // colHdr := ''; // FLastX := col; // if row <> FLastY then // begin if grid.FixedCols > 0 then rowHdr := Piece(grid.GetEditText(0, row), DELIM, 1) else rowHdr := ''; if rowHdr = '' then rowHdr := inttostr(row+1-grid.FixedRows) + ' of ' + inttostr(grid.RowCount-grid.FixedRows); rowHdr := 'row ' + rowhdr + ', '; // end // else // rowHdr := ''; // FLastY := row; txt := Piece(grid.GetEditText(col, row), DELIM, 1); if txt = '' then txt := 'blank'; Result := colHdr + rowHdr + txt; end else Result := ' '; end; { TVA508StaticTextManager } constructor TVA508StaticTextManager.Create; begin inherited Create(TVA508StaticText, [mtComponentName, mtCaption, mtValue], TRUE); end; function TVA508StaticTextManager.GetCaption(Component: TWinControl): string; begin Result := ' '; end; function TVA508StaticTextManager.GetComponentName( Component: TWinControl): string; begin Result := 'label'; end; function TVA508StaticTextManager.GetValue(Component: TWinControl): string; var next: TVA508ChainedLabel; comp: TVA508StaticText; begin comp := TVA508StaticText(Component); Result := comp.Caption; next := comp.NextLabel; while assigned(next) do begin Result := Result + ' ' + next.Caption; next := next.NextLabel; end; end; { TVA508EditManager } constructor TVA508EditManager.Create; begin inherited Create(TEdit, [mtValue], TRUE); end; function TVA508EditManager.GetValue(Component: TWinControl): string; begin Result := TEdit(Component).Text; end; { TVA508ComboManager } constructor TVA508ComboManager.Create; begin inherited Create(TComboBox, [mtValue], TRUE); end; function TVA508ComboManager.GetValue(Component: TWinControl): string; begin Result := TComboBox(Component).Text; end; initialization RegisterStandardDelphiComponents; end.
{test program for zpipe unit} program t_zpipe; {$ifdef win32} {$ifndef VirtualPascal} {$apptype console} {$endif} {$endif} uses zlibh, zpipe; {---------------------------------------------------------------------------} procedure abort(const msg: str255); {-write message and halt} begin writeln(msg); halt; end; var fi, fo: file; ok: boolean; oc: char8; ret: int; os: string[3]; begin ok := paramcount>2; oc := #0; if ok then begin os := {$ifdef unicode} str255 {$endif}(paramstr(1)); ok := (length(os)=2) and (os[1]='-'); if ok then begin oc := upcase(os[2]); ok := (oc='C') or (oc='D'); end; end; if not ok then abort('Usage: t_zpipe [-c|-d] <infile> <outfile>'); {allow read only infile} filemode := 0; assign(fi, paramstr(2)); reset(fi,1); if IOResult<>0 then Abort('Reset error: '+{$ifdef unicode} str255 {$endif}(paramstr(2))); assign(fo,paramstr(3)); rewrite(fo,1); if IOResult<>0 then Abort('Rewrite error: '+{$ifdef unicode} str255 {$endif}(paramstr(2))); if oc='C' then ret := def(fi,fo,Z_DEFAULT_COMPRESSION) else ret := inf(fi,fo); if ret=Z_OK then writeln('OK') else writeln('zlib error: ', ret); end.
unit StringUtils; interface uses SysUtils, WideStrUtils; (* Contains various string handling routines for parsing Jet SQL data. *) type {$IFDEF UNICODE} UniString = string; {$ELSE} UniString = WideString; {$ENDIF} TMarkerFlag = ( mfKeepOp, //do not consider op/ed to be part of the contents mfKeepEd, //for example, keep them when deleting comments mfNesting, //allow nesting mfEscaping, //ignore escaped EDs. Requires no nesting. mfEOFEnds //EOF is a legal terminator for this marker (usually the ones ending in CRLF) ); TMarkerFlags = set of TMarkerFlag; //Note on nesting: //Blocks can either allow nesting, in which case subblocks of any type can exist, //or be "comment-like", so that all the contents is treated as a data. //In nesting blocks, escaping is not allowed. TMarker = record s: UniString; e: UniString; f: TMarkerFlags; end; PMarker = ^TMarker; TMarkers = array of TMarker; function Marker(s, e: UniString; f: TMarkerFlags=[]): TMarker; procedure Append(var mk: TMarkers; r: TMarkers); var (* These will be populated on initialization. If they were consts, they would be type incompatible, plus it would have been a pain to pass both pointer and length everywhere. *) //For RemoveComments() CommentMarkers: TMarkers; //Everything in these is considered string literal (comment openers ignored) StringLiteralMarkers: TMarkers; //Sequences in which final ';' is ignored //Sequences, in which CREATE TABLE separator ',' is ignored //Match() NoEndCommandMarkers: TMarkers; //Pseudo marker (#13, #10) - used in CRLF deletion EndLineMarker: TMarker; function charPos(start, ptr: PWideChar): integer; function prevChar(ptr: PWideChar): PWideChar; function prevCharIs(start, ptr: PWideChar; c: WideChar): boolean; function nextChar(ptr: PWideChar): PWideChar; function SubStr(pc, pe: PWideChar): UniString; procedure Adjust(ups, upc, ps: PWideChar; out pc: PWideChar); function GetMeta(s: UniString; meta: UniString; out content: UniString): boolean; function MetaPresent(s, meta: UniString): boolean; function WStrPosIn(ps, pe, pattern: PWideChar): PWideChar; function WStrMatch(main, sub: PWideChar): boolean; function WStrPosEnd(pc: PWideChar; m: TMarkers; mk: TMarker): PWideChar; function RemoveParts(s: UniString; mk: TMarker; IgnoreBlocks: TMarkers): string; function RemoveCommentsI(s: UniString; m: TMarkers): UniString; function RemoveComments(s: UniString): UniString; function CommentTypeOpener(cType: integer): UniString; function CommentTypeCloser(cType: integer): UniString; function WStrPosAnyCommentI(ps: PWideChar; m: TMarkers; out pc: PWideChar): integer; function WStrPosAnyComment(ps: PWideChar; out pc: PWideChar): integer; function WStrPosCommentCloserI(pc: PWideChar; cType: integer; m: TMarkers): PWideChar; function WStrPosCommentCloser(pc: PWideChar; cType: integer): PWideChar; function WStrPosOrCommentI(ps: PWideChar; pattern: PWideChar; m: TMarkers; out pc: PWideChar): integer; function WStrPosOrComment(ps: PWideChar; pattern: PWideChar; out pc: PWideChar): integer; function WStrPosIgnoreCommentsI(ps: PWideChar; pattern: PWideChar; m: TMarkers): PWideChar; function WStrPosIgnoreComments(ps: PWideChar; pattern: PWideChar): PWideChar; type TUniStringArray = array of UniString; function MatchI(s: UniString; parts: array of UniString; m: TMarkers): TUniStringArray; function Match(s: UniString; parts: array of UniString): TUniStringArray; function CutIdBrackets(s: UniString): UniString; function SplitI(s: UniString; sep: WideChar; m: TMarkers): TUniStringArray; function Split(s: UniString; sep: WideChar): TUniStringArray; function Contains(list: TUniStringArray; item: UniString): boolean; function ToLowercase(const s: UniString): UniString; overload; function ToLowercase(const list: TUniStringArray): TUniStringArray; overload; function FieldNameFromDefinition(s: UniString): UniString; implementation //Returns character index of a character Ptr in string Start function charPos(start, ptr: PWideChar): integer; begin Result := 1+(integer(ptr) - integer(start)) div SizeOf(WideChar); end; //Returns a pointer to the previous character (obviously, no check for the start of the string) function prevChar(ptr: PWideChar): PWideChar; begin Result := PWideChar(integer(ptr)-SizeOf(WideChar)); end; //Checks if the previous character exists (using Start) and if it's the required one. function prevCharIs(start, ptr: PWideChar; c: WideChar): boolean; begin if integer(ptr) <= integer(start) then Result := false else Result := PWideChar(integer(ptr)-SizeOf(WideChar))^=c; end; function nextChar(ptr: PWideChar): PWideChar; begin Result := PWideChar(integer(ptr)+SizeOf(WideChar)); end; //Returns a string consisting of [pc, pe). Not including pe. function SubStr(pc, pe: PWideChar): UniString; begin SetLength(Result, (integer(pe)-integer(pc)) div SizeOf(WideChar)); Move(pc^, Result[1], (integer(pe)-integer(pc))); //size in bytes end; //Receives two starting pointers for two strings and one position pointer. //Adjusts the second position pointer so that it points in the second string //to the character with the same index first position pointer points at in the first string. //In other words: // ups: 'Sample text'; // upc: 'ple text'; // ps: 'SAMPLE TEXT'; //Output: // pc: 'PLE TEXT'; procedure Adjust(ups, upc, ps: PWideChar; out pc: PWideChar); begin pc := PWideChar(integer(ps) + integer(upc) - integer(ups)); end; //Scans string S for meta Meta (/**Meta* content */) and returns it's content. //Returns false if no meta was found. //Metas are a private way of storing information in comments. function GetMeta(s: UniString; meta: UniString; out content: UniString): boolean; var pc, pe: PWideChar; begin pc := WStrPos(@s[1], PWideChar('/**'+meta+'*')); if pc=nil then begin Result := false; exit; end; Inc(pc, 4+Length(meta)); pe := WStrPos(pc, PWideChar(UniString('*/'))); if pe=nil then begin //unterminated comment - very strange Result := false; exit; end; content := Trim(SubStr(pc, pe)); Result := true; end; //Checks if the specified meta is present in the string function MetaPresent(s, meta: UniString): boolean; begin Result := (WStrPos(@s[1], PWideChar('/**'+meta+'*')) <> nil); end; //Looks for a pattern inside of a substring [ps, pe) not including pe. //Returns a pointer to Pattern or nil. function WStrPosIn(ps, pe, pattern: PWideChar): PWideChar; var Str, SubStr: PWideChar; Ch: WideChar; begin Result := nil; if (ps = nil) or (ps^ = #0) or (pattern = nil) or (pattern^ = #0) or (integer(ps) >= integer(pe)) then Exit; Result := ps; Ch := pattern^; repeat if Result^ = Ch then begin Str := Result; SubStr := pattern; repeat Inc(Str); Inc(SubStr); if (SubStr^ = #0) or (integer(SubStr)>=integer(pe)) then exit; if (Str^ = #0) or (integer(Str)>=integer(pe)) then begin Result := nil; exit; end; if Str^ <> SubStr^ then break; until (FALSE); end; Inc(Result); until (Result^ = #0) or (integer(Result)>=integer(pe)); Result := nil; end; //Returns True if Main starts with Sub. function WStrMatch(main, sub: PWideChar): boolean; begin while (main^<>#00) and (sub^<>#00) and (main^=sub^) do begin Inc(main); Inc(sub); end; Result := (sub^=#00); end; //Receives a pointer to a start of the block of type Ind. //Looks for an ending marker, minding nesting. Returns a pointer to the start of ED. function WStrPosEnd(pc: PWideChar; m: TMarkers; mk: TMarker): PWideChar; var i: integer; SpecSymbol: boolean; begin //Skip opener Inc(pc, Length(mk.s)); //To find the block ED, we need to scan till the end markers: // I. For simple comments: minding specsymbols. // II. For nested comments: // - scan till the ED marker or the OP marker for any comment // - if it's the OP, recursively call the search to get it's ED, restart from there SpecSymbol := false; while pc^ <> #00 do begin if mfNesting in mk.f then //Look for any OP for i := 0 to Length(m) - 1 do if WStrMatch(pc, PWideChar(mk.s)) then begin //Find it's ED pc := WStrPosEnd(pc, m, m[i]); if pc=nil then begin Result := nil; exit; end; //Skip ED (should be available! it was matched) Inc(pc, Length(m[i].e)); break; end; if mfEscaping in mk.f then if SpecSymbol then begin SpecSymbol := false; Inc(pc); continue; end else if pc^='\' then begin SpecSymbol := true; Inc(pc); continue; end; if WStrMatch(pc, PWideChar(mk.e)) then begin Result := pc; exit; end; Inc(pc); end; Result := nil; end; //Removes all the parts of the text between Op-Ed markers, except those in IgnoreBlocks. //Usually you want to pass all the non-nesting block types in IgnoreBlocks. //Flags govern if the OP/ED markers themselves will be stripped or preserved. function RemoveParts(s: UniString; mk: TMarker; IgnoreBlocks: TMarkers): string; var ps, pc, pe: PWideChar; ctype: integer; //True when after the last block we've appended to Result, there have been blocks that we have skipped. //We'll need to ensure there's at least 1 space before the next block. lastPartSkipped: boolean; //Appends the block of characters from pc to pe to Result procedure appendResult(pc, pe: PWideChar); begin //Leave one or zero spaces at the start if (Length(Result) > 0) and (Result[Length(Result)]=' ') then while pc^=' ' do Inc(pc) else if pc^=' ' then begin //or we'd do Dec without an Inc while pc^=' ' do Inc(pc); Dec(pc); end else //no spaces at all //Ensure at least one space where we took out blocks (or we'll lump unrelated things together) if (Result <> '') and lastPartSkipped then Result := Result + ' '; //One space at most at the end Dec(pe); //now points to the last symbol if (pe^=' ') and (integer(pc) < integer(pe)) then begin while (pe^=' ') and (integer(pc) < integer(pe)) do Dec(pe); Inc(pe); //one space end; Inc(pe); //points to the symbol after the last one //Copy Result := Result + SubStr(pc, pe); //We have added something, so the last part has not been skipped lastPartSkipped := false; end; begin Result := ''; if s = '' then exit; lastPartSkipped := false; ps := @s[1]; ctype := WStrPosOrCommentI(ps, PWideChar(mk.s), IgnoreBlocks, pc); while pc <> nil do begin if ctype>=0 then begin //It's an IgnoreBlock pe := WStrPosEnd(pc, IgnoreBlocks, IgnoreBlocks[ctype]); //Incomplete block, treat as plaintext if (pe=nil) and not (mfEOFEnds in IgnoreBlocks[ctype].f) then begin appendResult(ps, WStrEnd(ps)); exit; end; //Next part if pe = nil then //ended with EOF pe := StrEnd(pc) else Inc(pe, Length(IgnoreBlocks[ctype].e)); //Disregard Flags.mfKeepEd because we copy the contents anyway appendResult(ps, pe); ps := pe; end else begin //It's a DeleteBlock pe := WStrPosEnd(pc, IgnoreBlocks, mk); //Incomplete block, treat as plaintext if (pe=nil) and not (mfEOFEnds in mk.f) then begin appendResult(ps, WStrEnd(ps)); exit; end; //Save the text till Pc and skip [pc, pe] if mfKeepOp in mk.f then Inc(pc, Length(mk.s)); appendResult(ps, pc); //Set the skipped flag so that we add spaces as neccessary later lastPartSkipped := true; //Next part if pe = nil then //ended with EOF ps := StrEnd(pc) else begin ps := pe; if not (mfKeepEd in mk.f) then Inc(ps, Length(mk.e)); end; end; ctype := WStrPosOrCommentI(ps, PWideChar(mk.s), IgnoreBlocks, pc); end; //If there's still text till the end, add it if ps^<>#00 then appendResult(ps, WStrEnd(ps)); end; //Removes all supported comments, linefeeds. function RemoveCommentsI(s: UniString; m: TMarkers): UniString; var i: integer; im: TMarkers; begin im := Copy(m); //Blocks to ignore comments in. Append(im, StringLiteralMarkers); for i := 0 to Length(m)-1 do s := RemoveParts(s, m[i], im); Result := RemoveParts(s, EndLineMarker, im); end; function RemoveComments(s: UniString): UniString; begin Result := RemoveCommentsI(s, CommentMarkers); end; function CommentTypeOpener(cType: integer): UniString; begin if (cType>=0) and (cType<Length(CommentMarkers)-1) then Result := CommentMarkers[cType].s else Result := ''; end; function CommentTypeCloser(cType: integer): UniString; begin if (cType>=0) and (cType<=Length(CommentMarkers)-1) then Result := CommentMarkers[cType].e else Result := ''; end; //Finds the first comment of any supported type or nil. Returns comment type (int) or -1. //Use WStrPosCommentCloser() to find comment closer for a given type. //Use CommentTypeOpener(), CommentTypeCloser() if you're curious about the details. function WStrPosAnyCommentI(ps: PWideChar; m: TMarkers; out pc: PWideChar): integer; var pt: PWideChar; i: integer; begin pc := nil; Result := -1; for i := 0 to Length(m) - 1 do begin if pc=nil then pt := WStrPos(ps, PWideChar(m[i].s)) else pt := WStrPosIn(ps, pc, PWideChar(m[i].s)); if pt<>nil then begin pc := pt; Result := i; end; end; end; function WStrPosAnyComment(ps: PWideChar; out pc: PWideChar): integer; begin Result := WStrPosAnyCommentI(ps, CommentMarkers, pc); end; //Finds the comment closer by comment type and returns the pointer to the first //symbol after the comment is over. Or nil. //Minds comment nesting, if it's enabled for this comment type. function WStrPosCommentCloserI(pc: PWideChar; cType: integer; m: TMarkers): PWideChar; begin if (cType >= 0) and (cType <= Length(m)-1) then begin Result := WStrPosEnd(pc, m, m[cType]); if (Result<>nil) and not (mfKeepEd in m[cType].f) then Inc(Result, Length(m[cType].e)); end else Result := nil; end; function WStrPosCommentCloser(pc: PWideChar; cType: integer): PWideChar; begin Result := WStrPosCommentCloserI(pc, cType, CommentMarkers); end; function WStrMatchAnyMarkerOp(ps: PWideChar; m: TMarkers): integer; var i: integer; begin Result := 0; for i := 0 to Length(m) - 1 do if WStrMatch(ps, PWideChar(m[i].s)) then begin Result := i; break; end; end; //Finds a first instance of Pattern in Ps OR a first instance of comment of any type, //whichever comes first. //Returns the comment type OR -1. If the comment-type >=0, then pc points //to a comment opener, else it points to the Pattern instance or nil. function WStrPosOrCommentI(ps: PWideChar; pattern: PWideChar; m: TMarkers; out pc: PWideChar): integer; begin pc := ps; while pc^<>#00 do begin if WStrMatch(pc, pattern) then begin Result := -1; exit; end; Result := WStrMatchAnyMarkerOp(pc, m); if Result<>0 then exit; Inc(pc); end; Result := -1; pc := nil; end; function WStrPosOrComment(ps: PWideChar; pattern: PWideChar; out pc: PWideChar): integer; begin Result := WStrPosOrCommentI(ps, pattern, CommentMarkers, pc); end; //Finds a first instance of Pattern in Ps IGNORING any comments on the way. function WStrPosIgnoreCommentsI(ps: PWideChar; pattern: PWideChar; m: TMarkers): PWideChar; var ct: integer; begin repeat ct := WStrPosOrCommentI(ps, pattern, m, Result); if ct<0 then break; Inc(Result, Length(m[ct].s)); //or else WStrPosCommentCloser will think it's another one ps := WStrPosCommentCloserI(Result, ct, m); if ps=nil then begin //malformed comment, ignore Result := nil; exit; end; until false; end; //Finds a first instance of Pattern in Ps, skipping comments. Returns nil //if no instance can be found function WStrPosIgnoreComments(ps: PWideChar; pattern: PWideChar): PWideChar; begin Result := WStrPosIgnoreCommentsI(ps, pattern, CommentMarkers); end; //Splits string by parts, for example: // Input: asd bsd (klmn pqrs) rte // Parts: bsd,(,) // Result: asd,,klmn pqrs,rte //Handles spaces and application-supported comments fine (comments are ignored //in matching but included in results) // m: Ignore markers function MatchI(s: UniString; parts: array of UniString; m: TMarkers): TUniStringArray; var us: UniString; ps, pc: PWideChar; ups, upc: PWideChar; i: integer; begin us := WideUpperCase(s); for i := 0 to Length(parts) - 1 do parts[i] := WideUpperCase(parts[i]); SetLength(Result, Length(parts)+1); //Empty string if Length(s)<=0 then begin if Length(parts)>0 then SetLength(Result, 0) //error else begin SetLength(Result, 1); //this is actually okay Result[0]:=''; end; exit; end; //Parse ps := @s[1]; ups := @us[1]; for i := 0 to Length(parts) - 1 do begin //Find next part, skipping comments as needed upc := WStrPosIgnoreCommentsI(ups, PWideChar(parts[i]), m); if upc=nil then begin //no match SetLength(Result, 0); exit; end; Adjust(ups, upc, ps, pc); Result[i] := Trim(SubStr(ps, pc)); ups := upc; ps := pc; Inc(ups, Length(parts[i])); Inc(ps, Length(parts[i])); end; Result[Length(Result)-1] := Trim(SubStr(ps, WStrEnd(ps))); end; function Match(s: UniString; parts: array of UniString): TUniStringArray; begin Result := MatchI(s, parts, NoEndCommandMarkers); end; //Deletes Jet identification brackets [] if they're present. (Also trims the string first) function CutIdBrackets(s: UniString): UniString; var ps, pe: PWideChar; begin if Length(s)=0 then begin Result := ''; exit; end; ps := @s[1]; while ps^=' ' do Inc(ps); pe := @s[Length(s)]; while (pe^=' ') and (integer(ps) < integer(pe)) do Dec(pe); if (ps^='[') and (pe^=']') then begin Inc(ps); Dec(pe); end; if (ps<>@s[1]) or (pe<>@s[Length(s)]) then begin Inc(pe); Result := SubStr(ps, pe); end else Result := s; //nothign to cut end; //Splits string by separator, trims parts. Comments are handled fine. function SplitI(s: UniString; sep: WideChar; m: TMarkers): TUniStringArray; var ps, pc: PWideChar; begin if Length(s)<=0 then begin SetLength(Result, 1); Result[0] := ''; exit; end; ps := @s[1]; SetLength(Result, 0); repeat pc := WStrPosIgnoreCommentsI(ps, PWideChar(UniString(sep)), m); SetLength(Result, Length(Result)+1); if pc=nil then begin Result[Length(Result)-1] := SubStr(ps, WStrEnd(ps)); exit; end; Result[Length(Result)-1] := SubStr(ps, pc); ps := pc; Inc(ps); until false; end; function Split(s: UniString; sep: WideChar): TUniStringArray; begin Result := SplitI(s, sep, NoEndCommandMarkers); end; //True if list contains item (case-sensitive) function Contains(list: TUniStringArray; item: UniString): boolean; var i: integer; begin Result := false; for i := 0 to Length(list)-1 do if list[i] = item then begin Result := true; break; end; end; function ToLowercase(const s: UniString): UniString; begin Result := s.ToLower; end; function ToLowercase(const list: TUniStringArray): TUniStringArray; overload; var i: integer; begin SetLength(Result, Length(list)); for i := 0 to Length(list)-1 do Result[i] := list[i].ToLower; end; //Extracts a field name (first word, possibly in [] brackets) from a CREATE TABLE //field definition. //Allows spaces in field name, treats comments inside of brackets as normal symbols, //treats comments outside as separators. function FieldNameFromDefinition(s: UniString): UniString; var pc: PWideChar; InBrackets: boolean; begin if Length(s)<=0 then begin Result := ''; exit; end; pc := @s[1]; InBrackets := false; while pc^<>#00 do begin if pc^='[' then InBrackets := true else if pc^=']' then InBrackets := false else if InBrackets then begin //do nothing end else if (pc^=' ') or (pc^='{') or ((pc^='-')and(nextChar(pc)^='-')) or ((pc^='/')and(nextChar(pc)^='*')) then begin Result := Trim(SubStr(@s[1], pc)); exit; end; Inc(pc); end; Result := Trim(s); end; function Marker(s, e: UniString; f: TMarkerFlags=[]): TMarker; begin Result.s := s; Result.e := e; Result.f := f; end; procedure Append(var mk: TMarkers; r: TMarkers); var i: integer; begin SetLength(mk, Length(mk)+Length(r)); for i := 0 to Length(r) - 1 do mk[Length(mk)-Length(r)+i] := r[i]; end; initialization SetLength(CommentMarkers, 3); CommentMarkers[0] := Marker('{', '}' , [mfEscaping]); CommentMarkers[1] := Marker('/*', '*/', [mfEscaping]); CommentMarkers[2] := Marker('--', #13#10, [mfKeepEd, mfEOFEnds]); SetLength(StringLiteralMarkers, 2); StringLiteralMarkers[0] := Marker('''', '''', [mfEscaping]); StringLiteralMarkers[1] := Marker('"', '"', [mfEscaping]); NoEndCommandMarkers := Copy(CommentMarkers); Append(NoEndCommandMarkers, StringLiteralMarkers); SetLength(NoEndCommandMarkers, 7); NoEndCommandMarkers[5] := Marker('[', ']'); NoEndCommandMarkers[6] := Marker('(', ')', [mfNesting]); EndLineMarker := Marker(#13, #10); end.
unit fConsulter; (* Projet : POC Notes de frais URL du projet : https://www.developpeur-pascal.fr/p/_6006-poc-notes-de-frais-une-application-multiplateforme-de-saisie-de-notes-de-frais-en-itinerance.html Auteur : Patrick Prémartin https://patrick.premartin.fr Editeur : Olf Software https://www.olfsoftware.fr Site web : https://www.developpeur-pascal.fr/ Ce fichier et ceux qui l'accompagnent sont fournis en l'état, sans garantie, à titre d'exemple d'utilisation de fonctionnalités de Delphi dans sa version Tokyo 10.2 Vous pouvez vous en inspirer dans vos projets mais n'êtes pas autorisé à rediffuser tout ou partie des fichiers de ce projet sans accord écrit préalable. *) interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, dmBaseFMX, System.Rtti, FMX.Grid.Style, Data.Bind.Controls, FMX.StdCtrls, FMX.Layouts, FMX.Bind.Navigator, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Grid, Data.Bind.EngExt, FMX.Bind.DBEngExt, FMX.Bind.Grid, System.Bindings.Outputs, FMX.Bind.Editors, Data.Bind.Components, Data.Bind.Grid, Data.Bind.DBScope; type TfrmConsulter = class(TForm) StringGrid1: TStringGrid; BindNavigator1: TBindNavigator; btnRetour: TButton; Header: TToolBar; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource; procedure btnRetourClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); private { Déclarations privées } public { Déclarations publiques } end; var frmConsulter: TfrmConsulter; implementation {$R *.fmx} uses uParam; procedure TfrmConsulter.btnRetourClick(Sender: TObject); begin Close; end; procedure TfrmConsulter.FormClose(Sender: TObject; var Action: TCloseAction); begin dm.qryNotesDeFrais.Close; end; procedure TfrmConsulter.FormShow(Sender: TObject); begin if not dm.FDConnection1.Connected then dm.FDConnection1.Connected := true; if dm.qryNotesDeFrais.Active then dm.qryNotesDeFrais.Close; dm.qryNotesDeFrais.open('select * from notesdefrais where utilisateur_code=:code order by datendf desc', [usercode]); end; initialization frmConsulter := nil; end.
{ This sample application demonstrates the following features of the TOLEContainer: - Toolbar negotiation - Status bar hints while inplace editing - Local popup menu with OLE verbs and standard OLE functions (See the popup menu in MDICHILD.PAS) - Using the TOLEContainer's dialogs including InsertObject, ObjectProperties and PasteSpecial. - Using the TOLEContainer's constructors CreateLinkToFile, CreateObjectFromFile. - Menu merging during in-place activation - Using OLE object verbs. } unit mdimain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, Buttons, ExtCtrls, Menus, OleCtnrs; type TMainForm = class(TForm) MainMenu1: TMainMenu; File1: TMenuItem; Exit1: TMenuItem; Window2: TMenuItem; Tile1: TMenuItem; Cascade1: TMenuItem; Help1: TMenuItem; About1: TMenuItem; Toolbar: TPanel; SpeedButton1: TSpeedButton; New1: TMenuItem; N1: TMenuItem; TileHorizontally1: TMenuItem; LinkButton: TSpeedButton; CopyButton: TSpeedButton; CutButton: TSpeedButton; PasteButton: TSpeedButton; OpenButton: TSpeedButton; OpenDialog1: TOpenDialog; StatusPanel: TPanel; StatusBar: TStatusBar; Save1: TMenuItem; SaveAs1: TMenuItem; Close2: TMenuItem; CloseAll1: TMenuItem; SaveDialog1: TSaveDialog; Open1: TMenuItem; N2: TMenuItem; ArrangeIcons1: TMenuItem; NewButton: TSpeedButton; SaveButton: TSpeedButton; procedure New1Click(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure Tile1Click(Sender: TObject); procedure TileHorizontally1Click(Sender: TObject); procedure Cascade1Click(Sender: TObject); procedure Close1Click(Sender: TObject); procedure Copy1Click(Sender: TObject); procedure Paste1Click(Sender: TObject); procedure Object2Click(Sender: TObject); procedure LinkButtonClick(Sender: TObject); procedure About1Click(Sender: TObject); procedure Save1Click(Sender: TObject); procedure File1Click(Sender: TObject); procedure Window2Click(Sender: TObject); procedure Open1Click(Sender: TObject); procedure CutButtonClick(Sender: TObject); procedure ArrangeIcons1Click(Sender: TObject); procedure CloseAll1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure ShowHint(Sender: TObject); public { Public declarations } end; var MainForm: TMainForm; implementation uses MDIChild, about; {$R *.DFM} procedure TMainForm.ShowHint(Sender: TObject); begin Statusbar.Panels[0].Text := Application.Hint; end; procedure TMainForm.New1Click(Sender: TObject); begin MDIChildForm := TMDIChildForm.Create(Self); with MDIChildForm do begin InsertObject1Click(Sender); with OleContainer1 do if NewInserted then DoVerb(PrimaryVerb); end; end; procedure TMainForm.Exit1Click(Sender: TObject); begin Close; end; procedure TMainForm.Tile1Click(Sender: TObject); begin TileMode := tbVertical; Tile; end; procedure TMainForm.TileHorizontally1Click(Sender: TObject); begin TileMode := tbHorizontal; Tile; end; procedure TMainForm.Cascade1Click(Sender: TObject); begin Cascade; end; procedure TMainForm.Close1Click(Sender: TObject); begin if ActiveMDIChild <> nil then TMDIChildForm(ActiveMDIChild).Close; end; procedure TMainForm.Copy1Click(Sender: TObject); begin if ActiveMDIChild <> nil then TMDIChildForm(ActiveMDIChild).OleContainer1.Copy; end; procedure TMainForm.Paste1Click(Sender: TObject); begin if ActiveMDIChild = nil then exit; with TMDIChildForm(ActiveMDIChild).OleContainer1 do if (State = osEmpty) or (MessageDlg('Replace existing object?', mtConfirmation, mbOkCancel, 0) = mrOk) then begin Paste; CutButton.Enabled := True; CopyButton.Enabled := True; end; end; procedure TMainForm.Object2Click(Sender: TObject); begin if ActiveMDIChild <> nil then TMDIChildForm(ActiveMDIChild).OleContainer1.ObjectPropertiesDialog; end; procedure TMainForm.LinkButtonClick(Sender: TObject); var MDIChild: TMDIChildForm; begin if ActiveMDIChild = nil then begin if OpenDialog1.Execute then begin MDIChild := TMDIChildForm.Create(Self); MDIChild.CreateFromFile(OpenDialog1.FileName, True); end; end else with TMDIChildForm(ActiveMDIChild) do if (OleContainer1.State = osEmpty) or (MessageDlg('Replace existing object?', mtConfirmation, mbOkCancel, 0) = mrOk) then if OpenDialog1.Execute then CreateFromFile(OpenDialog1.FileName, True); end; procedure TMainForm.About1Click(Sender: TObject); begin AboutBox := TAboutBox.Create(Self); try AboutBox.ShowModal; finally AboutBox.Free; end; end; procedure TMainForm.Save1Click(Sender: TObject); begin with TMDIChildForm(ActiveMDIChild), SaveDialog1 do if (Length(FileName) = 0) or (Sender = SaveAs1) then begin if Execute then SaveFile(FileName); end else SaveFile(FileName); end; procedure TMainForm.File1Click(Sender: TObject); begin if ActiveMDIChild <> nil then with TMDIChildForm(ActiveMDIChild).OleContainer1 do begin Save1.Enabled := Modified; SaveAs1.Enabled := Modified; end else begin Save1.Enabled := False; SaveAs1.Enabled := False; end; Close2.Enabled := ActiveMDIChild <> nil; CloseAll1.Enabled := ActiveMDIChild <> nil; end; procedure TMainForm.Window2Click(Sender: TObject); begin Tile1.Enabled := ActiveMDIChild <> nil; TileHorizontally1.Enabled := ActiveMDIChild <> nil; Cascade1.Enabled := ActiveMDIChild <> nil; ArrangeIcons1.Enabled := ActiveMDIChild <> nil; end; procedure TMainForm.Open1Click(Sender: TObject); begin with OpenDialog1 do if Execute then begin with TMDIChildForm.Create(Self) do CreateFromFile(OpenDialog1.FileName, False); CutButton.Enabled := True; CopyButton.Enabled := True; end; end; procedure TMainForm.CutButtonClick(Sender: TObject); begin if ActiveMDIChild <> nil then with TMDIChildForm(ActiveMDIChild).OleContainer1 do begin Copy; DestroyObject; CutButton.Enabled := False; CopyButton.Enabled := False; PasteButton.Enabled := True; end; end; procedure TMainForm.ArrangeIcons1Click(Sender: TObject); begin ArrangeIcons; end; procedure TMainForm.CloseAll1Click(Sender: TObject); var i: integer; begin for i := 0 to MDIChildCount - 1 do MDIChildren[i].Close; end; procedure TMainForm.FormCreate(Sender: TObject); begin Application.OnHint := ShowHint; end; end.
{Unit Type Data} unit typedata; {Interface} interface {Constant} const Nmax = 1000; Emax = 10; {Jumlah Energi Maksimum} {Type Data} type {Tanggal} tanggal = record dd : integer; {Hari} mm : integer; {Bulan} yy : integer; {Tahun} end; {Bahan Mentah} bahanMentah = record Nama : string; {Nama Bahan Mentah} Harga : longint; {Harga Beli Bahan Mentah} Durasi : integer; {Durasi Kadaluarsa Bahan Mentah (Hari)} end; {File Bahan Mentah} tabBahanMentah = record FBM : array [1..Nmax] of bahanMentah; Neff : integer; end; {Bahan Olahan} bahanOlahan = record Nama : string; {Nama Bahan Olahan} Harga : longint; {Harga Jual Bahan Olahan} Jumlah : integer; {Jumlah Bahan Mentah Yang Menyusun Bahan Olahan} Bahan : array [1..Nmax] of string; {Bahan Mentah Yang Digunakan Untuk Membuat Bahan Olahan} end; {File Bahan Olahan} tabBahanOlahan = record FBO : array [1..Nmax] of bahanOlahan; Neff : integer; end; {Inventori Bahan Mentah} inventoriBahanMentah = record Nama : string; {Nama Bahan Mentah Di Inventori} Waktu : tanggal; {Tanggal Bahan Mentah Dibeli} Jumlah : integer; {Jumlah Bahan Mentah Di Inventori} end; {File Inventori Bahan Mentah} tabInventoriBahanMentah = record FIBM : array [1..Nmax] of inventoriBahanMentah; Neff : integer; end; {List File Inventori Bahan Mentah} fileInventoriBahanMentah = record LFIBM : array [1..10] of tabInventoriBahanMentah; end; {Inventori Bahan Olahan} inventoriBahanOlahan = record Nama : string; {Nama Bahan Olahan Di Inventori} Waktu : tanggal; {Tanggal Bahan Olahan Dibuat} Jumlah : integer; {Jumlah Bahan Olahan Di Inventori} end; {File Inventori Bahan Olahan} tabInventoriBahanOlahan = record FIBO : array [1..Nmax] of inventoriBahanOlahan; Neff : integer; end; {List File Inventori Bahan Olahan} fileInventoriBahanOlahan = record LFIBO : array [1..10] of tabInventoriBahanOlahan; end; {Resep} resep = record Nama : string; {Nama Resep} Harga : longint; {Harga Jual Resep} Jumlah : integer; {Jumlah Bahan Yang Digunakan Untuk Membuat Resep} Bahan : array [1..Nmax] of string; {Bahan Yang Digunakan Untuk Membuat Resep} end; {File Resep} tabResep = record FR : array [1..Nmax] of resep; Neff : integer; end; {Simulasi} simulasi = record Nomor : integer; {Nomor Simulasi} Waktu : tanggal; {Tanggal Mulai Simulasi} Hidup : integer; {Waktu Bermain} Energi : integer; {Energi} Kapasitas : integer; {Kapasitas Maksimum Inventori} BeliMentah : integer; {Jumlah Bahan Mentah Yang Dibeli} BuatOlahan : integer; {Jumlah Bahan Olahan Yang Dibuat} JualOlahan : integer; {Jumlah Bahan Olahan Yang Dijual} JualResep : integer; {Jumlah Resep Yang Dijual} Pemasukan : longint; {Total Pemasukan} Pengeluaran : longint; {Total Pengeluaran} Saldo : longint; {Jumlah Saldo Tersisa} end; {File Simulasi} tabSimulasi = record FS : array [1..10] of simulasi; Neff : integer; end; var Btidur : boolean; {Boleh tidur atau tidak} v : boolean; {Validasi} JmlI : integer; {Jumlah item di inventori} JmlU : integer; {Jumlah Upgrade Inventori dilakukan} Kistirahat : integer; {Kesempatan istirahat tersisa} Kmakan : integer; {Kesempatan makan tersisa} TbahanMentah : tabBahanMentah; TbahanOlahan : tabBahanOlahan; TinventoriBahanMentah : fileInventoriBahanMentah; TinventoriBahanOlahan : fileInventoriBahanOlahan; Tresep : tabResep; Tsimulasi : tabSimulasi; {Implementation} implementation end.
unit uCommon; interface uses SysUtils, Classes, IniFiles, uGlobal, Rtti, uSQLHelper, uLogger, ADODB, System.JSON, DateUtils, syncobjs, System.IOUtils, idFtp, idHttp, idFtpCommon, Data.DB, System.Generics.Collections, IdGlobal; type TCommon = Class private class function ReadConfig(): Boolean; class function FtpGetFile(AHost, AUser, APwd, ASourceFile, ADestFile: string; APort: Integer; RetrieveTime: Integer = 3): Boolean; class function FtpPutFile(AHost, AUser, Apw, ASourceFile, ADestFile: string; APort: Integer): Boolean; static; public class procedure ProgramInit; class procedure ProgramDestroy; class function DownloadPic(url, fileName: String): Boolean; class function UploadPic(SourceFile, DestFile: String): Boolean; end; procedure SQLError(const SQL, Description: string); implementation class function TCommon.ReadConfig(): Boolean; begin Result := True; with TIniFile.Create(ExtractFilePath(Paramstr(0)) + 'Config.ini') do begin gDBConfig.DBServer := ReadString('DB', 'Server', '.'); gDBConfig.DBPort := ReadInteger('DB', 'Port', 1043); gDBConfig.DBUser := ReadString('DB', 'User', 'vioadmin'); gDBConfig.DBPwd := ReadString('DB', 'Pwd', 'lgm1224,./'); gDBConfig.DBName := ReadString('DB', 'Name', 'YjItsDB'); gFtpConfig.Host := ReadString('FTP', 'Host', '.'); gFtpConfig.Port := ReadInteger('FTP', 'Port', 1043); gFtpConfig.User := ReadString('FTP', 'User', 'vioadmin'); gFtpConfig.Password := ReadString('FTP', 'Password', 'lgm1224,./'); gFtpConfig.Passived := ReadString('FTP', 'Passived', '0') = '1'; gFtpConfig.Path := ReadString('FTP', 'Path', ''); gRootUrl := ReadString('Http', 'Url', ''); gHeartbeatUrl := ReadString('Heartbeat', 'Url', 'http://127.0.0.1:20090/'); gHeartbeatInterval := ReadInteger('Heartbeat', 'Interval', 3); Free; end; if gRootUrl <> '' then if copy(gRootUrl, Length(gRootUrl), 1) = '/' then gRootUrl := copy(gRootUrl, 1, Length(gRootUrl) - 1); if gFtpConfig.Path <> '' then if copy(gFtpConfig.Path, Length(gFtpConfig.Path), 1) = '/' then gFtpConfig.Path := copy(gFtpConfig.Path, 1, Length(gFtpConfig.Path) - 1); if copy(gHeartbeatUrl, Length(gHeartbeatUrl), 1) <> '/' then gHeartbeatUrl := gHeartbeatUrl + '/'; end; class function TCommon.UploadPic(SourceFile, DestFile: String): Boolean; begin Result := FtpPutFile(gFtpConfig.Host, gFtpConfig.User, gFtpConfig.Password, SourceFile, gFtpConfig.Path + DestFile, gFtpConfig.Port); end; procedure SQLError(const SQL, Description: string); begin gLogger.Error(Description + #13#10 + SQL); end; class procedure TCommon.ProgramInit; begin TCommon.ReadConfig(); gSQLHelper := TSQLHelper.Create; gSQLHelper.DBServer := gDBConfig.DBServer; gSQLHelper.DBName := gDBConfig.DBName; gSQLHelper.DBUser := gDBConfig.DBUser; gSQLHelper.DBPwd := gDBConfig.DBPwd; gSQLHelper.OnError := SQLError; if not DirectoryExists(ExtractFilePath(Paramstr(0)) + 'log') then ForceDirectories(ExtractFilePath(Paramstr(0)) + 'log'); gLogger := TLogger.Create(ExtractFilePath(Paramstr(0)) + 'log\PicReSave.log'); gTempPath := ExtractFilePath(Paramstr(0)) + 'temppic\'; if not DirectoryExists(gTempPath) then ForceDirectories(gTempPath); end; class function TCommon.DownloadPic(url, fileName: String): Boolean; var ms: TMemoryStream; Host, Port, User, pw, Path, urlcn: string; idHttp: TIdHTTP; idftp1: TIdFTP; begin Result := false; if FileExists(fileName) then deletefile(PWideChar(fileName)); if UpperCase(copy(url, 1, 3)) = 'FTP' then begin try Path := copy(url, pos('@', url) + 1, Length(url) - pos('@', url) + 1); Path := copy(Path, pos('/', Path), Length(Path)); Host := copy(url, pos('@', url) + 1, Length(url) - pos('@', url) + 1); Host := copy(Host, 1, pos('/', Host) - 1); if pos(':', Host) > 0 then begin Port := copy(Host, pos(':', Host) + 1, 100); Host := copy(Host, 1, pos(':', Host) - 1); end else Port := '21'; User := copy(url, 7, Length(url) - 6); User := copy(User, 1, pos(':', User) - 1); pw := copy(url, 7, Length(url) - 6); pw := copy(pw, pos(':', pw) + 1, Length(pw) - pos(':', pw) + 1); pw := copy(pw, 1, pos('@', pw) - 1); Result := FtpGetFile(Host, User, pw, Path, fileName, StrToIntDef(Port, 21)); except FreeAndNil(idftp1); FreeAndNil(ms); end; end else if UpperCase(copy(url, 1, 4)) = 'HTTP' then begin try try ms := TMemoryStream.Create; ms.Position := 0; idHttp := TIdHTTP.Create(nil); idHttp.HandleRedirects := True; // 必须支持重定向否则可能出错 idHttp.ConnectTimeout := 3000; // 超过这个时间则不再访问 idHttp.ReadTimeout := 3000; // urlcn := idHttp.url.URLEncode(url); idHttp.Get(urlcn, ms); if ms.Size > 0 then begin ms.SaveToFile(fileName); Result := True; end; finally FreeAndNil(idHttp); FreeAndNil(ms); end; except end; end; TThread.Sleep(50); end; class function TCommon.FtpGetFile(AHost, AUser, APwd, ASourceFile, ADestFile: string; APort, RetrieveTime: Integer): Boolean; var BytesToTransfer, BytesTransfered: Int64; stream: TStream; i: Integer; ftp: TIdFTP; begin Result := false; ftp := TIdFTP.Create(nil); ftp.ConnectTimeout := 3000; ftp.ReadTimeout := 3000; ftp.Host := AHost; ftp.Username := AUser; ftp.Password := APwd; ftp.Port := APort; ftp.TransferType := ftBinary; i := 0; if FileExists(ADestFile) then begin Sleep(3000); stream := TFileStream.Create(ADestFile, fmOpenWrite) end else stream := TFileStream.Create(ADestFile, fmCreate); while i < RetrieveTime do begin if not ftp.Connected then begin try ftp.Connect; ftp.Get(ASourceFile, stream); Result := True; break; except on e: exception do begin Inc(i); stream.Position := 0; Sleep(5000); continue; end; end; end; end; stream.Free; ftp.Free; Result := FileExists(ADestFile); end; class function TCommon.FtpPutFile(AHost, AUser, Apw, ASourceFile, ADestFile: string; APort: Integer): Boolean; function ChangeDir(ftp: TIdFTP; ADir: string): Boolean; begin Result := false; try ftp.ChangeDir(ADir); Result := True; except on e: exception do begin // if e.message.contains('No such file or directory') then // DONE: 待确认 begin ftp.MakeDir(ADir); ftp.ChangeDir(ADir); Result := True; end; end; end; end; var ftp: TIdFTP; ss: TArray<string>; i, n: Integer; begin // 创建Ftp try ftp := TIdFTP.Create(nil); ftp.ConnectTimeout := 3000; ftp.ReadTimeout := 3000; ftp.Host := AHost; ftp.Port := APort; ftp.Username := AUser; ftp.Password := Apw; ftp.Connect; // ShowMessage(ftplist.port); ftp.TransferType := ftBinary; ftp.IOHandler.DefStringEncoding := IndyTextEncoding(tencoding.Default); ss := ADestFile.Split(['/']); n := Length(ss); for i := 0 to n - 2 do begin ChangeDir(ftp, ss[i]); end; ftp.Passive := True; // 这里分为主动和被动 ftp.Noop; ftp.Put(ASourceFile, ss[n - 1], True); ftp.Free; Result := True; except Result := false; end; end; class procedure TCommon.ProgramDestroy; begin gSQLHelper.Free; gLogger.Free; if DirectoryExists(gTempPath) then TDirectory.Delete(gTempPath, True); end; end.
unit vorbis_parser; (* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) interface {$I 'compiler.inc'} {$I 'version.inc'} (** * @file * A public API for Vorbis parsing * * Determines the duration for each packet. *) //typedef struct AVVorbisParseContext AVVorbisParseContext; type TAVVorbisParseContext = record end; AVVorbisParseContext = TAVVorbisParseContext; PAVVorbisParseContext = ^TAVVorbisParseContext; (** * Allocate and initialize the Vorbis parser using headers in the extradata. *) //AVVorbisParseContext *av_vorbis_parse_init(const uint8_t *extradata, // int extradata_size); function av_vorbis_parse_init(const extradata: PByte; extradata_size: Integer): PAVVorbisParseContext; cdecl; external LIB_LIBAVCODEC; (** * Free the parser and everything associated with it. *) //void av_vorbis_parse_free(AVVorbisParseContext **s); procedure av_vorbis_parse_free(var s: PAVVorbisParseContext); cdecl; external LIB_LIBAVCODEC; //#define VORBIS_FLAG_HEADER 0x00000001 //#define VORBIS_FLAG_COMMENT 0x00000002 //#define VORBIS_FLAG_SETUP 0x00000004 const VORBIS_FLAG_HEADER = $00000001; VORBIS_FLAG_COMMENT = $00000002; VORBIS_FLAG_SETUP = $00000004; (** * Get the duration for a Vorbis packet. * * If @p flags is @c NULL, * special frames are considered invalid. * * @param s Vorbis parser context * @param buf buffer containing a Vorbis frame * @param buf_size size of the buffer * @param flags flags for special frames *) //int av_vorbis_parse_frame_flags(AVVorbisParseContext *s, const uint8_t *buf, // int buf_size, int *flags); function av_vorbis_parse_frame_flags(s: PAVVorbisParseContext; const buf: PByte; buf_size: Integer; var flags: Integer): Integer; cdecl; external LIB_LIBAVCODEC; (** * Get the duration for a Vorbis packet. * * @param s Vorbis parser context * @param buf buffer containing a Vorbis frame * @param buf_size size of the buffer *) //int av_vorbis_parse_frame(AVVorbisParseContext *s, const uint8_t *buf, // int buf_size); function av_vorbis_parse_frame(s: PAVVorbisParseContext; const buf: PByte; buf_size: Integer): Integer; cdecl; external LIB_LIBAVCODEC; //void av_vorbis_parse_reset(AVVorbisParseContext *s); procedure av_vorbis_parse_reset(s: PAVVorbisParseContext); cdecl; external LIB_LIBAVCODEC; implementation end.
unit SEA_CBC; (************************************************************************* DESCRIPTION : SEED CBC functions REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : B.Schneier, Applied Cryptography, 2nd ed., ch. 9.3 Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 07.06.07 W.Ehrhardt Initial version analog TF_CBC 0.11 23.11.08 we Uses BTypes 0.12 26.07.10 we Longint ILen **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2007-2010 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i STD.INC} interface uses BTypes, SEA_Base; {$ifdef CONST} function SEA_CBC_Init(const Key; KeyBits: word; const IV: TSEABlock; var ctx: TSEAContext): integer; {-SEED key expansion, error if invalid key size, save IV} {$ifdef DLL} stdcall; {$endif} procedure SEA_CBC_Reset(const IV: TSEABlock; var ctx: TSEAContext); {-Clears ctx fields bLen and Flag, save IV} {$ifdef DLL} stdcall; {$endif} {$else} function SEA_CBC_Init(var Key; KeyBits: word; var IV: TSEABlock; var ctx: TSEAContext): integer; {-SEED key expansion, error if invalid key size, save IV} procedure SEA_CBC_Reset(var IV: TSEABlock; var ctx: TSEAContext); {-Clears ctx fields bLen and Flag, save IV} {$endif} function SEA_CBC_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEAContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode} {$ifdef DLL} stdcall; {$endif} function SEA_CBC_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEAContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode} {$ifdef DLL} stdcall; {$endif} implementation {---------------------------------------------------------------------------} {$ifdef CONST} function SEA_CBC_Init(const Key; KeyBits: word; const IV: TSEABlock; var ctx: TSEAContext): integer; {$else} function SEA_CBC_Init(var Key; KeyBits: word; var IV: TSEABlock; var ctx: TSEAContext): integer; {$endif} {-SEED key expansion, error if invalid key size, encrypt IV} begin SEA_CBC_Init := SEA_Init(Key, KeyBits, ctx); ctx.IV := IV; end; {---------------------------------------------------------------------------} procedure SEA_CBC_Reset({$ifdef CONST}const {$else} var {$endif} IV: TSEABlock; var ctx: TSEAContext); {-Clears ctx fields bLen and Flag, save IV} begin SEA_Reset(ctx); ctx.IV := IV; end; {---------------------------------------------------------------------------} function SEA_CBC_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEAContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode} var i,n: longint; m: word; begin SEA_CBC_Encrypt := 0; if ILen<0 then ILen := 0; if (ptp=nil) or (ctp=nil) then begin if ILen>0 then begin SEA_CBC_Encrypt := SEA_Err_NIL_Pointer; exit; end; end; {$ifdef BIT16} if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin SEA_CBC_Encrypt := SEA_Err_Invalid_16Bit_Length; exit; end; {$endif} n := ILen div SEABLKSIZE; {Full blocks} m := ILen mod SEABLKSIZE; {Remaining bytes in short block} if m<>0 then begin if n=0 then begin SEA_CBC_Encrypt := SEA_Err_Invalid_Length; exit; end; dec(n); {CTS: special treatment of last TWO blocks} end; {Short block must be last, no more processing allowed} if ctx.Flag and 1 <> 0 then begin SEA_CBC_Encrypt := SEA_Err_Data_After_Short_Block; exit; end; with ctx do begin for i:=1 to n do begin {ct[i] = encr(ct[i-1] xor pt[i])} SEA_xorblock(PSEABlock(ptp)^, IV, IV); SEA_Encrypt(ctx, IV, IV); PSEABlock(ctp)^ := IV; inc(Ptr2Inc(ptp),SEABLKSIZE); inc(Ptr2Inc(ctp),SEABLKSIZE); end; if m<>0 then begin {Cipher text stealing} SEA_xorblock(PSEABlock(ptp)^, IV, IV); SEA_Encrypt(ctx, IV, IV); buf := IV; inc(Ptr2Inc(ptp),SEABLKSIZE); for i:=0 to m-1 do IV[i] := IV[i] xor PSEABlock(ptp)^[i]; SEA_Encrypt(ctx, IV, PSEABlock(ctp)^); inc(Ptr2Inc(ctp),SEABLKSIZE); move(buf,PSEABlock(ctp)^,m); {Set short block flag} Flag := Flag or 1; end; end; end; {---------------------------------------------------------------------------} function SEA_CBC_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEAContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode} var i,n: longint; m: word; tmp: TSEABlock; begin SEA_CBC_Decrypt := 0; if ILen<0 then ILen := 0; if (ptp=nil) or (ctp=nil) then begin if ILen>0 then begin SEA_CBC_Decrypt := SEA_Err_NIL_Pointer; exit; end; end; {$ifdef BIT16} if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin SEA_CBC_Decrypt := SEA_Err_Invalid_16Bit_Length; exit; end; {$endif} n := ILen div SEABLKSIZE; {Full blocks} m := ILen mod SEABLKSIZE; {Remaining bytes in short block} if m<>0 then begin if n=0 then begin SEA_CBC_Decrypt := SEA_Err_Invalid_Length; exit; end; dec(n); {CTS: special treatment of last TWO blocks} end; {Short block must be last, no more processing allowed} if ctx.Flag and 1 <> 0 then begin SEA_CBC_Decrypt := SEA_Err_Data_After_Short_Block; exit; end; with ctx do begin for i:=1 to n do begin {pt[i] = decr(ct[i]) xor ct[i-1])} buf := IV; IV := PSEABlock(ctp)^; SEA_Decrypt(ctx, IV, PSEABlock(ptp)^); SEA_xorblock(PSEABlock(ptp)^, buf, PSEABlock(ptp)^); inc(Ptr2Inc(ptp),SEABLKSIZE); inc(Ptr2Inc(ctp),SEABLKSIZE); end; if m<>0 then begin {Cipher text stealing, L=ILen (Schneier's n)} buf := IV; {C(L-2)} SEA_Decrypt(ctx, PSEABlock(ctp)^, IV); inc(Ptr2Inc(ctp),SEABLKSIZE); fillchar(tmp,sizeof(tmp),0); move(PSEABlock(ctp)^,tmp,m); {c[L]|0} SEA_xorblock(tmp,IV,IV); tmp := IV; move(PSEABlock(ctp)^,tmp,m); {c[L]| C'} SEA_Decrypt(ctx,tmp,tmp); SEA_xorblock(tmp, buf, PSEABlock(ptp)^); inc(Ptr2Inc(ptp),SEABLKSIZE); move(IV,PSEABlock(ptp)^,m); {Set short block flag} Flag := Flag or 1; end; end; end; end.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} { *************************************************************************** } { } { Licensees holding a valid Borland No-Nonsense License for this Software may } { use this file in accordance with such license, which appears in the file } { license.txt that came with this Software. } { } { *************************************************************************** } unit Web.WebConst; interface resourcestring sErrorDecodingURLText = 'Error decoding URL style (%%XX) encoded string at position %d'; sInvalidURLEncodedChar = 'Invalid URL encoded character (%s) at position %d'; sInvalidHTMLEncodedChar = 'Invalid HTML encoded character (%s) at position %d'; sInvalidActionRegistration = 'Invalid Action registration'; sDuplicateActionName = 'Duplicate action name'; sFactoryAlreadyRegistered = 'Web Module Factory already registered'; sAppFactoryAlreadyRegistered = 'Web App Module Factory already registered.'; sOnlyOneDispatcher = 'Only one WebDispatcher per form/data module'; sHTTPItemName = 'Name'; sHTTPItemURI = 'PathInfo'; sHTTPItemEnabled = 'Enabled'; sHTTPItemDefault = 'Default'; sHTTPItemProducer = 'Producer'; sResNotFound = 'Resource %s not found'; sTooManyColumns = 'Too many table columns'; sFieldNameColumn = 'Field Name'; sFieldTypeColumn = 'Field Type'; sInvalidWebComponentsRegistration = 'Invalid Web component registration'; sInvalidWebComponentsEnumeration = 'Invalid Web component enumeration'; sInvalidWebParent = 'Operation not supported. %s component does not support IGetWebComponentList'; sVariableIsNotAContainer = 'Variable %s is not a container'; sInternalApplicationError = '<html><body><h1>Internal Application Error</h1>' + sLineBreak + '<p>%0:s' + sLineBreak + '<p><hr width="100%%"><i>%1:s</i></body></html>'; sInvalidParent = 'Invalid parent'; sActionDoesNotProvideResponse = 'Action does not provide response'; sActionCantRespondToUnkownHTTPMethod = 'Action can''t respone to unknown HTTP method'; sActionCantRedirectToBlankURL = 'Action can''t redirect to blank URL'; sWebFileExtensionItemExtensions = 'Extensions'; sWebFileExtensionItemMimeType = 'Mime Type'; sDuplicateMimeTypes = 'Duplicate mime types for extension: %s'; sWebFileDirectoryItemMask = 'Directory Mask'; sWebFileDirectoryItemAction = 'Action'; sWebFileExtensionsItemDisplayName = 'Mime type: ''%0:s'', Extensions: ''%1:s'''; sWebDirectoryInclude = 'Include'; sWebDirectoryExclude = 'Exclude'; sWebDirectoryItemDisplayName = 'Action: %0:s, Mask: ''%1:s'''; implementation end.
unit Ths.Erp.Database.Table.SysCity; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table; type TSysCity = class(TTable) private FCityName: TFieldDB; FCarPlateCode: TFieldDB; FCountryID: TFieldDB; protected published constructor Create(OwnerDatabase:TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override; procedure Update(pPermissionControl: Boolean=True); override; function Clone():TTable;override; property CityName: TFieldDB read FCityName write FCityName; property CountryID: TFieldDB read FCountryID write FCountryID; property CarPlateCode: TFieldDB read FCarPlateCode write FCarPlateCode; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton, Ths.Erp.Database.Table.SysCountry; constructor TSysCity.Create(OwnerDatabase:TDatabase); begin inherited Create(OwnerDatabase); TableName := 'sys_city'; SourceCode := '1000'; FCityName := TFieldDB.Create('city_name', ftString, ''); FCountryID := TFieldDB.Create('country_id', ftInteger, 0, 0, True, False); FCountryID.FK.FKTable := TSysCountry.Create(Database); FCountryID.FK.FKCol := TFieldDB.Create(TSysCountry(FCountryID.FK.FKTable).CountryName.FieldName, TSysCountry(FCountryID.FK.FKTable).CountryName.FieldType, ''); FCarPlateCode := TFieldDB.Create('car_plate_code', ftInteger, 0); end; procedure TSysCity.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FCityName.FieldName, TableName + '.' + FCarPlateCode.FieldName, TableName + '.' + FCountryID.FieldName, ColumnFromIDCol(FCountryID.FK.FKCol.FieldName, FCountryID.FK.FKTable.TableName, FCountryID.FieldName, FCountryID.FK.FKCol.FieldName, TableName) ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FCityName.FieldName).DisplayLabel := 'City Name'; Self.DataSource.DataSet.FindField(FCarPlateCode.FieldName).DisplayLabel := 'Car Plate Code'; Self.DataSource.DataSet.FindField(FCountryID.FieldName).DisplayLabel := 'Country ID'; Self.DataSource.DataSet.FindField(FCountryID.FK.FKCol.FieldName).DisplayLabel := 'Country Name'; end; end; end; procedure TSysCity.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FCityName.FieldName, TableName + '.' + FCarPlateCode.FieldName, TableName + '.' + FCountryID.FieldName, ColumnFromIDCol(FCountryID.FK.FKCol.FieldName, FCountryID.FK.FKTable.TableName, FCountryID.FieldName, FCountryID.FK.FKCol.FieldName, TableName) ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Id.FieldName).DataType, FieldByName(Id.FieldName).Value); FCityName.Value := FormatedVariantVal(FieldByName(FCityName.FieldName).DataType, FieldByName(FCityName.FieldName).Value); FCarPlateCode.Value := FormatedVariantVal(FieldByName(FCarPlateCode.FieldName).DataType, FieldByName(FCarPlateCode.FieldName).Value); FCountryID.Value := FormatedVariantVal(FieldByName(FCountryID.FieldName).DataType, FieldByName(FCountryID.FieldName).Value); FCountryID.FK.FKCol.Value := FormatedVariantVal(FieldByName(FCountryID.FK.FKCol.FieldName).DataType, FieldByName(FCountryID.FK.FKCol.FieldName).Value); List.Add(Self.Clone()); Next; end; EmptyDataSet; Close; end; end; end; procedure TSysCity.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FCityName.FieldName, FCarPlateCode.FieldName, FCountryID.FieldName ]); NewParamForQuery(QueryOfInsert, FCityName); NewParamForQuery(QueryOfInsert, FCarPlateCode); NewParamForQuery(QueryOfInsert, FCountryID); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.notify; end; end; procedure TSysCity.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FCityName.FieldName, FCarPlateCode.FieldName, FCountryID.FieldName ]); NewParamForQuery(QueryOfUpdate, FCityName); NewParamForQuery(QueryOfUpdate, FCarPlateCode); NewParamForQuery(QueryOfUpdate, FCountryID); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.notify; end; end; function TSysCity.Clone():TTable; begin Result := TSysCity.Create(Database); Self.Id.Clone(TSysCity(Result).Id); FCityName.Clone(TSysCity(Result).FCityName); FCarPlateCode.Clone(TSysCity(Result).FCarPlateCode); FCountryID.Clone(TSysCity(Result).FCountryID); end; end.
{ String Matching - First Match K.M.P. Algorithm O(N) Input: S: Haystack string Q: Needle string SL, QL: The length of two strings above Output: Return Value: Position of first match of Q in S, 0 = Not Found Reference: Creative, p154 By Ali } program StringMatch; const MaxL = 1000 + 1; var S, Q: array[1 .. MaxL] of Char; SL, QL: Integer; Next: array[1 .. MaxL] of Integer; procedure ComputeNext; var i, j: Integer; begin Next[1] := -1; Next[2] := 0; for i := 3 to QL do begin j := Next[i - 1] + 1; while (j > 0) and (Q[i - 1] <> Q[j]) do j := Next[j] + 1; Next[i] := j; end; end; function KMP: Integer; var i, j, Start: Integer; begin ComputeNext; j := 1; i := 1; Start := 0; while (i <= SL) and (Start = 0) do begin if S[i] = Q[j] then begin Inc(i); Inc(j); end else begin j := Next[j] + 1; if j = 0 then begin j := 1; Inc(i); end; end; if j = QL + 1 then Start := i - QL; end; KMP := Start; end; begin Writeln(KMP); end.
{*********************************************} { TeeChart Delphi Component Library } { Custom Axis Drawing Demo } { Copyright (c) 1995-1996 by David Berneda } { All rights reserved } {*********************************************} unit Mulaxis; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Teengine, Chart, Series, Buttons, TeeProcs; type TCustomAxisForm = class(TForm) Chart1: TChart; LineSeries1: TLineSeries; Panel1: TPanel; CheckBox1: TCheckBox; Timer1: TTimer; BitBtn1: TBitBtn; CheckBox2: TCheckBox; PointSeries1: TPointSeries; FastLineSeries1: TFastLineSeries; DrawGrid: TCheckBox; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure LineSeries1AfterDrawValues(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure CheckBox2Click(Sender: TObject); procedure DrawGridClick(Sender: TObject); private { Private declarations } public { Public declarations } XPercent,YPercent:Integer; end; implementation {$R *.DFM} procedure TCustomAxisForm.FormCreate(Sender: TObject); Procedure CreateRandomPoints(Series:TChartSeries); var t,Old:Longint; begin With Series do begin Clear; Old:=Longint(Random(1000)); for t:=1 to 100 do begin Inc(Old,Longint(Random(20))-10); Add(Old,'',clTeeColor); end; end; end; begin XPercent:=50; YPercent:=50; Randomize; CreateRandomPoints(LineSeries1); CreateRandomPoints(PointSeries1); CreateRandomPoints(FastLineSeries1); end; procedure TCustomAxisForm.LineSeries1AfterDrawValues(Sender: TObject); var posaxis:longint; begin With Chart1 do begin { Calculate axis position and draw... } PosAxis:=ChartRect.Left+Trunc(ChartWidth*YPercent/100.0); LeftAxis.CustomDraw(posaxis-10,posaxis-40,posaxis,DrawGrid.Checked); PosAxis:=ChartRect.Left+Trunc(ChartWidth*(100.0-YPercent)/100.0); LeftAxis.CustomDraw(posaxis-10,posaxis-40,posaxis,DrawGrid.Checked); PosAxis:=ChartRect.Top+Trunc(ChartHeight*XPercent/100.0); BottomAxis.CustomDraw(posaxis+10,posaxis+40,posaxis,DrawGrid.Checked); PosAxis:=ChartRect.Top+Trunc(ChartHeight*(100.0-XPercent)/100.0); BottomAxis.CustomDraw(posaxis+10,posaxis+40,posaxis,DrawGrid.Checked); end; end; procedure TCustomAxisForm.CheckBox1Click(Sender: TObject); begin Chart1.AxisVisible:=not CheckBox1.Checked; Timer1.Enabled:=CheckBox1.Checked; end; procedure TCustomAxisForm.Timer1Timer(Sender: TObject); begin if XPercent<95 then Inc(XPercent,5) else XPercent:=5; if YPercent<97 then Inc(YPercent,3) else YPercent:=3; Chart1.Repaint; end; procedure TCustomAxisForm.CheckBox2Click(Sender: TObject); begin Chart1.LeftAxis.Inverted:=CheckBox2.Checked; Chart1.BottomAxis.Inverted:=CheckBox2.Checked; end; procedure TCustomAxisForm.DrawGridClick(Sender: TObject); begin Chart1.Repaint; end; end.
unit SourceNode; interface uses SourceLocation, SysUtils, StrUtils, Classes; type TSourceNodeKind = class public Kind: String; constructor Create(const Kind_: String); end; TSourceNode = class public Parent: TSourceNode; Previous: TSourceNode; Next: TSourceNode; FirstChild: TSourceNode; LastChild: TSourceNode; // SourceFile: String; Position: TLocation; Data: String; Kind: TSourceNodeKind; procedure FreeChildren; procedure Unhook; procedure AttachAsChildOf(Node: TSourceNode); procedure AttachNextTo(Node: TSourceNode); procedure WriteTo(Out: TStrings); end; implementation constructor TSourceNodeKind.Create(const Kind_: String); begin Kind := Kind_; end; procedure TSourceNode.FreeChildren; var Node: TSourceNode; begin while FirstChild <> nil do begin Node := FirstChild; Node.FreeChildren; FirstChild := Node.Next; if FirstChild <> nil then FirstChild.Previous := nil; Node.Free; end; LastChild := nil; end; procedure TSourceNode.WriteTo(Out: TStrings); var Node: TSourceNode; Str: String; begin Node := Parent; while Node <> nil do begin Node := Node.Parent; Str := Str + '-'; end; Out.Append(Str+Kind.Kind + ':' + Data); Node := FirstChild; while Node <> nil do begin Node.WriteTo(Out); Node := Node.Next; end; end; procedure TSourceNode.Unhook; begin FreeChildren; if Parent <> nil then begin if Parent.FirstChild = self then Parent.FirstChild := self.Next; if Parent.LastChild = self then Parent.LastChild := self.Previous; Parent := nil; end; if Next <> nil then Next.Previous := Previous; if Previous <> nil then Previous.Next := Next; Next := nil; Previous := nil; end; procedure TSourceNode.AttachAsChildOf(Node: TSourceNode); begin if Parent <> nil then begin if Parent.FirstChild = self then Parent.FirstChild := self.Next; if Parent.LastChild = self then Parent.LastChild := self.Previous; Parent := nil; end; if Next <> nil then Next.Previous := Previous; if Previous <> nil then Previous.Next := Next; Next := nil; Previous := nil; Previous := Node.LastChild; if Previous <> nil then Previous.Next := Self; Node.LastChild := Self; if Node.FirstChild = nil then Node.FirstChild := Self; Parent := Node; end; procedure TSourceNode.AttachNextTo(Node: TSourceNode); begin if Parent <> nil then begin if Parent.FirstChild = self then Parent.FirstChild := self.Next; if Parent.LastChild = self then Parent.LastChild := self.Previous; Parent := nil; end; if Next <> nil then Next.Previous := Previous; if Previous <> nil then Previous.Next := Next; Next := nil; Previous := nil; Previous := Node; Next := Node.Next; Parent := Node.Parent; if Next <> nil then Next.Previous := Self; Previous.Next := Self; if Parent.LastChild = Node then Parent.LastChild := Self; end; end.
unit copy_str_1; interface implementation var S1, S2: string; procedure Test; begin S1 := 'ABCD'; S2 := Copy(S1, 2, 2); end; initialization Test(); finalization Assert(S2 = 'CD'); end.
{$I Definition.Inc} unit PythonGUIInputOutput; (**************************************************************************) (* *) (* Module: Unit 'PythonGUIInputOutput' Copyright (c) 1997 *) (* *) (* Dr. Dietmar Budelsky *) (* dbudelsky@web.de *) (* Germany *) (* *) (* Morgan Martinet *) (* 4723 rue Brebeuf *) (* H2J 3L2 MONTREAL (QC) *) (* CANADA *) (* e-mail: p4d@mmm-experts.com *) (* *) (* look our page at: http://mmm-experts.com/ *) (**************************************************************************) (* Functionality: Delphi Components that provide an interface to the *) (* Python language (see python.txt for more infos on *) (* Python itself). *) (* *) (**************************************************************************) (* Contributors: *) (* Mark Watts(mark_watts@hotmail.com) *) (* Michiel du Toit (micdutoit@hsbfn.com) *) (**************************************************************************) (* This source code is distributed with no WARRANTY, for no reason or use.*) (* Everyone is allowed to use and change this code free for his own tasks *) (* and projects, as long as this header and its copyright text is intact. *) (* For changed versions of this code, which are public distributed the *) (* following additional conditions have to be fullfilled: *) (* 1) The header has to contain a comment on the change and the author of *) (* it. *) (* 2) A copy of the changed source has to be sent to the above E-Mail *) (* address or my then valid address, if this is possible to the *) (* author. *) (* The second condition has the target to maintain an up to date central *) (* version of the component. If this condition is not acceptable for *) (* confidential or legal reasons, everyone is free to derive a component *) (* or to generate a diff file to my or other original sources. *) (* Dr. Dietmar Budelsky, 1997-11-17 *) (**************************************************************************) interface uses {$IFDEF MSWINDOWS} Windows, Messages, {$ENDIF} SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, PythonEngine; {$IFDEF MSWINDOWS} const WM_WriteOutput = WM_USER + 1; {$ENDIF} type {$IF not Defined(FPC) and (CompilerVersion >= 23)} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$IFEND} TPythonGUIInputOutput = class(TPythonInputOutput) private { Private declarations } FCustomMemo : TCustomMemo; {$IFDEF MSWINDOWS} FWinHandle : HWND; {$ENDIF} protected { Protected declarations } {$IFDEF MSWINDOWS} procedure pyGUIOutputWndProc (var Message: TMessage); {$ENDIF} procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SendData( const Data : AnsiString ); override; function ReceiveData : AnsiString; override; procedure SendUniData( const Data : UnicodeString ); override; function ReceiveUniData : UnicodeString; override; procedure AddPendingWrite; override; procedure WriteOutput; public { Public declarations } constructor Create( AOwner : TComponent ); override; destructor Destroy; override; procedure DisplayString( const str : string ); published { Published declarations } property Output : TCustomMemo read FCustomMemo write FCustomMemo; end; procedure Register; implementation {$IFDEF FPC} {$IFDEF MSWINDOWS} Uses InterfaceBase; {$ENDIF} {$ENDIF} {PROTECTED METHODS} {------------------------------------------------------------------------------} procedure TPythonGUIInputOutput.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then if aComponent = fCustomMemo then fCustomMemo := nil; end; {------------------------------------------------------------------------------} {$IFDEF MSWINDOWS} procedure TPythonGUIInputOutput.pyGUIOutputWndProc(var Message: TMessage); begin case Message.Msg of WM_WriteOutput : WriteOutput; end;{case} end; {$ENDIF} {------------------------------------------------------------------------------} procedure TPythonGUIInputOutput.SendData( const Data : AnsiString ); begin if Assigned(FOnSendData) then inherited else DisplayString( string(Data) ); end; procedure TPythonGUIInputOutput.SendUniData(const Data: UnicodeString); begin if Assigned(FOnSendUniData) then inherited else DisplayString( Data ); end; {------------------------------------------------------------------------------} function TPythonGUIInputOutput.ReceiveData : AnsiString; Var S : string; begin if Assigned( FOnReceiveData ) then Result := inherited ReceiveData else begin InputQuery( 'Query from Python', 'Enter text', S); Result := AnsiString(S); end; end; function TPythonGUIInputOutput.ReceiveUniData: UnicodeString; Var S : string; begin if Assigned( FOnReceiveUniData ) then Result := inherited ReceiveUniData else begin InputQuery( 'Query from Python', 'Enter text', S); Result := S; end; end; {------------------------------------------------------------------------------} procedure TPythonGUIInputOutput.AddPendingWrite; begin {$IFDEF MSWINDOWS} PostMessage( fWinHandle, WM_WriteOutput, 0, 0 ); {$ENDIF} end; {------------------------------------------------------------------------------} procedure TPythonGUIInputOutput.WriteOutput; var S : IOString; begin if FQueue.Count = 0 then Exit; Lock; try while FQueue.Count > 0 do begin S := FQueue.Strings[ 0 ]; FQueue.Delete(0); DisplayString( S ); end; finally Unlock; end; end; {PUBLIC METHODS} {------------------------------------------------------------------------------} constructor TPythonGUIInputOutput.Create( AOwner : TComponent ); begin inherited Create(AOwner); {$IFDEF MSWINDOWS} // Create an internal window for use in delayed writes // This will allow writes from multiple threads to be queue up and // then written out to the associated TCustomMemo by the main UI thread. {$IFDEF FPC} fWinHandle := WidgetSet.AllocateHWnd(pyGUIOutputWndProc); {$ELSE} fWinHandle := Classes.AllocateHWnd(pyGUIOutputWndProc); {$ENDIF} {$ENDIF} UnicodeIO := True; end; {------------------------------------------------------------------------------} destructor TPythonGUIInputOutput.Destroy; begin {$IFDEF MSWINDOWS} // Destroy the internal window used for Delayed write operations {$IFDEF FPC} WidgetSet.DeallocateHWnd(fWinHandle); {$ELSE} Classes.DeallocateHWnd(fWinHandle); {$ENDIF} {$ENDIF} inherited Destroy; end; {------------------------------------------------------------------------------} type TMyCustomMemo = class(TCustomMemo); procedure TPythonGUIInputOutput.DisplayString( const str : string ); begin if Assigned(Output) then begin if TMyCustomMemo(Output).Lines.Count >= MaxLines then TMyCustomMemo(Output).Lines.Delete(0); TMyCustomMemo(Output).Lines.Add(str); {$IFDEF MSWINDOWS} SendMessage( Output.Handle, em_ScrollCaret, 0, 0); //SendMessage( Output.Handle, EM_LINESCROLL, 0, Output.Lines.Count); {$ENDIF} end;{if} end; {------------------------------------------------------------------------------} procedure Register; begin RegisterComponents('Python', [TPythonGUIInputOutput]); end; end.
unit TransparentInput; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types, FMX.Objects, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math, System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, Input, ColorClass; type TTransparentInput = class(TInput) private { Private declarations } protected { Protected declarations } { Events settings } procedure OnEditEnter(Sender: TObject); override; procedure OnEditExit(Sender: TObject); override; procedure SetFText(const Value: String); override; function GetFSelectedColor: TAlphaColor; procedure SetFSelectedColor(const Value: TAlphaColor); procedure HideEffectValidation(); public { Public declarations } constructor Create(AOwner: TComponent); override; function ValidateText(): Boolean; procedure Clear; override; procedure Select(); procedure Deselect(); published { Published declarations } property SelectedColor: TAlphaColor read GetFSelectedColor write SetFSelectedColor; end; procedure Register; implementation procedure Register; begin RegisterComponents('Componentes Customizados', [TTransparentInput]); end; { Protected declarations } { TTransparentAppleEdit } constructor TTransparentInput.Create(AOwner: TComponent); begin inherited; FSelectedTheme := TAlphaColor($C8006CD0); FBackground.Stroke.Kind := TBrushKind.Solid; FBackground.Stroke.Color := FSelectedTheme; FBackground.Stroke.Thickness := 0; end; procedure TTransparentInput.Select; begin FBackground.Stroke.Color := FSelectedTheme; FBackground.AnimateFloat('Stroke.Thickness', 1, 0.2); end; procedure TTransparentInput.Deselect; begin FBackground.AnimateFloat('Stroke.Thickness', 0, 0.2); if FInvalid then ValidateText(); end; procedure TTransparentInput.SetFSelectedColor(const Value: TAlphaColor); begin FSelectedTheme := Value; end; function TTransparentInput.GetFSelectedColor: TAlphaColor; begin Result := FSelectedTheme; end; procedure TTransparentInput.OnEditEnter(Sender: TObject); begin Select; inherited; end; procedure TTransparentInput.OnEditExit(Sender: TObject); begin Deselect; inherited; end; procedure TTransparentInput.SetFText(const Value: String); begin inherited; if not Self.Text.Equals('') then HideEffectValidation(); end; procedure TTransparentInput.Clear; begin inherited; HideEffectValidation(); end; function TTransparentInput.ValidateText: Boolean; begin if not Self.Validate then begin if FTextPromptAnimation then FLabelTextPrompt.AnimateColor('TextSettings.FontColor', SOLID_ERROR_COLOR, 0.25, TAnimationType.InOut, TInterpolationType.Circular); FBackground.Stroke.Color := SOLID_ERROR_COLOR; FBackground.AnimateFloat('Stroke.Thickness', 1, 0.2); end; FInvalid := not Self.Validate; Result := Self.Validate; end; procedure TTransparentInput.HideEffectValidation; begin if FBackground.Stroke.Color = SOLID_ERROR_COLOR then begin if FTextPromptAnimation then FLabelTextPrompt.AnimateColor('TextSettings.FontColor', TAlphaColor($FF999999), 0, TAnimationType.InOut, TInterpolationType.Circular); FBackground.Stroke.Color := FSelectedTheme; FBackground.AnimateFloat('Stroke.Thickness', 0, 0.2); end; end; end.
unit uDomainUpDowns; interface uses {$IF CompilerVersion > 22} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,Forms, Dialogs, StdCtrls, {$IFEND} CNClrLib.Control.EnumTypes, CNClrLib.Control.EventArgs, CNClrLib.Control.Base, CNClrLib.Control.ScrollableControl, CNClrLib.Control.ContainerControl, CNClrLib.Control.UpDownBase, CNClrLib.Control.DomainUpDown; type TForm10 = class(TForm) CnDomainUpDown1: TCnDomainUpDown; CnDomainUpDown2: TCnDomainUpDown; CnDomainUpDown3: TCnDomainUpDown; procedure CnDomainUpDown1DoubleClick(Sender: TObject; E: _EventArgs); procedure CnDomainUpDown1SelectedItemChanged(Sender: TObject; E: _EventArgs); procedure CnDomainUpDown1TextChanged(Sender: TObject; E: _EventArgs); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form10: TForm10; implementation {$R *.dfm} procedure TForm10.CnDomainUpDown1DoubleClick(Sender: TObject; E: _EventArgs); begin TClrMessageBox.Show('OnDoubleClick Event') end; procedure TForm10.CnDomainUpDown1SelectedItemChanged(Sender: TObject; E: _EventArgs); begin TClrMessageBox.Show('OnSelectedItemChanged Event') end; procedure TForm10.CnDomainUpDown1TextChanged(Sender: TObject; E: _EventArgs); begin TClrMessageBox.Show('OnTextChanged Event') end; procedure TForm10.FormCreate(Sender: TObject); begin TClrApplication.VisualStyleState := TVisualStyleState.vssClientAndNonClientAreasEnabled; end; end.
unit uGlobal; interface uses SysUtils, IniFiles, uSQLHelper, uLogger; const cDBUser = 'vioadmin'; cDBPwd = 'lgm1224,./'; cDB = 'YjItsDB'; var gServer: String; gUrlRoot: String; gBakPath: String; gUpdateTime: String; gLogger: TLogger; gSQLHelper: TSQLHelper; implementation procedure ProgramInit; begin with TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Config.ini') do begin gServer:= ReadString('Config', 'Server', '.'); gUrlRoot:= ReadString('Config', 'UrlRoot', ''); gBakPath:= ReadString('Config', 'BakPath', ''); gUpdateTime:= ReadString('Config', 'UpdateTime', ''); Free; end; if copy(gBakPath, Length(gBakPath), 1) <> '\' then gBakPath:= gBakPath + '\'; if copy(gUrlRoot, Length(gUrlRoot), 1) <> '/'then gUrlRoot:= gUrlRoot + '/'; gLogger:= TLogger.Create(ExtractFilePath(ParamStr(0)) + 'LOG\BackupsPic.log'); gSQLHelper:= TSQLHelper.Create; gSQLHelper.DBServer:= gServer; gSQLHelper.DBName:= cDB; gSQLHelper.DBUser:= cDBUser; gSQLHelper.DBPWD:= cDBPwd; end; procedure ProgramDestroy; begin gSQLHelper.Free; gLogger.Free; end; initialization ProgramInit; finalization ProgramDestroy; end.
//*********************************************************************** //CGIMAIL Version 1.0 //Copyright (c) 2001, Stuart King. All rights reserved. //PURPOSE: This program is a Common Gateway Interface (CGI) application // that sends email messages. //*********************************************************************** program cgimail(input, output); const MaxBuffer = 2400; //Size of the buffer used to store the data from GET and POST requests DEFAULT_SENDMAIL = '/usr/lib/sendmail'; //Default fullpathname to the sendmail program DEFAULT_SUCCESS_MESSAGE = '<p>Thank you. Your email message has been sent successfully.</p>'; CONFIG_FILENAME = 'cgimail.cfg'; //name of the configuration file type Buffer = string[MaxBuffer]; var strCGIData : Buffer; //Stores the data from the GET or POST request strFrom, strTo, strSubject, strBody : Buffer; strErrorLink, strSuccessLink : filename; strSuccessMessage : Buffer; SendMail : filename; procedure DisplayError(strMsg : string); begin //DisplayError writeln('ERROR: ', strMsg); halt end; //DisplayError //************************************************************* //PURPOSE: Returns the directory containing the application //NOTES: Used in this particular program to help locate the // configuration file. //************************************************************* function AppDir : filename; var fdir : filename; begin fsplit(paramstr(0), fdir,,); AppDir := fdir end; //***************************************************************** //PURPOSE: Returns an output string (strOut) that is generated // from an input string (strIn), by replacing all // occurrences of one string (strOld) with another // string (strNew). //NOTE: No error checking is done so it is up to the caller to // ensure that the replacing string does not contain the // string being replaced. //***************************************************************** function Replace(strIn : Buffer; strOld, strNew : string) : Buffer; var strOut : Buffer; i : 0..MaxBuffer; begin strOut := strIn; i := 1; repeat i := pos(strOld, strOut, i); if i > 0 then begin delete(strOut, i, length(strOld)); insert(strNew, strOut, i); end until i = 0; Replace := strOut end; (*************************************************************** ** PURPOSE: This procedure converts certain characters that ** have a special meaning in HTML documents to ** their HTML representation. ** The characters converted are < > " *) function EscapeCharacters(str : Buffer) : Buffer; const LessThanChar = '<'; GreaterThanChar = '>'; QuoteChar = '"'; HTMLLessThan = '&lt;'; HTMLGreaterThan = '&gt;'; HTMLQuote = '&quot;'; begin str := Replace(str, LessThanChar, HTMLLessThan); str := Replace(str, GreaterThanChar, HTMLGreaterThan); str := Replace(str, QuoteChar, HTMLQuote); EscapeCharacters := str end; procedure Initialize; begin //Initialize strFrom := ''; strTo := ''; strSubject := ''; strBody := ''; SendMail := DEFAULT_SENDMAIL; strSuccessMessage := DEFAULT_SUCCESS_MESSAGE; strErrorLink := ''; strSuccessLink := ''; end; //Initialize //**************************************************************** //PURPOSE: Looks for the configuration file in the application // directory, and if found prcesses the commands inside. //**************************************************************** procedure ReadConfigFile; var ConfigFile : filename; f : text; line : string; //********************************************************** //PURPOSE: Processes a line in the configuration file //NOTE: The line is assumed to look like // command=value // where "command" is a valid configuration command // and "value" is a valid configuration value // for example // // sendmail=/usr/lib/sendmail // //********************************************************** procedure ProcessConfigLine(line : string); const SENDMAIL_COMMAND = 'sendmail'; TO_COMMAND = 'to'; SUBJECT_COMMAND = 'subject'; FROM_COMMAND = 'from'; BODY_COMMAND = 'body'; ERROR_LINK_COMMAND = 'error_link'; SUCCESS_LINK_COMMAND = 'success_link'; SUCCESS_MESSAGE_COMMAND = 'success_message'; var command, value : string; begin //ProcessConfigLine if CountWords(line, '=') = 2 then begin command := lowercase(trim(CopyWord(line, 1, '='))); value := trim(CopyWord(line, 2, '=')); if command = SENDMAIL_COMMAND then SendMail := value else if command = TO_COMMAND then strTo := value else if command = SUBJECT_COMMAND then strSubject := value else if command = FROM_COMMAND then strFrom := value else if command = BODY_COMMAND then strBody := value else if command = ERROR_LINK_COMMAND then strErrorLink := value else if command = SUCCESS_LINK_COMMAND then strSuccessLink := value else if command = SUCCESS_MESSAGE_COMMAND then strSuccessMessage := value end; end; //ProcessConfigLine begin //ReadConfigFile ConfigFile := AppDir; //Look for configuration file in the Application directory if ConfigFile <> '' then begin //Ensure that the Application directory ends with a directory seperator if ConfigFile[length(ConfigFile)] <> dirsep then ConfigFile := ConfigFile + dirsep; //Append the name of the configuration file to the application directory ConfigFile := ConfigFile + CONFIG_FILENAME; end else //this shouldn't happen but just in case look for configuration file in current directory. ConfigFile := CONFIG_FILENAME; traperrors(false); //Turn off error trapping reset(f, ConfigFile); //Attempt to open configuaration file traperrors(true); //Turn on error trapping if getlasterror = 0 then //if the configuration file was successfully opened read it and process it begin while not eof(f) do begin readln(f, line); ProcessConfigLine(line); end; close(f); end; end; //ReadConfigFile //*************************************************************** //PURPOSE: Checks whether the input string (strAddress) is a // valid email address. //NOTE: This function does not perform a bullet-proof check // for the validity of the email address. It just ensures // that the address has at least one '@' and the first '@' is // not at the beginning of the address. This function also // checks to make sure that a '.' follows somewhere after the '@'. //*************************************************************** function IsValidEmailAddress(strAddress : Buffer) : boolean; var i : integer; begin //IsValidEmailAddress i := pos('@', strAddress); if (i > 1) and (pos('.', strAddress, i+1) > 0) then IsValidEmailAddress := true else IsValidEmailAddress := false; end; //IsValidEmailAddress //********************************************************************* //PURPOSE: Sends an email message using "sendmail" or the CDONTS object //********************************************************************* procedure SendEmail(strFrom, strTo, strSubject, strBody : Buffer); //******************************************************** //PURPOSE: Sends and email message using "sendmail" //NOTE: //The built-in procedure "popen" is used to execute "sendmail" and // open a pipe to the "sendmail" process. The email message is then // written to this pipe and the "sendmail" process reads the email // message and sends it to the recipients. //The "-t" option is passed to "sendmail" to cause it to examine the // email message for To:, Cc:, and Bcc: headers which it will then // use to find out who are the intended recipients of the message. //The configuration file (cgimail.cfg) can be used to specify where // "sendmail" is located or even that another program be used // instead of "sendmail". See the constant DEFAULT_SENDMAIL at the // top of this program for the default location of "sendmail". //If "sendmail" is not in the default location then use a command like // // sendmail=pathname // // in the configuration file to specify the correct location. //You can also use the "sendmail" command in the configuration file // to specify that a program other than "sendmail" be used // to send email (under Unix-like operating systems), as long // as the substitute email program has a similar interface to // "sendmail", (i.e. it can take the -t option, and it will examine // the email message for (at minimum) a To: header). //The configuration file (cgimail.cfg) should be placed in the same // directory as this program. //******************************************************** procedure SendEmailWithSendMail; const SENDMAIL_OPTIONS = '-t'; //Make sendmail examine To:, Cc:, and Bcc: in message var pipe : text; begin //SendEmailWithSendMail popen(pipe, SendMail + ' ' + SENDMAIL_OPTIONS, writemode); writeln(pipe, 'To: ', strTo); if strFrom <> '' then writeln(pipe, 'From: ', strFrom); if strSubject <> '' then writeln(pipe, 'Subject: ', strSubject); writeln(pipe); if strBody <> '' then writeln(pipe, strBody); writeln(pipe, '.'); close(pipe); end; //SendEmailWithSendMail //*************************************************************** //PURPOSE: Sends and email message using the CDONTS components //NOTE: The CDONTS components were created by Microsoft to // simplify the process of sending email. These components // are distributed with IIS so if IIS is your webserver // you can probably use these components. //*************************************************************** procedure SendEmailWithCDONTS; const NORMAL = 1; //LOW = 0; //HIGH = 2; var objMail : object; iLastError : integer; strError : string; begin //SendEmailWithCDONTS traperrors(false); objMail := CreateObject('CDONTS.NewMail'); traperrors(true); iLastError := getlasterror; if iLastError <> 0 then begin str(iLastError:1, strError); strError := strError+' ' + errors[1].description; DisplayError('#'+strError); end; objMail.Send(strFrom , strTo, strSubject, strBody, NORMAL); dispose(objMail); end; //SendEmailWithCDONTS begin //SendEmail //If this application is running under a Unix-Like platform then // use sendmail to send email message //If not use the CDONTS object if UnixPlatform then SendEmailWithSendMail else SendEmailWithCDONTS end; //SendEmail //******************************************************************** //PURPOSE: Reads the CGI request information and stores it in a buffer //NOTE: The environment variable "REQUEST_METHOD" is used to determine // whether a GET or POST request was made, and calls the // appropriate procedure to read the data. //This procedure is generic and can probably be used in almost any //CGI application. The only thing likely to change is the size of the // buffer used to store the CGI request information. //******************************************************************** procedure GetCGIData(var strData : Buffer); var RequestMethod : string; procedure GetRequest(var strData : Buffer); begin // GetRequest strData := getenv('QUERY_STRING') end; // GetRequest procedure PostRequest(var strData : Buffer); var len, i : 0..maxint; err : integer; ContentLength : string; c : char; begin // PostRequest strData := ''; ContentLength := getenv('CONTENT_LENGTH'); if ContentLength <> '' then val(ContentLength, len, err) else len := 0; if err > 0 then len := 0; if len <= MaxBuffer then for i := 1 to len do begin read(c); strData := strData + c end end; // PostRequest begin // GetCGIData RequestMethod := getenv('REQUEST_METHOD'); if RequestMethod = 'GET' then GetRequest(strData) else PostRequest(strData); end; // GetCGIData //******************************************************************** //PURPOSE: Processes the CGI request information that was earlier // stored in the buffer. This involves seperating the information // in the buffer into name/value pairs and then decoding them. // CGI request information is passed to applications in the following // form: // name=value // called name/value pairs. Each name/value pair is encoded, and then // joined together in one big block of data seperated by '&'. // So to process the name/value pairs the process is reversed. // The individual name/value pairs are seperated from the block and // then decoded, then the "name" part is seperated from the "value" // part, and finally the procedure ProcessNameValuePair is called to // do something with the the name/value pair. //Most of this procedure is generic and can be used in almost any // CGI application, the only part of this procedure that is // specific to this application is what goes on inside // "ProcessNameValuePair". In this case some values get assigned to // some global variables. //******************************************************************** procedure ProcessCGIData(var strData : Buffer); var i, num, p : integer; EncodedVariable, DecodedVariable, name, value : Buffer; procedure ProcessNameValuePair; begin //ProcessNameValuePair if name = 'to' then strTo := value else if name = 'subject' then strSubject := value else if name = 'from' then strFrom := value else if name = 'body' then strBody := value else if name = 'error_link' then strErrorLink := value else if name = 'success_link' then strSuccessLink := value else if name = 'success_message' then strSuccessMessage := value end; //ProcessNameValuePair begin // ProcessCGIData num := CountWords(strData, '&'); for i := 1 to num do begin EncodedVariable := CopyWord(strData, i, '&'); DecodedVariable := URLDecode(EncodedVariable); p := pos('=', DecodedVariable); if p > 0 then begin name := lowercase(trim(copy(DecodedVariable, 1, p-1))); value := trim(copy(DecodedVariable, p+1)); ProcessNameValuePair; end end end; // ProcessCGIData //******************************************************* //PURPOSE: Writes the HTTP response header //******************************************************* procedure WriteResponseHeader; begin //WriteResponseHeader writeln('Content-type: text/html'); writeln; end; //WriteResponseHeader //************************************************************** //PURPOSE: Generates the HTML response and possibly send // the email message. //************************************************************** procedure GenerateResponse; var i : integer; InvalidTo : boolean; procedure GenerateHTMLHeader; begin writeln('<html>'); writeln('<head>'); writeln('<title>CGIMail 1.0</title>'); writeln('<meta name="GENERATOR" content="CGIMail 1.0">'); writeln('<meta name="COPYRIGHT" content="Copyright (c) 2001, Stuart King.">'); writeln('</head>'); end; procedure GenerateHTMLFooter; begin writeln('<hr>'); writeln('<p>'); writeln('CGIMail 1.0 Copyright &copy; 2001, Stuart King<br>'); writeln('Home page <a href="http://www.irietools.com/">www.irietools.com</a>'); writeln('</p>'); writeln('</body>'); writeln('</html>'); end; //******************************************************************* //PURPOSE: Generates the response when the email recipient (in strTo) // is not specified. //******************************************************************* procedure GenerateNoTo; begin GenerateHTMLHeader; writeln('<body>'); writeln('<h1>'); writeln('Email Address (Recipient) Required'); writeln('</h1>'); writeln('<p>The address of the email recipient was not specified.</p>'); if strErrorLink <> '' then writeln('<p>Please click <a href="', EscapeCharacters(strErrorLink), '">here</a> to continue.</p>'); GenerateHTMLFooter; end; //******************************************************************* //PURPOSE: Generates the response when the email recipient (in strTo) // is invalid. //******************************************************************* procedure GenerateInvalidTo(strTo : string); begin GenerateHTMLHeader; writeln('<body>'); writeln('<h1>'); writeln('Invalid Email Address (Recipient)'); writeln('</h1>'); writeln('<p>The following email address (', EscapeCharacters(strTo), ') is invalid.</p>'); if strErrorLink <> '' then writeln('<p>Please click <a href="', EscapeCharacters(strErrorLink), '">here</a> to continue.</p>'); GenerateHTMLFooter; end; //******************************************************************* //PURPOSE: Generates the response when the email sender (in strFrom) // is invalid. //******************************************************************* procedure GenerateInvalidFrom; begin GenerateHTMLHeader; writeln('<body>'); writeln('<h1>'); writeln('Invalid Email Address (Sender)'); writeln('</h1>'); writeln('<p>The following email address (', EscapeCharacters(strFrom), ') is invalid.</p>'); if strErrorLink <> '' then writeln('<p>Please click <a href="', EscapeCharacters(strErrorLink), '">here</a> to continue.</p>'); GenerateHTMLFooter; end; //******************************************************************* //PURPOSE: Generates the response when everything is OK and the email // message has been sent. //******************************************************************* procedure GenerateEmailSent; begin GenerateHTMLHeader; writeln('<body>'); writeln(strSuccessMessage); if strSuccessLink <> '' then writeln('<p>Please click <a href="', EscapeCharacters(strSuccessLink), '">here</a> to continue.</p>'); GenerateHTMLFooter; end; begin // GenerateResponse if strTo = '' then GenerateNoTo else begin InvalidTo := false; //Check each recipient address, if an invalid recipient is found // generate the invalid recipient reponse and set the InValidTo // flag so that no other responses get generated. for i := 1 to CountWords(strTo, ',') do if (not InvalidTo) and (not IsValidEmailAddress(CopyWord(strTo, i, ','))) then begin GenerateInvalidTo(CopyWord(strTo, i, ',')); InvalidTo := true end; //If thr InvalidTo flag has not been set then check the // sender's email address if it was specified. if not InvalidTo then if (strFrom <> '') and (not IsValidEmailAddress(strFrom)) then GenerateInvalidFrom else begin //Everything is OK so send the email and generate //the email send response. SendEmail(strFrom, strTo, strSubject, strBody); GenerateEmailSent end end; end; // GenerateResponse begin WriteResponseHeader; Initialize; ReadConfigFile; GetCGIData(strCGIData); ProcessCGIData(strCGIData); GenerateResponse; end.
{----------------------------------------------------------------------------} { Written by Nguyen Le Quang Duy } { Nguyen Quang Dieu High School, An Giang } {----------------------------------------------------------------------------} Program V11WATER; Uses Math; Var n :LongInt; A,L,R :Array[0..100000] of LongInt; sum :Int64; procedure Enter; var i :LongInt; begin ReadLn(n); FillChar(A,SizeOf(A),0); FillChar(L,SizeOf(L),0); FillChar(R,SizeOf(R),0); for i:=1 to n do begin Read(A[i]); L[i]:=Max(L[i-1],A[i-1]); end; for i:=n downto 1 do R[i]:=Max(R[i+1],A[i+1]); sum:=0; end; procedure Optimize; var i,minV :LongInt; begin for i:=1 to n do begin minV:=Min(L[i],R[i]); if (minV>A[i]) then sum:=sum+minV-A[i]; end; end; Begin Assign(Input,''); Reset(Input); Assign(Output,''); Rewrite(Output); Enter; Optimize; Write(sum); Close(Input); Close(Output); End.
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { } { Copyright (c) 1997, 2001 Borland Software Corporation } { } { Licensees holding a valid Borland No-Nonsense License for this Software may } { use this file in accordance with such license, which appears in the file } { license.txt that came with this Software. } { } { *************************************************************************** } unit QDBConsts; interface resourcestring { DBCtrls } SFirstRecord = 'First record'; SPriorRecord = 'Prior record'; SNextRecord = 'Next record'; SLastRecord = 'Last record'; SInsertRecord = 'Insert record'; SDeleteRecord = 'Delete record'; SEditRecord = 'Edit record'; SPostEdit = 'Post edit'; SCancelEdit = 'Cancel edit'; SConfirmCaption = 'Confirm'; SRefreshRecord = 'Refresh data'; SDeleteRecordQuestion = 'Delete record?'; SDeleteMultipleRecordsQuestion = 'Delete all selected records?'; SDataSourceFixed = 'Operation not allowed in a DBCtrlGrid'; SNotReplicatable = 'Control cannot be used in a DBCtrlGrid'; SPropDefByLookup = 'Property already defined by lookup field'; STooManyColumns = 'Grid requested to display more than 256 columns'; { DBLogDlg } SRemoteLogin = 'Remote Login'; implementation end.
unit URTTI; {$mode objfpc}{$H+} interface uses TypInfo, UEdits, Controls, Dialogs, UFigures, Classes, UEditsStatic, sysutils; type TObjectArray = array of TObject; procedure EqualClassArray(AFigure1, AFigure2: TFigure); procedure EqualClassProperties(AClass1, AClass2: TObject); procedure GetComponentProperties(Instance: TObjectArray; Panel: TWinControl); overload; procedure GetComponentProperties(Instance: TObject; Panel: TWinControl); overload; function CopyObject(AObject: TObject): TObject; function CopyFigure(AFigure: TFigure): TFigure; implementation function CopyFigure(AFigure: TFigure): TFigure; begin Result := TFigure(AFigure.ClassType.Create); EqualClassProperties(Result, AFigure); EqualClassArray(Result, AFigure); end; function CopyObject(AObject: TObject): TObject; begin Result := AObject.ClassType.Create; EqualClassProperties(Result, AObject); end; procedure EqualClassArray(AFigure1, AFigure2: TFigure); var I: Integer; begin SetLength(AFigure1.PointsArray, Length(AFigure2.PointsArray)); for I := 0 to High(AFigure1.PointsArray) do AFigure1.PointsArray[I] := AFigure2.PointsArray[I]; end; procedure EqualClassProperties(AClass1, AClass2: TObject); var I, Count: Integer; PropList: PPropList; PropInfo: PPropInfo; begin Count := GetTypeData(AClass1.ClassInfo)^.PropCount; if Count > 0 then begin GetMem(PropList, SizeOf(PPropInfo) * Count); try GetPropInfos(AClass1.ClassInfo, PropList); for I := 0 to Count - 1 do begin PropInfo := PropList^[I]; if PropInfo^.PropType^.Kind <> tkDynArray then SetPropValue(AClass1, PropInfo^.Name, GetPropValue(AClass2, PropInfo^.Name)); end; finally FreeMem(PropList, SizeOf(Pointer) * Count); end; end; end; procedure GetComponentProperties(Instance: TObjectArray; Panel: TWinControl); type TPropListRec = record Count: Integer; PropList: PPropList; end; TPointerRec = record Kur: PointerArray; Name: String; end; var PropList_Array: array of TPropListRec; procedure FreeAllMem; var I: Integer; begin for I := 0 to High(PropList_Array) do FreeMem(PropList_Array[I].PropList); end; var NewEdit: TMainEditClass; NewEditNew: TMainEditStaticClass; MUFinal: array of TPointerRec; CurrentPointerArray: TPointerRec; Height: Integer; Flag: Boolean; I, Count, J, L: Integer; begin ControlEdits.Free_All_Edit; ControlEditsNew.Free_All_Edit; Height := High(Instance); if Height = -1 then exit; for I := 0 to Height do begin Count := GetTypeData(Instance[I].ClassInfo)^.PropCount; if Count = 0 then begin FreeAllMem; Exit; end; SetLength(PropList_Array, Length(PropList_Array) + 1); GetMem(PropList_Array[High(PropList_Array)].PropList, SizeOf(PPropInfo) * Count); GetPropInfos(Instance[I].ClassInfo, PropList_Array[High(PropList_Array)].PropList); PropList_Array[High(PropList_Array)].Count := Count; end; SetLength(CurrentPointerArray.Kur, Height + 1); for L := 0 to PropList_Array[0].Count -1 do begin for I := 0 to Height do begin Flag := False; for J := 0 to PropList_Array[I].Count -1 do begin if PropList_Array[0].PropList^[L]^.Name = PropList_Array[I].PropList^[J]^.Name then begin CurrentPointerArray.Kur[I] := Pointer(Instance[I]) + PtrUInt(PropList_Array[I].PropList^[J]^.SetProc); CurrentPointerArray.Name := PropList_Array[I].PropList^[J]^.Name; Flag := True; break; end; end; if not(Flag) then break; //Имеется недоработка в коде ДОПИШИ!!! УСТРАНЕНА, ОПТИМИЗИРОВАТЬ !!! end; if Flag then begin SetLength(MUFinal, Length(MUFinal) + 1); SetLength(MUFinal[High(MUFinal)].Kur, Height + 1); MUFinal[High(MUFinal)].Name := CurrentPointerArray.Name; for J := 0 to Height do begin MUFinal[High(MUFinal)].Kur[J] := CurrentPointerArray.Kur[J]; end; end; end; for I := 0 to High(MUFinal) do begin NewEdit := ControlEdits.CompareName(MUFinal[I].Name); if NewEdit = nil then continue; NewEdit.Create(Panel, MUFinal[I].Kur); end; for I := 0 to High(MUFinal) do begin NewEditNew := ControlEditsNew.CompareName(MUFinal[I].Name); if NewEditNew = nil then continue; NewEditNew.Create( ControlEditsNew.CompareName_Controls(NewEditNew), MUFinal[I].Kur); end; FreeAllMem; end; procedure GetComponentProperties(Instance: TObject; Panel: TWinControl); overload; var ArrayOneFigure: array[0..0] of TObject; begin if Instance = nil then exit; ArrayOneFigure[0] := Instance; GetComponentProperties(ArrayOneFigure, Panel); end; end.
unit UI.WaitDialog; interface uses UI.Base, UI.Toast, UI.Dialog, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Forms; /// <summary> /// 等待对话框是否被取消了 /// </summary> function IsWaitDismiss: Boolean; /// <summary> /// 隐藏等待对话框 /// </summary> procedure HideWaitDialog; /// <summary> /// 显示等待对话框 /// </summary> procedure ShowWaitDialog(const AMsg: string; ACancelable: Boolean = True); overload; /// <summary> /// 显示等待对话框 /// </summary> procedure ShowWaitDialog(const AMsg: string; OnDismissListener: TOnDialogListener; ACancelable: Boolean = True); overload; /// <summary> /// 显示等待对话框 /// </summary> procedure ShowWaitDialog(const AMsg: string; OnDismissListener: TOnDialogListenerA; ACancelable: Boolean = True); overload; /// <summary> /// 更新等待对话框消息内容 /// </summary> procedure UpdateWaitDialog(const AMsg: string); /// <summary> /// 非必须,初始化等待对话框 /// </summary> /// <remarks> /// 必须在 ShowWaitDialog 之前调用 /// </remarks> procedure InitWaitDialog(const AParent: TFmxObject); implementation var FWaitDialog: TProgressDialog = nil; function IsWaitDismiss: Boolean; begin Result := (not Assigned(FWaitDialog)) or (FWaitDialog.IsDismiss) end; procedure HideWaitDialog; begin if not IsWaitDismiss then begin FWaitDialog.Dismiss; FWaitDialog := nil; end; end; procedure ShowWaitDialog(const AMsg: string; OnDismissListener: TOnDialogListener; ACancelable: Boolean); begin ShowWaitDialog(AMsg, ACancelable); if Assigned(FWaitDialog) then FWaitDialog.OnDismissListener := OnDismissListener; end; procedure ShowWaitDialog(const AMsg: string; OnDismissListener: TOnDialogListenerA; ACancelable: Boolean); begin ShowWaitDialog(AMsg, ACancelable); if Assigned(FWaitDialog) then FWaitDialog.OnDismissListenerA := OnDismissListener; end; procedure ShowWaitDialog(const AMsg: string; ACancelable: Boolean); begin if IsWaitDismiss then begin FWaitDialog := nil; FWaitDialog := TProgressDialog.Create(Application.MainForm); end; FWaitDialog.Cancelable := ACancelable; if not Assigned(FWaitDialog.RootView) then FWaitDialog.InitView(AMsg) else FWaitDialog.Message := AMsg; TDialog(FWaitDialog).Show(); end; procedure UpdateWaitDialog(const AMsg: string); begin if IsWaitDismiss then Exit; if Assigned(FWaitDialog.RootView) then begin FWaitDialog.Message := AMsg; FWaitDialog.RootView.MessageView.Text := AMsg; end; end; procedure InitWaitDialog(const AParent: TFmxObject); begin if not Assigned(AParent) then Exit; if IsWaitDismiss then FWaitDialog := TProgressDialog.Create(AParent) else FWaitDialog.RootView.Parent := AParent; end; initialization finalization FWaitDialog := nil; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileSTL<p> Support-code to load STL Files into TGLFreeForm-Components in GLScene.<p> Note that you must manually add this unit to one of your project's uses to enable support for STL files at run-time.<p> <b>History : </b><font size=-1><ul> <li>16/10/08 - UweR - Compatibility fix for Delphi 2009 <li>22/11/02 - EG - Write capability now properly declared <li>17/10/02 - EG - Created from split of GLVectorFileObjects, ASCII STL support (Adem) </ul><p> } unit GLFileSTL; interface uses System.Classes, System.SysUtils, GLVectorFileObjects, GLApplicationFileIO, GLCrossPlatform; type // TGLSTLVectorFile // {: The STL vector file (stereolithography format).<p> It is a list of the triangular surfaces that describe a computer generated solid model. This is the standard input for most rapid prototyping machines.<p> There are two flavors of STL, the "text" and the "binary", this class reads both, but exports only the "binary" version.<p> Original Binary importer code by Paul M. Bearne, Text importer by Adem. } TGLSTLVectorFile = class(TVectorFile) public { Public Declarations } class function Capabilities : TDataFileCapabilities; override; procedure LoadFromStream(aStream: TStream); override; procedure SaveToStream(aStream: TStream); override; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses TypesSTL, GLVectorGeometry, GLVectorLists, GLUtils; const cSOLID_LABEL = 'SOLID'; cFACETNORMAL_LABEL = 'FACET NORMAL '; cOUTERLOOP_LABEL = 'OUTER LOOP'; cVERTEX_LABEL = 'VERTEX'; cENDLOOP_LABEL = 'ENDLOOP'; cENDFACET_LABEL = 'ENDFACET'; cENDSOLID_LABEL = 'ENDSOLID'; cFULL_HEADER_LEN = 84; // ------------------ // ------------------ TGLSTLVectorFile ------------------ // ------------------ // Capabilities // class function TGLSTLVectorFile.Capabilities : TDataFileCapabilities; begin Result:=[dfcRead, dfcWrite]; end; // LoadFromStream // procedure TGLSTLVectorFile.LoadFromStream(aStream : TStream); var sl : TStringList; procedure DecodeSTLNormals(const aString : String; var aNormal : TSTLVertex); begin sl.CommaText:=aString; if sl.Count<>5 then raise Exception.Create('Invalid Normal') else begin aNormal.V[0]:=GLUtils.StrToFloatDef(sl[2], 0); aNormal.V[1]:=GLUtils.StrToFloatDef(sl[3], 0); aNormal.V[2]:=GLUtils.StrToFloatDef(sl[4], 0); end; end; procedure DecodeSTLVertex(const aString : String; var aVertex : TSTLVertex); begin sl.CommaText:=aString; if (sl.Count<>4) or (CompareText(sl[0], cVERTEX_LABEL)<>0) then raise Exception.Create('Invalid Vertex') else begin aVertex.V[0]:=GLUtils.StrToFloatDef(sl[1], 0); aVertex.V[1]:=GLUtils.StrToFloatDef(sl[2], 0); aVertex.V[2]:=GLUtils.StrToFloatDef(sl[3], 0); end; end; var isBinary : Boolean; headerBuf : array [0..cFULL_HEADER_LEN-1] of AnsiChar; positionBackup : Integer; fileContent : TStringList; curLine : String; i : Integer; mesh : TMeshObject; header : TSTLHeader; dataFace : TSTLFace; calcNormal : TAffineVector; begin positionBackup:=aStream.Position; aStream.Read(headerBuf[0], cFULL_HEADER_LEN); aStream.Position:=positionBackup; isBinary:=True; i:=0; while i<80 do begin if (headerBuf[i]<#32) and (headerBuf[i]<>#0) then begin isBinary:=False; Break; end; Inc(i); end; mesh:=TMeshObject.CreateOwned(Owner.MeshObjects); try mesh.Mode:=momTriangles; if isBinary then begin aStream.Read(header, SizeOf(TSTLHeader)); for i:=0 to header.nbFaces-1 do begin aStream.Read(dataFace, SizeOf(TSTLFace)); with dataFace, mesh do begin // STL faces have a normal, but do not necessarily follow the winding rule, // so we must first determine if the triangle is properly oriented // and rewind it properly if not... calcNormal:=CalcPlaneNormal(v1, v2, v3); if VectorDotProduct(calcNormal, normal)>0 then Vertices.Add(v1, v2, v3) else Vertices.Add(v3, v2, v1); Normals.Add(normal, normal, normal); end; end; end else begin fileContent:=TStringList.Create; sl:=TStringList.Create; try fileContent.LoadFromStream(aStream); i:=0; curLine:=Trim(UpperCase(fileContent[i])); if Pos(cSOLID_LABEL, curLine)=1 then begin mesh.Vertices.Capacity:=(fileContent.Count-2) div 7; mesh.Normals.Capacity:=(fileContent.Count-2) div 7; Inc(i); curLine:=Trim(UpperCase(fileContent[i])); while i<fileContent.Count do begin if Pos(cFACETNORMAL_LABEL, curLine)=1 then begin DecodeSTLNormals(curLine, dataFace.normal); Inc(i); curLine:=Trim(UpperCase(fileContent[i])); if Pos(cOUTERLOOP_LABEL, curLine)=1 then begin Inc(i); curLine:=Trim(fileContent[i]); DecodeSTLVertex(curLine, dataFace.v1); Inc(i); curLine:=Trim(fileContent[i]); DecodeSTLVertex(curLine, dataFace.v2); Inc(i); curLine:=Trim(fileContent[i]); DecodeSTLVertex(curLine, dataFace.v3); end; Inc(i); curLine:=Trim(UpperCase(fileContent[i])); if Pos(cENDLOOP_LABEL, curLine)<>1 then raise Exception.Create('End of Loop Not Found') else begin calcNormal:=CalcPlaneNormal(dataFace.v1, dataFace.v2, dataFace.v3); if VectorDotProduct(calcNormal, dataFace.normal)>0 then mesh.Vertices.Add(dataFace.v1, dataFace.v2, dataFace.v3) else mesh.Vertices.Add(dataFace.v3, dataFace.v2, dataFace.v1); mesh.Normals.Add(dataFace.normal, dataFace.normal, dataFace.normal); end; end; Inc(i); curLine:=Trim(UpperCase(fileContent[i])); if Pos(cENDFACET_LABEL, curLine)<>1 then raise Exception.Create('End of Facet Not found'); Inc(i); curLine:=Trim(UpperCase(fileContent[i])); if Pos(cENDSOLID_LABEL, curLine)=1 then Break; end; end; finally sl.Free; fileContent.Free; end; end; except on E : Exception do begin mesh.Free; end; end; end; // SaveToStream // procedure TGLSTLVectorFile.SaveToStream(aStream: TStream); var i : Integer; header : TSTLHeader; dataFace : TSTLFace; list : TAffineVectorList; const cHeaderTag = 'GLScene STL export'; begin list:=Owner.MeshObjects.ExtractTriangles; try FillChar(header.dummy[0], SizeOf(header.dummy), 0); Move(cHeaderTag, header.dummy[0], Length(cHeaderTag)); header.nbFaces:=list.Count div 3; aStream.Write(header, SizeOf(header)); i:=0; while i<list.Count do begin dataFace.normal:=CalcPlaneNormal(list[i], list[i+1], list[i+2]); dataFace.v1:=list[i]; dataFace.v2:=list[i+1]; dataFace.v3:=list[i+2]; aStream.Write(dataFace, SizeOf(dataFace)); Inc(i, 3); end; finally list.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterVectorFileFormat('stl', 'Stereolithography files', TGLSTLVectorFile); end.
unit Bank_s; {This file was generated on 11 Aug 2000 20:16:15 GMT by version 03.03.03.C1.06} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file account.idl. } {Delphi Pascal unit : Bank_s } {derived from IDL module : Bank } interface uses CORBA, Bank_i, Bank_c; type TCheckingSkeleton = class; TSavingsSkeleton = class; TCheckingSkeleton = class(CORBA.TCorbaObject, Bank_i.Checking) private FImplementation : Checking; public constructor Create(const InstanceName: string; const Impl: Checking); destructor Destroy; override; function GetImplementation : Checking; function balance : Single; published procedure _balance(const _Input: CORBA.InputStream; _Cookie: Pointer); end; TSavingsSkeleton = class(CORBA.TCorbaObject, Bank_i.Savings) private FImplementation : Savings; public constructor Create(const InstanceName: string; const Impl: Savings); destructor Destroy; override; function GetImplementation : Savings; function interest_rate : Single; function balance : Single; published procedure _interest_rate(const _Input: CORBA.InputStream; _Cookie: Pointer); procedure _balance(const _Input: CORBA.InputStream; _Cookie: Pointer); end; implementation constructor TCheckingSkeleton.Create(const InstanceName : string; const Impl : Bank_i.Checking); begin inherited; inherited CreateSkeleton(InstanceName, 'Checking', 'IDL:Bank/Checking:1.0'); FImplementation := Impl; end; destructor TCheckingSkeleton.Destroy; begin FImplementation := nil; inherited; end; function TCheckingSkeleton.GetImplementation : Bank_i.Checking; begin result := FImplementation as Bank_i.Checking; end; function TCheckingSkeleton.balance : Single; begin Result := FImplementation.balance; end; procedure TCheckingSkeleton._balance(const _Input: CORBA.InputStream; _Cookie: Pointer); var _Output : CORBA.OutputStream; _Result : Single; begin _Result := balance; GetReplyBuffer(_Cookie, _Output); _Output.WriteFloat(_Result); end; constructor TSavingsSkeleton.Create(const InstanceName : string; const Impl : Bank_i.Savings); begin inherited; inherited CreateSkeleton(InstanceName, 'Savings', 'IDL:Bank/Savings:1.0'); FImplementation := Impl; end; destructor TSavingsSkeleton.Destroy; begin FImplementation := nil; inherited; end; function TSavingsSkeleton.GetImplementation : Bank_i.Savings; begin result := FImplementation as Bank_i.Savings; end; function TSavingsSkeleton.interest_rate : Single; begin Result := FImplementation.interest_rate; end; function TSavingsSkeleton.balance : Single; begin Result := FImplementation.balance; end; procedure TSavingsSkeleton._interest_rate(const _Input: CORBA.InputStream; _Cookie: Pointer); var _Output : CORBA.OutputStream; _Result : Single; begin _Result := interest_rate; GetReplyBuffer(_Cookie, _Output); _Output.WriteFloat(_Result); end; procedure TSavingsSkeleton._balance(const _Input: CORBA.InputStream; _Cookie: Pointer); var _Output : CORBA.OutputStream; _Result : Single; begin _Result := balance; GetReplyBuffer(_Cookie, _Output); _Output.WriteFloat(_Result); end; initialization end.
unit u_xpl_heart_beater; { Il y a un bug dans la version fpc 2.5.1 de fpTimer. Ce bug génère un 'hang' général de l'application dès que l'on active ou désactive un fptimer. il faut employer une version antérieure pour fonctionner correctement pour contourner le problème - Récupérer celle qui se trouve ici : http://svn.freepascal.org/cgi-bin/viewvc.cgi/trunk/packages/fcl-base/src/fptimer.pp?revision=13012 et forcer son utilisation en ajoutant le chemin de recherche : C:\pp\packages\fcl-base\src\ dans les paths du projet } {$i xpl.inc} interface uses Classes , SysUtils , fpc_delphi_compat , u_xpl_config ; type TxPLRateFrequency = (rfDiscovering, rfNoHubLowFreq, rfRandom, rfConfig, rfNone); TConnectionStatus = (discovering, connected, csNone); // TxPLConnHandler ======================================================= TxPLConnHandler = class(TComponent) private fTimer : TxPLTimer; fRate : TxPLRateFrequency; FNoHubTimerCount : integer; function GetConnectionStatus: TConnectionStatus; procedure SetConnectionStatus(const AValue: TConnectionStatus); procedure Set_Rate(const AValue: TxPLRateFrequency); procedure Tick({%H-}sender : TObject); public constructor Create(AOwner: TComponent); override; function StatusAsStr : string; published property Rate : TxPLRateFrequency write Set_Rate; property Status : TConnectionStatus read GetConnectionStatus write SetConnectionStatus; end; implementation // ============================================================= uses TypInfo , u_xpl_custom_listener , u_xpl_application ; const K_NETWORK_STATUS = 'xPL Network status : %s'; // Hub and listener constants ================================================= const NOHUB_HBEAT : Integer = 3; // seconds between HBEATs until hub is detected NOHUB_LOWERFREQ : Integer = 30; // lower frequency probing for hub NOHUB_TIMEOUT : Integer = 120; // after these nr of seconds lower the probing frequency to NOHUB_LOWERFREQ constructor TxPLConnHandler.create(AOwner: TComponent); begin Assert(aOwner is TxPLCustomListener); inherited; fTimer := TxPLApplication(aOwner).TimerPool.Add(0,{$ifdef fpc}@{$endif}Tick); fNoHubTimerCount := 0; Rate := rfNone; end; function TxPLConnHandler.StatusAsStr: string; begin Result := Format(K_NETWORK_STATUS, [GetEnumName(TypeInfo(TConnectionStatus), Ord(Status))]); end; procedure TxPLConnHandler.Tick(sender: TObject); begin with TxPLCustomListener(Owner) do begin if ConnectionStatus <> connected then begin inc(fNoHubTimerCount,NOHUB_HBEAT); if fNoHubTimerCount > NOHUB_TIMEOUT then Rate := rfNoHubLowFreq; // Still a high frequency ? end else begin fNoHubTimerCount := 0; Rate := rfConfig; // Always get back to preserved frequence end; SendHeartBeatMessage; end; end; procedure TxPLConnHandler.Set_Rate(const AValue: TxPLRateFrequency); procedure Set_Interval(aInterval : {$ifdef fpc}integer{$else}cardinal{$endif}); begin if fTimer.Interval <> aInterval then begin fTimer.Enabled := False; fTimer.Interval := aInterval; fTimer.Enabled := True; end; end; begin fRate:=AValue; case fRate of rfDiscovering : begin Set_Interval(NOHUB_HBEAT * 1000); // Force a tick right now in this case Tick(self); // to avoid waiting 3 secs before connection end; rfNoHubLowFreq : Set_Interval(NOHUB_LOWERFREQ * 1000); // Choose a random value between 2 and 6 seconds rfRandom : Set_Interval(Random(4000) + 2000); rfConfig : Set_Interval(TxPLCustomListener(owner).Config.Interval*60*1000); end; end; function TxPLConnHandler.GetConnectionStatus: TConnectionStatus; begin case fRate of rfDiscovering,rfNoHubLowFreq : result := Discovering; rfRandom,rfConfig : result := Connected; end; end; procedure TxPLConnHandler.SetConnectionStatus(const AValue: TConnectionStatus); begin if Status<>aValue then begin if aValue = connected then Rate := rfConfig else Rate := rfDiscovering; end; end; end.
unit UMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, classe.person, classe.client, classe.saler, Vcl.ComCtrls; type TForm1 = class(TForm) btSaveClient: TButton; edtName: TEdit; edtAge: TEdit; PageControl1: TPageControl; TabClient: TTabSheet; TabSaler: TTabSheet; edtPaymentDay: TEdit; edtAdress: TEdit; edtCommission: TEdit; edtType: TEdit; btSaveSaler: TButton; btSee: TButton; procedure btSaveClientClick(Sender: TObject); procedure btSaveSalerClick(Sender: TObject); procedure btSeeClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } public { Public declarations } SQL: TStringList; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btSaveClientClick(Sender: TObject); var ObjClient: TClient; begin ObjClient := TClient.Create; try ObjClient.Name := edtName.Text; ObjClient.Age := StrToInt(edtAge.Text); ObjClient.dayPayment := StrToInt(edtPaymentDay.Text); ObjClient.Adress := edtAdress.Text; if ObjClient.save(SQL) then begin ShowMessage('Cliente ' + edtName.Text + ' cadastrado com sucesso !'); end else begin ShowMessage('Erro ao cadastrar o Cliente.'); end; edtName.Clear; edtAge.Clear; edtPaymentDay.Clear; edtAdress.Clear; finally ObjClient.Free; end; end; procedure TForm1.btSaveSalerClick(Sender: TObject); var ObjSaler: TSaler; begin ObjSaler := TSaler.Create; try ObjSaler.Name := edtName.Text; ObjSaler.Age := StrToInt(edtAge.Text); ObjSaler.Commission := StrToFloat(edtCommission.Text); ObjSaler.TypeSaler := AnsiUpperCase(edtType.Text); if ObjSaler.save(SQL) THEN BEGIN ShowMessage('Vendedor ' + edtName.Text + ' cadastrado com sucesso !'); END else BEGIN showmessage('Erro ao cadastrar o Vendedor.'); END; edtName.Clear; edtAge.Clear; edtCommission.Clear; edtType.Clear; finally ObjSaler.Free; end; end; procedure TForm1.btSeeClick(Sender: TObject); begin ShowMessage(SQL.Text); end; procedure TForm1.FormCreate(Sender: TObject); begin SQL := TStringList.Create; end; procedure TForm1.FormDestroy(Sender: TObject); begin SQL.Free; end; end.
unit Es8Utils; interface Uses Windows, SysUtils, Classes, System.Variants, System.Generics.Defaults, StrUtils, Registry, Menus, System.DateUtils, System.RegularExpressions, System.Generics.Collections, {$IFNDEF ServerOprosa} //PSO не использует JCL JclSysInfo, {$ENDIF} esExceptions; const TRUE_AS_STRING = 'True'; FALSE_AS_STRING = 'False'; type TEsStringList = class(TStringList) public constructor CreateFromArray(const source: array of string); function ToStringWithDelimiter(const delimiter: string): string; end; {{ Аналог (обертка над) TStringList, TEsStringList Предназначен для утилитных операций со строками. Позволяет не писать Free для временного объекта} IStringListInterface = interface ['{4772449B-8E49-430E-B19F-BFC6DA2185BA}'] function OriginalStrings(): TStrings; procedure SetValue(const Name, Value: string); function GetName(Index: Integer): string; function GetValue(const Name: string): string; function GetCommaText: string; procedure SetCommaText(const Value: string); procedure SetText(const Value: string); function GetText: string; function GetCount(): Integer; function GetItem(Index: Integer): string; function GetObject(Index: Integer): TObject; function ToStringWithDelimiter(const delimiter: string): string; procedure Add(const s: string);overload; procedure AddIfNotEmpty(const s: string); procedure AddObject(const s: string; obj: TObject); overload; procedure AddObject(const s: string; obj: integer); overload; procedure Add(const FormatStr: string; const Args: array of const);overload; procedure AddStrings(Strings: IStringListInterface);overload; procedure AddStrings(Strings: TStrings);overload; procedure AddTo(dest: TStrings);overload; procedure AddTo(dest: ExceptionWithDetails);overload; function GetDelimiter: Char; procedure SetDelimiter(const Value: Char); function GetStrictDelimiter: Boolean; procedure SetStrictDelimiter(const Value: Boolean); function GetDelimitedText: string; procedure SetDelimitedText(const Value: string); procedure Delete(Index: Integer); procedure SaveToFile(const FileName: string); function GetEnumerator: TStringsEnumerator; procedure BeginUpdate; procedure EndUpdate; procedure Clear(); function Contains(const str: string): boolean; function ContainsValue(const valueName: string): boolean; property Count: Integer read GetCount; property Text: string read GetText write SetText; property CommaText: string read GetCommaText write SetCommaText; property Values[const Name: string]: string read GetValue write SetValue; property Items[Index: Integer]: string read GetItem;default; property Objects[Index: Integer]: TObject read GetObject; property Delimiter: Char read GetDelimiter write SetDelimiter; property Names[Index: Integer]: string read GetName; property StrictDelimiter: Boolean read GetStrictDelimiter write SetStrictDelimiter; property DelimitedText: string read GetDelimitedText write SetDelimitedText; end; {{См. IStringListInterface} TStringListInterfaced = class(TInterfacedObject, IStringListInterface) private FStrings: TEsStringList; function GetDelimiter: Char; procedure SetDelimiter(const Value: Char); function GetStrictDelimiter: Boolean; procedure SetStrictDelimiter(const Value: Boolean); function GetDelimitedText: string; procedure SetDelimitedText(const Value: string); protected function OriginalStrings(): TStrings; procedure SetValue(const Name, Value: string); function GetValue(const Name: string): string; function GetName(Index: Integer): string; function GetCommaText: string; procedure SetCommaText(const Value: string); procedure SetText(const Value: string); function GetText: string; function GetItem(Index: Integer): string; function GetObject(Index: Integer): TObject; function GetCount(): Integer; function ToStringWithDelimiter(const delimiter: string): string; procedure Add(const s: string);overload; procedure AddIfNotEmpty(const s: string); procedure Add(const FormatStr: string; const Args: array of const);overload; procedure AddObject(const s: string; obj: TObject); overload; procedure AddObject(const s: string; obj: integer); overload; procedure AddStrings(Strings: IStringListInterface);overload; procedure AddStrings(Strings: TStrings);overload; procedure AddTo(dest: TStrings);overload; procedure AddTo(dest: ExceptionWithDetails);overload; procedure Delete(Index: Integer); procedure SaveToFile(const FileName: string); function GetEnumerator: TStringsEnumerator; procedure BeginUpdate; procedure EndUpdate; procedure Clear(); function Contains(const str: string): boolean; function ContainsValue(const valueName: string): boolean; property Count: Integer read GetCount; property Text: string read GetText write SetText; property Names[Index: Integer]: string read GetName; property Values[const Name: string]: string read GetValue write SetValue; property CommaText: string read GetCommaText write SetCommaText; property Items[Index: Integer]: string read GetItem; property Delimiter: Char read GetDelimiter write SetDelimiter; property StrictDelimiter: Boolean read GetStrictDelimiter write SetStrictDelimiter; property DelimitedText: string read GetDelimitedText write SetDelimitedText; public constructor Create(const aText: string = ''); constructor CreateWithDelimiter(const aTextToDelimit: string; aDelimiter: Char); destructor Destroy;override; end; {{Обертка над реестром для упрощения вызовов} TEsRegistry = class private FRegistry: TRegistry; FKeyOpened: boolean; function NormalizeName(const name: string): string; protected function TryReadInteger(const Name: string; out value: Integer): boolean; function TryReadBoolean(const Name: string; out value: boolean): boolean; public constructor Create(const rootKeyName: string; canWrite: boolean); destructor Destroy();override; procedure WriteString(const Name, Value: string); procedure WriteAsString(const Name: string; Value: Integer);overload; procedure WriteAsString(const Name: string; Value: boolean);overload; function TryReadString(const Name: string; out value: string): boolean; function ReadString(const Name, defaultValue: string): string; function ReadInteger(const Name: string; aMin, aMax, defaultValue: Integer): Integer;overload; function ReadInteger(const Name: string; defaultValue: Integer): Integer;overload; function ReadBoolean(const Name: string; defaultValue: boolean): boolean; {{Пишет флаг "Checked" у item} procedure WriteChecked(item: TMenuItem); {{Читает значение флага "Checked" для item} procedure ReadChecked(item: TMenuItem); procedure WriteStringsByComma(const name: string; Value: IStringListInterface); function TryReadStringsByComma(const name: string): IStringListInterface; property KeyOpened: boolean read FKeyOpened; end; {{Источник "астрономического" времени. Астрономическое время не имеет переходов зима/лето. Время всегда только увеличивается.} TDateTimeProviderSimple = class function GetNowAstroTime(): TDateTime;virtual; //Текущее время компьютера, на котором работаем end; TExceptionHelper = class helper for Exception function MessageWithNestedExceptions(): string; end; {{ Умный указатель, не требует каноничного блока Create try .. finally Free end Пример использовния: var sl: ISmartPointer<TStringList>; begin sl := TSmartPointer<TStringList>.Create(); // конструктор по умолчанию sl := TSmartPointer<TStringList>.Create(TStringList.Create(true)); // конструктор с параметрами sl.Add('За мной не надо чистить память'); end; } ISmartPointer<T> = reference to function: T; TSmartPointer2<T: class> = class(TInterfacedObject, ISmartPointer<T>) private FValue: T; function Invoke: T; public constructor Create(AValue: T); overload; destructor Destroy; override; end; TSmartPointer<T: class, constructor> = class(TSmartPointer2<T>, ISmartPointer<T>) public constructor Create; overload; end; TFakeInterfaceObject = class(TObject, IInterface) private class var FInstance: TFakeInterfaceObject; class constructor ClassCreate(); class procedure UnitFinalizationWithoutThreads(); protected type TOnUnitFinalization = reference to procedure; class var OnUnitFinalization: TOnUnitFinalization; protected function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; class function GetInstance(): TFakeInterfaceObject;inline; end; ENullableNotAssignedException = class(ECheckException); Nullable<T> = record {{Inspired by https://community.embarcadero.com/blogs/entry/a-andquotnullableandquot-post-38869} private FValue: T; FHasValue: IInterface;//поле интерфейсного типа будет обнулено компиляторм при размещении структуры на стэке. Булевский флаг так бы не смог быть инициализирован function GetValue: T; public constructor Create(AValue: T); class function CreateEmpty(): Nullable<T>;static; function GetValueOrDefault: T; overload; function GetValueOrDefault(Default: T): T; overload; function Assigned(): boolean; property HasValue: Boolean read Assigned; property Value: T read GetValue; class operator NotEqual(const ALeft, ARight: Nullable<T>): Boolean; class operator Equal(const ALeft, ARight: Nullable<T>): Boolean; class operator Implicit(Value: Nullable<T>): T; class operator Implicit(Value: T): Nullable<T>; class operator Explicit(Value: Nullable<T>): T; end; INamedFormat = interface ['{C2627E6E-481F-40CB-94DD-F027F204E065}'] function AddNull(const name: string): INamedFormat; function Add(const name: string; Value: Integer): INamedFormat;overload; function Add(const name: string; Value: TDateTime): INamedFormat;overload; function Add(const name, Value: string): INamedFormat;overload; function Format(): string; end; TNamedFormat = class(TInterfacedObject, INamedFormat) public type TFormatMode = (fmDefault, fmSql); TFormatModeHelper = record helper for TFormatMode public function GetDefaultPrefix(): string; function GetReplaceFlags(): TReplaceFlags; end; TFormatParameter = record private FName: string; FIntValue: Nullable<Integer>; FDateTimeValue: Nullable<TDateTime>; FStringValue: Nullable<string>; public class function Int(const aName: string; const Value: Integer): TFormatParameter;static; class function DT(const aName: string; const Value: TDateTime): TFormatParameter;static; class function Str(const aName, Value: string): TFormatParameter;static; class function Null(const aName: string): TFormatParameter;static; function Format(parent: TNamedFormat; const format: string): string; property Name: string read FName; end; private FParameters: array of TFormatParameter; FFormatMode: TFormatMode; FFormatString: string; protected function Format(): string; constructor DoCreate(aMode: TFormatMode; const aformatStr: string); function DoAdd(var parameter: TFormatParameter): INamedFormat; public constructor ForSql(const resourceName: string); constructor Create(const formatStr: string; mode: TFormatMode = fmDefault); constructor FromResource(const resourceName: string; mode: TFormatMode = fmDefault); function Add(const name: string; Value: Integer): INamedFormat;overload; function Add(const name, Value: string): INamedFormat;overload; function Add(const name: string; Value: TDateTime): INamedFormat;overload; function AddNull(const name: string): INamedFormat; destructor Destroy;override; property FormatMode: TFormatMode read FFormatMode; end; {{Сортировка строк с адресами, применяемая во всей Энергосфере. Надо, чтобы было: Волгоградская 2 < Волгоградская 194} TStringNormalizer = class private class var AnyNumber: TRegEx; class var WhiteSpaces: TRegEx; private class constructor ClassCreate(); class function DoReplace(const Match: TMatch): string; public class function NormalizeStringForCompare(const value: string): string; class function CompareStrings(const str1, str2: string): Integer; end; {{Returns true if v is not NULL or EMPTY} function VarIsAssigned(const v: Variant): boolean; inline; {{Returns true if v IS NULL or EMPTY} function VarIsNullOrEmpty(const v: Variant): boolean; inline; {{Если в конце msg нет точки/воскл. знака, добавляет в конец msg точку} function AppendDotIfNeeded(const msg: string): string; {{ Выдергивает полный текст сообщения об ошибке, включая InnerException's (если есть). В простейшем случае результат == E.Message Если в конце сообщения об ощибке нет точки/воскл. знака, добавляет в конец сообщения точку} function FullMessage(const E: Exception): string; function LoadStringFromRcData(const resourceName: string): string; {$IFNDEF ServerOprosa} {{"PROSOFT-E\petrov" for domain user, or just "petrov", if can not get info from domain} function GetDomainAndUserName(): string; {$ENDIF} {{Same as GetTimeZoneInformation but throws an error if can not read time zone info} function GetTimeZoneInformationWithException(var lpTimeZoneInformation: TTimeZoneInformation): DWORD; {{'True' or 'False'} function BooleanToDebugStr(b: boolean): string; function GET_X_LPARAM(lParam: DWORD): SmallInt; function GET_Y_LPARAM(lParam: DWORD): SmallInt; implementation uses System.Math; function BooleanToDebugStr(b: boolean): string; begin Result := IfThen(b, TRUE_AS_STRING, FALSE_AS_STRING); end; function GET_X_LPARAM(lParam: DWORD): SmallInt; begin Result := SmallInt( lParam and $FFFF); end; function GET_Y_LPARAM(lParam: DWORD): SmallInt; begin Result := SmallInt( (lParam shr 16) and $FFFF); end; function VarIsAssigned(const v: Variant): boolean; inline; begin Result := (v <> System.Variants.Null) and (not VarIsNull(v)) and (not VarIsEmpty(v)); end; function VarIsNullOrEmpty(const v: Variant): boolean; inline; begin Result := VarIsNull(v) or VarIsEmpty(v) or (v = System.Variants.Null); end; {$IFNDEF ServerOprosa} function GetDomainAndUserName(): string; begin try Result := Trim(GetDomainName()); except on E: EOSError do Result := ''; end; if Result = '' then Result := GetLocalUserName() else Result := Format('%s\%s', [Result, GetLocalUserName()]); end; {$ENDIF} function GetTimeZoneInformationWithException(var lpTimeZoneInformation: TTimeZoneInformation): DWORD; begin Result:= GetTimeZoneInformation(lpTimeZoneInformation); if (Result = $FFFFFFFF) then RaiseLastOSError(); end; function AppendDotIfNeeded(const msg: string): string; var trimmedMessage: string; begin trimmedMessage := Trim(msg); Result := msg; if not (trimmedMessage.EndsWith('.') or trimmedMessage.EndsWith('!')) then Result := Result + '.'; end; function FullMessage(const E: Exception): string; var Ex: Exception; text: IStringListInterface; aMessage: string; begin if E = nil then begin Result := '[No Exception!]'; exit; end; if not Assigned(E.InnerException) then begin Result := AppendDotIfNeeded(E.Message); exit; end; Ex := E; text:= TStringListInterfaced.Create(); repeat if Trim(Ex.Message) <> '' then begin aMessage := AppendDotIfNeeded(Ex.Message); if text.Count = 0 then text.Add(aMessage) else text.Add('Причина: %s', [aMessage]); end; Ex := Ex.InnerException; until (Ex = nil); if text.Count = 0 then Result := '[Исключение без текста]' else Result := Text.ToStringWithDelimiter(sLineBreak); end; { TExceptionHelper } function TExceptionHelper.MessageWithNestedExceptions: string; begin Result := FullMessage(Self); end; function LoadStringFromRcData(const resourceName: string): string; var ResStream: TResourceStream; dest: TStringStream; begin ResStream := TResourceStream.Create(HInstance, resourceName, RT_RCDATA); try dest:= TStringStream.Create(); try ResStream.SaveToStream(dest); Result := dest.DataString; finally dest.Free(); end; finally ResStream.Free(); end; end; { TEsStringList } constructor TEsStringList.CreateFromArray(const source: array of string); var I: Integer; begin inherited Create(); for I:= Low(source) to High(source) do Add(source[I]); end; function TEsStringList.ToStringWithDelimiter(const delimiter: string): string; var old: string; begin if delimiter = '' then raise ECheckException.Create('ToStringWithDelimiter not tested with empty delimiter'); old := LineBreak; try LineBreak:= delimiter; Result:= Text; if EndsStr(delimiter, Result) then System.Delete(Result, Length(Result) - Length(delimiter) + 1, Length(delimiter)); finally LineBreak:= old; end; end; { TStringListInterfaced } constructor TStringListInterfaced.Create(const aText: string = ''); begin inherited Create(); FStrings:= TEsStringList.Create(); if Length(aText) > 0 then Text := aText; end; constructor TStringListInterfaced.CreateWithDelimiter(const aTextToDelimit: string; aDelimiter: Char); begin Create(); Delimiter := aDelimiter; StrictDelimiter := True; DelimitedText:= aTextToDelimit; end; destructor TStringListInterfaced.Destroy; begin FStrings.Free(); inherited; end; procedure TStringListInterfaced.EndUpdate; begin FStrings.EndUpdate(); end; procedure TStringListInterfaced.Clear; begin FStrings.Clear(); end; function TStringListInterfaced.GetCommaText: string; begin Result:= FStrings.CommaText; end; function TStringListInterfaced.GetCount: Integer; begin Result:= FStrings.Count; end; procedure TStringListInterfaced.Delete(Index: Integer); begin FStrings.Delete(Index); end; function TStringListInterfaced.GetDelimitedText: string; begin Result := FStrings.DelimitedText; end; function TStringListInterfaced.GetDelimiter: Char; begin Result := FStrings.Delimiter; end; function TStringListInterfaced.GetEnumerator: TStringsEnumerator; begin Result := FStrings.GetEnumerator; end; function TStringListInterfaced.GetItem(Index: Integer): string; begin Result:= FStrings[Index]; end; function TStringListInterfaced.GetObject(Index: Integer): TObject; begin REsult := FStrings.Objects[Index]; end; function TStringListInterfaced.GetStrictDelimiter: Boolean; begin Result := FStrings.StrictDelimiter; end; function TStringListInterfaced.GetText: string; begin Result:= FStrings.Text; end; function TStringListInterfaced.GetValue(const Name: string): string; begin Result:= FStrings.Values[Name]; end; function TStringListInterfaced.OriginalStrings: TStrings; begin Result:= FStrings; end; procedure TStringListInterfaced.SaveToFile(const FileName: string); begin FStrings.SaveToFile(FileName); end; procedure TStringListInterfaced.SetCommaText(const Value: string); begin FStrings.CommaText := Value; end; procedure TStringListInterfaced.SetDelimitedText(const Value: string); begin FStrings.DelimitedText := Value; end; procedure TStringListInterfaced.SetDelimiter(const Value: Char); begin FStrings.Delimiter := Value; end; procedure TStringListInterfaced.SetStrictDelimiter(const Value: Boolean); begin FStrings.StrictDelimiter := Value; end; procedure TStringListInterfaced.SetText(const Value: string); begin FStrings.Text := Value; end; procedure TStringListInterfaced.SetValue(const Name, Value: string); begin FStrings.Values[Name] := Value; end; procedure TStringListInterfaced.Add(const s: string); begin FStrings.Add(s); end; procedure TStringListInterfaced.AddIfNotEmpty(const s: string); begin if Trim(s) <> '' then FStrings.Add(s); end; procedure TStringListInterfaced.AddObject(const s: string; obj: integer); begin AddObject(s, TObject(obj)); end; procedure TStringListInterfaced.AddObject(const s: string; obj: TObject); begin FStrings.AddObject(s, obj); end; procedure TStringListInterfaced.Add(const FormatStr: string; const Args: array of const); begin FStrings.Add(Format(FormatStr, Args)); end; procedure TStringListInterfaced.AddStrings(Strings: TStrings); begin FStrings.AddStrings(Strings); end; procedure TStringListInterfaced.AddTo(dest: ExceptionWithDetails); begin EnsureNotNull(dest, 'dest'); dest.AddDetails(FStrings); end; procedure TStringListInterfaced.BeginUpdate; begin FStrings.BeginUpdate(); end; procedure TStringListInterfaced.AddTo(dest: TStrings); begin EnsureNotNull(dest, 'dest'); dest.AddStrings(FStrings); end; procedure TStringListInterfaced.AddStrings(Strings: IStringListInterface); begin FStrings.AddStrings(Strings.OriginalStrings); end; function TStringListInterfaced.ToStringWithDelimiter(const delimiter: string): string; begin Result:= FStrings.ToStringWithDelimiter(delimiter); end; function TStringListInterfaced.Contains(const str: string): boolean; begin Result := FStrings.IndexOf(str) >= 0; end; function TStringListInterfaced.ContainsValue(const valueName: string): boolean; begin if Trim(valueName)= '' then Result := False else Result := FStrings.IndexOfName(valueName) >= 0; end; function TStringListInterfaced.GetName(Index: Integer): string; begin Result := FStrings.Names[Index]; end; { TEsRegistry } constructor TEsRegistry.Create(const rootKeyName: string; canWrite: boolean); begin FRegistry:= TRegistry.Create(); FRegistry.RootKey:= HKEY_CURRENT_USER; FKeyOpened := FRegistry.OpenKey(rootKeyName, canWrite); end; destructor TEsRegistry.Destroy; begin if FKeyOpened then FRegistry.CloseKey(); FRegistry.Free(); inherited; end; function TEsRegistry.NormalizeName(const name: string): string; begin EnsureNotEmpty(name, 'name'); Result:= ReplaceText(Name, '.', '_'); end; function TEsRegistry.TryReadBoolean(const Name: string; out value: boolean): boolean; var tmp: string; begin value:= False; Result:= TryReadString(Name, tmp); if Result then Result:= TryStrToBool(tmp, value); end; function TEsRegistry.ReadBoolean(const Name: string; defaultValue: boolean): boolean; begin if not TryReadBoolean(Name, Result) then Result:= defaultValue; end; function TEsRegistry.TryReadInteger(const Name: string; out value: Integer): boolean; var tmp: string; begin value:= 0; Result:= TryReadString(Name, tmp); if Result then Result:= TryStrToInt(tmp, value); end; function TEsRegistry.ReadInteger(const Name: string; aMin, aMax, defaultValue: Integer): Integer; var tmp: Integer; begin if TryReadInteger(name, Result) then begin if aMin > aMax then begin tmp:= aMin; aMin:= aMax; aMax:= tmp; end; if (Result< aMin) or (Result > aMax) then Result:= defaultValue; end else Result:= defaultValue; end; function TEsRegistry.ReadInteger(const Name: string; defaultValue: Integer): Integer; begin if not TryReadInteger(name, Result) then Result:= defaultValue; end; function TEsRegistry.ReadString(const Name, defaultValue: string): string; begin if not TryReadString(Name, Result) then Result:= defaultValue; end; function TEsRegistry.TryReadString(const Name: string; out value: string): boolean; var newName: string; begin newName:= NormalizeName(Name); Result:= FRegistry.ValueExists(newName); if (Result) then try value:= FRegistry.ReadString(newName); except on ERegistryException do value := '' end else value:= ''; end; procedure TEsRegistry.WriteString(const Name, Value: string); var newName: string; begin newName:= NormalizeName(Name); FRegistry.WriteString(newName, Value); end; procedure TEsRegistry.WriteStringsByComma(const name: string; Value: IStringListInterface); begin EnsureNotNull(Value, 'Value'); WriteString(name, Value.CommaText); end; function TEsRegistry.TryReadStringsByComma(const name: string): IStringListInterface; var tmp: string; begin tmp := ''; if TryReadString(name, tmp) then begin Result:= TStringListInterfaced.Create(); Result.CommaText := tmp; end else Result:= nil; end; procedure TEsRegistry.WriteAsString(const Name: string; Value: Integer); begin WriteString(Name, IntToStr(Value)); end; procedure TEsRegistry.WriteAsString(const Name: string; Value: boolean); begin WriteString(Name, BoolToStr(Value, True)); end; procedure TEsRegistry.ReadChecked(item: TMenuItem); var b: boolean; begin EnsureNotNull(item, 'item = nil'); EnsureNotEmpty(item.Name, 'item.Name is empty'); if TryReadBoolean(Format('%s.Checked', [item.Name]), b) then item.Checked:= b; end; procedure TEsRegistry.WriteChecked(item: TMenuItem); begin EnsureNotNull(item, 'item = nil'); EnsureNotEmpty(item.Name, 'item.Name is empty'); WriteAsString(Format('%s.Checked', [item.Name]), item.Checked); end; { TDateTimeProviderSimple } function TDateTimeProviderSimple.GetNowAstroTime: TDateTime; var TZ: TTimeZoneInformation; currentDaylight: DWORD; daylightChangeAllowed: boolean; begin currentDaylight:= GetTimeZoneInformationWithException(TZ); daylightChangeAllowed := (currentDaylight in [TIME_ZONE_ID_STANDARD, TIME_ZONE_ID_DAYLIGHT]) and (TZ.DaylightBias <> 0) and (TZ.StandardDate.wMonth > 0) and (TZ.DaylightDate.wMonth > 0); Result := Now; if (daylightChangeAllowed) and (currentDaylight = TIME_ZONE_ID_DAYLIGHT) then Result := IncMinute(Result, TZ.DaylightBias);//DaylightBias в Windows отрицательный, потому + end; { TSmartPointer<T> } constructor TSmartPointer<T>.Create; begin inherited Create; FValue := T.Create; end; { TSmartPointer2<T> } constructor TSmartPointer2<T>.Create(AValue: T); begin inherited Create; FValue := AValue; end; destructor TSmartPointer2<T>.Destroy; begin FValue.Free; inherited; end; function TSmartPointer2<T>.Invoke: T; begin Result := FValue; end; { TFakeInterfaceObject } class constructor TFakeInterfaceObject.ClassCreate; begin FInstance:= TFakeInterfaceObject.Create(); OnUnitFinalization := UnitFinalizationWithoutThreads; end; class function TFakeInterfaceObject.GetInstance: TFakeInterfaceObject; begin Result := FInstance; end; class procedure TFakeInterfaceObject.UnitFinalizationWithoutThreads; begin FreeAndNil(FInstance); end; function TFakeInterfaceObject.QueryInterface(const IID: TGUID; out Obj): HResult; begin Result := E_NOINTERFACE; end; function TFakeInterfaceObject._AddRef: Integer; begin Result := -1; end; function TFakeInterfaceObject._Release: Integer; begin Result := -1; end; { Nullable<T> } constructor Nullable<T>.Create(AValue: T); begin FValue := AValue; FHasValue := TFakeInterfaceObject.GetInstance(); end; class function Nullable<T>.CreateEmpty(): Nullable<T>; begin Result.FHasValue := nil; end; class operator Nullable<T>.Equal(const ALeft, ARight: Nullable<T>): Boolean; var Comparer: IEqualityComparer<T>; begin if ALeft.HasValue and ARight.HasValue then begin Comparer := TEqualityComparer<T>.Default; Result := Comparer.Equals(ALeft.Value, ARight.Value); end else Result := ALeft.HasValue = ARight.HasValue; end; class operator Nullable<T>.NotEqual(const ALeft, ARight: Nullable<T>): Boolean; var Comparer: IEqualityComparer<T>; begin if ALeft.HasValue and ARight.HasValue then begin Comparer := TEqualityComparer<T>.Default; Result := not Comparer.Equals(ALeft.Value, ARight.Value); end else Result := ALeft.HasValue <> ARight.HasValue; end; class operator Nullable<T>.Explicit(Value: Nullable<T>): T; begin Result := Value.Value; end; function Nullable<T>.Assigned: boolean; begin Result := FHasValue <> nil; end; function Nullable<T>.GetValue: T; begin if not HasValue then raise ENullableNotAssignedException.Create('Invalid operation, Nullable type has no value'); Result := FValue; end; function Nullable<T>.GetValueOrDefault: T; begin if HasValue then Result := FValue else Result := Default(T); end; function Nullable<T>.GetValueOrDefault(Default: T): T; begin if HasValue then Result := FValue else Result := Default end; class operator Nullable<T>.Implicit(Value: Nullable<T>): T; begin Result := Value.Value; end; class operator Nullable<T>.Implicit(Value: T): Nullable<T>; begin Result := Nullable<T>.Create(Value); end; { TNamedFormat } constructor TNamedFormat.DoCreate(aMode: TFormatMode; const aformatStr: string); begin inherited Create(); EnsureNotEmpty(aformatStr, 'aformatStr'); Self.FFormatMode := aMode; Self.FFormatString := aformatStr; end; constructor TNamedFormat.Create(const formatStr: string; mode: TFormatMode = fmDefault); begin DoCreate(mode, formatStr); end; constructor TNamedFormat.ForSql(const resourceName: string); begin FromResource(resourceName, fmSql); end; constructor TNamedFormat.FromResource(const resourceName: string; mode: TFormatMode = fmDefault); begin DoCreate(mode, LoadStringFromRcData(resourceName)); end; destructor TNamedFormat.Destroy; begin SetLength(FParameters, 0); inherited; end; function TNamedFormat.Format(): string; var f: TFormatParameter; params: ISmartPointer<TList<TFormatParameter>>; begin Result := Self.FFormatString; // параметры надо обрабатывать в порядке уменьшения длины, // в противном случае возможно коллизии при вхождении имени одного параметра в другой, // например сначала отработает ID_PP, а потом ID_PP_TMP обработается неправильно params := TSmartPointer<TList<TFormatParameter>>.Create(); params.AddRange(Self.FParameters); params.Sort(TComparer<TFormatParameter>.Construct( function(const Left, Right: TFormatParameter): Integer begin Result := -CompareValue(Length(Left.Name), Length(Right.Name)); end)); for f in params do Result := f.Format(Self, Result); end; function TNamedFormat.DoAdd(var parameter: TFormatParameter): INamedFormat; var f: TFormatParameter; begin Result := Self; for f in FParameters do if LowerCase(f.Name) = LowerCase(parameter.Name) then raise EInternalException.CreateFmt('param with name = %s is already added', [parameter.Name]); SetLength(FParameters, Length(FParameters) + 1); FParameters[High(FParameters)] := parameter; end; function TNamedFormat.Add(const name: string; Value: Integer): INamedFormat; var tmp: TFormatParameter; begin tmp := TFormatParameter.Int(name, Value); Result := DoAdd(tmp); end; function TNamedFormat.Add(const name, Value: string): INamedFormat; var tmp: TFormatParameter; begin tmp := TFormatParameter.Str(name, Value); Result := DoAdd(tmp); end; function TNamedFormat.Add(const name: string; Value: TDateTime): INamedFormat; var tmp: TFormatParameter; begin tmp := TFormatParameter.DT(name, Value); Result := DoAdd(tmp); end; function TNamedFormat.AddNull(const name: string): INamedFormat; var tmp: TFormatParameter; begin tmp := TFormatParameter.Null(name); Result := DoAdd(tmp); end; { TNamedFormat.TFormatParameter } class function TNamedFormat.TFormatParameter.DT(const aName: string; const Value: TDateTime): TFormatParameter; begin EnsureNotEmpty(aName, 'aName'); Result.FName := aName; Result.FDateTimeValue := Value; end; function TNamedFormat.TFormatParameter.Format(parent: TNamedFormat; const format: string): string; var oldValue: string; newValue: Nullable<string>; begin if FIntValue.HasValue then begin newValue := IntToStr(FIntValue.Value); if FIntValue.Value < 0 then newValue := '(' + newValue.Value + ')'; end else if FStringValue.HasValue then begin if parent.FormatMode = fmSql then newValue := AnsiQuotedStr(FStringValue.Value, '''') else newValue := FStringValue.Value; end else if FDateTimeValue.HasValue then newValue := QuotedStr(FormatDateTime('YYYYMMDD HH:NN:SS.ZZZ', FDateTimeValue.Value)); if not newValue.HasValue then begin if parent.FormatMode = fmSql then newValue := 'NULL' else newValue := ''; end; oldValue := parent.FormatMode.GetDefaultPrefix() + Name; Result := StringReplace(format, oldValue, newValue.Value, parent.FormatMode.GetReplaceFlags()); end; class function TNamedFormat.TFormatParameter.Int(const aName: string; const Value: Integer): TFormatParameter; begin EnsureNotEmpty(aName, 'aName'); Result.FName := aName; Result.FIntValue := Value; end; class function TNamedFormat.TFormatParameter.Null(const aName: string): TFormatParameter; begin EnsureNotEmpty(aName, 'aName'); Result.FName := aName; end; class function TNamedFormat.TFormatParameter.Str(const aName, Value: string): TFormatParameter; begin EnsureNotEmpty(aName, 'aName'); Result.FName := aName; Result.FStringValue := Value; end; { TNamedFormat.TFormatModeHelper } function TNamedFormat.TFormatModeHelper.GetDefaultPrefix: string; begin case Self of fmSql: Result := '@'; else Result := '$'; end; end; function TNamedFormat.TFormatModeHelper.GetReplaceFlags: TReplaceFlags; begin case Self of fmSql: Result := [rfReplaceAll, rfIgnoreCase]; else Result := [rfReplaceAll]; end; end; { TStringNormalizer } class constructor TStringNormalizer.ClassCreate; begin AnyNumber:= TRegEx.Create('\d+', [roCompiled]); WhiteSpaces:= TRegEx.Create('\s+', [roCompiled]); end; class function TStringNormalizer.CompareStrings(const str1, str2: string): Integer; begin Result := AnsiCompareText(NormalizeStringForCompare(str1), NormalizeStringForCompare(str2)); end; class function TStringNormalizer.DoReplace(const Match: TMatch): string; var tmp: Int64; begin Result := Match.Value; if TryStrToInt64(Result, tmp) then Result := Format('%.10d', [tmp]); end; class function TStringNormalizer.NormalizeStringForCompare(const value: string): string; begin if Trim(value) = '' then begin Result := value; exit; end; Result := AnyNumber.Replace(value, DoReplace); Result := WhiteSpaces.Replace(Result, ''); end; initialization finalization if Assigned(TFakeInterfaceObject.OnUnitFinalization) then TFakeInterfaceObject.OnUnitFinalization(); end.
(* MPP: MM, 2020-04-29 *) (* ------ *) (* MiniPascal parser. *) (* ========================================================================= *) UNIT MPP; INTERFACE VAR success: BOOLEAN; PROCEDURE S; IMPLEMENTATION USES MPL; FUNCTION SyIsNot(expected: Symbol): BOOLEAN; BEGIN IF (sy <> expected) THEN BEGIN success := FALSE; END; (* IF *) SyIsNot := NOT success; END; (* SyIsNot *) PROCEDURE MP; FORWARD; PROCEDURE VarDecl; FORWARD; PROCEDURE StatSeq; FORWARD; PROCEDURE Stat; FORWARD; PROCEDURE Expr; FORWARD; PROCEDURE Term; FORWARD; PROCEDURE Fact; FORWARD; PROCEDURE S; BEGIN (* S *) success := TRUE; MP; IF (NOT success) THEN Exit; IF (SyIsNot(eofSy)) THEN Exit; END; (* S *) PROCEDURE MP; BEGIN (* MP *) IF (SyIsNot(programSy)) THEN Exit; NewSy; IF (SyIsNot(ident)) THEN Exit; NewSy; IF (SyIsNot(semcolSy)) THEN Exit; NewSy; IF (sy = varSy) THEN BEGIN VarDecl; IF (NOT success) THEN Exit; END; (* IF *) IF (SyIsNot(beginSy)) THEN Exit; NewSy; StatSeq; IF (NOT success) THEN Exit; IF (SyIsNot(endSy)) THEN Exit; NewSy; IF (SyIsNot(dotSy)) THEN Exit; NewSy; END; (* MP *) PROCEDURE VarDecl; BEGIN (* VarDecl *) IF (SyIsNot(varSy)) THEN Exit; NewSy; IF (SyIsNot(ident)) THEN Exit; NewSy; WHILE (sy = commaSy) DO BEGIN NewSy; IF (SyIsNot(ident)) THEN Exit; NewSy; END; (* WHILE *) IF (SyIsNot(colonSy)) THEN Exit; NewSy; IF (SyIsNot(integerSy)) THEN Exit; NewSy; IF (SyIsNot(semcolSy)) THEN Exit; NewSy; END; (* VarDecl *) PROCEDURE StatSeq; BEGIN (* StatSeq *) Stat; IF (NOT success) THEN Exit; WHILE (sy = semcolSy) DO BEGIN NewSy; Stat; IF (NOT success) THEN Exit; END; (* WHILE *) END; (* StatSeq *) PROCEDURE Stat; BEGIN (* Stat *) CASE sy OF ident: BEGIN NewSy; IF (SyIsNot(assignSy)) THEN Exit; NewSy; Expr; IF (NOT success) THEN Exit; END; readSy: BEGIN NewSy; IF (SyIsNot(leftParSy)) THEN Exit; NewSy; IF (SyIsNot(ident)) THEN Exit; NewSy; IF (SyIsNot(rightParSy)) THEN Exit; NewSy; END; writeSy: BEGIN NewSy; IF (SyIsNot(leftParSy)) THEN Exit; NewSy; Expr; IF (NOT success) THEN Exit; NewSy; IF (SyIsNot(rightParSy)) THEN Exit; NewSy; END; END; END; (* Stat *) (* Expr = Term { "+" | "-" Term] . *) PROCEDURE Expr; BEGIN (* Expr *) Term; IF (NOT success) THEN Exit; WHILE ((sy = plusSy) OR (sy = minusSy)) DO BEGIN CASE sy OF plusSy: BEGIN NewSy; Term; IF (NOT success) THEN Exit; END; minusSy: BEGIN NewSy; Term; IF (NOT success) THEN Exit; END; END; (* CASE *) END; (* WHILE *) END; (* Expr *) (* Term = Fact { "*" Fact | */* Fact} . *) PROCEDURE Term; BEGIN (* Term *) Fact; IF (NOT success) THEN Exit; WHILE ((sy = timesSy) OR (sy = divSy)) DO BEGIN CASE sy OF timesSy: BEGIN NewSy; Fact; IF (NOT success) THEN Exit; END; divSy: BEGIN NewSy; Fact; IF (NOT success) THEN Exit; END; END; (* CASE *) END; (* WHILE *) END; (* Term *) (* Fact = number | "(" Expr ")" . *) PROCEDURE Fact; BEGIN (* Fact *) CASE sy OF ident: BEGIN NewSy; END; number: BEGIN NewSy; END; leftParSy: BEGIN NewSy; Expr; IF (NOT success) THEN Exit; IF (SyIsNot(rightParSy)) THEN Exit; NewSy; END; ELSE BEGIN success := FALSE; Exit; END; (* ELSE *) END; (* CASE *) END; (* Fact *) BEGIN (* MPP *) END. (* MPP *)
unit TestDelphiNetDynamicArray; { This unit compiles but is not semantically meaningfull it is test cases for the code formatting utility Tests of the Delphi.net 'new' keyword for array creation from TridenT } interface implementation uses SysUtils; type TObjectDynArray = array of TObject; Procedure TabObjet(Args : array of TObject); var i: Integer; begin Writeln('Dans la procédure TabObjet'); for i := Low(Args) to High(Args) do WriteLn('L''élément ', I, ' est du type ', Args[i].GetType.FullName,' sa valeur est ''',Args[i],''''); ReadLn; end; procedure TabConst(A: array of const); var i: Integer; begin Writeln('Dans la procédure TabConst'); for i := Low(A) to High(A) do // WriteLn('Index ', I, ': ', A[i].GetType.FullName); WriteLn('L''élément ', I, ' est du type ', A[i].GetType.FullName,' sa valeur est ''',A[i],''''); ReadLn; end; procedure Test02; var X,Y: array[,] of Integer; // 2 dimensional array i,j: Integer; begin i := 2; j := 3; X := New(array[i,j] of Integer); // only size of 2x3 matrix X[0,0] := 1; X[0,1] := 2; X[0,2] := 3; X[1,0] := 4; X[1,1] := 5; X[1,2] := 6; // type and initializer list Y := New(array[,] of Integer, ((1,2,3), (4,5,6))); for i:=0 to 1 do for j:=0 to 2 do if X[i,j] <> Y[i,j] then writeln(i,j); writeln('done'); readln; end; // Déclare et initialise qq variables Var S1 : String='Une chaîne'; I : Integer=90; D1 : Double=5.6; D2 : Double=3.14159; Etat : Boolean=True; S2 : String='s'; TbObj : Array of TObject; begin // Passage d'un nombre de paramètre variable sans préciser le type, uniquement des constantes TabConst(['Une chaîne', 90, 5.6, 3.14159, True, 's']); // Passage d'un nombre paramètre variable sans préciser le type, mixte constantes et variables TabConst([S1, I, 5.6, D2, Etat, 's']); // Dans le second appel le type du 2 éme paramètre est différent // A la compilation 90 est vu comme un type Byte et I est de type Integer // Création dynamique d'un tableau TbObj:=New(TObjectDynArray,6); // La directive AutoBox permet d'éviter le transtypage explicite nécessaire pour chaque élément du tableau // Cette directive effectue implicitement le cast {$AutoBox on} // Renseigne le tableau avec des variables TbObj:= New(array[] of TObject, (S1, I, D1, D2, Etat, S2)); {$AutoBox off} TabObjet(TbObj); {$AutoBox on} // Renseigne le tableau avec des variables et des constantes TbObj:= New(array[] of TObject, (S1, I, 5.6, D2, Etat, 's')); {$AutoBox off} TabObjet(TbObj); end.
Program hello; (* File : HELLO.PAS *) (* menuliskan Hello ke layar *) begin writeln ('Hello, World!'); end.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit WSDLImpConst; {$IFNDEF VER150} {$INCLUDE 'CompVer.inc'} {$ENDIF} interface uses WSDLImpWriter, WSDLModelIntf; // This function is used in both the IDE's WSDL Importer Wizard and WSDLImp.exe to // to determine if the option is handled by the options page (Wizard) or is a code gen option (WSDLImp.exe) function IsOptionHandledByOptionsPage(const Flag: WSDLGenFlags): Boolean; {$IFDEF LINUX} { Linux linebreaks don't work in code previewer } const SLineBreak = #13#10; {$ENDIF} {$DEFINE USE_FREE_AND_NIL} type TIntfImplOption = (iiCBuilder, iiPascal, iiPascalIntf, iiPascalImpl, iiCBuilderIntf, iiCBuilderImpl); const fnOptionsFile = 'WSDLImp.ini'; sCommentDivider = '//---------------------------------------------------------------------------' + sLineBreak; { C++ specific constants } // Include statement of an Imported SOAP header // sInclude_WS = '#include "%s.h"' + sLineBreak; // Standard Include used in .CPP files // sStandardSourceInclude = '#pragma hdrstop' + sLineBreak + sLineBreak + '#include "%0:s.h"' + sLineBreak + sLineBreak; sStandardSourceIncludeVCL = '#include <vcl.h>' + sLineBreak + sStandardSourceInclude; sStandardSourceIncludeCLX = '#include <clx.h>' + sLineBreak + sStandardSourceInclude; sStandardSourceIncludeSystem = '#include <System.hpp>' + sLineBreak + sStandardSourceInclude; // Guard used in Headers // sHdrGuardBegin = '#ifndef %0:sH' + sLineBreak + '#define %0:sH' + sLineBreak + sLineBreak + '#include <System.hpp>' + sLineBreak + '#include <Soap.InvokeRegistry.hpp>' + sLineBreak + '#include <Soap.XSBuiltIns.hpp>' + sLineBreak; sClientHeaders = '#include <Soap.SOAPHTTPClient.hpp>' + sLineBreak + sLineBreak; sCppRemoteClass = '#if !defined(SOAP_REMOTABLE_CLASS)' + sLineBreak + '#define SOAP_REMOTABLE_CLASS __declspec(delphiclass)' + sLineBreak + '#endif' + sLineBreak; sCppIsOptn = '#if !defined(IS_OPTN)' + sLineBreak + '#define IS_OPTN 0x0001' + sLineBreak + '#endif' + sLineBreak; sCppIsUnbd = '#if !defined(IS_UNBD)' + sLineBreak + '#define IS_UNBD 0x0002' + sLineBreak + '#endif' + sLineBreak; sCppIsNlbl = '#if !defined(IS_NLBL)' + sLineBreak + '#define IS_NLBL 0x0004' + sLineBreak + '#endif' + sLineBreak; sCppIsUnql = '#if !defined(IS_UNQL)' + sLineBreak + '#define IS_UNQL 0x0008' + sLineBreak + '#endif' + sLineBreak; sCppIsAttr = '#if !defined(IS_ATTR)' + sLineBreak + '#define IS_ATTR 0x0010' + sLineBreak + '#endif' + sLineBreak; sCppIsText = '#if !defined(IS_TEXT)' + sLineBreak + '#define IS_TEXT 0x0020' + sLineBreak + '#endif' + sLineBreak; sCppIsAny = '#if !defined(IS_ANY)' + sLineBreak + '#define IS_ANY 0x0040' + sLineBreak + '#endif' + sLineBreak; sCppIsRef = '#if !defined(IS_REF)' + sLineBreak + '#define IS_REF 0x0080' + sLineBreak + '#endif' + sLineBreak; sCppIsQual = '#if !defined(IS_QUAL)' + sLineBreak + '#define IS_QUAL 0x0100' + sLineBreak + '#endif' + sLineBreak; sCppIsOut = '#if !defined(IS_OUT)' + sLineBreak + '#define IS_OUT 0x0200' + sLineBreak + '#endif' + sLineBreak; sHdrGuardEnd = sLineBreak + '#endif // %0:sH' + sLineBreak; // Namespace block in Headers // sNamespaceHdrBegin = sLineBreak + 'namespace NS_%0:s {' + sLineBreak + sLineBreak; sNamespaceHdrEnd = sLineBreak + '}; // NS_%0:s' + sLineBreak + sLineBreak; sNamespaceUsing = '#if !defined(NO_IMPLICIT_NAMESPACE_USE)' + sLineBreak + 'using namespace NS_%0:s;' + sLineBreak + '#endif' + sLineBreak + sLineBreak; // Namespace block in Source // sNamespaceSrcBegin = 'namespace NS_%s {' + sLineBreak; sNamespaceSrcEnd = sLineBreak + '}; // NS_%s' + sLineBreak; sInterfaceDecl = '__interface INTERFACE_UUID("%s") %s : public %s' + sLineBreak + '{' + sLineBreak + 'public:' + sLineBreak; sInterfaceDeclEnd = '};' + sLineBreak + 'typedef DelphiInterface<%0:s> _di_%0:s;' + sLineBreak + sLineBreak; sIntfFactoryDecl = '_di_%0:s Get%0:s(bool useWSDL=false, System::String addr= System::String(), Soaphttpclient::THTTPRIO* HTTPRIO=0);' + sLineBreak + sLineBreak; sImplDecl = 'class T%0:sImpl : public InvokeRegistry::TInvokableClass, public %0:s'+ sLineBreak + '{' + sLineBreak + 'public:' + sLineBreak + sLineBreak + ' /* %0:s */' + sLineBreak; sImplOther = sLineBreak + ' /* IUnknown */' + sLineBreak + ' HRESULT STDMETHODCALLTYPE QueryInterface(const GUID& IID, void **Obj)' + sLineBreak + ' { return GetInterface(IID, Obj) ? S_OK : E_NOINTERFACE; }' + sLineBreak + ' ULONG STDMETHODCALLTYPE AddRef() { return System::TInterfacedObject::_AddRef(); }' + sLineBreak + ' ULONG STDMETHODCALLTYPE Release(){ return System::TInterfacedObject::_Release(); }' + sLineBreak; sImplEnd = '};' + sLineBreak + sLineBreak; sMethImpl = '{' + sLineBreak + ' /* TODO : Implement WebService method %s */' + sLineBreak + '%s}' + sLineBreak + sLineBreak; sReturnDecl = ' %s %s;' + sLineBreak; sReturnTempl = ' return %s;' + sLineBreak; sReturnNewTempl = ' return new %s();' + sLineBreak; sFactoryImpl = '_di_%0:s Get%0:s(bool useWSDL, System::String addr, Soaphttpclient::THTTPRIO* HTTPRIO)' + sLineBreak + '{' + sLineBreak + ' static const char* defWSDL= "%1:s";' + sLineBreak + ' static const char* defURL = "%2:s";' + sLineBreak + ' static const char* defSvc = "%3:s";' + sLineBreak + ' static const char* defPrt = "%4:s";' + sLineBreak + ' if (addr=="")' + sLineBreak + ' addr = useWSDL ? defWSDL : defURL;' + sLineBreak + ' Soaphttpclient::THTTPRIO* rio = HTTPRIO ? HTTPRIO : new Soaphttpclient::THTTPRIO(0);' + sLineBreak + ' if (useWSDL) {' + sLineBreak + ' rio->WSDLLocation = addr;' + sLineBreak + ' rio->Service = defSvc;' + sLineBreak + ' rio->Port = defPrt;' + sLineBreak + ' } else {' + sLineBreak + ' rio->URL = addr;' + sLineBreak + ' }' + sLineBreak + ' _di_%0:s service;' + sLineBreak + ' rio->QueryInterface(service);' + sLineBreak + ' if (!service && !HTTPRIO)' + sLineBreak + ' delete rio;' + sLineBreak + ' return service;' + sLineBreak + '}' + sLineBreak + sLineBreak; sInitRoutineBeg = 'static void RegTypes()' + sLineBreak + '{' + sLineBreak; sInitRoutineEnd = '}' + sLineBreak + '#pragma startup RegTypes 32' + sLineBreak; sRegInterface1 = ' InvRegistry()->RegisterInterface(__delphirtti(%s), L"%s", L"%s");' + sLineBreak; sRegInterface2 = ' InvRegistry()->RegisterInterface(__delphirtti(%s), L"%s", L"%s",' + sLineBreak + ' "", L"%s");' + sLineBreak; sRegSOAPAction = ' InvRegistry()->RegisterDefaultSOAPAction(__delphirtti(%s), L"%s");' + sLineBreak; sRegAllSOAPAction = ' InvRegistry()->RegisterAllSOAPActions(__delphirtti(%s), L"%s");' + sLineBreak; {$IFDEF UNICODE} sRegParamNames = ' InvRegistry()->RegisterReturnParamNames(__delphirtti(%s), L"%s");' + sLineBreak; {$ELSE} sRegParamNames = ' InvRegistry()->RegisterReturnParamNames(__delphirtti(%s), "%s");' + sLineBreak; {$ENDIF} sRegInvokeOptDoc = ' InvRegistry()->RegisterInvokeOptions(__delphirtti(%s), ioDocument);' + sLineBreak; sRegInvokeOptLit = ' InvRegistry()->RegisterInvokeOptions(__delphirtti(%s), ioLiteral);' + sLineBreak; sRegInvokeOptSOAP12= ' InvRegistry()->RegisterInvokeOptions(__delphirtti(%s), ioSOAP12);' + sLineBreak; {$IFDEF UNICODE} sRegMethodRenamed = ' InvRegistry()->RegisterExternalMethName(__delphirtti(%s), L"%s", L"%s");' + sLineBreak; sRegParamRenamed = ' InvRegistry()->RegisterExternalParamName(__delphirtti(%s), L"%s", L"%s", L"%s");' + sLineBreak; sRegMemberRenamed = ' RemClassRegistry()->RegisterExternalPropName(__typeinfo(%s), L"%s", L"%s");' + sLineBreak; sRegMemberRenamedE = ' RemClassRegistry()->RegisterExternalPropName(GetClsMemberTypeInfo(__typeinfo(%0:s_TypeInfoHolder)), L"%s", L"%s");' + sLineBreak; {$ELSE} sRegMethodRenamed = ' InvRegistry()->RegisterExternalMethName(__delphirtti(%s), "%s", L"%s");' + sLineBreak; sRegParamRenamed = ' InvRegistry()->RegisterExternalParamName(__delphirtti(%s), "%s", "%s", L"%s");' + sLineBreak; sRegMemberRenamed = ' RemClassRegistry()->RegisterExternalPropName(__typeinfo(%s), "%s", L"%s");' + sLineBreak; sRegMemberRenamedE = ' RemClassRegistry()->RegisterExternalPropName(GetClsMemberTypeInfo(__typeinfo(%0:s_TypeInfoHolder)), "%s", L"%s");' + sLineBreak; {$ENDIF} sRegHolderTypeInfo1= ' RemClassRegistry()->RegisterXSInfo(GetClsMemberTypeInfo(__typeinfo(%0:s_TypeInfoHolder)), L"%1:s", L"%0:s");' + sLineBreak; sRegHolderTypeInfo2= ' RemClassRegistry()->RegisterXSInfo(GetClsMemberTypeInfo(__typeinfo(%0:s_TypeInfoHolder)), L"%1:s", L"%0:s", L"%2:s");' + sLineBreak; sRegArrayTypeInfo1 = ' RemClassRegistry()->RegisterXSInfo(__delphirtti(%s), L"%s", L"%s");' + sLineBreak; sRegArrayTypeInfo2 = ' RemClassRegistry()->RegisterXSInfo(__delphirtti(%s), L"%s", L"%s", L"%s");' + sLineBreak; sRegClassSerOptsCpp= ' RemClassRegistry()->RegisterSerializeOptions(__classid(%s), (TSerializationOptions() %s));' + sLineBreak; sRegInfoSerOptsCpp = ' RemClassRegistry()->RegisterSerializeOptions(__delphirtti(%s), (TSerializationOptions() %s));' + sLineBreak; sRegClass1 = ' RemClassRegistry()->RegisterXSClass(__classid(%s), L"%s", L"%s");' + sLineBreak; sRegClass2 = ' RemClassRegistry()->RegisterXSClass(__classid(%s), L"%s", L"%s", L"%s");' + sLineBreak; sRegImpl = ' InvRegistry()->RegisterInvokableClass(__classid(T%sImpl));' + sLineBreak; sRegHeaderClass = ' InvRegistry()->RegisterHeaderClass(__classid(T%sImpl), L"%s");' + sLineBreak; sProxyClassDecl = 'class %0:s_Proxy : public Soaphttpclient::THTTPRIO, public virtual %0:s {'+ sLineBreak; sTypeInfoHolder = 'class %0:s_TypeInfoHolder : public TObject {'+ sLineBreak + ' %0:s __instanceType;' + sLineBreak + 'public:' + sLineBreak + '__published:' + sLineBreak + ' __property %0:s __propType = { read=__instanceType };' + sLineBreak + '};' + sLineBreak; sStoredAsAttribute = ', stored = AS_ATTRIBUTE'; sStoredAsUnbounded = ', stored = AS_UNBOUNDED'; sRemoteBaseClass = 'TRemotable'; sRemoteClassDecl = 'class %0:s : public %1:s {' + sLineBreak + 'private:' + sLineBreak; sRemoteClassPublic = 'public:' + sLineBreak; sRemoteClassPublish= '__published:' + sLineBreak; sRemoteClassCtr = ' __fastcall %s();' + sLineBreak; sRemoteClassDtr = ' __fastcall ~%s();' + sLineBreak; sMemberField = ' %-15s F%s;'; sSpecifiedField = ' %-15s F%s_Specified;'; sSpecifiedStoredProcF = ', stored = F%s_Specified'; sSpecifiedStoredProcI = ', stored = %s_Specified'; sRemoteClassSetter = ' void __fastcall Set%0:s(%1:s _prop_val)' + sLineBreak + ' { F%0:s = _prop_val; }' + sLineBreak; sRemoteClassSetter2= ' void __fastcall Set%0:s(%1:s _prop_val;)' + sLineBreak + ' { F%0:s = _prop_val; F%0:s_Specified = true; }'+ sLineBreak; sRemoteClassGetter = ' %1:s __fastcall Get%0:s()'+ sLineBreak + ' { return F%0:s; }' + sLineBreak; sRemoteClassSetterIdx = ' void __fastcall Set%0:s(int Index, %1:s _prop_val)' + sLineBreak + ' { F%0:s = _prop_val; }' + sLineBreak; sRemoteClassSetterIdx2 = ' void __fastcall Set%0:s(int Index, %1:s _prop_val)' + sLineBreak + ' { F%0:s = _prop_val; F%0:s_Specified = true; }' + sLineBreak; sRemoteClassGetterIdx = ' %1:s __fastcall Get%0:s(int Index)'+ sLineBreak + ' { return F%0:s; }' + sLineBreak; sSpecifiedStoredProcIdx = ' bool __fastcall %0:s_Specified(int Index)' + sLineBreak + ' { return F%0:s_Specified; } ' + sLineBreak; sRemoteClsCtrImpl = '__fastcall %0:s::%0:s()' + sLineBreak + '{' + sLineBreak + '%1:s' + '}' + sLineBreak; sRemoteClsDtrImpl = '__fastcall %0:s::~%0:s()' + sLineBreak + '{' + sLineBreak + '%1:s' + '}' + sLineBreak; sDefaultArrayImpl = ' int GetLength() const { return F%0:s.get_length(); }' + sLineBreak + ' void SetLength(int len) { F%0:s.set_length(len); }' + sLineBreak; sDefaultArrayImplIdx=' int GetLength() const { return F%0:s.get_length(); }' + sLineBreak + ' void SetLength(int len) { F%0:s_Specified = true; F%0:s.set_length(len); }' + sLineBreak; sDefaultArrayImplOp= ' %1:s& operator[](int index) { return F%0:s[index]; }' + sLineBreak + ' __property int Len = { read=GetLength, write=SetLength };' + sLineBreak; sDefaultArrayImplOpIdx = ' %1:s& operator[](int index) { F%0:s_Specified = true; return F%0:s[index]; }' + sLineBreak + ' __property int Len = { read=GetLength, write=SetLength };' + sLineBreak; sCtrInitLine = '%s'+ ' %s= new %s();' + sLineBreak; sDtrClsLine = '%s'+ ' delete %s;' + sLineBreak; sDtrArrayLine = '%s'+ ' for(int i=0; i<%1:s.Length; i++)' + sLineBreak + ' if (%1:s[i])' + sLineBreak + ' delete %1:s[i];' + sLineBreak; sCtrDtrEnd = '}' + sLineBreak; sRemoteClassDeclEnd= '};' + sLineBreak; sOperationInfo = ' // %s'; sCppComment = '/* %s */'; sPasComment = '{ %s }'; sLineComment = '// %s'; sCppCommentIdent = ' /* %s */'; sPasCommentIdent = ' { %s }'; sPasCommentLF = '{ %s }' + sLineBreak; sTypeError = '[TYPE ERROR: %s]'; sPortTypeSignature = 'Name(%s), Namespace(%s), BindingName(%s), Service(%s), Port(%s)'; { Pascal constants } sUDDIOperator = 'sUDDIOperator'; sUDDIBindingKey = 'sUDDIBindingKey'; sUnitBeg = 'unit %0:s;' + sLineBreak + sLineBreak + 'interface' + sLineBreak + sLineBreak + 'uses Soap.InvokeRegistry, Soap.SOAPHTTPClient, System.Types, Soap.XSBuiltIns%s;' + sLineBreak; sConstBeg = sLineBreak + 'const' + sLineBreak; { NOTE: This is temporary. Ideally it would be defined in the SOAP runtime, same as 'AS_ATTRIBUTE' but that would require an interface change } sPasIsOptn = ' IS_OPTN = $0001;' + sLineBreak; sPasIsUnbd = ' IS_UNBD = $0002;' + sLineBreak; sPasIsNlbl = ' IS_NLBL = $0004;' + sLineBreak; sPasIsUnql = ' IS_UNQL = $0008;' + sLineBreak; sPasIsAttr = ' IS_ATTR = $0010;' + sLineBreak; sPasIsText = ' IS_TEXT = $0020;' + sLineBreak; sPasIsAny = ' IS_ANY = $0040;' + sLineBreak; sPasIsRef = ' IS_REF = $0080;' + sLineBreak; sPasIsQual = ' IS_QUAL = $0100;' + sLineBreak; { NOTE: $0200 is taken for C++ IS_OUT } sIS_OPTN = 'IS_OPTN'; sIS_UNBD = 'IS_UNBD'; sIS_NLBL = 'IS_NLBL'; sIS_UNQL = 'IS_UNQL'; sIS_ATTR = 'IS_ATTR'; sIS_TEXT = 'IS_TEXT'; sIS_ANY = 'IS_ANY'; sIS_REF = 'IS_REF'; sIS_QUAL = 'IS_QUAL'; sIS_OUT = 'IS_OUT'; sUDDIConst = ' '+sUDDIOperator+' = ''%s'';' + sLineBreak + ' '+sUDDIBindingKey+' = ''%s'';' + sLineBreak; sTypeBeg = sLineBreak + 'type' + sLineBreak + sLineBreak; sSOAPMidas = ', SOAPMidas'; sUnitImpl = sLineBreak + sLineBreak + 'implementation' + sLineBreak; sUnitUses = ' uses System.SysUtils;' + sLineBreak + sLineBreak; sUnitType = 'type' + sLineBreak + sLineBreak; sRegProcPrefix = 'RegisterTypeProc'; sRegProcStart = 'procedure '+sRegProcPrefix+'%d;' + sLineBreak + 'begin' + sLineBreak; sRegProcEnd = 'end;' + sLineBreak + sLineBreak; sRegProcCall = ' '+sRegProcPrefix+'%d;' + sLineBreak; sUnitInit = 'initialization' + sLineBreak; sUnitEnd = sLineBreak + 'end.'; sRemoteClassDeclPas = ' %0:s = class(%1:s)' + sLineBreak + ' private' + sLineBreak; sRemoteClassPublicPas = ' public' + sLineBreak; sRemoteClassPublishPas = ' published' + sLineBreak; sRemoteClassCtrPas = ' constructor Create; override;' + sLineBreak; sRemoteClassDtrPas = ' destructor Destroy; override;' + sLineBreak; sRemoteClassSetterPas = ' procedure Set%0:s(const A%1:s: %1:s);' + sLineBreak; sRemoteClassGetterPas = ' function Get%0:s: %1:s;' + sLineBreak; sRemoteClassSetterPasIdx = ' procedure Set%0:s(Index: Integer; const A%1:s: %1:s);' + sLineBreak; sRemoteClassGetterPasIdx = ' function Get%0:s(Index: Integer): %1:s;' + sLineBreak; sSpecifiedFieldPas = ' F%s_Specified: boolean;'; sSpecifiedStoredProcPasF = ' stored F%s_Specified'; sSpecifiedStoredProcPasI = ' stored %s_Specified'; sSpecifiedStoredProcDeclPasIdx = ' function %s_Specified(Index: Integer): boolean;' + sLineBreak; sSpecifiedStoredProcImplPasIdx= 'function %0:s.%1:s_Specified(Index: Integer): boolean;' + sLineBreak + 'begin' + sLineBreak + ' Result := F%1:s_Specified;' + sLineBreak + 'end;' + sLineBreak; sRemoteClassSetterImplPas = 'procedure %0:s.Set%1:s(const A%2:s: %2:s);' + sLineBreak + 'begin' + sLineBreak + ' F%1:s := A%2:s;' + sLineBreak + 'end;' + sLineBreak; sRemoteClassSetterImplPas2= 'procedure %0:s.Set%1:s(const A%2:s: %2:s);' + sLineBreak + 'begin' + sLineBreak + ' F%1:s := A%2:s;' + sLineBreak + ' F%1:s_Specified := True;' + sLineBreak + 'end;' + sLineBreak; sRemoteClassGetterImplPas = 'function %0:s.Get%1:s: %2:s;' + sLineBreak + 'begin' + sLineBreak + ' Result := F%1:s;' + sLineBreak + 'end;' + sLineBreak; sRemoteClassSetterImplPasIdx = 'procedure %0:s.Set%1:s(Index: Integer; const A%2:s: %2:s);' + sLineBreak + 'begin' + sLineBreak + ' F%1:s := A%2:s;' + sLineBreak + 'end;' + sLineBreak; sRemoteClassSetterImplPasIdx2= 'procedure %0:s.Set%1:s(Index: Integer; const A%2:s: %2:s);' + sLineBreak + 'begin' + sLineBreak + ' F%1:s := A%2:s;' + sLineBreak + ' F%1:s_Specified := True;' + sLineBreak + 'end;' + sLineBreak; sRemoteClassGetterImplPasIdx = 'function %0:s.Get%1:s(Index: Integer): %2:s;' + sLineBreak + 'begin' + sLineBreak + ' Result := F%1:s;' + sLineBreak + 'end;' + sLineBreak; sArrayAsClassDecl = ''; sRemoteClassDeclEndPas= ' end;' + sLineBreak; sRemoteClsCtrImplPas1 = 'constructor %0:s.Create;' + sLineBreak + 'begin' + sLineBreak + ' inherited Create;' + sLineBreak; sRemoteClsCtrImplPas2 = ' FSerializationOptions := [%s];' + sLineBreak; sRemoteClsCtrImplPas3 = 'end;' + sLineBreak; sRemoteClsDtrImplPas1 = 'destructor %0:s.Destroy;' + sLineBreak + 'begin' + sLineBreak; sRemoteClsDtrImplPas2 = 'destructor %0:s.Destroy;' + sLineBreak + 'var' + sLineBreak + ' I: Integer;' + sLineBreak + 'begin' + sLineBreak; {$IFDEF USE_FREE_AND_NIL} sRemoteClsDtrImplPas3 = ' for I := 0 to System.Length(%0:s)-1 do' + sLineBreak + ' System.SysUtils.FreeAndNil(%0:s[I]);' + sLineBreak + ' System.SetLength(%0:s, 0);' + sLineBreak; {$ELSE} sRemoteClsDtrImplPas3 = ' for I := 0 to System.Length(%0:s)-1 do' + sLineBreak + ' if Assigned(%0:s[I]) then' + sLineBreak + ' %0:s[I].Free;' + sLineBreak + ' System.SetLength(%0:s, 0);' + sLineBreak; {$ENDIF} {$IFDEF USE_FREE_AND_NIL} sRemoteClsDtrImplPas4 = ' System.SysUtils.FreeAndNil(%0:s);' + sLineBreak; {$ELSE} sRemoteClsDtrImplPas4 = ' if Assigned(%0:s) then' + sLineBreak + ' %0:s.Free;' + sLineBreak; {$ENDIF} sRemoteClsDtrImplPas5 = ' inherited Destroy;' + sLineBreak + 'end;' + sLineBreak; sInterfaceDeclPas = ' %s = interface(%s)' + sLineBreak + ' [''%s'']' + sLineBreak; sInterfaceDeclEndPas = ' end;' + sLineBreak + sLineBreak; { For cases where WSDL has Binding } sIntfFactoryDeclPas1 = 'function Get%0:s(UseWSDL: Boolean=System.False; Addr: string=''''; HTTPRIO: THTTPRIO = nil): %0:s;' + sLineBreak; sFactoryImplPas1 = 'function Get%0:s(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): %0:s;' + sLineBreak + 'const' + sLineBreak + ' defWSDL = ''%1:s'';' + sLineBreak + ' defURL = ''%2:s'';' + sLineBreak + ' defSvc = ''%3:s'';' + sLineBreak + ' defPrt = ''%4:s'';' + sLineBreak + 'var' + sLineBreak + ' RIO: THTTPRIO;' + sLineBreak + 'begin' + sLineBreak + ' Result := nil;' + sLineBreak + ' if (Addr = '''') then' + sLineBreak + ' begin' + sLineBreak + ' if UseWSDL then' + sLineBreak + ' Addr := defWSDL' + sLineBreak + ' else' + sLineBreak + ' Addr := defURL;' + sLineBreak + ' end;' + sLineBreak + ' if HTTPRIO = nil then' + sLineBreak + ' RIO := THTTPRIO.Create(nil)' + sLineBreak + ' else' + sLineBreak + ' RIO := HTTPRIO;' + sLineBreak + ' try' + sLineBreak + ' Result := (RIO as %0:s);' + sLineBreak + ' if UseWSDL then' + sLineBreak + ' begin' + sLineBreak + ' RIO.WSDLLocation := Addr;' + sLineBreak + ' RIO.Service := defSvc;' + sLineBreak + ' RIO.Port := defPrt;' + sLineBreak + ' end else' + sLineBreak + ' RIO.URL := Addr;' + sLineBreak + ' finally' + sLineBreak + ' if (Result = nil) and (HTTPRIO = nil) then' + sLineBreak + ' RIO.Free;' + sLineBreak + ' end;' + sLineBreak + 'end;' + sLineBreak + sLineBreak; { For cases where we have a URL but no binding } sIntfFactoryDeclPas2 = 'function Get%0:s(const Addr: string=''''): %0:s;' + sLineBreak; sFactoryImplPas2 = 'function Get%0:s(const Addr: string): %0:s;' + sLineBreak + 'const' + sLineBreak + ' defURL = ''%1:s'';' + sLineBreak + 'var' + sLineBreak + ' RIO: THTTPRIO;' + sLineBreak + 'begin' + sLineBreak + ' Result := nil;' + sLineBreak + ' RIO := THTTPRIO.Create(nil);' + sLineBreak + ' try' + sLineBreak + ' Result := (RIO as %0:s);' + sLineBreak + ' if (Addr = '''') then' + sLineBreak + ' RIO.URL := defURL' + sLineBreak + ' else' + sLineBreak + ' RIO.URL := Addr;' + sLineBreak + ' finally' + sLineBreak + ' if Result = nil then' + sLineBreak + ' RIO.Free;' + sLineBreak + ' end;' + sLineBreak + 'end;' + sLineBreak + sLineBreak; sImplDeclPas = ' %0:sImpl = class(TInvokableClass, %0:s)' + sLineBreak + ' public' + sLineBreak + ' { %0:s }' + sLineBreak; sImplDeclPas2 = ' T%0:s = class(TInvokableClass, %0:s)' + sLineBreak + ' public' + sLineBreak + ' { %0:s }' + sLineBreak; sImplDeclEndPas = ' end;' + sLineBreak + sLineBreak; sImplSuffix = 'Impl'; sIntfSuffix = 'Intf'; sDummyImplPas = 'begin' + sLineBreak + ' { TODO - Implement method %s }' + sLineBreak + 'end;' + sLineBreak + sLineBreak; {0: Element Type Name } sDefaultArrayDeclPas = ' function Get%0:sArray(Index: Integer): %0:s; ' + sLineBreak + ' procedure Set%0:sArray(Index: Integer; const Item: %0:s);' + sLineBreak + ' function Get%0:sArrayLength: Integer;' + sLineBreak + ' procedure Set%0:sArrayLength(Len: Integer);' + sLineBreak + sLineBreak + ' property %0:sArray[Index: Integer]: %0:s read Get%0:sArray write Set%0:sArray; default;' + sLineBreak + ' property Len: Integer read Get%0:sArrayLength write Set%0:sArrayLength;' + sLineBreak; { 0: Class Type Name, 1: Element Type Name, 2: Member Name } sDefaultArrayImplPas = 'function %0:s.Get%1:sArray(Index: Integer): %1:s;' + sLineBreak + 'begin' + sLineBreak + ' Result := F%2:s[Index];' + sLineBreak + 'end;' + sLineBreak + sLineBreak + 'procedure %0:s.Set%1:sArray(Index: Integer; const Item: %1:s);' + sLineBreak + 'begin' + sLineBreak + ' F%2:s[Index] := Item;' + sLineBreak + 'end;' + sLineBreak + sLineBreak + 'function %0:s.Get%1:sArrayLength: Integer;' + sLineBreak + 'begin' + sLineBreak + ' if Assigned(F%2:s) then' + sLineBreak + ' Result := System.Length(F%2:s)' + sLineBreak + ' else' + sLineBreak + ' Result := 0;' + sLineBreak + 'end;' + sLineBreak + sLineBreak + 'procedure %0:s.Set%1:sArrayLength(Len: Integer);' + sLineBreak + 'begin' + sLineBreak + ' System.SetLength(F%2:s, Len);' + sLineBreak + 'end;' + sLineBreak + sLineBreak; sRegInterfacePas3 = ' InvRegistry.RegisterInterface(TypeInfo(%s), ''%s'', ''%s'', '''', ''%s'', ''%s'');' + sLineBreak; sRegInterfacePas2 = ' InvRegistry.RegisterInterface(TypeInfo(%s), ''%s'', ''%s'', '''', ''%s'');' + sLineBreak; sRegInterfacePas1 = ' InvRegistry.RegisterInterface(TypeInfo(%s), ''%s'', ''%s'');' + sLineBreak; sRegInvokableClass = ' InvRegistry.RegisterInvokableClass(%s);' + sLineBreak; sRegSOAPActionPas = ' InvRegistry.RegisterDefaultSOAPAction(TypeInfo(%s), ''%s'');' + sLineBreak; sRegAllSOAPActionPas = ' InvRegistry.RegisterAllSOAPActions(TypeInfo(%s), %s);' + sLineBreak; sRegUDDIInfoPas = ' InvRegistry.RegisterUDDIInfo(TypeInfo(%s), ''%s'', ''%s'');' + sLineBreak; sRegParamNamesPasBeg = ' InvRegistry.RegisterReturnParamNames(TypeInfo(%s), '; sRegInvokeOptDocPas = ' InvRegistry.RegisterInvokeOptions(TypeInfo(%s), ioDocument);' + sLineBreak; sRegInvokeOptLitPas = ' InvRegistry.RegisterInvokeOptions(TypeInfo(%s), ioLiteral);' + sLineBreak; sRegInvokeOptUDDIPas = ' InvRegistry.RegisterInvokeOptions(TypeInfo(%s), ioHasUDDIInfo);' + sLineBreak; sRegInvokeOptSOAP12Pas= ' InvRegistry.RegisterInvokeOptions(TypeInfo(%s), ioSOAP12);' + sLineBreak; sRegMethodRenamedPas = ' InvRegistry.RegisterExternalMethName(TypeInfo(%s), ''%s'', ''%s'');' + sLineBreak; sRegParamRenamedPas = ' InvRegistry.RegisterExternalParamName(TypeInfo(%s), ''%s'', ''%s'', ''%s'');' + sLineBreak; sRegMemberRenamedPas = ' RemClassRegistry.RegisterExternalPropName(TypeInfo(%s), ''%s'', ''%s'');' + sLineBreak; // Delphi Param Registration sRegParamInfoPas = ' InvRegistry.RegisterParamInfo(TypeInfo(%s), ''%s'', ''%s'', ''%s'',' + sLineBreak + ' ''%s'', %s);' + sLineBreak; sRegParamInfoPasNoOpts = ' InvRegistry.RegisterParamInfo(TypeInfo(%s), ''%s'', ''%s'', ''%s'',' + sLineBreak + ' ''%s'');' + sLineBreak; sRegParamInfoPasNoInfo = ' InvRegistry.RegisterParamInfo(TypeInfo(%s), ''%s'', ''%s'', ''%s'', '''');' + sLineBreak; // C++ Param Registration sRegParamInfoCpp = ' InvRegistry()->RegisterParamInfo(__delphirtti(%s), "%s", "%s", L"%s",' + sLineBreak + ' L"%s", %s);' + sLineBreak; sRegParamInfoCppNoOpts = ' InvRegistry()->RegisterParamInfo(__delphirtti(%s), "%s", "%s", L"%s",' + sLineBreak + ' L"%s");' + sLineBreak; sRegParamInfoCppNoInfo = ' InvRegistry()->RegisterParamInfo(__delphirtti(%s), "%s", "%s", L"%s", L"");' + sLineBreak; // Delphi Method Registration sRegMethodInfoPas = ' InvRegistry.RegisterMethodInfo(TypeInfo(%s), ''%s'', ''%s'',' + sLineBreak + ' ''%s'', %s);' + sLineBreak; sRegMethodInfoPasNoOpts = ' InvRegistry.RegisterMethodInfo(TypeInfo(%s), ''%s'', ''%s'',' + sLineBreak + ' ''%s'');' + sLineBreak; sRegMethodInfoPasNoInfo = ' InvRegistry.RegisterMethodInfo(TypeInfo(%s), ''%s'', ''%s'', '''');' + sLineBreak; // C++ Method Registration sRegMethodInfoCpp = ' InvRegistry()->RegisterMethodInfo(__delphirtti(%s), "%s", "%s",' + sLineBreak + ' "%s", %s);' + sLineBreak; sRegMethodInfoCppNoOpts = ' InvRegistry()->RegisterMethodInfo(__delphirtti(%s), "%s", "%s",' + sLineBreak + ' "%s" );' + sLineBreak; sRegMethodInfoCppNoInfo = ' InvRegistry()->RegisterMethodInfo(__delphirtti(%s), "%s", "%s", "" );' + sLineBreak; { Class, Namespace, Name, ExternalName } sRegClassPas2 = ' RemClassRegistry.RegisterXSClass(%s, ''%s'', ''%s'', ''%s'');' + sLineBreak; { Class, Namespace, Name } sRegClassPas1 = ' RemClassRegistry.RegisterXSClass(%s, ''%s'', ''%s'');' + sLineBreak; { Interface, Namespace, Name, ExternalName } sRegTypePas2 = ' RemClassRegistry.RegisterXSInfo(TypeInfo(%s), ''%s'', ''%s'', ''%s'');' + sLineBreak; { Interface, Namespace, Name } sRegTypePas1 = ' RemClassRegistry.RegisterXSInfo(TypeInfo(%s), ''%s'', ''%s'');' + sLineBreak; sRegClassSerialOptsPas= ' RemClassRegistry.RegisterSerializeOptions(%s, %s);' + sLineBreak; sRegInfoSerialOptsPas = ' RemClassRegistry.RegisterSerializeOptions(TypeInfo(%s), %s);' + sLineBreak; sRegHeaderPas1 = ' InvRegistry.RegisterHeaderClass(TypeInfo(%s), %s, %s, %s);' + sLineBreak; sRegHeaderPas2 = ' InvRegistry.RegisterHeaderClass(TypeInfo(%s), %s, ''%s'', ''%s'');' + sLineBreak; sRegHeaderMethPas = ' InvRegistry.RegisterHeaderMethod(TypeInfo(%s), %s, ''%s'', %s, %s);' + sLineBreak; sRegFaultPas = ' InvRegistry.RegisterException(TypeInfo(%s), %s);' + sLineBreak; sRegFaultMethPas = ' InvRegistry.RegisterExceptionMethod(TypeInfo(%s), %s, ''%s'');' + sLineBreak; sUnitSuffix = '_WS'; SPasFileExt = '.pas'; SCppFileExt = '.cpp'; SHFileExt = '.h'; {$IFDEF MSWINDOWS} SDfmExt = '.dfm'; {$ENDIF} {$IFDEF LINUX} SDfmExt = '.xfm'; {$ENDIF} XMLItemInfoComment: array[XMLItemInfo] of string = ('global', 'predefined', '<element>', '<complexType>', '<simpleType>', '<attribute>', '<attributeGroup>', '<group>', 'unbounded', 'alias', 'nillable', 'mixed' ); resourcestring sImportWSDL = 'Import WSDL'; sImportWSDLEllipsis = 'Import WSDL...'; { Wizard Reg } SNewXMLDataBinding = 'XML Data Binding'; { Wizard Form } SWSDLDefExt = '.wsdl'; SSourceFilter = 'WSDL Files (*.wsdl, *.xml)|*.wsdl;*.xml|XML Files (*.xml)|*.xml|All files (*.*)|*.*'; SConfirmClose = 'Are you sure you want to close the WSDL Importer Wizard?'; sNoBindingsFound = 'No supported Bindings found in document'; sWSDLInfoBeg = '// ************************************************************************ //' + #13#10 + '// The types declared in this file were generated from data read from the' + #13#10 + '// WSDL File described below:' + #13#10 + '// WSDL : %0:s' + #13#10; sImportInfo = '// >Import : %s' + #13#10; sEncodingInfo = '// Encoding : %s' + #13#10; sVersionInfo = '// Version : %s' + #13#10; sSchemaRef = '// SchemaRef: %s' + #13#10; sServices = '// Services : %s' + #13#10; sPorts = '// Ports : [Srvc %d] - %s' + #13#10; sGenOptions = '// Codegen : %s' + #13#10; sWSDLInfoEnd = '// (%s - %s)'+ #13#10 + '// ************************************************************************ //' + #13#10 + #13#10; sInfoBeg = '// ************************************************************************ //'; sInfoEnd = '// ************************************************************************ //' + #13#10; sPredefinedInfo = '%0:s// The following types, referred to in the WSDL document are not being represented' + #13#10 + '%0:s// in this file. They are either aliases[@] of other types represented or were referred'+ #13#10 + '%0:s// to but never[!] declared in the document. The types from the latter category' + #13#10 + '%0:s// typically map to predefined/known XML or Embarcadero types; however, they could also ' + #13#10 + '%0:s// indicate incorrect WSDL documents that failed to declare or import a schema type.' + #13#10; sPredefinedTypes = '// !:%-15s - %s'; sDuplicateTypes = '// @:%-15s - %s'; sWarningInfoBegin = '%0:s// [WARNINGS]************************************************************** //'; sWarningInfo = '%0:s// %1:s'; sWarningInfoEnd = '%0:s// ************************************************************************ //'; sRegProcInfo = '// ************************************************************************ //' + #13#10 + '// This routine registers the interfaces and types exposed by the WebService.' + #13#10; sBindInfoGeneric = '// Info : %s'; sExternalName = '// Name : %s'; sSerialization = '// Serializtn: [%s]'; sXMLInfo = '// XML : %s'; sNamespaceInfo = '// Namespace : %s'; sSOAPActionInfo = '// soapAction: %s'; sTransportInfo = '// transport : %s'; sStyleInfo = '// style : %s'; sUseInfo = '// use : %s'; sBindingInfo = '// binding : %s'; sServiceInf = '// service : %s'; sPortInfo = '// port : %s'; sURLInfo = '// URL : %s'; sServerImpl = '%s - Server implementation class'; sBindInfoLocalName = '// LocalName : %s'; sBindInfoBaseType = '// BaseType : %s'; sBindInfoBound = '// Bound : %s'; sForwardDecl = #13#10 + '// *********************************************************************//' + #13#10 + '// Forward declaration of types defined in WSDL ' + #13#10 + '// *********************************************************************//' + #13#10; sFeedbackRead = 'Reading: %s'; sFeedbackWrite = 'Writing: %s'; sFeedbackImp = 'Import : %s'; sFeedbackDone = 'Done : %s'; sFeedbackUDDI = 'UDDI : %s'; sFeedbackSkip = '(Skip) : %s'; sFeedbackError = '*Error*: %s'; sFeedbackError2 = ' > %s'; sFeedbackDebug = '(Debug): %s'; sWritingType = '(Write): %s'; sReadingType = '(Read) : %s'; sSortingType = '(Sort) : %s:%d - %s'; sMovingType = '(Move) : %s:%d -> %s:%d, (%s: %s)'; sDottedLine = '------------------------------------------------'; sMissingDefinition = '*Error*: ''%s'' - Missing <definition> node of namespace "%s"'; sGenericTypeError = '*Error*: ''%s'' - Invalid Type Definition encountered'; sComplexTypeError = '*Error*: ''%s'' - Complex Type Definition Error, type="%s"'; sBindableTypeError = '*Error*: ''%s'' - %s'; sSchemaError = '*Error*: ''%s'' - Invalid schema detected'; sGenericError = '*Error*: %s'; sSummaryFeedback1 = 'Summary: Successfully imported %d of %d. %d failed:'; sSummaryFeedback2 = 'Summary: Successfully imported %d of %d Entries'; sFailureFeedback = #9'%s'; sSchemaWarning = 'Warning: ''%s'' - Error in processing XML Schema'; sUnwindWarningIn = 'Warning: Input Literal parameters of %s() cannot be unwrapped'; sUnwindWarningOut = 'Warning: Output Literal parameters of %s() cannot be unwrapped'; sWarningHeader = ' { ================== WARNING ================== }'; sWarningAttribute = ' { WARNING - Attribute - Name:%s, Type:%s }'; sCircularTypeLink = 'Circular reference detected in type: %s'; sUnableToSort = 'Unable to sort type ''%s'' due to circular reference!'; sUnableToSortTypes = 'Unable to sort types ''%s'' and ''%s'' due to circular references!'; { Import Options } sVerboseOpt = 'Generate &verbose information about types and interfaces'; sSkipHTTPBindOpt = 'Process only SOAP binding types'; sMapNamedArrays = 'Map pure collections to wrapper class t&ypes'; sSkipUnusedTypes = 'Do not emit unused &types'; sImportFaults = 'Import Fau&lt Types'; sValidateEnum = 'Validate Enumeration members'; sImportHeaders = 'Import &Header Types'; sGenTrueGUID = 'Generate interface GUIDs using &COM API'; //sCollapseAliases = 'Collapse simple alias types'; sForceSOAP11 = '&Process only WSDL Binding extensions for the SOAP 1.1 Protocol'; sForceSOAP12 = 'Process &only WSDL Binding extensions for the SOAP 1.2 Protocol'; sOneOutParamIsReturn = '&One out parameter is return value'; sGenServerImpl = 'Generate &server implementation instead of client proxies'; sGenerateWarnings = 'Generate &warning comments'; sAmbiguousComplexTypesAsArray = 'Ambiguous Complex Types are considered arrays'; sAutoDestroyMembers = 'Generate &destructors for remotable types'; sMapStringsToWideStrings = '&Map String to WideString'; sOutputLiteralTypes = '&Emit wrapper element Types'; sUnwindLiteralTypes = '&Unwrap wrapper elements (wrapped doc|lit services)'; sIgnoreSchemaErrors = 'Ignore Schema Errors'; sProcessRefSchemas = 'Process included &and imported schemas'; sStrongClassAliases= 'Gene&rate class aliases as class types'; sAllowOutParameters = 'Allow out &parameters'; sUseSettersAndGetters = 'Use Setters a&nd Getters for properties'; sProcessNillableOptional= 'Process n&illable and optional elements'; sUseXSTypeForSimpleNillable = 'Use T&XSxxxx classes for simple nillable types'; sUseScopedEnumerations = '&Generate scoped enumerations'; sCreateArrayElemTypeAlias = 'Generate alias for the element of pure collections'; sVerboseOptForCommandLineHelp = 'Generate verbose information about types and interfaces'; sSkipHTTPBindOptForCommandLineHelp = 'Process only SOAP binding types'; sMapNamedArraysForCommandLineHelp = 'Map pure collections to wrapper class types'; sSkipUnusedTypesForCommandLineHelp = 'Do not emit unused types'; sImportFaultsForCommandLineHelp = 'Import Fault Types'; sValidateEnumForCommandLineHelp = 'Validate Enumeration members'; sImportHeadersForCommandLineHelp = 'Import Header Types'; sGenTrueGUIDForCommandLineHelp = 'Generate interface GUIDs using COM API'; //sCollapseAliasesForCommandLineHelp = 'Collapse simple alias types'; sForceSOAP11ForCommandLineHelp = 'Process only WSDL Binding extensions for the SOAP 1.1 Protocol'; sForceSOAP12ForCommandLineHelp = 'Process only WSDL Binding extensions for the SOAP 1.2 Protocol'; sOneOutParamIsReturnForCommandLineHelp = 'One out parameter is return value'; sGenServerImplForCommandLineHelp = 'Generate server implementation instead of client proxies'; sGenerateWarningsForCommandLineHelp = 'Generate warning comments'; sAmbiguousComplexTypesAsArrayForCommandLineHelp = 'Ambiguous Complex Types are considered arrays'; sAutoDestroyMembersForCommandLineHelp = 'Generate destructors for remotable types'; sMapStringsToWideStringsForCommandLineHelp = 'Map String to WideString'; sOutputLiteralTypesForCommandLineHelp = 'Emit wrapper element Types'; sUnwindLiteralTypesForCommandLineHelp = 'Unwrap wrapper elements (wrapped doc|lit services)'; sIgnoreSchemaErrorsForCommandLineHelp = 'Ignore Schema Errors'; sProcessRefSchemasForCommandLineHelp = 'Process included and imported schemas'; sStrongClassAliasesForCommandLineHelp= 'Generate class aliases as class types'; sAllowOutParametersForCommandLineHelp = 'Allow out parameters'; sUseSettersAndGettersForCommandLineHelp = 'Use Setters and Getters for properties'; sProcessNillableOptionalForCommandLineHelp= 'Process nillable and optional elements'; sUseXSTypeForSimpleNillableForCommandLineHelp = 'Use TXSxxxx classes for simple nillable types'; sUseScopedEnumerationsForCommandLineHelp = 'Generate scoped enumerations'; sCreateArrayElemTypeAliasForCommandLineHelp = 'Generate alias for the element of pure collections'; sCouldNotUnwrapDocLitElementWrapper = 'Cannot unwrap'; sCUInputMessageHasMoreThanOnePart = 'Input message has more than one part'; sCUOutputMessageHasMoreThanOnePart= 'Output message has more than one part'; sCUInputPartRefersToTypeNotElement= 'Input part does not refer to an element'; sCUOutputPartRefersToTypeNotElement='Output part does not refer to an element'; sCUInputWrapperElementNotSameAsOperationName = 'Input element wrapper name does not match operation''s name'; sCUInputPartNotAComplexType = 'The input part is not a complex type'; sCUOutputPartNotAComplexType= 'The output part is not a complex type'; sCUMoreThanOneStrictlyOutMembersWereFound = 'More than one strictly out element was found'; sCUTypeNeedsSpecialSerialization = 'Wrapper type needs special serialization'; sCUOutputElementIsAPureCollection= 'Output element is a pure collection'; sMethodHeaders = 'Headers'; sWSDLImportError = 'WSDL Import Error'; sErrorImportingWSDL1 = 'An error was encountered importing ''%s'''; sErrorImportingWSDL2 = 'Please verify that you''ve entered the correct URL/file and that it''s a valid WSDL file.'; sErrorImportingWSDL3 = 'Do you want to try again?'; const CannotUnwrapStr: array[CannotUnwrap] of String = ( sCUInputMessageHasMoreThanOnePart, sCUOutputMessageHasMoreThanOnePart, sCUInputPartRefersToTypeNotElement, sCUOutputPartRefersToTypeNotElement, sCUInputWrapperElementNotSameAsOperationName, sCUInputPartNotAComplexType, sCUOutputPartNotAComplexType, sCUMoreThanOneStrictlyOutMembersWereFound, sCUTypeNeedsSpecialSerialization, sCUOutputElementIsAPureCollection ); OptionsSection = 'Import Options'; { do not localize } DeclareNamespace = 'DeclaredNamespace'; { do not localize } OneParamIsReturnSetting = 'OneParamIsResult'; { do not localize } UnwindLiteralParamsSetting= 'UnwindLitParams'; { do not localize } GenDestructorsSetting = 'GenDestructors'; { do not localize } IgnoreSchemaErrorsSetting = 'IgnoreSchemaErrors'; { do not localize } GenWarningsSetting = 'GenWarnings'; { do not localize } GenLiteralTypesSetting = 'GenLitTypes'; { do not localize } AmbTypesAsArraySetting = 'AmbiguousTypesAsArray'; { do not localize } GenServerSetting = 'GenServerImpl'; { do not localize } MapStringToWideStrSetting = 'MapStringToWS'; { do not localize } MapPureCollToClass = 'MapPureCollToClass'; { do not localize } UseClassForAttr = 'UseClassForAttr'; { do not localize } ProcessFaults = 'ProcessFaults'; { do not localize } SkipUnusedTypes = 'SkipUnusedTypes'; { do not localize } SkipHttpBindings = 'SkipHttpBindings'; { do not localize } VerboseMode = 'VerboseMode'; { do not localize } ValidateEnumMembers = 'ValidateEnumMembers'; { do not localize } ProcessHeaders = 'ProcessHeaders'; { do not localize } GenTrueGUIDs = 'GenerateTrueGUIDs'; { do not localize } ProcessRefSchemas = 'ProcessRefSchemas'; { do not localize } StrongClassAliases = 'StrongClassAliases'; { do not localize } AllowMultipleOutParams = 'AllowMultipleOutParams'; { do not localize } UseSettersAndGetters = 'UseSettersAndGetters'; { do not localize } ProcessNillableOptional = 'ProcessNillableOptional';{ do not localize } UseXSForSimpleNillable = 'UseXSForSimpleNillable'; { do not localize } UseScopedEnumerations = 'UseScopedEnumerations'; { do not localize } ForceSOAP11 = 'ForceSOAP11'; { do not localize } ForceSOAP12 = 'ForceSOAP12'; { do not localize } CreateArrayElemTypeAlias = 'CreateArrayElemTypeAlias';{ do not localize } OptStrings: array[WSDLGenFlags] of string = ('', { wfDebug } VerboseMode, { wfVerbose } SkipHttpBindings, { wfSkipHttpBindings } OneParamIsReturnSetting, { wfOneOutIsReturn } GenServerSetting, { wfServer } '', { wfUseXMLBindingManager } AmbTypesAsArraySetting, { wfAmbiguousComplexTypesAsArray } UnwindLiteralParamsSetting, { wfUnwindLiteralTypes } GenLiteralTypesSetting, { wfOutputLiterayTypes } MapStringToWideStrSetting, { wfMapStringsToWideStrings } IgnoreSchemaErrorsSetting, { wfIgnoreSchemaErrors } '', { wfAutoInitMembers } GenDestructorsSetting, { wfAutoDestroyMembers } '', { wfQuietMode } '', { wfSelectiveCodeGen } GenWarningsSetting, { wfGenerateWarnings } MapPureCollToClass, { wfMapArraysToClasses } DeclareNamespace, { wfTypesInNamespace } SkipUnusedTypes, { wfSkipUnusedTypes } UseClassForAttr, { wfUseSerializerClassForAttrs } ValidateEnumMembers, { wfValidateEnumMembers } ProcessFaults, { wfProcessFaults } ProcessHeaders, { wfProcessHeaders } GenTrueGUIDs, { wfGenTrueGUIDs } ProcessRefSchemas, { wfProcessRefSchemas } StrongClassAliases, { wfStrongClassAliases} AllowMultipleOutParams, { wfAllowOutParameters} UseSettersAndGetters, { wfUseSettersAndGetters } ProcessNillableOptional, { wfProcessOptionalNillable } UseXSForSimpleNillable, { wfUseXSTypeForSimpleNillable } UseScopedEnumerations, { wfUseScopedEnumerations } ForceSOAP11, { wfForceSOAP11 } ForceSOAP12, { wfForceSOAP12 } CreateArrayElemTypeAlias, { wfCreateArrayElemTypeAlias } '' { wfLastOption } ); OptDescriptions: array[WSDLGenFlags] of string = ('', { wfDebug } sVerboseOpt, { wfVerbose } sSkipHTTPBindOpt, { wfSkipHttpBindings } sOneOutParamIsReturn, { wfOneOutIsReturn } sGenServerImpl, { wfServer } '', { wfUseXMLBindingManager } sAmbiguousComplexTypesAsArray, { wfAmbiguousComplexTypesAsArray } sUnwindLiteralTypes, { wfUnwindLiteralTypes } sOutputLiteralTypes, { wfOutputLiterayTypes } sMapStringsToWideStrings, { wfMapStringsToWideStrings } sIgnoreSchemaErrors, { wfIgnoreSchemaErrors } '', { wfAutoInitMembers } sAutoDestroyMembers, { wfAutoDestroyMembers } '', { wfQuietMode } '', { wfSelectiveCodeGen } sGenerateWarnings, { wfGenerateWarnings } sMapNamedArrays, { wfMapArraysToClasses } '', { wfTypesInNamespace } sSkipUnusedTypes, { wfSkipUnusedTypes } '', { wfUseSerializerClassForAttrs } sValidateEnum, { wfValidateEnumMembers } sImportFaults, { wfProcessFaults } sImportHeaders, { wfProcessHeaders } sGenTrueGUID, { wfGenTrueGUIDs } sProcessRefSchemas, { wfProcessRefSchemas } sStrongClassAliases, { wfStrongClassAliases } sAllowOutParameters, { wfAllowOutParameters } sUseSettersAndGetters, { wfUseSettersAndGetters } sProcessNillableOptional, { wfProcessNillableOptional } sUseXSTypeForSimpleNillable, { wfUseXSTypeForSimpleNillable } sUseScopedEnumerations, { wfUseScopedEnumerations } sForceSOAP11, { wfForceSOAP11 } sForceSOAP12, { wfForceSOAP12 } sCreateArrayElemTypeAlias, { wfCreateArrayElemTypeAlias } '' { wfLastOption } ); OptDescriptionsForCommandLineHelp: array[WSDLGenFlags] of string = ('', { wfDebug } sVerboseOptForCommandLineHelp, { wfVerbose } sSkipHTTPBindOptForCommandLineHelp, { wfSkipHttpBindings } sOneOutParamIsReturnForCommandLineHelp, { wfOneOutIsReturn } sGenServerImplForCommandLineHelp, { wfServer } '', { wfUseXMLBindingManager } sAmbiguousComplexTypesAsArrayForCommandLineHelp, { wfAmbiguousComplexTypesAsArray } sUnwindLiteralTypesForCommandLineHelp, { wfUnwindLiteralTypes } sOutputLiteralTypesForCommandLineHelp, { wfOutputLiterayTypes } sMapStringsToWideStringsForCommandLineHelp, { wfMapStringsToWideStrings } sIgnoreSchemaErrorsForCommandLineHelp, { wfIgnoreSchemaErrors } '', { wfAutoInitMembers } sAutoDestroyMembersForCommandLineHelp, { wfAutoDestroyMembers } '', { wfQuietMode } '', { wfSelectiveCodeGen } sGenerateWarningsForCommandLineHelp, { wfGenerateWarnings } sMapNamedArraysForCommandLineHelp, { wfMapArraysToClasses } '', { wfTypesInNamespace } sSkipUnusedTypesForCommandLineHelp, { wfSkipUnusedTypes } '', { wfUseSerializerClassForAttrs } sValidateEnumForCommandLineHelp, { wfValidateEnumMembers } sImportFaultsForCommandLineHelp, { wfProcessFaults } sImportHeadersForCommandLineHelp, { wfProcessHeaders } sGenTrueGUIDForCommandLineHelp, { wfGenTrueGUIDs } sProcessRefSchemasForCommandLineHelp, { wfProcessRefSchemas } sStrongClassAliasesForCommandLineHelp, { wfStrongClassAliases } sAllowOutParametersForCommandLineHelp, { wfAllowOutParameters } sUseSettersAndGettersForCommandLineHelp, { wfUseSettersAndGetters } sProcessNillableOptionalForCommandLineHelp, { wfProcessNillableOptional } sUseXSTypeForSimpleNillableForCommandLineHelp, { wfUseXSTypeForSimpleNillable } sUseScopedEnumerationsForCommandLineHelp, { wfUseScopedEnumerations } sForceSOAP11ForCommandLineHelp, { wfForceSOAP11 } sForceSOAP12ForCommandLineHelp, { wfForceSOAP12 } sCreateArrayElemTypeAliasForCommandLineHelp, { wfCreateArrayElemTypeAlias } '' { wfLastOption } ); OptHiddenOptions: array[WSDLGenFlags] of Boolean = (True, { wfDebug } // Debugging output False, { wfVerbose } True, { wfSkipHttpBindings } //Removed temporarily until it can be properly implemented False, { wfOneOutIsReturn } False, { wfServer } True, { wfUseXMLBindingManager } // Deprecated True, { wfAmbiguousComplexTypesAsArray } // Deprecated False, { wfUnwindLiteralTypes } False, { wfOutputLiterayTypes } False, { wfMapStringsToWideStrings } True, { wfIgnoreSchemaErrors } // Deprecated (MarkE fixes Schema problems) True, { wfAutoInitMembers } // Never properly implemented False, { wfAutoDestroyMembers } True, { wfQuietMode } // Hidden option for testing (does not emit date) True, { wfSelectiveCodeGen } // Deprecated was used by old Importer False, { wfGenerateWarnings } False, { wfMapArraysToClasses } True, { wfTypesInNamespace } // Always ON (Only applicable to C++) False, { wfSkipUnusedTypes } True, { wfUseSerializerClassForAttrs } // Deprecated True, { wfValidateEnumMembers } //Not safe to turn off, Will generate code with keywords in enumerations False, { wfProcessFaults } False, { wfProcessHeaders } False, { wfGenTrueGUIDs } False, { wfProcessRefSchemas } False, { wfStrongClassAliases } False, { wfAllowOutParameters } // NA for C++ False, { wfUseSettersAndGetters } False, { wfProcessNillableOptional } False, { wfUseXSTypeForSimpleNillable } False, { wfUseScopedEnumerations } False, { wfForceSOAP11 } False, { wfForceSOAP12 } True, { wfCreateArrayElemTypeAlias } True { wfLastOption } ); OptCommandLineFlags: array[WSDLGenFlags] of string = ('debug', { wfDebug } 'v', { wfVerbose } '', { wfSkipHttpBindings } 'o', { wfOneOutIsReturn } 's', { wfServer } '', { wfUseXMLBindingManager } '', { wfAmbiguousComplexTypesAsArray } 'u', { wfUnwindLiteralTypes } 'l', { wfOutputLiterayTypes } 'w', { wfMapStringsToWideStrings } '', { wfIgnoreSchemaErrors } '', { wfAutoInitMembers } 'd', { wfAutoDestroyMembers } '', { wfQuietMode } '', { wfSelectiveCodeGen } 'i', { wfGenerateWarnings } 'k', { wfMapArraysToClasses } '', { wfTypesInNamespace } 't', { wfSkipUnusedTypes } '', { wfUseSerializerClassForAttrs } 'j', { wfValidateEnumMembers } 'f', { wfProcessFaults } 'h', { wfProcessHeaders } 'g', { wfGenTrueGUIDs } 'p', { wfProcessRefSchemas } 'x', { wfStrongClassAliases} 'm', { wfAllowOutParameters} 'b', { wfUseSettersAndGetters } 'a', { wfProcessOptionalNillable } 'z', { wfUseXSTypeForSimpleNillable } 'e', { wfUseScopedEnumerations } 'SOAP11', { wfForceSOAP11 } 'SOAP12', { wfForceSOAP12 } 'r', { wfCreateArrayElemTypeAlias } '' { wfLastOption } ); implementation function IsOptionHandledByOptionsPage(const Flag: WSDLGenFlags): Boolean; begin Result := Length(OptCommandLineFlags[Flag]) = 1; end; end.
unit AutoBinding; interface uses System.Classes, DocFieldInfo, System.Generics.Collections, FireDAC.Comp.Client, TableWithProgress, Data.DB, SearchProductParameterValuesQuery, DocBindExcelDataModule, DSWrap; type MySplitRec = record Name: string; Number: cardinal; end; TDocFilesTable = class(TTableWithProgress) private function GetIDParamSubParam: TField; function GetFileName: TField; function GetRootFolder: TField; public constructor Create(AOwner: TComponent); override; procedure LoadDocFiles(ADocFieldInfos: TList<TDocFieldInfo>); property IDParamSubParam: TField read GetIDParamSubParam; property FileName: TField read GetFileName; property RootFolder: TField read GetRootFolder; end; TAbsentDocTableW = class(TDSWrap) private FComponentName: TFieldWrap; FDescription: TFieldWrap; FFolder: TFieldWrap; public constructor Create(AOwner: TComponent); override; procedure AddError(const AFolder, AComponentName, AErrorMessage: string); property ComponentName: TFieldWrap read FComponentName; property Description: TFieldWrap read FDescription; property Folder: TFieldWrap read FFolder; end; TAbsentDocTable = class(TFDMemTable) private FW: TAbsentDocTableW; public constructor Create(AOwner: TComponent); override; property W: TAbsentDocTableW read FW; end; TPossibleLinkDocTable = class(TTableWithProgress) private function GetComponentName: TField; function GetRange: TField; function GetFileName: TField; function GetRootFolder: TField; protected public constructor Create(AOwner: TComponent); override; property ComponentName: TField read GetComponentName; property Range: TField read GetRange; property FileName: TField read GetFileName; property RootFolder: TField read GetRootFolder; end; TErrorLinkedDocTableW = class(TDSWrap) private FFolder: TFieldWrap; FErrorMessage: TFieldWrap; FComponentName: TFieldWrap; public constructor Create(AOwner: TComponent); override; property Folder: TFieldWrap read FFolder; property ErrorMessage: TFieldWrap read FErrorMessage; property ComponentName: TFieldWrap read FComponentName; end; TErrorLinkedDocTable = class(TTableWithProgress) private FW: TErrorLinkedDocTableW; public constructor Create(AOwner: TComponent); override; property W: TErrorLinkedDocTableW read FW; end; TAutoBind = class(TObject) private class function AnalizeDocFiles(ADocFilesTable: TDocFilesTable) : TDictionary<Integer, TPossibleLinkDocTable>; static; class function CheckAbsentDocFiles(ADocFieldInfos: TList<TDocFieldInfo>; const AFDQuery: TFDQuery): TAbsentDocTable; static; class function LinkToDocFiles(APossibleLinkDocTables : TDictionary<Integer, TPossibleLinkDocTable>; const AComponentsDataSet: TTableWithProgress; ADocFieldInfos: TList<TDocFieldInfo>; AConnection: TFDCustomConnection; const ANoRange: Boolean): TErrorLinkedDocTable; static; class function MySplit(const S: String): MySplitRec; static; protected public class procedure BindComponentDescriptions(const AIDCategory : Integer); static; class procedure BindProductDescriptions; static; class procedure BindDocs(ADocFieldInfos: TList<TDocFieldInfo>; const AFDQuery: TFDQuery; const ANoRange, ACheckAbsentDocFiles : Boolean); static; end; implementation uses cxGridDbBandedTableView, GridViewForm2, ProgressBarForm, System.SysUtils, System.IOUtils, DialogUnit, StrHelper, System.Types, SearchDescriptionsQuery, System.StrUtils, ProjectConst, SearchproductDescriptionQuery; class function TAutoBind.AnalizeDocFiles(ADocFilesTable: TDocFilesTable) : TDictionary<Integer, TPossibleLinkDocTable>; procedure Append(AIDParamSubParam: Integer; const AComponentName: String; const ARange: cardinal); begin Assert(AIDParamSubParam > 0); Assert(not AComponentName.IsEmpty); // Если такой таблицы в памяти ещё не существовало if not Result.ContainsKey(AIDParamSubParam) then Result.Add(AIDParamSubParam, TPossibleLinkDocTable.Create(nil)); with Result[AIDParamSubParam] do begin Append; FileName.AsString := ADocFilesTable.FileName.AsString; RootFolder.AsString := ADocFilesTable.RootFolder.AsString; ComponentName.AsString := AComponentName; Range.AsInteger := ARange; Post; end; end; var AFileName: string; d: TArray<String>; i: Integer; OK: Boolean; R0: MySplitRec; R1: MySplitRec; begin Assert(ADocFilesTable <> nil); // Создаём словарь из таблиц с теми файлами которые мы будем сопоставлять компонентам Result := TDictionary<Integer, TPossibleLinkDocTable>.Create; ADocFilesTable.First; ADocFilesTable.CallOnProcessEvent; // Цикл по всем найденным файлам while not ADocFilesTable.Eof do begin AFileName := TPath.GetFileNameWithoutExtension (ADocFilesTable.FileName.AsString); // Разделяем имя файла на границы диапазона d := AFileName.Split(['-']); // Если файл документации предназначен для одного компонента if Length(d) = 1 then begin Append(ADocFilesTable.IDParamSubParam.AsInteger, d[0], 1); end else begin // Надо вычленить номера начала и конца диапазона R0 := MySplit(d[0]); R1 := MySplit(d[1]); // ('Компонент в начале диапазона должен имееть номер меньше чем номер компонента в конце диапазона'); // ('Компонент в начале диапазона должен имееть номер'); // ('Компоненты в начале и в конце диапазона должны отличаться только номерами'); OK := (R0.Number < R1.Number) and (R0.Number > 0) and (R0.Name = R1.Name); if OK then begin // Цикл по всем номерам компонентов, входящих в диапазон for i := R0.Number to R1.Number do begin Append(ADocFilesTable.IDParamSubParam.AsInteger, Format('%s%d', [R0.Name, i]), R1.Number - R0.Number); ADocFilesTable.CallOnProcessEvent; end; end; end; ADocFilesTable.Next; ADocFilesTable.CallOnProcessEvent; end; end; class procedure TAutoBind.BindComponentDescriptions(const AIDCategory: Integer); var ABindQuery: TQuerySearchDescriptions; begin // Привязываем компоненты к кратким описаниям ABindQuery := TQuerySearchDescriptions.Create(nil); try // Если какя-то отдельная категория if AIDCategory > 0 then ABindQuery.Search(AIDCategory) else ABindQuery.SearchAll; // Если найдены компоненты, которые можно привязать if ABindQuery.FDQuery.RecordCount > 0 then begin TfrmProgressBar.Process(ABindQuery, ABindQuery.UpdateComponentDescriptions, sDoDescriptionsBind, sComponents); TDialog.Create.AutoBindResultDialog(ABindQuery.FDQuery.RecordCount); end else TDialog.Create.AutoBindNotFoundDialog; finally FreeAndNil(ABindQuery); end; end; class procedure TAutoBind.BindProductDescriptions; var ABindQuery: TQuerySearchProductDescription; begin // Привязываем компоненты к кратким описаниям ABindQuery := TQuerySearchProductDescription.Create(nil); try ABindQuery.FDQuery.Open(); // Если найдены компоненты, которые можно привязать if ABindQuery.FDQuery.RecordCount > 0 then begin TfrmProgressBar.Process(ABindQuery, ABindQuery.UpdateProductDescriptions, 'Выполняем привязку кратких описаний', sComponents); TDialog.Create.AutoBindResultDialog(ABindQuery.FDQuery.RecordCount); end else TDialog.Create.AutoBindNotFoundDialog; finally FreeAndNil(ABindQuery); end; end; class procedure TAutoBind.BindDocs(ADocFieldInfos: TList<TDocFieldInfo>; const AFDQuery: TFDQuery; const ANoRange, ACheckAbsentDocFiles: Boolean); var AAbsentDocTable: TAbsentDocTable; AcxGridDBBandedColumn: TcxGridDBBandedColumn; ADocFilesTable: TDocFilesTable; AfrmGridView: TfrmGridView2; AErrorLinkedDocTable: TErrorLinkedDocTable; AIDParamSubParam: Integer; APossibleLinkDocTables: TDictionary<Integer, TPossibleLinkDocTable>; ATableWithProgress: TTableWithProgress; OK: Boolean; begin Assert(AFDQuery <> nil); if AFDQuery.RecordCount = 0 then begin TDialog.Create.ErrorMessageDialog ('Нет компонентов в выбранной категории либо в БД'); Exit; end; // Создаём таблицу со всеми файлами документации ADocFilesTable := TDocFilesTable.Create(nil); try // Просим загрузить список файлов ADocFilesTable.LoadDocFiles(ADocFieldInfos); TfrmProgressBar.Process(ADocFilesTable, procedure(ASender: TObject) begin // Просим проанализировать, к каким компонентам можно привязать эти файлы APossibleLinkDocTables := AnalizeDocFiles(ADocFilesTable); end, 'Анализ найденных файлов документации', sFiles); finally FreeAndNil(ADocFilesTable); end; OK := False; for AIDParamSubParam in APossibleLinkDocTables.Keys do begin OK := APossibleLinkDocTables[AIDParamSubParam].RecordCount > 0; if OK then break; end; // Если есть что привязывать if OK then begin ATableWithProgress := TTableWithProgress.Create(nil); try // Клонируем курсор с компонентами ATableWithProgress.CloneCursor(AFDQuery); // Для того чтобы знать общее кол-во записей ATableWithProgress.Last; TfrmProgressBar.Process(ATableWithProgress, procedure(ASender: TObject) begin // Просим привязать компоненты к файлам AErrorLinkedDocTable := LinkToDocFiles(APossibleLinkDocTables, ATableWithProgress, ADocFieldInfos, AFDQuery.Connection, ANoRange); end, 'Поиск подходящих файлов документации', sComponents); finally FreeAndNil(ATableWithProgress); end; // Если в ходе привязки были ошибки if AErrorLinkedDocTable.RecordCount > 0 then begin // Отображаем список ошибок возникших при привязке AfrmGridView := TfrmGridView2.Create(nil); try with AfrmGridView do begin Caption := 'Ошибки автоматического прикрепления файлов документации'; ViewGridEx.DSWrap := AErrorLinkedDocTable.W; // Показываем что мы собираемся привязывать ShowModal; end; finally FreeAndNil(AfrmGridView); end; end; end else begin TDialog.Create.ComponentsDocFilesNotFound; end; for AIDParamSubParam in APossibleLinkDocTables.Keys do begin // Разрушаем таблицу в памяти APossibleLinkDocTables[AIDParamSubParam].Free; end; // Разрушаем сам словарь FreeAndNil(APossibleLinkDocTables); // Если нужно вывести отчёт об отсутсвующих файлах документации if ACheckAbsentDocFiles then begin // Проверяем на отсутсвующие файлы AAbsentDocTable := CheckAbsentDocFiles(ADocFieldInfos, AFDQuery); try // Если есть компоненты для которых отсутствует документация if AAbsentDocTable.RecordCount > 0 then begin AfrmGridView := TfrmGridView2.Create(nil); try AfrmGridView.Caption := 'Компоненты для которых отсутствует документация'; AfrmGridView.ViewGridEx.DSWrap := AAbsentDocTable.W; // группируем по папке AcxGridDBBandedColumn := AfrmGridView.ViewGridEx.MainView. GetColumnByFieldName(AAbsentDocTable.W.Folder.FieldName); Assert(AcxGridDBBandedColumn <> nil); AcxGridDBBandedColumn.GroupIndex := 0; AcxGridDBBandedColumn.Visible := False; // Показываем отчёт AfrmGridView.ShowModal; finally FreeAndNil(AfrmGridView); end; end; finally FreeAndNil(AAbsentDocTable); end; end; end; class function TAutoBind.CheckAbsentDocFiles(ADocFieldInfos : TList<TDocFieldInfo>; const AFDQuery: TFDQuery): TAbsentDocTable; var AComponentsClone: TTableWithProgress; ADocFieldInfo: TDocFieldInfo; AErrorMessage: string; AFolder: string; AFullName: string; f: TArray<String>; S: string; begin Assert(AFDQuery <> nil); // Создаём таблицу с компонентами у которых отсутствует документация Result := TAbsentDocTable.Create(nil); // Третий этап - ищем компоненты, для которых не задан (не найден) файл документации AComponentsClone := TTableWithProgress.Create(nil); try // Создаём клон компонентов AComponentsClone.CloneCursor(AFDQuery); // Цикл по всем видам документов, которые будем проверять for ADocFieldInfo in ADocFieldInfos do begin // Делим путь на части f := ADocFieldInfo.Folder.TrimRight(['\']).Split(['\']); Assert(Length(f) > 0); AFolder := f[Length(f) - 1]; AComponentsClone.First; AComponentsClone.CallOnProcessEvent; while not AComponentsClone.Eof do begin AErrorMessage := ''; S := AComponentsClone.FieldByName(ADocFieldInfo.FieldName).AsString; // Если компонент имеет файл документации if S <> '' then begin AFullName := TPath.Combine(ADocFieldInfo.Folder, S); if not TFile.Exists(AFullName) then AErrorMessage := Format('Cвязан с файлом %s, но файл не найден', [S]); end else begin // Если файл с документацией не задан AErrorMessage := 'Не задан файл документации'; end; if AErrorMessage <> '' then Result.W.AddError(AFolder, AComponentsClone.FieldByName('Value') .AsString, AErrorMessage); AComponentsClone.Next; AComponentsClone.CallOnProcessEvent; end; end; AComponentsClone.Close; finally FreeAndNil(AComponentsClone); end; Result.First; end; class function TAutoBind.LinkToDocFiles(APossibleLinkDocTables : TDictionary<Integer, TPossibleLinkDocTable>; const AComponentsDataSet: TTableWithProgress; ADocFieldInfos: TList<TDocFieldInfo>; AConnection: TFDCustomConnection; const ANoRange: Boolean): TErrorLinkedDocTable; procedure AppendError(APossibleLinkDocTable: TPossibleLinkDocTable); Var AFolder: string; S: String; begin S := ''; APossibleLinkDocTable.First; AFolder := TPath.Combine (TPath.GetFileName(APossibleLinkDocTable.RootFolder.AsString), TPath.GetDirectoryName(GetRelativeFileName(APossibleLinkDocTable.FileName. AsString, APossibleLinkDocTable.RootFolder.AsString))); while not APossibleLinkDocTable.Eof do begin S := IfThen(S.IsEmpty, '', S + ', '); S := S + TPath.GetFileNameWithoutExtension (APossibleLinkDocTable.FileName.AsString); APossibleLinkDocTable.Next; end; Result.Append; Result.W.ComponentName.F.AsString := APossibleLinkDocTable.ComponentName.AsString; Result.W.Folder.F.AsString := AFolder; Result.W.ErrorMessage.F.AsString := Format('Несколько возможных файлов (%s)', [S]); Result.Post; end; var ADocFieldInfo: TDocFieldInfo; APossibleLinkDocTable: TPossibleLinkDocTable; // ASQL: string; i: Integer; OK: Boolean; Q: TQuerySearchProductParameterValues; rc: Integer; S: String; begin Assert(APossibleLinkDocTables <> nil); Assert(AComponentsDataSet <> nil); Result := TErrorLinkedDocTable.Create(nil); AComponentsDataSet.BeginBatch(); // Список всех компонентов AComponentsDataSet.First; AComponentsDataSet.CallOnProcessEvent; Q := TQuerySearchProductParameterValues.Create(nil); // Будем работать в рамках одной транзакции AConnection.StartTransaction; try i := 0; while not AComponentsDataSet.Eof do begin // Цикл по всем типам файлов for ADocFieldInfo in ADocFieldInfos do begin // Если компонент ещё не имеет файла документации данного вида if (AComponentsDataSet.FieldByName(ADocFieldInfo.FieldName) .AsString.IsEmpty) then begin // Если для этого параметра существует таблица с возможными файлами if APossibleLinkDocTables.ContainsKey(ADocFieldInfo.IDParamSubParam) then begin APossibleLinkDocTable := APossibleLinkDocTables [ADocFieldInfo.IDParamSubParam]; // Ищем есть ли для этого компонента подходящие файлы подходящего типа APossibleLinkDocTable.Filter := Format('%s = %s', [APossibleLinkDocTable.ComponentName.FieldName, QuotedStr(AComponentsDataSet.FieldByName('Value').AsString)]); APossibleLinkDocTable.Filtered := True; rc := APossibleLinkDocTable.RecordCount; // Если нашли хотя-бы один подходящий файл if rc > 0 then begin // Первая запись - с самым узким диапазоном APossibleLinkDocTable.First; // Если подходящих файлов ровно 1 либо можно выбрать с самым узким диапазоном OK := (rc = 1) or (not ANoRange); // Если подходящих файлов несколько if not OK then begin // Имя файла без расширения S := TPath.GetFileNameWithoutExtension (APossibleLinkDocTable.FileName.AsString); // если первый из нескольких файлов в точности равен названию компонента OK := string.Compare(S, APossibleLinkDocTable.ComponentName.AsString, True) = 0; // Всё таки несколько файлов и ни один точно компоненту не соответствует if not OK then begin // Добавляем сообщение об ошибке AppendError(APossibleLinkDocTable); end; end; if OK then begin with Result do begin S := StrHelper.GetRelativeFileName (APossibleLinkDocTable.FileName.AsString, APossibleLinkDocTable.RootFolder.AsString); if Q.Search(ADocFieldInfo.IDParamSubParam, AComponentsDataSet.FieldByName('ID').AsInteger) = 0 then begin // А ТАК МОЖНО???? Q.AppendValue(S); { ASQL := 'INSERT INTO ParameterValues2' + '(ParamSubParamID, Value, ProductID) ' + Format('Values (%d, ''%s'', %d)', [ADocFieldInfo.IDParamSubParam, S, AComponentsDataSet.FieldByName('ID').AsInteger]); AConnection.ExecSQL(ASQL); } Inc(i); end; if i >= 1000 then begin AConnection.Commit; AConnection.StartTransaction; i := 0; end; end; end; end; end; end; end; AComponentsDataSet.Next; AComponentsDataSet.CallOnProcessEvent; end; finally AConnection.Commit; AComponentsDataSet.EndBatch; FreeAndNil(Q); end; end; class function TAutoBind.MySplit(const S: String): MySplitRec; var StartIndex: Integer; begin Result.Name := S; Result.Number := 0; StartIndex := S.Length - 1; // Пока в конце строки находим цифру while S.IndexOfAny(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], StartIndex) = StartIndex do Dec(StartIndex); Inc(StartIndex); // Если в конце строки были цифры if StartIndex < S.Length then begin Result.Number := StrToInt(S.Substring(StartIndex)); Result.Name := S.Substring(0, StartIndex); end; end; constructor TAbsentDocTable.Create(AOwner: TComponent); begin inherited; FW := TAbsentDocTableW.Create(Self); FieldDefs.Add(W.Folder.FieldName, ftWideString, 100); FieldDefs.Add(W.ComponentName.FieldName, ftWideString, 100); FieldDefs.Add(W.Description.FieldName, ftWideString, 150); CreateDataSet; Open; end; constructor TDocFilesTable.Create(AOwner: TComponent); begin inherited; FieldDefs.Add('FileName', ftWideString, 1000); FieldDefs.Add('RootFolder', ftWideString, 500); FieldDefs.Add('IDParamSubParam', ftInteger); CreateDataSet; Open; end; function TDocFilesTable.GetIDParamSubParam: TField; begin Result := FieldByName('IDParamSubParam'); end; function TDocFilesTable.GetFileName: TField; begin Result := FieldByName('FileName'); end; function TDocFilesTable.GetRootFolder: TField; begin Result := FieldByName('RootFolder'); end; procedure TDocFilesTable.LoadDocFiles(ADocFieldInfos: TList<TDocFieldInfo>); procedure AddFiles(ADocFieldInfo: TDocFieldInfo; const AFolder: String); Var // ASubFolder: string; m: TStringDynArray; S: string; begin m := TDirectory.GetFiles(AFolder); if Length(m) > 0 then begin // Цикл по всем найденным файлам for S in m do begin // Добавляем в таблицу запись о найденном файле Append; RootFolder.AsString := ADocFieldInfo.Folder; FileName.AsString := S; IDParamSubParam.AsInteger := ADocFieldInfo.IDParamSubParam; Post; end; end; // Получаем список дочерних директорий m := TDirectory.GetDirectories(AFolder); // Для каждой дочерней директории for S in m do begin // Рекурсивно получаем файлы в этой директории AddFiles(ADocFieldInfo, S); end; end; var ADocFieldInfo: TDocFieldInfo; begin // Цикл по всем видам документов, которые будем загружать for ADocFieldInfo in ADocFieldInfos do begin AddFiles(ADocFieldInfo, ADocFieldInfo.Folder); end; end; constructor TPossibleLinkDocTable.Create(AOwner: TComponent); begin inherited; FieldDefs.Add('FileName', ftWideString, 1000); FieldDefs.Add('RootFolder', ftWideString, 500); FieldDefs.Add('ComponentName', ftWideString, 200); FieldDefs.Add('Range', ftInteger); IndexDefs.Add('idxOrder', 'ComponentName;Range', []); CreateDataSet; IndexName := 'idxOrder'; Indexes[0].Active := True; Open; end; function TPossibleLinkDocTable.GetComponentName: TField; begin Result := FieldByName('ComponentName'); end; function TPossibleLinkDocTable.GetRange: TField; begin Result := FieldByName('Range'); end; function TPossibleLinkDocTable.GetFileName: TField; begin Result := FieldByName('FileName'); end; function TPossibleLinkDocTable.GetRootFolder: TField; begin Result := FieldByName('RootFolder'); end; constructor TErrorLinkedDocTable.Create(AOwner: TComponent); begin inherited; FW := TErrorLinkedDocTableW.Create(Self); FieldDefs.Add(W.ComponentName.FieldName, ftWideString, 200); FieldDefs.Add(W.Folder.FieldName, ftWideString, 500); FieldDefs.Add(W.ErrorMessage.FieldName, ftWideString, 1000); CreateDataSet; Open; end; constructor TErrorLinkedDocTableW.Create(AOwner: TComponent); begin inherited; FComponentName := TFieldWrap.Create(Self, 'ComponentName', 'Имя компонента'); FErrorMessage := TFieldWrap.Create(Self, 'ErrorMessage', 'Сообщение об ошибке'); FFolder := TFieldWrap.Create(Self, 'Folder', 'Папка'); end; constructor TAbsentDocTableW.Create(AOwner: TComponent); begin inherited; FComponentName := TFieldWrap.Create(Self, 'ComponentName', 'Имя компонента'); FDescription := TFieldWrap.Create(Self, 'Description', 'Описание'); FFolder := TFieldWrap.Create(Self, 'Folder', 'Папка'); end; procedure TAbsentDocTableW.AddError(const AFolder, AComponentName, AErrorMessage: string); begin Assert(Active); TryAppend; Folder.F.AsString := AFolder; ComponentName.F.AsString := AComponentName; Description.F.AsString := AErrorMessage; TryPost; end; end.
unit v_Env; interface uses System.sysutils, classes, IdStack, inifiles, variants, dateutils, h_db, firedac.comp.client; type TEnv = class(TObject) public class function UserName: string; class function MachineName: string; class function getIp: string; overload; // ip local class function getIp(pMachineName: string): string; overload; // ip de host específico class procedure LastAccess; type Date = class public class function FirstDayOfMonth: tdatetime; class function LastDayOfMonth: tdatetime; class function FirstDayOfYear: tdate; class function LastDayOfYear: tdate; class function FirstDayOfLastMonth: tdatetime; class function LastDayOfLastMonth: tdatetime; class function sumDays(i: integer): tdatetime; private class function f(pattern: string; date_base: tdatetime = 0): integer; end; type TUser = class(TObject) public class var NAME: string; ID: integer; class function isAdmin: boolean; class function isClient: boolean; class function isGerente: boolean; end; type TServerFTP = class public const User = 'u796938653.cliente'; password = '7JGCa7Ss6iu1o8tH'; // Old Host 31.170.166.122 host = 'ftp.smcsistemas.com.br'; end; type Database = class public type Local = Class private class function getServer: string; static; class procedure setServer(value: string); static; class function getDatabase: string; static; class procedure SetDatabase(const value: string); static; public class property Server: string read getServer write setServer; class function User: string; class function password: string; class property Database: string read getDatabase write SetDatabase; End; public type Online = Class const // Old Server: sql125.main-hosting.eu // New Server: sql1218.main-hosting.eu // Old Server IP: 31.170.166.103 // New IP: 31.220.50.194 * USE THIS // This configuration have to be made in TModule `connHostinger` component Server = '31.220.50.194'; User = 'u796938653_cli'; password = 'SGyHKA6yIVSCtL'; Database = 'u796938653_mngr'; End; end; type Version = class private class function getSys: variant; static; class procedure SetSys(value: variant); static; public class function Version: string; class property SYS: variant read getSys write SetSys; end; type Configurations = class private class function getLocalKey: TStringList; static; // dias sem verificar em inteiro class procedure setLocalKey(value: TStringList); static; // insere data de verificação em tdate public class property LOCAL_KEY: TStringList read getLocalKey write setLocalKey; end; Type Core = class const Caption = 'SMC LIGHT - v2.4.4012.47'; public class function isDebug: boolean; class function pdvOnly: boolean; end; type Printers = class public class function getNfce: string; static; class function getComprovanteVenda: string; static; class procedure setNFCe(value: string); static; class procedure setComprovanteVenda(value: string); static; class property NFCE: string read getNfce write setNFCe; class property COMPROVANTE_VENDA: string read getComprovanteVenda write setComprovanteVenda; end; end; implementation uses v_Dir, h_Functions; class function TEnv.UserName: string; begin result := GetEnvironmentVariable('USERNAME'); end; class function TEnv.MachineName: string; begin result := GetEnvironmentVariable('COMPUTERNAME'); end; class function TEnv.getIp: string; begin result := getIp(MachineName); end; class function TEnv.getIp(pMachineName: string): string; begin TIdStack.IncUsage; if GStack.IsIP(pMachineName) then result := pMachineName else result := GStack.ResolveHost(pMachineName); TIdStack.DecUsage; end; class procedure TEnv.LastAccess; procedure writeAccess; begin //tdb.ExecQuery('insert into acesso(data, usuario) values(?,?)', [System.sysutils.Date, TEnv.UserName]); end; var qry: tfdquery; i: integer; begin //qry := tdb.SimpleQuery('SELECT data from ACESSO order by data desc limit 1'); if qry <> nil then begin if comparedate(qry.Fields[0].AsDateTime, System.sysutils.Date) = 1 then raise Exception.Create('Verifique a data do seu computador!') else writeAccess; end else writeAccess end; { TEnv.Database } class function TEnv.Database.Local.getDatabase: string; begin result := TIniFile.Create(TDir.ConfigIni).readString('dados_conexao', 'Database', 'smc_automacao'); end; class function TEnv.Database.Local.password: string; begin result := TIniFile.Create(TDir.ConfigIni).readString('dados_conexao', 'password', '1234'); end; class procedure TEnv.Database.Local.SetDatabase(const value: string); begin TIniFile.Create(TDir.ConfigIni).writestring('dados_conexao', 'Database', value); end; class procedure TEnv.Database.Local.setServer(value: string); begin TIniFile.Create(TDir.ConfigIni).writestring('dados_conexao', 'Server', value); end; class function TEnv.Database.Local.getServer: string; begin result := TIniFile.Create(TDir.ConfigIni).readString('dados_conexao', 'Server', 'localhost'); end; class function TEnv.Database.Local.User: string; begin result := 'root'; end; class function TEnv.Version.getSys: variant; begin result := TIniFile.Create(TDir.ConfigIni).readString('atualizacao', 'versao', ''); result := TFunctions.replace(result, '.'); if result = '' then result := 0; end; class procedure TEnv.Version.SetSys(value: variant); begin TIniFile.Create(TDir.ConfigIni).writestring('atualizacao', 'versao', value); end; class function TEnv.Version.Version: string; begin result := TIniFile.Create(TDir.ConfigIni).readString('atualizacao', 'versao', ''); end; class function TEnv.TUser.isAdmin: boolean; begin result := name = 'ADMIN'; end; { TEnv.Date } class function TEnv.Date.f(pattern: string; date_base: tdatetime = 0): integer; begin if date_base = 0 then date_base := now; result := strtoint(formatdatetime(pattern, date_base)); end; class function TEnv.Date.FirstDayOfLastMonth: tdatetime; var dt: tdatetime; begin dt := IncMonth(now, -1); ReplaceDate(dt, EncodeDate(f('YYYY', dt), f('MM', dt), 1)); result := dt; end; class function TEnv.Date.LastDayOfLastMonth: tdatetime; var dt: tdatetime; begin dt := IncMonth(now, -1); ReplaceDate(dt, EndOfAMonth(f('YYYY', dt), f('MM', dt))); result := dt; end; class function TEnv.Date.FirstDayOfMonth: tdatetime; var dt: tdatetime; begin dt := now; ReplaceDate(dt, EncodeDate(f('YYYY'), f('MM'), 1)); result := dt; end; class function TEnv.Date.FirstDayOfYear: tdate; var dt: tdatetime; begin dt := now; ReplaceDate(dt, EncodeDate(f('YYYY'), 1, 1)); result := dt; end; class function TEnv.Date.LastDayOfMonth: tdatetime; var dt: tdatetime; begin dt := now; ReplaceDate(dt, EndOfAMonth(f('YYYY'), f('MM'))); result := dt; end; class function TEnv.Date.LastDayOfYear: tdate; var dt: tdatetime; begin dt := now; ReplaceDate(dt, EndOfAMonth(f('YYYY'), 12)); result := dt; end; class function TEnv.Date.sumDays(i: integer): tdatetime; begin result := incday(now, i); end; class function TEnv.TUser.isClient: boolean; var qry: tfdquery; begin result := False; //qry := tdb.SimpleQuery('select u.tipo_usuario, c.tipo_colaborador from usuario u join colaborador c on c.cod_usario = u.codigo where u.codigo = ?', // [SELF.ID]); //if qry <> nil then // result := (qry.Fields[0].asString = 'CLIENTE') and (qry.Fields[1].asString = '6'); end; class function TEnv.TUser.isGerente: boolean; var qry: tfdquery; begin result := False; //qry := tdb.SimpleQuery('select c.tipo_colaborador, u.tipo_usuario from usuario u left join colaborador c on c.cod_usuario = u.codigo where u.codigo = ?', // [TEnv.TUser.ID]); if qry <> nil then result := (qry.FieldByName('tipo_colaborador').value = '6') or (qry.FieldByName('tipo_usuario').value = 'SISTEMA'); end; class function TEnv.Configurations.getLocalKey: TStringList; var qry: tfdquery; key, cnpj, data, situacao: string; begin result := nil; //qry := tdb.SimpleQuery('select local_key from empresa'); if qry <> nil then begin key := TFunctions.CodeDecode(qry.Fields[0].asString, False); result := TStringList.Create; data := copy(key, 0, 10); key := TFunctions.replace(key, data); situacao := copy(key, length(key), 1); key := copy(key, 0, length(key) - 1); cnpj := key; result.Add(data); result.Add(cnpj); result.Add(situacao); result.Text; end; end; class procedure TEnv.Configurations.setLocalKey(value: TStringList); var str: string; begin if value <> nil then begin str := value.Strings[0]; str := str + value.Strings[1]; str := str + value.Strings[2]; str := TFunctions.CodeDecode(str, True); //tdb.ExecQuery('update empresa set local_key = ? where cnpj = ?', [str, value.Strings[1]]) end; end; { TEnv.Core } class function TEnv.Core.isDebug: boolean; begin result := {$IFDEF DEBUG}True{$ELSE}False{$ENDIF}; end; class function TEnv.Core.pdvOnly: boolean; begin TIniFile.Create(TDir.PreferencesIni).writebool('system', 'pdv_only', TIniFile.Create(TDir.PreferencesIni).readBool('system', 'pdv_only', False)); result := TIniFile.Create(TDir.PreferencesIni).readBool('system', 'pdv_only', False); end; { TEnv.Printer } class function TEnv.Printers.getComprovanteVenda: string; begin TEnv.Printers.COMPROVANTE_VENDA := TIniFile.Create(TDir.PreferencesIni).readString('printers', 'comprovante_venda', ''); result := TIniFile.Create(TDir.PreferencesIni).readString('printers', 'comprovante_venda', ''); end; class function TEnv.Printers.getNfce: string; begin TEnv.Printers.NFCE := TIniFile.Create(TDir.PreferencesIni).readString('printers', 'nfce', ''); result := TIniFile.Create(TDir.PreferencesIni).readString('printers', 'nfce', ''); end; class procedure TEnv.Printers.setComprovanteVenda(value: string); begin TIniFile.Create(TDir.PreferencesIni).writestring('printers', 'comprovante_venda', value); end; class procedure TEnv.Printers.setNFCe(value: string); begin TIniFile.Create(TDir.PreferencesIni).writestring('printers', 'nfce', value); end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 插件目录与插件参数类 //主要实现: //-----------------------------------------------------------------------------} unit untEasyClassPluginDirectory; interface uses Classes, DB, DBClient, Variants; type { TEasysysPluginsDirectory } TEasysysPluginsDirectory = class private { Private declarations } FPluginGUID: string; FPluginCName: string; FPluginEName: string; FiOrder: Integer; FImageIndex: Integer; FSelectedImageIndex: Integer; FIsDirectory: Boolean; FPluginFileName: string; FParentPluginGUID: string; FIsEnable: Boolean; FShowModal: Boolean; FRemark: string; public { Public declarations } property PluginGUID: string read FPluginGUID write FPluginGUID; property PluginCName: string read FPluginCName write FPluginCName; property PluginEName: string read FPluginEName write FPluginEName; property iOrder: Integer read FiOrder write FiOrder; property ImageIndex: Integer read FImageIndex write FImageIndex; property SelectedImageIndex: Integer read FSelectedImageIndex write FSelectedImageIndex; property IsDirectory: Boolean read FIsDirectory write FIsDirectory; property PluginFileName: string read FPluginFileName write FPluginFileName; property ParentPluginGUID: string read FParentPluginGUID write FParentPluginGUID; property IsEnable: Boolean read FIsEnable write FIsEnable; property ShowModal: Boolean read FShowModal write FShowModal; property Remark: string read FRemark write FRemark; class procedure GeneratePluginDirectory(var Data: OleVariant); class procedure GeneratePluginDirectoryList(var Data: OleVariant; AResult: TList); class procedure AppendClientDataSet(ACds: TClientDataSet; AObj: TEasysysPluginsDirectory; var AObjList: TList); class procedure EditClientDataSet(ACds: TClientDataSet; AObj: TEasysysPluginsDirectory); class procedure DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasysysPluginsDirectory; var AObjList: TList); end; { TEasysysPluginParam } TEasysysPluginParam = class private { Private declarations } FPluginParamGUID: string; FParamName: string; FValueType: string; FValue: string; FPluginGUID: string; public { Public declarations } property PluginParamGUID: string read FPluginParamGUID write FPluginParamGUID; property ParamName: string read FParamName write FParamName; property ValueType: string read FValueType write FValueType; property Value: string read FValue write FValue; property PluginGUID: string read FPluginGUID write FPluginGUID; class procedure GeneratePluginParam(var Data: OleVariant); class procedure GeneratePluginParamList(var Data: OleVariant; AResult: TList); class procedure AppendClientDataSet(ACds: TClientDataSet; AObj: TEasysysPluginParam; var AObjList: TList); class procedure EditClientDataSet(ACds: TClientDataSet; AObj: TEasysysPluginParam); class procedure DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasysysPluginParam; var AObjList: TList); end; var PluginDirectoryList, PluginParamsList: TList; implementation { TEasysysPluginsDirectory } class procedure TEasysysPluginsDirectory.GeneratePluginDirectoryList( var Data: OleVariant; AResult: TList); var I: Integer; AEasysysPluginsDirectory: TEasysysPluginsDirectory; AClientDataSet: TClientDataSet; begin //创建数据源,并获取数据 AClientDataSet := TClientDataSet.Create(nil); AClientDataSet.Data := Data; //此句为实例化指定的对象 AClientDataSet.First; try for I := 0 to AClientDataSet.RecordCount - 1 do begin AEasysysPluginsDirectory := TEasysysPluginsDirectory.Create; with AEasysysPluginsDirectory do begin PluginGUID := AClientDataSet.FieldByName('PluginGUID').AsString; PluginCName := AClientDataSet.FieldByName('PluginCName').AsString; PluginEName := AClientDataSet.FieldByName('PluginEName').AsString; iOrder := AClientDataSet.FieldByName('iOrder').AsInteger; ImageIndex := AClientDataSet.FieldByName('ImageIndex').AsInteger; SelectedImageIndex := AClientDataSet.FieldByName('SelectedImageIndex').AsInteger; IsDirectory := AClientDataSet.FieldByName('IsDirectory').AsBoolean; PluginFileName := AClientDataSet.FieldByName('PluginFileName').AsString; ParentPluginGUID := AClientDataSet.FieldByName('ParentPluginGUID').AsString; IsEnable := AClientDataSet.FieldByName('IsEnable').AsBoolean; ShowModal := AClientDataSet.FieldByName('ShowModal').AsBoolean; Remark := AClientDataSet.FieldByName('Remark').AsString; end; //在此添加将对象存放到指定容器的代码 AResult.Add(AEasysysPluginsDirectory); //如果要关联树也在此添加相应代码 AClientDataSet.Next; end; finally AClientDataSet.Free; end; end; class procedure TEasysysPluginsDirectory.GeneratePluginDirectory(var Data: OleVariant); var I: Integer; AEasysysPluginsDirectory: TEasysysPluginsDirectory; AClientDataSet: TClientDataSet; begin while (PluginDirectoryList.Count > 0) do begin TEasysysPluginsDirectory(PluginDirectoryList[0]).Free; PluginDirectoryList.Delete(0); end; //创建数据源,并获取数据 AClientDataSet := TClientDataSet.Create(nil); AClientDataSet.Data := Data; //此句为实例化指定的对象 AClientDataSet.First; try for I := 0 to AClientDataSet.RecordCount - 1 do begin AEasysysPluginsDirectory := TEasysysPluginsDirectory.Create; with AEasysysPluginsDirectory do begin PluginGUID := AClientDataSet.FieldByName('PluginGUID').AsString; PluginCName := AClientDataSet.FieldByName('PluginCName').AsString; PluginEName := AClientDataSet.FieldByName('PluginEName').AsString; iOrder := AClientDataSet.FieldByName('iOrder').AsInteger; ImageIndex := AClientDataSet.FieldByName('ImageIndex').AsInteger; SelectedImageIndex := AClientDataSet.FieldByName('SelectedImageIndex').AsInteger; IsDirectory := AClientDataSet.FieldByName('IsDirectory').AsBoolean; PluginFileName := AClientDataSet.FieldByName('PluginFileName').AsString; ParentPluginGUID := AClientDataSet.FieldByName('ParentPluginGUID').AsString; IsEnable := AClientDataSet.FieldByName('IsEnable').AsBoolean; ShowModal := AClientDataSet.FieldByName('ShowModal').AsBoolean; Remark := AClientDataSet.FieldByName('Remark').AsString; end; //在此添加将对象存放到指定容器的代码 PluginDirectoryList.Add(AEasysysPluginsDirectory); //如果要关联树也在此添加相应代码 AClientDataSet.Next; end; finally AClientDataSet.Free; end; end; class procedure TEasysysPluginsDirectory.AppendClientDataSet( ACds: TClientDataSet; AObj: TEasysysPluginsDirectory; var AObjList: TList); begin with ACds do begin Append; FieldByName('PluginGUID').AsString := AObj.PluginGUID; FieldByName('PluginCName').AsString := AObj.PluginCName; FieldByName('PluginEName').AsString := AObj.PluginEName; FieldByName('iOrder').AsInteger := AObj.iOrder; FieldByName('ImageIndex').AsInteger := AObj.ImageIndex; FieldByName('SelectedImageIndex').AsInteger := AObj.SelectedImageIndex; FieldByName('IsDirectory').AsBoolean := AObj.IsDirectory; FieldByName('PluginFileName').AsString := AObj.PluginFileName; FieldByName('ParentPluginGUID').AsString := AObj.ParentPluginGUID; FieldByName('IsEnable').AsBoolean := AObj.IsEnable; FieldByName('ShowModal').AsBoolean := AObj.ShowModal; FieldByName('Remark').AsString := AObj.Remark; Post; end; AObjList.Add(AObj) end; class procedure TEasysysPluginsDirectory.EditClientDataSet( ACds: TClientDataSet; AObj: TEasysysPluginsDirectory); begin if ACds.Locate('PluginGUID', VarArrayOf([AObj.PluginGUID]), [loCaseInsensitive]) then begin with ACds do begin Edit; FieldByName('PluginCName').AsString := AObj.PluginCName; FieldByName('PluginEName').AsString := AObj.PluginEName; FieldByName('iOrder').AsInteger := AObj.iOrder; FieldByName('ImageIndex').AsInteger := AObj.ImageIndex; FieldByName('SelectedImageIndex').AsInteger := AObj.SelectedImageIndex; FieldByName('IsDirectory').AsBoolean := AObj.IsDirectory; FieldByName('PluginFileName').AsString := AObj.PluginFileName; FieldByName('ParentPluginGUID').AsString := AObj.ParentPluginGUID; FieldByName('IsEnable').AsBoolean := AObj.IsEnable; FieldByName('ShowModal').AsBoolean := AObj.ShowModal; FieldByName('Remark').AsString := AObj.Remark; Post; end; end; end; class procedure TEasysysPluginsDirectory.DeleteClientDataSet( ACds: TClientDataSet; AObj: TEasysysPluginsDirectory; var AObjList: TList); var I, DelIndex: Integer; begin DelIndex := -1; if ACds.Locate('PluginGUID', VarArrayOf([AObj.PluginGUID]), [loCaseInsensitive]) then ACds.Delete; for I := 0 to AObjList.Count - 1 do begin if TEasysysPluginParam(AObjList[I]).PluginParamGUID = TEasysysPluginParam(AObj).PluginParamGUID then begin DelIndex := I; Break; end; end; if DelIndex <> -1 then begin TEasysysPluginParam(AObjList[DelIndex]).Free; AObjList.Delete(DelIndex); end; end; { TEasysysPluginParam } class procedure TEasysysPluginParam.AppendClientDataSet( ACds: TClientDataSet; AObj: TEasysysPluginParam; var AObjList: TList); begin with ACds do begin Append; FieldByName('PluginParamGUID').AsString := AObj.PluginParamGUID; FieldByName('ParamName').AsString := AObj.ParamName; FieldByName('ValueType').AsString := AObj.ValueType; FieldByName('Value').AsString := AObj.Value; FieldByName('PluginGUID').AsString := AObj.PluginGUID; Post; end; AObjList.Add(AObj); end; class procedure TEasysysPluginParam.DeleteClientDataSet( ACds: TClientDataSet; AObj: TEasysysPluginParam; var AObjList: TList); var I, DelIndex: Integer; begin DelIndex := -1; if ACds.Locate('PluginParamGUID', VarArrayOf([AObj.PluginParamGUID]), [loCaseInsensitive]) then ACds.Delete; for I := 0 to AObjList.Count - 1 do begin if TEasysysPluginParam(AObjList[I]).PluginParamGUID = TEasysysPluginParam(AObj).PluginParamGUID then begin DelIndex := I; Break; end; end; if DelIndex <> -1 then begin TEasysysPluginParam(AObjList[DelIndex]).Free; AObjList.Delete(DelIndex); end; end; class procedure TEasysysPluginParam.EditClientDataSet(ACds: TClientDataSet; AObj: TEasysysPluginParam); begin if ACds.Locate('PluginParamGUID', VarArrayOf([AObj.PluginParamGUID]), [loCaseInsensitive]) then begin with ACds do begin Edit; FieldByName('PluginParamGUID').AsString := AObj.PluginParamGUID; FieldByName('ParamName').AsString := AObj.ParamName; FieldByName('ValueType').AsString := AObj.ValueType; FieldByName('Value').AsString := AObj.Value; FieldByName('PluginGUID').AsString := AObj.PluginGUID; Post; end; end; end; class procedure TEasysysPluginParam.GeneratePluginParam(var Data: OleVariant); var I: Integer; AEasysysPluginParam: TEasysysPluginParam; AClientDataSet: TClientDataSet; begin if Assigned(PluginParamsList) then if PluginParamsList.Count > 0 then Exit; //创建数据源,并获取数据 AClientDataSet := TClientDataSet.Create(nil); AClientDataSet.Data := Data; //此句为实例化指定的对象 AClientDataSet.First; for I := 0 to AClientDataSet.RecordCount - 1 do begin AEasysysPluginParam := TEasysysPluginParam.Create; with AEasysysPluginParam do begin PluginParamGUID := AClientDataSet.FieldByName('PluginParamGUID').AsString; ParamName := AClientDataSet.FieldByName('ParamName').AsString; ValueType := AClientDataSet.FieldByName('ValueType').AsString; Value := AClientDataSet.FieldByName('Value').AsString; PluginGUID := AClientDataSet.FieldByName('PluginGUID').AsString; end; //在此添加将对象存放到指定容器的代码 PluginParamsList.Add(AEasysysPluginParam); //如果要关联树也在此添加相应代码 AClientDataSet.Next; end; end; class procedure TEasysysPluginParam.GeneratePluginParamList( var Data: OleVariant; AResult: TList); var I: Integer; AEasysysPluginParam: TEasysysPluginParam; AClientDataSet: TClientDataSet; begin //创建数据源,并获取数据 AClientDataSet := TClientDataSet.Create(nil); AClientDataSet.Data := Data; //此句为实例化指定的对象 AClientDataSet.First; for I := 0 to AClientDataSet.RecordCount - 1 do begin AEasysysPluginParam := TEasysysPluginParam.Create; with AEasysysPluginParam do begin PluginParamGUID := AClientDataSet.FieldByName('PluginParamGUID').AsString; ParamName := AClientDataSet.FieldByName('ParamName').AsString; ValueType := AClientDataSet.FieldByName('ValueType').AsString; Value := AClientDataSet.FieldByName('Value').AsString; PluginGUID := AClientDataSet.FieldByName('PluginGUID').AsString; end; //在此添加将对象存放到指定容器的代码 AResult.Add(AEasysysPluginParam); //如果要关联树也在此添加相应代码 AClientDataSet.Next; end; end; initialization PluginDirectoryList := TList.Create; finalization while (PluginDirectoryList.Count > 0) do begin TObject(PluginDirectoryList.Items[0]).Free; PluginDirectoryList.Delete(0); end; PluginDirectoryList.Free; if Assigned(PluginParamsList) then begin while (PluginParamsList.Count > 0) do begin TObject(PluginParamsList.Items[0]).Free; PluginParamsList.Delete(0); end; PluginParamsList.Free; end; end.
unit uTestUtils; interface uses DUnitX.TestFramework; type TAssertHelper = class helper for Assert class procedure AreEqual(const left, right : Cardinal; const message : string = '');overload; end; implementation { TAssertHelper } class procedure TAssertHelper.AreEqual(const left, right: Cardinal; const message: string); begin AreEqual(Integer(Left), Integer(right), message); end; end.
unit uNewGroup; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Rtti, FMX.Grid.Style, FMX.StdCtrls, FMX.Grid, FMX.ScrollBox, FMX.ListBox, FMX.Edit, FMX.Controls.Presentation, FMX.TabControl, FMX.Layouts, uUserInfo; type TfNewGroup = class(TForm) pgc1: TTabControl; ts1: TTabItem; Label1: TLabel; Label2: TLabel; edtGroupName: TEdit; edtGroupDesc: TEdit; ts2: TTabItem; Label6: TLabel; Label7: TLabel; lblNotice: TLabel; Button1: TButton; Button2: TButton; lstAllRight: TListBox; lstCurrRight: TListBox; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } FUserGroup : TUserGroup; procedure ShowAllRights; procedure ShowGroupRights; procedure MoveToGroupList(AFromList, AToList: TListBox); procedure MoveAll(AFromList, AToList: TListBox); public { Public declarations } procedure ShowInfo(AUserGroup : TUserGroup); procedure SaveInfo; end; var fNewGroup: TfNewGroup; implementation uses uUserControl, xFunction, FMX.DialogService; {$R *.fmx} { TfNewGroup } procedure TfNewGroup.Button1Click(Sender: TObject); procedure CheckUserGroup; begin if UserControl.CheckUGNameExists(edtGroupName.Text) then begin TDialogService.MessageDialog('该组名已存在!',TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, nil); pgc1.TabIndex := 0; edtGroupName.SetFocus; end else ModalResult := mrOk; end; begin if edtGroupName.Text = '' then begin TDialogService.MessageDialog('组名不能为空!',TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, nil); pgc1.TabIndex := 0; edtGroupName.SetFocus; end else begin if Assigned(FUserGroup) then begin if Assigned(UserControl) then begin if FUserGroup.ID = -1 then begin CheckUserGroup; end else begin if FUserGroup.Embedded then ModalResult := mrCancel else begin if FUserGroup.GroupName <> Trim(edtGroupName.Text) then CheckUserGroup else ModalResult := mrOk; end; end; end; end; end; end; procedure TfNewGroup.Button3Click(Sender: TObject); begin MoveToGroupList(lstAllRight, lstCurrRight); end; procedure TfNewGroup.Button4Click(Sender: TObject); begin MoveToGroupList(lstCurrRight, lstAllRight); end; procedure TfNewGroup.Button5Click(Sender: TObject); begin MoveAll(lstAllRight, lstCurrRight); end; procedure TfNewGroup.Button6Click(Sender: TObject); begin MoveAll(lstCurrRight, lstAllRight); end; procedure TfNewGroup.MoveAll(AFromList, AToList: TListBox); var I: Integer; begin for I := AFromList.Count - 1 downto 0 do begin AToList.Items.AddObject(AFromList.Items.Strings[I], AFromList.Items.Objects[I]); AFromList.Items.Delete(I); end; end; procedure TfNewGroup.MoveToGroupList(AFromList, AToList: TListBox); var I: Integer; begin for I := 0 to AFromList.Count - 1 do if AFromList.ItemIndex = i then begin AToList.Items.AddObject(AFromList.Items.Strings[I], AFromList.Items.Objects[I]); AFromList.Items.Delete(I); Break; end; end; procedure TfNewGroup.SaveInfo; var i : integer; ARight : TUserRight; begin if Assigned(FUserGroup) then begin FUserGroup.GroupName := Trim(edtGroupName.Text); FUserGroup.Description := Trim(edtGroupDesc.Text); ClearStringList(FUserGroup.Rights); for i := 0 to lstCurrRight.Items.Count - 1 do begin ARight := TUserRight.Create; ARight.Assign(TUserRight(lstCurrRight.Items.Objects[i])); FUserGroup.Rights.AddObject(ARight.RightName, ARight); end; end; end; procedure TfNewGroup.ShowAllRights; var AUserRightList : TStringList; i : integer; begin AUserRightList := UserControl.UserRightList; lstAllRight.Clear; lstCurrRight.Clear; for I := 0 to AUserRightList.Count - 1 do begin with lstAllRight.Items do begin AddObject(TUserRight(AUserRightList.Objects[i]).RightName, AUserRightList.Objects[i]); end; end; end; procedure TfNewGroup.ShowGroupRights; var i: Integer; nIndex : Integer; begin for i := 0 to FUserGroup.Rights.Count - 1 do begin nIndex := lstAllRight.Items.IndexOf( FUserGroup.Rights[ i ] ); if nIndex <> -1 then lstAllRight.ItemIndex := nIndex; MoveToGroupList( lstAllRight, lstCurrRight ); end; end; procedure TfNewGroup.ShowInfo(AUserGroup: TUserGroup); begin FUserGroup := AUserGroup; if Assigned(FUserGroup) then begin if Assigned(UserControl) then begin edtGroupName.Text := FUserGroup.GroupName; edtGroupDesc.Text := FUserGroup.Description; ShowAllRights; if FUserGroup.ID <> -1 then begin ShowGroupRights; if FUserGroup.Embedded then begin ts1.Enabled := False; ts2.Enabled := False; lblNotice.Text := '系统内置,不能编辑修改'; lblNotice.Visible := True; end; end; end; end; end; end.
(** This module contains common functions (non-OTA) for use throughout the application. @Author David Hoyle @Version 1.0 @Date 05 Jan 2018 **) Unit ITHelper.CommonFunctions; Interface Uses Classes, ITHelper.ExternalProcessInfo; {$INCLUDE CompilerDefinitions.inc} Type (** A type to define an array of strings. **) TDGHArrayOfString = Array Of String; (** A method signature for the DGHCreateProcess message event handler. **) TITHProcessMsgHandler = Procedure(Const strMsg : String; Var boolAbort : Boolean) Of Object; (** A method signature for the DGHCreateProcess idle event handler. **) TITHIdleHandler = Procedure Of Object; Procedure BuildNumber(Const strFileName : String; Var iMajor, iMinor, iBugFix, iBuild : Integer); Function BuildRootKey : String; Function ComputerName : String; Function DGHCreateProcess(Const Process : TITHProcessInfo; Const ProcessMsgHandler : TITHProcessMsgHandler; Const IdleHandler : TITHIdleHandler) : Integer; Function DGHFindOnPath(Var strEXEName : String; Const strDirs : String) : Boolean; Function DGHPos(Const cDelimiter : Char; Const strText : String; Const iStartPos : Integer) : Integer; Function DGHPathRelativePathTo(Const strBasePath : String; Var strFileName : String) : Boolean; Function DGHSplit(Const strText : String; Const cDelimiter : Char) : TDGHArrayOfString; Function Like(Const strPattern, strText : String) : Boolean; Function UserName : String; Implementation Uses SysUtils, Windows, SHFolder; (** This is a method which obtains information about the package from is version information with the package resources. @precon None. @postcon Extracts and display the applications version number present within the EXE file. @param strFileName as a String as a constant @param iMajor as an Integer as a reference @param iMinor as an Integer as a reference @param iBugFix as an Integer as a reference @param iBuild as an Integer as a reference **) Procedure BuildNumber(Const strFileName : String; Var iMajor, iMinor, iBugFix, iBuild : Integer); Const iShiftRight16 = 16; iWordMask = $FFFF; Var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; Begin VerInfoSize := GetFileVersionInfoSize(PChar(strFileName), Dummy); If VerInfoSize <> 0 Then Begin GetMem(VerInfo, VerInfoSize); Try GetFileVersionInfo(PChar(strFileName), 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); iMajor := VerValue^.dwFileVersionMS Shr iShiftRight16; iMinor := VerValue^.dwFileVersionMS And iWordMask; iBugFix := VerValue^.dwFileVersionLS Shr iShiftRight16; iBuild := VerValue^.dwFileVersionLS And iWordMask; Finally FreeMem(VerInfo, VerInfoSize); End; End; End; (** This method builds the root key INI filename for the loading and saving of settings from the instance handle for the module. @precon None. @postcon Builds the root key INI filename for the loading and saving of settings from the instance handle for the module. @return a String **) Function BuildRootKey : String; Const strINIPattern = '%s Settings for %s on %s.INI'; strSeasonsFall = '\Season''s Fall\'; Var strModuleName: String; strINIFileName: String; strUserAppDataPath: String; strBuffer: String; iSize: Integer; Begin SetLength(strBuffer, MAX_PATH); iSize := GetModuleFileName(hInstance, PChar(strBuffer), MAX_PATH); SetLength(strBuffer, iSize); strModuleName := strBuffer; strINIFileName := ChangeFileExt(ExtractFileName(strBuffer), ''); While (Length(strINIFileName) > 0) And (CharInSet(strINIFileName[Length(strINIFileName)], ['0' .. '9'])) Do strINIFileName := Copy(strINIFileName, 1, Length(strINIFileName) - 1); strINIFileName := Format(strINIPattern, [strINIFileName, UserName, ComputerName]); SetLength(strBuffer, MAX_PATH); SHGetFolderPath(0, CSIDL_APPDATA Or CSIDL_FLAG_CREATE, 0, SHGFP_TYPE_CURRENT, PChar(strBuffer)); strBuffer := StrPas(PChar(strBuffer)); strUserAppDataPath := strBuffer + strSeasonsFall; If Not DirectoryExists(strUserAppDataPath) Then ForceDirectories(strUserAppDataPath); Result := strUserAppDataPath + strINIFileName; End; (** This function returns the users computer name as a String. @precon None. @postcon Returns the users computer name as a String. @return a String **) Function ComputerName : String; Var iSize : Cardinal; Begin iSize := MAX_PATH; SetLength(Result, iSize); GetComputerName(@Result[1], iSize); Win32Check(LongBool(iSize)); SetLength(Result, iSize); End; (** This function creates a process with message handlers which must be implemented by the passed interface in order for the calling process to get messages from the process console and handle idle and abort. @precon ProcMsgHndr must be a valid class implementing TDGHCreateProcessEvent. @postcon Creates a process with message handlers which must be implemented by the passed interface in order for the calling process to get messages from the process console and handle idle and abort. @param Process as a TITHProcessInfo as a constant @param ProcessMsgHandler as a TITHProcessMsgHandler as a constant @param IdleHandler as a TITHIdleHandler as a constant @return an Integer **) Function DGHCreateProcess(Const Process : TITHProcessInfo; Const ProcessMsgHandler : TITHProcessMsgHandler; Const IdleHandler : TITHIdleHandler) : Integer; Type EDGHCreateProcessException = Exception; ResourceString strDirectoryNotFound = 'The directory "%s" does not exist.'; strUserAbort = 'User Abort!'; strEXENotFound = 'The executable file "%s" does not exist.'; Const iPipeSize = 4096; iWaitInMilliSec = 50; Var boolAbort: Boolean; strEXE: String; (** This prcoedure is called periodically by the process handler in order to retreive console output from the running process. Output everything from the console (pipe the anonymous pipe) but the last line as this may not be a complete line of information from the console (except if boolPurge is true). @precon slLines must be a valid instance of a TStringList class to accumulate the console output. @postcon Outputs to the IDGHCreareProcessEvent interface output information from the console. @param slLines as a TStringList as a constant @param hRead as a THandle as a constant @param Purge as a Boolean as a constant **) Procedure ProcessOutput(Const slLines : TStringList; Const hRead : THandle; Const Purge : Boolean = False); Const iLFCRLen = 2; Var iTotalBytesInPipe : Cardinal; iBytesRead : Cardinal; {$IFNDEF D2009} strOutput : String; {$ELSE} strOutput : AnsiString; {$ENDIF} Begin If Assigned(Idlehandler) Then IdleHandler; If boolAbort Then Begin If Assigned(ProcessMsgHandler) Then ProcessMsgHandler(strUserAbort, boolAbort); Exit; End; Win32Check(PeekNamedPipe(hRead, Nil, 0, Nil, @iTotalBytesInPipe, Nil)); If iTotalBytesInPipe > 0 Then Begin SetLength(strOutput, iTotalBytesInPipe); ReadFile(hRead, strOutput[1], iTotalBytesInPipe, iBytesRead, Nil); SetLength(strOutput, iBytesRead); {$IFNDEF D2009} slLines.Text := Copy(slLines.Text, 1, Length(slLines.Text) - iLFCRLen) + strOutput; {$ELSE} slLines.Text := Copy(slLines.Text, 1, Length(slLines.Text) - iLFCRLen) + UTF8ToString(strOutput); {$ENDIF} End; // Use a string list to output each line except the last as it may not // be complete yet. If Assigned(ProcessMsgHandler) Then While slLines.Count > 1 - Integer(Purge) Do Begin ProcessMsgHandler(slLines[0], boolAbort); slLines.Delete(0); End; End; Var hRead, hWrite : THandle; slLines : TStringList; SecurityAttrib : TSecurityAttributes; StartupInfo : TStartupInfo; ProcessInfo : TProcessInformation; iExitCode : Cardinal; Begin Result := 0; boolAbort := False; FillChar(SecurityAttrib, SizeOf(SecurityAttrib), 0); SecurityAttrib.nLength := SizeOf(SecurityAttrib); SecurityAttrib.bInheritHandle := True; SecurityAttrib.lpSecurityDescriptor := nil; Win32Check(CreatePipe(hRead, hWrite, @SecurityAttrib, iPipeSize)); Try If Process.FEnabled Then Try If Not DirectoryExists(Process.FDir) Then Raise EDGHCreateProcessException.CreateFmt(strDirectoryNotFound, [Process.FDir]); If Not FileExists(Process.FEXE) Then Begin strEXE := Process.FEXE; If Not DGHFindOnPath(strEXE, '') Then Raise EDGHCreateProcessException.CreateFmt(strEXENotFound, [strEXE]); End; FillChar(StartupInfo, SizeOf(TStartupInfo), 0); StartupInfo.cb := SizeOf(TStartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; StartupInfo.wShowWindow := SW_HIDE; StartupInfo.hStdOutput := hWrite; StartupInfo.hStdError := hWrite; Win32Check(CreateProcess(PChar(Process.FEXE), PChar('"' + Process.FEXE + '" ' + Process.FParams), @SecurityAttrib, Nil, True, CREATE_NEW_CONSOLE, Nil, PChar(Process.FDir), StartupInfo, ProcessInfo)); Try slLines := TStringList.Create; Try While WaitforSingleObject(ProcessInfo.hProcess, iWaitInMilliSec) = WAIT_TIMEOUT Do Begin ProcessOutput(slLines, hRead); If boolAbort Then Begin TerminateProcess(ProcessInfo.hProcess, 0); Break; End; End; ProcessOutput(slLines, hRead, True); Finally slLines.Free; End; If GetExitCodeProcess(ProcessInfo.hProcess, iExitCode) Then Inc(Result, iExitCode) Finally Win32Check(CloseHandle(ProcessInfo.hThread)); Win32Check(CloseHandle(ProcessInfo.hProcess)); End; Except On E : EDGHCreateProcessException Do If Assigned(ProcessMsgHandler) Then Begin ProcessMsgHandler(E.Message, boolAbort); Inc(Result); End; End; Finally Win32Check(CloseHandle(hWrite)); Win32Check(CloseHandle(hRead)); End; End; (** This method searches the given paths (semi-colon delimited) and the enironment path for the exe file name. If found the result is true and the full path to the file is returned in strEXEName. @precon None. @postcon Searches the given paths (semi-colon delimited) and the enironment path for the exe file name . If found the result is true and the full path to the file is returned in strEXEName. @param strEXEName as a String as a reference @param strDirs as a String as a constant @return a Boolean **) Function DGHFindOnPath(Var strEXEName : String; Const strDirs : String) : Boolean; (** This procedure checks the paths for being empty (and deltees them) and ensures they termiante with a backslash. @precon None. @postcon Empty paths are deleted and all end with a backslash. @param slPaths as a TStringList as a constant **) Procedure CheckPaths(Const slPaths : TStringList); Var iPath : Integer; iLength: Integer; Begin If strDirs <> '' Then slPaths.Text := strDirs + ';' + slPaths.Text; slPaths.Text := StringReplace(slPaths.Text, ';', #13#10, [rfReplaceAll]); For iPath := slPaths.Count - 1 DownTo 0 Do Begin iLength := Length(slPaths[iPath]); If iLength = 0 Then slPaths.Delete(iPath) Else If slPaths[iPath][iLength] <> '\' Then slPaths[iPath] := slPaths[iPath] + '\'; End; End; (** This method attempts to find the executable on the given path. @precon None. @postcon Returns true if the EXE is found. @param strExPath as a String as a constant @return a Boolean **) Function FindPath(Const strExPath : String) : Boolean; Var recSearch: TSearchRec; iResult: Integer; Begin Result := False; iResult := FindFirst(strExPath + strEXEName, faAnyFile, recSearch); Try If iResult = 0 Then Begin strEXEName := strExPath + strEXEName; Result := True; End; Finally SysUtils.FindClose(recSearch); End; End; Const strPathEnvName = 'path'; Var slPaths : TStringList; iPath: Integer; strPath, strExPath : String; iSize: Integer; Begin Result := False; slPaths := TStringList.Create; Try slPaths.Text := GetEnvironmentVariable(strPathEnvName); CheckPaths(slPaths); strEXEName := ExtractFileName(strEXEName); For iPath := 0 To slPaths.Count - 1 Do Begin strPath := slPaths[iPath]; SetLength(strExPath, MAX_PATH); iSize := ExpandEnvironmentStrings(PChar(strPath), PChar(strExPath), MAX_PATH); SetLength(strExPath, Pred(iSize)); If FindPath(strExPath) Then Begin Result := True; Break; End; End; Finally slPaths.Free; End; End; (** This method returns true and the given filename as a relative path IF the filename and the base path share the same root else returns false. @precon None. @postcon Returns true and the given filename as a relative path IF the filename and the base path share the same root else returns false. @param strBasePath as a String as a constant @param strFileName as a String as a reference @return a Boolean **) Function DGHPathRelativePathTo(Const strBasePath : String; Var strFileName : String) : Boolean; Const iLenOfUnicodePreamble = 2; Var iPos : Integer; strFile : String; strNewBasePath : String; Begin Result := False; strFile := strFileName; strNewBasePath := strBasePath; If (Copy(strNewBasePath, 1, iLenOfUnicodePreamble) = '\\') And (Copy(strFile, 1, iLenOfUnicodePreamble) = '\\') Then Begin strNewBasePath := Copy(strNewBasePath, iLenOfUnicodePreamble + 1, MAX_PATH); strFile := Copy(strFile, iLenOfUnicodePreamble + 1, MAX_PATH); End; iPos := Pos('\', strNewBasePath); While (iPos > 0) And (CompareText(Copy(strNewBasePath, 1, iPos), Copy(strFile, 1, iPos)) = 0) Do Begin Result := True; strNewBasePath := Copy(strNewBasePath, iPos + 1, MAX_PATH); strFile := Copy(strFile, iPos + 1, MAX_PATH); iPos := Pos('\', strNewBasePath); End; If Result Then Begin strFileName := ''; While iPos > 0 Do Begin strNewBasePath := Copy(strNewBasePath, iPos + 1, MAX_PATH); iPos := Pos('\', strNewBasePath); strFileName := strFileName + '..\'; End; strFileName := strFileName + strFile; End; End; (** This function returns the first position of the delimiter character in the given string on or after the starting point. @precon None. @postcon Returns the position of the firrst delimiter after the starting point. @note Used to workaround backward compatability issues with String.Split and StringSplit. @param cDelimiter as a Char as a constant @param strText as a String as a constant @param iStartPos as an Integer as a constant @return an Integer **) Function DGHPos(Const cDelimiter : Char; Const strText : String; Const iStartPos : Integer) : Integer; Var I : Integer; Begin Result := 0; For i := iStartPos To Length(strText) Do If strText[i] = cDelimiter Then Begin Result := i; Break; End; End; (** This function splits a string into an array of strings based on the given delimiter character. @precon None. @postcon Splits the given string by the delimmiters and returns an array of strings. @note Used to workaround backward compatability issues with String.Split and StringSplit. @param strText as a String as a constant @param cDelimiter as a Char as a constant @return a TDGHArrayOfString **) Function DGHSplit(Const strText : String; Const cDelimiter : Char) : TDGHArrayOfString; Var iSplits : Integer; i: Integer; iStart, iEnd : Integer; Begin iSplits := 0; For i := 1 To Length(strText) Do If strText[i] = cDelimiter Then Inc(iSplits); SetLength(Result, Succ(iSplits)); i := 0; iStart := 1; While DGHPos(cDelimiter, strText, iStart) > 0 Do Begin iEnd := DGHPos(cDelimiter, strText, iStart); Result[i] := Copy(strText, iStart, iEnd - iStart); Inc(i); iStart := iEnd + 1; End; Result[i] := Copy(strText, iStart, Length(strText) - iStart + 1); End; (** This function returns true if the pattern matches the text. @precon None. @postcon Returns true if the pattern matches the text. @param strPattern as a String as a constant @param strText as a String as a constant @return a Boolean **) Function Like(Const strPattern, strText : String) : Boolean; Type TMatchType = (mtStart, mtEnd); TMatchTypes = Set Of TMatchType; (** This method checks the start, middle and end of the text against the pattern. @precon None. @postcon Returns true of the text matches the pattern. @param strLocalPattern as a String as a constant @param MatchTypes as a TMatchTypes as a constant @return a Boolean **) Function CheckPattern(Const strLocalPattern : String; Const MatchTypes : TMatchTypes) : Boolean; (** This fucntion checks the end of the text against the given pattern stored in the string list. @precon sl must be a valid instance. @postcon Returns true of the pattern does not matches the end of the text. @param sl as a TStringList as a constant @param MatchTypes as a TMatchTypes as a constant @return a Boolean **) Function CheckEnd(Const sl : TStringList; Const MatchTypes : TMatchTypes) : Boolean; Begin Result := False; If sl.Count > 0 Then If mtEnd In MatchTypes Then If CompareText(sl[sl.Count - 1], Copy(strText, Length(strText) - Length(sl[sl.Count - 1]) + 1, Length(sl[sl.Count - 1]))) <> 0 Then Result := True; End; (** This method checks the inner part of the pattern against the text. @precon sl must be a valid instance. @postcon Returns true if the pattern does not match the text. @param sl as a TStringList as a constant @param MatchTypes as a TMatchTypes as a constant @param iStartIndex as an Integer as a reference @return a Boolean **) Function CheckInBetween(Const sl : TStringList; Const MatchTypes : TMatchTypes; Var iStartIndex : Integer) : Boolean; Var i : Integer; iPos : Integer; Begin Result := False; For i := Integer(mtStart In MatchTypes) To sl.Count - 1 - Integer(mtEnd In MatchTypes) Do Begin iPos := Pos(sl[i], lowercase(strText)); If (iPos = 0) Or (iPos < iStartIndex) Then Begin Result := True; Break; End;; Inc(iStartIndex, Length(sl[i])); End; End; (** This method checks the start of the tetx against the pattern. @precon sl must be a valid instance. @postcon Returns true if the pattern does not match. @param sl as a TStringList as a constant @param MatchTypes as a TMatchTypes as a constant @param iStartIndex as an Integer as a reference @return a Boolean **) Function CheckStart(Const sl : TStringList; Const MatchTypes : TMatchTypes; Var iStartIndex : Integer) : Boolean; Begin Result := False; iStartIndex := 1; If sl.Count > 0 Then If mtStart In MatchTypes Then If CompareText(sl[0], Copy(strText, 1, Length(sl[0]))) <> 0 Then Begin Result := True; Exit; End Else Inc(iStartIndex, Length(sl[0])); End; Var sl : TStringList; astrParts : TDGHArrayOfString; i: Integer; iStartIndex : Integer; Begin Result := False; sl := TStringList.Create; Try astrParts := DGHSplit(strLocalPattern, '*'); For i := Low(astrParts) To High(astrParts) Do sl.Add(astrParts[i]); If CheckStart(sl, MatchTypes, iStartIndex) Then Exit; If CheckInBetween(sl, MatchTypes, iStartIndex) Then Exit; If CheckEnd(sl, MatchTypes) Then Exit; Result := True; Finally sl.Free; End; End; Var MatchTypes : TMatchTypes; strLocalPattern : String; Begin strLocalPattern := strPattern; Result := False; MatchTypes := []; If Length(strLocalPattern) = 0 Then Exit; If strLocalPattern = '*' Then Begin Result := True; Exit; End; If strLocalPattern[1] <> '*' Then Include(MatchTypes, mtStart) Else Delete(strLocalPattern, 1, 1); If Length(strLocalPattern) > 0 Then If strLocalPattern[Length(strLocalPattern)] <> '*' Then Include(MatchTypes, mtEnd) Else Delete(strLocalPattern, Length(strLocalPattern), 1); Result := CheckPattern(strLocalPattern, MatchTypes); End; (** This function returns the users logon name as a String. @precon None. @postcon Returns the users logon name as a String. @return a String **) Function UserName : String; Var iSize : Cardinal; Begin iSize := MAX_PATH; SetLength(Result, iSize); GetUserName(@Result[1], iSize); Win32Check(LongBool(iSize)); SetLength(Result, iSize - 1); End; End.
{------------------------------------------------------------------------------ This file is part of the MotifMASTER project. This software is distributed under GPL (see gpl.txt for details). This software 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. Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru) ------------------------------------------------------------------------------} unit SelfCopied; interface uses Classes, ComponentList, SysUtils, CBRCComponent, SelfSaved, ClassInheritIDs; type ISelfCopied = interface ['{DF1ABB41-F255-11D4-968F-C7AD39AA7469}'] function GetCopy: TObject; procedure CopyParameters(const Dest: TObject); procedure SetSelfCopyingMode(const AMode: LongInt); function GetSelfCopyingMode: LongInt; end; const SelfCopiedGUID: TGUID = '{DF1ABB41-F255-11D4-968F-C7AD39AA7469}'; type TSelfCopiedComponent = class(TCBRCComponent, ISelfCopied) protected class function GetPropHeaderRec: TPropHeaderRec; override; class procedure ReadProperties( const Reader: TReader; const PropHeaderRec: TPropHeaderRec; const AnObject: TSelfSavedComponent ); override; class procedure WriteProperties( const Writer: TWriter; const AnObject: TSelfSavedComponent ); override; public function GetCopy: TObject; virtual; procedure CopyParameters(const Dest: TObject); virtual; procedure SetSelfCopyingMode(const AMode: LongInt); virtual; abstract; function GetSelfCopyingMode: LongInt; virtual; abstract; end; ESelfCopiedCompList = class(Exception); TSelfCopiedCompList = class(TComponentList, ISelfCopied) protected class function GetPropHeaderRec: TPropHeaderRec; override; class procedure ReadProperties( const Reader: TReader; const PropHeaderRec: TPropHeaderRec; const AnObject: TSelfSavedComponent ); override; class procedure WriteProperties( const Writer: TWriter; const AnObject: TSelfSavedComponent ); override; public function GetCopy: TObject; virtual; function GetSharedCopy: TObject; virtual; procedure CopyParameters(const Dest: TObject); virtual; procedure SetSelfCopyingMode(const AMode: LongInt); virtual; abstract; function GetSelfCopyingMode: LongInt; virtual; abstract; procedure Insert(Index: Integer; Item: TComponent); override; function Add(Item: TComponent): Integer; override; end; function CreateNewSelfCopiedCompList: TSelfCopiedCompList; implementation type TSCCL = class(TSelfCopiedCompList) protected class function GetPropHeaderRec: TPropHeaderRec; override; class procedure ReadProperties( const Reader: TReader; const PropHeaderRec: TPropHeaderRec; const AnObject: TSelfSavedComponent ); override; class procedure WriteProperties( const Writer: TWriter; const AnObject: TSelfSavedComponent ); override; end; function CreateNewSelfCopiedCompList: TSelfCopiedCompList; begin Result := TSCCL.Create(nil); end; function TSelfCopiedCompList.GetCopy: TObject; begin Result := NewInstance; TSelfCopiedCompList(Result).Create(nil); CopyParameters(Result); end; function TSelfCopiedCompList.GetSharedCopy: TObject; var i: LongInt; begin Result := NewInstance; TSelfCopiedCompList(Result).Create(nil); for i := 0 to Count - 1 do TSelfCopiedCompList(Result).Add(TComponent(Items[i])); end; procedure TSelfCopiedCompList.CopyParameters(const Dest: TObject); var i: LongInt; ISC: ISelfCopied; begin if Dest.ClassType <> Self.ClassType then raise ESelfCopiedCompList.Create('Invalid destination type...'); if Count <> 0 then if Count <> TSelfCopiedCompList(Dest).Count then begin TSelfCopiedCompList(Dest).Clear; for i := 0 to Count - 1 do begin if Items[i].GetInterface(SelfCopiedGUID, ISC) then TSelfCopiedCompList(Dest).Add(TComponent(ISC.GetCopy)) else raise ESelfCopiedCompList.Create('Invalid item type...'); end; end else begin for i := 0 to Count - 1 do begin if Items[i].GetInterface(SelfCopiedGUID, ISC) then ISC.CopyParameters(TSelfCopiedCompList(Dest).Items[i]) else raise ESelfCopiedCompList.Create('Invalid item type...'); end; end; end; procedure TSelfCopiedCompList.Insert(Index: Integer; Item: TComponent); var ISC: ISelfCopied; begin if Item.GetInterface(SelfCopiedGUID, ISC) then inherited else raise ESelfCopiedCompList.Create('Invalid item type...'); end; function TSelfCopiedCompList.Add(Item: TComponent): Integer; var ISC: ISelfCopied; begin if Item.GetInterface(SelfCopiedGUID, ISC) then Result := inherited Add(Item) else raise ESelfCopiedCompList.Create('Invalid item type...'); end; function TSelfCopiedComponent.GetCopy: TObject; begin Result := NewInstance; TSelfCopiedComponent(Result).Create(nil); CopyParameters(Result); end; procedure TSelfCopiedComponent.CopyParameters(const Dest: TObject); begin if Dest.ClassType <> Self.ClassType then raise ESelfCopiedCompList.Create('Invalid destination type...'); end; class function TSelfCopiedComponent.GetPropHeaderRec: TPropHeaderRec; begin Result.ClassInheritID := SCCClassInheritID; Result.PropVersionNum := SCCCurVerNum; end; class procedure TSelfCopiedComponent.ReadProperties(const Reader: TReader; const PropHeaderRec: TPropHeaderRec; const AnObject: TSelfSavedComponent); begin end; class procedure TSelfCopiedComponent.WriteProperties(const Writer: TWriter; const AnObject: TSelfSavedComponent); begin end; class function TSelfCopiedCompList.GetPropHeaderRec: TPropHeaderRec; begin Result.ClassInheritID := SCCLClassInheritID; Result.PropVersionNum := SCCLCurVerNum; end; class procedure TSelfCopiedCompList.ReadProperties(const Reader: TReader; const PropHeaderRec: TPropHeaderRec; const AnObject: TSelfSavedComponent); begin end; class procedure TSelfCopiedCompList.WriteProperties(const Writer: TWriter; const AnObject: TSelfSavedComponent); begin end; { TSCCL } class function TSCCL.GetPropHeaderRec: TPropHeaderRec; begin Result.ClassInheritID := SCCLAlClassInheritID; Result.PropVersionNum := SCCLAlCurVerNum; end; class procedure TSCCL.ReadProperties(const Reader: TReader; const PropHeaderRec: TPropHeaderRec; const AnObject: TSelfSavedComponent); begin end; class procedure TSCCL.WriteProperties(const Writer: TWriter; const AnObject: TSelfSavedComponent); begin end; initialization RegisterClass(TSelfCopiedComponent); RegisterClass(TSelfCopiedCompList); RegisterClass(TSCCL); end.
unit ORM.Model.EMPLOYEE; interface uses Spring, Spring.Collections, Spring.Persistence.Mapping.Attributes, ORM.Model.SALARY_HISTORY; {$M+} type [Entity] [Table('EMPLOYEE')] // [Sequence('SELECT GEN_ID(EMP_NO_GEN, 1) FROM RDB$DATABASE')] TEmployee = class private FId: Integer; FFirstname: string; FLastname: string; FPhoneExt: string; FHireDate: TDateTime; FDepartmentId: string; FJobCode: string; FJobGrande: Integer; FJobCountry: string; FSalary: Double; FFullName: string; FSalaryHistory: Lazy<IList<TSalaryHistory>>; function GetSalaryHistory(): IList<TSalaryHistory>; procedure SetSalaryHistory(const Value: IList<TSalaryHistory>); public constructor Create; destructor Destroy; override; [OneToMany(False, [ckCascadeAll])] property SalaryHistory: IList<TSalaryHistory> read GetSalaryHistory write SetSalaryHistory; [AutoGenerated] [Column('EMP_NO', [cpRequired, cpPrimaryKey, cpNotNull])] property Id: Integer read FId write FId; [Column('FIRST_NAME')] property Firstname: string read FFirstname write FFirstname; [Column('LAST_NAME')] property Lastname: string read FLastname write FLastname; [Column('PHONE_EXT', [], 4)] property PhoneExt: string read FPhoneExt write FPhoneExt; [Column('HIRE_DATE')] property HireDate: TDateTime read FHireDate write FHireDate; [Column('DEPT_NO', [cpRequired], 3)] property DepartmentId: string read FDepartmentId write FDepartmentId; [Column('JOB_CODE', [cpRequired], 5)] property JobCode: string read FJobCode write FJobCode; [Column('JOB_GRADE', [cpRequired])] property JobGrande: Integer read FJobGrande write FJobGrande; [Column('JOB_COUNTRY', [cpRequired], 15)] property JobCountry: string read FJobCountry write FJobCountry; [Column('SALARY', [], 10, 0, 2)] property Salary: Double read FSalary write FSalary; end; {$M-} implementation { TEmployee } constructor TEmployee.Create; begin inherited Create; FSalaryHistory := TCollections.CreateObjectList<TSalaryHistory>; end; destructor TEmployee.Destroy; begin //... inherited; end; function TEmployee.GetSalaryHistory: IList<TSalaryHistory>; begin Result := FSalaryHistory; end; procedure TEmployee.SetSalaryHistory(const Value: IList<TSalaryHistory>); begin FSalaryHistory := Value; end; end.
unit utils; interface uses Windows, TypInfo, Variables, SysUtils, Classes; type //自定义和SysUtil里的定义冲突了,悲剧 TByteArray = Variables.TByteArray; function CountMemoryRegionsAllMemory(MemoryRegions: TMemoryRegions): Integer; procedure AverageMemoryRegionsToArray(var MemoryRegions: TMemoryRegions; var resultArray: TMemoryRegionsArray{TResultArray}); procedure AverageMemoryRegionsToArray2(var MemoryRegions: TMemoryRegions; var resultArray: TMemoryRegionsArray); //把ListArray的8个TList类型的元素平均一下 procedure AverageListArray(data: TResultArray); function CountResultArray(resultArray: TResultArray):Cardinal; function CountByteArrayBlocksMemory(resultArray: TResultArray):Cardinal; function CountFirst(resultArray: TResultArray):Cardinal; function CountListArray(resultArray: TResultArray):Cardinal; function JoinListArrayFast(data: TResultArray): TList; procedure InitMemoLog; procedure CloseMemoLog; procedure ClearMemoLog; procedure ShowLogToMemo(s: string); implementation uses ReadMemoryFrm; function CountMemoryRegionsAllMemory(MemoryRegions: TMemoryRegions): Integer; var i: Integer; begin Result := 0; for i := Low(memoryRegions) to High(memoryRegions) do Inc(Result, MemoryRegions[i].MemorySize); end; procedure SortMemoryRegions(var MemoryRegions: TMemoryRegions); var i, j, k, high1: Integer; max: Cardinal; begin high1 := High(MemoryRegions); for i := Low(MemoryRegions) to high1 do begin max := MemoryRegions[i].MemorySize; for j := i + 1 to high1 do if max < MemoryRegions[j].MemorySize then begin max := MemoryRegions[j].MemorySize; k := j; end; if i <> k then begin MemoryRegions[k].MemorySize := MemoryRegions[i].MemorySize; MemoryRegions[i].MemorySize := max; max := MemoryRegions[k].BaseAddress; MemoryRegions[k].BaseAddress := MemoryRegions[i].BaseAddress; MemoryRegions[i].BaseAddress := max; end; end; end; procedure AverageMemoryRegionsToArray(var MemoryRegions: TMemoryRegions; var resultArray: TMemoryRegionsArray); var i, j, k, m, jHead, jBackwardHead, len, jBackward: Integer; count: Cardinal; avr, c1, c2: Integer; mr: TMemoryRegions; counts: array[0..threadCount - 1] of Integer; begin count := CountMemoryRegionsAllMemory(MemoryRegions); //showLogToMemo(Format('count1=%d',[count])); avr := count div threadCount + 1 ;// +1预防丢弃 SortMemoryRegions(MemoryRegions); //count := CountMemoryRegionsAllMemory(MemoryRegions); //showLogToMemo(Format('count2=%d',[count])); j := Low(MemoryRegions); jBackward := High(MemoryRegions); jHead := j; jBackwardHead := jBackward; for i := 0 to threadCount - 2 do//减2,最后剩下的不用这么麻烦了,还产生bug begin count := 0; c1 := 0; //while count < avr do//理论上只需要这样便可以了,j < jBackward不可能发生 while (count < avr) and (j < jBackward) do begin Inc(count, MemoryRegions[j].MemorySize); Inc(j); Inc(c1); end; if c1 > 1 then//才一项就大于avr时,则保留 begin Dec(j);//减1 Dec(count, MemoryRegions[j].MemorySize); end; c2 := 0; while (count < avr) and (j < jBackward) do begin Inc(count, MemoryRegions[jBackward].MemorySize); Dec(jBackward); Inc(c2); end; //Dec(j);//再减1,因为最后一次加上的已经被减去了 //Inc(jBackward);//加1,因为? //这个计算要慢慢思考 len := (j - jHead) + (jBackwardHead - jBackward); mr := nil; SetLength(mr, len); m := 0; for k := jHead to j - 1 do//j代表的项并未计算 begin mr[m].BaseAddress := MemoryRegions[k].BaseAddress; mr[m].MemorySize := MemoryRegions[k].MemorySize; Inc(m); end; for k := jBackward + 1 to jBackwardHead do//jBackward代表的项并未计算 begin mr[m].BaseAddress := MemoryRegions[k].BaseAddress; mr[m].MemorySize := MemoryRegions[k].MemorySize; Inc(m); end; resultArray[i] := mr; jHead := j; jBackwardHead := jBackward; //showLogToMemo(Format('jHead=%d,j=%d,jbackward=%d,jbackwarHead=%d',[jHead,j,jbackward,jbackwardHead])); end; len := jBackward - j + 1; mr := nil; SetLength(mr, len); m := 0; for k := j to jBackward do//j代表的项并未计算 begin mr[m].BaseAddress := MemoryRegions[k].BaseAddress; mr[m].MemorySize := MemoryRegions[k].MemorySize; Inc(m); end; resultArray[threadCount - 1] := mr; end; procedure AverageMemoryRegionsToArray2(var MemoryRegions: TMemoryRegions; var resultArray: TMemoryRegionsArray{TResultArray}); var i, count, j, k, m, last, this, len: Cardinal; avr: Integer; //mra: TMemoryRegionsArray; //pms: PMemoryRegions; tms: TMemoryRegions; counts: array[0..threadCount - 1] of Integer; begin count := CountMemoryRegionsAllMemory(MemoryRegions); avr := count div threadCount + 1 ;// +1预防丢弃 count := 0; this := High(MemoryRegions); last := this; j := Low(MemoryRegions);//至少留下一项 for i := threadCount - 1 downto 1 do begin repeat Inc(count, MemoryRegions[this].MemorySize); Dec(this); until (count > avr) or (this = j); //内存管理啊,对我来说太难了,这段要设置外部数组的改了好多好多次 tms := resultArray[i]; len := last - this; SetLength(tms, len); len := SizeOf(TMemoryRegion) * len; //GetMem(resultArray[i], len);//setLength后再用GetMem就再次分配了 CopyMemory(tms, @MemoryRegions[this + 1], len); resultArray[i] := tms;//setLength可能改变tms的值(地址) last := this; count := 0; if this = 0 then Break;//不知为什么会发生这种情况 end; SetLength(MemoryRegions, this + 1); resultArray[0] := MemoryRegions; end; //把ListArray的8个TList类型的元素平均一下 procedure AverageListArray(data: TResultArray); var i, count, j, k, m: Cardinal; avr: Integer; list1, list2: TList; begin count := 0; for i := 0 to threadCount - 1 do if data[i] <> nil then Inc(count, TList(data[i]).Count); avr := count div threadCount + 1 ;// +1预防丢弃 ShowLogToMemo(Format('count%d,avr=%d', [count, avr])); for i := 0 to threadCount - 1 do begin if TList(data[i]) <> nil then if TList(data[i]).Count > avr then begin list1 := TList(data[i]); for j := 0 to threadCount - 1 do begin if data[j] <> nil then if TList(data[j]).Count < avr then begin list2 := TList(data[j]); //计算应该转移的数量,避免又加多了 m := avr - list2.Count;//laa[j]比平均数少的数量,多于laa[i]比平均数多的数量 if ((list1.Count - avr) <= m )then for k := list1.Count - 1 downto avr do begin list2.Add((list1[k])); list1.Delete(k); end else//laa[j]比平均数少的数量,少于laa[i]比平均数多的数量 for k := list1.Count - 1 downto list1.Count - 1 - m do begin list2.Add((list1[k])); list1.Delete(k); end; end; end; end; end; end; function CountResultArray(resultArray: TResultArray):Cardinal; var i: Integer; begin Result := 0; for i:= 0 to threadCount - 1 do inc(Result, Cardinal(resultArray[i])); end; function CountListArray(resultArray: TResultArray):Cardinal; var i: Integer; begin Result := 0; for i:= 0 to threadCount - 1 do if resultArray[i] <> nil then inc(Result, TList(resultArray[i]).Count); end; function CountByteArrayBlocksMemory(resultArray: TResultArray):Cardinal; var i, j: Integer; babs: TByteArrayBlocks; begin Result := 0; for i:= 0 to threadCount - 1 do begin babs := TByteArrayBlocks(resultArray[i]); if babs <> nil then for j := Low(babs) to High(babs) do try inc(Result, babs[j].count); except ShowLogToMemo(Format( 'i=%d,j=%d,Low()=%d,High()=%d' , [i,j, Low(babs),High(babs)])); end; end; end; function CountFirst(resultArray: TResultArray):Cardinal; var i, j: Integer; begin Result := 0; for i:= 0 to threadCount - 1 do if(resultArray[i] <> nil) then for j := 0 to Tlist(resultArray[i]).Count - 1 do inc(Result, PByteArrayBlock(Tlist(resultArray[i])).count); end; function JoinListArrayFast(data: TResultArray): TList; var i, j: integer; list: TList; begin Result := TList.Create; for i := 0 to threadCount - 1 do if data[i] <> nil then begin list := TList(data[i]); for j := list.Count - 1 downto 0 do begin Result.Add(list[j]); list.Delete(j); end; FreeAndNil(list); end; end; procedure InitMemoLog; begin mmLog := ReadMemoryForm.mmLog; end; procedure CloseMemoLog; begin mmLog := nil; end; procedure showLogToMemo(s: string); begin mmlog.Lines.Add(s); end; procedure ClearMemoLog; begin mmLog.Lines.Clear; end; end.
unit BCEditor.Editor.Selection; interface uses Classes, Graphics, BCEditor.Editor.Selection.Colors, BCEditor.Types; type TBCEditorSelection = class(TPersistent) strict private FActiveMode: TBCEditorSelectionMode; FColors: TBCEditorSelectedColor; FMode: TBCEditorSelectionMode; FOnChange: TNotifyEvent; FOptions: TBCEditorSelectionOptions; FVisible: Boolean; procedure DoChange; procedure SetActiveMode(const Value: TBCEditorSelectionMode); procedure SetColors(const Value: TBCEditorSelectedColor); procedure SetMode(const Value: TBCEditorSelectionMode); procedure SetOnChange(Value: TNotifyEvent); procedure SetOptions(Value: TBCEditorSelectionOptions); procedure SetVisible(const Value: Boolean); public constructor Create; destructor Destroy; override; procedure Assign(Source: TPersistent); override; property ActiveMode: TBCEditorSelectionMode read FActiveMode write SetActiveMode stored False; published property Colors: TBCEditorSelectedColor read FColors write SetColors; property Mode: TBCEditorSelectionMode read FMode write SetMode default smNormal; property Options: TBCEditorSelectionOptions read FOptions write SetOptions default [soHighlightSimilarTerms]; property Visible: Boolean read FVisible write SetVisible default True; property OnChange: TNotifyEvent read FOnChange write SetOnChange; end; implementation { TBCEditorSelection } constructor TBCEditorSelection.Create; begin inherited; FColors := TBCEditorSelectedColor.Create; FActiveMode := smNormal; FMode := smNormal; FOptions := [soHighlightSimilarTerms]; FVisible := True; end; destructor TBCEditorSelection.Destroy; begin FColors.Free; inherited Destroy; end; procedure TBCEditorSelection.SetOnChange(Value: TNotifyEvent); begin FOnChange := Value; FColors.OnChange := FOnChange; end; procedure TBCEditorSelection.Assign(Source: TPersistent); begin if Assigned(Source) and (Source is TBCEditorSelection) then with Source as TBCEditorSelection do begin Self.FColors.Assign(FColors); Self.FActiveMode := FActiveMode; Self.FMode := FMode; Self.FOptions := FOptions; Self.FVisible := FVisible; if Assigned(Self.FOnChange) then Self.FOnChange(Self); end else inherited Assign(Source); end; procedure TBCEditorSelection.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TBCEditorSelection.SetColors(const Value: TBCEditorSelectedColor); begin FColors.Assign(Value); end; procedure TBCEditorSelection.SetMode(const Value: TBCEditorSelectionMode); begin if FMode <> Value then begin FMode := Value; ActiveMode := Value; DoChange; end; end; procedure TBCEditorSelection.SetActiveMode(const Value: TBCEditorSelectionMode); begin if FActiveMode <> Value then begin FActiveMode := Value; DoChange; end; end; procedure TBCEditorSelection.SetVisible(const Value: Boolean); begin if FVisible <> Value then begin FVisible := Value; DoChange; end; end; procedure TBCEditorSelection.SetOptions(Value: TBCEditorSelectionOptions); begin if (Value <> FOptions) then begin FOptions := Value; DoChange; end; end; end.
unit PopupForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxDropDownEdit, NotifyEvents; type TfrmPopupForm = class(TForm) procedure FormHide(Sender: TObject); private FCloseOnEscape: Boolean; FOnHide: TNotifyEventsEx; function GetPopupWindow: TcxCustomEditPopupWindow; { Private declarations } protected procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY; property PopupWindow: TcxCustomEditPopupWindow read GetPopupWindow; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property CloseOnEscape: Boolean read FCloseOnEscape write FCloseOnEscape; property OnHide: TNotifyEventsEx read FOnHide; { Public declarations } end; implementation uses FormsHelper, ProjectConst; {$R *.dfm} constructor TfrmPopupForm.Create(AOwner: TComponent); begin inherited Create(AOwner); FCloseOnEscape := True; FOnHide := TNotifyEventsEx.Create(Self); TFormsHelper.SetFont(Self, BaseFontSize); end; destructor TfrmPopupForm.Destroy; begin FreeAndNil(FOnHide); inherited; end; procedure TfrmPopupForm.CMDialogKey(var Message: TCMDialogKey); begin with Message do if (FCloseOnEscape) and // разрешено закрывать окно по Esc (CharCode = VK_ESCAPE) and // была нажата клавиша Escape (KeyDataToShiftState(KeyData) = []) then // сдвиговые клавиши не тронуты begin PopupWindow.CloseUp; end; inherited; end; procedure TfrmPopupForm.FormHide(Sender: TObject); begin FOnHide.CallEventHandlers(Self); end; function TfrmPopupForm.GetPopupWindow: TcxCustomEditPopupWindow; var PopupWindow: TCustomForm; begin PopupWindow := GetParentForm(Self); Result := PopupWindow as TcxCustomEditPopupWindow; end; end.
unit PascalCoin.RPC.Test.DM; interface uses System.SysUtils, System.Classes, Spring; type TDM = class(TDataModule) private FOnURIChange: Event<TGetStrProc>; FURI: string; function GetOnURIChange: IEvent<TGetStrProc>; procedure SetURI(const Value: string); { Private declarations } public { Public declarations } property OnURIChange: IEvent<TGetStrProc> read GetOnURIChange; property URI: string read FURI write SetURI; end; var DM: TDM; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} { TDataModule1 } function TDM.GetOnURIChange: IEvent<TGetStrProc>; begin result := FOnURIChange; end; procedure TDM.SetURI(const Value: string); begin FURI := Value; FOnURIChange.Invoke(Value); end; end.
unit Md5ExplorerMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, Vcl.Menus, cxMemo, Vcl.StdCtrls, cxButtons, cxLabel, cxTextEdit, cxMaskEdit, cxButtonEdit, cxClasses, dxSkinsForm, dxSkinOffice2010Silver; type TForm8 = class(TForm) cxButtonEdit1: TcxButtonEdit; cxLabel1: TcxLabel; cxButton1: TcxButton; cxMemo1: TcxMemo; OpenDialog1: TOpenDialog; dxSkinController1: TdxSkinController; procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxButton1Click(Sender: TObject); private procedure PrintMD5(const fn: string); procedure PrintVersion(const fn: string); public end; var Form8: TForm8; implementation uses IdHashMessageDigest; {$R *.dfm} procedure TForm8.PrintVersion(const fn: string); begin var FHandle, FSize: DWORD; FSize := GetFileVersionInfoSize(PChar(fn), FHandle); if FSize = 0 then begin Application.MessageBox('Не удалось найти информацию о версии!', PChar(Application.Title), MB_ICONSTOP); Exit; end; var FBuffer: pointer; GetMem(FBuffer, FSize); try if not GetFileVersionInfo(PChar(fn), FHandle, FSize, FBuffer) then begin Application.MessageBox('Не удалось прочитать информацию о версии!', PChar(Application.Title), MB_ICONSTOP); Exit; end; var Len: UINT; var FFI: PVSFixedFileInfo; if not VerQueryValue(FBuffer, '\', Pointer(FFI), Len) then begin Application.MessageBox('Не удалось прочитать информацию о версии!', PChar(Application.Title), MB_ICONSTOP); Exit; end; var s: string; s := IntToStr(FFI^.dwProductVersionMS shr 16) + '.' + IntToStr(FFI^.dwProductVersionMS and $FFFF) + '.' + IntToStr(FFI^.dwProductVersionLS shr 16) + '.' + IntToStr(FFI^.dwProductVersionLS and $FFFF); cxMemo1.Lines.Add('Версия: ' + s); // verSys.DW[0] := FFI^.dwProductVersionLS; // verSys.DW[1] := FFI^.dwProductVersionMS; finally FreeMem(FBuffer); end; end; procedure TForm8.PrintMD5(const fn: string); begin var f := TFileStream.Create(fn, fmOpenRead or fmShareDenyNone); var md5 := TIdHashMessageDigest5.Create; try cxMemo1.Lines.Add('MD5: ' + md5.HashStreamAsHex(f)); finally md5.Free(); f.Free(); end; end; procedure TForm8.cxButton1Click(Sender: TObject); begin var fn := OpenDialog1.FileName; cxMemo1.Lines.Clear(); if not FileExists(fn) then begin Application.MessageBox('Файл не найден!', PChar(Application.Title), MB_ICONSTOP); Exit; end; cxMemo1.Lines.Add('Файл: ' + fn); PrintMD5(fn); PrintVersion(fn); end; procedure TForm8.cxButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin if not OpenDialog1.Execute() then Exit; cxButtonEdit1.Text := OpenDialog1.FileName; cxButton1Click(nil); end; end.
{ ALGORITHME : Morpions Une partie se déroule avec 2 joueurs, l'un choisi les croix l'autre les ronds. Le joueur qui commence est choisi au hasard. CONST MaxCell=3 NbToursMax=9 Type RondCroix = (X,O) Victoire = (VictoireJ1,VictoireJ2) Type Joueur = ENREGISTREMENT Symbole:RondCroix NbMancheGagnee:Entier FIN ENREGISTREMENT Type TabMorp=Tableau [1..3,1..3] de car TabJ=Tableau[1..2] de Joueur procedure Initiatilisation(VAR Morp:TabMorp) VAR i,j:entier DEBUT //Revoir Initialisation POUR i DE 1 A MaxCell FAIRE POUR j DE 1 A MaxCell FAIRE Morp[i,j]<-" " FINPOUR FINPOUR FIN procedure Affichage(Morp:TabMorp) VAR i,j:entier DEBUT ECRIRE("MORPION : ") POUR i DE 1 A MaxCell FAIRE POUR j DE 1 A MaxCell FAIRE SI (j=MaxCell) ALORS ECRIRE(Morp[i,j]) SINON ECRIRE(Morp[i,j],'|') FINPOUR ECRIRE() //Fonction saut de ligne FINPOUR FIN FONCTION ChoixJoueur:ENTIER VAR J:entier nb:entier DEBUT // Fonction permettant de créer un aléatoire randomize nb<-random((2)+1) SI (nb=1) alors J<-1 SINON J<-2 FINSI ChoixJoueur<-J FIN procedure ChoixRC(VAR TabJoueur:TabJ;J:entier) VAR RC,RC2:RondCroix i:entier DEBUT REPETER ECRIRE("Taper 'X' ou 'O' pour choisir") LIRE(RC) JUSQU'A (RC=X) OU (RC=O) TabJoueur[J].Symbole<-RC SI RC=X alors RC2<-O SINON RC2<-X FINSI SI J=1 alors TabJoueur[2].Symbole<-RC2 SINON TabJoueur[1].Symbole<-RC2 FINSI POUR i DE 1 A 2 FAIRE ECRIRE('Le joueur ',i,' jouera avec les ',TabJoueur[i].Symbole) FINPOUR FIN FONCTION VideOk(L,C:Entier;Morp:TabMorp):boolean DEBUT SI (Morp[L,C]<>' ') ALORS VideOk<-FAUX SINON VideOk<-VRAI FINSI FIN procedure Placement(VAR Morp:TabMorp;TabJoueur:TabJ;Joueur:Entier) VAR PosChaine:chaine L,C:entier TestVide:booleen Symb:car DEBUT REPETER ECRIRE("Veuillez placer votre symbole - Saisir de cette maniere (L/C)"); LIRE(PosChaine); L<-StrToInt(Extraction(PosChaine,1,1)) //Appel d'une fonction de changement de type d'une chaine à un entier C<-StrToInt(Extraction(PosChaine,3,1)) TestVide<-VideOk(L,C,Morp) // Fait appel à la fonction VideOk qui vérifie si la cellule du tableau est vide. JUSQU'A (TestVide=VRAI) SI TestVide=VRAI ALORS SI TabJoueur[Joueur].Symbole=O ALORS Symb<-'O' SINON Symb<-'X' FINSI Morp[L,C]<-Symb FINSI FIN procedure Alignement(Morp:TabMorp;TabJoueur:TabJ;VAR Vict:Victoire) DEBUT SI ((Morp[1,1]='X') ET (Morp[1,2]='X') ET (Morp[1,3]='X')) OU ((Morp[2,1]='X') ET (Morp[2,2]='X') ET (Morp[2,3]='X')) OU ((Morp[3,1]='X') ET (Morp[3,2]='X') ET (Morp[3,3]='X')) OU ((Morp[1,1]='X') ET (Morp[2,1]='X') ET (Morp[3,1]='X')) OU ((Morp[1,2]='X') ET (Morp[2,2]='X') ET (Morp[3,2]='X')) OU ((Morp[1,3]='X') ET (Morp[2,3]='X') ET (Morp[3,3]='X')) OU ((Morp[1,1]='X') ET (Morp[2,2]='X') ET (Morp[3,3]='X')) OU ((Morp[3,1]='X') ET (Morp[2,2]='X') ET (Morp[1,3]='X')) ALORS SI TabJoueur[1].Symbole=X ALORS Vict<-VictoireJ1 SINON Vict<-VictoireJ2 FINSI FINSI SI ((Morp[1,1]='O') ET (Morp[1,2]='O') ET (Morp[1,3]='O')) OU ((Morp[2,1]='O') ET (Morp[2,2]='O') ET (Morp[2,3]='O')) OU ((Morp[3,1]='O') ET (Morp[3,2]='O') ET (Morp[3,3]='O')) OU ((Morp[1,1]='O') ET (Morp[2,1]='O') ET (Morp[3,1]='O')) OU ((Morp[1,2]='O') ET (Morp[2,2]='O') ET (Morp[3,2]='O')) OU ((Morp[1,3]='O') ET (Morp[2,3]='O') ET (Morp[3,3]='O')) OU ((Morp[1,1]='O') ET (Morp[2,2]='O') ET (Morp[3,3]='O')) OU ((Morp[3,1]='O') ET (Morp[2,2]='O') ET (Morp[1,3]='O')) ALORS SI TabJoueur[1].Symbole=O ALORS Vict<-VictoireJ1 SINON Vict<-VictoireJ2 FINSI FINSI FIN procedure TourDeJeu(VAR Morp:TabMorp;VAR J:entier;VAR TabJoueur:TabJ) VAR i:entier PosChaine:chaine L,C:entier Vict:Victoire DEBUT i<-0 REPETER Clear // Appel de la fonction clrscr pour "nettoyer" l'écran i<-i+1 Affichage(Morp) SI J=1 ALORS ECRIRE("Tour ",i," : Le joueur ",J," joue les ",TabJoueur[J].Symbole) Placement(Morp,TabJoueur,J) Affichage(Morp) Alignement(Morp,TabJoueur,Vict) J<-J+1 Attendre// Appel de la fonction readln pour laisser l'affichage SINON ECRIRE("Tour ",i," : Le joueur ",J," joue les ",TabJoueur[J].Symbole) Placement(Morp,TabJoueur,J) Affichage(Morp) Alignement(Morp,TabJoueur,Vict) J<-J-1 Attendre// Appel de la fonction readln pour laisser l'affichage FINSI JUSQU'A ((i=NbToursMax) OU (Vict=VictoireJ1) OU (Vict=VictoireJ2)); SI (Vict=VictoireJ1) ALORS ECRIRE("Le joueur 1 a gagné !") TabJoueur[1].NbMancheGagnee:=TabJoueur[1].NbMancheGagnee+1 FINSI SI (Vict=VictoireJ2) ALORS ECRIRE("Le joueur 2 a gagné !") TabJoueur[2].NbMancheGagnee:=TabJoueur[2].NbMancheGagnee+1 FINSI SI ((i=NbToursMax) ET NON (Vict=VictoireJ1) ET NON (Vict=VictoireJ2)) ALORS ECRIRE("Egalité") FIN //Programme principal : VAR Morp:TabMorp J:entier TabJoueur:TabJ manche:entier i,k:entier DEBUT Clear // Appel de la fonction clrscr qui "nettoie" l'écran ECRIRE("Entrez le nombre de manches que vous voulez jouer") LIRE(manche) POUR i DE 1 A manche FAIRE Clear // Appel de la fonction clrscr qui "nettoie" l'écran Initiatilisation(Morp) Affichage(Morp) J:=ChoixJoueur ECRIRE("Le joueur ",J," commence et choisit les X ou les O ") ChoixRC(TabJoueur,J) Attendre //Appel de la fonction readln pour laisser l'affichage TourDeJeu(Morp,J,TabJoueur) FINPOUR ECRIRE("Nombre de manche(s) gagnée(s)")) POUR k DE 1 A 2 FAIRE ECRIRE("Joueur ",k," : "TabJoueur[k].NbMancheGagnee) FINPOUR Attendre //Appel de la fonction readln pour laisser l'affichage FIN } Program Morpion; uses crt,sysutils; CONST MaxCell=3; NbToursMax=9; Type RondCroix = (X,O); Victoire = (VictoireJ1,VictoireJ2); Type Joueur = RECORD Symbole:RondCroix; NbMancheGagnee:integer; Nom:string; END; Type TabMorp=Array [1..MaxCell,1..MaxCell] of char; TabJ=Array[1..2] of Joueur; procedure Initiatilisation(VAR Morp:TabMorp); //Initialise le tableau du morpion qui contiendra soit les X soit les O VAR i,j:integer; BEGIN for i:=1 to MaxCell do BEGIN for j:=1 to MaxCell do BEGIN Morp[i,j]:=' '; END; END; END; procedure NomJoueur(VAR T1:TabJ); var i:integer; begin For i:=1 to 2 do begin writeln('Entrez le nom du joueur :'); readln(T1[i].Nom); end; end; procedure Affichage(Morp:TabMorp); // Fonction d'affichage du tableau contenant les X et les O VAR i,j:integer; BEGIN writeln('MORPION :'); for i:=1 to MaxCell do BEGIN for j:=1 to MaxCell do BEGIN if (j=MaxCell) then write(Morp[i,j]) else write(Morp[i,j],'|'); END; writeln; END; END; function ChoixJoueur(VAR T1:TabJ):integer; VAR J:integer; nb:integer; BEGIN randomize; nb:=random((2)+1); if (nb=1) then J:=1 else J:=2; ChoixJoueur:=J; END; procedure ChoixRC(VAR TabJoueur:TabJ;J:integer;VAR T1:TabJ); VAR RC,RC2:RondCroix; i:integer; BEGIN REPEAT begin writeln('X ou O pour choisir'); readln(RC); end; UNTIL (RC=X) OR (RC=O) ; TabJoueur[J].Symbole:=RC; if RC=X then RC2:=O else RC2:=X; if J=1 then TabJoueur[2].Symbole:=RC2 else TabJoueur[1].Symbole:=RC2; FOR i:=1 TO 2 DO begin writeln('Le joueur ',T1[i].Nom,' a les ',TabJoueur[i].Symbole); end; END; function VideOk(L,C:integer;Morp:TabMorp):boolean; BEGIN if (Morp[L,C]<>' ') then VideOk:=FALSE else VideOk:=TRUE; END; procedure Placement(VAR Morp:TabMorp;TabJoueur:TabJ;Joueur:integer); VAR PosChaine:string; L,C:integer; TestVide:boolean; Symb:char; BEGIN REPEAT writeln('Veuillez placer votre symbole - saisissez (Ligne,Colonne)'); readln(PosChaine); L:=StrToInt(copy(PosChaine,1,1)); C:=StrToInt(copy(PosChaine,3,1)); TestVide:=VideOk(L,C,Morp); UNTIL (TestVide=TRUE); if TestVide=TRUE then begin if TabJoueur[Joueur].Symbole=O then Symb:='O' else Symb:='X'; Morp[L,C]:=Symb; end; END; procedure Alignement(Morp:TabMorp;TabJoueur:TabJ;VAR Vict:Victoire); BEGIN if ((Morp[1,1]='X') AND (Morp[1,2]='X') AND (Morp[1,3]='X')) OR ((Morp[2,1]='X') AND (Morp[2,2]='X') AND (Morp[2,3]='X')) OR ((Morp[3,1]='X') AND (Morp[3,2]='X') AND (Morp[3,3]='X')) OR ((Morp[1,1]='X') AND (Morp[2,1]='X') AND (Morp[3,1]='X')) OR ((Morp[1,2]='X') AND (Morp[2,2]='X') AND (Morp[3,2]='X')) OR ((Morp[1,3]='X') AND (Morp[2,3]='X') AND (Morp[3,3]='X')) OR ((Morp[1,1]='X') AND (Morp[2,2]='X') AND (Morp[3,3]='X')) OR ((Morp[3,1]='X') AND (Morp[2,2]='X') AND (Morp[1,3]='X')) then if TabJoueur[1].Symbole=X then Vict:=VictoireJ1 else Vict:=VictoireJ2; if ((Morp[1,1]='O') AND (Morp[1,2]='O') AND (Morp[1,3]='O')) OR ((Morp[2,1]='O') AND (Morp[2,2]='O') AND (Morp[2,3]='O')) OR ((Morp[3,1]='O') AND (Morp[3,2]='O') AND (Morp[3,3]='O')) OR ((Morp[1,1]='O') AND (Morp[2,1]='O') AND (Morp[3,1]='O')) OR ((Morp[1,2]='O') AND (Morp[2,2]='O') AND (Morp[3,2]='O')) OR ((Morp[1,3]='O') AND (Morp[2,3]='O') AND (Morp[3,3]='O')) OR ((Morp[1,1]='O') AND (Morp[2,2]='O') AND (Morp[3,3]='O')) OR ((Morp[3,1]='O') AND (Morp[2,2]='O') AND (Morp[1,3]='O')) then if TabJoueur[1].Symbole=O then Vict:=VictoireJ1 else Vict:=VictoireJ2; END; procedure TourDeJeu(VAR Morp:TabMorp;VAR J:integer;VAR TabJoueur:TabJ; VAR T1:TabJ); VAR PosChaine:string; L,C,i:integer; Vict:Victoire; BEGIN i:=0; REPEAT begin clrscr; i:=i+1; Affichage(Morp); if J=1 then begin writeln('Tour num ',i,' : Le joueur ',T1[J].Nom,' joue avec les ',TabJoueur[J].Symbole); Placement(Morp,TabJoueur,J); Affichage(Morp); Alignement(Morp,TabJoueur,Vict); J:=J+1; readln; end else BEGIN writeln('Tour ',i,' : Le joueur ',T1[J].Nom,' joue les ',TabJoueur[J].Symbole); Placement(Morp,TabJoueur,J); Affichage(Morp); Alignement(Morp,TabJoueur,Vict); J:=J-1; readln; end; end; UNTIL ((i=NbToursMax) OR (Vict=VictoireJ1) OR (Vict=VictoireJ2)); if Vict=VictoireJ1 then begin writeln(T1[1].Nom,' gagne la partie !'); TabJoueur[1].NbMancheGagnee:=TabJoueur[1].NbMancheGagnee+1; end; if Vict=VictoireJ2 then begin writeln(T1[2].Nom,' gagne la partie !'); TabJoueur[2].NbMancheGagnee:=TabJoueur[2].NbMancheGagnee+1; end; if ((i=NbToursMax) AND (Vict<>VictoireJ1) AND (Vict<>VictoireJ2)) then writeln('Egalité'); END; Procedure EnregiFichier( VAR F:TextFile;VAR T1:Tabj;VAR TabJoueur:TabJ;VAR manche:integer); var j:integer; begin Assign(F,'texte.txt'); Rewrite(F); If (IOResult <> 0) Then writeln('Le fichier n''existe pas'); close(F); Append(F); writeln(F,'L''heure de debut de partie est : ',TimeToStr(Time)); writeln(F,'Le nombre total de manche est de : ',manche,' manche(s)'); writeln(F,'Le joueur ', T1[1].Nom, ' a remporte ',TabJoueur[1].NbMancheGagnee); writeln(F,'Le joueur ', T1[2].Nom, ' a remporte ',TabJoueur[2].NbMancheGagnee); If TabJoueur[1].NbMancheGagnee>TabJoueur[2].NbMancheGagnee then writeln(F,'Le joueur ', T1[1].Nom,' a gagne la partie !' ) else if TabJoueur[1].NbMancheGagnee<TabJoueur[2].NbMancheGagnee then writeln(F,'Le joueur ',T1[2].Nom,' a gagne la partie !') else writeln(F,'Egalité entre les joueurs'); close (F); end; VAR Morp:TabMorp; J:integer; TabJoueur:TabJ; manche:integer; p,k,i:integer; T1:TabJ; F:TextFile; BEGIN clrscr; writeln('Entrez le nombre de manches que vous voulez jouer'); readln(manche); NomJoueur(T1); FOR p:=1 TO manche DO begin clrscr; Initiatilisation(Morp); //Appel de la procédure initialisation Affichage(Morp); //Appel de la procédure affichage J:=ChoixJoueur(T1); //Appel de la fonction choixjoueur writeln('Le joueur ',T1[J].Nom,' commence et choisit les X ou les O '); ChoixRC(TabJoueur,J,T1); //Appel de la procédure choix rond ou croix readln; TourDeJeu(Morp,J,TabJoueur,T1); //Appel de la procédure tourdejeu end; writeln(UTF8ToAnsi('Nombre de manches gagnees')); FOR k:=1 to 2 DO begin writeln(T1[k].Nom,' : ',TabJoueur[k].NbMancheGagnee); end; EnregiFichier(F,T1,TabJoueur,manche); readln; END.
unit ServiceControlU; interface uses Dialogs, SysUtils, Windows, Messages, WinSvc, SvcMgr, Classes; type TNTServiceStatus = (svStopped, svRunning, svPaused, svStartPending, svStopPending, svContinuePending, svPausePending, svUnknown); type TNTServiceFailureAction = (sfaNone = integer(SC_ACTION_NONE), sfaRestart = integer(SC_ACTION_RESTART), sfaReboot = integer(SC_ACTION_REBOOT), sfaRunCommand = integer(SC_ACTION_RUN_COMMAND)); type TNTServiceControl = class(TComponent) private FMachineName: string; FServiceName: string; FNTServiceStatus: TNTServiceStatus; FStopDependencies: boolean; FStartDependencies: boolean; protected procedure UpdateServiceStatus; function GetServiceStatusString: string; function GetServiceStatus: TNTServiceStatus; procedure SetServiceName(AValue: string); procedure SetMachineName(AValue: string); function GetServiceDependencies(AServer: String; AServiceName: string; ADependencies: TStrings): boolean; function StopService(AServer: string; AServiceName: string): boolean; function StartService(AServer: string; AServiceName: string): boolean; public constructor Create(AOwner: TComponent); reintroduce; function Start: boolean; function Stop: boolean; function Resume: boolean; function Pause: boolean; function IsInstalled: boolean; function IsRunning: boolean; function Install(ADisplayName: string; AFileName: TFileName; AServiceStartName: string = ''; AServicePassword: string = ''; AInteractiveService: boolean = False): boolean; function Uninstall: boolean; function GetServiceList(AServiceList: TStrings): boolean; function GetDependencies(AList: TStrings): boolean; function SetServiceFailureActions (Action1: TNTServiceFailureAction = sfaNone; Action1Delay: Cardinal = 0; Action2: TNTServiceFailureAction = sfaNone; Action2Delay: Cardinal = 0; Action3: TNTServiceFailureAction = sfaNone; Action3Delay: Cardinal = 0; AResetPeriod: Cardinal = 0; ACommand: string = ''): boolean; published property ServiceName: string Read FServiceName Write SetServiceName; property MachineName: string Read FMachineName Write SetMachineName; property NTServiceStatus: TNTServiceStatus Read GetServiceStatus; property Status: string Read GetServiceStatusString; property StopDependencies: boolean read FStopDependencies write FStopDependencies; property StartDependencies: boolean read FStartDependencies write FStartDependencies; end; implementation constructor TNTServiceControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FNTServiceStatus := svUnknown; FStopDependencies := False; FStartDependencies := False; end; procedure TNTServiceControl.UpdateServiceStatus; var schm: SC_Handle; // service control manager handle schs: SC_Handle; // service handle ss: TServiceStatus; // service status dwStat: DWord; // current service status begin dwStat := 0; // connect to the service control manager schm := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_CONNECT); // if successful... if (schm > 0) then begin // open a handle to the specified service // we want to query service status schs := OpenService(schm, PChar(FServiceName), SERVICE_QUERY_STATUS); // if successful... if (schs > 0) then begin // retrieve the current status // of the specified service if (QueryServiceStatus(schs, ss)) then begin dwStat := ss.dwCurrentState; end; // close service handle CloseServiceHandle(schs); end; // close service control manager handle CloseServiceHandle(schm); end; case dwStat of SERVICE_STOPPED: FNTServiceStatus := svStopped; SERVICE_RUNNING: FNTServiceStatus := svRunning; SERVICE_PAUSED: FNTServiceStatus := svPaused; SERVICE_START_PENDING: FNTServiceStatus := svStartPending; SERVICE_STOP_PENDING: FNTServiceStatus := svStopPending; SERVICE_CONTINUE_PENDING: FNTServiceStatus := svContinuePending; SERVICE_PAUSE_PENDING: FNTServiceStatus := svPausePending; else FNTServiceStatus := svUnknown; end; end; procedure TNTServiceControl.SetServiceName(AValue: string); begin FServiceName := AValue; UpdateServiceStatus; end; procedure TNTServiceControl.SetMachineName(AValue: string); begin FMachineName := AValue; end; function TNTServiceControl.GetServiceStatus: TNTServiceStatus; begin UpdateServiceStatus; Result := FNTServiceStatus; end; function TNTServiceControl.GetServiceStatusString: string; var s: string; begin case GetServiceStatus of svStopped: s := 'STOPPED'; svRunning: s := 'RUNNING'; svPaused: s := 'PAUSED'; svStartPending: s := 'START/PENDING'; svStopPending: s := 'STOP/PENDING'; svContinuePending: s := 'CONTINUE/PENDING'; svPausePending: s := 'PAUSE/PENDING'; else s := 'UNKNOWN'; end; Result := s; end; function TNTServiceControl.Pause: boolean; var schm: SC_Handle; // service control manager handle schs: SC_Handle; // service handle ss: TServiceStatus; // service status dwChkP: DWord; // check point begin // connect to the service control manager schm := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_ALL_ACCESS); // if successful... if (schm > 0) then begin // open a handle to the specified service // we want to query service status schs := OpenService(schm, PChar(FServiceName), SERVICE_ALL_ACCESS); // if successful... if (schs > 0) then begin if ControlService(schs, SERVICE_CONTROL_PAUSE, ss) then begin // check status if (QueryServiceStatus(schs, ss)) then begin while (SERVICE_PAUSED <> ss.dwCurrentState) do begin // dwCheckPoint contains a value that the // service increments periodically to // report its progress during a // lengthy operation. Save current value dwChkP := ss.dwCheckPoint; // wait a bit before checking status again // dwWaitHint is the estimated amount of // time the calling program should wait // before calling QueryServiceStatus() // again. Idle events should be // handled here... Sleep(ss.dwWaitHint); if not QueryServiceStatus(schs, ss) then begin // couldn't check status break from the // loop break; end; if ss.dwCheckPoint < dwChkP then begin // QueryServiceStatus didn't increment // dwCheckPoint as it should have. // Avoid an infinite loop by breaking break; end; end; end; end else RaiseLastOsError; // close service handle CloseServiceHandle(schs); end; // close service control manager handle CloseServiceHandle(schm); end; Result := SERVICE_PAUSED = ss.dwCurrentState; end; function TNTServiceControl.Resume: boolean; var schm: SC_Handle; // service control manager handle schs: SC_Handle; // service handle ss: TServiceStatus; // service status dwChkP: DWord; // check point begin // connect to the service control manager schm := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_ALL_ACCESS); // if successful... if (schm > 0) then begin // open a handle to the specified service // we want to query service status schs := OpenService(schm, PChar(FServiceName), SERVICE_ALL_ACCESS); // if successful... if (schs > 0) then begin if ControlService(schs, SERVICE_CONTROL_CONTINUE, ss) then begin // check status if (QueryServiceStatus(schs, ss)) then begin while (SERVICE_RUNNING <> ss.dwCurrentState) do begin // dwCheckPoint contains a value that the // service increments periodically to // report its progress during a // lengthy operation. Save current value dwChkP := ss.dwCheckPoint; // wait a bit before checking status again // dwWaitHint is the estimated amount of // time the calling program should wait // before calling QueryServiceStatus() // again. Idle events should be // handled here... Sleep(ss.dwWaitHint); if not QueryServiceStatus(schs, ss) then begin // couldn't check status break from the // loop break; end; if ss.dwCheckPoint < dwChkP then begin // QueryServiceStatus didn't increment // dwCheckPoint as it should have. // Avoid an infinite loop by breaking break; end; end; end; end else RaiseLastOsError; // close service handle CloseServiceHandle(schs); end; // close service control manager handle CloseServiceHandle(schm); end; Result := SERVICE_RUNNING = ss.dwCurrentState; end; function TNTServiceControl.Start: boolean; var Dependencies: TStringList; Idx: integer; begin Dependencies := TStringList.Create; try Result := StartService(FMachineName, FServiceName); if Result and FStartDependencies then begin // Log(Format('Starting %s', [FServiceName])); GetServiceDependencies(FMachineName, FServiceName, Dependencies); for Idx := 0 to Pred(Dependencies.Count) do begin // Log(Format('Starting Dependency %s (%s)', [Dependencies.Names[Idx], // Dependencies.ValueFromIndex[Idx]])); try StartService(FMachineName, Dependencies.Names[Idx]); except on E: Exception do begin // Error(E); end; end; end; end; finally FreeAndNil(Dependencies); end; end; function TNTServiceControl.GetServiceDependencies(AServer: String; AServiceName: string; ADependencies: TStrings): boolean; var schm, schs: SC_Handle; Services, s: PEnumServiceStatus; BytesNeeded, ServicesReturned: DWord; i: integer; begin Result := False; ADependencies.Clear; schm := OpenSCManager(PChar(AServer), nil, SC_MANAGER_CONNECT); Services := nil; // if successful... if schm > 0 then begin // open a handle to the specified service // we want to stop the service and // query service status schs := OpenService(schm, PChar(AServiceName), SERVICE_ENUMERATE_DEPENDENTS); if schs > 0 then begin if EnumDependentServices(schs, SERVICE_ACTIVE + SERVICE_INACTIVE, Services, 0, BytesNeeded, ServicesReturned) then begin GetMem(Services, BytesNeeded); try if EnumDependentServices(schs, SERVICE_ACTIVE + SERVICE_INACTIVE, Services, BytesNeeded, BytesNeeded, ServicesReturned) then begin // Now process it... s := Services; for i := 0 to Pred(ServicesReturned) do begin ADependencies.Add(s^.lpServiceName + '=' + s^.lpDisplayName); Inc(s); end; Result := True; end; finally FreeMem(Services); end; // WinSvc.QueryServiceConfig(schs, nil, 0, R); // GetMem(ServiceConfig, R + 1); // if WinSvc.QueryServiceConfig(schs, ServiceConfig, R + 1, R) then // begin // Debug('GetServiceDependencies', ServiceConfig.lpDisplayName); // Debug('GetServiceDependencies', ServiceConfig.lpServiceStartName); // Debug('GetServiceDependencies', ServiceConfig.lpDependencies); // DepList := ServiceConfig.lpDependencies; // if Assigned(DepList) then // begin // while DepList[0] <> #0 do // begin // Dep := DepList; // ADependencies.Add(Dep); // Inc(DepList, StrLen(DepList) + 1) // end; // end; // FreeMem(ServiceConfig); // Result := True; end; CloseServiceHandle(schs); end; end; CloseServiceHandle(schm); end; function TNTServiceControl.StopService(AServer: string; AServiceName: string): boolean; var schm, schs: SC_Handle; ss: TServiceStatus; dwChkP: DWord; begin // connect to the service control manager schm := OpenSCManager(PChar(AServer), nil, SC_MANAGER_CONNECT); // if successful... if schm > 0 then begin // open a handle to the specified service // we want to stop the service and // query service status schs := OpenService(schm, PChar(AServiceName), SERVICE_STOP or SERVICE_QUERY_STATUS); // if successful... if schs > 0 then begin if ControlService(schs, SERVICE_CONTROL_STOP, ss) then begin // check status if (QueryServiceStatus(schs, ss)) then begin while (SERVICE_STOPPED <> ss.dwCurrentState) do begin // dwCheckPoint contains a value that the // service increments periodically to // report its progress during a lengthy // operation. Save current value dwChkP := ss.dwCheckPoint; // Wait a bit before checking status again. // dwWaitHint is the estimated amount of // time the calling program should wait // before calling QueryServiceStatus() // again. Idle events should be // handled here... Sleep(ss.dwWaitHint); if (not QueryServiceStatus(schs, ss)) then begin // couldn't check status // break from the loop break; end; if (ss.dwCheckPoint < dwChkP) then begin // QueryServiceStatus didn't increment // dwCheckPoint as it should have. // Avoid an infinite loop by breaking break; end; end; end; end; // close service handle CloseServiceHandle(schs); end; // close service control manager handle CloseServiceHandle(schm); end; // return TRUE if the service status is stopped Result := SERVICE_STOPPED = ss.dwCurrentState; end; function TNTServiceControl.StartService(AServer: string; AServiceName: string): boolean; var schm, schs: SC_Handle; ss: TServiceStatus; psTemp: PChar; dwChkP: DWord; // check point begin // connect to the service control manager schm := OpenSCManager(PChar(AServer), nil, SC_MANAGER_CONNECT); // if successful... if (schm > 0) then begin // open a handle to the specified service // we want to start the service and query service // status schs := OpenService(schm, PChar(AServiceName), SERVICE_START or SERVICE_QUERY_STATUS); // if successful... if (schs > 0) then begin psTemp := nil; if (WinSvc.StartService(schs, 0, psTemp)) then begin // check status if (QueryServiceStatus(schs, ss)) then begin while (SERVICE_RUNNING <> ss.dwCurrentState) do begin // dwCheckPoint contains a value that the // service increments periodically to // report its progress during a // lengthy operation. Save current value dwChkP := ss.dwCheckPoint; // wait a bit before checking status again // dwWaitHint is the estimated amount of // time the calling program should wait // before calling QueryServiceStatus() // again. Idle events should be // handled here... Sleep(ss.dwWaitHint); if not QueryServiceStatus(schs, ss) then begin // couldn't check status break from the // loop break; end; if ss.dwCheckPoint < dwChkP then begin // QueryServiceStatus didn't increment // dwCheckPoint as it should have. // Avoid an infinite loop by breaking break; end; end; end; end; // close service handle CloseServiceHandle(schs); end; // close service control manager handle CloseServiceHandle(schm); end; // Return TRUE if the service status is running Result := GetServiceStatus = svRunning; end; function TNTServiceControl.SetServiceFailureActions (Action1: TNTServiceFailureAction = sfaNone; Action1Delay: Cardinal = 0; Action2: TNTServiceFailureAction = sfaNone; Action2Delay: Cardinal = 0; Action3: TNTServiceFailureAction = sfaNone; Action3Delay: Cardinal = 0; AResetPeriod: Cardinal = 0; ACommand: string = ''): boolean; var schm, schs: SC_Handle; sfa: SERVICE_FAILURE_ACTIONS; actions: array [0 .. 2] of SC_ACTION; function GetActionTypes(ANTServiceFailureAction: TNTServiceFailureAction) : SC_ACTION_TYPE; begin case ANTServiceFailureAction of sfaRestart: Result := SC_ACTION_RESTART; sfaReboot: Result := SC_ACTION_REBOOT; sfaRunCommand: Result := SC_ACTION_RUN_COMMAND else Result := SC_ACTION_NONE; end; end; begin Result := False; schm := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_ALL_ACCESS); if (schm > 0) then begin schs := OpenService(schm, PChar(FServiceName), SERVICE_ALL_ACCESS); if (schs > 0) then begin try try sfa.dwResetPeriod := AResetPeriod; sfa.lpCommand := PChar(ACommand); sfa.lpRebootMsg := Nil; sfa.cActions := 3; actions[0].&Type := GetActionTypes(Action1); actions[0].Delay := Action1Delay; actions[1].&Type := GetActionTypes(Action2); actions[1].Delay := Action2Delay; actions[2].&Type := GetActionTypes(Action3); actions[2].Delay := Action3Delay; sfa.lpsaActions := @actions; Result := ChangeServiceConfig2(schs, SERVICE_CONFIG_FAILURE_ACTIONS, @sfa); except on E: Exception do begin // Error(E); end; end; finally CloseServiceHandle(schs); end; end; CloseServiceHandle(schm); end; end; // Return TRUE if successful function TNTServiceControl.Stop: boolean; var Dependencies: TStringList; Idx: integer; begin Dependencies := TStringList.Create; try if FStopDependencies then begin GetServiceDependencies(FMachineName, FServiceName, Dependencies); for Idx := 0 to Pred(Dependencies.Count) do begin // Log(Format('Stopping Dependency %s (%s)', [Dependencies.Names[Idx], // Dependencies.ValueFromIndex[Idx]])); try StopService(FMachineName, Dependencies.Names[Idx]); except on E: Exception do begin // Error(E); end; end; end; end; // Log(Format('Stopping %s', [FServiceName])); Result := StopService(FMachineName, FServiceName); finally FreeAndNil(Dependencies); end; end; function TNTServiceControl.GetServiceList(AServiceList: TStrings): boolean; var hSCM: THandle; pEnumStatus: PEnumServiceStatusW; dwByteNeeded: DWord; dwNumOfService: DWord; dwResumeHandle: DWord; nI: integer; begin pEnumStatus := nil; dwByteNeeded := 0; dwResumeHandle := 0; try hSCM := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_ALL_ACCESS); if not EnumServicesStatus(hSCM, SERVICE_WIN32 or SERVICE_DRIVER, SERVICE_ACTIVE or SERVICE_INACTIVE, pEnumStatus, 0, dwByteNeeded, dwNumOfService, dwResumeHandle) then begin if GetLastError = ERROR_MORE_DATA then begin GetMem(pEnumStatus, dwByteNeeded); if not EnumServicesStatus(hSCM, SERVICE_WIN32 or SERVICE_DRIVER, SERVICE_ACTIVE or SERVICE_INACTIVE, pEnumStatus, dwByteNeeded, dwByteNeeded, dwNumOfService, dwResumeHandle) then begin Result := False; Exit; end; end else begin Result := False; Exit; end; end; AServiceList.Clear; for nI := 0 to dwNumOfService - 1 do begin AServiceList.Add(TEnumServiceStatus(PEnumServiceStatus(PChar(pEnumStatus) + nI * SizeOf(TEnumServiceStatus))^).lpServiceName); end; CloseServiceHandle(hSCM); Result := True; finally if Assigned(pEnumStatus) then FreeMem(pEnumStatus); end; end; function TNTServiceControl.GetDependencies(AList: TStrings): boolean; begin Result := GetServiceDependencies(FMachineName, FServiceName, AList); end; function TNTServiceControl.IsInstalled: boolean; var hSCM: THandle; schs: THandle; begin hSCM := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_CONNECT); Result := False; if hSCM <> 0 then begin schs := OpenService(hSCM, PChar(FServiceName), SERVICE_QUERY_CONFIG); if schs <> 0 then begin Result := True; CloseServiceHandle(schs); end; CloseServiceHandle(hSCM); end; end; function TNTServiceControl.IsRunning: boolean; begin case GetServiceStatus of svStopped: Result := False; svRunning: Result := True; svPaused: Result := True; svStartPending: Result := True; svStopPending: Result := True; svContinuePending: Result := True; svPausePending: Result := True; else Result := False; end; end; function TNTServiceControl.Install(ADisplayName: string; AFileName: TFileName; AServiceStartName: string = ''; AServicePassword: string = ''; AInteractiveService: boolean = False): boolean; var schm: SC_Handle; schs: SC_Handle; ServiceType: Cardinal; ServiceStartName: PChar; ServicePassword: PChar; begin Result := False; schm := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_ALL_ACCESS); if (schm > 0) then begin try ServiceStartName := nil; ServicePassword := nil; if AInteractiveService then begin ServiceType := SERVICE_WIN32_OWN_PROCESS + SERVICE_INTERACTIVE_PROCESS; end else begin ServiceType := SERVICE_WIN32_OWN_PROCESS; if Trim(AServiceStartName) <> '' then begin ServiceStartName := PChar(AServiceStartName); ServicePassword := PChar(AServicePassword); end else begin end; end; schs := CreateService(schm, PChar(FServiceName), PChar(ADisplayName), SERVICE_ALL_ACCESS, ServiceType, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, PChar(AFileName), '', nil, '', ServiceStartName, ServicePassword); if (schs = 0) then begin RaiseLastOsError; end else begin Result := True; end; if schs <> 0 then CloseServiceHandle(schs); finally CloseServiceHandle(schm); end; end; end; function TNTServiceControl.Uninstall: boolean; var SCMHandle: longword; ServiceHandle: longword; begin Result := False; SCMHandle := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_ALL_ACCESS); if SCMHandle <> 0 then begin try ServiceHandle := OpenService(SCMHandle, PChar(FServiceName), SERVICE_ALL_ACCESS); if ServiceHandle <> 0 then begin try if DeleteService(ServiceHandle) then begin Result := True; end else begin RaiseLastOsError; end; finally if ServiceHandle <> 0 then CloseServiceHandle(ServiceHandle); end; end; finally if SCMHandle <> 0 then CloseServiceHandle(SCMHandle); end; end; end; end.
(********************************************************) (* *) (* Print Mender *) (* *) (* Mend Code Unit *) (* *) (* *) (********************************************************) unit PMMCU; interface uses SysUtils, Classes, MemBuf, VarPointer, PMTypedef, Mender, Windows; type TPrnMend = class (TObject) private FOffset: Integer; FOwner: TMender; FPinState: LongWord; FEnter: Boolean; public constructor Create; destructor Destroy; override; protected FCodeBuf: TMemoryBuffer; //存放打印数据(含打印指令和图形指令) FCmdBuf: TMemoryBuffer; //存放非图形指令 FGraphicsBuf: TMemoryBuffer; //存放图形指令 FMendBuf: TMemoryBuffer; procedure SplitCode; virtual; //代码分类 procedure MendCode; procedure MergeBuffer; procedure GetPinStateArray(PinState: LongWord; var PinStateArray: TLongWordDynArray);overload; procedure GetPinStateArray(PinState: LongWord; PinStateList: TLongWordList);overload; function GetHighBitPos(I: LongWord): Integer; procedure GetMendData(PinState: LongWord; GraphicsState: LongWord; var BestPinState: LongWord; MendDataList: TMendDataList); virtual; procedure InternalMend(PinState: LongWord; GraphicsState: LongWord; MendDataList: TMendDataList); virtual; end; implementation { TMCU } constructor TPrnMend.Create; begin FOffset := 0; FCodeBuf := TMemoryBuffer.Create; FCmdBuf := TMemoryBuffer.Create; FGraphicsBuf := TMemoryBuffer.Create; FMendBuf := TMemoryBuffer.Create; end; destructor TPrnMend.Destroy; begin if FCodeBuf <> nil then FCodeBuf.Free; if FCmdBuf <> nil then FCmdBuf.Free; if FGraphicsBuf <> nil then FGraphicsBuf.Free; if FMendBuf <> nil then FMendBuf.Free; inherited; end; function TPrnMend.GetHighBitPos(I: LongWord): Integer; begin Result := -1; while I <> 0 do begin I := I shr 1; Inc(Result); end; end; procedure TPrnMend.GetPinStateArray(PinState: LongWord; var PinStateArray: TLongWordDynArray); var Count: Integer; Index: Integer; begin SetLength(PinStateArray, 24); Index := 0; Count := 0; PinState := PinState and $FFFFFF; while PinState <> 0 do begin while (PinState and (1 shl 23)) = 0 do begin PinState := PinState shl 1 and $FFFFFF; Inc(Count); end; PinStateArray[Index] := PinState shr Count; PinState := PinState shl 1 and $FFFFFF; Inc(Count); Inc(Index); end; SetLength(PinStateArray, Index); end; procedure TPrnMend.GetMendData(PinState, GraphicsState: LongWord; var BestPinState: LongWord; MendDataList: TMendDataList); var PinStateArray: TLongWordList; TempList: TMendDataList; I: Integer; tmp_Offset: Integer; dat_Offset: Integer; J: Integer; begin if not Assigned(MendDataList) then begin raise EListError.Create('MendDataList Invaild Pointer'); end; MendDataList.Clear; PinStateArray := TLongWordList.Create; TempList := TMendDataList.Create; GetPinStateArray(PinState, PinStateArray); BestPinState := PinState; for I := 0 to PinStateArray.Count - 1 do begin TempList.Clear; InternalMend(PinStateArray.Items[I], GraphicsState, TempList); if I = 0 then begin MendDataList.Assign(TempList); Continue; end; if TempList.Count < MendDataList.Count - 1 then begin BestPinState := PinStateArray[I]; MendDataList.Assign(TempList); Continue; end; if TempList.Count = MendDataList.Count - 1 then begin tmp_Offset := 0; dat_Offset := 0; for J := 0 to TempList.Count - 1 do begin Inc(tmp_Offset, TempList.Items[J].Offset); end; for J := 0 to MendDataList.Count - 1 do begin Inc(dat_Offset, MendDataList.Items[J].Offset); end; if tmp_Offset < dat_Offset then begin BestPinState := PinStateArray.Items[I]; MendDataList.Assign(TempList) end; end; end; PinStateArray.Free; TempList.Free; end; procedure TPrnMend.GetPinStateArray(PinState: LongWord; PinStateList: TLongWordList); var I: Integer; begin if not Assigned(PinStateList) then raise EListError.Create('PinStateList Invaild Pointer'); I := 0; PinStateList.Clear; PinState := PinState and $FFFFFF; while PinState <> 0 do begin if (PinState and (1 shl 23)) <> 0 then PinStateList.Add(PinState shr I); PinState := PinState shl 1 and $FFFFFF; Inc(I); end; end; procedure TPrnMend.MendCode; var gsState: LongWord; TotalOffset: Integer; BestPin: LongWord; I: Integer; MendDataList: TMendDataList; PassDataList: TLongWordList; Pass: DWORD; Residual: DWORD; G_IP: PGraphicsRecord; G_EP: PGraphicsRecord; BitDif: Integer; J: Integer; Rec: TGraphicsRecord; begin if FGraphicsBuf.Size = 0 then begin MergeBuffer; Exit; end; gsState := GetGraphicsBitOr(FGraphicsBuf.Memory, FGraphicsBuf.Size div 3); if gsState = 0 then begin MergeBuffer; Exit; end; try FEnter := False; MendDataList := TMendDataList.Create; PassDataList := TLongWordList.Create; TotalOffset := 0; G_EP := FGraphicsBuf.Memory; Inc(G_EP, FGraphicsBuf.Size div PM_GRSIZE); GetMendData(FPinState, gsState, BestPin, MendDataList); for I := 0 to MendDataList.Count - 1 do begin PassDataList.Clear; G_IP := PGraphicsRecord(FGraphicsBuf.Memory); while LongInt(G_IP) < LongInt(G_EP) do begin Pass := MakeDWord(MendDataList.Items[I].gsRec); Residual := MakeDWord(G_IP); Pass := Pass and Residual; Residual := Pass xor Residual; G_IP^ := MakeGraphicsRec(Residual); Inc(G_IP); PassDataList.Add(Pass); end; BitDif := GetHighBitPos(BestPin) - GetHighBitPos(MakeDWord(MendDataList.Items[I].GsRec)); if BitDif < 0 then begin for J := 0 to PassDataList.Count - 1 do begin Rec := MakeGraphicsRec(PassDataList.Items[J] shr Abs(BitDif)); FMendBuf.Write(Rec, SizeOf(Rec)); end; end else begin for J := 0 to PassDataList.Count - 1 do begin Rec := MakeGraphicsRec(PassDataList.Items[J] shl BitDif); FMendBuf.Write(Rec, SizeOf(Rec)); end; end; FOffset := MendDataList.Items[I].Offset; Inc(TotalOffset, FOffset); MergeBuffer; FMendBuf.Clear; FEnter := True; end; FOffset := TotalOffset; finally MendDataList.Free; PassDataList.Free; end; end; procedure TPrnMend.MergeBuffer; begin FCodeBuf.Clear; if FGraphicsBuf.Size = 0 then begin FCodeBuf.Write(FCmdBuf.Memory^, FCmdBuf.Size); Exit; end; end; procedure TPrnMend.SplitCode; {功能:纠正补打后的针位偏移、代码分类和强制打印方向} var BP: PChar; //基址指针 OBP: PChar; //输出数据的基址指针 _IP: TPointer; //索引指针 BufSize: Cardinal; //打印数据的字节数 GrBytes: Cardinal; //图形指令的字节数 SV: Integer; VSCmd: array [0..2] of Byte; //垂直进纸指令 begin BP := FCodeBuf.Memory; BufSize := FCodeBuf.Size; OBP := BP; _IP := TPointer.Create; _IP.Ptr := BP; while _IP.Ptr < BP + BufSize do begin if _IP.ReadByte() <> PM_CMDFLAG then begin _IP.SkipBytes(NextPosition(_IP.Ptr)); Continue; end; case _IP.ReadByte(1) of PM_CMD_GRAPHICS: // 代码分类 begin GrBytes := _IP.ReadWord(3) * PM_GRSIZE; //获得图形指令的字节数 _IP.SkipBytes(5); //跳到图形指令标识的后面,准备输出非图形指令 FCmdBuf.Write(OBP, _IP.Ptr - OBP); FGraphicsBuf.Write(_IP.Ptr, GrBytes); _IP.SkipBytes(GrBytes); OBP := _IP.Ptr; Continue; end; PM_CMD_PRINTWAY: //设置单双向打印 begin if FOwner.PrintWay = pwBidirectional then _IP.WriteByte(2, 2) else _IP.WriteByte(1, 2); end; PM_CMD_HSCROLL: //纠正针位偏移 begin SV := Integer(_IP.ReadByte(2)) + FOffset; if SV > 255 then //超过单字节长度,分两次进纸 begin _IP.WriteByte($FF, 2); _IP.SkipBytes(NextPosition(_IP.Ptr)); FCmdBuf.Write(OBP, _IP.Ptr - OBP); VSCmd[0] := $1B; VSCmd[1] := $4A; VSCmd[2] := SV - 255; FCmdBuf.Write(VSCmd, SizeOf(VSCmd)); OBP := _IP.Ptr; end else if SV < 0 then //后退 begin _IP.WriteByte($6A, 1); _IP.WriteByte(Byte(Abs(SV)), 2); end else _IP.WriteByte(Byte(SV), 2); end; end; _IP.SkipBytes(NextPosition(_IP.Ptr)); end; //End While _IP.Free; FCodeBuf.Clear; end; procedure TPrnMend.InternalMend(PinState, GraphicsState: LongWord; MendDataList: TMendDataList); var MendData: TMendData; BitDif: SmallInt; Pass: LongWord; begin while GraphicsState <> 0 do begin BitDif := GetHighBitPos(PinState) - GetHighBitPos(GraphicsState); if BitDif > 0 then PinState := PinState shr BitDif else PinState := PinState shl Abs(BitDif); Pass := PinState and GraphicsState; GraphicsState := GraphicsState xor Pass; MendData.Offset := BitDif; MendData.GsRec := MakeGraphicsRec(Pass); MendDataList.Add(MendData); end; end; end.
unit adot.Tools; {$OVERFLOWCHECKS OFF} {$IFNDEF Debug} { $Define UseInline} {$ENDIF} { Definition of classes/record types: TArrayUtils = record Fill/fillRandom/Randomize and other tools for arrays. TComponentUtils = class Enumeration and other component-specific tools. TCurrencyUtils = class Currency type utils. TDateTimeRec = record Record type to define TDateTime compatible constants in readable way. TDateTimeUtils = class Check TDateTime correctness, convert to string etc. TGUIDUtils = class IsValid and other utils. THex = class Set of functions for HEX conversion. TIfThen = class Generic implementation of IfThen (to accept virtually any type). Example: A := TIfThen.Get(Visible, fsMDIChild, fsNormal); TInterfacedObject<T: class> = class Wrapper class to make any class type available through interface (that means that lifetime of the class will be controlled by reference counter) TNullable<T> = record Extends any type by IsNull property. } interface uses adot.Types, adot.Collections, adot.Collections.Maps, System.DateUtils, System.Types, System.Rtti, System.Math, System.Generics.Collections, System.Generics.Defaults, System.Classes, System.SysUtils, System.StrUtils, System.TimeSpan; type { Set of functions for HEX conversion } THex = class protected const { System.SysUtils.TwoHexLookup is hidden behind implementation section, so we have to reintroduce it. } TwoHexLookup : packed array[0..255] of array[0..1] of Char = ('00','01','02','03','04','05','06','07','08','09','0A','0B','0C','0D','0E','0F', '10','11','12','13','14','15','16','17','18','19','1A','1B','1C','1D','1E','1F', '20','21','22','23','24','25','26','27','28','29','2A','2B','2C','2D','2E','2F', '30','31','32','33','34','35','36','37','38','39','3A','3B','3C','3D','3E','3F', '40','41','42','43','44','45','46','47','48','49','4A','4B','4C','4D','4E','4F', '50','51','52','53','54','55','56','57','58','59','5A','5B','5C','5D','5E','5F', '60','61','62','63','64','65','66','67','68','69','6A','6B','6C','6D','6E','6F', '70','71','72','73','74','75','76','77','78','79','7A','7B','7C','7D','7E','7F', '80','81','82','83','84','85','86','87','88','89','8A','8B','8C','8D','8E','8F', '90','91','92','93','94','95','96','97','98','99','9A','9B','9C','9D','9E','9F', 'A0','A1','A2','A3','A4','A5','A6','A7','A8','A9','AA','AB','AC','AD','AE','AF', 'B0','B1','B2','B3','B4','B5','B6','B7','B8','B9','BA','BB','BC','BD','BE','BF', 'C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','CA','CB','CC','CD','CE','CF', 'D0','D1','D2','D3','D4','D5','D6','D7','D8','D9','DA','DB','DC','DD','DE','DF', 'E0','E1','E2','E3','E4','E5','E6','E7','E8','E9','EA','EB','EC','ED','EE','EF', 'F0','F1','F2','F3','F4','F5','F6','F7','F8','F9','FA','FB','FC','FD','FE','FF'); H2B: packed array['0'..'f'] of SmallInt = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1, { 0..9 } -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, { a..f } -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15); { A..F } public class function EncodedSizeChars(SourceSizeBytes: integer): integer; static; class function DecodedSizeBytes(EncodedSizeChars: integer): integer; static; class function Encode(const Buf; ByteBufSize: integer): String; overload; static; class function Encode<T: Record>(const Value: T): String; overload; static; class function Encode(const s: TBytes):String; overload; static; class function Encode(const s: string): string; overload; static; class function Encode(const s: string; utf8: boolean): string; overload; static; {$If Defined(MSWindows)} class function EncodeAnsiString(const s: AnsiString):String; static; {$EndIf} class function EncodeByteH(Src: byte): char; static; class function EncodeByteL(Src: byte): char; static; class procedure Decode(const HexEncodedStr: String; var Buf); overload; static; class function Decode<T: Record>(const HexEncodedStr: String): T; overload; static; class function DecodeBytes(const HexEncodedStr: String):TBytes; static; class function DecodeString(const HexEncodedStr: string): string; overload; static; class function DecodeString(const HexEncodedStr: string; utf8: boolean): string; overload; static; {$If Defined(MSWindows)} class function DecodeAnsiString(const HexEncodedStr: String):AnsiString; static; {$EndIf} class function DecodeByte(H,L: Char): byte; static; class function DecodeHexChar(HexChar: Char): byte; static; class function IsValid(const HexEncodedStr: String):Boolean; overload; static; class function IsValid(const HexEncodedStr: String; ZeroBasedStartIdx,Len: integer):Boolean; overload; static; class function IsValid(const C: Char):Boolean; overload; static; { Int64ToHex(Value) <> Encode(Value, SizeOf(Value)) for x86-compatible CPU family, because lower bytes of integers are stored by lower addresses. When we translate integer/pointer to hex we would like to use regular notation, when higher digits are shown first. } class function Int64ToHex(s: Int64): string; static; class function UInt64ToHex(s: UInt64): string; static; class function NativeIntToHex(s: NativeInt): string; static; class function NativeUIntToHex(s: NativeUInt): string; static; class function PointerToHex(s: Pointer): string; static; class function CardinalToHex(s: cardinal): string; static; class function WordToHex(s: word): string; static; class function HexToInt64(const HexEncodedInt: String):Int64; static; class function HexToUInt64(const HexEncodedInt: String):UInt64; static; class function HexToNativeInt(const HexEncodedInt: String):NativeInt; static; class function HexToNativeUInt(const HexEncodedInt: String):NativeUInt; static; class function HexToPointer(const HexEncodedPointer: String):Pointer; static; class function HexToCardinal(const HexEncodedCardinal: String):Cardinal; static; class function HexToWord(const HexEncodedWord: String):Word; static; end; TInvertedComparer<TValueType> = class(TInterfacedObject, IComparer<TValueType>) protected FExtComparer: IComparer<TValueType>; public constructor Create(AExtComparer: IComparer<TValueType>); function Compare(const Left, Right: TValueType): Integer; end; { Examples: const Date1 : TDateTimeRec = (Year:2009; Month:05; Day:11); Date2 : TDateTimeRec = (Year:2009; Month:05; Day:11; Hour:05); } { Record type to define TDateTime compatible constants in readable way } TDateTimeRec = record Year, Month, Day, Hour, Minute, Second, Millisecond : Word; class operator Implicit(const ADateTime : TDateTimeRec): TDateTime; class operator Implicit(const ADateTime : TDateTime): TDateTimeRec; class operator Implicit(const ADateTime : TDateTimeRec): String; class operator Implicit(const ADateTime : String): TDateTimeRec; end; { Check TDateTime correctness, convert to string etc } TDateTimeUtils = class public const NoDateStr = ''; class function StdEuFormatSettings: TFormatSettings; static; class function IsCorrectDate(const t: TDateTime): boolean; static; class function ToStr(const t: TDateTime; ANoDateStr: string = NoDateStr): string; static; class function ToStringStd(const t: TDateTime): string; static; class function FromStringStd(const t: string; def: TDateTime = 0): TDateTime; static; end; TFuncConst<T,TResult> = reference to function (const Arg1: T): TResult; TFuncConst<T1,T2,TResult> = reference to function (const Arg1: T1; const Arg2: T2): TResult; TFuncConst<T1,T2,T3,TResult> = reference to function (const Arg1: T1; const Arg2: T2; const Arg3: T3): TResult; { Fill/fillRandom/Randomize and other tools for arrays } TArrayUtils = record public class procedure SaveToFileAsText<T>(const Arr: TArray<T>; const AFileName: string); static; class procedure SaveToFileAsBin<T>(const Arr: TArray<T>; const AFileName: string); static; class function Get<T>(const Arr: array of T):TArray<T>; overload; static; class function Get(const Arr: TStringDynArray):TArray<string>; overload; static; class procedure Randomize<T>(var Arr: TArray<T>); static; class procedure Inverse<T>(var Arr: TArray<T>; AStartIndex: integer = 0; ACount: integer = -1); static; class procedure Delete<T>(var Arr: TArray<T>; AFilter: TFuncConst<T,Boolean>); overload; static; class procedure Delete<T>(var Arr: TArray<T>; Index: integer); overload; static; class function Add<T>(const A,B: TArray<T>): TArray<T>; overload; static; class function Copy<T>(const Src: TArray<T>): TArray<T>; overload; static; class function Copy<T>(const Src: TArray<T>; StartIndex,Count: integer): TArray<T>; overload; static; class function Copy<T>(const Src: TArray<T>; ACopyFilter: TFuncConst<T,Boolean>): TArray<T>; overload; static; class function Equal<T>(const A,B: TArray<T>; AComparer: IEqualityComparer<T> = nil): Boolean; overload; static; class function Equal<T>(const A,B: TArray<T>; IndexA,IndexB,Count: integer; AComparer: IEqualityComparer<T> = nil): Boolean; overload; static; class procedure Append<T>(var Dst: TArray<T>; const Src: T); overload; static; class procedure Append<T>(var Dst: TArray<T>; const Src: TArray<T>); overload; static; class procedure Append<T>(var Dst: TArray<T>; const Src: TEnumerable<T>); overload; static; class procedure FillRandom(var Dst: TArray<byte>; Count: integer; AValRangeFrom,AValRangeTo: byte); overload; static; class procedure FillRandom(var Dst: TArray<integer>; Count: integer; AValRangeFrom,AValRangeTo: integer); overload; static; class procedure FillRandom(var Dst: TArray<double>; Count: integer; AValRangeFrom,AValRangeTo: double); overload; static; class procedure FillRandom(var Dst: TArray<string>; Count,ValMaxLen: integer); overload; static; class procedure Fill(var Dst: TArray<byte>; Count: integer; AValueStart,AValueInc: integer); overload; static; class procedure Fill(var Dst: TArray<integer>; Count: integer; AValueStart,AValueInc: integer); overload; static; class procedure Fill(var Dst: TArray<double>; Count: integer; AValueStart,AValueInc: double); overload; static; class procedure StableSort<T>(var Dst: TArray<T>; StartIndex,Count: integer; Comparer: IComparer<T>); static; class function Cut<T>(var Dst: TArray<T>; Capacity,StartIndex,Count: integer): integer; overload; static; class function Cut<T>(var Dst: TArray<T>; StartIndex,Count: integer): integer; overload; static; class function Slice<T>(const Src: TArray<T>; Capacity,StartIndex,Count: integer): TArray<T>; overload; static; class function Slice<T>(const Src: TArray<T>; StartIndex,Count: integer): TArray<T>; overload; static; class function Slice<T>(const Src: TArray<T>; CopyValue: TFunc<T,boolean>): TArray<T>; overload; static; { 9 1 7 2 5 8 -> [1-2] [5] [7-9] } class function Ranges(Src: TArray<integer>): TRangeEnumerable; overload; static; class function Ranges(Src: TEnumerable<integer>): TRangeEnumerable; overload; static; class function IndexOf<T>(const Item: T; const Src: TEnumerable<T>; AComparer: IEqualityComparer<T> = nil): integer; overload; static; class function IndexOf<T>(const Item: T; const Src: TArray<T>; AComparer: IEqualityComparer<T> = nil): integer; overload; static; class function IndexOf<T>(const Template, Data: TArray<T>; AComparer: IEqualityComparer<T> = nil): integer; overload; static; class function GetPtr<T>(const Src: TArray<T>): pointer; static; class function GetFromDynArray(const Src: TStringDynArray): TArray<string>; static; class function Sum(var Arr: double; Count: integer): double; overload; static; class function Sum(var Arr: integer; Count: integer): int64; overload; static; class function Sum(var Arr: int64; Count: integer): int64; overload; static; class function StartWith<T>(const Data,Template: TArray<T>; AComparer: IEqualityComparer<T> = nil): boolean; overload; static; class function EndsWith<T>(const Data,Template: TArray<T>; AComparer: IEqualityComparer<T> = nil): boolean; overload; static; class function Contains<T>(const Template: T; const Data: TArray<T>; AComparer: IEqualityComparer<T> = nil): boolean; overload; static; class function Contains<T>(const Template,Data: TArray<T>; AComparer: IEqualityComparer<T> = nil): boolean; overload; static; class function Sorted<T>(const Arr: TArray<T>; AComparer: IComparer<T> = nil): boolean; overload; static; class function Sorted<T>(const Arr: TArray<T>; AStartIndex,ACount: integer; AComparer: IComparer<T> = nil): boolean; overload; static; class procedure Sort<T>(var Arr: TArray<T>; AComparer: TComparison<T>); static; end; { Wrapper class to make any class type available through interface (that means that lifetime of the class will be controlled by reference counter) } TInterfacedObject<T: class> = class(TInterfacedObject, IInterfacedObject<T>) protected FData: T; function GetData: T; procedure SetData(const AData: T); function GetRefCount: integer; public constructor Create(AData: T); destructor Destroy; override; function Extract: T; property Data: T read GetData write SetData; end; { TInterfacedType provides interfaced access to any type. Unlike TInterfacedObject it will not destroy inner object (if T is object type). } TInterfacedType<T> = class(TInterfacedObject, IInterfacedObject<T>) protected FData: T; function GetData: T; procedure SetData(const AData: T); function GetRefCount: integer; public constructor Create(AData: T); function Extract: T; end; { IsValid and other utils } TGUIDUtils = class public const NullGuid: TGUID = '{00000000-0000-0000-0000-000000000000}'; class function IsValid(const S: string): Boolean; static; class function TryStrToGuid(const S: string; out Dst: TGUID): boolean; static; class function StrToGuid(const S: string): TGUID; static; class function StrToGuidDef(const S: string; const Def: TGUID): TGUID; overload; static; class function StrToGuidDef(const S: string): TGUID; overload; static; class function IntToGuid(N: integer): TGUID; static; class function GuidToInt(const Src: TGUID): integer; static; class function GetNew: TGUID; static; class function GetNewAsString: string; static; end; { Currency type utils } TCurrencyUtils = class public class function ToString(const Value: Currency; FractionalPart: boolean = False): string; reintroduce; static; end; { Extends any type by IsNull property. Compare operator will use case insensitive comparer for strings (unlike default comparer for strings in Delphi). } TBox<T> = record private type PT = ^T; var FValue: T; FHasValue: string; { AH: all "inline" directives are commented, because Delphi failed to compile it in release configuration (internal error). Reproduced in Delphi 10.1 } function GetValue: T; procedure SetValue(const AValue: T); function GetEmpty: boolean; function GetPointer: PT; public procedure Init; overload; procedure Init(const AValue: T); overload; procedure Clear; function Extract: T; { assign operators } class operator Implicit(const AValue: TBox<T>): T; class operator Implicit(const AValue: T): TBox<T>; { We can't disable assigning of variant to TBox and some wrong assignments will not be checked in compile time. Delphi has different rules for conversion of Null (exception generated) and Unassigned (converted to default value). We rely on Delphi in such conversion to keep default behaviour. //class operator Implicit(const AValue: Variant): TBox<T>; { compare operators } class operator Equal(const Left, Right: TBox<T>): Boolean; class operator Equal(const Left: TBox<T>; const Right: T): Boolean; class operator Equal(const Left: T; const Right: TBox<T>): Boolean; class operator NotEqual(const Left, Right: TBox<T>): Boolean; class operator LessThan(const Left,Right: TBox<T>): Boolean; class operator LessThanOrEqual(const Left,Right: TBox<T>): Boolean; class operator GreaterThan(const Left,Right: TBox<T>): Boolean; class operator GreaterThanOrEqual(const Left,Right: TBox<T>): Boolean; { basic math operators (available for numeric types) } class operator Add(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator Subtract(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator Multiply(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator Divide(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator IntDivide(Left: TBox<T>; Right: TBox<T>): TBox<T>; class operator Negative(Value: TBox<T>): TBox<T>; property Value: T read GetValue write SetValue; property Empty: boolean read GetEmpty; property ValuePtr: PT read GetPointer; end; { Collections of system functions. We call it Sys (not TSys), because Sys.FreeAndNil looks more natural than TSys.FreeAndNil } Sys = class public { Generic IfThen, compatible with any type. Example: Rect := Sys.IfThen(Condition, Rect1, Rect2); } class function IfThen<T>(ACondition: Boolean; AValueTrue,AValueFalse: T):T; static; { Generic swap function, compatible with any type. Example: Sys.Exchange(Rect1,Rect2); } class procedure Exchange<T>(var A,B: T); static; {$IFDEF UseInline}inline;{$ENDIF} { Generic version of FreeAndNil. Much safe than regular FreeAndNil, it accepts classes only and wrong use with other type will be reported as error in compile time. Example: Sys.FreeAndNil(Obj); } class procedure FreeAndNil<T: class>(var Obj: T); static; { Safe generic implementation of FillChar(A,SizeOf(A),0) : - Strictly typified, size is calculated by compiler. - Supports managed types (strings, interfaces, dynamic arrays and other managed types will be freed correctly) } class procedure Clear<T>(var R: T); static; { creates new array (not just a reference to original one) with copy of all items } class function Copy<T>(const Src: TArray<T>): TArray<T>; overload; static; class function Copy<T>(const Src: TArray<T>; AStartIndex,ACount: integer): TArray<T>; overload; static; { Generic function to check if value is withing range } class function ValueInRange<T>(AValue, AValueFrom, AValueTo: T): boolean; static; { Type specific functions to check if value is withing range (more efficient than generic ValueInRange) } class function InRange(const AValue, AValueFrom, AValueTo: integer): boolean; overload; static; class function InRange(const AValue, AValueFrom, AValueTo: double): boolean; overload; static; { Type specific functions to check if two ranges are overlapped } class function Overlapped(const AFrom,ATo, BFrom,BTo: integer): boolean; overload; static; class function Overlapped(const AFrom,ATo, BFrom,BTo: double): boolean; overload; static; class function Min(const A,B: integer): integer; overload; static; class function Min(const A,B,C: integer): integer; overload; static; class function Min(const Values: TArray<integer>): integer; overload; static; class function Max(const A,B: integer): integer; overload; static; class function Max(const A,B,C: integer): integer; overload; static; class function Max(const Values: TArray<integer>): integer; overload; static; class function Min(const A,B: double): double; overload; static; class function Min(const A,B,C: double): double; overload; static; class function Min(const Values: TArray<double>): double; overload; static; class function Max(const A,B: double): double; overload; static; class function Max(const A,B,C: double): double; overload; static; class function Max(const Values: TArray<double>): double; overload; static; class function Min(const Values: TArray<TBox<integer>>): TBox<integer>; overload; static; class function Max(const Values: TArray<TBox<integer>>): TBox<integer>; overload; static; class function Add(const Values: TArray<TBox<integer>>): TBox<integer>; overload; static; class function Neg(const A: TBox<integer>): TBox<integer>; overload; static; class function Sub(const A,B: TBox<integer>): TBox<integer>; overload; static; class function Min(const Values: TArray<TBox<double>>): TBox<double>; overload; static; class function Max(const Values: TArray<TBox<double>>): TBox<double>; overload; static; class function Add(const Values: TArray<TBox<double>>): TBox<double>; overload; static; class function Neg(const A: TBox<double>): TBox<double>; overload; static; class function Sub(const A,B: TBox<double>): TBox<double>; overload; static; class function GetPtr(const Values: TArray<byte>): pointer; overload; static; end; { Simple generic class to keep record as object } TEnvelop<T> = class public Value: T; constructor Create; overload; constructor Create(AValue: T); overload; end; TForEachComponentBreakProc = reference to procedure(AComponent: TComponent; var ABreak: boolean); { Enumeration and other component-specific tools } TComponentUtils = class public { Enumerates all child components recursively. Returns True if canceled (ACancel is set True by ACallback) } class function ForEach(AStart: TComponent; ACallback: TProcVar1<TComponent, Boolean>): Boolean; overload; static; { Enumerates child components of type T recursively. Returns True if canceled (ACancel is set True by ACallback) } class function ForEach<T: class>(AStart: TComponent; ACallback: TProcVar1<T, Boolean>): Boolean; overload; static; { Enumerates all child components recursively } class procedure ForEach(AStart: TComponent; ACallback: TProc<TComponent>); overload; static; { Enumerates all child components of type T recursively } class procedure ForEach<T: class>(AStart: TComponent; ACallback: TProc<T>); overload; static; { Get all child components recursively } class function GetAll(AStart: TComponent): TArray<TComponent>; overload; static; { Get all child components of type T recursively } class function GetAll<T: class>(AStart: TComponent): TArray<T>; overload; static; { Generates unique component name } class function GetUniqueName: string; static; { Creates copy of the component } class function Copy<T: TComponent>(Src: T): T; static; end; { Executes custom action (procedure/method) when last instance goes out of scope (automatic finalization etc). } TOutOfScopeAction = record private FProc: IInterfacedObject<TObject>; public procedure Init(AProc: TProc); end; { Executes custom action (procedure/method) with specific parameter when last instance goes out of scope. } TOutOfScopeAction<T> = record private type TRunOnDestroy = class private FProc: TProc<T>; FValue: T; public constructor Create(AProc: TProc<T>; AValue: T); destructor Destroy; override; end; var FProc: IInterfacedObject<TRunOnDestroy>; public procedure Init(AProc: TProc<T>; AValue: T); end; TEventUtils = class public class function IsSameHandler(const A,B: TNotifyEvent): Boolean; overload; static; class function IsSameHandler(const A,B: TActionEvent): Boolean; overload; static; class function Equal<T>(const A,B: T): boolean; static; end; TDataSize = record private FSize: int64; function GetGb: double; function GetKb: double; function GetMb: double; function GetTb: double; procedure SetGb(const Value: double); procedure SetKb(const Value: double); procedure SetMb(const Value: double); procedure SetTb(const Value: double); function GetAsString: string; public const Kb = int64(1024); Mb = int64(1024)*Kb; Gb = int64(1024)*Mb; Tb = int64(1024)*Gb; procedure Init(const AValue: int64); procedure InitMb(const AValue: double); class function SizeToString(const AValue: int64): string; static; class operator Implicit(const AValue: TDataSize): int64; class operator Implicit(const AValue: int64): TDataSize; class operator Equal(const Left, Right: TDataSize): Boolean; class operator NotEqual(const Left, Right: TDataSize): Boolean; class operator LessThan(const Left,Right: TDataSize): Boolean; class operator LessThanOrEqual(const Left,Right: TDataSize): Boolean; class operator GreaterThan(const Left,Right: TDataSize): Boolean; class operator GreaterThanOrEqual(const Left,Right: TDataSize): Boolean; class operator Add(Left: TDataSize; Right: TDataSize): TDataSize; class operator Subtract(Left: TDataSize; Right: TDataSize): TDataSize; class operator Multiply(Left: TDataSize; Right: TDataSize): TDataSize; class operator Divide(Left: TDataSize; Right: TDataSize): TDataSize; class operator IntDivide(Left: TDataSize; Right: TDataSize): TDataSize; class operator Negative(Value: TDataSize): TDataSize; property SizeBytes: int64 read FSize write FSize; property SizeKb: double read GetKb write SetKb; property SizeMb: double read GetMb write SetMb; property SizeGb: double read GetGb write SetGb; property SizeTb: double read GetTb write SetTb; property AsString: string read GetAsString; end; TDebugUtils = class public { returns True if application is started from IDE for example } class function DebuggerIsAttached: boolean; static; end; implementation Uses adot.Arithmetic, adot.Tools.Rtti, adot.Tools.IO, adot.Strings, adot.Collections.Vectors; { THex } class function THex.EncodedSizeChars(SourceSizeBytes: integer): integer; begin Assert(SourceSizeBytes>=0); result := SourceSizeBytes shl 1; end; class function THex.EncodeByteH(Src: byte): char; begin result := TwoHexLookup[Src][0]; end; class function THex.EncodeByteL(Src: byte): char; begin result := TwoHexLookup[Src][1]; end; class function THex.DecodedSizeBytes(EncodedSizeChars: integer): integer; begin Assert(EncodedSizeChars and 1=0); result := EncodedSizeChars shr 1; end; class function THex.DecodeHexChar(HexChar: Char): byte; begin Assert(IsValid(HexChar)); result := H2B[HexChar]; end; {$IF Defined(NEXTGEN)} class function THex.Encode(const Buf; ByteBufSize: integer): String; const B2HConvert: array[0..15] of Byte = ($30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $41, $42, $43, $44, $45, $46); var I: Integer; begin SetLength(result, EncodedSizeChars(ByteBufSize)); for I := 0 to ByteBufSize - 1 do begin Result[Low(Result) + I*2 ] := Char(B2HConvert[PByte(@Buf)[I] shr 4]); Result[Low(Result) + I*2 + 1] := Char(B2HConvert[PByte(@Buf)[I] and $0F]); end; end; {$Else} class function THex.Encode(const Buf; ByteBufSize: integer): String; begin SetLength(result, EncodedSizeChars(ByteBufSize)); BinToHex(@Buf, PChar(result), ByteBufSize); end; {$EndIF} {$If Defined(MSWindows)} class function THex.EncodeAnsiString(const s: AnsiString): String; begin { need this check only to range check error (when "check range check" is on) } if s='' then result := '' else result := Encode(s[Low(s)], length(s)*SizeOf(s[Low(s)])); end; {$EndIf} class function THex.Encode<T>(const Value: T): String; begin Result := Encode(Value, SizeOf(Value)); end; class function THex.Encode(const s: TBytes): String; begin { need this check only to range check error (when "check range check" is on) } if Length(s)=0 then result := '' else result := Encode(s[0], length(s)); end; class function THex.Encode(const s: string): string; begin { need this check only to range check error (when "check range check" is on) } if s='' then result := '' else result := Encode(s[Low(s)], length(s)*SizeOf(s[Low(s)])); end; class function THex.Encode(const s: string; utf8: boolean): string; begin if utf8 then result := Encode(TEncoding.UTF8.GetBytes(s)) else result := Encode(s); end; {$IF Defined(NEXTGEN)} class procedure THex.Decode(const HexEncodedStr: String; var Buf); const H2BValidSet = ['0'..'9','A'..'F','a'..'f']; H2BConvert: array['0'..'f'] of SmallInt = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15); var I: Integer; C1,C2: Char; begin for I := 0 to DecodedSizeBytes(length(HexEncodedStr)) - 1 do begin C1 := HexEncodedStr[Low(String) + I * 2 ]; C2 := HexEncodedStr[Low(String) + I * 2 + 1]; if (C1 >= Low(H2BConvert)) and (C1 <= High(H2BConvert)) and (H2BConvert[C1] >=0 ) and (C2 >= Low(H2BConvert)) and (C2 <= High(H2BConvert)) and (H2BConvert[C2] >=0 ) then PByte(@Buf)[I] := (H2BConvert[C1] shl 4) or H2BConvert[C2] else Break; end; end; {$Else} class procedure THex.Decode(const HexEncodedStr: String; var Buf); begin HexToBin(PChar(HexEncodedStr), Buf, DecodedSizeBytes(length(HexEncodedStr))); end; {$EndIf} class function THex.Decode<T>(const HexEncodedStr: String): T; begin Decode(HexEncodedStr, Result); end; {$If Defined(MSWindows)} class function THex.DecodeAnsiString(const HexEncodedStr: String): AnsiString; begin { need this check only to range check error (when "check range check" is on) } if HexEncodedStr='' then Result := '' else begin SetLength(Result, DecodedSizeBytes(length(HexEncodedStr))); { AnsiString is always 1 byte per char } Decode(HexEncodedStr, result[Low(result)]); end; end; {$EndIf} class function THex.DecodeByte(H, L: Char): byte; begin result := (DecodeHexChar(H) shl 4) or DecodeHexChar(L); end; class function THex.DecodeBytes(const HexEncodedStr: String): TBytes; begin { need this check only to range check error (when "check range check" is on) } if HexEncodedStr='' then SetLength(result, 0) else begin SetLength(Result, DecodedSizeBytes(length(HexEncodedStr))); Decode(HexEncodedStr, Result[Low(Result)]); end; end; {$IF SizeOf(Char)=2} class function THex.DecodeString(const HexEncodedStr: string): string; begin { need this check only to range check error (when "check range check" is on) } if HexEncodedStr='' then result := '' else begin Assert(length(HexEncodedStr) and 3=0); SetLength(Result, length(HexEncodedStr) shr 2); Decode(HexEncodedStr, Result[Low(Result)]); end; end; {$ELSE} class function THex.DecodeString(const HexEncodedStr: string): string; var SizeInBytes: Integer; begin { need this check only to range check error (when "check range check" is on) } if HexEncodedStr='' then result := '' else begin SizeInBytes := DecodedSizeBytes(length(HexEncodedStr)); Assert(SizeInBytes mod SizeOf(Result[Low(Result)]) = 0); SetLength(Result, SizeInBytes div SizeOf(Result[Low(Result)])); Decode(HexEncodedStr, Result[Low(Result)]); end; end; {$IFEND} class function THex.DecodeString(const HexEncodedStr: string; utf8: boolean): string; begin if utf8 then result := TEncoding.UTF8.GetString( DecodeBytes(HexEncodedStr) ) else result := DecodeString(HexEncodedStr); end; class function THex.IsValid(const C: Char): Boolean; begin result := (c>=Low(H2B)) and (c<=High(H2B)) and (H2B[c]>=0); end; class function THex.IsValid(const HexEncodedStr: String; ZeroBasedStartIdx, Len: integer): Boolean; var i: Integer; begin if Len and 1<>0 then Exit(False); for i := ZeroBasedStartIdx to ZeroBasedStartIdx+Len-1 do if not IsValid(HexEncodedStr.Chars[i]) then Exit(False); Result := True; end; class function THex.IsValid(const HexEncodedStr: String): Boolean; begin if Length(HexEncodedStr) and 1<>0 then Exit(False); Result := IsValid(HexEncodedStr, 0,Length(HexEncodedStr)); end; class function THex.HexToInt64(const HexEncodedInt: String):Int64; var i: Integer; begin assert(IsValid(HexEncodedInt)); result := 0; for i := Low(HexEncodedInt) to High(HexEncodedInt) do result := (result shl 4) or H2B[HexEncodedInt[i]]; end; class function THex.HexToUInt64(const HexEncodedInt: String):UInt64; begin result := UInt64(HexToInt64(HexEncodedInt)); end; class function THex.HexToNativeInt(const HexEncodedInt: String):NativeInt; var i: Integer; begin assert(IsValid(HexEncodedInt)); result := 0; for i := Low(HexEncodedInt) to High(HexEncodedInt) do result := (result shl 4) or H2B[HexEncodedInt[i]]; end; class function THex.HexToNativeUInt(const HexEncodedInt: String):NativeUInt; begin result := NativeUInt(HexToNativeInt(HexEncodedInt)); end; class function THex.HexToPointer(const HexEncodedPointer: String): Pointer; begin result := Pointer(HexToNativeUInt(HexEncodedPointer)); end; class function THex.HexToCardinal(const HexEncodedCardinal: String):Cardinal; var i: Integer; begin assert(IsValid(HexEncodedCardinal)); result := 0; for i := Low(HexEncodedCardinal) to High(HexEncodedCardinal) do result := (result shl 4) or Cardinal(H2B[HexEncodedCardinal[i]]); end; class function THex.HexToWord(const HexEncodedWord: String):Word; begin result := Word(HexToCardinal(HexEncodedWord)); end; class function THex.Int64ToHex(s: Int64): string; var i,j: Integer; begin SetLength(result, SizeOf(s)*2); for i := High(result) shr 1 downto 0 do begin J := S and $FF; S := S shr 8; Result[i*2 + Low(result) ] := TwoHexLookup[J][0]; Result[i*2 + Low(result) + 1] := TwoHexLookup[J][1]; end; end; class function THex.UInt64ToHex(s: UInt64): string; begin result := Int64ToHex(Int64(s)); end; class function THex.NativeIntToHex(s: NativeInt): string; var i,j: Integer; begin SetLength(result, SizeOf(s)*2); for i := SizeOf(s)-1 downto 0 do begin J := S and $FF; S := S shr 8; Result[i*2 + Low(result) ] := TwoHexLookup[J][0]; Result[i*2 + Low(result) + 1] := TwoHexLookup[J][1]; end; end; class function THex.NativeUIntToHex(s: NativeUInt): string; begin result := NativeIntToHex(NativeInt(s)); end; class function THex.PointerToHex(s: Pointer): string; begin result := NativeIntToHex(NativeInt(s)); end; class function THex.CardinalToHex(s: cardinal): string; var i,j: Integer; begin SetLength(result, SizeOf(s)*2); for i := SizeOf(s)-1 downto 0 do begin J := S and $FF; S := S shr 8; Result[i*2 + Low(result) ] := TwoHexLookup[J][0]; Result[i*2 + Low(result) + 1] := TwoHexLookup[J][1]; end; end; class function THex.WordToHex(s: word): string; var i,j: Integer; begin SetLength(result, SizeOf(s)*2); for i := SizeOf(s)-1 downto 0 do begin J := S and $FF; S := S shr 8; Result[i*2 + Low(result) ] := TwoHexLookup[J][0]; Result[i*2 + Low(result) + 1] := TwoHexLookup[J][1]; end; end; { TInvertedComparer<TValue> } constructor TInvertedComparer<TValueType>.Create(AExtComparer: IComparer<TValueType>); begin inherited Create; FExtComparer := AExtComparer; if FExtComparer=nil then FExtComparer := TComparer<TValueType>.Default; end; function TInvertedComparer<TValueType>.Compare(const Left, Right: TValueType): Integer; begin result := -FExtComparer.Compare(Left, Right); end; { TDateTimeRec } class operator TDateTimeRec.Implicit(const ADateTime: TDateTime): TDateTimeRec; begin with Result do DecodeDateTime(ADateTime, Year, Month, Day, Hour, Minute, Second, Millisecond); end; class operator TDateTimeRec.Implicit(const ADateTime: TDateTimeRec): TDateTime; begin with ADateTime do Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, Millisecond); end; class operator TDateTimeRec.Implicit(const ADateTime: String): TDateTimeRec; begin Result := StrToDateTime(ADateTime); end; class operator TDateTimeRec.Implicit(const ADateTime: TDateTimeRec): String; begin Result := DateTimeToStr(ADateTime); end; { TArrayUtils } class function TArrayUtils.Copy<T>(const Src: TArray<T>): TArray<T>; begin result := Copy<T>(Src, 0, Length(Src)); end; class function TArrayUtils.Copy<T>(const Src: TArray<T>; StartIndex, Count: integer): TArray<T>; var i: Integer; begin SetLength(result, Count); if Count > 0 then if TRttiUtils.IsOrdinal<T> then System.Move(Src[StartIndex], Result[0], Count*SizeOf(T)) else for i := 0 to Count-1 do result[i] := Src[i + StartIndex]; end; class function TArrayUtils.Copy<T>(const Src: TArray<T>; ACopyFilter: TFuncConst<T, Boolean>): TArray<T>; var i,j: Integer; begin SetLength(result, Length(Src)); j := 0; for i := 0 to High(Src) do if ACopyFilter(Src[i]) then begin result[j] := Src[i]; inc(j); end; SetLength(result, j); end; class procedure TArrayUtils.Append<T>(var Dst: TArray<T>; const Src: T); var i: integer; begin i := Length(Dst); SetLength(Dst, i+1); Dst[i] := Src; end; class procedure TArrayUtils.Append<T>(var Dst: TArray<T>; const Src: TArray<T>); var i,j: integer; begin j := Length(Dst); SetLength(Dst, j + Length(Src)); for I := 0 to High(Src) do Dst[I+J] := Src[I]; end; class function TArrayUtils.Add<T>(const A, B: TArray<T>): TArray<T>; var I,J: Integer; begin SetLength(Result, Length(A) + Length(B)); for I := 0 to Length(A)-1 do Result[I] := A[I]; J := Length(A); for I := 0 to Length(B)-1 do Result[I+J] := B[I]; end; class procedure TArrayUtils.Append<T>(var Dst: TArray<T>; const Src: TEnumerable<T>); var I: integer; Value: T; begin I := 0; for Value in Src do inc(I); SetLength(dst, Length(dst) + I); I := Length(dst) - I; for Value in Src do begin Dst[I] := Value; inc(I); end; Assert(I=Length(Dst)); end; class function TArrayUtils.Contains<T>(const Template: T; const Data: TArray<T>; AComparer: IEqualityComparer<T>): boolean; begin result := IndexOf<T>(Template, Data, AComparer) >= 0; end; class function TArrayUtils.Contains<T>(const Template, Data: TArray<T>; AComparer: IEqualityComparer<T>): boolean; begin result := IndexOf<T>(Template, Data, AComparer) >= 0; end; class function TArrayUtils.Sorted<T>(const Arr: TArray<T>; AComparer: IComparer<T> = nil): boolean; begin result := Sorted<T>(Arr, 0, Length(Arr), AComparer); end; class procedure TArrayUtils.Sort<T>(var Arr: TArray<T>; AComparer: TComparison<T>); var C: IComparer<T>; begin C := TDelegatedComparer<T>.Create(AComparer); TArray.Sort<T>(Arr, C); end; class function TArrayUtils.Sorted<T>(const Arr: TArray<T>; AStartIndex,ACount: integer; AComparer: IComparer<T> = nil): boolean; var I: Integer; begin if ACount <= 0 then Exit(True); if AComparer = nil then AComparer := TComparerUtils.DefaultComparer<T>; Assert((AStartIndex >= 0) and (AStartIndex + ACount - 1 < Length(Arr))); for I := AStartIndex to AStartIndex + ACount - 2 do if AComparer.Compare(Arr[I], Arr[I+1]) > 0 then Exit(False); result := True; end; class procedure TArrayUtils.Delete<T>(var Arr: TArray<T>; AFilter: TFuncConst<T, Boolean>); var i,j: Integer; begin j := -1; for i := 0 to High(Arr) do if AFilter(Arr[i]) then begin j := i; Break; end; if j<0 then Exit; for i := j+1 to High(Arr) do if not AFilter(Arr[i]) then begin Arr[j] := Arr[i]; inc(j); end; SetLength(Arr, j); end; class procedure TArrayUtils.Delete<T>(var Arr: TArray<T>; Index: integer); var I: Integer; begin if (Index >= Low(Arr)) and (Index <= High(Arr)) then begin for I := Index to High(Arr)-1 do Arr[I] := Arr[I+1]; SetLength(Arr, Length(Arr)-1); end; end; class function TArrayUtils.Equal<T>(const A, B: TArray<T>; IndexA, IndexB, Count: integer; AComparer: IEqualityComparer<T>): Boolean; var I,J: Integer; begin if (Length(A)-IndexA < Count) or (Length(B)-IndexB < Count) then Exit(False); if Count <= 0 then Exit(True); if TRttiUtils.IsOrdinal<T> and (AComparer=nil) then { A & B are not empty -> it is safe to use @A[0] / @B[0] } result := CompareMem(@A[IndexA], @B[IndexB], Count*SizeOF(T)) else begin if AComparer=nil then AComparer := TEqualityComparer<T>.Default; for i := 0 to Count-1 do if not AComparer.Equals(A[i+IndexA], B[i+IndexB]) then Exit(False); result := True; end; end; class function TArrayUtils.Equal<T>(const A, B: TArray<T>; AComparer: IEqualityComparer<T>): Boolean; var i: Integer; begin result := Length(A)=Length(B); if result and (Length(A) > 0) then if TRttiUtils.IsOrdinal<T> and (AComparer=nil) then { A & B are not empty -> it is safe to use @A[0] / @B[0] } result := CompareMem(@A[0], @B[0], Length(A)*SizeOF(T)) else begin if AComparer=nil then AComparer := TEqualityComparer<T>.Default; for i := 0 to High(A) do if not AComparer.Equals(A[i], B[i]) then Exit(False); end; end; class procedure TArrayUtils.Fill(var Dst: TArray<byte>; Count, AValueStart, AValueInc: integer); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do begin Dst[I] := AValueStart; inc(AValueStart, AValueInc); end; end; class procedure TArrayUtils.Fill(var Dst: TArray<integer>; Count, AValueStart, AValueInc: integer); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do begin Dst[I] := AValueStart; inc(AValueStart, AValueInc); end; end; class procedure TArrayUtils.Fill(var Dst: TArray<double>; Count: integer; AValueStart, AValueInc: double); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do begin Dst[I] := AValueStart; AValueStart := AValueStart + AValueInc; end; end; class procedure TArrayUtils.FillRandom(var Dst: TArray<byte>; Count: integer; AValRangeFrom, AValRangeTo: byte); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do Dst[I] := AValRangeFrom + Random(integer(AValRangeTo)-integer(AValRangeFrom)+1); end; class procedure TArrayUtils.FillRandom(var Dst: TArray<integer>; Count, AValRangeFrom, AValRangeTo: integer); var I: Integer; begin if Count >= 0 then SetLength(Dst, Count); for I := 0 to High(Dst) do Dst[I] := AValRangeFrom + Random(AValRangeTo-AValRangeFrom+1); end; class procedure TArrayUtils.FillRandom(var Dst: TArray<string>; Count, ValMaxLen: integer); var i: Integer; begin if Count >=0 then SetLength(Dst, Count); if ValMaxLen <= 0 then ValMaxLen := 10; for i := 0 to High(Dst) do Dst[i] := TStr.Random(System.Random(ValMaxLen), 'a','z'); end; class procedure TArrayUtils.FillRandom(var Dst: TArray<double>; Count: integer; AValRangeFrom, AValRangeTo: double); var i: Integer; begin if Count >=0 then SetLength(Dst, Count); for I := 0 to High(Dst) do Dst[I] := AValRangeFrom + Random*(AValRangeTo-AValRangeFrom); end; class function TArrayUtils.Get(const Arr: TStringDynArray): TArray<string>; var I: Integer; begin SetLength(result, Length(Arr)); for I := Low(Arr) to High(Arr) do result[I] := Arr[I]; end; class function TArrayUtils.Get<T>(const Arr: array of T): TArray<T>; var i: Integer; begin SetLength(result, Length(Arr)); for i := 0 to High(result) do result[i] := Arr[i]; end; class function TArrayUtils.GetFromDynArray(const Src: TStringDynArray): TArray<string>; var I: Integer; begin SetLEngth(result, Length(Src)); for I := Low(Src) to High(Src) do result[I] := Src[I]; end; class function TArrayUtils.GetPtr<T>(const Src: TArray<T>): pointer; begin if Length(Src)=0 then result := nil else result := @Src[0]; end; class function TArrayUtils.IndexOf<T>(const Item: T; const Src: TEnumerable<T>; AComparer: IEqualityComparer<T> = nil): integer; var V: T; begin if AComparer = nil then AComparer := TComparerUtils.DefaultEqualityComparer<T>; result := 0; for V in Src do if AComparer.Equals(V, Item) then Exit else inc(result); result := -1; end; class function TArrayUtils.IndexOf<T>(const Item: T; const Src: TArray<T>; AComparer: IEqualityComparer<T> = nil): integer; var I: integer; begin if AComparer = nil then AComparer := TComparerUtils.DefaultEqualityComparer<T>; for I := 0 to High(Src) do if AComparer.Equals(Src[I], Item) then Exit(I); result := -1; end; class function TArrayUtils.IndexOf<T>(const Template, Data: TArray<T>; AComparer: IEqualityComparer<T>): integer; var I,J: integer; begin result := -1; if (Length(Data)=0) or (Length(Data) < Length(Template)) then Exit; if AComparer = nil then AComparer := TComparerUtils.DefaultEqualityComparer<T>; for I := 0 to Length(Data)-Length(Template) do if AComparer.Equals(Data[I], Template[0]) then begin result := I; for J := 1 to High(Template) do if not AComparer.Equals(Data[I+J], Template[J]) then begin result := -1; break; end; if result >= 0 then break; end; end; class procedure TArrayUtils.Inverse<T>(var Arr: TArray<T>; AStartIndex, ACount: integer); var i,EndIndex: Integer; Value: T; begin if ACount < 0 then ACount := Length(Arr); EndIndex := AStartIndex + ACount - 1; for i := 0 to ACount div 2-1 do begin Value := Arr[AStartIndex]; Arr[AStartIndex] := Arr[EndIndex]; Arr[EndIndex] := Value; inc(AStartIndex); dec(EndIndex); end; end; class procedure TArrayUtils.Randomize<T>(var Arr: TArray<T>); var I,J,N: Integer; V: T; begin N := Length(Arr); for I := 0 to N-1 do begin J := Random(N); V := Arr[I]; Arr[I] := Arr[J]; Arr[J] := V; end; end; class function TArrayUtils.Ranges(Src: TEnumerable<integer>): TRangeEnumerable; begin result := Ranges(Src.ToArray); end; class function TArrayUtils.Ranges(Src: TArray<integer>): TRangeEnumerable; begin result.Init(Src); end; class procedure TArrayUtils.SaveToFileAsBin<T>(const Arr: TArray<T>; const AFileName: string); var Stream: TFileStream; begin Stream := TFileStream.Create(AFileName, fmCreate); try Stream.Write(Arr[Low(Arr)], SizeOf(T)*Length(Arr)) finally Stream.Free; end; end; class procedure TArrayUtils.SaveToFileAsText<T>(const Arr: TArray<T>; const AFileName: string); var Stream: TFileStream; Writer: TStreamWriter; Value: T; begin Stream := nil; Writer := nil; try Stream := TFileStream.Create(AFileName, fmCreate); Writer := TStreamWriter.Create(Stream); for Value in Arr do Writer.Write( TValue.From(Value).ToString ); finally Writer.Free; Stream.Free; end; end; class procedure TArrayUtils.StableSort<T>(var Dst: TArray<T>; StartIndex, Count: integer; Comparer: IComparer<T>); var Idx: TArray<integer>; Src,Tmp: TArray<T>; Cmp: IComparer<integer>; I: Integer; begin SetLength(Idx, Count); for I := 0 to High(Idx) do Idx[I] := I + StartIndex; Src := Dst; Cmp := TDelegatedComparer<integer>.Create( function(const A,B: integer): integer begin result := Comparer.Compare(Src[Idx[A]], Src[Idx[B]]); if result=0 then result := Idx[B]-Idx[A]; end); TArray.Sort<integer>(Idx, Cmp); SetLength(Tmp, Count); for I := 0 to High(Tmp) do Tmp[I] := Dst[Idx[I]]; for I := 0 to High(Tmp) do Dst[I+StartIndex] := Tmp[I]; end; class function TArrayUtils.StartWith<T>(const Data, Template: TArray<T>; AComparer: IEqualityComparer<T>): boolean; begin result := (Length(Data) >= Length(Template)) and TArrayUtils.Equal<T>(Data, Template, 0, 0, Length(Template), AComparer); end; class function TArrayUtils.EndsWith<T>(const Data, Template: TArray<T>; AComparer: IEqualityComparer<T>): boolean; begin result := (Length(Data) >= Length(Template)) and TArrayUtils.Equal<T>(Data, Template, Length(Data)-Length(Template), 0, Length(Template), AComparer); end; class function TArrayUtils.Sum(var Arr: integer; Count: integer): int64; var p: ^integer; begin p := @Arr; result := 0; while Count > 0 do begin dec(Count); inc(result, p^); inc(p); end; end; class function TArrayUtils.Sum(var Arr: int64; Count: integer): int64; var p: ^int64; begin p := @Arr; result := 0; while Count > 0 do begin dec(Count); inc(result, p^); inc(p); end; end; class function TArrayUtils.Sum(var Arr: double; Count: integer): double; var p: ^double; begin p := @Arr; result := 0; while Count > 0 do begin dec(Count); result := result + p^; inc(p); end; end; class function TArrayUtils.Cut<T>(var Dst: TArray<T>; Capacity,StartIndex,Count: integer): integer; var I: Integer; begin if StartIndex >= Capacity then Exit(0); result := Count; if StartIndex < 0 then begin inc(result, StartIndex); StartIndex := 0; end; result := Max(Min(result, Capacity-StartIndex), 0); if result = 0 then Exit; if TRttiUtils.IsOrdinal<T> then System.Move(Dst[StartIndex+result], Dst[StartIndex], (Capacity-StartIndex-result)*SizeOf(T)) else for I := 0 to result-1 do Dst[I+StartIndex] := Dst[I+StartIndex+result]; end; class function TArrayUtils.Cut<T>(var Dst: TArray<T>; StartIndex,Count: integer): integer; begin result := Cut<T>(Dst, Length(Dst), StartIndex, Count); end; class function TArrayUtils.Slice<T>(const Src: TArray<T>; Capacity,StartIndex,Count: integer): TArray<T>; var I: Integer; begin if StartIndex >= Capacity then Count := 0 else begin if StartIndex < 0 then begin inc(Count, StartIndex); StartIndex := 0; end; Count := Min(Count, Capacity-StartIndex); end; if Count <= 0 then SetLength(result, 0) else begin SetLength(result, Count); if TRttiUtils.IsOrdinal<T> then System.Move(Src[StartIndex], result[0], Count*SizeOf(T)) else for I := 0 to Count-1 do result[I] := Src[I+StartIndex]; end; end; class function TArrayUtils.Slice<T>(const Src: TArray<T>; StartIndex,Count: integer): TArray<T>; begin result := Slice<T>(Src, Length(Src), StartIndex, Count); end; class function TArrayUtils.Slice<T>(const Src: TArray<T>; CopyValue: TFunc<T, boolean>): TArray<T>; var V: TVector<T>; I: Integer; begin V.Init; for I := Low(Src) to High(Src) do if CopyValue(Src[I]) then V.Add(Src[I]); result := V.ToArray; end; { TDateTimeUtils } class function TDateTimeUtils.ToStringStd(const t: TDateTime): string; var F: TFormatSettings; begin F := StdEuFormatSettings; result := DateTimeToStr(t, F); end; class function TDateTimeUtils.FromStringStd(const t: string; def: TDateTime = 0): TDateTime; var F: TFormatSettings; begin F := StdEuFormatSettings; if not TryStrToDateTime(t, result, F) then result := Def; end; class function TDateTimeUtils.IsCorrectDate(const t: TDateTime): boolean; begin result := (Trunc(t)<>0) and { 0 (30.12.1899) as empty value } (YearOf(t)>0); { -700000 (00.00.0000) as empty value + Delphi supports only "01.01.01" and later } end; class function TDateTimeUtils.StdEuFormatSettings: TFormatSettings; begin result := TFormatSettings.Create; result.CurrencyString := 'eur'; result.CurrencyFormat := 2; result.CurrencyDecimals := 2; result.DateSeparator := '.'; result.TimeSeparator := '.'; result.ListSeparator := ';'; result.ShortDateFormat := 'dd/MM/yyyy'; result.LongDateFormat := 'dddd d/ MMMM yyyy'; result.TimeAMString := 'a.m.'; result.TimePMString := 'p.m.'; result.ShortTimeFormat := 'hh:mm'; result.LongTimeFormat := 'hh:mm:ss'; result.ThousandSeparator := ' '; result.DecimalSeparator := '.'; { not EU, but std in math etc } result.TwoDigitYearCenturyWindow := 50; {h32} result.NegCurrFormat := 9; result.NormalizedLocaleName := ''; end; class function TDateTimeUtils.ToStr(const t: TDateTime; ANoDateStr: string): string; begin if IsCorrectDate(t) then result := DateToStr(t) else result := ANoDateStr; end; { TInterfacedObject<T> } constructor TInterfacedObject<T>.Create(AData: T); begin inherited Create; FData := AData; end; destructor TInterfacedObject<T>.Destroy; begin Sys.FreeAndNil(FData); inherited; end; function TInterfacedObject<T>.Extract: T; begin result := FData; FData := nil; end; function TInterfacedObject<T>.GetData: T; begin result := FData; end; procedure TInterfacedObject<T>.SetData(const AData: T); begin if (FData<>nil) and (FData<>AData) then Sys.FreeAndNil(FData); FData := AData; end; function TInterfacedObject<T>.GetRefCount: integer; begin result := RefCount; end; { TGUIDUtils } class function TGUIDUtils.IntToGuid(N: integer): TGUID; begin {$If SizeOf(integer)<>4} {$MESSAGE ERROR 'unexpected size of integer type' } {$EndIf} result := Default(TGUID); result.D1 := cardinal(N); end; class function TGUIDUtils.GuidToInt(const Src: TGUID): integer; begin {$If SizeOf(integer)<>4} {$MESSAGE ERROR 'unexpected size of integer type' } {$EndIf} result := integer(Src.D1); end; class function TGUIDUtils.IsValid(const S: string): Boolean; var i: Integer; begin (* {41D3CDB4-1249-41CF-91E8-52D2C2EDC314} *) i := Length(S); result := (i = 38) and (S.Chars[ 0] = '{') and (S.Chars[i-1] = '}') and (S.Chars[ 9] = '-') and (S.Chars[ 14] = '-') and (S.Chars[ 19] = '-') and (S.Chars[ 24] = '-') and THex.IsValid(S, 1, 8) and THex.IsValid(S, 10, 4) and THex.IsValid(S, 15, 4) and THex.IsValid(S, 20, 4) and THex.IsValid(S, 25,12); end; class function TGUIDUtils.GetNew: TGUID; begin CreateGUID(Result); end; class function TGUIDUtils.GetNewAsString: string; var G: TGUID; begin CreateGUID(G); result := GuidToString(G); end; class function TGUIDUtils.TryStrToGuid(const S: string; out Dst: TGUID): boolean; var V: string; begin V := Trim(S); result := IsValid(V); if result then Dst := StringToGuid(V); end; class function TGUIDUtils.StrToGuid(const S: string): TGUID; begin result := StringToGuid(Trim(S)); end; class function TGUIDUtils.StrToGuidDef(const S: string): TGUID; begin result := StrToGuidDef(S, NullGuid); end; class function TGUIDUtils.StrToGuidDef(const S: string; const Def: TGUID): TGUID; var V: string; begin V := Trim(S); if IsValid(V) then result := StringToGuid(V) else result := Def; end; { TCurrencyUtils } class function TCurrencyUtils.ToString(const Value: currency; FractionalPart: boolean): string; begin result := FormatCurr( IfThen(FractionalPart, '#,##', '#,'), Value); end; { TBox<T> } procedure TBox<T>.Init; begin Self := Default(TBox<T>); end; procedure TBox<T>.Init(const AValue: T); begin Self := Default(TBox<T>); Value := AValue; end; procedure TBox<T>.Clear; begin Self := Default(TBox<T>); end; function TBox<T>.GetValue: T; begin if Empty then raise EInvalidOperation.Create('No value to read'); result := FValue; end; procedure TBox<T>.SetValue(const AValue: T); begin FValue := AValue; FHasValue := '1'; end; function TBox<T>.GetEmpty: boolean; begin result := FHasValue=''; end; function TBox<T>.GetPointer: PT; begin result := @FValue; end; class operator TBox<T>.GreaterThan(const Left, Right: TBox<T>): Boolean; begin { we have LessThan implementation already } Result := Right < Left; end; class operator TBox<T>.GreaterThanOrEqual(const Left, Right: TBox<T>): Boolean; begin { we have LessThanOrEqual implementation already } result := Right <= Left; end; class operator TBox<T>.Equal(const Left, Right: TBox<T>): Boolean; var Comparer: IEqualityComparer<T>; begin if Left.Empty or Right.Empty then Result := Left.Empty = Right.Empty else begin Comparer := TComparerUtils.DefaultEqualityComparer<T>; Result := Comparer.Equals(Left.Value, Right.Value); end; end; class operator TBox<T>.Equal(const Left: TBox<T>; const Right: T): Boolean; var Comparer: IEqualityComparer<T>; begin if Left.Empty then result := False else begin Comparer := TComparerUtils.DefaultEqualityComparer<T>; Result := Comparer.Equals(Left.Value, Right); end end; class operator TBox<T>.Equal(const Left: T; const Right: TBox<T>): Boolean; begin { We have implementation for (Left: TBox<T>; Right: T) already. } Result := Right=Left; end; function TBox<T>.Extract: T; begin Assert(not Empty); result := Value; Clear; end; class operator TBox<T>.NotEqual(const Left, Right: TBox<T>): Boolean; begin result := not (Left=Right); end; class operator TBox<T>.Implicit(const AValue: T): TBox<T>; begin result.Init(AValue); end; class operator TBox<T>.Implicit(const AValue: TBox<T>): T; begin result := AValue.Value; end; class operator TBox<T>.LessThan(const Left, Right: TBox<T>): Boolean; var C: IComparer<T>; begin { Null < any real value } if Left.Empty then result := not Right.Empty else if Right.Empty then Result := False else begin C := TComparerUtils.DefaultComparer<T>; result := C.Compare(Left.Value, Right.Value) < 0; end; end; class operator TBox<T>.LessThanOrEqual(const Left, Right: TBox<T>): Boolean; var C: IComparer<T>; begin { Null < any real value } if Left.Empty then Result := True else if Right.Empty then Result := False else begin C := TComparerUtils.DefaultComparer<T>; result := C.Compare(Left.Value, Right.Value) <= 0; end; end; class operator TBox<T>.Add(Left, Right: TBox<T>): TBox<T>; begin if Left.Empty or Right.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Add(Left, Right); end; class operator TBox<T>.Divide(Left, Right: TBox<T>): TBox<T>; begin if Left.Empty or Right.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Divide(Left, Right); end; class operator TBox<T>.IntDivide(Left, Right: TBox<T>): TBox<T>; begin result := Left / Right; end; class operator TBox<T>.Subtract(Left, Right: TBox<T>): TBox<T>; begin if Left.Empty or Right.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Subtract(Left, Right); end; class operator TBox<T>.Multiply(Left, Right: TBox<T>): TBox<T>; begin if Left.Empty or Right.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Multiply(Left, Right); end; class operator TBox<T>.Negative(Value: TBox<T>): TBox<T>; begin if Value.Empty then raise Exception.Create('Bad operation'); result := TArithmeticUtils<T>.DefaultArithmetic.Negative(Value); end; { TComponentUtils } class function TComponentUtils.ForEach(AStart: TComponent; ACallback: TProcVar1<TComponent, Boolean>): Boolean; var i: Integer; begin if AStart<>nil then begin { check if canceled by callback function } result := False; ACallback(AStart, result); if result then Exit(False); { check if any subsearch canceled } for i := AStart.ComponentCount-1 downto 0 do if not ForEach(AStart.Components[i], ACallback) then Exit(False); end; result := True; end; class function TComponentUtils.Copy<T>(Src: T): T; var MemoryStream: TMemoryStream; begin MemoryStream := TMemoryStream.Create; try MemoryStream.WriteComponent(Src); MemoryStream.Seek(0, TSeekOrigin.soBeginning); Result := MemoryStream.ReadComponent(nil) as T; finally MemoryStream.free; end; end; class procedure TComponentUtils.ForEach(AStart: TComponent; ACallback: TProc<TComponent>); var i: Integer; begin if AStart=nil then Exit; ACallback(AStart); for i := AStart.ComponentCount-1 downto 0 do ForEach(AStart.Components[i], ACallback); end; class function TComponentUtils.ForEach<T>(AStart: TComponent; ACallback: TProcVar1<T, Boolean>): Boolean; begin result := ForEach(AStart, procedure(C: TComponent; var Break: boolean) begin if C is T then ACallback(T(C), Break); end); end; class procedure TComponentUtils.ForEach<T>(AStart: TComponent; ACallback: TProc<T>); begin ForEach(AStart, procedure(C: TComponent) begin if C is T then ACallback(T(C)); end); end; class function TComponentUtils.GetAll(AStart: TComponent): TArray<TComponent>; var V: TVector<TComponent>; begin V.Init(AStart.ComponentCount); ForEach(AStart, procedure(C: TComponent) begin V.Add(C); end); Result := V.ToArray; end; class function TComponentUtils.GetAll<T>(AStart: TComponent): TArray<T>; var V: TVector<T>; begin V.Init(AStart.ComponentCount); ForEach(AStart, procedure(C: TComponent) begin if C is T then V.Add(T(C)); end); result := V.ToArray; end; class function TComponentUtils.GetUniqueName: string; begin result := GuidToString(TGUIDUtils.GetNew).Replace('-','', [rfReplaceAll]); result := 'G' + result.Substring(1, Length(result)-2); end; { TOutOfScopeAction.TOnDestroyRunner } type TOnDestroyRunner = class private FProc: TProc; constructor Create(AProc: TProc); destructor Destroy; override; end; constructor TOnDestroyRunner.Create(AProc: TProc); begin FProc := AProc; end; destructor TOnDestroyRunner.Destroy; begin if Assigned(FProc) then FProc; inherited; end; { TOutOfScopeAction } procedure TOutOfScopeAction.Init(AProc: TProc); begin Self := Default(TOutOfScopeAction); FProc := TInterfacedObject<TObject>.Create(TOnDestroyRunner.Create(AProc)); end; { TOutOfScopeAction<T> } procedure TOutOfScopeAction<T>.Init(AProc: TProc<T>; AValue: T); begin Self := Default(TOutOfScopeAction<T>); FProc := TInterfacedObject<TRunOnDestroy>.Create(TRunOnDestroy.Create(AProc, AValue)); end; { TOutOfScopeAction<T>.TRunOnDestroy } constructor TOutOfScopeAction<T>.TRunOnDestroy.Create(AProc: TProc<T>; AValue: T); begin FProc := AProc; FValue := AValue; end; destructor TOutOfScopeAction<T>.TRunOnDestroy.Destroy; begin FProc(FValue); inherited; end; { TEventUtils } class function TEventUtils.IsSameHandler(const A, B: TNotifyEvent): Boolean; begin result := CompareMem(@A, @B, SizeOF(TNotifyEvent)); end; class function TEventUtils.Equal<T>(const A, B: T): boolean; begin result := CompareMem(@A, @B, SizeOF(T)); end; class function TEventUtils.IsSameHandler(const A, B: TActionEvent): Boolean; begin result := CompareMem(@A, @B, SizeOF(TActionEvent)); end; { TFun } class procedure Sys.Clear<T>(var R: T); begin R := Default(T); end; class function Sys.Copy<T>(const Src: TArray<T>; AStartIndex, ACount: integer): TArray<T>; begin SetLength(Result, ACount); TArray.Copy<T>(Src, Result, AStartIndex, 0, ACount); end; class function Sys.Copy<T>(const Src: TArray<T>): TArray<T>; begin SetLength(Result, Length(Src)); TArray.Copy<T>(Src, Result, Length(Src)); end; class procedure Sys.Exchange<T>(var A, B: T); var C: T; begin C := A; A := B; B := C; end; class procedure Sys.FreeAndNil<T>(var Obj: T); begin {$IF Defined(AUTOREFCOUNT)} Obj := nil; {$ELSE} { unlike SysUtils.FreeAndNil we call destructor first and only after set to nil } if Obj<>nil then begin Obj.Destroy; Obj := nil; end; {$ENDIF} end; class function Sys.GetPtr(const Values: TArray<byte>): pointer; begin if Length(Values)=0 then result := nil else result := @Values[0]; end; class function Sys.IfThen<T>(ACondition: Boolean; AValueTrue, AValueFalse: T): T; begin if ACondition then result := AValueTrue else result := AValueFalse; end; class function Sys.InRange(const AValue, AValueFrom, AValueTo: integer): boolean; begin if AValueFrom <= AValueTo then result := (AValue >= AValueFrom) and (AValue <= AValueTo) else result := (AValue >= AValueTo) and (AValue <= AValueFrom); end; class function Sys.InRange(const AValue, AValueFrom, AValueTo: double): boolean; begin if AValueFrom <= AValueTo then result := (AValue >= AValueFrom) and (AValue <= AValueTo) else result := (AValue >= AValueTo) and (AValue <= AValueFrom); end; class function Sys.ValueInRange<T>(AValue, AValueFrom, AValueTo: T): boolean; var Comparer: IComparer<T>; begin Comparer := TComparerUtils.DefaultComparer<T>; if Comparer.Compare(AValueFrom, AValueTo) <= 0 then Result := (Comparer.Compare(AValue, AValueFrom) >= 0) and (Comparer.Compare(AValue, AValueTo) <= 0) else Result := (Comparer.Compare(AValue, AValueTo) >= 0) and (Comparer.Compare(AValue, AValueFrom) <= 0); end; class function Sys.Max(const A, B, C: double): double; begin Result := A; if B > Result then Result := B; if C > Result then Result := C; end; class function Sys.Max(const A, B: double): double; begin if A >= B then result := A else result := B; end; class function Sys.Max(const A, B: integer): integer; begin if A >= B then result := A else result := B; end; class function Sys.Min(const Values: TArray<integer>): integer; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] < result then result := Values[I]; end; class function Sys.Max(const Values: TArray<integer>): integer; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] > result then result := Values[I]; end; class function Sys.Max(const A, B, C: integer): integer; begin Result := A; if B > Result then Result := B; if C > Result then Result := C; end; class function Sys.Min(const A, B, C: double): double; begin Result := A; if B < Result then Result := B; if C < Result then Result := C; end; class function Sys.Min(const A, B: double): double; begin if A <= B then result := A else result := B; end; class function Sys.Min(const A, B: integer): integer; begin if A <= B then result := A else result := B; end; class function Sys.Min(const A, B, C: integer): integer; begin Result := A; if B < Result then Result := B; if C < Result then Result := C; end; class function Sys.Overlapped(const AFrom, ATo, BFrom, BTo: integer): boolean; begin if AFrom <= ATo then if BFrom <= BTo then result := (AFrom <= BTo) and (BFrom <= ATo) else result := (AFrom <= BFrom) and (BTo <= ATo) else if BFrom <= BTo then result := (ATo <= BTo) and (BFrom <= AFrom) else result := (ATo <= BFrom) and (BTo <= AFrom); end; class function Sys.Overlapped(const AFrom, ATo, BFrom, BTo: double): boolean; begin if AFrom <= ATo then if BFrom <= BTo then result := (AFrom <= BTo) and (BFrom <= ATo) else result := (AFrom <= BFrom) and (BTo <= ATo) else if BFrom <= BTo then result := (ATo <= BTo) and (BFrom <= AFrom) else result := (ATo <= BFrom) and (BTo <= AFrom); end; class function Sys.Sub(const A, B: TBox<double>): TBox<double>; begin if A.Empty then if B.Empty then result.Init else result.Value := -B.Value else if B.Empty then result.Value := A.Value else result.Value := A.Value - B.Value; end; class function Sys.Sub(const A, B: TBox<integer>): TBox<integer>; begin if A.Empty then if B.Empty then result.Init else result.Value := -B.Value else if B.Empty then result.Value := A.Value else result.Value := A.Value - B.Value; end; class function Sys.Min(const Values: TArray<double>): double; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] < result then result := Values[I]; end; class function Sys.Max(const Values: TArray<double>): double; var I: integer; begin Assert(Length(Values)>0); Result := Values[Low(Values)]; for I := Low(Values)+1 to High(Values) do if Values[I] > result then result := Values[I]; end; class function Sys.Max(const Values: TArray<TBox<integer>>): TBox<integer>; var I: Integer; begin result.Init; for I := Low(Values) to High(Values) do if not Values[I].Empty then if result.Empty then result := Values[I] else result.Value := Max(result.Value, Values[I].Value); end; class function Sys.Min(const Values: TArray<TBox<integer>>): TBox<integer>; var I: Integer; begin result.Init; for I := Low(Values) to High(Values) do if not Values[I].Empty then if result.Empty then result := Values[I] else result.Value := Min(result.Value, Values[I].Value); end; class function Sys.Max(const Values: TArray<TBox<double>>): TBox<double>; var I: Integer; begin result.Init; for I := Low(Values) to High(Values) do if not Values[I].Empty then if result.Empty then result := Values[I] else result.Value := Max(result.Value, Values[I].Value); end; class function Sys.Min(const Values: TArray<TBox<double>>): TBox<double>; var I: Integer; begin result.Init; for I := Low(Values) to High(Values) do if not Values[I].Empty then if result.Empty then result := Values[I] else result.Value := Min(result.Value, Values[I].Value); end; class function Sys.Neg(const A: TBox<double>): TBox<double>; begin if A.Empty then result.Init else result.Value := -A.Value; end; class function Sys.Neg(const A: TBox<integer>): TBox<integer>; begin if A.Empty then result.Init else result.Value := -A.Value; end; class function Sys.Add(const Values: TArray<TBox<integer>>): TBox<integer>; var I: Integer; begin result.Init; for I := Low(Values) to High(Values) do if not Values[I].Empty then if result.Empty then result := Values[I] else result.Value := result.Value + Values[I].Value; end; class function Sys.Add(const Values: TArray<TBox<double>>): TBox<double>; var I: Integer; begin result.Init; for I := Low(Values) to High(Values) do if not Values[I].Empty then if result.Empty then result := Values[I] else result.Value := result.Value + Values[I].Value; end; { TDataSize } procedure TDataSize.Init(const AValue: int64); begin Self := Default(TDataSize); FSize := AValue; end; procedure TDataSize.InitMb(const AValue: double); begin Self := Default(TDataSize); SizeMb := AValue; end; class operator TDataSize.Add(Left, Right: TDataSize): TDataSize; begin result := Left.FSize+right.FSize; end; class operator TDataSize.Divide(Left, Right: TDataSize): TDataSize; begin result := Left.FSize div Right.FSize; end; class operator TDataSize.Equal(const Left, Right: TDataSize): Boolean; begin result := Left.FSize=Right.FSize; end; function TDataSize.GetAsString: string; begin {case FSize of 0 .. Kb-1 : result := Format('%d', [FSize]); Kb .. Mb-1 : result := Format('%.1f Kb', [FSize/Kb]); Mb .. Gb-1 : result := Format('%.1f Mb', [FSize/Mb]); Gb .. Tb-1 : result := Format('%.1f Gb', [FSize/Gb]); else result := Format('%.1f Tb', [FSize/Tb]); end;} if FSize<Mb then if FSize<Kb then result := Format('%d', [FSize]) else result := Format('%.2f Kb', [FSize/Kb]) else if FSize<Gb then result := Format('%.2f Mb', [FSize/Mb]) else if FSize<Tb then result := Format('%.2f Gb', [FSize/Gb]) else result := Format('%.2f Tb', [FSize/Tb]); end; function TDataSize.GetGb: double; begin result := FSIze / Gb; end; function TDataSize.GetKb: double; begin result := FSIze / Kb; end; function TDataSize.GetMb: double; begin result := FSIze / Mb; end; function TDataSize.GetTb: double; begin result := FSIze / Tb; end; class operator TDataSize.GreaterThan(const Left, Right: TDataSize): Boolean; begin result := Left.FSize>Right.FSize; end; class operator TDataSize.GreaterThanOrEqual(const Left, Right: TDataSize): Boolean; begin result := Left.FSize>=Right.FSize; end; class operator TDataSize.Implicit(const AValue: int64): TDataSize; begin result.FSize := AValue; end; class operator TDataSize.IntDivide(Left, Right: TDataSize): TDataSize; begin result := Left.FSize div Right.FSize; end; class operator TDataSize.LessThan(const Left, Right: TDataSize): Boolean; begin result := Left.FSize<Right.FSize; end; class operator TDataSize.LessThanOrEqual(const Left, Right: TDataSize): Boolean; begin result := Left.FSize<=Right.FSize; end; class operator TDataSize.Multiply(Left, Right: TDataSize): TDataSize; begin result := Left.FSize*Right.FSize; end; class operator TDataSize.Negative(Value: TDataSize): TDataSize; begin result := -Value.FSize; end; class operator TDataSize.NotEqual(const Left, Right: TDataSize): Boolean; begin result := Left.FSize<>Right.FSize; end; class operator TDataSize.Implicit(const AValue: TDataSize): int64; begin result := AValue.FSize; end; procedure TDataSize.SetGb(const Value: double); begin FSize := Trunc(Value*Gb); end; procedure TDataSize.SetKb(const Value: double); begin FSize := Trunc(Value*Kb); end; procedure TDataSize.SetMb(const Value: double); begin FSize := Trunc(Value*Mb); end; procedure TDataSize.SetTb(const Value: double); begin FSize := Trunc(Value*Tb); end; class function TDataSize.SizeToString(const AValue: int64): string; var S: TDataSize; begin S.Init(AValue); result := S.AsString; end; class operator TDataSize.Subtract(Left, Right: TDataSize): TDataSize; begin result := Left.FSize-Right.FSize; end; { TDebugUtils } class function TDebugUtils.DebuggerIsAttached: boolean; begin {$WARN SYMBOL_PLATFORM OFF} result := DebugHook <> 0; {$WARN SYMBOL_PLATFORM DEFAULT} end; { TInterfacedType<T> } constructor TInterfacedType<T>.Create(AData: T); begin inherited Create; FData := AData; end; function TInterfacedType<T>.Extract: T; begin result := FData; FData := Default(T); end; function TInterfacedType<T>.GetData: T; begin result := FData; end; function TInterfacedType<T>.GetRefCount: integer; begin result := RefCount; end; procedure TInterfacedType<T>.SetData(const AData: T); begin FData := AData; end; { TEnvelop<T> } constructor TEnvelop<T>.Create; begin end; constructor TEnvelop<T>.Create(AValue: T); begin Value := AValue; end; end.
(***********************************************************) (* xPLRFX *) (* part of Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (***********************************************************) unit uxPLRFX_0x12; interface Uses uxPLRFXConst, u_xPL_Message, u_xpl_common; procedure RFX2xPL(Buffer : BytesArray; xPLMessage : TxPLMessage); procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray); implementation (* Type $12 - Lighting3 - Koppla Buffer[0] = packetlength = $08; Buffer[1] = packettype Buffer[2] = subtype Buffer[3] = seqnbr Buffer[4] = system // Housecode Buffer[5] = channel8_1 (bit 8 7 6 5 4 3 2 1) // Unitcode Buffer[6] = channel10_9 (bit x x x x x x 10 9) Buffer[7] = cmnd Buffer[8] = battery:4/rssi:4 Test Strings : 0B11000600109B520B000080 xPL Schema x10.basic { device=<housecode[unitcode] command=on|off|dim|bright|preset [level=1-9] protocol=koppla } *) const // Packet Length PACKETLENGTH = $08; // Type LIGHTING3 = $12; // Subtype IKEAKOPPLA = $00; // Commands COMMAND_BRIGHT = 'bright'; COMMAND_ON = 'on'; COMMAND_DIM = 'dim'; COMMAND_OFF = 'off'; // TO CHECK ?? COMMAND_PROGRAM ?? var // Lookup table for commands RFXCommandArray : array[1..4] of TRFXCommandRec = ((RFXCode : $00; xPLCommand : COMMAND_BRIGHT), (RFXCode : $08; xPLCommand : COMMAND_DIM), (RFXCode : $10; xPLCommand : COMMAND_ON), (RFXCode : $1A; xPLCommand : COMMAND_OFF)); procedure RFX2xPL(Buffer : BytesArray; xPLMessage : TxPLMessage); begin end; procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray); begin end; end.
unit IWCompMemo; {PUBDIST} interface uses Classes, {$IFDEF Linux}QControls,{$ELSE}Controls,{$ENDIF} IWHTMLTag, IWControl; type TIWCustomMemo = class(TIWControl) protected FLines: TStrings; FRawText: Boolean; FReadOnly: Boolean; FRequired: Boolean; FEndsWithCRLF: Boolean; FWantReturns: Boolean; // procedure SetLines(const AValue: TStrings); procedure SetValue(const AValue: string); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RenderHTML: TIWHTMLTag; override; // make it visible to PaintHandler property Lines: TStrings read FLines write SetLines; published property Editable; property ExtraTagParams; //@@ Font is not supported when Editable = False. property Font; property ScriptEvents; property RawText: Boolean read FRawText write FRawText; //@@ Makes the memo control read only in the browser. //Note: This has no effect in Netscape 4. property ReadOnly: Boolean read FReadOnly write FReadOnly; //@@ If Required is True the user must enter data in this field before submiting the page. //SeeAlso: FriendlyName property Required: Boolean read FRequired write FRequired; property TabOrder; property WantReturns: Boolean read FWantReturns write FWantReturns; end; TIWMemo = class(TIWCustomMemo) public published property FriendlyName; property Lines; end; implementation uses {$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF} IWAppForm, IWCompText, IWResourceStrings, IWGlobal, SysUtils, SWSystem; constructor TIWCustomMemo.Create(AOwner: TComponent); begin inherited; FLines := TStringList.Create; FNeedsFormTag := True; FSupportsInput := True; FSupportedScriptEvents := 'OnBlur,OnChange,OnFocus,OnKeyDown,OnKeyPress,OnKeyUp,OnSelect'; Height := 121; Width := 121; FEndsWithCRLF := true; end; destructor TIWCustomMemo.Destroy; begin FreeAndNil(FLines); inherited; end; function TIWCustomMemo.RenderHTML: TIWHTMLTag; var LDest: TIWText; S: String; begin Result := nil; if Editable then begin Result := TIWHTMLTag.CreateTag('TEXTAREA'); try // Netscape can handle fonts here using method in TIWEdit, but IE cannot. Result.AddStringParam('NAME', HTMLName); Result.AddIntegerParam('ROWS', Height div 16); Result.AddIntegerParam('COLS', Width div 7); Result.Add(iif(ReadOnly, 'READONLY')); S := FLines.Text; if not FEndsWithCRLF and (Length(S) >= Length(sLineBreak)) then SetLength(S, Length(S) - Length(sLineBreak)); Result.Contents.AddText(S); UseFrame := False; except FreeAndNil(Result); raise; end; end else begin LDest := TIWText.Create(Self); try LDest.Name := Self.Name; LDest.Color := Self.Color; LDest.FriendlyName := Self.FriendlyName; LDest.ExtraTagParams := Self.ExtraTagParams; LDest.Font.Assign(Self.Font); LDest.ScriptEvents.Assign(Self.ScriptEvents); LDest.RawText := Self.RawText; LDest.Width := Self.Width; LDest.Height := Self.Height; LDest.Lines := Lines; LDest.WantReturns := Self.WantReturns; Result := LDest.RenderHTML; finally FreeAndNil(LDest); end; UseFrame := True; end; if Required and SupportsInput then begin TIWAppForm(Form).AddValidation('GSubmitter.' + HTMLName + '.value.length==0' , Format(RSValidationRequeredField, [FriendlyName])); end; end; procedure TIWCustomMemo.SetLines(const AValue: TStrings); begin FLines.Assign(AValue); FEndsWithCRLF := true; Invalidate; end; procedure TIWCustomMemo.SetValue(const AValue: string); begin FLines.Text := AValue; FEndsWithCRLF := FLines.Text = AValue; // Will use Text internally to set the real value Text := AValue; Invalidate; end; end.
{******************************************} { } { vtk GridReport library } { } { Copyright (c) 2003 by vtkTools } { } {******************************************} {Contains the TvgrFontComboBox component that is used for represents a combo box that lets users select a font. Use this component to provide the user with a drop-down combo box from which to select a font name. See also: vgr_ControlBar,vgr_ColorButton,vgr_Label} unit vgr_FontComboBox; {$I vtk.inc} interface uses SysUtils, Messages, Windows, Classes, StdCtrls, graphics, Controls; type { TvgrFontComboBoxOptions specify options for a TvgrFontComboBox component. Syntax: TvgrFontComboBoxOptions = (prfcboFixedOnly); Items: prfcboFixedOnly - show in drop down list only fixed fonts (all characters in the font have the same width). } TvgrFontComboBoxOptions = (prfcboFixedOnly); { TvgrFontComboBoxOptionsSet specify options for a TvgrFontComboBox component. Syntax: TvgrFontComboBoxOptionsSet = set of TvgrFontComboBoxOptions; } TvgrFontComboBoxOptionsSet = set of TvgrFontComboBoxOptions; ///////////////////////////////////////////////// // // TvgrFontComboBox // ///////////////////////////////////////////////// { TvgrFontComboBox represents a combo box that lets users select a font. Use TvgrFontComboBox to provide the user with a drop-down combo box from which to select a font name. Use the Options property to specify which fonts the font box should list. Use the ListFontSize property to specify size of font in font box. Use the SelectedFontName property to access the font that the user selects. } TvgrFontComboBox = class(TCustomComboBox) private FTempFont: TFont; FListFontSize: integer; FItemHeight: integer; FMaxWidth: integer; FDroppingDown: boolean; FFocusChanged: boolean; FIsFocused: boolean; FOptions: TvgrFontComboBoxOptionsSet; procedure SetListFontSize(Value : integer); function GetOptions: TvgrFontComboBoxOptionsSet; procedure SetOptions(Value : TvgrFontComboBoxOptionsSet); procedure UpdateItems; function GetSelectedFontName: string; function GetIsFontSelected: Boolean; protected procedure AdjustDropDown; {$IFDEF VTK_D6_OR_D7} override; {$ENDIF} procedure WMDrawItem(var Msg: TWMDrawItem); message WM_DRAWITEM; procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; procedure CNCommand(var Msg: TWMCommand); message CN_COMMAND; procedure CBGetItemHeight(var Msg: TMessage); message CB_GETITEMHEIGHT; procedure CreateWnd; override; procedure WndProc(var Msg: TMessage); override; public {Creates a instance of class.} constructor Create(AOwner : TComponent); override; { Use the SelectedFontName property to access the font that the user selects. } property SelectedFontName: string read GetSelectedFontName; { IsFontSelected returns true if user select font in the list. (ItemIndex <> -1) } property IsFontSelected: Boolean read GetIsFontSelected; published { Use the ListFontSize property to specify size of font in font box. } property ListFontSize: integer read FListFontSize write SetListFontSize; { Use the Options property to specify which fonts the font box should list. } property Options: TvgrFontComboBoxOptionsSet read GetOptions write SetOptions default []; property Anchors; property BiDiMode; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property DropDownCount; property Enabled; property Font; property ImeMode; property ImeName; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Sorted; property TabOrder; property TabStop; property Text; property Visible; property OnChange; property OnClick; {$IFDEF VTK_D5} property OnContextPopup; {$ENDIF} property OnDblClick; property OnDragDrop; property OnDragOver; property OnDropDown; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnStartDock; property OnStartDrag; end; implementation uses vgr_Functions, vgr_GUIFunctions; {$R vgrFontComboBox.res} var TrueTypeBitmap : TBitmap; ///////////////////////////////////////////////// // // TvgrFontComboBox // ///////////////////////////////////////////////// constructor TvgrFontComboBox.Create; begin inherited; {$IFDEF VGR_DEMO} ShowDemoWarning; {$ENDIF} Style := csOwnerDrawFixed; FListFontSize := 12; FItemHeight := ItemHeight; end; function TvgrFontComboBox.GetSelectedFontName: string; begin if (ItemIndex >= 0) and (ItemIndex < Items.Count) then Result := Items[ItemIndex] else Result := ''; end; function TvgrFontComboBox.GetIsFontSelected: Boolean; begin Result := (ItemIndex >= 0) and (ItemIndex < Items.Count); end; function EnumFontsProc(var LogFont : TLogFont; var TextMetric : TTextMetric; FontType : Integer; Data : Pointer): Integer; stdcall; var AHeight, AWidth: Integer; begin with TvgrFontComboBox(Data) do begin if not (prfcboFixedOnly in Options) or ((LogFont.lfPitchAndFamily and FIXED_PITCH)<>0) then begin Items.AddObject(StrPas(LogFont.lfFaceName), TObject(FontType)); FTempFont.Name := LogFont.lfFaceName; AHeight := GetFontHeight(FTempFont); AWidth := GetStringWidth(LogFont.lfFaceName, FTempFont); if AHeight > FItemHeight then FItemHeight := AHeight; if AWidth > FMaxWidth then FMaxWidth := AWidth; end; end; Result := 1; end; procedure TvgrFontComboBox.UpdateItems; var ADC: HDC; begin FTempFont := TFont.Create; FTempFont.Size := ListFontSize; Items.BeginUpdate; Items.Clear; FItemHeight := 0; FMaxWidth := 0; ADC := GetDC(0); EnumFonts(ADC, nil, @EnumFontsProc, pointer(Self)); ReleaseDC(0, ADC); FItemHeight := FItemHeight + 2; FMaxWidth := FMaxWidth + 4; SendMessage(Handle, CB_SETITEMHEIGHT, 0, FItemHeight); // update item height SendMessage(Handle, CB_SETDROPPEDWIDTH, FMaxWidth, 0); Items.EndUpdate; FreeAndNil(FTempFont); end; procedure TvgrFontComboBox.CreateWnd; begin inherited; UpdateItems; end; procedure TvgrFontComboBox.WndProc; begin if Msg.Msg=WM_SIZE then begin if FDroppingDown then begin DefaultHandler(Msg); Exit; end; end; inherited; end; procedure TvgrFontComboBox.SetListFontSize; begin if Value<>FListFontSize then begin FListFontSize := Value; RecreateWnd; end; end; function TvgrFontComboBox.GetOptions: TvgrFontComboBoxOptionsSet; begin Result := FOptions; end; procedure TvgrFontComboBox.SetOptions(Value : TvgrFontComboBoxOptionsSet); begin if Value<>FOptions then begin FOptions := Value; if not (csLoading in ComponentState) then UpdateItems; end; end; procedure TvgrFontComboBox.AdjustDropDown; var ItemCount: Integer; begin ItemCount := Items.Count; if ItemCount > DropDownCount then ItemCount := DropDownCount; if ItemCount < 1 then ItemCount := 1; FDroppingDown := True; try SetWindowPos(Handle, 0, 0, 0, Width, FItemHeight * ItemCount + Height + 2, SWP_NOMOVE + SWP_NOZORDER + SWP_NOACTIVATE + SWP_NOREDRAW + SWP_HIDEWINDOW); finally FDroppingDown := False; end; SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE + SWP_NOZORDER + SWP_NOACTIVATE + SWP_NOREDRAW + SWP_SHOWWINDOW); end; procedure TvgrFontComboBox.CBGetItemHeight(var Msg: TMessage); begin inherited; end; procedure TvgrFontComboBox.CNCommand(var Msg: TWMCommand); begin case Msg.NotifyCode of CBN_DROPDOWN: begin FFocusChanged := False; DropDown; AdjustDropDown; if FFocusChanged then begin PostMessage(Handle, WM_CANCELMODE, 0, 0); if not FIsFocused then PostMessage(Handle, CB_SHOWDROPDOWN, 0, 0); end; end; CBN_SETFOCUS: begin FIsFocused := True; FFocusChanged := True; SetIme; end; CBN_KILLFOCUS: begin FIsFocused := False; FFocusChanged := True; ResetIme; end; else inherited; end; end; procedure TvgrFontComboBox.WMPaint(var Msg: TWMPaint); begin if Enabled then Font.Color := clWindowText else Font.Color := clGrayText; inherited; end; procedure TvgrFontComboBox.WMDrawItem; var s: string; sz: TSize; Canvas: TCanvas; begin Msg.Result := 1; Canvas := TCanvas.Create; try with Msg.DrawItemStruct^ do begin Canvas.Handle := hDC; if (itemState and ODS_COMBOBOXEDIT) <> 0 then begin if ItemIndex = -1 then s := '' else s := Items[ItemIndex]; Canvas.Font.Size := Font.Size; Canvas.Font.Name := Font.Name; if (itemState and ODS_DISABLED) <> 0 then Canvas.Font.Color := clGrayText else Canvas.Font.Color := clWindowText; end else begin s := Items[ItemID]; Canvas.Font.Size := ListFontSize; Canvas.Font.Name := s; if (itemState and ODS_SELECTED)<>0 then begin Canvas.Font.Color := clHighlightText; Canvas.Brush.Color := clHighlight; end else begin Canvas.Font.Color := clWindowText; Canvas.Brush.Color := clWindow; end; end; Canvas.Brush.Style := bsSolid; Canvas.FillRect(rcItem); Canvas.Brush.Style := bsClear; sz := Canvas.TextExtent(s); Canvas.TextOut(rcItem.Left + TrueTypeBitmap.Width + 2 + 2, rcItem.Top + (rcItem.Bottom - rcItem.Top - sz.cy) div 2, s); if (ItemID<>$FFFFFFFF) and ((Integer(Items.Objects[ItemID]) and TRUETYPE_FONTTYPE) <> 0) then Canvas.Draw(rcItem.Left, rcItem.Top + (rcItem.Bottom - rcItem.Top - TrueTypeBitmap.Height) div 2, TrueTypeBitmap); end; finally Canvas.Free; end; end; initialization TrueTypeBitmap := TBitmap.Create; try TrueTypeBitmap.LoadFromResourceName(hInstance,'VGR_BMP_TRUETYPE'); except end; TrueTypeBitmap.Transparent := True; finalization TrueTypeBitmap.Free; end.
unit fODLab; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ORCtrls, ORfn, fODBase, ExtCtrls, ComCtrls, uConst, ORDtTm, Buttons, Menus, VA508AccessibilityManager, VA508AccessibilityRouter; type TfrmODLab = class(TfrmODBase) lblAvailTests: TLabel; cboAvailTest: TORComboBox; lblCollTime: TLabel; cboFrequency: TORComboBox; lblTestName: TLabel; lblCollSamp: TLabel; cboCollSamp: TORComboBox; lblSpecimen: TLabel; cboSpecimen: TORComboBox; lblUrgency: TLabel; cboUrgency: TORComboBox; lblAddlComment: TLabel; txtAddlComment: TCaptionEdit; txtDays: TCaptionEdit; bvlTestName: TBevel; lblFrequency: TLabel; pnlHide: TORAutoPanel; pnlOrderComment: TORAutoPanel; lblOrderComment: TOROffsetLabel; pnlAntiCoagulation: TORAutoPanel; lblAntiCoagulant: TOROffsetLabel; txtAntiCoagulant: TCaptionEdit; pnlUrineVolume: TORAutoPanel; lblUrineVolume: TOROffsetLabel; txtUrineVolume: TCaptionEdit; pnlPeakTrough: TORAutoPanel; lblPeakTrough: TOROffsetLabel; grpPeakTrough: TRadioGroup; lblReqComment: TOROffsetLabel; pnlDoseDraw: TORAutoPanel; lblDose: TOROffsetLabel; lblDraw: TOROffsetLabel; txtDoseTime: TCaptionEdit; txtDrawTime: TCaptionEdit; txtOrderComment: TCaptionEdit; FLabCommonCombo: TORListBox; lblHowManyDays: TLabel; cboCollTime: TORComboBox; lblCollType: TLabel; pnlCollTimeButton: TKeyClickPanel; cboCollType: TORComboBox; calCollTime: TORDateBox; dlgLabCollTime: TORDateTimeDlg; txtImmedColl: TCaptionEdit; cmdImmedColl: TSpeedButton; MessagePopup: TPopupMenu; ViewinReportWindow1: TMenuItem; Frequencylbl508: TVA508StaticText; HowManyDayslbl508: TVA508StaticText; specimenlbl508: TVA508StaticText; CollSamplbl508: TVA508StaticText; procedure FormCreate(Sender: TObject); procedure ControlChange(Sender: TObject); procedure cboAvailTestNeedData(Sender: TObject; const StartFrom: string; Direction, InsertAt: Integer); procedure cboAvailTestSelect(Sender: TObject); procedure cboCollSampChange(Sender: TObject); procedure cboUrgencyChange(Sender: TObject); procedure cboSpecimenChange(Sender: TObject); procedure txtAddlCommentExit(Sender: TObject); procedure cboCollTimeChange(Sender: TObject); procedure cboFrequencyChange(Sender: TObject); procedure cboCollTypeChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure txtOrderCommentExit(Sender: TObject); procedure txtAntiCoagulantExit(Sender: TObject); procedure txtUrineVolumeExit(Sender: TObject); procedure grpPeakTroughClick(Sender: TObject); procedure txtDoseTimeExit(Sender: TObject); procedure txtDrawTimeExit(Sender: TObject); procedure DisableCommentPanels; procedure cboAvailTestExit(Sender: TObject); procedure cboCollSampKeyPause(Sender: TObject); procedure cboCollSampMouseClick(Sender: TObject); procedure cboCollTimeExit(Sender: TObject); procedure cboSpecimenMouseClick(Sender: TObject); procedure cboSpecimenKeyPause(Sender: TObject); procedure cmdImmedCollClick(Sender: TObject); procedure pnlCollTimeButtonEnter(Sender: TObject); procedure pnlCollTimeButtonExit(Sender: TObject); procedure ViewinReportWindow1Click(Sender: TObject); protected FCmtTypes: TStringList ; procedure InitDialog; override; procedure Validate(var AnErrMsg: string); override; function ValidCollTime(UserEntry: string): string; procedure DoseDrawComment; procedure GetAllCollSamples(AComboBox: TORComboBox); procedure GetAllSpecimens(AComboBox: TORComboBox); procedure SetupCollTimes(CollType: string); procedure LoadCollType(AComboBox:TORComboBox); private FLastCollType: string; FLastCollTime: string; FLastLabCollTime: string; FLastLabID: string; FLastItemID: string; FEvtDelayLoc: integer; FEvtDivision: integer; procedure ReadServerVariables; procedure DisplayChangedOrders(ACollType: string); procedure setup508Label(text: string; lbl: TVA508StaticText; ctrl: TControl; lbl2: string); public procedure SetupDialog(OrderAction: Integer; const ID: string); override; procedure LoadRequiredComment(CmtType: integer); procedure DetermineCollectionDefaults(Responses: TResponses); property EvtDelayLoc: integer read FEvtDelayLoc write FEvtDelayLoc; property EvtDivision: integer read FEvtDivision write FEvtDivision; end; type TCollSamp = class(TObject) public CollSampID: Integer; { IEN of CollSamp } CollSampName: string; { Name of CollSamp } SpecimenID: Integer; { IEN of default specimen } SpecimenName: string; { Name of the specimen } TubeColor: string; { TubeColor (text) } MinInterval: Integer; { Minimum days between orders } MaxPerDay: Integer; { Maximum orders per day } LabCanCollect: Boolean; { True if lab can collect } SampReqComment: string; { Name of required comment } WardComment: TStringList; { CollSamp specific comment } end; TLabTest = class(TObject) public TestID: Integer; { IEN of Lab Test } TestName: string; { Name of Lab Test } LabSubscript: string ; { which section of Lab? } CollSamp: Integer; { index into CollSampList } Specimen: Integer; { IEN of specimen } Urgency: Integer; { IEN of urgency } Comment: TStringList; { text of comment } TestReqComment: string; { Name of required comment } CurReqComment: string; { name of required comment } CurWardComment: TStringList; { WP of Ward Comment } UniqueCollSamp: Boolean; { true if not prompt CollSamp } CollSampList: TList; { collection sample objects } CollSampCount: integer; { count of original contents of CollSampList} SpecimenList: TStringList; { Strings: IEN^Specimen Name } SpecListCount: integer; { count of original contents of SpecimenList} UrgencyList: TStringList; { Strings: IEN^Urgency Name } ForceUrgency: Boolean; { true if not prompt Urgency } QuickOrderResponses: TResponses; { if created as a result of a quick order selection} { functions & procedures } constructor Create(const LabTestIEN: string; Responses: TResponses); destructor Destroy; override ; function IndexOfCollSamp(CollSampIEN: Integer): Integer; procedure FillCollSampList(LoadData: TStringList; DfltCollSamp: Integer); procedure LoadAllSamples; procedure SetCollSampDflts; procedure ChangeCollSamp(CollSampIEN: Integer); procedure ChangeSpecimen(const SpecimenIEN: string); procedure ChangeUrgency(const UrgencyIEN: string); procedure ChangeComment(const CommentText: string); function LabCanCollect: Boolean; procedure LoadCollSamp(AComboBox: TORComboBox); procedure LoadSpecimen(AComboBox: TORComboBox); procedure LoadUrgency(CollType: string; AComboBox:TORComboBox); function NameOfCollSamp: string; function NameOfSpecimen: string; function NameOfUrgency: string; function ObtainCollSamp: Boolean; function ObtainSpecimen: Boolean; function ObtainUrgency: Boolean; function ObtainComment: Boolean; end; const CmtType: array[0..6] of string = ('ANTICOAGULATION','DOSE/DRAW TIMES','ORDER COMMENT', 'ORDER COMMENT MODIFIED','TDM (PEAK-TROUGH)', 'TRANSFUSION','URINE VOLUME'); implementation {$R *.DFM} uses rODBase, rODLab, uCore, rCore, fODLabOthCollSamp, fODLabOthSpec, fODLabImmedColl, fLabCollTimes, rOrders, uODBase, fRptBox, fFrame, VAUtils; var uDfltUrgency: Integer; uDfltCollType: string; ALabTest: TLabTest; UserHasLRLABKey: boolean; LRFZX : string; //the default collection type (LC,WC,SP,I) LRFSAMP : string; //the default sample (ptr) LRFSPEC : string; //the default specimen (ptr) LRFDATE : string; //the default collection time (NOW,NEXT,AM,PM,T...) LRFURG : string; //the default urgency (number) TRY '2' LRFSCH : string; //the default schedule? (ONE TIME, QD, ...) const TX_NO_TEST = 'A Lab Test must be specified.' ; TX_NO_IMMED = 'Immediate collect is not available for this test/sample'; TX_NO_IMMED_CAP = 'Invalid Collection Type'; { base form procedures shared by all dialogs ------------------------------------------------ } procedure TfrmODLab.FormCreate(Sender: TObject); var i, n, HMD508: integer; AList: TStringList; begin frmFrame.pnlVisit.Enabled := false; AutoSizeDisabled := True; inherited; AList := TStringList.Create; try LRFZX := ''; LRFSAMP := ''; LRFSPEC := ''; LRFDATE := ''; LRFURG := ''; LRFSCH := ''; FLastColltime := ''; FLastLabCollTime := ''; FLastItemID := ''; uDfltCollType := ''; FillerID := 'LR'; FEvtDelayLoc := 0; FEvtDivision := 0; UserHasLRLABKey := User.HasKey('LRLAB'); AllowQuickOrder := True; StatusText('Loading Dialog Definition'); pnlHide.BringToFront; lblReqComment.Visible := False ; FCmtTypes := TStringList.Create; for i := 0 to 6 do FCmtTypes.Add(CmtType[i]) ; Responses.Dialog := 'LR OTHER LAB TESTS'; // loads formatting info StatusText('Loading Default Values'); if Self.EvtID > 0 then begin EvtDelayLoc := StrToIntDef(GetEventLoc1(IntToStr(Self.EvtID)),0); EvtDivision := StrToIntDef(GetEventDiv1(IntToStr(Self.EvtID)),0); if EvtDelayLoc>0 then ODForLab(AList, EvtDelayLoc, EvtDivision) else ODForLab(AList, Encounter.Location, EvtDivision); end else ODForLab(aList, Encounter.Location); CtrlInits.LoadDefaults(AList); InitDialog; with CtrlInits do begin SetControl(cboCollType, 'Collection Types'); uDfltCollType := ExtractDefault(AList, 'Collection Types'); if uDfltCollType <> '' then cboCollType.SelectByID(uDfltCollType) else if OrderForInpatient then cboCollType.SelectByID('LC') else cboCollType.SelectByID('SP'); SetupCollTimes(cboCollType.ItemID); StatusText('Initializing List of Tests'); SetControl(cboAvailTest, 'ShortList'); if cboAvailTest.Items.Count > 0 then cboAvailTest.InsertSeparator; cboAvailTest.InitLongList(''); //TDP - CQ#19396 HMD508 added to guarantee 508 label did not change width HMD508 := HowManyDayslbl508.Width; SetControl(cboFrequency, 'Schedules'); HowManydayslbl508.Width := HMD508; with cboFrequency do begin if ItemIndex < 0 then ItemIndex := Items.IndexOf('ONE TIME'); if ItemIndex < 0 then ItemIndex := Items.IndexOf('ONCE'); end; lblHowManyDays.Enabled := False; { have this call change event in case } txtDays.Enabled := False; { the default is not 'one time'? } //TDP - CQ#19396 Following line does not appear to be needed //setup508Label(HowManyText, HowManyDayslbl508, txtDays, lblHowManyDays.Caption); end; if EvTDelayLoc>0 then n := MaxDays(EvtDelayLoc, 0) else n := MaxDays(Encounter.Location, 0); if n < 0 then with cboFrequency do begin ItemIndex := Items.IndexOf('ONE TIME'); if ItemIndex = -1 then ItemIndex := Items.IndexOf('ONCE'); Enabled := False; Font.Color := clGrayText; lblFrequency.Enabled := False; setup508Label(Text, Frequencylbl508, cboFrequency, lblFrequency.Caption); end; PreserveControl(cboAvailTest); PreserveControl(cboCollType); PreserveControl(cboCollTime); PreserveControl(calCollTime); PreserveControl(cboFrequency); PreserveControl(txtDays); StatusText(''); finally AList.Free; end; end; {TDP - CQ#19396 Added to address 508 related changes. I modified slightly to change lbl.Caption and retain lbl.Width} procedure TfrmODLab.setup508Label(text: string; lbl: TVA508StaticText; ctrl: TControl; lbl2: string); var Width: integer; begin if ScreenReaderSystemActive and not ctrl.Enabled then begin lbl.Enabled := True; lbl.Visible := True; Width := lbl.Width; lbl.Caption := lbl2 +'. Read Only. Value is ' + Text; lbl.Width := Width; end else lbl.Visible := false; end; procedure TfrmODLab.InitDialog; begin inherited; Changing := True; if ALabTest <> nil then begin ALabTest.Destroy; ALabTest := nil; end; with CtrlInits do begin SetControl(cboUrgency, 'Default Urgency') ; uDfltUrgency := StrToInt(Piece(cboUrgency.Items[0],U,1)); end; lblTestName.Caption := ''; DisableCommentPanels; cboAvailTest.SelectByID(FLastItemID); ActiveControl := cboAvailTest; cboAvailTest.ItemIndex := -1; StatusText(''); Changing := False ; end; procedure TfrmODLab.SetupDialog(OrderAction: Integer; const ID: string); var tmpResp: TResponse; i: integer; begin inherited; ReadServerVariables; if LRFZX <> '' then begin cboCollType.SelectByID(LRFZX); if cboCollType.ItemIndex > -1 then SetupCollTimes(LRFZX); end; if (LRFSCH <> '') and (cboFrequency.Enabled) then begin cboFrequency.ItemIndex := cboFrequency.Items.IndexOf(LRFSCH); cboFrequencyChange(Self); end; if OrderAction in [ORDER_COPY, ORDER_EDIT, ORDER_QUICK] then with Responses, ALabTest do begin SetControl(cboAvailTest, 'ORDERABLE', 1); cboAvailTestSelect(Self); if ALabTest = nil then Exit; // Causes access violation in FillCollSampleList Changing := True; SetControl(cboFrequency, 'SCHEDULE', 1); SetControl(txtDays, 'DAYS', 1); tmpResp := FindResponseByName('SAMPLE' ,1); if (tmpResp <> nil) and (tmpResp.IValue <> '') then with cboCollSamp do begin SelectByID(tmpResp.IValue); if ItemIndex < 0 then begin LoadAllSamples; Items.Insert(0, tmpResp.IValue + U + tmpResp.EValue); ItemIndex := 0 ; end; end; cboCollSampChange(Self); DetermineCollectionDefaults(Responses); tmpResp := FindResponseByName('SPECIMEN' ,1); if (tmpResp <> nil) and (tmpResp.IValue <> '') then with cboSpecimen do begin SelectByID(tmpResp.IValue); if ItemIndex < 0 then begin if ALabTest <> nil then ALabTest.SpecimenList.Add(tmpResp.IValue + U + tmpResp.EValue); Items.Insert(0, tmpResp.IValue + U + tmpResp.EValue); ItemIndex := 0 ; end; end else if (LRFSPEC <> '') then cboSpecimen.SelectByID(LRFSPEC); if ALabTest <> nil then Specimen := cboSpecimen.ItemIEN; if ALabTest <> nil then AlabTest.LoadUrgency(cboCollType.ItemID, cboUrgency); SetControl(cboUrgency, 'URGENCY', 1); if cboUrgency.ItemIEN = 0 then begin if StrToIntDef(LRFURG, 0) > 0 then cboUrgency.SelectByID(LRFURG) else if (ALabTest <> nil) and (Urgency = 0) and (cboUrgency.Items.Count = 1) then cboUrgency.ItemIndex := 0; end; if ALabTest <> nil then Urgency := cboUrgency.ItemIEN; i := 1 ; tmpResp := Responses.FindResponseByName('COMMENT',i); while tmpResp <> nil do begin Comment.Add(tmpResp.EValue); Inc(i); tmpResp := Responses.FindResponseByName('COMMENT',i); end ; with cboFrequency do if not Enabled then begin ItemIndex := Items.IndexOf('ONE TIME'); if ItemIndex = -1 then ItemIndex := Items.IndexOf('ONCE'); end; cboFrequencyChange(Self); Changing := False; ControlChange(Self); end; end; { dialog specific event procedures follow here ---------------------------------------------- } constructor TLabTest.Create(const LabTestIEN: string; Responses: TResponses); var LoadData, OneSamp: TStringList; DfltCollSamp: Integer; x: string; tmpResp: TResponse; begin LoadData := TStringList.Create; try LoadLabTestData(LoadData, LabTestIEN) ; with LoadData do begin QuickOrderResponses := Responses; TestID := StrToInt(LabTestIEN); TestName := Piece(ExtractDefault(LoadData, 'Test Name'),U,1); LabSubscript := Piece(ExtractDefault(LoadData, 'Item ID'),U,2); TestReqComment := ExtractDefault(LoadData, 'ReqCom'); if Length(ExtractDefault(LoadData, 'Unique CollSamp')) > 0 then UniqueCollSamp := True; x := ExtractDefault(LoadData, 'Unique CollSamp'); if Length(x) = 0 then x := ExtractDefault(LoadData, 'Lab CollSamp'); if Length(x) = 0 then x := ExtractDefault(LoadData, 'Default CollSamp'); if Length(x) = 0 then x := '-1'; DfltCollSamp := StrToInt(x); SpecimenList := TStringList.Create; ExtractItems(SpecimenList, LoadData, 'Specimens'); if LRFSPEC <> '' then SpecimenList.Add(GetOneSpecimen(StrToInt(LRFSPEC))); UrgencyList := TStringList.Create; if Length(ExtractDefault(LoadData, 'Default Urgency')) > 0 then { forced urgency } begin ForceUrgency := True; UrgencyList.Add(ExtractDefault(LoadData, 'Default Urgency')); Urgency := StrToInt(Piece(ExtractDefault(LoadData, 'Default Urgency'), '^', 1)); uDfltUrgency := Urgency; end else begin { list of urgencies } ExtractItems(UrgencyList, LoadData, 'Urgencies'); if StrToIntDef(LRFURG, 0) > 0 then Urgency := StrToInt(LRFURG) else Urgency := uDfltUrgency; end; Comment := TStringList.Create ; CurWardComment := TStringList.Create; ExtractText(CurWardComment, LoadData, 'GenWardInstructions'); CollSamp := 0; CollSampList := TList.Create; FillCollSampList(LoadData, DfltCollSamp); with QuickOrderResponses do tmpResp := FindResponseByName('SAMPLE' ,1); if (LRFSAMP <> '') and (IndexOfCollSamp(StrToInt(LRFSAMP)) < 0) and (not UniqueCollSamp) and (tmpResp = nil) then begin OneSamp := TStringList.Create; try GetOneCollSamp(OneSamp, StrToInt(LRFSAMP)); FillCollSampList(OneSamp, CollSampList.Count); finally OneSamp.Free; end; end; if (not UniqueCollSamp) and (CollSampList.Count = 0) then LoadAllSamples; CollSampCount := CollSampList.Count; end; finally LoadData.Free; end; SetCollSampDflts; end; destructor TLabTest.Destroy; var i: Integer; begin if CollSampList <> nil then with CollSampList do for i := 0 to Count - 1 do with TCollSamp(Items[i]) do begin WardComment.Free; Free; end; CollSampList.Free; SpecimenList.Free; UrgencyList.Free; CurWardComment.Free; Comment.Free; inherited Destroy; end; function TLabTest.IndexOfCollSamp(CollSampIEN: Integer): Integer; var i: Integer; begin Result := -1; with CollSampList do for i := 0 to Count - 1 do with TCollSamp(Items[i]) do if CollSampIEN = CollSampID then begin Result := i; break; end; end; procedure TLabTest.LoadAllSamples; var LoadList, SpecList: TStringList; i: Integer; begin LoadList := TStringList.Create; SpecList := TStringList.Create; try LoadSamples(LoadList) ; FillCollSampList(LoadList, 0); ExtractItems(SpecList, LoadList, 'Specimens'); with SpecList do for i := 0 to Count - 1 do if SpecimenList.IndexOf(Strings[i]) = -1 then SpecimenList.Add(Strings[i]); finally LoadList.Free; SpecList.Free; end; end; procedure TLabTest.FillCollSampList(LoadData: TStringList; DfltCollSamp: Integer); {1 2 3 4 5 6 7 8 9 10 } {n^IEN^CollSampName^SpecIEN^TubeTop^MinInterval^MaxPerDay^LabCollect^SampReqCommentIEN;name^SpecName} var i, LastListItem, AnIndex: Integer; ACollSamp: TCollSamp; LabCollSamp: Integer; begin i := -1; if CollSampList = nil then CollSampList := TList.Create; LastListItem := CollSampList.Count ; LabCollSamp := StrToIntDef(ExtractDefault(LoadData, 'Lab CollSamp'), 0); repeat Inc(i) until (i = LoadData.Count) or (LoadData[i] = '~CollSamp'); Inc(i); if i < LoadData.Count then repeat if LoadData[i][1] = 'i' then begin ACollSamp := TCollSamp.Create; with ACollSamp do begin AnIndex := StrToIntDef(Copy(Piece(LoadData[i], '^', 1), 2, 999), -1); CollSampID := StrToInt(Piece(LoadData[i], '^', 2)); CollSampName := Piece(LoadData[i], '^', 3); SpecimenID := StrToIntDef(Piece(LoadData[i], '^', 4), 0); SpecimenName := Piece(LoadData[i], '^', 10); TubeColor := Piece(LoadData[i], '^', 5); MinInterval := StrToIntDef(Piece(LoadData[i], '^', 6), 0); MaxPerDay := StrToIntDef(Piece(LoadData[i], '^', 7), 0); LabCanCollect := AnIndex = LabCollSamp; SampReqComment := Piece(LoadData[i], '^', 9); WardComment := TStringList.Create; if CollSampID = StrToIntDef(LRFSAMP, 0) then CollSamp := CollSampID else if AnIndex = DfltCollSamp then CollSamp := CollSampID; end; {with} LastListItem := CollSampList.Add(ACollSamp); end; {if} if (LoadData[i][1] = 't') then TCollSamp(CollSampList.Items[LastListItem]).WardComment.Add(Copy(LoadData[i], 2, 255)); Inc(i); until (i = LoadData.Count) or (LoadData[i][1] = '~'); end; procedure TLabTest.SetCollSampDflts; var tmpResp: TResponse; begin Specimen := 0; Comment.Clear; CurReqComment := TestReqComment; if CollSamp = 0 then Exit; with QuickOrderResponses do tmpResp := FindResponseByName('SPECIMEN' ,1); if (LRFSPEC <> '') and (tmpResp = nil) then ChangeSpecimen(LRFSPEC) else with TCollSamp(CollSampList.Items[IndexOfCollSamp(CollSamp)]) do begin Specimen := SpecimenID; if SampReqcomment <> '' then CurReqComment := SampReqComment; end; end; procedure TLabTest.ChangeCollSamp(CollSampIEN: Integer); begin CollSamp := CollSampIEN; SetCollSampDflts; end; procedure TLabTest.ChangeSpecimen(const SpecimenIEN: string); begin Specimen := StrToIntDef(SpecimenIEN,0); end; procedure TLabTest.ChangeUrgency(const UrgencyIEN: string); begin Urgency := StrToIntDef(UrgencyIEN,0); end; procedure TLabTest.ChangeComment(const CommentText: string); begin Comment.Add(CommentText); end; function TLabTest.LabCanCollect: Boolean; var i: Integer; begin Result := False; i := IndexOfCollSamp(CollSamp); if i > -1 then with TCollSamp(CollSampList.Items[i]) do Result := LabCanCollect; end; procedure TLabTest.LoadCollSamp(AComboBox: TORComboBox); { loads the collection sample combo box, expects CollSamp to already be set to default } var i: Integer; x: string; begin AComboBox.Clear; with CollSampList do for i := 0 to Count - 1 do with TCollSamp(Items[i]) do begin x := IntToStr(CollSampID) + '^' + CollSampName; if Length(TubeColor) <> 0 then x := x + ' (' + TubeColor + ')'; AComboBox.Items.Add(x); if CollSamp = CollSampID then AComboBox.ItemIndex := i; end; if ((ALabTest.LabSubscript = 'CH') and (not UserHasLRLABKey)) then begin // do not add 'Other' (coded this way for clarity) end else with AComboBox do begin Items.Add('0^Other...'); if ItemIndex < 0 then ItemIndex := Items.IndexOf('Other...'); end; end; procedure TLabTest.LoadSpecimen(AComboBox: TORComboBox); { loads specimen combo box, if SpecimenList is empty, use 'E' xref on 61 ?? } var i: Integer; tmpResp: TResponse; begin AComboBox.Clear; if ObtainSpecimen then begin if SpecimenList.Count = 0 then LoadSpecimens(SpecimenList) ; FastAssign(SpecimenList, AComboBox.Items); AComboBox.Items.Add('0^Other...'); with QuickOrderResponses do tmpResp := FindResponseByName('SPECIMEN' ,1); if (LRFSPEC <> '') and (tmpResp = nil) then AComboBox.SelectByID(LRFSPEC) else if Specimen > 0 then AComboBox.SelectByIEN(Specimen) else AComboBox.ItemIndex := AComboBox.Items.IndexOf('Other...'); end else begin i := IndexOfCollSamp(CollSamp); if i < CollSampList.Count then with TCollSamp(CollSampList.Items[i]) do begin AComboBox.Items.Add(IntToStr(SpecimenID) + '^' + SpecimenName); AComboBox.ItemIndex := 0; end; with QuickOrderResponses do tmpResp := FindResponseByName('SPECIMEN' ,1); if (LRFSPEC <> '') and (tmpResp = nil) then begin AComboBox.Items.Add(GetOneSpecimen(StrToInt(LRFSPEC))); AComboBox.SelectByID(LRFSPEC); end; end; ChangeSpecimen(AComboBox.ItemID); end; procedure TfrmODLab.LoadCollType(AComboBox:TORComboBox); var i: integer; begin with CtrlInits, cboCollType do begin SetControl(cboCollType, 'Collection Types'); if not ALabTest.LabCanCollect then begin i := SelectByID('LC'); if i > -1 then Items.Delete(i); i := SelectByID('I'); if i > -1 then Items.Delete(i); end ; if LRFZX <> '' then begin if (LRFZX = 'LC') or (LRFZX = 'I') then begin if ALabTest.LabCanCollect then cboCollType.SelectByID(LRFZX) else cboCollType.SelectByID('WC'); end else cboCollType.SelectByID(LRFZX); end else if FLastCollType <> '' then begin if (FLastCollType = 'LC') or (FLastCollType = 'I') then begin if ALabTest.LabCanCollect then cboCollType.SelectByID(FLastCollType) else cboCollType.SelectByID('WC'); end else cboCollType.SelectByID(FLastCollType); end else if uDfltCollType <> '' then begin if (uDfltCollType = 'LC') or (uDfltCollType = 'I') then begin if ALabTest.LabCanCollect then cboCollType.SelectByID(uDfltCollType) else cboCollType.SelectByID('WC'); end else cboCollType.SelectByID(uDfltCollType); end else if OrderForInpatient then begin if ALabTest.LabCanCollect then cboCollType.SelectByID('LC') else SelectByID('WC'); end else cboCollType.SelectByID('SP'); end; SetupCollTimes(cboCollType.ItemID); end; procedure TLabTest.LoadUrgency(CollType: string; AComboBox:TORComboBox); var i, PreviousSelectionIndex: integer; PreviousSelectionString: String; begin with AComboBox do begin PreviousSelectionIndex := -1; PreviousSelectionString := SelText; Clear; for i := 0 to UrgencyList.Count - 1 do begin if (CollType = 'LC') and (Piece(UrgencyList[i], U, 3) = '') then Continue else Items.Add(UrgencyList[i]); if (PreviousSelectionString <> '') and (PreviousSelectionString = Piece(UrgencyList[i], U, 2)) then PreviousSelectionIndex := i; end; if (LRFURG <> '') and (ALabTest.ObtainUrgency) then SelectByID(LRFURG) else if PreviousSelectionIndex > -1 then ItemIndex := PreviousSelectionIndex else SelectByIEN(uDfltUrgency); Urgency := AComboBox.ItemIEN; end; end; function TLabTest.NameOfCollSamp: string; var i: Integer; begin Result := ''; i := IndexOfCollSamp(CollSamp); if i > -1 then with TCollSamp(CollSampList.Items[i]) do Result := CollSampName; end; function TLabTest.NameOfSpecimen: string; var i: Integer; begin Result := ''; if CollSamp > 0 then with TCollSamp(CollSampList[IndexOfCollSamp(CollSamp)]) do if (Specimen > 0) and (Specimen = SpecimenID) then Result := SpecimenName; if (Length(Result) = 0) and (Specimen > 0) then with SpecimenList do for i := 0 to Count - 1 do if Specimen = StrToInt(Piece(Strings[i], '^', 1)) then begin Result := Piece(Strings[i], '^', 2); break; end; end; function TLabTest.NameOfUrgency: string; var i: Integer; begin Result := ''; with UrgencyList do for i := 0 to Count - 1 do begin if StrToInt(Piece(Strings[i], '^', 1)) = Urgency then Result := Piece(Strings[i], '^', 2); break; end; end; function TLabTest.ObtainCollSamp: Boolean; begin Result := (not UniqueCollSamp); end; function TLabTest.ObtainSpecimen: Boolean; var i: Integer; begin Result := True; i := IndexOfCollSamp(CollSamp); if (i > -1) and (i < CollSampList.Count) then with TCollSamp(CollSampList.Items[i]) do if SpecimenID > 0 then Result := False; end; function TLabTest.ObtainUrgency: Boolean; begin Result := not ForceUrgency; end; function TLabTest.ObtainComment: Boolean; begin Result := Length(CurReqComment) > 0; end; { end of TLabTest object } procedure TfrmODLab.ControlChange(Sender: TObject); var AResponse: TResponse; AVisitStr: string; begin inherited; if Changing or (ALabTest = nil) then Exit; AResponse := Responses.FindResponseByName('VISITSTR', 1); if AResponse <> nil then AVisitStr := AResponse.EValue; Responses.Clear; with ALabTest do begin if TestID > 0 then Responses.Update('ORDERABLE', 1, IntToStr(TestID), TestName); if CollSamp > 0 then Responses.Update('SAMPLE', 1, IntToStr(CollSamp), NameOfCollSamp) else Responses.Update('SAMPLE', 1, '', ''); if Specimen > 0 then Responses.Update('SPECIMEN', 1, IntToStr(Specimen), NameOfSpecimen) else Responses.Update('SPECIMEN', 1, '', ''); if Urgency > 0 then Responses.Update('URGENCY', 1, IntToStr(Urgency), NameOfUrgency); if Length(Comment.Text) > 0 then Responses.Update('COMMENT', 1, TX_WPTYPE, Comment.Text); with cboCollType do if Length(ItemID) > 0 then begin Responses.Update('COLLECT', 1, ItemID, ItemID) ; FLastCollType := ItemID; end; end; if cboCollType.ItemID = 'LC' then begin with cboCollTime do if Length(ItemID) > 0 then begin Responses.Update('START', 1, Copy(ItemID, 2, 999), Copy(ItemID, 2, 999)); FLastLabCollTime := ItemID + U + Text; end else if Length(Text) > 0 then begin Responses.Update('START', 1, ValidCollTime(Text), Text) ; FLastLabCollTime := ValidCollTime(Text); end; end else begin with calCollTime do if FMDateTime > 0 then begin Responses.Update('START', 1, ValidCollTime(Text), Text); FLastColltime := ValidCollTime(Text); end else begin Responses.Update('START', 1, '', '') ; FLastCollTime := ''; end; end; with cboFrequency do if Length(ItemID) > 0 then Responses.Update('SCHEDULE', 1, ItemID, Text); with txtDays do if Enabled then Responses.Update('DAYS', 1, Text, Text); { worry about stop date later } if AVisitStr <> '' then Responses.Update('VISITSTR', 1, AVisitStr, AVisitStr); memOrder.Text := Responses.OrderText; end; procedure TfrmODLab.Validate(var AnErrMsg: string); procedure SetError(const x: string); begin if Length(AnErrMsg) > 0 then AnErrMsg := AnErrMsg + CRLF; AnErrMsg := AnErrMsg + x; end; var CmtType,DaysofFuturePast, y: integer; (*Hours, *)DayMax, (*Daily, *)NoOfTimes, (*DayFreq,*) Minutes: integer; d1, d2: TDateTime; Days, MsgTxt: Double; x: string; ACollType: string; const TX_NO_TIME = 'Collection Time is required.' ; TX_NO_TCOLLTYPE = 'Collection Type is required.' ; TX_NO_TESTS = 'A Lab Test or tests must be selected.' ; TX_BAD_TIME = 'Collection times must be chosen from the drop down list or entered as valid' + ' Fileman date/times (T@1700, T+1@0800, etc.).' ; TX_PAST_TIME = 'Collection times in the past are not allowed.'; TX_NO_DAYS = 'A number of days must be entered for continuous orders.'; TX_NO_TIMES = 'A number of times must be entered for continuous orders.'; TX_NO_STOP_DATE = 'Could not calculate the stop date for the order. Check "for n Days".'; TX_TOO_MANY_DAYS = 'Maximum number of days allowed is '; TX_TOO_MANY_TIMES = 'For this frequency, the maximum number of times allowed is: X'; //TX_NO_COMMENT = 'A comment is required for this test and collection sample.'; TX_NUMERIC_REQD = 'A numeric value is required for urine volume.'; TX_DOSEDRAW_REQD = 'Both DOSE and DRAW times are required for this order.'; TX_TDM_REQD = 'A value for LEVEL is required for this order.'; //TX_ANTICOAG_REQD = 'You must specify an anticoagulant on this order.' ; TX_NO_COLLSAMPLE = 'A collection sample MUST be specified.'; TX_NO_SPECIMEN = 'A specimen MUST be specified.'; TX_NO_URGENCY = 'An urgency MUST be specified.'; TX_NO_FREQUENCY = 'A collection frequency MUST be specified.'; TX_NOT_LAB_COLL_TIME = ' is not a routine lab collection time.'; TX_NO_ALPHA = 'For continuous orders, enter a number of days, or an "X" followed by a number of times.'; TX_BADTIME_CAP = 'Invalid Immediate Collect Time'; begin inherited; { need to go thru list and make sure everything is filled in } with cboAvailTest do if ItemIEN <= 0 then SetError(TX_NO_TESTS); if ALabTest <> nil then if (cboCollType.ItemID = 'I') and (not ALabTest.LabCanCollect) then begin SetError(TX_NO_IMMED); cboCollType.ItemIndex := -1; end; if cboCollType.ItemID = '' then SetError(TX_NO_TCOLLTYPE) else if cboCollType.ItemID = 'LC' then begin if Length(cboCollTime.Text) = 0 then SetError(TX_NO_TIME); with cboCollTime do if (Length(Text) > 0) and (ItemIndex = -1) then begin if StrToFMDateTime(Text) < 0 then SetError(TX_BAD_TIME) else if StrToFMDateTime(Text) < FMNow then SetError(TX_PAST_TIME) else if OrderForInpatient then begin d1 := FMDateTimeToDateTime(Trunc(StrToFMDateTime(cboColltime.Text))); d2 := FMDateTimeToDateTime(FMToday); if EvtDelayLoc > 0 then DaysofFuturePast := LabCollectFutureDays(EvtDelayLoc,EvtDivision) else DaysofFuturePast := LabCollectFutureDays(Encounter.Location); if DaysofFuturePast = 0 then DaysofFuturePast := 7; if ((d1 - d2) > DaysofFuturePast) then SetError('A lab collection cannot be ordered more than ' + IntToStr(DaysofFuturePast) + ' days in advance'); end else if EvtDelayLoc > 0 then begin if (not IsLabCollectTime(StrToFMDateTime(cboCollTime.Text), EvtDelayLoc)) then SetError(cboCollTime.Text + TX_NOT_LAB_COLL_TIME); end else if EvtDelayLoc <= 0 then begin if (not IsLabCollectTime(StrToFMDateTime(cboCollTime.Text), Encounter.Location)) then SetError(cboCollTime.Text + TX_NOT_LAB_COLL_TIME); end; end; end else begin if cboCollType.ItemID = 'I' then begin calCollTime.Text := txtImmedColl.Text; x := ValidImmCollTime(calCollTime.FMDateTime); if (Piece(x, U, 1) <> '1') then SetError(Piece(x, U, 2)); end; with calColltime do begin if FMDateTime = 0 then SetError(TX_BAD_TIME) else begin // date only was entered if (FMDateTime - Trunc(FMDateTime) = 0) then begin if (Trunc(FMDateTime) < FMToday) then SetError(TX_PAST_TIME); end // date/time was entered else begin if (UpperCase(Text) <> 'NOW') and (FMDateTime < FMNow) then SetError(TX_PAST_TIME); end; end; end; end; with cboCollSamp do if ItemIndex < 0 then SetError(TX_NO_COLLSAMPLE) else if (ItemIndex >= 0) and (ItemIEN = 0) then begin if ALabTest <> nil then GetAllCollSamples(cboCollSamp); if ItemIEN = 0 then SetError(TX_NO_COLLSAMPLE); end; with cboSpecimen do if ItemIndex < 0 then SetError(TX_NO_SPECIMEN) else if (ItemIndex >= 0) and (ItemIEN = 0) then begin if (ALabTest <> nil) and (cboCollSamp.ItemIEN > 0) then GetAllSpecimens(cboSpecimen); if ItemIEN = 0 then SetError(TX_NO_SPECIMEN); end; If (ALabTest <> nil) and (ALabTest.Urgency <= 0) then begin with ALabTest do ChangeUrgency(cboUrgency.ItemID); ControlChange(Self); end; with cboUrgency do if ItemIEN <= 0 then SetError(TX_NO_URGENCY); with cboFrequency do if ItemIEN <= 0 then SetError(TX_NO_FREQUENCY); if ALabTest <> nil then begin CmtType := FCmtTypes.IndexOf(ALabTest.CurReqComment) ; with ALabTest do case CmtType of 0 : {ANTICOAGULATION} {if (Pos('ANTICOAGULANT',Comment.Text)=0) then SetError(TX_ANTICOAG_REQD)}; 1 : {DOSE/DRAW TIMES} if (Pos('Last dose:',Comment.Text)=0) or (Pos('draw time:',Comment.Text)=0) then SetError(TX_DOSEDRAW_REQD); 2 : {ORDER COMMENT} {if (Length(Comment.Text)=0) then SetError(TX_NO_COMMENT)}; 3 : {ORDER COMMENT MODIFIED} {if (Length(Comment.Text)=0) then SetError(TX_NO_COMMENT)}; 4 : {TDM (PEAK-TROUGH} if (Pos('Dose is expected',Comment.Text)=0) then SetError(TX_TDM_REQD); 5 : {TRANSFUSION} {if (Length(Comment.Text)=0) then SetError(TX_NO_COMMENT)}; 6 : {URINE VOLUME} if (Length(Comment.Text)>0) and (ExtractInteger(Comment.Text)<=0) then Comment.Text := '?'; {SetError(TX_NUMERIC_REQD);} { else if (Length(CurReqComment)>0) and (Length(Comment.Text)=0) then SetError(TX_NO_COMMENT); } end; end; with txtDays do if Enabled then begin DayMax := 0; if (cboCollType.ItemID = 'LC') or (cboCollType.ItemID = 'I') then begin if EvtDelayLoc > 0 then DayMax := LabCollectFutureDays(EvtDelayLoc,EvtDivision) else DayMax := LabCollectFutureDays(Encounter.Location); end; if DayMax = 0 then begin if EvtDelayLoc > 0 then DayMax := MaxDays(EvtDelayLoc, cboFrequency.ItemIEN) else DayMax := MaxDays(Encounter.Location, cboFrequency.ItemIEN); end; x := Piece(cboFrequency.Items[cboFrequency.ItemIndex], U, 3); if (x = 'C') or (x = 'D') then begin Minutes := StrToIntDef(Piece(cboFrequency.Items[cboFrequency.ItemIndex], U, 4), 0); Days := Minutes / 1440; if (Days = 0) then Days := 1; if Pos('X', UpperCase(txtDays.Text)) > 0 then begin x := Trim(Copy(txtDays.Text, 1, Pos('X', UpperCase(txtDays.Text)) - 1)) + Trim(Copy(txtDays.Text, Pos('X', UpperCase(txtDays.Text)) + 1, 99)); NoOfTimes := ExtractInteger(x); Days := NoOfTimes * Days; // # days requested if FloatToStr(NoOfTimes) <> x then SetError(TX_NO_ALPHA) else if NoOfTimes = 0 then SetError(TX_NO_TIMES) else if (Days > DayMax) then begin MsgTxt := Minutes / 60; x := ' hour'; if MsgTxt > 24 then begin MsgTxt := MsgTxt / 24; x := ' day'; end; if MsgTxt > 1 then x := x + 's'; y := 0; if Minutes > 0 then y := (DayMax * 1440) div Minutes; if y = 0 then y := 1; //if y > 0 then SetError(TX_TOO_MANY_TIMES + IntToStr(y) + CRLF + ' (Every ' + FloatToStr(MsgTxt) + x + ' for a maximum of ' + IntToStr(DayMax) + ' days.)') //else // Responses.Update('DAYS', 1, 'X1', 'X1'); end else begin x := 'X' + IntToStr(NoOfTimes); Responses.Update('DAYS', 1, x, x); end; end else begin Days := ExtractInteger(txtDays.Text); if FloatToStr(Days) <> Trim(txtDays.Text) then SetError(TX_NO_ALPHA) //SetError(TX_NO_DAYS) v18.6 (RV) else if (Days > DayMax) then SetError(TX_TOO_MANY_DAYS + IntToStr(DayMax)) else Responses.Update('DAYS', 1, txtDays.Text, txtDays.Text); end; end; end; if (AnErrMsg <> '') or (Self.EvtID > 0) then exit; // add check and display for auto-change from LC to WC - v27.1 - CQ #10226 ACollType := Responses.FindResponseByName('COLLECT', 1).EValue; if ((ACollType = 'LC') or (ACollType = 'I')) then DisplayChangedOrders(ACollType); end; procedure TfrmODLab.DisplayChangedOrders(ACollType: string); var AStartDate, ASchedule, ADuration: string; ChangedOrdersList, AList: TStringlist; i, j, k: integer; begin ChangedOrdersList := TStringList.Create; try AStartDate := Responses.FindResponseByName('START', 1).IValue; ASchedule := Responses.FindResponseByName('SCHEDULE', 1).IValue; if txtDays.Enabled then ADuration := Responses.FindResponseByName('DAYS', 1).EValue else ADuration := ''; CheckForChangeFromLCtoWCOnAccept(ChangedOrdersList, Encounter.Location, AStartDate, ACollType, ASchedule, ADuration); if ChangedOrdersList.Text <> '' then begin AList := TStringList.Create; try AList.Text := Responses.OrderText; with ChangedOrdersList do begin Insert(5, 'Order :' + #9 + AList[0]); k := Length(ChangedOrdersList[5]); i := 0; if AList.Count > 1 then for j := 1 to AList.Count - 1 do begin Insert(5 + j, StringOfChar(' ', 9) + #9 + AList[j]); k := HigherOf(k, Length(ChangedOrdersList[5 + j])); i := j; end; Insert(5 + i + 1, StringOfChar('-', k + 4)); end; ReportBox(ChangedOrdersList, 'Changed Orders', TRUE); finally AList.Free; end; end; finally ChangedOrdersList.Free; end; end; procedure TfrmODLab.cboAvailTestNeedData(Sender: TObject; const StartFrom: string; Direction, InsertAt: Integer); begin cboAvailTest.ForDataUse(SubsetOfOrderItems(StartFrom, Direction, 'S.LAB', Responses.QuickOrder)); end; procedure TfrmODLab.cboAvailTestExit(Sender: TObject); begin inherited; if (Length(cboAvailTest.ItemID) = 0) or (cboAvailTest.ItemID = '0') then Exit; if cboAvailTest.ItemID = FLastLabID then Exit; cboAvailTestSelect(cboAvailTest); cboAvailTest.SetFocus; PostMessage(Handle, WM_NEXTDLGCTL, 0, 0); end; procedure TfrmODLab.cboAvailTestSelect(Sender: TObject); var x: string; i: integer; tmpResp: TResponse; begin with cboAvailTest do begin if (Length(ItemID) = 0) or (ItemID = '0') then Exit; FLastLabID := ItemID ; FLastItemID := ItemID; Changing := True; if Sender <> Self then Responses.Clear; // Sender=Self when called from SetupDialog if CharAt(ItemID, 1) = 'Q' then with Responses do begin FLastItemID := ItemID; QuickOrder := ExtractInteger(ItemID); SetControl(cboAvailTest, 'ORDERABLE', 1); if (Length(ItemID) = 0) or (ItemID = '0') then Exit; FLastLabID := ItemID; end; ALabTest := TLabTest.Create(ItemID, Responses); end; with ALabTest do begin lblTestName.Caption := TestName; LoadCollSamp(cboCollSamp); cboCollSampChange(Self); LoadSpecimen(cboSpecimen); LoadUrgency(cboCollType.ItemID, cboUrgency); with Responses do if QuickOrder > 0 then begin StatusText('Initializing Quick Order'); Changing := True; SetControl(cboAvailTest, 'ORDERABLE', 1); SetControl(cboFrequency, 'SCHEDULE', 1); SetControl(txtDays, 'DAYS', 1); tmpResp := FindResponseByName('SAMPLE' ,1); if (tmpResp <> nil) and (tmpResp.IValue <> '') then with cboCollSamp do begin SelectByID(tmpResp.IValue); if ItemIndex < 0 then begin LoadAllSamples; Items.Insert(0, tmpResp.IValue + U + tmpResp.EValue); ItemIndex := 0 ; end; end else if LRFSAMP <> '' then cboCollSamp.SelectByID(LRFSAMP); if (cboCollSamp.ItemIndex < 0) and (cboCollSamp.Items.IndexOf('Other...') >= 0) then cboCollSamp.SelectByID('0'); cboCollSampChange(Self); DetermineCollectionDefaults(Responses); LoadUrgency(cboCollType.ItemID, cboUrgency); SetControl(cboUrgency, 'URGENCY', 1); Urgency := cboUrgency.ItemIEN; if (Urgency = 0) and (cboUrgency.Items.Count = 1) then begin cboUrgency.ItemIndex := 0; Urgency := cboUrgency.ItemIEN; end; tmpResp := FindResponseByName('SPECIMEN' ,1); if (tmpResp <> nil) and (tmpResp.IValue <> '') then with cboSpecimen do begin SelectByID(tmpResp.IValue); if ItemIndex < 0 then begin if ALabTest <> nil then ALabTest.SpecimenList.Add(tmpResp.IValue + U + tmpResp.EValue); Items.Insert(0, tmpResp.IValue + U + tmpResp.EValue); ItemIndex := 0 ; end; end else if LRFSPEC <> '' then cboSpecimen.SelectByID(LRFSPEC); if (cboSpecimen.ItemIndex < 0) and (cboSpecimen.Items.IndexOf('Other...') >= 0) then cboSpecimen.SelectByID('0'); Specimen := cboSpecimen.ItemIEN; i := 1 ; tmpResp := Responses.FindResponseByName('COMMENT',i); while tmpResp <> nil do begin Comment.Add(tmpResp.EValue); Inc(i); tmpResp := Responses.FindResponseByName('COMMENT',i); end ; with cboFrequency do if not Enabled then begin ItemIndex := Items.IndexOf('ONE TIME'); if ItemIndex = -1 then ItemIndex := Items.IndexOf('ONCE'); end; cboFrequencyChange(Self); end; // Quick Order if ObtainCollSamp then begin lblCollSamp.Enabled := True; cboCollSamp.Enabled := True; //TDP - CQ#19396 Added cboCollSamp 508 changes setup508Label(cboCollSamp.Text, collsamplbl508, cboCollSamp, lblCollSamp.Caption); end else begin with ALabTest do with TCollSamp(CollSampList.Items[IndexOfCollSamp(CollSamp)]) do begin x := '' ; for i := 0 to WardComment.Count-1 do x := x + WardComment.strings[i]+#13#10 ; pnlMessage.TabOrder := cboAvailTest.TabOrder + 1; OrderMessage(x) ; end ; lblCollSamp.Enabled := False; cboCollSamp.Enabled := False; //TDP - CQ#19396 Added cboCollSamp 508 changes setup508Label(cboCollSamp.Text, collsamplbl508, cboCollSamp, lblCollSamp.Caption); end; if ObtainSpecimen then begin lblSpecimen.Enabled:= True; cboSpecimen.Enabled:= True; setup508Label(cboSpecimen.Text, specimenlbl508, cboSpecimen, lblSpecimen.Caption); end else begin lblSpecimen.Enabled:= False; cboSpecimen.Enabled:= False; setup508Label(cboSpecimen.Text, specimenlbl508, cboSpecimen, lblSpecimen.Caption); end; if ObtainUrgency then begin lblUrgency.Enabled := True; cboUrgency.Enabled := True; end else begin lblUrgency.Enabled := False; cboUrgency.Enabled := False; end; if ObtainComment then LoadRequiredComment(FCmtTypes.IndexOf(CurReqComment)) else DisableCommentPanels; x := '' ; for i := 0 to CurWardComment.Count-1 do x := x + CurWardComment.strings[i]+#13#10 ; i := IndexOfCollSamp(CollSamp); if i > -1 then with TCollSamp(CollSampList.Items[IndexOfCollSamp(CollSamp)]) do for i := 0 to WardComment.Count-1 do x := x + WardComment.strings[i]+#13#10 ; pnlMessage.TabOrder := cboAvailTest.TabOrder + 1; OrderMessage(x) ; end; { with } StatusText(''); Changing := False; if Sender <> Self then ControlChange(Self); end; procedure TfrmODLab.cboCollSampChange(Sender: TObject); var i: integer; x: string; begin if (ALabTest = nil) or (cboCollSamp.ItemIEN = 0) then exit; with ALabTest do begin ChangeCollSamp(cboCollSamp.ItemIEN); LoadSpecimen(cboSpecimen); LoadCollType(cbocollType); LoadUrgency(cboCollType.ItemID, cboUrgency); if ObtainSpecimen then begin lblSpecimen.Enabled:= True; cboSpecimen.Enabled:= True; setup508Label(cboSpecimen.Text, specimenlbl508, cboSpecimen, lblSpecimen.Caption); end else begin lblSpecimen.Enabled:= False; cboSpecimen.Enabled:= False; setup508Label(cboSpecimen.Text, specimenlbl508, cboSpecimen, lblSpecimen.Caption); end; if ObtainComment then LoadRequiredComment(FCmtTypes.IndexOf(CurReqComment)) else DisableCommentPanels; if not Changing then with TCollSamp(CollSampList.Items[IndexOfCollSamp(CollSamp)]) do begin x := '' ; for i := 0 to WardComment.Count-1 do x := x + WardComment.strings[i]+#13#10 ; pnlMessage.TabOrder := cboCollSamp.TabOrder + 1; OrderMessage(x) ; end ; end; ControlChange(Self); end; procedure TfrmODLab.cboUrgencyChange(Sender: TObject); begin if ALabTest = nil then exit; with ALabTest do ChangeUrgency(cboUrgency.ItemID); ControlChange(Self); end; procedure TfrmODLab.cboSpecimenChange(Sender: TObject); begin if ALabTest = nil then exit; with cboSpecimen do if Text = 'Other...' then if (ItemIndex >= 0) and (ItemIEN = 0) then GetAllSpecimens(cboSpecimen); with ALabTest do ChangeSpecimen(cboSpecimen.ItemID); ControlChange(Self); end; procedure TfrmODLab.cboCollTimeChange(Sender: TObject); var CollType: string; const TX_BAD_TIME = ' is not a routine lab collection time.' ; TX_BAD_TIME_CAP = 'Invalid Time'; begin CollType := 'LC'; with cboCollTime do if ItemID = 'LO' then begin ItemIndex := -1; Text := GetFutureLabTime(FMToday); end; //cboCollType.SelectByID(CollType); ControlChange(Self); end; procedure TfrmODLab.cboFrequencyChange(Sender: TObject); var x, HowManyText: string; const HINT_TEXT1 = 'Enter a number of days'; HINT_TEXT2 = ', or an "X" followed by a number of times.'; begin with cboFrequency do if ItemIndex > -1 then x := Items[ItemIndex]; with cboFrequency do if (ItemIndex > -1) and (Piece(Items[ItemIndex], U, 3) <> 'O') then begin lblHowManyDays.Enabled := True; if Piece(Items[ItemIndex], U, 3) = 'C' then txtDays.Hint := HINT_TEXT1 + HINT_TEXT2 else txtDays.Hint := ''; txtDays.Enabled := True; //TDP - txtDays 508 changes if txtDays.Text = '' then HowManyText := 'no value' else HowManyText := txtDays.Text; setup508Label(HowManyText, HowManyDayslbl508, txtDays, lblHowManyDays.Caption); txtDays.Showhint := True; end else begin txtDays.Text := ''; lblHowManyDays.Enabled := False; txtDays.Enabled := False; //TDP - txtDays 508 changes HowManyText := 'no value'; setup508Label(HowManyText, HowManyDayslbl508, txtDays, lblHowManyDays.Caption); txtDays.ShowHint := False; end; ControlChange(Self); end; procedure TfrmODLab.cboCollTypeChange(Sender: TObject); begin if (ALabTest = nil) or Changing or (cboCollType.ItemID = '') then exit; if (cboCollType.ItemID = 'I') and (not ALabTest.LabCanCollect) then begin InfoBox(TX_NO_IMMED, TX_NO_IMMED_CAP, MB_OK or MB_ICONWARNING); cboCollType.ItemIndex := -1; Exit; end; SetupCollTimes(cboCollType.ItemID); ALabTest.LoadUrgency(cboCollType.ItemID, cboUrgency); ControlChange(Self); end; procedure TfrmODLab.SetupCollTimes(CollType: string); var tmpImmTime, tmpTime: TFMDateTime; x, tmpORECALLType, tmpORECALLTime: string; begin x := GetLastCollectionTime; tmpORECALLType := Piece(x, U, 1); tmpORECALLTime := Piece(x, U, 2); if CollType = 'SP' then begin cboColltime.Visible := False; txtImmedColl.Visible := False; pnlCollTimeButton.Visible := False; pnlCollTimeButton.TabStop := False; calCollTime.Visible := True; calColltime.Enabled := True; if FLastCollTime <> '' then begin calCollTime.Text := ValidCollTime(FLastColltime); if IsFMDateTime(calCollTime.Text) then begin calCollTime.Text := FormatFMDateTime('mmm dd,yy@hh:nn', StrToFMDateTime(calColltime.Text)); calColltime.FMDateTime := StrToFMDateTime(FLastCollTime); end; end else if tmpORECALLTime <> '' then begin calCollTime.Text := ValidCollTime(tmpORECALLTime); if IsFMDateTime(calCollTime.Text) then begin calCollTime.Text := FormatFMDateTime('mmm dd,yy@hh:nn', StrToFMDateTime(calColltime.Text)); calColltime.FMDateTime := StrToFMDateTime(tmpORECALLTime); end; end else if LRFDATE <> '' then calCollTime.Text := LRFDATE else calCollTime.Text := 'TODAY'; end else if CollType = 'WC' then begin cboColltime.Visible := False; txtImmedColl.Visible := False; pnlCollTimeButton.Visible := False; pnlCollTimeButton.TabStop := False; calCollTime.Visible := True; calColltime.Enabled := True; if FLastCollTime <> '' then begin calCollTime.Text := ValidColltime(FLastColltime); if IsFMDateTime(calCollTime.Text) then begin calCollTime.Text := FormatFMDateTime('mmm dd,yy@hh:nn', StrToFMDateTime(calColltime.Text)); calColltime.FMDateTime := StrToFMDateTime(FLastCollTime); end; end else if tmpORECALLTime <> '' then begin calCollTime.Text := ValidColltime(tmpORECALLTime); if IsFMDateTime(calCollTime.Text) then begin calCollTime.Text := FormatFMDateTime('mmm dd,yy@hh:nn', StrToFMDateTime(calColltime.Text)); calColltime.FMDateTime := StrToFMDateTime(tmpORECALLTime); end; end else if LRFDATE <> '' then calCollTime.Text := LRFDATE else calCollTime.Text := 'NOW'; end else if CollType = 'LC' then begin cboColltime.Visible := True; calCollTime.Visible := False; calColltime.Enabled := False; txtImmedColl.Visible := False; pnlCollTimeButton.Visible := False; pnlCollTimeButton.TabStop := False; with CtrlInits do SetControl(cboCollTime, 'Lab Collection Times'); if Pos(U, FLastLabCollTime) > 0 then cboColltime.SelectByID(Piece(FLastLabCollTime, U, 1)) else if FLastLabCollTime <> '' then cboCollTime.Text := FLastLabCollTime else if (tmpORECALLTime <> '') and (tmpORECALLType = 'LC') then cboCollTime.Text := MakeRelativeDateTime(StrToFMDateTime(tmpORECALLTime)) else if LRFDATE <> '' then cboCollTime.Text := LRFDATE else cboCollTime.ItemIndex := 0; end else if CollType = 'I' then begin cboColltime.Visible := False; calCollTime.Visible := False; calColltime.Enabled := False; txtImmedColl.Visible := True; pnlCollTimeButton.Visible := True; pnlCollTimeButton.TabStop := True; tmpImmTime := GetDefaultImmCollTime; tmpTime := 0; if (FLastColltime <> '') then tmpTime := StrToFMDateTime(FLastColltime) else if (tmpORECALLTime <> '') then tmpTime := StrToFMDateTime(tmpORECALLTime) else if LRFDATE <> '' then tmpTime := StrToFMDateTime(LRFDATE); if tmpTime > tmpImmTime then begin calCollTime.FMDateTime := tmpTime; txtImmedColl.Text := FormatFMDateTime('mmm dd,yy@hh:nn', tmpTime); end else begin calCollTime.FMDateTime := GetDefaultImmCollTime; txtImmedColl.Text := FormatFMDateTime('mmm dd,yy@hh:nn', calCollTime.FMDateTime); end; end; end; procedure TfrmODLab.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; if FCmtTypes <> nil then FCmtTypes.Free; frmFrame.pnlVisit.Enabled := true; end; procedure TfrmODLab.LoadRequiredComment(CmtType: integer); begin DisableCommentPanels; pnlHide.SendToBack; lblReqComment.Visible := True ; case CmtType of 0 : {ANTICOAGULATION} pnlAntiCoagulation.Show ; 1 : {DOSE/DRAW TIMES} pnlDoseDraw.Show ; 2 : {ORDER COMMENT} pnlOrderComment.Show ; 3 : {ORDER COMMENT MODIFIED} pnlOrderComment.Show ; // DIFFERENT ??? 4 : {TDM (PEAK-TROUGH} begin pnlPeakTrough.Show ; grpPeakTrough.ItemIndex := -1; txtAddlComment.Show; lblAddlComment.Show; end; 5 : {TRANSFUSION} pnlOrderComment.Show ; 6 : {URINE VOLUME} pnlUrineVolume.Show ; else pnlOrderComment.Show ; end; end; procedure TfrmODLab.txtOrderCommentExit(Sender: TObject); begin inherited; if (not pnlOrderComment.Visible) or (ALabTest = nil) then exit; with ALabTest do if Length(txtOrderComment.Text)>0 then begin Comment.Clear; ChangeComment('~For Test: ' + TestName); ChangeComment('~' + txtOrderComment.Text) ; end else Comment.Clear; ControlChange(Self); end; procedure TfrmODLab.txtAntiCoagulantExit(Sender: TObject); begin inherited; if (not pnlAntiCoagulation.Visible) or (ALabTest = nil) then exit; with ALabTest do if Length(txtAntiCoagulant.Text)>0 then begin Comment.Clear; ChangeComment('~For Test: ' + TestName); ChangeComment('~ANTICOAGULANT: ' + txtAntiCoagulant.Text); end else Comment.Clear; ControlChange(Self); end; procedure TfrmODLab.txtUrineVolumeExit(Sender: TObject); begin inherited; if (not pnlUrineVolume.Visible) or (ALabTest = nil) then exit; with ALabTest do begin Comment.Clear; ChangeComment(txtUrineVolume.Text) ; end; ControlChange(Self); end; procedure TfrmODLab.grpPeakTroughClick(Sender: TObject); begin inherited; if (not pnlPeakTrough.Visible) or (ALabTest = nil) then exit; with ALabTest,grpPeakTrough do if ItemIndex > -1 then begin Comment.Clear; ChangeComment('~For Test: ' + TestName); ChangeComment('~Dose is expected to be at ' + UpperCase(Items[ItemIndex]) + ' level.'); ChangeComment(txtAddlComment.Text) ; end else Comment.Clear; ControlChange(Self); end; procedure TfrmODLab.txtDoseTimeExit(Sender: TObject); begin inherited; if (not pnlDoseDraw.Visible) or (ALabTest = nil) then exit; with txtDoseTime do if Length(Text)>0 then Text := FormatFMDateTime('mm/dd/yy@hh:nn', StrToFMDateTime(Text)) else Text := 'UNKNOWN'; DoseDrawComment; ControlChange(Self); end; procedure TfrmODLab.txtDrawTimeExit(Sender: TObject); begin inherited; if (not pnlDoseDraw.Visible) or (ALabTest = nil) then exit; with txtDrawTime do if Length(Text)>0 then Text := FormatFMDateTime('mm/dd/yy@hh:nn', StrToFMDateTime(Text)) else Text := 'UNKNOWN'; DoseDrawComment; ControlChange(Self); end; procedure TfrmODLab.DoseDrawComment; begin if ALabTest = nil then exit; with ALabTest do begin Comment.Clear; ChangeComment('~For Test: ' + TestName); ChangeComment('~Last dose: ' + txtDoseTime.Text + ' draw time: '+txtDrawTime.Text); end; end; procedure TfrmODLab.txtAddlCommentExit(Sender: TObject); begin if (not pnlPeakTrough.Visible) or (ALabTest = nil) then exit; grpPeakTroughClick(Sender); end; procedure TfrmODLab.DisableCommentPanels; begin pnlHide.BringToFront; lblReqComment.Visible := False; pnlAntiCoagulation.Visible := False; pnlOrderComment.Visible := False; pnlDoseDraw.Visible := False; pnlPeakTrough.Visible := False; pnlUrineVolume.Visible := False; lblAddlComment.Visible := False; txtAddlComment.Visible := False; //pnlTransfusion.Visible := False; end; procedure TfrmODLab.cboCollSampKeyPause(Sender: TObject); begin inherited; if ALabTest = nil then exit; with cboCollSamp do if (ItemIndex >= 0) and (ItemIEN = 0) then GetAllCollSamples(cboCollSamp); if (cboCollSamp.ItemIEN = 0) then begin ALabTest.Specimen := 0; ALabTest.CollSamp := 0; cboCollSamp.ItemIndex := -1; cboSpecimen.ItemIndex := -1; end else ALabTest.LoadSpecimen(cboSpecimen); ControlChange(Self); end; procedure TfrmODLab.cboCollSampMouseClick(Sender: TObject); begin inherited; if ALabTest = nil then exit; with cboCollSamp do begin if (ItemIndex >= 0) and (ItemIEN = 0) then GetAllCollSamples(cboCollSamp); if (ItemIEN = 0) then begin ALabTest.Specimen := 0; ALabTest.CollSamp := 0; ItemIndex := -1; cboSpecimen.ItemIndex := -1; end else ALabTest.LoadSpecimen(cboSpecimen); end; ControlChange(Self); end; function TfrmODLab.ValidCollTime(UserEntry: string): string; var i: integer; const FMDateResponses: array[0..3] of string = ('TODAY','NOW','NOON','MID'); begin Result := ''; UserEntry := UpperCase(UserEntry); if StrToFMDateTime(UserEntry) < 0 then exit; if (UserEntry = 'T') or (UserEntry = 'N') or (Copy(UserEntry,1,2)='T+') or (Copy(UserEntry,1,2)='T@') or (Copy(UserEntry,1,2)='T-') or (Copy(UserEntry,1,2)='N+') then Result := UserEntry else for i := 0 to 3 do if Pos(FMDateResponses[i],UserEntry)>0 then Result := UserEntry ; if Result = '' then Result := FloatToStr(StrToFMDateTime(UserEntry)); end; procedure TfrmODLab.cboCollTimeExit(Sender: TObject); var ADateTime: TFMDateTime; CollType: string; isTrue: boolean; const TX_BAD_TIME = ' is not a routine lab collection time.' ; TX_BAD_TIME_CAP = 'Invalid Time'; begin inherited; if (ALabTest = nil) or (cboColltime.Text = '') then Exit; Changing := True; CollType := 'LC'; with cboCollTime do if (ItemIndex < 0) or (ITEMID = 'LO') then if ALabTest.LabCanCollect then begin ADateTime := StrToFMDateTime(cboCollTime.Text); if EvtDelayLoc > 0 then isTrue := IsLabCollectTime(ADateTime, EvtDelayLoc) else isTrue := IsLabCollectTime(ADateTime, Encounter.Location); if isTrue then begin calCollTime.Clear; cboCollTime.Visible := True; calCollTime.Visible := False; calCollTime.Enabled := False; end {if IsLabCollectTime} else begin InfoBox(cboCollTime.Text + TX_BAD_TIME, TX_BAD_TIME_CAP, MB_OK or MB_ICONWARNING) ; ItemIndex := -1; Text := GetFutureLabTime(ADateTime); end ; end {if (LabCanCollect...} else begin if OrderForInpatient then CollType := 'WC' else CollType := 'SP'; calCollTime.Text := cboCollTime.Text; cboCollTime.Clear; cboCollTime.Visible := False; calCollTime.Visible := True; calCollTime.Enabled := True; end; cboCollType.SelectByID(CollType); Changing := False; //v16.3 RV ControlChange(Self); //v16.3 RV //Responses.Update('COLLECT', 1, CollType, CollType) ; //v16.3 RV //memOrder.Text := Responses.OrderText; //v16.3 RV end; procedure TfrmODLab.cboSpecimenMouseClick(Sender: TObject); begin inherited; if ALabTest = nil then exit; with cboSpecimen do begin if (ItemIndex >= 0) and (ItemIEN = 0) then GetAllSpecimens(cboSpecimen); if (ItemIEN = 0) then begin ALabTest.Specimen := 0; ItemIndex := -1; end; end; ControlChange(Self); end; procedure TfrmODLab.GetAllCollSamples(AComboBox: TORComboBox); var OtherSamp: string; begin with ALabTest, AComboBox do begin if ((CollSampList.Count + 1) <= AComboBox.Items.Count) then LoadAllSamples; OtherSamp := SelectOtherCollSample(Font.Size, CollSampCount, CollSampList); if OtherSamp = '-1' then exit; if SelectByID(Piece(OtherSamp, U, 1)) = -1 then if Items.Count > CollSampCount + 1 then Items[0] := OtherSamp else Items.Insert(0, OtherSamp) ; SelectByID(Piece(OtherSamp, U, 1)); AComboBox.OnChange(Self); ActiveControl := cmdAccept; end; end; procedure TfrmODLab.GetAllSpecimens(AComboBox: TORComboBox); var OtherSpec: string; begin inherited; if ALabTest <> nil then with ALabTest, AComboBox do begin AComboBox.DroppedDown := False; OtherSpec := SelectOtherSpecimen(Font.Size, SpecimenList); if OtherSpec = '-1' then exit; if SelectByID(Piece(OtherSpec, U, 1)) = -1 then if Items.Count > SpecListCount + 1 then Items[0] := OtherSpec else Items.Insert(0, OtherSpec) ; SpecimenList.Add(OtherSpec); SelectByID(Piece(OtherSpec, U, 1)); AComboBox.OnChange(Self); end; end; procedure TfrmODLab.cboSpecimenKeyPause(Sender: TObject); begin inherited; if ALabTest = nil then exit; with cboSpecimen do if (ItemIndex >= 0) and (ItemIEN = 0) then GetAllSpecimens(cboSpecimen); if (cboSpecimen.ItemIEN = 0) then begin ALabTest.Specimen := 0; cboSpecimen.ItemIndex := -1; end ; ControlChange(Self); end; procedure TfrmODLab.cmdImmedCollClick(Sender: TObject); var ImmedCollTime: string; begin inherited; ImmedCollTime := SelectImmediateCollectTime(Font.Size, txtImmedColl.Text); if ImmedCollTime <> '-1' then begin txtImmedColl.Text := ImmedCollTime; calCollTime.FMDateTime := StrToFMDateTime(ImmedCollTime); end else begin txtImmedColl.Clear; calCollTime.Clear; end; end; procedure TfrmODLab.ReadServerVariables; begin LRFZX := KeyVariable['LRFZX']; LRFSAMP := KeyVariable['LRFSAMP']; LRFSPEC := KeyVariable['LRFSPEC']; LRFDATE := KeyVariable['LRFDATE']; LRFURG := KeyVariable['LRFURG']; LRFSCH := KeyVariable['LRFSCH']; end; procedure TfrmODLab.DetermineCollectionDefaults(Responses: TResponses); var RespCollect, RespStart: TResponse; //i: integer; begin if ALabTest = nil then exit; calCollTime.Clear; cboCollTime.Clear; calCollTime.Enabled := True; lblCollTime.Enabled := True; cboColltime.Enabled := True; with Responses, ALabTest do begin RespCollect := FindResponseByName('COLLECT',1); RespStart := FindResponseByName('START' ,1); if (RespCollect <> nil) then with RespCollect do begin if IValue = 'LC' then begin if not LabCanCollect then begin cboCollType.SelectByID('WC'); SetupCollTimes('WC'); end else // if LabCanCollect begin cboCollType.SelectByID('LC'); SetupCollTimes('LC'); CtrlInits.SetControl(cboCollTime, 'Lab Collection Times') ; if RespStart <> nil then begin cboCollTime.SelectByID('L' + RespStart.IValue); if cboCollTime.ItemIndex < 0 then cboCollTime.Text := RespStart.IValue; end; end; end else // if IValue <> 'LC' begin cboCollType.SelectByID(IValue) ; SetupCollTimes(IValue); if RespStart <> nil then begin if ContainsAlpha(RespStart.IValue) then calColltime.Text := RespStart.IValue else calColltime.FMDateTime := StrToFMDateTime(RespStart.IValue); end; end ; if IValue = 'I' then if not LabCanCollect then begin cboCollType.SelectByID('WC'); SetupCollTimes('WC'); end else begin calCollTime.Enabled := False; if RespStart <> nil then txtImmedColl.Text := RespStart.EValue; end; end else // if (RespCollect = nil) LoadCollType(cbocollType); end; end; procedure TfrmODLab.pnlCollTimeButtonEnter(Sender: TObject); begin inherited; (Sender as TPanel).BevelOuter := bvRaised; end; procedure TfrmODLab.pnlCollTimeButtonExit(Sender: TObject); begin inherited; (Sender as TPanel).BevelOuter := bvNone; end; procedure TfrmODLab.ViewinReportWindow1Click(Sender: TObject); begin inherited; ReportBox(memMessage.Lines, 'Lab Procedure', True); end; end.
unit PointersTestForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public procedure Show (const msg: string); end; var Form1: TForm1; implementation {$R *.fmx} type TPointerToInt = ^Integer; procedure TForm1.Button1Click(Sender: TObject); var P: ^Integer; X: Integer; begin X := 10; P := @X; // change the value of X using the pointer P^ := 20; Show ('X: ' + X.ToString); Show ('P^: ' + P^.ToString); Show ('P: ' + Integer(P).ToHexString (8)); end; procedure TForm1.Button2Click(Sender: TObject); var P: ^Integer; begin // initialization New (P); // operations P^ := 20; Show (P^.ToString); // termination Dispose (P); end; procedure TForm1.Button3Click(Sender: TObject); var P: ^Integer; begin P := nil; // if Assigned (P) then Show (P^.ToString); end; procedure TForm1.Show(const msg: string); begin Memo1.Lines.Add(msg); end; end.