text
stringlengths
14
6.51M
unit utilfunc; {$mode objfpc}{$H+} interface uses Classes, SysUtils; function SetBit(const value: byte; const BitNum: byte): byte; function ClearBit(const value: byte; const BitNum: byte): byte; function IsBitSet(const value: DWORD; const BitNum : byte): boolean; procedure BitSet(bit_val: byte; var val: byte; bit_num: byte); function BitNum(value: cardinal): integer; function ByteNum(value: cardinal): integer; function IsNumber(strSource: string): boolean; function UpdateCRC32(InitCRC: Cardinal; BufPtr: Pointer; Len: Int64): Cardinal; implementation const CRC32Table: array[0..255] of Cardinal = ($00000000, $77073096, $EE0E612C, $990951BA, $076DC419, $706AF48F, $E963A535, $9E6495A3, $0EDB8832, $79DCB8A4, $E0D5E91E, $97D2D988, $09B64C2B, $7EB17CBD, $E7B82D07, $90BF1D91, $1DB71064, $6AB020F2, $F3B97148, $84BE41DE, $1ADAD47D, $6DDDE4EB, $F4D4B551, $83D385C7, $136C9856, $646BA8C0, $FD62F97A, $8A65C9EC, $14015C4F, $63066CD9, $FA0F3D63, $8D080DF5, $3B6E20C8, $4C69105E, $D56041E4, $A2677172, $3C03E4D1, $4B04D447, $D20D85FD, $A50AB56B, $35B5A8FA, $42B2986C, $DBBBC9D6, $ACBCF940, $32D86CE3, $45DF5C75, $DCD60DCF, $ABD13D59, $26D930AC, $51DE003A, $C8D75180, $BFD06116, $21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F, $2802B89E, $5F058808, $C60CD9B2, $B10BE924, $2F6F7C87, $58684C11, $C1611DAB, $B6662D3D, $76DC4190, $01DB7106, $98D220BC, $EFD5102A, $71B18589, $06B6B51F, $9FBFE4A5, $E8B8D433, $7807C9A2, $0F00F934, $9609A88E, $E10E9818, $7F6A0DBB, $086D3D2D, $91646C97, $E6635C01, $6B6B51F4, $1C6C6162, $856530D8, $F262004E, $6C0695ED, $1B01A57B, $8208F4C1, $F50FC457, $65B0D9C6, $12B7E950, $8BBEB8EA, $FCB9887C, $62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65, $4DB26158, $3AB551CE, $A3BC0074, $D4BB30E2, $4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB, $4369E96A, $346ED9FC, $AD678846, $DA60B8D0, $44042D73, $33031DE5, $AA0A4C5F, $DD0D7CC9, $5005713C, $270241AA, $BE0B1010, $C90C2086, $5768B525, $206F85B3, $B966D409, $CE61E49F, $5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4, $59B33D17, $2EB40D81, $B7BD5C3B, $C0BA6CAD, $EDB88320, $9ABFB3B6, $03B6E20C, $74B1D29A, $EAD54739, $9DD277AF, $04DB2615, $73DC1683, $E3630B12, $94643B84, $0D6D6A3E, $7A6A5AA8, $E40ECF0B, $9309FF9D, $0A00AE27, $7D079EB1, $F00F9344, $8708A3D2, $1E01F268, $6906C2FE, $F762575D, $806567CB, $196C3671, $6E6B06E7, $FED41B76, $89D32BE0, $10DA7A5A, $67DD4ACC, $F9B9DF6F, $8EBEEFF9, $17B7BE43, $60B08ED5, $D6D6A3E8, $A1D1937E, $38D8C2C4, $04FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD, $048B2364B, $D80D2BDA, $AF0A1B4C, $36034AF6, $041047A60, $DF60EFC3, $A867DF55, $316E8EEF, $04669BE79, $CB61B38C, $BC66831A, $256FD2A0, $5268E236, $CC0C7795, $BB0B4703, $220216B9, $5505262F, $C5BA3BBE, $B2BD0B28, $2BB45A92, $5CB36A04, $C2D7FFA7, $B5D0CF31, $2CD99E8B, $5BDEAE1D, $9B64C2B0, $EC63F226, $756AA39C, $026D930A, $9C0906A9, $EB0E363F, $72076785, $05005713, $95BF4A82, $E2B87A14, $7BB12BAE, $0CB61B38, $92D28E9B, $E5D5BE0D, $7CDCEFB7, $0BDBDF21, $86D3D2D4, $F1D4E242, $68DDB3F8, $1FDA836E, $81BE16CD, $F6B9265B, $6FB077E1, $18B74777, $88085AE6, $FF0F6A70, $66063BCA, $11010B5C, $8F659EFF, $F862AE69, $616BFFD3, $166CCF45, $A00AE278, $D70DD2EE, $4E048354, $3903B3C2, $A7672661, $D06016F7, $4969474D, $3E6E77DB, $AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0, $A9BCAE53, $DEBB9EC5, $47B2CF7F, $30B5FFE9, $BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6, $BAD03605, $CDD70693, $54DE5729, $23D967BF, $B3667A2E, $C4614AB8, $5D681B02, $2A6F2B94, $B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D); function SetBit(const value: byte; const BitNum: byte): byte; begin Result := value or (1 shl BitNum); end; function ClearBit(const value: byte; const BitNum: byte): byte; begin Result := value and (not (1 shl BitNum)); end; function IsBitSet(const value: DWORD; const BitNum : byte): boolean; begin result:=((Value shr BitNum) and 1) = 1; end; procedure BitSet(bit_val: byte; var val: byte; bit_num: byte); begin if Boolean(bit_val) then val := SetBit(val, bit_num) else val := ClearBit(val, bit_num); end; //сколько бит нужно для хранения данного значения function BitNum(value: cardinal): integer; var i: integer; m: cardinal; begin i:= 0; m:= 1; while m < value do begin m := m*2; Inc(i); end; result := i; end; //Сколько байт нужно для хранение количества бит function ByteNum(value: cardinal): integer; begin result := value div 8; if (Frac(value /8) > 0) then Inc(result); end; function IsNumber(strSource: string): boolean; begin try StrToInt(strSource); Result:=true; except on EConvertError do Result:=false; end; end; function UpdateCRC32(InitCRC: Cardinal; BufPtr: Pointer; Len: Int64): Cardinal; var crc: Cardinal; index: Integer; i: Cardinal; begin if len < 1 then Exit(0); crc := InitCRC; for i := 0 to Len - 1 do begin index := ( crc xor Cardinal((BufPtr + i)^) ) and $000000FF; crc := (crc shr 8) xor CRC32Table[index]; end; Result := not crc; end; end.
unit UConfigMySql; interface uses UConfigJson, UConfigBase, JsonDataObjects, System.SysUtils, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset, Ils.MySQL.Conf, Ils.Kafka; type TConfigMySqlAbstract = class(TConfigJson) protected FMySqlConnection: TZConnection; FMySqlQuery: TZQuery; protected function Reload: Boolean; override; function CheckConnect: Boolean; virtual; abstract; function GetModifiedDateTime: TDateTime; override; function GetModifiedCount: Integer; override; function GetDBConfigModifiedDateTime: TDateTime; virtual; abstract; function GetDBConfigModifiedCount: Integer; virtual; abstract; function ReloadDBConfig: Boolean; virtual; abstract; public constructor Create(const ADBConf: TMySQlDatabaseConfig; const AConfigChangeCB: TConfigEvent; const ALogCB: TLogFunc = nil; const ACheckInterval: Integer = 1000); reintroduce; virtual; destructor Destroy; override; end; TConfigMySql = class(TConfigMySqlAbstract) protected FFormatSettings: TFormatSettings; function CheckConnect: Boolean; override; function MakeConfigJson: Boolean; virtual; abstract; function ReloadDBConfig: Boolean; override; public constructor Create(const ADBConf: TMySQlDatabaseConfig; const AConfigChangeCB: TConfigEvent; const ALogCB: TLogFunc = nil; const ACheckInterval: Integer = 1000); reintroduce; virtual; destructor Destroy; override; end; implementation { TConfigMySqlAbstract } constructor TConfigMySqlAbstract.Create(const ADBConf: TMySQlDatabaseConfig; const AConfigChangeCB: TConfigEvent; const ALogCB: TLogFunc; const ACheckInterval: Integer); begin FLogCB := ALogCB; FMySqlConnection := TZConnection.Create(nil); ADBConf.ConfigConnection(FMySqlConnection, False); FMySqlQuery := TZQuery.Create(nil); FMySqlQuery.Connection := FMySqlConnection; try FMySqlConnection.Connect; except on E: Exception do Log('Ошибка соединения с базой данных: ' + E.Message); end; inherited Create('', AConfigChangeCB, ALogCB, ACheckInterval); end; destructor TConfigMySqlAbstract.Destroy; begin FMySqlQuery.Free; FMySqlConnection.Free; inherited; end; function TConfigMySqlAbstract.GetModifiedDateTime: TDateTime; begin if not CheckConnect then Exit(0); Result := GetDBConfigModifiedDateTime; end; function TConfigMySqlAbstract.GetModifiedCount: Integer; begin if not CheckConnect then Exit(0); Result := GetDBConfigModifiedCount; end; function TConfigMySqlAbstract.Reload: Boolean; begin Result := ReloadDBConfig; end; { TConfigMySql } function TConfigMySql.CheckConnect: Boolean; begin Result := False; try if not FMySqlConnection.Connected then FMySqlConnection.Connect; Result := FMySqlConnection.PingServer; except end; end; constructor TConfigMySql.Create(const ADBConf: TMySQlDatabaseConfig; const AConfigChangeCB: TConfigEvent; const ALogCB: TLogFunc; const ACheckInterval: Integer); begin FFormatSettings.DecimalSeparator := '.'; inherited Create(ADBConf, AConfigChangeCB, ALogCB, ACheckInterval); end; destructor TConfigMySql.Destroy; begin inherited; end; function TConfigMySql.ReloadDBConfig: Boolean; begin Result := MakeConfigJson; end; end.
{@abstract(Implements a lightweight, high-performance, non-allocating advanced-record-based wrapper around the SysUtils file handling routines as an alternative to Classes.TFileStream.)} unit LightFileStream; {$mode Delphi}{$H+}{$J-}{$I-}{$R-} {Uncomment LIGHTFILESTREAM_NOCHECKS when building production releases of thoroughly tested software.} {.$define LIGHTFILESTREAM_NOCHECKS} interface uses SysUtils; type {Type alias for a pointer to the TLightFileStream type.} PLightFileStream = ^TLightFileStream; {@abstract( The sole type implemented by this unit so far. Returns a pointer to itself from all functions to avoid unnecessary allocation or copying and to allow for a convenient "method chaining" API.)} TLightFileStream = record public type (*Determines whether read or write operations are actively accepted. All functions return immediately without doing anything if the current state is "wrong" relative to them, unless @code({$define LIGHTFILESTREAM_NOCHECKS}) is set, which improves performance but is somewhat less "safe."*) TFileState = (fsReading, fsWriting); strict private {The name of the underlying file on disk.} FFileName: PChar; {The handle of the underlying file on disk.} FHandle: THandle; (*Indicates whether the file is @noAutoLink(open) and can be accessed at all. All functions return immediately without doing anything in the event that this is false, unless @code({$define LIGHTFILESTREAM_NOCHECKS}) is set, which improves performance but is somewhat less "safe."*) FOpen: Boolean; {A private instance of TFileState, used as described above.} FState: TFileState; public {Assumes @code(FileName) does not yet exist on disk. Calls @code(FileCreate()) internally. FState is then set to fsWriting, and FOpen is set to True.} class function Create(const FileName: PChar): TLightFileStream; static; {$IFNDEF DEBUG}inline;{$ENDIF} {Assumes @code(FileName) already exists on disk. Calls @code(FileOpen()) with either @code(fmOpenRead) or @code(fmOpenWrite) internally based on the provided @code(InitialState) value. FState is then set to @code(InitialState), and FOpen is set to True.} class function Open(const FileName: PChar; const InitialState: TFileState): TLightFileStream; static; {$IFNDEF DEBUG}inline;{$ENDIF} {Closes the underlying file. Does not return a self-pointer, as it should always be the last method called.} procedure Close; {$IFNDEF DEBUG}inline;{$ENDIF} {Calls @code(FileClose()) on FHandle, then calls @code(FileOpen()) with either @code(fmOpenRead) or @code(fmOpenWrite) internally based on the provided @code(State) value. FState is then set to @code(State).} function ChangeFileStateTo(const State: TFileState): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Sets the current @noAutoLink(position) of the underlying file to @code(ToPosition), relative to 0.} function SeekFromBeginning(const ToPosition: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Sets the current @noAutoLink(position) of the underlying file to @code(ToPosition), relative to itself.} function SeekFromCurrent(const ToPosition: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Sets the current @noAutoLink(position) of the underlying file to @code(ToPosition), relative to the end of the file.} function SeekFromEnd(const ToPosition: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Returns the @noAutoLink(size) in bytes of the underlying file in @code(TheSize), and a self-pointer from the function itself.} function GetSize(out TheSize: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Returns the @noAutoLink(size) in bytes of the underlying file.} function PutSize: SizeInt; {$IFNDEF DEBUG}inline;{$ENDIF} {Calls GetSize() internally and displays the value with @code(WriteLn()).} function LogSize: PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Returns the current @noAutoLink(position) of the underlying file in @code(ThePosition), and a self-pointer from the function itself.} function GetPosition(out ThePosition: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Returns the current @noAutoLink(position) of the underlying file.} function PutPosition: SizeInt; {$IFNDEF DEBUG}inline;{$ENDIF} {Calls GetPosition() internally and displays the value with @code(WriteLn()).} function LogPosition: PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Truncates the underlying file at the current position.} function Truncate: PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of T into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadType<T>(var Item: T): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of T from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteType<T>(constref Item: T): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of T from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendType<T>(constref Item: T): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes @code(NumInstances) instances of @code(Value) to the underlying file at the current position.} function FillWith<T>(constref Value: T; const NumInstances: SizeUInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Assumes @code(Buffer) is something like the first value of an array of T. Reads @code(ItemCount) items into it from the underlying file at the current @noAutoLink(position).} function ReadTypedBuffer<T>(var Buffer: T; const ItemCount: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Assumes @code(Buffer) is something like the first value of an array of T. Writes @code(ItemCount) items from it to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteTypedBuffer<T>(constref Buffer: T; const ItemCount: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Assumes @code(Buffer) is something like the first value of an array of T. Writes @code(ItemCount) items from it to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendTypedBuffer<T>(constref Buffer: T; const ItemCount: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Assumes @code(Buffer) is pointing to something like the first value of an array of any type. Reads @code(NumBytesToRead) bytes into it from the underlying file at the current @noAutoLink(position).} function ReadPointerBuffer(const Buffer: Pointer; const NumBytesToRead: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Assumes @code(Buffer) is pointing to something like the first value of an array of any type. Writes @code(NumBytesToWrite) bytes from it to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WritePointerBuffer(const Buffer: Pointer; const NumBytesToWrite: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Assumes @code(Buffer) is pointing to something like the first value of an array of any type. Writes @code(NumBytesToWrite) bytes from it to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendPointerBuffer(const Buffer: Pointer; const NumBytesToWrite: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of Byte into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadByte(var Item: Byte): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Byte from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteByte(const Item: Byte): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Byte from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendByte(const Item: Byte): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of Word into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadWord(var Item: Word): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Word from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteWord(const Item: Word): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Word from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendWord(const Item: Word): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of LongWord into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadLongWord(var Item: LongWord): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of LongWord from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteLongWord(const Item: LongWord): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of LongWord from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendLongWord(const Item: LongWord): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of QWord into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadQWord(var Item: QWord): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of QWord from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteQWord(const Item: QWord): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of QWord from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendQWord(const Item: QWord): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of ShortInt into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadShortInt(var Item: ShortInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of ShortInt from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteShortInt(const Item: ShortInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of ShortInt from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendShortInt(const Item: ShortInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of SmallInt into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadSmallInt(var Item: SmallInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of SmallInt from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteSmallInt(const Item: SmallInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of SmallInt from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendSmallInt(const Item: SmallInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of LongInt into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadLongInt(var Item: LongInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of LongInt from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteLongInt(const Item: LongInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of LongInt from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendLongInt(const Item: LongInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of Int64 into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadInt64(var Item: Int64): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Int64 from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteInt64(const Item: Int64): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Int64 from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendInt64(const Item: Int64): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of Single into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadSingle(var Item: Single): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Single from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteSingle(const Item: Single): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Single from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendSingle(const Item: Single): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of Double into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadDouble(var Item: Double): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Double from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteDouble(const Item: Double): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Double from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendDouble(const Item: Double): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of Extended into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadExtended(var Item: Extended): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Extended from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteExtended(const Item: Extended): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Extended from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendExtended(const Item: Extended): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of Currency into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadCurrency(var Item: Currency): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Currency from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteCurrency(const Item: Currency): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of Currency from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendCurrency(const Item: Currency): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of TDateTime into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadDateTime(var Item: TDateTime): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of TDateTime from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteDateTime(const Item: TDateTime): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of TDateTime from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendDateTime(const Item: TDateTime): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of AnsiChar into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadAnsiChar(var Item: AnsiChar): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of AnsiChar from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteAnsiChar(const Item: AnsiChar): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of AnsiChar from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendAnsiChar(const Item: AnsiChar): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of WideChar into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadWideChar(var Item: WideChar): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of WideChar from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteWideChar(const Item: WideChar): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of WideChar from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendWideChar(const Item: WideChar): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads a single instance of UnicodeChar into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadUnicodeChar(var Item: UnicodeChar): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of UnicodeChar from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteUnicodeChar(const Item: UnicodeChar): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of UnicodeChar from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendUnicodeChar(const Item: UnicodeChar): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads @code(NumChars) worth of AnsiChars into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadShortString(var Item: ShortString; const NumChars: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of ShortString from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteShortString(const Item: ShortString): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of ShortString from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendShortString(const Item: ShortString): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads @code(NumChars) worth of AnsiChars into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadAnsiString(var Item: AnsiString; const NumChars: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of AnsiString from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteAnsiString(const Item: AnsiString): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of AnsiString from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendAnsiString(const Item: AnsiString): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads @code(NumChars) worth of WideChars into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadWideString(var Item: WideString; const NumChars: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of WideString from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteWideString(const Item: WideString): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of WideString from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendWideString(const Item: WideString): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Reads @code(NumChars) worth of UnicodeChars into @code(Item) from the underlying file at the current @noAutoLink(position).} function ReadUnicodeString(var Item: UnicodeString; const NumChars: SizeInt): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of UnicodeString from @code(Item) to the underlying file at the current @noAutoLink(position), possibly overwriting existing data.} function WriteUnicodeString(const Item: UnicodeString): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Writes a single instance of UnicodeString from @code(Item) to the underlying file at the last @noAutoLink(position), behind any existing data.} function AppendUnicodeString(const Item: UnicodeString): PLightFileStream; {$IFNDEF DEBUG}inline;{$ENDIF} {Indicates directly whether or not the underlying file is open.} property IsOpen: Boolean read FOpen; end; implementation class function TLightFileStream.Create(const FileName: PChar): TLightFileStream; begin with Result do begin FFileName := FileName; FHandle := FileCreate(FFileName); FOpen := (FHandle <> THandle(-1)); FState := fsWriting; end; end; class function TLightFileStream.Open(const FileName: PChar; const InitialState: TFileState): TLightFileStream; begin with Result do begin FFileName := FileName; case InitialState of fsReading: FHandle := FileOpen(FFileName, fmOpenRead); fsWriting: FHandle := FileOpen(FFileName, fmOpenWrite); end; FOpen := (FHandle <> THandle(-1)); FState := InitialState; end; end; procedure TLightFileStream.Close; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if not FOpen then Exit(); {$ENDIF} FileClose(FHandle); end; function TLightFileStream.ChangeFileStateTo(const State: TFileState): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (State = FState) then Exit(@Self); {$ENDIF} FileClose(FHandle); case State of fsReading: FHandle := FileOpen(FFileName, fmOpenRead); fsWriting: FHandle := FileOpen(FFileName, fmOpenWrite); end; FOpen := (FHandle <> THandle(-1)); FState := State; Result := @Self; end; function TLightFileStream.SeekFromBeginning(const ToPosition: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if not FOpen then Exit(@Self); {$ENDIF} FileSeek(FHandle, ToPosition, fsFromBeginning); Result := @Self; end; function TLightFileStream.SeekFromCurrent(const ToPosition: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if not FOpen then Exit(@Self); {$ENDIF} FileSeek(FHandle, ToPosition, fsFromCurrent); Result := @Self; end; function TLightFileStream.SeekFromEnd(const ToPosition: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if not FOpen then Exit(@Self); {$ENDIF} FileSeek(FHandle, ToPosition, fsFromEnd); Result := @Self; end; function TLightFileStream.GetSize(out TheSize: SizeInt): PLightFileStream; var CurrentPosition: SizeInt; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if not FOpen then Exit(@Self); {$ENDIF} CurrentPosition := FileSeek(FHandle, 0, fsFromCurrent); TheSize := FileSeek(FHandle, 0, fsFromEnd); FileSeek(FHandle, CurrentPosition, fsFromBeginning); Result := @Self; end; function TLightFileStream.PutSize: SizeInt; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if not FOpen then Exit(0); {$ENDIF} GetSize(Result); end; function TLightFileStream.LogSize: PLightFileStream; var CurrentSize: SizeInt = 0; begin if not IsConsole then Exit(@Self); GetSize(CurrentSize); WriteLn('Size of TLightFileStream instance with file handle ', FHandle, ': ', CurrentSize); Result := @Self; end; function TLightFileStream.GetPosition(out ThePosition: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if not FOpen then Exit(@Self); {$ENDIF} ThePosition := FileSeek(FHandle, 0, fsFromCurrent); Result := @Self; end; function TLightFileStream.PutPosition: SizeInt; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if not FOpen then Exit(0); {$ENDIF} GetPosition(Result); end; function TLightFileStream.LogPosition: PLightFileStream; var CurrentPosition: SizeInt = 0; begin if not IsConsole then Exit(@Self); GetPosition(CurrentPosition); WriteLn('Position of TLightFileStream instance with file handle ', FHandle, ': ', CurrentPosition); Result := @Self; end; function TLightFileStream.Truncate: PLightFileStream; var CurrentSize: SizeInt; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if not FOpen then Exit(@Self); {$ENDIF} GetSize(CurrentSize); FileTruncate(FHandle, CurrentSize - (CurrentSize - FileSeek(FHandle, 0, fsFromCurrent))); Result := @Self; end; function TLightFileStream.ReadType<T>(var Item: T): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(T)); Result := @Self; end; function TLightFileStream.WriteType<T>(constref Item: T): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(T)); Result := @Self; end; function TLightFileStream.AppendType<T>(constref Item: T): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(T)); Result := @Self; end; function TLightFileStream.FillWith<T>(constref Value: T; const NumInstances: SizeUInt): PLightFileStream; var I: SizeUInt; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} for I := 1 to NumInstances do WriteType<T>(Value); Result := @Self; end; function TLightFileStream.ReadTypedBuffer<T>(var Buffer: T; const ItemCount: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Buffer, SizeOf(T) * ItemCount); Result := @Self; end; function TLightFileStream.WriteTypedBuffer<T>(constref Buffer: T; const ItemCount: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Buffer, SizeOf(T) * ItemCount); Result := @Self; end; function TLightFileStream.AppendTypedBuffer<T>(constref Buffer: T; const ItemCount: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Buffer, SizeOf(T) * ItemCount); Result := @Self; end; function TLightFileStream.ReadPointerBuffer(const Buffer: Pointer; const NumBytesToRead: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Buffer^, NumBytesToRead); Result := @Self; end; function TLightFileStream.WritePointerBuffer(const Buffer: Pointer; const NumBytesToWrite: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Buffer^, NumBytesToWrite); Result := @Self; end; function TLightFileStream.AppendPointerBuffer(const Buffer: Pointer; const NumBytesToWrite: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Buffer^, NumBytesToWrite); Result := @Self; end; function TLightFileStream.ReadByte(var Item: Byte): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(Byte)); Result := @Self; end; function TLightFileStream.WriteByte(const Item: Byte): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(Byte)); Result := @Self; end; function TLightFileStream.AppendByte(const Item: Byte): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(Byte)); Result := @Self; end; function TLightFileStream.ReadWord(var Item: Word): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(Word)); Result := @Self; end; function TLightFileStream.WriteWord(const Item: Word): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(Word)); Result := @Self; end; function TLightFileStream.AppendWord(const Item: Word): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(Word)); Result := @Self; end; function TLightFileStream.ReadLongWord(var Item: LongWord): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(LongWord)); Result := @Self; end; function TLightFileStream.WriteLongWord(const Item: LongWord): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(LongWord)); Result := @Self; end; function TLightFileStream.AppendLongWord(const Item: LongWord): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(LongWord)); Result := @Self; end; function TLightFileStream.ReadQWord(var Item: QWord): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(QWord)); Result := @Self; end; function TLightFileStream.WriteQWord(const Item: QWord): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(QWord)); Result := @Self; end; function TLightFileStream.AppendQWord(const Item: QWord): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(QWord)); Result := @Self; end; function TLightFileStream.ReadShortInt(var Item: ShortInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(ShortInt)); Result := @Self; end; function TLightFileStream.WriteShortInt(const Item: ShortInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(ShortInt)); Result := @Self; end; function TLightFileStream.AppendShortInt(const Item: ShortInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(ShortInt)); Result := @Self; end; function TLightFileStream.ReadSmallInt(var Item: SmallInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(SmallInt)); Result := @Self; end; function TLightFileStream.WriteSmallInt(const Item: SmallInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(SmallInt)); Result := @Self; end; function TLightFileStream.AppendSmallInt(const Item: SmallInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(SmallInt)); Result := @Self; end; function TLightFileStream.ReadLongInt(var Item: LongInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(LongInt)); Result := @Self; end; function TLightFileStream.WriteLongInt(const Item: LongInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(LongInt)); Result := @Self; end; function TLightFileStream.AppendLongInt(const Item: LongInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(LongInt)); Result := @Self; end; function TLightFileStream.ReadInt64(var Item: Int64): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(Int64)); Result := @Self; end; function TLightFileStream.WriteInt64(const Item: Int64): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(Int64)); Result := @Self; end; function TLightFileStream.AppendInt64(const Item: Int64): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(Int64)); Result := @Self; end; function TLightFileStream.ReadSingle(var Item: Single): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(Single)); Result := @Self; end; function TLightFileStream.WriteSingle(const Item: Single): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(Single)); Result := @Self; end; function TLightFileStream.AppendSingle(const Item: Single): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(Single)); Result := @Self; end; function TLightFileStream.ReadDouble(var Item: Double): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(Double)); Result := @Self; end; function TLightFileStream.WriteDouble(const Item: Double): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(Double)); Result := @Self; end; function TLightFileStream.AppendDouble(const Item: Double): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(Double)); Result := @Self; end; function TLightFileStream.ReadExtended(var Item: Extended): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(Extended)); Result := @Self; end; function TLightFileStream.WriteExtended(const Item: Extended): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(Extended)); Result := @Self; end; function TLightFileStream.AppendExtended(const Item: Extended): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(Extended)); Result := @Self; end; function TLightFileStream.ReadCurrency(var Item: Currency): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(Currency)); Result := @Self; end; function TLightFileStream.WriteCurrency(const Item: Currency): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(Currency)); Result := @Self; end; function TLightFileStream.AppendCurrency(const Item: Currency): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(Currency)); Result := @Self; end; function TLightFileStream.ReadDateTime(var Item: TDateTime): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(TDateTime)); Result := @Self; end; function TLightFileStream.WriteDateTime(const Item: TDateTime): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(TDateTime)); Result := @Self; end; function TLightFileStream.AppendDateTime(const Item: TDateTime): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(TDateTime)); Result := @Self; end; function TLightFileStream.ReadAnsiChar(var Item: AnsiChar): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(AnsiChar)); Result := @Self; end; function TLightFileStream.WriteAnsiChar(const Item: AnsiChar): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(AnsiChar)); Result := @Self; end; function TLightFileStream.AppendAnsiChar(const Item: AnsiChar): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(AnsiChar)); Result := @Self; end; function TLightFileStream.ReadWideChar(var Item: WideChar): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(WideChar)); Result := @Self; end; function TLightFileStream.WriteWideChar(const Item: WideChar): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(WideChar)); Result := @Self; end; function TLightFileStream.AppendWideChar(const Item: WideChar): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(WideChar)); Result := @Self; end; function TLightFileStream.ReadUnicodeChar(var Item: UnicodeChar): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item, SizeOf(UnicodeChar)); Result := @Self; end; function TLightFileStream.WriteUnicodeChar(const Item: UnicodeChar): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item, SizeOf(UnicodeChar)); Result := @Self; end; function TLightFileStream.AppendUnicodeChar(const Item: UnicodeChar): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item, SizeOf(UnicodeChar)); Result := @Self; end; function TLightFileStream.ReadShortString(var Item: ShortString; const NumChars: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item[1], NumChars); Result := @Self; end; function TLightFileStream.WriteShortString(const Item: ShortString): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item[1], Length(Item)); Result := @Self; end; function TLightFileStream.AppendShortString(const Item: ShortString): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item[1], Length(Item)); Result := @Self; end; function TLightFileStream.ReadAnsiString(var Item: AnsiString; const NumChars: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item[1], NumChars); Result := @Self; end; function TLightFileStream.WriteAnsiString(const Item: AnsiString): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item[1], Length(Item)); Result := @Self; end; function TLightFileStream.AppendAnsiString(const Item: AnsiString): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item[1], Length(Item)); Result := @Self; end; function TLightFileStream.ReadWideString(var Item: WideString; const NumChars: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item[1], SizeOf(WideChar) * NumChars); Result := @Self; end; function TLightFileStream.WriteWideString(const Item: WideString): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item[1], TEncoding.Unicode.GetByteCount(Item)); Result := @Self; end; function TLightFileStream.AppendWideString(const Item: WideString): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item[1], TEncoding.Unicode.GetByteCount(Item)); Result := @Self; end; function TLightFileStream.ReadUnicodeString(var Item: UnicodeString; const NumChars: SizeInt): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsReading) then Exit(@Self); {$ENDIF} FileRead(FHandle, Item[1], SizeOf(UnicodeChar) * NumChars); Result := @Self; end; function TLightFileStream.WriteUnicodeString(const Item: UnicodeString): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileWrite(FHandle, Item[1], TEncoding.Unicode.GetByteCount(Item)); Result := @Self; end; function TLightFileStream.AppendUnicodeString(const Item: UnicodeString): PLightFileStream; begin {$IFNDEF LIGHTFILESTREAM_NOCHECKS} if (not FOpen) or (FState <> fsWriting) then Exit(@Self); {$ENDIF} FileSeek(FHandle, 0, fsFromEnd); FileWrite(FHandle, Item[1], TEncoding.Unicode.GetByteCount(Item)); Result := @Self; end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* EXFLIST0.PAS 4.06 *} {*********************************************************} {**********************Description************************} {*Shows a TApdProtocol OnNextFile event handler that *} {* transmits a list of files. *} {*********************************************************} unit Exflist0; interface uses WinTypes, WinProcs, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, AdProtcl, AdPStat, AdPort, StdCtrls, AdExcept, OoMisc, ADTrmEmu; type TExampleFList = class(TForm) ApdComPort1: TApdComPort; ApdProtocol1: TApdProtocol; ApdProtocolStatus1: TApdProtocolStatus; ApdProtocolLog1: TApdProtocolLog; AddFiles: TButton; AdTerminal1: TAdTerminal; procedure ApdTerminal1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ApdProtocol1ProtocolError(CP: TObject; ErrorCode: Integer); procedure AddFilesClick(Sender: TObject); procedure ApdProtocol1ProtocolNextFile(CP: TObject; var FName: TPassString); private { Private declarations } FileList : TStringList; FileIndex : Word; public { Public declarations } constructor Create(AComponent : TComponent); override; end; var ExampleFList: TExampleFList; implementation {$R *.DFM} constructor TExampleFList.Create(AComponent : TComponent); begin inherited Create(AComponent); FileList := TStringList.Create; end; procedure TExampleFList.ApdTerminal1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_PRIOR then ApdProtocol1.StartTransmit else if Key = VK_NEXT then ApdProtocol1.StartReceive; end; procedure TExampleFList.ApdProtocol1ProtocolError(CP: TObject; ErrorCode: Integer); begin ShowMessage('Fatal protocol error: ' + ErrorMsg(ErrorCode)); end; procedure TExampleFList.AddFilesClick(Sender: TObject); begin FileList.Add('EXFLIST.DPR'); FileList.Add('EXFLIST0.PAS'); FileList.Add('EXFLIST0.DFM'); FileIndex := 0; AdTerminal1.WriteString('Files added!'); AdTerminal1.SetFocus; end; procedure TExampleFList.ApdProtocol1ProtocolNextFile(CP: TObject; var FName: TPassString); begin try FName := FileList[FileIndex]; Inc(FileIndex); except FName := ''; end; end; end.
unit RGBASingleDataSet; interface uses SingleDataSet; type TRGBASingleDataSet = class (TSingleDataSet) private FLength : integer; // Gets function GetData(_pos: integer): single; reintroduce; overload; function GetRed(_pos: integer): single; function GetGreen(_pos: integer): single; function GetBlue(_pos: integer): single; function GetAlpha(_pos: integer): single; // Sets procedure SetData(_pos: integer; _data: single); reintroduce; overload; procedure SetRed(_pos: integer; _data: single); procedure SetGreen(_pos: integer; _data: single); procedure SetBlue(_pos: integer; _data: single); procedure SetAlpha(_pos: integer; _data: single); protected // Gets function GetDataLength: integer; override; function GetLength: integer; override; function GetLast: integer; override; // Sets procedure SetLength(_size: integer); override; public // properties property Data[_pos: integer]:single read GetData write SetData; property Red[_pos: integer]:single read GetRed write SetRed; property Green[_pos: integer]:single read GetGreen write SetGreen; property Blue[_pos: integer]:single read GetBlue write SetBlue; property Alpha[_pos: integer]:single read GetAlpha write SetAlpha; end; implementation // Gets function TRGBASingleDataSet.GetData(_pos: integer): single; begin Result := FData[_pos]; end; function TRGBASingleDataSet.GetRed(_pos: integer): single; begin Result := FData[4*_pos]; end; function TRGBASingleDataSet.GetGreen(_pos: integer): single; begin Result := FData[(4*_pos)+1]; end; function TRGBASingleDataSet.GetBlue(_pos: integer): single; begin Result := FData[(4*_pos)+2]; end; function TRGBASingleDataSet.GetAlpha(_pos: integer): single; begin Result := FData[(4*_pos)+3]; end; function TRGBASingleDataSet.GetLength: integer; begin Result := FLength; end; function TRGBASingleDataSet.GetDataLength: integer; begin Result := High(FData) + 1; end; function TRGBASingleDataSet.GetLast: integer; begin Result := FLength - 1; end; // Sets procedure TRGBASingleDataSet.SetData(_pos: integer; _data: single); begin FData[_pos] := _data; end; procedure TRGBASingleDataSet.SetRed(_pos: integer; _data: single); begin FData[4*_pos] := _data; end; procedure TRGBASingleDataSet.SetGreen(_pos: integer; _data: single); begin FData[(4*_pos)+1] := _data; end; procedure TRGBASingleDataSet.SetBlue(_pos: integer; _data: single); begin FData[(4*_pos)+2] := _data; end; procedure TRGBASingleDataSet.SetAlpha(_pos: integer; _data: single); begin FData[(4*_pos)+3] := _data; end; procedure TRGBASingleDataSet.SetLength(_size: Integer); begin FLength := _size; System.SetLength(FData,_size*4); end; end.
object PerspectiveForm: TPerspectiveForm Left = 185 Top = 282 BorderStyle = bsDialog Caption = 'Perspective' ClientHeight = 145 ClientWidth = 375 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object Panel1: TPanel Left = 291 Top = 0 Width = 84 Height = 145 Align = alRight BevelInner = bvLowered TabOrder = 0 object OKBtn: TBitBtn Left = 5 Top = 8 Width = 75 Height = 25 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 0 OnClick = OKBtnClick Glyph.Data = { DE010000424DDE01000000000000760000002800000024000000120000000100 0400000000006801000000000000000000001000000000000000000000000000 80000080000000808000800000008000800080800000C0C0C000808080000000 FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333 3333333333333333333333330000333333333333333333333333F33333333333 00003333344333333333333333388F3333333333000033334224333333333333 338338F3333333330000333422224333333333333833338F3333333300003342 222224333333333383333338F3333333000034222A22224333333338F338F333 8F33333300003222A3A2224333333338F3838F338F33333300003A2A333A2224 33333338F83338F338F33333000033A33333A222433333338333338F338F3333 0000333333333A222433333333333338F338F33300003333333333A222433333 333333338F338F33000033333333333A222433333333333338F338F300003333 33333333A222433333333333338F338F00003333333333333A22433333333333 3338F38F000033333333333333A223333333333333338F830000333333333333 333A333333333333333338330000333333333333333333333333333333333333 0000} NumGlyphs = 2 end object ApplyBtn: TButton Left = 5 Top = 44 Width = 75 Height = 25 Caption = 'Apply' TabOrder = 1 OnClick = ApplyBtnClick end object BitBtn1: TBitBtn Left = 5 Top = 80 Width = 75 Height = 25 TabOrder = 2 OnClick = BitBtn1Click Kind = bkCancel end end object GroupBox1: TGroupBox Left = 6 Top = 3 Width = 275 Height = 138 Caption = 'Perspective' TabOrder = 1 object Label3: TLabel Left = 6 Top = 19 Width = 114 Height = 16 Caption = 'Field of view angle:' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object Label4: TLabel Left = 26 Top = 50 Width = 74 Height = 16 Caption = 'Aspect ratio:' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object Label1: TLabel Left = 40 Top = 77 Width = 39 Height = 16 Caption = 'zNear:' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object Label2: TLabel Left = 47 Top = 107 Width = 29 Height = 16 Caption = 'zFar:' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object ZFarEdit: TEdit Left = 120 Top = 107 Width = 65 Height = 21 TabOrder = 4 end object ZNearEdit: TEdit Left = 120 Top = 78 Width = 65 Height = 21 TabOrder = 3 end object AspectEdit: TEdit Left = 120 Top = 48 Width = 65 Height = 21 TabOrder = 1 end object FovEdit: TEdit Left = 120 Top = 19 Width = 65 Height = 21 TabOrder = 0 end object AutoBox: TCheckBox Left = 191 Top = 51 Width = 79 Height = 17 Caption = 'Auto aspect' TabOrder = 2 OnClick = AutoBoxClick end end end
namespace AwaitSample; interface uses System.Threading, System.Windows.Forms; type Program = assembly static class private class method OnThreadException(sender: Object; e: ThreadExceptionEventArgs); public class method Main(args: array of String); end; implementation /// <summary> /// The main entry point for the application. /// </summary> [STAThread] class method Program.Main(args: array of String); begin Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += OnThreadException; using lMainForm := new MainForm do Application.Run(lMainForm); end; /// <summary> /// Default exception handler /// </summary> class method Program.OnThreadException(sender: Object; e: ThreadExceptionEventArgs); begin MessageBox.Show(e.Exception.Message); end; end.
unit uSp_Class_Kat_AE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxTextEdit, cxLabel, cxControls, cxContainer, cxEdit, cxGroupBox, StdCtrls, cxButtons, st_ConstUnit, st_common_funcs, cxCurrencyEdit; type TfrmClass_Kat_AE = class(TForm) OKButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; NameLabel: TcxLabel; NameEdit: TcxTextEdit; PeopleLabel: TcxLabel; PlaceLabel: TcxLabel; PeopleEdit: TcxCurrencyEdit; PlaceEdit: TcxCurrencyEdit; procedure FormShow(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure NameEditKeyPress(Sender: TObject; var Key: Char); procedure PeopleEditKeyPress(Sender: TObject; var Key: Char); procedure PlaceEditKeyPress(Sender: TObject; var Key: Char); private procedure FormIniLanguage(); public PLanguageIndex :byte; end; var frmClass_Kat_AE: TfrmClass_Kat_AE; implementation {$R *.dfm} procedure TfrmClass_Kat_AE.FormIniLanguage(); begin //названия кнопок OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex]; CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex]; NameLabel.Caption := st_ConstUnit.st_NameLable[PLanguageIndex]; PeopleLabel.Caption := st_ConstUnit.st_KolvoLudey[PLanguageIndex]; PlaceLabel.Caption := st_ConstUnit.st_KolvoMest[PLanguageIndex]; end; procedure TfrmClass_Kat_AE.FormShow(Sender: TObject); begin FormIniLanguage(); NameEdit.SetFocus; end; procedure TfrmClass_Kat_AE.CancelButtonClick(Sender: TObject); begin Close; end; procedure TfrmClass_Kat_AE.OKButtonClick(Sender: TObject); begin if NameEdit.Text = '' then begin ShowMessage(PChar(st_ConstUnit.st_mess_FullName_need[PLanguageIndex])); NameEdit.SetFocus; exit; end; if not IntegerCheck(PeopleEdit.Text) then begin ShowMessage(PChar(st_ConstUnit.st_CountNotValid[PLanguageIndex])); PeopleEdit.SetFocus; exit; end; if not FloatCheck(PlaceEdit.Text) then begin ShowMessage(PChar(st_ConstUnit.st_MestNotValid[PLanguageIndex])); PlaceEdit.Setfocus; exit; end; ModalResult := mrOK; end; procedure TfrmClass_Kat_AE.NameEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 Then PeopleEdit.SetFocus; end; procedure TfrmClass_Kat_AE.PeopleEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 Then PlaceEdit.SetFocus; end; procedure TfrmClass_Kat_AE.PlaceEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 Then OkButton.SetFocus; end; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: CustomUIUnit.pas,v 1.19 2007/02/05 22:21:04 clootie Exp $ *----------------------------------------------------------------------------*) //-------------------------------------------------------------------------------------- // File: CustomUI.cpp // // Starting point for new Direct3D applications // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- {$I DirectX.inc} unit CustomUIUnit; interface uses Windows, SysUtils, StrSafe, DXTypes, Direct3D9, D3DX9, DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTmesh, DXUTSettingsDlg; {.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders {.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- var g_pFont: ID3DXFont; // Font for drawing text g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls g_pEffect: ID3DXEffect; // D3DX effect interface g_Mesh: CDXUTMesh; // Background mesh g_mView: TD3DXMatrixA16; g_Camera: CModelViewerCamera; // A model viewing camera g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog g_HUD: CDXUTDialog; // dialog for standard controls g_SampleUI: CDXUTDialog; // dialog for sample specific controls //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- const IDC_TOGGLEFULLSCREEN = 1; IDC_TOGGLEREF = 3; IDC_CHANGEDEVICE = 4; IDC_EDITBOX1 = 5; IDC_EDITBOX2 = 6; IDC_ENABLEIME = 7; IDC_DISABLEIME = 8; IDC_COMBOBOX = 9; IDC_STATIC = 10; IDC_OUTPUT = 12; IDC_SLIDER = 13; IDC_CHECKBOX = 14; IDC_CLEAREDIT = 15; IDC_RADIO1A = 16; IDC_RADIO1B = 17; IDC_RADIO1C = 18; IDC_RADIO2A = 19; IDC_RADIO2B = 20; IDC_RADIO2C = 21; IDC_LISTBOX = 22; IDC_LISTBOXM = 23; //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; procedure OnLostDevice(pUserContext: Pointer); stdcall; procedure OnDestroyDevice(pUserContext: Pointer); stdcall; procedure InitApp; function LoadMesh(pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; procedure RenderText; procedure CreateCustomDXUTobjects; procedure DestroyCustomDXUTobjects; implementation //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- procedure InitApp; var iY: Integer; pIMEEdit: CDXUTIMEEditBox; pCombo: CDXUTComboBox; i: Integer; wszText: WideString; begin // Initialize dialogs g_SettingsDlg.Init(g_DialogResourceManager); g_HUD.Init(g_DialogResourceManager); g_SampleUI.Init(g_DialogResourceManager); g_HUD.SetCallback(OnGUIEvent); iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2); // Inc(iY, 24); g_SampleUI.SetCallback(OnGUIEvent); g_SampleUI.SetFont(1, 'Comic Sans MS', 24, FW_NORMAL); g_SampleUI.SetFont(2, 'Courier New', 16, FW_NORMAL); // Static g_SampleUI.AddStatic(IDC_STATIC, 'This is a static control.', 0, 0, 200, 30 ); g_SampleUI.AddStatic(IDC_OUTPUT, 'This static control provides feedback for your action. It will change as you interact with the UI controls.', 20, 50, 620, 300 ); g_SampleUI.GetStatic(IDC_OUTPUT).TextColor:= D3DCOLOR_ARGB(255, 255, 0, 0); // Change color to red g_SampleUI.GetStatic(IDC_STATIC).TextColor:= D3DCOLOR_ARGB(255, 0, 255, 0); // Change color to green g_SampleUI.GetControl(IDC_OUTPUT).Element[0].dwTextFormat := DT_LEFT or DT_TOP or DT_WORDBREAK; g_SampleUI.GetControl(IDC_OUTPUT).Element[0].iFont := 2; g_SampleUI.GetControl(IDC_STATIC).Element[0].dwTextFormat := DT_CENTER or DT_VCENTER or DT_WORDBREAK; // Buttons g_SampleUI.AddButton(IDC_ENABLEIME, 'Enable (I)ME', 30, 390, 80, 35, Ord('I')); g_SampleUI.AddButton(IDC_DISABLEIME, 'Disable I(M)E', 30, 430, 80, 35, Ord('M')); // Edit box g_SampleUI.AddEditBox(IDC_EDITBOX1, 'Edit control with default styles. Type text here and press Enter', 20, 440, 600, 32); // IME-enabled edit box if SUCCEEDED(g_SampleUI.AddIMEEditBox(IDC_EDITBOX2, 'IME-capable edit control with custom styles. Type and press Enter', 20, 390, 600, 45, False, @pIMEEdit)) then begin pIMEEdit.Element[0].iFont := 1; pIMEEdit.Element[1].iFont := 1; pIMEEdit.Element[9].iFont := 1; pIMEEdit.Element[0].TextureColor.Init(D3DCOLOR_ARGB( 128, 255, 255, 255 )); // Transparent center pIMEEdit.BorderWidth := 7; pIMEEdit.TextColor := D3DCOLOR_ARGB(255, 64, 64, 64); pIMEEdit.CaretColor := D3DCOLOR_ARGB(255, 64, 64, 64); pIMEEdit.SelectedTextColor := D3DCOLOR_ARGB(255, 255, 255, 255); pIMEEdit.SelectedBackColor := D3DCOLOR_ARGB(255, 40, 72, 72); end; // Slider g_SampleUI.AddSlider(IDC_SLIDER, 200, 450, 200, 24, 0, 100, 50, False); // Checkbox g_SampleUI.AddCheckBox(IDC_CHECKBOX, 'This is a checkbox with hotkey. Press ''C'' to toggle the check state.', 170, 450, 350, 24, False, Ord('C'), False ); g_SampleUI.AddCheckBox(IDC_CLEAREDIT, 'This checkbox controls whether edit control text is cleared when Enter is pressed. (T)', 170, 460, 450, 24, False, Ord('T'), False ); // Combobox g_SampleUI.AddComboBox(IDC_COMBOBOX, 0, 0, 200, 24, Ord('O'), False, @pCombo); if (pCombo <> nil) then begin pCombo.SetDropHeight(100); pCombo.AddItem('Combobox item (O)', Pointer($11111111)); pCombo.AddItem('Placeholder (O)', Pointer($12121212)); pCombo.AddItem('One more (O)', Pointer($13131313)); pCombo.AddItem('I can''t get enough (O)', Pointer($14141414)); pCombo.AddItem('Ok, last one, I promise (O)', Pointer($15151515)); end; // Radio buttons g_SampleUI.AddRadioButton(IDC_RADIO1A, 1, 'Radio group 1 Amy (1)', 0, 50, 220, 24, False, Ord('1')); g_SampleUI.AddRadioButton(IDC_RADIO1B, 1, 'Radio group 1 Brian (2)', 0, 50, 220, 24, False, Ord('2')); g_SampleUI.AddRadioButton(IDC_RADIO1C, 1, 'Radio group 1 Clark (3)', 0, 50, 220, 24, False, Ord('3')); g_SampleUI.AddRadioButton(IDC_RADIO2A, 2, 'Single (4)', 0, 50, 90, 24, False, Ord('4')); g_SampleUI.AddRadioButton(IDC_RADIO2B, 2, 'Double (5)', 0, 50, 90, 24, False, Ord('5')); g_SampleUI.AddRadioButton(IDC_RADIO2C, 2, 'Triple (6)', 0, 50, 90, 24, False, Ord('6')); // List box g_SampleUI.AddListBox(IDC_LISTBOX, 30, 400, 200, 150, NORMAL); for i := 0 to 14 do begin wszText := WideFormat('Single-selection listbox item %d', [i]); g_SampleUI.GetListBox(IDC_LISTBOX).AddItem(PWideChar(wszText), Pointer(size_t(i))); end; g_SampleUI.AddListBox(IDC_LISTBOXM, 30, 400, 200, 150, MULTISELECTION); for i := 0 to 29 do begin wszText := WideFormat('Multi-selection listbox item %d', [i]); g_SampleUI.GetListBox(IDC_LISTBOXM).AddItem(PWideChar(wszText), Pointer(size_t(i))); end; end; //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by returning false. //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; var pD3D: IDirect3D9; begin Result:= False; // Skip backbuffer formats that don't support alpha blending pD3D := DXUTGetD3DObject; if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat)) then Exit; // Must support pixel shader 2.0 if (pCaps.PixelShaderVersion < D3DPS_VERSION(2, 0)) then Exit; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function is called immediately before a device is created to allow the // application to modify the device settings. The supplied pDeviceSettings parameter // contains the settings that the framework has selected for the new device, and the // application can make any desired changes directly to this structure. Note however that // DXUT will not correct invalid device settings so care must be taken // to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. //-------------------------------------------------------------------------------------- {static} var s_bFirstTime: Boolean = True; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; begin // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or (pCaps.VertexShaderVersion < D3DVS_VERSION(1,1)) then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING; // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. {$IFDEF DEBUG_VS} if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then with pDeviceSettings do begin BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING; BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE; BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING; end; {$ENDIF} {$IFDEF DEBUG_PS} pDeviceSettings.DeviceType := D3DDEVTYPE_REF; {$ENDIF} // For the first device created if its a REF device, optionally display a warning dialog box if s_bFirstTime then begin s_bFirstTime := False; if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning; end; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnDestroyDevice callback. //-------------------------------------------------------------------------------------- function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var dwShaderFlags: DWORD; str: array[0..MAX_PATH-1] of WideChar; vecEye, vecAt, vecUp: TD3DXVector3; begin Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; // Initialize the font Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, 'Arial', g_pFont); if V_Failed(Result) then Exit; // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. dwShaderFlags := D3DXFX_NOT_CLONEABLE; {$IFDEF DEBUG} // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_VS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; {$ENDIF} {$IFDEF DEBUG_PS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; {$ENDIF} // Read the D3DX effect file Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString('CustomUI.fx')); if V_Failed(Result) then Exit; // If this fails, there should be debug output as to // they the .fx file failed to compile Result := D3DXCreateEffectFromFileW(pd3dDevice, @str, nil, nil, dwShaderFlags, nil, g_pEffect, nil); if V_Failed(Result) then Exit; g_Mesh.CreateMesh(pd3dDevice, WideString('misc\cell.x')); // Setup the camera's view parameters vecEye:= D3DXVector3(0.0, 1.5, -7.0); vecAt:= D3DXVector3(0.0, 0.2, 0.0); vecUp:= D3DXVector3(0.0, 1.0, 0.0); g_Camera.SetViewParams(vecEye, vecAt); D3DXMatrixLookAtLH(g_mView, vecEye, vecAt, vecUp); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This function loads the mesh and ensures the mesh has normals; it also optimizes the // mesh for the graphics card's vertex cache, which improves performance by organizing // the internal triangle list for less cache misses. //-------------------------------------------------------------------------------------- function LoadMesh(pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; var pMesh: ID3DXMesh; str: array[0..MAX_PATH-1] of WideChar; rgdwAdjacency: PDWORD; pTempMesh: ID3DXMesh; begin // Load the mesh with D3DX and get back a ID3DXMesh*. For this // sample we'll ignore the X file's embedded materials since we know // exactly the model we're loading. See the mesh samples such as // "OptimizedMesh" for a more generic mesh loading example. Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, strFileName); if V_Failed(Result) then Exit; Result := D3DXLoadMeshFromX(@str, D3DXMESH_MANAGED, pd3dDevice, nil, nil, nil, nil, pMesh); if V_Failed(Result) then Exit; // rgdwAdjacency := nil; // Make sure there are normals which are required for lighting if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then begin Result := V(pMesh.CloneMeshFVF(pMesh.GetOptions, pMesh.GetFVF or D3DFVF_NORMAL, pd3dDevice, pTempMesh)); if Failed(Result) then Exit; Result := V(D3DXComputeNormals(pTempMesh, nil)); if Failed(Result) then Exit; SAFE_RELEASE(pMesh); pMesh := pTempMesh; end; // Optimize the mesh for this graphics card's vertex cache // so when rendering the mesh's triangle list the vertices will // cache hit more often so it won't have to re-execute the vertex shader // on those vertices so it will improve perf. try GetMem(rgdwAdjacency, SizeOf(DWORD)*pMesh.GetNumFaces*3); V(pMesh.GenerateAdjacency(1e-6,rgdwAdjacency)); V(pMesh.OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, nil, nil, nil)); FreeMem(rgdwAdjacency); ppMesh := pMesh; Result:= S_OK; except on EOutOfMemory do Result:= E_OUTOFMEMORY; end; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // reset, which will happen after a lost device scenario. This is the best location to // create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever // the device is lost. Resources created here should be released in the OnLostDevice // callback. //-------------------------------------------------------------------------------------- function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var fAspectRatio: Single; begin Result:= g_DialogResourceManager.OnResetDevice; if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnResetDevice; if V_Failed(Result) then Exit; Result:= S_OK; if (g_pFont <> nil) then Result := g_pFont.OnResetDevice; if V_Failed(Result) then Exit; if (g_pEffect <> nil) then Result:= g_pEffect.OnResetDevice; if V_Failed(Result) then Exit; // Create a sprite to help batch calls when drawing many lines of text Result := D3DXCreateSprite(pd3dDevice, g_pTextSprite); if V_Failed(Result) then Exit; // Setup the camera's projection parameters fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height; g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0); g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height); g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0); g_HUD.SetSize(170, 170); g_SampleUI.SetLocation(0, 0); g_SampleUI.SetSize(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height); g_SampleUI.GetControl(IDC_STATIC).SetSize(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height * 6 div 10); g_SampleUI.GetControl(IDC_OUTPUT).SetSize(pBackBufferSurfaceDesc.Width - 170, pBackBufferSurfaceDesc.Height div 4); g_SampleUI.GetControl(IDC_EDITBOX1).SetLocation(20, pBackBufferSurfaceDesc.Height - 230); g_SampleUI.GetControl(IDC_EDITBOX1).SetSize(pBackBufferSurfaceDesc.Width - 40, 32); g_SampleUI.GetControl(IDC_EDITBOX2).SetLocation(20, pBackBufferSurfaceDesc.Height - 280); g_SampleUI.GetControl(IDC_EDITBOX2).SetSize(pBackBufferSurfaceDesc.Width - 40, 45); g_SampleUI.GetControl(IDC_ENABLEIME).SetLocation(130, pBackBufferSurfaceDesc.Height - 80); g_SampleUI.GetControl(IDC_DISABLEIME).SetLocation(220, pBackBufferSurfaceDesc.Height - 80); g_SampleUI.GetControl(IDC_SLIDER).SetLocation(10, pBackBufferSurfaceDesc.Height - 140); g_SampleUI.GetControl(IDC_CHECKBOX).SetLocation(120, pBackBufferSurfaceDesc.Height - 50); g_SampleUI.GetControl(IDC_CLEAREDIT).SetLocation(120, pBackBufferSurfaceDesc.Height - 25); g_SampleUI.GetControl(IDC_COMBOBOX).SetLocation(20, pBackBufferSurfaceDesc.Height - 180); g_SampleUI.GetControl(IDC_RADIO1A).SetLocation(pBackBufferSurfaceDesc.Width - 160, 100); g_SampleUI.GetControl(IDC_RADIO1B).SetLocation(pBackBufferSurfaceDesc.Width - 160, 124); g_SampleUI.GetControl(IDC_RADIO1C).SetLocation(pBackBufferSurfaceDesc.Width - 160, 148); g_SampleUI.GetControl(IDC_RADIO2A).SetLocation(20, pBackBufferSurfaceDesc.Height - 100); g_SampleUI.GetControl(IDC_RADIO2B).SetLocation(20, pBackBufferSurfaceDesc.Height - 76); g_SampleUI.GetControl(IDC_RADIO2C).SetLocation(20, pBackBufferSurfaceDesc.Height - 52); g_SampleUI.GetControl(IDC_LISTBOX).SetLocation(pBackBufferSurfaceDesc.Width - 400, pBackBufferSurfaceDesc.Height - 180); g_SampleUI.GetControl(IDC_LISTBOX).SetSize(190, 96); g_SampleUI.GetControl(IDC_LISTBOXM).SetLocation(pBackBufferSurfaceDesc.Width - 200, pBackBufferSurfaceDesc.Height - 180); g_SampleUI.GetControl(IDC_LISTBOXM).SetSize(190, 124); g_Mesh.RestoreDeviceObjects(pd3dDevice); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var m: TD3DXMatrixA16; begin D3DXMatrixRotationY(m, D3DX_PI * fElapsedTime / 40.0); D3DXMatrixMultiply(g_mView, m, g_mView); end; //-------------------------------------------------------------------------------------- // This callback function will be called at the end of every frame to perform all the // rendering calls for the scene, and it will also be called if the window needs to be // repainted. After this function has returned, DXUT will call // IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain //-------------------------------------------------------------------------------------- procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var mat: TD3DXMatrixA16; mWorld: TD3DXMatrixA16; mView: TD3DXMatrixA16; mProj: TD3DXMatrixA16; mWorldViewProjection: TD3DXMatrixA16; cPasses: LongWord; pMesh: ID3DXMesh; p, m: Integer; begin // If the settings dialog is being shown, then // render it instead of rendering the app's scene if g_SettingsDlg.Active then begin g_SettingsDlg.OnRender(fElapsedTime); Exit; end; // Clear the render target and the zbuffer V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 50, 170), 1.0, 0)); // Render the scene if SUCCEEDED(pd3dDevice.BeginScene) then begin // Get the projection & view matrix from the camera class mWorld := g_Camera.GetWorldMatrix^; mProj := g_Camera.GetProjMatrix^; mView := g_mView; // mWorldViewProjection = mWorld * mView * mProj; D3DXMatrixMultiply(mat, mView, mProj); D3DXMatrixMultiply(mWorldViewProjection, mWorld, mat); // Update the effect's variables. Instead of using strings, it would // be more efficient to cache a handle to the parameter by calling // ID3DXEffect::GetParameterByName V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection)); V(g_pEffect.SetMatrix('g_mWorld', mWorld)); V(g_pEffect.SetFloat('g_fTime', fTime)); if (GetDXUTState.Caps.PixelShaderVersion < D3DPS_VERSION(1, 1)) then g_pEffect.SetTechnique('no_ps_HW') else g_pEffect.SetTechnique('RenderScene'); g_pEffect._Begin(@cPasses, 0); pMesh := g_Mesh.Mesh; for p := 0 to cPasses - 1 do begin g_pEffect.BeginPass(p); for m := 0 to g_Mesh.m_dwNumMaterials - 1 do begin g_pEffect.SetTexture('g_txScene', g_Mesh.m_pTextures[m]); g_pEffect.CommitChanges; pMesh.DrawSubset(m); end; g_pEffect.EndPass; end; g_pEffect._End; RenderText; V(g_HUD.OnRender(fElapsedTime)); V(g_SampleUI.OnRender(fElapsedTime)); V(pd3dDevice.EndScene); end; end; //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- procedure RenderText; var txtHelper: CDXUTTextHelper; begin // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr ); // If NULL is passed in as the sprite object, then it will work however the // pFont->DrawText() will not be batched together. Batching calls will improves performance. txtHelper:= CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15 ); try // Output statistics txtHelper._Begin; txtHelper.SetInsertionPos(5, 5); txtHelper.SetForegroundColor(D3DXCOLOR(1.0, 1.0, 0.0, 1.0)); txtHelper.DrawTextLine(DXUTGetFrameStats); txtHelper.DrawTextLine(DXUTGetDeviceStats); txtHelper.SetForegroundColor(D3DXCOLOR(1.0, 1.0, 1.0, 1.0)); // Draw help txtHelper.SetForegroundColor(D3DXCOLOR(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('Press ESC to quit'); txtHelper._End; finally txtHelper.Free; end; end; //-------------------------------------------------------------------------------------- // Before handling window messages, DXUT passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then DXUT will not process this message. //-------------------------------------------------------------------------------------- function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; begin Result:= 0; // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; if g_SettingsDlg.IsActive then begin g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); Exit; end; // Give the dialogs a chance to handle the message first pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam); end; //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; begin end; //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; var wszOutput: array[0..1023] of WideChar; pItem: PDXUTComboBoxItem; pListItem: PDXUTListBoxItem ; nSelected: Integer; begin FillChar(wszOutput, SizeOf(wszOutput), 0); case nControlID of IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen; IDC_TOGGLEREF: DXUTToggleREF; IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active; IDC_ENABLEIME: begin CDXUTIMEEditBox.EnableImeSystem(True); g_SampleUI.GetStatic(IDC_OUTPUT).Text := 'You clicked the ''Enable IME'' button.'#10'IME text input is enabled for IME-capable edit controls.'; end; IDC_DISABLEIME: begin CDXUTIMEEditBox.EnableImeSystem(False); g_SampleUI.GetStatic(IDC_OUTPUT).Text := 'You clicked the ''Disable IME'' button.'#10'IME text input is disabled for IME-capable edit controls.'; end; IDC_EDITBOX1, IDC_EDITBOX2: case nEvent of EVENT_EDITBOX_STRING: begin StringCchFormat(wszOutput, 1024, 'You have pressed Enter in edit control (ID %u).'#10'The content of the edit control is:'#10'"%s"', [nControlID, CDXUTEditBox(pControl).Text]); g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; // Clear the text if needed if g_SampleUI.GetCheckBox(IDC_CLEAREDIT).Checked then CDXUTEditBox(pControl).Text := ''; end; EVENT_EDITBOX_CHANGE: begin StringCchFormat(wszOutput, 1024, 'You have changed the content of an edit control (ID %u).'#10'It is now:'#10'"%s"', [nControlID, CDXUTEditBox(pControl).Text]); g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; end; IDC_SLIDER: begin StringCchFormat(wszOutput, 1024, 'You adjusted the slider control.'#10'The new value reported is %d', [CDXUTSlider(pControl).Value]); g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; IDC_CHECKBOX: begin StringCchFormat(wszOutput, 1024, 'You %s the upper check box.', [IfThen(CDXUTCheckBox(pControl).Checked, 'checked', 'cleared')]); g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; IDC_CLEAREDIT: begin StringCchFormat(wszOutput, 1024, 'You %s the lower check box.'#10'Now edit controls will %s', [IfThen(CDXUTCheckBox(pControl).Checked, 'checked', 'cleared'), IfThen(CDXUTCheckBox(pControl).Checked, 'be cleared when you press Enter to send the text', 'retain the text context when you press Enter to send the text')]); g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; IDC_COMBOBOX: begin pItem := CDXUTComboBox(pControl).GetSelectedItem; if Assigned(pItem) then begin {todo: Fill BUG REPORT to Borland -> D7 - WideFormatBuf('%p') - @CvtPointer: - CvtInt -> CvtIntW Check: if FPC have the similiar bug? Well it's still not fixed in D9, althrow been corrected in TNT Unicode Controls long time ago :-((( } StringCchFormat(wszOutput, 1024, 'You selected a new item in the combobox.'#10 + 'The new item is "%s" and the associated data value is 0x%x', //was: '0x%p' and Pointer(pItem.pData) {$IFDEF FPC} [PWideChar(pItem.strText), pItem.pData]); {$ELSE} [pItem.strText, Integer(pItem.pData)]); {$ENDIF} g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; end; IDC_RADIO1A, IDC_RADIO1B, IDC_RADIO1C: begin StringCchFormat(wszOutput, 1024, 'You selected a new radio button in the UPPER radio group.'#10'The new button is "%s"', [CDXUTRadioButton(pControl).Text]); g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; IDC_RADIO2A, IDC_RADIO2B, IDC_RADIO2C: begin StringCchFormat(wszOutput, 1024, 'You selected a new radio button in the LOWER radio group.'#10'The new button is "%s"', [CDXUTRadioButton(pControl).Text]); g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; IDC_LISTBOX: case nEvent of EVENT_LISTBOX_ITEM_DBLCLK: begin pListItem := CDXUTListBox(pControl).GetItem(CDXUTListBox(pControl).GetSelectedIndex(-1)); StringCchFormat(wszOutput, 1024, 'You double clicked an item in the left list box. The item is'#10'"%s"', {$IFDEF FPC} [IfThen(pListItem<>nil, PWideChar(pListItem.strText), '')]); {$ELSE} [IfThen(pListItem<>nil, pListItem.strText, '')]); {$ENDIF} g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; EVENT_LISTBOX_SELECTION: begin StringCchFormat(wszOutput, 1024, 'You changed the selection in the left list box. The selected item is %d', [CDXUTListBox(pControl).GetSelectedIndex]); g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; end; IDC_LISTBOXM: case nEvent of EVENT_LISTBOX_ITEM_DBLCLK: begin pListItem := CDXUTListBox(pControl).GetItem(CDXUTListBox(pControl).GetSelectedIndex(-1)); StringCchFormat(wszOutput, 1024, 'You double clicked an item in the right list box. The item is'#10'"%s"', {$IFDEF FPC} [IfThen(pListItem<>nil, PWideChar(pListItem.strText), '')]); {$ELSE} [IfThen(pListItem<>nil, pListItem.strText, '')]); {$ENDIF} g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; EVENT_LISTBOX_SELECTION: begin StringCchFormat(wszOutput, 1024, 'You changed the selection in the right list box. The selected item(s) are'#10, []); nSelected := -1; nSelected := CDXUTListBox(pControl).GetSelectedIndex(nSelected); while (nSelected <> -1) do begin {$IFDEF FPC} StringCchFormat(PWideChar(wszOutput + 2*lstrlenW(wszOutput)), 1024 - lstrlenW(wszOutput), '%d,', [nSelected]); {$ELSE} StringCchFormat(PWideChar(wszOutput + lstrlenW(wszOutput)), 1024 - lstrlenW(wszOutput), '%d,', [nSelected]); {$ENDIF} nSelected := CDXUTListBox(pControl).GetSelectedIndex(nSelected); end; // Remove the trailing comma if one exists. if (wszOutput[lstrlenW(wszOutput)-1] = ',') then wszOutput[lstrlenW(wszOutput)-1] := #0; g_SampleUI.GetStatic(IDC_OUTPUT).Text := wszOutput; end; end; end; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // entered a lost state and before IDirect3DDevice9::Reset is called. Resources created // in the OnResetDevice callback should be released here, which generally includes all // D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for // information about lost devices. //-------------------------------------------------------------------------------------- procedure OnLostDevice(pUserContext: Pointer); stdcall; begin g_DialogResourceManager.OnLostDevice; g_SettingsDlg.OnLostDevice; g_Mesh.InvalidateDeviceObjects; if (g_pFont <> nil) then g_pFont.OnLostDevice; if (g_pEffect <> nil) then g_pEffect.OnLostDevice; SAFE_RELEASE(g_pTextSprite); end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnCreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- procedure OnDestroyDevice(pUserContext: Pointer); stdcall; begin g_DialogResourceManager.OnDestroyDevice; g_SettingsDlg.OnDestroyDevice; if Assigned(g_Mesh) then g_Mesh.DestroyMesh; SAFE_RELEASE(g_pEffect); SAFE_RELEASE(g_pFont); end; procedure CreateCustomDXUTobjects; begin g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog g_Mesh:= CDXUTMesh.Create; // Background mesh g_Camera:= CModelViewerCamera.Create; // A model viewing camera g_HUD:= CDXUTDialog.Create; // dialog for standard controls g_SampleUI:= CDXUTDialog.Create; // dialog for sample specific controls end; procedure DestroyCustomDXUTobjects; begin FreeAndNil(g_DialogResourceManager); FreeAndNil(g_SettingsDlg); FreeAndNil(g_Mesh); //Clootie: Mesh will be destroyed in DXState.Free... FreeAndNil(g_Camera); FreeAndNil(g_HUD); FreeAndNil(g_SampleUI); end; end.
unit Main; interface uses Winapi.OpenGL, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, System.UITypes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus, Vcl.ComCtrls, Vcl.StdCtrls, GLScene, GLGraph, GLObjects, GLWin32Viewer, GLColor, GLTexture, GLVectorGeometry, GLNavigator, GLCoordinates, GLCrossPlatform, GLBaseClasses, GridImportfn, Commasplit; type TForm1 = class(TForm) MainMenu1: TMainMenu; miFile: TMenuItem; miClose: TMenuItem; pnlSurferView: TPanel; GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCamera: TGLCamera; DummyCube: TGLDummyCube; HeightField1: TGLHeightField; N1: TMenuItem; miOpenSurfer: TMenuItem; OpenSurfer: TOpenDialog; lblVerticalExaggeration: TLabel; Edit1: TEdit; TrackBarz: TTrackBar; lblCameraHeight: TLabel; Label1: TLabel; TrackBarx: TTrackBar; GLLightSource1: TGLLightSource; TrackBary: TTrackBar; Label2: TLabel; lblColour1: TLabel; lblMaxColour: TLabel; pnlMin: TPanel; pnlMax: TPanel; ColorDialog: TColorDialog; miHelp: TMenuItem; miAbout: TMenuItem; procedure miCloseClick(Sender: TObject); procedure miOpenSurferClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Edit1Change(Sender: TObject); procedure TrackBarzChange(Sender: TObject); procedure TrackBarxChange(Sender: TObject); procedure TrackBaryChange(Sender: TObject); procedure pnlMaxClick(Sender: TObject); procedure pnlMinClick(Sender: TObject); procedure miAboutClick(Sender: TObject); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); private vscale: single; mdx, mdy: Integer; glColour1: TGLColor; glColour2: TGLColor; contourdata: TContourGridData; procedure ContourZ(const X, Y: single; var z: single; var color: TColorVector; var texPoint: TTexPoint); procedure OpenSurferFile(sFileName: string); public end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin glColour1 := TGLColor.Create(nil); glColour1.AsWinColor := pnlMin.color; glColour2 := TGLColor.Create(nil); glColour2.AsWinColor := pnlMax.color; contourdata := TContourGridData.Create; vscale := 10.0; end; { ** provides z as a function of x and y. This uses the xscale and yscale vectors to "lookup" the correct indices of the points array } procedure TForm1.ContourZ(const X, Y: single; var z: single; var color: TColorVector; var texPoint: TTexPoint); const SMALL = 0.01; var c, i, j: Integer; r: single; begin { ** probably not necessary - just sets to the last row and column } i := contourdata.ny - 1; j := contourdata.nx - 1; for c := 0 to contourdata.nx - 1 do begin if abs(X - contourdata.xscale[c]) < SMALL then begin j := c; break; end; end; for c := 0 to contourdata.ny - 1 do begin if abs(Y - contourdata.yscale[c]) < SMALL then begin i := c; break; end; end; { ** r is a ratio between 0 and 1. Use this to ramp the colour between colour1 and colour2 } r := (contourdata.points[i, j] - contourdata.zlo) / (contourdata.zrange); VectorLerp(glColour1.color, glColour2.color, r, color); { ** apply z but remember the vertical exaggeration } z := contourdata.points[i, j] * vscale; end; procedure TForm1.OpenSurferFile(sFileName: string); begin { ** the LoadSurferGrid function will try and open a surfer grid file in its 3 different formats - surfer grid, gs binary, gs ascii } if (contourdata.LoadSurferGrid(sFileName) = 0) then begin with HeightField1 do begin { ** the 0.1 * step is to compensate for rounding } xSamplingScale.Min := 0.0; xSamplingScale.Max := contourdata.XRange + 0.1 * contourdata.XStep; xSamplingScale.Origin := 0.0; xSamplingScale.Step := contourdata.XStep; { ** the 0.1 * step is to compensate for rounding } ySamplingScale.Min := 0.0; ySamplingScale.Max := contourdata.yrange + 0.1 * contourdata.yStep; ySamplingScale.Origin := 0.0; ySamplingScale.Step := contourdata.yStep; OnGetHeight := ContourZ; Visible := true; { ** in this demo the grid is translated so xmin,ymin = 0,0. To display in real world coordinates just move the HeightField Position accordingly } end; { ** move the dummycube, and camera, to a reasonable location } DummyCube.Position.X := 0.5 * contourdata.XRange; DummyCube.Position.Y := 0.5 * contourdata.yrange; DummyCube.Position.z := contourdata.zhi; GLCamera.TransformationChanged; { ** init the trackbars } with TrackBarx do begin Max := 2 * Round(contourdata.XRange); Min := -Max; Position := 0; end; with TrackBary do begin Max := 2 * Round(contourdata.yrange); Min := -Max; Position := 0; end; with TrackBarz do begin Min := -Round(2 * contourdata.zlo); Max := Round(2 * contourdata.zhi); Position := Max; end; { ** apply the vertical scale } Edit1Change(nil); end; end; procedure TForm1.miCloseClick(Sender: TObject); begin self.close; end; procedure TForm1.miOpenSurferClick(Sender: TObject); begin if OpenSurfer.Execute then OpenSurferFile(OpenSurfer.Filename); end; procedure TForm1.FormDestroy(Sender: TObject); begin glColour1.free; glColour2.free; contourdata.free; end; procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin GLCamera.AdjustDistanceToTarget(Power(1.1, WheelDelta / 120)); end; // ------ TForm1.GLSceneViewer1MouseDown --------------------------------------- procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mdx := X; mdy := Y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var dx, dy: Integer; begin // calculate delta since last move or last mousedown dx := mdx - X; dy := mdy - Y; mdx := X; mdy := Y; if ssLeft in Shift then GLCamera.MoveAroundTarget(dy, dx); end; // ------ TForm1.Edit1Change --------------------------------------------------- procedure TForm1.Edit1Change(Sender: TObject); var ve: single; code: Integer; begin val(Edit1.text, ve, code); If (code = 0) and (ve > 0.0) then begin vscale := ve; with TrackBarz do begin Min := -2 * Round(ve * contourdata.zlo); Max := 2 * Round(ve * contourdata.zhi); Position := Max; end; HeightField1.StructureChanged; // update end; GLSceneViewer1.SetFocus; end; procedure TForm1.TrackBarzChange(Sender: TObject); begin DummyCube.Position.z := TrackBarz.Position; GLCamera.TransformationChanged; end; // ------ TForm1.TrackBarxChange ----------------------------------------------- procedure TForm1.TrackBarxChange(Sender: TObject); begin DummyCube.Position.X := TrackBarx.Position; GLCamera.TransformationChanged; end; procedure TForm1.TrackBaryChange(Sender: TObject); begin DummyCube.Position.Y := TrackBary.Position; GLCamera.TransformationChanged; end; procedure TForm1.pnlMaxClick(Sender: TObject); begin ColorDialog.color := pnlMax.color; if ColorDialog.Execute then begin pnlMax.color := ColorDialog.color; glColour2.AsWinColor := pnlMax.color; HeightField1.StructureChanged; end; end; procedure TForm1.pnlMinClick(Sender: TObject); begin ColorDialog.color := pnlMin.color; if ColorDialog.Execute then begin pnlMin.color := ColorDialog.color; glColour1.AsWinColor := pnlMin.color; HeightField1.StructureChanged; end; end; procedure TForm1.miAboutClick(Sender: TObject); begin MessageDlg('GridGLS Viewer' + #13 + #10 + 'based on Aaron Hochwimmer Surfer Grid Parser' + #13 + #10 + 'Built with GLScene: http://www.glscene.org.', mtWarning, [mbOK], 0); end; // ============================================================================= end.
unit SDUComCtrls; // TSDListView: An extended TListView // Inherits from TListView, but includes functionality when in vsReport mode // such that events are available when columns are resized, and supports // ordering columns // TSDProgressBarIndeterminate: An indeterminate progress bar // ! IMPORTANT ! // Requires XP manifest in order to work! interface uses ComCtrls, Classes, Messages, windows, CommCtrl, Controls; type PNMHEADER = ^TNMHEADER; {$EXTERNALSYM tagNMHEADER} tagNMHEADER = packed record hdr: NMHDR; iItem: integer; iButton: integer; pitem: PHdItem;//PHDITEM; end; TNMHEADER = tagNMHEADER; {$EXTERNALSYM NMHEADER} NMHEADER = tagNMHEADER; TColumnResizeEvent = procedure (Sender: TListview; ColumnIdx: integer; NewWidth: integer) of object; TColumnSortEvent = procedure (Sender: TListview; ColumnIdx: integer) of object; TColumnSortDirection = (csdAscending, csdDescending); TSDListView = class(TListView) private FOnBeforeColumnSort: TColumnSortEvent; FOnAfterColumnSort: TColumnSortEvent; FOnBeforeColumnResize: TColumnResizeEvent; FOnColumnResize: TColumnResizeEvent; FOnAfterColumnResize: TColumnResizeEvent; procedure DoOnBeforeColumnSort(ColumnIdx: integer); procedure DoOnAfterColumnSort(ColumnIdx: integer); procedure DoOnBeforeColumnResize(ColumnIdx: integer; newWidth: integer); procedure DoOnColumnResize(ColumnIdx: integer; newWidth: integer); procedure DoOnAfterColumnResize(ColumnIdx: integer; newWidth: integer); procedure DoColumnSort(Column: TListColumn); procedure WMNotify(var Message: TWMNotify); message WM_NOTIFY; function GetRealColWidth(col: TListColumn): integer; procedure SetRealColWidth(col: TListColumn; newWidth: integer); protected FColumnToSort: integer; procedure ColClick(Column: TListColumn); override; // specify -1 (HEADER_ROW) as y to get column headers function GetCellText(x, y: integer): string; procedure SetCellText(x, y: integer; newText: string); function GetSelectedIdx(): integer; public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; function AddCol(colCaption: string): TListColumn; function InsertRow(position: integer; rowFields: TStringList; data: Pointer = nil): TListItem; overload; function InsertRow(position: integer; rowFields: array of const; data: Pointer = nil): TListItem; overload; function AppendRow(rowFields: TStringList; data: Pointer = nil): TListItem; overload; function AppendRow(rowFields: array of const; data: Pointer = nil): TListItem; overload; procedure ResizeColumns(); procedure _ColumnSortCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); virtual; procedure SwapItems(a: integer; b: integer); procedure InvertSelection(); procedure SelectedMoveUp(); procedure SelectedMoveDown(); function GetFocused(): integer; function GetColumnByID(colID: integer): TListColumn; function GetColumnDisplayIndex(col: TListColumn): integer; property CellText[x: integer; y: integer]: string read GetCellText write SetCellText; property RealColWidth[col: TListColumn]: integer read GetRealColWidth write SetRealColWidth; // Note: This takes/return a TListColumn.Index value - NOT a column index // returned by GetColumnDisplayIndex(...) function GetSelectedColumn(): integer; procedure SetSelectedColumn(ColIdx: integer); published property OnBeforeColumnSort: TColumnSortEvent read FOnBeforeColumnSort write FOnBeforeColumnSort; property OnAfterColumnSort: TColumnSortEvent read FOnAfterColumnSort write FOnAfterColumnSort; property OnBeforeColumnResize: TColumnResizeEvent read FOnBeforeColumnResize write FOnBeforeColumnResize; property OnColumnResize: TColumnResizeEvent read FOnColumnResize write FOnColumnResize; property OnAfterColumnResize: TColumnResizeEvent read FOnAfterColumnResize write FOnAfterColumnResize; // Note: This returns the *lowest* index number of all sected items. // Returns -1 if none selected property SelectedIdx: integer read GetSelectedIdx; property SelectedColumn: integer read GetSelectedColumn write SetSelectedColumn nodefault; end; TSDProgressBarIndeterminate = class(TProgressBar) private FMarquee: boolean; FMarqueeUpdateDelay: integer; public procedure CreateParams(var Params: TCreateParams); override; function GetMarquee(): boolean; procedure SetMarquee(newValue: boolean); published constructor Create(AOwner: TComponent); override; destructor Destroy(); override; property Marquee: boolean read GetMarquee write SetMarquee; property MarqueeUpdate: integer read FMarqueeUpdateDelay write FMarqueeUpdateDelay; end; procedure Register; implementation uses SysUtils, SDUGeneral; const HEADER_ROW = -1; PBS_MARQUEE = $08; PBM_SETMARQUEE = (WM_USER + 10); // Windows XP and later only LVM_SETSELECTEDCOLUMN = LVM_FIRST + 140; LVM_GETSELECTEDCOLUMN = LVM_FIRST + 174; procedure Register; begin RegisterComponents('SDeanUtils', [TSDListView]); RegisterComponents('SDeanUtils', [TSDProgressBarIndeterminate]); end; constructor TSDListView.Create(AOwner: TComponent); begin inherited; ViewStyle := vsReport; FColumnToSort := 0; end; destructor TSDListView.Destroy(); begin inherited; end; procedure TSDListView.ColClick(Column: TListColumn); begin DoOnBeforeColumnSort(Column.Index); DoColumnSort(Column); inherited; DoOnAfterColumnSort(Column.Index); end; function DefaultListViewColumnSort(Item1, Item2: TListItem; lParam: Integer): Integer; stdcall; begin if Assigned(TListView(Item1.ListView).OnCompare) then begin TListView(Item1.ListView).OnCompare(Item1.ListView, Item1, Item2, lParam, Result); end else begin TSDListView(Item1.ListView)._ColumnSortCompare(Item1.ListView, Item1, Item2, lParam, Result); end; end; // Note: This returns a TListColumn.Index value - NOT a column index returned // by GetColumnDisplayIndex(...) function TSDListView.GetSelectedColumn(): integer; begin Result := SendMessage( self.Handle, LVM_GETSELECTEDCOLUMN, 0, 0 ); end; // Note: This takes a TListColumn.Index value - NOT a column index returned // by GetColumnDisplayIndex(...) procedure TSDListView.SetSelectedColumn(ColIdx: integer); begin SendMessage( self.Handle, LVM_SETSELECTEDCOLUMN, ColIdx, 0 ); end; procedure TSDListView.DoColumnSort(Column: TListColumn); begin FColumnToSort := Column.ID; // Make sorted column have shaded background SetSelectedColumn(Column.Index); // Don't call AlphaSort(...) - that uses the default sort; instead do what // AlphaSort(...) does, but call *our* version if HandleAllocated then begin ListView_SortItems(Handle, @DefaultListViewColumnSort, 0); end; { if (FColumnToSort = 0) then begin if (Tag = 1) then begin Tag := 0; end else begin Tag := 1; end; end else begin if (Column.Tag = csdDescending) then begin Column.Tag := csdAscending; end else begin Column.Tag := csdDescending; end; end; } if (Column.Tag = ord(csdDescending)) then begin Column.Tag := ord(csdAscending); end else begin Column.Tag := ord(csdDescending); end; end; procedure TSDListView._ColumnSortCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); function _CompareText(str1, str2: string): integer; { var retval: integer; } begin { retval := 0; str1 := uppercase(str1); str2 := uppercase(str2); if (str1 > str2) then begin retval := 1; end else if (str1 < str2) then begin retval := -1; end; Result := retval; } // This uses the same method to sort as TTreeView does when sorting it's // nodes Result := lstrcmp(PChar(str1), PChar(str2)); end; function CompareNumbers(ext1, ext2: extended): integer; var retval: integer; begin retval := 0; if (ext1 > ext2) then begin retval := 1; end else if (ext1 < ext2) then begin retval := -1; end; Result := retval; end; var str1, str2: string; ext1, ext2: Extended; sortDirection: TColumnSortDirection; areNumbers: boolean; sortCol: TListColumn; sortColOrderIdx: integer; begin sortCol := self.GetColumnByID(FColumnToSort); // We use GetColumnDisplayIndex(...) and NOT sortCol.Index because the user // could have reordered the columns, in which case the column order is // changed, but the SubItems (and the item.Caption) don't sortColOrderIdx := GetColumnDisplayIndex(sortCol); if (sortColOrderIdx = 0) then begin Str1 := Item1.Caption; Str2 := Item2.Caption; end else begin Str1 := Item1.SubItems.Strings[sortColOrderIdx-1]; Str2 := Item2.SubItems.Strings[sortColOrderIdx-1]; end; sortDirection := TColumnSortDirection(sortCol.Tag); try ext1 := StrToFloat(Str1); ext2 := StrToFloat(Str2); areNumbers := TRUE; if (sortDirection = csdAscending) then begin Compare := CompareNumbers(ext1, ext2); end else begin Compare := CompareNumbers(ext2, ext1); end; except areNumbers := FALSE; end; if not(areNumbers) then begin if (sortDirection = csdAscending) then begin // Don't use Delphi's CompareText(...) - that places "_ABC" after "ABC" // - we want it before Compare := _CompareText(Str1, Str2); end else begin // Don't use Delphi's CompareText(...) - that places "_ABC" after "ABC" // - we want it before Compare := _CompareText(Str2, Str1); end; end; end; function TSDListView.AddCol(colCaption: string): TListColumn; var newCol: TListColumn; begin newCol := Columns.Add(); newCol.Caption := colCaption; // Note: DON'T set AutoSize to TRUE; otherwise if the user resizes the // dialog, any user set column widths will be reverted // newCol.AutoSize := TRUE; Result := newCol; end; function TSDListView.InsertRow(position: integer; rowFields: array of const; data: Pointer = nil): TListItem; var i: integer; stlArgs: TStringList; begin stlArgs:= TStringList.Create(); try for i:=low(rowFields) to high(rowFields) do begin case rowFields[i].vtype of vtInteger : stlArgs.Add(inttostr(rowFields[i].vinteger)); vtBoolean : stlArgs.Add(SDUBoolToStr(rowFields[i].vboolean)); vtChar : stlArgs.Add(rowFields[i].vchar); vtExtended : stlArgs.Add(FloatToStr(rowFields[i].VExtended^)); vtString : stlArgs.Add(rowFields[i].VString^); vtPointer : stlArgs.Add('0x'+inttohex(integer(rowFields[i].VPointer), 8)); vtPChar : stlArgs.Add(rowFields[i].VPChar); vtObject : stlArgs.Add(rowFields[i].VObject.Classname); vtClass : stlArgs.Add(rowFields[i].VClass.Classname); vtWideChar : stlArgs.Add(rowFields[i].VWideChar); vtPWideChar : stlArgs.Add(rowFields[i].VPWideChar); vtAnsiString : stlArgs.Add(PChar(rowFields[i].VAnsiString)); // vtCurrency : stlArgs.Add(rowFields[i].VCurrency); vtVariant : stlArgs.Add(rowFields[i].VVariant^); // vtInterface : stlArgs.Add(rowFields[i].VInterface); vtWideString : stlArgs.Add(PWideChar(rowFields[i].VWideString)); vtInt64 : stlArgs.Add(inttostr(int64(rowFields[i].VInt64))); else stlArgs.Add('0x'+inttohex(rowFields[i].vtype, 2)); end; end; Result := InsertRow(position, stlArgs, data); finally stlArgs.Free(); end; end; function TSDListView.InsertRow(position: integer; rowFields: TStringList; data: Pointer = nil): TListItem; var item: TListItem; stlPaddedFields: TStringList; i: integer; begin stlPaddedFields:= TStringList.Create(); try stlPaddedFields.Assign(rowFields); // Pad with blank strings so we have enough for each column for i:=stlPaddedFields.count to Columns.count do begin stlPaddedFields.Add(''); end; item := Items.Insert(position); item.data := data; item.Caption := stlPaddedFields[0]; // Start from 1 here; we've already done the initial caption for i:=1 to (stlPaddedFields.count - 1) do begin item.SubItems.Add(stlPaddedFields[i]); end; finally stlPaddedFields.Free(); end; Result := item; end; function TSDListView.AppendRow(rowFields: TStringList; data: Pointer = nil): TListItem; begin Result := InsertRow(Items.count, rowFields, data); end; function TSDListView.AppendRow(rowFields: array of const; data: Pointer = nil): TListItem; begin Result := InsertRow(Items.count, rowFields, data); end; procedure TSDListView.ResizeColumns(); const // Resize the columns such that they're as wide as the widest item/subitem // text RESIZE_EXCL_HEADER = -1; // Resize the columns such that they're as wide as the column header text/the // widest item/subitem RESIZE_INCL_HEADER = -2; var i: integer; prevAutoSize: boolean; begin for i:=0 to (Columns.count -1) do begin prevAutoSize := Column[i].AutoSize; Column[i].AutoSize := TRUE; Column[i].width := RESIZE_INCL_HEADER; // Revert AutoSize... Column[i].AutoSize := prevAutoSize; end; end; function TSDListView.GetCellText(x, y: integer): string; var itemText: string; item: TListItem; begin if (y = HEADER_ROW) then begin itemText := Columns[x].caption end else begin item := Items[y]; if (x = 0) then begin itemText := item.caption; end else begin itemText := item.SubItems.Strings[x-1]; end; end; Result := itemText; end; procedure TSDListView.SetCellText(x, y: integer; newText: string); var item: TListItem; begin if (y = HEADER_ROW) then begin Columns[x].caption := newText; end else begin item := Items[y]; if (x = 0) then begin item.caption := newText; end else begin item.SubItems.Strings[x-1] := newText; end; end; end; procedure TSDListView.SwapItems(a: integer; b: integer); var tempLI: TListItem; begin Items.BeginUpdate; try tempLI := TListItem.Create(Items); try tempLI.Assign(Items.Item[a]); Items.Item[a].Assign(Items.Item[b]); Items.Item[b].Assign(tempLI); finally tempLI.Free; end; finally Items.EndUpdate end; end; function TSDListView.GetFocused(): integer; var i: integer; retval: integer; begin retval := -1; for i:=0 to (items.count-1) do begin if Items[i].focused then begin retval := i; break; end; end; Result := retval; end; function TSDListView.GetColumnByID(colID: integer): TListColumn; var retval: TListColumn; tmpItem: TCollectionItem; begin retval := nil; tmpItem := self.Columns.FindItemID(colID); if (tmpItem <> nil) then begin retval := self.Columns.Items[tmpItem.Index]; end; // Alternativly (using casting) // retval := TListColumn(self.Columns.FindItemID(colID)); Result := retval; end; // This retrieves the ordered index of the specified column // e.g. If FullDrag is TRUE, and the user moves the 2nd column between the 4th // and 5th columns, this will return 2, while the (previously 2nd) column // will have its .Index property set to 4 function TSDListView.GetColumnDisplayIndex(col: TListColumn): integer; var colOrder: array of integer; colCollection: TListColumns; begin colCollection := TListColumns(col.Collection); SetLength(colOrder, colCollection.Count); ListView_GetColumnOrderArray( colCollection.Owner.Handle, colCollection.Count, PInteger(colOrder) ); Result := colOrder[col.Index]; end; function TSDListView.GetRealColWidth(col: TListColumn): integer; var widthColIdx: integer; begin // This is UGLY. // We can't just use this: // colLayout.Width := listCol.Width; // If columns have been moved around, listCol.Width returns the *wrong* // *columns* *width*! // See also Delphi fault # 30134 at: // http://qc.embarcadero.com/wc/qcmain.aspx?d=30134 // (URL correct as of 1st July 2009) // Apparently, this has been fixed in Delphi 2009; in which case it // should be possible to use listCol.Width directly with that version // of Delphi (and later) widthColIdx := GetColumnDisplayIndex(col); Result := self.Columns[widthColIdx].Width; end; procedure TSDListView.SetRealColWidth(col: TListColumn; newWidth: integer); begin // Set directly - unlike how GetRealColWidth(...) works col.Width := newwidth; end; procedure TSDListView.InvertSelection(); var i: integer; begin for i:=0 to (Items.Count - 1) do begin Items[i].Selected := not(Items[i].Selected); end; end; procedure TSDListView.SelectedMoveUp(); var i: integer; focusedIdx: integer; selStateOther: boolean; begin focusedIdx:= GetFocused(); // Start from 1 - can't move the first item up for i:=1 to (items.count-1) do begin if items[i].selected then begin selStateOther:= items[i-1].selected; SwapItems(i, (i-1)); items[i].selected := selStateOther; items[i-1].selected := TRUE; end; end; if ( ((focusedIdx-1) >= 0) and ((focusedIdx-1) <= (Items.count - 1)) ) then begin items[focusedIdx-1].focused := TRUE; end; end; procedure TSDListView.SelectedMoveDown(); var i: integer; focusedIdx: integer; selStateOther: boolean; begin focusedIdx:= GetFocused(); // -2 because we can't move the last item down for i:=(items.count-2) downto 0 do begin if items[i].selected then begin selStateOther:= items[i+1].selected; SwapItems(i, (i+1)); items[i].selected := selStateOther; items[i+1].selected := TRUE; end; end; if ( ((focusedIdx+1) >= 0) and ((focusedIdx+1) <= (Items.count - 1)) ) then begin items[focusedIdx+1].focused := TRUE; end; end; procedure TSDListView.WMNotify(var Message: TWMNotify); var header: PNMHEADER; newWidth: integer; begin case Message.NMHdr.code of // HDN_BEGINTRACK: HDN_BEGINTRACKA, HDN_BEGINTRACKW, // HDN_TRACK: HDN_TRACKA, HDN_TRACKW, // HDN_ENDTRACK, HDN_ENDTRACKA, HDN_ENDTRACKW: begin newWidth := -1; header := PNMHEADER(Message.NMHdr); if (header.pitem <> nil) then begin if ((header.pItem.mask and HDI_WIDTH) <> 0) then begin newWidth := header.pItem.cxy; end; end; case Message.NMHdr.code of // HDN_BEGINTRACK: HDN_BEGINTRACKA, HDN_BEGINTRACKW: begin DoOnBeforeColumnResize(header.iItem, newWidth); end; // HDN_TRACK: HDN_TRACKA, HDN_TRACKW: begin DoOnColumnResize(header.iItem, newWidth); end; // HDN_ENDTRACK, HDN_ENDTRACKA, HDN_ENDTRACKW: begin DoOnAfterColumnResize(header.iItem, newWidth); end; end; end; end; inherited; end; procedure TSDListView.DoOnBeforeColumnSort(ColumnIdx: integer); begin if assigned(FOnBeforeColumnSort) then begin FOnBeforeColumnSort(self, ColumnIdx); end; end; procedure TSDListView.DoOnAfterColumnSort(ColumnIdx: integer); begin if assigned(FOnAfterColumnSort) then begin FOnAfterColumnSort(self, ColumnIdx); end; end; procedure TSDListView.DoOnBeforeColumnResize(ColumnIdx: integer; newWidth: integer); begin if assigned(FOnBeforeColumnResize) then begin FOnBeforeColumnResize(self, ColumnIdx, newWidth); end; end; procedure TSDListView.DoOnColumnResize(ColumnIdx: integer; newWidth: integer); begin if assigned(FOnColumnResize) then begin FOnColumnResize(self, ColumnIdx, newWidth); end; end; procedure TSDListView.DoOnAfterColumnResize(ColumnIdx: integer; newWidth: integer); begin if assigned(FOnAfterColumnResize) then begin FOnAfterColumnResize(self, ColumnIdx, newWidth); end; end; function TSDListView.GetSelectedIdx(): integer; var retval: integer; i: integer; begin retval := -1; for i:=0 to (self.Items.count - 1) do begin if self.Items[i].Selected then begin retval := i; break; end; end; Result := retval; end; procedure TSDProgressBarIndeterminate.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or PBS_MARQUEE; end; constructor TSDProgressBarIndeterminate.Create(AOwner: TComponent); begin inherited; FMarqueeUpdateDelay := 200; FMarquee := FALSE; end; destructor TSDProgressBarIndeterminate.Destroy(); begin inherited; end; function TSDProgressBarIndeterminate.GetMarquee(): boolean; begin Result := FMarquee; end; procedure TSDProgressBarIndeterminate.SetMarquee(newValue: boolean); var lParam: integer; begin lParam := 0; if newValue then begin lParam := 1; end; FMarquee := newValue; SendMessage(self.Handle, PBM_SETMARQUEE, lParam, FMarqueeUpdateDelay); end; END.
unit uFornecedorDAOClient; interface uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Fornecedor, DBXJSONReflect; type TFornecedorDAOClient = class(TDSAdminClient) private FListCommand: TDBXCommand; FNextCodigoCommand: TDBXCommand; FInsertCommand: TDBXCommand; FUpdateCommand: TDBXCommand; FDeleteCommand: TDBXCommand; FFindByCodigoCommand: TDBXCommand; FListagemFornecedoresCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function List: TDBXReader; function NextCodigo: string; function Insert(Fornecedor: TFornecedor): Boolean; function Update(Fornecedor: TFornecedor): Boolean; function Delete(Fornecedor: TFornecedor): Boolean; function FindByCodigo(Codigo: string): TFornecedor; function ListagemFornecedores(CodigoProduto: string): TDBXReader; end; implementation function TFornecedorDAOClient.List: TDBXReader; begin if FListCommand = nil then begin FListCommand := FDBXConnection.CreateCommand; FListCommand.CommandType := TDBXCommandTypes.DSServerMethod; FListCommand.Text := 'TFornecedorDAO.List'; FListCommand.Prepare; end; FListCommand.ExecuteUpdate; Result := FListCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner); end; function TFornecedorDAOClient.NextCodigo: string; begin if FNextCodigoCommand = nil then begin FNextCodigoCommand := FDBXConnection.CreateCommand; FNextCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod; FNextCodigoCommand.Text := 'TFornecedorDAO.NextCodigo'; FNextCodigoCommand.Prepare; end; FNextCodigoCommand.ExecuteUpdate; Result := FNextCodigoCommand.Parameters[0].Value.GetWideString; end; function TFornecedorDAOClient.Insert(Fornecedor: TFornecedor): Boolean; begin if FInsertCommand = nil then begin FInsertCommand := FDBXConnection.CreateCommand; FInsertCommand.CommandType := TDBXCommandTypes.DSServerMethod; FInsertCommand.Text := 'TFornecedorDAO.Insert'; FInsertCommand.Prepare; end; if not Assigned(Fornecedor) then FInsertCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FInsertCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FInsertCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Fornecedor), True); if FInstanceOwner then Fornecedor.Free finally FreeAndNil(FMarshal) end end; FInsertCommand.ExecuteUpdate; Result := FInsertCommand.Parameters[1].Value.GetBoolean; end; function TFornecedorDAOClient.Update(Fornecedor: TFornecedor): Boolean; begin if FUpdateCommand = nil then begin FUpdateCommand := FDBXConnection.CreateCommand; FUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod; FUpdateCommand.Text := 'TFornecedorDAO.Update'; FUpdateCommand.Prepare; end; if not Assigned(Fornecedor) then FUpdateCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FUpdateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FUpdateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Fornecedor), True); if FInstanceOwner then Fornecedor.Free finally FreeAndNil(FMarshal) end end; FUpdateCommand.ExecuteUpdate; Result := FUpdateCommand.Parameters[1].Value.GetBoolean; end; function TFornecedorDAOClient.Delete(Fornecedor: TFornecedor): Boolean; begin if FDeleteCommand = nil then begin FDeleteCommand := FDBXConnection.CreateCommand; FDeleteCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDeleteCommand.Text := 'TFornecedorDAO.Delete'; FDeleteCommand.Prepare; end; if not Assigned(Fornecedor) then FDeleteCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FDeleteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FDeleteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Fornecedor), True); if FInstanceOwner then Fornecedor.Free finally FreeAndNil(FMarshal) end end; FDeleteCommand.ExecuteUpdate; Result := FDeleteCommand.Parameters[1].Value.GetBoolean; end; function TFornecedorDAOClient.FindByCodigo(Codigo: string): TFornecedor; begin if FFindByCodigoCommand = nil then begin FFindByCodigoCommand := FDBXConnection.CreateCommand; FFindByCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod; FFindByCodigoCommand.Text := 'TFornecedorDAO.FindByCodigo'; FFindByCodigoCommand.Prepare; end; FFindByCodigoCommand.Parameters[0].Value.SetWideString(Codigo); FFindByCodigoCommand.ExecuteUpdate; if not FFindByCodigoCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDBXClientCommand(FFindByCodigoCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFornecedor(FUnMarshal.UnMarshal(FFindByCodigoCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FFindByCodigoCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TFornecedorDAOClient.ListagemFornecedores(CodigoProduto: string): TDBXReader; begin if FListagemFornecedoresCommand = nil then begin FListagemFornecedoresCommand := FDBXConnection.CreateCommand; FListagemFornecedoresCommand.CommandType := TDBXCommandTypes.DSServerMethod; FListagemFornecedoresCommand.Text := 'TFornecedorDAO.ListagemFornecedores'; FListagemFornecedoresCommand.Prepare; end; FListagemFornecedoresCommand.Parameters[0].Value.SetWideString(CodigoProduto); FListagemFornecedoresCommand.ExecuteUpdate; Result := FListagemFornecedoresCommand.Parameters[1].Value.GetDBXReader(FInstanceOwner); end; constructor TFornecedorDAOClient.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TFornecedorDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TFornecedorDAOClient.Destroy; begin FreeAndNil(FListCommand); FreeAndNil(FNextCodigoCommand); FreeAndNil(FInsertCommand); FreeAndNil(FUpdateCommand); FreeAndNil(FDeleteCommand); FreeAndNil(FFindByCodigoCommand); FreeAndNil(FListagemFornecedoresCommand); inherited; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFDeleteCookiesCallback; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefDeleteCookiesCallbackOwn = class(TCefBaseRefCountedOwn, ICefDeleteCookiesCallback) protected procedure OnComplete(numDeleted: Integer); virtual; abstract; public constructor Create; virtual; end; TCefFastDeleteCookiesCallback = class(TCefDeleteCookiesCallbackOwn) protected FCallback: TCefDeleteCookiesCallbackProc; procedure OnComplete(numDeleted: Integer); override; public constructor Create(const callback: TCefDeleteCookiesCallbackProc); reintroduce; end; TCefCustomDeleteCookiesCallback = class(TCefDeleteCookiesCallbackOwn) protected FChromiumBrowser : TObject; procedure OnComplete(numDeleted: Integer); override; public constructor Create(const aChromiumBrowser : TObject); reintroduce; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFChromium; procedure cef_delete_cookie_callback_on_complete(self: PCefDeleteCookiesCallback; num_deleted: Integer); stdcall; begin with TCefDeleteCookiesCallbackOwn(CefGetObject(self)) do OnComplete(num_deleted); end; // TCefDeleteCookiesCallbackOwn constructor TCefDeleteCookiesCallbackOwn.Create; begin inherited CreateData(SizeOf(TCefDeleteCookiesCallback)); with PCefDeleteCookiesCallback(FData)^ do on_complete := cef_delete_cookie_callback_on_complete; end; // TCefFastDeleteCookiesCallback constructor TCefFastDeleteCookiesCallback.Create(const callback: TCefDeleteCookiesCallbackProc); begin inherited Create; FCallback := callback; end; procedure TCefFastDeleteCookiesCallback.OnComplete(numDeleted: Integer); begin FCallback(numDeleted) end; // TCefCustomDeleteCookiesCallback constructor TCefCustomDeleteCookiesCallback.Create(const aChromiumBrowser : TObject); begin inherited Create; FChromiumBrowser := aChromiumBrowser; end; procedure TCefCustomDeleteCookiesCallback.OnComplete(numDeleted: Integer); begin if (FChromiumBrowser <> nil) and (FChromiumBrowser is TChromium) then TChromium(FChromiumBrowser).Internal_CookiesDeleted(numDeleted); end; end.
{=============================================================================== RadiantPlaylistForm Unit Radiant Shapes - Demo Source Unit Copyright © 2012-2014 by Raize Software, Inc. All Rights Reserved. Modification History ------------------------------------------------------------------------------ 1.0 (29 Oct 2014) * Initial release. ===============================================================================} {$MESSAGE 'Copy the RadiantPlaylist.xml file to directory containing the RadiantPlaylist application'} unit RadiantPlaylistForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Objects, FMX.Layouts, FMX.Graphics, FMX.Controls, FMX.Controls.Presentation, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView, FMX.ListView.Adapters.Base, Data.DB, Datasnap.DBClient; type TfrmPlaylist = class(TForm) lvwPlaylist: TListView; cdsPlaylist: TClientDataSet; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure lvwPlaylistUpdateObjects(const Sender: TObject; const AItem: TListViewItem); private { Private declarations } procedure LoadPlaylist; procedure RatingChangeHandler( const Sender: TObject; const Item: TListViewItem; NewRating: Integer ); public { Public declarations } end; var frmPlaylist: TfrmPlaylist; implementation {$R *.fmx} uses Radiant.Shapes; const sRating = 'Rating'; {==========================} {== TListItemRatingStars ==} {==========================} type TListItemRatingChangeEvent = procedure( const Sender: TObject; const Item: TListViewItem; NewRating: Integer ) of object; TListItemRatingStars = class( TListItemEmbeddedControl ) private FOwner: TListItem; FRating: Integer; FStars: array[ 1..5 ] of TRadiantStar; FOnChange: TListItemRatingChangeEvent; procedure SetRating( Value: Integer ); procedure StarClicked( Sender: TObject ); procedure StarDblClicked( Sender: TObject ); protected procedure Render( const Canvas: TCanvas; const DrawItemIndex: Integer; const DrawStates: TListItemDrawStates; const Resources: TListItemStyleResources; const Params: TListItemDrawable.TParams; const SubPassNo: Integer = 0); override; procedure Change; dynamic; public constructor Create( const AOwner: TListItem ); override; destructor Destroy; override; property Rating: Integer read FRating write SetRating; property OnChange: TListItemRatingChangeEvent read FOnChange write FOnChange; end; {==================================} {== TListItemRatingStars Methods ==} {==================================} constructor TListItemRatingStars.Create( const AOwner: TListItem ); var I: Integer; X, Y: Single; begin inherited; FOwner := AOwner; Align := TListItemAlign.Trailing; VertAlign := TListItemAlign.Center; Width := 125; Height := 30; Rating := 0; X := 0; Y := 0; for I := 1 to 5 do begin FStars[ I ] := TRadiantStar.Create( nil ); FStars[ I ].Parent := Container; FStars[ I ].Name := 'Star' + IntToStr( I ); FStars[ I ].Position.X := X + ( I - 1 ) * 25; FStars[ I ].Position.Y := Y; FStars[ I ].Width := 30; FStars[ I ].Height := 30; FStars[ I ].Fill.Kind := TBrushKind.None; FStars[ I ].Stroke.Color := TAlphaColors.LightGray; FStars[ I ].Stroke.Thickness := 1.5; FStars[ I ].Tag := I; FStars[ I ].OnClick := StarClicked; FStars[ I ].OnDblClick := StarDblClicked; end; end; destructor TListItemRatingStars.Destroy; var I: Integer; begin for I := 1 to 5 do FStars[ I ].Free; inherited; end; procedure TListItemRatingStars.SetRating( Value: Integer ); var I: Integer; begin if FRating <> Value then begin FRating := Value; for I := 1 to 5 do begin if FRating >= I then begin FStars[ I ].Fill.Kind := TBrushKind.Solid; FStars[ I ].Fill.Color := TAlphaColors.Gold; FStars[ I ].Stroke.Color := TAlphaColors.DarkOrange; end else begin FStars[ I ].Fill.Kind := TBrushKind.None; FStars[ I ].Stroke.Color := TAlphaColors.Lightgray; end; end; Change; TListViewItem( FOwner ).Invalidate; end; end; procedure TListItemRatingStars.Render( const Canvas: TCanvas; const DrawItemIndex: Integer; const DrawStates: TListItemDrawStates; const Resources: TListItemStyleResources; const Params: TListItemDrawable.TParams; const SubPassNo: Integer = 0 ); begin inherited; //!! Canvas.DrawRect( ); end; procedure TListItemRatingStars.Change; begin if Assigned( FOnChange ) then FOnChange( Self, TListViewItem( FOwner ), Rating ); end; procedure TListItemRatingStars.StarClicked( Sender: TObject ); begin if Sender is TRadiantStar then begin Rating := TRadiantStar( Sender ).Tag; end; end; procedure TListItemRatingStars.StarDblClicked( Sender: TObject ); begin if Sender is TRadiantStar then begin Rating := 0; end; end; {==========================} {== TfrmPlaylist Methods ==} {==========================} procedure TfrmPlaylist.FormCreate(Sender: TObject); begin LoadPlaylist; end; procedure TfrmPlaylist.LoadPlaylist; var I: Integer; Item: TListViewItem; begin cdsPlaylist.LoadFromFile( '.\RadiantPlayList.xml' ); for I := 1 to cdsPlaylist.RecordCount do begin Item := lvwPlayList.Items.Add; Item.Text := cdsPlaylist.FieldByName( 'Song' ).AsString; Item.Detail := cdsPlaylist.FieldByName( 'Artist' ).AsString; Item.Accessory := TAccessoryType.Detail; Item.Tag := cdsPlayList.FieldByName( 'Rating' ).AsInteger; cdsPlaylist.Next; end; end; procedure TfrmPlaylist.lvwPlaylistUpdateObjects(const Sender: TObject; const AItem: TListViewItem); var ItemRatingStars: TListItemRatingStars; begin ItemRatingStars := TListItemRatingStars.Create( AItem ); ItemRatingStars.Name := sRating; ItemRatingStars.Rating := AItem.Tag; ItemRatingStars.OnChange := RatingChangeHandler; end; procedure TfrmPlaylist.FormClose(Sender: TObject; var Action: TCloseAction); begin cdsPlaylist.MergeChangeLog; cdsPlaylist.SaveToFile( '.\RadiantPlayList.xml', TDataPacketFormat.dfXML ); end; procedure TfrmPlaylist.RatingChangeHandler( const Sender: TObject; const Item: TListViewItem; NewRating: Integer ); begin cdsPlaylist.Filter := 'Song=' + QuotedStr( Item.Text ); cdsPlaylist.Filtered := True; cdsPlaylist.Edit; cdsPlaylist.FieldByName( 'Rating' ).AsInteger := NewRating; cdsPlaylist.Post; cdsPlaylist.Filtered := False; end; end.
unit uTicketRequisitionList; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Frm_BillListBase, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxHyperLinkEdit, Menus, cxLookAndFeelPainters, ADODB, ActnList, DBClient, jpeg, Series, TeEngine, TeeProcs, Chart, DbChart, StdCtrls, cxButtons, cxMaskEdit, cxDropDownEdit, Buttons, cxPC, cxContainer, cxTextEdit, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, ExtCtrls; type TTicketRequisitionList = class(TFM_BillListBase) procedure FormCreate(Sender: TObject); procedure btn_NewBillClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure Open_Bill(KeyFields: String; KeyValues: String); override; //非供应链单据删除,审核方法 function NotScmBillDelBill(BillFID:string;var ErrMsg:string):Boolean;override; function NotScmBillAuditBill(BillFID:string;var ErrMsg:string):Boolean;override; function NotScmBillUnAuditBill(BillFID:string;var ErrMsg:string):Boolean;override; end; var TicketRequisitionList: TTicketRequisitionList; implementation uses uOtherBillBaseEditFrm,uTicketRequisition,FrmCliDM; {$R *.dfm} { TTicketRequisitionList } procedure TTicketRequisitionList.Open_Bill(KeyFields, KeyValues: String); var tmpEditForm : TOtherEditFormPar; begin inherited; tmpEditForm :=TOtherEditFormPar.Create; tmpEditForm.BillFID := KeyValues; tmpEditForm.ListDataset := cdsList; OpenOtherBillEditFrom(TicketRequisitionFrm,TTicketRequisitionFrm,tmpEditForm); end; procedure TTicketRequisitionList.FormCreate(Sender: TObject); begin Self.Bill_Sign := 'CT_BIL_TICKETREQUISITION'; Self.BillKeyFields := 'FID'; Self.FBillTypeFID := BillConst.BILLTYPE_TR; sIniBillFlag := 'TR' ; sSPPack :='SALE'; FNotScmBill := True; inherited; end; procedure TTicketRequisitionList.btn_NewBillClick(Sender: TObject); begin inherited; Open_Bill('FID',''); end; function TTicketRequisitionList.NotScmBillAuditBill(BillFID: string; var ErrMsg: string): Boolean; var SQL_1:string; begin SQL_1 := 'update CT_BIL_TICKETREQUISITION set CFBILLSTATUS=4 ,FAUDITDATE=sysdate,FAUDITORID=' +Quotedstr(UserInfo.LoginUser_FID)+' where fid='+Quotedstr(BillFID); Result := CliDM.E_ExecSQLArrays(SQL_1,'','','','','','','',ErrMsg) end; function TTicketRequisitionList.NotScmBillDelBill(BillFID: string; var ErrMsg: string): Boolean; var SQL_1,SQL_2,SQL_3:string; begin SQL_1 := 'delete from CT_BIL_TICKETREQUISITION where fid='+Quotedstr(BillFID); SQL_2 := 'delete from CT_BIL_TICKETREQUISITIONENTRY where FPARENTID='+Quotedstr(BillFID); SQL_3 := 'delete from CT_BIL_TICKETRSDE where FPARENTID='+Quotedstr(BillFID); Result := CliDM.E_ExecSQLArrays(SQL_1,SQL_2,SQL_3,'','','','','',ErrMsg); end; function TTicketRequisitionList.NotScmBillUnAuditBill(BillFID: string; var ErrMsg: string): Boolean; var SQL_1:string; begin SQL_1 := 'update CT_BIL_TICKETREQUISITION set CFBILLSTATUS=1 ,FAUDITDATE=null,FAUDITORID='''' where fid='+Quotedstr(BillFID); Result := CliDM.E_ExecSQLArrays(SQL_1,'','','','','','','',ErrMsg) end; end.
unit ConverterClass; interface type TTemperature = class private FCelsius : Extended; protected procedure Assign(AValue: TTemperature); function GetCelsius: Extended; procedure SetCelsius(AValue : Extended); function GetKelvin: Extended; procedure SetKelvin(AValue : Extended); function GetFahrenheit: Extended; procedure SetFahrenheit(AValue : Extended); public constructor Create; property Temperature : TTemperature write Assign; property Celsius : Extended read GetCelsius write SetCelsius; property Fahrenheit : Extended read GetFahrenheit write SetFahrenheit; property Kelvin: Extended read GetKelvin write SetKelvin; end; implementation // from Celsius to Celsius // Fahrenheit [F] = [C] x 9/5 + 32 [C] = ([F] - 32) x 5/9 // Kelvin [K] = [C] + 273.15 [C] = [K] - 273.15 // Rankine [R] = ([C] + 273.15) x 9/5 [C] = ([R] - 491.67) x 5/9 constructor TTemperature.Create; begin FCelsius := 0; end; function TTemperature.GetCelsius: Extended; begin Result := FCelsius; end; procedure TTemperature.SetCelsius(AValue: Extended); begin FCelsius := AValue; end; function TTemperature.GetKelvin: Extended; begin Result := FCelsius + 273.15; end; procedure TTemperature.SetKelvin(AValue: Extended); begin FCelsius := AValue - 273.15; end; function TTemperature.GetFahrenheit: Extended; begin Result := FCelsius * 9 / 5 + 32; end; procedure TTemperature.SetFahrenheit(AValue: Extended); begin FCelsius := (AValue - 32) * 5 / 9; end; procedure TTemperature.Assign(AValue: TTemperature); begin FCelsius := AValue.FCelsius; end; end.
unit FormPreferences; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, StdCtrls, ComCtrls, ExtCtrls, Registry; type TFrmPreferences = class(TForm) GbOptionsBox: TGroupBox; Pref_List: TTreeView; pcOptions: TPageControl; FileAssociationTab: TTabSheet; cbAssociate: TCheckBox; gbAssociationIcon: TGroupBox; IconPrev: TImage; IconID: TTrackBar; btnApply: TButton; Palette_tab: TTabSheet; cbUseNameSpecificPalettes: TCheckBox; lblTiberianSunPalette: TLabel; lblRedAlert2Palette: TLabel; cbRedAlert2Palette: TComboBoxEx; cbTiberianSunPalette: TComboBoxEx; Bevel2: TBevel; pnlTop: TPanel; ImgPreferences: TImage; lblPreferencesDescription: TLabel; lblPreferences: TLabel; Bevel3: TBevel; pnlBottom: TPanel; btnOK: TButton; btnCancel: TButton; Rendering_tab: TTabSheet; cbFPSCap: TCheckBox; Measures_tab: TTabSheet; lblLeptonSize: TLabel; EdLeptonSize: TEdit; rbCustomLeptonSize: TRadioButton; rbMiggyLeptonSize: TRadioButton; rbStuLeptonSize: TRadioButton; lblBulletSize: TLabel; EdBulletSize: TEdit; procedure EdLeptonSizeChange(Sender: TObject); procedure rbMiggyLeptonSizeClick(Sender: TObject); procedure rbStuLeptonSizeClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnApplyClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure IconIDChange(Sender: TObject); procedure Pref_ListClick(Sender: TObject); procedure Pref_ListKeyPress(Sender: TObject; var Key: Char); procedure Pref_ListKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbUseNameSpecificPalettesClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } IconPath: String; procedure ExtractIcon; procedure GetSettings; procedure DefaultSettings; function IsFileInUse(const _FileName: string): Boolean; procedure SetPalette(const _PaletteName: string; var _PaletteCheckBox: TComboBoxEx); end; var FrmPreferences: TFrmPreferences; implementation uses FormMain, VH_Global; {$R *.dfm} procedure TFrmPreferences.EdLeptonSizeChange(Sender: TObject); var Value: single; begin Value := StrToFloatDef(EdLeptonSize.Text, C_ONE_LEPTON); if Value = C_ONE_LEPTON then begin rbMiggyLeptonSize.Checked := true; end else if Value = C_ONE_LEPTON_GE then begin rbStuLeptonSize.Checked := true; end else begin rbCustomLeptonSize.Checked := true; end; end; procedure TFrmPreferences.ExtractIcon; var sWinDir: String; iLength: Integer; {Res: TResourceStream; } MIcon: TIcon; begin // Initialize Variable iLength := 255; setLength(sWinDir, iLength); iLength := GetWindowsDirectory(PChar(sWinDir), iLength); setLength(sWinDir, iLength); IconPath := sWinDir + '\hvabuilder'+inttostr(IconID.Position)+'.ico'; MIcon := TIcon.Create; FrmMain.IconList.GetIcon(IconID.Position,MIcon); MIcon.SaveToFile(IconPath); MIcon.Free; { Res := TResourceStream.Create(hInstance,'Icon_'+IntToStr(IconID.Position+1),RT_RCDATA); Res.SaveToFile(IconPath); Res.Free; } end; function TFrmPreferences.IsFileInUse(const _FileName: string): Boolean; var HFileRes: HFILE; begin Result := False; if not FileExists(_FileName) then Exit; HFileRes := CreateFile(PChar(_FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); Result := (HFileRes = INVALID_HANDLE_VALUE); if not Result then CloseHandle(HFileRes); end; procedure TFrmPreferences.GetSettings; var Reg: TRegistry; F: TSearchRec; dir, path, Name: string; begin // Let's build the list of items on Tiberian Sun Palette combo box first. dir := IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0)) + '\Palettes\TS'); if DirectoryExists(dir) then begin // prepare path := Concat(dir, '*.pal'); // find files if FindFirst(path, faAnyFile, f) = 0 then repeat Name := IncludeTrailingPathDelimiter(Dir) + f.Name; if FileExists(Name) and (not IsFileInUse(Name)) then begin cbTiberianSunPalette.ItemsEx.AddItem(f.Name, 0, 0, 0, 0, 0); end; until FindNext(f) <> 0; FindClose(f); end; // Let's build the list of items on Red Alert 2 Palette combo box now. dir := IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0)) + '\Palettes\RA2'); if DirectoryExists(dir) then begin // prepare path := Concat(dir, '*.pal'); // find files if FindFirst(path, faAnyFile, f) = 0 then repeat Name := IncludeTrailingPathDelimiter(Dir) + f.Name; if FileExists(Name) and (not IsFileInUse(Name)) then begin cbRedAlert2Palette.ItemsEx.AddItem(f.Name, 0, 0, 0, 0, 0); end; until FindNext(f) <> 0; FindClose(f); end; Reg :=TRegistry.Create; // File Association Reg.RootKey := HKEY_CLASSES_ROOT; cbAssociate.Checked := Reg.KeyExists('\HVABuilder\shell\'); Reg.CloseKey; // Other settings Reg.RootKey := HKEY_CURRENT_USER; if Reg.KeyExists('\SOFTWARE\CnC Tools\OS HVA Builder\') then begin if Reg.OpenKey('\SOFTWARE\CnC Tools\OS HVA Builder\', true) then begin // Palette Settings SetPalette(Reg.ReadString('TiberianSunPalette'), cbTiberianSunPalette); SetPalette(Reg.ReadString('RedAlert2Palette'), cbRedAlert2Palette); cbUseNameSpecificPalettes.Checked := Reg.ReadBool('UseNameSpecificPalette'); // Rendering Options cbFPSCap.Checked := Reg.ReadBool('FPSCap'); try // Bullet Size EdBulletSize.Text := FloatToStr(Reg.ReadFloat('BulletSize')); // Lepton Size EdLeptonSize.Text := FloatToStr(Reg.ReadFloat('LeptonSize')); if Reg.ReadFloat('LeptonSize') = C_ONE_LEPTON then begin rbMiggyLeptonSize.Checked := true; end else if Reg.ReadFloat('LeptonSize') = C_ONE_LEPTON_GE then begin rbStuLeptonSize.Checked := true; end else begin rbCustomLeptonSize.Checked := true; end; // And it is over. except // Bullet Size EdBulletSize.Text := FloatToStr(BulletSize); // Lepton Size EdLeptonSize.Text := FloatToStr(LeptonSize); if LeptonSize = C_ONE_LEPTON then begin rbMiggyLeptonSize.Checked := true; end else if LeptonSize = C_ONE_LEPTON_GE then begin rbStuLeptonSize.Checked := true; end else begin rbCustomLeptonSize.Checked := true; end; end; Reg.CloseKey; end else begin DefaultSettings; end; end else begin DefaultSettings; end; Reg.Free; IconIDChange(Self); end; procedure TFrmPreferences.SetPalette(const _PaletteName: string; var _PaletteCheckBox: TComboBoxEx); var i: integer; isEnabled: boolean; begin isEnabled := _PaletteCheckBox.Enabled; i := 0; _PaletteCheckBox.ItemIndex := 0; while i < _PaletteCheckBox.ItemsEx.Count do begin if _PaletteCheckBox.ItemsEx.Items[i].Caption = _PaletteName then begin _PaletteCheckBox.ItemIndex := i; end; inc(i); end; _PaletteCheckBox.Enabled := isEnabled; end; procedure TFrmPreferences.DefaultSettings; var i: integer; begin cbUseNameSpecificPalettes.Checked := false; // Get TS palette. SetPalette('unittem.pal', cbTiberianSunPalette); cbTiberianSunPalette.Enabled := false; // Get RA2 palette. SetPalette('unittem.pal', cbRedAlert2Palette); cbRedAlert2Palette.Enabled := false; // Get FPS cap. cbFPSCap.Checked := true; // Get Bullet Size EdBulletSize.Text := FloatToStr(C_DEFAULT_BULLET_SIZE); // Get Lepton Size rbMiggyLeptonSize.Checked := true; rbCustomLeptonSize.Checked := false; rbStuLeptonSize.Checked := false; EdLeptonSize.Text := FloatToStr(C_ONE_LEPTON); end; procedure TFrmPreferences.btnApplyClick(Sender: TObject); var Reg: TRegistry; begin // Config.Icon:=IconID.Position; ExtractIcon; Reg := TRegistry.Create; Reg.RootKey := HKEY_CLASSES_ROOT; if Reg.OpenKey('\HVABuilder\DefaultIcon\',true) then begin Reg.WriteString('',IconPath); Reg.CloseKey; end; if cbAssociate.Checked = true then begin Reg.RootKey := HKEY_CLASSES_ROOT; if Reg.OpenKey('\.hva\',true) then begin Reg.WriteString('','HVABuilder'); Reg.CloseKey; end; Reg.RootKey := HKEY_CLASSES_ROOT; if Reg.OpenKey('\HVABuilder\shell\',true) then begin Reg.WriteString('','Open'); if Reg.OpenKey('\HVABuilder\shell\open\command\',true) then begin Reg.WriteString('',ParamStr(0)+' %1'); Reg.CloseKey; end; end; Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.hva\',true) then begin Reg.WriteString('Application',ParamStr(0)+' "%1"'); Reg.CloseKey; end; end else begin // Config.Assoc:=False; Reg :=TRegistry.Create; Reg.RootKey := HKEY_CLASSES_ROOT; Reg.DeleteKey('.hva'); Reg.CloseKey; Reg.RootKey := HKEY_CLASSES_ROOT; Reg.DeleteKey('\HVABuilder\'); Reg.CloseKey; Reg.RootKey := HKEY_CURRENT_USER; Reg.DeleteKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.hva\'); Reg.CloseKey; end; // Save the other settings. Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\SOFTWARE\CnC Tools\OS HVA Builder\', true) then begin // Palette Settings Reg.WriteString('TiberianSunPalette', cbTiberianSunPalette.ItemsEx.Items[cbTiberianSunPalette.ItemIndex].Caption); Reg.WriteString('RedAlert2Palette', cbRedAlert2Palette.ItemsEx.Items[cbRedAlert2Palette.ItemIndex].Caption); Reg.WriteBool('UseNameSpecificPalette', cbUseNameSpecificPalettes.Checked); if cbUseNameSpecificPalettes.Checked then begin FrmMain.Palette[C_GAME_TS] := 'Palettes\TS\' + cbTiberianSunPalette.ItemsEx.Items[cbTiberianSunPalette.ItemIndex].Caption; FrmMain.Palette[C_GAME_RA2] := 'Palettes\RA2\' + cbRedAlert2Palette.ItemsEx.Items[cbRedAlert2Palette.ItemIndex].Caption; end else begin FrmMain.Palette[C_GAME_TS] := 'Palettes\TS\unittem.pal'; FrmMain.Palette[C_GAME_RA2] := 'Palettes\RA2\unittem.pal'; end; FrmMain.RefreshGame; // Rendering Options Reg.WriteBool('FPSCap', cbFPSCap.Checked); FrmMain.SetFPSCap(cbFPSCap.Checked); // Bullet Size BulletSize := StrToFloatDef(EdBulletSize.Text, C_DEFAULT_BULLET_SIZE); Reg.WriteFloat('BulletSize', BulletSize); // Lepton Size LeptonSize := StrToFloatDef(EdLeptonSize.Text, C_ONE_LEPTON); Reg.WriteFloat('LeptonSize', LeptonSize); // And it is over. Reg.CloseKey; end; Reg.Free; Close; end; procedure TFrmPreferences.FormShow(Sender: TObject); begin GetSettings; pcOptions.ActivePageIndex := 0; gbOptionsBox.Caption := 'File Associations'; end; procedure TFrmPreferences.IconIDChange(Sender: TObject); var MIcon: TIcon;//Icon: TResourceStream; begin // Icon := TResourceStream.Create(hInstance,'Icon_'+IntToStr(IconID.Position+1),RT_RCDATA); MIcon := TIcon.Create; FrmMain.IconList.GetIcon(IconID.Position,MIcon); IconPrev.Picture.Icon := MIcon; // Icon.Free; MIcon.Free; end; procedure TFrmPreferences.Pref_ListClick(Sender: TObject); begin if pref_list.SelectionCount > 0 then begin if pref_list.Selected.Text = 'File Associations' then pcOptions.ActivePageIndex := 0 else if pref_list.Selected.Text = 'Palette Options' then pcOptions.ActivePageIndex := 1 else if pref_list.Selected.Text = 'Rendering Options' then pcOptions.ActivePageIndex := 2 else if pref_list.Selected.Text = 'Measures' then pcOptions.ActivePageIndex := 3; GbOptionsBox.Caption := pref_list.Selected.Text; end; end; procedure TFrmPreferences.Pref_ListKeyPress(Sender: TObject; var Key: Char); begin Pref_ListClick(sender); end; procedure TFrmPreferences.Pref_ListKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin Pref_ListClick(sender); end; procedure TFrmPreferences.rbMiggyLeptonSizeClick(Sender: TObject); begin EdLeptonSize.Text := FloatToStr(C_ONE_LEPTON); end; procedure TFrmPreferences.rbStuLeptonSizeClick(Sender: TObject); begin EdLeptonSize.Text := FloatToStr(C_ONE_LEPTON_GE); end; procedure TFrmPreferences.cbUseNameSpecificPalettesClick(Sender: TObject); begin lblTiberianSunPalette.Enabled := cbUseNameSpecificPalettes.Checked; lblRedAlert2Palette.Enabled := cbUseNameSpecificPalettes.Checked; cbTiberianSunPalette.Enabled := cbUseNameSpecificPalettes.Checked; cbRedAlert2Palette.Enabled := cbUseNameSpecificPalettes.Checked; end; procedure TFrmPreferences.btnCancelClick(Sender: TObject); begin Close; end; procedure TFrmPreferences.btnOKClick(Sender: TObject); begin btnApplyClick(Sender); Close; end; procedure TFrmPreferences.FormCreate(Sender: TObject); begin pnlTop.DoubleBuffered := true; end; end.
unit Dmitry.Utils.ShellIcons; interface uses System.SysUtils, System.Classes, System.SyncObjs, Winapi.Windows, Winapi.CommCtrl, Winapi.ShellAPI, Vcl.Graphics, Vcl.ImgList, Dmitry.Utils.SystemImageLists, Dmitry.Memory; procedure FindIcon(hLib: Cardinal; NameRes: string; Size, ColorDepth: Byte; var Icon: TIcon); function ExtractShellIcon(Path: string; Size: Integer): HIcon; function ExtractDefaultAssociatedIcon(Extension: string; Size: Integer): HIcon; implementation var FVirtualSysImages: VirtualSysImages = nil; FSyncGlobalImages: TCriticalSection = nil; FSyncSH: TCriticalSection = nil; procedure FindIcon(hLib: cardinal; NameRes: string; Size, ColorDepth: Byte; var Icon: TIcon); type GRPICONDIRENTRY = packed record bWidth: Byte; // Width, in pixels, of the image bHeight: Byte; // Height, in pixels, of the image bColorCount: Byte; // Number of colors in image (0 if >=8bpp) bReserved: Byte; // Reserved wPlanes: WORD; // Color Planes wBitCount: WORD; // Bits per pixel dwBytesInRes: DWORD; // how many bytes in this resource? nID: WORD; // the ID end; GRPICONDIR = packed record idReserved: WORD; // Reserved (must be 0) idType: WORD; // Resource type (1 for icons) idCount: WORD; // How many images? idEntries: array [1 .. 16] of GRPICONDIRENTRY; // The entries for each image end; ICONIMAGE = record icHeader: BITMAPINFOHEADER; // DIB header icColors: array of RGBQUAD; // Color table icXOR: array of Byte; // DIB bits for XOR mask icAND: array of Byte; // DIB bits for AND mask end; var hRsrc, hGlobal: cardinal; GRP: GRPICONDIR; lpGrpIconDir: ^GRPICONDIR; lpIconImage: ^ICONIMAGE; Stream: TMemoryStream; i, i0, nID: Integer; begin Icon := nil; lpIconImage:=nil; // Find the group resource which lists its images hRsrc := FindResource(hLib, PWideChar(NameRes), RT_GROUP_ICON); // Load and Lock to get a pointer to a GRPICONDIR hGlobal := LoadResource(hLib, hRsrc); lpGrpIconDir := LockResource(hGlobal); // Using an ID from the group, Find, Load and Lock the RT_ICON i0 := Low(lpGrpIconDir.idEntries); for i := i0 to lpGrpIconDir.idCount do begin hRsrc := FindResource(hLib, MAKEINTRESOURCE(lpGrpIconDir.idEntries[i].nID), RT_ICON); hGlobal := LoadResource(hLib, hRsrc); lpIconImage := LockResource(hGlobal); if (lpIconImage.icHeader.biWidth = Size) and ((lpIconImage.icHeader.biBitCount = ColorDepth) or (ColorDepth = 0)) then Break; end; if Assigned(lpIconImage) and (lpIconImage.icHeader.biWidth = Size) and (lpIconImage.icHeader.biBitCount = ColorDepth) then begin Stream := TMemoryStream.Create; try Stream.Clear; ZeroMemory(@GRP, SizeOf(GRP)); GRP.idCount := 1; GRP.idType := 1; GRP.idReserved := 0; GRP.idEntries[i0] := lpGrpIconDir.idEntries[i]; nID := SizeOf(WORD) * 3 + SizeOf(GRPICONDIRENTRY) + 2; //$16 GRP.idEntries[i0].nID := nID; Stream.WriteBuffer(GRP, nID); Stream.WriteBuffer(lpIconImage^, GRP.idEntries[i0].dwBytesInRes); Stream.Position := 0; Icon := TIcon.Create; Icon.LoadFromStream(Stream); finally Stream.Free; end; end; end; function GetShellFlagdBySize(Size: Integer): Cardinal; begin Result := SHGFI_ADDOVERLAYS; if (Size < 48) then Result := Result or SHGFI_SYSICONINDEX or SHGFI_ICON; if (Size = 48) then Result := Result or SHGFI_SYSICONINDEX; if (Size = 32) then Result := Result or SHGFI_LARGEICON; if (Size = 16) then Result := Result or SHGFI_SMALLICON; end; function GetShellInternalIcon(FileInfo: TSHFileInfo; Size: Integer): HIcon; const DrawingStyles: array[TDrawingStyle] of Longint = (ILD_FOCUS, ILD_SELECTED, ILD_NORMAL, ILD_TRANSPARENT); Images: array[TImageType] of Longint = (0, ILD_MASK); begin if (Size < 48) then begin Result := FileInfo.hIcon; end else begin //create this object when it needed! FSyncGlobalImages.Enter; try if FVirtualSysImages = nil then FVirtualSysImages := ExtraLargeSysImages; Result := ImageList_GetIcon(FVirtualSysImages.Handle, FileInfo.iIcon, DrawingStyles[FVirtualSysImages.DrawingStyle] or Images[FVirtualSysImages.ImageType]); finally FSyncGlobalImages.Leave; end; end; end; function ExtractDefaultAssociatedIcon(Extension: string; Size: Integer): HIcon; var FileInfo: SHFILEINFO; Flags: Integer; begin Extension := '*' + Extension; FillChar(FileInfo, SizeOf(FileInfo), #0); Flags := GetShellFlagdBySize(Size); FSyncSH.Enter; try SHGetFileInfo(PChar(Extension), FILE_ATTRIBUTE_NORMAL, FileInfo, SizeOf(FileInfo), SHGFI_SYSICONINDEX or Flags or SHGFI_USEFILEATTRIBUTES ); finally FSyncSH.Leave; end; Result := GetShellInternalIcon(FileInfo, Size); end; function ExtractShellIcon(Path: string; Size: Integer): HIcon; var FileInfo: TSHFileInfo; Flags: UINT; begin FillChar(FileInfo, SizeOf(FileInfo), #0); Flags := GetShellFlagdBySize(Size); FSyncSH.Enter; try SHGetFileInfo(PWideChar(Path), FILE_ATTRIBUTE_NORMAL, FileInfo, SizeOf(FileInfo), Flags); finally FSyncSH.Leave; end; Result := GetShellInternalIcon(FileInfo, Size); end; initialization FSyncGlobalImages := TCriticalSection.Create; FSyncSH := TCriticalSection.Create; finalization F(FSyncGlobalImages); F(FSyncSH); end.
unit TESTORCAMENTOITENS.Entidade.Model; interface uses DB, Classes, SysUtils, Generics.Collections, /// orm ormbr.types.blob, ormbr.types.lazy, ormbr.types.mapping, ormbr.types.nullable, ormbr.mapping.classes, ormbr.mapping.register, ormbr.mapping.attributes, TESTORCAMENTO.Entidade.Model, TESTPRODUTO.Entidade.Model; type [Entity] [Table('TESTORCAMENTOITENS', '')] [PrimaryKey('ID', NotInc, NoSort, False, 'Chave primária')] TTESTORCAMENTOITENS = class private { Private declarations } FID: Integer; FIDORCAMENTO: String; FIDPRODUTO: String; FQTDE: Nullable<Double>; FDATA_CADASTRO: TDateTime; FULTIMA_ATUALIZACAO: TDateTime; FTESTORCAMENTO_0: TTESTORCAMENTO ; FTESTPRODUTO_1: TTESTPRODUTO ; function getULTIMA_ATUALIZACAO: TDateTime; function getDATA_CADASTRO: TDateTime; public { Public declarations } constructor Create; destructor Destroy; override; [Restrictions([NotNull])] [Column('ID', ftInteger)] [Dictionary('ID', 'Mensagem de validação', '', '', '', taCenter)] property ID: Integer read FID write FID; [Restrictions([NotNull])] [Column('IDORCAMENTO', ftString, 64)] [ForeignKey('FK_TESTORCAMENTOITENS_1', 'IDORCAMENTO', 'TESTORCAMENTO', 'CODIGO', SetNull, SetNull)] [Dictionary('IDORCAMENTO', 'Mensagem de validação', '', '', '', taLeftJustify)] property IDORCAMENTO: String read FIDORCAMENTO write FIDORCAMENTO; [Restrictions([NotNull])] [Column('IDPRODUTO', ftString, 64)] [ForeignKey('FK_TESTORCAMENTOITENS_2', 'IDPRODUTO', 'TESTPRODUTO', 'CODIGO', SetNull, SetNull)] [Dictionary('IDPRODUTO', 'Mensagem de validação', '', '', '', taLeftJustify)] property IDPRODUTO: String read FIDPRODUTO write FIDPRODUTO; [Column('QTDE', ftBCD)] [Dictionary('QTDE', 'Mensagem de validação', '0', '', '', taRightJustify)] property QTDE: Nullable<Double> read FQTDE write FQTDE; [Restrictions([NotNull])] [Column('DATA_CADASTRO', ftDateTime)] [Dictionary('DATA_CADASTRO', 'Mensagem de validação', 'Now', '', '!##/##/####;1;_', taCenter)] property DATA_CADASTRO: TDateTime read getDATA_CADASTRO write FDATA_CADASTRO; [Restrictions([NotNull])] [Column('ULTIMA_ATUALIZACAO', ftDateTime)] [Dictionary('ULTIMA_ATUALIZACAO', 'Mensagem de validação', 'Now', '', '!##/##/####;1;_', taCenter)] property ULTIMA_ATUALIZACAO: TDateTime read getULTIMA_ATUALIZACAO write FULTIMA_ATUALIZACAO; [Association(OneToOne,'IDORCAMENTO','TESTORCAMENTO','CODIGO')] property TESTORCAMENTO: TTESTORCAMENTO read FTESTORCAMENTO_0 write FTESTORCAMENTO_0; [Association(OneToOne,'IDPRODUTO','TESTPRODUTO','CODIGO')] property TESTPRODUTO: TTESTPRODUTO read FTESTPRODUTO_1 write FTESTPRODUTO_1; end; implementation constructor TTESTORCAMENTOITENS.Create; begin FTESTORCAMENTO_0 := TTESTORCAMENTO.Create; FTESTPRODUTO_1 := TTESTPRODUTO.Create; end; destructor TTESTORCAMENTOITENS.Destroy; begin if Assigned(FTESTORCAMENTO_0) then FTESTORCAMENTO_0.Free; if Assigned(FTESTPRODUTO_1) then FTESTPRODUTO_1.Free; inherited; end; function TTESTORCAMENTOITENS.getDATA_CADASTRO: TDateTime; begin if FDATA_CADASTRO = StrToDateTime('30/12/1899 00:00') then FDATA_CADASTRO := Now; Result := FDATA_CADASTRO; end; function TTESTORCAMENTOITENS.getULTIMA_ATUALIZACAO: TDateTime; begin FULTIMA_ATUALIZACAO := Now; Result := FULTIMA_ATUALIZACAO; end; initialization TRegisterClass.RegisterEntity(TTESTORCAMENTOITENS) end.
unit CCJSO_AutoGenRefNomencl; (* © PgkSoft 08.08.2016 Справочник автогенерации Номенклатура заказов *) interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UCCenterJournalNetZkz, ExtCtrls, ActnList, StdCtrls, ComCtrls, ToolWin, Grids, DBGrids, DB, ADODB; type TfrmAutoGenRefNomencl = class(TForm) pnlSelect: TPanel; pnlCond: TPanel; pnlControl: TPanel; pnlGrid: TPanel; aList: TActionList; aExit: TAction; aSelect: TAction; aClearCond: TAction; pnlSelect_Tool: TPanel; tbarSelect: TToolBar; tbtnSelect_Ok: TToolButton; tbtnSelect_Exit: TToolButton; pnlSelect_Show: TPanel; pnlControl_Show: TPanel; pnlControl_Tool: TPanel; pnlCond_Tool: TPanel; tbarCond: TToolBar; tbtnCond_Clear: TToolButton; pnlCond_Fields: TPanel; lblCond_ArtCode: TLabel; edCond_ArtCode: TEdit; lblCond_Name: TLabel; edCond_Name: TEdit; aRefresh: TAction; tbarControl: TToolBar; ToolButton1: TToolButton; aChangeCond: TAction; GridMain: TDBGrid; qrspMain: TADOStoredProc; dsMain: TDataSource; aCondExec: TAction; tbtnCond_Exec: TToolButton; aCondFieldsClick: TAction; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure aExitExecute(Sender: TObject); procedure aSelectExecute(Sender: TObject); procedure aClearCondExecute(Sender: TObject); procedure aRefreshExecute(Sender: TObject); procedure aChangeCondExecute(Sender: TObject); procedure GridMainDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); function GetStateClearMainCondition : boolean; procedure GridMainTitleClick(Column: TColumn); procedure aCondExecExecute(Sender: TObject); procedure GridMainDblClick(Sender: TObject); procedure aCondFieldsClickExecute(Sender: TObject); private { Private declarations } bSignActive : boolean; ScreenPos : TPoint; Mode : integer; RecSession : TUserSession; SortField : string; SortDirection : boolean; SignSelect : boolean; SlArtCode : integer; SLArtName : string; procedure ShowGets; procedure ExecConditionQRMain; procedure CreateConditionQRMain; procedure GridMainRefresh; procedure SetClearCondition; public { Public declarations } procedure SetMode(Parm : integer); procedure SetRecSession(Parm : TUserSession); procedure SetScreenPos(Parm : TPoint); function GetSignSelect : boolean; function GetArtCode : integer; function GetArtName : string; end; Const cFAutoGenRefNomMode_Show = 0; cFAutoGenRefNomMode_Select = 1; var frmAutoGenRefNomencl: TfrmAutoGenRefNomencl; implementation uses UMAIN, UTIL, Types; {$R *.dfm} procedure TfrmAutoGenRefNomencl.FormCreate(Sender: TObject); begin { Иницализация } bSignActive := false; Mode := cFAutoGenRefNomMode_Show; SignSelect := false; SlArtCode := 0; SLArtName := ''; SortField := ''; SortDirection := false; ScreenPos := Point(0,0); end; procedure TfrmAutoGenRefNomencl.FormActivate(Sender: TObject); begin if not bSignActive then begin { Специальное позиционирование окна } if (ScreenPos.X <> 0) or (ScreenPos.Y <> 0) then begin self.Left := ScreenPos.X; self.Top := ScreenPos.Y; end; { Иконка формы } FCCenterJournalNetZkz.imgMain.GetIcon(383,self.Icon); { Инициализация } if Mode = cFAutoGenRefNomMode_Show then begin pnlSelect.Visible := false; end; { Форма активна } bSignActive := true; { Инициализация сортировки } GridMain.OnTitleClick(GridMain.Columns[0]); GridMain.SetFocus; end; end; procedure TfrmAutoGenRefNomencl.ShowGets; var SCaption : string; begin if bSignActive then begin { Доступ к очистке условий отбора } if GetStateClearMainCondition then begin aClearCond.Enabled := false; aCondExec.Enabled := false; end else begin aClearCond.Enabled := true; aCondExec.Enabled := true; end; { Доступ к элементам управления } if not qrspMain.IsEmpty then begin aSelect.Enabled := true; end else begin aSelect.Enabled := false; end; { Количество номеклатуры заказов } SCaption := VarToStr(qrspMain.RecordCount); pnlControl_Show.Caption := SCaption; pnlControl_Show.Width := TextPixWidth(SCaption, pnlControl_Show.Font) + 20; end; end; function TfrmAutoGenRefNomencl.GetStateClearMainCondition : boolean; var bResReturn : boolean; begin if (length(trim(edCond_ArtCode.Text)) = 0) and (length(trim(edCond_Name.Text)) = 0) then bResReturn := true else bResReturn := false; result := bResReturn; end; procedure TfrmAutoGenRefNomencl.SetRecSession(Parm : TUserSession); begin RecSession := Parm; end; procedure TfrmAutoGenRefNomencl.SetMode(Parm : integer); begin Mode := Parm; end; procedure TfrmAutoGenRefNomencl.SetScreenPos(Parm : TPoint); begin ScreenPos := Parm; end; function TfrmAutoGenRefNomencl.GetSignSelect : boolean; begin result := SignSelect; end; function TfrmAutoGenRefNomencl.GetArtCode : integer; begin result := SLArtCode; end; function TfrmAutoGenRefNomencl.GetArtName : string; begin result := SLArtName; end; procedure TfrmAutoGenRefNomencl.ExecConditionQRMain; var RN: Integer; begin if not qrspMain.IsEmpty then RN := qrspMain.FieldByName('NRN').AsInteger else RN := -1; qrspMain.Active := false; CreateConditionQRMain; qrspMain.Active := true; qrspMain.Locate('NRN', RN, []); end; procedure TfrmAutoGenRefNomencl.CreateConditionQRMain; begin if length(trim(edCond_ArtCode.Text)) = 0 then qrspMain.Parameters.ParamValues['@ArtCode'] := '' else qrspMain.Parameters.ParamValues['@ArtCode'] := edCond_ArtCode.Text; if length(trim(edCond_Name.Text)) = 0 then qrspMain.Parameters.ParamValues['@Name'] := '' else qrspMain.Parameters.ParamValues['@Name'] := edCond_Name.Text; qrspMain.Parameters.ParamValues['@OrderBy'] := SortField; qrspMain.Parameters.ParamValues['@Direction'] := SortDirection; end; procedure TfrmAutoGenRefNomencl.GridMainRefresh; var RN: Integer; begin if not qrspMain.IsEmpty then RN := qrspMain.FieldByName('NRN').AsInteger else RN := -1; qrspMain.Requery; qrspMain.Locate('NRN', RN, []); end; procedure TfrmAutoGenRefNomencl.SetClearCondition; begin edCond_ArtCode.Text := ''; edCond_Name.Text := ''; end; procedure TfrmAutoGenRefNomencl.aExitExecute(Sender: TObject); begin self.Close; end; procedure TfrmAutoGenRefNomencl.aSelectExecute(Sender: TObject); begin SignSelect := true; SLArtCode := GridMain.DataSource.DataSet.FieldByName('NRN').AsInteger; SLArtName := GridMain.DataSource.DataSet.FieldByName('SNomenclature').AsString; self.Close; end; procedure TfrmAutoGenRefNomencl.aClearCondExecute(Sender: TObject); begin SetClearCondition; ExecConditionQRMain; ShowGets; end; procedure TfrmAutoGenRefNomencl.aRefreshExecute(Sender: TObject); begin GridMainRefresh; ShowGets; end; procedure TfrmAutoGenRefNomencl.aChangeCondExecute(Sender: TObject); begin ShowGets; end; procedure TfrmAutoGenRefNomencl.GridMainDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var db: TDBGrid; begin if Sender = nil then Exit; db := TDBGrid(Sender); if (gdSelected in State) then begin db.Canvas.Font.Style := [fsBold]; end; db.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TfrmAutoGenRefNomencl.GridMainTitleClick(Column: TColumn); var iCkl : integer; begin if Column.Title.Font.Color = clWindowText then begin { Восстанавливаем прорисовку по умолчанию } for iCkl := 0 to GridMain.Columns.count - 1 do begin if GridMain.Columns[iCkl].Title.Font.Color <> clWindowText then begin GridMain.Columns[iCkl].Title.Font.Color := clWindowText; GridMain.Columns[iCkl].Title.Font.Style := []; GridMain.Columns[iCkl].Title.Caption := copy(GridMain.Columns[iCkl].Title.Caption,2,length(GridMain.Columns[iCkl].Title.Caption)-1); end; end; { Для выбранного столбца включаем сортировку по возрастанию } Column.Title.Font.Color := clBlue; Column.Title.Font.Style := [fsBold]; Column.Title.Caption := chr(24)+Column.Title.Caption; SortField := Column.FieldName; SortDirection := false; ExecConditionQRMain; end else if Column.Title.Font.Color = clBlue then begin { Для выбранного столбца переключаем на сортировку по убыванию } Column.Title.Font.Color := clFuchsia; Column.Title.Font.Style := [fsBold]; Column.Title.Caption := '!'+copy(Column.Title.Caption,2,length(Column.Title.Caption)-1); SortField := Column.FieldName; SortDirection := true; ExecConditionQRMain; end else if Column.Title.Font.Color = clFuchsia then begin { Для выбранного столбца переключаем на сортировку по возрастанию } Column.Title.Font.Color := clBlue; Column.Title.Font.Style := [fsBold]; Column.Title.Caption := chr(24)+copy(Column.Title.Caption,2,length(Column.Title.Caption)-1); SortField := Column.FieldName; SortDirection := false; ExecConditionQRMain; end; ShowGets; end; procedure TfrmAutoGenRefNomencl.aCondExecExecute(Sender: TObject); begin ExecConditionQRMain; ShowGets; end; procedure TfrmAutoGenRefNomencl.GridMainDblClick(Sender: TObject); begin if not qrspMain.IsEmpty then begin SignSelect := true; SLArtCode := GridMain.DataSource.DataSet.FieldByName('NRN').AsInteger; SLArtName := GridMain.DataSource.DataSet.FieldByName('SNomenclature').AsString; self.Close; end; end; procedure TfrmAutoGenRefNomencl.aCondFieldsClickExecute(Sender: TObject); begin if not GetStateClearMainCondition then aCondExec.Execute; end; end.
unit meshify_simplify_quadric; {$mode objfpc}{$H+} interface //Mesh Simplification Unit // (C) by Sven Forstmann in 2014 //License : MIT (http://opensource.org/licenses/MIT) // https://github.com/sp4cerat/Fast-Quadric-Mesh-Simplification // http://www.gamedev.net/topic/656486-high-speed-quadric-mesh-simplification-without-problems-resolved/ // http://voxels.blogspot.com/2014/05/quadric-mesh-simplification-with-source.html // https://github.com/neurolabusc/Fast-Quadric-Mesh-Simplification-Pascal- //5/2016: Chris Rorden ported from C++ to FreePascal/Delphi uses Math, define_types; procedure simplify_mesh(var faces : TFaces; var verts: TVertices; target_count: integer; aggressiveness : double=7; resize: boolean=true); // target_count : target nr. of triangles // aggressiveness : sharpness to increase the threshold. // 5..8 are good numbers // more iterations yield higher quality // resize : scale to unit size before decimation, rescale to original size after (helps threshold) procedure simplify_mesh_lossless(var faces : TFaces; var verts: TVertices); implementation type TFloat = double; //"TFloat = single" is faster "TFloat = double" more precise //double recommended - especially for lossless which can fail to detect small differences (e.g. knot.mz3) TSymetricMatrix = array [0..9] of TFloat; TRef = record tid,tvertex: integer; end; TVertex = record p: TPoint3f; border, tstart,tcount: integer; q: TSymetricMatrix; end; TTriangle = record v: array[0..2] of integer; err: array[0..3] of TFloat; dirty, deleted: boolean; n: TPoint3f; end; TBools = array of boolean; TVs = array of TVertex; TTs = array of TTriangle; TRs = array of TRef; function symMat(c: TFloat): TSymetricMatrix; inline; overload; var i: integer; begin for i := 0 to 9 do result[i] := c; end; // symMat() function symMat(a,b,c,d: TFloat): TSymetricMatrix; inline; overload; begin result[0] := a*a; result[1] := a*b; result[2] := a*c; result[3] := a*d; result[4] := b*b; result[5] := b*c; result[6] := b*d; result[7] :=c*c; result[8] := c*d; result[9] := d*d; end; // symMat() function symMat( m11, m12, m13, m14, m22, m23, m24, m33, m34, m44: TFloat): TSymetricMatrix; inline; overload; begin result[0] := m11; result[1] := m12; result[2] := m13; result[3] := m14; result[4] := m22; result[5] := m23; result[6] := m24; result[7] := m33; result[8] := m34; result[9] := m44; end; // symMat() function symMatAdd(n,m: TSymetricMatrix): TSymetricMatrix; inline; begin result := symMat(n[0]+m[0], n[1]+m[1], n[2]+m[2], n[3]+m[3], n[4]+m[4], n[5]+m[5], n[6]+m[6], n[7]+m[7], n[8]+m[8], n[9]+m[9]); end; // symMatAdd() function symMatDet(m: TSymetricMatrix; a11, a12, a13, a21, a22, a23, a31, a32, a33: integer): TFloat; inline; begin result := m[a11]*m[a22]*m[a33] + m[a13]*m[a21]*m[a32] + m[a12]*m[a23]*m[a31] - m[a13]*m[a22]*m[a31] - m[a11]*m[a23]*m[a32]- m[a12]*m[a21]*m[a33]; end; // symMatDet() function ptf(x,y,z: single):TPoint3f; begin result.x := x; result.y := y; result.z := z; end; // ptf() function vCross(v1, v2: TPoint3f): TPoint3f; inline; begin result := ptf(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x); end; // vCross() function vSum(a,b: TPoint3f): TPoint3f; inline; begin result.X := a.X+b.X; result.Y := a.Y+b.Y; result.Z := a.Z+b.Z; end; // vSum() function vSubtract (a,b: TPoint3f): TPoint3f; inline; begin result.X := A.X - B.X; result.Y := A.Y - B.Y; result.Z := A.Z - B.Z; end; // vSubtract() procedure vNormalize(var v: TPoint3f); inline; var len: single; begin len := sqrt( (v.X*v.X) + (v.Y*v.Y) + (v.Z*v.Z) ); if len <= 0 then len := 0.0000001; v.X := v.X / len; v.Y := v.Y / len; v.Z := v.Z / len; end; // vNormalize() function vDot (A, B: TPoint3f): single; inline; begin //dot product result := A.X*B.X + A.Y*B.Y + A.Z*B.Z; end; // vDot() function vMult(a: TPoint3f; v: TFloat):TPoint3f; inline; begin result.X := a.X*v; result.Y := a.Y*v; result.Z := a.Z*v; end; // vMult() // Error between vertex and Quadric function vertex_error(q: TSymetricMatrix; x,y,z: TFloat): TFloat; inline; begin result := q[0]*x*x + 2*q[1]*x*y + 2*q[2]*x*z + 2*q[3]*x + q[4]*y*y + 2*q[5]*y*z + 2*q[6]*y + q[7]*z*z + 2*q[8]*z + q[9]; end; // vertex_error() // Error for one edge function calculate_error(id_v1, id_v2: integer; var p_result: TPoint3f; var vertices: TVs): TFloat; inline; var q : TSymetricMatrix; border: integer; error1,error2,error3,error, det: TFloat; p1, p2, p3: TPoint3f; begin // compute interpolated vertex q := symMatAdd(vertices[id_v1].q, vertices[id_v2].q); border := vertices[id_v1].border + vertices[id_v2].border; error := 0; det := symMatDet(q, 0, 1, 2, 1, 4, 5, 2, 5, 7); if ( det <> 0) and ( border = 0) then begin // q_delta is invertible p_result.x := -1/det*(symMatDet(q,1, 2, 3, 4, 5, 6, 5, 7 , 8)); // vx = A41/det(q_delta) p_result.y := 1/det*(symMatDet(q,0, 2, 3, 1, 5, 6, 2, 7 , 8)); // vy = A42/det(q_delta) p_result.z := -1/det*(symMatDet(q,0, 1, 3, 1, 4, 6, 2, 5, 8)); // vz = A43/det(q_delta) error := vertex_error(q, p_result.x, p_result.y, p_result.z); end else begin // det = 0 -> try to find best result p1 := vertices[id_v1].p; p2 := vertices[id_v2].p; p3 := vMult(vSum(p1, p2), 0.5); error1 := vertex_error(q, p1.x,p1.y,p1.z); error2 := vertex_error(q, p2.x,p2.y,p2.z); error3 := vertex_error(q, p3.x,p3.y,p3.z); error := min(error1, min(error2, error3)); if (error1 = error) then p_result := p1; if (error2 = error) then p_result := p2; if (error3 = error) then p_result := p3; end; result := error; end; // calculate_error() procedure update_mesh(iteration: integer; var triangles: TTs; var vertices: TVs; var refs :TRs; var nrefs: integer); var dst, i, j, k, tstart, ofs, id: integer; t: ^Ttriangle; v: ^TVertex; p,n: TPoint3f; p3 : array[0..2] of TPoint3f; vcount,vids: array of integer; begin if(iteration>0) then begin // compact triangles dst := 0; for i := 0 to high(triangles) do begin if(not triangles[i].deleted) then begin triangles[dst] := triangles[i]; dst := dst + 1; end; //if not deleted end; //for each triangle setlength(triangles, dst); end; //if iteration > 0 // // Init Quadrics by Plane & Edge Errors // // required at the beginning ( iteration == 0 ) // recomputing during the simplification is not required, // but mostly improves the result for closed meshes // if( iteration = 0 ) then begin for i := 0 to high(vertices) do vertices[i].q := symMat(0.0); for i := 0 to high(triangles) do begin t := @triangles[i]; for j := 0 to 2 do p3[j] := vertices[t^.v[j]].p; p3[1] := vSubtract(p3[1],p3[0]); p3[2] := vSubtract(p3[2],p3[0]); n := vCross(p3[1], p3[2]); vNormalize(n); t^.n :=n; for j := 0 to 2 do vertices[t^.v[j]].q := symMatAdd(vertices[t^.v[j]].q, symMat(n.x,n.y,n.z,-vDot(n,p3[0]))); end; //for i: triangles for i := 0 to high(triangles) do begin // Calc Edge Error t := @triangles[i]; p := ptf(0,0,0); for j := 0 to 2 do t^.err[j] := calculate_error(t^.v[j],t^.v[(j+1) mod 3] ,p, vertices); t^.err[3] := min(t^.err[0],min(t^.err[1],t^.err[2])); end; //for i: triangles end; //if iteration = 0 // Init Reference ID list for i := 0 to high(vertices) do begin vertices[i].tstart := 0; vertices[i].tcount := 0; end; for i := 0 to high(triangles) do for j := 0 to 2 do vertices[triangles[i].v[j]].tcount := vertices[triangles[i].v[j]].tcount + 1; tstart := 0; for i := 0 to high(vertices) do begin vertices[i].tstart := tstart; tstart := tstart + vertices[i].tcount; vertices[i].tcount := 0; end; // Write References // setlength(refs, length(triangles) * 3); //initial size, replicates C code setlength(refs, length(triangles) * 6); //Pascal setlength() is expensive, so set larger than initially required to reduce re-allocation nrefs := length(refs); for i := 0 to high(triangles) do begin t := @triangles[i]; for j := 0 to 2 do begin v := @vertices[t^.v[j]]; refs[v^.tstart+v^.tcount].tid := i; refs[v^.tstart+v^.tcount].tvertex := j; v^.tcount := v^.tcount + 1; end; end; //for i: triangles // Identify boundary : vertices[].border=0,1 if( iteration = 0 ) then begin for i := 0 to high(vertices) do vertices[i].border := 0; for i := 0 to high(vertices) do begin v := @vertices[i]; setlength(vcount, 0); setlength(vids, 0); for j := 0 to (v^.tcount -1) do begin k := refs[v^.tstart+j].tid; t := @triangles[k]; for k := 0 to 2 do begin ofs := 0; id := t^.v[k]; while ( ofs< length(vcount) ) do begin if (vids[ofs] = id) then break; ofs := ofs + 1; end; if(ofs = length(vcount)) then begin setlength(vcount, length(vcount)+1); vcount[high(vcount)] := 1; setlength(vids, length(vids)+1); vids[high(vids)] := id; end else vcount[ofs] := vcount[ofs] + 1; end; // for k end; //for j for j := 0 to (length(vcount)-1) do if vcount[j] = 1 then vertices[vids[j]].border := 1; end; //for i end; // if iteration = 0 end; // update_mesh() procedure compact_mesh(var triangles: TTs; var vertices: TVs); // Finally compact mesh before exiting var dst, i, j: integer; begin dst := 0; for i := 0 to high(vertices) do vertices[i].tcount := 0; for i := 0 to high(triangles) do begin if (not triangles[i].deleted) then begin triangles[dst] := triangles[i]; dst := dst + 1; for j := 0 to 2 do vertices[triangles[i].v[j]].tcount := 1; end; //if not deleted end; //for i setlength(triangles, dst); dst := 0; for i := 0 to high(vertices) do begin if vertices[i].tcount <> 0 then begin vertices[i].tstart := dst; vertices[dst].p := vertices[i].p; dst := dst + 1; end; end; //for i for i := 0 to high(triangles) do for j := 0 to 2 do triangles[i].v[j] := vertices[triangles[i].v[j]].tstart; setlength(vertices, dst); end; // compact_mesh() function flipped(p: TPoint3f; i1: integer; var v0: TVertex; var deleted: TBools; var triangles: TTs; var vertices: TVs; var refs :TRs): boolean; inline; var k, bordercount, s, id1, id2: integer; t: ^Ttriangle; n, d1, d2: TPoint3f; begin bordercount := 0; result := true; for k := 0 to (v0.tcount -1) do begin t := @triangles[refs[v0.tstart+k].tid]; if(t^.deleted) then continue; s := refs[v0.tstart+k].tvertex; id1 := t^.v[(s+1) mod 3]; id2 := t^.v[(s+2) mod 3]; if(id1=i1) or (id2=i1) then begin// delete ? bordercount := bordercount + 1; deleted[k] := true; continue; end; d1 := vSubtract(vertices[id1].p, p); vNormalize(d1); d2 := vSubtract(vertices[id2].p, p); vNormalize(d2); if(abs(vDot(d1, d2))>0.999) then exit; n := vCross(d1, d2); vNormalize(n); deleted[k] := false; if(vDot(n, t^.n)<0.2) then exit; end; result := false; end; // flipped() procedure update_triangles(i0: integer; var v: TVertex; var deleted :TBools; var deleted_triangles: integer; var triangles: TTs; var vertices: TVs; var refs :TRs; var nrefs: integer); inline; const kBlockSz = 64000; //re-allocate memory in chunks var p: TPoint3f; k: integer; r: ^TRef; t: ^TTriangle; ref: TRef; begin p := ptf(0,0,0); //to hide compiler hint for k := 0 to (v.tcount-1) do begin r := @refs[v.tstart+k]; t := @triangles[r^.tid]; if(t^.deleted) then continue; if (deleted[k]) then begin t^.deleted := true; deleted_triangles := deleted_triangles + 1; continue; end; t^.v[r^.tvertex] := i0; t^.dirty := true; t^.err[0] := calculate_error(t^.v[0],t^.v[1],p, vertices); t^.err[1] := calculate_error(t^.v[1],t^.v[2],p, vertices); t^.err[2] := calculate_error(t^.v[2],t^.v[0],p, vertices); t^.err[3] := min(t^.err[0],min(t^.err[1],t^.err[2])); // setlength() is costly, so we do resize the array in chunks ref := r^; //<- n.b. setlength() can change address of refs, so copy data to ref prior to resize! if (nrefs >= length(refs)) then setlength(refs, nrefs + kBlockSz); refs[nrefs] := ref; nrefs := nrefs + 1; end; end; // update_triangles() procedure scale_mesh(var verts: TVertices; scale: TFloat); var i: integer; begin if scale = 1.0 then exit; for i := 0 to high(verts) do verts[i] := vMult(verts[i], scale); end; function normalize_mesh(var verts: TVertices): TFloat; //make largest dimension have size of 1. Provides reasonable threshold var i: integer; mn, mx: TPoint3f; invert : TFloat; begin mn := verts[0]; mx := mn; for i := 0 to high(verts) do begin if (verts[i].X < mn.X) then mn.X := verts[i].X; if (verts[i].Y < mn.Y) then mn.Y := verts[i].Y; if (verts[i].Z < mn.Z) then mn.Z := verts[i].Z; if (verts[i].X > mx.X) then mx.X := verts[i].X; if (verts[i].Y > mx.Y) then mx.Y := verts[i].Y; if (verts[i].Z > mx.Z) then mx.Z := verts[i].Z; end; result := max(max(mx.X-mn.X, mx.Y-mn.Y), mx.Z - mn.Z); if (result = 0) or (result = 1.0) then exit; invert := 1.0/result; for i := 0 to high(verts) do verts[i] := vMult(verts[i], invert); end; procedure simplify_mesh(var faces : TFaces; var verts: TVertices; target_count: integer; aggressiveness : double=7; resize: boolean=true); var vertices : TVs; triangles : TTs; iteration, i, j, deleted_triangles, triangle_count, i0, i1, tstart, tcount: integer; deleted0,deleted1: TBools; threshold: TFloat; t: ^TTriangle; v0, v1: ^TVertex; p: TPoint3f; refs : TRs; nrefs: integer; scale: TFloat = 1.0; begin if (length(faces) < 5) or (length(verts) < 5) or (target_count < 4) or (target_count > length(faces)) then exit; if resize then scale := normalize_mesh(verts); //convert simple mesh to verbose structure that allows us to represent quadric properties setlength(triangles, length(Faces)); setlength(vertices, length(Verts)); for i := 0 to high(triangles) do begin triangles[i].v[0] := Faces[i].X; triangles[i].v[1] := Faces[i].Y; triangles[i].v[2] := Faces[i].Z; end; for i := 0 to high(verts) do vertices[i].p := verts[i]; setlength(verts,0); setlength(faces,0); //now build mesh setlength(refs,0); //to hide compiler hint for i := 0 to high(triangles) do triangles[i].deleted := false; // main iteration loop deleted_triangles := 0; triangle_count := length(triangles); for iteration := 0 to (100-1) do begin // target number of triangles reached ? Then break //printf("iteration %d - triangles %d\n",iteration,triangle_count-deleted_triangles); if(triangle_count-deleted_triangles<=target_count) then break; // update mesh once in a while if(iteration mod 5 =0) then update_mesh(iteration, triangles, vertices, refs, nrefs); // clear dirty flag for i := 0 to high(triangles) do triangles[i].dirty := false; // All triangles with edges below the threshold will be removed // The following numbers works well for most models. // If it does not, try to adjust the 3 parameters threshold := 0.000000001*power(TFloat(iteration+3),aggressiveness); // remove vertices & mark deleted triangles for i := 0 to high(triangles) do begin t := @triangles[i]; if (t^.err[3]>threshold) then continue; if (t^.deleted) then continue; if (t^.dirty) then continue; for j := 0 to 2 do begin if (t^.err[j]<threshold) then begin i0 := t^.v[ j]; v0 := @vertices[i0]; i1 := t^.v[(j+1) mod 3]; v1 := @vertices[i1]; //https://github.com/sp4cerat/Fast-Quadric-Mesh-Simplification/issues/14 // Border check //if (v0^.border <> v1^.border) then continue; if (v0^.border > 0) or (v1^.border > 0) then continue; // Compute vertex to collapse to calculate_error(i0,i1,p, vertices); setlength(deleted0, v0^.tcount); setlength(deleted1, v1^.tcount); // dont remove if flipped if( flipped(p,i1,v0^,deleted0, triangles, vertices, refs) ) then continue; if( flipped(p,i0,v1^,deleted1, triangles, vertices, refs) ) then continue; // not flipped, so remove edge v0^.p := p; v0^.q := symMatAdd(v1^.q, v0^.q); tstart := nrefs; //length(refs); update_triangles(i0,v0^,deleted0,deleted_triangles, triangles, vertices, refs, nrefs); update_triangles(i0,v1^,deleted1,deleted_triangles, triangles, vertices, refs, nrefs); tcount := nrefs - tstart;//length(refs)-tstart; if(tcount<=v0^.tcount) then begin // save ram if (tcount > 0) then move(refs[tstart], refs[v0^.tstart], tcount * sizeof(TRef)); //Move(src,dest,count); end else // append v0^.tstart := tstart; v0^.tcount := tcount; break; end; //if <threshold end; //loop j // done? if(triangle_count-deleted_triangles<=target_count) then break; end;//for i :, each triangle end; //for iteration // clean up mesh compact_mesh(triangles, vertices); //now convert back to simple structure setlength(Faces, length(triangles)); setlength(Verts, length(vertices)); for i := 0 to high(triangles) do begin Faces[i].X := triangles[i].v[0]; Faces[i].Y := triangles[i].v[1]; Faces[i].Z := triangles[i].v[2]; end; for i := 0 to high(verts) do verts[i] := vertices[i].p; if resize then scale_mesh(verts, scale); end; // simplify_mesh() procedure simplify_mesh_lossless(var faces : TFaces; var verts: TVertices); var vertices : TVs; triangles : TTs; iteration, i, j, deleted_triangles, i0, i1, tstart, tcount: integer; deleted0,deleted1: TBools; t: ^TTriangle; v0, v1: ^TVertex; p: TPoint3f; refs : TRs; nrefs: integer; begin if (length(faces) < 5) or (length(verts) < 5) then exit; //convert simple mesh to verbose structure that allows us to represent quadric properties setlength(triangles, length(Faces)); setlength(vertices, length(Verts)); for i := 0 to high(triangles) do begin triangles[i].v[0] := Faces[i].X; triangles[i].v[1] := Faces[i].Y; triangles[i].v[2] := Faces[i].Z; end; for i := 0 to high(verts) do vertices[i].p := verts[i]; setlength(verts,0); setlength(faces,0); //now build mesh setlength(refs,0); //to hide compiler hint for i := 0 to high(triangles) do triangles[i].deleted := false; // main iteration loop deleted_triangles := 1; //just to start first loop iteration := 0; while deleted_triangles > 0 do begin deleted_triangles := 0; // update mesh continuously update_mesh(iteration, triangles, vertices, refs, nrefs); iteration := iteration + 1; // clear dirty flag for i := 0 to high(triangles) do triangles[i].dirty := false; // All triangles with edges of zero will be removed // remove vertices & mark deleted triangles for i := 0 to high(triangles) do begin t := @triangles[i]; if not IsZero(t^.err[3]) then continue; if (t^.deleted) then continue; if (t^.dirty) then continue; for j := 0 to 2 do begin if IsZero(t^.err[j]) then begin i0 := t^.v[ j]; v0 := @vertices[i0]; i1 := t^.v[(j+1) mod 3]; v1 := @vertices[i1]; // Border check if(v0^.border <> v1^.border) then continue; // Compute vertex to collapse to calculate_error(i0,i1,p, vertices); setlength(deleted0, v0^.tcount); setlength(deleted1, v1^.tcount); // dont remove if flipped if( flipped(p,i1,v0^,deleted0, triangles, vertices, refs) ) then continue; if( flipped(p,i0,v1^,deleted1, triangles, vertices, refs) ) then continue; // not flipped, so remove edge v0^.p := p; v0^.q := symMatAdd(v1^.q, v0^.q); tstart := nrefs; //length(refs); update_triangles(i0,v0^,deleted0,deleted_triangles, triangles, vertices, refs, nrefs); update_triangles(i0,v1^,deleted1,deleted_triangles, triangles, vertices, refs, nrefs); tcount := nrefs - tstart;//length(refs)-tstart; if(tcount<=v0^.tcount) then begin // save ram if (tcount > 0) then move(refs[tstart], refs[v0^.tstart], tcount * sizeof(TRef)); //Move(src,dest,count); end else // append v0^.tstart := tstart; v0^.tcount := tcount; break; end; //if <threshold end; //loop j // done? end;//for i :, each triangle end; //while we are still deleting triangles // clean up mesh compact_mesh(triangles, vertices); //now convert back to simple structure setlength(Faces, length(triangles)); setlength(Verts, length(vertices)); for i := 0 to high(triangles) do begin Faces[i].X := triangles[i].v[0]; Faces[i].Y := triangles[i].v[1]; Faces[i].Z := triangles[i].v[2]; end; for i := 0 to high(verts) do verts[i] := vertices[i].p; end; // simplify_mesh_lossless() end.
// // Created by the DataSnap proxy generator. // 26/05/2017 22:28:57 // unit ClientClassesUnit1; interface uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TServerMethods1Client = class(TDSAdminRestClient) private Fpr_Registrar_GCMCommand: TDSRestCommand; public constructor Create(ARestConnection: TDSRestConnection); overload; constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function pr_Registrar_GCM(id_usuario: Integer; token: string; latidude: string; longitude: string; const ARequestFilter: string = ''): Integer; end; const TServerMethods1_pr_Registrar_GCM: array [0..4] of TDSRestParameterMetaData = ( (Name: 'id_usuario'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'token'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'latidude'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'longitude'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 6; TypeName: 'Integer') ); implementation function TServerMethods1Client.pr_Registrar_GCM(id_usuario: Integer; token: string; latidude: string; longitude: string; const ARequestFilter: string): Integer; begin if Fpr_Registrar_GCMCommand = nil then begin Fpr_Registrar_GCMCommand := FConnection.CreateCommand; Fpr_Registrar_GCMCommand.RequestType := 'GET'; Fpr_Registrar_GCMCommand.Text := 'TServerMethods1.pr_Registrar_GCM'; Fpr_Registrar_GCMCommand.Prepare(TServerMethods1_pr_Registrar_GCM); end; Fpr_Registrar_GCMCommand.Parameters[0].Value.SetInt32(id_usuario); Fpr_Registrar_GCMCommand.Parameters[1].Value.SetWideString(token); Fpr_Registrar_GCMCommand.Parameters[2].Value.SetWideString(latidude); Fpr_Registrar_GCMCommand.Parameters[3].Value.SetWideString(longitude); Fpr_Registrar_GCMCommand.Execute(ARequestFilter); Result := Fpr_Registrar_GCMCommand.Parameters[4].Value.GetInt32; end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection); begin inherited Create(ARestConnection); end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); begin inherited Create(ARestConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin Fpr_Registrar_GCMCommand.DisposeOf; inherited; end; end.
// 211. 添加与搜索单词 - 数据结构设计 // // 设计一个支持以下两种操作的数据结构: // // void addWord(word) // bool search(word) // search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。 // // 示例: // // addWord("bad") // addWord("dad") // addWord("mad") // search("pad") -> false // search("bad") -> true // search(".ad") -> true // search("b..") -> true // 说明: // // 你可以假设所有单词都是由小写字母 a-z 组成的。 // // class WordDictionary // { // // // /** Initialize your data structure here. */ // public WordDictionary() { // // } // // /** Adds a word into the data structure. */ // public void addWord(String word) { // // } // // /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ // public boolean search(String word) { // // } // } // // /** // * Your WordDictionary object will be instantiated and called as such: // * WordDictionary obj = new WordDictionary(); // * obj.addWord(word); // * boolean param_2 = obj.search(word); // */ unit DSA.LeetCode._211; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DSA.Tree.BSTMap, DSA.Utils; type TWordDictionary = class private type TNode = class private type TreeMap = specialize TBSTMap<char, TNode, TComparer_chr>; public IsWord: boolean; Next: TreeMap; constructor Create(newIsWord: boolean = False); end; var __root: TNode; function __match(node: TNode; word: string; index: integer): boolean; public /// <summary> Initialize your data structure here. </summary> constructor Create; /// <summary> Adds a word into the data structure. </summary> procedure AddWord(word: string); /// <summary> Returns if the word is in the data structure. /// A word could contain the dot character '.' to represent any one letter. /// </summary> function Search(word: string): boolean; end; procedure Main(); implementation procedure Main(); var wd: TWordDictionary; b: boolean; begin wd := TWordDictionary.Create; with wd do begin AddWord('bad'); AddWord('dad'); AddWord('mad'); b := Search('pad'); // - > false Writeln(b); b := Search('bad'); // - > true Writeln(b); b := Search('.ad'); // - > true Writeln(b); b := Search('b..'); // - > true Writeln(b); end; end; { TWordDictionary.TNode } constructor TWordDictionary.TNode.Create(newIsWord: boolean); begin IsWord := newIsWord; Next := TreeMap.Create; end; { TWordDictionary } procedure TWordDictionary.AddWord(word: string); var cur: TNode; i: integer; c: char; begin cur := __root; for i := low(word) to high(word) do begin c := word[i]; if cur.Next.Contains(c) = False then cur.Next.Add(c, TNode.Create()); cur := cur.Next.Get(c).PValue^; end; if cur.IsWord = False then begin cur.IsWord := True; end; end; constructor TWordDictionary.Create; begin __root := TNode.Create(); end; function TWordDictionary.Search(word: string): boolean; begin Result := __match(__root, word, 0); end; function TWordDictionary.__match(node: TNode; word: string; index: integer): boolean; var c: char; nextChar: char; begin if index = word.Length then Exit(node.IsWord); c := word.Chars[index]; if c <> '.' then begin if node.Next.Get(c).PValue = nil then Exit(False); Result := __match(node.Next.Get(c).PValue^, word, index + 1); end else begin for nextChar in node.Next.KeySets.ToArray do begin if __match(node.Next.Get(nextChar).PValue^, word, index + 1) then Exit(True); end; Result := False; end; end; end.
unit DirectD0; interface uses classes,Forms, SysUtils, DirectXGS, Windows, Graphics, util1,debug0,Dpalette; type {TDDcanvas définit un canvas attaché à une surface directdraw. Ce qui permet d'utiliser facilement les fonctions GDI sur une surface } TDDcanvas = class(Tcanvas) private Fsurface:IdirectDrawSurface4; public constructor Create(Asurface: IdirectDrawSurface4 ); destructor Destroy; override; end; {TDDsurface encapsule une surface DirectDraw} TDDsurface= class surface:IDirectDrawSurface4 ; canvas:TDDcanvas; canvasRef:integer; attached:boolean; lpSurface:PtabOctet; width,height,pitch:integer; constructor create(ddraw:IdirectDraw4;var surfaceDesc:TDDSURFACEDESC2); constructor createAttached(MainSurf:IdirectDrawSurface4; var BackCaps:TDDSCAPS2); destructor destroy;override; procedure initCanvas; procedure doneCanvas; procedure clear(color:integer); procedure clearRect(rr:Trect;color:integer); procedure lock; procedure unlock; function PixelAd(i,j:integer):PtabOctet; procedure FillLine(var tb;i,j,nb:integer); procedure setColorKey(n1,n2:integer); procedure restore; end; {TDDscreen permet de gérer complètement un objet directDraw en mode plein écran exclusif, avec 2 buffers, une palette et un clipper. } TDDScreen = class public ddraw:IdirectDraw4; Front, Back: TDDSurface ; PaletteON: IDirectDrawPalette ; clipper:IdirectDrawClipper; constructor Create (Width, Height, Depth: DWORD;Numguid:integer) ; destructor Destroy ; override ; procedure Flip(wait:boolean) ;virtual; procedure flipRect(rr:Trect); procedure BltBackRect(surf:TDDsurface;rr:Trect); function createSingleSurface(dx,dy:integer):TDDsurface; procedure BLT(surf:TDDsurface;x,y:integer); function getCaps:string; end ; {TDDnormalWindow permet de gérer complètement un objet directDraw en mode fenêtre normale. } TDDNormalWindow = class ( TDDscreen) public wnd0:hwnd; constructor Create(wnd:hwnd;ppal:PmaxLogPalette) ; destructor destroy;override; procedure flip(wait:boolean);override; procedure modifySize; end ; procedure initDirectD0; function createRectClipper(ddraw:IdirectDraw4; x1,y1,x2,y2:integer):IdirectDrawClipper; IMPLEMENTATION {--------- TDDcanvas -------------} constructor TDDcanvas.Create(Asurface: IdirectDrawSurface4 ); var dd:Hresult; dc:hdc; begin inherited create; Fsurface:=Asurface; dd:=Fsurface.getDC(dc); if dd<>DD_OK then messageCentral('TDDcanvas.create failed: '+longtoHexa(dd)+' '+DDerrorString(dd) ) ; handle:=dc; end; destructor TDDcanvas.Destroy; var dd:hresult; hand:Thandle; begin hand:=handle; handle:=0; if hand<>0 then begin dd:=Fsurface.releaseDC(hand); if dd<>DD_OK then messageCentral('TDDcanvas.destroy failed: '+longtoHexa(dd)+' '+DDerrorString(dd) ); end; inherited destroy; end; {------------ TDDsurface -----------} constructor TDDsurface.create(ddraw:IdirectDraw4;var surfaceDesc:TDDSURFACEDESC2); var dd:hresult; begin if ddraw=nil then begin affdebug('TDDsurface.create ddraw=nil',0); exit; end; affdebug('TDDsurface.create 001',0); dd := DDraw.CreateSurface ( SurfaceDesc, surface, nil ) ; affdebug('TDDsurface.create 002 '+Istr(dd)+DDerrorString(dd),0); if dd <> DD_OK then begin messageCentral('IDirectDraw.CreateSurface failed:' +Istr(surfaceDesc.dwWidth)+' ' +Istr(surfaceDesc.dwHeight) +longtoHexa(dd)+' '+DDerrorString(dd) ) ; exit; end; fillchar(surfaceDesc,sizeof(surfaceDesc),0); surfaceDesc.dwSize:=sizeof(surfaceDesc); affdebug('TDDsurface.create 002bis',0); dd:=surface.getSurfaceDesc(surfaceDesc); affdebug('TDDsurface.create 003',0); width:=surfaceDesc.dwWidth; height:=surfaceDesc.dwHeight; pitch:=surfaceDesc.lPitch; end; constructor TDDsurface.createAttached(MainSurf:IdirectDrawSurface4; var BackCaps:TDDSCAPS2); var dd:hresult; begin if mainSurf=nil then exit; dd := MainSurf.GetAttachedSurface (BackCaps, surface); if dd <> DD_OK then messageCentral('IDirectDrawSurface.GetAttachedSurface failed: '+longtoHexa(dd)+' '+DDerrorString(dd) ); attached:=true; end; destructor TDDsurface.destroy; var dd:hresult; begin if surface=nil then exit; doneCanvas; if (surface<>nil) and not attached then begin surface:=nil; end; end; procedure TDDsurface.initCanvas; begin if surface=nil then exit; restore; if canvasRef=0 then canvas:=TDDcanvas.create(surface); inc(canvasRef); end; procedure TDDsurface.doneCanvas; begin if surface=nil then exit; if canvasRef>0 then dec(canvasRef); if (canvas<>nil) and (canvasRef=0) then begin canvas.free; canvas:=nil; end; end; procedure TDDsurface.clear(color:integer); var TestBltEx: TDDBLTFX ; dd:hresult; begin if surface=nil then exit; fillchar(TestBltEx,sizeof(TestBltEx),0); TestBltEx.dwSize := sizeof ( TestBltEx ) ; TestBltEx.dwFillColor := Color ; dd:=Surface.Blt ( nil, nil,nil, DDBLT_COLORFILL + DDBLT_WAIT, @TestBltEx ) ; if dd<>DD_OK then messageCentral('surface.BLT failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); end; procedure TDDsurface.clearRect(rr:Trect;color:integer); var TestBltEx: TDDBLTFX ; dd:hresult; begin if surface=nil then exit; if isRectEmpty(rr) then exit; zeroMemory(@TestBltEx,sizeof(TestBltEx)); TestBltEx.dwSize := sizeof ( TestBltEx ) ; TestBltEx.dwFillColor := Color ; dd:=Surface.Blt ( @rr, nil,nil, DDBLT_COLORFILL + DDBLT_WAIT, @TestBltEx ) ; if dd<>DD_OK then messageCentral('surface.BLT failed: '+longtoHexa(dd)+' '+DDerrorString(dd) +' '+Istr(rr.left)+' '+Istr(rr.top) +' '+Istr(rr.right)+' '+Istr(rr.bottom) ); end; procedure TDDsurface.lock; var dd:hresult; surfaceDesc:TDDSURFACEDesc2; begin if surface=nil then exit; surfaceDesc.dwSize:=sizeof(surfaceDesc); dd:=surface.lock(nil,surfaceDesc,ddlock_wait,0); if dd <> DD_OK then messageCentral('surface.lock failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); lpSurface:=surfaceDesc.lpSurface; width:=surfaceDesc.dwWidth; height:=surfaceDesc.dwHeight; pitch:=surfaceDesc.lPitch; end; procedure TDDsurface.unlock; var dd:hresult; begin if surface=nil then exit; dd:=surface.unlock(nil); if dd <> DD_OK then messageCentral('surface.unlock failed: '+longtoHexa(dd)+' '+DDerrorString(dd)) ; end; function TDDsurface.PixelAd(i,j:integer):PtabOctet; var dd:hresult; begin if surface=nil then exit; PixelAd:=Pointer(integer(lpSurface)+j*pitch+i); end; procedure TDDsurface.FillLine(var tb;i,j,nb:integer); begin if surface=nil then exit; if (j<0) or (j>=height) or (i>=width) then exit; if i<0 then begin nb:=nb+i; if nb<=0 then exit; i:=0; end else if (i+nb>width) then nb:=width-i; move(tb,pixelAd(i,j)^,nb); end; procedure TDDsurface.setColorKey(n1,n2:integer); var colorKey:TDDColorKey; dd:Hresult; begin if surface=nil then exit; with colorKey do begin dwColorSpaceLowValue:=n1; dwColorSpaceHighValue:=n2; end; dd:=surface.setColorKey(DDCKEY_SrcBlt,@colorKey); if dd<>DD_OK then messageCentral('surface.setColorKey failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); end; procedure TDDsurface.restore; begin if (surface.isLost=DDerr_surfaceLost) then surface._restore; end; var RecGuid:array[0..5] of Tguid; guid0:array[0..5] of Pguid; nbGuid:integer; stDesc:string; function callBack(guid:Pguid;desc,driver:lpstr;context:pointer;hm:Thandle):bool;stdCall; begin if guid<>nil then begin recGuid[nbGuid]:=guid^; guid0[nbguid]:=@recGuid[nbGuid]; end else guid0[nbguid]:=nil; inc(nbguid); stDesc:=stDesc+desc+'|'; callBack:=true; end; procedure initDirectD0; begin InitializeDDraw; nbguid:=0; stDesc:=''; if not assigned(DirectDrawEnumerateEx) then exit; DirectDrawEnumerateEx(@callback,nil,7); delete(stDesc,length(stDesc),1); end; function createRectClipper(ddraw:IdirectDraw4; x1,y1,x2,y2:integer):IdirectDrawClipper; type TRG=record rgnDataHeader:TrgnDataHeader; rr:Trect; end; var rgn:TRG; dd:hresult; clipper:IdirectDrawClipper; begin dd:=ddraw.createClipper(0,clipper,nil); if dd <> DD_OK then messageCentral('CreateClipper failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); with rgn,rgnDataHeader do begin dwSize:=sizeof(rgnDataHeader); itype:=rdh_rectangles; nCount:=1; nRgnSize:=sizeof(Trect); rcBound:=rect(0,0,0,0); rr:=rect(x1,y1,x2,y2); end; dd:=clipper.setClipList(@rgn,0); if dd <> DD_OK then messageCentral('Clipper.setClipList failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); createRectClipper:=clipper; end; {----------------------------------------------------------- TDDSCREEN -----------------------------------------------------------} constructor TDDScreen.Create ( Width, Height, Depth: DWORD;Numguid:integer ) ; var SurfaceDesc: TDDSURFACEDESC2; BackCaps: TDDSCAPS2 ; i: Integer ; DD:hresult; ddrawBid:IdirectDraw; PalEntry: Array [ 0..255 ] of TPaletteEntry ; begin if (numGuid<0) or (numGuid>=nbGuid) then begin messageCentral('No secondary screen'); exit; end; affdebug('TDDScreen.Create 1',0); dd := DirectDrawCreate ( guid0[numGuid], DDrawBid, nil ) ; if dd <> DD_OK then messageCentral('DirectDrawCreate failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); dd:=DDrawBid.queryInterface(IID_IDirectDraw4,DDraw); if dd <> DD_OK then messageCentral('QueryInterface failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); DDrawBid:=nil ; dd := Ddraw.SetCooperativeLevel ( Application.Handle, DDSCL_FULLSCREEN + DDSCL_ALLOWREBOOT + {DDSCL_NOWINDOWCHANGES +} DDSCL_EXCLUSIVE ) ; if dd <> DD_OK then messageCentral('SetCooperativeLevel failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); dd := Ddraw.SetDisplayMode ( Width, Height, Depth,0,0 ) ; if dd <> DD_OK then messageCentral('SetDisplayMode failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); fillchar(surfaceDesc,sizeof(surfaceDesc),0); with surfaceDesc do begin dwSize:= sizeof ( SurfaceDesc ) ; dwFlags:= DDSD_CAPS + DDSD_BACKBUFFERCOUNT ; dwBackBufferCount:= 1 ; ddsCaps.dwCaps:= DDSCAPS_PRIMARYSURFACE + DDSCAPS_FLIP + DDSCAPS_COMPLEX; end; Front:=TDDsurface.create(Ddraw, SurfaceDesc); BackCaps.dwCaps := DDSCAPS_BACKBUFFER ; Back:=TDDsurface.createAttached(Front.surface,BackCaps); for i:=0 to 255 do with PalEntry [i] do begin peRed :=0 ; peGreen :=i ; peBlue :=0 ; peFlags := 0 ; end ; dd:=Ddraw.CreatePalette ( DDPCAPS_8BIT+DDPCAPS_Allow256, @PalEntry[0], PaletteON, nil ) ; if dd<>DD_OK then messageCentral('ddraw.createPalette failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); dd:=Front.surface.SetPalette ( PaletteOn ) ; if dd<>DD_OK then messageCentral('surface.setPalette failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); dd:=PaletteON.setEntries(0,0,256,@PalEntry[0]); if dd<>DD_OK then messageCentral('palette.setEntries failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); clipper:=createRectClipper(ddraw,0,0,640,480); dd:=front.surface.setClipper(clipper); if dd<>DD_OK then messageCentral('surface.setClipper failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); dd:=back.surface.setClipper(clipper); if dd<>DD_OK then messageCentral('surface.setClipper failed: '+longtoHexa(dd)+' '+DDerrorString(dd)); affdebug('TDDScreen.Create 2',0); end ; destructor TDDScreen.Destroy ; begin if ddraw=nil then exit; clipper:=nil; {paletteON:=nil;} back.free; Front.free; Ddraw:=nil ; inherited Destroy ; end ; procedure TDDScreen.Flip(wait:boolean) ; var v:longint; dd:hresult; b:longint; DDBLTFX:TDDBLTFX; begin if ddraw=nil then exit; repeat until dd_ok=Front.surface.Flip ( nil, DDFLIP_WAIT *ord(wait)) ; end ; procedure TDDscreen.flipRect(rr:Trect); var DDBLTFX:TDDBLTFX; dd:hresult; begin fillchar(DDBLTFX,sizeof(DDBLTFX),0); DDBLTFX.dwSize:= sizeof ( DDBLTFX ) ; dd:=front.surface.blt(@rr,back.surface,@rr,0,@DDBLTFX); end; procedure TDDscreen.BltBackRect(surf:TDDsurface;rr:Trect); var DDBLTFX:TDDBLTFX; dd:hresult; begin fillchar(DDBLTFX,sizeof(DDBLTFX),0); DDBLTFX.dwSize:= sizeof ( DDBLTFX ) ; dd:=back.surface.blt(@rr,surf.surface,@rr,DDBLT_keySrc,@DDBLTFX); end; function TDDscreen.createSingleSurface(dx,dy:integer):TDDsurface; var SurfaceDesc: TDDSURFACEDESC2; begin if ddraw=nil then exit; fillchar(surfaceDesc,sizeof(surfaceDesc),0); with surfaceDesc do begin dwSize:= sizeof ( SurfaceDesc ) ; dwFlags:= DDSD_CAPS+DDSD_height+DDSD_width; ddsCaps.dwCaps:= DDSCAPS_offscreenPlain; dwWidth:=dx; dwHeight:=dy; end; createSingleSurface:=TDDsurface.create(Ddraw, SurfaceDesc); end ; procedure TDDscreen.BLT(surf:TDDsurface;x,y:integer); var DDBLTFX:TDDBLTFX; var rr1,rr2:Trect; dd:hresult; begin if ddraw=nil then exit; { BLT se plante quand x et y sont simultanément égaux à zéro. Provisoirement, on interdit le blt sur le point (0,0) Il faut aussi que les deux rectangles aient les mêmes dimensions. } if (x<=-surf.width+1) or (y<=-surf.height+1) then exit; fillchar(DDBLTFX,sizeof(DDBLTFX),0); DDBLTFX.dwSize:= sizeof ( DDBLTFX ) ; if (x=0) and (y=0) and (back.width=surf.width) and (back.height=surf.height) then begin dd:=back.surface.blt(nil,surf.surface,nil, DDBLT_keySrc, @DDBLTFX); end else if (x<=0) and (y<=0) then begin rr1:=rect(-x+1,-y+1,surf.width,surf.height); rr2:=rect(1,1,x+surf.width,y+surf.height); dd:=back.surface.blt(@rr2,surf.surface,@rr1, DDBLT_keySrc, @DDBLTFX); end else begin rr1:=rect(0,0,surf.width,surf.height); rr2:=rect(x,y,x+surf.width,y+surf.height); dd:=back.surface.blt(@rr2,surf.surface,@rr1, DDBLT_keySrc, @DDBLTFX); end; if dd <> DD_OK then messageCentral('surface.blt failed: '+ Istr(x)+' '+Istr(y)+' '+ Istr(x+surf.width)+' '+ Istr(y+surf.height) + ' '+ Istr(back.width)+' '+ Istr(back.height)+ longtoHexa(dd)+' '+DDerrorString(dd)); end; function TDDscreen.getCaps:string; var bb:array[1..1000] of byte; DDdriverCaps:TDDCaps absolute bb; DDHelCaps:TDDCaps; st:string; dd:hresult; begin if ddraw=nil then exit; fillchar(DDdriverCaps,sizeof(DDdriverCaps),0); fillchar(DDHelCaps,sizeof(DDHelCaps),0); DDdriverCaps.dwSize:=sizeof(DDdriverCaps); DDHelCaps.dwSize:=sizeof(DDHelCaps); dd:=ddraw.getCaps(DDdriverCaps,DDhelCaps); with DDdriverCaps do st:= 'hResult= ' +longtoHexa(dd)+' '+DDerrorString(dd)+#13+#10+ 'DwCaps= ' +longtoHexa(DwCaps)+#13+#10+ 'DwCaps2= ' +longtoHexa(DwCaps2)+#13+#10+ 'DwCkeyCaps= ' +longtoHexa(DwCkeyCaps)+#13+#10+ 'DwFXCaps= ' +longtoHexa(DwFXCaps)+#13+#10+ 'DwFXAlphaCaps= ' +longtoHexa(DwFXAlphaCaps)+#13+#10+ 'DwPalCaps= ' +longtoHexa(DwPalCaps)+#13+#10+ 'VidMemTotal= ' +Istr(dwVidMemTotal)+#13+#10+ 'VidMemFree= ' +Istr(dwVidMemFree)+#13+#10 ; getCaps:=st; end; {----------------------------------------------------------- TDDNormalWindow -----------------------------------------------------------} constructor TDDNormalWindow.Create(wnd:hwnd;ppal:PmaxLogPalette) ; var SurfaceDesc: TDDSURFACEDESC2; BackCaps: TDDSCAPS ; i: Integer ; DD:hresult; ddrawBid:IdirectDraw; PalEntry: Array [ 0..255 ] of TPaletteEntry ; dc:hdc; rect:Trect; clp:IdirectDrawClipper; begin wnd0:=wnd; dd := DirectDrawCreate ( guid0[0], DDrawBid, nil ) ; affdebug('NW DirectDrawCreate : '+longtoHexa(dd)+' '+DDerrorString(dd),0); dd:=DDrawBid.queryInterface(IID_IDirectDraw4,DDraw); affdebug('NW QueryInterface : '+longtoHexa(dd)+' '+DDerrorString(dd),0); DDrawBid:=nil; affdebug('TDDNormalWindow.Create 4',0) ; dd := Ddraw.SetCooperativeLevel ( 0, DDSCL_NORMAL ); affdebug('NW SetCooperativeLevel : '+longtoHexa(dd)+' '+DDerrorString(dd),0); fillchar(surfaceDesc,sizeof(surfaceDesc),0); with SurfaceDesc do begin dwSize:= sizeof ( SurfaceDesc ) ; dwFlags:= DDSD_CAPS ; ddsCaps.dwCaps:= DDSCAPS_PRIMARYSURFACE ; end; affdebug('Avant TDDsurface.create',0); Front:=TDDsurface.create(Ddraw, SurfaceDesc); affdebug('Front.surface='+longtoHexa(integer(front.surface)),0) ; affdebug('TDDNormalWindow.Create 6',0) ; getClientRect(wnd,rect); Back:=createSingleSurface(rect.right,rect.bottom); affdebug('Back='+Istr(integer(back))+' '+Istr(rect.right)+' '+Istr(rect.bottom),0); dd:=ddraw.createClipper(0,clipper,nil); affdebug('NW CreateClipper : '+longtoHexa(dd)+' '+DDerrorString(dd),0); dd:=Clipper.setHwnd(0,wnd0); affdebug('NW Clipper.setHwnd : '+longtoHexa(dd)+' '+DDerrorString(dd),0); dd:=front.surface.setClipper(clipper); affdebug('surface.setClipper : '+longtoHexa(dd)+' '+DDerrorString(dd),0); with rect do clp:=createRectClipper(ddraw,left,top,right,bottom); dd:=back.surface.setClipper(clp); affdebug('surface.setClipper : '+longtoHexa(dd)+' '+DDerrorString(dd),0 ); clp:=nil; affdebug('TDDNormalWindow.Create 9',0) ; fillchar(surfaceDesc,sizeof(surfaceDesc),0); surfaceDesc.dwSize:=sizeof(surfaceDesc); dd:=front.surface.getSurfaceDesc(surfaceDesc); affdebug('NW getSurfaceDesc :'+longtoHexa(dd)+' '+DDerrorString(dd),0 ); if surfaceDesc.ddpfPixelFormat.dwFlags and DDPF_PaletteIndexed8 <>0 then begin affdebug('TDDNormalWindow.Create 10bis',0); dc:=getDC(0); affdebug('TDDNormalWindow.Create 10bis 1',0); getSystemPaletteEntries(dc,0,256,PalEntry); affdebug('TDDNormalWindow.Create 10bis 2',0); releaseDC(0,dc); affdebug('TDDNormalWindow.Create 10bis 3',0); if ppal<>nil then for i:=0 to 159 do palEntry[10+i]:=ppal^.palpalEntry[i]; {fillchar(palEntry,sizeof(palEntry),0);} for i:=0 to 9 do with palEntry[i] do begin peflags:=pc_explicit; peRed:=i; end; for i:=10 to 245 do with palEntry[i] do begin peflags:=pc_noCollapse or pc_reserved; end; for i:=246 to 255 do with palEntry[i] do begin peflags:=pc_explicit; peRed:=i; end; dd:=Ddraw.CreatePalette ( DDPCAPS_8BIT, @PalEntry[0], PaletteON, nil ) ; affdebug('NW ddraw.createPalette : '+longtoHexa(dd)+' '+DDerrorString(dd)+' '+Bstr(dd=DD_OK),0); affDebug('Front.surface.isLost= '+longtoHexa(Front.surface.isLost),0); dd:=Front.surface.SetPalette ( PaletteOn ) ; affdebug('NW surface.setPalette : '+longtoHexa(dd)+' '+DDerrorString(dd)+' '+Bstr(dd=DD_OK),0); dd:=back.surface.SetPalette ( PaletteOn ) ; affdebug('NW surface.setPalette : '+longtoHexa(dd)+' '+DDerrorString(dd)+' '+Bstr(dd=DD_OK),0); end; affdebug('TDDNormalWindow.Create 20',0) ; {Front.clear(0);} end ; destructor TDDNormalWindow.destroy; begin inherited; affdebug('TDDNormalWindow.destroy',0); end; { procedure TDDNormalWindow.updateClipper; var dd:hresult; begin dd:=Clipper.setHwnd(0,wnd0); if dd <> DD_OK then raise Exception.Create ( Format ('NW Clipper.setHwnd failed: %x', [ dd ] ) ) ; dd:=front.surface.setClipper(clipper); if dd<>DD_OK then raise Exception.Create ( Format ( 'surface.setClipper failed: %x', [ dd ] ) ) ; end; } procedure TDDNormalWindow.flip(wait:boolean); var DDBLTFX:TDDBLTFX; var rr1,rr2:Trect; dd:hresult; p:Tpoint; b,v:longint; begin fillchar(DDBLTFX,sizeof(DDBLTFX),0); DDBLTFX.dwSize:= sizeof ( DDBLTFX ) ; if wait then ddraw.waitForVerticalBlank(DDwaitVB_blockBegin,0); { if wait then repeat v:=Ddraw.GetVerticalBlankStatus(@b); until b<>0; } rr1:=rect(0,0,back.width,back.height); p:=point(0,0); windows.clientToScreen(wnd0,p); rr2:=rect(p.x,p.y,p.x+back.width,p.y+back.height); dd:=front.surface.blt(@rr2,back.surface,@rr1, 0, @DDBLTFX); end; procedure TDDNormalWindow.modifySize; var rect:Trect; clp:IdirectDrawClipper; dd:integer; begin getClientRect(wnd0,rect); back.free; Back:=createSingleSurface(rect.right,rect.bottom); with rect do clp:=createRectClipper(ddraw,left,top,right,bottom); dd:=back.surface.setClipper(clp); affdebug('surface.setClipper : '+longtoHexa(dd)+' '+DDerrorString(dd),0 ); clp:=nil; dd:=back.surface.SetPalette ( PaletteOn ) ; end; initialization initDirectD0; affdebug('initialization initDirectD0',0); end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFv8Interceptor; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes, uCEFv8Types; type TCefV8InterceptorOwn = class(TCefBaseRefCountedOwn, ICefV8Interceptor) protected function GetByName(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean; virtual; function GetByIndex(index: integer; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean; virtual; function SetByName(const name: ustring; const obj, value: ICefv8Value; const exception: ustring): boolean; virtual; function SetByIndex(index: integer; const obj, value: ICefv8Value; const exception: ustring): boolean; virtual; public constructor Create; virtual; end; TCefFastV8Interceptor = class(TCefV8InterceptorOwn) protected FGetterByName : TCefV8InterceptorGetterByNameProc; FSetterByName : TCefV8InterceptorSetterByNameProc; FGetterByIndex : TCefV8InterceptorGetterByIndexProc; FSetterByIndex : TCefV8InterceptorSetterByIndexProc; function GetByName(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean; override; function GetByIndex(index: integer; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean; override; function SetByName(const name: ustring; const obj, value: ICefv8Value; const exception: ustring): boolean; override; function SetByIndex(index: integer; const obj, value: ICefv8Value; const exception: ustring): boolean; override; public constructor Create(const getterbyname : TCefV8InterceptorGetterByNameProc; const setterbyname : TCefV8InterceptorSetterByNameProc; const getterbyindex : TCefV8InterceptorGetterByIndexProc; const setterbyindex : TCefV8InterceptorSetterByIndexProc); reintroduce; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFv8Value; function cef_v8_interceptor_get_byname(self: PCefV8Interceptor; const name: PCefString; const obj: PCefV8Value; out retval: PCefv8Value; exception: PCefString): Integer; stdcall; var ret: ICefv8Value; begin Result := Ord(TCefV8InterceptorOwn(CefGetObject(self)).GetByName(CefString(name), TCefv8ValueRef.UnWrap(obj), ret, CefString(exception))); retval := CefGetData(ret); end; function cef_v8_interceptor_get_byindex(self: PCefV8Interceptor; index: integer; const obj: PCefV8Value; out retval: PCefv8Value; exception: PCefString): integer; stdcall; var ret: ICefv8Value; begin Result := Ord(TCefV8InterceptorOwn(CefGetObject(self)).GetByIndex(index, TCefv8ValueRef.UnWrap(obj), ret, CefString(exception))); retval := CefGetData(ret); end; function cef_v8_interceptor_set_byname(self: PCefV8Interceptor; const name: PCefString; const obj: PCefV8Value; value: PCefv8Value; exception: PCefString): integer; stdcall; begin Result := Ord(TCefV8InterceptorOwn(CefGetObject(self)).SetByName(CefString(name), TCefv8ValueRef.UnWrap(obj), TCefv8ValueRef.UnWrap(value), CefString(exception))); end; function cef_v8_interceptor_set_byindex(self: PCefV8Interceptor; index: integer; const obj: PCefV8Value; value: PCefv8Value; exception: PCefString): integer; stdcall; begin Result := Ord(TCefV8InterceptorOwn(CefGetObject(self)).SetByIndex(index, TCefv8ValueRef.UnWrap(obj), TCefv8ValueRef.UnWrap(value), CefString(exception))); end; // TCefV8InterceptorOwn constructor TCefV8InterceptorOwn.Create; begin inherited CreateData(SizeOf(TCefV8InterceptorOwn)); with PCefV8Interceptor(FData)^ do begin get_byname := cef_v8_interceptor_get_byname; get_byindex := cef_v8_interceptor_get_byindex; set_byname := cef_v8_interceptor_set_byname; set_byindex := cef_v8_interceptor_set_byindex; end; end; function TCefV8InterceptorOwn.GetByName(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean; begin Result := False; end; function TCefV8InterceptorOwn.GetByIndex(index: integer; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean; begin Result := False; end; function TCefV8InterceptorOwn.SetByName(const name: ustring; const obj, value: ICefv8Value; const exception: ustring): boolean; begin Result := False; end; function TCefV8InterceptorOwn.SetByIndex(index: integer; const obj, value: ICefv8Value; const exception: ustring): boolean; begin Result := False; end; // TCefFastV8Interceptor constructor TCefFastV8Interceptor.Create(const getterbyname : TCefV8InterceptorGetterByNameProc; const setterbyname : TCefV8InterceptorSetterByNameProc; const getterbyindex : TCefV8InterceptorGetterByIndexProc; const setterbyindex : TCefV8InterceptorSetterByIndexProc); begin FGetterByName := getterbyname; FSetterByName := setterbyname; FGetterByIndex := getterbyindex; FSetterByIndex := setterbyindex; end; function TCefFastV8Interceptor.GetByName(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean; begin if assigned(FGetterByName) then Result := FGetterByName(name, obj, retval, exception) else Result := False; end; function TCefFastV8Interceptor.GetByIndex(index: integer; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean; begin if assigned(FGetterByIndex) then Result := FGetterByIndex(index, obj, retval, exception) else Result := False; end; function TCefFastV8Interceptor.SetByName(const name: ustring; const obj, value: ICefv8Value; const exception: ustring): boolean; begin if assigned(FSetterByName) then Result := FSetterByName(name, obj, value, exception) else Result := False; end; function TCefFastV8Interceptor.SetByIndex(index: integer; const obj, value: ICefv8Value; const exception: ustring): boolean; begin if assigned(FSetterByIndex) then Result := FSetterByIndex(index, obj, value, exception) else Result := False; end; end.
unit feli_stack_tracer; {$mode objfpc} interface uses fpjson; type FeliStackTrace = class(TObject) public class procedure trace(kind, name: ansiString); static; class procedure reset(); static; class procedure out(load: String); static; class procedure breakPoint(); static; end; function simpleSpaceReplaceText(str: ansiString): ansiString; implementation uses feli_file, feli_constants, feli_config, sysutils; function simpleSpaceReplaceText(str: ansiString): ansiString; var i: integer; tempStr: ansiString; begin tempStr := ''; for i := 1 to length(str) do begin if ((i - 1) mod 4) = 0 then tempStr := tempStr + '|' else tempStr := tempStr + ' '; end; result := tempStr; end; class procedure FeliStackTrace.trace(kind, name: ansiString); static; var tempString, spaces: ansiString; i, depth: integer; begin if (FeliConfig.getIsDebug()) then begin spaces := ''; tempString := FeliFileAPI.get(stackTraceDepthPath); depth := StrToInt(trim(tempString)); case kind of 'begin': depth := depth + 1; 'end': depth := depth - 1; end; if ((depth - 3) <> 0) then for i := 0 to (depth - 3) do spaces := spaces + '| '; case kind of 'begin': depth := depth + 1; 'end': depth := depth - 1; end; tempString := kind; if (tempString = 'end') then tempString := ' end '; spaces := simpleSpaceReplaceText(spaces); writeln(format('%s[%s] %s', [spaces, tempString, name])); FeliFileAPI.put(stackTraceDepthPath, IntToStr(depth)); end; end; class procedure FeliStackTrace.out(load: String); static; var tempString, spaces: ansiString; i, depth: integer; begin spaces := ''; tempString := FeliFileAPI.get(stackTraceDepthPath); depth := StrToInt(trim(tempString)); if ((depth - 4) <> 0) then for i := 0 to (depth - 4) do spaces := spaces + '| '; if (tempString = 'end') then tempString := ' end '; spaces := simpleSpaceReplaceText(spaces); writeln(format('%s%s', [spaces, load])); end; class procedure FeliStackTrace.reset(); static; begin FeliFileAPI.put(stackTraceDepthPath, '1'); end; class procedure FeliStackTrace.breakPoint(); static; begin write('Press Enter to continue'); readln(); end; end.
unit PreFileList; {$mode objfpc}{$H+} interface uses Classes, SysUtils, PreFile; Type TPreFileList = class private { private declarations } FPreFileList : TList; protected { protected declarations } public { public declarations } constructor Create; procedure Add(pPreFile: TPreFile); procedure Delete(Index: Integer); function Count: Integer; function Items(index: integer): TPreFile; procedure Free; procedure Clear; published { published declarations } end; implementation constructor TPreFileList.Create; begin inherited Create; FPreFileList := TList.Create; end; function TPreFileList.Count: Integer; begin Result := FPreFileList.Count; end; procedure TPreFileList.Add(pPreFile: TPreFile); begin FPreFileList.Add(pPreFile); end; procedure TPreFileList.Delete(Index: Integer); begin FPreFileList.Delete(Index) end; function TPreFileList.Items(index: integer): TPreFile; begin result:=TPreFile(FPreFileList.Items[index]); end; procedure TPreFileList.Free; begin FPreFileList.Free; end; procedure TPreFileList.Clear; begin FPreFileList.Clear; end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Edit, FMX.StdCtrls, FMX.Platform, FMX.Notification, FMX.ListBox, FMX.Layouts; type TSettingBadgeNumberForm = class(TForm) btnSetBadgeNumber: TButton; ToolBar1: TToolBar; Label1: TLabel; ListBox1: TListBox; ListBoxItem1: TListBoxItem; nbBadgeNumber: TNumberBox; btnBadgeNumberDown: TButton; btnBadgeNumberUp: TButton; btnResetBadgeNumber: TButton; procedure btnSetBadgeNumberClick(Sender: TObject); procedure btnBadgeNumberDownClick(Sender: TObject); procedure btnBadgeNumberUpClick(Sender: TObject); procedure btnResetBadgeNumberClick(Sender: TObject); procedure FormCreate(Sender: TObject); private function GetBadgeNumber: single; public { Public declarations } end; var SettingBadgeNumberForm: TSettingBadgeNumberForm; implementation {$R *.fmx} uses iOSapi.UIKit; procedure TSettingBadgeNumberForm.btnSetBadgeNumberClick(Sender: TObject); var NotificationService: IFMXNotificationCenter; begin { verify if the service is actually supported } if TPlatformServices.Current.SupportsPlatformService(IFMXNotificationCenter) then NotificationService := TPlatformServices.Current.GetPlatformService(IFMXNotificationCenter) as IFMXNotificationCenter; { set Icon Badge Number } if Assigned(NotificationService) then NotificationService.SetIconBadgeNumber(Trunc(nbBadgeNumber.Value)); end; procedure TSettingBadgeNumberForm.FormCreate(Sender: TObject); begin { display current Icon Badge Number } nbBadgeNumber.Value := GetBadgeNumber; end; procedure TSettingBadgeNumberForm.btnBadgeNumberDownClick(Sender: TObject); begin nbBadgeNumber.Value := nbBadgeNumber.Value - 1; end; procedure TSettingBadgeNumberForm.btnBadgeNumberUpClick(Sender: TObject); begin nbBadgeNumber.Value := nbBadgeNumber.Value + 1; end; procedure TSettingBadgeNumberForm.btnResetBadgeNumberClick(Sender: TObject); var NotificationService: IFMXNotificationCenter; begin { verify if the service is actually supported } if TPlatformServices.Current.SupportsPlatformService(IFMXNotificationCenter) then NotificationService := TPlatformServices.Current.GetPlatformService(IFMXNotificationCenter) as IFMXNotificationCenter; { reset Icon Badge Number } if Assigned(NotificationService) then NotificationService.ResetIconBadgeNumber; nbBadgeNumber.Value := 0; end; function TSettingBadgeNumberForm.GetBadgeNumber; begin Result:= TUIApplication.Wrap(TUIApplication.OCClass.sharedApplication).applicationIconBadgeNumber; end; end.
unit PE.Imports.Lib; interface uses System.Classes, System.SysUtils, PE.Common, PE.Imports.Func; type TPEImportLibrary = class private FName: String; // imported library name FBound: Boolean; FFunctions: TPEImportFunctions; FTimeDateStamp: uint32; FOriginal: boolean; procedure CheckAddingToOriginalLib; public // Relative address of IAT region for this library. // It is address of first word in array of words (4/8 bytes) corresponding // to each imported function in same order as in Functions list. // // Each RVA is patched by loader if it's mapped into process memory. // // If image is not bound loader get address of function and write it at RVA. // If image is bound nothing changed because value at RVA is already set. // // This value is modified when import directory parsed on loading or // when import directory is rebuilt. IatRva: TRVA; constructor Create(const AName: String; Bound: Boolean = False; Original: Boolean = False); destructor Destroy; override; function NewFunction(const Name: string): TPEImportFunction; overload; function NewFunction(Ordinal: uint16): TPEImportFunction; overload; property Name: String read FName; // List of imported functions. // Order must be kept to match array of words at IatRva. property Functions: TPEImportFunctions read FFunctions; property Bound: Boolean read FBound; property TimeDateStamp: uint32 read FTimeDateStamp write FTimeDateStamp; // True if it is library parsed from executable. // You can't add new functions to this library, because IAT must stay untouched. // Add new library instead. property Original: boolean read FOriginal; end; implementation { TImportLibrary } constructor TPEImportLibrary.Create(const AName: String; Bound: Boolean; Original: Boolean); begin inherited Create; FFunctions := TPEImportFunctions.Create; FName := AName; FBound := Bound; FOriginal := Original; end; destructor TPEImportLibrary.Destroy; begin FFunctions.Free; inherited; end; procedure TPEImportLibrary.CheckAddingToOriginalLib(); begin if (Original) then raise Exception.Create('You can''t add new function to original library.'); end; function TPEImportLibrary.NewFunction(const Name: string): TPEImportFunction; begin CheckAddingToOriginalLib(); Result := TPEImportFunction.Create(Name); FFunctions.Add(Result); end; function TPEImportLibrary.NewFunction(Ordinal: uint16): TPEImportFunction; begin CheckAddingToOriginalLib(); Result := TPEImportFunction.Create('', Ordinal); FFunctions.Add(Result); end; end.
unit NewFrontiers.Entity.Engineering; interface uses NewFrontiers.Entity, NewFrontiers.Entity.Mapping; type /// <summary> /// Die Klasse stellt Funktionen bereit, um ein Entity in der Datenbank /// anzulegen /// </summary> TForwardEngineering = class public /// <summary> /// Erzeugt die Tabelle, den Generator und die Felder in der /// Datenbank sofern diese nicht bereits angelegt sind. Kann beliebig /// oft aufgerufen werden /// </summary> class procedure forwardEngineer<T: class, constructor>(); end; implementation uses NewFrontiers.Database, System.SysUtils; { TForwardEngineering } class procedure TForwardEngineering.forwardEngineer<T>; var mapping: TEntityMapping; sql: string; query: TNfsQuery; aktFeld: TEntityField; begin // TODO: Queries kann man auch hübscher schreiben. mapping := TEntityMappingDictionary.getMappingFor(T); query := TDatabaseProvider.getQuery(); query.Transaction.StartTransaction; // Tabelle anlegen sql := 'EXECUTE BLOCK AS BEGIN ' + 'if (not exists(select 1 from rdb$relations where rdb$relation_name = "' + UpperCase(mapping.Tablename) + '")) then ' + 'execute statement "create table ' + mapping.Tablename + ' ( ' + mapping.Primary + ' integer );"; ' + 'END'; query.SQL.Text := sql; query.execute(); // Generator anlegen sql := 'EXECUTE BLOCK AS BEGIN ' + 'if (not exists(select 1 from rdb$generators where rdb$generator_name = "' + UpperCase(mapping.Generator) + '")) then ' + 'execute statement "create generator ' + mapping.Generator + ';"; ' + 'END'; query.SQL.Text := sql; query.execute(); // Felder prüfen for aktFeld in mapping.Fields do begin sql := 'EXECUTE BLOCK AS BEGIN ' + 'if (not exists(select 1 from rdb$RELATION_FIELDS where rdb$relation_name = "' + UpperCase(mapping.Tablename) + '" and rdb$field_name = "' + UpperCase(mapping.Prefix + '_' + aktFeld.Fieldname) + '")) then ' + 'execute statement "alter table ' + mapping.Tablename + ' add ' + mapping.Prefix + '_' + aktFeld.Fieldname + ' ' + aktFeld.DBType + ';"; ' + 'END'; query.SQL.Text := sql; query.execute(); end; query.transaction.Commit; query.Free; end; end.
program lab_9; function getNumber(numbers: string):integer; begin if (numbers = 'positive') then begin getNumber:= random(50) + 1;// [1-50] exit; end; if (numbers = 'negative') then begin getNumber:= random(50) - 51;//[(-1)-(-50)] exit; end; end; procedure printFileOnWindow(pathToFile: string); var number: integer; f: file of integer; begin //Open file for reading Assign(f, pathToFile); Reset(f); while not eof(f) do begin read(f, number); write(number); end; //close file close(f); end; procedure sortingFileFandH(pathToFileF: string; pathToFileG: string; pathToTempFile: string); var number: integer; fileF, fileG, tempFile: file of integer; begin assign(fileF, pathToFileF); assign(fileG, pathToFileG); assign(tempFile, pathToTempFile); reset(fileF); rewrite(fileG); rewrite(tempFile); while not eof(fileF) do begin read(fileF, number); if (number < 0) then write(fileG, number) else write(tempFile, number); end; close(fileF); close(fileG); close(tempFile); //delete old file erase(fileF); rename(fileG, pathToFileF); writeln('Result sorting:'); write('Negative numbers "fileNameF"-> '); printFileOnWindow(pathToFileF); writeln; write('Positive numbers "fileNameH"-> '); printFileOnWindow(pathToTempFile); writeln; end; procedure sortingFilesTaskOne(pathToFileF: string; pathToFileG: string; pathToTempFile: string); var numberF, numberTemp: integer; fileF, fileG, tempFile: file of integer; begin assign(fileF, pathToFileF); assign(fileG, pathToFileG); assign(tempFile, pathToTempFile); reset(fileF); rewrite(fileG); reset(tempFile); while not eof(fileF) do begin read(fileF, numberF); read(tempFile, numberTemp); write(fileG, numberF); write(fileG, numberTemp); end; close(fileF); close(fileG); close(tempFile); write('Result -> '); printFileOnWindow(pathToFileG); writeln; end; procedure sortingFilesTaskTwo(pathToFileF: string; pathToFileG: string; pathToTempFile: string); var numberF, numberTemp: integer; fileF, fileG, tempFile: file of integer; begin assign(fileF, pathToFileF); assign(fileG, pathToFileG); assign(tempFile, pathToTempFile); reset(fileF); rewrite(fileG); reset(tempFile); //first positive numbers while not eof(tempFile) do begin read(tempFile, numberTemp); write(fileG, numberTemp); end; //negative numbers while not eof(fileF) do begin read(fileF, numberF); write(fileG, numberF); end; close(fileF); close(fileG); close(tempFile); write('Result -> '); printFileOnWindow(pathToFileG); writeln; end; procedure sortingFilesTaskThree(pathToFileF: string; pathToFileG: string; pathToTempFile: string); var numberF, numberTemp: integer; fileF, fileG, tempFile: file of integer; filesSize, number, id: integer; numbers: string:= 'positive'; point, pointF, pointTemp: integer; begin //default val point:= 0; pointF:= 0; pointTemp:= 0; assign(fileF, pathToFileF); assign(fileG, pathToFileG); assign(tempFile, pathToTempFile); reset(fileF); rewrite(fileG); reset(tempFile); //set size two files filesSize:= FileSize(fileF) + FileSize(tempFile); for id:= 0 to (filesSize - 1) do begin if (point > 1) then begin //set default val point:= 0; //set utput numbers: -2, -22, 1, 23.. if (numbers = 'negative') then numbers:= 'positive' else numbers:= 'negative'; end; if (numbers = 'negative') then begin Seek(fileF, pointF); read(fileF, number); inc(pointF); end; if (numbers = 'positive') then begin Seek(tempFile, pointTemp); read(tempFile, number); inc(pointTemp); end; write(fileG, number); //inc inc(point); end; close(fileF); close(fileG); close(tempFile); write('Result -> '); printFileOnWindow(pathToFileG); writeln; end; //...число компонент в файле f делится на 4 const COUNT_NUMBERS_FILE = 40; var fileNameF: file of integer; pathToFileF: string:= 'files\fileNameF.ak'; pathToFileG: string:= 'files\fileNameG.ak'; pathToTempFile: string:= 'files\temp\fileNameH.ak'; id, number: integer; point: integer:= 0; numbers: string:= 'negative'; begin Assign(fileNameF, pathToFileF); //Set numbers in File, observing the conditions lab 9 Rewrite(fileNameF); for id:= 0 to (COUNT_NUMBERS_FILE - 1) do begin if (point > 1) then begin //set default val point:= 0; //set utput numbers: 2, 22, -1, -23.. if (numbers = 'negative') then numbers:= 'positive' else numbers:= 'negative'; end; number:= getNumber(numbers); write(fileNameF, number); //inc inc(point); end; //close file close(fileNameF); write('Data filled file "fileNameF.ak" -> '); printFileOnWindow(pathToFileF); writeln; writeln; //Sorting files sortingFileFandH(pathToFileF, pathToFileG, pathToTempFile); writeln; writeln('а) не было двух соседних чисел с одинаковым знаком;'); sortingFilesTaskOne(pathToFileF, pathToFileG, pathToTempFile); writeln; writeln('б) вначале шли положительные, затем отрицательные числа;'); sortingFilesTaskTwo(pathToFileF, pathToFileG, pathToTempFile); writeln; writeln('в) числа шли в следующем порядке: два положительных, два отрицательных'); sortingFilesTaskThree(pathToFileF, pathToFileG, pathToTempFile); end.
unit Stmerror; INTERFACE {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses classes, util1,Dgraphic,Ncdef2,debug0; var E_InvalidObjectNam:integer; E_InvalidObjectType:integer; E_InvalidVariable:integer; procedure AfficherMessageErreurEXE(num:integer); procedure InstallError(var num:integer;st:AnsiString); function getErrorString(num:integer):AnsiString; procedure AfficherMessageErreurEXE2(num:integer;stError:AnsiString); IMPLEMENTATION const ErrorList:TstringList=nil; procedure InstallError(var num:integer;st:AnsiString); var i:integer; begin if not assigned(ErrorList) then begin errorList:=TstringList.create; errorList.add(''); end; num:=errorList.add(st) +10000; end; function getErrorString(num:integer):AnsiString; begin if num=999 then begin result:=GenericExeError; exit; end; num:=num-10000; with errorList do begin if (num>0) and (num<count) then result:=strings[num] else result:=''; end; end; procedure AfficherMessageErreurEXE(num:integer); var i:integer; BoiteInfo:typeBoiteInfo; st:AnsiString; begin { st:=''; if num=1 then st:=errorEXEMsg else with errorList do begin i:=indexOfObject(pointer(num)); if i>=0 then st:=strings[i]; end; with Boiteinfo do begin init('ERROR'); writeln('Run-time error '+Istr(num)); writeln(st); done(formStm.handle); end; } end; procedure AfficherMessageErreurEXE2(num:integer;stError:AnsiString); var i:integer; BoiteInfo:typeBoiteInfo; st:AnsiString; begin st:=''; if num=1 then st:=stError else with errorList do begin i:=indexOfObject(pointer(num)); if i>=0 then st:=strings[i]; end; with Boiteinfo do begin init('ERROR'); writeln('Run-time error '+Istr(num)); writeln(st); done; end; end; procedure InstallStdErrors; begin installError( E_parametre,'Invalid parameter'); installError( E_mem,'Not enough memory to perform operation'); installError( E_NumFichier,'Invalid file number'); installError( E_lecture,'Read error'); installError( E_FichierNonConforme,'Invalid Acquis1 data file'); installError( E_FichierNonOuvert,'File not open'); installError( E_TamponMoyenneNonAlloue,'Average buffer not allocated'); installError( E_pile,'Stack overflow'); installError( E_fenetre,'Invalid window parameters or too many windows'); installError( E_FichierDejaOuvert,'File already open'); installError( E_NomDeFichierIncorrect,'Invalid file name'); installError( E_fichierInexistant,'File does not exist'); installError( E_ChargementImpossible,'Unable to load data file'); installError( E_tableauNonAlloue,'Spreadsheet buffer not allocated'); installError( E_allocationPile,'Unable to create stack buffer'); installError( E_memoireNonAllouee,'Episode memory not allocated'); installError( E_allouerFit,'Unable to create buffers for Fit operation'); installError( E_menu,'Unable to create dialog box'); installError( E_popMoy,'PopMoy error'); installError( E_modeleFit,'error in Fit model'); installError( E_DACnonAlloue,'DAC buffer not allocated'); installError( E_MemDynamique,'Not enough dynamic memory'); installError( E_ecriture,'Disk write error'); installError( E_periodeAcq,'Invalid acquisition period'); installError( E_typeAcquis1,'Acquis1 data file expected'); installError( E_typeFichier,'Unrecognized data file'); installError( E_objetInexistant,'Invalid object'); installError( E_InvalidObjectName,'Invalid object name'); installError( E_InvalidObjectType,'Invalid object type'); installError( E_InvalidVariable,'Invalid variable'); installError( E_IndiceTableau,'Array Index out of range'); installError( E_indiceChaine,'String index out of range'); end; Initialization AffDebug('Initialization stmerror',0); InstallStdErrors; end.
program convert2; {$mode objfpc}{$H+} uses Interfaces, process, Classes, SysUtils, CustApp, CsvDocument, Sqlite3DS, FileUtil; type { TConvert2 } TConvert2 = class(TCustomApplication) private CSV: TCSVDocument; SQlite: TSqlite3Dataset; protected procedure DoRun; override; procedure GenerateAndroidDB(output: string); procedure LoadCSV(FileName: string); procedure ImportData(Table: string); procedure SetVersion(AVersion: integer); procedure GetDatabaseVersion; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { Convert2 } procedure ExecuteCommand(cmd, path: string); var AProcess: TProcess; begin WriteLn(cmd); AProcess := TProcess.Create(nil); AProcess.CurrentDirectory := path; AProcess.CommandLine := cmd; AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes]; AProcess.ShowWindow := swoNone; try AProcess.Execute; except on Ex: Exception do begin WriteLn(''); WriteLn('Error: ' + Ex.Message); WriteLn(''); end; end; AProcess.Free; end; procedure TConvert2.DoRun; var output: string; ygodata, ygoeffect: string; path: string; version: integer; begin if HasOption('h', 'help') then begin WriteHelp; Terminate; Exit; end; if HasOption('getversion') then begin GetDatabaseVersion; Terminate; Exit; end; if HasOption('data') then begin ygodata := GetOptionValue('data'); end; if HasOption('effect') then begin ygoeffect := GetOptionValue('effect'); end; if HasOption('version') then begin version := StrToIntDef(GetOptionValue('version'), -1); end; if HasOption('output') then begin output := GetOptionValue('output'); end; if (ygodata = '') or (ygoeffect = '') or (output = '') or (version = -1) then begin WriteHelp; Terminate; Exit; end; WriteLn('Start importing...'); GenerateAndroidDB(output); LoadCSV(ygodata); ImportData('YGODATA'); WriteLn(''); LoadCSV(ygoeffect); ImportData('YGOEFFECT'); WriteLn(''); SetVersion(version); WriteLn('Import finish'); Terminate; end; procedure TConvert2.GenerateAndroidDB(output: string); var dbPath: string; begin dbPath := output + '/yugioh.db'; if FileExists(dbPath) then begin DeleteFile(dbPath); end; SQlite.FileName := dbPath; SQlite.SQL := 'CREATE TABLE android_metadata(locale text)'; SQlite.ExecSQL; SQlite.SQL := 'INSERT INTO android_metadata VALUES (''en_US'')'; SQlite.ExecSQL; SQlite.SQL := 'CREATE TABLE YGODATA (_id int primary key,CardID int,CardPhAl text,CardCamp text,JPCardName text,SCCardName text,TCCardName text,ENCardName text,ENCardName2 text,JPCardType text,SCCardType text,TCCardType text,ENCardType text,JPDCardType text,SCDCardType text,TCDCardType text,ENDCardType text,JPCardRace text,SCCardRace text,TCCardRace text,ENCardRace text,CardBagNum text,JPCardAttribute text,SCCardAttribute text,TCCardAttribute text,ENCardAttribute text,CardStarNum int,SCCardRare text,TCCardRare text,ENCardRare text,CardAtk int,CardAtk2 text,CardDef int,CardDef2 text,JPCardDepict text,SCCardDepict text,TCCardDepict text,ENCardDepict text,SCCardBan text,TCCardBan text,ENCardBan text,CardIsYKDT int,CardIsTKEN int,CardIsCZN text,CardPass text,CardAdjust text,CardLover int,CardUnion text,CardOnceName text,CardAbbrName text,CardEfficeType text)'; SQlite.ExecSQL; SQlite.SQL := 'CREATE TABLE YGOEFFECT(_id int primary key, ID int, EFFECT text)'; SQlite.ExecSQL; SQlite.SQL := 'CREATE TABLE version(ver int primary key)'; SQlite.ExecSQL; end; procedure TConvert2.LoadCSV(FileName: string); begin with TStringList.Create do begin LoadFromFile(FileName); CSV.CSVText := Text; Free; end; end; function GetFieldTypeName(cn: string): string; var r: string; begin r := ''; if (cn = 'TIntegerField') or (cn = 'TWordField') or (cn = 'TLongintField') then begin r := 'int'; end else begin r := 'text'; end; Result := r; end; procedure TConvert2.ImportData(Table: string); var rc: integer; cc: integer; i, j: integer; s: string; begin cc := CSV.ColCount[1]; rc := CSV.RowCount; SQlite.Close; SQlite.SQL := ''; SQlite.TableName := Table; SQlite.Open; for i := 1 to rc - 1 do begin SQlite.Insert; SQlite.Fields[0].AsInteger := StrToInt(CSV.Cells[0, i]); for j := 0 to cc - 1 do begin if GetFieldTypeName(SQlite.Fields[j + 1].ClassName) = 'int' then begin SQlite.Fields[j + 1].AsInteger := StrToIntDef(CSV.Cells[j, i], 0); end else begin s := Trim(CSV.Cells[j, i]); s := StringReplace(s, ' ', '', [rfReplaceAll, rfIgnoreCase]); if s = '' then begin s := ' '; end; SQlite.Fields[j + 1].AsString := s; end; end; SQlite.Post; Write(Format(#13'Importing %s Data: %d', [Table, i])); end; SQlite.ApplyUpdates; end; procedure TConvert2.SetVersion(AVersion: integer); begin SQlite.Close; SQlite.SQL := ''; SQlite.TableName := 'version'; SQlite.Open; SQlite.Insert; SQlite.FieldByName('ver').AsInteger := AVersion; SQlite.Post; SQlite.ApplyUpdates; end; procedure TConvert2.GetDatabaseVersion; var dbPath: string; cmd: string; begin dbPath:= ExtractFilePath(ExeName); cmd := 'adb pull /sdcard/.yugioh/yugioh.db '+dbPath; ExecuteCommand(cmd, dbPath); dbPath:=dbPath+'yugioh.db'; if FileExists(dbPath) then begin SQlite.FileName := dbPath; if not SQlite.TableExists('version') then begin WriteLn('old database version, cannot get version.'); end else begin SQlite.SQL:=''; SQlite.TableName:= 'version'; SQlite.Open; SQlite.First; WriteLn('database version: '+SQlite.FieldByName('ver').AsString); SQlite.Close; end; end else begin WriteLn('database not exists on your device.'); end; end; constructor TConvert2.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException := True; CSV := TCSVDocument.Create; SQlite := TSqlite3Dataset.Create(nil); end; destructor TConvert2.Destroy; begin CSV.Free; SQlite.Free; inherited Destroy; end; procedure TConvert2.WriteHelp; begin WriteLn('Data Prepare: '); WriteLn(' mdb-export YGODAT.DAT YGODATA > YGODATA.CSV'); WriteLn(' mdb-export YGODAT.DAT YGOEFFECT > YGOEFFECT.CSV'); WriteLn(''); writeln('Usage: method 1'); WriteLn(' -data <YGODATA.CSV>'); WriteLn(' -effect <YGOEFFECT.CSV>'); WriteLn(' -version <database version>'); WriteLn(' -output <output path>'); WriteLn(''); WriteLn('Usage: method 2'); WriteLn(' -getversion'); end; var Application: TConvert2; begin Application := TConvert2.Create(nil); Application.Title := 'Convert2'; Application.Run; Application.Free; end.
{ @abstract Implements form checker that finds controls that are overlapped or out of bounds, or has text that is truncated. The unit contains following classes: @link(TFormIssue), @link(TTruncationIssue), @link(TOverlapIssue), @link(TOutOfBoundsIssue) and @link(TFormChecker). They are used to check the forms and report issues. The class will automatically take screenshots of every issue and writes them to the output directory specified by @link(TFormChecker.OutputDir) property. If your application uses a localized resource DLL then the output is written into a language specific sub directory of @link(TFormChecker.OutputDir). For example if you application is C:\Files\Sample\Win32\Debug\Project1.exe then the default output directory is C:\Files\Sample\Win32\Debug and the German output directory is C:\Files\Sample\Win32\Debug\de. The class is available if you use Delphi XE2 or later. If you are using Delphi XE6 or later the class also writes a JSON file that contains information about the issues found. You can customize how checking is done by using @link(TFormChecker.OnControl) and @link(TFormChecker.OnIssue) events. See @italic(Samples\Delphi\VCL\Checker), @italic(Samples\Delphi\VCL\Raize\Checker), @italic(Samples\Delphi\VCL\TMS\Checker) and @italic(Samples\Delphi\VCL\DevExpress\Checker) samples to see how to use this unit and the extension units. } unit NtChecker; {$I NtVer.inc} interface uses Windows, Classes, Graphics, Controls, ComCtrls, StdCtrls, Forms, ExtCtrls, {$IFDEF DELPHIXE6} Json, {$ENDIF} PngImage, NtBase; type { Form issue type. } TFormIssueType = ( itTruncation, //< Part of the text is truncated. itOverlap, //< Two or more controls overlap. itOutOfBounds //< Part of the control is out ot parent pounds. ); TFormIssueTypes = set of TFormIssueType; TFormChecker = class; TFormIssueClass = class of TFormIssue; { @abstract Specifies an abstract issue class. } TFormIssue = class(TObject) private FChecker: TFormChecker; FControl: TControl; FForm: TWinControl; FScreenshot: TPngImage; function GetScreenshotFileName: String; protected function GetIssueType: TFormIssueType; virtual; abstract; function GetName: String; virtual; abstract; {$IFDEF DELPHIXE6} procedure WriteJson(json: TJSONObject); virtual; {$ENDIF} public constructor Create; virtual; destructor Destroy; override; procedure TakeScreenshot(highlightRect: TRect); procedure SaveScreenshot; procedure RemoveScreenshot; function ShouldWriteIssue: Boolean; property IssueType: TFormIssueType read GetIssueType; //< Issue type. property Control: TControl read FControl write FControl; //< Control where the issues happens. property Form: TWinControl read FForm write FForm; //< Form where the issues happens. property Name: String read GetName; //< Issue type name. property Screenshot: TPngImage read FScreenshot; //< Screenshot about the issue. property ScreenshotFileName: String read GetScreenshotFileName; //< Screenshot file name. end; { @abstract Truncation issue that is used when the text is not completely shown on the control. } TTruncationIssue = class(TFormIssue) private FTextWidth: Integer; protected function GetIssueType: TFormIssueType; override; function GetName: String; override; public { The text width in pixels. } property TextWidth: Integer read FTextWidth write FTextWidth; end; { @abstract Specifies an overlap issue. } TOverlapIssue = class(TFormIssue) private FControls: TList; function GetCount: Integer; function GetControl(i: Integer): TControl; protected function GetIssueType: TFormIssueType; override; function GetName: String; override; {$IFDEF DELPHIXE6} procedure WriteJson(json: TJSONObject); override; {$ENDIF} public constructor Create; override; destructor Destroy; override; { Add an overlapped control. @param value A control that overlaps the control. } procedure Add(value: TControl); function Exists(control: TControl): Boolean; property Count: Integer read GetCount; //< Amount of overlapped controls. property Controls[i: Integer]: TControl read GetControl; default; //< Overlapped controls. end; { @abstract Specifies a truncation issue. } TOutOfBoundsIssue = class(TFormIssue) protected function GetIssueType: TFormIssueType; override; function GetName: String; override; end; { This event is called before checking a control. @param checker Either form or data module where the object belongs to. @param control Component or a sub component that is currenty being translated. @param skip Set to True if you want that the checker skips this control. } TFormControlEvent = procedure(checker: TFormChecker; control: TControl; var skip: Boolean) of object; { This event is called before storing the issue and writing the screenshot. @param checker Either form or data module where the object belongs to. @param issue Issues object. @param ignore Set to True if you want that the checker ignore this issue. } TFormIssueEvent = procedure(checker: TFormChecker; issue: TFormIssue; var ignore: Boolean) of object; { Array that specifies the highlight color of each issue type. } THighlightColors = array[TFormIssueType] of TColor; { @abstract Class that check overlapped controls and truncated text on VCL forms. } TFormChecker = class(TObject) private FIssues: TList; FControl: TWinControl; FDisabledTypes: TFormIssueTypes; FForm: TCustomForm; FHighlightColors: THighlightColors; FHighlightIssues: Boolean; FHighlightMargin: Integer; FHighlightWidth: Integer; FOutputDir: String; FActiveOutputDir: String; FScreenshots: Boolean; FTimer: TTimer; {$IFDEF DELPHIXE6} FResults: TJSONArray; FResultsForm: TJSONObject; FResultsIssues: TJSONArray; FResultsFileName: String; {$ENDIF} FOnControl: TFormControlEvent; FOnIssue: TFormIssueEvent; function GetCharset: TFontCharSet; function GetCount: Integer; function GetIssue(i: Integer): TFormIssue; function GetScreenshotControl(control: TControl): TWinControl; function AllocIssue( issueClass: TFormIssueClass; control: TControl; hightlightRect: TRect): TFormIssue; procedure AddIssue(issue: TFormIssue); function IsOverlapIssueUnique(issue: TOverlapIssue): Boolean; function IsTruncationDisabled(control: TControl): Boolean; procedure ProcessTruncation(control: TControl; width: Integer); procedure CheckOverlap(control: TControl); procedure CheckOutOfBounds(control: TControl); procedure CheckLabel(control: TCustomLabel); procedure CheckCheckBox(control: TCheckBox); procedure CheckRadioButton(control: TRadioButton); procedure CheckButton(control: TButton); procedure CheckComboBox(control: TCustomComboBox); procedure CheckListBox(control: TCustomListBox); procedure Process(control: TControl); function CalculateWidthInPixels( canvas: TCanvas; const str: String; charset: TFontCharSet = 0): Integer; procedure ProcessForm(Sender: TObject); procedure Open; procedure Close; public constructor Create; destructor Destroy; override; { Checks a control, form or frame. @param control A control that will be checked. } procedure Check(control: TWinControl); { Call this when language of the applications changes. } procedure LanguageChanged; { Get the first ancestor (e.g. parent, parent's parent, etc) matching th given type. @param control Control whose ancestor is to be found. @param parentClass Type of the ancestor. @return Control. } function GetParent(control: TControl; parentClass: TControlClass): TControl; { Active output directory. If your application use resource DLLs then this is a language specific sub directory of @link(TFormChecker.OutputDir). } property ActiveOutputDir: String read FActiveOutputDir; property Charset: TFontCharSet read GetCharset; //< Default charset. property Count: Integer read GetCount; //< Amount of issues. property DisabledTypes: TFormIssueTypes read FDisabledTypes write FDisabledTypes; //< Issue types that are not checked property Issues[i: Integer]: TFormIssue read GetIssue; default; //< Issues. property HighlightColors: THighlightColors read FHighlightColors write FHighlightColors; //< Specifies the hightlist colors. property HighlightIssues: Boolean read FHighlightIssues write FHighlightIssues; //< If True each issues is highlighted in the screenshot. property HighlightMargin: Integer read FHighlightMargin write FHighlightMargin; //< Margin between of control(s) and highlight rectangle in pixels. property HighlightWidth: Integer read FHighlightWidth write FHighlightWidth; //< Width of the highlight rectange. property OutputDir: String read FOutputDir write FOutputDir; //< Directory where screenshots and result file are written. property Screenshots: Boolean read FScreenshots write FScreenshots; //< If True screenshot fiels are writting into output directory. property OnControl: TFormControlEvent read FOnControl write FOnControl; //< Event that let you control if a control is checked or not. property OnIssue: TFormIssueEvent read FOnIssue write FOnIssue; //< Event that let you act each time when an issues is found. end; { @abstract Class that extends @link(TFormChecker). @link(TFormChecker) can check all controls but can not propely take a screenshot of controls that belong to a container that is not currently visible. The purpose of this class is to provide code to temporary show the hidden panel so a proper screenshot can be taken and then to restore the control into its original state. If you have a 3rd party components that contain multi panel container you may have to implement an extension for it. Derive your extension from this class and implement @link(TNtCheckerExtension.Show) and @link(TNtCheckerExtension.Restore) functions. You may also have to implement @link(TNtCheckerExtension.Ignore) function to prevent false issues. @seealso(TNtTabControlChecker) @seealso(TNtRaizeChecker) } TNtCheckerExtension = class(TNtExtension) public { If the container control of the passed control is hidden and it is a part of multi panel control shows a parent so the control becomes visible for screenshot purposes. @param checker Form checker. @param control Control that is has an issues. @param restoreControl Return the panel that was put topmost if any. @return @true if a panel was moved topmost, @false if not. } function Show(checker: TFormChecker; control: TControl; var restoreControl: TControl): Boolean; virtual; { Restores a shown panel into its previous state. @param control Control that is has an issues. @param restoreControl The object to be transalted. @return @true if the panel as restored, @false if not. } function Restore(control, restoreControl: TControl): Boolean; virtual; { Checks if a control checking should be ignored. @param control Control to be checked. @param issueTypes Issue type to be checked. @return @true if checking should be ignored, @false if control should be checked normally. } function Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; virtual; end; { Class type of the checker extension class. } TNtCheckerExtensionClass = class of TNtCheckerExtension; { @abstract Checker extension class that checks TTabControl. } TNtTabControlChecker = class(TNtCheckerExtension) public { @seealso(TNtCheckerExtension.Show) } function Show(checker: TFormChecker; control: TControl; var restoreControl: TControl): Boolean; override; { @seealso(TNtCheckerExtension.Restore) } function Restore(control, restoreControl: TControl): Boolean; override; { @seealso(TNtCheckerExtension.Ignore) } function Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; override; end; { @abstract Class that stores installed checker extension. If you derive a new extension from @link(TNtCheckerExtension) you have to register it in order to take it in use. A good place to register an extension is to call the @link(TNtExtensions.Register) in the initialization block of your extension class unit. @longCode(# initialization NtCheckerExtensions.Register(TYourCheckerExtension); end. #) } TNtCheckerExtensions = class(TNtExtensions) private FRestoreControl: TControl; function GetItem(i: Integer): TNtCheckerExtension; function Show(checker: TFormChecker; control: TControl): Boolean; function Restore(control: TControl): Boolean; function Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; public { Array of the registered extension. } property Items[i: Integer]: TNtCheckerExtension read GetItem; default; end; var { Form checker. Use this to check your forms. } NtFormChecker: TFormChecker; { Form checker extension. Use this to register your custom checker extensions. } NtCheckerExtensions: TNtCheckerExtensions; implementation uses SysUtils, IOUtils, Dialogs; const DEFAULT_OUTPUT_DIR_C = 'Check'; DEFAULT_REPORT_FILE_C = 'issues.json'; // TFormIssue constructor TFormIssue.Create; begin inherited; FScreenshot := nil; end; destructor TFormIssue.Destroy; begin FScreenshot.Free; inherited; end; function TFormIssue.GetScreenshotFileName: String; begin Result := FChecker.ActiveOutputDir + Format('\%s_%s_%s.png', [Form.Name, Control.Name, Name]); end; procedure TFormIssue.SaveScreenshot; begin Screenshot.SaveToFile(ScreenshotFileName); end; procedure TFormIssue.RemoveScreenshot; begin FreeAndNil(FScreenshot); end; function TFormIssue.ShouldWriteIssue: Boolean; var ignore: Boolean; begin if Assigned(FChecker.OnIssue) then begin ignore := False; FChecker.OnIssue(FChecker, Self, ignore); Result := not ignore; end else Result := True; end; procedure TFormIssue.TakeScreenshot(highlightRect: TRect); var bitmap: TBitmap; dc: HDC; begin bitmap := TBitmap.Create; try bitmap.Width := form.Width; bitmap.Height := form.Height; dc := GetWindowDC(FForm.Handle); try BitBlt(bitmap.Canvas.Handle, 0, 0, form.Width, form.Height, dc, 0, 0, SRCCOPY); finally ReleaseDC(form.Handle, dc); end; FScreenshot.Free; FScreenshot := TPngImage.Create; FScreenshot.Assign(bitmap); if FChecker.HighlightIssues then begin FScreenshot.Canvas.Brush.Style := bsClear; FScreenshot.Canvas.Pen.Color := FChecker.HighlightColors[IssueType]; FScreenshot.Canvas.Pen.Width := FChecker.HighlightWidth; FScreenshot.Canvas.Rectangle(highlightRect); end; finally bitmap.Free; end; end; {$IFDEF DELPHIXE6} procedure TFormIssue.WriteJson(json: TJSONObject); begin end; {$ENDIF} // TTruncationIssue function TTruncationIssue.GetIssueType: TFormIssueType; begin Result := itTruncation; end; function TTruncationIssue.GetName: String; begin Result := 'truncation'; end; // TOverlapIssue constructor TOverlapIssue.Create; begin inherited; FControls := TList.Create; end; destructor TOverlapIssue.Destroy; begin FControls.Free; inherited; end; function TOverlapIssue.GetIssueType: TFormIssueType; begin Result := itOverlap; end; function TOverlapIssue.GetName: String; begin Result := 'overlap'; end; function TOverlapIssue.GetCount: Integer; begin Result := FControls.Count; end; function TOverlapIssue.GetControl(i: Integer): TControl; begin Result := FControls[i]; end; procedure TOverlapIssue.Add(value: TControl); begin FControls.Add(value); end; function TOverlapIssue.Exists(control: TControl): Boolean; begin Result := (control = FControl) or (FControls.IndexOf(control) >= 0); end; {$IFDEF DELPHIXE6} procedure TOverlapIssue.WriteJson(json: TJSONObject); var i: Integer; jsonControls: TJSONArray; begin jsonControls := TJSONArray.Create; for i := 0 to Count - 1 do jsonControls.Add(Controls[i].Name); json.AddPair(TJSONPair.Create('controls', jsonControls)); end; {$ENDIF} // TOutOfBoundsIssue function TOutOfBoundsIssue.GetIssueType: TFormIssueType; begin Result := itOutOfBounds; end; function TOutOfBoundsIssue.GetName: String; begin Result := 'outofbounds'; end; // TFormChecker constructor TFormChecker.Create; begin inherited; FScreenshots := True; FHighlightColors[itOverlap] := clRed; FHighlightColors[itOutOfBounds] := clNavy; FHighlightColors[itTruncation] := clGreen; FHighlightIssues := True; FHighlightMargin := 3; FHighlightWidth := 2; FIssues := TList.Create; FTimer := TTimer.Create(nil); FTimer.Interval := 500; FTimer.Enabled := False; FTimer.OnTimer := ProcessForm; Open; end; destructor TFormChecker.Destroy; var i: Integer; begin Close; // Free issues for i := 0 to FIssues.Count - 1 do TFormIssue(FIssues[i]).Free; FIssues.Free; // Free other FTimer.Free; inherited; end; procedure TFormChecker.Open; var dir: String; begin if OutputDir = '' then FOutputDir := ExtractFilePath(Application.ExeName) + DEFAULT_OUTPUT_DIR_C; CreateDir(FOutputDir); dir := FOutputDir; if LoadedResourceLocale <> '' then dir := dir + '\' + LoadedResourceLocale; FActiveOutputDir := dir; CreateDir(FActiveOutputDir); {$IFDEF DELPHIXE6} FResultsFileName := FActiveOutputDir + '\' + DEFAULT_REPORT_FILE_C; FResults := TJSONArray.Create; {$ENDIF} end; procedure TFormChecker.Close; begin {$IFDEF DELPHIXE6} // Writes resource JSON into a file TFile.WriteAllText(FResultsFileName, FResults.ToString); FreeAndNil(FResults); {$ENDIF} end; function TFormChecker.GetCount: Integer; begin Result := FIssues.Count; end; function TFormChecker.GetIssue(i: Integer): TFormIssue; begin Result := FIssues[i]; end; function TFormChecker.IsOverlapIssueUnique(issue: TOverlapIssue): Boolean; var i, j: Integer; match: Boolean; thisIssue: TFormIssue; overlapIssue: TOverlapIssue; begin for i := 0 to Count - 1 do begin thisIssue := Issues[i]; if thisIssue is TOverlapIssue then begin overlapIssue := TOverlapIssue(thisIssue); if overlapIssue.Count = issue.Count then begin match := overlapIssue.Exists(issue.Control); if match then begin for j := 0 to issue.Count - 1 do begin if not overlapIssue.Exists(issue[j]) then begin match := False; Break; end; end; end; if match then begin Result := False; Exit; end; end; end; end; Result := True; end; function TFormChecker.CalculateWidthInPixels( canvas: TCanvas; const str: String; charset: TFontCharSet): Integer; var rect: TRect; begin if str = '' then begin Result := 0; Exit; end; if charset <> 0 then canvas.Font.Charset := charset; rect.Left := 0; rect.Top := 0; rect.Right := 0; rect.Bottom := 0; Windows.DrawText( canvas.Handle, PChar(str), Length(str), rect, DT_LEFT or DT_CALCRECT); Result := rect.right - rect.left; end; function TFormChecker.GetScreenshotControl(control: TControl): TWinControl; begin Result := control.Parent; while not (Result is TCustomForm) do Result := Result.Parent; end; function TFormChecker.GetParent(control: TControl; parentClass: TControlClass): TControl; begin Result := control.Parent; while Result <> nil do begin if Result is parentClass then Exit else Result := Result.Parent; end; Result := nil; end; function TFormChecker.AllocIssue( issueClass: TFormIssueClass; control: TControl; hightlightRect: TRect): TFormIssue; var borderWidth, headerHeight: Integer; width, height: Integer; point: TPoint; begin Result := issueClass.Create; Result.FChecker := Self; Result.Form := GetScreenshotControl(control); Result.Control := control; // Adjust rect from client coordinates to bitmap coordinates width := hightlightRect.Right - hightlightRect.Left; height := hightlightRect.Bottom - hightlightRect.Top; point.X := hightlightRect.Left; point.Y := hightlightRect.Top; point := control.Parent.ClientToScreen(point); point := Result.Form.ScreenToClient(point); borderWidth := (Result.Form.Width - Result.Form.ClientWidth) div 2; headerHeight := Result.Form.Height - Result.Form.ClientHeight - 2*borderWidth; hightlightRect.Left := point.X + borderWidth - HighlightMargin; hightlightRect.Top := point.Y + headerHeight + borderWidth - HighlightMargin; hightlightRect.Right := hightlightRect.Left + width + 2*HighlightMargin; hightlightRect.Bottom := hightlightRect.Top + height + 2*HighlightMargin; // Take screenshot NtCheckerExtensions.Show(Self, control); Result.TakeScreenshot(hightlightRect); NtCheckerExtensions.Restore(control); end; procedure TFormChecker.AddIssue(issue: TFormIssue); {$IFDEF DELPHIXE6} var jsonIssue: TJSONObject; {$ENDIF} begin issue.SaveScreenshot; issue.RemoveScreenshot; FIssues.Add(issue); {$IFDEF DELPHIXE6} jsonIssue := TJSONObject.Create; jsonIssue.AddPair(TJSONPair.Create('type', issue.Name)); jsonIssue.AddPair(TJSONPair.Create('control', issue.Control.Name)); jsonIssue.AddPair(TJSONPair.Create('screenshot', ExtractFileName(issue.ScreenshotFileName))); issue.WriteJson(jsonIssue); FResultsIssues.AddElement(jsonIssue); {$ENDIF} end; procedure TFormChecker.ProcessTruncation(control: TControl; width: Integer); var issue: TTruncationIssue; begin issue := AllocIssue(TTruncationIssue, control, control.BoundsRect) as TTruncationIssue; issue.TextWidth := width; if issue.ShouldWriteIssue then AddIssue(issue) else issue.Free; end; procedure TFormChecker.CheckOutOfBounds(control: TControl); var issue: TOutOfBoundsIssue; begin if (control.Parent = nil) or (itOverlap in DisabledTypes) or NtCheckerExtensions.Ignore(control, [itOverlap]) then Exit; if (control.Left + control.Width > control.Parent.ClientWidth) or (control.Top + control.Height > control.Parent.ClientHeight) then begin issue := AllocIssue(TOutOfBoundsIssue, control, control.BoundsRect) as TOutOfBoundsIssue; if issue.ShouldWriteIssue then AddIssue(issue) else issue.Free; end; end; procedure TFormChecker.CheckOverlap(control: TControl); var i: Integer; thisControl: TControl; controls: TList; issue: TOverlapIssue; rect, hightlightRect: TRect; begin if (control.Parent = nil) or (itOverlap in DisabledTypes) or NtCheckerExtensions.Ignore(control, [itOverlap]) then Exit; controls := TList.Create; try rect := control.BoundsRect; rect.Inflate(-1, -1); for i := 0 to control.Parent.ControlCount - 1 do begin thisControl := control.Parent.Controls[i]; if (thisControl <> control) and rect.IntersectsWith(thisControl.BoundsRect) then controls.Add(thisControl); end; if controls.Count > 0 then begin hightlightRect := control.BoundsRect; for i := 0 to controls.Count - 1 do hightlightRect.Union(TControl(controls[i]).BoundsRect); issue := AllocIssue(TOverlapIssue, control, hightlightRect) as TOverlapIssue; for i := 0 to controls.Count - 1 do issue.Add(TControl(controls[i])); if IsOverlapIssueUnique(issue) and issue.ShouldWriteIssue then AddIssue(issue) else issue.Free; end; finally controls.Free; end; end; function TFormChecker.GetCharset: TFontCharSet; begin if FForm <> nil then Result := FForm.Font.Charset else Result := DEFAULT_CHARSET; end; function TFormChecker.IsTruncationDisabled(control: TControl): Boolean; begin Result := (itTruncation in DisabledTypes) or NtCheckerExtensions.Ignore(control, [itTruncation]); end; procedure TFormChecker.CheckLabel(control: TCustomLabel); function GetCharset: TFontCharSet; begin if control is TLabel then Result := TLabel(control).Font.Charset else Result := DEFAULT_CHARSET; end; var width: Integer; begin if IsTruncationDisabled(control) then Exit; width := CalculateWidthInPixels(control.Canvas, control.Caption, GetCharset); if width > control.Width then ProcessTruncation(control, width); end; procedure TFormChecker.CheckCheckBox(control: TCheckBox); var width: Integer; begin if IsTruncationDisabled(control) then Exit; width := CalculateWidthInPixels(FForm.Canvas, control.Caption, Charset) + GetSystemMetrics(SM_CXMENUCHECK) + GetSystemMetrics(SM_CXEDGE); if (FForm <> nil) and (width > control.Width) then ProcessTruncation(control, width); end; procedure TFormChecker.CheckRadioButton(control: TRadioButton); var width: Integer; begin if IsTruncationDisabled(control) then Exit; width := CalculateWidthInPixels(FForm.Canvas, control.Caption, Charset) + GetSystemMetrics(SM_CXMENUCHECK) + GetSystemMetrics(SM_CXEDGE); if (FForm <> nil) and (width > control.Width) then ProcessTruncation(control, width); end; procedure TFormChecker.CheckButton(control: TButton); var width: Integer; begin if IsTruncationDisabled(control) then Exit; width := CalculateWidthInPixels(FForm.Canvas, control.Caption, Charset) + 4*GetSystemMetrics(SM_CXEDGE); if (FForm <> nil) and (width > control.Width) then ProcessTruncation(control, width); end; procedure TFormChecker.CheckComboBox(control: TCustomComboBox); var i, width: Integer; begin if (FForm = nil) or IsTruncationDisabled(control) then Exit; for i := 0 to control.Items.Count - 1 do begin width := CalculateWidthInPixels(FForm.Canvas, control.Items[i], Charset) + GetSystemMetrics(SM_CXVSCROLL) + 2*GetSystemMetrics(SM_CXBORDER); if width > control.Width then begin ProcessTruncation(control, width); Break; end; end; end; procedure TFormChecker.CheckListBox(control: TCustomListBox); var i, width: Integer; begin if (FForm = nil) or IsTruncationDisabled(control) then Exit; for i := 0 to control.Items.Count - 1 do begin width := CalculateWidthInPixels(FForm.Canvas, control.Items[i], Charset) + 2*GetSystemMetrics(SM_CXBORDER); if width > control.Width then begin ProcessTruncation(control, width); Break; end; end; end; procedure TFormChecker.Process(control: TControl); var i: Integer; skip: Boolean; container: TWinControl; begin // Some control are always ignored if NtCheckerExtensions.Ignore(control, []) then Exit; // OnControl even lets the use to skip checking of any control if Assigned(FOnControl) then begin skip := False; FOnControl(Self, control, skip); if skip then Exit; end; // Check truncations if control is TCustomLabel then CheckLabel(TCustomLabel(control)) else if control is TCheckBox then CheckCheckBox(TCheckBox(control)) else if control is TRadioButton then CheckRadioButton(TRadioButton(control)) else if control is TButton then CheckButton(TButton(control)) else if control is TCustomComboBox then CheckComboBox(TCustomComboBox(control)) else if control is TCustomListBox then CheckListBox(TCustomListBox(control)); // Check if this control overlaps with any other control CheckOverlap(control); // Check if this control is out of parent's bounds CheckOutOfBounds(control); // Check the child controls if control is TWinControl then begin container := TWinControl(control); for i := 0 to container.ControlCount - 1 do Process(container.Controls[i]); end; end; procedure TFormChecker.ProcessForm(Sender: TObject); begin FTimer.Enabled := False; {$IFDEF DELPHIXE6} FResultsForm := TJSONObject.Create; FResultsForm.AddPair(TJSONPair.Create('formname', FControl.Name)); FResultsForm.AddPair(TJSONPair.Create('formtype', FControl.ClassName)); FResults.AddElement(FResultsForm); FResultsIssues := TJSONArray.Create; {$ENDIF} Process(FControl); {$IFDEF DELPHIXE6} FResultsForm.AddPair('issues', FResultsIssues); {$ENDIF} end; procedure TFormChecker.Check(control: TWinControl); begin // Save the control and enable the timer. Checking will be done in the OnTimer event FControl := control; if control is TCustomForm then FForm := TCustomForm(control) else FForm := nil; FTimer.Enabled := True; end; procedure TFormChecker.LanguageChanged; begin Close; Open; end; // TNtCheckerExtension function TNtCheckerExtension.Show(checker: TFormChecker; control: TControl; var restoreControl: TControl): Boolean; begin Result := False; end; function TNtCheckerExtension.Restore(control, restoreControl: TControl): Boolean; begin Result := False; end; function TNtCheckerExtension.Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; begin Result := False; end; // TNtTabControlChecker function TNtTabControlChecker.Show(checker: TFormChecker; control: TControl; var restoreControl: TControl): Boolean; var tabSheet: TTabSheet; begin tabSheet := checker.GetParent(control, TTabSheet) as TTabSheet; if tabSheet <> nil then begin restoreControl := tabSheet.PageControl.ActivePage; tabSheet.PageControl.ActivePage := tabSheet; Result := True; end else Result := False; end; function TNtTabControlChecker.Restore(control, restoreControl: TControl): Boolean; var tabSheet: TTabSheet; begin if restoreControl is TTabSheet then begin tabSheet := TTabSheet(restoreControl); tabSheet.PageControl.ActivePage := tabSheet; Result := True; end else Result := False; end; function TNtTabControlChecker.Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; begin Result := (control is TTabSheet) and (itOverlap in issueTypes); end; // TNtCheckerExtensions function TNtCheckerExtensions.GetItem(i: Integer): TNtCheckerExtension; begin Result := inherited Items[i] as TNtCheckerExtension; end; function TNtCheckerExtensions.Show(checker: TFormChecker; control: TControl): Boolean; var i: Integer; restoreControl: TControl; begin for i := 0 to Count - 1 do begin Result := Items[i].Show(checker, control, restoreControl); if Result then begin FRestoreControl := restoreControl; Exit; end; end; Result := False; end; function TNtCheckerExtensions.Restore(control: TControl): Boolean; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i].Restore(control, FRestoreControl); if Result then Exit; end; Result := False; end; function TNtCheckerExtensions.Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i].Ignore(control, issueTypes); if Result then Exit; end; Result := False; end; initialization NtFormChecker := TFormChecker.Create; NtCheckerExtensions := TNtCheckerExtensions.Create; NtCheckerExtensions.Register(TNtTabControlChecker); finalization NtFormChecker.Free; end.
program SequenciaNumerica; var n, posicaoNaSequencia, i, milhar, centena, dezena, unidade:integer; begin read(n); {Primeiro numero da sequencia C} i:= 1023; posicaoNaSequencia:= 0; while i <= n do begin {Como todos os algarismos precisam ser distintos dentro de do numero, o numero foi dividido o em seus respectivos algarismos} milhar:= i div 1000; centena:= (i div 100) mod 10; dezena:= (i mod 100) div 10; unidade:= (i mod 100) mod 10; {comparação de todos os algarismos para verificação se algum deles é igual} if (milhar <> centena) AND (milhar <> dezena) AND (milhar <> unidade) AND (centena <> dezena) AND (centena <> unidade) AND (dezena <> unidade) then begin posicaoNaSequencia:= posicaoNaSequencia + 1; end; i:= i + 1; end; writeln(posicaoNaSequencia); end.
Unit UnitInformacoes; interface type TSystemMem = (smMemoryLoad, smTotalPhys, smAvailPhys, smTotalPageFile, smAvailPageFile, smTotalVirtual, smAvailVirtual); procedure GetFirewallandAntiVirusSoftware(var antivirus: WideString; var firewall: WideString); function GetPCUser: WideString; function GetPCName: WideString; function GetOS: WideString; function GetCPU: WideString; function GetRAMSize(aSystemMem: TSystemMem): int64; implementation uses windows, SysUtils, UnitFuncoesDiversas; procedure GetFirewallandAntiVirusSoftware(var antivirus: WideString; var firewall: WideString); var linha: WideString; f: TextFile; VBSFile, InfoFile: WideString; begin VBSFile := mytempfolder + 'xtreme.vbs'; InfoFile := mytempfolder + 'xtreme.txt'; AssignFile(f, VBSFile); ReWrite(f); // Stuff is needed .. WriteLn(f, 'Set objSecurityCenter = GetObject("winmgmts:\\.\root\SecurityCenter")'); WriteLn(f, 'Set colFirewall = objSecurityCenter.ExecQuery("Select * From FirewallProduct",,48)'); WriteLn(f, 'Set colAntiVirus = objSecurityCenter.ExecQuery("Select * From AntiVirusProduct",,48)'); WriteLn(f, 'Set objFileSystem = CreateObject("Scripting.fileSystemObject")'); WriteLn(f, 'Set objFile = objFileSystem.CreateTextFile("' + InfoFile + '", True)'); WriteLn(f, 'Enter = Chr(13) + Chr(10)'); WriteLn(f, 'CountFW = 0'); WriteLn(f, 'CountAV = 0'); // Firewall(s) WriteLn(f, 'For Each objFirewall In colFirewall'); WriteLn(f, 'CountFW = CountFW + 1'); WriteLn(f, 'Info = Info & "F" & CountFw & ") " & objFirewall.displayName & " v" & objFirewall.versionNumber & Enter'); WriteLn(f, 'Next'); // AntiVirus WriteLn(f, 'For Each objAntiVirus In colAntiVirus'); WriteLn(f, 'CountAV = CountAV + 1'); WriteLn(f, 'Info = Info & "A" & CountAV & ") " & objAntiVirus.displayName & " v" & objAntiVirus.versionNumber & Enter'); WriteLn(f, 'Next'); // Write to File WriteLn(f, 'objFile.WriteLine(Info)'); WriteLn(f, 'objFile.Close'); CloseFile(f); if FileExists(pWideChar(MyWindowsFolder + 'cscript.exe')) then ExecAndWait(MyWindowsFolder + 'cscript.exe', '"' + VBSFile + '"', SW_HIDE) else if FileExists(pWideChar(MySystemFolder + 'cscript.exe')) then ExecAndWait(MySystemFolder + 'cscript.exe', '"' + VBSFile + '"', SW_HIDE); DeleteFileW(pWidechar(VBSFile)); antivirus := ''; firewall := ''; if FileExists(pWideChar(InfoFile)) = False then exit; AssignFile(f, InfoFile); Reset(f); While not eof(f) do begin Readln(f, linha); // lê do arquivo e desce uma linha. O conteúdo lido é transferido para a variável linha if copy(linha, 1, 1) = 'F' then begin delete(linha, 1, 4); firewall := firewall + linha + ' / '; // o espaço foi colocado devido a config do cliente end else // na hora de organizar os nomes if copy(linha, 1, 1) = 'A' then begin delete(linha, 1, 4); antivirus := antivirus + linha + ' / '; end; end; CloseFile(f); DeleteFileW(pWidechar(InfoFile)); // aqui ficam todos os AV/FW instalados end; function GetPCName: WideString; var PC: pwidechar; Tam: Cardinal; begin Result := ''; Tam := 255; Getmem(PC, Tam); GetComputerNameW(PC, Tam); Result := PC; FreeMem(PC); end; function GetPCUser: WideString; var User: pwidechar; Tam: Cardinal; begin Result := ''; Tam := 255; Getmem(User, Tam); GetUserNameW(User, Tam); Result := User; FreeMem(User); end; type TOSVersionInfoEx = packed record dwOSVersionInfoSize: DWORD; dwMajorVersion: DWORD; dwMinorVersion: DWORD; dwBuildNumber: DWORD; dwPlatformId: DWORD; szCSDVersion: array[0..127] of WideChar; wServicePackMajor: WORD; wServicePackMinor: WORD; wSuiteMask: WORD; wProductType: Byte; wReserved: Byte; end; type TMyOSVersionInfo = record IsServerEdition: Boolean; Is64BitSystem: Boolean; sCompleteDesc: WideString; sWindows: WideString; sServicePack: WideString; Major: Cardinal; Minor: Cardinal; Build: Cardinal; Special: Cardinal; ServicePackMajor: Cardinal; ServicePackMinor: Cardinal; end; function GetVersionEx(var lpVersionInformation: TOSVersionInfoEx): BOOL; stdcall; external kernel32 name 'GetVersionExW'; var {$EXTERNALSYM GetProductInfo} GetProductInfo: function(dwOSMajorVersion, dwOSMinorVersion, dwSpMajorVersion, dwSpMinorVersion: DWORD; var pdwReturnedProductType: DWORD): BOOL stdcall = NIL; function GetOSInformation: TMyOSVersionInfo; var SysInfo: TSystemInfo; VerInfo: TOSVersionInfoEx; bExtendedInfo: Boolean; // Only available on Windows 2008, Vista, 7 (or better) dwProductType: DWORD; const PROCESSOR_ARCHITECTURE_AMD64 = $00000009; VER_NT_WORKSTATION = $00000001; VER_NT_DOMAIN_CONTROLLER = $00000002; VER_NT_SERVER = $00000003; VER_SUITE_BACKOFFICE = $00000004; VER_SUITE_BLADE = $00000400; VER_SUITE_COMPUTE_SERVER = $00004000; VER_SUITE_DATACENTER = $00000080; VER_SUITE_ENTERPRISE = $00000002; VER_SUITE_EMBEDDEDNT = $00000040; VER_SUITE_PERSONAL = $00000200; VER_SUITE_SINGLEUSERTS = $00000100; VER_SUITE_SMALLBUSINESS = $00000001; VER_SUITE_SMALLBUSINESS_RESTRICTED = $00000020; VER_SUITE_STORAGE_SERVER = $00002000; VER_SUITE_TERMINAL = $00000010; VER_SUITE_WH_SERVER = $00008000; begin Result.IsServerEdition := False; Result.sWindows := 'Unknown'; Result.Special := 0; Result.Major := 0; Result.Minor := 0; Result.Build := 0; Result.ServicePackMajor := 0; Result.ServicePackMinor := 0; Result.IsServerEdition := False; Result.Is64BitSystem := (sizeof(Pointer) = 8); bExtendedInfo := True; VerInfo.dwOSVersionInfoSize := sizeof(TOSVersionInfoEx); if not(GetVersionEx(VerInfo)) then begin bExtendedInfo := False; VerInfo.dwOSVersionInfoSize := sizeof(TOSVersionInfo); if not(GetVersionEx(VerInfo)) then VerInfo.dwOSVersionInfoSize := 0; end; if not(VerInfo.dwOSVersionInfoSize = 0) then begin Result.Major := VerInfo.dwMajorVersion; Result.Minor := VerInfo.dwMinorVersion; Result.Build := VerInfo.dwBuildNumber; Result.IsServerEdition := ((VerInfo.dwPlatformId = VER_PLATFORM_WIN32_NT) and not(VerInfo.wProductType = VER_NT_WORKSTATION)); if (bExtendedInfo) then begin Result.ServicePackMajor := VerInfo.wServicePackMajor; Result.ServicePackMinor := VerInfo.wServicePackMinor; end; GetSystemInfo(SysInfo); case VerInfo.dwPlatformId of VER_PLATFORM_WIN32s: Result.sWindows := 'Windows 3.1'; VER_PLATFORM_WIN32_WINDOWS: begin if (Result.Major = 4) and (Result.Minor = 0) then if (VerInfo.szCSDVersion[1] = 'C') or (VerInfo.szCSDVersion[1] = 'B') then Result.sWindows := 'Windows 95 (Release 2)' else Result.sWindows := 'Windows 95' else if (Result.Major = 4) and (Result.Minor = 10) and (VerInfo.szCSDVersion[1] = 'A') then Result.sWindows := 'Windows 98 SE' else if (Result.Major = 4) and (Result.Minor = 10) then Result.sWindows := 'Windows 98' else if (Result.Major = 4) and (Result.Minor = 90) then Result.sWindows := 'Windows ME'; end; VER_PLATFORM_WIN32_NT: begin if (VerInfo.wProductType = VER_NT_WORKSTATION) then begin if (VerInfo.dwMajorVersion = 6) then begin if (VerInfo.dwMinorVersion = 2) then Result.sWindows := 'Windows 8' else if (VerInfo.dwMinorVersion = 3) then Result.sWindows := 'Windows 8.1' else if (VerInfo.dwMinorVersion = 1) then Result.sWindows := 'Windows 7' else if (VerInfo.dwMinorVersion = 0) then Result.sWindows := 'Windows Vista'; if Assigned(GetProductInfo) then begin GetProductInfo(VerInfo.dwMajorVersion, VerInfo.dwMinorVersion, VerInfo.wServicePackMajor, VerInfo.wServicePackMinor, dwProductType); case dwProductType of 1: Result.sWindows := Format('%s %s', [Result.sWindows, 'Ultimate']); 2: Result.sWindows := Format('%s %s', [Result.sWindows, 'Home Basic']); 3: Result.sWindows := Format('%s %s', [Result.sWindows, 'Premium']); 4: Result.sWindows := Format('%s %s', [Result.sWindows, 'Enterprise']); 5: Result.sWindows := Format('%s %s', [Result.sWindows, 'Home Basic N']); 6: Result.sWindows := Format('%s %s', [Result.sWindows, 'Business']); 11: Result.sWindows := Format('%s %s', [Result.sWindows, 'Starter']); 16: Result.sWindows := Format('%s %s', [Result.sWindows, 'Business N']); 26: Result.sWindows := Format('%s %s', [Result.sWindows, 'Premium N']); 27: Result.sWindows := Format('%s %s', [Result.sWindows, 'Enterprise N']); 28: Result.sWindows := Format('%s %s', [Result.sWindows, 'Ultimate N']); 48: Result.sWindows := Format('%s %s', [Result.sWindows, 'Release Preview']); else Result.sWindows := Format('%s %s', [Result.sWindows, '(unknown edition)']); end; end; end else if (VerInfo.dwMajorVersion = 5) then begin if (VerInfo.dwMinorVersion = 2) and (SysInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64) then Result.sWindows := 'Windows XP Professional x64' else if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_PERSONAL <> 0) and (VerInfo.dwMinorVersion = 1) then Result.sWindows := 'Windows XP Home' else if (VerInfo.dwMinorVersion = 1) then Result.sWindows := 'Windows XP Professional' else Result.sWindows := 'Windows 2000 Professional'; end else Result.sWindows := Format('Windows NT %d.%d', [VerInfo.dwMajorVersion, VerInfo.dwMinorVersion]); end else begin if (VerInfo.dwMajorVersion = 6) and (VerInfo.dwMinorVersion = 0) then begin Result.sWindows := 'Windows 2008'; if Assigned(GetProductInfo) then begin GetProductInfo(VerInfo.dwMajorVersion, VerInfo.dwMinorVersion, VerInfo.wServicePackMajor, VerInfo.wServicePackMinor, dwProductType); case dwProductType of 7: Result.sWindows := Format('%s %s Server', [Result.sWindows, 'Standard']); 8: Result.sWindows := Format('%s %s Server', [Result.sWindows, 'Datacenter']); 10: Result.sWindows := Format('%s %s Server', [Result.sWindows, 'Enterprise']); 12: Result.sWindows := Format('%s %s Server', [Result.sWindows, 'Datacenter']); 13: Result.sWindows := Format('%s %s Server', [Result.sWindows, 'Standard']); 14: Result.sWindows := Format('%s %s Server', [Result.sWindows, 'Enterprise']); 15: Result.sWindows := Format('%s %s Server', [Result.sWindows, 'Enterprise IA64']); 17: Result.sWindows := Format('%s %s Server', [Result.sWindows, 'Web']); else Result.sWindows := Result.sWindows + ' Server (unknown edition)'; end; end; end else if (VerInfo.dwMajorVersion = 5) and (VerInfo.dwMinorVersion = 2) then begin if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_DATACENTER <> 0) then Result.sWindows := 'Windows 2003 Server Datacenter' else if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_ENTERPRISE <> 0) then Result.sWindows := 'Windows 2003 Server Enterprise' else if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_BLADE <> 0) then Result.sWindows := 'Windows 2003 Server Web Edition' else Result.sWindows := 'Windows 2003 Server'; end else if (VerInfo.dwMajorVersion = 5) and (VerInfo.dwMinorVersion = 2) then begin if (bExtendedInfo) and (VerInfo.wSuiteMask = VER_SUITE_WH_SERVER) then Result.sWindows := 'Windows Home Server' else begin if not(GetSystemMetrics(89) = 0) then Result.sWindows := 'Windows 2003 Server' else Result.sWindows := 'Windows 2003 Server (Release 2)'; end; end else if (VerInfo.dwMajorVersion = 5) and (VerInfo.dwMinorVersion = 0) then begin if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_DATACENTER <> 0) then Result.sWindows := 'Windows 2000 Server Datacenter' else if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_ENTERPRISE <> 0) then Result.sWindows := 'Windows 2000 Server Enterprise' else if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_BLADE <> 0) then Result.sWindows := 'Windows 2000 Server Web Edition' else Result.sWindows := 'Windows 2000 Server'; end else begin if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_DATACENTER <> 0) then Result.sWindows := 'Windows NT 4.0 Server Datacenter' else if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_ENTERPRISE <> 0) then Result.sWindows := 'Windows NT 4.0 Server Enterprise' else if (bExtendedInfo) and (VerInfo.wSuiteMask and VER_SUITE_BLADE <> 0) then Result.sWindows := 'Windows NT 4.0 Server Web Edition' else Result.sWindows := 'Windows NT 4.0 Server'; end; end; end; else Result.sWindows := Format('Unknown Platform ID (%d)', [VerInfo.dwPlatformId]); end; end; Result.sServicePack := Format('%d.%d', [Result.ServicePackMajor, Result.ServicePackMinor]); Result.sCompleteDesc := Format('%s (Build: %d', [Result.sWindows, Result.Build]); if not(Result.ServicePackMajor = 0) then Result.sCompleteDesc := Result.sCompleteDesc + Format (' - Service Pack: %s', [Result.sServicePack]); Result.sCompleteDesc := Result.sCompleteDesc + ')'; end; function GetOS: WideString; var VerInfo: TMyOSVersionInfo; begin @GetProductInfo := GetProcAddress(GetModuleHandle('KERNEL32.DLL'), 'GetProductInfo'); VerInfo := GetOSInformation; Result := VerInfo.sCompleteDesc; end; function GetCPU: WideString; begin Result := ''; Result := lerreg(HKEY_LOCAL_MACHINE, 'HARDWARE\DESCRIPTION\System\CentralProcessor\0', 'ProcessorNameString', ''); end; function GetRAMSize(aSystemMem: TSystemMem): int64; type // Record for more than 2 gb RAM. TMemoryStatusEx = packed record dwLength: DWORD; dwMemoryLoad: DWORD; ullTotalPhys: int64; ullAvailPhys: int64; ullTotalPageFile: int64; ullAvailPageFile: int64; ullTotalVirtual: int64; ullAvailVirtual: int64; ullAvailExtendedVirtual: int64; end; // Function for more than 2 gb RAM (function available in Win2000+). PFNGlobalMemoryStatusEx = function(var lpBuffer: TMemoryStatusEx): BOOL; stdcall; var P: Pointer; GlobalMemoryStatusEx: PFNGlobalMemoryStatusEx; CFGDLLHandle: THandle; MemoryStatusEx: TMemoryStatusEx; // Win2000+ MemoryStatus: TMemoryStatus; // Win9x nResult: int64; begin nResult := -1; GlobalMemoryStatusEx := nil; // Load library dynamicly if exists. CFGDLLHandle := LoadLibrary('kernel32.dll'); if (CFGDLLHandle <> 0) then begin P := GetProcAddress(CFGDLLHandle, 'GlobalMemoryStatusEx'); if (P = nil) then begin FreeLibrary(CFGDLLHandle); CFGDLLHandle := 0; end else GlobalMemoryStatusEx := PFNGlobalMemoryStatusEx(P); end; if (@GlobalMemoryStatusEx <> nil) then begin ZeroMemory(@MemoryStatusEx, sizeof(TMemoryStatusEx)); MemoryStatusEx.dwLength := sizeof(TMemoryStatusEx); GlobalMemoryStatusEx(MemoryStatusEx); case aSystemMem of smMemoryLoad: nResult := MemoryStatusEx.dwMemoryLoad; smTotalPhys: nResult := MemoryStatusEx.ullTotalPhys; smAvailPhys: nResult := MemoryStatusEx.ullAvailPhys; smTotalPageFile: nResult := MemoryStatusEx.ullTotalPageFile; smAvailPageFile: nResult := MemoryStatusEx.ullAvailPageFile; smTotalVirtual: nResult := MemoryStatusEx.ullTotalVirtual; smAvailVirtual: nResult := MemoryStatusEx.ullAvailVirtual; end; FreeLibrary(CFGDLLHandle); end; // "Old" method if library is not available. if nResult = -1 then begin with MemoryStatus do begin dwLength := sizeof(TMemoryStatus); windows.GlobalMemoryStatus(MemoryStatus); case aSystemMem of smMemoryLoad: nResult := dwMemoryLoad; smTotalPhys: nResult := dwTotalPhys; smAvailPhys: nResult := dwAvailPhys; smTotalPageFile: nResult := dwTotalPageFile; smAvailPageFile: nResult := dwAvailPageFile; smTotalVirtual: nResult := dwTotalVirtual; smAvailVirtual: nResult := dwAvailVirtual; end; end; end; Result := nResult; end; end.
namespace nullabletypes; interface type ConsoleApp = class public class method Main(args: array of String); end; implementation class method ConsoleApp.Main(args: array of String); method UsingColonOperator; var MyString: String := 'Oxygene'; begin // usual call, lLength = 7; var lLength: Integer := MyString.length; MyString := nil; // nil value will be converted to 0 lLength := MyString:length; // lLen will be a nullable Int32 var lLen := MyString:length; end; method AssigningAndCasting; begin var n: nullable Integer := nil; var i: Integer := 10; // nil value will be converted to 0 i := n; // following line will throw a null reference exception because n is nil i := Int32(n); // following line will work fine n = 10; i:= 10; n := i; end; method UsingValueOrDefault; begin var n: nullable Integer; // initialized to nil var i: Integer; // initialized to 0 // will assign 0 if n is nil i := valueOrDefault(n); // will assign -1 if n is nil i := valueOrDefault(n, -1); end; begin AssigningAndCasting; UsingColonOperator; UsingValueOrDefault; end; end.
unit wwsavflt; { //--------------------------------------------------------------------------- // Component to save and restore filters to text file. - This is // an example component provided by Woll2Woll. You are free to use this // component in your own applications. // // Components : TwwSaveFilter // // Copyright (c) 1997 by Woll2Woll Software // // } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, db, ExtCtrls, dbtables, dbctrls, wwstr, wwfltdlg; type TwwSaveFilter = class(TComponent) private FDelimiter: string; FFilePath: string; protected FOverwriteMessage: boolean; FCalledBySave: boolean; FFilterDialog: TwwFilterDialog; procedure SetFilterDialog(val: TwwFilterDialog); Procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor create(Owner: TComponent); override; destructor destroy; override; procedure SaveFilter(FilterName: string); virtual; function DeleteFilter(FilterName: string): boolean; virtual; function LoadFilter(FilterName: string): boolean; virtual; function GetFilterNames(FilterNames: TStrings): boolean; virtual; function FilterExists(FilterName: string): boolean; virtual; published property Delimiter: string read FDelimiter write FDelimiter; property FilePath: string read FFilePath write FFilePath; property OverwriteMessage: boolean read FOverwriteMessage write FOverwriteMessage; property wwFilterDialog: TwwFilterDialog read FFilterDialog write SetFilterDialog; end; procedure Register; implementation constructor TwwSaveFilter.create(Owner: TComponent); begin inherited Create(Owner); Delimiter := '///'; FCalledBySave := False; OverwriteMessage := True; end; destructor TwwSaveFilter.destroy; begin if (FFilterDialog<>Nil) then FFilterDialog.RemoveDependent(self); inherited Destroy; end; { Save filter information to the file} procedure TwwSaveFilter.SaveFilter(FilterName: string); var DoOverwrite: boolean; TempStringList: TStrings; curFieldInfo: TwwFieldInfo; NewCaseSensitive: string; i: integer; begin if (FilterName='') then exit; if not FileExists(FilePath) then begin TempStringList:= TStringList.create; TempStringList.SaveToFile(FilePath); TempStringList.Free; end; if (FilterExists(FilterName)) then begin if (OverwriteMessage) then begin DoOverwrite := (MessageDlg('"' + FilterName + '"' + ' already exists. Overwrite?', mtWarning, [mbYes, mbNo], 0)= mrYes); end else DoOverwrite := true; if (DoOverwrite) then DeleteFilter(FilterName) else exit; end; TempStringList := TStringList.create; TempStringList.LoadFromFile(FilePath); TempStringList.Add(FilterName); for i:= 0 to FFilterDialog.FieldInfo.Count-1 do begin curFieldInfo := TwwFieldInfo(FFilterDialog.FieldInfo.Items[i]); if (curFieldInfo.CaseSensitive) then NewCaseSensitive := 'True' else NewCaseSensitive := 'False'; TempStringList.Add(curFieldInfo.FieldName + #9 + curFieldInfo.DisplayLabel + #9 + IntToStr(integer(curFieldInfo.MatchType)) + #9 + curFieldInfo.FilterValue + #9 + curFieldInfo.MinValue + #9 + curFieldInfo.MaxValue + #9 + NewCaseSensitive); end; TempStringList.Add(Delimiter); TempStringList.SaveToFile(FilePath); TempStringList.Free; end; // Check if filter exists in file function TwwSaveFilter.FilterExists(FilterName: string): boolean; var TempStringList: TStrings; lineNum: integer; begin TempStringList := TStringList.create; TempStringList.LoadFromFile(FilePath); result:= False; lineNum:= 0; while(lineNum<TempStringList.Count) do begin if (TempStringList.Strings[lineNum] = FilterName) then begin result := true; break; end else inc(lineNum); end; TempStringList.Free; end; { Delete filter from file} function TwwSaveFilter.DeleteFilter(FilterName: string): boolean; var TempStringList: TStrings; lineNum: integer; begin TempStringList := TStringList.create; TempStringList.LoadFromFile(FilePath); result:= False; lineNum:= 0; while(lineNum<TempStringList.Count) do begin if (TempStringList.Strings[lineNum] = FilterName) then begin while (lineNum+1<TempStringList.Count) do begin TempStringList.Delete(lineNum); if (TempStringList.Strings[lineNum]= Delimiter) then begin TempStringList.Delete(lineNum); result := true; break; end end; if (result) then break; end else inc(lineNum); end; TempStringList.SaveToFile(FilePath); TempStringList.Free; end; { // Pass the name of the filter you want to load, the same name passed // from the SaveFilterToFile procedure. } function TwwSaveFilter.LoadFilter(FilterName: string): boolean; var myFieldInfoStrings, TempStringList: TStrings; lineNum: integer; curFieldInfo: TwwFieldInfo; begin TempStringList := TStringList.create; TempStringList.LoadFromFile(FilePath); lineNum:=0; result:= false; while(lineNum<TempStringList.Count) do begin if (TempStringList.Strings[lineNum] = FilterName) then begin FFilterDialog.ClearFilter; myFieldInfoStrings := TStringList.create; while (lineNum+1<TempStringList.Count) do begin inc(lineNum); if (TempStringList.Strings[lineNum]= Delimiter) then break; curFieldInfo := TwwFieldInfo.create; strBreakApart(TempStringList.Strings[lineNum], #9, myFieldInfoStrings); curFieldInfo.FieldName := myFieldInfoStrings.Strings[0]; curFieldInfo.DisplayLabel := myFieldInfoStrings.Strings[1]; curFieldInfo.MatchType := TwwFilterMatchType(StrToInt(myFieldInfoStrings.Strings[2])); curFieldInfo.FilterValue := myFieldInfoStrings.Strings[3]; curFieldInfo.MinValue := myFieldInfoStrings.Strings[4]; curFieldInfo.MaxValue := myFieldInfoStrings.Strings[5]; if (myFieldInfoStrings.Strings[6] = 'True') then curFieldInfo.CaseSensitive := True else curFieldInfo.CaseSensitive := False; FFilterDialog.FieldInfo.Add(curFieldInfo); end; myFieldInfoStrings.Free; FFilterDialog.ApplyFilter; result := true; break; end else inc(lineNum); end; TempStringList.Free; end; { // Get list of filter names } function TwwSaveFilter.GetFilterNames(FilterNames: TStrings): boolean; var TempStringList: TStrings; lineNum: integer; begin FilterNames.Clear; if (not FileExists(FilePath)) then begin result:= false; exit; end; TempStringList := TStringList.create; TempStringList.LoadFromFile(FilePath); LineNum:=0; while(lineNum<TempStringList.Count) do begin if (length(TempStringList.Strings[lineNum])=0) then begin{ Skip null lines} inc(lineNum); continue; end; if (lineNum<TempStringList.Count) then FilterNames.Add(TempStringList.Strings[lineNum]); { Skip text until encounter delimeter, then add line following delimeter to list } while ((TempStringList.Strings[lineNum] <> Delimiter) and (lineNum<TempStringList.Count-1)) do inc(lineNum); inc(lineNum); end; TempStringList.Free; result:= FilterNames.count>0; end; {// Inform filterdialog to notify us when it is destroyed} procedure TwwSaveFilter.SetFilterDialog(val: TwwFilterDialog); begin if (FFilterDialog<>Nil) then FFilterDialog.RemoveDependent(self); FFilterDialog:=val; if (val<>Nil) then FFilterDialog.AddDependent(self); end; procedure TwwSaveFilter.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if ((Operation = opRemove) and (AComponent = FFilterDialog)) then FFilterDialog:= Nil; end; procedure Register; begin RegisterComponents('Samples', [TwwSaveFilter]); end; end.
unit uControllerThread; interface uses System.Classes, System.SysUtils, uController, uModbus; type TJobError = procedure(Error: TModbusError) of object; TControllerThread = class(TThread) private FController: TController; FAddr: byte; FPort: integer; FSpeed: integer; FHost: string; FError: TModbusError; FOnJobError: TJobError; FDeviceType: byte; //0-турникет 1-ЖКИ индикатор procedure DoJobError; procedure JobError(Error: TModbusError); protected procedure Execute; override; public constructor Create(Port: byte; Speed: integer; Addr: byte); overload; constructor Create(Host: string; Port: integer; Addr: byte); overload; destructor Destroy; override; property OnJobError: TJobError read FOnJobError write FOnJobError; property Controller: TController read FController; property DeviceType: byte write FDeviceType; end; implementation uses uMain; { ProtocolThread } constructor TControllerThread.Create(Port: byte; Speed: integer; Addr: byte); begin inherited Create(true); FreeOnTerminate := true; Priority := tpNormal; FAddr := Addr; FPort := port; FSpeed := speed; end; constructor TControllerThread.Create(Host: string; Port: integer; Addr: byte); begin inherited Create(true); FreeOnTerminate := true; Priority := tpNormal; FAddr := Addr; FPort := port; FHost := host; end; destructor TControllerThread.Destroy; begin if FController <> nil then begin FController.Close; FController := nil; try // FController.Free; finally FController := nil; end; end; inherited; end; procedure TControllerThread.DoJobError; begin if Assigned(FOnJobError) then FOnJobError(FError); end; procedure TControllerThread.Execute; var t: byte; n: word; ln: longword; IsNew: boolean; Card: Tar; i: byte; count: word; s, s1: ansistring; begin FController := TController.Create; if FHost = '' then FError := FController.Open(FPort, FSpeed, FAddr) else FError := FController.Open(FHost, FPort, FAddr); if FError <> merNone then begin FController.Free; JobError(FError); Terminate; end else Synchronize( procedure begin fmMain.edCompany.Text := FController.DeviceInfo.Company; fmMain.edProduct.Text := FController.DeviceInfo.Product; fmMain.edVer.Text := FController.DeviceInfo.Version; end ); while not Terminated do begin if FDeviceType = 0 then begin FError := FController.GetEnter(FAddr, n); if n = 0 then t := 0 else if n = $FFFF then t := 2 else t := 1; Synchronize( procedure begin fmMain.rgEnterState.ItemIndex := t; end ); JobError(FError); if Terminated then exit; FError := FController.GetExit(FAddr, n); if n = 0 then t := 0 else if n = $FFFF then t := 2 else t := 1; Synchronize( procedure begin fmMain.rgExitState.ItemIndex := t; end ); JobError(FError); if Terminated then exit; FError := FController.GetEnterState(FAddr, n); if n = 0 then t := 0 else t := 1; Synchronize( procedure begin fmMain.rgEnterPassState.ItemIndex := t; end ); JobError(FError); if Terminated then exit; FError := FController.GetExitState(FAddr, n); if n = 0 then t := 0 else t := 1; Synchronize( procedure begin fmMain.rgExitPassState.ItemIndex := t; end ); JobError(FError); if Terminated then exit; FError := FController.GetEnterCount(FAddr, ln); Synchronize( procedure begin fmMain.edEnterCount.Text := IntToStr(ln); end ); JobError(FError); if Terminated then exit; FError := FController.GetExitCount(FAddr, ln); Synchronize( procedure begin fmMain.edExitCount.Text := IntToStr(ln); end ); JobError(FError); if Terminated then exit; FError := FController.GetErrorState(FAddr, n); Synchronize( procedure begin fmMain.cbEngineBlockState.Checked := Boolean(n); end ); JobError(FError); if Terminated then exit; FError := FController.GetEnterCard(FAddr, IsNew, Card, count); if IsNew then begin s := ''; s1 := ''; for i := 0 to count - 1 do begin try s := s + chr(Card[i]) + ' '; s1 := s1 + '$' + IntToHex(Card[i], 2) + ' '; except end; end; Synchronize( procedure begin fmMain.edCard.Text := trim(s1); fmMain.edCardASCII.Text := s; end ); end; JobError(FError); if Terminated then exit; FError := FController.GetExitCard(FAddr, IsNew, Card, count); if IsNew then begin s := ''; s1 := ''; for i := 0 to count - 1 do begin try s := s + chr(Card[i]) + ' '; s1 := s1 + '$' + IntToHex(Card[i], 2) + ' '; except end; end; Synchronize( procedure begin fmMain.edCard2.Text := trim(s1); fmMain.edCard2ASCII.Text := s; end ); end; JobError(FError); if Terminated then exit; FError := FController.GetDemo(FAddr, n); Synchronize( procedure begin if n = 1 then fmMain.Caption := 'Modbus demo on' else fmMain.Caption := 'Modbus demo off'; end ); JobError(FError); end; sleep(900); end; end; procedure TControllerThread.JobError(Error: TModbusError); begin DoJobError; end; end.
unit Modules.Reporting; interface uses System.SysUtils, System.Classes, System.Generics.Collections; type TReportStep = class strict private FLine: Integer; FInstruction: String; FDistance: Double; FDuration: Integer; function GetDistanceKm: Double; function GetDurationMin: Double; public property Line: Integer read FLine write FLine; property Instruction: String read FInstruction write FInstruction; property Distance: Double read FDistance write FDistance; property Duration: Integer read FDuration write FDuration; property DurationMin: Double read GetDurationMin; property DistanceKm: Double read GetDistanceKm; end; type TReporting = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FCustomerAddress: String; FSteps: TObjectList<TReportStep>; FRatePerHour: Double; FRatePerKm: Double; function GetCostDriving: Double; function GetCostDuration: Double; function GetTotalDistance: Double; function GetTotalDuration: Integer; function GetCostHalfHour: Double; function GetHalfHours: Integer; function GetTotalDistanceKm: Integer; { Private declarations } public { Public declarations } procedure Clear; procedure AddStep( ALine: Integer; AInstruction: String; ADistance:Double; ADuration:Integer ); function AsPDF: TMemoryStream; property Steps: TObjectList<TReportStep> read FSteps; property TotalDuration: Integer read GetTotalDuration; property TotalDistance: Double read GetTotalDistance; property CostDuration: Double read GetCostDuration; property CostDistance: Double read GetCostDriving; property CustomerAddress: String read FCustomerAddress write FCustomerAddress; property TotalDistanceKm : Integer read GetTotalDistanceKm; property HalfHours : Integer read GetHalfHours; property CostHalfHour : Double read GetCostHalfHour; property RatePerHour: Double read FRatePerHour write FRatePerHour; property RatePerKm: Double read FRatePerKm write FRatePerKm; end; var Reporting: TReporting; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} uses System.IOUtils, VCL.FlexCel.Core, TMSFNCUtils, FlexCel.XlsAdapter, FlexCel.Render, FlexCel.Report, FlexCel.PDF; { TReporting } procedure TReporting.AddStep(ALine: Integer; AInstruction: String; ADistance: Double; ADuration: Integer); var LItem: TReportStep; begin LItem := TReportStep.Create; LItem.Line := ALine; LItem.Instruction := AInstruction; LItem.Distance := ADistance; LItem.Duration := ADuration; Steps.Add(LItem); end; function TReporting.AsPDF: TMemoryStream; var LReport : TFlexCelReport; LResource: TResourceStream; LTemplate: TMemoryStream; LOutput: TMemoryStream; LXlsFile: TXlsFile; LPdf: TFlexCelPdfExport; begin LReport := TFlexCelReport.Create; LTemplate := TMemoryStream.Create; LXlsFile := TXlsFile.Create; LOutput := TMemoryStream.Create; LPdf := TFlexCelPdfExport.Create; try // load template from the resource LResource := TTMSFNCUtils.GetResourceStream('Report'); LTemplate.LoadFromStream( LResource ); LTemplate.Position := 0; // set placeholders LReport.SetValue('CustomerAddr', self.CustomerAddress ); LReport.SetValue('TotalDuration', Format( '%d min', [self.TotalDuration DIV 60]) ); LReport.SetValue('TotalDistance', Format( '%d km', [self.TotalDistanceKm]) ); LReport.SetValue('CostDuration', Format( '%m', [CostDuration] )); LReport.SetValue('CostDistance', Format( '%m', [CostDistance] )); LReport.SetValue('CostTotal', Format( '%m', [CostDuration + CostDistance] )); // link list of steps to report LReport.AddTable<TReportStep>('Q', Steps); // run the report LReport.Run(LTemplate, LOutput); // convert to PDF LPdf.Workbook := LXlsFile; LOutput.Position := 0; LPdf.Workbook.Open(LOutput); // return PDF as stream Result := TMemoryStream.Create; LPdf.Export(Result); finally LPdf.Free; LOutput.Free; LXlsFile.Free; LTemplate.Free; LReport.Free; LResource.Free; end; end; procedure TReporting.Clear; begin Steps.Clear; end; procedure TReporting.DataModuleCreate(Sender: TObject); begin FSteps := TObjectList<TReportStep>.Create; FRatePerHour := 100.0; FRatePerKm := 0.5; end; procedure TReporting.DataModuleDestroy(Sender: TObject); begin FSteps.Free; end; function TReporting.GetCostDriving: Double; begin Result := ( TotalDistanceKm ) * RatePerKm; end; function TReporting.GetCostDuration: Double; begin Result := CostHalfHour * HalfHours; end; function TReporting.GetCostHalfHour: Double; begin Result := RatePerHour / 2; end; function TReporting.GetHalfHours: Integer; begin Result := ( TRUNC( TotalDuration/60/60 ) + 1) * 2; end; function TReporting.GetTotalDistance: Double; var LItem: TReportStep; begin Result := 0; for LItem in Steps do begin Result := Result + LItem.Distance; end; end; function TReporting.GetTotalDistanceKm: Integer; begin Result := TRUNC( TotalDistance/1000 ) + 1; end; function TReporting.GetTotalDuration: Integer; var LItem: TReportStep; begin Result := 0; for LItem in Steps do begin Result := Result + LItem.Duration; end; end; { TReportStep } function TReportStep.GetDistanceKm: Double; begin Result := Distance / 1000; end; function TReportStep.GetDurationMin: Double; begin Result := Duration / 60; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmOutlookReg Purpose : Declares the component and property editors for the rmOutlook control Date : 03-06-01 Author : Ryan J. Mills Version : 1.92 Notes : This unit was originally based upon the work of Patrick O'Keeffe. It was at his request that I took the component over and rm'ified it. ================================================================================} unit rmOutlookReg; interface {$I CompilerDefines.INC} {$ifdef D6_or_higher} uses Classes, DesignIntf, DesignEditors, TypInfo; {$else} uses Classes, DsgnIntf, TypInfo; {$endif} type TrmOutlookActivePageProperty = class(TComponentProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; TrmOutlookControlEditor = class(TDefaultEditor) procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; implementation uses rmOutlook; const SOutlookIndexError = 'Outlook Page Index Error'; StrAddPage = 'New Page'; StrNextPage = 'Next Page'; StrPrevPage = 'Previous Page'; { TrmOutlookActivePageProperty } function TrmOutlookActivePageProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TrmOutlookActivePageProperty.GetValues(Proc: TGetStrProc); var I: Integer; Component: TComponent; begin {$ifdef D6_or_higher} for I := 0 to Designer.Root.ComponentCount - 1 do begin Component := Designer.Root.Components[I]; if (Component.Name <> '') and (Component is TrmOutLookPage) and (TrmOutLookPage(Component).OutlookControl = GetComponent(0)) then Proc(Component.Name); end; {$else} for I := 0 to Designer.Form.ComponentCount - 1 do begin Component := Designer.Form.Components[I]; if (Component.Name <> '') and (Component is TrmOutLookPage) and (TrmOutLookPage(Component).OutlookControl = GetComponent(0)) then Proc(Component.Name); end; {$endif} end; { TrmOutlookControlEditor } procedure TrmOutlookControlEditor.ExecuteVerb(Index: Integer); var OutlookControl: TrmOutLookControl; Page: TrmOutLookPage; // Designer: IDesigner; begin if Component is TrmOutLookPage then OutlookControl := TrmOutLookPage(Component).OutlookControl else OutlookControl := TrmOutLookControl(Component); if OutlookControl <> nil then begin // Designer := Self.Designer; if Index = 0 then begin {$ifdef D6_or_higher} Page := TrmOutLookPage.Create(Designer.Root); {$else} Page := TrmOutLookPage.Create(Designer.Form); {$endif} try Page.Name := Designer.UniqueName(TrmOutLookPage.ClassName); Page.OutlookControl := OutlookControl; Page.Caption := Page.Name; except Page.Free; raise; end; OutlookControl.ActivePage := Page; Designer.SelectComponent(Page); Designer.Modified; end else begin Page := OutlookControl.FindNextPage(OutlookControl.ActivePage, Index = 1); if (Page <> nil) and (Page <> OutlookControl.ActivePage) then begin OutlookControl.ActivePage := Page; if Component is TrmOutLookPage then Designer.SelectComponent(Page); Designer.Modified; end; end; end; end; function TrmOutlookControlEditor.GetVerb(Index: Integer): string; begin case Index of 0 : Result:= StrAddPage; 1 : Result:= StrNextPage; 2 : Result:= StrPrevPage; end; end; function TrmOutlookControlEditor.GetVerbCount: Integer; begin Result := 3; end; end.
namespace MetalExample; interface uses Metal, MetalKit; type //"Basic Texturing" MetalExample4 = class(MetalBaseDelegate) private const cShaderName = 'AAPLShaders4.metallib'; cVertexFuncName = 'vertexShaderTex2'; cFragmentFuncName = 'samplingShader2'; var _pipelineState :MTLRenderPipelineState ; _viewportSize : array [0..1] of UInt32;//Integer; _texture : array of MTLTexture; _Vertextes : array of AAPLVertex3; akttex : Integer := 0; aktloop : Integer; method mtkView(view: not nullable MTKView) drawableSizeWillChange(size: CGSize); override; method drawInMTKView(view: not nullable MTKView); override; method loadTextureWithLoader; method fillVertexes : array of AAPLVertex3; public constructor initWithMetalKitView(const mtkView: not nullable MTKView); end; implementation constructor MetalExample4 initWithMetalKitView(const mtkView: not nullable MTKView); begin inherited; var ShaderLoader := new shaderLoader(_device) Shadername(cShaderName) Vertexname(cVertexFuncName) Fragmentname(cFragmentFuncName); if ShaderLoader = nil then exit nil else begin var lError : Error; // Configure a pipeline descriptor that is used to create a pipeline state var pipelineStateDescriptor : MTLRenderPipelineDescriptor := new MTLRenderPipelineDescriptor(); pipelineStateDescriptor.label := "Simple Pipeline"; pipelineStateDescriptor.vertexFunction := ShaderLoader.VertexFunc; pipelineStateDescriptor.fragmentFunction := ShaderLoader.FragmentFunc; var renderbufferAttachment := pipelineStateDescriptor.colorAttachments[0]; renderbufferAttachment.pixelFormat := mtkView.colorPixelFormat; const blending = true; if blending then begin renderbufferAttachment.blendingEnabled := true; renderbufferAttachment.rgbBlendOperation := MTLBlendOperation.MTLBlendOperationAdd; renderbufferAttachment.alphaBlendOperation := MTLBlendOperation.MTLBlendOperationAdd; renderbufferAttachment.sourceRGBBlendFactor := MTLBlendFactor.MTLBlendFactorSourceAlpha; renderbufferAttachment.sourceAlphaBlendFactor := MTLBlendFactor.MTLBlendFactorSourceAlpha; renderbufferAttachment.destinationRGBBlendFactor := MTLBlendFactor.MTLBlendFactorOneMinusSourceAlpha; renderbufferAttachment.destinationAlphaBlendFactor := MTLBlendFactor.MTLBlendFactorOneMinusSourceAlpha; end; _pipelineState := _device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor) error(var lError); if (_pipelineState = nil) then begin // Pipeline State creation could fail if we haven't properly set up our pipeline descriptor. // If the Metal API validation is enabled, we can find out more information about what // went wrong. (Metal API validation is enabled by default when a debug build is run // from Xcode) NSLog("Failed to created pipeline state, error %@", lError); exit nil; end; loadTextureWithLoader; _Vertextes := fillVertexes; end; end; method MetalExample4.mtkView(view: not nullable MTKView) drawableSizeWillChange(size: CGSize); begin _viewportSize[0] := Convert.ToInt32(size.width); _viewportSize[1] := Convert.ToInt32(size.height); end; method MetalExample4.loadTextureWithLoader; begin var Loader : MTKTextureLoader := new MTKTextureLoader withDevice(_device); var Lerror : Error; var texturl0 := Asset.getUrlfor("Tex1.JPG"); var texturl1 := Asset.getUrlfor("coral.JPG"); var lDict := NSDictionary<MTKTextureLoaderOption, NSNumber>.dictionaryWithObjects( [ NSNumber.numberWithBool(false) ] ) forKeys( [ MTKTextureLoaderOptionSRGB ] ) ; // Load the textures _texture := new MTLTexture[2]; _texture[0] := Loader.newTextureWithContentsOfURL(texturl0) options(lDict) error(var Lerror); if Lerror <> nil then begin NSLog("Failed to Load Texture, error %@", Lerror); exit; end; _texture[1] := Loader.newTextureWithContentsOfURL(texturl1) options(lDict) error(var Lerror); if Lerror <> nil then begin NSLog("Failed to Load Texture, error %@", Lerror); exit; end; end; method MetalExample4.fillVertexes : array of AAPLVertex3; begin result := new AAPLVertex3[6]; const hsize = 600.0; const vsize = 400.0; //Positions result[0].position := [hsize, -vsize]; result[1].position := [-hsize, -vsize]; result[2].position := [-hsize, vsize]; result[3].position := [hsize, -vsize]; result[4].position := [-hsize, vsize]; result[5].position := [hsize, vsize]; // Texture result[0].textureCoordinate := [1.0, 1.0]; result[1].textureCoordinate := [0.0, 1.0]; result[2].textureCoordinate := [0, 0]; result[3].textureCoordinate := [1,1]; result[4].textureCoordinate := [0,0]; result[5].textureCoordinate := [1,0]; //NSLog("SizeStruct %d", sizeOf(AAPLVertex3)); end; method MetalExample4.drawInMTKView(view: not nullable MTKView); begin var commandBuffer := _commandQueue.commandBuffer(); commandBuffer.label := 'MyCommand'; var renderPassDescriptor: MTLRenderPassDescriptor := view.currentRenderPassDescriptor; if renderPassDescriptor ≠ nil then begin view.clearColor := MTLClearColorMake(0, 0, 0, 1); var renderEncoder: IMTLRenderCommandEncoder := commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor); renderEncoder.label := 'MyRenderEncoder'; // Set the region of the drawable to which we'll draw. var vp : MTLViewport; vp.originX:=0.0;; vp.originY:=0.0; vp.width:=_viewportSize[0]; vp.height:= _viewportSize[1]; vp.znear:= -1.0; vp.zfar:= 1.0; renderEncoder.setViewport(vp); renderEncoder.setRenderPipelineState(_pipelineState); var sizeTriangle := _Vertextes.length * sizeOf(AAPLVertex3); // var sizeTriangle := sizeOf(triangleVertices);//.length * sizeOf(AAPLVertex); renderEncoder.setVertexBytes(@_Vertextes[0] ) length(sizeTriangle) atIndex(AAPLVertexInputIndexVertices); // You send a pointer to `_viewportSize` and also indicate its size // The `AAPLVertexInputIndexViewportSize` enum value corresponds to the // `viewportSizePointer` argument in the `vertexShader` function because its // buffer attribute also uses the `AAPLVertexInputIndexViewportSize` enum value // for its index renderEncoder.setVertexBytes(@_viewportSize[0]) length(sizeOf(Int32)*2) atIndex(AAPLVertexInputIndexViewportSize ); renderEncoder.setFragmentTexture(_texture[0]) atIndex(0); // Draw the 3 vertices of our triangle renderEncoder.drawPrimitives(MTLPrimitiveType.MTLPrimitiveTypeTriangle) vertexStart(0) vertexCount(6); renderEncoder.setFragmentTexture(_texture[1]) atIndex(0); // Draw the 3 vertices of our triangle renderEncoder.drawPrimitives(MTLPrimitiveType.MTLPrimitiveTypeTriangle) vertexStart(0) vertexCount(6); renderEncoder.endEncoding(); commandBuffer.presentDrawable(view.currentDrawable); end; commandBuffer.commit(); inc(aktloop); if aktloop > 100 then begin akttex := if akttex = 0 then 1 else 0; aktloop := 0; end; end; end.
unit ufrmDialogQuotation; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialogBrowse, ExtCtrls, StdCtrls, ufrmQuotation, uRetnoUnit,DB,jpeg, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, cxDBData, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, cxDropDownEdit, cxCalendar, cxTextEdit, cxMaskEdit, cxButtonEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, cxGroupBox, cxCheckBox, Vcl.Menus, cxButtons, cxCurrencyEdit, ufrmMasterDialog, cxGridBandedTableView, cxSplitter, cxGridDBBandedTableView, uInterface, Datasnap.DBClient, cxMemo, uModQuotation, uModelHelper; type TfrmDialogQuotation = class(TfrmMasterDialog, ICrudAble) cxGroupBox1: TcxGroupBox; Label6: TLabel; cxLookupSupplierMerchan: TcxExtLookupComboBox; Label7: TLabel; cxLookupMerchan: TcxExtLookupComboBox; dtEffective: TcxDateEdit; Label8: TLabel; Label9: TLabel; dtEnd: TcxDateEdit; ckIsMailer: TcxCheckBox; Label10: TLabel; Label11: TLabel; edQuotNo: TcxTextEdit; cxGridMasterLevel1: TcxGridLevel; cxGridMaster: TcxGrid; cxGrdDBHeader: TcxGridDBBandedTableView; cxSplitter1: TcxSplitter; colHeaderBrgCode: TcxGridDBBandedColumn; colHeaderBrgName: TcxGridDBBandedColumn; colHeaderSatuan: TcxGridDBBandedColumn; colHeaderBuyPrice: TcxGridDBBandedColumn; colHeaderBuyDisc1: TcxGridDBBandedColumn; colHeaderBuyDisc2: TcxGridDBBandedColumn; colHeaderBuyDisc3: TcxGridDBBandedColumn; colHeaderMargin: TcxGridDBBandedColumn; colHeaderSellPrice: TcxGridDBBandedColumn; colHeaderSellDiscPerc: TcxGridDBBandedColumn; colHeaderSellDiscRp: TcxGridDBBandedColumn; colHeaderSellNetPrice: TcxGridDBBandedColumn; colHeaderSellPricePPN: TcxGridDBBandedColumn; mmRemark: TcxMemo; colHeaderBuyPricePPN: TcxGridDBBandedColumn; pmHeader: TPopupMenu; SetHargaBeliHargaIncludePPN1: TMenuItem; gbSuppOption: TcxGroupBox; ckShowPPN: TcxCheckBox; chkUpdateSellPrice: TcxCheckBox; colHeaderUpdateSellPrice: TcxGridDBBandedColumn; pnlDetail: TcxGroupBox; cxGridDetail: TcxGrid; cxGrdDBDetail: TcxGridDBTableView; colDetailTipeHarga: TcxGridDBColumn; colDetailSatuan: TcxGridDBColumn; colDetailKonversi: TcxGridDBColumn; cxGrdDBDetailColumn1: TcxGridDBColumn; colDetailMargin: TcxGridDBColumn; colDetailSellPrice: TcxGridDBColumn; colDetailSellDiscPerc: TcxGridDBColumn; colDetailSellDiscRp: TcxGridDBColumn; colDetailSellNetPrice: TcxGridDBColumn; colDetailSellPricePPN: TcxGridDBColumn; cxGrdDBDetailColumn2: TcxGridDBColumn; cxGrdDBDetailColumn3: TcxGridDBColumn; cxGrdDBDetailColumn4: TcxGridDBColumn; cxGrdDBDetailColumn5: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; cxGroupBox2: TcxGroupBox; btnAddSat: TcxButton; btnDelSat: TcxButton; pmDetail: TPopupMenu; SetHargaJualiHargaIncludePPN1: TMenuItem; cxGroupBox3: TcxGroupBox; btnAddProd: TcxButton; btnDelProd: TcxButton; btnActivate: TcxButton; colHeaderBuyNetPrice: TcxGridDBBandedColumn; procedure actDeleteExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cxLookupMerchanPropertiesEditValueChanged(Sender: TObject); procedure colHeaderBuyPricePropertiesEditValueChanged(Sender: TObject); procedure colHeaderBuyDisc1PropertiesEditValueChanged(Sender: TObject); procedure colHeaderBuyDisc2PropertiesEditValueChanged(Sender: TObject); procedure colHeaderBuyDisc3PropertiesEditValueChanged(Sender: TObject); procedure SetHargaBeliHargaIncludePPN1Click(Sender: TObject); procedure colDetailSellPricePropertiesEditValueChanged(Sender: TObject); procedure colDetailSellDiscPercPropertiesEditValueChanged(Sender: TObject); procedure colDetailSellDiscRpPropertiesEditValueChanged(Sender: TObject); procedure colDetailMarginPropertiesEditValueChanged(Sender: TObject); procedure btnDelKonvClick(Sender: TObject); procedure SetHargaJualiHargaIncludePPN1Click(Sender: TObject); procedure btnAddProdClick(Sender: TObject); procedure btnDelProdClick(Sender: TObject); procedure ckShowPPNPropertiesEditValueChanged(Sender: TObject); procedure btnAddSatClick(Sender: TObject); procedure btnDelSatClick(Sender: TObject); procedure colDetailSatuanPropertiesEditValueChanged(Sender: TObject); procedure btnActivateClick(Sender: TObject); private FCDSHeader: TClientDataSet; FCDSDetail: TClientDataSet; FCDSSuplierMerchan: TClientDataSet; FModQuotation: TModQuotation; procedure AddProduct; procedure AddSellPrice; procedure CalculateNetBuyPrice; procedure CalculateNetSellPrice(Sender: TcxGridDBColumn); procedure CheckAndUpdateKonversi; procedure DeleteProduct; procedure DeleteSellPrice; function GetCDSHeader: TClientDataSet; function GetCDSDetail: TClientDataSet; function GetCDSSuplierMerchan: TClientDataSet; function GetModQuotation: TModQuotation; procedure InitReadOnly; procedure initView; procedure LoadHargaJual; procedure UpdateData; procedure UpdateSellingPrice(IsUpdateSellPrice: Boolean = True); function ValidateData: Boolean; property CDSHeader: TClientDataSet read GetCDSHeader write FCDSHeader; property CDSDetail: TClientDataSet read GetCDSDetail write FCDSDetail; property CDSSuplierMerchan: TClientDataSet read GetCDSSuplierMerchan write FCDSSuplierMerchan; property ModQuotation: TModQuotation read GetModQuotation write FModQuotation; public procedure InitActivation(aAktivasi: Boolean = True); procedure LoadData(aID: String); end; var frmDialogQuotation: TfrmDialogQuotation; implementation uses uTSCommonDlg, DateUtils, Math, uConstanta, uAppUtils, uDBUtils, uDXUtils, uDMClient, ufrmCXLookup, uModBarang, uModSuplier, uClientClasses; {$R *.dfm} procedure TfrmDialogQuotation.actDeleteExecute(Sender: TObject); begin inherited; if ModQuotation.IsProcessed=1 then begin TAppUtils.Warning('Quotation sudah diaktivasi tidak bisa dihapus'); exit; end; Try DMClient.CrudClient.DeleteFromDB(ModQuotation); TAppUtils.Information(CONF_DELETE_SUCCESSFULLY); Self.ModalResult := mrOk; except TAppUtils.Error(ER_DELETE_FAILED); raise; End; end; procedure TfrmDialogQuotation.actSaveExecute(Sender: TObject); begin inherited; if not ValidateData then exit; UpdateData; Try ModQuotation.ID := DMClient.CrudClient.SaveToDBID(ModQuotation); TAppUtils.Information(CONF_ADD_SUCCESSFULLY); Self.ModalResult := mrOk; except TAppUtils.Error(ER_INSERT_FAILED); raise; End; end; procedure TfrmDialogQuotation.AddProduct; var frm: TfrmCXLookup; lCDS: TClientDataSet; lModBrg: TModBarang; begin inherited; if VarIsNull(cxLookupSupplierMerchan.EditValue) then begin TAppUtils.Warning('Supplier Merchan harap dipilih terlebih dahulu'); exit; end; lCDS := TClientDataSet( DMClient.DSProviderClient.BarangQuotation_GetDSLookup(cxLookupSupplierMerchan.EditValue) ); frm := TfrmCXLookup.Execute(lCDS, True); Try frm.HideFields(['BARANG_SUPLIER_ID', 'BARANG_ID', 'SUPLIER_ID', 'SUP_CODE', 'SUP_NAME', 'SUPLIER_MERCHAN_GRUP_ID', 'REF$SATUAN_PURCHASE']); if frm.ShowModal = mrOk then begin while not frm.Data.eof do begin if not CDSHeader.Locate('Barang', frm.Data.FieldByName('BARANG_ID').AsString, [loCaseInsensitive]) then begin lModBrg := TCRUDObj.Retrieve<TModBarang>(frm.Data.FieldByName('BARANG_ID').AsString); Try CDSHeader.Append; CDSHeader.SetFieldFrom('BrgCode', frm.Data, 'BRG_CODE'); CDSHeader.SetFieldFrom('Satuan', frm.Data, 'REF$SATUAN_PURCHASE'); CDSHeader.SetFieldFrom('BrgName', frm.Data, 'BRG_NAME'); CDSHeader.SetFieldFrom('BuyPrice', frm.Data, 'BuyPrice'); CDSHeader.SetFieldFrom('BuyDisc1', frm.Data, 'Disc1'); CDSHeader.SetFieldFrom('BuyDisc2', frm.Data, 'Disc2'); CDSHeader.SetFieldFrom('BuyDisc3', frm.Data, 'Disc3'); CDSHeader.SetFieldFrom('Konversi', frm.Data, 'Konversi'); CDSHeader.SetFieldFrom('Barang', frm.Data, 'BARANG_ID'); CDSHeader.SetFieldFrom('IsBKP', frm.Data, 'Is_BKP'); CDSHeader.SetFieldFrom('Margin', frm.Data, 'BRGSUP_MARK_UP'); CDSHeader.SetFieldFrom('BarangSupplier', frm.Data, 'BARANG_SUPLIER_ID'); if chkUpdateSellPrice.Checked then CDSHeader.FieldByName('IsUpdateSellPrice').AsInteger := 1 else CDSHeader.FieldByName('IsUpdateSellPrice').AsInteger := 0; if lModBrg.RefPajak <> nil then begin lModBrg.RefPajak.Reload; CDSHeader.FieldByName('PPN').AsFloat := lModBrg.RefPajak.PJK_PPN; end; CDSHeader.Post; CalculateNetBuyPrice; LoadHargaJual; Finally FreeAndNil(lModBrg); End; end; frm.Data.Next; end; end; Finally frm.Free; lCDS.Free; End; end; procedure TfrmDialogQuotation.AddSellPrice; begin CDSDetail.Append; CDSDetail.FieldByName('Barang').AsString := CDSHeader.FieldByName('Barang').AsString; CDSDetail.FieldByName('BarangSupplier').AsString := CDSHeader.FieldByName('BarangSupplier').AsString; // CDSDetail.FieldByName('TipeHarga').AsString := ''; // CDSDetail.FieldByName('Satuan').AsString := ''; CDSDetail.FieldByName('SellPrice').AsFloat := 0; CDSDetail.FieldByName('SellDiscPercent').AsFloat := 0; CDSDetail.FieldByName('SellDiscRp').AsFloat := 0; CDSDetail.FieldByName('Konversi').AsFloat := 0; CDSDetail.FieldByName('Margin').AsFloat := 0; CDSDetail.FieldByName('BuyPrice').AsFloat := 0; CDSDetail.FieldByName('BuyDisc1').AsFloat := 0; CDSDetail.FieldByName('BuyDisc2').AsFloat := 0; CDSDetail.FieldByName('BuyDisc3').AsFloat := 0; CDSDetail.FieldByName('BUYPRICE_INC_DISC').AsFloat := 0; CDSDetail.FieldByName('BUYPRICE_INC_PPN').AsFloat := 0; CDSDetail.FieldByName('IsBKP').AsInteger := CDSHeader.FieldByName('IsBKP').AsInteger; CDSDetail.Post; end; procedure TfrmDialogQuotation.btnDelKonvClick(Sender: TObject); begin inherited; DeleteProduct; end; procedure TfrmDialogQuotation.CalculateNetBuyPrice; var dDisc1: Double; dDisc2: Double; dDisc3: Double; dNet: Double; dPrice: Double; begin if CDSHeader.State in [dsEdit] then CDSHeader.Post; dPrice := CDSHeader.FieldByName('BuyPrice').AsFloat; dDisc1 := CDSHeader.FieldByName('BuyDisc1').AsFloat * dPrice / 100; dNet := dPrice - dDisc1; dDisc2 := CDSHeader.FieldByName('BuyDisc2').AsFloat * dNet / 100; dNet := dNet - dDisc2; dDisc3 := CDSHeader.FieldByName('BuyDisc3').AsFloat; dNet := dNet - dDisc3; CDSHeader.Edit; CDSHeader.FieldByName('BUYPRICE_INC_DISC').AsFloat := dNet; CDSHeader.FieldByName('BUYPRICE_INC_PPN').AsFloat := dNet; if CDSHeader.FieldByName('ISBKP').AsInteger = 1 then CDSHeader.FieldByName('BUYPRICE_INC_PPN').AsFloat := dNet * 1.1; CDSHeader.Post; UpdateSellingPrice(CDSHeader.FieldByName('IsUpdateSellPrice').AsInteger=1); end; procedure TfrmDialogQuotation.CalculateNetSellPrice(Sender: TcxGridDBColumn); var dBuyPrice: Double; dDiscRp: Double; dDiscPr: Double; dMargin: Double; dNet: Double; dPrice: Double; begin if CDSDetail.State in [dsEdit] then CDSDetail.Post; dMargin := CDSDetail.FieldByName('Margin').AsFloat; dDiscRp := CDSDetail.FieldByName('SellDiscRp').AsFloat; dDiscPr := CDSDetail.FieldByName('SellDiscPercent').AsFloat; dPrice := CDSDetail.FieldByName('SellPrice').AsFloat; dBuyPrice := CDSDetail.FieldByName('BUYPRICE_INC_PPN').AsFloat; if Sender = colDetailMargin then begin dPrice := dBuyPrice * (100+dMargin)/100; dDiscRp := dPrice * dDiscRp/100; end else if (Sender = colDetailSellPrice) and (dBuyPrice<>0) then begin dMargin := (dPrice-dBuyPrice) / dBuyPrice * 100; end else if Sender = colDetailSellDiscPerc then begin dDiscRp := dPrice * dDiscPr/100; end else if (Sender = colDetailSellDiscRp) and (dPrice<>0) then begin dDiscPr := dDiscRp / dPrice * 100; end; dNet := dPrice - dDiscRp; CDSDetail.Edit; CDSDetail.FieldByName('SellPrice').AsFloat := dPrice; CDSDetail.FieldByName('Margin').AsFloat := dMargin; CDSDetail.FieldByName('SellDiscPercent').AsFloat := dDiscPr; CDSDetail.FieldByName('SellDiscRp').AsFloat := dDiscRp; CDSDetail.FieldByName('SellNetPrice').AsFloat := dNet; // if CDSHeader.FieldByName('IsBKP').AsInteger = 1 then // CDSDetail.FieldByName('SellPricePPN').AsFloat := dNet * 1.1; CDSDetail.Post; end; procedure TfrmDialogQuotation.CheckAndUpdateKonversi; var i: Integer; lBarang: TModBarang; lBarangID: string; lSatCode: string; lSatuanID: string; begin if CDSDetail.State in [dsEdit] then CDSDetail.Post; lBarangID := CDSHeader.FieldByName('Barang').AsString; lSatuanID := CDSDetail.FieldByName('Satuan').AsString; lSatCode := VarToStr(cxGrdDBDetail.DataController.DisplayTexts[ cxGrdDBDetail.DataController.FocusedRecordIndex, colDetailSatuan.Index]); lBarang := DMClient.CrudClient.Retrieve(TModBarang.ClassName, lBarangID) as TModBarang; Try CDSDetail.Edit; CDSDetail.FieldByName('Konversi').AsFloat := 0; CDSDetail.FieldByName('Satuan').AsString := ''; for i := 0 to lBarang.Konversi.Count-1 do begin if lBarang.Konversi[i].Satuan.ID = lSatuanID then begin CDSDetail.FieldByName('Konversi').AsFloat := lBarang.Konversi[i].KONVSAT_SCALE; CDSDetail.FieldByName('Satuan').AsString := lSatuanID; end; end; CDSDetail.Post; if CDSDetail.FieldByName('Satuan').AsString <> '' then UpdateSellingPrice(CDSHeader.FieldByName('IsUpdateSellPrice').AsInteger=1) else TAppUtils.Error('Satuan ' + lSatCode + ' tidak ditemukan di daftar Konversi Product ' + lBarang.BRG_NAME ); Finally lBarang.Free; End; end; procedure TfrmDialogQuotation.ckShowPPNPropertiesEditValueChanged( Sender: TObject); begin inherited; // colDetailSellPricePPN.Visible := ckShowPPN.Checked; colHeaderBuyPricePPN.Position.Band.Visible := ckShowPPN.Checked; end; procedure TfrmDialogQuotation.colDetailMarginPropertiesEditValueChanged( Sender: TObject); begin inherited; CalculateNetSellPrice(colDetailMargin); end; procedure TfrmDialogQuotation.colDetailSatuanPropertiesEditValueChanged( Sender: TObject); begin inherited; CheckAndUpdateKonversi; end; procedure TfrmDialogQuotation.colDetailSellDiscPercPropertiesEditValueChanged( Sender: TObject); begin inherited; CalculateNetSellPrice(colDetailSellDiscPerc); end; procedure TfrmDialogQuotation.colDetailSellDiscRpPropertiesEditValueChanged( Sender: TObject); begin inherited; CalculateNetSellPrice(colDetailSellDiscRp); end; procedure TfrmDialogQuotation.colDetailSellPricePropertiesEditValueChanged( Sender: TObject); begin inherited; CalculateNetSellPrice(colDetailSellPrice); end; procedure TfrmDialogQuotation.colHeaderBuyDisc1PropertiesEditValueChanged( Sender: TObject); begin inherited; CalculateNetBuyPrice(); end; procedure TfrmDialogQuotation.colHeaderBuyDisc2PropertiesEditValueChanged( Sender: TObject); begin inherited; CalculateNetBuyPrice(); end; procedure TfrmDialogQuotation.colHeaderBuyDisc3PropertiesEditValueChanged( Sender: TObject); begin inherited; CalculateNetBuyPrice(); end; procedure TfrmDialogQuotation.colHeaderBuyPricePropertiesEditValueChanged( Sender: TObject); begin inherited; CalculateNetBuyPrice(); end; procedure TfrmDialogQuotation.btnAddSatClick(Sender: TObject); begin inherited; AddSellPrice; end; procedure TfrmDialogQuotation.btnDelSatClick(Sender: TObject); begin inherited; DeleteSellPrice; end; procedure TfrmDialogQuotation.btnActivateClick(Sender: TObject); var lQuot: TCrudQuotationClient; begin inherited; if ModQuotation.ID = '' then begin TAppUtils.Warning('Harap simpan terlebih dahulu Quotation sebelum aktivasi'); end; lQuot := TCrudQuotationClient.Create(DMClient.RestConn, False); Try if lQuot.ActivateQuotation(ModQuotation) then begin TAppUtils.Information('Quotation Berhasil di aktivasi'); actSave.Enabled := False; btnActivate.Enabled := False; exit; end; Finally lQuot.Free; End; end; procedure TfrmDialogQuotation.btnAddProdClick(Sender: TObject); begin inherited; AddProduct; end; procedure TfrmDialogQuotation.btnDelProdClick(Sender: TObject); begin inherited; DeleteProduct; end; procedure TfrmDialogQuotation.cxLookupMerchanPropertiesEditValueChanged( Sender: TObject); begin inherited; cxLookupSupplierMerchan.DS.Filtered := True; cxLookupSupplierMerchan.DS.Filter := '[REF$MERCHANDISE_ID] = ' + QuotedStr(cxLookupMerchan.EditValue); end; procedure TfrmDialogQuotation.DeleteProduct; begin CDSHeader.DisableControls; CDSDetail.DisableControls; Try CDSDetail.First; while not CDSDetail.Eof do begin CDSDetail.Delete; end; CDSHeader.Delete; Finally CDSHeader.EnableControls; CDSDetail.EnableControls; End; end; procedure TfrmDialogQuotation.DeleteSellPrice; begin If not CDSDetail.Eof then CDSDetail.Delete; end; procedure TfrmDialogQuotation.FormCreate(Sender: TObject); begin inherited; initView; LoadData(''); end; function TfrmDialogQuotation.GetCDSHeader: TClientDataSet; begin If not Assigned(FCDSHeader) then begin FCDSHeader := TDBUtils.CreateObjectDataSet(TModQuotationDetail, Self, False); FCDSHeader.AddField('BrgCode', ftString); FCDSHeader.AddField('BrgName', ftString); // FCDSHeader.AddField('IsPurchaseUOM', ftBoolean); // FCDSHeader.AddField('SellPricePPN', ftFloat); // FCDSHeader.AddField('BuyNetPrice', ftFloat); FCDSHeader.CreateDataSet; end; Result := FCDSHeader; end; function TfrmDialogQuotation.GetCDSDetail: TClientDataSet; begin If not Assigned(FCDSDetail) then begin FCDSDetail := TDBUtils.CreateObjectDataSet(TModQuotationDetail, Self, False); FCDSDetail.AddField('SellNetPrice', ftFloat); FCDSDetail.CreateDataSet; end; Result := FCDSDetail; end; function TfrmDialogQuotation.GetCDSSuplierMerchan: TClientDataSet; begin if not Assigned(FCDSSuplierMerchan) then begin FCDSSuplierMerchan := TDBUtils.DSToCDS( DMClient.DSProviderClient.SuplierMerchan_GetDSLookup, Self); end; Result := FCDSSuplierMerchan; end; function TfrmDialogQuotation.GetModQuotation: TModQuotation; begin if not Assigned(FModQuotation) then FModQuotation := TModQuotation.Create; Result := FModQuotation; end; procedure TfrmDialogQuotation.InitActivation(aAktivasi: Boolean = True); begin btnActivate.Enabled := aAktivasi; btnAddProd.Enabled := not aAktivasi; btnAddSat.Enabled := not aAktivasi; btnDelProd.Enabled := not aAktivasi; btnDelSat.Enabled := not aAktivasi; actSave.Enabled := not aAktivasi; end; procedure TfrmDialogQuotation.InitReadOnly; begin btnActivate.Enabled := False; btnAddProd.Enabled := False; btnAddSat.Enabled := False; btnDelProd.Enabled := False; btnDelSat.Enabled := False; actSave.Enabled := False; actDelete.Enabled := False; end; procedure TfrmDialogQuotation.initView; var lCDS: TClientDataSet; begin With DMClient.DSProviderClient do begin lCDS := TClientDataSet.Create(Self); lCDS.CloneCursor(CDSSuplierMerchan, True); cxLookupSupplierMerchan.LoadFromCDS(CDSSuplierMerchan, 'SUPLIER_MERCHAN_GRUP_ID' , 'SUP_NAME', Self); cxLookupSupplierMerchan.SetVisibleColumnsOnly(['SUP_CODE', 'SUP_NAME', 'MERCHANGRUP_NAME']); cxLookupMerchan.LoadFromDS(Merchandise_GetDSLookup, 'REF$MERCHANDISE_ID','MERCHAN_NAME' ,Self); TcxExtLookupComboBoxProperties(colHeaderSatuan.Properties).LoadFromDS( Satuan_GetDSLookup, 'ref$satuan_id', 'SAT_CODE', Self); TcxExtLookupComboBoxProperties(colDetailSatuan.Properties).LoadFromDS( Satuan_GetDSLookup, 'ref$satuan_id', 'SAT_CODE', Self); TcxExtLookupComboBoxProperties(colDetailTipeHarga.Properties).LoadFromDS( TipeHarga_GetDSLookup, 'ref$tipe_harga_id', 'tphrg_name', Self); end; cxLookupMerchan.SetDefaultValue(); cxLookupSupplierMerchan.SetMultiPurposeLookup; cxGrdDBHeader.PrepareFromCDS(CDSHeader); cxGrdDBDetail.PrepareFromCDS(CDSDetail); cxGrdDBHeader.OptionsView.Header := False; CDSDetail.IndexFieldNames := 'Barang'; CDSDetail.MasterSource := cxGrdDBHeader.DataController.DataSource; CDSDetail.MasterFields := 'Barang'; //debug only cxLookupMerchan.DS.Locate('MERCHAN_NAME','DRY FOOD', [loCaseInsensitive]); cxLookupMerchan.EditValue := cxLookupMerchan.DS.FieldByName('REF$MERCHANDISE_ID').AsString; cxLookupSupplierMerchan.EditValue := '5C729EEC-6E9C-4E95-8EA0-BE8D8586B71F'; end; procedure TfrmDialogQuotation.LoadData(aID: String); var i: Integer; lBarang: TModBarang; lDetail: TModQuotationDetail; begin if aID <> '' then FModQuotation := DMClient.CrudClient.Retrieve(TModQuotation.ClassName, aID) as TModQuotation else begin ModQuotation.RefNo := DMClient.CrudClient.GenerateNo(TModQuotation.ClassName); ModQuotation.EffectiveDate := Now(); ModQuotation.EndDate := Now(); ModQuotation.Remark := ''; ModQuotation.Details.Clear; end; edQuotNo.Text := ModQuotation.RefNo; dtEffective.Date := ModQuotation.EffectiveDate; dtEnd.Date := ModQuotation.EndDate; mmRemark.Lines.Text := ModQuotation.Remark; ckIsMailer.EditValue := ModQuotation.IsMailer; if Assigned(ModQuotation.Merchandise) then cxLookupMerchan.EditValue := ModQuotation.Merchandise.ID; if Assigned(ModQuotation.SupplierMerchanGroup) then cxLookupSupplierMerchan.EditValue := ModQuotation.SupplierMerchanGroup.ID; lBarang := TModBarang.Create; for i := 0 to ModQuotation.Details.Count-1 do begin lDetail := ModQuotation.Details[i]; if lBarang.ID <> lDetail.Barang.ID then FreeAndNil(lBarang); if lBarang = nil then lBarang := DMClient.CrudClient.Retrieve(TModBarang.ClassName, lDetail.Barang.ID) as TModBarang; if lDetail.IsSellingPrice = 1 then begin CDSDetail.Append; lDetail.UpdateToDataset(CDSDetail); CDSDetail.FieldByName('SellNetPrice').AsFloat := lDetail.SellPrice - lDetail.SellDiscRp; CDSDetail.Post; end else begin CDSHeader.Append; lDetail.UpdateToDataset(CDSHeader); CDSHeader.FieldByName('BrgCode').AsString := lBarang.BRG_CODE; CDSHeader.FieldByName('BrgName').AsString := lBarang.BRG_NAME; CDSHeader.FieldByName('BUYPRICE_INC_DISC').AsFloat := lDetail.BUYPRICE_INC_DISC; if lDetail.IsBKP = 1 then CDSHeader.FieldByName('BUYPRICE_INC_DISC').AsFloat := lDetail.BUYPRICE_INC_DISC * 1.1; CDSHeader.Post; end; end; InitActivation(False); if ModQuotation.IsProcessed=1 then InitReadOnly; end; procedure TfrmDialogQuotation.LoadHargaJual; var dProportion: Double; i: Integer; lBarang: TModBarang; lBarangID: String; lRecNO: Integer; begin lRecNO := CDSHeader.RecNo; CDSHeader.DisableControls; CDSDetail.DisableControls; Try lBarangID := CDSHeader.FieldByName('Barang').AsString; lBarang := DMClient.CrudClient.Retrieve(TModBarang.ClassName, lBarangID) as TModBarang; Try //existing for i:=0 to lBarang.HargaJual.Count-1 do begin CDSDetail.Append; CDSDetail.FieldByName('Barang').AsString := lBarang.ID; CDSDetail.FieldByName('BarangSupplier').AsString := CDSHeader.FieldByName('BarangSupplier').AsString; CDSDetail.FieldByName('TipeHarga').AsString := lBarang.HargaJual[i].TipeHarga.ID; CDSDetail.FieldByName('Satuan').AsString := lBarang.HargaJual[i].Satuan.ID; CDSDetail.FieldByName('SellPrice').AsFloat := lBarang.HargaJual[i].BHJ_SELL_PRICE; CDSDetail.FieldByName('SellDiscPercent').AsFloat := lBarang.HargaJual[i].BHJ_DISC_PERSEN; CDSDetail.FieldByName('SellDiscRp').AsFloat := lBarang.HargaJual[i].BHJ_DISC_NOMINAL; CDSDetail.FieldByName('Konversi').AsFloat := lBarang.HargaJual[i].BHJ_CONV_VALUE; //data master produk masih salah CDSDetail.FieldByName('Margin').AsFloat := lBarang.HargaJual[i].BHJ_MARK_UP; if lBarang.HargaJual[i].BHJ_MARK_UP = 0 then CDSDetail.FieldByName('Margin').AsFloat := CDSHeader.FieldByName('Margin').AsFloat; dProportion := lBarang.HargaJual[i].BHJ_CONV_VALUE / CDSHeader.FieldByName('Konversi').AsFloat ; CDSDetail.FieldByName('BuyPrice').AsFloat := dProportion * CDSHeader.FieldByName('BuyPrice').AsFloat; CDSDetail.FieldByName('BuyDisc1').AsFloat := CDSHeader.FieldByName('BuyDisc1').AsFloat; CDSDetail.FieldByName('BuyDisc2').AsFloat := CDSHeader.FieldByName('BuyDisc2').AsFloat; CDSDetail.FieldByName('BuyDisc3').AsFloat := dProportion * CDSHeader.FieldByName('BuyDisc3').AsFloat; CDSDetail.FieldByName('BUYPRICE_INC_PPN').AsFloat := dProportion * CDSHeader.FieldByName('BUYPRICE_INC_PPN').AsFloat; CDSDetail.FieldByName('BUYPRICE_INC_DISC').AsFloat := dProportion * CDSHeader.FieldByName('BUYPRICE_INC_DISC').AsFloat; CDSDetail.FieldByName('IsBKP').AsInteger := CDSHeader.FieldByName('IsBKP').AsInteger; CDSDetail.FieldByName('PPN').AsFloat := CDSHeader.FieldByName('PPN').AsFloat; CDSDetail.Post; CalculateNetSellPrice(nil); end; Finally FreeAndNil(lBarang); End; Finally CDSHeader.EnableControls; CDSDetail.EnableControls; CDSHeader.RecNo := lRecNO; End; end; procedure TfrmDialogQuotation.SetHargaBeliHargaIncludePPN1Click(Sender: TObject); begin inherited; if CDSHeader.FieldByName('IsBKP').AsInteger <> 1 then exit; if CDSHeader.State in [dsEdit] then CDSHeader.Post; CDSHeader.Edit; CDSHeader.FieldByName('BuyPrice').AsFloat := CDSHeader.FieldByName('BuyPrice').AsFloat / 1.1; CDSHeader.Post; CalculateNetBuyPrice; end; procedure TfrmDialogQuotation.SetHargaJualiHargaIncludePPN1Click(Sender: TObject); var dSellPrice: Double; begin inherited; if CDSDetail.FieldByName('IsBKP').AsInteger <> 1 then exit; if CDSDetail.State in [dsEdit] then CDSDetail.Post; dSellPrice := CDSDetail.FieldByName('SellPrice').AsFloat / 1.1; CDSDetail.Edit; CDSDetail.FieldByName('SellPrice').AsFloat := dSellPrice; CDSDetail.Post; CalculateNetSellPrice(colDetailSellPrice); end; procedure TfrmDialogQuotation.UpdateData; var lDetail: TModQuotationDetail; begin ModQuotation.RefNo := edQuotNo.Text; ModQuotation.TransDate := Now(); ModQuotation.EffectiveDate := dtEffective.Date; ModQuotation.EndDate := dtEnd.Date; ModQuotation.Remark := mmRemark.Text; ModQuotation.IsMailer := ckIsMailer.EditValue; ModQuotation.IsProcessed := 0; ModQuotation.Merchandise := TModMerchandise.CreateID(cxLookupMerchan.EditValue); ModQuotation.SupplierMerchanGroup := TModSuplierMerchanGroup.CreateID(cxLookupSupplierMerchan.EditValue); ModQuotation.Details.Clear; //header CDSHeader.First; while not CDSHeader.Eof do begin lDetail := TModQuotationDetail.Create; lDetail.SetFromDataset(CDSHeader); lDetail.IsSellingPrice := 0; ModQuotation.Details.Add(lDetail); CDSDetail.First; while not CDSDetail.Eof do begin lDetail := TModQuotationDetail.Create; lDetail.SetFromDataset(CDSDetail); lDetail.IsSellingPrice := 1; ModQuotation.Details.Add(lDetail); CDSDetail.Next; end; CDSHeader.Next; end; end; procedure TfrmDialogQuotation.UpdateSellingPrice(IsUpdateSellPrice: Boolean = True); var dBuyPrice: Double; dMargin: Double; dProportion: Double; dSellPrice: Double; lRecNo: Integer; begin if CDSHeader.State in [dsEdit] then CDSHeader.Post; lRecNo := CDSDetail.RecNo; CDSDetail.DisableControls; try CDSDetail.First; while not CDSDetail.Eof do begin CDSDetail.Edit; //new dProportion := 1; if CDSHeader.FieldByName('Konversi').AsFloat <> 0 then dProportion := CDSDetail.FieldByName('Konversi').AsFloat / CDSHeader.FieldByName('Konversi').AsFloat ; CDSDetail.FieldByName('BuyPrice').AsFloat := dProportion * CDSHeader.FieldByName('BuyPrice').AsFloat; CDSDetail.FieldByName('BuyDisc1').AsFloat := CDSHeader.FieldByName('BuyDisc1').AsFloat; CDSDetail.FieldByName('BuyDisc2').AsFloat := CDSHeader.FieldByName('BuyDisc2').AsFloat; CDSDetail.FieldByName('PPN').AsFloat := CDSHeader.FieldByName('PPN').AsFloat; CDSDetail.FieldByName('BuyDisc3').AsFloat := dProportion * CDSHeader.FieldByName('BuyDisc3').AsFloat; CDSDetail.FieldByName('BUYPRICE_INC_PPN').AsFloat := dProportion * CDSHeader.FieldByName('BUYPRICE_INC_PPN').AsFloat; CDSDetail.FieldByName('BUYPRICE_INC_DISC').AsFloat := dProportion * CDSHeader.FieldByName('BUYPRICE_INC_DISC').AsFloat; //fixed margin dMargin := CDSDetail.FieldByName('Margin').AsFloat; dSellPrice := CDSDetail.FieldByName('SellPrice').AsFloat; dBuyPrice := CDSDetail.FieldByName('BUYPRICE_INC_PPN').AsFloat; if IsUpdateSellPrice then dSellPrice := (100+dMargin)/100 * dBuyPrice else if dBuyPrice <> 0 then dMargin := (dSellPrice-dBuyPrice)/dBuyPrice * 100; CDSDetail.FieldByName('Margin').AsFloat := dMargin; CDSDetail.FieldByName('SellPrice').AsFloat := dSellPrice; CDSDetail.FieldByName('SellNetPrice').AsFloat := dSellPrice - CDSDetail.FieldByName('SellDiscRp').AsFloat; CDSDetail.Post; CDSDetail.Next; end; finally CDSDetail.RecNo := lRecNo; CDSDetail.EnableControls; end; end; function TfrmDialogQuotation.ValidateData: Boolean; begin Result := False; if VarIsNull(cxLookupMerchan.EditValue) then begin TAppUtils.Warning('Merchan belum diisi'); exit; end; if VarIsNull(cxLookupSupplierMerchan.EditValue) then begin TAppUtils.Warning('Supplier belum diisi'); exit; end; if CDSHeader.RecordCount = 0 then begin TAppUtils.Warning('Data Produk kosong'); exit; end; if not Result then Result := True; end; end.
unit StyleActionBar; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, StdCtrls, ToolWin, ActnMan, ActnCtrls, ActnList, XPStyleActnCtrls, LMDFontComboBox, LMDCustomComboBox, LMDComboBox, ThCssStyle, ThStyledCtrl; type TStyleActionBarForm = class(TForm) ActionManager1: TActionManager; StyleBoldAction: TAction; StyleItalicAction: TAction; StyleUnderlineAction: TAction; StyleBordersAction: TAction; StyleLeftBorder: TAction; StyleRightBorderAction: TAction; StyleTopBorderAction: TAction; StyleBottomBorderAction: TAction; ActionToolBar1: TActionToolBar; StyleCombo: TLMDComboBox; FontCombo: TLMDFontComboBox; FontSizeCombo: TLMDComboBox; ToolImages: TImageList; procedure FormCreate(Sender: TObject); procedure StyleItalicActionUpdate(Sender: TObject); procedure StyleBoldActionUpdate(Sender: TObject); procedure StyleBoldActionExecute(Sender: TObject); procedure StyleItalicActionExecute(Sender: TObject); procedure StyleUnderlineActionUpdate(Sender: TObject); procedure StyleUnderlineActionExecute(Sender: TObject); procedure StyleLeftBorderUpdate(Sender: TObject); procedure StyleRightBorderActionUpdate(Sender: TObject); procedure StyleTopBorderActionUpdate(Sender: TObject); procedure StyleBottomBorderActionUpdate(Sender: TObject); procedure StyleBordersActionUpdate(Sender: TObject); procedure StyleBordersActionExecute(Sender: TObject); procedure StyleLeftBorderExecute(Sender: TObject); procedure StyleRightBorderActionExecute(Sender: TObject); procedure StyleTopBorderActionExecute(Sender: TObject); procedure StyleBottomBorderActionExecute(Sender: TObject); procedure FontComboChange(Sender: TObject); procedure FontSizeComboChange(Sender: TObject); procedure StyleComboChange(Sender: TObject); private { Private declarations } FComponent: TComponent; FStyle: TThCssStyle; FStyleClass: string; function HaveStyle: Boolean; procedure SetComponent(const Value: TComponent); procedure BorderExecute(inBorder: TThCssBorder); procedure BorderUpdate(inSender: TObject; inBorder: TThCssBorder); procedure StyleChange; procedure UpdateControls; procedure UpdateFontControls; procedure UpdateStyleList; public { Public declarations } procedure UpdateStyle; property Component: TComponent read FComponent write SetComponent; end; var StyleActionBarForm: TStyleActionBarForm; implementation uses LrUtils, ThStyleSheet, InspectorView; {$R *.dfm} procedure TStyleActionBarForm.FormCreate(Sender: TObject); begin AutoSize := true; end; procedure TStyleActionBarForm.UpdateStyle; begin with InspectorForm.ObjectInspector do if (CurrentControl is TComponent) then Component := TComponent(CurrentControl) else Component := nil; UpdateFontControls; end; procedure TStyleActionBarForm.SetComponent(const Value: TComponent); begin if (FComponent <> Value) then begin FComponent := Value; UpdateControls; end; end; procedure TStyleActionBarForm.UpdateControls; var e: Boolean; s: IThStyled; begin //UpdateStyle; e := (Component <> nil) and IsAs(Component, IThStyled, s); if e then begin UpdateStyleList; FStyle := s.GetStyle; FStyleClass := s.GetStyleClass; end else begin FStyle := nil; FStyleClass := ''; end; //UpdateFontControls; end; procedure TStyleActionBarForm.UpdateFontControls; begin FontCombo.Enabled := HaveStyle; FontSizeCombo.Enabled := HaveStyle; StyleCombo.Enabled := HaveStyle; if HaveStyle then begin FontCombo.SelectedFont := FStyle.Font.FontFamily; if FStyle.Font.FontSizePx = 0 then FontSizeCombo.Text := '' else FontSizeCombo.Text := IntToStr(FStyle.Font.FontSizePx); StyleCombo.Text := FStyleClass; end else begin FontCombo.SelectedFont := ''; FontSizeCombo.Text := ''; StyleCombo.Text := ''; end; end; procedure TStyleActionBarForm.UpdateStyleList; var s: TThStyleSheet; i: Integer; begin if (Component <> nil) and (Component is TControl) then begin s := ThFindStyleSheet(TControl(Component)); if (s <> nil) then begin StyleCombo.Items.BeginUpdate; try StyleCombo.Items.Clear; for i := 0 to s.Styles.Count - 1 do StyleCombo.Items.Add(s.Styles.StyleItem[i].Name); finally StyleCombo.Items.EndUpdate; end; end; end; end; function TStyleActionBarForm.HaveStyle: Boolean; begin Result := FStyle <> nil; end; procedure TStyleActionBarForm.StyleChange; begin InspectorForm.ObjectInspector.Rescan; end; procedure TStyleActionBarForm.StyleBoldActionUpdate(Sender: TObject); begin UpdateStyle; TAction(Sender).Enabled := HaveStyle; TAction(Sender).Checked := HaveStyle and (FStyle.Font.FontWeight = fwBold); end; procedure TStyleActionBarForm.StyleItalicActionUpdate(Sender: TObject); begin UpdateStyle; TAction(Sender).Enabled := HaveStyle; TAction(Sender).Checked := HaveStyle and (FStyle.Font.FontStyle = fstItalic); end; procedure TStyleActionBarForm.StyleUnderlineActionUpdate(Sender: TObject); begin UpdateStyle; TAction(Sender).Enabled := HaveStyle; TAction(Sender).Checked := HaveStyle and (FStyle.Font.FontDecoration = fdUnderline); end; procedure TStyleActionBarForm.BorderUpdate(inSender: TObject; inBorder: TThCssBorder); begin UpdateStyle; TAction(inSender).Checked := (inBorder.BorderStyle <> bsNone) and (inBorder.BorderStyle <> bsDefault); end; procedure TStyleActionBarForm.StyleBordersActionUpdate(Sender: TObject); begin UpdateStyle; TAction(Sender).Enabled := HaveStyle; if HaveStyle then BorderUpdate(Sender, FStyle.Border); end; procedure TStyleActionBarForm.StyleLeftBorderUpdate(Sender: TObject); begin UpdateStyle; TAction(Sender).Enabled := HaveStyle; if HaveStyle then BorderUpdate(Sender, FStyle.Border.Edges.BorderLeft); end; procedure TStyleActionBarForm.StyleRightBorderActionUpdate( Sender: TObject); begin UpdateStyle; TAction(Sender).Enabled := HaveStyle; if HaveStyle then BorderUpdate(Sender, FStyle.Border.Edges.BorderRight); end; procedure TStyleActionBarForm.StyleTopBorderActionUpdate(Sender: TObject); begin UpdateStyle; TAction(Sender).Enabled := HaveStyle; if HaveStyle then BorderUpdate(Sender, FStyle.Border.Edges.BorderTop); end; procedure TStyleActionBarForm.StyleBottomBorderActionUpdate( Sender: TObject); begin UpdateStyle; TAction(Sender).Enabled := HaveStyle; if HaveStyle then BorderUpdate(Sender, FStyle.Border.Edges.BorderBottom); end; procedure TStyleActionBarForm.StyleBoldActionExecute(Sender: TObject); begin if TAction(Sender).Checked then FStyle.Font.FontWeight := fwDefault else FStyle.Font.FontWeight := fwBold; StyleChange; end; procedure TStyleActionBarForm.StyleItalicActionExecute(Sender: TObject); begin if TAction(Sender).Checked then FStyle.Font.FontStyle := fstDefault else FStyle.Font.FontStyle := fstItalic; StyleChange; end; procedure TStyleActionBarForm.StyleUnderlineActionExecute(Sender: TObject); begin if TAction(Sender).Checked then FStyle.Font.FontDecoration := fdDefault else FStyle.Font.FontDecoration := fdUnderline; StyleChange; end; procedure TStyleActionBarForm.BorderExecute(inBorder: TThCssBorder); begin if inBorder.BorderStyle = bsSolidBorder then inBorder.BorderStyle := bsDefault else inBorder.BorderStyle := bsSolidBorder; StyleChange; end; procedure TStyleActionBarForm.StyleBordersActionExecute(Sender: TObject); begin BorderExecute(FStyle.Border); StyleChange; end; procedure TStyleActionBarForm.StyleLeftBorderExecute(Sender: TObject); begin BorderExecute(FStyle.Border.Edges.BorderLeft); end; procedure TStyleActionBarForm.StyleRightBorderActionExecute( Sender: TObject); begin BorderExecute(FStyle.Border.Edges.BorderRight); end; procedure TStyleActionBarForm.StyleTopBorderActionExecute(Sender: TObject); begin BorderExecute(FStyle.Border.Edges.BorderTop); end; procedure TStyleActionBarForm.StyleBottomBorderActionExecute( Sender: TObject); begin BorderExecute(FStyle.Border.Edges.BorderBottom); end; procedure TStyleActionBarForm.FontComboChange(Sender: TObject); begin if HaveStyle then begin FStyle.Font.FontFamily := FontCombo.SelectedFont; StyleChange; end; end; procedure TStyleActionBarForm.FontSizeComboChange(Sender: TObject); begin if HaveStyle and (FontSizeCombo.Text <> '') then begin FStyle.Font.FontSizePx := StrToIntDef(FontSizeCombo.Text, FStyle.Font.FontSizePx); StyleChange; end; end; procedure TStyleActionBarForm.StyleComboChange(Sender: TObject); var s: IThStyled; begin if HaveStyle then begin if (Component <> nil) and IsAs(Component, IThStyled, s) then s.SetStyleClass(StyleCombo.Text); StyleChange; end; end; end.
unit stuff; interface Uses Classes; function GetIPFromHost(const HostName: string): string; function GetLongIp(s : String) : Cardinal; Function GetShortIp(const s: int64): string; Procedure SendSock(s:string); function Resolve(const host: PChar;Var Ip:Longint): Boolean; // function for resolving host to ip Function SpiltStr(S:String;Posx:integer):String; Function StrCount(S:String):Integer; function GetLocalIP: string; Function Vise(i:cardinal):cardinal; function GetProgramFilesDir: string; function GetSysDir: string; implementation Uses Config,Winsock,errors,sysutils,WinInet,Windows,Registry,Main{$ifdef debug},logger{$endif}; function GetSysDir: string; var dir: array [0..MAX_PATH] of Char; begin GetSystemDirectory(dir, MAX_PATH); Result := StrPas(dir); end; function GetProgramFilesDir: string; var reg: TRegistry; begin reg := TRegistry.Create; try reg.RootKey := HKEY_LOCAL_MACHINE; reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion', False); Result := reg.ReadString('ProgramFilesDir'); finally reg.Free; end; end; function GetLocalIP: string; var wsaData: TWSAData; addr: TSockAddrIn; Phe: PHostEnt; szHostName: array[0..128] of Char; begin Result := ''; if WSAStartup($101, WSAData) <> 0 then Exit; try if GetHostName(szHostName, 128) <> SOCKET_ERROR then begin Phe := GetHostByName(szHostName); if Assigned(Phe) then begin addr.sin_addr.S_addr := longint(plongint(Phe^.h_addr_list^)^); Result := inet_ntoa(addr.sin_addr); end; end; finally WSACleanup; end; end; function GetComputerNetName: string; var buffer: array[0..255] of char; size: dword; begin size := 256; if GetComputerName(buffer, size) then Result := '\\'+buffer else Result := '' end; Function IsInt(Str:String):Boolean; var i:int64; begin i:=StrToInt64Def(STR,-1); if i = -1 then result:=false else result:=true; end; function GetIPFromHost(const HostName: string): string; type TaPInAddr = array[0..10] of PInAddr; PaPInAddr = ^TaPInAddr; var phe: PHostEnt; pptr: PaPInAddr; i: Integer; GInitData: TWSAData; begin WSAStartup($101, GInitData); Result := ''; phe := GetHostByName(PChar(HostName)); if phe = nil then Exit; pPtr := PaPInAddr(phe^.h_addr_list); i := 0; while pPtr^[i] <> nil do begin Result := inet_ntoa(pptr^[i]^); Inc(i); end; WSACleanup; end; Function StrCount(S:String):Integer; Var i:integer; begin i:=0; while pos(' ',s) > 0 do begin inc(i); delete(s,pos(' ',s),1); end; strcount:=i+1; end; Function SpiltStr(S:String;Posx:integer):String; {* <HI Fuck You> *} Var i:integer; Q:integer; begin q:=StrCount(S); if (q <> 0) and (posx <= q) then begin i:=1; while i <> posx do begin s:=copy(s,pos(' ',s)+1,length(s)); inc(i); end; if pos(' ',s) > 0 then result:=copy(s,1,pos(' ',s)-1) else result:=s; end else result:=''; end; function Resolve; // function for resolving host to ip var InAddr: TInAddr; HostEnt: PHostEnt; begin Result:=True; InAddr.S_addr := inet_addr(host); // convert ip address format (ex: 127.0.0.1) to cardinal if InAddr.S_addr = INADDR_NONE then // if it is not a ip address then resolve it begin HostEnt := GetHostByName(host); if not Assigned(HostEnt) then // if couldn't resolve the host then exit begin //sendsock('[ERROR]: '+ER_005); Result:=False; end else Move((HostEnt^.h_addr_list^)^, InAddr.S_addr, HostEnt^.h_length); // move resolved host to InAddr.S_addr end; Ip := InAddr.S_addr; end; function GetLongIp(s : String) : Cardinal; var r, i, c : Cardinal; p : LongInt; t : String; begin GetLongIp := 0; r := 0; for i := 3 downto 0 do begin p := Pos('.', s); if p = 0 then p := Length(s) + 1; if p <= 1 then exit; t := Copy(s, 1, p - 1); Delete(s, 1, p); Val(t, p, c); if (c <> 0) or (p < 0) or (p > 255) then begin GetLongIp:=0; exit; end; r := r or cardinal(p) shl (i * 8); end; GetLongIp := r; end; Function Vise(i:cardinal):cardinal; begin result:=(i and $000000FF) * $FFFFFF + (i and $000000FF) + (i AND $0000FF00) SHR 8 * $FFFF + (i AND $0000FF00) SHR 8 + (i AND $00FF0000) SHR 16 * $FF + (i AND $00FF0000) SHR 16 + (i AND $FF000000) SHR 24; end; Function GetShortIp; Var a, b, c, d : Byte; Begin a := (S AND $FF000000) SHR 24; b := (S AND $00FF0000) SHR 16; c := (S AND $0000FF00) SHR 8; d := (S AND $000000FF); GetShortIp := inttostr(a) + '.' + inttostr(b) + '.' + inttostr(c) + '.' + inttostr(d); End; Procedure SendSock(s:string); var str01:string; begin str01:=('PRIVMSG '+ Data.bot_channal + ' :'+s+ #10#13); {$ifdef debug} logger.AddToMessageLog('[DEBUG] ' + S); {$endif} send(Sock1,str01[1],Length(str01),0); end; end.
unit uSpeedIndicator; interface uses System.SysUtils, System.Classes, System.Math, GLScene, GLOBjects, GLHUDOBjects, GLMaterial, GLWindowsFont, GLTexture, GLVectorGeometry, GLVectorTypes, GLCrossPlatform; const C_HUD_PATH = 'data\hud\'; C_INDICATOR_OFFSET_X = -10; C_INDICATOR_OFFSET_Y = -10; C_INDICATOR_FULLANLGE = 90; C_MATNAME_ACTIVE = 'cell_active'; C_MATNAME_INACTIVE = 'cell_inactive'; C_CELL_COUNT = 10; C_CELL_RADIUS = 120; C_CELL_INACTIVE_R = 1.0; C_CELL_INACTIVE_G = 0.0; C_CELL_INACTIVE_B = 0.0; C_CELL_INACTIVE_A = 0.5; C_CELL_ACTIVE_R = 0.0; C_CELL_ACTIVE_G = 1.0; C_CELL_ACTIVE_B = 0.0; C_CELL_ACTIVE_A = 1.0; type TdfSpeedIndicator = class (TGLDummyCube) private FActiveCount: Integer; FMaxSpeed, FSpeed: Single; FSpeedText: TGLHUDText; FCells: array of TGLHUDSprite; FCellCount: Integer; function GetCell(Index: Integer): TGLHUDSprite; function GetInactiveColor(): TVector; function GetActiveColor(): TVector; procedure SetCell(Index: Integer; const Value: TGLHUDSprite); procedure SetSpeed(const Value: Single); public constructor CreateAsChild(aParentOwner: TGLBaseSceneObject); reintroduce; property SpeedText: TGLHUDText read FSpeedText write FSpeedText; property Cells[Index: Integer]: TGLHUDSprite read GetCell write SetCell; property CellCount: Integer read FCellCount default C_CELL_COUNT; property MaxSpeed: Single read FMaxSpeed write FMaxSpeed; property Speed: Single read FSpeed write SetSpeed; procedure AddMaterialToCells(aTextureName: String); procedure AddFontToText(aFont: TGLWindowsBitmapFont); end; //======================================================================= implementation //======================================================================= uses uGLSceneObjects; { TdfSpeedIndicator } procedure TdfSpeedIndicator.AddFontToText(aFont: TGLWindowsBitmapFont); begin FSpeedText.BitmapFont := aFont; aFont.EnsureChars('0', '9'); end; procedure TdfSpeedIndicator.AddMaterialToCells(aTextureName: String); var w, h: Single; i: Integer; begin if not Assigned(dfGLSceneObjects.MatLibrary.LibMaterialByName(C_MATNAME_ACTIVE)) then with dfGLSceneObjects.MatLibrary.Materials.Add do begin Name := C_MATNAME_ACTIVE; with Material do begin Texture.Image.LoadFromFile(C_HUD_PATH + aTextureName); w := Texture.Image.Width; h := Texture.Image.Height; Texture.Enabled := True; Texture.TextureMode := tmModulate; Texture.TextureWrap := twNone; BlendingMode := bmTransparency; MaterialOptions := [moIgnoreFog, moNoLighting]; FrontProperties.Diffuse.Color := GetActiveColor(); end; end else with dfGLSceneObjects.MatLibrary.LibMaterialByName(aTextureName).Material.Texture.Image do begin w := Width; h := Height; end; if not Assigned(dfGLSceneObjects.MatLibrary.LibMaterialByName(C_MATNAME_INACTIVE)) then with dfGLSceneObjects.MatLibrary.Materials.Add do begin Name := C_MATNAME_INACTIVE; Material.Assign(dfGLSceneObjects.MatLibrary.LibMaterialByName(C_MATNAME_ACTIVE).Material); Material.FrontProperties.Diffuse.Color := GetInactiveColor; end; for i := 0 to FCellCount - 1 do begin FCells[i].Material.MaterialLibrary := dfGLSceneObjects.MatLibrary; FCells[i].Material.LibMaterialName := C_MATNAME_INACTIVE; FCells[i].Width := w; FCells[i].Height := h; end; end; constructor TdfSpeedIndicator.CreateAsChild(aParentOwner: TGLBaseSceneObject); var i: Integer; stepAngle: Single; origin: TVector2f; cellPos: TAffineVector; begin inherited; FCellCount := C_CELL_COUNT; FActiveCount := 0; SetLength(FCells, FCellCount); stepAngle := C_INDICATOR_FULLANLGE / (FCellCount - 1); origin.X := dfGLSceneObjects.Viewer.Width + C_INDICATOR_OFFSET_X; origin.Y := dfGLSceneObjects.Viewer.Height + C_INDICATOR_OFFSET_Y; for i := 0 to FCellCount - 1 do begin FCells[i] := TGLHUDSprite.CreateAsChild(Self); cellPos.X := - C_CELL_RADIUS * cos((pi / 180) * stepAngle * i); cellPos.Y := - C_CELL_RADIUS * sin((pi / 180) * stepAngle * i); cellPos.Z := 0.5; FCells[i].Rotation := (180 / pi) * ArcCos(VectorAngleCosine(YVector, cellPos)); if cellPos.X < origin.X then FCells[i].Rotation := - FCells[i].Rotation; cellPos.X := cellPos.X + origin.X; cellPos.Y := cellPos.Y + origin.Y; FCells[i].Position.SetPoint(cellPos); end; FSpeedText := TGLHUDText.CreateAsChild(Self); FSpeedText.Alignment := taRightJustify; FSpeedText.Layout := tlBottom; FSpeedText.Position.SetPoint(origin.X, origin.Y, 0.5); FSpeedText.ModulateColor.SetColor(0, 1, 0, 0.8); end; function TdfSpeedIndicator.GetActiveColor: TVector; begin Result.X := C_CELL_ACTIVE_R; Result.Y := C_CELL_ACTIVE_G; Result.Z := C_CELL_ACTIVE_B; Result.W := C_CELL_ACTIVE_A; end; function TdfSpeedIndicator.GetCell(Index: Integer): TGLHUDSprite; begin Result := FCells[Index]; end; function TdfSpeedIndicator.GetInactiveColor: TVector; begin Result.X := C_CELL_INACTIVE_R; Result.Y := C_CELL_INACTIVE_G; Result.Z := C_CELL_INACTIVE_B; Result.W := C_CELL_INACTIVE_A; end; procedure TdfSpeedIndicator.SetCell(Index: Integer; const Value: TGLHUDSprite); begin FCells[Index] := Value; end; procedure TdfSpeedIndicator.SetSpeed(const Value: Single); var i, NewActiveCount, roundSpeed: Integer; begin FSpeed := Value; roundSpeed := Round(FSpeed); FSpeedText.Text := IntToStr(roundSpeed); if roundSpeed = 0 then FSpeedText.ModulateColor.SetColor(1, 0, 0) else FSpeedText.ModulateColor.SetColor(0, 1, 0); NewActiveCount := Round(FSpeed / FMaxSpeed * FCellCount); if NewActiveCount <> FActiveCount then begin FActiveCount := NewActiveCount; for i := 0 to FActiveCount - 1 do FCells[i].Material.LibMaterialName := C_MATNAME_ACTIVE; for i := FActiveCount to FCellCount - 1 do FCells[i].Material.LibMaterialName := C_MATNAME_INACTIVE; end; end; end.
unit Mouse; {$INCLUDE Global_Conditionals.inc} interface uses Windows, SysUtils, Forms,Controls; Const MouseBrush = 1201; MouseLine = 1203; MouseDropper = 1204; MouseFill = 1205; MouseDraw = 1206; MouseMagnify = 1207; MouseSpray = 8029; MouseMoveC = 1033; // Named MouseMoveC cos of other things named MouseMove Var Mouse_Current : integer = crDefault; function LoadMouseCursors : boolean; function LoadMouseCursor(Number:integer) : integer; implementation function LoadMouseCursors : boolean; var temp : integer; begin result := true; temp := 0; temp := temp + LoadMouseCursor(MouseBrush); temp := temp + LoadMouseCursor(MouseLine); temp := temp + LoadMouseCursor(MouseDropper); temp := temp + LoadMouseCursor(MouseFill); temp := temp + LoadMouseCursor(MouseDraw); temp := temp + LoadMouseCursor(MouseMagnify); temp := temp + LoadMouseCursor(MouseSpray); temp := temp + LoadMouseCursor(MouseMoveC); if temp < 0 then Result := false; end; function LoadMouseCursor(Number:integer) : integer; var filename : pchar; begin Result := 0; filename := pchar(ExtractFileDir(ParamStr(0)) + '\cursors\'+inttostr(Number)+'.cur'); if Not fileexists(filename) then begin Result := -1; MessageBox(0,pchar('Error Cursor Missing < ' + extractfilename(filename) + ' >'),'Cursor Error',0); end else Screen.Cursors[Number] := LoadCursorFromFile(filename); end; end.
(** This module contains a class / form to extract all the JEDI VCS commits for a series of projects that match a pattern and output them chronologically and commit these to a new Git Repositiory. @Author David Hoyle @Version 1.0 @Date 22 Feb 2018 Exclude checkin from atestd10 **) Unit JVTGMainForm; Interface Uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, 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.MSSQL, FireDAC.Phys.MSSQLDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, Datasnap.Provider, Vcl.Grids, Vcl.DBGrids, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, FireDAC.Phys.MySQLDef, FireDAC.Phys.MySQL; Type (** A form to hold data sets from the JED VCS database containing the revisions and blobs. **) TfrmJEDIVCSToGit = Class(TForm) FDConnection: TFDConnection; DBGrid: TDBGrid; RevisionsDataSource: TDataSource; RevisionsFDQuery: TFDQuery; btnGetRevisions: TButton; Splitter: TSplitter; pnlTop: TPanel; lblNewGitRepoPath: TLabel; edtNewGitRepoPath: TEdit; StatusBar: TStatusBar; pnlMain: TPanel; BlobsGrid: TDBGrid; BlobsFDQuery: TFDQuery; BlobsDataSource: TDataSource; lblProjectNamePattern: TLabel; edtProjectNamePattern: TEdit; pnlMainqq: TPanel; DBGridSplitter: TSplitter; pnlGitRepos: TGridPanel; lblOldGitRepoPath: TLabel; edtOldGitRepoPath: TEdit; lbxGitOutput: TListBox; chkStatus: TCheckBox; FDPhysMySQLDriverLink1: TFDPhysMySQLDriverLink; Label1: TLabel; edtMinRevID: TEdit; Procedure btnGetRevisionsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure edtProjectNamePatternExit(Sender: TObject); procedure StatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); procedure lbxGitOutputDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure DBGridDrawDataCell(Sender: TObject; const Rect: TRect; Field: TField; State: TGridDrawState); procedure RevisionsDataSourceDataChange(Sender: TObject; Field: TField); Strict Private Type (** A record to describe the information required by DGHCreateProcess. @nohints **) TProcessInfo = Record boolEnabled : Boolean; strEXE : String; strParams : String; strDir : String; strTitle : String; End; (** An enumerate to define the types of the messages. @nohints **) TMsgType = (mtInformation, mtTitle); (** A method signature for the DGHCreateProcess message event handler. @nohints **) TProcessMsgHandler = Procedure(Const strMsg : String; var boolAbort : Boolean; Const MsgType : TMsgType = mtInformation) Of Object; (** A method signature for the DGHCreateProcess idle event handler. @nohints **) TIdleHandler = Procedure Of Object; Strict Private FFileNames : TStringList; FLastMessage : String; FItemCount : Integer; FItem : Integer; FGitPI : TProcessInfo; FNewGitRepoPath : String; FStartTime : UInt64; FPercentage : Double; FRelativePaths : TStringList; FOldGitRepoPath : String; Strict Protected Procedure LoadSettings; Procedure SaveSettings; Procedure CommitToGit(Const _Comment, _Author: String; Const _CommitDateTime: TDateTime); Procedure ProcessMsgevent(Const strMsg: String; Var boolAbort: Boolean; Const MsgType : TMsgType = mtInformation); Procedure IdleEvent; Procedure ExecuteGit(Const strCmdParams : String); Procedure CheckGitRepoPath; Procedure CheckThereIsAnExistingGitRepo; Procedure UpdateStatus; Function CalcTime(Const iTime : UInt64): String; Function DGHCreateProcess(Var Process : TProcessInfo; Const ProcessMsgHandler : TProcessMsgHandler; Const IdleHandler : TIdleHandler) : Integer; Function GetActualPathAndFileCase(Const strRelPathFile: String) : String; Public End; Var (** A form variable managed by Delphi for the application main form. **) frmJEDIVCSToGit: TfrmJEDIVCSToGit; Implementation {$R *.dfm} Uses {$IFDEF DEBUG} // CodeSiteLogging, {$ENDIF} System.IniFiles, System.Zip, System.UITypes, JVTGRelativePathForm, JVTGTypes, JVTGGitErrorForm, JVTGFunctions, System.StrUtils; ResourceString (** A resource string to say that the directory was not found. **) strDirectoryNotFound = 'The directory "%s" does not exist.'; (** A resource string to say the user aborted the process. **) strUserAbort = 'User Abort!'; (** A resource string to say that the EXE file was not found. **) strEXENotFound = 'The executable file "%s" does not exist.'; Const strProjectNamePatternMacro = 'ProjectNamePattern'; strMinRevID = 'MinRevID'; Const (** An ini section name for the majority of the application settings. **) strSetupINISection = 'Setup'; (** Ini file extension. **) strIniExt = '.ini'; (** An ini key for the top of the main window. **) strTopKey = 'Top'; (** An ini key for the left of the main window. **) strLeftKey = 'Left'; (** An ini key for the Height of the main window. **) strHeightKey = 'Height'; (** An ini key for the Width of the main window. **) strWidthKey = 'Width'; (** An ini section name for the revision column widths. **) strRevsColWidthsIniSection = 'RevisionsColumnWidths'; (** An ini section name for the blob column widths. **) strBlobColumnWidthsIniSection = 'BlobColumnWidths'; (** An ini key for the ProjectNamePattern for matching revisions. **) strProjectNamePatternKey = 'ProjectNamePattern'; (** An ini key for the new repository path. **) strNewRepoPathKey = 'NewRepoPath'; (** An ini key for the old repository path. **) strOldRepoPathKey = 'OldRepoPath'; (** An ini key for the output height **) strOutputHeightKey = 'OutputHeight'; (** An ini key for the height of the Blob Grid. **) strBlobGridHeightKey = 'BlobGridHeight'; (** A constant double for the percentable multiplier. **) dblPercentageMultiplier = 100.0; (** An ini key for whether the GIT STATUS should be shown. **) strShowStatusKey = 'ShowStatus'; Function DGHFindOnPath(var strEXEName : String; Const strDirs : String) : Boolean; Forward; (** 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 and deletes empty paths and ensures the rest have a trailing backslash. @precon slPaths must be a valid instance. @postcon Empty paths are deleted and all paths are terminated with a backslash. @param slPaths as a TStringList as a constant **) Procedure CheckPaths(Const slPaths : TStringList); Var iPath: Integer; iLength: Integer; Begin 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 function searches the paths for the executeable and returns true if found and strEXEName is updated. @precon slPaths must be a valid instance. @postcon If found, returns true and strEXEName is updated. @param slPaths as a TStringList as a constant @return a Boolean **) Function SearchPaths(Const slPaths : TStringList) : Boolean; Var iPath: Integer; i : Integer; recSearch: TSearchRec; strPath, strExPath : String; iSize: Integer; Begin Result := False; 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)); i := FindFirst(strExPath + strEXEName, faAnyFile, recSearch); Try If i = 0 Then Begin strEXEName := strExPath + strEXEName; Result := True; Break; End; Finally FindClose(recSearch); End; End; End; Const strPathEnVar = 'path'; Var slPaths : TStringList; Begin slPaths := TStringList.Create; Try slPaths.Text := GetEnvironmentVariable(strPathEnVar); If strDirs <> '' Then slPaths.Text := strDirs + ';' + slPaths.Text; slPaths.Text := StringReplace(slPaths.Text, ';', #13#10, [rfReplaceAll]); CheckPaths(slPaths); Result := SearchPaths(slPaths); Finally slPaths.Free; End; End; (** This is an on click event handler for the Get Revisions button. @precon None. @postcon This method starts the process of extracting files from JEDI VCS to put into GIT. @param Sender as a TObject **) Procedure TfrmJEDIVCSToGit.btnGetRevisionsClick(Sender: TObject); Const strGitStatus = 'status'; (** This method processes the blobs associated with a revision and adds them to the git repo. @precon strZipFileName must be a valid ZIP file. @postcon The revisiob blobs are added to the Git Repo. @param strZipFileName as a String as a constant @return an Integer **) Function ProcessBlobs(Const strZipFileName : String) : Integer; (** This method checks the file to be extracted and whether it needs to rename an existing file. @precon None. @postcon Renames the file if its name has changed and updates the output filename. @param strSubDir as a String as a constant @param strFileToExtract as a String as a constant **) // Procedure CheckFileNamesForRename(Const strSubDir, strFileToExtract : String); // // ResourceString // strFileNeedsRenaming = 'The file "%s" needs renaming to "%s"!'; // // Const // strModuleName = 'ModuleName'; // strExtension = 'Extension'; // strMoveParams = 'mv -v "%s" "%s%s"'; // // Var // strOldFileName: String; // strRepoFileName: String; // strActualPathAndFile: String; // // Begin // strRepoFileName := // RevisionsDataSource.DataSet.FieldByName(strModuleName).AsString + '.' + // BlobsDataSource.DataSet.FieldByName(strExtension).AsString; // strOldFileName := FFileNames.Values[strRepoFileName]; // If strOldFileName <> '' Then // If CompareText(strOldFileName, strFileToExtract) <> 0 Then // Begin //// CodeSite.Send(Format(strFileNeedsRenaming, [strOldFileName, strFileToExtract])); // strActualPathAndFile := strSubDir + strOldFileName; // strActualPathAndFile := GetActualPathAndFileCase(strActualPathAndFile); // ExecuteGit(Format(strMoveParams, [strActualPathAndFile, // ExtractFilePath(strActualPathAndFile), strFileToExtract])); // If chkStatus.Checked Then // ExecuteGit(strGitStatus); // End; // FFileNames.Values[strRepoFilename] := strFileToExtract; // End; ResourceString strExtracting = 'Extracting: %s'; Const strFileData = 'FileData'; strAddParams = 'add -v "%s"'; strPath = 'path'; strModuleName = 'ModuleName'; Var Z: TZipFile; iFile: Integer; strSubDir: String; boolAbort: Boolean; RepoData : TJVTGRepoData; strActualFileCase: String; Begin Result := 0; BlobsDataSource.DataSet.First; While Not BlobsDataSource.DataSet.Eof Do Begin (BlobsDataSource.DataSet.FieldByName(strFileData) As TBlobField).SaveToFile(strZipFileName); Z := TZipFile.Create; Try Z.Open(strZipFileName, zmRead); For iFile := 0 To Z.FileCount - 1 Do Begin RepoData.Create(FOldGitRepoPath, FNewGitRepoPath, RevisionsDataSource.Dataset.FieldByName(strPath).AsString, RevisionsDataSource.Dataset.FieldByName(strModuleName).AsString); If TfrmExtractRelPath.Execute(FRelativePaths, RepoData, strSubDir) Then Begin //CheckFileNamesForRename(strSubDir, Z.FileName[iFile]); Z.Extract(Z.FileName[iFile], FNewGitRepoPath + strSubDir); ProcessMsgevent(Format(strExtracting, [FNewGitRepoPath + strSubDir + Z.FileName[iFile]]), boolAbort); strActualFileCase := strSubDir + Z.FileName[iFile]; strActualFileCase := GetActualPathAndFileCase(strActualFileCase); ExecuteGit(Format(strAddParams, [strActualFileCase])); Inc(Result); If chkStatus.Checked Then ExecuteGit(strGitStatus); End; End; Z.Close; Finally Z.Free; End; BlobsDataSource.DataSet.Next; End; End; (** This method iterates through the revision records processing the blobs assoviated with each revision extracting the files, adding them and committing them. @precon None. @postcon The revision records are processed. **) Procedure ProcessRevisions; Const strBlobZip = 'Blob.zip'; strComment_i = 'comment_i'; strTSTAMP = 'TSTAMP'; strAuthor = 'Author'; Var strZipFileName: String; Begin strZipFileName := FNewGitRepoPath + strBlobZip; While Not RevisionsDataSource.DataSet.Eof Do Begin ProcessBlobs(strZipFileName); CommitToGit(RevisionsDataSource.DataSet.FieldByName(strComment_i).AsString, RevisionsDataSource.DataSet.FieldByName(strAuthor).AsString, RevisionsDataSource.DataSet.FieldByName(strTSTAMP).AsDateTime); If chkStatus.Checked Then ExecuteGit(strGitStatus); Inc(FItem); UpdateStatus; RevisionsDataSource.DataSet.Next; End; End; Begin CheckGitRepoPath; CheckThereIsAnExistingGitRepo; DBGrid.ReadOnly := True; BlobsGrid.ReadOnly := True; Try FStartTime := GetTickCount64; RevisionsDataSource.DataSet.Last; FItemCount := RevisionsDataSource.DataSet.RecordCount; RevisionsDataSource.DataSet.First; ProcessRevisions; Finally DBGrid.ReadOnly := False; BlobsGrid.ReadOnly := False;; End; End; (** This method calculates the time (in milliseconds) as minutes and seconds. @precon None. @postcon Returns the number of milliseconds as minutes and seconds as a string. @param iTime as an UInt64 as a constant @return a String **) Function TfrmJEDIVCSToGit.CalcTime(Const iTime : UInt64): String; ResourceString strMinsSecs = '%d mins %d secs'; Const dblMSInSec = 1000.0; iSecsInMin = 60; Var iSeconds: Int64; iMinutes: Int64; Begin iSeconds := Trunc(Int(iTime) / dblMSInSec); iMinutes := iSeconds Div iSecsInMin; iSeconds := iSeconds Mod iSecsInMin; Result := Format(strMinsSecs, [iMinutes, iSeconds]); End; (** This method checks the Git Repository Path to ensure its a valid directory. @precon None. @postcon Raises an exception if the path does not exist or is empty. **) Procedure TfrmJEDIVCSToGit.CheckGitRepoPath; ResourceString strGitRepositoryPathDoesNotExist = 'The Git Repository path "%s" does not exist!'; Begin If (Length(edtNewGitRepoPath.Text) = 0) Or (Not DirectoryExists(edtNewGitRepoPath.Text)) Then Raise Exception.CreateFmt(strGitRepositoryPathDoesNotExist, [edtNewGitRepoPath.Text]); FNewGitRepoPath := edtNewGitRepoPath.Text; If FNewGitRepoPath[Length(FNewGitRepoPath)] <> '\' Then FNewGitRepoPath := FNewGitRepoPath + '\'; FOldGitRepoPath := edtOldGitRepoPath.Text; If FOldGitRepoPath[Length(FOldGitRepoPath)] <> '\' Then FOldGitRepoPath := FOldGitRepoPath + '\'; End; (** This method checks that there is no existing GIT repository in the repository path. @precon None. @postcon Raises an exception if there is already a repository. **) Procedure TfrmJEDIVCSToGit.CheckThereIsAnExistingGitRepo; ResourceString strGitRepositoryDoesNotExists = 'A GIT repository does NOT exists in "%s"!'; Const strGitDir = '.git'; Begin If Not DirectoryExists(FNewGitRepoPath + strGitDir) Then Raise Exception.CreateFmt(strGitRepositoryDoesNotExists, [FNewGitRepoPath]); End; (** This method commits the current staged files to git using the given comment and time and date stamp. @precon None. @postcon The currently staged files are committed. @param strComment as a String as a constant @param dtCommitDateTime as a TDateTime as a constant **) Procedure TfrmJEDIVCSToGit.CommitToGit(Const _Comment, _Author: String; Const _CommitDateTime: TDateTime); Const strCommitDate = 'commit -v --date "%s" -m "%s"'; strDateFmt = 'YYYY-MM-DD hh:nn:ss'; Var strCleanComment : String; Begin if trim(_Comment) = '' then begin strCleanComment := IfThen(_Author <> '', 'commited by ' + _Author, 'no commit message'); end else begin strCleanComment := StringReplace(trim(_Comment), '"', '''', [rfReplaceAll]); end; // strCleanComment := StringReplace(strCleanComment, #13, '', [rfReplaceAll]); // strCleanComment := StringReplace(strCleanComment, #10, '\n', [rfReplaceAll]); ExecuteGit(Format(strCommitDate, [FormatDateTime(strDateFmt, _CommitDateTime), strCleanComment]) + IfThen(_Author <> '', ' --author="' + _Author + '"')); End; (** This is an on Draw Data Cell event handler for the DBGrids. @precon None. @postcon Draws the grid data with clWindow background. @param Sender as a TObject @param Rect as a TRect as a constant @param Field as a TField @param State as a TGridDrawState **) Procedure TfrmJEDIVCSToGit.DBGridDrawDataCell(Sender: TObject; Const Rect: TRect; Field: TField; State: TGridDrawState); ResourceString strBlob = '(Blob)'; Const iPaddding = 5; Var C: TCanvas; strText: String; R: TRect; Begin C := (Sender As TDBGrid).Canvas; If gdSelected In State Then Begin C.Brush.Color := clHighlight; C.Font.Color := clHighlightText; End Else Begin C.Brush.Color := clWindow; C.Font.Color := clWindowText; End; C.FillRect(Rect); Case Field.DataType Of ftBlob: strText := strBlob; Else strText := Field.AsString; End; R := Rect; InflateRect(R, -iPaddding, 0); Case Field.Alignment Of taLeftJustify: C.TextRect(R, strText, [tfLeft, tfVerticalCenter]); taRightJustify: C.TextRect(R, strText, [tfRight, tfVerticalCenter]); taCenter: C.TextRect(R, strText, [tfCenter, tfVerticalCenter]); End; 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 TProcessInfo as a reference @param ProcessMsgHandler as a TProcessMsgHandler as a constant @param IdleHandler as a TIdleHandler as a constant @return an Integer **) Function TfrmJEDIVCSToGit.DGHCreateProcess(Var Process : TProcessInfo; Const ProcessMsgHandler : TProcessMsgHandler; Const IdleHandler : TIdleHandler) : Integer; Type EDGHCreateProcessException = Exception; Const iPipeSize = 4096; Var boolAbort: Boolean; (** This method checks that the process directory and executable exists. @precon None. @postcon Raises exceptions if either the process directory or EXE are not valid. **) Procedure CheckProcess; Begin If Not DirectoryExists(Process.strDir) Then Raise EDGHCreateProcessException.CreateFmt(strDirectoryNotFound, [Process.strDir]); If Not FileExists(Process.strEXE) Then Begin If Not DGHFindOnPath(Process.strEXE, '') Then Raise EDGHCreateProcessException.CreateFmt(strEXENotFound, [Process.strEXE]); End; End; (** This procedure configures the security attributes for the progress to be created. @precon None. @postcon The passed security attributes are configured. @param SecurityAttrib as a TSecurityAttributes as a reference **) Procedure ConfigSecurityAttrib(Var SecurityAttrib : TSecurityAttributes); Begin FillChar(SecurityAttrib, SizeOf(SecurityAttrib), 0); SecurityAttrib.nLength := SizeOf(SecurityAttrib); SecurityAttrib.bInheritHandle := True; SecurityAttrib.lpSecurityDescriptor := Nil; End; (** This procedure configures the startup information for the new process to be created. @precon None. @postcon The startup information is configured. @param StartupInfo as a TStartupInfo as a reference @param hWrite as a THandle as a constant **) Procedure ConfigStartUp(Var StartupInfo : TStartupInfo; Const hWrite : THandle); Begin FillChar(StartupInfo, SizeOf(TStartupInfo), 0); StartupInfo.cb := SizeOf(TStartupInfo); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; StartupInfo.wShowWindow := SW_HIDE; StartupInfo.hStdOutput := hWrite; StartupInfo.hStdError := hWrite; End; (** 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); Var iTotalBytesInPipe : Cardinal; iBytesRead : Cardinal; strOutput : AnsiString; 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); slLines.Append(StringReplace(UTF8ToString(strOutput), #10, #13#10, [rfReplaceAll])); 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; (** This procedure runs the process collecting information from the console output and feeding it back into the output memo. @precon None. @postcon The process is run and the output captured. @param SecurityAttrib as a TSecurityAttributes as a constant @param StartupInfo as a TStartupInfo as a constant @param hRead as a THandle as a constant **) Procedure RunProcess(Const SecurityAttrib : TSecurityAttributes; Const StartupInfo : TStartupInfo; Const hRead : THandle); Const iWaitIntervalInMS = 50; Var ProcessInfo : TProcessInformation; slLines : TStringList; iExitCode : Cardinal; Begin Win32Check(CreateProcess(PChar(Process.strEXE), PChar('"' + Process.strEXE + '" ' + Process.strParams), @SecurityAttrib, Nil, True, CREATE_NEW_CONSOLE, Nil, PChar(Process.strDir), StartupInfo, ProcessInfo)); Try slLines := TStringList.Create; Try While WaitforSingleObject(ProcessInfo.hProcess, iWaitIntervalInMS) = 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; End; Var hRead, hWrite : THandle; SecurityAttrib : TSecurityAttributes; StartupInfo : TStartupInfo; Begin Result := 0; boolAbort := False; ConfigSecurityAttrib(SecurityAttrib); Win32Check(CreatePipe(hRead, hWrite, @SecurityAttrib, iPipeSize)); Try If Process.boolEnabled Then Try CheckProcess; ConfigStartUp(StartupInfo, hWrite); RunProcess(SecurityAttrib, StartupInfo, hRead); 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 updates the ProjectNamePattern macro in the revisiob query while maintaining the DBGrids column widths. @precon None. @postcon Updates the ProjectNamePattern macro in the revisiob query while maintaining the DBGrids column widths. @param Sender as a TObject **) Procedure TfrmJEDIVCSToGit.edtProjectNamePatternExit(Sender: TObject); Var iColumn: Integer; aiColumnWidths : TArray<Integer>; M: TFDMacro; Begin If FDConnection.Connected Then Begin SetLength(aiColumnWidths, DBGrid.Columns.Count); For iColumn := 0 To DBGrid.Columns.Count - 1 Do aiColumnWidths[iColumn] := DBGrid.Columns[iColumn].Width; M := RevisionsFDQuery.MacroByName(strProjectNamePatternMacro); M.Value := edtProjectNamePattern.Text; M := RevisionsFDQuery.MacroByName(strMinRevID); M.Value := edtMinRevID.Text; RevisionsFDQuery.Active := True; For iColumn := 0 To DBGrid.Columns.Count - 1 Do DBGrid.Columns[iColumn].Width := aiColumnWidths[iColumn]; End; End; (** This method executes GIT and captures any errors and prompts for an action. @precon None. @postcon Executes GIT and captures any errors and prompts for an action. @param strCmdParams as a String as a constant **) Procedure TfrmJEDIVCSToGit.ExecuteGit(Const strCmdParams: String); ResourceString strMsg = 'The last GIT command (%s) failed:'#13#10'%s'; Var boolAbort : Boolean; iResult: Integer; Begin FGitPI.strDir := FNewGitRepoPath; FGitPI.strParams := strCmdParams; ProcessMsgevent(Format('%s%s %s', [FGitPI.strDir, ExtractFileName(FGitPI.strEXE), FGitPI.strParams]), boolAbort, mtTitle); FLastMessage := ''; iResult := DGHCreateProcess(FGitPI, ProcessMsgEvent, IdleEvent); If iResult <> 0 Then begin if not FLastMessage.Contains('.gitignore') then begin Case TfrmGITError.Execute(Format(strMsg, [strCmdParams, FLastMessage])) Of mrAbort: Abort; End; end; end; ProcessMsgevent(#13#10, boolAbort); End; (** This is an OnFormCreate Event Handler for the TfrmJEDVICSToGit class. @precon None. @postcon Loads the applications settings and cretes a string list for filenames. @param Sender as a TObject **) Procedure TfrmJEDIVCSToGit.FormCreate(Sender: TObject); ResourceString strPleaseSpecifyFireDACINIFileAsFirstParameter = 'Please specify a FireDAC INI file as the first ' + 'parameter!'; strCouldNotLoadINIFile = 'Could not load the INI file "%s"'; strJEDIVCSToGitBuild = 'JEDI VCS to Git %d.%d%s (Build %d.%d.%d.%d): '; Const strBugFix = ' abcedfghijklmnopqrstuvwxyz'; strGITExe = 'GIT.exe'; Var BuildInfo: TJVTGBuildInfo; M: TFDMacro; Begin GetBuildInfo(BuildInfo); Caption := Format(strJEDIVCSToGitBuild, [ BuildInfo.FMajor, BuildInfo.FMinor, strBugFix[BuildInfo.FRelease + 1], BuildInfo.FMajor, BuildInfo.FMinor, BuildInfo.FRelease, BuildInfo.FBuild ]); FFilenames := TStringList.Create; FFileNames.Duplicates := dupIgnore; FItemCount := 0; FItem := 0; FGitPI.boolEnabled := True; FGitPI.strEXE := strGITExe; If (ParamCount > 0) And FileExists(ParamStr(1)) Then Begin FDConnection.Params.LoadFromFile(ParamStr(1)); FDConnection.Connected := True; M := RevisionsFDQuery.MacroByName(strProjectNamePatternMacro); M.Value := edtProjectNamePattern.Text; M := RevisionsFDQuery.MacroByName(strMinRevID); M.Value := edtMinRevID.Text; RevisionsFDQuery.Active := True; BlobsFDQuery.Active := True; End Else If ParamCount = 0 Then ShowMessage(strPleaseSpecifyFireDACINIFileAsFirstParameter) Else ShowMessage(Format(strCouldNotLoadINIFile, [ParamStr(1)])); FRelativePaths := TStringList.Create; FRelativePaths.Duplicates := dupIgnore; LoadSettings; End; (** This is an OnFormDestroy Event Handler for the TfrmJEDVCSToGit class. @precon None. @postcon Saves the applications settings and the log file and free memory used by the filename string list. @param Sender as a TObject **) Procedure TfrmJEDIVCSToGit.FormDestroy(Sender: TObject); Const strLog = 'Git.log'; Begin SaveSettings; lbxGitOutput.Items.SaveToFile(FNewGitRepoPath + strLog); FRelativePaths.Free; FFileNames.Free; End; (** This method searches for the actual case for the file path and filename so that GIT ADD does not fail to add the file. @precon None. @postcon Returns the correct cased file path and name. @param strRelPathFile as a String as a constant @return a String **) Function TfrmJEDIVCSToGit.GetActualPathAndFileCase(Const strRelPathFile: String) : String; Var sl : TStringList; i: Integer; strCurrentPath : String; recSearch: TSearchRec; iResult: Integer; Begin Result := ''; sl := TStringList.Create; Try sl.Text := StringReplace(strRelPathFile, '\', #13#10, [rfReplaceAll]); strCurrentPath := FNewGitRepoPath; For i := 0 To sl.Count - 1 Do Begin If (Result <> '') And (Result[Length(Result)] <> '\') Then Result := Result + '\'; If (strCurrentPath <> '') And (strCurrentPath[Length(strCurrentPath)] <> '\') Then strCurrentPath := strCurrentPath + '\'; iResult := FindFirst(strCurrentPath + sl[i], faAnyFile, recSearch); Try If iResult = 0 Then Begin Result := Result + recSearch.Name; strCurrentPath := strCurrentPath + recSearch.Name; End; Finally FindClose(recSearch); End; End; Finally sl.Free; End; End; (** This is an on idle event handler for the command line processes to ensure the application updates its interface. @precon None. @postcon The application messge query is updated. **) Procedure TfrmJEDIVCSToGit.IdleEvent; Begin Application.ProcessMessages; End; (** This is an on draw item event handler for the Git Output listbox. @precon None. @postcon Custom Draws the list box items to show GIT commands differently from the rest of the information. @nocheck MissingConstInParam @nohint Control @param Control as a TWinControl @param Index as an Integer @param Rect as a TRect @param State as a TOwnerDrawState **) Procedure TfrmJEDIVCSToGit.lbxGitOutputDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); Var strText: String; Begin If odSelected In State Then Begin lbxGitOutput.Canvas.Brush.Color := clHighlight; lbxGitOutput.Canvas.FillRect(Rect); lbxGitOutput.Canvas.FrameRect(Rect); End Else Begin lbxGitOutput.Canvas.Brush.Color := clWindow; lbxGitOutput.Canvas.FillRect(Rect); End; Case NativeUInt(lbxGitOutput.Items.Objects[Index]) Of NativeUInt(mtTitle): Begin lbxGitOutput.Canvas.Font.Style := [fsBold]; lbxGitOutput.Canvas.Font.Color := clMaroon; End; Else lbxGitOutput.Canvas.Font.Style := []; lbxGitOutput.Canvas.Font.Color := clNavy; End; If odSelected In State Then lbxGitOutput.Canvas.Font.Color := clHighlightText; strText := lbxGitOutput.Items[Index]; lbxGitOutput.Canvas.TextRect(Rect, strText, [tfLeft, tfVerticalCenter]); End; (** This method loads the applications settings from an INI file. @precon None. @postcon The applications settings are loaded from an INI file. **) Procedure TfrmJEDIVCSToGit.LoadSettings; Const iDefaultWidth = 100; Var iniFile: TMemIniFile; iColumn : Integer; Begin iniFile := TMemIniFile.Create(ChangeFileExt(ParamStr(0), strIniExt)); Try Top := iniFile.ReadInteger(strSetupINISection, strTopKey, Top); Left := iniFile.ReadInteger(strSetupIniSection, strLeftKey, Left); Height := iniFile.ReadInteger(strSetupIniSection, strHeightKey, Height); Width := iniFile.ReadInteger(strSetupIniSection, strWidthKey, Width); For iColumn := 0 To DBGrid.Columns.Count - 1 Do DBGrid.Columns[iColumn].Width := iniFile.ReadInteger(strRevsColWidthsIniSection, DBGrid.Columns[iColumn].FieldName, iDefaultWidth); For iColumn := 0 To BlobsGrid.Columns.Count - 1 Do BlobsGrid.Columns[iColumn].Width := iniFile.ReadInteger(strBlobColumnWidthsIniSection, BlobsGrid.Columns[iColumn].FieldName, iDefaultWidth); edtProjectNamePattern.Text := iniFile.ReadString(strSetupIniSection, strProjectNamePatternKey, ''); edtNewGitRepoPath.Text := iniFile.ReadString(strSetupIniSection, strNewRepoPathKey, ''); edtOldGitRepoPath.Text := iniFile.ReadString(strSetupIniSection, strOldRepoPathKey, ''); lbxGitOutput.Height := iniFile.ReadInteger(strSetupIniSection, strOutputHeightKey, lbxGitOutput.Height); BlobsGrid.Height := iniFile.ReadInteger(strSetupIniSection, strBlobGridHeightKey, BlobsGrid.Height); chkStatus.Checked := iniFile.ReadBool(strSetupINISection, strShowStatusKey, True); Finally iniFile.Free; End; edtProjectNamePatternExit(Nil); End; (** This method processses a message from a command line and outputs the information to the output log. @precon None. @postcon Command line process information is output to the output log. @nohint boolAbort @param strMsg as a String as a constant @param boolAbort as a Boolean as a reference @param MsgType as a TMsgType as a constant **) Procedure TfrmJEDIVCSToGit.ProcessMsgevent(Const strMsg: String; Var boolAbort: Boolean; Const MsgType : TMsgType = mtInformation); Var sl : TStringList; iLine: Integer; Begin sl := TStringList.Create; Try sl.Text := strMsg; For iLine := 0 To sl.Count - 1 Do Begin lbxGitOutput.Items.AddObject(sl[iLine], TObject(MsgType)); lbxGitOutput.ItemIndex := Pred(lbxGitOutput.Items.Count); If sl[iLine] <> '' Then Begin If FLastMessage <> '' Then FLastMessage := FLastMessage + #13#10; FLastMessage := FLastMessage + sl[iLine]; End; End; Finally sl.Free; End; End; procedure TfrmJEDIVCSToGit.RevisionsDataSourceDataChange(Sender: TObject; Field: TField); begin end; (** This method saves the applications settings to an ini file. @precon None. @postcon The applications settings are saved. **) Procedure TfrmJEDIVCSToGit.SaveSettings; Var iniFile: TMemIniFile; iColumn : Integer; Begin iniFile := TMemIniFile.Create(ChangeFileExt(ParamStr(0), strIniExt)); Try iniFile.WriteInteger(strSetupIniSection, strTopKey, Top); iniFile.WriteInteger(strSetupIniSection, strLeftKey, Left); iniFile.WriteInteger(strSetupIniSection, strHeightKey, Height); iniFile.WriteInteger(strSetupIniSection, strWidthKey, Width); For iColumn := 0 To DBGrid.Columns.Count - 1 Do iniFile.WriteInteger(strRevsColWidthsIniSection, DBGrid.Columns[iColumn].FieldName, DBGrid.Columns[iColumn].Width); For iColumn := 0 To BlobsGrid.Columns.Count - 1 Do iniFile.WriteInteger(strBlobColumnWidthsIniSection, BlobsGrid.Columns[iColumn].FieldName, BlobsGrid.Columns[iColumn].Width); iniFile.WriteString(strSetupIniSection, strProjectNamePatternKey, edtProjectNamePattern.Text); iniFile.WriteString(strSetupIniSection, strNewRepoPathKey, edtNewGitRepoPath.Text); iniFile.WriteString(strSetupIniSection, strOldRepoPathKey, edtOldGitRepoPath.Text); iniFile.WriteInteger(strSetupIniSection, strOutputHeightKey, lbxGitOutput.Height); iniFile.WriteInteger(strSetupIniSection, strBlobGridHeightKey, BlobsGrid.Height); iniFile.WriteBool(strSetupINISection, strShowStatusKey, chkStatus.Checked); iniFile.UpdateFile; Finally iniFile.Free; End; End; (** This is an on draw panel event handler for the statusbar. @precon None. @postcon Draws the main panel (0) with a progress bar. @nocheck MissingConstInParam @param StatusBar as a TStatusBar @param Panel as a TStatusPanel @param Rect as a TRect as a constant **) Procedure TfrmJEDIVCSToGit.StatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; Const Rect: TRect); Const iPadding = 0; iLightRed = $8080FF; iLightGreen = $80FF80; Var R : TRect; strText: String; Begin R := Rect; strText := Panel.Text; StatusBar.Canvas.Brush.Color := iLightRed; InflateRect(R, -iPadding, 0); StatusBar.Canvas.FillRect(R); StatusBar.Canvas.TextRect(R, strText, [tfLeft]); StatusBar.Canvas.Brush.Color := iLightGreen; R.Right := R.Left + Trunc(Int(R.Right - R.Left) * (FPercentage / dblPercentageMultiplier)); StatusBar.Canvas.FillRect(R); StatusBar.Canvas.TextRect(R, strText, [tfLeft]); End; (** This method updates the statusbar status and pregress position. @precon None. @postcon The statusbar status and position is updated. **) Procedure TfrmJEDIVCSToGit.UpdateStatus; ResourceString strRecOfRecs = ' %d of %d (%1.1n%%), Elapsed: %s, Remaining: %s, Total: %s...'; Var iTotal: UINt64; Begin FPercentage := Int(FItem) / Int(FItemCount) * dblPercentageMultiplier; If FPercentage > 0 Then iTotal := Trunc(Int(GetTickCount64 - FStartTime) * dblPercentageMultiplier / FPercentage) Else iTotal := 0; StatusBar.Panels[0].Text := Format(strRecOfRecs, [ FItem, FItemCount, FPercentage, CalcTime(GetTickCount64 - FStartTime), CalcTime(iTotal - (GetTickCount64 - FStartTime)), CalcTime(iTotal) ]); End; End.
program show; (* This program prints the current memory size in kilobytes *) (* and the version number of CP/M on the console. *) (* Written by Robert Bedichek September 1980 *) (* NOTE: The external routines used herein are not in LIB.REL *) (* and thus must be explicitly linked in. *) const cpm = 5; (* BDOS entry point address. *) vercode = 12; (* CP/M code to return the version number *) type byte = 0..255; registers = record a: byte; bc, de, hl: integer end; var reg: registers; BDOS: integer; kilobytes: byte; quarterK: byte; procedure call( var x: registers; start: integer ); external; function peek( address: integer ): integer; external; begin writeln; writeln; reg.bc := vercode; call( reg, cpm ); write( 'This is ' ); (* If register h is zero then we are under CP/M, else we are under MP/M. *) if (reg.hl div 256) > 0 then write( 'MP/M' ) else write( 'CP/M' ); writeln( ' version ', reg.hl div 16:1, '.', reg.hl mod 16:1 ); (* Now figure out how big the workspace is. We look at the jump *) (* instruction at location 5. It points to one past the end of the *) (* workspace. Note the trickery involved because Pascal/Z can not have *) (* an integer bigger than 32,767. *) (* I know this code could be shorter, but I thought that this was clearer *) BDOS := peek( cpm + 1 ) - 256; if BDOS < 0 then begin kilobytes := (BDOS div 1024) + 64; quarterK := 25 * (((BDOS div 256) mod 4) + 3) end else begin kilobytes := BDOS div 1024; quarterK := 25 * ((BDOS div 256) mod 4) end; writeln( 'There are ', kilobytes:1, '.', quarterK:1, ' kilobytes in the Transient Program Area' ); end. 
//--------------------------------------------------------------- // CharPrinter.pas - Tratamento de impressoras em modo caractere //--------------------------------------------------------------- // Autor : Fernando Allen Marques de Oliveira // Dezembro de 2000. // // TPrinterStream : classe derivada de TStream para enviar dados // diretamente para o spool da impressora sele- // cionada. // // TCharPrinter : Classe base para implementação de impressoras. // não inclui personalização para nenhuma impres- // sora específica, envia dados sem formatação. // // Modificado em 20/05/2003 - Compatibilização com diretivas padrão do Delphi 7 unit CharPrinter; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Printers, WinSpool; type { Stream para enviar caracteres à impressora atual } TPrinterStream = class (TStream) private fPrinter : TPrinter; fHandle : THandle; fTitle : String; procedure CreateHandle; procedure FreeHandle; public constructor Create (aPrinter: TPrinter; aTitle : String); destructor Destroy; override; function Write (const Buffer; Count : Longint): Longint; override; property Handle : THandle read fHandle; end; TCharPrinter = class(TObject) private { Private declarations } fStream : TStream; protected { Protected declarations } public { Public declarations } published { Published declarations } constructor Create; virtual; destructor Destroy; override; procedure OpenDoc (aTitle : String); virtual; procedure SendData (aData : String); procedure CloseDoc; virtual; property PrintStream : TStream read fStream; end; // Definições para TAdvancedPrinter // TprtLang = (lngEPFX,lngESCP2,lngHPPCL); TprtFontSize = (pfs5cpi,pfs10cpi,pfs12cpi,pfs17cpi,pfs20cpi); TprtTextStyle = (psBold,psItalic,psUnderline); TprtTextStyles = set of TprtTextStyle; TAdvancedPrinter = class (TCharPrinter) private fLang : TprtLang; fFontSize : TprtFontSize; fTextStyle : TprtTextStyles; procedure SetLang (lang : TprtLang); function GetLang : TprtLang; procedure SetFontSize (size : TprtFontSize); function GetFontSize : TprtFontSize; procedure SetTextStyle (styles : TprtTextStyles); function GetTextStyle : TprtTextStyles; procedure UpdateStyle; procedure Initialize; function Convert (s : string) : string; published constructor Create; override; procedure OpenDoc (aTitle : String); override; property Language : TprtLang read GetLang write SetLang; property FontSize : TprtFontSize read GetFontSize write SetFontSize; property TextStyle : TprtTextStyles read GetTextStyle write SetTextStyle; public procedure CR; procedure LF; overload; procedure LF (Lines : integer); overload; procedure CRLF; procedure FF; procedure Write (txt : string); procedure WriteLeft (txt, fill : string; size : integer); procedure WriteRight (txt, fill : string; size : integer); procedure WriteCenter(txt, fill : string; size : integer); procedure WriteRepeat(txt : string; quant : integer); end; procedure Register; implementation procedure Register; begin { RegisterComponents('AeF', [TCharPrinter]);} end; { =================== } { = TPrinterStream = } { =================== } constructor TPrinterStream.Create (aPrinter : TPrinter; aTitle : String); begin inherited Create; fPrinter := aPrinter; fTitle := aTitle; CreateHandle; end; destructor TPrinterStream.Destroy; begin FreeHandle; inherited; end; procedure TPrinterStream.FreeHandle; begin if fHandle <> 0 then begin EndPagePrinter (fHandle); EndDocPrinter (fHandle); ClosePrinter (Handle); fHandle := 0; end; end; procedure TPrinterStream.CreateHandle; type DOC_INFO_1 = packed record pDocName : PChar; pOutputFile : PChar; pDataType : PChar; end; var aDevice, aDriver, aPort : array[0..255] of Char; aMode : NativeUInt; DocInfo : DOC_INFO_1; begin DocInfo.pDocName := nil; DocInfo.pOutputFile := nil; DocInfo.pDataType := 'RAW'; FreeHandle; if fHandle = 0 then begin fPrinter.GetPrinter (aDevice, aDriver, aPort, aMode); if OpenPrinter (aDevice, fHandle, nil) then begin DocInfo.pDocName := PChar(fTitle); if StartDocPrinter (fHandle, 1, @DocInfo) = 0 then begin ClosePrinter (fHandle); fHandle := 0; end else if not StartPagePrinter (fHandle) then begin EndDocPrinter (fHandle); ClosePrinter (fHandle); fHandle := 0; end; end; end; end; function TPrinterStream.Write (const Buffer; Count : Longint) : Longint; var Bytes : Cardinal; begin WritePrinter (Handle, @Buffer, Count, Bytes); Result := Bytes; end; { ================= } { = TCharPrinter = } { ================= } constructor TCharPrinter.Create; begin inherited Create; fStream := nil; end; destructor TCharPrinter.Destroy; begin if fStream <> nil then fStream.Free; inherited; end; procedure TCharPrinter.OpenDoc (aTitle : String); begin if fStream = nil then fStream := TPrinterStream.Create (Printer, aTitle); end; procedure TCharPrinter.CloseDoc; begin if fStream <> nil then begin fStream.Free; fStream := nil; end; end; procedure TCharPrinter.SendData (aData : String); var Data : AnsiString; begin Data := AnsiString(aData); fStream.Write(PAnsiChar(Data)^, Length(Data)); {var Data : array[0..255] of char; cnt : integer; begin for cnt := 0 to length(aData) -1 do Data[cnt] := aData[cnt + 1]; fStream.Write (Data, length(aData));} end; { ===================== } { = TAdvancedPrinter = } { ===================== } procedure TAdvancedPrinter.SetLang (lang : TprtLang); begin fLang := lang; end; function TAdvancedPrinter.GetLang : TprtLang; begin result := fLang; end; procedure TAdvancedPrinter.SetFontSize (size : TprtFontSize); begin fFontSize := size; UpdateStyle; end; function TAdvancedPrinter.GetFontSize : TprtFontSize; begin result := fFontSize; UpdateStyle; end; procedure TAdvancedPrinter.SetTextStyle (styles : TprtTextStyles); begin fTextStyle := styles; UpdateStyle; end; function TAdvancedPrinter.GetTextStyle : TprtTextStyles; begin result := fTextStyle; UpdateStyle; end; procedure TAdvancedPrinter.UpdateStyle; var cmd : string; i : byte; begin cmd := ''; case fLang of lngESCP2, lngEPFX : begin i := 0; Case fFontSize of pfs5cpi : i := 32; pfs10cpi : i := 0; pfs12cpi : i := 1; pfs17cpi : i := 4; pfs20cpi : i := 5; end; if psBold in fTextStyle then i := i + 8; if psItalic in fTextStyle then i := i + 64; if psUnderline in fTextStyle then i := i + 128; cmd := #27'!'+chr(i); end; lngHPPCL : begin Case fFontSize of pfs5cpi : cmd := #27'(s5H'; pfs10cpi : cmd := #27'(s10H'; pfs12cpi : cmd := #27'(s12H'; pfs17cpi : cmd := #27'(s17H'; pfs20cpi : cmd := #27'(s20H'; end; if psBold in fTextStyle then cmd := cmd + #27'(s3B' else cmd := cmd + #27'(s0B'; if psItalic in fTextStyle then cmd := cmd + #27'(s1S' else cmd := cmd + #27'(s0S'; if psUnderline in fTextStyle then cmd := cmd + #27'&d0D' else cmd := cmd + #27'&d@'; end; end; SendData(cmd); end; procedure TAdvancedPrinter.Initialize; begin case fLang of lngEPFX : SendData (#27'@'#27'2'#27'P'#18); lngESCP2 : SendData (#27'@'#27'O'#27'2'#27'C0'#11#27'!'#0); lngHPPCL : SendData (#27'E'#27'&l2A'#27'&l0O'#27'&l6D'#27'(s4099T'#27'(s0P'#27'&k0S'#27'(s0S'); end; end; function TAdvancedPrinter.Convert (s : string) : string; const accent : string = 'ãàáäâèéëêìíïîõòóöôùúüûçÃÀÁÄÂÈÉËÊÌÍÏÎÕÒÓÖÔÙÚÜÛÇ'; noaccent : string = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC'; var i : integer; begin for i := 1 to length(accent) do While Pos(accent[i],s) > 0 do s[Pos(accent[i],s)] := noaccent[i]; result := s; end; constructor TAdvancedPrinter.Create; begin inherited Create; fLang := lngESCP2; fFontSize := pfs10cpi; fTextStyle := []; end; procedure TAdvancedPrinter.OpenDoc (aTitle : String); begin inherited OpenDoc (aTitle); Initialize; end; procedure TAdvancedPrinter.CR; begin SendData (#13); end; procedure TAdvancedPrinter.LF; begin SendData (#10); end; procedure TAdvancedPrinter.LF (Lines : integer); begin while lines > 0 do begin SendData(#10); dec(lines); end; end; procedure TAdvancedPrinter.CRLF; begin SendData (#13#10); end; procedure TAdvancedPrinter.FF; begin SendData(#12); end; procedure TAdvancedPrinter.Write (txt : string); begin txt := Convert (txt); SendData (txt); end; procedure TAdvancedPrinter.WriteLeft (txt, fill : string; size : integer); begin txt := Convert(txt); while Length(txt) < size do txt := txt + fill; SendData (Copy(txt,1,size)); end; procedure TAdvancedPrinter.WriteRight (txt, fill : string; size : integer); begin txt := Convert(txt); while Length(txt) < size do txt := fill + txt; SendData (Copy(txt,Length(txt)-size+1,size)); end; procedure TAdvancedPrinter.WriteCenter(txt, fill : string; size : integer); begin txt := Convert(txt); while Length(txt) < size do txt := fill + txt + fill; SendData (Copy(txt,(Length(txt)-size) div 2 + 1,size)); end; procedure TAdvancedPrinter.WriteRepeat(txt : string; quant : integer); var s : string; begin s := ''; txt := Convert(txt); while quant > 0 do begin s := s + txt; dec(quant); end; SendData (s); end; end. procedure TForm1.Button1Click (Sender : TObject); var Prn : TCharPrinter; begin // Cria o objeto de impressora e abre o documento para impressão Prn := TCharPrinter.Create; Prn.OpenDoc ('Nome do seu relatório que aparecerá no spool do windows'); // Inicializa a impressora Prn.SendData (#27'@'); // Envia seu texto #13#10 = CR+LF (Retorno de carro mas avanço de linha = pula para próxima linha) Prn.SendData ('Escreva seu texto aqui'#13#10); Prn.SendData (#13#10); Prn.SendData (#15'Esta linha esta com os caracteres condensados'#18#13#10); // Avanço de página Prn.SendData (#12); // Fecha o relatório, manda para o spool e destroy o objeto Prn.CloseDoc; Prn.Free; end; O objeto TAdvancedPrinter, descendente de TCharPrinter foi personalizado para reconhecer a linguagem das impressoras Epson LX/FX/ESCP2 e ainda HPPCL para escrever em Deskjets e Laserjets. Também inclui métodos para controlar o tamanho dos caracteres, avançar linhas e escrever textos com tamanho fixo e alinhados à direita, à esquerda e centralizados. qualquer dúvida na utilização, mande mensagem particular para mim. Fernando Allen08-July-2003, 09:29 Amigos, Como estou recebendo muitas dúvidas na utilização desta classe, criei um pequeno projeto em delphi para melhor exemplificar. Vocês podem fazer o download deste arquivo através deste link: http://www.devmind.kit.net/demo_charprinter.zip Se você obsevarem o código fonte, verão que na TAdvancedPrinter eu acrescentei alguns métodos adicionais muito úteis e a capacidade de trabalhar com três padrões de comandos de impressão: EpsonFX, EpsonESC/P2 e HPPCL podendo escolher os tamanhos mais comuns de caracteres nas matriciais: // Determina qual a linguagem (código de controle) de impressora será utilizado property Language : TprtLang read GetLang write SetLang; // Muda o tamanho da fonte padrão da impressora (em CPI - Caracteres por polegada) property FontSize : TprtFontSize read GetFontSize write SetFontSize; // Conjunto de atributos que combinados definem o estilo de texto (Bold, Itálico, Sublinhado, etc) property TextStyle : TprtTextStyles read GetTextStyle write SetTextStyle; // Promove o retorno de carro procedure CR; // Promove o avanço de linha procedure LF; overload; // Faz avançar n linhas procedure LF (Lines : integer); overload; // Retorno de carro + avanço de linha = começo da próxima linha procedure CRLF; // Avanço de formulário - próxima página procedure FF; // Envia uma string para a impressora - sem pular linha procedure Write (txt : string); // Envia uma string (txt) alinhada à esquerda com tamanho máximo = size e // com o espaço restante preenchido com a string fill (sim, pode ser mais de um caractere) procedure WriteLeft (txt, fill : string; size : integer); // O mesmo que o método anterior, mas alinhando à direita procedure WriteRight (txt, fill : string; size : integer); // Alinhamento centralizado procedure WriteCenter(txt, fill : string; size : integer); // Para quem quiser repetir uma string ou caracteres uma determinada quantidade de vezes procedure WriteRepeat(txt : string; quant : integer);
unit SendMail; interface uses {$IFDEF IOS} Macapi.ObjectiveC, Macapi.CoreFoundation, Macapi.Dispatch, iOSApi.CocoaTypes, iOSApi.Foundation, Posix.SysSocket; {$ENDIF} {$IFDEF ANDROID} FMX.Helpers.Android, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.Net, Androidapi.JNI.Os; {$ENDIF} procedure CreateEmail(const Recipient, Subject, Content, FileToAttach: string); implementation procedure CreateEmail(const Recipient, Subject, Content, FileToAttach: string); {$IFDEF ANDROID} var Uri: Jnet_Uri; Intent: JIntent; Recipients: TJavaObjectArray<JString>; {$ENDIF} begin {$IFDEF ANDROID} Intent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_SEND); Recipients := TJavaObjectArray<JString>.Create(1); Recipients.Items[0] := StringToJString(Recipient); Intent.putExtra(TJIntent.JavaClass.EXTRA_EMAIL, Recipients); Intent.putExtra(TJIntent.JavaClass.EXTRA_SUBJECT, StringToJString(Subject)); Intent.putExtra(TJIntent.JavaClass.EXTRA_TEXT, StringToJString(Content)); Intent.setType(StringToJString('plain/text')); SharedActivity.startActivity(TJIntent.JavaClass.createChooser(Intent, StrToJCharSequence('Which email app?'))); if FileToAttach <> '' then begin Uri := TJnet_Uri.JavaClass.parse(StringToJString(FileToAttach)); Intent.putExtra(TJIntent.JavaClass.EXTRA_STREAM, TJParcelable.Wrap((Uri as ILocalObject).GetObjectID)); end; {$ENDIF} end; end.
unit MainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, LuaWrapper, pLuaRecord, StdCtrls; type { TForm1 } TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { private declarations } public { public declarations } Lua : TLua; end; var Form1: TForm1; implementation uses lua, plua, RecTest; var r : TMyRecord; function lua_ShowMessage(l : PLua_State) : integer; cdecl; var n, i : Integer; msg : AnsiString; begin result := 0; n := lua_gettop(l); if n > 0 then begin msg := ''; for i := 1 to n do msg := msg + plua_tostring(L, i); ShowMessage(msg); end; end; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin Lua := TLua.Create(self); Lua.RegisterLuaMethod('ShowMessage', @lua_ShowMessage); RegisterMyRecordType(Lua.LuaState); RegisterExistingMyRecord(Lua.LuaState, 'r', @r); end; procedure TForm1.Button1Click(Sender: TObject); begin if FileExists('script.lua') then Lua.Execute; end; procedure TForm1.FormShow(Sender: TObject); begin if FileExists('script.lua') then begin try Lua.LoadFile('script.lua'); Lua.Execute; except on e : Exception do Caption := e.message; end; end else Caption := 'No script.lua file found in path.'; end; initialization {$I MainForm.lrs} end.
(* Given an S(n,n) matrix such that n<9, print the index of each row containing more digits than letters. *) type CharArray = array of Char; type IntegerArray = array of Integer; function isDigit(c: Char): Boolean; var i: Integer; res: Boolean; const arr: array[0..9] of Char = '0123456789'; begin res := False; for i := 0 to Length(arr)-1 do if (c = arr[i]) then begin res := True; break; end; Result := res; end; procedure f(arr: array of CharArray); var i, j, digits, letters: Integer; begin for i := 0 to Length(arr)-1 do begin digits := 0; letters := 0; for j := 0 to Length(arr[i])-1 do if (isDigit(arr[i,j])) then digits := digits + 1 else letters := letters + 1; if (digits > letters) then WriteLn(i); end; end; var arr1: array of CharArray; begin SetLength(arr1, 4); SetLength(arr1[0], 4); SetLength(arr1[1], 4); SetLength(arr1[2], 4); SetLength(arr1[3], 4); arr1[0,0] := 'a'; arr1[0,1] := 'b'; arr1[0,2] := 'c'; arr1[0,3] := 'd'; arr1[1,0] := 'e'; arr1[1,1] := '2'; arr1[1,2] := 'g'; arr1[1,3] := '4'; arr1[2,0] := '1'; arr1[2,1] := 'j'; arr1[2,2] := '3'; arr1[2,3] := '4'; arr1[3,0] := '1'; arr1[3,1] := '2'; arr1[3,2] := 'o'; arr1[3,3] := '4'; f(arr1); end.
unit ClsGames; interface uses Windows, Contnrs, Forms; //SysUtils Type THotKeyInfo = Class private FID: Integer; FIniFileName: WideString; FInfoName: WideString; FVirtualKey: WORD; FModifiers: UINT; FShowText: WideString; public constructor Create(const InfoName: WideString); destructor Destroy; override; property ID: Integer read FID; property IniFileName: WideString read FIniFileName write FIniFileName; property Modifiers: UINT read FModifiers write FModifiers; property VirtualKey: Word read FVirtualKey write FVirtualKey; property ShowText: WideString read FShowText write FShowText; procedure ReadHotKeyInfo; function RegisterHotKey(FormHandle: THandle): Boolean; function UnRegisterHotKey(FormHandle: THandle): Boolean; procedure WriteHotKeyInfo; end; TWindowInfo = Class; THLUser = Class; THLInfo = class(TObjectList) ProcessId: LongWord; UserNick: WideString; // 绰号 UserSpouse: WideString; // 配偶 private FMainHotKeyInfo: THotKeyInfo; FUser: THLUser; FUserName: WideString; // 名字 FWinInfoHotKeyInfo: THotKeyInfo; function GetItem(Index: Integer): TWindowInfo; procedure SetItem(Index: Integer; const Value: TWindowInfo); function GetIniFileName: WideString; procedure SetUserName(const Value: WIdeString); public constructor Create; destructor Destroy; override; procedure DeepGetWindow(hCurrentWindow: HWND; ParentWindow: TWindowInfo; sPrefix: WideString); property IniFileName: WideString read GetIniFileName; function ItemOfWindowID(const WindowID: LongWord): TWindowInfo; function ItemOfWindowTitle(const SubTitle: WideString): TWindowInfo; property Items[Index: Integer]: TWindowInfo read GetItem write SetItem; default; procedure LoadFormAttribute(const FormNameStr: string; f: TForm); function LocateChildWindowWNDByTitle(hwndParentWin: HWND; const SubTitle: WideString; const isDirectChild: Boolean): HWND; overload; function LocateChildWindowWNDByTitle(ParentWinInfo: TWindowInfo; const SubTitle: WideString; const isDirectChild: Boolean): HWND; overload; function LocateChildWindowInfoByTitle(hwndParentWin: HWND; const SubTitle: WideString; const isDirectChild: Boolean): TWindowInfo; overload; function LocateChildWindowInfoByTitle(ParentWinInfo: TWindowInfo; const SubTitle: WideString; const isDirectChild: Boolean): TWindowInfo; overload; function LocateToMainPanel: Integer; function LocateToPlayWindow(var wPlayWindow: TWindowInfo): Integer; function LocatePetMarchingButton(slot: Integer): HWND; property MainHotKeyInfo: THotKeyInfo read FMainHotKeyInfo; function ReCalWin: Integer; procedure SaveFormAttribute(const FormNameStr: Widestring; f: TForm); property User: THLUser read FUser; property UserName: WIdeString read FUserName write SetUserName; procedure WaitWindowDisAppearbyHwnd(const myHwnd: HWND); procedure WaitWindowDisAppearbyTitle(const SubTitle: WideString); property WinInfoHotKeyInfo: THotKeyInfo read FWinInfoHotKeyInfo; end; THLInfoList = class(TObjectList) private FSelectIndex: Integer; function GetItem(Index: Integer): THLInfo; procedure SetItem(Index: Integer; const Value: THLInfo); function GetCurrHLInfo: THLInfo; procedure SetSelectIndex(const Value: Integer); public constructor Create; property Items[Index: Integer]: THLInfo read GetItem write SetItem; default; property SelectIndex: Integer write SetSelectIndex; property GlobalHL: THLInfo read GetCurrHLInfo; end; THLUser = Class private FHLInfo: THLInfo; public constructor Create(aObj: THLInfo); end; TWindowInfo = Class Prefix : WideString; Title : WideString; ClassName : WideString; Window : LongWord; //HWND; ParentWin : TWindowInfo; Left : LongInt; Right : LongInt; Top : LongInt; Bottom : LongInt; end; var HLInfoList: THLInfoList; implementation uses UnitConsts, IniFiles; { THL_Info } constructor THLInfo.Create; begin inherited; FUser := THLUser.Create(self); FMainHotKeyInfo := THotKeyInfo.Create(IDS_MainHotKeyInfo); FWinInfoHotKeyInfo := THotKeyInfo.Create(IDS_WinInfoHotKeyInfo); end; procedure THLInfo.DeepGetWindow(hCurrentWindow: HWND; ParentWindow: TWindowInfo; sPrefix: WideString); // 深入获取窗口信息 var hChildCW, hNext: HWnd; szText: array[0..254]of char; WinRect: TRECT; MyWin: TWindowInfo; tmpPrefix: String; begin hCurrentWindow := GetWindow(hCurrentWindow, GW_HWNDFIRST); While hCurrentWindow <> 0 Do Begin GetWindowText(hCurrentWindow, @szText, 255); GetWindowRect(hCurrentWindow, WinRect); MyWin := TWindowInfo.Create; with MyWin do begin Prefix := sPrefix; Title := szText; Window := hCurrentWindow; ParentWin := ParentWindow; Top := WinRect.Top; Left := WinRect.Left; Bottom := WinRect.Bottom; Right := WinRect.Right; GetClassName(hCurrentWindow, @szText, 255); ClassName := szText; end; hChildCW := GetWindow(hCurrentWindow, GW_CHILD); hNext := GetWindow(hCurrentWindow, GW_HWNDNEXT); if hNext <> 0 then begin MyWin.Prefix := MyWin.Prefix + '┣'; tmpPrefix := sPrefix + '┃'; end else begin MyWin.Prefix := MyWin.Prefix+'┗'; tmpPrefix := sPrefix + ' '; end; Self.Add(mywin); if hChildCW <> 0 then DeepGetWindow(hChildCW, MyWin, tmpPrefix); hCurrentWindow := hNext; end; end; destructor THLInfo.Destroy; begin FUser.Free; FMainHotKeyInfo.Free; FWinInfoHotKeyInfo.Free; inherited; end; function THLInfo.GetIniFileName: WideString; begin Result := IDS_UsersPath + UserName + '.Ini'; end; function THLInfo.GetItem(Index: Integer): TWindowInfo; begin Result := TWindowInfo(inherited Items[Index]); end; function THLInfo.ItemOfWindowID(const WindowID: LongWord): TWindowInfo; // 根据编号查找窗口 var i: Integer; begin ReCalWin; for i := 0 to Self.Count - 1 do begin Result := Self.Items[i]; if Result.Window = WindowID then Exit; end; Result := nil; end; function THLInfo.ItemOfWindowTitle( const SubTitle: WideString): TWindowInfo; // 根据标题查找窗口 var i: Integer; begin ReCalWin; for i := 0 to Self.Count - 1 do begin Result := Self.Items[i]; if SubTitle = Result.Title then Exit; end; Result := nil; end; procedure THLInfo.LoadFormAttribute(const FormNameStr: string; f: TForm); // 装载窗体属性 var iTmp: integer; begin with TIniFile.Create(self.IniFileName) do // 窗体属性 try // 设置窗体位置 iTmp := ReadInteger(FormNameStr, IDS_FormTopStr, 0); if (iTmp <= 0) or (iTmp >= Screen.DesktopHeight) then iTmp := 0; f.Top := iTmp; iTmp := ReadInteger(FormNameStr, IDS_FormLeftStr, 0); if (iTmp <= 0) or (iTmp >= Screen.DesktopWidth) then iTmp := 0; f.Left := iTmp; finally Free; end; end; function THLInfo.LocateChildWindowInfoByTitle(hwndParentWin: HWND; const SubTitle: WideString; const isDirectChild: Boolean): TWindowInfo; // 定位一个子窗口(不一定是直接子窗口) var i: integer; tmpWin, tmpRecursionWin: TWindowInfo; begin ReCalWin; Result := nil; for i := 0 to Self.Count - 1 do begin tmpWin := Self.Items[i]; if (SubTitle <> tmpWin.Title) and (SubTitle <> '') then Continue; // Title 没对应上 if isDirectChild then begin // 自接子窗口 if tmpWin.ParentWin = nil then begin if hwndParentWin = 0 then // 本身就指定无父窗口 begin Result := tmpWin; Exit; end; Continue; end; if tmpWin.ParentWin.Window = hwndParentWin then begin Result := tmpWin; Exit; end; end else begin // 间接子窗口 tmpRecursionWin := tmpWin; // 检查是否为ParentWin的某层子窗口 while tmpRecursionWin.ParentWin <> nil do if (hwndParentWin = 0) or (tmpRecursionWin.ParentWin.Window = hwndParentWin) then begin Result := tmpWin; Exit; end else tmpRecursionWin := tmpRecursionWin.ParentWin; end; end; {for} end; function THLInfo.LocateChildWindowInfoByTitle(ParentWinInfo: TWindowInfo; const SubTitle: WideString; const isDirectChild: Boolean): TWindowInfo; // 定位一个子窗口(不一定是直接子窗口) begin Result := LocateChildWindowInfoByTitle(ParentWinInfo.Window, SubTitle, isDirectChild); end; function THLInfo.LocateChildWindowWNDByTitle(hwndParentWin: HWND; const SubTitle: WideString; const isDirectChild: Boolean): HWND; // 定位一个子窗口(不一定是直接子窗口) var tmpWin: TWindowInfo; begin tmpWin := LocateChildWindowInfoByTitle(hwndParentWin, SubTitle, isDirectChild); if tmpWin = nil then Result := 0 else Result := tmpWin.Window; end; function THLInfo.LocateChildWindowWNDByTitle(ParentWinInfo: TWindowInfo; const SubTitle: WideString; const isDirectChild: Boolean): HWND; // 定位一个子窗口(不一定是直接子窗口) begin Result := LocateChildWindowWNDByTitle(ParentWinInfo.Window, SubTitle, isDirectChild); end; function THLInfo.LocateToMainPanel: Integer; // 定位到主面板 var i: Integer; winApp: TWindowInfo; begin ReCalWin; Result := -1; winApp := nil; for i := 0 to Self.Count - 1 do begin if Pos(WideString('Monster&Me - '), Self.Items[i].Title) <> 0 then begin winApp := Self.Items[i]; end; if winApp <> nil then begin if Self.Items[i].Title = PnlMainTitle then begin Result := i; Break; end; end; end; end; function THLInfo.LocateToPlayWindow(var wPlayWindow: TWindowInfo): Integer; // Locate and return game window. var i, MainLeft, MainRight, MainTop, MainBottom: Integer; tmpWin: TWindowInfo; myFile: TextFile; text: string; begin Result := -1; wPlayWindow := nil; if ReCalWin = 0 then Exit; //memory address of handle 66C0BC //AssignFile(myFile, 'Test.txt'); //ReWrite(myFile); i := 0; repeat tmpWin := self.Items[i]; // Find main form //if Pos(AnsiString('Monster&Me - '), tmpWin.Title) <> 0 then if tmpWin.ClassName = 'TFormMain' then begin MainLeft := tmpWin.Left; MainRight := tmpWin.Right; MainTop := tmpWin.Top; MainBottom := tmpWin.Bottom; Result := i; wPlayWindow := tmpWin; Exit; Break; end; Inc(i); until i > self.Count - 1; if i > self.Count - 1 then begin //CloseFile(myFile); Exit; end ; i := 0; repeat tmpWin := self.Items[i]; // Locate game form? if (tmpWin.Left - PlayLeftJust = MainLeft) and (tmpWin.Right - PlayRightJust = MainRight) and (tmpWin.Top - PlayTopJust = MainTop) and (tmpWin.Bottom - PlayBottomJust = MainBottom) then begin tmpWin.Left := MainLeft + PlayLeftJust; tmpWin.Top := MainTop + PlayTopJust; Result := i; wPlayWindow := tmpWin; Break; end; //text := tmpWin.Prefix + ' ' + tmpWin.Title + ' ' + tmpWin.ClassName; //text := text + '[' + IntToStr(tmpWin.Left) + ',' + IntToStr(tmpWin.Top) + ',' + IntToStr(tmpWin.Right) + ',' + IntToStr(tmpWin.Bottom) + ']'; //WriteLn(myFile, text); Inc(i); until i > self.Count - 1; //CloseFile(myFile); end; function THLInfo.LocatePetMarchingButton(slot: Integer): HWND; // Find marching button for pet in slot var i: Integer; slotIter: Integer; nextWin: TWindowInfo; begin ReCalWin; Result := 0; nextWin := nil; slotIter := 6 - slot; for i := 0 to Self.Count - 1 do begin nextWin := Self.Items[i]; if (nextWin.ParentWin <> nil) and (nextWin.ParentWin.Title = 'Pet List') then begin if (nextWin.Title = 'Marching') OR (nextWin.Title = 'Resting') then begin if slotIter = 1 then begin Result := nextWin.Window; Break; end; slotIter := slotIter - 1; end; end; end; end; function THLInfo.ReCalWin: Integer; // 返回找到窗口的个数 var hCurrentWindow, hChildCW: HWnd; tmpProcID: DWORD; szText: array [0..254] of char; WinRect: TRECT; tmpPrefix: WideString; MyWin: TWindowInfo; begin // 销毁原有的窗口信息 Self.Clear; hCurrentWindow := FindWindow('Progman', nil); hCurrentWindow := GetWindow(hCurrentWindow, GW_HWNDFIRST); While hCurrentWindow <> 0 Do Begin GetWindowThreadProcessId(hCurrentWindow, @tmpProcID); if tmpProcID = Self.ProcessId then begin GetWindowText(hCurrentWindow, @szText, 255); GetWindowRect(hCurrentWindow, WinRect); MyWin := TWindowInfo.Create; with MyWin do begin if IsWindowVisible(hCurrentWindow) then Prefix := '★' else Prefix := '☆'; Title := szText; Window := hCurrentWindow; ParentWin := nil; Top := WinRect.Top; Left := WinRect.Left; Bottom := WinRect.Bottom; Right := WinRect.Right; GetClassName(hCurrentWindow, @szText, 255); ClassName := szText; end; Self.Add(MyWin); hChildCW := GetWindow(MyWin.Window, GW_CHILD); tmpPrefix := ' '; if hChildCW <> 0 then DeepGetWindow(hChildCW, MyWin, tmpPrefix); end; hCurrentWindow := GetWindow(hCurrentWindow, GW_HWNDNEXT); end; Result := Self.Count; end; procedure THLInfo.SaveFormAttribute(const FormNameStr: Widestring; f: TForm); // 保存窗体属性 begin with TIniFile.Create(self.IniFileName) do // 窗体属性 try // 保存窗体位置 WriteInteger(FormNameStr, IDS_FormTopStr, f.Top); WriteInteger(FormNameStr, IDS_FormLeftStr, f.Left); finally Free; end; end; procedure THLInfo.SetItem(Index: Integer; const Value: TWindowInfo); begin inherited Items[Index] := Value; end; procedure THLInfo.SetUserName(const Value: WIdeString); begin FUserName := Value; with self.MainHotKeyInfo do begin IniFileName := Self.IniFileName; ReadHotKeyInfo; end; with self.WinInfoHotKeyInfo do begin IniFileName := Self.IniFileName; ReadHotKeyInfo; end; end; procedure THLInfo.WaitWindowDisAppearbyHwnd(const myHwnd: HWND); // 等待指定句柄的窗体消失 var tmp: Boolean; i: Integer; tmpWin: TWindowInfo; begin repeat tmp := True; ReCalWin; for i := 0 to Self.Count-1 do begin tmpWin := Self.Items[i]; if myHwnd = tmpWin.Window then begin tmp := False; Break; end; end; Sleep(100); until tmp; end; procedure THLInfo.WaitWindowDisAppearbyTitle(const SubTitle: WideString); // 等待指定标题的窗体消失 var tmp: Boolean; i: Integer; tmpWin: TWindowInfo; begin repeat tmp := True; ReCalWin; for i := 0 to Self.Count - 1 do begin tmpWin := self.Items[i]; if SubTitle = tmpWin.Title then begin tmp := False; Break; end; end; Sleep(100); until tmp; end; { THL_InfoList } constructor THLInfoList.Create; begin inherited; self.FSelectIndex := -1; end; function THLInfoList.GetCurrHLInfo: THLInfo; begin if (FSelectIndex > self.Count - 1) or (FSelectIndex < 0)then Result := nil else Result := self.Items[FSelectIndex]; end; function THLInfoList.GetItem(Index: Integer): THLInfo; begin Result := THLInfo(inherited Items[Index]); end; procedure THLInfoList.SetItem(Index: Integer; const Value: THLInfo); begin inherited Items[Index] := Value; end; procedure THLInfoList.SetSelectIndex(const Value: Integer); begin if (Value > self.Count - 1) or (Value < -1)then FSelectIndex := -1 else FSelectIndex := Value; end; { THLUser } constructor THLUser.Create(aObj: THLInfo); begin FHLInfo := aObj; end; { THotKeyInfo } constructor THotKeyInfo.Create(const InfoName: WideString); var tmpS: string; begin inherited Create(); self.FInfoName := InfoName; // 创建全局因子 tmpS := 'HLHL' + InfoName; FID := GlobalAddAtom(PChar(tmpS)) - $C000; end; destructor THotKeyInfo.Destroy; begin // 销毁全局因子 DeleteAtom(FID); inherited; end; procedure THotKeyInfo.ReadHotKeyInfo; // 装载热键,各人物独立 begin with TIniFile.Create(FIniFileName) do // 热键 try FVirtualKey := ReadInteger(FInfoName, IDS_VirtualKey, 0); FModifiers := ReadInteger(FInfoName, IDS_Modifiers, 0); FShowText := ReadString(FInfoName, IDS_ShowText, ''); finally Free; end; end; function THotKeyInfo.RegisterHotKey(FormHandle: THandle): Boolean; // 注册热键 begin Windows.RegisterHotkey(FormHandle, FID, FModifiers, FVirtualKey); end; function THotKeyInfo.UnRegisterHotKey(FormHandle: THandle): Boolean; // 注销热键 begin Windows.UnRegisterHotkey(FormHandle, FID); end; procedure THotKeyInfo.WriteHotKeyInfo; // 保存热键,各人物独立 begin with TIniFile.Create(self.FIniFileName) do // 热键 try WriteInteger(FInfoName, IDS_VirtualKey, FVirtualKey); WriteInteger(FInfoName, IDS_Modifiers, FModifiers); WriteString(FInfoName, IDS_ShowText, FShowText); finally Free; end; end; initialization HLInfoList := THLInfoList.Create; finalization HLInfoList.Free; end.
// PALETTE.PAS 2.0 // By Banshee // Built from Stucuk's PALETTE.PAS. unit Palette; interface uses Graphics, Windows, SysUtils, math, BasicMathsTypes; const TRANSPARENT = 0; C_MAX_BITS = 32; // works for both 24 and 32 bits. type TRGB = record r,g,b,a : byte; end; TPalette = class private NumBits : byte; FPalette : array of TColor; function ReadColour(_id : longword): TColor; procedure SetColour(_id : longword; _colour : TColor); function ReadRGB(_id : longword): TRGB; procedure SetRGB(_id : longword; _colour : TRGB); function ReadGL(_id : longword): TVector3f; procedure SetGL(_id: longword; _colour: TVector3f); function ReadGL4(_id : longword): TVector4f; procedure SetGL4(_id: longword; _colour: TVector4f); public // Constructors constructor Create; overload; procedure Initialize; constructor Create(const _Filename : string); overload; constructor Create(const _Palette : TPalette); overload; destructor Destroy; override; // Input and Output function LoadPalette(_Filename : string): boolean; procedure NewPalette(_NumBits : longword); // Gets function GetColourFromPalette(_colour : TColor): longword; // Copies procedure Assign(const _Palette : TPalette); // Misc procedure PaletteGradient(_StartNum,_EndNum :longword; _StartColour,_EndColour : TColor); procedure ChangeRemappable (_Colour : TColor); // Properties property Colour[_id : longword] : TColor read ReadColour write SetColour; default; property ColourRGB[_id: longword] : TRGB read ReadRGB write SetRGB; property ColourGL[_id: longword] : TVector3f read ReadGL write SetGL; property ColourGL4[_id: longword] : TVector4f read ReadGL4 write SetGL4; end; PPalette = ^TPalette; implementation uses Dialogs; // Constructors constructor TPalette.Create; begin Initialize; end; constructor TPalette.Create(const _Filename: string); begin if not LoadPalette(_Filename) then begin Initialize; end; end; constructor TPalette.Create(const _Palette : TPalette); begin Assign(_Palette); end; procedure TPalette.Initialize; begin NumBits := C_MAX_BITS; SetLength(FPalette,0); end; destructor TPalette.Destroy; begin SetLength(FPalette,0); inherited Destroy; end; // Input and Output function TPalette.LoadPalette(_Filename: string): boolean; var Palette_f : array [0..255] of record red,green,blue:byte; end; x: Integer; F : file; JASCFile : System.Text; signature,binaryvalue:string[10]; colours : Integer; R,G,B : byte; begin Result := false; if FileExists(_Filename) then begin try // open palette file AssignFile(F,_Filename); // VK set good file mode for file // This allow to run program from write-protected media FileMode := fmOpenRead; Reset(F,1); // file of byte if FileSize(F) = 768 then begin BlockRead(F,Palette_f,sizeof(Palette_f)); CloseFile(F); NumBits := 8; SetLength(FPalette,256); for x := 0 to 255 do FPalette[x] := RGB(Palette_f[x].red*4,Palette_f[x].green*4,Palette_f[x].blue*4); Result := true; end else // Try JASC begin CloseFile(F); AssignFile(JASCFile,_Filename); FileMode := fmOpenRead; Reset(JASCFile); // file of byte {Jasc format validation} readln(JASCFile,signature); {JASC-PAL} readln(JASCFile,binaryvalue); {0100} readln(JASCFile,colours); {256 (number of colours)} if (signature <> 'JASC-PAL') then MessageBox(0,'Error: JASC Signature Incorrect','Load Palette Error',0) else if ((binaryvalue <> '0100') or (colours <> 256)) then MessageBox(0,'Error: Palette Must Be 8Bit(256 Colours)','Load Palette Error',0) else Begin {Now, convert colour per colour} SetLength(FPalette, 256); NumBits := 8; for x:=0 to 255 do begin {read source info} readln(JASCFile,R,G,B); {Note: No colour conversion needed since JASC-PAL colours are the same as VXLPalette ones} Palette_f[x].red := r; Palette_f[x].green := g; Palette_f[x].blue := b; FPalette[x] := RGB(Palette_f[x].red,Palette_f[x].green,Palette_f[x].blue); end; Result := true; end; CloseFile(JASCFile); end; except on E : EInOutError do MessageDlg('Error: ' + E.Message + Char($0A) + _Filename, mtError, [mbOK], 0); end; end; end; procedure TPalette.NewPalette(_NumBits : longword); var x : longword; Size : single; Interval : real; begin // First, we unload the existing palette. SetLength(FPalette,0); NumBits := _NumBits; if _NumBits = 8 then begin SetLength(FPalette,256); for x := 0 to 255 do FPalette[x] := RGB(255-x,255-x,255-x); end else if _NumBits <> C_MAX_BITS then begin Size := Power(2,_NumBits); SetLength(FPalette,Round(Size)); Interval := 16777215 / Size; for x := Low(FPalette) to High(FPalette) do begin FPalette[x] := Round(x * Interval) and $00FFFFFF; end; end; end; // Gets function TPalette.ReadColour(_id: Cardinal): TColor; begin if NumBits = C_MAX_BITS then begin Result := _id; end else if NumBits = 8 then begin if (_id < 256) then Result := FPalette[_id] else Result := FPalette[0]; end else Result := _id; end; function TPalette.ReadRGB(_id : longword): TRGB; begin if NumBits = C_MAX_BITS then begin Result.r := Byte(_id); Result.g := Byte(_id shr 8); Result.b := Byte(_id shr 16); Result.a := Byte(_id shr 24); end else if NumBits = 8 then begin if (_id < 256) then begin Result.r := Byte(FPalette[_id]); Result.g := Byte(FPalette[_id] shr 8); Result.b := Byte(FPalette[_id] shr 16); Result.a := Byte(FPalette[_id] shr 24); end else begin Result.r := Byte(FPalette[0]); Result.g := Byte(FPalette[0] shr 8); Result.b := Byte(FPalette[0] shr 16); Result.a := Byte(FPalette[0] shr 24); end; end else begin Result.r := Byte(_id); Result.g := Byte(_id shr 8); Result.b := Byte(_id shr 16); Result.a := Byte(_id shr 24); end; end; function TPalette.ReadGL(_id : longword): TVector3f; begin if NumBits = C_MAX_BITS then begin Result.X := Byte(_id and $FF) / 255; Result.Y := Byte((_id shr 8) and $FF) / 255; Result.Z := Byte((_id shr 16) and $FF) / 255; end else if NumBits = 8 then begin if (_id < 256) then begin Result.X := Byte(FPalette[_id] and $FF) / 255; Result.Y := Byte((FPalette[_id] shr 8) and $FF) / 255; Result.Z := Byte((FPalette[_id] shr 16) and $FF) / 255; end else begin Result.X := Byte(FPalette[0] and $FF) / 255; Result.Y := Byte((FPalette[0] shr 8) and $FF) / 255; Result.Z := Byte((FPalette[0] shr 16) and $FF) / 255; end; end else begin Result.X := Byte(_id and $FF) / 255; Result.Y := Byte((_id shr 8) and $FF) / 255; Result.Z := Byte((_id shr 16) and $FF) / 255; end; end; function TPalette.ReadGL4(_id : longword): TVector4f; begin if NumBits = C_MAX_BITS then begin Result.X := Byte(_id and $FF) / 255; Result.Y := Byte((_id shr 8) and $FF) / 255; Result.Z := Byte((_id shr 16) and $FF) / 255; Result.W := Byte(_id shr 24) / 255; end else if NumBits = 8 then begin if (_id < 256) then begin Result.X := Byte(FPalette[_id] and $FF) / 255; Result.Y := Byte((FPalette[_id] shr 8) and $FF) / 255; Result.Z := Byte((FPalette[_id] shr 16) and $FF) / 255; Result.W := Byte(FPalette[_id] shr 24) / 255; end else begin Result.X := Byte(FPalette[0] and $FF) / 255; Result.Y := Byte((FPalette[0] shr 8) and $FF) / 255; Result.Z := Byte((FPalette[0] shr 16) and $FF) / 255; Result.W := Byte(FPalette[0] shr 24) / 255; end; end else begin Result.X := Byte(_id and $FF) / 255; Result.Y := Byte((_id shr 8) and $FF) / 255; Result.Z := Byte((_id shr 16) and $FF) / 255; Result.W := Byte(_id shr 24) / 255; end; end; function TPalette.GetColourFromPalette(_colour : TColor): longword; var colour : integer; r,g,b,rx,gx,bx : byte; // (r,g,b) of the original colour and (rx,gx,bx) current diff,min_diff : real; // Current difference and Minimum difference x : longword; // The colour structure related ones. rs,gs,bs,rxs,bxs,gxs : real; diffs,min_diffs : real; top : byte; begin if High(FPalette) >= 0 then begin // Get the original colours. r := GetRValue(_Colour); g := GetGValue(_Colour); b := GetBValue(_Colour); // Reset min_diff and colour min_diff := 9999999; min_diffs := 999999; colour := 0; // Prepare the colour structure part. top := max(r,max(g,b)); if top <> 0 then begin rs := r / top; gs := g / top; bs := b / top; end else begin rs := 1; gs := 1; bs := 1; end; for x := Low(FPalette) to High(FPalette) do begin rx := GetRValue(FPalette[x]); gx := GetGValue(FPalette[x]); bx := GetBValue(FPalette[x]); if (r = rx) and (g = gx) and (b = bx) then begin Result := x; exit; end; diff := sqrt(((r - rx) * (r - rx)) + ((g - gx) * (g - gx)) + ((b - bx) * (b - bx))); if diff < min_diff then begin colour := x; min_diff := diff; // Setup colour structure comparison. top := max(rx,max(gx,bx)); if top <> 0 then begin rxs := rx / top; gxs := gx / top; bxs := bx / top; end else begin rxs := 1; gxs := 1; bxs := 1; end; min_diffs := sqrt(((rs - rxs) * (rs - rxs)) + ((gs - gxs) * (gs - gxs)) + ((bs - bxs) * (bs - bxs))); end else if diff = min_diff then begin // Now, here comes the challenge, based on Structuralis algorithm // from OS SHP Builder top := max(rx,max(gx,bx)); if top <> 0 then begin rxs := rx / top; gxs := gx / top; bxs := bx / top; end else begin rxs := 1; gxs := 1; bxs := 1; end; diffs := sqrt(((rs - rxs) * (rs - rxs)) + ((gs - gxs) * (gs - gxs)) + ((bs - bxs) * (bs - bxs))); if diffs < min_diffs then begin min_diffs := diffs; colour := x; end; end; end; Result := colour; end else begin Result := _colour; end end; // Sets procedure TPalette.SetColour(_id: longword; _colour: TColor); begin if NumBits <> C_MAX_BITS then begin if (Integer(_id) <= High(FPalette)) then begin FPalette[_id] := _colour; end; end; end; procedure TPalette.SetRGB(_id: longword; _colour: TRGB); begin if NumBits <> C_MAX_BITS then begin if (Integer(_id) <= High(FPalette)) then begin FPalette[_id] := (_colour.r or (_colour.g shl 8) or (_colour.b shl 16) or (_colour.a shl 24)); end; end; end; procedure TPalette.SetGL(_id: longword; _colour: TVector3f); begin if NumBits <> C_MAX_BITS then begin if (Integer(_id) <= High(FPalette)) then begin FPalette[_id] := (Round(_colour.X * 255) or (Round(_colour.Y * 255) shl 8) or (Round(_colour.Z * 255) shl 16)); end; end; end; procedure TPalette.SetGL4(_id: longword; _colour: TVector4f); begin if NumBits <> C_MAX_BITS then begin if (Integer(_id) <= High(FPalette)) then begin FPalette[_id] := (Round(_colour.X * 255) or (Round(_colour.Y * 255) shl 8) or (Round(_colour.Z * 255) shl 16) or (Round(_colour.W * 255) shl 24)); end; end; end; // Copies procedure TPalette.Assign(const _Palette: TPalette); var i : longword; begin NumBits := _Palette.NumBits; if High(_Palette.FPalette) > 0 then begin SetLength(FPalette,High(_Palette.FPalette)+1); for i := Low(FPalette) to High(FPalette) do begin FPalette[i] := _Palette.FPalette[i]; end; end else SetLength(FPalette,0); end; // Misc procedure TPalette.PaletteGradient(_StartNum,_EndNum :longword; _StartColour,_EndColour : TColor); var X,Distance : integer; Temp : longword; StepR,StepG,StepB : Real; R,G,B : integer; Rx,Gx,Bx : real; begin // Let's catch the errors. // 24bits has no palette. if NumBits <> 8 then exit; // For optimization purposes, we make sure _EndNum is the highest value. if _StartNum > _EndNum then begin Temp := _StartNum; _StartNum := _EndNum; _EndNum := Temp; end; // Catch if it is at the palette's scope. if (_EndNum > High(FPalette)) then exit; Distance := _EndNum - _StartNum; if Distance = 0 then // Catch the Divison By 0's begin MessageBox(0,'Error: PaletteGradient Needs Start Num And '+#13+#13+'End Num To Be Different Numbers','PaletteGradient Input Error',0); Exit; end; // Now, we start the procedure. StepR := (GetRValue(_EndColour) - GetRValue(_StartColour)) / Distance; StepG := (GetGValue(_EndColour) - GetGValue(_StartColour)) / Distance; StepB := (GetBValue(_EndColour) - GetBValue(_StartColour)) / Distance; R := GetRValue(_StartColour); G := GetGValue(_StartColour); B := GetBValue(_StartColour); Rx := R; Bx := B; Gx := G; for x := _StartNum to _EndNum do begin if Round(Rx + StepR) < 0 then R := 0 else begin R := Round(Rx + StepR); Rx := Rx + StepR; end; if Round(Gx + StepG) < 0 then G := 0 else begin G := Round(Gx + StepG); Gx := Gx + StepG; end; if Round(Bx + StepB) < 0 then B := 0 else begin B := Round(Bx + StepB); Bx := Bx + StepB; end; if R > 255 then R := 255; if G > 255 then G := 255; if B > 255 then B := 255; FPalette[x] := RGB(R,G,B); end; end; // Importing and adapting change remappable from OS SHP Builder. procedure TPalette.ChangeRemappable (_Colour : TColor); const RedMultiples : array[16..31] of byte = ($FC, $EC, $DC, $D0, $C0, $B0, $A4, $94, $84, $78, $68, $58, $4C, $3C, $2C, $20); var rmult,gmult,bmult: single; x : byte; begin if NumBits <> 8 then exit; rmult := GetRValue(_Colour) / 255; gmult := GetGValue(_Colour) / 255; bmult := GetBValue(_Colour) / 255; // Generate Remmapable colours for x := 16 to 31 do begin FPalette[x]:= RGB(Round(rmult * RedMultiples[x]),Round(gmult * RedMultiples[x]),Round(bmult * RedMultiples[x])); end; end; end.
unit ufrmResetCashier; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, uConstanta, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, ComCtrls, dxCore, cxDateUtils, Menus, System.Actions, ActnList, ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC, Datasnap.DBClient, System.Generics.Collections, uModApp, uModBeginningBalance; type TfrmResetCashier = class(TfrmMasterBrowse) pnl1: TPanel; pnl3: TPanel; btnResetCashier: TcxButton; btnUnResetCashier: TcxButton; actResetCashier: TAction; actUnResetCashier: TAction; edtShift: TcxTextEdit; lblClearAll: TcxLabel; lblCheckAll: TcxLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actResetCashierExecute(Sender: TObject); procedure actUnResetCashierExecute(Sender: TObject); procedure edtShiftEnter(Sender: TObject); procedure lblCheckAllClick(Sender: TObject); procedure lblClearAllClick(Sender: TObject); procedure edtShiftExit(Sender: TObject); procedure edtShiftKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lblCheckAllMouseEnter(Sender: TObject); procedure lblCheckAllMouseLeave(Sender: TObject); procedure lblClearAllMouseEnter(Sender: TObject); procedure lblClearAllMouseLeave(Sender: TObject); procedure dtAkhirFilterPropertiesEditValueChanged(Sender: TObject); private // dataBeginningBlnc: TDataSet; FCDS: TClientDataSet; procedure ChangeResetStatus(AReset: string); function IsShiftExist: Boolean; // datacashier: TResultDataSet; procedure ParseHeaderGrid; procedure ParseDataGrid(); procedure WM_STORE_MESSAGE_Handle(var msg: TMessage); message WM_STORE_MESSAGE; property CDS: TClientDataSet read FCDS write FCDS; public procedure RefreshData; override; end; var frmResetCashier: TfrmResetCashier; implementation {$R *.dfm} uses uTSCommonDlg, uRetnoUnit, uAppUtils, uModShift, uDMClient, uDBUtils, uDXUtils; const { POS CODE CASHIER NAME TRANSACTION NO LAST COUNTER NO LAST TRANSACTION NO FINAL PAYMENT IS RESET } _KolCheck : Integer = 0; _KolPosCode : Integer = 1; _KolCashier : Integer = 2; _kolTrans : Integer = 3; _kolLCounter : Integer = 4; _kolLTransNo : Integer = 5; _kolFPay : Integer = 6; _kolStatusFP : Integer = 7; _KolisReset : Integer = 8; _kolClosed : Integer = 9; _kolBalId : Integer = 10; _kolPosIsAct : Integer = 11; _kolPosIp : Integer = 12; _kolPosTerml : Integer = 13; _colCount : Integer = 9; _rowCount : Integer = 2; _fixedRow : Integer = 1; procedure TfrmResetCashier.FormCreate(Sender: TObject); begin inherited; lblHeader.Caption := 'RESET CASHIER'; end; procedure TfrmResetCashier.FormDestroy(Sender: TObject); begin inherited; frmResetCashier := nil; end; procedure TfrmResetCashier.ParseDataGrid; //var // intI: Integer; // aIsReset: Boolean; // ssQL: string; // tempTransc: string; begin // ssQL := 'SELECT SP.*, FP.FINPAYMENT_GRAND_TOTAL, AU.USR_FULLNAME,' // + ' BB.BALANCE_ID, BB.BALANCE_STATUS, S.SHIFT_NAME, FP.FINPAYMENT_BALANCE_ID' // + ' FROM SETUPPOS SP' // + ' INNER JOIN BEGINNING_BALANCE BB ON BB.BALANCE_SETUPPOS_ID = SP.SETUPPOS_ID' // + ' AND BB.BALANCE_SETUPPOS_UNT_ID = SP.SETUPPOS_UNT_ID' // + ' INNER JOIN SHIFT S ON S.SHIFT_ID = BB.BALANCE_SHIFT_ID' // + ' AND S.SHIFT_UNT_ID = BB.BALANCE_SHIFT_UNT_ID' // + ' LEFT JOIN FINAL_PAYMENT FP ON FP.FINPAYMENT_BALANCE_ID = BB.BALANCE_ID' // + ' AND FP.FINPAYMENT_BALANCE_UNT_ID = BB.BALANCE_UNT_ID' // + ' LEFT JOIN AUT$USER AU ON AU.USR_ID = BB.BALANCE_USR_ID' // + ' AND AU.USR_UNT_ID=BB.BALANCE_USR_UNT_ID' // + ' WHERE BB.BALANCE_SHIFT_DATE = '+ TAppUtils.QuotD(dtActivate.Date) // + ' AND BB.BALANCE_UNT_ID = '+ IntToStr(MasterNewUnit) //// + ' and BB.BALANCE_STATUS = ''CLOSE''' //// + ' and sp.SETUPPOS_IS_RESET = 0' // + ' ORDER BY SP.SETUPPOS_TERMINAL_CODE'; { ParseHeaderGrid; with cOpenQuery(ssQL) do begin try //initiate intI := strgGrid.FixedRows; while not Eof do begin if intI > strgGrid.FixedRows then strgGrid.AddRow; strgGrid.AddCheckBox(_KolCheck,intI,False,False); strgGrid.Cells[_KolPosCode,intI] := FieldByName('SETUPPOS_TERMINAL_CODE').AsString + ' (SHIFT ' + FieldByName('SHIFT_NAME').AsString + ')'; strgGrid.Cells[_KolCashier,intI] := FieldByName('USR_FULLNAME').AsString; strgGrid.Cells[_kolTrans,intI] := FieldByName('SETUPPOS_NO_TRANSAKSI').AsString; strgGrid.Cells[_kolLCounter,intI]:= FieldByName('SETUPPOS_COUNTER_NO').AsString; //========format transc no.============================================= tempTransc := strgGrid.Cells[_kolTrans,intI]; if StrToInt(strgGrid.Cells[_kolLCounter,intI]) < 10 then SetLength(tempTransc,11) else if StrToInt(strgGrid.Cells[_kolLCounter,intI]) < 100 then SetLength(tempTransc,10) else if StrToInt(strgGrid.Cells[_kolLCounter,intI]) < 1000 then SetLength(tempTransc,9) else SetLength(tempTransc,8); //========format transc no.============================================= strgGrid.Cells[_kolLTransNo,intI] := tempTransc + strgGrid.Cells[_kolLCounter,intI]; strgGrid.Cells[_kolFPay,intI] := FieldByName('FINPAYMENT_GRAND_TOTAL').AsString; strgGrid.Cells[_kolStatusFP,intI] := FieldByName('BALANCE_STATUS').AsString; if FieldByName('SETUPPOS_IS_RESET').AsInteger = 1 then aIsReset := True else aIsReset := False; strgGrid.AddCheckBox(_KolisReset,intI,aIsReset,False); strgGrid.Cells[_kolBalId,intI] := FieldByName('BALANCE_ID').AsString; strgGrid.Cells[_kolPosIsAct,intI] := IntToStr(FieldByName('SETUPPOS_IS_ACTIVE').AsInteger); strgGrid.Cells[_kolPosIp,intI] := FieldByName('SETUPPOS_IP').AsString; strgGrid.Cells[_kolPosTerml,intI] := FieldByName('SETUPPOS_TERMINAL_CODE').AsString; strgGrid.Cells[_kolClosed,intI] := IntToStr(FieldByName('FINPAYMENT_BALANCE_ID').AsInteger); Inc(intI); Next; end; finally Free; end; end; strgGrid.AutoSize := true; } end; procedure TfrmResetCashier.ParseHeaderGrid; begin { with strgGrid do begin Clear; ColCount := _colCount;//12; RowCount := _rowCount; FixedRows := _fixedRow; Cells[_KolCheck,0] := ' '; Cells[_KolPosCode,0] := 'POS CODE'; Cells[_KolCashier,0] := 'CASHIER NAME'; Cells[_kolTrans,0] := 'TRANSACTION NO.'; Cells[_kolLCounter,0] := 'LAST COUNTER NO.'; Cells[_kolLTransNo,0] := 'LAST TRANSACTION NO.'; Cells[_kolFPay,0] := 'FINAL PAYMENT'; Cells[_kolStatusFP,0] := 'STATUS FPAY.'; Cells[_KolisReset,0] := 'IS RESET'; Cells[_kolClosed,0] := 'IS CLOSED'; Autosize := true; end; } end; procedure TfrmResetCashier.actResetCashierExecute(Sender: TObject); //var // chkReset: Boolean; // cKey: Char; // iResetCount: Integer; // isSuccess: boolean; // PosIP: string; // PosCode: string; // chkStatus: Boolean; // i: Integer; begin { if not IsValidDateKarenaEOD(MasterNewUnit.ID,dtActivate.Date,FMasterIsStore) then Exit; if (strgGrid.RowCount = _rowCount) and (strgGrid.Cells[_KolPosCode,_fixedRow] = '') then Exit; //tidak ada data if CommonDlg.Confirm(CONF_RESET_CASHIER) = mrYes then begin isSuccess := False; with strgGrid, frmMain do begin PosIP := '0'; PosCode := '0'; iResetCount := 0; for i:=_fixedRow to RowCount-1 do begin GetCheckBoxState(_KolCheck,i,chkStatus); GetCheckBoxState(_KolisReset,i,chkReset); //if(chkStatue)and(strgGrid.Cells[9,i]='0')then if (chkStatus) and (chkReset = False) then begin Inc(iResetCount); if(strgGrid.Cells[_kolStatusFP,i] = 'OPEN')then // belum melakukan final payment begin if(Cells[_kolPosIp,i] = '')then PosIP:= '0.0.0.0' else PosIP:= Cells[_kolPosIp,i]; if(Cells[_kolPosTerml,i] = '')then PosCode:= '-' else PosCode:= Cells[_kolPosTerml,i]; isSuccess := False; with TBeginningBalance.Create(Self) do begin if LoadByID(StrToInt(Cells[_kolBalId,i]),MasterNewUnit.ID) then begin UpdateStatus('CLOSE'); isSuccess := SaveToDB; end; end; if not isSuccess then Break; end; end; end; if iResetCount > 0 then begin if (isSuccess) then begin cCommitTrans; CommonDlg.ShowMessage('Reset cashier successfully.'); cKey := Chr(VK_RETURN); edtShiftKeyPress(nil, cKey) end else begin cRollbackTrans; CommonDlg.ShowError('Reset cashier failed.'); end; end; end; end; } if (CommonDlg.Confirm(CONF_RESET_CASHIER) = mrYes) then begin ChangeResetStatus('CLOSE'); end; end; procedure TfrmResetCashier.actUnResetCashierExecute(Sender: TObject); //var // chkReset: Boolean; // chkStatus: Boolean; // cKey: Char; // PosIP: string; // PosCode: string; // i: Integer; begin { if not IsValidDateKarenaEOD(MasterNewUnit.ID, dtActivate.Date, FMasterIsStore) then Exit; if (strgGrid.RowCount = _rowCount) and (strgGrid.Cells[_KolPosCode,_fixedRow] = '') then Exit; //tidak ada data if (strgGrid.Cells[_kolStatusFP, strgGrid.Row] = 'OPEN') then // status cashier begin CommonDlg.ShowMessage('Cashier is OPEN'); Exit; end; if (strgGrid.Ints[_kolClosed, strgGrid.Row] <> 0) then // belum closing payment begin CommonDlg.ShowMessage('Cashier was already CLOSING PAYMENT'); Exit; end; strgGrid.GetCheckBoxState(_KolCheck, strgGrid.Row, chkStatus); strgGrid.GetCheckBoxState(_KolisReset, strgGrid.Row, chkReset); if (not chkStatus) and (chkReset = False) then begin if CommonDlg.Confirm(CONF_UNRESET_CASHIER) = mrYes then begin with strgGrid, frmMain do begin PosIP := '0'; PosCode := '0'; i := Row; if(Cells[_kolPosIp,i] = '')then PosIP := '0.0.0.0' else PosIP := Cells[_kolPosIp,i]; if(Cells[_kolPosTerml,i] = '')then PosCode := '-' else PosCode := Cells[_kolPosTerml,i]; with TBeginningBalance.Create(Self) do begin if LoadByID(StrToInt(Cells[_kolBalId,i]), MasterNewUnit.ID) then begin UpdateStatus('OPEN'); if SaveToDB then begin cCommitTrans; CommonDlg.ShowMessage('UnReset cashier successfully.'); cKey := Chr(VK_RETURN); edtShiftKeyPress(nil, cKey) end else begin cRollbackTrans; CommonDlg.ShowError('UnReset cashier failed.'); end; end; end; end; end; end else begin CommonDlg.ShowMessage('POS was reset'); Exit; end; } if (CommonDlg.Confirm(CONF_UNRESET_CASHIER) = mrYes) then begin ChangeResetStatus('OPEN'); end; end; procedure TfrmResetCashier.edtShiftEnter(Sender: TObject); begin edtShift.SelectAll; end; procedure TfrmResetCashier.lblCheckAllClick(Sender: TObject); var i: integer; begin {with strgGrid do begin for i:= FixedRows to RowCount-1 do begin if Cells[_kolStatusFP, i] = 'OPEN' then SetCheckBoxState(_KolCheck,i,true); end; end; } CDS.First; while not CDS.Eof do begin CDS.Edit; CDS.FieldByName('CHECK').AsBoolean := True; CDS.Post; CDS.Next; end; end; procedure TfrmResetCashier.lblClearAllClick(Sender: TObject); var i: integer; begin {with strgGrid do begin for i:=FixedRows to RowCount-1 do begin SetCheckBoxState(_KolCheck,i,false); end; end; } CDS.First; while not CDS.Eof do begin CDS.Edit; CDS.FieldByName('CHECK').AsBoolean := False; CDS.Post; CDS.Next; end; end; procedure TfrmResetCashier.edtShiftExit(Sender: TObject); begin inherited; RefreshData; end; procedure TfrmResetCashier.edtShiftKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key=(Chr(VK_RETURN)) then RefreshData; end; procedure TfrmResetCashier.dtAkhirFilterPropertiesEditValueChanged( Sender: TObject); begin inherited; RefreshData; end; procedure TfrmResetCashier.WM_STORE_MESSAGE_Handle(var msg: TMessage); begin case msg.WParam of STORE_REFRESH_RESET_CASHIER: ParseDataGrid; end; end; procedure TfrmResetCashier.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (ssctrl in Shift) and (Key = VK_RETURN) then actResetCashierExecute(Self) else if (ssShift in Shift) and (Key = VK_RETURN) then actUnResetCashierExecute(Self); end; procedure TfrmResetCashier.ChangeResetStatus(AReset: string); var lListBalance: TObjectList<TModApp>; lModBalance: TModBeginningBalance; begin lListBalance := TObjectList<TModApp>.Create(); try CDS.First; while not CDS.Eof do begin if CDS.FieldByName('CHECK').AsBoolean = True then begin lModBalance := DMClient.CrudClient.Retrieve(TModBeginningBalance.ClassName, CDS.FieldByName('BEGINNING_BALANCE_ID').AsString) as TModBeginningBalance; if lModBalance.BALANCE_STATUS <> AReset then begin lModBalance.BALANCE_STATUS := AReset; lListBalance.Add(lModBalance); end; end; CDS.Next; end; if DMClient.CrudClient.SaveBatch(lListBalance) then begin FreeAndNil(lListBalance); TAppUtils.Information(CONF_EDIT_SUCCESSFULLY, False); RefreshData; end; except TAppUtils.Error(ER_UPDATE_FAILED); raise; end; end; function TfrmResetCashier.IsShiftExist: Boolean; var lModShift: TModShift; begin Result := False; lModShift := TModShift.Create; try lModShift := DMClient.CrudClient.RetrieveByCode(TModShift.ClassName, edtShift.EditValue) as TModShift; if lModShift.ID = '' then begin TAppUtils.Error(ER_SHIFT_NOT_FOUND); edtShift.SetFocus; end else begin Result := True; end; finally lModShift.Free; end; end; procedure TfrmResetCashier.lblCheckAllMouseEnter(Sender: TObject); begin inherited; lblCheckAll.Style.TextStyle := [fsUnderline]; end; procedure TfrmResetCashier.lblCheckAllMouseLeave(Sender: TObject); begin inherited; lblCheckAll.Style.TextStyle := []; end; procedure TfrmResetCashier.lblClearAllMouseEnter(Sender: TObject); begin inherited; lblClearAll.Style.TextStyle := [fsUnderline]; end; procedure TfrmResetCashier.lblClearAllMouseLeave(Sender: TObject); begin inherited; lblClearAll.Style.TextStyle := []; end; procedure TfrmResetCashier.RefreshData; begin inherited; if edtShift.Text = '' then Exit else if not IsShiftExist then Exit; if Assigned(FCDS) then FreeAndNil(FCDS); FCDS := TDBUtils.DSToCDS(DMClient.DSProviderClient.ResetCashier_GetDSOverview(dtAkhirFilter.Date, edtShift.EditValue, TRetno.UnitStore.ID) ,Self ); cxGridView.LoadFromCDS(CDS); cxGridView.SetVisibleColumns(['BEGINNING_BALANCE_ID','FINAL_PAYMENT_ID','SHIFT_NAME','BALANCE_SHIFT_DATE','AUT$UNIT_ID'],False); cxGridView.SetReadOnlyAllColumns(True); cxGridView.SetReadOnlyColumns(['CHECK'],False); end; end.
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Messaging, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation, System.Actions, FMX.ActnList, FMX.Edit, FMX.Media, ZXing.BarcodeFormat, ZXing.ReadResult, ZXing.ScanManager, FMX.Platform, FMX.Layouts, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, FMX.Barcode.DROID, FMX.Barcode.IOS, FMX.StdActns, FMX.MediaLibrary.Actions; type TMainForm = class(TForm) ToolBar1: TToolBar; imgCamera: TImage; butStart: TButton; butStop: TButton; butSend: TButton; CameraComponent1: TCameraComponent; TetheringManager1: TTetheringManager; TetheringAppProfile1: TTetheringAppProfile; timAutoConnect: TTimer; StyleBook1: TStyleBook; LayoutBottom: TLayout; lblScanStatus: TLabel; edtResult: TEdit; chkLibrary: TCheckBox; butShare: TButton; ActionList1: TActionList; ShowShareSheetAction1: TShowShareSheetAction; chkAutoSend: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure butStartClick(Sender: TObject); procedure butStopClick(Sender: TObject); procedure CameraComponent1SampleBufferReady(Sender: TObject; const ATime: TMediaTime); procedure timAutoConnectTimer(Sender: TObject); procedure TetheringManager1EndAutoConnect(Sender: TObject); procedure butSendClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure edtResultChange(Sender: TObject); procedure ShowShareSheetAction1BeforeExecute(Sender: TObject); private { Private declarations } // for the external library fInProgress: boolean; fFMXBarcode: TFMXBarcode; // for the native zxing.delphi library fScanManager: TScanManager; fScanInProgress: Boolean; fFrameTake: Integer; procedure GetImage(); function AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; // for the external library procedure OnFMXBarcodeResult(Sender: TObject; ABarcode: string); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} {$R *.NmXhdpiPh.fmx ANDROID} uses System.Threading, FMX.VirtualKeyboard; function TMainForm.AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; begin Result := False; case AAppEvent of TApplicationEvent.WillBecomeInactive, TApplicationEvent.EnteredBackground, TApplicationEvent.WillTerminate: begin CameraComponent1.Active := False; Result := True; end; end; end; procedure TMainForm.butSendClick(Sender: TObject); begin TetheringAppProfile1.SendString(TetheringManager1.RemoteProfiles.First, 'Barcode', edtResult.Text); end; procedure TMainForm.butStartClick(Sender: TObject); begin if chkLibrary.IsChecked then begin fInProgress := True; if Assigned(fFMXBarcode) then fFMXBarcode.Free; fFMXBarcode := TFMXBarcode.Create(Application); fFMXBarcode.OnGetResult := OnFMXBarcodeResult; fFMXBarcode.Show(False); end else begin if Assigned(fScanManager) then fScanManager.Free; fScanManager := TScanManager.Create(TBarcodeFormat.Auto, nil); CameraComponent1.Quality := FMX.Media.TVideoCaptureQuality.MediumQuality; CameraComponent1.Active := False; CameraComponent1.Kind := FMX.Media.TCameraKind.BackCamera; CameraComponent1.FocusMode := FMX.Media.TFocusMode.ContinuousAutoFocus; CameraComponent1.Active := True; end; lblScanStatus.Text := ''; edtResult.Text := ''; end; procedure TMainForm.butStopClick(Sender: TObject); begin CameraComponent1.Active := False; end; procedure TMainForm.CameraComponent1SampleBufferReady(Sender: TObject; const ATime: TMediaTime); begin TThread.Synchronize(TThread.CurrentThread, GetImage); end; procedure TMainForm.edtResultChange(Sender: TObject); begin ShowShareSheetAction1.Enabled := not edtResult.Text.IsEmpty; if not edtResult.Text.IsEmpty then if butSend.Enabled then butSendClick(Self); end; procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := not fInProgress; end; procedure TMainForm.FormCreate(Sender: TObject); var AppEventSvc: IFMXApplicationEventService; begin if TPlatformServices.Current.SupportsPlatformService (IFMXApplicationEventService, IInterface(AppEventSvc)) then begin AppEventSvc.SetApplicationEventHandler(AppEvent); end; fFrameTake := 0; fInProgress := False; end; procedure TMainForm.FormDestroy(Sender: TObject); begin fScanManager.Free; fFMXBarcode.Free; end; procedure TMainForm.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); var FService: IFMXVirtualKeyboardService; begin if Key = vkHardwareBack then begin TPlatformServices.Current.SupportsPlatformService (IFMXVirtualKeyboardService, IInterface(FService)); if (FService <> nil) and (TVirtualKeyboardState.Visible in FService.VirtualKeyBoardState) then begin // Back button pressed, keyboard visible, so do nothing... end else begin // Back button pressed, keyboard not visible or not supported on this platform if fInProgress then begin Key := 0; fInProgress := False; end; end; end; end; procedure TMainForm.GetImage; var scanBitmap: TBitmap; ReadResult: TReadResult; begin CameraComponent1.SampleBufferToBitmap(imgCamera.Bitmap, True); if (fScanInProgress) then begin exit; end; { This code will take every 2 frame. } inc(fFrameTake); if (fFrameTake mod 2 <> 0) then begin exit; end; scanBitmap := TBitmap.Create(); scanBitmap.Assign(imgCamera.Bitmap); ReadResult := nil; TTask.Run( procedure begin try fScanInProgress := True; try ReadResult := fScanManager.Scan(scanBitmap); except on E: Exception do begin TThread.Synchronize(nil, procedure begin lblScanStatus.Text := E.Message; end); exit; end; end; TThread.Synchronize(nil, procedure begin if (length(lblScanStatus.Text) > 10) then begin lblScanStatus.Text := '*'; end; lblScanStatus.Text := lblScanStatus.Text + '*'; if (ReadResult <> nil) then begin edtResult.Text := ReadResult.Text; end; end); finally ReadResult.Free; scanBitmap.Free; fScanInProgress := False; end; end); end; procedure TMainForm.OnFMXBarcodeResult(Sender: TObject; ABarcode: string); begin edtResult.Text := ABarcode; if (ABarcode <> '') and fInProgress then fInProgress := False; end; procedure TMainForm.ShowShareSheetAction1BeforeExecute(Sender: TObject); begin ShowShareSheetAction1.TextMessage := edtResult.Text; end; procedure TMainForm.TetheringManager1EndAutoConnect(Sender: TObject); begin try butSend.Enabled := TetheringAppProfile1.Connect (TetheringManager1.RemoteProfiles.First); except on E: Exception do butSend.Enabled := False; end; end; procedure TMainForm.timAutoConnectTimer(Sender: TObject); begin if not butSend.Enabled then TetheringManager1.AutoConnect; end; end.
unit libFilmFile; interface uses sysutils; const STRSIZE = 127; type TFilm = record name, genre, mainActor: string[STRSIZE]; year, rating: integer; constructor create(_name, _genre, _mainActor: string; _year, _rating: integer); end; type TFilmArray = array of TFilm; type TFilmFile = class num: integer; dataFile: file of TFilm; constructor create(filename: string); function update: TFilmArray; procedure add(_new: TFilm); procedure delete(_index: integer); end; implementation constructor TFilm.create(_name: string; _genre: string; _mainActor: string; _year: Integer; _rating: Integer); begin name := _name; genre := _genre; mainActor := _mainActor; year := _year; rating := _rating; end; constructor TFilmFile.create(filename: string); begin assignfile(dataFile, filename); if not sysutils.fileexists(filename) then begin rewrite(dataFile); closefile(dataFile); end; end; function TFilmFile.update: TFilmArray; var temp: TFilmArray; t: TFilm; begin reset(dataFile); setlength(temp, 0); num := 0; while not eof(dataFile) do begin setlength(temp, num + 1); read(dataFile, temp[num]); inc(num); end; result := temp; closefile(dataFile); end; procedure TFilmFile.add(_new: TFilm); var temp: TFilm; i, ins: integer; begin reset(dataFile); if eof(dataFile) then write(dataFile, _new) else begin read(dataFile, temp); while ((not eof(dataFile)) and (compareStr(temp.name, _new.name) < 0)) do read(dataFile, temp); ins := filepos(dataFile); if temp.name > _new.name then begin dec(ins); for i := num - 1 downto ins do begin seek(dataFile, i); read(dataFile, temp); seek(dataFile, i + 1); write(dataFile, temp); end; seek(dataFile, ins); end; write(dataFile, _new); end; closefile(dataFile); end; procedure TFilmFile.delete(_index: integer); var temp: TFilm; begin reset(dataFile); seek(dataFile, _index + 1); while not eof(dataFile) do begin read(dataFile, temp); seek(dataFile, filepos(dataFile) - 2); write(dataFile, temp); seek(dataFile, filepos(dataFile) + 1); end; seek(dataFile, num - 1); truncate(dataFile); closefile(dataFile); end; end.
unit pkcs11_slot; interface uses pkcs11t, pkcs11_api, pkcs11_token; type TPKCS11Slot = class(TPKCS11API) private FSlotID: integer; protected function GetDescription(): string; function GetManufacturerID(): string; function GetFlags(): CK_FLAGS; function GetHardwareVersion(): CK_VERSION; function GetFirmwareVersion(): CK_VERSION; // Flags... function GetTokenPresent(): boolean; function GetRemovableDevice(): boolean; function GetHWSlot(): boolean; function CheckInfoFlagSet(testFlag: integer): boolean; public property SlotID: integer read FSlotID write FSlotID; // WARNING: Calling this function will return a *new* TPKCS11Token object // each time it's called. // It's the *callers* responsibility to free off this object after // use function Token(): TPKCS11Token; function GetSlotInfo(var info: CK_SLOT_INFO): boolean; property Description: string read GetDescription; property ManufacturerID: string read GetManufacturerID; property Flags: CK_FLAGS read GetFlags; property HardwareVersion: CK_VERSION read GetHardwareVersion; property FirmwareVersion: CK_VERSION read GetFirmwareVersion; // Flags property TokenPresent: boolean read GetTokenPresent; property RemovableDevice: boolean read GetRemovableDevice; property HWSlot: boolean read GetHWSlot; end; TPKCS11SlotArray = array of TPKCS11Slot; implementation uses SysUtils, SDUGeneral; // Note: *Caller* is responsible for freeing returned attribute object function TPKCS11Slot.Token(): TPKCS11Token; begin if (not(TokenPresent)) then begin raise EPKCS11TokenNotPresent.Create(E_EPKCS11_TOKENNOTPRESENT); end; Result := TPKCS11Token.Create(); Result.SlotID := SlotID; Result.LibraryFunctionList := LibraryFunctionList; end; function TPKCS11Slot.GetSlotInfo(var info: CK_SLOT_INFO): boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_GetSlotInfo, FN_NAME_C_GetSlotInfo); LastRV := LibraryFunctionList.CK_C_GetSlotInfo(SlotID, @info); Result := RVSuccess(LastRV); end; function TPKCS11Slot.GetDescription(): string; var info: CK_SLOT_INFO; begin Result := ''; if (GetSlotInfo(info)) then begin Result := UTF8CHARArrayToString(TCK_UTF8CHARArray_64(info.slotDescription)); end; end; function TPKCS11Slot.GetManufacturerID(): string; var info: CK_SLOT_INFO; begin Result := ''; if (GetSlotInfo(info)) then begin Result := UTF8CHARArrayToString(TCK_UTF8CHARArray_32(info.manufacturerID)); end; end; function TPKCS11Slot.GetFlags(): CK_FLAGS; var info: CK_SLOT_INFO; begin Result := 0; if (GetSlotInfo(info)) then begin Result := info.Flags; end; end; function TPKCS11Slot.GetHardwareVersion(): CK_VERSION; var info: CK_SLOT_INFO; begin Result := NULL_VERSION; if (GetSlotInfo(info)) then begin Result := info.hardwareVersion; end; end; function TPKCS11Slot.GetFirmwareVersion(): CK_VERSION; var info: CK_SLOT_INFO; begin Result := NULL_VERSION; if (GetSlotInfo(info)) then begin Result := info.firmwareVersion; end; end; function TPKCS11Slot.CheckInfoFlagSet(testFlag: integer): boolean; var info: CK_SLOT_INFO; begin Result := FALSE; if (GetSlotInfo(info)) then begin Result := SDUBitWiseTest(info.flags, testFlag); end; end; function TPKCS11Slot.GetTokenPresent(): boolean; begin Result := CheckInfoFlagSet(CKF_TOKEN_PRESENT); end; function TPKCS11Slot.GetRemovableDevice(): boolean; begin Result := CheckInfoFlagSet(CKF_REMOVABLE_DEVICE); end; function TPKCS11Slot.GetHWSlot(): boolean; begin Result := CheckInfoFlagSet(CKF_HW_SLOT); end; END.
unit GLDTaperParamsFrame; interface uses Classes, Controls, Forms, ComCtrls, StdCtrls, GL, GLDTypes, GLDSystem, GLDAxisFrame, GLDModifyLimitEffectFrame, GLDUpDown; type TGLDTaperParamsFrame = class(TFrame) GB_Rotate: TGroupBox; L_Amount: TLabel; E_Amount: TEdit; UD_Amount: TGLDUpDown; F_Axis: TGLDAxisFrame; GB_Effect: TGroupBox; CB_X: TCheckBox; CB_Y: TCheckBox; CB_Z: TCheckBox; F_LimitEffect: TGLDModifyLimitEffectFrame; procedure ValueChange(Sender: TObject); procedure AxisChange(Sender: TObject); procedure EditEnter(Sender: TObject); private FDrawer: TGLDDrawer; procedure SetDrawer(Value: TGLDDrawer); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; function HaveTaper: GLboolean; function GetParams: TGLDTaperParams; procedure SetParams(const Params: TGLDTaperParams); procedure SetParamsFrom(Source: TPersistent); procedure ApplyParams; property Drawer: TGLDDrawer read FDrawer write SetDrawer; end; implementation {$R *.dfm} uses SysUtils, GLDConst, GLDX, GLDModify; constructor TGLDTaperParamsFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FDrawer := nil; F_Axis.OnAxisChange := Self.AxisChange; end; function TGLDTaperParamsFrame.HaveTaper: GLboolean; begin Result := False; if Assigned(FDrawer) and Assigned(FDrawer.EditedModify) and (FDrawer.EditedModify is TGLDTaper) then Result := True; end; function TGLDTaperParamsFrame.GetParams: TGLDTaperParams; begin Result.Amount := UD_Amount.Position; Result.Axis := F_Axis.Axis; Result.Effect := GLDXTaperEffectSetToTaperEffect(GLDXTaperEffectSet( CB_X.Checked, CB_Y.Checked, CB_Z.Checked)); Result.LimitEffect := F_LimitEffect.CB_LimitEffect.Checked; Result.UpperLimit := F_LimitEffect.UD_UpperLimit.Position; Result.LowerLimit := F_LimitEffect.UD_LowerLimit.Position; end; procedure TGLDTaperParamsFrame.SetParams(const Params: TGLDTaperParams); begin UD_Amount.Position := Params.Amount; F_Axis.Axis := Params.Axis; CB_X.Checked := (Params.Effect and GLD_TAPER_EFFECT_X) <> 0; CB_Y.Checked := (Params.Effect and GLD_TAPER_EFFECT_Y) <> 0; CB_Z.Checked := (Params.Effect and GLD_TAPER_EFFECT_Z) <> 0; F_LimitEffect.SetParams(Params.LimitEffect, Params.UpperLimit, Params.LowerLimit); end; procedure TGLDTaperParamsFrame.SetParamsFrom(Source: TPersistent); begin if Assigned(Source) and (Source is TGLDTaper) then SetParams(TGLDTaper(Source).Params); end; procedure TGLDTaperParamsFrame.ApplyParams; begin if HaveTaper then TGLDTaper(FDrawer.EditedModify).Params := GetParams; end; procedure TGLDTaperParamsFrame.ValueChange(Sender: TObject); begin if HaveTaper then with TGLDTaper(FDrawer.EditedModify) do if Sender = UD_Amount then Amount := UD_Amount.Position else if (Sender = CB_X) or (Sender = CB_Y) or (Sender = CB_Z) then Effect := GLDXTaperEffectSet(CB_X.Checked, CB_Y.Checked, CB_Z.Checked) else if Sender = F_LimitEffect.CB_LimitEffect then LimitEffect := F_LimitEffect.CB_LimitEffect.Checked else if Sender = F_LimitEffect.UD_UpperLimit then UpperLimit := F_LimitEffect.UD_UpperLimit.Position else if Sender = F_LimitEffect.UD_LowerLimit then LowerLimit := F_LimitEffect.UD_LowerLimit.Position; end; procedure TGLDTaperParamsFrame.AxisChange(Sender: TObject); begin if HaveTaper then with TGLDTaper(FDrawer.EditedModify) do Axis := F_Axis.Axis; end; procedure TGLDTaperParamsFrame.EditEnter(Sender: TObject); begin ApplyParams; end; procedure TGLDTaperParamsFrame.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and (Operation = opRemove) then FDrawer := nil; inherited Notification(AComponent, Operation); end; procedure TGLDTaperParamsFrame.SetDrawer(Value: TGLDDrawer); begin FDrawer := Value; if Assigned(FDrawer) then SetParamsFrom(FDrawer.EditedModify); end; end.
unit ParseFastTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, Math, SysUtils, TestHelper, uEnums, uIntX; type { TTestToParseFast } TTestToParseFast = class(TTestCase) private F_length: integer; function GetAllNineChars(mlength: integer): string; function GetRandomChars(): string; procedure Inner(); procedure InnerTwo(); const StartLength = integer(1024); LengthIncrement = integer(101); RepeatCount = integer(50); RandomStartLength = integer(1024); RandomEndLength = integer(4000); RandomRepeatCount = integer(50); published procedure CompareWithClassic(); procedure CompareWithClassicRandom(); protected procedure SetUp; override; end; implementation procedure TTestToParseFast.CompareWithClassic(); begin TTestHelper.Repeater(RepeatCount, @Inner); end; procedure TTestToParseFast.CompareWithClassicRandom(); begin TTestHelper.Repeater(RandomRepeatCount, @InnerTwo); end; procedure TTestToParseFast.Inner(); var str: string; classic, fast: TIntX; begin str := GetAllNineChars(F_length); classic := TIntX.Parse(str, TParseMode.pmClassic); fast := TIntX.Parse(str, TParseMode.pmFast); AssertTrue(classic = fast); F_length := F_length + LengthIncrement; end; procedure TTestToParseFast.InnerTwo(); var str: string; classic, fast: TIntX; begin str := GetRandomChars(); classic := TIntX.Parse(str, TParseMode.pmClassic); fast := TIntX.Parse(str, TParseMode.pmFast); AssertTrue(classic = fast); end; procedure TTestToParseFast.SetUp; begin inherited SetUp; F_length := StartLength; Randomize; end; function TTestToParseFast.GetAllNineChars(mlength: integer): string; begin Result := StringOfChar('9', mlength); end; function TTestToParseFast.GetRandomChars(): string; var mlength: integer; builder: string; begin mlength := RandomRange(RandomStartLength, RandomEndLength); builder := ''; builder := builder + IntToStr(RandomRange(1, 9)); Dec(mlength); while mlength <> 0 do begin builder := builder + IntToStr(RandomRange(0, 9)); Dec(mlength); end; Result := builder; end; initialization RegisterTest(TTestToParseFast); end.
unit ExEffectFormUnit; interface uses System.SysUtils, System.Math, System.Classes, Winapi.Windows, Winapi.Messages, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.AppEvnts, Vcl.ExtCtrls, Vcl.Buttons, Dmitry.Utils.System, ExEffects, ToolsUnit, ScrollingImage, uGOM, uMemory, uDBForm, uEditorTypes; type TExEffectForm = class(TDBForm) BottomPanel: TPanel; ExEffectPanel: TPanel; ButtonPanel: TPanel; BtnCancel: TButton; BtnOk: TButton; EffectPanel: TGroupBox; CbPreview: TCheckBox; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; Label1: TLabel; OriginalImage: TFastScrollingImage; NewImage: TFastScrollingImage; Timer1: TTimer; CbTransparent: TCheckBox; TbTransparent: TTrackBar; ApplicationEvents1: TApplicationEvents; procedure BtnCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BtnOkClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure OriginalImageChangePos(Sender: TObject); procedure NewImageChangePos(Sender: TObject); procedure CbPreviewClick(Sender: TObject); procedure CbTransparentClick(Sender: TObject); procedure TbTransparentChange(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure Timer1Timer(Sender: TObject); procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); private { Private declarations } FEffect: TExEffect; FOwner: TToolsPanelClass; FInitialString: string; InitiatedByString: Boolean; FEditor: TImageEditorForm; procedure LoadLanguage; protected { Protected declarations } function GetFormID : string; override; public { Public declarations } function Execute(Owner: TToolsPanelClass; S, D: TBitmap; Effect: TExEffectsClass; var InitialString: string): Boolean; procedure SetImage(Image: TBitmap); property Editor: TImageEditorForm read FEditor write FEditor; end; implementation {$R *.dfm} uses EffectsToolUnit, ImEditor; { TExEffectForm } function TExEffectForm.Execute(Owner : TToolsPanelClass; S,D : TBitmap; Effect: TExEffectsClass; var InitialString : string): boolean; begin FInitialString := InitialString; if FInitialString <> '' then begin SpeedButton1.Enabled := False; SpeedButton2.Enabled := False; EffectPanel.Enabled := False; CbPreview.Enabled := False; CbTransparent.Enabled := False; BtnCancel.Enabled := False; BtnOk.Enabled := False; InitiatedByString := True; end else InitiatedByString := False; FOwner := Owner; FEffect := Effect.Create; FEffect.SetImageProc := SetImage; FEffect.Editor := Editor; if InitiatedByString then begin FEffect.Execute(S, D, EffectPanel, False); FEffect.SetProperties(InitialString); end else FEffect.Execute(S, D, EffectPanel, True); S.PixelFormat := pf24bit; D.PixelFormat := pf24bit; if not InitiatedByString then begin OriginalImage.Picture.Assign(S); NewImage.Picture.Assign(S); end; ShowModal; InitialString := FInitialString; Result := True; end; procedure TExEffectForm.BtnCancelClick(Sender: TObject); begin (FOwner as TEffectsToolPanelClass).CancelTempImage(True); Close; end; procedure TExEffectForm.FormCreate(Sender: TObject); begin FEffect := nil; LoadLanguage; end; procedure TExEffectForm.FormDestroy(Sender: TObject); begin if GOM.IsObj(FEffect) then F(FEffect); (Editor as TImageEditor).FStatusProgress.Position := 0; (Editor as TImageEditor).StatusBar1.Panels[1].Text := ''; end; procedure TExEffectForm.SetImage(Image: TBitmap); var OldPos: TPoint; begin if InitiatedByString then begin (FOwner as TEffectsToolPanelClass).SetNewImage(Image); FInitialString := FEffect.GetProperties; Close; end else begin OriginalImage.Tag := 1; OldPos := NewImage.ImagePos; NewImage.Picture.Assign(Image); NewImage.ImagePos := OldPos; NewImage.Transparent := True; NewImage.Transparent := False; OriginalImage.Tag := 0; if CbPreview.Checked then begin (FOwner as TEffectsToolPanelClass).SetTempImage(Image); FInitialString := FEffect.GetProperties; end else F(Image); end; end; procedure TExEffectForm.BtnOkClick(Sender: TObject); var Bitmap: TBitmap; begin Bitmap := TBitmap.Create; Bitmap.Assign(NewImage.Picture); Bitmap.PixelFormat := pf24bit; (FOwner as TEffectsToolPanelClass).CancelTempImage(True); (FOwner as TEffectsToolPanelClass).SetNewImage(Bitmap); Close; end; procedure TExEffectForm.SpeedButton1Click(Sender: TObject); begin OriginalImage.Tag := 1; OriginalImage.Zoom := Min(1600, Max(1, OriginalImage.Zoom * 1.2)); NewImage.Zoom := OriginalImage.Zoom; Label1.Caption := IntToStr(Round(NewImage.Zoom)) + '%'; OriginalImage.Tag := 0; end; procedure TExEffectForm.SpeedButton2Click(Sender: TObject); begin OriginalImage.Tag := 1; OriginalImage.Zoom := Min(1600, Max(1, OriginalImage.Zoom / 1.2)); NewImage.Zoom := OriginalImage.Zoom; Label1.Caption := IntToStr(Round(NewImage.Zoom)) + '%'; OriginalImage.Tag := 0; end; procedure TExEffectForm.OriginalImageChangePos(Sender: TObject); begin if OriginalImage.Tag <> 1 then NewImage.ImagePos := OriginalImage.ImagePos; end; procedure TExEffectForm.NewImageChangePos(Sender: TObject); begin if OriginalImage.Tag = 1 then Exit; OriginalImage.Tag := 1; OriginalImage.ImagePos := NewImage.ImagePos; OriginalImage.Tag := 0; end; procedure TExEffectForm.CbPreviewClick(Sender: TObject); var Image: TBitmap; begin if CbPreview.Checked then begin Image := TBitmap.Create; Image.PixelFormat := pf24bit; Image.Assign(NewImage.Picture); (FOwner as TEffectsToolPanelClass).SetTempImage(Image); end else begin (FOwner as TEffectsToolPanelClass).CancelTempImage(True); end; end; procedure TExEffectForm.CbTransparentClick(Sender: TObject); begin AlphaBlend := CbTransparent.Checked; end; procedure TExEffectForm.TbTransparentChange(Sender: TObject); begin AlphaBlendvalue := 255 - Round(TbTransparent.Position * 255 / 20); end; procedure TExEffectForm.FormKeyPress(Sender: TObject; var Key: Char); begin if Ord(Key) = VK_ESCAPE then BtnCancelClick(Sender); end; function TExEffectForm.GetFormID: string; begin Result := 'ExEffectForm'; end; procedure TExEffectForm.LoadLanguage; begin BeginTranslate; try BtnCancel.Caption := L('Cancel'); BtnOk.Caption := L('Ok'); Caption := L('Effects'); CbPreview.Caption := L('Preview'); CbTransparent.Caption := L('Transparency'); finally EndTranslate; end; end; procedure TExEffectForm.Timer1Timer(Sender: TObject); begin if CtrlKeyDown and Active then begin if Visible then Hide; end else begin if not Visible then Show; end end; procedure TExEffectForm.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); begin if not Active then Exit; if Msg.message = WM_MOUSEWHEEL then begin if NativeInt(Msg.WParam) < 0 then SpeedButton1Click(Self) else SpeedButton2Click(Self); end; end; end.
unit Command.Button1; interface uses System.Classes, System.SysUtils, Vcl.StdCtrls, Vcl.Pattern.Command; type TButon1Command = class (TCommand) private FMemo: TMemo; protected procedure Guard; override; public procedure Execute; override; published property Memo: Vcl.StdCtrls.TMemo read FMemo write FMemo; end; implementation procedure TButon1Command.Guard; begin inherited; Assert(Memo<>nil); end; procedure TButon1Command.Execute; begin inherited; Memo.Lines.Add('Simple message from command 1'); end; end.
unit uBaseForm; interface uses Classes, SysUtils, Dialogs, uSvcInfoIntf, uDefCom, uParamObject, uFactoryFormIntf; type TFromFactory = class(TInterfacedObject, ISvcInfo, IFromFactory) private protected {ISvcInfo} function GetModuleName: string; function GetTitle: string; function GetVersion: string; function GetComments: string; {IFromFactory} function GetFormAsFromName(AFromName: string; AParam: TParamObject; AOwner: TComponent): IFormIntf; overload; function GetFormAsFromNo(AFromNo: Integer; AParam: TParamObject; AOwner: TComponent): IFormIntf; overload; public constructor Create; destructor Destroy; override; end; implementation uses uSysFactory, uBaseFormPlugin; procedure CreateFromFactory(out anInstance: IInterface); begin anInstance := TFromFactory.Create; end; { TExManagement } constructor TFromFactory.Create; begin end; destructor TFromFactory.Destroy; begin inherited; end; function TFromFactory.GetComments: string; begin Result := '用于业务显示窗体接口的操作'; end; function TFromFactory.GetModuleName: string; begin Result := '业务窗体接口(IExManagement)'; end; function TFromFactory.GetTitle: string; begin Result := '用于业务窗体接口操作'; end; function TFromFactory.GetVersion: string; begin Result := '20150508.001'; end; function TFromFactory.GetFormAsFromName(AFromName: string; AParam: TParamObject; AOwner: TComponent): IFormIntf; begin Result := IFormIntf(gFormManage.GetFormAsFromName(AFromName, AParam, AOwner)); end; function TFromFactory.GetFormAsFromNo(AFromNo: Integer; AParam: TParamObject; AOwner: TComponent): IFormIntf; begin Result := IFormIntf(gFormManage.GetFormAsFromNo(AFromNo, AParam, AOwner)); end; initialization TSingletonFactory.Create(IFromFactory, @CreateFromFactory); finalization end.
{......................................................................................................................} Var gv_ListBoxIndexToLayerArray : TList; {......................................................................................................................} {......................................................................................................................} Function GetLayerFromComboBox(ComboBox : TComboBox; Board : IPCB_Board) : TLayer; Begin Result := eTopLayer; If ComboBox.ItemIndex < 0 Then Exit; If ComboBox.ItemIndex >= ComboBox.Items.Count Then Exit; Result := gv_ListBoxIndexToLayerArray.Items(ComboBox.ItemIndex); End; {......................................................................................................................} {......................................................................................................................} Procedure SetupComboBoxFromLayer(ComboBox : TComboBox; Board : IPCB_Board); Var DesiredLayers : IPCB_LayerSet; Layer : TLayer; LayerObject : IPCB_LayerObject; LayerIterator : IPCB_LayerObjectIterator; Begin gv_ListBoxIndexToLayerArray := TList.Create; ComboBox.Items.Clear; DesiredLayers := LayerSet.EmptySet; DesiredLayers.Include(eDrillGuide); DesiredLayers.Include(eDrillDrawing); DesiredLayers.Include(eKeepOutLayer); DesiredLayers.IncludeMechanicalLayers; LayerIterator := ILayer.LayerIterator_PossibleLayers; LayerIterator.AddFilter_LayerSet(DesiredLayers); While LayerIterator.Next Do Begin gv_ListBoxIndexToLayerArray.Add(LayerIterator.Layer); ComboBox.Items.Add(ILayer.AsString(LayerIterator.Layer)); If LayerIterator.Layer = Board.CurrentLayer Then ComboBox.ItemIndex := ComboBox.Items.Count - 1; End; If ComboBox.ItemIndex < 0 Then ComboBox.ItemIndex := 0; End; {......................................................................................................................}
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFSE_DETALHE] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfseDetalheVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TNfseDetalheVO = class(TVO) private FID: Integer; FID_NFSE_LISTA_SERVICO: Integer; FID_NFSE_CABECALHO: Integer; FVALOR_SERVICOS: Extended; FVALOR_DEDUCOES: Extended; FVALOR_PIS: Extended; FVALOR_COFINS: Extended; FVALOR_INSS: Extended; FVALOR_IR: Extended; FVALOR_CSLL: Extended; FCODIGO_CNAE: String; FCODIGO_TRIBUTACAO_MUNICIPIO: String; FVALOR_BASE_CALCULO: Extended; FALIQUOTA: Extended; FVALOR_ISS: Extended; FVALOR_LIQUIDO: Extended; FOUTRAS_RETENCOES: Extended; FVALOR_CREDITO: Extended; FISS_RETIDO: String; FVALOR_ISS_RETIDO: Extended; FVALOR_DESCONTO_CONDICIONADO: Extended; FVALOR_DESCONTO_INCONDICIONADO: Extended; FDISCRIMINACAO: String; FMUNICIPIO_PRESTACAO: Integer; //Transientes //Usado no lado cliente para controlar quais registros serão persistidos FPersiste: String; published property Id: Integer read FID write FID; property IdNfseListaServico: Integer read FID_NFSE_LISTA_SERVICO write FID_NFSE_LISTA_SERVICO; property IdNfseCabecalho: Integer read FID_NFSE_CABECALHO write FID_NFSE_CABECALHO; property ValorServicos: Extended read FVALOR_SERVICOS write FVALOR_SERVICOS; property ValorDeducoes: Extended read FVALOR_DEDUCOES write FVALOR_DEDUCOES; property ValorPis: Extended read FVALOR_PIS write FVALOR_PIS; property ValorCofins: Extended read FVALOR_COFINS write FVALOR_COFINS; property ValorInss: Extended read FVALOR_INSS write FVALOR_INSS; property ValorIr: Extended read FVALOR_IR write FVALOR_IR; property ValorCsll: Extended read FVALOR_CSLL write FVALOR_CSLL; property CodigoCnae: String read FCODIGO_CNAE write FCODIGO_CNAE; property CodigoTributacaoMunicipio: String read FCODIGO_TRIBUTACAO_MUNICIPIO write FCODIGO_TRIBUTACAO_MUNICIPIO; property ValorBaseCalculo: Extended read FVALOR_BASE_CALCULO write FVALOR_BASE_CALCULO; property Aliquota: Extended read FALIQUOTA write FALIQUOTA; property ValorIss: Extended read FVALOR_ISS write FVALOR_ISS; property ValorLiquido: Extended read FVALOR_LIQUIDO write FVALOR_LIQUIDO; property OutrasRetencoes: Extended read FOUTRAS_RETENCOES write FOUTRAS_RETENCOES; property ValorCredito: Extended read FVALOR_CREDITO write FVALOR_CREDITO; property IssRetido: String read FISS_RETIDO write FISS_RETIDO; property ValorIssRetido: Extended read FVALOR_ISS_RETIDO write FVALOR_ISS_RETIDO; property ValorDescontoCondicionado: Extended read FVALOR_DESCONTO_CONDICIONADO write FVALOR_DESCONTO_CONDICIONADO; property ValorDescontoIncondicionado: Extended read FVALOR_DESCONTO_INCONDICIONADO write FVALOR_DESCONTO_INCONDICIONADO; property Discriminacao: String read FDISCRIMINACAO write FDISCRIMINACAO; property MunicipioPrestacao: Integer read FMUNICIPIO_PRESTACAO write FMUNICIPIO_PRESTACAO; //Transientes property Persiste: String read FPersiste write FPersiste; end; TListaNfseDetalheVO = specialize TFPGObjectList<TNfseDetalheVO>; implementation initialization Classes.RegisterClass(TNfseDetalheVO); finalization Classes.UnRegisterClass(TNfseDetalheVO); end.
unit uWizImportInventory; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentWizImp, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, DBClient, ImgList, StdCtrls, ExtCtrls, Grids, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Buttons, ComCtrls, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TWizImportInventory = class(TParentWizImp) gbConfigImportQty: TGroupBox; Label18: TLabel; Label4: TLabel; Label13: TLabel; cbxStore: TcxLookupComboBox; rgQtyActionType: TRadioGroup; tsList: TTabSheet; grdListFile: TcxGrid; grdListFileTableView: TcxGridDBTableView; cxGridLevel1: TcxGridLevel; chkInventory: TCheckBox; lqQtyInfo: TLabel; procedure rgQtyActionTypeClick(Sender: TObject); procedure sgColumnsExit(Sender: TObject); procedure chkInventoryClick(Sender: TObject); private QtyActionType : Char; procedure SaveGridColumns; procedure GetGridColumn; procedure AddColumnsToListGrid; protected procedure AddColumnsToImport; procedure FillColumnsGrid; function TestBeforeNavigate:Boolean; override; function OnAfterChangePage:Boolean; override; function VerifyFieldsRequired: Boolean; function DoFinish:Integer; override; function AddSpecificFieldsToCDS(Position : Integer): Integer; override; procedure AddSpecificFriendFieldsToCDS(Position : Integer); override; procedure OnBeforeBackClick; override; end; implementation uses uMsgBox, uDMGlobalNTier, uParamFunctions, uDMImportExport, uParentWizard, uSystemConst; {$R *.dfm} { TWizImportInventory } procedure TWizImportInventory.AddColumnsToImport; begin sgColumns.Cells[0,1] := 'Model'; sgColumns.Cells[0,2] := 'Barcode'; sgColumns.Cells[0,3] := 'Category'; sgColumns.Cells[0,4] := 'Sub-Category'; sgColumns.Cells[0,5] := 'Group'; sgColumns.Cells[0,6] := 'Manufacturer'; sgColumns.Cells[0,7] := 'Vendor'; sgColumns.Cells[0,8] := 'Qty'; sgColumns.Cells[0,9] := 'CaseQty'; sgColumns.Cells[0,10] := 'Description'; sgColumns.Cells[0,11] := 'VendorCost'; sgColumns.Cells[0,12] := 'MarkUp'; sgColumns.Cells[0,13] := 'SellingPrice'; sgColumns.Cells[0,14] := 'SuggRetail'; sgColumns.Cells[0,15] := 'ClassABC'; sgColumns.Cells[0,16] := 'DiscountPerc'; sgColumns.Cells[0,17] := 'VendorModelCode'; sgColumns.RowCount := 18; end; function TWizImportInventory.DoFinish: Integer; begin Result := inherited DoFinish; end; procedure TWizImportInventory.FillColumnsGrid; begin sgColumns.Cells[0,0] := 'Main Retail'; sgColumns.Cells[1,0] := 'Inventory File'; AddColumnsToImport; AddComboColumnsToImport; end; function TWizImportInventory.OnAfterChangePage: Boolean; var Passed : Boolean; sError: String; begin Result := inherited OnAfterChangePage; Passed := False; if pgOption.ActivePage.Name = 'tsCrossColumn' then begin cbColumns.Visible := False; FillColumnsGrid; GetGridColumn; end else if pgOption.ActivePage.Name = 'tsSpecificConfig' then begin gbConfigImportQty.Visible := False; DMImportExport.ImportConn.Connected := True; DMImportExport.OpenStore; end else if pgOption.ActivePage.Name = 'tsList' then begin SaveGridColumns; ScreenStatusWait; SetGridToRegistryValues(MR_BRW_REG_PATH + 'MRImportExport\ImpPO\Vendor_' + SpecificConfig.Values['UseQty'] + '_List', grdListFile); cdsFile.Data := (DMImportExport.ImportConn.AppServer.ValidateInventoryTextFile(cdsFile.Data, LinkedColumns.Text,SpecificConfig.Text,LogError.Text, Passed)); grdListFileTableView.DataController.DataSource := dtsFile; AddColumnsToListGrid; RestoreGridFromRegistry; ScreenStatusOk; end else if pgOption.ActivePage.Name = 'tsImport' then begin ScreenStatusWait; DMImportExport.ImportConn.AppServer.ImportInventoryTextFile(cdsFile.Data, LinkedColumns.Text, SpecificConfig.Text, sError); LogError.Text := sError; if sError <> '' then ShowError(sError) else MsgBox('Import Success!', vbInformation + vbOKOnly); ScreenStatusOk; end; end; function TWizImportInventory.TestBeforeNavigate: Boolean; begin Result := inherited TestBeforeNavigate; if pgOption.ActivePage.Name = 'tsSpecificConfig' then begin if chkInventory.Checked then begin if not(VerifyFieldsRequired) then begin MsgBox('Field Required!', vbInformation + vbOKOnly); Result := False; Exit; end else begin AddSpecificConfigList('UseQty','Y'); AddSpecificConfigList('QtyActionType', QtyActionType); AddSpecificConfigList('IDStore', cbxStore.EditValue); AddSpecificConfigList('IDUser', IntToStr(DMImportExport.FUser.ID)); end; end else AddSpecificConfigList('UseQty','N'); if DMImportExport.ActiveConnection.AppServer.IsClientServer then begin MsgBox('Inventory cannot be imported!_This is a Replication Database!', vbInformation + vbOKOnly); Result := False; Exit; end; end else if pgOption.ActivePage.Name = 'tsList' then SaveGridToRegistry; end; function TWizImportInventory.VerifyFieldsRequired: Boolean; begin Result := True; if (cbxStore.EditingText = '') or (rgQtyActionType.ItemIndex = -1) then Result := False; end; procedure TWizImportInventory.rgQtyActionTypeClick(Sender: TObject); begin if rgQtyActionType.ItemIndex = 0 then QtyActionType := 'R' //REPLACE else QtyActionType := 'A' //ADD end; procedure TWizImportInventory.GetGridColumn; var sColumn, sError, sResult : String; sCaseCost : WordBool; i : integer; begin //sColumn := DMImportExport.GetAppProperty('ColumnImportInventorySetup', SpecificConfig.Values['UseQty']); sError := DMImportExport.GetConfigImport( 0, IMPORT_TYPE_INVENTORY, sColumn, sCaseCost); LogError.Text := sError; if LogError.Text = '' then begin if sColumn = '' then Exit; for i:=1 to sgColumns.RowCount-1 do begin sResult := ParseParam(sColumn, Trim(sgColumns.Cells[0,i])); if sResult <> '' then sgColumns.Cells[1,i] := sResult; sColumn := DeleteParam(sColumn, Trim(sgColumns.Cells[0,i])); end; end; end; procedure TWizImportInventory.SaveGridColumns; var sColumn, sError : String; i : integer; begin for i:=1 to sgColumns.RowCount-1 do if Trim(sgColumns.Cells[0,i]) <> '' then //if Pos(Trim(sgColumns.Cells[1,i]), sColumn) = 0 then sColumn := sColumn + sgColumns.Cells[0,i] + '=' + sgColumns.Cells[1,i] + ';'; if sColumn = '' then Exit; //DMImportExport.SetAppProperty('ColumnImportInventorySetup', SpecificConfig.Values['UseQty'], sColumn); sError := DMImportExport.InsertConfigImport( 0, IMPORT_TYPE_INVENTORY, sColumn, False); LogError.Text := sError; if LogError.Text <> '' then begin MsgBox(LogError.Text, vbCritical + vbOkOnly); end; end; procedure TWizImportInventory.sgColumnsExit(Sender: TObject); begin //SaveGridColumns; end; procedure TWizImportInventory.AddColumnsToListGrid; var i: Integer; NewColumn: TcxGridDBColumn; begin grdListFileTableView.ClearItems; for i := 0 to Pred(cdsFile.FieldDefs.Count) do begin NewColumn := grdListFileTableView.CreateColumn; with NewColumn do begin Caption := cdsFile.FieldDefs[i].DisplayName; Name := 'grdListFileTableViewDB' + cdsFile.FieldDefs[i].DisplayName; DataBinding.FieldName := cdsFile.FieldDefs[i].Name; if cdsFile.FieldDefs[i].Name = 'Warning' then begin NewColumn.IsPreview := True; grdListFileTableView.Preview.Column := NewColumn; end; end; end; end; procedure TWizImportInventory.chkInventoryClick(Sender: TObject); begin gbConfigImportQty.Visible := chkInventory.Checked; end; function TWizImportInventory.AddSpecificFieldsToCDS( Position: Integer): Integer; begin Result := Position; end; procedure TWizImportInventory.AddSpecificFriendFieldsToCDS( Position: Integer); begin inherited; end; procedure TWizImportInventory.OnBeforeBackClick; begin if pgOption.ActivePage.Name = 'tsCrossColumn' then SaveGridColumns; inherited; end; end.
unit ui2ximg_G32; interface uses Windows, Classes, uStrUtil, Graphics, SysUtils, GR32, GR32_Image, uI2XImg, MapStream, uDWImage, uI2XConstants, Typinfo; const UNIT_NAME = 'ui2ximg_G32'; type TImageInstructionsG32 = ( iRBG_COLOR_STRIP = 0 ); TI2XImgG32 = class(TI2XImg) private //FBMP32 : TDWBitmap32; FBMP32 : TBitmap32; function shouldBeBlackPixel(const color: TColor; Threshold: string): boolean; function HexToByte(hexStr: string): byte; function HexToInt(hexStr: string): integer; function HexToTColor(const sColor: string): TColor; function TColorToHex(const colColor: TColor): string; public function StripColors( RGBThresHold : Cardinal ): boolean; overload; function StripColors( Parm : string ): boolean; overload; function ExecuteInstruction( const InstructionString : string ) : boolean; override; constructor Create( const GUID, ParmFileName : string ); override; destructor Destroy; override; function ProcessImage( const MemoryMapName : string; InstructionList : TStrings ) : boolean; override; end; implementation { TI2XImgG32 } constructor TI2XImgG32.Create(const GUID, ParmFileName: string); begin inherited Create( GUID, ParmFileName ); FBMP32 := TBitmap32.Create; end; destructor TI2XImgG32.Destroy; begin FreeAndNil( FBMP32 ); inherited; end; function TI2XImgG32.ExecuteInstruction( const InstructionString: string): boolean; var sInst, sParmString, key, val : string; ParmCount : byte; sl : TStringList; i : integer; bRes : boolean; Begin try sl := TStringList.Create; bRes := false; sInst := Split( InstructionString, IMGPROC_PARM_SEP, 0 ); //get the instruction sInst := Split( sInst, IMGPROC_PLUGIN_SEP, 1 ); //strip the PlugIn Numonic ParmCount := StringCount(InstructionString, IMGPROC_VALUE_SEP ); if ( Length( InstructionString ) > 0 ) then begin if ( Integer( self.DebugLevel ) > 0 ) then FBMP32.SaveToFile( self.DebugPath + 'G32-' + sInst + '_IN.bmp' ); case TImageInstructionsG32(GetEnumValue(TypeInfo(TImageInstructionsG32),'i' + sInst)) of iRBG_COLOR_STRIP: begin if ( ParmCount <> 1 ) then raise Exception.Create('Instruction "' + sInst + '" was passed an incorrect amount of parameters. Parm string=' + InstructionString); Result := self.StripColors( InstructionString ); end; end; if (( bRes ) and ( Integer( self.DebugLevel ) > 0 )) then FBMP32.SaveToFile( self.DebugPath + 'G32-' + sInst + '_OUT.bmp' ); Result := bRes; end; finally FreeAndNil( sl ); end; End; function TI2XImgG32.ProcessImage(const MemoryMapName: string; InstructionList: TStrings): boolean; var i : integer; sMemoryMapName : string; Begin try FMemoryMapManager.Flush(); sMemoryMapName := MemoryMapName; FMemoryMapManager.DebugMessageText := 'TI2XImgG32.ProcessImage - Image FROM from UI - ' + InstructionList.Text; Result := FMemoryMapManager.Read( sMemoryMapName, FBMP32 ); if ( not Result ) then raise Exception.Create( 'Could not read from memory map.' ); for i := 0 to InstructionList.Count - 1 do begin if ( not ExecuteInstruction( InstructionList[i] ) ) then Exit; end; //self.FBMP32.SaveToMemoryMap( MemoryMapName ); FMemoryMapManager.DebugMessageText := 'TI2XImgG32.ProcessImage - Image FOR from UI'; Result := FMemoryMapManager.Write( sMemoryMapName, FBMP32 ); if ( not Result ) then raise Exception.Create( 'Could not save to memory map.' ); except on E : Exception do begin self.ErrorUpdate( E.Message, ERROR_IMAGE_PROC_FAILED ); end; end; End; (* Returns a string representation of the colColor parameter in XXXXXX format, ** X being a hex digit. Thanks http://www.delphifaq.net/how-to-convert-tcolor-to-a-hex-string-and-vice-versa/ *) function TI2XImgG32.TColorToHex(const colColor: TColor): string; begin Result := IntToHex(GetRValue(colColor), 2) + { Red value } IntToHex(GetGValue(colColor), 2) + { Green value } IntToHex(GetBValue(colColor), 2); { Blue value } end; { sColor should be in XXXXXX format, X being a hex digit } function TI2XImgG32.HexToTColor(const sColor: string): TColor; begin Result := RGB( StrToInt('$' + Copy(sColor, 1, 2)), { Get red value } StrToInt('$' + Copy(sColor, 3, 2)), { Get green value } StrToInt('$' + Copy(sColor, 5, 2)) ); { Get blue value } end; function TI2XImgG32.HexToInt(hexStr : string) : integer; CONST HEX : ARRAY['A'..'F'] OF INTEGER = (10,11,12,13,14,15); var i : integer; begin result := 0; FOR i := 1 TO Length(hexStr) DO if ( hexStr[i] < 'A' ) then result := result * 16 + ORD(hexStr[i]) - 48 else result := result * 16 + HEX[hexStr[i]]; End; function TI2XImgG32.HexToByte(hexStr : string) : byte; CONST HEX : ARRAY['A'..'F'] OF INTEGER = (10,11,12,13,14,15); var i : integer; begin result := 0; FOR i := 1 TO Length(hexStr) DO if ( hexStr[i] < 'A' ) then result := result * 16 + ORD(hexStr[i]) - 48 else result := result * 16 + HEX[hexStr[i]]; End; function TI2XImgG32.StripColors(RGBThresHold: Cardinal): boolean; const uBlack = $00000000; uWhite = $00FFFFFF; uRed = $000000FF; uBlue = $00FF0000; var pixel : TColor; x, y : Cardinal; i : integer; sRGBThreshold : string; Begin sRGBThreshold := IntToHex(RGBThresHold, 6); Initialize( i ); for x := 0 to Fbmp32.Width - 1 do begin for y := 0 to Fbmp32.Height - 1 do begin //if ((x = 135) and (y = 221)) then // i := i * 1; pixel := WinColor(FBmp32.Pixel[x, y]); if ( shouldBeBlackPixel( pixel, sRGBThreshold ) ) then begin Fbmp32.Pixel[x, y] := clBlack32; end else begin Fbmp32.Pixel[x, y] := clWhite32; end; end; Inc(i); end; End; function TI2XImgG32.shouldBeBlackPixel(const color: TColor; Threshold: string): boolean; var r, g, b: Byte; lColor: Longint; begin lColor := ColorToRGB(color); r := lColor; g := lColor shr 8; b := lColor shr 16; result := ( (r <= HexToByte(Copy(Threshold, 1, 2))) and (g <= HexToByte(Copy(Threshold, 3, 2))) and (b <= HexToByte(Copy(Threshold, 5, 2))) ); // result := (( color >= $00000000 ) and ( ColorToRGB(color) <= HexToInt( FRGBThreshold ) )); End; function TI2XImgG32.StripColors(Parm: string): boolean; begin Result := false; self.ParseParmString( Parm ); if ( self.ParmMustExist( 'threshold' )) then Result := StripColors( StrToInt( Parms.Items['threshold'] ) ); end; END.
unit nifti_types; {$IFDEF FPC} {$mode objfpc}{$ENDIF}{$H+} interface uses Classes, SysUtils; //, define_types; type TNIFTI2hdr = packed record //Next: analyze Format Header structure HdrSz : longint; //MUST BE 540 magic: array [1..8] of ansichar; //valid sig datatype, bitpix: word; dim: array [0..7] of int64; //unused intent_p1,intent_p2,intent_p3: double; pixdim: array [0..7] of double; //unused vox_offset: int64; scl_slope,scl_inter,cal_max,cal_min,slice_duration,toffset: double; slice_start, slice_end: int64; descrip: array[1..80] of ansichar; aux_file: array[1..24] of ansichar; qform_code, sform_code: longint; quatern_b,quatern_c,quatern_d, qoffset_x,qoffset_y,qoffset_z: double; srow_x: array[0..3]of double; srow_y: array[0..3]of double; srow_z: array[0..3]of double; slice_code, xyzt_units, intent_code: longint; intent_name: array[1..16] of ansichar; dim_info: byte; unused_str: array[1..15] of ansichar; end; //TNIFTI2hdr Header Structure TNIFTIhdr = packed record //Next: analyze Format Header structure HdrSz : longint; //MUST BE 348 Data_Type: array [1..10] of ansichar; //unused db_name: array [1..18] of ansichar; //unused extents: longint; //unused session_error: smallint; //unused regular: ansichar; ////unused: in Analyze 7.5 this must be 114 dim_info: byte; //MRI slice order dim: array[0..7] of smallint; //Data array dimensions intent_p1, intent_p2, intent_p3: single; intent_code: smallint; datatype: smallint; bitpix: smallint; slice_start: smallint; pixdim: array[0..7]of single; vox_offset: single; scl_slope: single;//scaling slope scl_inter: single;//scaling intercept slice_end: smallint; slice_code: byte; //e.g. ascending xyzt_units: byte; //e.g. mm and sec cal_max,cal_min: single; //unused slice_duration: single; //time for one slice toffset: single; //time axis to shift glmax, glmin: longint; //UNUSED descrip: array[1..80] of ansichar; aux_file: array[1..24] of ansichar; qform_code, sform_code: smallint; quatern_b,quatern_c,quatern_d, qoffset_x,qoffset_y,qoffset_z: single; srow_x: array[0..3]of single; srow_y: array[0..3]of single; srow_z: array[0..3]of single; intent_name: array[1..16] of ansichar; magic: longint; end; //TNIFTIhdr Header Structure TAnalyzeHdrSection = packed record //Next: analyze Format Header structure Pad: array [1..253] of byte; originator: array [1..5] of smallint; (* 105 + 10 *) end;//TAnalyzeHdrSection Structure const K_bz2Bytes_headerAndImageCompressed = -4; K_bz2Bytes_onlyImageCompressed = -3; K_gzBytes_headerAndImageCompressed = -2; K_gzBytes_onlyImageCompressed= -1; K_gzBytes_headerAndImageUncompressed= 0; //DataTypes kDT_BINARY =1; // binary (1 bit/voxel) kDT_UNSIGNED_CHAR =2; // unsigned char (8 bits/voxel) kDT_UINT8 = kDT_UNSIGNED_CHAR; kDT_SIGNED_SHORT =4; // signed short (16 bits/voxel) kDT_INT16 = kDT_SIGNED_SHORT; kDT_SIGNED_INT =8; // signed int (32 bits/voxel) kDT_INT32 = kDT_SIGNED_INT; kDT_FLOAT =16; // float (32 bits/voxel) kDT_FLOAT32 = kDT_FLOAT; kDT_COMPLEX =32; // complex (64 bits/voxel) kDT_DOUBLE =64; // double (64 bits/voxel) kDT_FLOAT64 = kDT_DOUBLE; kDT_RGB =128; // RGB triple (24 bits/voxel) kDT_RGBplanar3D =129; //RRR..RGGG..GBBBB...B (24 bits/voxel) entire 3D volume continguous kDT_INT8 =256; // signed char (8 bits) kDT_UINT16 =512; // unsigned short (16 bits) kDT_UINT32 =768; // unsigned int (32 bits) kDT_INT64 =1024; // long long (64 bits) kDT_UINT64 =1280; // unsigned long long (64 bits) kDT_FLOAT128 =1536; // long double (128 bits) kDT_COMPLEX128 =1792; // double pair (128 bits) kDT_COMPLEX256 =2048; // long double pair (256 bits) kDT_RGBA32 =2304; // 4 byte RGBA (32 bits/voxel) // slice_code values kNIFTI_SLICE_SEQ_UNKNOWN = 0; kNIFTI_SLICE_SEQ_INC = 1; kNIFTI_SLICE_SEQ_DEC = 2; kNIFTI_SLICE_ALT_INC = 3; kNIFTI_SLICE_ALT_DEC = 4; //xyzt_units values: note 3bit space and 3bit time packed into single byte kNIFTI_UNITS_UNKNOWN = 0; kNIFTI_UNITS_METER = 1; kNIFTI_UNITS_MM = 2; kNIFTI_UNITS_MICRON = 3; kNIFTI_UNITS_SEC = 8; kNIFTI_UNITS_MSEC = 16; kNIFTI_UNITS_USEC = 24; kNIFTI_UNITS_HZ = 32; kNIFTI_UNITS_PPM = 40; //qform_code, sform_code values kNIFTI_XFORM_UNKNOWN = 0; kNIFTI_XFORM_SCANNER_ANAT = 1;//Scanner-based anatomical coordinates kNIFTI_XFORM_ALIGNED_ANAT = 2; //Coordinates aligned to another file e.g. EPI coregistered to T1 kNIFTI_XFORM_TALAIRACH = 3; //Talairach-Tournoux Atlas; (0,0,0)=AC, etc. kNIFTI_XFORM_MNI_152 = 4; //MNI 152 normalized coordinates {$IFDEF ENDIAN_BIG} //Magic values kswapNIFTI_MAGIC_SEPARATE_HDR = $0031696E; kswapNIFTI_MAGIC_EMBEDDED_HDR = $00312B6E; kNIFTI_MAGIC_DCM = $0044434D;//DCM //byte-swapped magic values kNIFTI_MAGIC_SEPARATE_HDR = $6E693100; kNIFTI_MAGIC_EMBEDDED_HDR = $6E2B3100; {$ELSE} //Magic values kNIFTI_MAGIC_SEPARATE_HDR = $0031696E; kNIFTI_MAGIC_EMBEDDED_HDR = $00312B6E; kNIFTI_MAGIC_DCM = $0044434D;//DCM //byte-swapped magic values kswapNIFTI_MAGIC_SEPARATE_HDR = $6E693100; kswapNIFTI_MAGIC_EMBEDDED_HDR = $6E2B3100; {$ENDIF} //Statistics Intention kNIFTI_INTENT_NONE =0; kNIFTI_INTENT_CORREL =2; kNIFTI_INTENT_TTEST =3; kNIFTI_INTENT_FTEST =4; kNIFTI_INTENT_ZSCORE =5; kNIFTI_INTENT_CHISQ =6; kNIFTI_INTENT_BETA =7; kNIFTI_INTENT_BINOM =8; kNIFTI_INTENT_GAMMA =9; kNIFTI_INTENT_POISSON =10; kNIFTI_INTENT_NORMAL =11; kNIFTI_INTENT_FTEST_NONC =12; kNIFTI_INTENT_CHISQ_NONC =13; kNIFTI_INTENT_LOGISTIC =14; kNIFTI_INTENT_LAPLACE =15; kNIFTI_INTENT_UNIFORM =16; kNIFTI_INTENT_TTEST_NONC =17; kNIFTI_INTENT_WEIBULL =18; kNIFTI_INTENT_CHI =19; kNIFTI_INTENT_INVGAUSS =20; kNIFTI_INTENT_EXTVAL =21; kNIFTI_INTENT_PVAL =22; NIFTI_INTENT_LOGPVAL =23; NIFTI_INTENT_LOG10PVAL =24; kNIFTI_LAST_STATCODE = 24;//kNIFTI_INTENT_PVAL; kNIFTI_INTENT_ESTIMATE =1001; kNIFTI_FIRST_NONSTATCODE = kNIFTI_INTENT_ESTIMATE; kNIFTI_INTENT_LABEL =1002; kNIFTI_INTENT_NEURONAME =1003; kNIFTI_INTENT_GENMATRIX =1004; kNIFTI_INTENT_SYMMATRIX =1005; kNIFTI_INTENT_DISPVECT =1006; kNIFTI_INTENT_VECTOR =1007; kNIFTI_INTENT_POINTSET =1008; kNIFTI_INTENT_TRIANGLE =1009; kNIFTI_INTENT_QUATERNION =1010; procedure NII_Clear (out lHdr: TNIFTIHdr); implementation procedure NII_SetIdentityMatrix (var lHdr: TNIFTIHdr); //create neutral rotation matrix var lInc: integer; begin with lHdr do begin for lInc := 0 to 3 do srow_x[lInc] := 0; for lInc := 0 to 3 do srow_y[lInc] := 0; for lInc := 0 to 3 do srow_z[lInc] := 0; for lInc := 1 to 16 do intent_name[lInc] := chr(0); //next: create identity matrix: if code is switched on there will not be a problem srow_x[0] := 1; srow_y[1] := 1; srow_z[2] := 1; end; end; // NII_SetIdentityMatrix() procedure NII_Clear (out lHdr: TNIFTIHdr); var lInc: integer; begin with lHdr do begin HdrSz := sizeof(TNIFTIhdr); for lInc := 1 to 10 do Data_Type[lInc] := chr(0); for lInc := 1 to 18 do db_name[lInc] := chr(0); extents:=0; session_error:= 0; regular:='r'{chr(0)}; dim_info:=(0); intent_p1 := 0; intent_p2 := 0; intent_p3 := 0; intent_code:=0; datatype:=0 ; bitpix:=0; slice_start:=0; for lInc := 1 to 7 do pixdim[linc]:= 1.0; vox_offset:= 0.0; scl_slope := 1.0; scl_inter:= 0.0; slice_end:= 0; slice_code := 0; xyzt_units := 10; cal_max:= 0.0; cal_min:= 0.0; slice_duration:=0; toffset:= 0; glmax:= 0; glmin:= 0; for lInc := 1 to 80 do descrip[lInc] := chr(0);{80 spaces} for lInc := 1 to 24 do aux_file[lInc] := chr(0);{80 spaces} {below are standard settings which are not 0} bitpix := 16;//vc16; {8bits per pixel, e.g. unsigned char 136} DataType := 4;//vc4;{2=unsigned char, 4=16bit int 136} Dim[0] := 3; Dim[1] := 256; Dim[2] := 256; Dim[3] := 1; Dim[4] := 1; {n vols} Dim[5] := 1; Dim[6] := 1; Dim[7] := 1; glMin := 0; glMax := 255; qform_code := kNIFTI_XFORM_UNKNOWN; sform_code:= kNIFTI_XFORM_UNKNOWN; quatern_b := 0; quatern_c := 0; quatern_d := 0; qoffset_x := 0; qoffset_y := 0; qoffset_z := 0; NII_SetIdentityMatrix(lHdr); magic := kNIFTI_MAGIC_SEPARATE_HDR; end; //with the NIfTI header... end; // NII_Clear() end.
unit fIntegrateX; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls, Vcl.Menus, Vcl.ExtCtrls; type TIntegrateXForm = class(TForm) Label3: TLabel; Label1: TLabel; Label4: TLabel; MinIntegXLabel: TLabel; Label6: TLabel; ColorButton: TSpeedButton; Label5: TLabel; AreaLabel: TLabel; Label7: TLabel; PositiveButton: TSpeedButton; NegativeButton: TSpeedButton; MaxIntegXLabel: TLabel; NegAreaLabel: TLabel; PosAreaLabel: TLabel; MinIntegYLabel: TLabel; MaxIntegYLabel: TLabel; TotalAreaLabel: TLabel; CentreButton: TSpeedButton; EditIntegMin: TEdit; EditIntegMax: TEdit; EditCount: TEdit; UpDown1: TUpDown; RecalcBtn: TBitBtn; CloseBtn: TBitBtn; EditPenWidth: TEdit; UpDown2: TUpDown; EditConst: TEdit; IntegCheckBox: TCheckBox; ShadeCheckBox: TCheckBox; EditOpacity: TEdit; UpDown3: TUpDown; ColorDialog: TColorDialog; Label2: TLabel; KeepRangeCheckBox: TCheckBox; ColorPanel: TPanel; NegativePanel: TPanel; PositivePanel: TPanel; SumAreaLabel: TLabel; procedure FormShow(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormDeactivate(Sender: TObject); procedure ParseKeyPress(Sender: TObject; var Key: Char); procedure IntKeyPress(Sender: TObject; var Key: Char); procedure EditIntegMinKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIntegMaxKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditCountKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditConstKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditPenWidthKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditOpacityKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditCountExit(Sender: TObject); procedure UpDown1Click(Sender: TObject; Button: TUDBtnType); procedure UpDown2Click(Sender: TObject; Button: TUDBtnType); procedure UpDown3Click(Sender: TObject; Button: TUDBtnType); procedure UpDown1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure CheckBoxClick(Sender: TObject); procedure CentreButtonClick(Sender: TObject); procedure ColorButtonClick(Sender: TObject); procedure PositiveButtonClick(Sender: TObject); procedure NegativeButtonClick(Sender: TObject); procedure RecalcBtnClick(Sender: TObject); procedure CloseBtnClick(Sender: TObject); procedure IntegLabelClick(Sender: TObject); procedure KeepRangeCheckBoxClick(Sender: TObject); private procedure UpdateRangeData; public PlotIntegrated: byte; { piCalc = 0; piShow = 1; piArea = 2; piBoth = 3 } procedure ShowData; end; var IntegrateXForm: TIntegrateXForm; //====================================================================== implementation //====================================================================== uses uParser, uGlobal, fFuncts, fMain, Clipbrd; {$R *.dfm} procedure TIntegrateXForm.FormShow(Sender: TObject); begin KeepRangeCheckBox.Checked := KeepRange; ShowData; end; procedure TIntegrateXForm.FormActivate(Sender: TObject); begin EditIntegMin.SetFocus; EditIntegMin.SelText; end; procedure TIntegrateXForm.FormKeyPress(Sender: TObject; var Key: Char); begin case Key of #13:begin RecalcBtnClick(Sender); Key := #0; end; #27:begin Key := #0; Close; end; end; end; procedure TIntegrateXForm.FormDeactivate(Sender: TObject); begin if KeepRange then UpdateRangeData; end; procedure TIntegrateXForm.ParseKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do begin if not CharInSet(UpCase(Key), [' ', '!', '(', ')', '*', '+', '-', '.', ',', '/', '0'..'9', 'A'..'C', 'E', 'G'..'I', 'L', 'N'..'T', 'X', '^', '`', #8]) then begin Key := #0; Exit; end; if Key = '`' then Key := '°'; end; end; procedure TIntegrateXForm.IntKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do if not CharInSet(Key, ['0'..'9', #8]) then Key := #0 end; procedure TIntegrateXForm.EditIntegMinKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var s: string; e: byte; begin s := ScanText(EditIntegMin.Text); IntegMin := ParseAndEvaluate(s, e); //if isNAN(IntegMin) then IntegMin := 0; //if e > 0 then IntegMin := 0; if isNAN(IntegMin) or isInfinite(IntegMin) or (e > 0) then IntegMin := 0; end; procedure TIntegrateXForm.EditIntegMaxKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var s: string; e: byte; begin s := ScanText(EditIntegMax.Text); IntegMax := ParseAndEvaluate(s, e); // if isNAN(IntegMax) then IntegMax := 0; // if e > 0 then IntegMax := 0; if isNAN(IntegMax) or isInfinite(IntegMax) or (e > 0) then IntegMax := 0; end; procedure TIntegrateXForm.EditCountKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin with GraphData do begin try IntegCount := StrToInt(EditCount.Text); if IntegCount = 0 then IntegCount := IntegCountPos; except IntegCount := IntegCountPos; end; if IntegCount > IntegCountMax then IntegCount := IntegCountMax; end; Altered := true; end; procedure TIntegrateXForm.EditConstKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin try IntegConst := StrToFloat(EditConst.Text); except IntegConst := 0; end; end; procedure TIntegrateXForm.EditPenWidthKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin try GraphData.ydxWidth := StrToInt(EditPenWidth.Text); if Graphdata.ydxWidth = 0 then GraphData.ydxWidth := 1; except GraphData.ydxWidth := 1; end; Altered := true; MainForm.GLViewer.Invalidate; end; procedure TIntegrateXForm.EditOpacityKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var n: integer; begin try n := StrToInt(EditOpacity.Text); except n := 1; end; GraphData.AreaAlpha := n/100; Altered := true; MainForm.GLViewer.Invalidate; end; procedure TIntegrateXForm.EditCountExit(Sender: TObject); begin EditCount.Text := IntToStr(GraphData.IntegCount); end; procedure TIntegrateXForm.UpDown1Click(Sender: TObject; Button: TUDBtnType); var k: word; begin k := 0; EditCountKeyUp(Sender, k, []); end; procedure TIntegrateXForm.UpDown2Click(Sender: TObject; Button: TUDBtnType); var k: word; begin k := 0; EditPenWidthKeyUp(Sender, k, []); end; procedure TIntegrateXForm.UpDown3Click(Sender: TObject; Button: TUDBtnType); var k: word; begin k := 0; EditOpacityKeyUp(Sender, k, []); end; procedure TIntegrateXForm.UpDown1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RecalcBtnClick(Sender); end; procedure TIntegrateXForm.CheckBoxClick(Sender: TObject); begin with Sender as TCheckBox do if Checked then begin { tag = piShow for IntegCheckBox; piArea for ShadeCheckBox } if not Ord(PlotIntegrated) and Tag = Tag then Inc(PlotIntegrated, Tag); { now selected } end else if Ord(PlotIntegrated) and Tag = Tag then Dec(PlotIntegrated, Tag); { now de-selected } RecalcBtnClick(Sender); end; procedure TIntegrateXForm.CentreButtonClick(Sender: TObject); var y1, y2: extended; begin y1 := StrToFloat(Copy(MinIntegYLabel.Caption, pos('=', MinIntegYLabel.Caption)+2, Length(MinIntegYLabel.Caption))); y2 := StrToFloat(Copy(MaxIntegYLabel.Caption, pos('=', MaxIntegYLabel.Caption)+2, Length(MaxIntegYLabel.Caption))); IntegConst := IntegConst-(y1 + y2)/2; EditConst.Text := FloatToStr(IntegConst); RecalcBtnclick(Sender); end; procedure TIntegrateXForm.ColorButtonClick(Sender: TObject); begin ColorDialog.Color := GraphData.ydxColor; if ColorDialog.Execute then begin GraphData.ydxColor := ColorDialog.Color; ColorPanel.Color := GraphData.ydxColor; MainForm.GLViewer.Invalidate; Altered := TRUE end; end; procedure TIntegrateXForm.PositiveButtonClick(Sender: TObject); begin ColorDialog.Color := GraphData.PosAreaColor; if ColorDialog.Execute then begin GraphData.PosAreaColor := ColorDialog.Color; PositivePanel.Color := GraphData.PosAreaColor; MainForm.GLViewer.Invalidate; Altered := TRUE end; end; procedure TIntegrateXForm.NegativeButtonClick(Sender: TObject); begin ColorDialog.Color := GraphData.NegAreaColor; if ColorDialog.Execute then begin GraphData.NegAreaColor := ColorDialog.Color; NegativePanel.Color := GraphData.NegAreaColor; MainForm.GLViewer.Invalidate; Altered := TRUE end; end; procedure TIntegrateXForm.RecalcBtnClick(Sender: TObject); begin MainForm.GLViewer.Invalidate; end; procedure TIntegrateXForm.IntegLabelClick(Sender: TObject); begin Clipboard.Clear; with Sender as TLabel do Clipboard.AsText := Copy(Caption, pos('=', Caption)+2, Length(Caption)); end; procedure TIntegrateXForm.KeepRangeCheckBoxClick(Sender: TObject); begin KeepRange := KeepRangeCheckBox.Checked; end; procedure TIntegrateXForm.CloseBtnClick(Sender: TObject); begin Close; end; procedure TIntegrateXForm.UpdateRangeData; begin KeptMin := IntegMin; KeptMax := IntegMax; end; procedure TIntegrateXForm.ShowData; begin with GraphData, PlotData do begin EditCount.Text := IntToStr(IntegCount); UpDown2.Position := ydxWidth; UpDown3.Position := round(AreaAlpha*100); KeepRangeCheckBox.Checked := KeepRange; ColorPanel.Color := ydxColor; PositivePanel.Color := PosAreaColor; NegativePanel.Color := NegAreaColor; if PlotAsFx then begin if TextStr = '' then Caption := '' else Caption := 'y = '+TextStr; if IsSegment then begin if KeepRange then begin IntegMin := KeptMin; IntegMax := KeptMax; end else begin IntegMin := SegMin; IntegMax := SegMax; end; end else begin if KeepRange then begin IntegMin := KeptMin; IntegMax := KeptMax; end else begin IntegMin := xMin; IntegMax := xMax; end; end; Label1.Caption := 'where a = x1'; Label2.Caption := 'and b = x2'; Label5.Caption := 'Integral y at a = x1:'; CentreButton.Caption := 'Centre to x a&xis'; end else begin Caption := 'r = '+TextStr; if KeepRange then begin IntegMin := KeptMin; IntegMax := KeptMax; end else begin IntegMin := SegMin; IntegMax := SegMax; end; Label1.Caption := 'For a = Ø1'; Label2.Caption := 'b = Ø2 (radians)'; Label5.Caption := 'Integral r at (a = Ø1):'; CentreButton.Caption := 'Centre to x a&xis'; end; end; EditIntegMin.Text := FloatToStrF(IntegMin, ffGeneral, 13, 4); EditIntegMax.Text := FloatToStrF(IntegMax, ffGeneral, 13, 4); EditConst.Text := FloatToStrF(IntegConst, ffGeneral, 13, 4); end; end.
unit uDialogs; (* ╔═════════════════════════════╗ ║ created by: warleyalex ║ ╚═════════════════════════════╝ *) {$mode objfpc}{$H+} {$MODESWITCH externalclass} interface uses Classes, SysUtils, Types, JS, Web; type aCallBack = procedure(data: JSValue) of object; aCancelCallBack = procedure(data: JSValue) of object; aLoginCallBack = procedure(username, password: string) of object; aPasswordOKCallBack = procedure(password: string) of object; TProcedure = procedure of object; type TDialog = class external name 'pas2js.dialogs' public constructor New; overload; function modal(params: JSValue): TDialog; function alert(text: string): TDialog; overload; function alert(text: string; title: string): TDialog; overload; function alert(text: string; callbackOk: TProcedure): TDialog; overload; function alert(text: string; title: string; callbackOk: TProcedure): TDialog; overload; function confirm(text: string): TDialog; overload; function confirm(text: string; title: string): TDialog; overload; function confirm(text: string; callbackOk: TProcedure): TDialog; overload; function confirm(text: string; title: string; callbackOk: TProcedure): TDialog; overload; function confirm(text: string; callbackOk: TProcedure; callbackCancel: TProcedure): TDialog; overload; function confirm(text: string; title: string; callbackOk: TProcedure; callbackCancel: TProcedure): TDialog; overload; function prompt(text: string): TDialog; overload; function prompt(text: string; title: string): TDialog; overload; function prompt(text: string; callbackOk: aCallBack): TDialog; overload; function prompt(text: string; callbackOk: aCallBack; callbackCancel: aCancelCallBack): TDialog; overload; function prompt(text: string; title: string; callbackOk: aCallBack): TDialog; overload; function prompt(text: string; title: string; callbackOk: aCallBack; callbackCancel: aCancelCallBack): TDialog; overload; function modalLogin(text: string): TDialog; overload; function modalLogin(text: string; title: string): TDialog; overload; function modalLogin(text: string; title: string; callbackOk: aLoginCallBack): TDialog; overload; function modalLogin(text: string; callbackOk: aLoginCallBack): TDialog; overload; function modalLogin(text: string; title: string; callbackOk: aLoginCallBack; callbackCancel: aLoginCallBack): TDialog; overload; function modalPassword(text: string): TDialog; overload; function modalPassword(text: string; title: string): TDialog; overload; function modalPassword(text: string; title: string; callbackOk: aPasswordOKCallBack): TDialog; overload; function modalPassword(text: string; callbackOk: aPasswordOKCallBack): TDialog; overload; function modalPassword(text: string; title: string; callbackOk: aPasswordOKCallBack; callbackCancel: TProcedure): TDialog; overload; function showPreloader: TDialog; overload; function showPreloader(text: string): TDialog; overload; function hidePreloader(): TDialog; function showIndicator(): TDialog; function hideIndicator(): TDialog; function actions(params: JSValue): TDialog; function openModal(modal: JSValue): TDialog; function closeModal(modal: JSValue): TDialog; end; implementation end.
{ Red-black tree class, based on the STL tree implementation of gcc-3.4.4 (/libstdc++-v3/include/bits/stl_tree.h and /libstdc++-v3/src/tree.cc) of which the insertion and deletion algorithms are based on those in Cormen, Leiserson and Rivest, Introduction to Algorithms (MIT Press, 1990). This unit should work ok with Borland Delphi and Free Pascal (I used fpc-2.0.0 with the -Sd commandline switch). USAGE The TRBTree class behaves somewhat like a TList: it stores pointers and uses the same comparison function as TList.Sort (TListSortCompare). Functions Clear, Add, Delete, First and Last are equivalent, except that First and Last return a TRBNodeP instead of its key so they can be used for comparisons in loops. All values occur only once in the tree: when the same value is added twice, the second one is not stored. To be able to manage the tree, the Create constructor has a argument specifying the comparison function that should be used. The function Find can be used to find a value that was put in the tree, it searches for the given pointer using the comparison function given at time of object creation. It returns a TRBNodeP. The functions RBInc and RBDec can be used to "walk" through the tree: given a TRBNodeP x, RBInc returns the TRBNodeP with the smallest key that is larger than x, RBDec returns the TRBNodeP with the largest key that is smaller than x. RBInc(tree.Last) and RBDec(tree.First) are not defined. EXAMPLE An example for usage of this unit can be found at http://www.vanwal.nl/rbtree/example.dpr COMPLEXITY Create, First and Last are done in constant time. Find, Add, Delete, RBInc and RBDec take O(log n) time, where n is the number of items in the tree. Destroy and Clear take O(n) time. AUTHOR Written (or "translated" ;-)) by Freek van Walderveen, November 2005. Includes bug fixes by Jani Mбtyбs, July 2008. LICENCE This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. See http://www.gnu.org/copyleft/gpl.html This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. As a special exception, you may use this file as part of a free software library without restriction. Specifically, if you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. } unit rbtree; interface uses Classes; type TColor = (clRed, clBlack); TRBNodeP = ^TRBNode; TRBNode = record k: Pointer; left, right, parent: TRBNodeP; color: TColor; end; TRBTree = class private root: TRBNodeP; leftmost: TRBNodeP; rightmost: TRBNodeP; compareFunc: TListSortCompare; procedure RotateLeft(var x: TRBNodeP); procedure RotateRight(var x: TRBNodeP); function Minimum(var x: TRBNodeP): TRBNodeP; function Maximum(var x: TRBNodeP): TRBNodeP; public constructor Create(Compare: TListSortCompare); destructor Destroy(); override; procedure Clear(); function Find(key: Pointer): TRBNodeP; function Add(key: Pointer): TRBNodeP; procedure Delete(z: TRBNodeP); property First: TRBNodeP read leftmost; property Last: TRBNodeP read rightmost; end; { class TRBTree } procedure RBInc(var x: TRBNodeP); procedure RBDec(var x: TRBNodeP); implementation constructor TRBTree.Create(Compare: TListSortCompare); begin inherited Create; compareFunc := Compare; root := nil; leftmost := nil; rightmost := nil; end; destructor TRBTree.Destroy(); begin Clear(); inherited Destroy; end; procedure fast_erase(x: TRBNodeP); begin if (x^.left <> nil) then fast_erase(x^.left); if (x^.right <> nil) then fast_erase(x^.right); dispose(x); end; procedure TRBTree.Clear(); begin if (root <> nil) then fast_erase(root); root := nil; leftmost := nil; rightmost := nil; end; function TRBTree.Find(key: Pointer): TRBNodeP; var cmp: integer; begin Result := root; while (Result <> nil) do begin cmp := compareFunc(Result^.k, key); if cmp < 0 then begin Result := Result^.right; end else if cmp > 0 then begin Result := Result^.left; end else begin break; end; end; end; procedure TRBTree.RotateLeft(var x: TRBNodeP); var y: TRBNodeP; begin y := x^.right; x^.right := y^.left; if (y^.left <> nil) then begin y^.left^.parent := x; end; y^.parent := x^.parent; if (x = root) then begin root := y; end else if (x = x^.parent^.left) then begin x^.parent^.left := y; end else begin x^.parent^.right := y; end; y^.left := x; x^.parent := y; end; procedure TRBTree.RotateRight(var x: TRBNodeP); var y: TRBNodeP; begin y := x^.left; x^.left := y^.right; if (y^.right <> nil) then begin y^.right^.parent := x; end; y^.parent := x^.parent; if (x = root) then begin root := y; end else if (x = x^.parent^.right) then begin x^.parent^.right := y; end else begin x^.parent^.left := y; end; y^.right := x; x^.parent := y; end; function TRBTree.Minimum(var x: TRBNodeP): TRBNodeP; begin Result := x; while (Result^.left <> nil) do Result := Result^.left; end; function TRBTree.Maximum(var x: TRBNodeP): TRBNodeP; begin Result := x; while (Result^.right <> nil) do Result := Result^.right; end; function TRBTree.Add(key: Pointer): TRBNodeP; var x, y, z, zpp: TRBNodeP; cmp: Integer; begin z := New(TRBNodeP); { Initialize fields in new node z } z^.k := key; z^.left := nil; z^.right := nil; z^.color := clRed; Result := z; { Maintain leftmost and rightmost nodes } if ((leftmost = nil) or (compareFunc(key, leftmost^.k) < 0)) then begin leftmost := z; end; if ((rightmost = nil) or (compareFunc(rightmost^.k, key) < 0)) then begin rightmost := z; end; { Insert node z } y := nil; x := root; while (x <> nil) do begin y := x; cmp := compareFunc(key, x^.k); if (cmp < 0) then begin x := x^.left; end else if (cmp > 0) then begin x := x^.right; end else begin { Value already exists in tree. } Result := x; dispose(z); exit; end; end; z^.parent := y; if (y = nil) then begin root := z; end else if (compareFunc(key, y^.k) < 0) then begin y^.left := z; end else begin y^.right := z; end; { Rebalance tree } while ((z <> root) and (z^.parent^.color = clRed)) do begin zpp := z^.parent^.parent; if (z^.parent = zpp^.left) then begin y := zpp^.right; if ((y <> nil) and (y^.color = clRed)) then begin z^.parent^.color := clBlack; y^.color := clBlack; zpp^.color := clRed; z := zpp; end else begin if (z = z^.parent^.right) then begin z := z^.parent; rotateLeft(z); end; z^.parent^.color := clBlack; zpp^.color := clRed; rotateRight(zpp); end; end else begin y := zpp^.left; if ((y <> nil) and (y^.color = clRed)) then begin z^.parent^.color := clBlack; y^.color := clBlack; zpp^.color := clRed; z := zpp; end else begin if (z = z^.parent^.left) then begin z := z^.parent; rotateRight(z); end; z^.parent^.color := clBlack; zpp^.color := clRed; rotateLeft(zpp); end; end; end; root^.color := clBlack; end; procedure TRBTree.Delete(z: TRBNodeP); var w, x, y, x_parent: TRBNodeP; tmpcol: TColor; begin y := z; x := nil; x_parent := nil; if (y^.left = nil) then begin { z has at most one non-null child. y = z. } x := y^.right; { x might be null. } end else begin if (y^.right = nil) then begin { z has exactly one non-null child. y = z. } x := y^.left; { x is not null. } end else begin { z has two non-null children. Set y to } y := y^.right; { z's successor. x might be null. } while (y^.left <> nil) do begin y := y^.left; end; x := y^.right; end; end; if (y <> z) then begin { "copy y's sattelite data into z" } { relink y in place of z. y is z's successor } z^.left^.parent := y; y^.left := z^.left; if (y <> z^.right) then begin x_parent := y^.parent; if (x <> nil) then begin x^.parent := y^.parent; end; y^.parent^.left := x; { y must be a child of left } y^.right := z^.right; z^.right^.parent := y; end else begin x_parent := y; end; if (root = z) then begin root := y; end else if (z^.parent^.left = z) then begin z^.parent^.left := y; end else begin z^.parent^.right := y; end; y^.parent := z^.parent; tmpcol := y^.color; y^.color := z^.color; z^.color := tmpcol; y := z; { y now points to node to be actually deleted } end else begin { y = z } x_parent := y^.parent; if (x <> nil) then begin x^.parent := y^.parent; end; if (root = z) then begin root := x; end else begin if (z^.parent^.left = z) then begin z^.parent^.left := x; end else begin z^.parent^.right := x; end; end; if (leftmost = z) then begin if (z^.right = nil) then begin { z^.left must be null also } leftmost := z^.parent; end else begin leftmost := minimum(x); end; end; if (rightmost = z) then begin if (z^.left = nil) then begin { z^.right must be null also } rightmost := z^.parent; end else begin { x == z^.left } rightmost := maximum(x); end; end; end; { Rebalance tree } if (y^.color = clBlack) then begin while ((x <> root) and ((x = nil) or (x^.color = clBlack))) do begin if (x = x_parent^.left) then begin w := x_parent^.right; if (w^.color = clRed) then begin w^.color := clBlack; x_parent^.color := clRed; rotateLeft(x_parent); w := x_parent^.right; end; if (((w^.left = nil) or (w^.left^.color = clBlack)) and ((w^.right = nil) or (w^.right^.color = clBlack))) then begin w^.color := clRed; x := x_parent; x_parent := x_parent^.parent; end else begin if ((w^.right = nil) or (w^.right^.color = clBlack)) then begin w^.left^.color := clBlack; w^.color := clRed; rotateRight(w); w := x_parent^.right; end; w^.color := x_parent^.color; x_parent^.color := clBlack; if (w^.right <> nil) then begin w^.right^.color := clBlack; end; rotateLeft(x_parent); x := root; { break; } end end else begin { same as above, with right <^. left. } w := x_parent^.left; if (w^.color = clRed) then begin w^.color := clBlack; x_parent^.color := clRed; rotateRight(x_parent); w := x_parent^.left; end; if (((w^.right = nil) or (w^.right^.color = clBlack)) and ((w^.left = nil) or (w^.left^.color = clBlack))) then begin w^.color := clRed; x := x_parent; x_parent := x_parent^.parent; end else begin if ((w^.left = nil) or (w^.left^.color = clBlack)) then begin w^.right^.color := clBlack; w^.color := clRed; rotateLeft(w); w := x_parent^.left; end; w^.color := x_parent^.color; x_parent^.color := clBlack; if (w^.left <> nil) then begin w^.left^.color := clBlack; end; rotateRight(x_parent); x := root; { break; } end; end; end; if (x <> nil) then begin x^.color := clBlack; end; end; dispose(y); end; (*{ Pr e: x <> las 't' }*) 'hhhhh'#26'fwef{rewetgwert' //} procedure RBInc(var x: TRBNodeP); var y: TRBNodeP; begin if (x^.right <> nil) then begin x := x^.right; while (x^.left <> nil) do begin x := x^.left; end; end else begin y := x^.parent; while (x = y^.right) do begin x := y; y := y^.parent; end; if (x^.right <> y) then x := y; end end; {(* Pr e: x } } //*) <> 'first' // } procedure RBDec(var x: TRBNodeP); var y: TRBNodeP; begin if (x^.left <> nil) then begin y := x^.left; while (y^.right <> nil) do begin y := y^.right; end; x := y; end else begin y := x^.parent; while (x = y^.left) do begin x := y; y := y^.parent; end; x := y; end end; end.
// // Title: SFDBGrid // // Description: An extension to TDBGrid that fixes the partial problems of customizing scollbars // // Created by: Frank Huber // // Copyright: Frank Huber - The SoftwareFactory - // Alberweilerstr. 1 // D-88433 Schemmerhofen // // http://www.thesoftwarefactory.de // unit SFDBGrid; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.Grids, Vcl.DBGrids, Winapi.Windows, Vcl.Themes, Data.DB, Winapi.Messages; type TSFDBGridExtOption = ( extOptDisableDataDelete, extOptDisableDataAppend ); TSFDBGridExtOptions = set of TSFDBGridExtOption; TSFDBGrid = class(TDBGrid) private mColumnAdjustment: Boolean; mOnMouseDown: TMouseEvent; mMouseDownFired: Boolean; mDeletedOptions: TDBGridOptions; mExtOptions: TSFDBGridExtOptions; private procedure adjustColumns(pNewW, pOldW: Integer); function getColumnsWidth: Integer; procedure setColumnAdjustment(pVal: Boolean); procedure parentMouseDownEvt(pSender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure WMSetFocus(var Message: TWMSetFocus); message WM_SetFOCUS; procedure adjustColumnEditing; protected procedure Resize; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure ColEnter; override; public procedure Assign(Source: TPersistent); override; procedure UpdateScrollBar; override; public constructor Create(pOwner: TComponent); override; published property ColumnAdjustment: Boolean read mColumnAdjustment write setColumnAdjustment; property OnMouseDown: TMouseEvent read mOnMouseDown write mOnMouseDown; property OptionsExt: TSFDBGridExtOptions read mExtOptions write mExtOptions; property OnResize; end; implementation constructor TSFDBGrid.Create(pOwner: TComponent); begin inherited; mOnMouseDown := nil; inherited OnMouseDown := parentMouseDownEvt; mMouseDownFired := False; mDeletedOptions := []; mExtOptions := [extOptDisableDataDelete]; end; procedure TSFDBGrid.UpdateScrollBar; var lOldScrollInfo, lNewScrollInfo: TScrollInfo; lScrollBarVisible: Boolean; begin if (Datalink.Active) and (HandleAllocated) then begin with Datalink.DataSet do begin lOldScrollInfo.cbSize := sizeof(lOldScrollInfo); lOldScrollInfo.fMask := SIF_ALL; GetScrollInfo(Self.Handle, SB_VERT, lOldScrollInfo); lNewScrollInfo := lOldScrollInfo; if IsSequenced then begin lScrollBarVisible := (RecordCount > Self.VisibleRowCount); if (lScrollBarVisible) then begin lNewScrollInfo.nMin := 1; lNewScrollInfo.nPage := Self.VisibleRowCount; lNewScrollInfo.nMax := Integer(DWORD(RecordCount) + lNewScrollInfo.nPage - 1); if State in [dsInactive, dsBrowse, dsEdit] then lNewScrollInfo.nPos := RecNo; // else keep old pos end else begin lNewScrollInfo.nMin := Self.VisibleRowCount; lNewScrollInfo.nPage := lNewScrollInfo.nMin; lNewScrollInfo.nMax := lNewScrollInfo.nMin; lNewScrollInfo.nPos := 1; end; end else begin lScrollBarVisible := True; lNewScrollInfo.nMin := 0; lNewScrollInfo.nPage := 0; lNewScrollInfo.nMax := 4; if (DataLink.BOF) then lNewScrollInfo.nPos := 0 else if (DataLink.EOF) then lNewScrollInfo.nPos := 4 else lNewScrollInfo.nPos := 2; end; // mHasVertScrollBar := lScrollBarVisible; ShowScrollBar(Self.Handle, SB_VERT, lScrollBarVisible); SetScrollInfo(Self.Handle, SB_VERT, lNewScrollInfo, True); if TStyleManager.IsCustomStyleActive then SendMessage(Handle, WM_NCPAINT, 0, 0); end; end; end; procedure TSFDBGrid.Resize; begin if (mColumnAdjustment) then adjustColumns(ClientWidth, getColumnsWidth); inherited; end; procedure TSFDBGrid.KeyDown(var Key: Word; Shift: TShiftState); var lReadOnly: Boolean; begin lReadOnly := ReadOnly; try if (Key = VK_DELETE) and (ssCtrl in Shift) then ReadOnly := ReadOnly or (extOptDisableDataDelete in mExtOptions) else begin case Key of VK_DOWN, VK_RIGHT, VK_TAB: ReadOnly := ReadOnly or (extOptDisableDataAppend in mExtOptions); end; end; inherited; finally ReadOnly := lReadOnly; end; end; procedure TSFDBGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mMouseDownFired := False; try inherited; if not(mMouseDownFired) then parentMouseDownEvt(Self, Button, Shift, X, Y); finally mMouseDownFired := False; end; end; procedure TSFDBGrid.ColEnter; begin adjustColumnEditing; inherited; end; procedure TSFDBGrid.Assign(Source: TPersistent); begin inherited; if (Source is TSFDBGrid) then begin ColumnAdjustment := TSFDBGrid(Source).ColumnAdjustment; OptionsExt := TSFDBGrid(Source).OptionsExt; end; end; procedure TSFDBGrid.adjustColumns(pNewW, pOldW: Integer); var lFactor: Real; i, lNewW: Integer; begin if (pNewW <= 0) or (pOldW <= 0) then Exit; lNewW := pNewW - 5; if (dgIndicator in Options) then lNewW := lNewW - 15; if (lNewW <> pOldW) then begin BeginUpdate; try lFactor := lNewW / pOldW; for i := 0 to (Columns.Count - 1) do Columns[i].Width := Round(Columns[i].Width * lFactor); finally EndUpdate; end; end; end; function TSFDBGrid.getColumnsWidth: Integer; var i: Integer; begin Result := 0; for i := 0 to (Columns.Count - 1) do Result := Result + Columns[i].Width; end; procedure TSFDBGrid.setColumnAdjustment(pVal: Boolean); begin if (pVal <> mColumnAdjustment) then begin mColumnAdjustment := pVal; adjustColumns(ClientWidth, getColumnsWidth); end; end; procedure TSFDBGrid.parentMouseDownEvt(pSender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Assigned(mOnMouseDown)) then mOnMouseDown(pSender, Button, Shift, X, Y); mMouseDownFired := True; end; procedure TSFDBGrid.WMSetFocus(var Message: TWMSetFocus); begin adjustColumnEditing; inherited; end; procedure TSFDBGrid.adjustColumnEditing; begin Options := Options + mDeletedOptions; if (SelectedIndex < Columns.Count) then begin if (dgEditing in Options) and not(dgAlwaysShowEditor in Options) and (Columns.Items[SelectedIndex].ReadOnly) then begin Options := Options - [dgEditing]; mDeletedOptions := mDeletedOptions + [dgEditing]; end; end; end; end.
unit frmMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Actions, System.DateUtils, System.SyncObjs, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ActnList, FMX.Memo.Types, FMX.ScrollBox, FMX.Edit, FMX.EditBox, FMX.SpinBox, FMX.Memo, FMX.Layouts, Kafka.Lib, Kafka.Factory, Kafka.Interfaces, Kafka.Helper, Kafka.Types; type EKafkaError = class(Exception); TfrmKafkaDemo = class(TForm) ActionList1: TActionList; actProduceMessage: TAction; actStartConsuming: TAction; tmrUpdate: TTimer; actStopConsuming: TAction; GridPanelLayout1: TGridPanelLayout; actFlush: TAction; GroupBox2: TGroupBox; layConsumeControl: TLayout; btnConsumingStart: TButton; Button3: TButton; memLogConsumer: TMemo; GroupBox1: TGroupBox; Layout3: TLayout; edtMessageCount: TSpinBox; Button1: TButton; Button4: TButton; chkFlushAfterProduce: TCheckBox; memLogProducer: TMemo; chkLogProduceCallbacks: TCheckBox; chkLogConsumeCallbacks: TCheckBox; Options: TGroupBox; memLogOther: TMemo; lblStatus: TLabel; GroupBox3: TGroupBox; Layout1: TLayout; Label1: TLabel; edtKafkaServer: TEdit; Layout2: TLayout; Label2: TLabel; edtTopic: TEdit; Layout4: TLayout; Label3: TLabel; edtMessage: TEdit; procedure actProduceMessageExecute(Sender: TObject); procedure actStartConsumingExecute(Sender: TObject); procedure tmrUpdateTimer(Sender: TObject); procedure actStopConsumingExecute(Sender: TObject); procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean); procedure actFlushExecute(Sender: TObject); procedure layConsumeControlResize(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure edtKafkaServerChange(Sender: TObject); procedure edtTopicChange(Sender: TObject); private FKafkaProducer: IKafkaProducer; FKafkaConsumer: IKafkaConsumer; procedure OnLog(const Values: TStrings); procedure UpdateStatus; procedure DestroyClasses; public constructor Create(AOwner: TComponent); override; end; var frmKafkaDemo: TfrmKafkaDemo; implementation {$R *.fmx} { TfrmKafkaDemo } procedure TfrmKafkaDemo.OnLog(const Values: TStrings); var i: Integer; Memo: TMemo; begin for i := 0 to pred(Values.Count) do begin case TKafkaLogType(Values.Objects[i]) of kltProducer: Memo := memLogProducer; kltConsumer: Memo := memLogConsumer; else Memo := memLogOther; end; if (Memo = memLogOther) or ((chkLogProduceCallbacks.IsChecked) and (Memo = memLogProducer)) or ((chkLogConsumeCallbacks.IsChecked) and (Memo = memLogConsumer)) then begin Memo.Lines.Add(Values[i]); end; end; end; procedure TfrmKafkaDemo.actStartConsumingExecute(Sender: TObject); begin if FKafkaConsumer = nil then begin FKafkaConsumer := TKafkaFactory.NewConsumer( ['group.id'], ['GroupID'], ['auto.offset.reset'], ['earliest'], edtKafkaServer.Text, [edtTopic.Text], [0], procedure(const Msg: prd_kafka_message_t) begin // This is called from the consumer thread, but TKafka.Log is threadsafe TKafkaHelper.Log(format('Message received - %s', [TKafkaHelper.PointerToStr(Msg.payload, Msg.len)]), TKafkaLogType.kltConsumer); end); end; end; procedure TfrmKafkaDemo.actStopConsumingExecute(Sender: TObject); begin FKafkaConsumer := nil; end; procedure TfrmKafkaDemo.actFlushExecute(Sender: TObject); begin TKafkaHelper.Flush(FKafkaProducer.KafkaHandle); end; procedure TfrmKafkaDemo.ActionList1Update(Action: TBasicAction; var Handled: Boolean); begin actStartConsuming.Enabled := (FKafkaConsumer = nil) and (edtKafkaServer.Text <> ''); actStopConsuming.Enabled := FKafkaConsumer <> nil; actFlush.Enabled := FKafkaProducer <> nil; Handled := True; end; procedure TfrmKafkaDemo.actProduceMessageExecute(Sender: TObject); var Msgs: TArray<String>; i: Integer; begin if FKafkaProducer = nil then begin FKafkaProducer := TKafkaFactory.NewProducer( ['bootstrap.servers'], [edtKafkaServer.Text]); end; SetLength(Msgs, Trunc(edtMessageCount.Value)); for i := 0 to pred(Trunc(edtMessageCount.Value)) do begin Msgs[i] := edtMessage.Text + ' - ' + DateTimeToStr(now) + '.' + MilliSecondOf(now).ToString.PadLeft(3, '0'); end; FKafkaProducer.Produce( edtTopic.Text, Msgs, nil, 0, RD_KAFKA_PARTITION_UA, RD_KAFKA_MSG_F_COPY, nil); if chkFlushAfterProduce.IsChecked then begin TKafkaHelper.Flush(FKafkaProducer.KafkaHandle); end; end; constructor TfrmKafkaDemo.Create(AOwner: TComponent); begin inherited; TKafkaHelper.OnLog := OnLog; UpdateStatus; end; procedure TfrmKafkaDemo.edtKafkaServerChange(Sender: TObject); begin DestroyClasses; end; procedure TfrmKafkaDemo.edtTopicChange(Sender: TObject); begin FKafkaConsumer := nil; end; procedure TfrmKafkaDemo.DestroyClasses; begin FKafkaProducer := nil; FKafkaConsumer := nil; end; procedure TfrmKafkaDemo.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin DestroyClasses; // Wait for all the threads to terminate sleep(1000); end; procedure TfrmKafkaDemo.layConsumeControlResize(Sender: TObject); begin btnConsumingStart.Width := (layConsumeControl.Width - 20) / 2; end; procedure TfrmKafkaDemo.tmrUpdateTimer(Sender: TObject); begin UpdateStatus; end; procedure TfrmKafkaDemo.UpdateStatus; var ProducedStr, ConsumedStr: String; begin TKafkaHelper.FlushLogs; if FKafkaProducer = nil then begin ProducedStr := 'Idle'; end else begin ProducedStr := FKafkaProducer.ProducedCount.ToString; end; if FKafkaConsumer = nil then begin ConsumedStr := 'Idle'; end else begin ConsumedStr := FKafkaConsumer.ConsumedCount.ToString; end; lblStatus.Text := format('Produced: %s | Consumed: %s', [ProducedStr, ConsumedStr]); end; end.
unit LrTable; interface uses SysUtils, Types, Windows, Classes, Controls, ExtCtrls, Graphics; type TLrCell = class(TCustomControl) private FRowSpan: Integer; FCol: Integer; FColSpan: Integer; FRow: Integer; FFixedWidth: Boolean; FFixedHeight: Boolean; protected procedure SetFixedHeight(const Value: Boolean); procedure SetFixedWidth(const Value: Boolean); procedure SetCol(const Value: Integer); procedure SetColSpan(const Value: Integer); procedure SetRow(const Value: Integer); procedure SetRowSpan(const Value: Integer); protected procedure AdjustClientRect(var ioRect: TRect); override; procedure DefineProperties(Filer: TFiler); override; procedure ReadGrid(Reader: TReader); procedure WriteGrid(Writer: TWriter); public constructor Create(AOwner: TComponent); override; procedure Paint; override; public property Col: Integer read FCol write SetCol; property Row: Integer read FRow write SetRow; published property Align; property Color; property FixedHeight: Boolean read FFixedHeight write SetFixedHeight; property FixedWidth: Boolean read FFixedWidth write SetFixedWidth; property ColSpan: Integer read FColSpan write SetColSpan; property RowSpan: Integer read FRowSpan write SetRowSpan; end; // TLrTable = class(TCustomControl) private FColCount: Integer; FUpdating: Boolean; FRowCount: Integer; FWidths: array of Integer; protected function GetCells(inIndex: Integer): TLrCell; function GetGridCells(inCol, inRow: Integer): TLrCell; procedure SetColCount(const Value: Integer); procedure SetRowCount(const Value: Integer); protected procedure AdjustClientRect(var ioRect: TRect); override; procedure AlignControls(AControl: TControl; var Rect: TRect); override; procedure CalcWidths; function ColLeft(inCol: Integer): Integer; procedure DistributeCells; procedure RebuildCells; procedure RefreshCells; protected property GridCells[inCol: Integer; inRow: Integer]: TLrCell read GetGridCells; property Cells[inIndex: Integer]: TLrCell read GetCells; public constructor Create(AOwner: TComponent); override; procedure CellChanged(inCell: TLrCell); published property Align; property Color; property ColCount: Integer read FColCount write SetColCount; property RowCount: Integer read FRowCount write SetRowCount; end; implementation { TLrCell } constructor TLrCell.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [ csAcceptsControls ]; end; procedure TLrCell.ReadGrid(Reader: TReader); begin Reader.ReadListBegin; FCol := Reader.ReadInteger; FRow := Reader.ReadInteger; Reader.ReadListEnd; end; procedure TLrCell.WriteGrid(Writer: TWriter); begin Writer.WriteListBegin; Writer.WriteInteger(FCol); Writer.WriteInteger(FRow); Writer.WriteListEnd; end; procedure TLrCell.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('Coords', ReadGrid, WriteGrid, true); end; procedure TLrCell.AdjustClientRect(var ioRect: TRect); begin InflateRect(ioRect, -2, -2); end; procedure TLrCell.Paint; var r: TRect; begin inherited; r := ClientRect; Frame3D(Canvas, r, clGray, clWhite, 1); end; procedure TLrCell.SetCol(const Value: Integer); begin FCol := Value; end; procedure TLrCell.SetColSpan(const Value: Integer); begin FColSpan := Value; end; procedure TLrCell.SetRow(const Value: Integer); begin FRow := Value; end; procedure TLrCell.SetRowSpan(const Value: Integer); begin FRowSpan := Value; end; procedure TLrCell.SetFixedWidth(const Value: Boolean); begin FFixedWidth := Value; TLrTable(Parent).CellChanged(Self); end; procedure TLrCell.SetFixedHeight(const Value: Boolean); begin FFixedHeight := Value; TLrTable(Parent).CellChanged(Self); end; { TLrTable } constructor TLrTable.Create(AOwner: TComponent); begin inherited; //ControlStyle := ControlStyle + [ csAcceptsControls ]; end; procedure TLrTable.AdjustClientRect(var ioRect: TRect); begin InflateRect(ioRect, -2, -2); end; procedure TLrTable.RebuildCells; var i, j: Integer; cell: TLrCell; begin for i := 0 to Pred(ColCount) do for j := 0 to Pred(RowCount) do begin cell := GridCells[i, j]; if (cell = nil) then begin cell := TLrCell.Create(Owner); cell.Name := Format('Cell_%d_%d', [ i, j]); cell.Parent := Self; cell.Col := i; cell.Row := j; end; end; i := 0; while (i < ControlCount) do begin cell := Cells[i]; if (cell.Col >= ColCount) or (cell.Row >= RowCount) then cell.Free else Inc(i); end; end; procedure TLrTable.CalcWidths; var i, c, cw, w, wx: Integer; begin SetLength(FWidths, ColCount); FillChar(FWidths[0], ColCount * 4, 0); for i := 0 to Pred(ControlCount) do with Cells[i] do begin if (Width > FWidths[Col]) and FixedWidth then FWidths[Col] := Width; end; c := 0; cw := ClientWidth - 4; for i := 0 to Pred(ColCount) do if FWidths[i] = 0 then Inc(c) else Dec(cw, FWidths[i]); if (c > 0) then begin w := cw div c; if (w < 4) then begin w := 4; ClientWidth := ClientWidth + w * c; Inc(cw, w*c); end; wx := cw - (w * c); for i := 0 to Pred(ColCount) do if FWidths[i] = 0 then begin if (wx > 0) then FWidths[i] := w + 1 else FWidths[i] := w; Dec(wx); end; end; end; function TLrTable.ColLeft(inCol: Integer): Integer; var i: Integer; begin Result := 2; for i := 0 to Pred(inCol) do Inc(Result, FWidths[i]); end; procedure TLrTable.DistributeCells; var h, hx: Integer; i: Integer; begin if (ColCount = 0) or (RowCount = 0) then exit; DisableAlign; try CalcWidths; h := (ClientHeight - 4) div RowCount; hx := (ClientHeight - 4) - (h * RowCount); for i := 0 to Pred(ControlCount) do with Cells[i] do begin Left := ColLeft(Col); Width := FWidths[Col]; Top := h * Row + 2; if (Row = Pred(RowCount)) then Height := h + hx else Height := h; end; finally EnableAlign; end; end; procedure TLrTable.RefreshCells; begin if not (csLoading in ComponentState) and not FUpdating then begin FUpdating := true; try RebuildCells; finally FUpdating := false; end; DistributeCells; end; end; procedure TLrTable.AlignControls(AControl: TControl; var Rect: TRect); begin if not FUpdating then DistributeCells; end; function TLrTable.GetCells(inIndex: Integer): TLrCell; begin Result := TLrCell(Controls[inIndex]); end; function TLrTable.GetGridCells(inCol, inRow: Integer): TLrCell; var i: Integer; begin for i := 0 to Pred(ControlCount) do with Cells[i] do if (Col = inCol) and (Row = inRow) then begin Result := Cells[i]; exit; end; Result := nil; // raise Exception.Create( // Format('Bad cell grid index (%d, %d)', [ inCol, inRow ])); end; procedure TLrTable.SetRowCount(const Value: Integer); begin FRowCount := Value; RefreshCells; end; procedure TLrTable.SetColCount(const Value: Integer); begin FColCount := Value; RefreshCells; end; procedure TLrTable.CellChanged(inCell: TLrCell); var i: Integer; begin exit; if not FUpdating then begin FUpdating := true; try for i := 0 to Pred(ControlCount) do with Cells[i] do if Col = inCell.Col then FixedWidth := inCell.FixedWidth; finally FUpdating := false end; end; end; initialization Classes.RegisterClass(TLrCell); end.
unit frmBenchMark; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.UITypes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.CheckLst, Vcl.Dialogs, Vcl.ExtCtrls, VclTee.TeEngine, VclTee.Series, Vcl.StdCtrls, VclTee.TeeProcs, VclTee.TeeGDIPlus, VclTee.Chart, Vcl.Buttons, GLCadencer, GLAVIRecorder, //GLData geIntegerEdit; type TformBenchMark = class(TForm) Series1: TLineSeries; Series2: TLineSeries; Series3: TLineSeries; Series4: TLineSeries; Series5: TLineSeries; Series6: TLineSeries; Series7: TLineSeries; Series8: TLineSeries; Series9: TLineSeries; Series10: TLineSeries; chartBench: TChart; splitterBench: TSplitter; pnlBenchMark: TPanel; BenchTimer: TTimer; GLCadencer: TGLCadencer; pnlSettings: TPanel; memBenchmark: TMemo; pnlTop: TPanel; lblTest: TLabel; cbBenchMark: TComboBox; lblN: TLabel; clbSeries: TCheckListBox; bTest: TBitBtn; bOK: TBitBtn; bCopyCurrent: TButton; ColorDialog: TColorDialog; bCopyAverage: TButton; bRename: TButton; bColour: TButton; procedure BenchTimerTimer(Sender: TObject); procedure bTestClick(Sender: TObject); procedure GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); procedure FormShow(Sender: TObject); procedure geieSecondsExit(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure clbSeriesClickCheck(Sender: TObject); procedure bOKClick(Sender: TObject); procedure bCopyCurrentClick(Sender: TObject); procedure bRenameClick(Sender: TObject); procedure bCopyAverageClick(Sender: TObject); procedure bColourClick(Sender: TObject); private dMin:single; dmax:single; dSum:single; dAverage:single; iTime:integer; iCount:integer; procedure UpdateBenchMarkStats; public end; var formBenchMark: TformBenchMark; implementation uses frmMain; {$R *.dfm} // ----- TformBenchMark.UpdateBenchMarkStats ----------------------------------- procedure TformBenchMark.UpdateBenchMarkStats; begin with memBenchMark do begin Lines.Clear; Lines.Add(Format('Time: %d seconds',[iTime])); Lines.Add(Format('Current: %.2f FPS', [formMain.GLSceneViewer.FramesPerSecond])); Lines.Add(''); Lines.Add(Format('Minimum: %.2f FPS',[dMin])); Lines.Add(Format('Average: %.2f FPS',[dAverage])); Lines.Add(Format('Maximum: %.2f FPS',[dMax])); end; end; // ----- TformBenchMark.BenchTimerTimer ---------------------------------------- procedure TformBenchMark.BenchTimerTimer(Sender: TObject); begin iTime := iTime + Trunc(BenchTimer.Interval*0.001); // if iTime > geIESeconds.Value then bTestClick(nil); if formMain.GLSceneViewer.FramesPerSecond < dMin then dMin := formMain.GLSceneViewer.FramesPerSecond; if formMain.GLSceneViewer.FramesPerSecond > dMax then dmax := formMain.GLSceneViewer.FramesPerSecond; Inc(iCount); dSum := dSum + formMain.GLSceneViewer.FramesPerSecond; dAverage := dSum/iCount; UpdateBenchMarkStats; Series1.AddXY(iTime,formMain.GLSceneViewer.FramesPerSecond); Series2.AddXY(iTime,dAverage); formmain.GLSceneViewer.ResetPerformanceMonitor; end; // ----- TformBenchMark.bTestClick --------------------------------------------- procedure TformBenchMark.bTestClick(Sender: TObject); begin if bTest.Caption = 'Start' then begin iTime := 0; // on show dmax := 0.0; dSum := 0.0; dmin := 1000; iCount := 0; Series1.Clear; Series2.Clear; bTest.Caption := 'Stop'; bOk.Enabled := false; end else begin bTest.Caption := 'Start'; bOK.Enabled := true; end; GLCadencer.Enabled := (bTest.Caption = 'Stop'); BenchTimer.Enabled := GLCadencer.Enabled; end; // ----- TformBenchMark.GLCadencerProgress ------------------------------------- procedure TformBenchMark.GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); begin formMain.GLCamera.MoveAroundTarget(0,1); // turn at one degree intervals... Application.ProcessMessages; end; // ----- TformBenchMark.FormShow ----------------------------------------------- procedure TformBenchMark.FormShow(Sender: TObject); begin // geieSeconds.Value := 30; geiesecondsExit(nil); end; // ----- TformBenchMark.geieSecondsExit ---------------------------------------- procedure TformBenchMark.geieSecondsExit(Sender: TObject); begin // chartBench.BottomAxis.Maximum := geieSeconds.Value; // chartBench.BottomAxis.Increment := Trunc(0.1*geieSeconds.Value); clbSeries.Checked[0] := true; // preset current and average to be checked clbSeries.Checked[1] := true; end; // ----- TformBenchMark.FormClose ---------------------------------------------- procedure TformBenchMark.FormClose(Sender: TObject; var Action: TCloseAction); begin GLCadencer.Enabled := false; BenchTimer.Enabled := false; end; // ----- TformBenchMark.clbSeriesClickCheck ------------------------------------ procedure TformBenchMark.clbSeriesClickCheck(Sender: TObject); var bCheck : boolean; begin if clbSeries.ItemIndex = -1 then exit; bcheck := clbSeries.CHecked[clbSeries.ItemIndex]; case clbSeries.ItemIndex of 0: Series1.Active := bCheck; 1: Series2.Active := bCheck; 2: Series3.Active := bCheck; 3: Series4.Active := bCheck; 4: Series5.Active := bCheck; 5: Series6.Active := bCheck; 6: Series7.Active := bCheck; 7: Series8.Active := bCheck; 8: Series9.Active := bCheck; 9: Series10.Active := bCheck; end; end; // ----- TformBenchMark.bOKClick ----------------------------------------------- procedure TformBenchMark.bOKClick(Sender: TObject); begin Close; end; // ----- TformBenchMark.bCopyCurrentClick -------------------------------------- procedure TformBenchMark.bCopyCurrentClick(Sender: TObject); var i:integer; aSeries : TLineSeries; begin if clbSeries.ItemIndex = -1 then exit; case clbSeries.ItemIndex of 0,1: begin MessageDlg('Cannot copy to the live series!',mtError,[mbOK],0); exit; end; 2: aSeries := Series3; 3: aSeries := Series4; 4: aSeries := Series5; 5: aSeries := Series6; 6: aSeries := Series7; 7: aSeries := Series8; 8: aSeries := Series9; 9: aSeries := Series10; end; bRenameClick(nil); aSeries.Clear; for i := 0 to Series1.Count-1 do aSeries.AddXY(Series1.XValue[i],Series1.YValue[i]); end; // ----- TformBenchMark.bRenameClick ------------------------------------------- procedure TformBenchMark.bRenameClick(Sender: TObject); var aSeries:TLineSeries; begin if clbSeries.ItemIndex = -1 then exit; case clbSeries.ItemIndex of 0: aSeries := Series1; 1: aSeries := Series2; 2: aSeries := Series3; 3: aSeries := Series4; 4: aSeries := Series5; 5: aSeries := Series6; 6: aSeries := Series7; 7: aSeries := Series8; 8: aSeries := Series9; 9: aSeries := Series10; end; aSeries.Title := InputBox('Name series', 'Please enter a name for this series',aSeries.Title); clbSeries.Items.Strings[clbSeries.ItemIndex] := aSeries.Title; end; // ----- TformBenchMark.bCopyAverageClick -------------------------------------- procedure TformBenchMark.bCopyAverageClick(Sender: TObject); var i:integer; aSeries : TLineSeries; begin if clbSeries.ItemIndex = -1 then exit; case clbSeries.ItemIndex of 0,1: begin MessageDlg('Cannot copy to the live series!',mtError,[mbOK],0); exit; end; 2: aSeries := Series3; 3: aSeries := Series4; 4: aSeries := Series5; 5: aSeries := Series6; 6: aSeries := Series7; 7: aSeries := Series8; 8: aSeries := Series9; 9: aSeries := Series10; end; bRenameClick(nil); aSeries.Clear; for i := 0 to Series2.Count-1 do aSeries.AddXY(Series2.XValue[i],Series2.YValue[i]); end; // ----- TformBenchMark.bColourClick ------------------------------------------- procedure TformBenchMark.bColourClick(Sender: TObject); var aSeries:TLineSeries; begin if clbSeries.ItemIndex = -1 then exit; case clbSeries.ItemIndex of 0: aSeries := Series1; 1: aSeries := Series2; 2: aSeries := Series3; 3: aSeries := Series4; 4: aSeries := Series5; 5: aSeries := Series6; 6: aSeries := Series7; 7: aSeries := Series8; 8: aSeries := Series9; 9: aSeries := Series10; end; ColorDialog.Color := aSeries.SeriesColor; if ColorDialog.Execute then aSeries.SeriesColor := ColorDialog.Color; end; // ============================================================================= end.
unit uPereocPrint; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxDropDownEdit, StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxSpinEdit, cxControls, cxContainer, cxEdit, cxCheckBox, uMatasUtils, uMatasVars; type TVedPereocPrintForm = class(TForm) Label1: TLabel; cxCheckOnPrinter: TcxCheckBox; cxSelectPrinter: TcxCheckBox; CheckBoxDoc: TcxCheckBox; cxCopies: TcxSpinEdit; cxButtonExit: TcxButton; cxButtonPrint: TcxButton; Label2: TLabel; cxComboReport: TcxComboBox; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } _ON_PRINTER, _SEL_PRINTER, _EDIT_TEMPLATE: boolean; _NUM_COPIES: integer; end; var VedPereocPrintForm: TVedPereocPrintForm; implementation {$R *.dfm} procedure TVedPereocPrintForm.FormCreate(Sender: TObject); begin cxCopies.Value:=1; cxCheckOnPrinter.Checked:=IntToBool(_SET_PRINT_ON_PRINTER); CheckBoxDoc.Visible := IntToBool(_ALLOW_EDIT_TEMPLATE); _ON_PRINTER:=IntToBool(_SET_PRINT_ON_PRINTER); _SEL_PRINTER:=false; _EDIT_TEMPLATE:=IntToBool(_ALLOW_EDIT_TEMPLATE); _NUM_COPIES:=1; cxComboReport.ItemIndex:=0; end; end.
{ @abstract Contains @link(TNtFmxTranslator) class that perform runtime language switch for a FireMonkey application. } unit FMX.NtTranslator; {$I NtVer.inc} interface uses System.Classes, FMX.Forms, FMX.Types, NtBase, NtBaseTranslator; type { @abstract Class that translates FMX forms. This class performs runtime language switch by going through each component and property on the host form. Call @link(TNtFmxTranslator.TranslateForms) to translate all forms. } TNtTranslator = class(TNtBaseTranslator) private procedure TranslateForm(form: TCommonCustomForm); procedure TranslateDelta(component: TFmxObject); protected procedure AfterProcessComponent(component: TComponent); override; procedure Translate(component: TComponent); override; public { Load a new resource DLL file, initialize the language depend values, and finally translate the forms. @param code Specifies the file extension without period of the new resource DLL. @param options Language change options. @param originalCode Language used in the original application. @return @true if succesful, @false if failed. } class function SetNew( const code: String = ''; options: TNtResourceOptions = []; const originalCode: String = ''): Boolean; { Translate all created forms, frames and data modules. } class procedure TranslateForms; class function GetDevices(component: TFmxObject; devices: TStrings): Integer; class function GetDevice(component: TFmxObject): String; end; { Makes the initial translation and flips the form layout if needed. @param form Form to be initialized. } procedure _T(form: TCustomForm); overload; { Same as _T. Makes the initial translation and flips the form layout if needed. @param form Form to be initialized. } procedure Translate(form: TCustomForm); overload; { Makes the initial translation. @param component Component to be initialized. } procedure _T(component: TComponent); overload; procedure Translate(component: TComponent); overload; implementation uses System.Devices, System.SysUtils, System.Types, NtResource, FMX.BehaviorManager, FMX.Controls, FMX.NtLocalization, FMX.Menus; procedure _T(form: TCustomForm); var translator: TNtTranslator; begin translator := TNtTranslator.Create; try translator.TranslateForm(form); finally translator.Free; end; end; procedure Translate(form: TCustomForm); begin _T(form); end; procedure _T(component: TComponent); var translator: TNtTranslator; begin translator := TNtTranslator.Create; try translator.Translate(component); finally translator.Free; end; end; procedure Translate(component: TComponent); begin _T(component); end; procedure TNtTranslator.AfterProcessComponent(component: TComponent); begin if component is TControl then TControl(component).Repaint; end; class function TNtTranslator.GetDevice(component: TFmxObject): String; var devices: TStrings; begin devices := TStringList.Create; try GetDevices(component, devices); if devices.Count > 0 then Result := devices[0] else Result := ''; finally devices.Free; end; end; class function TNtTranslator.GetDevices(component: TFmxObject; devices: TStrings): Integer; var i: Integer; deviceBehavior: IDeviceBehavior; deviceClass: TDeviceInfo.TDeviceClass; displayMetrics: TDeviceDisplayMetrics; logicalScreenSize, PhysicalScreenSize: TSize; deviceInfos: TArray<TDeviceInfo>; begin if TBehaviorServices.Current.SupportsBehaviorService(IDeviceBehavior, deviceBehavior, component) then begin deviceClass := deviceBehavior.GetDeviceClass(component); displayMetrics := deviceBehavior.GetDisplayMetrics(component); if displayMetrics.LogicalScreenSize.Height > displayMetrics.LogicalScreenSize.Width then begin logicalScreenSize := TSize.Create(displayMetrics.LogicalScreenSize.Height, displayMetrics.LogicalScreenSize.Width); physicalScreenSize := TSize.Create(displayMetrics.RawScreenSize.Height, displayMetrics.RawScreenSize.Width); end else begin logicalScreenSize := displayMetrics.LogicalScreenSize; physicalScreenSize := displayMetrics.RawScreenSize; end; deviceInfos := TDeviceInfo.SelectDevices( deviceClass, physicalScreenSize, logicalScreenSize, TOSVersion.Platform, displayMetrics.PixelsPerInch); Result := Length(deviceInfos); for i := Low(deviceInfos) to High(deviceInfos) do devices.Add(deviceInfos[i].ID); end else Result := 0; end; procedure TNtTranslator.TranslateDelta(component: TFmxObject); var devices: TStrings; device, rootName, resName: String; begin rootName := component.ClassType.ClassName; devices := TStringList.Create; try GetDevices(component, devices); for device in devices do begin resName := String.Join('_', [rootName, device]); if DoTranslate(component, resName) then Break; end; finally devices.Free; end; end; procedure TNtTranslator.Translate(component: TComponent); var i: Integer; begin // Translate frame for i := 0 to component.ComponentCount - 1 do if component.Components[i] is TFrame then Translate(component.Components[i]); // Translate component inherited; // Translate delta (e.g. device depend data) if component is TFmxObject then TranslateDelta(TFmxObject(component)); end; procedure TNtTranslator.TranslateForm(form: TCommonCustomForm); begin //if (roFlipChildren in ResourceOptions) and TNtLocale.IsPreviousLocaleBidi then // form.FlipChildren(True); Translate(form); //if (roFlipChildren in ResourceOptions) and TNtLocale.IsActiveLocaleBidi then // form.FlipChildren(True); end; class procedure TNtTranslator.TranslateForms; var translator: TNtTranslator; { procedure SetNewLayout(value: TNtLayout); begin translator.FTranslateLayout := UiLayout <> value; UiLayout := value; end; } var i: Integer; begin translator := TNtTranslator.Create; try { if TNtLocale.IsActiveLocaleBidi and (UiLayout = laLeftToRight) then SetNewLayout(laRightToLeft) else if not TNtLocale.IsActiveLocaleBidi and (UiLayout = laRightToLeft) then SetNewLayout(laLeftToRight); } for i := 0 to Screen.DataModuleCount - 1 do translator.Translate(Screen.DataModules[i]); for i := 0 to Screen.FormCount - 1 do translator.TranslateForm(Screen.Forms[i]); finally translator.Free; end; end; class function TNtTranslator.SetNew( const code: String; options: TNtResourceOptions; const originalCode: String): Boolean; begin ResourceOptions := options; if NtResources.Count > 0 then begin NtResources.LanguageId := code; LoadedResourceLocale := NtResources.LanguageId; Result := True; end else Result := TNtBase.LoadNew(code) <> 0; if Result then begin TranslateForms; { if code = '' then locale := TNtLocale.ExtensionToLocale(originalCode) else locale := TNtLocale.ExtensionToLocale(code); // Updates thred's locale, format settings and bidi mode to match if not (roNoThreadLocale in options) then SetThreadLocale(locale); if not (roNoLocaleVariables in options) then TNtSystem.UpdateFormatSettings(locale); if not (roNoUpdateBidiMode in options) then begin if TNtLocale.IsLocaleBiDi(TNtLocale.LocaleToExtension(locale)) then Application.BiDiMode := bdRightToLeft else Application.BiDiMode := bdLeftToRight; end; // Translate forms TNtTranslator.TranslateForms; } end; //if roSaveLocale in options then // TNtRegistry.SetCurrentDefaultLocale; end; end.
unit Secrch1111; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, bsSkinCtrls, StdCtrls, RzLabel, ExtCtrls, RzPanel, RzButton, GameLoginShare, bsSkinShellCtrls; type TFrmSecrch = class(TForm) GroupBox1: TRzGroupBox; Label1: TLabel; GroupBox2: TRzGroupBox; Label2: TLabel; SecrchInfoLabel: TRzLabel; Label3: TLabel; Label4: TLabel; EditPath: TEdit; Label5: TLabel; RzToolButtonSearch: TbsSkinButton; RzButtonSelDir: TbsSkinButton; StopButton: TbsSkinButton; SelectDirectoryDialog: TbsSkinSelectDirectoryDialog; procedure RzButtonSelDirClick(Sender: TObject); procedure StopButtonClick(Sender: TObject); procedure RzToolButtonSearchClick(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure SearchMirClient(); //智能搜索客户端 function DoSearchFile(path: string; var Files: TStringList): Boolean; public { Public declarations } end; var FrmSecrch: TFrmSecrch; implementation uses Main, MsgBox; var boStopSearch: Boolean = FALSE; boSearchFinish: Boolean = FALSE; {$R *.dfm} //手工选择目录 procedure TFrmSecrch.RzButtonSelDirClick(Sender: TObject); begin if SelectDirectoryDialog.Execute then begin EditPath.Text := SelectDirectoryDialog.Directory; m_sMirClient := EditPath.Text; if m_sMirClient[Length(m_sMirClient)] <> '\' then m_sMirClient := m_sMirClient + '\'; if CheckMirDir(m_sMirClient) then begin m_BoSearchFinish := True; Close; end else begin //MainFrm.bsSkinMessage1.MessageDlg('你选择的不是传奇目录,请重新选择!!!',mtError,[mbOK],0); FrmMessageBox.LabelHintMsg.Caption := '你选择的不是传奇目录,请重新选择!!!'; FrmMessageBox.ShowModal; end; end; end; //取消按钮 procedure TFrmSecrch.StopButtonClick(Sender: TObject); begin boStopSearch := True; Sleep(100); Close; end; //智能搜索按钮 procedure TFrmSecrch.RzToolButtonSearchClick(Sender: TObject); begin if boSearchFinish then Exit; RzButtonSelDir.Enabled:=False; SearchMirClient(); RzButtonSelDir.Enabled:=TRUE; Close; end; //智能搜索客户端 procedure TFrmSecrch.SearchMirClient(); var I, II: Integer; sList, sTempList, List01, List02: TStringList; begin boSearchFinish:=TRUE; sList := TStringList.Create; sTempList := TStringList.Create; List01 := TStringList.Create; List02 := TStringList.Create; GetdriveName(sList); for I := 0 to sList.Count - 1 do begin Application.ProcessMessages; if m_BoSearchFinish then break; if boStopSearch then break; SecrchInfoLabel.Caption := '正在搜索:' + sList.Strings[I]; if CheckMirDir(sList.Strings[I]) then begin m_sMirClient := sList.Strings[I]; m_BoSearchFinish := True; break; end; if DoSearchFile(sList.Strings[I], sTempList) then begin if m_BoSearchFinish then break; if boStopSearch then break; for II := 0 to sTempList.Count - 1 do begin SecrchInfoLabel.Caption := '正在搜索:' + sTempList.Strings[II]; if CheckMirDir(sTempList.Strings[II]) then begin m_sMirClient := sTempList.Strings[II]; m_BoSearchFinish := True; break; end; end; end; end; List01.AddStrings(sTempList); if (not m_BoSearchFinish) and (not boStopSearch) then begin I := 0; while True do begin //从C盘到最后一个盘反复搜索 if m_BoSearchFinish then break; if boStopSearch then break; Application.ProcessMessages; if List01.Count <=0 then Break; sTempList.Clear; if DoSearchFile(List01.Strings[I], sTempList) then begin if m_BoSearchFinish then break; if boStopSearch then break; List02.AddStrings(sTempList); for II := 0 to sTempList.Count - 1 do begin if m_BoSearchFinish then break; if boStopSearch then break; SecrchInfoLabel.Caption := '正在搜索:' + sTempList.Strings[II]; if CheckMirDir(sTempList.Strings[II]) then begin m_sMirClient := sTempList.Strings[II]; m_BoSearchFinish := True; break; end; end; end; Inc(I); if I > List01.Count - 1 then begin List01.Clear; List01.AddStrings(List02); List02.Clear; I := 0; end; end; end; sList.Free; sTempList.Free; List01.Free; List02.Free; boSearchFinish:=FALSE; end; //搜索文件 function TFrmSecrch.DoSearchFile(path: string; var Files: TStringList): Boolean; var Info: TsearchRec; s01: string; procedure ProcessAFile(FileName: string); begin {if Assigned(PnlPanel) then PnlPanel.Caption := FileName; Label2.Caption := FileName;} end; function IsDir: Boolean; begin with Info do result := (Name <> '.') and (Name <> '..') and ((Attr and faDirectory) = faDirectory); end; function IsFile: Boolean; begin result := not ((Info.Attr and faDirectory) = faDirectory); end; begin try result := FALSE; if findfirst(path + '*.*', faAnyFile, Info) = 0 then begin if IsDir then begin s01 := path + Info.Name; if s01[Length(s01)] <> '\' then s01 := s01 + '\'; Files.Add(s01); end; while True do begin if m_BoSearchFinish then break; if boStopSearch then break; s01 := path + Info.Name; if s01[Length(s01)] <> '\' then s01 := s01 + '\'; if IsDir then Files.Add(s01); Application.ProcessMessages; if findnext(Info) <> 0 then break; end; end; result := True; finally findclose(Info); end; end; procedure TFrmSecrch.FormCreate(Sender: TObject); begin boStopSearch := False; m_BoSearchFinish := False; end; end.
unit mainGUI; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, LCLType, Spin, processor; type { TForm1 } TForm1 = class(TForm) btnStart: TButton; btnAddFiles: TButton; btnFindFFmpeg: TButton; ckbDeinterlace: TCheckBox; ckbStabilize: TCheckBox; ckbProxy: TCheckBox; edtFFmpegPath: TEdit; lblBitrate: TLabel; lbxFiles: TListBox; dlgFindFFmpeg: TOpenDialog; dlgOpenFiles: TOpenDialog; dlgOutputFolder: TSelectDirectoryDialog; spnBitrate: TSpinEdit; spnShakiness: TSpinEdit; procedure btnAddFilesClick(Sender: TObject); procedure btnFindFFmpegClick(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure ckbProxyChange(Sender: TObject); procedure ckbStabilizeChange(Sender: TObject); procedure FormDropFiles(Sender: TObject; const FileNames: array of String); procedure lbxFilesKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.btnStartClick(Sender: TObject); begin //test: any videos selected? if lbxFiles.Count = 0 then Application.MessageBox('Select at least one video to process!', 'No Videos', MB_ICONERROR) else //test: ffmpeg selected? if not FileExists(edtFFmpegPath.Text) then Application.MessageBox('Please select FFmpeg first!', 'Missing FFmpeg', MB_ICONERROR) else //select output folder if dlgOutputFolder.Execute then begin //push information to processor FFmpegPath:=edtFFmpegPath.Text; OutputPath := dlgOutputFolder.FileName; Shakiness := spnShakiness.Value; Bitrate := spnBitrate.Value; Deinterlace := ckbDeinterlace.Checked; Stabilize := ckbStabilize.Checked; InputFiles := lbxFiles.Items; //run, ffmpeg, run! Form2.Show; if ckbProxy.Checked then begin Form2.makeProxy(); end else begin Form2.run(); end; end else Application.MessageBox('Please select an output folder!', 'No Output Selected', MB_ICONERROR) end; procedure TForm1.ckbProxyChange(Sender: TObject); begin spnShakiness.Enabled:=not ckbProxy.Checked; ckbStabilize.Enabled:=not ckbProxy.Checked; ckbDeinterlace.Enabled:=not ckbProxy.Checked; end; procedure TForm1.ckbStabilizeChange(Sender: TObject); begin spnShakiness.Enabled:=ckbStabilize.Checked; end; procedure TForm1.FormDropFiles(Sender: TObject; const FileNames: array of String ); begin lbxFiles.Items.AddStrings(FileNames); end; procedure TForm1.lbxFilesKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var i: Integer; begin if Key = VK_DELETE then for i := lbxFiles.Count-1 downto 0 do if lbxFiles.Selected[i] then lbxFiles.Items.Delete(i); end; procedure TForm1.btnAddFilesClick(Sender: TObject); begin if dlgOpenFiles.Execute then lbxFiles.Items.AddStrings(dlgOpenFiles.Files); end; procedure TForm1.btnFindFFmpegClick(Sender: TObject); begin if dlgFindFFmpeg.Execute then edtFFmpegPath.Text:=dlgFindFFmpeg.FileName; end; end.
unit CSV.ViewModel; interface uses System.Classes, Spring, Spring.Collections, CSV.Interfaces, MVVM.Interfaces.Architectural, MVVM.Attributes, MVVM.Observable, MVVM.Bindings; type [ViewModel_Implements(ICSVFile_ViewModel, itSingleton)] TCSVFile_ViewModel = class(TViewModel, ICSVFile_ViewModel) private FModelo : ICSVFile_Model; FOnProcesamientoFinalizado: IEvent<TFinProcesamiento>; FOnProgresoProcesamiento : IEvent<TProgresoProcesamiento>; protected function GetModel: ICSVFile_Model; function GetFileName: String; procedure SetFileName(const AFileName: String); function GetProgresoProcesamiento: Integer; procedure OnProgresoProceso(const ADato: Integer); procedure OnModelNotifyChanged(const ASender: TObject; const APropertyName: String); function GetOnProcesamientoFinalizado: IEvent<TFinProcesamiento>; function GetOnProgresoProcesamiento: IEvent<TProgresoProcesamiento>; procedure Notify(const APropertyName: string = ''); public constructor Create; destructor Destroy; override; procedure SetupViewModel; procedure SetModel(AModel: ICSVFile_Model); function GetAsObject: TObject; procedure ProcesarFicheroCSV; procedure ProcesarFicheroCSV_Parallel; procedure CreateNewView; function GetIsValidFile: Boolean; property FileName: String read GetFileName write SetFileName; property IsValidFile: Boolean read GetIsValidFile; property ProgresoProcesamiento: Integer read GetProgresoProcesamiento; property OnDatosProcesamientoFinalizado: IEvent<TFinProcesamiento> read GetOnProcesamientoFinalizado; property OnProgresoProcesamiento: IEvent<TProgresoProcesamiento> read GetOnProgresoProcesamiento; property Model: ICSVFile_Model read GetModel; end; implementation uses System.SysUtils, System.Threading, System.Diagnostics, MVVM.Interfaces, MVVM.ViewFactory, MVVM.Utils, MVVM.Core; { TCSVFile_ViewModel } constructor TCSVFile_ViewModel.Create; var I: Integer; begin inherited; FOnProcesamientoFinalizado := Utils.CreateEvent<TFinProcesamiento>; FOnProgresoProcesamiento := Utils.CreateEvent<TProgresoProcesamiento>; end; procedure TCSVFile_ViewModel.CreateNewView; begin Utils.ShowView<ICSVFile_ViewModel>(Self, ICSVFile_View_NAME, MVVMCore.DefaultViewPlatform); end; destructor TCSVFile_ViewModel.Destroy; begin FOnProcesamientoFinalizado := nil; FOnProgresoProcesamiento := nil; inherited; end; function TCSVFile_ViewModel.GetAsObject: TObject; begin Result := Self end; function TCSVFile_ViewModel.GetFileName: String; begin Guard.CheckNotNull(FModelo, 'Modelo no asignado'); Result := FModelo.FileName; end; function TCSVFile_ViewModel.GetIsValidFile: Boolean; begin Guard.CheckNotNull(FModelo, 'Modelo no asignado'); Result := FModelo.IsPathOk; end; function TCSVFile_ViewModel.GetModel: ICSVFile_Model; begin Result := FModelo end; function TCSVFile_ViewModel.GetOnProcesamientoFinalizado: IEvent<TFinProcesamiento>; begin Result := FOnProcesamientoFinalizado; end; function TCSVFile_ViewModel.GetOnProgresoProcesamiento: IEvent<TProgresoProcesamiento>; begin Result := FOnProgresoProcesamiento; end; function TCSVFile_ViewModel.GetProgresoProcesamiento: Integer; begin Guard.CheckNotNull(FModelo, 'Modelo no asignado'); Result := FModelo.ProgresoProcesamiento; end; procedure TCSVFile_ViewModel.Notify(const APropertyName: string); begin Manager.BindingStrategy.Notify(Self, APropertyName); end; procedure TCSVFile_ViewModel.ProcesarFicheroCSV; var LTiming: TStopwatch; begin Guard.CheckNotNull(FModelo, 'Modelo no asignado'); Guard.CheckTrue(FModelo.IsPathOk, 'El fichero no existe: ' + FModelo.FileName); if MVVMCore.PlatformServices.MessageDlg('Estas seguro?', 'Test') then begin LTiming := TStopwatch.Create; LTiming.Start; FModelo.ProcesarFicheroCSV; FOnProcesamientoFinalizado.Invoke('Fichero ' + FModelo.FileName + ' procesado (normal) en ' + LTiming.ElapsedMilliseconds.ToString + ' msg'); end; end; procedure TCSVFile_ViewModel.ProcesarFicheroCSV_Parallel; var LTiming : TStopwatch; LFromFile: TStrings; LRes : TParallel.TLoopResult; begin Guard.CheckNotNull(FModelo, 'Modelo no asignado'); Guard.CheckTrue(FModelo.IsPathOk, 'El fichero no existe: ' + FModelo.FileName); if MVVMCore.PlatformServices.MessageDlg('Estas seguro?', 'Test') then begin LTiming := TStopwatch.Create; LTiming.Start; FModelo.ProcesarFicheroCSV_Parallel; FOnProcesamientoFinalizado.Invoke('Fichero ' + FModelo.FileName + ' procesado (Paralelo) en ' + LTiming.ElapsedMilliseconds.ToString + ' msg'); end; end; procedure TCSVFile_ViewModel.SetFileName(const AFileName: String); begin Guard.CheckNotNull(FModelo, 'Modelo no asignado'); if FModelo.FileName <> AFileName then begin FModelo.FileName := AFileName; Notify('FileName'); Notify('IsValidFile'); end; end; procedure TCSVFile_ViewModel.SetModel(AModel: ICSVFile_Model); begin if FModelo <> AModel then begin FModelo := AModel; SetupViewModel; Notify; end; end; procedure TCSVFile_ViewModel.OnModelNotifyChanged(const ASender: TObject; const APropertyName: String); begin case Utils.StringToCaseSelect(APropertyName, ['FileName', 'IsPathOK']) of 0: begin Notify('FileName'); Notify('IsValidFile'); end; 1: begin Notify('IsValidFile'); end; end; end; procedure TCSVFile_ViewModel.OnProgresoProceso(const ADato: Integer); begin FOnProgresoProcesamiento.Invoke(ADato); end; procedure TCSVFile_ViewModel.SetupViewModel; var [weak] LObservable: INotifyChangedProperty; begin //Bindings FModelo.OnProgresoProcesamiento.Add(OnProgresoProceso); FModelo.OnPropertyChanged.Add(OnModelNotifyChanged); end; initialization TCSVFile_ViewModel.ClassName; //as there should be no implicit create, we must do this so the rtti info of the class is included in the final exe end.
unit uShellNamespaceUtils; interface uses uMemory, System.Classes, System.StrUtils, System.Win.ComObj, Winapi.Windows, Winapi.ActiveX, Winapi.ShlObj, Vcl.Controls, Dmitry.Utils.System, uConstants, uPortableDeviceManager, uPortableDeviceUtils, DragDropPIDL, ShellContextMenu; function ExecuteShellPathRelativeToMyComputerMenuAction(Handle: THandle; Path: string; Files: TStrings; P: TPoint; WC: TWinControl; Verb: AnsiString): Boolean; function ClipboardHasPIDList: Boolean; procedure PastePIDListToFolder(Handle: THandle; Folder: string); implementation //WPD shell extension //code from MSDN, ported to DELPHI XE2 by Dmitry Veresov (c) 2012 (*procedure ProcessDataObject(pdto: IDataObject); var fmte: TFORMATETC; stm: TSTGMEDIUM; hr: HRESULT; pid: PIDA; I: UINT; psfRoot: IShellFolder; psf2: IShellFolder2; pidl: PItemIDList; vt: POleVariant; PKEY_Size: SHCOLUMNID; pName: TStrRet; spSetStorage: IPropertySetStorage; spPropStorage: IPropertyStorage; PropSpec: array of TPropSpec; PropVariant: array of TPropVariant; begin //copy data from clipboard fmte.cfFormat := RegisterClipboardFormat(CFSTR_SHELLIDLIST); fmte.ptd:= nil; fmte.dwAspect := DVASPECT_CONTENT; fmte.lindex := -1; fmte.tymed := TYMED_HGLOBAL ; hr := pdto.GetData(fmte, stm); if SUCCEEDED(hr) and (stm.hGlobal <> 0) then begin pid := PIDA(GlobalLock(stm.hGlobal)); if (pid <> nil) then // defend against buggy data object begin hr := SHBindToObject(nil, HIDA_GetPIDLFolder(pid), nil, StringToGUID(SID_IShellFolder), Pointer(psfRoot)); if (SUCCEEDED(hr)) then begin for i := 0 to pid.cidl - 1 do begin hr := SHBindToFolderIDListParent(psfRoot, HIDA_GetPIDLItem(pid, i), StringToGUID(SID_IShellFolder2), Pointer(psf2), pidl); if (SUCCEEDED(hr)) then begin hr := psf2.BindToObject(ILFindLastID(pidl), nil, StringToGUID('{0000013A-0000-0000-C000-000000000046}'), spSetStorage); if (SUCCEEDED(hr)) then begin hr := spSetStorage.Open(PKEY_GenericObj, STGM_READ, spPropStorage); if (SUCCEEDED(hr)) then begin Setlength(PropSpec, 1); Setlength(PropVariant, 1); PropSpec[0].ulKind := PRSPEC_PROPID; PropSpec[0].propid := WPD_OBJECT_ID; // WPD_FUNCTIONAL_OBJECT_CATEGORY hr := spPropStorage.ReadMultiple(1, @PropSpec[0], @PropVariant[0]); //profit! end; end; end; end; end; GlobalUnlock(stm.hGlobal); end; ReleaseStgMedium(&stm); end; end; *) function GetFolder(Handle: HWND; Path: WideString): IShellFolder; var Desktop: IShellFolder; ItemIDList: PITEMIDLIST; Eaten, Attr: ULONG; begin Result := nil; if Succeeded(SHGetDesktopFolder(Desktop)) then begin if Path <> '' then begin if Succeeded(Desktop.ParseDisplayName(Handle, nil, PWideChar(Path), Eaten, ItemIDList, Attr)) then begin Desktop.BindToObject(ItemIDList, nil, IShellFolder, Result); CoTaskMemFree(ItemIDList); end; end; end; end; function ClipboardHasPIDList: Boolean; var fmte: TFORMATETC; stm: TSTGMEDIUM; D: IDataObject; HR: HRESULT; begin Result := False; HR := OleGetClipboard(D); if Succeeded(HR) then begin fmte.cfFormat := RegisterClipboardFormat(CFSTR_SHELLIDLIST); fmte.ptd:= nil; fmte.dwAspect := DVASPECT_CONTENT; fmte.lindex := -1; fmte.tymed := TYMED_HGLOBAL; HR := D.GetData(fmte, stm); Result := SUCCEEDED(HR) and (stm.hGlobal <> 0); end; end; function GetDisplayName( pidl: PItemIDList; pMalloc: IMalloc; const Value: STRRET ): string; begin with Value do case uType of STRRET_CSTR: Result := PChar(@cStr[0]); STRRET_WSTR: begin Result := pOleStr; pMalloc.Free( pOleStr ); end; STRRET_OFFSET: Result := PChar( LongWord(pidl) + uOffset ); end; end; procedure PastePIDListToFolder(Handle: THandle; Folder: string); var Desktop: IShellFolder; HR: HRESULT; PathPIDL: PItemIDList; L: Cardinal; FPath: PWideChar; Menu: IContextMenu; cmd: TCMInvokeCommandInfo; Attr: Cardinal; begin HR := SHGetDesktopFolder(Desktop); if Succeeded(HR) then begin FPath := StringToOleStr(Folder); L := Length(FPath); Attr := 0; HR := Desktop.ParseDisplayName(Handle, nil, FPath, L, PathPIDL, Attr); if Succeeded(HR) then begin HR := Desktop.GetUIObjectOf( 0, 1, PathPIDL, IContextMenu, nil, Pointer(Menu)); if Succeeded(HR) then begin FillMemory( @cmd, SizeOf(cmd), 0 ); with cmd do begin cbSize := SizeOf( cmd ); fMask := 0; hwnd := 0; lpVerb := PAnsiChar( 'Paste' ); nShow := SW_SHOWNORMAL; end; HR := Menu.InvokeCommand( cmd ); OleCheck(hr); end; end; end; end; function GetShellName(Path, APathName: string): string; var P: Integer; begin if (IsDeviceItemPath(cDevicesPath + '\' + Path) or IsDevicePath(cDevicesPath + '\' + Path)) and not IsWPDSupport then begin P := Pos('.', ReverseString(APathName)); if P > 0 then APathName := Copy(APathName, 1, Length(APathName) - P); //Delete(APathName, Length(APathName) - P, P); end; Result := APathName; end; function ExecuteShellPathRelativeToMyComputerMenuAction(Handle: THandle; Path: string; Files: TStrings; P: TPoint; WC: TWinControl; Verb: AnsiString): Boolean; type TPItemIDListArray = array of PItemIDList; var PathParts: TStringList; I, J: Integer; HR: HRESULT; pMalloc: IMalloc; MyComputer, CurrentFolder: IShellFolder; EnumIDList: IEnumIDList; pceltFetched: ULONG; rgelt: PItemIDList; FilePIDLs: TPItemIDListArray; Value: STRRET; Name, PathName: string; Menu: IContextMenu; procedure ExecuteMenuAction; var cmd: TCMInvokeCommandInfo; begin if Failed(HR) then Exit; if Verb <> '' then begin FillMemory( @cmd, sizeof(cmd), 0 ); with cmd do begin cbSize := SizeOf( cmd ); fMask := 0; hwnd := 0; lpVerb := PAnsiChar( Verb ); nShow := SW_SHOWNORMAL; end; HR := Menu.InvokeCommand( cmd ); Result := Succeeded(HR); end else begin DisplayShellMenu(Menu, P, WC, ''); end; end; begin if Files <> nil then begin SetLength(FilePIDLs, Files.Count + 1); FillChar(FilePIDLs[Files.Count], Sizeof(PItemIDList), #0); for I := 0 to Files.Count - 1 do FilePIDLs[I] := nil; end; HR := SHGetMalloc(pMalloc); if Succeeded(HR) then begin MyComputer := GetFolder(Handle, '::{20D04FE0-3AEA-1069-A2D8-08002B30309D}'); PathParts := TStringList.Create; try PathParts.Delimiter := '\'; PathParts.StrictDelimiter := True; PathParts.DelimitedText := Path; CurrentFolder := MyComputer; for I := 0 to PathParts.Count do begin if CurrentFolder = nil then Exit; if (I < PathParts.Count) and (PathParts[I] = '') then Continue; CurrentFolder.EnumObjects(handle, SHCONTF_FOLDERS or SHCONTF_NONFOLDERS or SHCONTF_FASTITEMS or SHCONTF_INCLUDEHIDDEN, EnumIDList); pceltFetched := 1; while(pceltFetched = 1) do begin EnumIDList.Next(1, rgelt, pceltFetched); if pceltFetched > 0 then begin HR := CurrentFolder.GetDisplayNameOf(rgelt, SHGDN_INFOLDER or SHGDN_INCLUDE_NONFILESYS, Value); Name := GetDisplayName(rgelt, pMalloc, Value); PathName := ''; if (I < PathParts.Count) then PathName := PathParts[I]; if (I = PathParts.Count - 1) then PathName := GetShellName(Path, PathParts[I]); if I < PathParts.Count then begin if Name = PathName then begin if I = PathParts.Count - 1 then begin if (Files <> nil) and (Files.Count > 0) then begin HR := CurrentFolder.BindToObject(rgelt, nil, StringToGUID(SID_IShellFolder), Pointer(CurrentFolder)); Break; end else begin HR := CurrentFolder.GetUIObjectOf(Handle, 1, rgelt, IContextMenu, nil, Pointer(Menu)); if Succeeded(HR) then ExecuteMenuAction; end; end else begin HR := CurrentFolder.BindToObject(rgelt, nil, StringToGUID(SID_IShellFolder), Pointer(CurrentFolder)); Break; end; end; end else begin if Files <> nil then begin for J := 0 to Files.Count - 1 do begin if GetShellName(Path, Files[J]) = Name then //win200 fails FilePIDLs[J] := CopyPIDL(rgelt); end; end; end; end else Break; end; end; if (Files <> nil) and (FilePIDLs <> nil) then begin HR := CurrentFolder.GetUIObjectOf(Handle, Files.Count, FilePIDLs[0], IContextMenu, nil, Pointer(Menu)); if Succeeded(HR) then ExecuteMenuAction; end; finally F(PathParts); end; end; if (Files <> nil) then begin for I := 0 to Files.Count - 1 do if FilePIDLs[I] <> nil then pMalloc.Free(FilePIDLs[I]); end; end; end.
unit eUsusario.View.Query.Firedac; interface uses eUsusario.View.Conexao.Interfaces,Data.DB, 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.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client; Type TModelQueryFiredac = class(TInterfacedObject, iQuery) private FQuery : TFDQuery; FParrent : iConexao; public constructor Create(Parrent : iConexao); destructor Destroy; override; class function New(Parrent : iConexao) : iQuery; function SQL(Value : String) : iQuery; function DataSet : TDataSet; function Open(aSQL : String) : iQuery; end; implementation uses System.SysUtils, eUsusario.View.Conexao.Faredac; { TModelQueryFiredac } constructor TModelQueryFiredac.Create(Parrent : iConexao); begin FParrent := Parrent; FQuery := TFDQuery.Create(nil); if not Assigned(FParrent)then FParrent := TModelConexaoFaredac.New; FQuery.Connection := TFDConnection(FParrent.Connection); end; function TModelQueryFiredac.DataSet: TDataSet; begin Result := FQuery; end; destructor TModelQueryFiredac.Destroy; begin FreeAndNil(FQuery); inherited; end; class function TModelQueryFiredac.New(Parrent : iConexao): iQuery; begin Result := Self.Create(Parrent); end; function TModelQueryFiredac.Open(aSQL : String) : iQuery; begin Result := Self; FQuery.Open(aSQL); end; function TModelQueryFiredac.SQL(Value: String): iQuery; begin Result := Self; FQuery.SQL.Clear; FQuery.SQL.Add(Value); FQuery.Active := True; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmPathTreeView Purpose : Visual treeview that supports operations on nodes via path structures Date : 08-15-2000 Author : Ryan J. Mills Version : 1.92 Notes : This unit was originally based upon the work of Patrick O'Keeffe. It was at his request that I took the component over and rm'ified it. ================================================================================} unit rmPathTreeView; interface {$I CompilerDefines.INC} uses Windows, Messages, controls, classes, commctrl, comctrls, forms, ImgList, extctrls, sysutils, Graphics, Contnrs; type TrmCustomPathTreeView = class; TrmTreeNodes = class; TrmTreeNode = class; TrmNodeInfo = class(TComponent) private fImageIndex: Integer; fSelectedIndex: Integer; fStateIndex: Integer; fOverlayIndex: Integer; fData: Integer; fPath: string; published property ImageIndex: integer read fImageIndex write fImageIndex default -1; property SelectedIndex: integer read fSelectedIndex write fSelectedIndex default -1; property StateIndex: integer read fStateIndex write fStateIndex default -1; property OverlayIndex: integer read fOverlayIndex write fOverlayIndex default -1; property Data: Integer read fData write fData; property Path: String read fPath write fPath; end; { TrmCustomPathTreeView Events } TrmTVChangingEvent = procedure(Sender: TObject; Node: TrmTreeNode; var AllowChange: Boolean) of object; TrmTVChangedEvent = procedure(Sender: TObject; Node: TrmTreeNode) of object; TrmTVEditingEvent = procedure(Sender: TObject; Node: TrmTreeNode; var AllowEdit: Boolean) of object; TrmTVEditedEvent = procedure(Sender: TObject; Node: TrmTreeNode; var S: string) of object; TrmTVExpandingEvent = procedure(Sender: TObject; Node: TrmTreeNode; var AllowExpansion: Boolean) of object; TrmTVCollapsingEvent = procedure(Sender: TObject; Node: TrmTreeNode; var AllowCollapse: Boolean) of object; TrmTVExpandedEvent = procedure(Sender: TObject; Node: TrmTreeNode) of object; TrmTVCompareEvent = procedure(Sender: TObject; Node1, Node2: TrmTreeNode; Data: Integer; var Compare: Integer) of object; TrmTVCustomDrawEvent = procedure(Sender: TrmCustomPathTreeView; const ARect: TRect; var DefaultDraw: Boolean) of object; TrmTVCustomDrawItemEvent = procedure(Sender: TrmCustomPathTreeView; Node: TrmTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean) of object; TrmTVAdvancedCustomDrawEvent = procedure(Sender: TrmCustomPathTreeView; const ARect: TRect; Stage: TCustomDrawStage; var DefaultDraw: Boolean) of object; TrmTVAdvancedCustomDrawItemEvent = procedure(Sender: TrmCustomPathTreeView; Node: TrmTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean) of object; { TrmTreeNode } TrmTreeNode = class(TPersistent) private FOwner: TrmTreeNodes; FText: string; FData: Pointer; FItemId: HTreeItem; FImageIndex: TImageIndex; FSelectedIndex: Integer; FOverlayIndex: Integer; FStateIndex: Integer; FDeleting: Boolean; FInTree: Boolean; function CompareCount(CompareMe: Integer) : Boolean; function DoCanExpand(Expand: Boolean) : Boolean; procedure DoExpand(Expand: Boolean) ; procedure ExpandItem(Expand: Boolean; Recurse: Boolean) ; function GetAbsoluteIndex: Integer; function GetExpanded: Boolean; function GetLevel: Integer; function GetParent: TrmTreeNode; function GetChildren: Boolean; function GetCut: Boolean; function GetDropTarget: Boolean; function GetFocused: Boolean; function GetIndex: Integer; function GetItem(Index: Integer) : TrmTreeNode; function GetSelected: Boolean; function GetState(NodeState: TNodeState) : Boolean; function GetCount: Integer; function GetTreeView: TrmCustomPathTreeView; procedure InternalMove(ParentNode, Node: TrmTreeNode; HItem: HTreeItem; AddMode: TAddMode) ; function IsEqual(Node: TrmTreeNode) : Boolean; function IsNodeVisible: Boolean; procedure ReadData(Stream: TStream; Info: PNodeInfo) ; procedure SetChildren(Value: Boolean) ; procedure SetCut(Value: Boolean) ; procedure SetData(Value: Pointer) ; procedure SetDropTarget(Value: Boolean) ; procedure SetItem(Index: Integer; Value: TrmTreeNode) ; procedure SetExpanded(Value: Boolean) ; procedure SetFocused(Value: Boolean) ; procedure SetImageIndex(Value: TImageIndex) ; procedure SetOverlayIndex(Value: Integer) ; procedure SetSelectedIndex(Value: Integer) ; procedure SetSelected(Value: Boolean) ; procedure SetStateIndex(Value: Integer) ; procedure SetText(const S: string) ; procedure WriteData(Stream: TStream; Info: PNodeInfo) ; procedure RemoveHash; procedure RenewHash; procedure SetParent(const Value: TrmTreeNode); public constructor Create(AOwner: TrmTreeNodes) ; destructor Destroy; override; function AlphaSort: Boolean; procedure Assign(Source: TPersistent) ; override; procedure Collapse(Recurse: Boolean) ; function CustomSort(SortProc: TTVCompare; Data: Longint) : Boolean; procedure Delete; procedure DeleteChildren; function DisplayRect(TextOnly: Boolean) : TRect; function EditText: Boolean; procedure EndEdit(Cancel: Boolean) ; procedure Expand(Recurse: Boolean) ; function getFirstChild: TrmTreeNode; {GetFirstChild conflicts with C++ macro} function GetHandle: HWND; function GetLastChild: TrmTreeNode; function GetNext: TrmTreeNode; function GetNextChild(Value: TrmTreeNode) : TrmTreeNode; function getNextSibling: TrmTreeNode; {GetNextSibling conflicts with C++ macro} function GetNextVisible: TrmTreeNode; function GetPrev: TrmTreeNode; function GetPrevChild(Value: TrmTreeNode) : TrmTreeNode; function getPrevSibling: TrmTreeNode; {GetPrevSibling conflicts with a C++ macro} function GetPrevVisible: TrmTreeNode; function HasAsParent(Value: TrmTreeNode) : Boolean; function IndexOf(Value: TrmTreeNode) : Integer; procedure MakeVisible; procedure MoveTo(Destination: TrmTreeNode; Mode: TNodeAttachMode) ; virtual; property AbsoluteIndex: Integer read GetAbsoluteIndex; property Count: Integer read GetCount; property Cut: Boolean read GetCut write SetCut; property Data: Pointer read FData write SetData; property Deleting: Boolean read FDeleting; property Focused: Boolean read GetFocused write SetFocused; property DropTarget: Boolean read GetDropTarget write SetDropTarget; property Selected: Boolean read GetSelected write SetSelected; property Expanded: Boolean read GetExpanded write SetExpanded; property Handle: HWND read GetHandle; property HasChildren: Boolean read GetChildren write SetChildren; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex; property Index: Integer read GetIndex; property IsVisible: Boolean read IsNodeVisible; property Item[Index: Integer]: TrmTreeNode read GetItem write SetItem; default; property ItemId: HTreeItem read FItemId; property Level: Integer read GetLevel; property OverlayIndex: Integer read FOverlayIndex write SetOverlayIndex; property Owner: TrmTreeNodes read FOwner; property Parent: TrmTreeNode read GetParent write SetParent; property SelectedIndex: Integer read FSelectedIndex write SetSelectedIndex; property StateIndex: Integer read FStateIndex write SetStateIndex; property Text: string read FText write SetText; property TreeView: TrmCustomPathTreeView read GetTreeView; end; { TrmTreeNodes } TrmHashData = class(TObject) Hash: longint; IDLength: Integer; Node: TrmTreeNode; end; PrmNodeCache = ^TrmNodeCache; TrmNodeCache = record CacheNode: TrmTreeNode; CacheIndex: Integer; end; TrmTreeNodes = class(TPersistent) private FOwner: TrmCustomPathTreeView; FUpdateCount: Integer; FNodeCache: TrmNodeCache; FHashList: TObjectList; procedure AddedNode(Value: TrmTreeNode) ; function GetHandle: HWND; function GetNodeFromIndex(Index: Integer) : TrmTreeNode; procedure ReadData(Stream: TStream) ; procedure Repaint(Node: TrmTreeNode) ; procedure WriteData(Stream: TStream) ; procedure ClearCache; procedure WriteExpandedState(Stream: TStream) ; procedure ReadExpandedState(Stream: TStream) ; //Path Index Hashing function HashValue(St: string) : LongInt; function LocateHashIndex(Path: string) : integer; procedure BinaryInsert(Path: string; Node: TrmTreeNode) ; procedure RemoveHash(Node: TrmTreeNode) ; protected function AddItem(Parent, Target: HTreeItem; const Item: TTVItem; AddMode: TAddMode) : HTreeItem; function InternalAddObject(Node: TrmTreeNode; const S: string; Ptr: Pointer; AddMode: TAddMode) : TrmTreeNode; procedure DefineProperties(Filer: TFiler) ; override; function CreateItem(Node: TrmTreeNode) : TTVItem; function GetCount: Integer; procedure SetItem(Index: Integer; Value: TrmTreeNode) ; procedure SetUpdateState(Updating: Boolean) ; public procedure DumpHash; constructor Create(AOwner: TrmCustomPathTreeView) ; destructor Destroy; override; function AddChildFirst(Node: TrmTreeNode; const S: string) : TrmTreeNode; function AddChild(Node: TrmTreeNode; const S: string) : TrmTreeNode; function AddChildObjectFirst(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; function AddChildObject(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; function AddFirst(Node: TrmTreeNode; const S: string) : TrmTreeNode; function Add(Node: TrmTreeNode; const S: string) : TrmTreeNode; function AddObjectFirst(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; function AddObject(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; procedure Assign(Source: TPersistent) ; override; procedure BeginUpdate; procedure Clear; procedure Delete(Node: TrmTreeNode) ; procedure EndUpdate; function GetFirstNode: TrmTreeNode; function GetNode(ItemId: HTreeItem) : TrmTreeNode; function Insert(Node: TrmTreeNode; const S: string) : TrmTreeNode; function InsertObject(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; function LocateNode(Path: string) : TrmTreeNode; property Count: Integer read GetCount; property Handle: HWND read GetHandle; property Item[Index: Integer]: TrmTreeNode read GetNodeFromIndex; default; property Owner: TrmCustomPathTreeView read FOwner; end; { TrmCustomPathTreeView } TrmCustomPathTreeView = class(TWinControl) private FAutoExpand: Boolean; FBorderStyle: TBorderStyle; FCanvas: TCanvas; FCanvasChanged: Boolean; FDefEditProc: Pointer; FDragged: Boolean; FDragImage: TDragImageList; FDragNode: TrmTreeNode; FEditHandle: HWND; FEditInstance: Pointer; FHideSelection: Boolean; FHotTrack: Boolean; FImageChangeLink: TChangeLink; FImages: TCustomImageList; FLastDropTarget: TrmTreeNode; FMemStream: TMemoryStream; FRClickNode: TrmTreeNode; FRightClickSelect: Boolean; FManualNotify: Boolean; FReadOnly: Boolean; FRowSelect: Boolean; FSaveIndex: Integer; FSaveIndent: Integer; FSaveItems: TStringList; FSaveTopIndex: Integer; FShowButtons: Boolean; FShowLines: Boolean; FShowRoot: Boolean; FSortType: TSortType; FStateChanging: Boolean; FStateImages: TCustomImageList; FStateChangeLink: TChangeLink; FToolTips: Boolean; FTreeNodes: TrmTreeNodes; FWideText: WideString; FOnAdvancedCustomDraw: TrmTVAdvancedCustomDrawEvent; FOnAdvancedCustomDrawItem: TrmTVAdvancedCustomDrawItemEvent; FOnChange: TrmTVChangedEvent; FOnChanging: TrmTVChangingEvent; FOnCollapsed: TrmTVExpandedEvent; FOnCollapsing: TrmTVCollapsingEvent; FOnCompare: TrmTVCompareEvent; FOnCustomDraw: TrmTVCustomDrawEvent; FOnCustomDrawItem: TrmTVCustomDrawItemEvent; FOnDeletion: TrmTVExpandedEvent; FOnEditing: TrmTVEditingEvent; FOnEdited: TrmTVEditedEvent; FOnExpanded: TrmTVExpandedEvent; FOnExpanding: TrmTVExpandingEvent; FOnGetImageIndex: TrmTVExpandedEvent; FOnGetSelectedIndex: TrmTVExpandedEvent; //Path seperator character FSepChar: Char; procedure CanvasChanged(Sender: TObject) ; procedure CMColorChanged(var Message: TMessage) ; message CM_COLORCHANGED; procedure CMCtl3DChanged(var Message: TMessage) ; message CM_CTL3DCHANGED; procedure CMFontChanged(var Message: TMessage) ; message CM_FONTCHANGED; procedure CMDrag(var Message: TCMDrag) ; message CM_DRAG; procedure CNNotify(var Message: TWMNotify) ; message CN_NOTIFY; procedure EditWndProc(var Message: TMessage) ; procedure DoDragOver(Source: TDragObject; X, Y: Integer; CanDrop: Boolean) ; function GetChangeDelay: Integer; function GetDropTarget: TrmTreeNode; function GetIndent: Integer; function GetNodeFromItem(const Item: TTVItem) : TrmTreeNode; function GetSelection: TrmTreeNode; function GetTopItem: TrmTreeNode; procedure ImageListChange(Sender: TObject) ; procedure SetAutoExpand(Value: Boolean) ; procedure SetBorderStyle(Value: TBorderStyle) ; procedure SetButtonStyle(Value: Boolean) ; procedure SetChangeDelay(Value: Integer) ; procedure SetDropTarget(Value: TrmTreeNode) ; procedure SetHideSelection(Value: Boolean) ; procedure SetHotTrack(Value: Boolean) ; procedure SetImageList(Value: HImageList; Flags: Integer) ; procedure SetIndent(Value: Integer) ; procedure SetImages(Value: TCustomImageList) ; procedure SetLineStyle(Value: Boolean) ; procedure SetReadOnly(Value: Boolean) ; procedure SetRootStyle(Value: Boolean) ; procedure SetRowSelect(Value: Boolean) ; procedure SetSelection(Value: TrmTreeNode) ; procedure SetSortType(Value: TSortType) ; procedure SetStateImages(Value: TCustomImageList) ; procedure SetToolTips(Value: Boolean) ; procedure SetrmTreeNodes(Value: TrmTreeNodes) ; procedure SetTopItem(Value: TrmTreeNode) ; procedure OnChangeTimer(Sender: TObject) ; procedure WMLButtonDown(var Message: TWMLButtonDown) ; message WM_LBUTTONDOWN; procedure WMNotify(var Message: TWMNotify) ; message WM_NOTIFY; procedure WMContextMenu(var Message: TWMContextMenu) ; message WM_CONTEXTMENU; procedure CMSysColorChange(var Message: TMessage) ; message CM_SYSCOLORCHANGE; //Pathing functions... function ChildName(s: string) : string; function ParentName(s: string) : string; //Fix for MS ComCtrl bug with treeviews and hintwindows... procedure SetNewHint(Node: TrmTreeNode) ; procedure CMCancelMode(var Message: TMessage) ; message CM_CancelMode; procedure CMMouseLeave(var Message: TMessage) ; message CM_MouseLeave; //Extranous functions from Pat's original code... function GetFocussedNode: TrmTreeNode; procedure SetFocussedNode(const Value: TrmTreeNode) ; protected FChangeTimer: TTimer; function CanEdit(Node: TrmTreeNode) : Boolean; dynamic; function CanChange(Node: TrmTreeNode) : Boolean; dynamic; function CanCollapse(Node: TrmTreeNode) : Boolean; dynamic; function CanExpand(Node: TrmTreeNode) : Boolean; dynamic; procedure Change(Node: TrmTreeNode) ; dynamic; procedure Collapse(Node: TrmTreeNode) ; dynamic; function CreateNode: TrmTreeNode; virtual; procedure CreateParams(var Params: TCreateParams) ; override; procedure CreateWnd; override; function CustomDraw(const ARect: TRect; Stage: TCustomDrawStage) : Boolean; virtual; function CustomDrawItem(Node: TrmTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages: Boolean) : Boolean; virtual; procedure Delete(Node: TrmTreeNode) ; dynamic; procedure DestroyWnd; override; procedure DoEndDrag(Target: TObject; X, Y: Integer) ; override; procedure DoStartDrag(var DragObject: TDragObject) ; override; procedure Edit(const Item: TTVItem) ; dynamic; procedure Expand(Node: TrmTreeNode) ; dynamic; function GetDragImages: TDragImageList; override; procedure GetImageIndex(Node: TrmTreeNode) ; virtual; procedure GetSelectedIndex(Node: TrmTreeNode) ; virtual; function IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage) : Boolean; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation) ; override; procedure SetDragMode(Value: TDragMode) ; override; procedure WndProc(var Message: TMessage) ; override; //Fix for MS ComCtrl bug with treeviews and hintwindows... procedure MouseMove(Shift: TShiftState; X, Y: Integer) ; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer) ; override; property AutoExpand: Boolean read FAutoExpand write SetAutoExpand default False; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property ChangeDelay: Integer read GetChangeDelay write SetChangeDelay default 0; property HideSelection: Boolean read FHideSelection write SetHideSelection default True; property HotTrack: Boolean read FHotTrack write SetHotTrack default False; property Images: TCustomImageList read FImages write SetImages; property Indent: Integer read GetIndent write SetIndent; property Items: TrmTreeNodes read FTreeNodes write SeTrmTreeNodes; property ReadOnly: Boolean read FReadOnly write SetReadOnly default False; property RightClickSelect: Boolean read FRightClickSelect write FRightClickSelect default False; property RowSelect: Boolean read FRowSelect write SetRowSelect default False; property ShowButtons: Boolean read FShowButtons write SetButtonStyle default True; property ShowLines: Boolean read FShowLines write SetLineStyle default True; property ShowRoot: Boolean read FShowRoot write SetRootStyle default True; property SortType: TSortType read FSortType write SetSortType default stNone; property StateImages: TCustomImageList read FStateImages write SetStateImages; property ToolTips: Boolean read FToolTips write SetToolTips default True; property OnAdvancedCustomDraw: TrmTVAdvancedCustomDrawEvent read FOnAdvancedCustomDraw write FOnAdvancedCustomDraw; property OnAdvancedCustomDrawItem: TrmTVAdvancedCustomDrawItemEvent read FOnAdvancedCustomDrawItem write FOnAdvancedCustomDrawItem; property OnChange: TrmTVChangedEvent read FOnChange write FOnChange; property OnChanging: TrmTVChangingEvent read FOnChanging write FOnChanging; property OnCollapsed: TrmTVExpandedEvent read FOnCollapsed write FOnCollapsed; property OnCollapsing: TrmTVCollapsingEvent read FOnCollapsing write FOnCollapsing; property OnCompare: TrmTVCompareEvent read FOnCompare write FOnCompare; property OnCustomDraw: TrmTVCustomDrawEvent read FOnCustomDraw write FOnCustomDraw; property OnCustomDrawItem: TrmTVCustomDrawItemEvent read FOnCustomDrawItem write FOnCustomDrawItem; property OnDeletion: TrmTVExpandedEvent read FOnDeletion write FOnDeletion; property OnEditing: TrmTVEditingEvent read FOnEditing write FOnEditing; property OnEdited: TrmTVEditedEvent read FOnEdited write FOnEdited; property OnExpanding: TrmTVExpandingEvent read FOnExpanding write FOnExpanding; property OnExpanded: TrmTVExpandedEvent read FOnExpanded write FOnExpanded; property OnGetImageIndex: TrmTVExpandedEvent read FOnGetImageIndex write FOnGetImageIndex; property OnGetSelectedIndex: TrmTVExpandedEvent read FOnGetSelectedIndex write FOnGetSelectedIndex; public constructor Create(AOwner: TComponent) ; override; destructor Destroy; override; function AlphaSort: Boolean; function CustomSort(SortProc: TTVCompare; Data: Longint) : Boolean; procedure FullCollapse; procedure FullExpand; function GetHitTestInfoAt(X, Y: Integer) : THitTests; function GetNodeAt(X, Y: Integer) : TrmTreeNode; function IsEditing: Boolean; procedure LoadFromFile(const FileName: string) ; procedure LoadFromStream(Stream: TStream) ; procedure SaveToFile(const FileName: string) ; procedure SaveToStream(Stream: TStream) ; //Pathing functions... function AddPathNode(Node: TrmTreeNode; Path: string) : TrmTreeNode; function FindPathNode(Path: string) : TrmTreeNode; function NodePath(Node: TrmTreeNode) : string; property Canvas: TCanvas read FCanvas; property DropTarget: TrmTreeNode read GetDropTarget write SetDropTarget; property Selected: TrmTreeNode read GetSelection write SetSelection; property TopItem: TrmTreeNode read GetTopItem write SetTopItem; //Original PathTreeView property. Not exactly sure why Pat had this in here but.... property FocussedNode: TrmTreeNode read GetFocussedNode write SetFocussedNode; published //Path seperator character property SepChar: Char read FSepChar write FSepChar default #47; end; TrmPathTreeView = class(TrmCustomPathTreeView) published property Align; property Anchors; property AutoExpand; property BiDiMode; property BorderStyle; property BorderWidth; property ChangeDelay; property Color; property Ctl3D; property Constraints; property DragKind; property DragCursor; property DragMode; property Enabled; property Font; property HideSelection; property HotTrack; property Images; property Indent; property ParentBiDiMode; property ParentColor default False; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property RightClickSelect; property RowSelect; property ShowButtons; property ShowHint; property ShowLines; property ShowRoot; property SortType; property StateImages; property TabOrder; property TabStop default True; property ToolTips; property Visible; property OnAdvancedCustomDraw; property OnAdvancedCustomDrawItem; property OnChange; property OnChanging; property OnClick; property OnCollapsed; property OnCollapsing; property OnCompare; property OnContextPopup; property OnCustomDraw; property OnCustomDrawItem; property OnDblClick; property OnDeletion; property OnDragDrop; property OnDragOver; property OnEdited; property OnEditing; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnExpanding; property OnExpanded; property OnGetImageIndex; property OnGetSelectedIndex; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; { Items must be published after OnGetImageIndex and OnGetSelectedIndex } property Items; end; implementation {$ifdef D6_or_higher} uses rmHint, RTLConsts, comstrs, rmLibrary; {$else} uses rmHint, Consts, comstrs, rmLibrary; {$endif} type PFontHandles = ^TFontHandles; TFontHandles = record OurFont, StockFont: Integer; end; var fHint: TrmHintWindow; procedure SetComCtlStyle(Ctl: TWinControl; Value: Integer; UseStyle: Boolean) ; var Style: Integer; begin if Ctl.HandleAllocated then begin Style := GetWindowLong(Ctl.Handle, GWL_STYLE) ; if not UseStyle then Style := Style and not Value else Style := Style or Value; SetWindowLong(Ctl.Handle, GWL_STYLE, Style) ; end; end; { TrmTreeNode } function DefaultTreeViewSort(Node1, Node2: TrmTreeNode; lParam: Integer) : Integer; stdcall; begin with Node1 do if Assigned(TreeView.OnCompare) then TreeView.OnCompare(TreeView, Node1, Node2, lParam, Result) else Result := lstrcmp(PChar(Node1.Text) , PChar(Node2.Text) ) ; end; procedure TreeViewError(const Msg: string) ; begin raise ETreeViewError.Create(Msg) ; end; procedure TreeViewErrorFmt(const Msg: string; Format: array of const) ; begin raise ETreeViewError.CreateFmt(Msg, Format) ; end; constructor TrmTreeNode.Create(AOwner: TrmTreeNodes) ; begin inherited Create; FOverlayIndex := -1; FStateIndex := -1; FOwner := AOwner; end; destructor TrmTreeNode.Destroy; var Node: TrmTreeNode; CheckValue: Integer; begin Owner.ClearCache; FDeleting := True; Owner.RemoveHash(self) ; if Owner.Owner.FLastDropTarget = Self then Owner.Owner.FLastDropTarget := nil; Node := Parent; if (Node <> nil) and (not Node.Deleting) then begin if Node.IndexOf(Self) <> -1 then CheckValue := 1 else CheckValue := 0; if Node.CompareCount(CheckValue) then begin Expanded := False; Node.HasChildren := False; end; end; if ItemId <> nil then TreeView_DeleteItem(Handle, ItemId) ; Data := nil; inherited Destroy; end; function TrmTreeNode.GetHandle: HWND; begin Result := TreeView.Handle; end; function TrmTreeNode.GetTreeView: TrmCustomPathTreeView; begin Result := Owner.Owner; end; function TrmTreeNode.HasAsParent(Value: TrmTreeNode) : Boolean; begin if Value <> Nil then begin if Parent = nil then Result := False else if Parent = Value then Result := True else Result := Parent.HasAsParent(Value) ; end else Result := True; end; procedure TrmTreeNode.SetText(const S: string) ; var Item: TTVItem; fRemoved: boolean; begin fRemoved := false; if not (FText = '') and (FText <> S) then begin Self.RemoveHash; fRemoved := true; end; FText := S; with Item do begin mask := TVIF_TEXT; hItem := ItemId; pszText := LPSTR_TEXTCALLBACK; end; TreeView_SetItem(Handle, Item) ; if (TreeView.SortType in [stText, stBoth]) and FInTree then begin if (Parent <> nil) then Parent.AlphaSort else TreeView.AlphaSort; end; if fremoved and not (fText = '') then begin Self.RenewHash; end; end; procedure TrmTreeNode.SetData(Value: Pointer) ; begin FData := Value; if (TreeView.SortType in [stData, stBoth]) and Assigned(TreeView.OnCompare) and (not Deleting) and FInTree then begin if Parent <> nil then Parent.AlphaSort else TreeView.AlphaSort; end; end; function TrmTreeNode.GetState(NodeState: TNodeState) : Boolean; var Item: TTVItem; begin Result := False; with Item do begin mask := TVIF_STATE; hItem := ItemId; if TreeView_GetItem(Handle, Item) then case NodeState of nsCut: Result := (state and TVIS_CUT) <> 0; nsFocused: Result := (state and TVIS_FOCUSED) <> 0; nsSelected: Result := (state and TVIS_SELECTED) <> 0; nsExpanded: Result := (state and TVIS_EXPANDED) <> 0; nsDropHilited: Result := (state and TVIS_DROPHILITED) <> 0; end; end; end; procedure TrmTreeNode.SetImageIndex(Value: TImageIndex) ; var Item: TTVItem; begin FImageIndex := Value; with Item do begin mask := TVIF_IMAGE or TVIF_HANDLE; hItem := ItemId; if Assigned(TrmCustomPathTreeView(Owner.Owner) .OnGetImageIndex) then iImage := I_IMAGECALLBACK else iImage := FImageIndex; end; TreeView_SetItem(Handle, Item) ; end; procedure TrmTreeNode.SetSelectedIndex(Value: Integer) ; var Item: TTVItem; begin FSelectedIndex := Value; with Item do begin mask := TVIF_SELECTEDIMAGE or TVIF_HANDLE; hItem := ItemId; if Assigned(TrmCustomPathTreeView(Owner.Owner) .OnGetSelectedIndex) then iSelectedImage := I_IMAGECALLBACK else iSelectedImage := FSelectedIndex; end; TreeView_SetItem(Handle, Item) ; end; procedure TrmTreeNode.SetOverlayIndex(Value: Integer) ; var Item: TTVItem; begin FOverlayIndex := Value; with Item do begin mask := TVIF_STATE or TVIF_HANDLE; stateMask := TVIS_OVERLAYMASK; hItem := ItemId; state := IndexToOverlayMask(FOverlayIndex + 1) ; end; TreeView_SetItem(Handle, Item) ; end; procedure TrmTreeNode.SetStateIndex(Value: Integer) ; var Item: TTVItem; begin FStateIndex := Value; if Value >= 0 then Dec(Value) ; with Item do begin mask := TVIF_STATE or TVIF_HANDLE; stateMask := TVIS_STATEIMAGEMASK; hItem := ItemId; state := IndexToStateImageMask(Value + 1) ; end; TreeView_SetItem(Handle, Item) ; end; function TrmTreeNode.CompareCount(CompareMe: Integer) : Boolean; var Count: integer; Node: TrmTreeNode; Begin Count := 0; Result := False; Node := GetFirstChild; while Node <> nil do begin Inc(Count) ; Node := Node.GetNextChild(Node) ; if Count > CompareMe then Exit; end; if Count = CompareMe then Result := True; end; function TrmTreeNode.DoCanExpand(Expand: Boolean) : Boolean; begin Result := False; if HasChildren then begin if Expand then Result := TreeView.CanExpand(Self) else Result := TreeView.CanCollapse(Self) ; end; end; procedure TrmTreeNode.DoExpand(Expand: Boolean) ; begin if HasChildren then begin if Expand then TreeView.Expand(Self) else TreeView.Collapse(Self) ; end; end; procedure TrmTreeNode.ExpandItem(Expand: Boolean; Recurse: Boolean) ; var Flag: Integer; Node: TrmTreeNode; begin if Recurse then begin Node := Self; repeat Node.ExpandItem(Expand, False) ; Node := Node.GetNext; until (Node = nil) or (not Node.HasAsParent(Self) ) ; end else begin TreeView.FManualNotify := True; try Flag := 0; if Expand then begin if DoCanExpand(True) then begin Flag := TVE_EXPAND; DoExpand(True) ; end; end else begin if DoCanExpand(False) then begin Flag := TVE_COLLAPSE; DoExpand(False) ; end; end; if Flag <> 0 then TreeView_Expand(Handle, ItemId, Flag) ; finally TreeView.FManualNotify := False; end; end; end; procedure TrmTreeNode.Expand(Recurse: Boolean) ; begin ExpandItem(True, Recurse) ; end; procedure TrmTreeNode.Collapse(Recurse: Boolean) ; begin ExpandItem(False, Recurse) ; end; function TrmTreeNode.GetExpanded: Boolean; begin Result := GetState(nsExpanded) ; end; procedure TrmTreeNode.SetExpanded(Value: Boolean) ; begin if Value then Expand(False) else Collapse(False) ; end; function TrmTreeNode.GetSelected: Boolean; begin Result := GetState(nsSelected) ; end; procedure TrmTreeNode.SetSelected(Value: Boolean) ; begin if Value then TreeView_SelectItem(Handle, ItemId) else if Selected then TreeView_SelectItem(Handle, nil) ; end; function TrmTreeNode.GetCut: Boolean; begin Result := GetState(nsCut) ; end; procedure TrmTreeNode.SetCut(Value: Boolean) ; var Item: TTVItem; Template: DWORD; begin if Value then Template := DWORD(-1) else Template := 0; with Item do begin mask := TVIF_STATE; hItem := ItemId; stateMask := TVIS_CUT; state := stateMask and Template; end; TreeView_SetItem(Handle, Item) ; end; function TrmTreeNode.GetDropTarget: Boolean; begin Result := GetState(nsDropHilited) ; end; procedure TrmTreeNode.SetDropTarget(Value: Boolean) ; begin if Value then TreeView_SelectDropTarget(Handle, ItemId) else if DropTarget then TreeView_SelectDropTarget(Handle, nil) ; end; function TrmTreeNode.GetChildren: Boolean; var Item: TTVItem; begin Item.mask := TVIF_CHILDREN; Item.hItem := ItemId; if TreeView_GetItem(Handle, Item) then Result := Item.cChildren > 0 else Result := False; end; procedure TrmTreeNode.SetFocused(Value: Boolean) ; var Item: TTVItem; Template: DWORD; begin if Value then Template := DWORD(-1) else Template := 0; with Item do begin mask := TVIF_STATE; hItem := ItemId; stateMask := TVIS_FOCUSED; state := stateMask and Template; end; TreeView_SetItem(Handle, Item) ; end; function TrmTreeNode.GetFocused: Boolean; begin Result := GetState(nsFocused) ; end; procedure TrmTreeNode.SetChildren(Value: Boolean) ; var Item: TTVItem; begin with Item do begin mask := TVIF_CHILDREN; hItem := ItemId; cChildren := Ord(Value) ; end; TreeView_SetItem(Handle, Item) ; end; function TrmTreeNode.GetParent: TrmTreeNode; begin with FOwner do Result := GetNode(TreeView_GetParent(Handle, ItemId) ) ; end; function TrmTreeNode.GetNextSibling: TrmTreeNode; begin with FOwner do Result := GetNode(TreeView_GetNextSibling(Handle, ItemId) ) ; end; function TrmTreeNode.GetPrevSibling: TrmTreeNode; begin with FOwner do Result := GetNode(TreeView_GetPrevSibling(Handle, ItemId) ) ; end; function TrmTreeNode.GetNextVisible: TrmTreeNode; begin if IsVisible then with FOwner do Result := GetNode(TreeView_GetNextVisible(Handle, ItemId) ) else Result := nil; end; function TrmTreeNode.GetPrevVisible: TrmTreeNode; begin with FOwner do Result := GetNode(TreeView_GetPrevVisible(Handle, ItemId) ) ; end; function TrmTreeNode.GetNextChild(Value: TrmTreeNode) : TrmTreeNode; begin if Value <> nil then Result := Value.GetNextSibling else Result := nil; end; function TrmTreeNode.GetPrevChild(Value: TrmTreeNode) : TrmTreeNode; begin if Value <> nil then Result := Value.GetPrevSibling else Result := nil; end; function TrmTreeNode.GetFirstChild: TrmTreeNode; begin with FOwner do Result := GetNode(TreeView_GetChild(Handle, ItemId) ) ; end; function TrmTreeNode.GetLastChild: TrmTreeNode; var Node: TrmTreeNode; begin Result := GetFirstChild; if Result <> nil then begin Node := Result; repeat Result := Node; Node := Result.GetNextSibling; until Node = nil; end; end; function TrmTreeNode.GetNext: TrmTreeNode; var NodeID, ParentID: HTreeItem; Handle: HWND; begin Handle := FOwner.Handle; NodeID := TreeView_GetChild(Handle, ItemId) ; if NodeID = nil then NodeID := TreeView_GetNextSibling(Handle, ItemId) ; ParentID := ItemId; while (NodeID = nil) and (ParentID <> nil) do begin ParentID := TreeView_GetParent(Handle, ParentID) ; NodeID := TreeView_GetNextSibling(Handle, ParentID) ; end; Result := FOwner.GetNode(NodeID) ; end; function TrmTreeNode.GetPrev: TrmTreeNode; var Node: TrmTreeNode; begin Result := GetPrevSibling; if Result <> nil then begin Node := Result; repeat Result := Node; Node := Result.GetLastChild; until Node = nil; end else Result := Parent; end; function TrmTreeNode.GetAbsoluteIndex: Integer; var Node: TrmTreeNode; begin if Owner.FNodeCache.CacheNode = Self then Result := Owner.FNodeCache.CacheIndex else begin Result := -1; Node := Self; while Node <> nil do begin Inc(Result) ; Node := Node.GetPrev; end; end; end; function TrmTreeNode.GetIndex: Integer; var Node: TrmTreeNode; begin Result := -1; Node := Self; while Node <> nil do begin Inc(Result) ; Node := Node.GetPrevSibling; end; end; function TrmTreeNode.GetItem(Index: Integer) : TrmTreeNode; begin Result := GetFirstChild; while (Result <> nil) and (Index > 0) do begin Result := GetNextChild(Result) ; Dec(Index) ; end; if Result = nil then TreeViewError(SListIndexError) ; end; procedure TrmTreeNode.SetItem(Index: Integer; Value: TrmTreeNode) ; begin item[Index].Assign(Value) ; end; function TrmTreeNode.IndexOf(Value: TrmTreeNode) : Integer; var Node: TrmTreeNode; begin Result := -1; Node := GetFirstChild; while (Node <> nil) do begin Inc(Result) ; if Node = Value then Break; Node := GetNextChild(Node) ; end; if Node = nil then Result := -1; end; function TrmTreeNode.GetCount: Integer; var Node: TrmTreeNode; begin Result := 0; Node := GetFirstChild; while Node <> nil do begin Inc(Result) ; Node := Node.GetNextChild(Node) ; end; end; procedure TrmTreeNode.EndEdit(Cancel: Boolean) ; begin TreeView_EndEditLabelNow(Handle, Cancel) ; end; procedure TrmTreeNode.InternalMove(ParentNode, Node: TrmTreeNode; HItem: HTreeItem; AddMode: TAddMode) ; var I: Integer; NodeId: HTreeItem; TreeViewItem: TTVItem; Children: Boolean; IsSelected: Boolean; begin Owner.ClearCache; if (AddMode = taInsert) and (Node <> nil) then NodeId := Node.ItemId else NodeId := nil; Children := HasChildren; IsSelected := Selected; if (Parent <> nil) and (Parent.CompareCount(1) ) then begin Parent.Expanded := False; Parent.HasChildren := False; end; with TreeViewItem do begin mask := TVIF_PARAM; hItem := ItemId; lParam := 0; end; TreeView_SetItem(Handle, TreeViewItem) ; with Owner do HItem := AddItem(HItem, NodeId, CreateItem(Self) , AddMode) ; if HItem = nil then raise EOutOfResources.Create(sInsertError) ; for I := Count - 1 downto 0 do Item[I].InternalMove(Self, nil, HItem, taAddFirst) ; TreeView_DeleteItem(Handle, ItemId) ; FItemId := HItem; Assign(Self) ; HasChildren := Children; Selected := IsSelected; end; procedure TrmTreeNode.MoveTo(Destination: TrmTreeNode; Mode: TNodeAttachMode) ; var AddMode: TAddMode; Node: TrmTreeNode; HItem: HTreeItem; OldOnChanging: TrmTVChangingEvent; OldOnChange: TrmTVChangedEvent; begin OldOnChanging := TreeView.OnChanging; OldOnChange := TreeView.OnChange; TreeView.OnChanging := nil; TreeView.OnChange := nil; try if (Destination = nil) or not Destination.HasAsParent(Self) then begin AddMode := taAdd; if (Destination <> nil) and not (Mode in [naAddChild, naAddChildFirst]) then Node := Destination.Parent else Node := Destination; case Mode of naAdd, naAddChild: AddMode := taAdd; naAddFirst, naAddChildFirst: AddMode := taAddFirst; naInsert: begin Destination := Destination.GetPrevSibling; if Destination = nil then AddMode := taAddFirst else AddMode := taInsert; end; end; if Node <> nil then HItem := Node.ItemId else HItem := nil; if (Destination <> Self) then begin RemoveHash; InternalMove(Node, Destination, HItem, AddMode) ; RenewHash; end; Node := Parent; if Node <> nil then begin Node.HasChildren := True; Node.Expanded := True; end; end; finally TreeView.OnChanging := OldOnChanging; TreeView.OnChange := OldOnChange; end; end; procedure TrmTreeNode.MakeVisible; begin TreeView_EnsureVisible(Handle, ItemId) ; end; function TrmTreeNode.GetLevel: Integer; var Node: TrmTreeNode; begin Result := 0; Node := Parent; while Node <> nil do begin Inc(Result) ; Node := Node.Parent; end; end; function TrmTreeNode.IsNodeVisible: Boolean; var Rect: TRect; begin Result := TreeView_GetItemRect(Handle, ItemId, Rect, True) ; end; function TrmTreeNode.EditText: Boolean; begin Result := TreeView_EditLabel(Handle, ItemId) <> 0; end; function TrmTreeNode.DisplayRect(TextOnly: Boolean) : TRect; begin FillChar(Result, SizeOf(Result) , 0) ; TreeView_GetItemRect(Handle, ItemId, Result, TextOnly) ; end; function TrmTreeNode.AlphaSort: Boolean; begin Result := CustomSort(nil, 0) ; end; function TrmTreeNode.CustomSort(SortProc: TTVCompare; Data: Longint) : Boolean; var SortCB: TTVSortCB; begin Owner.ClearCache; with SortCB do begin if not Assigned(SortProc) then lpfnCompare := @DefaultTreeViewSort else lpfnCompare := SortProc; hParent := ItemId; lParam := Data; end; Result := TreeView_SortChildrenCB(Handle, SortCB, 0) ; end; procedure TrmTreeNode.Delete; begin if not Deleting then begin Owner.RemoveHash(self) ; Free; end; end; procedure TrmTreeNode.DeleteChildren; procedure recurseChildren(Node: TrmTreeNode) ; begin if assigned(Node) then begin Node := Node.getFirstChild; while node <> nil do begin Node.removeHash; recurseChildren(node) ; node := node.getNextSibling; end; end; end; begin recurseChildren(self) ; Owner.ClearCache; TreeView_Expand(TreeView.Handle, ItemID, TVE_COLLAPSE or TVE_COLLAPSERESET) ; HasChildren := False; end; procedure TrmTreeNode.Assign(Source: TPersistent) ; var Node: TrmTreeNode; begin Owner.ClearCache; if Source is TrmTreeNode then begin Node := TrmTreeNode(Source) ; Text := Node.Text; Data := Node.Data; ImageIndex := Node.ImageIndex; SelectedIndex := Node.SelectedIndex; StateIndex := Node.StateIndex; OverlayIndex := Node.OverlayIndex; Focused := Node.Focused; DropTarget := Node.DropTarget; Cut := Node.Cut; HasChildren := Node.HasChildren; end else inherited Assign(Source) ; end; function TrmTreeNode.IsEqual(Node: TrmTreeNode) : Boolean; begin Result := (Text = Node.Text) and (Data = Node.Data) ; end; procedure TrmTreeNode.ReadData(Stream: TStream; Info: PNodeInfo) ; var I, Size, ItemCount: Integer; begin Owner.ClearCache; Stream.ReadBuffer(Size, SizeOf(Size) ) ; Stream.ReadBuffer(Info^, Size) ; Text := Info^.Text; ImageIndex := Info^.ImageIndex; SelectedIndex := Info^.SelectedIndex; StateIndex := Info^.StateIndex; OverlayIndex := Info^.OverlayIndex; Data := Info^.Data; ItemCount := Info^.Count; for I := 0 to ItemCount - 1 do Owner.AddChild(Self, '') .ReadData(Stream, Info) ; end; procedure TrmTreeNode.WriteData(Stream: TStream; Info: PNodeInfo) ; var I, Size, L, ItemCount: Integer; begin L := Length(Text) ; if L > 255 then L := 255; Size := SizeOf(TNodeInfo) + L - 255; Info^.Text := Text; Info^.ImageIndex := ImageIndex; Info^.SelectedIndex := SelectedIndex; Info^.OverlayIndex := OverlayIndex; Info^.StateIndex := StateIndex; Info^.Data := Data; ItemCount := Count; Info^.Count := ItemCount; Stream.WriteBuffer(Size, SizeOf(Size) ) ; Stream.WriteBuffer(Info^, Size) ; for I := 0 to ItemCount - 1 do Item[I].WriteData(Stream, Info) ; end; procedure TrmTreeNode.RemoveHash; var wNode: TrmTreeNode; begin FOwner.RemoveHash(self) ; wNode := getFirstChild; while wNode <> nil do begin wNode.RemoveHash; wNode := wNode.getNextSibling; end; end; procedure TrmTreeNode.RenewHash; var wNode: TrmTreeNode; begin FOwner.BinaryInsert(FOwner.Owner.NodePath(self) , self) ; wNode := getFirstChild; while wNode <> nil do begin wNode.RenewHash; wNode := wNode.getNextSibling; end; end; procedure TrmTreeNodes.DumpHash; var fstr: TextFile; loop: integer; wdata: trmhashdata; begin AssignFile(fstr, 'c:\tvhash.txt') ; rewrite(fstr) ; for loop := 0 to fhashlist.count - 1 do begin wData := Trmhashdata(fhashlist[loop]) ; writeln(fstr, owner.nodepath(wdata.node) ) ; end; closefile(fstr) ; end; procedure TrmTreeNode.SetParent(const Value: TrmTreeNode); begin //Do Nothing... end; { TrmTreeNodes } constructor TrmTreeNodes.Create(AOwner: TrmCustomPathTreeView) ; begin inherited Create; FOwner := AOwner; FHashList := TObjectList.Create; FHashList.OwnsObjects := true; end; destructor TrmTreeNodes.Destroy; begin Clear; FHashList.Free; inherited Destroy; end; function TrmTreeNodes.GetCount: Integer; begin if Owner.HandleAllocated then Result := TreeView_GetCount(Handle) else Result := 0; end; function TrmTreeNodes.GetHandle: HWND; begin Result := Owner.Handle; end; procedure TrmTreeNodes.Delete(Node: TrmTreeNode) ; var wIndex: integer; begin //Remove the path index reference... wIndex := LocateHashIndex(Owner.NodePath(Node) ) ; if wIndex > -1 then FHashList.delete(wIndex) ; if (Node.ItemId = nil) then Owner.Delete(Node) ; Node.Delete; end; procedure TrmTreeNodes.Clear; begin ClearCache; if not (csDestroying in Owner.ComponentState) and Owner.HandleAllocated then begin FHashList.Clear; TreeView_DeleteAllItems(Owner.Handle) ; end; end; function TrmTreeNodes.AddChildFirst(Node: TrmTreeNode; const S: string) : TrmTreeNode; begin Result := AddChildObjectFirst(Node, S, nil) ; end; function TrmTreeNodes.AddChildObjectFirst(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; begin Result := InternalAddObject(Node, S, Ptr, taAddFirst) ; end; function TrmTreeNodes.AddChild(Node: TrmTreeNode; const S: string) : TrmTreeNode; begin Result := AddChildObject(Node, S, nil) ; end; function TrmTreeNodes.AddChildObject(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; begin Result := InternalAddObject(Node, S, Ptr, taAdd) ; end; function TrmTreeNodes.AddFirst(Node: TrmTreeNode; const S: string) : TrmTreeNode; begin Result := AddObjectFirst(Node, S, nil) ; end; function TrmTreeNodes.AddObjectFirst(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; begin if Node <> nil then Node := Node.Parent; Result := InternalAddObject(Node, S, Ptr, taAddFirst) ; end; function TrmTreeNodes.Add(Node: TrmTreeNode; const S: string) : TrmTreeNode; begin Result := AddObject(Node, S, nil) ; end; procedure TrmTreeNodes.Repaint(Node: TrmTreeNode) ; var R: TRect; begin if FUpdateCount < 1 then begin while (Node <> nil) and not Node.IsVisible do Node := Node.Parent; if Node <> nil then begin R := Node.DisplayRect(False) ; InvalidateRect(Owner.Handle, @R, True) ; end; end; end; function TrmTreeNodes.AddObject(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; begin if Node <> nil then Node := Node.Parent; Result := InternalAddObject(Node, S, Ptr, taAdd) ; end; function TrmTreeNodes.Insert(Node: TrmTreeNode; const S: string) : TrmTreeNode; begin Result := InsertObject(Node, S, nil) ; end; procedure TrmTreeNodes.AddedNode(Value: TrmTreeNode) ; begin if Value <> nil then begin Value.HasChildren := True; Repaint(Value) ; end; end; function TrmTreeNodes.InsertObject(Node: TrmTreeNode; const S: string; Ptr: Pointer) : TrmTreeNode; var Item, ItemId: HTreeItem; Parent: TrmTreeNode; AddMode: TAddMode; begin Result := Owner.CreateNode; try Item := nil; ItemId := nil; Parent := nil; AddMode := taInsert; if Node <> nil then begin Parent := Node.Parent; if Parent <> nil then Item := Parent.ItemId; Node := Node.GetPrevSibling; if Node <> nil then ItemId := Node.ItemId else AddMode := taAddFirst; end; Result.Data := Ptr; Result.Text := S; Item := AddItem(Item, ItemId, CreateItem(Result) , AddMode) ; if Item = nil then raise EOutOfResources.Create(sInsertError) ; Result.FItemId := Item; AddedNode(Parent) ; except Result.Free; raise; end; end; function TrmTreeNodes.InternalAddObject(Node: TrmTreeNode; const S: string; Ptr: Pointer; AddMode: TAddMode) : TrmTreeNode; var Item: HTreeItem; begin Result := Owner.CreateNode; try if Node <> nil then Item := Node.ItemId else Item := nil; Result.Data := Ptr; Result.Text := S; Item := AddItem(Item, nil, CreateItem(Result) , AddMode) ; if Item = nil then raise EOutOfResources.Create(sInsertError) ; Result.FItemId := Item; //Setting up the path index... if not (s = '') then BinaryInsert(Owner.NodePath(Result) , Result) ; if (FUpdateCount = 0) and (Result = GetFirstNode) then SendMessage(Handle, WM_SETREDRAW, 1, 0) ; AddedNode(Node) ; except Result.Free; raise; end; end; function TrmTreeNodes.CreateItem(Node: TrmTreeNode) : TTVItem; begin Node.FInTree := True; with Result do begin mask := TVIF_TEXT or TVIF_PARAM or TVIF_IMAGE or TVIF_SELECTEDIMAGE; lParam := Longint(Node) ; pszText := LPSTR_TEXTCALLBACK; iImage := I_IMAGECALLBACK; iSelectedImage := I_IMAGECALLBACK; end; end; function TrmTreeNodes.AddItem(Parent, Target: HTreeItem; const Item: TTVItem; AddMode: TAddMode) : HTreeItem; var InsertStruct: TTVInsertStruct; begin ClearCache; with InsertStruct do begin hParent := Parent; case AddMode of taAddFirst: hInsertAfter := TVI_FIRST; taAdd: hInsertAfter := TVI_LAST; taInsert: hInsertAfter := Target; end; end; InsertStruct.item := Item; FOwner.FChangeTimer.Enabled := False; Result := TreeView_InsertItem(Handle, InsertStruct) ; end; function TrmTreeNodes.GetFirstNode: TrmTreeNode; begin Result := GetNode(TreeView_GetRoot(Handle) ) ; end; function TrmTreeNodes.GetNodeFromIndex(Index: Integer) : TrmTreeNode; var I: Integer; begin if Index < 0 then TreeViewError(sInvalidIndex) ; if (FNodeCache.CacheNode <> nil) and (Abs(FNodeCache.CacheIndex - Index) <= 1) then begin with FNodeCache do begin if Index = CacheIndex then Result := CacheNode else if Index < CacheIndex then Result := CacheNode.GetPrev else Result := CacheNode.GetNext; end; end else begin Result := GetFirstNode; I := Index; while (I <> 0) and (Result <> nil) do begin Result := Result.GetNext; Dec(I) ; end; end; if Result = nil then TreeViewError(sInvalidIndex) ; FNodeCache.CacheNode := Result; FNodeCache.CacheIndex := Index; end; function TrmTreeNodes.GetNode(ItemId: HTreeItem) : TrmTreeNode; var Item: TTVItem; begin with Item do begin hItem := ItemId; mask := TVIF_PARAM; end; if TreeView_GetItem(Handle, Item) then Result := TrmTreeNode(Item.lParam) else Result := nil; end; procedure TrmTreeNodes.SetItem(Index: Integer; Value: TrmTreeNode) ; begin GetNodeFromIndex(Index) .Assign(Value) ; end; procedure TrmTreeNodes.BeginUpdate; begin if FUpdateCount = 0 then SetUpdateState(True) ; Inc(FUpdateCount) ; end; procedure TrmTreeNodes.SetUpdateState(Updating: Boolean) ; begin SendMessage(Handle, WM_SETREDRAW, Ord(not Updating) , 0) ; if not Updating then Owner.Refresh; end; procedure TrmTreeNodes.EndUpdate; begin Dec(FUpdateCount) ; if FUpdateCount = 0 then SetUpdateState(False) ; end; procedure TrmTreeNodes.Assign(Source: TPersistent) ; var TreeNodes: TrmTreeNodes; MemStream: TMemoryStream; wNode: TrmTreeNode; begin ClearCache; if Source is TrmTreeNodes then begin TreeNodes := TrmTreeNodes(Source) ; Clear; MemStream := TMemoryStream.Create; try TreeNodes.WriteData(MemStream) ; MemStream.Position := 0; ReadData(MemStream) ; finally MemStream.Free; end; //Now that we've assigned all the nodes //we need to redo that hashlist wNode := Self.GetFirstNode; while wNode <> nil do begin wNode.RenewHash; wNode := wNode.GetNextSibling; end; end else inherited Assign(Source) ; end; procedure TrmTreeNodes.DefineProperties(Filer: TFiler) ; function WriteNodes: Boolean; var I: Integer; Nodes: TrmTreeNodes; begin Nodes := TrmTreeNodes(Filer.Ancestor) ; if Nodes = nil then Result := Count > 0 else if Nodes.Count <> Count then Result := True else begin Result := False; for I := 0 to Count - 1 do begin Result := not Item[I].IsEqual(Nodes[I]) ; if Result then Break; end end; end; begin inherited DefineProperties(Filer) ; Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteNodes) ; end; procedure TrmTreeNodes.ReadData(Stream: TStream) ; var I, Count: Integer; NodeInfo: TNodeInfo; begin if Owner.HandleAllocated then BeginUpdate; try Clear; Stream.ReadBuffer(Count, SizeOf(Count) ) ; for I := 0 to Count - 1 do begin Add(nil, '') .ReadData(Stream, @NodeInfo) ; end; finally if Owner.HandleAllocated then EndUpdate; end; end; procedure TrmTreeNodes.WriteData(Stream: TStream) ; var I: Integer; NodeInfo: TNodeInfo; Node: TrmTreeNode; begin I := 0; Node := GetFirstNode; while Node <> nil do begin Inc(I) ; Node := Node.GetNextSibling; end; Stream.WriteBuffer(I, SizeOf(I) ) ; Node := GetFirstNode; while Node <> nil do begin Node.WriteData(Stream, @NodeInfo) ; Node := Node.GetNextSibling; end; end; procedure TrmTreeNodes.ReadExpandedState(Stream: TStream) ; var ItemCount, Index: Integer; Node: TrmTreeNode; NodeExpanded: Boolean; begin if Stream.Position < Stream.Size then Stream.ReadBuffer(ItemCount, SizeOf(ItemCount) ) else Exit; Index := 0; Node := GetFirstNode; while (Index < ItemCount) and (Node <> nil) do begin Stream.ReadBuffer(NodeExpanded, SizeOf(NodeExpanded) ) ; Node.Expanded := NodeExpanded; Inc(Index) ; Node := Node.GetNext; end; end; procedure TrmTreeNodes.WriteExpandedState(Stream: TStream) ; var Size: Integer; Node: TrmTreeNode; NodeExpanded: Boolean; begin Size := SizeOf(Boolean) * Count; Stream.WriteBuffer(Size, SizeOf(Size) ) ; Node := GetFirstNode; while (Node <> nil) do begin NodeExpanded := Node.Expanded; Stream.WriteBuffer(NodeExpanded, SizeOf(Boolean) ) ; Node := Node.GetNext; end; end; procedure TrmTreeNodes.ClearCache; begin FNodeCache.CacheNode := nil; end; type TTreeStrings = class(TStrings) private FOwner: TrmTreeNodes; protected function Get(Index: Integer) : string; override; function GetBufStart(Buffer: PChar; var Level: Integer) : PChar; function GetCount: Integer; override; function GetObject(Index: Integer) : TObject; override; procedure PutObject(Index: Integer; AObject: TObject) ; override; procedure SetUpdateState(Updating: Boolean) ; override; public constructor Create(AOwner: TrmTreeNodes) ; function Add(const S: string) : Integer; override; procedure Clear; override; procedure Delete(Index: Integer) ; override; procedure Insert(Index: Integer; const S: string) ; override; procedure LoadTreeFromStream(Stream: TStream) ; procedure SaveTreeToStream(Stream: TStream) ; property Owner: TrmTreeNodes read FOwner; end; constructor TTreeStrings.Create(AOwner: TrmTreeNodes) ; begin inherited Create; FOwner := AOwner; end; function TTreeStrings.Get(Index: Integer) : string; const TabChar = #9; var Level, I: Integer; Node: TrmTreeNode; begin Result := ''; Node := Owner.GetNodeFromIndex(Index) ; Level := Node.Level; for I := 0 to Level - 1 do Result := Result + TabChar; Result := Result + Node.Text; end; function TTreeStrings.GetBufStart(Buffer: PChar; var Level: Integer) : PChar; begin Level := 0; while Buffer^ in [' ', #9] do begin Inc(Buffer) ; Inc(Level) ; end; Result := Buffer; end; function TTreeStrings.GetObject(Index: Integer) : TObject; begin Result := Owner.GetNodeFromIndex(Index) .Data; end; procedure TTreeStrings.PutObject(Index: Integer; AObject: TObject) ; begin Owner.GetNodeFromIndex(Index) .Data := AObject; end; function TTreeStrings.GetCount: Integer; begin Result := Owner.Count; end; procedure TTreeStrings.Clear; begin Owner.Clear; end; procedure TTreeStrings.Delete(Index: Integer) ; begin Owner.GetNodeFromIndex(Index) .Delete; end; procedure TTreeStrings.SetUpdateState(Updating: Boolean) ; begin SendMessage(Owner.Handle, WM_SETREDRAW, Ord(not Updating) , 0) ; if not Updating then Owner.Owner.Refresh; end; function TTreeStrings.Add(const S: string) : Integer; var Level, OldLevel, I: Integer; NewStr: string; Node: TrmTreeNode; begin Result := GetCount; if (Length(S) = 1) and (S[1] = Chr($1A) ) then Exit; Node := nil; OldLevel := 0; NewStr := GetBufStart(PChar(S) , Level) ; if Result > 0 then begin Node := Owner.GetNodeFromIndex(Result - 1) ; OldLevel := Node.Level; end; if (Level > OldLevel) or (Node = nil) then begin if Level - OldLevel > 1 then TreeViewError(sInvalidLevel) ; end else begin for I := OldLevel downto Level do begin Node := Node.Parent; if (Node = nil) and (I - Level > 0) then TreeViewError(sInvalidLevel) ; end; end; Owner.AddChild(Node, NewStr) ; end; procedure TTreeStrings.Insert(Index: Integer; const S: string) ; begin with Owner do Insert(GetNodeFromIndex(Index) , S) ; end; procedure TTreeStrings.LoadTreeFromStream(Stream: TStream) ; var List: TStringList; ANode, NextNode: TrmTreeNode; ALevel, i: Integer; CurrStr: string; begin List := TStringList.Create; Owner.BeginUpdate; try try Clear; List.LoadFromStream(Stream) ; ANode := nil; for i := 0 to List.Count - 1 do begin CurrStr := GetBufStart(PChar(List[i]) , ALevel) ; if ANode = nil then ANode := Owner.AddChild(nil, CurrStr) else if ANode.Level = ALevel then ANode := Owner.AddChild(ANode.Parent, CurrStr) else if ANode.Level = (ALevel - 1) then ANode := Owner.AddChild(ANode, CurrStr) else if ANode.Level > ALevel then begin NextNode := ANode.Parent; while NextNode.Level > ALevel do NextNode := NextNode.Parent; ANode := Owner.AddChild(NextNode.Parent, CurrStr) ; end else TreeViewErrorFmt(sInvalidLevelEx, [ALevel, CurrStr]) ; end; finally Owner.EndUpdate; List.Free; end; except Owner.Owner.Invalidate; // force repaint on exception raise; end; end; procedure TTreeStrings.SaveTreeToStream(Stream: TStream) ; const TabChar = #9; EndOfLine = #13#10; var i: Integer; ANode: TrmTreeNode; NodeStr: string; begin if Count > 0 then begin ANode := Owner[0]; while ANode <> nil do begin NodeStr := ''; for i := 0 to ANode.Level - 1 do NodeStr := NodeStr + TabChar; NodeStr := NodeStr + ANode.Text + EndOfLine; Stream.Write(Pointer(NodeStr) ^, Length(NodeStr) ) ; ANode := ANode.GetNext; end; end; end; procedure TrmTreeNodes.BinaryInsert(Path: string; Node: TrmTreeNode) ; var wHash: longint; wLen: integer; wData: TrmHashData; First, Middle, Last: longint; wFound: boolean; begin wHash := HashValue(Path) ; wLen := Length(Path) ; First := 0; Last := FHashList.count - 1; wFound := false; while (not wFound) and (first <= last) do begin middle := round((last + first) / 2) ; wData := TrmHashData(fHashlist[middle]) ; if wHash = wData.hash then wFound := true else begin if wHash < wData.hash then last := middle - 1 else first := middle + 1; end; end; if wFound then begin middle := round((last + first) / 2) ; wFound := false; while (Middle > 0) and (Middle - 1 >= First) and (TrmHashData(FHashList[middle - 1]) .Hash = wHash) do dec(Middle) ; while (not wfound) and (Middle < FHashList.Count) and (Middle + 1 < Last) and (TrmHashData(FHashList[middle + 1]) .Hash = wHash) do begin wData := TrmHashData(FHashList[middle]) ; if (Owner.NodePath(wData.Node) = Path) then wFound := true else inc(Middle) ; end; if not wFound then first := middle; end; if not wfound then begin wData := TrmHashData.create; wData.Hash := wHash; wData.IDLength := wLen; wData.Node := Node; fHashList.Insert(first, wData) ; end; end; function TrmTreeNodes.HashValue(St: string) : LongInt; begin result := GetStrCRC32(St) ; end; function TrmTreeNodes.LocateHashIndex(Path: string) : integer; var wHash: longint; wData: TrmHashData; First, Middle, Last, Temp: longint; wFound: boolean; begin wHash := HashValue(Path) ; result := -1; First := 0; Last := FHashList.count - 1; wFound := false; middle := round((last + first) / 2) ; while (not wFound) and (first <= last) do begin middle := round((last + first) / 2) ; wData := TrmHashData(fHashlist[middle]) ; if wHash = wData.hash then wFound := true else begin if wHash < wData.hash then last := middle - 1 else first := middle + 1; end; end; if wFound then begin Temp := middle; while (Middle > 0) and (Middle - 1 >= First) and (TrmHashData(FHashList[middle - 1]) .Hash = wHash) do dec(Middle) ; while (result = -1) and (Middle < FHashList.Count) and (Middle + 1 < Last) and (TrmHashData(FHashList[middle + 1]) .Hash = wHash) do begin wData := TrmHashData(FHashList[middle]) ; if (Owner.NodePath(wData.Node) = Path) then result := middle else inc(Middle) ; end; if result = -1 then result := temp; end; end; procedure TrmTreeNodes.RemoveHash(Node: TrmTreeNode) ; var wIndex: integer; begin wIndex := LocateHashIndex(Owner.NodePath(Node) ) ; if wIndex > -1 then FHashList.delete(wIndex) ; end; function TrmTreeNodes.LocateNode(Path: string) : TrmTreeNode; var wIndex: integer; begin wIndex := LocateHashIndex(Path) ; if wIndex = -1 then result := nil else result := TrmHashData(FHashList[wIndex]) .Node; end; { TrmCustomPathTreeView } constructor TrmCustomPathTreeView.Create(AOwner: TComponent) ; begin inherited Create(AOwner) ; ControlStyle := ControlStyle - [csCaptureMouse] + [csDisplayDragImage, csReflector]; Width := 121; Height := 97; TabStop := True; ParentColor := False; FCanvas := TControlCanvas.Create; TControlCanvas(FCanvas) .Control := Self; FTreeNodes := TrmTreeNodes.Create(Self) ; FBorderStyle := bsSingle; FShowButtons := True; FShowRoot := True; FShowLines := True; FHideSelection := True; FDragImage := TDragImageList.CreateSize(32, 32) ; FSaveIndent := -1; FChangeTimer := TTimer.Create(Self) ; FChangeTimer.Enabled := False; FChangeTimer.Interval := 0; FChangeTimer.OnTimer := OnChangeTimer; FToolTips := True; {$ifdef D6_or_higher} FEditInstance := Classes.MakeObjectInstance(EditWndProc) ; {$else} FEditInstance := MakeObjectInstance(EditWndProc) ; {$endif} FImageChangeLink := TChangeLink.Create; FImageChangeLink.OnChange := ImageListChange; FStateChangeLink := TChangeLink.Create; FStateChangeLink.OnChange := ImageListChange; { Version 5.01: DesignInfo is used here to store information necessary for deleting font handles allocated in CustomDraw routines. Fields can't be added now since class signatures must not be modified in a minor version. This will be removed in the next major version } if not (csDesigning in ComponentState) then DesignInfo := Integer(New(PFontHandles) ) ; FSepChar := '/'; end; destructor TrmCustomPathTreeView.Destroy; begin Try SetNewHint(nil) ; except //Do Nothing... end; FreeAndNil(FTreeNodes) ; FChangeTimer.Free; FSaveItems.Free; FDragImage.Free; FMemStream.Free; {$ifdef D6_or_higher} Classes.FreeObjectInstance(FEditInstance) ; {$else} FreeObjectInstance(FEditInstance) ; {$endif} FImageChangeLink.Free; FStateChangeLink.Free; FCanvas.Free; if not (csDesigning in ComponentState) then Dispose(PFontHandles(DesignInfo) ) ; inherited Destroy; end; procedure TrmCustomPathTreeView.CreateParams(var Params: TCreateParams) ; const BorderStyles: array[TBorderStyle] of DWORD = (0, WS_BORDER) ; LineStyles: array[Boolean] of DWORD = (0, TVS_HASLINES) ; RootStyles: array[Boolean] of DWORD = (0, TVS_LINESATROOT) ; ButtonStyles: array[Boolean] of DWORD = (0, TVS_HASBUTTONS) ; EditStyles: array[Boolean] of DWORD = (TVS_EDITLABELS, 0) ; HideSelections: array[Boolean] of DWORD = (TVS_SHOWSELALWAYS, 0) ; DragStyles: array[TDragMode] of DWORD = (TVS_DISABLEDRAGDROP, 0) ; RTLStyles: array[Boolean] of DWORD = (0, TVS_RTLREADING) ; ToolTipStyles: array[Boolean] of DWORD = (TVS_NOTOOLTIPS, 0) ; AutoExpandStyles: array[Boolean] of DWORD = (0, TVS_SINGLEEXPAND) ; HotTrackStyles: array[Boolean] of DWORD = (0, TVS_TRACKSELECT) ; RowSelectStyles: array[Boolean] of DWORD = (0, TVS_FULLROWSELECT) ; begin InitCommonControl(ICC_TREEVIEW_CLASSES) ; inherited CreateParams(Params) ; CreateSubClass(Params, WC_TREEVIEW) ; with Params do begin Style := Style or LineStyles[FShowLines] or BorderStyles[FBorderStyle] or RootStyles[FShowRoot] or ButtonStyles[FShowButtons] or EditStyles[FReadOnly] or HideSelections[FHideSelection] or DragStyles[DragMode] or RTLStyles[UseRightToLeftReading] or AutoExpandStyles[FAutoExpand] or HotTrackStyles[FHotTrack] or RowSelectStyles[FRowSelect] or TVS_NOTOOLTIPS; if Ctl3D and NewStyleControls and (FBorderStyle = bsSingle) then begin Style := Style and not WS_BORDER; ExStyle := Params.ExStyle or WS_EX_CLIENTEDGE; end; WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW) ; end; end; procedure TrmCustomPathTreeView.CreateWnd; begin FStateChanging := False; inherited CreateWnd; TreeView_SetBkColor(Handle, ColorToRGB(Color) ) ; TreeView_SetTextColor(Handle, ColorToRGB(Font.Color) ) ; if FMemStream <> nil then begin Items.ReadData(FMemStream) ; Items.ReadExpandedState(FMemStream) ; FMemStream.Destroy; FMemStream := nil; SetTopItem(Items.GetNodeFromIndex(FSaveTopIndex) ) ; FSaveTopIndex := 0; SetSelection(Items.GetNodeFromIndex(FSaveIndex) ) ; FSaveIndex := 0; end; if FSaveIndent <> -1 then Indent := FSaveIndent; if (Images <> nil) and Images.HandleAllocated then SetImageList(Images.Handle, TVSIL_NORMAL) ; if (StateImages <> nil) and StateImages.HandleAllocated then SetImageList(StateImages.Handle, TVSIL_STATE) ; end; procedure TrmCustomPathTreeView.DestroyWnd; var Node: TrmTreeNode; begin FStateChanging := True; if Items.Count > 0 then begin FMemStream := TMemoryStream.Create; Items.WriteData(FMemStream) ; Items.WriteExpandedState(FMemStream) ; FMemStream.Position := 0; Node := GetTopItem; if Node <> nil then FSaveTopIndex := Node.AbsoluteIndex; Node := Selected; if Node <> nil then FSaveIndex := Node.AbsoluteIndex; Items.BeginUpdate; try Items.Clear; finally Items.EndUpdate; end; end; FSaveIndent := Indent; inherited DestroyWnd; end; procedure TrmCustomPathTreeView.EditWndProc(var Message: TMessage) ; begin try with Message do begin case Msg of WM_KEYDOWN, WM_SYSKEYDOWN: if DoKeyDown(TWMKey(Message) ) then Exit; WM_CHAR: if DoKeyPress(TWMKey(Message) ) then Exit; WM_KEYUP, WM_SYSKEYUP: if DoKeyUp(TWMKey(Message) ) then Exit; CN_KEYDOWN, CN_CHAR, CN_SYSKEYDOWN, CN_SYSCHAR: begin WndProc(Message) ; Exit; end; end; Result := CallWindowProc(FDefEditProc, FEditHandle, Msg, WParam, LParam) ; end; except Application.HandleException(Self) ; end; end; procedure TrmCustomPathTreeView.CMColorChanged(var Message: TMessage) ; begin inherited; RecreateWnd; end; procedure TrmCustomPathTreeView.CMCtl3DChanged(var Message: TMessage) ; begin inherited; if FBorderStyle = bsSingle then RecreateWnd; end; procedure TrmCustomPathTreeView.CMFontChanged(var Message: TMessage) ; begin inherited; TreeView_SetTextColor(Handle, ColorToRGB(Font.Color) ) ; end; procedure TrmCustomPathTreeView.CMSysColorChange(var Message: TMessage) ; begin inherited; if not (csLoading in ComponentState) then begin Message.Msg := WM_SYSCOLORCHANGE; DefaultHandler(Message) ; end; end; function TrmCustomPathTreeView.AlphaSort: Boolean; var Node: TrmTreeNode; begin if HandleAllocated then begin Result := CustomSort(nil, 0) ; Node := FTreeNodes.GetFirstNode; while Node <> nil do begin if Node.HasChildren then Node.AlphaSort; Node := Node.GetNext; end; end else Result := False; end; function TrmCustomPathTreeView.CustomSort(SortProc: TTVCompare; Data: Longint) : Boolean; var SortCB: TTVSortCB; Node: TrmTreeNode; begin Result := False; if HandleAllocated then begin with SortCB do begin if not Assigned(SortProc) then lpfnCompare := @DefaultTreeViewSort else lpfnCompare := SortProc; hParent := TVI_ROOT; lParam := Data; Result := TreeView_SortChildrenCB(Handle, SortCB, 0) ; end; Node := FTreeNodes.GetFirstNode; while Node <> nil do begin if Node.HasChildren then Node.CustomSort(SortProc, Data) ; Node := Node.GetNext; end; Items.ClearCache; end; end; procedure TrmCustomPathTreeView.SetAutoExpand(Value: Boolean) ; begin if FAutoExpand <> Value then begin FAutoExpand := Value; SetComCtlStyle(Self, TVS_SINGLEEXPAND, Value) ; end; end; procedure TrmCustomPathTreeView.SetHotTrack(Value: Boolean) ; begin if FHotTrack <> Value then begin FHotTrack := Value; SetComCtlStyle(Self, TVS_TRACKSELECT, Value) ; end; end; procedure TrmCustomPathTreeView.SetRowSelect(Value: Boolean) ; begin if FRowSelect <> Value then begin FRowSelect := Value; SetComCtlStyle(Self, TVS_FULLROWSELECT, Value) ; end; end; procedure TrmCustomPathTreeView.SetToolTips(Value: Boolean) ; begin if FToolTips <> Value then FToolTips := Value; Try SetNewHint(nil) ; except //Do Nothing... end; end; procedure TrmCustomPathTreeView.SetSortType(Value: TSortType) ; begin if SortType <> Value then begin FSortType := Value; if ((SortType in [stData, stBoth]) and Assigned(OnCompare) ) or (SortType in [stText, stBoth]) then AlphaSort; end; end; procedure TrmCustomPathTreeView.SetBorderStyle(Value: TBorderStyle) ; begin if BorderStyle <> Value then begin FBorderStyle := Value; RecreateWnd; end; end; procedure TrmCustomPathTreeView.SetDragMode(Value: TDragMode) ; begin if Value <> DragMode then SetComCtlStyle(Self, TVS_DISABLEDRAGDROP, Value = dmManual) ; inherited; end; procedure TrmCustomPathTreeView.SetButtonStyle(Value: Boolean) ; begin if ShowButtons <> Value then begin FShowButtons := Value; SetComCtlStyle(Self, TVS_HASBUTTONS, Value) ; end; end; procedure TrmCustomPathTreeView.SetLineStyle(Value: Boolean) ; begin if ShowLines <> Value then begin FShowLines := Value; SetComCtlStyle(Self, TVS_HASLINES, Value) ; end; end; procedure TrmCustomPathTreeView.SetRootStyle(Value: Boolean) ; begin if ShowRoot <> Value then begin FShowRoot := Value; SetComCtlStyle(Self, TVS_LINESATROOT, Value) ; end; end; procedure TrmCustomPathTreeView.SetReadOnly(Value: Boolean) ; begin if ReadOnly <> Value then begin FReadOnly := Value; SetComCtlStyle(Self, TVS_EDITLABELS, not Value) ; end; end; procedure TrmCustomPathTreeView.SetHideSelection(Value: Boolean) ; begin if HideSelection <> Value then begin FHideSelection := Value; SetComCtlStyle(Self, TVS_SHOWSELALWAYS, not Value) ; Invalidate; end; end; function TrmCustomPathTreeView.GetNodeAt(X, Y: Integer) : TrmTreeNode; var HitTest: TTVHitTestInfo; begin with HitTest do begin pt.X := X; pt.Y := Y; if TreeView_HitTest(Handle, HitTest) <> nil then Result := Items.GetNode(HitTest.hItem) else Result := nil; end; end; function TrmCustomPathTreeView.GetHitTestInfoAt(X, Y: Integer) : THitTests; var HitTest: TTVHitTestInfo; begin Result := []; with HitTest do begin pt.X := X; pt.Y := Y; TreeView_HitTest(Handle, HitTest) ; if (flags and TVHT_ABOVE) <> 0 then Include(Result, htAbove) ; if (flags and TVHT_BELOW) <> 0 then Include(Result, htBelow) ; if (flags and TVHT_NOWHERE) <> 0 then Include(Result, htNowhere) ; if (flags and TVHT_ONITEM) = TVHT_ONITEM then Include(Result, htOnItem) else begin if (flags and TVHT_ONITEM) <> 0 then Include(Result, htOnItem) ; if (flags and TVHT_ONITEMICON) <> 0 then Include(Result, htOnIcon) ; if (flags and TVHT_ONITEMLABEL) <> 0 then Include(Result, htOnLabel) ; if (flags and TVHT_ONITEMSTATEICON) <> 0 then Include(Result, htOnStateIcon) ; end; if (flags and TVHT_ONITEMBUTTON) <> 0 then Include(Result, htOnButton) ; if (flags and TVHT_ONITEMINDENT) <> 0 then Include(Result, htOnIndent) ; if (flags and TVHT_ONITEMRIGHT) <> 0 then Include(Result, htOnRight) ; if (flags and TVHT_TOLEFT) <> 0 then Include(Result, htToLeft) ; if (flags and TVHT_TORIGHT) <> 0 then Include(Result, htToRight) ; end; end; procedure TrmCustomPathTreeView.SetrmTreeNodes(Value: TrmTreeNodes) ; begin Items.Assign(Value) ; end; procedure TrmCustomPathTreeView.SetIndent(Value: Integer) ; begin if Value <> Indent then TreeView_SetIndent(Handle, Value) ; end; function TrmCustomPathTreeView.GetIndent: Integer; begin Result := TreeView_GetIndent(Handle) end; procedure TrmCustomPathTreeView.FullExpand; var Node: TrmTreeNode; begin Node := Items.GetFirstNode; while Node <> nil do begin Node.Expand(True) ; Node := Node.GetNextSibling; end; end; procedure TrmCustomPathTreeView.FullCollapse; var Node: TrmTreeNode; begin Node := Items.GetFirstNode; while Node <> nil do begin Node.Collapse(True) ; Node := Node.GetNextSibling; end; end; procedure TrmCustomPathTreeView.Loaded; begin inherited Loaded; if csDesigning in ComponentState then FullExpand; end; function TrmCustomPathTreeView.GetTopItem: TrmTreeNode; begin if HandleAllocated then Result := Items.GetNode(TreeView_GetFirstVisible(Handle) ) else Result := nil; end; procedure TrmCustomPathTreeView.SetTopItem(Value: TrmTreeNode) ; begin if HandleAllocated and (Value <> nil) then TreeView_SelectSetFirstVisible(Handle, Value.ItemId) ; end; procedure TrmCustomPathTreeView.OnChangeTimer(Sender: TObject) ; begin FChangeTimer.Enabled := False; Change(TrmTreeNode(FChangeTimer.Tag) ) ; end; function TrmCustomPathTreeView.GetSelection: TrmTreeNode; begin if HandleAllocated then begin if FRightClickSelect and Assigned(FRClickNode) then Result := FRClickNode else Result := Items.GetNode(TreeView_GetSelection(Handle) ) ; end else Result := nil; end; procedure TrmCustomPathTreeView.SetSelection(Value: TrmTreeNode) ; begin if Value <> nil then Value.Selected := True else TreeView_SelectItem(Handle, nil) ; end; procedure TrmCustomPathTreeView.SetChangeDelay(Value: Integer) ; begin FChangeTimer.Interval := Value; end; function TrmCustomPathTreeView.GetChangeDelay: Integer; begin Result := FChangeTimer.Interval; end; function TrmCustomPathTreeView.GetDropTarget: TrmTreeNode; begin if HandleAllocated then begin Result := Items.GetNode(TreeView_GetDropHilite(Handle) ) ; if Result = nil then Result := FLastDropTarget; end else Result := nil; end; procedure TrmCustomPathTreeView.SetDropTarget(Value: TrmTreeNode) ; begin if HandleAllocated then if Value <> nil then Value.DropTarget := True else TreeView_SelectDropTarget(Handle, nil) ; end; function TrmCustomPathTreeView.GetNodeFromItem(const Item: TTVItem) : TrmTreeNode; begin Result := nil; if Items <> nil then with Item do if (state and TVIF_PARAM) <> 0 then Result := Pointer(lParam) else Result := Items.GetNode(hItem) ; end; function TrmCustomPathTreeView.IsEditing: Boolean; var ControlHand: HWnd; begin ControlHand := TreeView_GetEditControl(Handle) ; Result := (ControlHand <> 0) and IsWindowVisible(ControlHand) ; end; procedure TrmCustomPathTreeView.CNNotify(var Message: TWMNotify) ; var Node: TrmTreeNode; MousePos: TPoint; R: TRect; DefaultDraw, PaintImages: Boolean; TmpItem: TTVItem; LogFont: TLogFont; begin with Message do case NMHdr^.code of NM_CUSTOMDRAW: with PNMCustomDraw(NMHdr) ^ do begin FCanvas.Lock; try Result := CDRF_DODEFAULT; if (dwDrawStage and CDDS_ITEM) = 0 then begin R := ClientRect; case dwDrawStage of CDDS_PREPAINT: begin if IsCustomDrawn(dtControl, cdPrePaint) then begin try FCanvas.Handle := hdc; FCanvas.Font := Font; FCanvas.Brush := Brush; DefaultDraw := CustomDraw(R, cdPrePaint) ; finally FCanvas.Handle := 0; end; if not DefaultDraw then begin Result := CDRF_SKIPDEFAULT; Exit; end; end; if IsCustomDrawn(dtItem, cdPrePaint) or IsCustomDrawn(dtItem, cdPreErase) then Result := Result or CDRF_NOTIFYITEMDRAW; if IsCustomDrawn(dtItem, cdPostPaint) then Result := Result or CDRF_NOTIFYPOSTPAINT; if IsCustomDrawn(dtItem, cdPostErase) then Result := Result or CDRF_NOTIFYPOSTERASE; end; CDDS_POSTPAINT: if IsCustomDrawn(dtControl, cdPostPaint) then CustomDraw(R, cdPostPaint) ; CDDS_PREERASE: if IsCustomDrawn(dtControl, cdPreErase) then CustomDraw(R, cdPreErase) ; CDDS_POSTERASE: if IsCustomDrawn(dtControl, cdPostErase) then CustomDraw(R, cdPostErase) ; end; end else begin FillChar(TmpItem, SizeOf(TmpItem) , 0) ; TmpItem.hItem := HTREEITEM(dwItemSpec) ; Node := GetNodeFromItem(TmpItem) ; if Node = nil then Exit; case dwDrawStage of CDDS_ITEMPREPAINT: begin //release the font we may have loaned during item drawing. if (dwDrawStage and CDDS_ITEMPOSTPAINT <> 0) and (PFontHandles(DesignInfo) .OurFont + PFontHandles(DesignInfo) .StockFont <> 0) then begin SelectObject(hdc, PFontHandles(DesignInfo) .StockFont) ; DeleteObject(PFontHandles(DesignInfo) .OurFont) ; PFontHandles(DesignInfo) .OurFont := 0; PFontHandles(DesignInfo) .StockFont := 0; end; try FCanvas.Handle := hdc; FCanvas.Font := Font; FCanvas.Brush := Brush; { Unlike the list view, the tree view doesn't override the text foreground and background colors of selected items. } if uItemState and CDIS_SELECTED <> 0 then begin FCanvas.Font.Color := clHighlightText; FCanvas.Brush.Color := clHighlight; end; FCanvas.Font.OnChange := CanvasChanged; FCanvas.Brush.OnChange := CanvasChanged; FCanvasChanged := False; DefaultDraw := CustomDrawItem(Node, TCustomDrawState(Word(uItemState) ) , cdPrePaint, PaintImages) ; if not PaintImages then Result := Result or TVCDRF_NOIMAGES; if not DefaultDraw then Result := Result or CDRF_SKIPDEFAULT else if FCanvasChanged then begin FCanvasChanged := False; FCanvas.Font.OnChange := nil; FCanvas.Brush.OnChange := nil; with PNMTVCustomDraw(NMHdr) ^ do begin clrText := ColorToRGB(FCanvas.Font.Color) ; clrTextBk := ColorToRGB(FCanvas.Brush.Color) ; if GetObject(FCanvas.Font.Handle, SizeOf(LogFont) , @LogFont) <> 0 then begin FCanvas.Handle := 0; // disconnect from hdc // don't delete the stock font PFontHandles(DesignInfo) .OurFont := CreateFontIndirect(LogFont) ; PFontHandles(DesignInfo) .StockFont := SelectObject(hdc, PFontHandles(DesignInfo) .OurFont) ; Result := Result or CDRF_NEWFONT; end; end; end; if IsCustomDrawn(dtItem, cdPostPaint) then Result := Result or CDRF_NOTIFYPOSTPAINT; finally FCanvas.Handle := 0; end; end; CDDS_ITEMPOSTPAINT: if IsCustomDrawn(dtItem, cdPostPaint) then CustomDrawItem(Node, TCustomDrawState(Word(uItemState) ) , cdPostPaint, PaintImages) ; CDDS_ITEMPREERASE: if IsCustomDrawn(dtItem, cdPreErase) then CustomDrawItem(Node, TCustomDrawState(Word(uItemState) ) , cdPreErase, PaintImages) ; CDDS_ITEMPOSTERASE: if IsCustomDrawn(dtItem, cdPostErase) then CustomDrawItem(Node, TCustomDrawState(Word(uItemState) ) , cdPostErase, PaintImages) ; end; end; finally FCanvas.Unlock; end; end; TVN_BEGINDRAG: begin FDragged := True; with PNMTreeView(NMHdr) ^ do FDragNode := GetNodeFromItem(ItemNew) ; end; TVN_BEGINLABELEDIT: begin Try SetNewHint(nil) ; except //Do Nothing... end; with PTVDispInfo(NMHdr) ^ do if Dragging or not CanEdit(GetNodeFromItem(item) ) then Result := 1; if Result = 0 then begin FEditHandle := TreeView_GetEditControl(Handle) ; FDefEditProc := Pointer(GetWindowLong(FEditHandle, GWL_WNDPROC) ) ; SetWindowLong(FEditHandle, GWL_WNDPROC, LongInt(FEditInstance) ) ; end; end; TVN_ENDLABELEDIT: Edit(PTVDispInfo(NMHdr) ^.item) ; TVN_ITEMEXPANDING: if not FManualNotify then begin with PNMTreeView(NMHdr) ^ do begin Node := GetNodeFromItem(ItemNew) ; if (action = TVE_EXPAND) and not CanExpand(Node) then Result := 1 else if (action = TVE_COLLAPSE) and not CanCollapse(Node) then Result := 1; end; end; TVN_ITEMEXPANDED: if not FManualNotify then begin with PNMTreeView(NMHdr) ^ do begin Node := GetNodeFromItem(itemNew) ; if (action = TVE_EXPAND) then Expand(Node) else if (action = TVE_COLLAPSE) then Collapse(Node) ; end; end; TVN_SELCHANGINGA, TVN_SELCHANGINGW: if not CanChange(GetNodeFromItem(PNMTreeView(NMHdr) ^.itemNew) ) then Result := 1; TVN_SELCHANGEDA, TVN_SELCHANGEDW: with PNMTreeView(NMHdr) ^ do if FChangeTimer.Interval > 0 then with FChangeTimer do begin Enabled := False; Tag := Integer(GetNodeFromItem(itemNew) ) ; Enabled := True; end else Change(GetNodeFromItem(itemNew) ) ; TVN_DELETEITEM: begin Node := GetNodeFromItem(PNMTreeView(NMHdr) ^.itemOld) ; if Node <> nil then begin Node.FItemId := nil; FChangeTimer.Enabled := False; if FStateChanging then Node.Delete else Items.Delete(Node) ; end; end; TVN_SETDISPINFO: with PTVDispInfo(NMHdr) ^ do begin Node := GetNodeFromItem(item) ; if (Node <> nil) and ((item.mask and TVIF_TEXT) <> 0) then Node.Text := item.pszText; end; TVN_GETDISPINFO: with PTVDispInfo(NMHdr) ^ do begin Node := GetNodeFromItem(item) ; if Node <> nil then begin if (item.mask and TVIF_TEXT) <> 0 then StrLCopy(item.pszText, PChar(Node.Text) , item.cchTextMax) ; if (item.mask and TVIF_IMAGE) <> 0 then begin GetImageIndex(Node) ; item.iImage := Node.ImageIndex; end; if (item.mask and TVIF_SELECTEDIMAGE) <> 0 then begin GetSelectedIndex(Node) ; item.iSelectedImage := Node.SelectedIndex; end; end; end; NM_RCLICK: begin FRClickNode := nil; GetCursorPos(MousePos) ; if RightClickSelect then with PointToSmallPoint(ScreenToClient(MousePos) ) do begin FRClickNode := GetNodeAt(X, Y) ; Perform(WM_CONTEXTMENU, Handle, Integer(PointToSmallPoint(MousePos) ) ) ; FRClickNode := nil; end else // Win95/98 eat WM_CONTEXTMENU when posted to the message queue PostMessage(Handle, CN_BASE + WM_CONTEXTMENU, Handle, Integer(PointToSmallPoint(MousePos) ) ) ; Message.Result := 1; // tell treeview not to perform default response end; end; end; function TrmCustomPathTreeView.GetDragImages: TDragImageList; begin if FDragImage.Count > 0 then Result := FDragImage else Result := nil; end; procedure TrmCustomPathTreeView.WndProc(var Message: TMessage) ; begin if not (csDesigning in ComponentState) and ((Message.Msg = WM_LBUTTONDOWN) or (Message.Msg = WM_LBUTTONDBLCLK) ) and not Dragging and (DragMode = dmAutomatic) and (DragKind = dkDrag) then begin if not IsControlMouseMsg(TWMMouse(Message) ) then begin ControlState := ControlState + [csLButtonDown]; Dispatch(Message) ; end; end else if Message.Msg = CN_BASE + WM_CONTEXTMENU then Message.Result := Perform(WM_CONTEXTMENU, Message.WParam, Message.LParam) else inherited WndProc(Message) ; end; procedure TrmCustomPathTreeView.DoStartDrag(var DragObject: TDragObject) ; var ImageHandle: HImageList; DragNode: TrmTreeNode; P: TPoint; begin inherited DoStartDrag(DragObject) ; DragNode := FDragNode; FLastDropTarget := nil; FDragNode := nil; if DragNode = nil then begin GetCursorPos(P) ; with ScreenToClient(P) do DragNode := GetNodeAt(X, Y) ; end; if DragNode <> nil then begin ImageHandle := TreeView_CreateDragImage(Handle, DragNode.ItemId) ; if ImageHandle <> 0 then with FDragImage do begin Handle := ImageHandle; SetDragImage(0, 2, 2) ; end; end; end; procedure TrmCustomPathTreeView.DoEndDrag(Target: TObject; X, Y: Integer) ; begin inherited DoEndDrag(Target, X, Y) ; FLastDropTarget := nil; end; procedure TrmCustomPathTreeView.CMDrag(var Message: TCMDrag) ; begin inherited; with Message, DragRec^ do case DragMessage of dmDragMove: with ScreenToClient(Pos) do DoDragOver(Source, X, Y, Message.Result <> 0) ; dmDragLeave: begin TDragObject(Source) .HideDragImage; FLastDropTarget := DropTarget; DropTarget := nil; TDragObject(Source) .ShowDragImage; end; dmDragDrop: FLastDropTarget := nil; end; end; procedure TrmCustomPathTreeView.DoDragOver(Source: TDragObject; X, Y: Integer; CanDrop: Boolean) ; var Node: TrmTreeNode; begin Node := GetNodeAt(X, Y) ; if (Node <> nil) and ((Node <> DropTarget) or (Node = FLastDropTarget) ) then begin FLastDropTarget := nil; TDragObject(Source) .HideDragImage; Node.DropTarget := True; TDragObject(Source) .ShowDragImage; end; end; procedure TrmCustomPathTreeView.GetImageIndex(Node: TrmTreeNode) ; begin if Assigned(FOnGetImageIndex) then FOnGetImageIndex(Self, Node) ; end; procedure TrmCustomPathTreeView.GetSelectedIndex(Node: TrmTreeNode) ; begin if Assigned(FOnGetSelectedIndex) then FOnGetSelectedIndex(Self, Node) ; end; function TrmCustomPathTreeView.CanChange(Node: TrmTreeNode) : Boolean; begin Result := True; if Assigned(FOnChanging) then FOnChanging(Self, Node, Result) ; end; procedure TrmCustomPathTreeView.Change(Node: TrmTreeNode) ; begin if Assigned(FOnChange) then FOnChange(Self, Node) ; end; procedure TrmCustomPathTreeView.Delete(Node: TrmTreeNode) ; begin if Assigned(FOnDeletion) then FOnDeletion(Self, Node) ; end; procedure TrmCustomPathTreeView.Expand(Node: TrmTreeNode) ; begin if Assigned(FOnExpanded) then FOnExpanded(Self, Node) ; end; function TrmCustomPathTreeView.CanExpand(Node: TrmTreeNode) : Boolean; begin Result := True; if Assigned(FOnExpanding) then FOnExpanding(Self, Node, Result) ; end; procedure TrmCustomPathTreeView.Collapse(Node: TrmTreeNode) ; begin if Assigned(FOnCollapsed) then FOnCollapsed(Self, Node) ; end; function TrmCustomPathTreeView.CanCollapse(Node: TrmTreeNode) : Boolean; begin Result := True; if Assigned(FOnCollapsing) then FOnCollapsing(Self, Node, Result) ; end; function TrmCustomPathTreeView.CanEdit(Node: TrmTreeNode) : Boolean; begin Result := True; if Assigned(FOnEditing) then FOnEditing(Self, Node, Result) ; end; procedure TrmCustomPathTreeView.Edit(const Item: TTVItem) ; var S: string; Node: TrmTreeNode; begin with Item do if pszText <> nil then begin S := pszText; Node := GetNodeFromItem(Item) ; if Assigned(FOnEdited) then FOnEdited(Self, Node, S) ; if Node <> nil then Node.Text := S; end; end; function TrmCustomPathTreeView.CreateNode: TrmTreeNode; begin Result := TrmTreeNode.Create(Items) ; end; procedure TrmCustomPathTreeView.SetImageList(Value: HImageList; Flags: Integer) ; begin if HandleAllocated then TreeView_SetImageList(Handle, Value, Flags) ; end; procedure TrmCustomPathTreeView.ImageListChange(Sender: TObject) ; var ImageHandle: HImageList; begin if HandleAllocated then begin if TCustomImageList(Sender) .HandleAllocated then ImageHandle := TCustomImageList(Sender) .Handle else ImageHandle := 0; if Sender = Images then SetImageList(ImageHandle, TVSIL_NORMAL) else if Sender = StateImages then SetImageList(ImageHandle, TVSIL_STATE) ; end; end; procedure TrmCustomPathTreeView.Notification(AComponent: TComponent; Operation: TOperation) ; begin inherited Notification(AComponent, Operation) ; if Operation = opRemove then begin if AComponent = Images then Images := nil; if AComponent = StateImages then StateImages := nil; end; end; procedure TrmCustomPathTreeView.SetImages(Value: TCustomImageList) ; begin if Images <> nil then Images.UnRegisterChanges(FImageChangeLink) ; FImages := Value; if Images <> nil then begin Images.RegisterChanges(FImageChangeLink) ; Images.FreeNotification(Self) ; SetImageList(Images.Handle, TVSIL_NORMAL) end else SetImageList(0, TVSIL_NORMAL) ; end; procedure TrmCustomPathTreeView.SetStateImages(Value: TCustomImageList) ; begin if StateImages <> nil then StateImages.UnRegisterChanges(FStateChangeLink) ; FStateImages := Value; if StateImages <> nil then begin StateImages.RegisterChanges(FStateChangeLink) ; StateImages.FreeNotification(Self) ; SetImageList(StateImages.Handle, TVSIL_STATE) end else SetImageList(0, TVSIL_STATE) ; end; procedure TrmCustomPathTreeView.LoadFromFile(const FileName: string) ; var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead) ; try LoadFromStream(Stream) ; finally Stream.Free; end; end; procedure TrmCustomPathTreeView.LoadFromStream(Stream: TStream) ; begin with TTreeStrings.Create(Items) do try LoadTreeFromStream(Stream) ; finally Free; end; end; procedure TrmCustomPathTreeView.SaveToFile(const FileName: string) ; var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate) ; try SaveToStream(Stream) ; finally Stream.Free; end; end; procedure TrmCustomPathTreeView.SaveToStream(Stream: TStream) ; begin with TTreeStrings.Create(Items) do try SaveTreeToStream(Stream) ; finally Free; end; end; procedure TrmCustomPathTreeView.WMContextMenu(var Message: TWMContextMenu) ; var R: TRect; begin if (Message.XPos < 0) and (Selected <> nil) then begin R := Selected.DisplayRect(True) ; Message.Pos := PointToSmallPoint(ClientToScreen(Point(R.Left, R.Bottom) ) ) ; end; inherited; end; procedure TrmCustomPathTreeView.WMLButtonDown(var Message: TWMLButtonDown) ; var Node: TrmTreeNode; MousePos: TPoint; begin FDragged := False; FDragNode := nil; try inherited; if (DragMode = dmAutomatic) and (DragKind = dkDrag) then begin SetFocus; if not FDragged then begin GetCursorPos(MousePos) ; with PointToSmallPoint(ScreenToClient(MousePos) ) do Perform(WM_LBUTTONUP, 0, MakeLong(X, Y) ) ; end else begin Node := GetNodeAt(Message.XPos, Message.YPos) ; if Node <> nil then begin Node.Focused := True; Node.Selected := True; BeginDrag(False) ; end; end; end; finally FDragNode := nil; end; end; procedure TrmCustomPathTreeView.WMNotify(var Message: TWMNotify) ; var Node: TrmTreeNode; MaxTextLen: Integer; Pt: TPoint; begin with Message do if NMHdr^.code = TTN_NEEDTEXTW then begin // Work around NT COMCTL32 problem with tool tips >= 80 characters GetCursorPos(Pt) ; Pt := ScreenToClient(Pt) ; Node := GetNodeAt(Pt.X, Pt.Y) ; if (Node = nil) or (Node.Text = '') or (PToolTipTextW(NMHdr) ^.uFlags and TTF_IDISHWND = 0) then Exit; if (GetComCtlVersion >= ComCtlVersionIE4) and (Length(Node.Text) < 80) then begin inherited; Exit; end; FWideText := Node.Text; MaxTextLen := SizeOf(PToolTipTextW(NMHdr) ^.szText) div SizeOf(WideChar) ; if Length(FWideText) >= MaxTextLen then SetLength(FWideText, MaxTextLen - 1) ; PToolTipTextW(NMHdr) ^.lpszText := PWideChar(FWideText) ; FillChar(PToolTipTextW(NMHdr) ^.szText, MaxTextLen, 0) ; Move(Pointer(FWideText) ^, PToolTipTextW(NMHdr) ^.szText, Length(FWideText) * SizeOf(WideChar) ) ; PToolTipTextW(NMHdr) ^.hInst := 0; SetWindowPos(NMHdr^.hwndFrom, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE or SWP_NOSIZE or SWP_NOMOVE or SWP_NOOWNERZORDER) ; Result := 1; end else inherited; end; { CustomDraw support } procedure TrmCustomPathTreeView.CanvasChanged; begin FCanvasChanged := True; end; function TrmCustomPathTreeView.IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage) : Boolean; begin { Tree view doesn't support erase notifications } if Stage = cdPrePaint then begin if Target = dtItem then Result := Assigned(FOnCustomDrawItem) or Assigned(FOnAdvancedCustomDrawItem) else if Target = dtControl then Result := Assigned(FOnCustomDraw) or Assigned(FOnAdvancedCustomDraw) or Assigned(FOnCustomDrawItem) or Assigned(FOnAdvancedCustomDrawItem) else Result := False; end else begin if Target = dtItem then Result := Assigned(FOnAdvancedCustomDrawItem) else if Target = dtControl then Result := Assigned(FOnAdvancedCustomDraw) or Assigned(FOnAdvancedCustomDrawItem) else Result := False; end; end; function TrmCustomPathTreeView.CustomDraw(const ARect: TRect; Stage: TCustomDrawStage) : Boolean; begin Result := True; if (Stage = cdPrePaint) and Assigned(FOnCustomDraw) then FOnCustomDraw(Self, ARect, Result) ; if Assigned(FOnAdvancedCustomDraw) then FOnAdvancedCustomDraw(Self, ARect, Stage, Result) ; end; function TrmCustomPathTreeView.CustomDrawItem(Node: TrmTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages: Boolean) : Boolean; begin Result := True; PaintImages := True; if (Stage = cdPrePaint) and Assigned(FOnCustomDrawItem) then FOnCustomDrawItem(Self, Node, State, Result) ; if Assigned(FOnAdvancedCustomDrawItem) then FOnAdvancedCustomDrawItem(Self, Node, State, Stage, PaintImages, Result) ; end; function TrmCustomPathTreeView.ParentName(s: string) : string; var wLen: integer; begin wLen := length(s) ; if (wlen > 0) and (s[wLen] = SepChar) then begin system.Delete(s, wLen, 1) ; dec(wLen) ; end; while (wlen > 0) and (s[wLen] <> sepchar) do begin system.Delete(s, wLen, 1) ; dec(wLen) ; end; if (wlen > 0) and (s[wLen] = SepChar) then system.Delete(s, wLen, 1) ; result := s; end; function TrmCustomPathTreeView.ChildName(s: string) : string; var wLen: integer; begin wLen := length(s) ; if (wlen > 0) and (s[wLen] = SepChar) then begin system.Delete(s, wLen, 1) ; dec(wLen) ; end; while (wlen > 0) and (s[wLen] <> sepchar) do dec(wLen) ; system.delete(s, 1, wLen) ; result := s; end; function TrmCustomPathTreeView.AddPathNode(Node: TrmTreeNode; Path: string) : TrmTreeNode; var wNode, wParent, wChild: TrmTreeNode; wPName, wCName: string; begin result := nil; if path = '' then exit; if pos(sepchar, path) <> 1 then path := sepchar+path; wNode := Items.LocateNode(Path) ; if wNode = nil then begin wPName := ParentName(Path) ; wCName := ChildName(Path) ; wParent := Items.LocateNode(wPName) ; if wParent = nil then wParent := AddPathNode(nil, wPname) ; wChild := Items.AddChild(wParent, wCName) ; if assigned(OnGetImageIndex) then OnGetImageIndex(self, wChild); result := wChild; end else result := wNode; end; function TrmCustomPathTreeView.FindPathNode(Path: string) : TrmTreeNode; begin result := Items.LocateNode(Path) ; end; function TrmCustomPathTreeView.NodePath(Node: TrmTreeNode) : string; var Temp: string; begin Temp := ''; while Node <> nil do begin Temp := FSepChar + Node.Text + Temp; Node := Node.Parent; end; Result := Temp; end; procedure TrmCustomPathTreeView.SetNewHint(Node: TrmTreeNode) ; var wRect: TRect; begin if FToolTips and assigned(Node) then begin if assigned(fHint) and (Node.text = fHint.Caption) then exit else begin fHint.free; fHint := nil; end; wRect := Node.DisplayRect(true) ; if (wRect.Right > Self.Width) then begin wRect.TopLeft := Self.ClientToScreen(wRect.TopLeft) ; wRect.BottomRight := Self.ClientToScreen(wRect.BottomRight) ; if not assigned(fHint) then fHint := TrmHintWindow.Create(nil) ; fHint.Color := clInfoBk; fHint.Font.Assign(self.font) ; fHint.ActivateHint(wRect, Node.Text) ; end; end else begin fHint.free; fHint := nil; end; end; function TrmCustomPathTreeView.GetFocussedNode: TrmTreeNode; begin if HandleAllocated then Result := Items.GetNode(TreeView_GetSelection(Handle) ) else Result := nil; end; procedure TrmCustomPathTreeView.SetFocussedNode(const Value: TrmTreeNode) ; begin Selected := Value; // ie: use SetSelection end; procedure TrmCustomPathTreeView.CMCancelMode(var Message: TMessage) ; begin Try SetNewHint(nil) ; except //Do Nothing... end; inherited; end; procedure TrmCustomPathTreeView.CMMouseLeave(var Message: TMessage) ; begin Try SetNewHint(nil) ; except //Do Nothing... end; inherited; end; procedure TrmCustomPathTreeView.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer) ; var N: TrmTreeNode; begin if (Button = mbRight) and (RightClickSelect) then begin N := GetNodeAt(X, Y) ; if N <> nil then Selected := N; end; inherited; end; procedure TrmCustomPathTreeView.MouseMove(Shift: TShiftState; X, Y: Integer) ; begin Try if (Application.Active) and (htOnItem in GetHitTestInfoAt(X, y) ) then SetNewHint(GetNodeAt(x, y) ) else SetNewHint(nil) ; except //Do Nothing... end; inherited; end; initialization RegisterClass(TrmNodeInfo) ; end.
{------------------------------------------------------------------------------- Copyright 2012 Ethea S.r.l. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------} unit Kitto.Config; {$I Kitto.Defines.inc} interface uses SysUtils, Types, Generics.Collections, EF.Tree, EF.Macros, EF.Classes, EF.DB, EF.ObserverIntf, Kitto.Metadata.Models, Kitto.Metadata.Views, Kitto.Auth, Kitto.AccessControl; type TKConfigMacroExpander = class; TKConfig = class; TKConfigClass = class of TKConfig; TKGetConfig = reference to function: TKConfig; TKConfigGetAppNameEvent = procedure (out AAppName: string) of object; TKConfig = class(TEFComponent) strict private type TPathURL = record Path: string; URL: string; constructor Create(const APath, AURL: string); end; class var FAppHomePath: string; FJSFormatSettings: TFormatSettings; FBaseConfigFileName: string; FOnGetInstance: TKGetConfig; FInstance: TKConfig; FResourcePathsURLs: TList<TPathURL>; FSystemHomePath: string; FConfigClass: TKConfigClass; FOnGetAppName: TKConfigGetAppNameEvent; FUseAltLanguage: Boolean; var FDBConnections: TDictionary<string, TEFDBConnection>; FMacroExpansionEngine: TEFMacroExpansionEngine; FModels: TKModels; FViews: TKViews; FAuthenticator: TKAuthenticator; FAC: TKAccessController; FUserFormatSettings: TFormatSettings; class function GetInstance: TKConfig; static; class function GetAppName: string; static; class procedure SetupResourcePathsURLs; class function GetAppHomeURL: string; static; class function GetAppHomePath: string; static; class procedure SetAppHomePath(const AValue: string); static; class function GetSystemHomePath: string; static; class procedure SetSystemHomePath(const AValue: string); static; class function GetDatabase: TEFDBConnection; static; function GetDBConnectionNames: TStringDynArray; function GetMultiFieldSeparator: string; function GetAC: TKAccessController; function GetDBConnection(const ADatabaseName: string): TEFDBConnection; function GetAuthenticator: TKAuthenticator; function GetDBAdapter(const ADatabaseName: string): TEFDBAdapter; function GetMacroExpansionEngine: TEFMacroExpansionEngine; function GetAppTitle: string; function GetAppIcon: string; function GetModels: TKModels; function GetViews: TKViews; procedure FinalizeDBConnections; function GetDefaultDatabaseName: string; function GetDatabaseName: string; function GetLanguagePerSession: Boolean; function GetFOPEnginePath: string; class function AdaptImageName(const AResourceName: string; const ASuffix: string = ''): string; function GetDefaultDBConnection: TEFDBConnection; strict protected function GetUploadPath: string; function GetUploadURL: string; function GetConfigFileName: string; override; class function FindSystemHomePath: string; public class procedure DestroyInstance; procedure AfterConstruction; override; destructor Destroy; override; class constructor Create; class destructor Destroy; procedure UpdateObserver(const ASubject: IEFSubject; const AContext: string = ''); override; public class procedure SetConfigClass(const AValue: TKConfigClass); class property AppName: string read GetAppName; class property OnGetAppName: TKConfigGetAppNameEvent read FOnGetAppName write FOnGetAppName; class property UseAltLanguage: Boolean read FUseAltLanguage write FUseAltLanguage; /// <summary> /// <para>Returns or changes the Application Home path.</para> /// <para>The Application Home path defaults to the exe file directory /// unless specified through the '-home' command line argument.</para> /// <para>Setting this property, if necessary, should be done at /// application startup, preferably in a unit's initialization /// section.</para> /// </summary> /// <remarks>Changing this property affects all TKConfg instances created /// from that point on, not existing instances.</remarks> class property AppHomePath: string read GetAppHomePath write SetAppHomePath; /// <summary> /// <para>Returns or changes the System Home path, which is used to find /// any resources that are not found in the Application Home path. /// Generally, the System Home path contains all predefined metadata and /// resources of the framework.</para> /// <para>The System Home path defaults to a "Home" directory inside a /// nearby directory named "Kitto". The following paths, relative to the /// executable directory, are searched in order:</para> /// <list type="number"> /// <item>..\Externals\Kitto\Home</item> /// <item>..\..\Externals\Kitto\Home</item> /// <item>..\..\..\Home</item> /// <item>%KITTO%\Home</item> /// </list> /// <para>The first existing path is used. If none of these exist, the /// value of AppHomePath is assumed.</para> /// <para>If no default is suitable for your application, you can set /// this property at application startup, preferably in a unit's /// initialization section. If you also need to set AppHomePath, do it /// <b>before</b> setting this property.</para> /// </summary> /// <remarks>Changing this property affects all TKConfg instances created /// from that point on, not existing instances.</remarks> class property SystemHomePath: string read GetSystemHomePath write SetSystemHomePath; /// <summary> /// Returns the full path of the Metadata directory inside the home path. /// </summary> class function GetMetadataPath: string; /// <summary> /// Format settings for Javascript/JSON data encoded in text format. use /// it, don't change it. /// </summary> class property JSFormatSettings: TFormatSettings read FJSFormatSettings; /// <summary> /// Name of the config file. Defaults to Config.yaml. Changing this /// property only affects instances created afterwards. /// </summary> class property BaseConfigFileName: string read FBaseConfigFileName write FBaseConfigFileName; /// <summary> /// Sets a global function that returns the global config object. In web /// applications there will be a config object per session. /// </summary> class property OnGetInstance: TKGetConfig read FOnGetInstance write FOnGetInstance; /// <summary> /// Returns a singleton instance. /// </summary> class property Instance: TKConfig read GetInstance; /// <summary> /// Returns the database instance. /// </summary> class property Database: TEFDBConnection read GetDatabase; /// <summary> /// Returns the URL of the Application /// </summary> class property AppHomeURL: string read GetAppHomeURL; /// <summary> /// Returns the URL for the specified resource, based on the first /// existing file in the ordered list of resource folders. If no existing /// file is found, an exception is raised. /// </summary> /// <param name="AResourceFileName"> /// Resource file name relative to the resource folder. Examples: /// some_image.png, js\some_library.js. /// </param> function GetResourceURL(const AResourceFileName: string): string; /// <summary>Returns the URL for the specified resource, based on the first /// existing file in the ordered list of resource folders. If no existing /// file is found, returns ''.</summary> /// <param name="AResourceFileName">Resource file name relative to the /// resource folder. Examples: some_image.png, js\some_library.js.</param> function FindResourceURL(const AResourceFileName: string): string; /// <summary> /// Returns the full pathname for the specified resource, based on /// the first existing file in the ordered list of resource folders. If no /// existing file is found, returns ''. /// </summary> /// <param name="AResourceFileName"> /// Resource file name relative to the resource folder. /// Examples: some_image.png, js\some_library.js. /// </param> function FindResourcePathName(const AResourceFileName: string): string; /// <summary> /// Returns the full pathname for the specified resource, based on the first /// existing file in the ordered list of resource folders. If no existing /// file is found, an exception is raised. /// </summary> /// <param name="AResourceFileName"> /// Resource file name relative to the resource folder. Examples: /// some_image.png, js\some_library.js. /// </param> function GetResourcePathName(const AResourceFileName: string): string; function FindImagePath(const AResourceName: string; const ASuffix: string = ''): string; function FindImageURL(const AResourceName: string; const ASuffix: string = ''): string; function GetImageURL(const AResourceName: string; const ASuffix: string = ''): string; /// <summary>Returns informations about Help support for the application: /// AHRef, AHrefStyle, AHrefCaption.</summary> procedure GetHelpSupport(out AShowLink: Boolean; out AHRef, AHrefStyle, AShortText, ALongText: string); /// <summary>A reference to the model catalog, opened on first /// access.</summary> property Models: TKModels read GetModels; /// <summary>A reference to the model catalog, opened on first /// access.</summary> property Views: TKViews read GetViews; /// <summary>Makes sure catalogs are recreated upon next access.</summary> procedure InvalidateCatalogs; /// <summary>Returns the Home URL of the Kitto application (lowercase of AppName)</summary> function GetHomeURL: string; /// <summary>Gives access to a database connection by name, created on /// demand.</summary> property DBConnections[const AName: string]: TEFDBConnection read GetDBConnection; /// <summary>Returns the names of all defined database /// connections.</summary> property DBConnectionNames: TStringDynArray read GetDBConnectionNames; /// <summary>Default DatabaseName to use when not specified elsewhere. Can /// be set through the DatabaseRouter/DatabaseName node or through the /// DefaultDatabaseName node.</summary> property DatabaseName: string read GetDatabaseName; /// <summary> /// Returns a reference to the default database connection, if any. /// </summary> property DefaultDBConnection: TEFDBConnection read GetDefaultDBConnection; /// <summary>Returns the application title, to be used for captions, about /// boxes, etc.</summary> property AppTitle: string read GetAppTitle; /// <summary>Returns the application Icon, to be used mobile apps /// and Browser</summary> property AppIcon: string read GetAppIcon; /// <summary> /// Global expansion engine. Kitto-specific macro expanders should be /// added here at run time. This engine is chained to the default engine, /// so all default EF macros are supported. /// </summary> property MacroExpansionEngine: TEFMacroExpansionEngine read GetMacroExpansionEngine; /// <summary>Access to the current authenticator.</summary> property Authenticator: TKAuthenticator read GetAuthenticator; /// <summary>The current Access Controller.</summary> property AC: TKAccessController read GetAC; /// <summary>Calls AC.GetAccessGrantValue passing the current user and /// returns the result.</summary> function GetAccessGrantValue(const AACURI, AMode: string; const ADefaultValue: Variant): Variant; virtual; /// <summary>Shortcut for GetAccessGrantValue for Boolean /// values. Returns True if a value is granted and it equals /// ACV_TRUE.</summary> function IsAccessGranted(const AACURI, AMode: string): Boolean; /// <summary>Calls IsAccessGranted and raises an "access denied" exception /// if the return value is not True.</summary> procedure CheckAccessGranted(const AResourceURI, AMode: string); property UserFormatSettings: TFormatSettings read FUserFormatSettings; property MultiFieldSeparator: string read GetMultiFieldSeparator; property LanguagePerSession: Boolean read GetLanguagePerSession; /// <summary> /// <para>Returns or changes the home path for FOP engine.</para> /// </summary> property FOPEnginePath: string read GetFOPEnginePath; /// <summary> /// <para>Returns or changes the Upload path accessible via %UPLOAD_PATH% macro.</para> /// </summary> property UploadPath: string read GetUploadPath; /// <summary> /// Returns the URL of the UploadPath /// </summary> property UploadURL: string read GetUploadURL; end; /// <summary> /// <para> /// A macro expander that can expand globally available macros. /// </para> /// <para> /// %HOME_PATH% = TKConfig.Instance.GetAppHomePath. /// </para> /// <para> /// It also expands any macros in the Config namespace to the /// corresponding environment config string. Example: /// </para> /// <para> /// %Config:AppTitle% = The string value of the AppTitle node in /// Config.yaml. /// </para> /// </summary> TKConfigMacroExpander = class(TEFTreeMacroExpander) strict private FConfig: TKConfig; strict protected property Config: TKConfig read FConfig; procedure InternalExpand(var AString: string); override; public constructor Create(const AConfig: TKConfig); reintroduce; end; implementation uses StrUtils, Variants, EF.SysUtils, EF.StrUtils, EF.YAML, EF.Localization, Kitto.Types, Kitto.DatabaseRouter; procedure TKConfig.AfterConstruction; begin inherited; { TODO : read default user format settings from config and allow to change them on a per-user basis. } FUserFormatSettings := GetFormatSettings; FUserFormatSettings.ShortTimeFormat := Config.GetString('UserFormats/Time', FUserFormatSettings.ShortTimeFormat); if Pos('.', FUserFormatSettings.ShortTimeFormat) > 0 then FUserFormatSettings.TimeSeparator := '.' else FUserFormatSettings.TimeSeparator := ':'; FUserFormatSettings.ShortDateFormat := Config.GetString('UserFormats/Date', FUserFormatSettings.ShortDateFormat); if Pos('.', FUserFormatSettings.ShortDateFormat) > 0 then FUserFormatSettings.DateSeparator := '.' else if Pos('-', FUserFormatSettings.ShortDateFormat) > 0 then FUserFormatSettings.DateSeparator := '-' else FUserFormatSettings.DateSeparator := '/'; FDBConnections := TDictionary<string, TEFDBConnection>.Create; end; destructor TKConfig.Destroy; begin inherited; FreeAndNil(FViews); FreeAndNil(FModels); if Assigned(FAuthenticator) then FMacroExpansionEngine.RemoveExpander(FAuthenticator.MacroExpander); FreeAndNil(FAuthenticator); FreeAndNil(FAC); FinalizeDBConnections; FreeAndNil(FMacroExpansionEngine); end; class procedure TKConfig.SetupResourcePathsURLs; var LPath: string; function PathInList(const APath: string): Boolean; var LPathURL: TPathURL; begin Result := False; for LPathURL in FResourcePathsURLs do if SameText(LPathURL.Path, APath) then Exit(True); end; begin FResourcePathsURLs.Clear; //Path delle risorse mappate sulla "virtual-directory" di Apache //eg. /MyApp/ LPath := GetAppHomePath + 'Resources'; if DirectoryExists(LPath) then FResourcePathsURLs.Add(TPathURL.Create(IncludeTrailingPathDelimiter(LPath), '/' + GetAppName + '/')); //Path delle risorse di Kitto mappate sulla "virtual-directory" di Apache //eg. /MyApp-kitto/ LPath := FindSystemHomePath + 'Resources'; if DirectoryExists(LPath) and not PathInList(IncludeTrailingPathDelimiter(LPath)) then FResourcePathsURLs.Add(TPathURL.Create(IncludeTrailingPathDelimiter(LPath), '/' + GetAppName + '-Kitto/')); end; procedure TKConfig.UpdateObserver(const ASubject: IEFSubject; const AContext: string); begin inherited; NotifyObservers(AContext); end; procedure TKConfig.FinalizeDBConnections; var LDBConnection: TEFDBConnection; begin for LDBConnection in FDBConnections.Values do LDBConnection.Free; FreeAndNil(FDBConnections); end; procedure TKConfig.InvalidateCatalogs; begin FreeAndNil(FViews); FreeAndNil(FModels); end; function TKConfig.IsAccessGranted(const AACURI, AMode: string): Boolean; begin Result := GetAccessGrantValue(AACURI, AMode, Null) = ACV_TRUE; end; function TKConfig.GetDBConnection(const ADatabaseName: string): TEFDBConnection; var LConfig: TEFNode; begin if not FDBConnections.ContainsKey(ADatabaseName) then begin Result := GetDBAdapter(ADatabaseName).CreateDBConnection; Result.Config.AddChild(TEFNode.Clone(Config.GetNode('Databases/' + ADatabaseName + '/Connection'))); LConfig := Config.FindNode('Databases/' + ADatabaseName + '/Config'); if Assigned(LConfig) then Result.Config.AddChild(TEFNode.Clone(LConfig)); FDBConnections.Add(ADatabaseName, Result); end else Result := FDBConnections[ADatabaseName]; end; function TKConfig.GetDBConnectionNames: TStringDynArray; var LNode: TEFNode; begin LNode := Config.FindNode('Databases'); if Assigned(LNode) then Result := LNode.GetChildNames else Result := nil; end; function TKConfig.GetDatabaseName: string; var LDatabaseRouterNode: TEFNode; begin LDatabaseRouterNode := Config.FindNode('DatabaseRouter'); if Assigned(LDatabaseRouterNode) then Result := TKDatabaseRouterFactory.Instance.GetDatabaseName( LDatabaseRouterNode.AsString, Self, LDatabaseRouterNode) else Result := GetDefaultDatabaseName; end; function TKConfig.GetDefaultDatabaseName: string; begin Result := Config.GetExpandedString('DefaultDatabaseName', 'Main'); end; function TKConfig.GetDefaultDBConnection: TEFDBConnection; begin Result := DBConnections[DatabaseName]; end; function TKConfig.GetFOPEnginePath: string; begin Result := Config.GetExpandedString('FOPEnginePath'); end; procedure TKConfig.GetHelpSupport(out AShowLink: Boolean; out AHRef, AHrefStyle, AShortText, ALongText: string); begin AHRef := Config.GetExpandedString('Defaults/Help/HRef',''); AHrefStyle := Config.GetExpandedString('Defaults/Help/HrefStyle','font-size: small'); AShortText := Config.GetExpandedString('Defaults/Help/ShortText',_('Help...')); ALongText := Config.GetExpandedString('Defaults/Help/LongText',_('Help guide for "%s"...')); AShowLink := AHRef <> ''; end; function TKConfig.GetHomeURL: string; begin Result := Config.GetString('HomeUrl', LowerCase(Format('http://localhost/kitto/%s', [Self.AppName]))); end; function TKConfig.GetDBAdapter(const ADatabaseName: string): TEFDBAdapter; var LDbAdapterKey: string; begin Try LDbAdapterKey := Config.GetExpandedString('Databases/' + ADatabaseName); Result := TEFDBAdapterRegistry.Instance[LDbAdapterKey]; except raise EKError.CreateFmt(_('DB connection type "%s" for database "%s" not available'), [LDbAdapterKey, ADatabaseName]); end; end; function TKConfig.GetMacroExpansionEngine: TEFMacroExpansionEngine; begin if not Assigned(FMacroExpansionEngine) then begin FMacroExpansionEngine := TEFMacroExpansionEngine.Create; FMacroExpansionEngine.OnGetFormatSettings := function: TFormatSettings begin Result := UserFormatSettings; end; AddStandardMacroExpanders(FMacroExpansionEngine); FMacroExpansionEngine.AddExpander(TKConfigMacroExpander.Create(Self)); end; Result := FMacroExpansionEngine; end; class function TKConfig.GetMetadataPath: string; begin Result := GetAppHomePath + IncludeTrailingPathDelimiter('Metadata'); end; function TKConfig.GetModels: TKModels; begin if not Assigned(FModels) then begin FModels := TKModels.Create; FModels.AttachObserver(Self); FModels.Path := GetMetadataPath + 'Models'; FModels.Open; end; Result := FModels; end; function TKConfig.GetMultiFieldSeparator: string; begin Result := Config.GetString('MultiFieldSeparator', '~'); end; function TKConfig.FindResourcePathName(const AResourceFileName: string): string; var LPathURL: TPathURL; LPath: string; begin Result := ''; for LPathURL in FResourcePathsURLs do begin LPath := LPathURL.Path + AResourceFileName; if FileExists(LPath) then begin Result := LPath; Break; end; end; end; function TKConfig.GetResourcePathName(const AResourceFileName: string): string; begin Result := FindResourcePathName(AResourceFileName); if Result = '' then raise EKError.CreateFmt(_('Resource %s not found.'), [AResourceFileName]); end; function TKConfig.FindResourceURL(const AResourceFileName: string): string; function TryFind(const AName: string): string; var LURL: TPathURL; LPath: string; begin Result := ''; for LURL in FResourcePathsURLs do begin LPath := LURL.Path + AName; if FileExists(LPath) then begin Result := LURL.URL + ReplaceStr(AName, '\', '/'); Break; end; end; end; var LLocalizedName: string; begin if SameText(Config.GetString('LanguageId'), 'en') or SameText(Config.GetString('LanguageId'), '') then Result := TryFind(AResourceFileName) else begin LLocalizedName := ChangeFileExt(AResourceFileName, '_' + Config.GetString('LanguageId') + ExtractFileExt(AResourceFileName)); Result := TryFind(LLocalizedName); if Result = '' then Result := TryFind(AResourceFileName); end; end; function TKConfig.GetResourceURL(const AResourceFileName: string): string; begin Result := FindResourceURL(AResourceFileName); if Result = '' then raise EKError.CreateFmt(_('Resource %s not found.'), [AResourceFileName]); end; class function TKConfig.GetSystemHomePath: string; begin if FSystemHomePath <> '' then Result := FSystemHomePath else Result := FindSystemHomePath; Result := IncludeTrailingPathDelimiter(Result); end; function TKConfig.GetUploadPath: string; begin Result := Config.GetExpandedString('UploadPath'); end; function TKConfig.GetUploadURL: string; begin Result := Config.GetExpandedString('UploadURL', AppHomeURL); end; function TKConfig.GetViews: TKViews; begin if not Assigned(FViews) then begin FViews := TKViews.Create(Models); FViews.AttachObserver(Self); FViews.Layouts.AttachObserver(Self); FViews.Path := GetMetadataPath + 'Views'; FViews.Open; end; Result := FViews; end; procedure TKConfig.CheckAccessGranted(const AResourceURI, AMode: string); var LErrorMsg: string; begin if not IsAccessGranted(AResourceURI, AMode) then begin LErrorMsg := _('Access denied. The user is not allowed to perform this operation.'); {$IFDEF DEBUG} LErrorMsg := LErrorMsg + sLineBreak + Format(_('Resource URI: %s; access mode: %s.'), [AResourceURI, AMode]); {$ENDIF} raise EKAccessDeniedError.Create(LErrorMsg); end; end; class constructor TKConfig.Create; var LAppName: string; LDefaultConfig: string; begin LAppName := ChangeFileExt(ExtractFileName(ParamStr(0)),''); FConfigClass := TKConfig; LDefaultConfig := Format('Config_%s.yaml',[LAppName]); if FileExists(GetMetadataPath + LDefaultConfig) then FBaseConfigFileName := LDefaultConfig else FBaseConfigFileName := 'Config.yaml'; FResourcePathsURLs := TList<TPathURL>.Create; SetupResourcePathsURLs; FJSFormatSettings := GetFormatSettings; FJSFormatSettings.DecimalSeparator := '.'; FJSFormatSettings.ThousandSeparator := ','; FJSFormatSettings.ShortDateFormat := 'yyyy/mm/dd'; FJSFormatSettings.ShortTimeFormat := 'hh:nn:ss'; FJSFormatSettings.DateSeparator := '/'; FJSFormatSettings.TimeSeparator := ':'; TEFYAMLReader.FormatSettings := FJSFormatSettings; end; class destructor TKConfig.Destroy; begin FreeAndNil(FResourcePathsURLs); FreeAndNil(FInstance); end; function TKConfig.GetAppTitle: string; begin Result := Config.GetString('AppTitle', 'Kitto'); end; function TKConfig.GetAuthenticator: TKAuthenticator; var LType: string; LConfig: TEFNode; I: Integer; begin if not Assigned(FAuthenticator) then begin LType := Config.GetExpandedString('Auth', NODE_NULL_VALUE); FAuthenticator := TKAuthenticatorFactory.Instance.CreateObject(LType); MacroExpansionEngine.AddExpander(FAuthenticator.MacroExpander); LConfig := Config.FindNode('Auth'); if Assigned(LConfig) then for I := 0 to LConfig.ChildCount - 1 do FAuthenticator.Config.AddChild(TEFNode.Clone(LConfig.Children[I])); end; Result := FAuthenticator; end; function TKConfig.GetAC: TKAccessController; var LType: string; LConfig: TEFNode; I: Integer; begin if not Assigned(FAC) then begin LType := Config.GetExpandedString('AccessControl', NODE_NULL_VALUE); FAC := TKAccessControllerFactory.Instance.CreateObject(LType); LConfig := Config.FindNode('AccessControl'); if Assigned(LConfig) then begin for I := 0 to LConfig.ChildCount - 1 do FAC.Config.AddChild(TEFNode.Clone(LConfig.Children[I])); FAC.Init; end; end; Result := FAC; end; function TKConfig.GetConfigFileName: string; begin Result := GetMetadataPath + FBaseConfigFileName; end; function TKConfig.GetAccessGrantValue(const AACURI, AMode: string; const ADefaultValue: Variant): Variant; begin Result := AC.GetAccessGrantValue(Authenticator.UserName, AACURI, AMode, ADefaultValue); end; // Adds a .png extension to the resource name. // ASuffix, if specified, is added before the file extension. // If the image name ends with _ and a two-digit number among 16, 24, 32, and 48, // then the suffix is added before the _. class function TKConfig.AdaptImageName(const AResourceName: string; const ASuffix: string = ''): string; function HasSize(const AName: string): Boolean; begin Result := EndsStr('_16', AName) or EndsStr('_24', AName) or EndsStr('_32', AName) or EndsStr('_48', AName); end; begin Result := AResourceName; if HasSize(Result) then Insert(ASuffix, Result, Length(Result) - 2) else Result := Result + ASuffix; Result := Result + '.png'; end; function TKConfig.GetAppIcon: string; begin Result := Config.GetString('AppIcon', 'kitto_128'); end; function TKConfig.GetImageURL(const AResourceName: string; const ASuffix: string = ''): string; begin Result := GetResourceURL(AdaptImageName(AResourceName, ASuffix)); end; function TKConfig.FindImagePath(const AResourceName: string; const ASuffix: string = ''): string; begin Result := FindResourcePathName(AdaptImageName(AResourceName, ASuffix)); end; function TKConfig.FindImageURL(const AResourceName, ASuffix: string): string; begin Result := FindResourceURL(AdaptImageName(AResourceName, ASuffix)); end; class function TKConfig.GetInstance: TKConfig; begin Result := nil; if Assigned(FOnGetInstance) then Result := FOnGetInstance(); if not Assigned(Result) then begin if not Assigned(FInstance) then FInstance := FConfigClass.Create; Result := FInstance; end; end; class function TKConfig.GetDatabase: TEFDBConnection; begin Result := TKConfig.Instance.DBConnections[TKConfig.Instance.DatabaseName]; end; function TKConfig.GetLanguagePerSession: Boolean; begin Result := Config.GetBoolean('LanguagePerSession', False); end; class procedure TKConfig.SetAppHomePath(const AValue: string); begin if FAppHomePath <> AValue then begin FAppHomePath := AValue; SetupResourcePathsURLs; end; end; class procedure TKConfig.SetConfigClass(const AValue: TKConfigClass); begin FConfigClass := AValue; end; class procedure TKConfig.SetSystemHomePath(const AValue: string); begin if AValue <> SystemHomePath then begin FSystemHomePath := AValue; SetupResourcePathsURLs; end; end; class function TKConfig.GetAppName: string; begin if Assigned(FOnGetAppName) then FOnGetAppName(Result) else Result := ChangeFileExt(ExtractFileName(ParamStr(0)), ''); end; class function TKConfig.GetAppHomeURL: string; begin if FResourcePathsURLs.Count > 0 then Result := FResourcePathsURLs[0].URL else Result := ''; end; class function TKConfig.GetAppHomePath: string; begin if FAppHomePath = '' then begin FAppHomePath := GetCmdLineParamValue('home', ExtractFilePath(ParamStr(0))); if not IsAbsolutePath(FAppHomePath) then FAppHomePath := ExtractFilePath(ParamStr(0)) + FAppHomePath; end; Result := IncludeTrailingPathDelimiter(FAppHomePath); end; class function TKConfig.FindSystemHomePath: string; var LExePath: string; begin LExePath := ExtractFilePath(ParamStr(0)); Result := LExePath + '..\Externals\Kitto\Home\'; if not DirectoryExists(Result) then begin Result := LExePath + '..\..\Externals\Kitto\Home\'; if not DirectoryExists(Result) then begin Result := LExePath + '..\..\..\Home\'; if not DirectoryExists(Result) then begin Result := LExePath + '..\..\..\..\Kitto\Home\'; if not DirectoryExists(Result) then begin Result := '%KITTO%\Home\'; ExpandEnvironmentVariables(Result); if not DirectoryExists(Result) then Result := GetAppHomePath; end; end; end; end; end; class procedure TKConfig.DestroyInstance; begin FreeAndNil(FResourcePathsURLs); FreeAndNil(FInstance); end; { TKConfigMacroExpander } constructor TKConfigMacroExpander.Create(const AConfig: TKConfig); begin Assert(Assigned(AConfig)); FConfig := AConfig; FConfig.UseAltLanguage := False; inherited Create(AConfig.Config, 'Config'); end; procedure TKConfigMacroExpander.InternalExpand(var AString: string); const IMAGE_MACRO_HEAD = '%IMAGE('; MACRO_TAIL = ')%'; UPLOAD_PATH = '%UPLOAD_PATH%'; var LPosHead: Integer; LPosTail: Integer; LName: string; LURL: string; LRest: string; begin inherited InternalExpand(AString); ExpandMacros(AString, '%HOME_PATH%', TKConfig.AppHomePath); if Pos(UPLOAD_PATH, AString) > 0 then ExpandMacros(AString, UPLOAD_PATH, IncludeTrailingPathDelimiter(Config.UploadPath)); LPosHead := Pos(IMAGE_MACRO_HEAD, AString); if LPosHead > 0 then begin LPosTail := PosEx(MACRO_TAIL, AString, LPosHead + 1); if LPosTail > 0 then begin LName := Copy(AString, LPosHead + Length(IMAGE_MACRO_HEAD), LPosTail - (LPosHead + Length(IMAGE_MACRO_HEAD))); LURL := Config.GetImageURL(LName); LRest := Copy(AString, LPosTail + Length(MACRO_TAIL), MaxInt); InternalExpand(LRest); Delete(AString, LPosHead, MaxInt); Insert(LURL, AString, Length(AString) + 1); Insert(LRest, AString, Length(AString) + 1); end; end; end; { TKConfig.TResourcePathURL } constructor TKConfig.TPathURL.Create(const APath, AURL: string); begin Path := APath; URL := AURL; end; end.
unit uModCNRecv; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModApp, System.Generics.Collections, uModBarang, uModSatuan, uModDO, uModPO, uModUnit, uModSuplier, uModGudang; type TModCNRecvItem = class; TModCNRecv = class(TModApp) private FCNR_CNRDITEMS: TObjectList<TModCNRecvItem>; FCNR_DATE: TDatetime; FCNR_DESCRIPTION: Double; FCNR_DO: TModDO; FCNR_GUDANG: TModGudang; FCNR_INV_NO: string; FCNR_IS_CLAIM: Integer; FCNR_NO: string; FCNR_PO: TModPO; FCNR_PPN: Double; FCNR_PPNBM: Double; FCNR_TOTAL: Double; FCNR_TOTAL_DISC: Double; FCNR_UNT: TModUnit; function GetCNR_CNRDITEMS: TObjectList<TModCNRecvItem>; function GetCNR_TOTAL_TAX: Double; public class function GetTableName: string; override; property CNR_CNRDITEMS: TObjectList<TModCNRecvItem> read GetCNR_CNRDITEMS write FCNR_CNRDITEMS; published property CNR_DATE: TDatetime read FCNR_DATE write FCNR_DATE; property CNR_DESCRIPTION: Double read FCNR_DESCRIPTION write FCNR_DESCRIPTION; [AttributeOfForeign('DO_ID')] property CNR_DO: TModDO read FCNR_DO write FCNR_DO; property CNR_GUDANG: TModGudang read FCNR_GUDANG write FCNR_GUDANG; property CNR_INV_NO: string read FCNR_INV_NO write FCNR_INV_NO; property CNR_IS_CLAIM: Integer read FCNR_IS_CLAIM write FCNR_IS_CLAIM; [AttributeOfCode] property CNR_NO: string read FCNR_NO write FCNR_NO; [AttributeOfForeign('PO_ID')] property CNR_PO: TModPO read FCNR_PO write FCNR_PO; property CNR_PPN: Double read FCNR_PPN write FCNR_PPN; property CNR_PPNBM: Double read FCNR_PPNBM write FCNR_PPNBM; property CNR_TOTAL: Double read FCNR_TOTAL write FCNR_TOTAL; property CNR_TOTAL_DISC: Double read FCNR_TOTAL_DISC write FCNR_TOTAL_DISC; property CNR_TOTAL_TAX: Double read GetCNR_TOTAL_TAX; [AttributeOfForeign('AUT$UNIT_ID')] property CNR_UNT: TModUnit read FCNR_UNT write FCNR_UNT; end; TModCNRecvItem = class(TModApp) private FBARANG_SUPLIER: TModBarangSupplier; FBARANG: TModBarang; FCN_RECV: TModCNRecv; FCNRD_IS_CLAIM_TTF: Integer; FCNRD_IS_OUTSTANDING: Integer; FCNRD_IS_PROCESS: Integer; FPO_DETAIL: TmODPOItem; FCNRD_PPN: Double; FDISCOUNT: Double; FCNRD_PPNBM: Double; FCNRD_PPNBM_PERSEN: Double; FCNRD_PPN_PERSEN: Double; FCNRD_PRICE: Double; FCNRD_QTY: Double; FCNRD_TOTAL: Double; FCNRD_TOTAL_DISC: Double; FCNRD_UOM: TModSatuan; public class function GetTableName: string; override; published property BARANG_SUPLIER: TModBarangSupplier read FBARANG_SUPLIER write FBARANG_SUPLIER; property BARANG: TModBarang read FBARANG write FBARANG; [AttributeOfHeader] property CN_RECV: TModCNRecv read FCN_RECV write FCN_RECV; property CNRD_IS_CLAIM_TTF: Integer read FCNRD_IS_CLAIM_TTF write FCNRD_IS_CLAIM_TTF; property CNRD_IS_OUTSTANDING: Integer read FCNRD_IS_OUTSTANDING write FCNRD_IS_OUTSTANDING; property CNRD_IS_PROCESS: Integer read FCNRD_IS_PROCESS write FCNRD_IS_PROCESS; property PO_DETAIL: TmODPOItem read FPO_DETAIL write FPO_DETAIL; property CNRD_PPN: Double read FCNRD_PPN write FCNRD_PPN; property DISCOUNT: Double read FDISCOUNT write FDISCOUNT; property CNRD_PPNBM: Double read FCNRD_PPNBM write FCNRD_PPNBM; property CNRD_PPNBM_PERSEN: Double read FCNRD_PPNBM_PERSEN write FCNRD_PPNBM_PERSEN; property CNRD_PPN_PERSEN: Double read FCNRD_PPN_PERSEN write FCNRD_PPN_PERSEN; property CNRD_PRICE: Double read FCNRD_PRICE write FCNRD_PRICE; property CNRD_QTY: Double read FCNRD_QTY write FCNRD_QTY; property CNRD_TOTAL: Double read FCNRD_TOTAL write FCNRD_TOTAL; property CNRD_TOTAL_DISC: Double read FCNRD_TOTAL_DISC write FCNRD_TOTAL_DISC; [AttributeOfForeign('REF$SATUAN_ID')] property CNRD_UOM: TModSatuan read FCNRD_UOM write FCNRD_UOM; end; implementation { ********************************** TModCNRecv ********************************** } function TModCNRecv.GetCNR_CNRDITEMS: TObjectList<TModCNRecvItem>; begin if not Assigned(FCNR_CNRDITEMS) then FCNR_CNRDITEMS := TObjectList<TModCNRecvItem>.Create(); Result := FCNR_CNRDITEMS; end; function TModCNRecv.GetCNR_TOTAL_TAX: Double; begin Result := CNR_PPN + CNR_PPNBM; end; class function TModCNRecv.GetTableName: string; begin Result := 'CN_RECV'; end; class function TModCNRecvItem.GetTableName: string; begin Result := 'CN_RECV_DETIL'; end; initialization TModCNRecv.RegisterRTTI; TModCNRecvItem.RegisterRTTI; end.
unit AStar64.Common; //------------------------------------------------------------------------------ // модуль внешних определений AStar64.dll // // содержит определения, необходимые как внутри dll, // так и для определения экспортируемых функций //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface const ERROR_ASTAR_SUCCESS = 0; ERROR_ASTAR_REQUEST_TOO_SHORT_BUFFER = -1; ERROR_ASTAR_REQUEST_NOT_ASSIGNED = -2; ERROR_ASTAR_REQUEST_WRONG_VERSION = -3; ERROR_ASTAR_HAS_WRONG_FILE_VERSION = -4; ERROR_ASTAR_TIMEOUT = -5; ERROR_ASTAR_NOT_ENOUGH_MEMORY = -6; ERROR_ASTAR_FILE_NOT_FOUND = -7; ERROR_ASTAR_NO_WAY_FOUND = -8; ERROR_ASTAR_NEAR_EDGE_NOT_FOUND = -9; ERROR_UNKNOWN_ERROR = -10; ERROR_ASTAR_ZONE_FILE_WRONG_SIZE = -11; //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! запись метаданных - версия №1 //------------------------------------------------------------------------------ PMetaDataV1 = ^TMetaDataV1; TMetaDataV1 = packed record //! версия Version: Integer; // 4 //! тип дороги RoadType: Integer; // 8 //! время в пути к этому моменту RouteTime: Double; // 16 //! зоны Zones: UInt64; // 24 //! суперполе ограничений (*** на данный момент - максимальная скорость в младшем байте ***) Restrictions: UInt64; // 32 end; //------------------------------------------------------------------------------ //! прототип процедуры обратного вызова //------------------------------------------------------------------------------ TSpeedCallbackFunc = function( //! ссылка на внешние данные const AHandle: Pointer; //! ссылка на передаваемые данные const AMetaData: Pointer ): Integer; stdcall; //------------------------------------------------------------------------------ implementation end.
unit uniteTestConsigneur; interface uses TestFrameWork, SysUtils, shellapi, uniteConsigneur; type TestConsigneur = class (TTestCase) published // Teste que les succes sont enregistrés procedure testConsigner; // Teste que les erreurs sont enregistrés procedure testConsignerErreur; //Sert a tester si on peut creer le fichier Acces.log procedure testConstructeurCreerFichierAcces; //Sert a tester si on peut ouvrire/fermer le fichier Erreur.log procedure testConstructeurCreerFichierErreur; // Teste le cas où on ne peut pas créer et ouvrir un fichier procedure testConstructeurOnNePeutPasCreerUnFichier; // Teste le cas où on ne peut pas écrire dans un fichier procedure testConstructeurOnNePeutPasEcrireDansUnFichier; //Vérifie si getRepertoire retourne le bon nom de répertoire. procedure testGetRepertoireJournaux; end; implementation procedure TestConsigneur.testConsigner; var sortie : String; fichier : TextFile; unConsigneur : Consigneur; begin unConsigneur := Consigneur.create('c:\repertoireJournaux'); assignFile(fichier, 'c:\repertoireJournaux\Acces.log'); fileMode := fmOpenRead; reset(fichier); readln(fichier, sortie); checkEquals('2013-10-25 08:09:10 [Oscar Wilde] : Be warned in time, James, and remain, as I do, incomprehensible: to be great is to be misunderstood.', sortie); close(fichier); erase(fichier); end; procedure TestConsigneur.testConsignerErreur; var sortie : String; fichier : TextFile; unConsigneur : Consigneur; begin unConsigneur := Consigneur.create('c:\repertoireJournaux');; assignFile(fichier, 'c:\repertoireJournaux\Acces.log'); fileMode := fmOpenRead; reset(fichier); readln(fichier, sortie); checkEquals('2013-10-25 08:09:10 [ERREUR - Charles J. Sykes] : 640K ought to be enough for anybody', sortie); close(fichier); erase(fichier); end; procedure testConsigneur.testConstructeurCreerFichierAcces; var fichier : TextFile; unConsigneur : Consigneur; begin // Creation d'un répertoire pour contenir les fichier .log unConsigneur := Consigneur.create('c:\repertoireJournaux'); //nommer les fichier assignFile(fichier,'c:\repertoireJournaux\Acces.log'); //On verifie si le fichier existe donc si il est créé. check(fileExists('c:\repertoireJournaux\Acces.log')); //ferme le fichier en question close(fichier); unConsigneur.destroy; end; procedure testConsigneur.testConstructeurCreerFichierErreur; var fichier : TextFile; unConsigneur : Consigneur; begin unConsigneur := Consigneur.create('c:\repertoireJournaux'); assignFile(fichier,'c:\repertoireJournaux\Erreur.log'); check(fileExists('c:\repertoireJournaux\Erreur.log')); close(fichier); unConsigneur.destroy; end; procedure testConsigneur.testConstructeurOnNePeutPasCreerUnFichier; var fichier : TextFile; unConsigneur : Consigneur; begin try unConsigneur := Consigneur.create('c:\totoRina'); unConsigneur.destroy; fail('Pas d''exception lancée'); except on e:Exception do check(e.Message = 'Incapable de créer le fichier c:\totoRina\Acces.log dans le rpertoireJournaux'); end; end; // On crée le fichier (Acces.log) manuellement dans le répertoire Journaux // et on modifie manuellement aussi les perméssions on le mettons en LECTURE SEUL // et on essaie de l'ouvrire en écriture procedure testConsigneur.testConstructeurOnNePeutPasEcrireDansUnFichier; var fichier : TextFile; unConsigneur : Consigneur; begin unConsigneur := Consigneur.create('c:\journauxRO'); try //On essaie d'ouvrire le fichier Acces.log en écriture unConsigneur.destroy; fail('Pas d''exception lancée'); except on e:Exception do check(e.Message = 'Incapable d''ouvrire en écriture le fichier Acces.log dans le journauxRO'); end; end; //Vérifie si getRepertoire retourne le bon nom de répertoire. procedure testConsigneur.testGetRepertoireJournaux; var unConsigneur : Consigneur; begin unConsigneur := Consigneur.create('c:\repertoireJournaux'); check(unConsigneur.getRepertoireJournaux = 'c:\repertoireJournaux'); unConsigneur.destroy; end; initialization TestFrameWork.RegisterTest(TestConsigneur.Suite); end.
unit Demo.BubbleChart.ColorByNumbers; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_BubbleChart_ColorByNumbers = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_BubbleChart_ColorByNumbers.GenerateChart; var Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_BUBBLE_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'ID'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'X'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Y'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Temperature') ]); Chart.Data.AddRow(['', 80, 167, 120]); Chart.Data.AddRow(['', 79, 136, 130]); Chart.Data.AddRow(['', 78, 184, 50]); Chart.Data.AddRow(['', 72, 278, 230]); Chart.Data.AddRow(['', 81, 200, 210]); Chart.Data.AddRow(['', 72, 170, 100]); Chart.Data.AddRow(['', 68, 477, 80]); // Options Chart.Options.ColorAxis('colors', TcfsGChartOptions.ArrayOfStringToJS(['yellow', 'red'])); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>'); GChartsFrame.DocumentGenerate('Chart1', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_BubbleChart_ColorByNumbers); end.
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uDocumentation; {$mode objfpc}{$H+} interface uses SysUtils; type //Instance of this class is a member of TModelEntity TDocumentation = class private FDescription : string; procedure SetDescription(const Value: string); public { TODO : add SeeAlso etc here } function ShortDescription : string; property Description : string read FDescription write SetDescription; end; implementation { TDocumentation } procedure TDocumentation.SetDescription(const Value: string); var I : integer; begin { TODO : Maybe use some kind of TCommentaryParser-class to extract javadoc style tags here } I := 1; while (I<Length(Value)+1) and (Value[I] in ['*','_','/',' ',#13,#10]) do Inc(I); if I>1 then FDescription := Copy(Value,I,MAXINT) else FDescription := Value; end; function TDocumentation.ShortDescription: string; var I : integer; begin I := Pos('.',Description); if (I=0) or (I>80) then I:=80; Result := Copy(Description,1,I); end; end.
unit M_option; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, TabNotBk, StdCtrls, Buttons, FileCtrl, M_global, ExtCtrls, ColorGrd, {$IFDEF WDF32} ComCtrls, {$ENDIF} DdeMan, ShellAPI; type TOptionsDialog = class(TForm) OptionsNotebook: TTabbedNotebook; OKBtn: TBitBtn; CancelBtn: TBitBtn; OptionsTestLaunchDF: TCheckBox; OptionToolsLabel2: TLabel; ToolsOptionsInfEditor: TEdit; ToolsOptionsBrowseInfEditor: TBitBtn; ToolsOptionsLabelVOC2WAV: TLabel; ToolsOptionsVoc2Wav: TEdit; ToolsOptionsBrowseVOC2WAV: TBitBtn; ComboInstall: TDriveComboBox; DirectoryListBox1: TDirectoryListBox; LabelDFInstalled: TLabel; Panel1: TPanel; Panel2: TPanel; ComboDFCD: TDriveComboBox; OpenDialogInfEditor: TOpenDialog; OpenDialogVoc2Wav: TOpenDialog; RG_Backup: TRadioGroup; LBColors: TListBox; ColorDialog: TColorDialog; ShapeColorBack: TShape; ShapeColorFore: TShape; BitBtnColor: TBitBtn; CBSCDel: TCheckBox; CBMultiDel: TCheckBox; CBMultiUpd: TCheckBox; GroupBox1: TGroupBox; GroupBox2: TGroupBox; CBWLDel: TCheckBox; CBVXDel: TCheckBox; CBOBDel: TCheckBox; CBWallSplit: TCheckBox; GroupBox3: TGroupBox; CBMultiIns: TCheckBox; CBWallExtrude: TCheckBox; Label3: TLabel; Label4: TLabel; Label5: TLabel; BNHelp: TBitBtn; Bevel1: TBevel; MemoLabels: TMemo; MemoCmdLines: TMemo; Label6: TLabel; Label7: TLabel; Label8: TLabel; CBUsePlusVX: TCheckBox; CBSpecialsVX: TCheckBox; CBSpecialsOB: TCheckBox; CBUsePlusOBShad: TCheckBox; EDVXScale: TEdit; EDVXDimMax: TEdit; EDBigVXScale: TEdit; EDBigVXDimMax: TEdit; Label9: TLabel; Label10: TLabel; Label11: TLabel; EDOBScale: TEdit; EDOBDimMax: TEdit; EDBigOBScale: TEdit; EDBigOBDimMax: TEdit; Label12: TLabel; Label13: TLabel; Label14: TLabel; Bevel2: TBevel; Bevel3: TBevel; CBFastSCROLL: TCheckBox; CBFastDRAG: TCheckBox; BitBtnRegGOB: TBitBtn; BitBtnRegWDP: TBitBtn; BitBtnGrpStart: TBitBtn; DdeClientConv: TDdeClientConv; Image1: TImage; Image2: TImage; Image3: TImage; BitBtnRegLFD: TBitBtn; Image4: TImage; LBColors2: TListBox; BitBtnColor2: TBitBtn; ToolsOptionsLabelWAV2VOC: TLabel; ToolsOptionsWav2Voc: TEdit; ToolsOptionsBrowseWAV2VOC: TBitBtn; OpenDialogWav2Voc: TOpenDialog; CBChecksHeaders: TCheckBox; CBChecksAMW: TCheckBox; CBChecksSector: TCheckBox; CBChecksPlayer: TCheckBox; CBChecksLayering: TCheckBox; CBChecksGeneral: TCheckBox; CBChecksParsing: TCheckBox; CBChecksSCT: TCheckBox; CBChecksBM: TCheckBox; CBChecksFME: TCheckBox; CBChecksWAX: TCheckBox; CBChecks3DO: TCheckBox; CBChecksVOC: TCheckBox; GroupBox4: TGroupBox; GroupBox5: TGroupBox; GroupBox6: TGroupBox; GroupBox7: TGroupBox; Label1: TLabel; Label2: TLabel; procedure FormShow(Sender: TObject); procedure OKBtnClick(Sender: TObject); procedure LBColorsClick(Sender: TObject); procedure LBColorsDblClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure BNHelpClick(Sender: TObject); procedure ToolsOptionsBrowseInfEditorClick(Sender: TObject); procedure ToolsOptionsBrowseVOC2WAVClick(Sender: TObject); procedure BitBtnGrpStartClick(Sender: TObject); procedure BitBtnRegWDPClick(Sender: TObject); procedure BitBtnRegGOBClick(Sender: TObject); procedure BitBtnRegLFDClick(Sender: TObject); procedure LBColors2Click(Sender: TObject); procedure LBColors2DblClick(Sender: TObject); procedure ToolsOptionsBrowseWAV2VOCClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var OptionsDialog: TOptionsDialog; implementation uses Mapper; {$R *.DFM} procedure TOptionsDialog.FormShow(Sender: TObject); begin ComboInstall.Drive := DarkInst[1]; if DirectoryExists(DarkInst) then DirectoryListBox1.Directory := DarkInst else DirectoryListBox1.Directory := 'c:\'; ComboDFCD.Drive := DarkCD[1]; ToolsOptionsInfEditor.Text := INFEditor; ToolsOptionsVoc2Wav.Text := Voc2Wav; ToolsOptionsWav2Voc.Text := Wav2Voc; if FileExists(WDFUSEdir + '\WDFDATA\external.wdl') then MemoLabels.Lines.LoadFromFile(WDFUSEdir + '\WDFDATA\external.wdl') else MemoLabels.Clear; if FileExists(WDFUSEdir + '\WDFDATA\external.wdn') then MemoCmdLines.Lines.LoadFromFile(WDFUSEdir + '\WDFDATA\external.wdn') else MemoCmdLines.Clear; OptionsTestLaunchDF.Checked := TestLaunch; RG_Backup.ItemIndex := Backup_Method; LBColors.ItemIndex := 0; ShapeColorBack.Brush.Color := col_back; ShapeColorFore.Brush.Color := col_back; ShapeColorFore.Pen.Color := col_select; CBMultiDel.Checked := CONFIRMMultiDelete; CBMultiUpd.Checked := CONFIRMMultiUpdate; CBMultiIns.Checked := CONFIRMMultiInsert; CBSCDel.Checked := CONFIRMSectorDelete; CBWLDel.Checked := CONFIRMWallDelete; CBVXDel.Checked := CONFIRMVertexDelete; CBOBDel.Checked := CONFIRMObjectDelete; CBWallSplit.Checked := CONFIRMWallSplit; CBWallExtrude.Checked := CONFIRMWallExtrude; CBFastSCROLL.Checked := FastSCROLL; CBFastDRAG.Checked := FastDRAG; CBUsePlusVX.Checked := UsePlusVX; CBUsePlusOBShad.Checked := UsePlusOBShad; CBSpecialsVX.Checked := SpecialsVX; CBSpecialsOB.Checked := SpecialsOB; EDvxscale.Text := IntToStr(vx_scale); EDvxdimmax.Text := IntToStr(vx_dim_max); EDbigvxscale.Text := IntToStr(bigvx_scale); EDbigvxdimmax.Text := IntToStr(bigvx_dim_max); EDobscale.Text := IntToStr(ob_scale); EDobdimmax.Text := IntToStr(ob_dim_max); EDbigobscale.Text := IntToStr(bigob_scale); EDbigobdimmax.Text := IntToStr(bigob_dim_max); CBChecksAMW.Checked := Ini.ReadBool('CHECKS', 'AMW', TRUE); CBChecksSector.Checked := Ini.ReadBool('CHECKS', 'Sector', TRUE); CBChecksPlayer.Checked := Ini.ReadBool('CHECKS', 'Player', TRUE); CBChecksLayering.Checked := Ini.ReadBool('CHECKS', 'Layering', TRUE); CBChecksGeneral.Checked := Ini.ReadBool('CHECKS', 'General', TRUE); CBChecksParsing.Checked := Ini.ReadBool('CHECKS', 'Parsing', TRUE); CBChecksSCT.Checked := Ini.ReadBool('CHECKS', 'SCT', TRUE); CBChecksBM.Checked := Ini.ReadBool('CHECKS', 'BM', TRUE); CBChecksFME.Checked := Ini.ReadBool('CHECKS', 'FME', TRUE); CBChecksWAX.Checked := Ini.ReadBool('CHECKS', 'WAX', TRUE); CBChecks3DO.Checked := Ini.ReadBool('CHECKS', '3DO', TRUE); CBChecksVOC.Checked := Ini.ReadBool('CHECKS', 'VOC', TRUE); CBChecksHeaders.Checked := Ini.ReadBool('CHECKS', 'Headers', TRUE); end; procedure TOptionsDialog.OKBtnClick(Sender: TObject); begin DarkInst := LabelDFInstalled.Caption; DarkCD[1] := ComboDFCD.Drive; INFEditor := ToolsOptionsINFEditor.Text; Voc2Wav := ToolsOptionsVoc2Wav.Text; Wav2Voc := ToolsOptionsWav2Voc.Text; TestLaunch := OptionsTestLaunchDF.Checked; Backup_Method := RG_Backup.ItemIndex; Ini.WriteString('DARK FORCES', 'Installed', DarkInst); DarkCD := '?'; DarkCD[1] := ComboDFCD.Drive; Ini.WriteString('DARK FORCES', 'CD_Letter', DarkCD); Ini.WriteString('TOOLS', 'INF Editor', INFEditor); Ini.WriteString('TOOLS', 'VOC2WAV', Voc2Wav); Ini.WriteString('TOOLS', 'WAV2VOC', Wav2Voc); MemoLabels.Lines.SaveToFile(WDFUSEdir + '\WDFDATA\external.wdl'); MemoCmdLines.Lines.SaveToFile(WDFUSEdir + '\WDFDATA\external.wdn'); Ini.WriteBool('TESTING', 'Launch DF', TestLaunch); Ini.WriteInteger('BACKUP', 'Method', Backup_Method); Ini.WriteInteger('MAP-COLORS', 'back', col_back); Ini.WriteInteger('MAP-COLORS', 'wall_n', col_wall_n); Ini.WriteInteger('MAP-COLORS', 'wall_a', col_wall_a); Ini.WriteInteger('MAP-COLORS', 'shadow', col_shadow); Ini.WriteInteger('MAP-COLORS', 'grid', col_grid); Ini.WriteInteger('MAP-COLORS', 'select', col_select); Ini.WriteInteger('MAP-COLORS', 'multis', col_multis); Ini.WriteInteger('MAP-COLORS', 'elev', col_elev); Ini.WriteInteger('MAP-COLORS', 'trig', col_trig); Ini.WriteInteger('MAP-COLORS', 'goal', col_goal); Ini.WriteInteger('MAP-COLORS', 'secr', col_secr); Ini.WriteInteger('MAP-COLORS', 'dm_low', col_dm_low); Ini.WriteInteger('MAP-COLORS', 'dm_high', col_dm_high); Ini.WriteInteger('MAP-COLORS', 'dm_gas', col_dm_gas); Ini.WriteInteger('MAP-COLORS', '2a_water', col_2a_water); Ini.WriteInteger('MAP-COLORS', '2a_catwlk', col_2a_catwlk); Ini.WriteInteger('MAP-COLORS', 'sp_sky', col_sp_sky); Ini.WriteInteger('MAP-COLORS', 'sp_pit', col_sp_pit); CONFIRMMultiDelete := CBMultiDel.Checked; CONFIRMMultiUpdate := CBMultiUpd.Checked; CONFIRMMultiInsert := CBMultiIns.Checked; CONFIRMSectorDelete := CBSCDel.Checked; CONFIRMWallDelete := CBWLDel.Checked; CONFIRMVertexDelete := CBVXDel.Checked; CONFIRMObjectDelete := CBOBDel.Checked; CONFIRMWallSplit := CBWallSplit.Checked; CONFIRMWallExtrude := CBWallExtrude.Checked; Ini.WriteBool('CONFIRM', 'MultiDelete', CONFIRMMultiDelete); Ini.WriteBool('CONFIRM', 'MultiUpdate', CONFIRMMultiUpdate); Ini.WriteBool('CONFIRM', 'MultiInsert', CONFIRMMultiInsert); Ini.WriteBool('CONFIRM', 'SectorDelete', CONFIRMSectorDelete); Ini.WriteBool('CONFIRM', 'WallDelete', CONFIRMWallDelete); Ini.WriteBool('CONFIRM', 'VertexDelete', CONFIRMVertexDelete); Ini.WriteBool('CONFIRM', 'ObjectDelete', CONFIRMObjectDelete); Ini.WriteBool('CONFIRM', 'WallSplit', CONFIRMWallSplit); Ini.WriteBool('CONFIRM', 'WallExtrude', CONFIRMWallExtrude); FastSCROLL := CBFastSCROLL.Checked; FastDRAG := CBFastDRAG.Checked; Ini.WriteBool('FINE TUNING', 'FastScroll', FastSCROLL); Ini.WriteBool('FINE TUNING', 'FastDrag', FastDRAG); UsePlusVX := CBUsePlusVX.Checked; UsePlusOBShad := CBUsePlusOBShad.Checked; SpecialsVX := CBSpecialsVX.Checked; SpecialsOB := CBSpecialsOB.Checked; Ini.WriteBool('FINE TUNING', 'UsePlusVX', CBUsePlusVX.Checked); Ini.WriteBool('FINE TUNING', 'UsePlusOBShad', CBUsePlusOBShad.Checked); Ini.WriteBool('FINE TUNING', 'SpecialsVX', CBSpecialsVX.Checked); Ini.WriteBool('FINE TUNING', 'SpecialsOB', CBSpecialsOB.Checked); vx_scale := StrToInt(EDvxscale.Text); vx_dim_max := StrToInt(EDvxdimmax.Text); bigvx_scale := StrToInt(EDbigvxscale.Text); bigvx_dim_max := StrToInt(EDbigvxdimmax.Text); ob_scale := StrToInt(EDobscale.Text); ob_dim_max := StrToInt(EDobdimmax.Text); bigob_scale := StrToInt(EDbigobscale.Text); bigob_dim_max := StrToInt(EDbigobdimmax.Text); Ini.WriteInteger('FINE TUNING', 'vx_scale', vx_scale); Ini.WriteInteger('FINE TUNING', 'vx_dim_max', vx_dim_max); Ini.WriteInteger('FINE TUNING', 'bigvx_scale', bigvx_scale); Ini.WriteInteger('FINE TUNING', 'bigvx_dim_max', bigvx_dim_max); Ini.WriteInteger('FINE TUNING', 'ob_scale', ob_scale); Ini.WriteInteger('FINE TUNING', 'ob_dim_max', ob_dim_max); Ini.WriteInteger('FINE TUNING', 'bigob_scale', bigob_scale); Ini.WriteInteger('FINE TUNING', 'bigob_dim_max', bigob_dim_max); Ini.WriteBool('CHECKS', 'AMW', CBChecksAMW.Checked); Ini.WriteBool('CHECKS', 'Sector', CBChecksSector.Checked); Ini.WriteBool('CHECKS', 'Player', CBChecksPlayer.Checked); Ini.WriteBool('CHECKS', 'Layering', CBChecksLayering.Checked); Ini.WriteBool('CHECKS', 'General', CBChecksGeneral.Checked); Ini.WriteBool('CHECKS', 'Parsing', CBChecksParsing.Checked); Ini.WriteBool('CHECKS', 'SCT', CBChecksSCT.Checked); Ini.WriteBool('CHECKS', 'BM', CBChecksBM.Checked); Ini.WriteBool('CHECKS', 'FME', CBChecksFME.Checked); Ini.WriteBool('CHECKS', 'WAX', CBChecksWAX.Checked); Ini.WriteBool('CHECKS', '3DO', CBChecks3DO.Checked); Ini.WriteBool('CHECKS', 'VOC', CBChecksVOC.Checked); Ini.WriteBool('CHECKS', 'Headers', CBChecksHeaders.Checked); MapWindow.Map.Invalidate; end; procedure TOptionsDialog.CancelBtnClick(Sender: TObject); begin col_back := Ini.ReadInteger('MAP-COLORS', 'back', Ccol_back); col_wall_n := Ini.ReadInteger('MAP-COLORS', 'wall_n', Ccol_wall_n); col_wall_a := Ini.ReadInteger('MAP-COLORS', 'wall_a', Ccol_wall_a); col_shadow := Ini.ReadInteger('MAP-COLORS', 'shadow', Ccol_shadow); col_grid := Ini.ReadInteger('MAP-COLORS', 'grid', Ccol_grid); col_select := Ini.ReadInteger('MAP-COLORS', 'select', Ccol_select); col_multis := Ini.ReadInteger('MAP-COLORS', 'multis', Ccol_multis); col_elev := Ini.ReadInteger('MAP-COLORS', 'elev', Ccol_elev); col_trig := Ini.ReadInteger('MAP-COLORS', 'trig', Ccol_trig); col_goal := Ini.ReadInteger('MAP-COLORS', 'goal', Ccol_goal); col_secr := Ini.ReadInteger('MAP-COLORS', 'secr', Ccol_secr); MapWindow.Color := col_back; MapWindow.Map.Invalidate; end; procedure TOptionsDialog.LBColorsClick(Sender: TObject); begin CASE LBColors.ItemIndex OF 0: ShapeColorFore.Pen.Color := col_select; 1: ShapeColorFore.Pen.Color := col_multis; 2: ShapeColorFore.Pen.Color := col_wall_n; 3: ShapeColorFore.Pen.Color := col_wall_a; 4: ShapeColorFore.Pen.Color := col_shadow; 5: ShapeColorFore.Pen.Color := col_grid; 6: ShapeColorFore.Pen.Color := col_elev; 7: ShapeColorFore.Pen.Color := col_trig; 8: ShapeColorFore.Pen.Color := col_goal; 9: ShapeColorFore.Pen.Color := col_secr; ELSE ShapeColorFore.Pen.Color := col_back; END; end; procedure TOptionsDialog.LBColors2Click(Sender: TObject); begin CASE LBColors2.ItemIndex OF 0: ShapeColorFore.Brush.Color := col_back; 1: ShapeColorFore.Brush.Color := col_dm_low; 2: ShapeColorFore.Brush.Color := col_dm_high; 3: ShapeColorFore.Brush.Color := col_dm_gas; 4: ShapeColorFore.Brush.Color := col_2a_water; 5: ShapeColorFore.Brush.Color := col_2a_catwlk; 6: ShapeColorFore.Brush.Color := col_sp_sky; 7: ShapeColorFore.Brush.Color := col_sp_pit; ELSE ShapeColorFore.Brush.Color := col_back; END; end; procedure TOptionsDialog.LBColorsDblClick(Sender: TObject); var TheColor : TColor; begin CASE LBColors.ItemIndex OF 0: TheColor := col_select; 1: TheColor := col_multis; 2: TheColor := col_wall_n; 3: TheColor := col_wall_a; 4: TheColor := col_shadow; 5: TheColor := col_grid; 6: TheColor := col_elev; 7: TheColor := col_trig; 8: TheColor := col_goal; 9: TheColor := col_secr; END; ColorDialog.Color := TheColor; if ColorDialog.Execute then begin TheColor := ColorDialog.Color; CASE LBColors.ItemIndex OF 0: col_select := TheColor; 1: col_multis := TheColor; 2: col_wall_n := TheColor; 3: col_wall_a := TheColor; 4: col_shadow := TheColor; 5: col_grid := TheColor; 6: col_elev := TheColor; 7: col_trig := TheColor; 8: col_goal := TheColor; 9: col_secr := TheColor; END; ShapeColorFore.Pen.Color := TheColor; MapWindow.Map.Invalidate; end; end; procedure TOptionsDialog.LBColors2DblClick(Sender: TObject); var TheColor : TColor; begin CASE LBColors2.ItemIndex OF 0: TheColor := col_back; 1: TheColor := col_dm_low; 2: TheColor := col_dm_high; 3: TheColor := col_dm_gas; 4: TheColor := col_2a_water; 5: TheColor := col_2a_catwlk; 6: TheColor := col_sp_sky; 7: TheColor := col_sp_pit; END; ColorDialog.Color := TheColor; if ColorDialog.Execute then begin TheColor := ColorDialog.Color; CASE LBColors2.ItemIndex OF 0: begin col_back := TheColor; ShapeColorBack.Brush.Color := col_back; { MapWindow.Color := col_back; } MapWindow.PanelMapALL.Color := col_back; end; 1: col_dm_low := TheColor; 2: col_dm_high := TheColor; 3: col_dm_gas := TheColor; 4: col_2a_water := TheColor; 5: col_2a_catwlk := TheColor; 6: col_sp_sky := TheColor; 7: col_sp_pit := TheColor; END; ShapeColorFore.Brush.Color := TheColor; MapWindow.Map.Invalidate; end; end; procedure TOptionsDialog.BNHelpClick(Sender: TObject); begin {Application.HelpJump('wdfuse_help_options');} case OptionsNotebook.PageIndex of 0: Application.HelpJump('wdfuse_help_optionsdarkforces'); 1: Application.HelpJump('wdfuse_help_optionsbackupandtest'); 2: Application.HelpJump('wdfuse_help_optionsconfirmations'); 3: Application.HelpJump('wdfuse_help_optionschecks'); 4: Application.HelpJump('wdfuse_help_optionsfinetuning'); 5: Application.HelpJump('wdfuse_help_optionscolors'); 6: Application.HelpJump('wdfuse_help_optionsexternal'); 7: Application.HelpJump('wdfuse_help_optionswindows'); end; end; procedure TOptionsDialog.ToolsOptionsBrowseInfEditorClick(Sender: TObject); begin with OpenDialogInfEditor do begin Filename := INFEditor; InitialDir := ExtractFilePath(INFEditor); if Execute then ToolsOptionsInfEditor.Text := FileName; end; end; procedure TOptionsDialog.ToolsOptionsBrowseVOC2WAVClick(Sender: TObject); begin with OpenDialogVoc2Wav do begin if UpperCase(Voc2Wav) = 'VOC2WAV.PIF' then begin FileName := WDFUSEdir + '\VOC2WAV.PIF'; InitialDir := WDFUSEDir; end else begin Filename := Voc2Wav; InitialDir := ExtractFilePath(Voc2Wav); end; if Execute then ToolsOptionsVoc2Wav.Text := FileName; end; end; procedure TOptionsDialog.ToolsOptionsBrowseWAV2VOCClick(Sender: TObject); begin with OpenDialogWav2Voc do begin if UpperCase(Wav2Voc) = 'WAV2VOC.PIF' then begin FileName := WDFUSEdir + '\WAV2VOC.PIF'; InitialDir := WDFUSEDir; end else begin Filename := Wav2Voc; InitialDir := ExtractFilePath(Wav2Voc); end; if Execute then ToolsOptionsWav2Voc.Text := FileName; end; end; procedure TOptionsDialog.BitBtnGrpStartClick(Sender: TObject); var cmd : TStringList; begin cmd := TStringList.Create; cmd.Add('[DeleteGroup("WDFUSE")]'); cmd.Add('[CreateGroup("WDFUSE")]'); cmd.Add('[ShowGroup("Win DFUSE",1)]'); cmd.Add('[AddItem('+WDFUSEDir+'\wdfuse.exe,WDFUSE,'+WDFUSEDir+'\wdfuse.exe)]'); cmd.Add('[AddItem('+WDFUSEDir+'\wdfuse32.exe,WDFUSE32,'+WDFUSEDir+'\wdfuse32.exe)]'); cmd.Add('[AddItem('+WDFUSEDir+'\wdfuse.hlp,WDFUSE Help,'+WDFUSEDir+'\wdfuse.hlp)]'); cmd.Add('[AddItem('+WDFUSEDir+'\wdftutor.hlp,WDFUSE Tutorial,'+WDFUSEDir+'\wdftutor.hlp)]'); cmd.Add('[AddItem('+WDFUSEDir+'\df_specs.hlp,DARK FORCES Specs,'+WDFUSEDir+'\df_specs.hlp)]'); if DdeClientConv.OpenLink then begin DdeClientConv.ExecuteMacroLines(cmd, TRUE); DdeClientConv.CloseLink; end; cmd.Free; end; procedure TOptionsDialog.BitBtnRegWDPClick(Sender: TObject); var Key : HKey; Value : array[0..127] of char; begin if RegCreateKey(HKEY_CLASSES_ROOT, '.wdp', Key) = ERROR_SUCCESS then begin strPCopy(Value, 'wdp_auto_file'); RegSetValue(Key, '', REG_SZ, Value, StrLen(Value)); end; if RegCreateKey(HKEY_CLASSES_ROOT, '\wdp_auto_file', Key) = ERROR_SUCCESS then begin strPCopy(Value, 'WDFUSE Project Files'); RegSetValue(Key, '', REG_SZ, Value, StrLen(Value)); end; if RegCreateKey(HKEY_CLASSES_ROOT, '\wdp_auto_file\shell\open\command', Key) = ERROR_SUCCESS then begin {$IFNDEF WDF32} strPCopy(Value, WDFUSEdir + '\wdfuse.exe %1'); {$ELSE} strPCopy(Value, WDFUSEdir + '\wdfuse32.exe %1'); {$ENDIF} RegSetValue(Key, '', REG_SZ, Value, StrLen(Value)); end; end; procedure TOptionsDialog.BitBtnRegGOBClick(Sender: TObject); var Key : HKey; Value : array[0..127] of char; begin if RegCreateKey(HKEY_CLASSES_ROOT, '.gob', Key) = ERROR_SUCCESS then begin strPCopy(Value, 'gob_auto_file'); RegSetValue(Key, '', REG_SZ, Value, StrLen(Value)); end; if RegCreateKey(HKEY_CLASSES_ROOT, '\gob_auto_file', Key) = ERROR_SUCCESS then begin strPCopy(Value, 'Dark Forces GOB Files'); RegSetValue(Key, '', REG_SZ, Value, StrLen(Value)); end; if RegCreateKey(HKEY_CLASSES_ROOT, '\gob_auto_file\shell\open\command', Key) = ERROR_SUCCESS then begin {$IFNDEF WDF32} strPCopy(Value, WDFUSEdir + '\wdfuse.exe %1'); {$ELSE} strPCopy(Value, WDFUSEdir + '\wdfuse32.exe %1'); {$ENDIF} RegSetValue(Key, '', REG_SZ, Value, StrLen(Value)); end; end; procedure TOptionsDialog.BitBtnRegLFDClick(Sender: TObject); var Key : HKey; Value : array[0..127] of char; begin if RegCreateKey(HKEY_CLASSES_ROOT, '.lfd', Key) = ERROR_SUCCESS then begin strPCopy(Value, 'lfd_auto_file'); RegSetValue(Key, '', REG_SZ, Value, StrLen(Value)); end; if RegCreateKey(HKEY_CLASSES_ROOT, '\lfd_auto_file', Key) = ERROR_SUCCESS then begin strPCopy(Value, 'Dark Forces LFD Files'); RegSetValue(Key, '', REG_SZ, Value, StrLen(Value)); end; if RegCreateKey(HKEY_CLASSES_ROOT, '\lfd_auto_file\shell\open\command', Key) = ERROR_SUCCESS then begin {$IFNDEF WDF32} strPCopy(Value, WDFUSEdir + '\wdfuse.exe %1'); {$ELSE} strPCopy(Value, WDFUSEdir + '\wdfuse32.exe %1'); {$ENDIF} RegSetValue(Key, '', REG_SZ, Value, StrLen(Value)); end; end; end.
unit PromoDiscountAmountClass; interface uses PromoDiscountInterface, PromoItemClass; type TPromoDiscountAmount = class(TInterfacedObject, IPromoDiscount) public function calculatePromoDiscountFlat(arg_item: TPromoItem): Double; function calculatePromoDiscount(arg_item: TPromoItem): Double; end; implementation { TPromoDiscountAmount } function TPromoDiscountAmount.calculatePromoDiscount( arg_item: TPromoItem): Double; begin result := 0; // deal Modelx and ModelY end; function TPromoDiscountAmount.calculatePromoDiscountFlat(arg_item: TPromoItem): Double; var discount: Double; begin if ( arg_item.getDiscount > arg_item.getCustomerDiscount ) then discount := arg_Item.getDiscount else discount := arg_item.getCustomerDiscount; result := arg_item.getHighestDiscount(discount); // better item discount end; end.
unit QuickSearchMap; interface uses Windows, Classes, SysUtils, Grobal2; type // ------------------------------------------------------------------------------- // Map // ------------------------------------------------------------------------------- TQuickSearchMapHeader = packed record Width: Word; Height: Word; Title: string[15]; UpdateDate: TDateTime; Reserved: array[0..23] of Char; end; TQuickSearchMapInfo = packed record BkImg: Word; MidImg: Word; FrImg: Word; DoorIndex: Byte; //$80 (문짝), 문의 식별 인덱스 DoorOffset: Byte; //닫힌 문의 그림의 상대 위치, $80 (열림/닫힘(기본)) AniFrame: Byte; //$80(Draw Alpha) + 프래임 수 anitick: Byte; Area: Byte; //지역 정보 light: Byte; //0..1..4 광원 효과 end; TQuickMapInfo = packed record BkImg: Word; FrImg: Word; DoorIndex: Byte; //$80 (문짝), 문의 식별 인덱스 DoorOffset: Byte; //닫힌 문의 그림의 상대 위치, $80 (열림/닫힘(기본)) end; PTQuickSearchMapInfo = ^TQuickSearchMapInfo; TQuickSearchMap = class private // function loadmapinfo(mapfile: string; var Width, Height: Integer): Boolean; // procedure updatemapseg(cx, cy: Integer); //, maxsegx, maxsegy: integer); procedure updatemap(cx, cy: Integer); public MapBase: string; MapHeight, Mapwidth: Integer; MArr: array of array of TQuickMapInfo; pass: array of longword; ClientRect: TRect; OldClientRect: TRect; BlockLeft, BlockTop: Integer; //타일 좌표로 왼쪽, 꼭대기 좌표 oldleft, oldtop: Integer; oldmap: string; CurUnitX, CurUnitY: Integer; CurrentMap: string; Segmented: Boolean; SegXCount, SegYCount: Integer; // MiniMapBmp: TBitMap; constructor Create; destructor Destroy; override; procedure UpdateMapSquare(cx, cy: Integer); procedure UpdateMapPos(mx, my: Integer); procedure ReadyReload; procedure LoadMap(mapname: string; mx, my: Integer); procedure MarkCanWalk(mx, my: Integer; bowalk: Boolean); function CanMove(mx, my: Integer): Boolean; function CanFly(mx, my: Integer): Boolean; function GetDoor(mx, my: Integer): Integer; function IsDoorOpen(mx, my: Integer): Boolean; function OpenDoor(mx, my: Integer): Boolean; function CloseDoor(mx, my: Integer): Boolean; end; implementation constructor TQuickSearchMap.Create; begin inherited Create; //GetMem (MInfoArr, sizeof(TMapInfo) * LOGICALMAPUNIT * 3 * LOGICALMAPUNIT * 3); ClientRect := Rect(0, 0, 0, 0); MapBase := '.\Map\'; CurrentMap := ''; Segmented := False; SegXCount := 0; SegYCount := 0; CurUnitX := -1; CurUnitY := -1; BlockLeft := -1; BlockTop := -1; oldmap := ''; //MiniMapBmp := TBitMap.Create; end; destructor TQuickSearchMap.Destroy; begin setlength(MArr, 0, 0); setlength(pass, 0); inherited Destroy; end; {function TQuickSearchMap.loadmapinfo(mapfile: string; var Width, Height: Integer): Boolean; var flname: string; fhandle: Integer; header: TQuickSearchMapHeader; begin Result := False; flname := MapBase + mapfile; if FileExists(flname) then begin fhandle := FileOpen(flname, fmOpenRead or fmShareDenyNone); if fhandle > 0 then begin FileRead(fhandle, header, SizeOf(TQuickSearchMapHeader)); Width := header.Width; Height := header.Height; setlength(MArr, Width, Height); end; FileClose(fhandle); end; end; //segmented map 인 경우 procedure TQuickSearchMap.updatemapseg(cx, cy: Integer); //, maxsegx, maxsegy: integer); begin end;} procedure TQuickSearchMap.updatemap(cx, cy: Integer); var fhandle, i, j, aline, lx, rx, ty, by,count: Integer; header: TQuickSearchMapHeader; flname: string; TempMaar:Array of TQuickSearchMapInfo; begin Fillchar(MArr, SizeOf(MArr), 0); //Fillchar(pass, SizeOf(pass), 0); flname := MapBase + CurrentMap + '.map'; if FileExists(flname) then begin fhandle := FileOpen(flname, fmOpenRead or fmShareDenyNone); if fhandle > 0 then begin FileRead(fhandle, header, SizeOf(TQuickSearchMapHeader)); lx := 0; rx := header.Width; //rx ty := 0; by := header.Height; if lx < 0 then lx := 0; if ty < 0 then ty := 0; if by >= header.Height then by := header.Height; aline := SizeOf(TQuickSearchMapInfo) * header.Height; //SetLength(Marr,0,0); SetLength(MArr, header.Width, header.Height); SetLength(TempMaar,Header.Height); MapHeight := header.Height; Mapwidth := header.Width; for i := lx to rx - 1 do begin if (i >= 0) and (i < header.Width) then begin FileSeek(fhandle, SizeOf(TQuickSearchMapHeader) + (aline * i) + (SizeOf(TQuickSearchMapInfo) * ty), 0); Count:=(by - ty); FileRead(fhandle, TempMaar[0], SizeOf(TQuickSearchMapInfo) * (by - ty)); for j:=0 to Count-1 do begin Marr[i-lx,j].BkImg:= TempMaar[j].BkImg; Marr[i-lx,j].FrImg:= TempMaar[j].FrImg; Marr[i-lx,j].DoorIndex:= TempMaar[j].DoorIndex; Marr[i-lx,j].DoorOffset:= TempMaar[j].DoorOffset; end; end; end; SetLength(TempMaar,0); //20080728 姦렴코닸 //TempMaar := nil; FileClose(fhandle); end; end; end; procedure TQuickSearchMap.ReadyReload; begin CurUnitX := -1; CurUnitY := -1; end; //cx, cy: 중앙, Counted by unit.. procedure TQuickSearchMap.UpdateMapSquare(cx, cy: Integer); begin updatemap(cx, cy); end; procedure TQuickSearchMap.UpdateMapPos(mx, my: Integer); var cx, cy: Integer; begin cx := mx div LOGICALMAPUNIT; cy := my div LOGICALMAPUNIT; BlockLeft := 0; BlockTop := 0; UpdateMapSquare(cx, cy); oldleft := BlockLeft; oldtop := BlockTop; end; procedure TQuickSearchMap.LoadMap(mapname: string; mx, my: Integer); begin CurUnitX := -1; CurUnitY := -1; CurrentMap := mapname; Segmented := False; UpdateMapPos(mx, my); oldmap := CurrentMap; end; procedure TQuickSearchMap.MarkCanWalk(mx, my: Integer; bowalk: Boolean); begin end; function TQuickSearchMap.CanMove(mx, my: Integer): Boolean; var cx, cy: Integer; begin Result := False; cx := mx - BlockLeft; cy := my - BlockTop; // if (cx > MAXX * 3) or (cy > MAXX * 3) then // Exit; if (cx < 0) or (cy < 0) then Exit; if (cx>Mapwidth) or(Cy>MapHeight) then Exit; Result := ((MArr[cx, cy].BkImg and $8000) + (MArr[cx, cy].FrImg and $8000)) = 0; if Result then begin //문검사 if MArr[cx, cy].DoorIndex and $80 > 0 then begin //문짝이 있음 if (MArr[cx, cy].DoorOffset and $80) = 0 then Result := False; //문이 안 열렸음. end; end; end; function TQuickSearchMap.CanFly(mx, my: Integer): Boolean; var cx, cy: Integer; begin cx := mx - BlockLeft; cy := my - BlockTop; // if (cx < 0) or (cy < 0) then // Exit; Result := (MArr[cx, cy].FrImg and $8000) = 0; if Result then begin //문검사 if MArr[cx, cy].DoorIndex and $80 > 0 then begin //문짝이 있음 if (MArr[cx, cy].DoorOffset and $80) = 0 then Result := False; //문이 안 열렸음. end; end; end; function TQuickSearchMap.GetDoor(mx, my: Integer): Integer; var cx, cy: Integer; begin Result := 0; cx := mx - BlockLeft; cy := my - BlockTop; if (cx>Mapwidth) or(Cy>MapHeight) then Exit; if MArr[cx, cy].DoorIndex and $80 > 0 then begin Result := MArr[cx, cy].DoorIndex and $7F; end; end; function TQuickSearchMap.IsDoorOpen(mx, my: Integer): Boolean; var cx, cy: Integer; begin Result := False; cx := mx - BlockLeft; cy := my - BlockTop; if (cx>Mapwidth) or(Cy>MapHeight) then Exit; if MArr[cx, cy].DoorIndex and $80 > 0 then begin Result := (MArr[cx, cy].DoorOffset and $80 <> 0); end; end; function TQuickSearchMap.OpenDoor(mx, my: Integer): Boolean; var i, j, cx, cy, idx: Integer; begin Result := False; cx := mx - BlockLeft; cy := my - BlockTop; // if (cx < 0) or (cy < 0) then // Exit; if (cx>Mapwidth) or(Cy>MapHeight) then Exit; if MArr[cx, cy].DoorIndex and $80 > 0 then begin idx := MArr[cx, cy].DoorIndex and $7F; for i := cx - 10 to cx + 10 do for j := cy - 10 to cy + 10 do begin if (i > 0) and (j > 0) then if (MArr[i, j].DoorIndex and $7F) = idx then MArr[i, j].DoorOffset := MArr[i, j].DoorOffset or $80; end; end; end; function TQuickSearchMap.CloseDoor(mx, my: Integer): Boolean; var i, j, cx, cy, idx: Integer; begin Result := False; cx := mx - BlockLeft; cy := my - BlockTop; if (cx < 0) or (cy < 0) then Exit; if (cx > Mapwidth) or(Cy > MapHeight) then Exit; if MArr[cx, cy].DoorIndex and $80 > 0 then begin idx := MArr[cx, cy].DoorIndex and $7F; for i := cx - 8 to cx + 10 do for j := cy - 8 to cy + 10 do begin if (MArr[i, j].DoorIndex and $7F) = idx then MArr[i, j].DoorOffset := MArr[i, j].DoorOffset and $7F; end; end; end; end.
unit UnitSendMessageWithTimeoutThread; interface uses Winapi.Windows, System.Classes, Vcl.Forms, uLogger, uDBThread; type TSendMessageWithTimeoutThread = class(TDBThread) private { Private declarations } FhWnd: HWND; FMsg: UINT; FwParam: WPARAM; FlParam: LPARAM; protected procedure Execute; override; public constructor Create(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM); destructor Destroy; override; end; function SendMessageEx(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM) : boolean; implementation var SendMessageMessageWork: Boolean = false; SendMessageResult: Boolean = false; function SendMessageEx(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM) : boolean; var SendMessageThread: TThread; begin EventLog(':SendMessageEx()...'); while SendMessageMessageWork do Application.ProcessMessages; SendMessageMessageWork := True; SendMessageResult:= False; SendMessageThread := TSendMessageWithTimeoutThread.Create(hWnd, Msg, wParam, lParam); WaitForSingleObject(SendMessageThread.Handle, 5000); Result := SendMessageResult; end; { TSendMessageWithTimeoutThread } constructor TSendMessageWithTimeoutThread.Create( hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM); begin inherited Create(nil, False); FhWnd := HWnd; FMsg := Msg; FwParam := FwParam; FlParam := LParam; end; destructor TSendMessageWithTimeoutThread.Destroy; begin SendMessageMessageWork := False; inherited; end; procedure TSendMessageWithTimeoutThread.Execute; begin inherited; FreeOnTerminate := True; SendMessage(FhWnd, FMsg, FwParam, FlParam); SendMessageResult := True; end; end.
{ ThShape를 상속받아 도형을 구현 - RegistItem에 반드시 추가 할 것 주요 추상메소드 - PaintItem : 아이템을 캔버스에 그린다.(Paint에서 호출) - PtInItem : Pt가 도형에 포함되는지 여부 반환 } unit ThShapeItem; interface uses System.Types, System.Classes, System.UITypes, System.SysUtils, System.UIConsts, FMX.Types, ThTypes, ThItem; type TThShapeItem = class(TThItem, IItemHighlightObject, IItemSelectionObject) private procedure SetBgColor(const Value: TAlphaColor); protected procedure Paint; override; protected FBgColor: TAlphaColor; function CreateHighlighter: IItemHighlighter; override; function CreateSelection: IItemSelection; override; // Abstract method procedure PaintItem(ARect: TRectF; AFillColor: TAlphaColor); virtual; abstract; function PtInItem(Pt: TPointF): Boolean; override; abstract; function GetMinimumSize: TSizeF; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function IsContain(AChild: TThItem): Boolean; override; property BgColor: TAlphaColor read FBgColor write SetBgColor; property MinimumSize: TSizeF read GetMinimumSize; end; TThRectangle = class(TThShapeItem) protected function PtInItem(Pt: TPointF): Boolean; override; procedure PaintItem(ARect: TRectF; AFillColor: TAlphaColor); override; public procedure DrawItemAtMouse(AFrom, ATo: TPointF); override; end; TThLine = class(TThShapeItem) private function IsTopLeftToBottomRight: Boolean; function IsHorizon: Boolean; function IsVertical: Boolean; protected function CreateSelection: IItemSelection; override; function GetMinimumSize: TSizeF; override; function PtInItem(Pt: TPointF): Boolean; override; procedure PaintItem(ARect: TRectF; AFillColor: TAlphaColor); override; public function IsContain(AChild: TThItem): Boolean; override; procedure DrawItemAtMouse(AFrom, ATo: TPointF); override; end; TThCircle = class(TThShapeItem) protected function CreateSelection: IItemSelection; override; function PtInItem(Pt: TPointF): Boolean; override; procedure PaintItem(ARect: TRectF; AFillColor: TAlphaColor); override; public procedure DrawItemAtMouse(AFrom, ATo: TPointF); override; end; implementation uses System.Math, FMX.Controls, FMX.Graphics, ThConsts, ThItemFactory, ThItemHighlighter, SpotCornerUtils, ThItemSelection, DebugUtils; { TThShape } constructor TThShapeItem.Create(AOwner: TComponent); begin inherited; Width := MinimumSize.Width; Height := MinimumSize.Height; FOpacity := ItemDefaultOpacity; FBgColor := ItemShapeDefaultColor; SetAcceptsControls(False); end; destructor TThShapeItem.Destroy; begin inherited; end; function TThShapeItem.GetMinimumSize: TSizeF; var MinSize: Single; begin MinSize := ItemMinimumSize / AbsoluteScale.X; Result := PointF(MinSize, MinSize); end; function TThShapeItem.IsContain(AChild: TThItem): Boolean; begin Result := AbsoluteRect.Contains(AChild.AbsoluteRect); end; function TThShapeItem.CreateHighlighter: IItemHighlighter; var Highlighter: TThItemShadowHighlighter; begin Highlighter := TThItemShadowHighlighter.Create(Self); Highlighter.HighlightColor := ItemHighlightColor; Highlighter.HighlightSize := ItemHighlightSize; Result := Highlighter; end; function TThShapeItem.CreateSelection: IItemSelection; var Selection: TThItemSelection; begin Selection := TThItemSelection.Create(Self); {$IFDEF ON_ALLCORNER_RESIZESPOT} Selection.SetResizeSpots([scLeft, scTop, scRight, scBottom, scTopLeft, scTopRight, scBottomLeft, scBottomRight]); {$ELSE} Selection.SetResizeSpots([scTopLeft, scTopRight, scBottomLeft, scBottomRight]); {$ENDIF} Selection.OnTracking := SpotTracking; Result := Selection; end; procedure TThShapeItem.Paint; {$IFDEF DEBUG} var S: string; {$ENDIF} begin PaintItem(GetItemRect, FBgColor); {$IFDEF DEBUG} S := Format('(%s<P:%s>)Position(%f, %f)', [Name, Parent.ClassName, Position.X, Position.Y]); S := S + Format(' W, H(%f, %f)', [Width, Height]); Canvas.Fill.Color := claRed; Canvas.Font.Size := 10 / AbsoluteScale.X; Canvas.FillText(ClipRect, S, True, 1, [], TTextAlign.Center); {$ENDIF} end; procedure TThShapeItem.SetBgColor(const Value: TAlphaColor); begin if FBgColor = Value then Exit; FBgColor := Value; Repaint; end; {$REGION RECTANGLE} { TThRectangle } function TThRectangle.PtInItem(Pt: TPointF): Boolean; begin Result := False; if (AbsoluteRect.Width < ItemFocusMinimumSize) and (AbsoluteRect.Height < ItemFocusMinimumSize) then Exit; Result := PtInRect(GetItemRect, Pt); end; procedure TThRectangle.PaintItem(ARect: TRectF; AFillColor: TAlphaColor); var R: TRectF; begin R := ARect; Canvas.Stroke.Thickness := 0; Canvas.Stroke.Color := claNull; Canvas.Fill.Color := AFillColor; Canvas.FillRect(R, 0, 0, AllCorners, AbsoluteOpacity, TCornerType.Round); Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity, TCornerType.Round); end; procedure TThRectangle.DrawItemAtMouse(AFrom, ATo: TPointF); var R: TRectF; begin if Abs(AFrom.X - ATo.X) < MinimumSize.Width then ATo.X := AFrom.X + IfThen(AFrom.X > ATo.X, -1, 1) * MinimumSize.Width; if Abs(AFrom.Y - ATo.Y) < MinimumSize.Height then ATo.Y := AFrom.Y + IfThen(AFrom.Y > ATo.Y, -1, 1) * MinimumSize.Height; R := RectF(AFrom.X, AFrom.Y, ATo.X, ATo.Y); R.NormalizeRect; BoundsRect := R; end; {$ENDREGION} {$REGION LINE} { TThLine } function TThLine.CreateSelection: IItemSelection; var Selection: TThItemSelection; begin Selection := TThLineSelection.Create(Self); Selection.SetResizeSpots([scTopLeft, scBottomRight]); Selection.OnTracking := nil; Result := Selection; end; function TThLine.IsTopLeftToBottomRight: Boolean; begin Result := TItemResizeSpot(FSelection.Spots[0]).SpotCorner in [scTopLeft, scBottomRight]; end; function TThLine.IsContain(AChild: TThItem): Boolean; begin Result := False; end; function TThLine.IsHorizon: Boolean; begin Result := TItemResizeSpot(FSelection.Spots[0]).Position.Y = TItemResizeSpot(FSelection.Spots[1]).Position.Y; end; function TThLine.IsVertical: Boolean; begin Result := TItemResizeSpot(FSelection.Spots[0]).Position.X = TItemResizeSpot(FSelection.Spots[1]).Position.X; end; function TThLine.GetMinimumSize: TSizeF; var MinSize, Rad: Single; R: TRectF; begin R := TThItemSelection(FSelection).GetActiveSpotsItemRect; MinSize := ItemMinimumSize / AbsoluteScale.X; if R.Height = 0 then Result := PointF(MinSize, 0) else if R.Width = 0 then Result := PointF(0, MinSize) else begin Rad := ArcTan(R.Height / R.Width); Result.Width := Cos(Rad) * MinSize; Result.Height := Sin(Rad) * MinSize; end; end; function TThLine.PtInItem(Pt: TPointF): Boolean; var RangeD: Single; Rect: TRectF; PtX, PtY: Single; Rad: Single; BaseP: TPointF; TopP, LeftP, RightP, BottomP: TPointF; ExtendRect: TRectF; ExtendX, ExtendY: Single; Y1, Y2: Single; begin Result := False; // 나누면 모두 1이하로 계산되기때문에 곱하여 계산처리로 변경 Rect := GetItemRect; Rect.TopLeft := ScalePoint(Rect.TopLeft, AbsoluteScale.X, AbsoluteScale.Y); Rect.BottomRight := ScalePoint(Rect.BottomRight, AbsoluteScale.X, AbsoluteScale.Y); Pt := ScalePoint(Pt, AbsoluteScale.X, AbsoluteScale.Y); RangeD := (ItemLineSelectionThickness-1) / 2; if (Rect.TopLeft.Distance(Rect.BottomRight) < ItemFocusMinimumSize) then Exit; if IsHorizon then begin Rect.Height := 0; if (Pt.X >= Rect.Left) and (Pt.X <= Rect.Right) then begin Result := Abs(Pt.Y) <= RangeD; end else begin if Pt.X < Rect.Left then // Result := PtInCircle(Pt.Truncate, Rect.TopLeft.Truncate, Trunc(RangeD)) Result := TPoint.PointInCircle(Pt.Truncate, Rect.TopLeft.Truncate, Trunc(RangeD)) else Result := TPoint.PointInCircle(Pt.Truncate, Rect.BottomRight.Truncate, Trunc(RangeD)); end; end else if IsVertical then begin Rect.Width := 0; if (Pt.Y >= Rect.Top) and (Pt.Y <= Rect.Bottom) then begin Result := Abs(Pt.X) <= RangeD; end else begin if Pt.Y < Rect.Top then Result := TPoint.PointInCircle(Pt.Truncate, Rect.TopLeft.Truncate, Trunc(RangeD)) else Result := TPoint.PointInCircle(Pt.Truncate, Rect.BottomRight.Truncate, Trunc(RangeD)); end; end else begin PtX := Pt.X; PtY := IfThen(IsTopLeftToBottomRight, Pt.Y, Rect.Height - Pt.Y); // 꼭지점의 원 포함 확인 if not Result then Result := TPoint.PointInCircle(PointF(PtX, PtY).Truncate, Rect.TopLeft.Truncate, Trunc(RangeD+1)) or // 소수점 보정(+1) TPoint.PointInCircle(PointF(PtX, PtY).Truncate, Rect.BottomRight.Truncate, Trunc(RangeD+1)); if not Result then begin // 꼭지점과 직각인 사각형 포인트의 영역(ExtendRect)계산 Rad := ArcTan(Rect.Height / Rect.Width); BaseP := PointF(RangeD / Sin(Rad), RangeD / Cos(Rad)); LeftP := Rect.TopLeft + PointF(-BaseP.X, BaseP.Y); TopP := Rect.TopLeft + PointF(BaseP.X, -BaseP.Y); RightP := Rect.BottomRight + PointF(BaseP.X, -BaseP.Y); BottomP := Rect.BottomRight + PointF(-BaseP.X, BaseP.Y); // 대각선에서 범위 ExtendRect := RectF(LeftP.X, TopP.Y, RightP.X, BottomP.Y); if PtInRect(ExtendRect, PointF(PtX, PtY)) then begin ExtendX := PtX - BaseP.X; ExtendY := PtY - BaseP.Y; Result := PtInRect(RectF(LeftP.X, TopP.Y, TopP.X, LeftP.Y), PointF(PtX, PtY)) or PtInRect(RectF(BottomP.X, RightP.Y, RightP.X, BottomP.Y), PointF(PtX, PtY)); if not Result then begin Y1 := Round(Tan(Rad) * ExtendX - BaseP.Y); Y2 := Round(Tan(Rad) * ExtendX + BaseP.Y); // Result := InRange(ExtendY, Y1, Y2); Result := InRange(Round(ExtendY), Y1, Y2); end; end; end; end; end; procedure TThLine.PaintItem(ARect: TRectF; AFillColor: TAlphaColor); var P1, P2: TPointF; LineThickness: Single; begin // LineThickness := ItemLineThickness / AbsoluteScale.X; LineThickness := ItemLineThickness / CanvasZoomScaleDefault; Canvas.Stroke.Thickness := LineThickness; Canvas.Stroke.Color := AFillColor; Canvas.Stroke.Cap := TStrokeCap.Round; if IsTopLeftToBottomRight then begin P1 := ARect.TopLeft; P2 := ARect.BottomRight; end else if IsHorizon then begin P1 := PointF(ARect.Left, ARect.Top); P2 := PointF(ARect.Right, ARect.Top); end else if IsVertical then begin P1 := PointF(ARect.Left, ARect.Top); P2 := PointF(ARect.Left, ARect.Bottom); end else begin P1 := PointF(ARect.Left, ARect.Bottom); P2 := PointF(ARect.Right, ARect.Top); end; Canvas.DrawLine(P1, P2, 1); end; procedure TThLine.DrawItemAtMouse(AFrom, ATo: TPointF); var Rect: TRectF; BaseSpot, ActiveSpot: TItemResizeSpot; Min: TPointF; begin Rect := RectF(AFrom.X, AFrom.Y, ATo.X, ATo.Y); Rect.NormalizeRect; BaseSpot := TItemResizeSpot(FSelection.Spots[0]); ActiveSpot := TItemResizeSpot(FSelection.Spots[1]); BaseSpot.Position.Point := AFrom - Position.Point; ActiveSpot.Position.Point := ATo - Position.Point; Min := MinimumSize; if (AFrom.Distance(ATo) < ItemMinimumSize / AbsoluteScale.X) and ((Rect.Width < Min.X) or (Rect.Height < Min.Y)) then begin if InRange(Rect.Width, 1, Min.X - 1) then ATo.X := AFrom.X + Min.X * IfThen(AFrom.X > ATo.X, -1, 1); if InRange(Rect.Height, 1, Min.Y - 1) then ATo.Y := AFrom.Y + Min.Y * IfThen(AFrom.Y > ATo.Y, -1, 1); ActiveSpot.Position.Point := ATo - Position.Point; Rect := RectF(AFrom.X, AFrom.Y, ATo.X, ATo.Y); Rect.NormalizeRect; end; if Rect.Width < 1 then Rect.Width := 1; if Rect.Height < 1 then Rect.Height := 1; BoundsRect := Rect; if AFrom.X = ATo.X then // vertical begin BaseSpot.SpotCorner := IfThenSpotCorner(AFrom.Y > ATo.Y, scBottom, scTop); ActiveSpot.SpotCorner := IfThenSpotCorner(AFrom.Y > ATo.Y, scTop, scBottom); end else if AFrom.Y = ATo.Y then // horizon begin BaseSpot.SpotCorner := IfThenSpotCorner(AFrom.X > ATo.X, scRight, scLeft); ActiveSpot.SpotCorner := IfThenSpotCorner(AFrom.X > ATo.X, scLeft, scRight); end else begin if AFrom.X > ATo.X then ActiveSpot.SpotCorner := IfThenSpotCorner(AFrom.Y > ATo.Y, scBottomRight, scTopRight) else ActiveSpot.SpotCorner := IfThenSpotCorner(AFrom.Y > ATo.Y, scBottomLeft, scTopLeft); BaseSpot.SpotCorner := HorizonSpotCornerExchange(ActiveSpot.SpotCorner); BaseSpot.SpotCorner := VerticalSpotCornerExchange(BaseSpot.SpotCorner); end; end; {$ENDREGION} {$REGION Circle} { TThCircle } function TThCircle.CreateSelection: IItemSelection; var Selection: TThItemSelection; begin Selection := TThCircleSelection.Create(Self); {$IFDEF ON_ALLCORNER_RESIZESPOT} Selection.SetResizeSpots([scLeft, scTop, scRight, scBottom, scTopLeft, scTopRight, scBottomLeft, scBottomRight]); {$ELSE} Selection.SetResizeSpots([scLeft, scTop, scRight, scBottom]); {$ENDIF} Selection.OnTracking := SpotTracking; Result := Selection; end; procedure TThCircle.DrawItemAtMouse(AFrom, ATo: TPointF); var R: TRectF; begin if Abs(AFrom.X - ATo.X) < MinimumSize.Width then ATo.X := AFrom.X + IfThen(AFrom.X > ATo.X, -1, 1) * MinimumSize.Width; if Abs(AFrom.Y - ATo.Y) < MinimumSize.Height then ATo.Y := AFrom.Y + IfThen(AFrom.Y > ATo.Y, -1, 1) * MinimumSize.Height; R := RectF(AFrom.X, AFrom.Y, ATo.X, ATo.Y); R.NormalizeRect; BoundsRect := R; end; procedure TThCircle.PaintItem(ARect: TRectF; AFillColor: TAlphaColor); var R: TRectF; C: TCanvas; begin R := ARect; C := Canvas; C.Stroke.Thickness := 0; C.Stroke.Color := claNull; C.Fill.Color := AFillColor; C.FillEllipse(R, AbsoluteOpacity); C.DrawEllipse(R, AbsoluteOpacity); end; function TThCircle.PtInItem(Pt: TPointF): Boolean; begin Result := False; if (AbsoluteRect.Width < ItemFocusMinimumSize) and (AbsoluteRect.Height < ItemFocusMinimumSize) then Exit; if Width * Height = 0 then Exit; if (Sqr((Pt.X * 2 - Width) / Width) + Sqr((Pt.Y * 2 - Height) / Height) <= 1) then begin Result := True; end; end; {$ENDREGION} initialization RegisterItem(ItemFactoryIDRectangle, TThRectangle); RegisterItem(ItemFactoryIDLine, TThLine); RegisterItem(ItemFactoryIDCircle, TThCircle); end.
unit Backend.iPool.DM; interface uses System.SysUtils, System.JSON, System.Classes, IPPeerClient, REST.Client, REST.Authenticator.Basic, Data.Bind.Components, Data.Bind.ObjectScope, Data.User.Preferences; type TDMiPool = class(TDataModule) RESTClient1: TRESTClient; RESTRequest1: TRESTRequest; RESTResponse1: TRESTResponse; HTTPBasicAuthenticator1: THTTPBasicAuthenticator; private { Private declarations } public { Public declarations } function MakeRequest(AORQueryList: TStringList): TJSONObject; end; function DoRequestiPool(APreferences: IPreferences): TJSONObject; implementation function DoRequestiPool(APreferences: IPreferences): TJSONObject; var LDMiPool: TDMiPool; begin LDMiPool := TDMiPool.Create(nil); Result := LDMiPool.MakeRequest(APreferences.GetAllPreferences); end; {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} { TDataModule1 } function TDMiPool.MakeRequest(AORQueryList: TStringList): TJSONObject; var LURL: string; LQueryPreference: string; FlagStarted: boolean; begin LURL := 'https://sandbox-api.ipool.asideas.de/sandbox/api/search?types=article&languages=EN&limit=10&q='; FlagStarted := false; for LQueryPreference in AORQueryList do begin if FlagStarted then LURL := LURL + '%20OR%20' else FlagStarted := true; LURL := LURL + LQueryPreference; end; RESTClient1.BaseURL := LURL; RESTRequest1.Execute; Result := RESTResponse1.JSONValue as TJSONObject; end; end.
unit uSprEditDlg; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uSprQuery, StdCtrls, DB, DBClient, Mask, DBCtrls, Grids, DBGrids, ExtCtrls; type TedMode = (edBrowse, edEdit, edInsert); TControlDef = class(TObject) private FFieldName: string; //FCtrlClass: string; FIsLookup: Boolean; FKeyField: string; FListField: string; FListDSCreate: TsprDSCreateMethod; FField: TField; public property FieldName: string read FFieldName write FFieldName; //property CtrlClass: string read FCtrlClass write FCtrlClass; property IsLookup: Boolean read FIsLookup write FIsLookup; property KeyField: string read FKeyField write FKeyField; property ListField: string read FListField write FListField; property ListDSCreate: TsprDSCreateMethod read FListDSCreate write FListDSCreate; property Field: TField read FField write FField; end; TsprEditDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; ClientDataSet1: TClientDataSet; DataSource1: TDataSource; DBEdit1: TDBEdit; DBNavigator1: TDBNavigator; DBGrid1: TDBGrid; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } FDataSet: TDataSet;//TsprQuery; FControlDefs: TStringList; //procedure CreateControl( public { Public declarations } property DataSet: TDataSet {read TsprQuery } read FDataSet write FDataSet; procedure Initialize(Mode: TedMode); //procedure AddDef(AFieldName: string; AIsLookup: Boolean; AKeyField: string; AListField: string; AListDSCreate: TsprDSCreateMethod); end; var sprEditDlg: TsprEditDlg; implementation {$R *.dfm} procedure TsprEditDlg.FormCreate(Sender: TObject); begin FControlDefs := TStringList.Create; end; procedure TsprEditDlg.FormDestroy(Sender: TObject); var I: Integer; begin if Assigned(FControlDefs) then begin for I := 0 to FControlDefs.Count - 1 do FControlDefs.Objects[I].Free; FControlDefs.Clear; FreeAndNil(FControlDefs); end; end; procedure TsprEditDlg.Initialize(Mode: TedMode); var I: Integer; begin DataSource1.DataSet := FDataSet; { ClientDataSet1.FieldDefs.Assign(DataSet.FieldDefs); ClientDataSet1.CreateDataSet; ClientDataSet1.Active; if Mode = edInsert then ClientDataSet1.Insert else if Mode = edEdit then begin if DataSet.RecordCount > 0 then begin end else ClientDataSet1.Insert; end } end; { procedure TsprEditDlg.AddDef(AFieldName: string; AIsLookup: Boolean; AKeyField: string; AListField: string; AListDSCreate: TsprDSCreateMethod); var F: TField; vDef: TControlDef; vCtrl: TControl; begin if not Assigned(DataSet) then raise Exception.Create('DataSet не определен'); F := DataSet.FindField(AFieldName); if not Assigned(F) then raise Exception.Create('Не найдено поле ' + AFieldName); ClientDataSet1.FieldDefs. vDef := TControlDef.Create; vDef.FieldName := AFieldName; vDef.Field := F; if not AIsLookup then begin end else begin end; end;} procedure TsprEditDlg.Button1Click(Sender: TObject); begin FDataSet.Insert; end; end.
unit fos_firmbox_infrastructureapp; {$mode objfpc}{$H+} {$modeswitch nestedprocvars} interface uses Classes, SysUtils, FOS_TOOL_INTERFACES, FRE_DB_INTERFACE; type { TFRE_FIRMBOX_INFRASTRUCTURE_APP } TFRE_FIRMBOX_INFRASTRUCTURE_APP=class(TFRE_DB_APPLICATION) private procedure SetupApplicationStructure ; override; procedure _UpdateSitemap (const session: TFRE_DB_UserSession); protected procedure MySessionInitialize (const session: TFRE_DB_UserSession);override; procedure MySessionPromotion (const session: TFRE_DB_UserSession); override; public class procedure RegisterSystemScheme (const scheme:IFRE_DB_SCHEMEOBJECT); override; class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override; end; procedure Register_DB_Extensions; implementation procedure Register_DB_Extensions; begin GFRE_DBI.RegisterObjectClassEx(TFRE_FIRMBOX_INFRASTRUCTURE_APP); end; { TFRE_FIRMBOX_INFRASTRUCTURE_APP } procedure TFRE_FIRMBOX_INFRASTRUCTURE_APP.SetupApplicationStructure; begin inherited SetupApplicationStructure; end; procedure TFRE_FIRMBOX_INFRASTRUCTURE_APP._UpdateSitemap( const session: TFRE_DB_UserSession); var SiteMapData : IFRE_DB_Object; conn : IFRE_DB_CONNECTION; i : integer; //INFRA -> COMPUTER/GERÄTEVERWALTUNG | AP'S L2 (LANCOM | UBNT)  | NETZWERK | INFRASTRUKTUR | SWITCH PORTSECURITY | ASSETS | VPN begin conn:=session.GetDBConnection; SiteMapData := GFRE_DBI.NewObject; FREDB_SiteMap_AddRadialEntry(SiteMapData,'Infrastructure','Infrastructure','images_apps/firmbox_infrastructure/infrastructure_white.svg','',0,conn.SYS.CheckClassRight4MyDomain(sr_FETCH,TFRE_FIRMBOX_INFRASTRUCTURE_APP)); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Infrastructure/Computer','Devices','images_apps/firmbox_infrastructure/computer_white.svg','',0,false); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Infrastructure/AP','Wifi','images_apps/firmbox_infrastructure/wireless_white.svg','',0,false); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Infrastructure/Network','Network','images_apps/firmbox_infrastructure/network_white.svg','',0,false); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Infrastructure/VPN','VPN','images_apps/firmbox_infrastructure/house_white.svg','',0,false); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Infrastructure/Portsecurity','Portsecurity','images_apps/firmbox_infrastructure/security_white.svg','',0,false); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Infrastructure/Assets','Assets','images_apps/firmbox_infrastructure/handheld_white.svg','',0,false); FREDB_SiteMap_RadialAutoposition(SiteMapData); Session.GetSessionAppData(ClassName).Field('SITEMAP').AsObject := SiteMapData; end; procedure TFRE_FIRMBOX_INFRASTRUCTURE_APP.MySessionInitialize( const session: TFRE_DB_UserSession); begin inherited MySessionInitialize(session); if session.IsInteractiveSession then begin _UpdateSitemap(session); end; end; procedure TFRE_FIRMBOX_INFRASTRUCTURE_APP.MySessionPromotion( const session: TFRE_DB_UserSession); begin inherited MySessionPromotion(session); if session.IsInteractiveSession then _UpdateSitemap(session); end; class procedure TFRE_FIRMBOX_INFRASTRUCTURE_APP.RegisterSystemScheme( const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_APPLICATION'); end; class procedure TFRE_FIRMBOX_INFRASTRUCTURE_APP.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); begin newVersionId:='1.0'; if (currentVersionId='') then begin CreateAppText(conn,'caption','Infrastructure','Infrastructure','Infrastructure'); currentVersionId:='1.0'; end; end; end. end.
unit Unserializer; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, ComCtrls, Dialogs, ExtCtrls, Utils; type TSerializedArray = class; TSerialized = class(TObject) private FSerialized: string; FDataType: Char; FIntegerData: Integer; FDoubleData: Double; FStringData: string; FBooleanData: Boolean; FArrayData: TSerializedArray; private function ParseIntegerData(const Data: string; var Len: Integer): Boolean; function ParseDoubleData(const Data: string; var Len: Integer): Boolean; function ParseStringData(const Data: string; var Len: Integer): Boolean; function ParseBooleanData(const Data: string; var Len: Integer): Boolean; function ParseArrayData(const Data: string; var Len: Integer): Boolean; function GetArrayValue(const Key: string): TSerialized; public constructor Create; destructor Destroy; override; public function ArrayParse(var Serialized: string): Boolean; function Parse(const Serialized: string): Boolean; function FillTreeView(const TreeView: TTreeView; const Parent: TTreeNode = nil): Boolean; function DataAsString: string; public property Serialized: string read FSerialized; property DataType: Char read FDataType; public property IntegerData: Integer read FIntegerData; property DoubleData: Double read FDoubleData; property StringData: string read FStringData; property BooleanData: Boolean read FBooleanData; property ArrayData: TSerializedArray read FArrayData; property ArrayValues[const Key: string]: TSerialized read GetArrayValue; default; end; TSerializedArray = class(TObject) private FSerialized: string; FItems: Classes.TStrings; private function GetCount: Integer; function GetValue(const Key: string): TSerialized; public constructor Create; destructor Destroy; override; public procedure Clear; function IndexOf(const Key: string): Integer; function Parse(const Serialized: string): Boolean; function ParseLength(const Serialized: string): Integer; public property Serialized: string read FSerialized; property Count: Integer read GetCount; property Items: Classes.TStrings read FItems; property Values[const Key: string]: TSerialized read GetValue; default; end; procedure RunUnserializeTests; implementation const ERROR_MESSAGE: string = 'ERROR: ClassName=%s Method=%s Serialized=%s'; procedure RunUnserializeTests; var Msg: TSerialized; S: string; Passed: Boolean; FileName: string; begin Passed := True; Msg := TSerialized.Create; (*S := 'a:3:{s:6:"server";s:12:"irc.sylnt.us";s:9:"microtime";d:1428721291.088635;s:4:"nick";s:4:"exec";}'; if Msg.Parse(S) then begin if Msg.ArrayData.Count <> 3 then Passed := False; if Msg.ArrayData['server'] = nil then Passed := False else if Msg.ArrayData['server'].StringData <> 'irc.sylnt.us' then Passed := False; end else Passed := False; S := 'a:0:{}'; if Msg.Parse(S) then begin if Msg.ArrayData.Count <> 0 then Passed := False; end else Passed := False; S := 'a:1:{s:4:"type";a:1:{s:7:"process";i:10;}}'; if Msg.Parse(S) then begin if Msg.ArrayData.Count <> 1 then Passed := False; end else begin ShowMessage('Test failed: ' + Msg.Serialized); Passed := False; end; S := 'a:2:{s:3:"foo";a:0:{}s:3:"bar";i:3;}'; if Msg.Parse(S) then begin if Msg.ArrayData.Count <> 2 then Passed := False; end else begin ShowMessage('Test failed: ' + Msg.Serialized); Passed := False; end; S := 'a:1:{s:3:"foo";b:1;}'; if Msg.Parse(S) then begin if Msg.ArrayData.Count <> 1 then Passed := False; end else begin ShowMessage('Test failed: ' + Msg.Serialized); Passed := False; end; S := 'a:1:{s:10:"0123456789";b:1;}'; if Msg.Parse(S) then begin if Msg.ArrayData.Count <> 1 then Passed := False; end else begin ShowMessage('Test failed: ' + Msg.Serialized); Passed := False; end; S := 'a:1:{s:28:"/BUCKET_GET MINION_CMD_sylnt";s:6:"handle";}'; if Msg.Parse(S) then begin if Msg.ArrayData.Count <> 1 then Passed := False; end else begin ShowMessage('Test failed: ' + Msg.Serialized); Passed := False; end;*) FileName := ExtractFilePath(ParamStr(0)) + 'tests\test001.txt'; if FileToStr(FileName, S) = False then begin ShowMessage('Test failed: ' + S); Passed := False; end else if Msg.Parse(S) then // TODO: TRYING TO GET THIS TEST TO WORK - MESSAGES GETTING MIXED TOGETHER. MAYBE DUE TO LENGTH OF EXEC_LIST MESSAGES. TRY HAVE BOT BREAK UP INTO SUBARRAYS & SEE IF IT HELPS (THOUGH SEEMS HACKISH) ???? begin end else begin ShowMessage('Test failed: ' + S); Passed := False; end; Msg.Free; if Passed then ShowMessage('Tests passed!'); end; { TSerialized } function TSerialized.ArrayParse(var Serialized: string): Boolean; var S: string; L: Integer; begin Result := False; FSerialized := ''; FIntegerData := 0; FDoubleData := 0.0; FStringData := ''; FBooleanData := False; FArrayData.Clear; if Length(Serialized) < 3 then Exit; if Serialized[2] <> ':' then Exit; S := Copy(Serialized, 3, Length(Serialized) - 2); L := -1; case Serialized[1] of 'a': if ParseArrayData(Serialized, L) = False then Exit; 'b': if ParseBooleanData(S, L) = False then Exit; 'd': if ParseDoubleData(S, L) = False then Exit; 'i': if ParseIntegerData(S, L) = False then Exit; 's': if ParseStringData(S, L) = False then Exit; else Exit; end; FSerialized := Serialized; FDataType := Serialized[1]; if L >= 0 then Delete(Serialized, 1, L + 2); Result := True; end; constructor TSerialized.Create; begin FArrayData := TSerializedArray.Create; end; function TSerialized.DataAsString: string; begin Result := ''; case FDataType of 'b': if FBooleanData then Result := 'True' else Result := 'False'; 'd': Result := FloatToStr(FDoubleData); 'i': Result := IntToStr(FIntegerData); 's': Result := FStringData; end; end; destructor TSerialized.Destroy; begin FArrayData.Free; inherited; end; function TSerialized.FillTreeView(const TreeView: TTreeView; const Parent: TTreeNode = nil): Boolean; var N: TTreeNode; i: Integer; begin N := TreeView.Items.AddChildObject(Parent, DataAsString, Self); for i := 0 to FArrayData.Count - 1 do TSerialized(FArrayData.Items.Objects[i]).FillTreeView(TreeView, N); Result := True; end; function TSerialized.GetArrayValue(const Key: string): TSerialized; begin Result := FArrayData[Key]; end; function TSerialized.Parse(const Serialized: string): Boolean; var S: string; begin S := Serialized; Result := ArrayParse(S); end; function TSerialized.ParseArrayData(const Data: string; var Len: Integer): Boolean; begin Len := FArrayData.ParseLength(Data); Result := Len <> -1; if Result = False then FSerialized := SysUtils.Format(ERROR_MESSAGE, [Self.ClassName, 'ParseArrayData', FSerialized]); end; function TSerialized.ParseBooleanData(const Data: string; var Len: Integer): Boolean; begin Len := 1; Result := False; if Data <> '' then if Data[1] = '1' then begin FBooleanData := True; Result := True; end else if Data[1] = '0' then begin FBooleanData := False; Result := True; end; if Result = False then FSerialized := SysUtils.Format(ERROR_MESSAGE, [Self.ClassName, 'ParseBooleanData', FSerialized]); end; function TSerialized.ParseDoubleData(const Data: string; var Len: Integer): Boolean; var S: string; i: Integer; begin S := Data; i := Pos(';', S); if i > 0 then S := Copy(S, 1, i - 1); Len := Length(S); try FDoubleData := SysUtils.StrToFloat(S); Result := True; except FDoubleData := 0.0; Result := False; end; if Result = False then FSerialized := SysUtils.Format(ERROR_MESSAGE, [Self.ClassName, 'ParseDoubleData', FSerialized]); end; function TSerialized.ParseIntegerData(const Data: string; var Len: Integer): Boolean; var S: string; i: Integer; begin Result := True; S := Data; i := Pos(';', S); if i > 0 then S := Copy(S, 1, i - 1); Len := Length(S); for i := 1 to Len do case S[i] of '0'..'9': ; else Result := False; Break; end; if Result then try FIntegerData := SysUtils.StrToInt(S); except Result := False; FIntegerData := 0; end; if Result = False then FSerialized := SysUtils.Format(ERROR_MESSAGE, [Self.ClassName, 'ParseIntegerData', FSerialized]); end; function TSerialized.ParseStringData(const Data: string; var Len: Integer): Boolean; begin Result := Utils.ExtractSerialzedString(Data, FStringData); Len := Length(SysUtils.IntToStr(Length(FStringData))) + 3 + Length(FStringData); if Result = False then FSerialized := SysUtils.Format(ERROR_MESSAGE, [Self.ClassName, 'ParseStringData', FSerialized]); end; { TSerializedArray } procedure TSerializedArray.Clear; var i: Integer; begin for i := 0 to Count - 1 do FItems.Objects[i].Free; FItems.Clear; end; constructor TSerializedArray.Create; begin FItems := Classes.TStringList.Create; end; destructor TSerializedArray.Destroy; begin Clear; FItems.Free; inherited; end; function TSerializedArray.GetCount: Integer; begin Result := FItems.Count; end; function TSerializedArray.GetValue(const Key: string): TSerialized; var i: Integer; begin i := IndexOf(Key); if i >= 0 then Result := TSerialized(FItems.Objects[i]) else Result := nil; end; function TSerializedArray.IndexOf(const Key: string): Integer; var i: Integer; begin for i := 0 to Count - 1 do if FItems[i] = Key then begin Result := i; Exit; end; Result := -1; end; function TSerializedArray.Parse(const Serialized: string): Boolean; begin Result := ParseLength(Serialized) <> -1; end; function TSerializedArray.ParseLength(const Serialized: string): Integer; var S: string; n: Integer; i: Integer; Children: TList; Child: TSerialized; begin FSerialized := Serialized; Result := -1; S := Serialized; Delete(S, 1, 2); i := Pos(':', S); if i <= 0 then Exit; try n := SysUtils.StrToInt(Copy(S, 1, i - 1)); // number of elements in the array except StrToFile(ExtractFilePath(ParamStr(0)) + 'debug.txt', S); Exit; end; Delete(S, 1, i); if Length(S) < 2 then Exit; if S[1] <> '{' then Exit; Delete(S, 1, 1); Children := TList.Create; try for i := 1 to n * 2 do begin Child := TSerialized.Create; if Child.ArrayParse(S) = False then begin Child.Free; Exit; end else begin Children.Add(Child); if (Child.DataType <> 'a') and (S <> '') then if S[1] = ';' then Delete(S, 1, 1) else Exit; end; end; for i := 0 to n - 1 do begin case TSerialized(Children[i * 2]).DataType of 's': FItems.AddObject(TSerialized(Children[i * 2]).StringData, TSerialized(Children[i * 2 + 1])); 'i': FItems.AddObject(SysUtils.IntToStr(TSerialized(Children[i * 2]).IntegerData), TSerialized(Children[i * 2 + 1])); else Exit; end; end; if Length(S) < 1 then Exit; if S[1] <> '}' then Exit; Delete(S, 1, 1); Result := Length(Serialized) - Length(S) - 2; finally if Result = -1 then begin for i := 0 to Children.Count - 1 do TSerialized(Children[i]).Free; FItems.Clear; end else for i := 0 to Children.Count - 1 do if i mod 2 = 0 then TSerialized(Children[i]).Free; Children.Free; end; end; end.
unit Dmitry.Controls.ComboBoxExDB; interface uses System.Types, System.UITypes, System.SysUtils, System.Classes, Winapi.Windows, Winapi.Messages, Winapi.CommCtrl, Vcl.Controls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Graphics, Vcl.Themes, Dmitry.Memory, Dmitry.Graphics.LayeredBitmap; {$R-} type TOnGetAdditionalImageEvent = procedure(Sender: TObject; Index: Integer; HDC: THandle; var Top, Left: Integer) of object; TComboBoxExDBStyleHook = class(TComboBoxStyleHook) strict private FDroppedDown: Boolean; FComboBoxHandle: HWnd; FComboBoxInstance: Pointer; FDefComboBoxProc: Pointer; procedure InitComboBoxWnd; procedure PaintComboBoxWnd; procedure WMCommand(var Message: TWMCommand); message WM_COMMAND; procedure WMNCPaint(var Message: TMessage); message WM_NCPaint; procedure WMParentNotify(var Message: TMessage); message WM_ParentNotify; strict protected procedure ComboBoxWndProc(var Msg: TMessage); virtual; procedure DoHotTrackTimer(Sender: TObject); override; procedure DrawComboBox(DC: HDC); virtual; procedure MouseLeave; override; procedure DrawListBoxItem(ADC: HDC; ARect: TRect; AIndex: Integer; ASelected: Boolean); procedure WndProc(var Message: TMessage); override; public constructor Create(AControl: TWinControl); override; destructor Destroy; override; end; type TComboBoxExDB = class(TComboBoxEx) private { Private declarations } FShowDropDownMenu: Boolean; FLastItemIndex: Integer; FOnEnterDown: TNotifyEvent; FNullText: string; FStartText: string; FOnGetAdditionalImage: TOnGetAdditionalImageEvent; FShowEditIndex: Integer; FDefaultIcon: TIcon; FEditInnerMouse: Boolean; FText: string; FHideItemIcons: Boolean; FDefaultImage: TLayeredBitmap; FCanClickIcon: Boolean; FIconInnerMouse: Boolean; FPressed: Boolean; FIconClick: TNotifyEvent; procedure SetShowDropDownMenu(const Value: Boolean); procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; procedure WMDrawItem(var Message: TWMDrawItem); message WM_DRAWITEM; procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN; procedure CMMouseLeave(var Message: TWMNoParams); message CM_MOUSELEAVE; procedure CMMouseEnter(var Message: TWMNoParams); message CM_MOUSEENTER; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure WmSetFocus(var Message: TMessage); message WM_SETFOCUS; procedure WmKillFocus(var Message: TMessage); message WM_KILLFOCUS; procedure SetOnEnterDown(const Value: TNotifyEvent); procedure SetNullText(const Value: string); procedure SetOnGetAdditionalImage(const Value: TOnGetAdditionalImageEvent); procedure SetLastItemIndex(const Value: integer); procedure SetShowEditIndex(const Value: integer); procedure SetDefaultIcon(const Value: TIcon); procedure SetHideItemIcons(const Value: Boolean); procedure SetCanClickIcon(const Value: Boolean); protected { Protected declarations } procedure ComboWndProc(var Message: TMessage; ComboWnd: HWnd; ComboProc: Pointer); override; procedure WndProc(var Message: TMessage); override; procedure DrawEditIcon(DC: HDC); public { Public declarations } class constructor Create; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AdjustDropDown; override; procedure SetItemIndex(const Value: Integer); override; published { Published declarations } property Align; property Anchors; property ShowDropDownMenu: Boolean read FShowDropDownMenu write SetShowDropDownMenu; property LastItemIndex: Integer read FLastItemIndex write SetLastItemIndex; property OnEnterDown: TNotifyEvent read FOnEnterDown write SetOnEnterDown; property NullText: string read FNullText write SetNullText; property ShowEditIndex: Integer read FShowEditIndex write SetShowEditIndex; property OnGetAdditionalImage: TOnGetAdditionalImageEvent read FOnGetAdditionalImage write SetOnGetAdditionalImage; property StartText: string read FStartText write FStartText; property DefaultIcon: TIcon read FDefaultIcon write SetDefaultIcon; property HideItemIcons: Boolean read FHideItemIcons write SetHideItemIcons; property CanClickIcon: Boolean read FCanClickIcon write SetCanClickIcon; property IconClick: TNotifyEvent read FIconClick write FIconClick; property ListHandle: HWND read FListHandle; property EditHandle: HWND read FEditHandle; end; procedure Register; implementation procedure Register; begin RegisterComponents('Dm', [TComboBoxExDB]); end; { TComboBoxExDB } function ColorDiv2(Color1, Color2 : TColor) : TColor; begin Result:=RGB((GetRValue(Color1) + GetRValue(Color2)) div 2, (GetGValue(Color1) + GetGValue(Color2)) div 2, (GetBValue(Color1) + GetBValue(Color2)) div 2); end; procedure TComboBoxExDB.AdjustDropDown; var Count: Integer; aItemHeight: integer; begin if not ShowDropDownMenu then Exit; Count := ItemCount; if Count > DropDownCount then Count := DropDownCount; if Count < 1 then Count := 1; FDroppingDown := True; try aItemHeight := 32; SetWindowPos(FDropHandle, 0, 0, 0, Width, aItemHeight * Count + Height + 2, SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_NOREDRAW or SWP_HIDEWINDOW); finally FDroppingDown := False; end; SetWindowPos(FDropHandle, 0, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_NOREDRAW or SWP_SHOWWINDOW); end; procedure TComboBoxExDB.CMMouseEnter(var Message: TWMNoParams); begin FEditInnerMouse := True; inherited; end; procedure TComboBoxExDB.CMMouseLeave(var Message: TWMNoParams); begin FEditInnerMouse := False; FPressed := False; inherited; end; procedure TComboBoxExDB.CMTextChanged(var Message: TMessage); begin FText := Text; end; procedure TComboBoxExDB.CNCommand(var Message: TWMCommand); begin inherited; case Message.NotifyCode of CBN_SELCHANGE: FText := Items[ItemIndex]; end; end; procedure TComboBoxExDB.ComboWndProc(var Message: TMessage; ComboWnd: HWnd; ComboProc: Pointer); var rcItem: TRect; DC: HDC; Bitmap: TBitmap; PS: TPaintStruct; C, FC: TColor; begin if ComboWnd = FEditHandle then begin if not Focused and (Message.Msg <> WM_GETTEXT) and Visible and (FText = '') then begin if (Message.Msg = WM_PAINT) or (Message.Msg = WM_ERASEBKGND) then begin rcItem := Rect(1, 0, Width, Height); Bitmap := TBitmap.Create; try if StyleServices.Enabled then begin C := StyleServices.GetStyleColor(scEdit); FC := StyleServices.GetStyleFontColor(sfEditBoxTextNormal); end else begin C := Color; FC := Font.Color; end; Bitmap.Canvas.Font.Assign(Font); Bitmap.Canvas.Font.Color := ColorDiv2(ColorToRGB(C), ColorToRGB(FC)); Bitmap.Canvas.Brush.Color := C; Bitmap.Canvas.Pen.Color := C; Bitmap.Width := Width; Bitmap.Height := Height; Bitmap.Canvas.Rectangle(0, 0, Width, Height); DrawText(Bitmap.Canvas.Handle, PChar(FStartText), Length(FStartText), rcItem, DT_TOP); DC := BeginPaint(FEditHandle, PS); try BitBlt(DC, 0, 0, Width, Height, Bitmap.Canvas.Handle, 0, 0, SrcCopy); finally EndPaint(Handle, PS); end; finally F(Bitmap); end; Exit; end end; end else begin if Message.Msg = WM_MOUSEMOVE then begin if FCanClickIcon then begin rcItem := Rect(3, 3, 3 + FDefaultImage.Width, 3 + FDefaultImage.Height); FIconInnerMouse := PtInRect(rcItem, Point(TWMMouse(Message).XPos, TWMMouse(Message).YPos)); if FIconInnerMouse then Perform(CBEM_SETIMAGELIST, 0, Images.Handle); end; end else if Message.Msg = WM_MOUSELEAVE then begin if FCanClickIcon then begin FIconInnerMouse := False; FPressed := False; rcItem := Rect(3, 3, 3 + FDefaultImage.Width, 3 + FDefaultImage.Height); end; end else if Message.Msg = WM_LBUTTONDOWN then begin if FCanClickIcon then begin FPressed := True; Perform(CBEM_SETIMAGELIST, 0, Images.Handle); end; end else if Message.Msg = WM_LBUTTONUP then begin if FCanClickIcon then begin if FIconInnerMouse and FCanClickIcon and Assigned(FIconClick) then FIconClick(Self); FPressed := False; end; end; end; if ComboWnd <> 0 then inherited; if (ComboWnd = FEditHandle) and (Message.Msg = WM_KEYDOWN) then PostMessage(Handle, CM_TEXTCHANGED, 0, 0); end; class constructor TComboBoxExDB.Create; begin TCustomStyleEngine.RegisterStyleHook(TComboBoxExDB, TComboBoxExDBStyleHook); end; constructor TComboBoxExDB.Create(AOwner: TComponent); begin inherited Create(AOwner); FDefaultImage := TLayeredBitmap.Create; FShowDropDownMenu := True; FOnEnterDown := nil; fShowEditIndex := -1; FDefaultIcon := TIcon.Create; FEditInnerMouse := False; FHideItemIcons := False; FPressed := False; end; destructor TComboBoxExDB.Destroy; begin F(FDefaultIcon); F(FDefaultImage); inherited; end; procedure TComboBoxExDB.DrawEditIcon(DC: HDC); var BIco: TBitmap; begin FDefaultImage.LoadFromHIcon(FDefaultIcon.Handle); BIco := TBitmap.Create; try BIco.PixelFormat := pf24bit; BIco.SetSize(FDefaultImage.Width, FDefaultImage.Height); if StyleServices.Enabled then begin BIco.Canvas.Brush.Color := StyleServices.GetStyleColor(scEdit); BIco.Canvas.Pen.Color := StyleServices.GetStyleColor(scEdit); end else begin BIco.Canvas.Brush.Color := clWindow; BIco.Canvas.Pen.Color := clWindow; end; BIco.Canvas.Rectangle(0, 0, FDefaultImage.Width, FDefaultImage.Height); if FCanClickIcon then begin if FIconInnerMouse then FDefaultImage.DoLayeredDraw(0, 0, 255, BIco) else FDefaultImage.DoLayeredDraw(0, 0, 127, BIco); if FPressed and FIconInnerMouse then DrawFocusRect(BIco.Canvas.Handle, Rect(0, 0, BIco.Width - 1, BIco.Height - 1)); end else FDefaultImage.DoLayeredDraw(0, 0, 255, BIco); BitBlt(DC, 3, 3, Width, Height, BIco.Canvas.Handle, 0, 0, SRCCOPY); finally F(BIco); end; end; procedure TComboBoxExDB.SetCanClickIcon(const Value: Boolean); begin FCanClickIcon := Value; PostMessage(Handle, WM_PAINT, 0, 0); end; procedure TComboBoxExDB.SetDefaultIcon(const Value: TIcon); begin if Value <> nil then FDefaultIcon.Assign(Value); end; procedure TComboBoxExDB.SetHideItemIcons(const Value: Boolean); begin FHideItemIcons := Value; end; procedure TComboBoxExDB.SetItemIndex(const Value: Integer); begin inherited; PostMessage(Handle, CM_TEXTCHANGED, 0, 0); PostMessage(Handle, WM_PAINT, 0, 0); end; procedure TComboBoxExDB.SetLastItemIndex(const Value: integer); begin FLastItemIndex := Value; end; procedure TComboBoxExDB.SetNullText(const Value: string); begin FNullText := Value; end; procedure TComboBoxExDB.SetOnEnterDown(const Value: TNotifyEvent); begin FOnEnterDown := Value; end; procedure TComboBoxExDB.SetOnGetAdditionalImage( const Value: TOnGetAdditionalImageEvent); begin FOnGetAdditionalImage := Value; end; procedure TComboBoxExDB.SetShowDropDownMenu(const Value: boolean); begin FShowDropDownMenu := Value; end; procedure TComboBoxExDB.SetShowEditIndex(const Value: integer); begin FShowEditIndex := Value; end; procedure TComboBoxExDB.WMDrawItem(var Message: TWMDrawItem); var OldState, State: TOwnerDrawState; Bitmap: TBitmap; OldRect: TRect; ItemID: Cardinal; ABrush: TBrush; DC: HDC; S: string; begin if Images = nil then begin inherited; Exit; end; DC := message.DrawItemStruct^.hDC; ItemID := message.DrawItemStruct^.itemID; OldState := TOwnerDrawState(LongRec(message.DrawItemStruct^.ItemState).Lo); State := OldState - [OdNoFocusRect, OdFocused]; if OdComboBoxEdit in State then State := State - [OdSelected]; LongRec(message.DrawItemStruct^.ItemState).Lo := Word(State); if Int64(ItemID) >= Int64(MaxInt) then ItemID := FLastItemIndex; if (not(OdComboBoxEdit in State)) and HideItemIcons then begin ABrush := TBrush.Create; try ABrush.Style := bsSolid; if OdSelected in OldState then ABrush.Color := clHighlight else ABrush.Color := clWindow; FillRect(DC, message.DrawItemStruct^.rcItem, ABrush.Handle); InflateRect(message.DrawItemStruct^.rcItem, -5, 0); SetBkColor(DC, COLORREF(ABrush.Color)); SetBkMode(DC, BS_NULL); if Integer(ItemID) < ItemsEx.Count then S := ItemsEx[ItemID].Caption else S := Name; DrawText(DC, PChar(S), Length(S), message.DrawItemStruct^.RcItem, DT_TOP); finally F(ABrush); end; end else DefaultHandler(Message); Bitmap := TBitmap.Create; try if Int64(ItemID) >= (MaxInt) then ItemID := FLastItemIndex else begin if OdComboBoxEdit in State then begin if FShowEditIndex <> -1 then begin if (FShowEditIndex < Images.Count) then ItemID := FShowEditIndex else ItemID := FLastItemIndex; end else FLastItemIndex := ItemID; end; end; Images.GetBitmap(ItemID, Bitmap); if not (FHideItemIcons and (not(OdComboBoxEdit in State))) then begin if OdComboBoxEdit in State then begin if not Bitmap.Empty then BitBlt(DC, message.DrawItemStruct^.RcItem.Left, message.DrawItemStruct^.RcItem.Top, 32, 32, Bitmap.Canvas.Handle, 0, 0, SRCCOPY) else begin DrawEditIcon(DC); end; end else BitBlt(DC, message.DrawItemStruct^.RcItem.Left + 3, message.DrawItemStruct^.RcItem.Top, 32, 32, Bitmap.Canvas.Handle, 0, 0, SRCCOPY); OldRect := message.DrawItemStruct^.RcItem; OldRect.Left := message.DrawItemStruct^.RcItem.Left + 3 + Images.Width; message.DrawItemStruct^.RcItem.Top := message.DrawItemStruct^.RcItem.Top + 1; message.DrawItemStruct^.RcItem.Left := message.DrawItemStruct^.RcItem.Left + 16 + Images.Width; end else OldRect := message.DrawItemStruct^.RcItem; if Int64(ItemID) < Int64(ItemsEx.Count) then if ItemsEx[ItemID].Caption = '' then begin if not(OdComboBoxEdit in State) then begin SetBkMode(DC, BS_NULL); SetDCPenColor(DC, ColorDiv2(Font.Color, Color)); DrawText(DC, PChar(FNullText), Length(FNullText), message.DrawItemStruct^.RcItem, DT_TOP); end; end; finally F(Bitmap); end; if not(OdComboBoxEdit in State) then if Assigned(FOnGetAdditionalImage) then FOnGetAdditionalImage(Self, ItemID, message.DrawItemStruct^.HDC, message.DrawItemStruct^.RcItem.Top, message.DrawItemStruct^.RcItem.Left); end; procedure TComboBoxExDB.WMKeyDown(var Message: TWMKeyDown); begin case Message.CharCode of VK_RETURN: begin if Assigned(FOnEnterDown) then FOnEnterDown(Self); Message.Msg := 0; end; end; inherited; end; procedure TComboBoxExDB.WmKillFocus(var Message: TMessage); begin PostMessage(Handle, WM_PAINT, 0, 0); inherited; end; procedure TComboBoxExDB.WmSetFocus(var Message: TMessage); begin PostMessage(Handle, WM_PAINT, 0, 0); inherited; end; procedure TComboBoxExDB.WndProc(var Message: TMessage); begin inherited; ComboWndProc(Message, 0, nil); end; { TComboBoxExDBStyleHook } constructor TComboBoxExDBStyleHook.Create(AControl: TWinControl); begin inherited; OverridePaint := False; OverridePaintNC := False; FDroppedDown := False; FComboBoxHandle := 0; FComboBoxInstance := MakeObjectInstance(ComboBoxWndProc); FDefComboBoxProc := nil; end; destructor TComboBoxExDBStyleHook.Destroy; begin if FComboBoxHandle <> 0 then SetWindowLong(FComboBoxHandle, GWL_WNDPROC, IntPtr(FDefComboBoxProc)); FreeObjectInstance(FComboBoxInstance); inherited; end; procedure TComboBoxExDBStyleHook.WMParentNotify(var Message: TMessage); begin if TStyleManager.SystemStyle.Enabled then inherited; end; procedure TComboBoxExDBStyleHook.WndProc(var Message: TMessage); begin // Reserved for potential updates inherited; if Message.Msg = CM_RECREATEWND then begin MouseInControl := False; MouseLeave; end; end; procedure TComboBoxExDBStyleHook.DoHotTrackTimer; var P: TPoint; begin GetCursorPos(P); if WindowFromPoint(P) <> FComboBoxHandle then begin StopHotTrackTimer; MouseInControl := False; MouseLeave; end; end; procedure TComboBoxExDBStyleHook.MouseLeave; begin MouseOnButton := False; PaintComboBoxWnd; end; procedure TComboBoxExDBStyleHook.DrawListBoxItem(ADC: HDC; ARect: TRect; AIndex: Integer; ASelected: Boolean); var Canvas: TCanvas; Offset: Integer; IconX, IconY: Integer; Buffer: TBitMap; LCaption: String; R: TRect; begin if (AIndex < 0) or (AIndex >= TComboBoxEx(Control).ItemsEx.Count) then Exit; Canvas := TCanvas.Create; Canvas.Handle := ADC; Buffer := TBitmap.Create; Buffer.Width := ARect.Width; Buffer.Height := ARect.Height; try Buffer.Canvas.Font.Assign(TComboBoxEx(Control).Font); with Buffer.Canvas do begin // draw item background Brush.Style := bsSolid; if ASelected then begin Brush.Color := clHighLight; Font.Color := clHighLightText; end else begin Brush.Color := StyleServices.GetStyleColor(scComboBox); Font.Color := StyleServices.GetStyleFontColor(sfComboBoxItemNormal); end; FillRect(Rect(0, 0, Buffer.Width, Buffer.Height)); Offset := TComboExItem(TComboBoxEx(Control).ItemsEx[AIndex]).Indent; if Offset > 0 then Offset := (Offset * 10) + 5 else Offset := 5; // draw item image if (TComboBoxEx(Control).Images <> nil) and not TComboBoxExDB(Control).HideItemIcons then with TComboBoxEx(Control) do begin IconX := Offset; IconY := Buffer.Height div 2 - Images.Height div 2; if IconY < 0 then IconY := 0; if (ItemsEx[AIndex].ImageIndex >= 0) and (ItemsEx[AIndex].ImageIndex < Images.Count) then Images.Draw(Buffer.Canvas, IconX, IconY, ItemsEx[AIndex].ImageIndex, True); Offset := Offset + Images.Width + 5; end; // draw item text R := Rect(Offset, 0, Buffer.Width, Buffer.Height); Buffer.Canvas.Brush.Style := bsClear; LCaption := TComboBoxEx(Control).ItemsEx[AIndex].Caption; if LCaption <> '' then DrawText(Buffer.Canvas.Handle, PWideChar(LCaption), Length(LCaption), R, DT_LEFT OR DT_VCENTER or DT_SINGLELINE); end; Canvas.Draw(ARect.Left, ARect.Top, Buffer); finally Buffer.Free; Canvas.Handle := 0; Canvas.Free; end; end; procedure TComboBoxExDBStyleHook.ComboBoxWndProc(var Msg: TMessage); var FCallOldProc: Boolean; PS: TPaintStruct; DC, PaintDC: HDC; P: TPoint; FOldMouseOnButton: Boolean; R: TRect; begin FCallOldProc := True; case Msg.Msg of WM_ERASEBKGND: begin Msg.Result := 1; FCallOldProc := False; end; WM_CTLCOLORLISTBOX: if (ListHandle = 0) and (Msg.LParam <> 0) and (ListBoxInstance = nil) then HookListBox(Msg.LParam); WM_DRAWITEM: begin with TWMDrawItem(Msg) do begin DrawListBoxItem(DrawItemStruct.hDC, DrawItemStruct.rcItem, DrawItemStruct.itemID, DrawItemStruct.itemState and ODS_SELECTED <> 0); end; FCallOldProc := False; end; WM_PAINT: begin DC := HDC(Msg.WParam); if DC <> 0 then PaintDC := DC else PaintDC := BeginPaint(FComboBoxHandle, PS); try DrawComboBox(PaintDC); finally if DC = 0 then EndPaint(FComboBoxHandle, PS); end; FCallOldProc := False; end; WM_MOUSEMOVE: begin if not MouseInControl then begin MouseInControl := True; StartHotTrackTimer; MouseEnter; end; P := Point(TWMMouse(Msg).XPos, TWMMouse(Msg).YPos); FOldMouseOnButton := MouseOnButton; R := ButtonRect; if PtInRect(R, P) then MouseOnButton := True else MouseOnButton := False; if FOldMouseOnButton <> MouseOnButton then InvalidateRect(FComboBoxHandle, @R, False); end; end; if FCallOldProc then with Msg do Result := CallWindowProc(FDefComboBoxProc, FComboBoxHandle, Msg, WParam, LParam); end; procedure TComboBoxExDBStyleHook.PaintComboBoxWnd; begin RedrawWindow(FComboBoxHandle, nil, 0, RDW_INVALIDATE or RDW_UPDATENOW); end; procedure TComboBoxExDBStyleHook.WMNCPaint(var Message: TMessage); begin if FComboBoxHandle = 0 then InitComboBoxWnd; end; procedure TComboBoxExDBStyleHook.WMCommand(var Message: TWMCommand); begin CallDefaultProc(TMessage(Message)); case Message.NotifyCode of CBN_SELCHANGE, CBN_SELENDOK, CBN_SETFOCUS, CBN_KILLFOCUS: PaintComboBoxWnd; CBN_DROPDOWN: begin FDroppedDown := True; PaintComboBoxWnd; end; CBN_CLOSEUP: begin FDroppedDown := False; PaintComboBoxWnd; end; end; Handled := True; end; procedure TComboBoxExDBStyleHook.DrawComboBox(DC: HDC); var Canvas: TCanvas; DrawState: TThemedComboBox; Details: TThemedElementDetails; R: TRect; BtnDrawState: TThemedComboBox; IconX, IconY: Integer; LCaption: string; Buffer: TBitmap; begin if not StyleServices.Available or (Control.Width = 0) or (Control.Height = 0) then Exit; Canvas := TCanvas.Create; try Canvas.Handle := DC; Buffer := TBitMap.Create; try Buffer.Width := Control.Width; Buffer.Height := Control.Height; if not Control.Enabled then DrawState := tcBorderDisabled else if MouseInControl then DrawState := tcBorderHot else if Focused then DrawState := tcBorderFocused else DrawState := tcBorderNormal; R := Rect(0, 0, Control.Width, Control.Height); Details := StyleServices.GetElementDetails(DrawState); StyleServices.DrawElement(Buffer.Canvas.Handle, Details, R); if not Control.Enabled then BtnDrawState := tcDropDownButtonDisabled else if FDroppedDown then BtnDrawState := tcDropDownButtonPressed else if MouseOnButton then BtnDrawState := tcDropDownButtonHot else BtnDrawState := tcDropDownButtonNormal; if TCustomComboBoxEx(Control).Style <> csExSimple then begin Details := StyleServices.GetElementDetails(BtnDrawState); StyleServices.DrawElement(Buffer.Canvas.Handle, Details, ButtonRect); end; R := Control.ClientRect; InflateRect(R, -3, -3); R.Right := ButtonRect.Left - 2; Buffer.Canvas.Font.Assign(TComboBoxEx(Control).Font); if Control.Enabled then Buffer.Canvas.Font.Color := StyleServices.GetStyleFontColor(sfComboBoxItemNormal) else Buffer.Canvas.Font.Color := StyleServices.GetStyleFontColor(sfComboBoxItemDisabled); if TComboBoxEx(Control).Style = csExDropDownList then begin if TComboBoxEx(Control).Focused then with Buffer.Canvas do begin if TComboBoxEx(Control).ItemIndex <> -1 then begin Brush.Color := clHighLight; Brush.Style := bsSolid; FillRect(R); Font.Color := clHighLightText; end; DrawFocusRect(R); end else with Buffer.Canvas do begin Brush.Color := Self.Brush.Color; Brush.Style := bsSolid; FillRect(R); end; end; if TComboBoxEx(Control).Style <> csExSimple then begin // draw image if TComboBoxExDB(Control).CanClickIcon then TComboBoxExDB(Control).DrawEditIcon(Buffer.Canvas.Handle) else begin if (TComboBoxEx(Control).Images <> nil) and (TComboBoxEx(Control).ItemIndex <> -1) then with TComboBoxEx(Control) do begin IconX := 5; IconY := R.Top + R.Height div 2 - Images.Height div 2; if IconY < R.Top then IconY := R.Top; if (ItemsEx[ItemIndex].ImageIndex >= 0) and (ItemsEx[ItemIndex].ImageIndex < Images.Count) then Images.Draw(Buffer.Canvas, IconX, IconY, ItemsEx[ItemIndex].ImageIndex, Control.Enabled); R.Left := IconX + IMages.Width + 5; end else Inc(R.Left, 5); // draw text if (TComboBoxEx(Control).ItemIndex <> -1) then begin Buffer.Canvas.Brush.Style := bsClear; LCaption := TComboBoxEx(Control).ItemsEx[TComboBoxEx(Control).ItemIndex].Caption; if LCaption <> '' then DrawText(Buffer.Canvas.Handle, PWideChar(LCaption), Length(LCaption), R, DT_LEFT OR DT_VCENTER or DT_SINGLELINE); end; end; end; Canvas.Draw(0, 0, Buffer); finally Buffer.Free; end; finally Canvas.Handle := 0; Canvas.Free; end; Handled := True; end; procedure TComboBoxExDBStyleHook.InitComboBoxWnd; begin if FComboBoxHandle = 0 then begin FComboBoxHandle := SendMessage(Handle, CBEM_GETCOMBOCONTROL, 0, 0); if FComboBoxHandle <> 0 then begin FDefComboBoxProc := Pointer(GetWindowLong(FComboBoxHandle, GWL_WNDPROC)); SetWindowLong(FComboBoxHandle, GWL_WNDPROC, IntPtr(FComboBoxInstance)); end; end; end; end.