text
stringlengths
14
6.51M
unit intensive.Controller; interface uses FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteWrapper.Stat, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, Data.DB, FireDAC.Comp.Client, intensive.Controller.Interfaces, intensive.Model.Entity.Cliente, intensive.Services.Generic, intensive.Controller.DTO.Interfaces, intensive.Controller.DTO.Cliente; type TController = class(TInterfacedObject, iController) private FCliente : iClienteDTO; public constructor Create; destructor Destroy; override; class function New : iController; function Cliente : iClienteDTO; end; implementation constructor TController.Create; begin end; destructor TController.Destroy; begin inherited; end; class function TController.New : iController; begin Result := Self.Create; end; function TController.Cliente: iClienteDTO; begin if not Assigned(FCliente) then FCliente := TClienteDTO.New; Result := FCliente; end; end.
unit IteratorMenu; interface uses System.SysUtils, ItensDoMenu, InterfaceIterator, System.Generics.Collections; type ListaDeMenus = array of TItensMenu; TMenuIterator = class(TInterfacedObject, IIterator) private Itens: ListaDeMenus; Posição: Integer; PizzaAtual: TItensMenu; public constructor Create(Itens: ListaDeMenus); function TemProximo: Boolean; function Proximo: TItensMenu; function Nome: String; function Descricao: String; function Preco: Currency; function Vegano: String; destructor Destroy; override; end; implementation { TMenuIterator } constructor TMenuIterator.Create(Itens: ListaDeMenus); begin Self.Itens := Itens; Posição := 0; end; function TMenuIterator.Descricao: String; begin PizzaAtual := Itens[Posição]; Result := PizzaAtual.GetDescricao; end; destructor TMenuIterator.Destroy; var Item: TItensMenu; begin for Item in Self.Itens do Item.Free; inherited; end; function TMenuIterator.Nome: String; begin PizzaAtual := Itens[Posição]; Result := PizzaAtual.GetNome; end; function TMenuIterator.Preco: Currency; begin PizzaAtual := Itens[Posição]; Result := PizzaAtual.GetPreco; end; function TMenuIterator.Proximo: TItensMenu; begin PizzaAtual := Itens[Posição]; Posição := +1; Result := PizzaAtual; end; function TMenuIterator.TemProximo: Boolean; begin if (Posição > Length(Itens)) or (Itens[Posição] = nil) then Result := False else Result := True; end; function TMenuIterator.Vegano: String; begin PizzaAtual := Itens[Posição]; Writeln(PizzaAtual.IsVegan); end; end.
{ Application main form. @author(Tomáš Borek <tomas.borek@post.cz>) } unit UMainF; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs; type { TMainForm } TMainForm = class(TForm) public { Customizes form when created. } constructor Create(AOwner: TComponent); override; end; var MainForm: TMainForm; implementation {$R *.lfm} resourcestring sFormTitle = 'ZBackup'; { TMainForm } constructor TMainForm.Create(AOwner: TComponent); begin inherited Create(AOwner); Caption := sFormTitle; end; end.
unit uConexao; interface uses System.IniFiles, System.SysUtils, 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.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, Vcl.Forms, uArquivoUDL, FPrincipal, uRegPgn; type TTipoConexao = (tcFirebird, tcSqlServer, tcOracle, tcMySql); type TTipoArquivo = (taIni, taUdl); type TTipoInicializacao = (taServico, taWindows); const cSection : String = 'CONEXAO'; cTipo : String = 'TIPO'; cServidor : String = 'SERVIDOR'; cAlias : String = 'ALIAS'; cUsuario : String = 'USUARIO'; cSenha : string = 'SENHA'; cPorta : string = 'PORTA'; cTipoArquivo : String = 'ARQUIVO'; cCaminhoUDL : String = 'CAMINHOUDL'; type TConexao = class private FTipoConexao : TTipoConexao; FServidor : string; FAlias : string; FUsuario : string; FSenha : string; FPorta : string; FCaminhoUdl: string; FTipoArquivo: TTipoArquivo; public property tipoConexao: TTipoConexao read FTipoConexao; // write FTipoConexao; property servidor : string read FServidor; // write FServidor; property alias : String read FAlias; // write FAlias; property usuario : String read FUsuario; // write FUsuario; property senha : String read FSenha; // write FSenha; property porta : string read FPorta; property tipoArquivo: TTipoArquivo read FTipoArquivo; property caminhoUDL : string read FCaminhoUdl; procedure configuraFDConnection(AFDConn: TFDConnection); function testarConexao(AFDConn: TFDConnection): boolean; procedure salvarIni(ADiretorio: String); constructor Create( ATipoConexao: TTipoConexao; AServidor : string; AAlias : string; AUsuario : string; ASenha : string; APorta : String; ATipoArquivo: TTipoArquivo; ACaminhoUDL : string ); overload; constructor create(ACaminhoIni: string = ''); overload; constructor create(ATipoInicializacao : TTipoInicializacao; ACaminhoIni: String = ''); overload; end; var conexao : TConexao; implementation { TConexao } constructor TConexao.Create(ATipoConexao: TTipoConexao; AServidor, AAlias, AUsuario, ASenha, APorta: string; ATipoArquivo: TTipoArquivo; ACaminhoUDL: string); var udl : TArquivoUdl; begin Self.FTipoConexao := ATipoConexao; Self.FServidor := AServidor; Self.Falias := AAlias; Self.Fusuario := AUsuario; Self.Fsenha := ASenha; Self.Fporta := APorta; Self.FTipoArquivo := ATipoArquivo; Self.FCaminhoUdl := ACaminhoUDL; if FTipoArquivo = taUdl then begin udl := TArquivoUdl.create(FCaminhoUdl); FTipoConexao := tcSqlServer; FAlias := udl.catalogo; FServidor := udl.dataSource; FUsuario := udl.userId; FSenha := udl.password; FreeAndNil(udl); end; end; procedure TConexao.configuraFDConnection(AFDConn: TFDConnection); var driver: string; begin try case tipoConexao of tcFirebird : driver := 'FB'; tcSqlServer: driver := 'MSSQL'; tcOracle : driver := 'ORA'; tcMySql : driver := 'MYSQL'; end; with AFDConn do begin Connected := False; LoginPrompt := False; Params.Clear; Params.Add('User_Name=' + usuario); Params.Add('password=' + senha); Params.Add('Database=' + alias); Params.Add('DriverID=' + driver); if servidor <> '' then Params.Add('Server=' + servidor); if porta <> '' then Params.Add('port=' + porta); if senha = '' then Params.Add('OSAuthent=Yes'); end; except on E : Exception do raise Exception.Create('Erro ao carregar parâmetros de conexão!'#13#10 + E.Message); end; end; constructor TConexao.Create(ACaminhoIni: string); var iniFile: TIniFile; arquivo: string; udl : TArquivoUdl; begin try if ACaminhoIni = '' then arquivo := ExtractFilePath(Application.ExeName) + 'conexao.ini' else arquivo := ACaminhoIni + '\conexao.ini'; if FileExists(arquivo) then begin iniFile := TIniFile.Create(arquivo); FtipoConexao := TTipoConexao ( iniFile.ReadString(cSection, cTipo, '0').ToInteger ); FTipoArquivo := TTipoArquivo ( iniFile.ReadString(cSection, cTipoArquivo, '0').ToInteger ); Fservidor := iniFile.ReadString(cSection, cServidor, ''); Falias := iniFile.ReadString(cSection, cAlias, ''); Fusuario := iniFile.ReadString(cSection, cUsuario, ''); Fsenha := iniFile.ReadString(cSection, cSenha, ''); Fporta := iniFile.ReadString(cSection, cPorta, ''); FCaminhoUdl := iniFile.ReadString(cSection, cCaminhoUDL, ''); if FTipoArquivo = taUdl then begin udl := TArquivoUdl.create(FCaminhoUdl); FTipoConexao := tcSqlServer; FAlias := udl.catalogo; FServidor := udl.dataSource; FUsuario := udl.userId; FSenha := udl.password; FreeAndNil(udl); end; end else raise Exception.Create('Arquivo de conexão: ' + arquivo + ' não encontrado.'); except // on e : Exception do // escreveLog(e.Message); end; end; procedure TConexao.salvarIni(ADiretorio: String); var iniFile: TIniFile; begin if not DirectoryExists(ADiretorio) then raise Exception.Create('Diretório não existe...'); iniFile := TIniFile.Create(ADiretorio + '\conexao.ini'); iniFile.WriteString(cSection, cTipo, Integer(tipoConexao).ToString); iniFile.WriteString(cSection, cTipoArquivo, Integer(tipoArquivo).ToString); iniFile.WriteString(cSection, cServidor, servidor); iniFile.WriteString(cSection, cAlias, alias); iniFile.WriteString(cSection, cUsuario, usuario); iniFile.WriteString(cSection, cSenha, senha); iniFile.WriteString(cSection, cPorta, porta); iniFile.WriteString(cSection, cCaminhoUDL, caminhoUDL); end; function TConexao.testarConexao(AFDConn: TFDConnection): boolean; begin try Result := False; AFDConn.Connected := True; Result := AFDConn.Connected; except on e : Exception do raise Exception.Create('Erro ao conectar. ' + e.Message); end; end; constructor TConexao.Create(ATipoInicializacao: TTipoInicializacao; ACaminhoIni: String); var caminho : string; begin case ATipoInicializacao of taServico: begin caminho := LerStringReg(CHAVE_RAIZ, PathGeradorDeArquivos, 'Path', ''); end; taWindows: begin caminho := ACaminhoIni; if caminho = '' then caminho := ExtractFilePath(Application.ExeName); end; end; Create(caminho); end; end.
unit uSecurity; {$mode objfpc}{$H+} interface uses SynCommons, mORMot, uForwardDeclaration;//Classes, SysUtils; type // 1 TSQLX509IssuerProvision = class(TSQLRecord) private fCommonName: RawUTF8; fOrganizationalUnit: RawUTF8; fOrganizationName: RawUTF8; fCityLocality: RawUTF8; fStateProvince: RawUTF8; fCountry: RawUTF8; fSerialNumber: RawUTF8; published property CommonName: RawUTF8 read fCommonName write fCommonName; property OrganizationalUnit: RawUTF8 read fOrganizationalUnit write fOrganizationalUnit; property OrganizationName: RawUTF8 read fOrganizationName write fOrganizationName; property CityLocality: RawUTF8 read fCityLocality write fCityLocality; property StateProvince: RawUTF8 read fStateProvince write fStateProvince; property Country: RawUTF8 read fCountry write fCountry; property SerialNumber: RawUTF8 read fSerialNumber write fSerialNumber; end; // 2 TSQLUserLogin = class(TSQLRecord) private fCurrentPassword: RawUTF8; fPasswordHint: RawUTF8; fIsSystem: Boolean; fEnabled: Boolean; fHasLoggedOut: Boolean; fRequirePasswordChange: Boolean; fLastCurrencyUom: TSQLUomID; fLastLocale: RawUTF8; fLastTimeZone: RawUTF8; fDisabledDateTime: TDateTime; fSuccessiveFailedLogins: Integer; fExternalAuthId: RawUTF8; published property CurrentPassword: RawUTF8 read fCurrentPassword write fCurrentPassword; property PasswordHint: RawUTF8 read fPasswordHint write fPasswordHint; property IsSystem: Boolean read fIsSystem write fIsSystem; property Enabled: Boolean read fEnabled write fEnabled; property HasLoggedOut: Boolean read fHasLoggedOut write fHasLoggedOut; property RequirePasswordChange: Boolean read fRequirePasswordChange write fRequirePasswordChange; property LastCurrencyUom: TSQLUomID read fLastCurrencyUom write fLastCurrencyUom; property LastLocale: RawUTF8 read fLastLocale write fLastLocale; property LastTimeZone: RawUTF8 read fLastTimeZone write fLastTimeZone; property DisabledDateTime: TDateTime read fDisabledDateTime write fDisabledDateTime; property SuccessiveFailedLogins: Integer read fSuccessiveFailedLogins write fSuccessiveFailedLogins; property ExternalAuthId: RawUTF8 read fExternalAuthId write fExternalAuthId; end; // 3 TSQLUserLoginPasswordHistory = class(TSQLRecord) private fUserLogin: TSQLUserLoginID; fFromDate: TDateTime; fThruDate: TDateTime; fCurrentPassword: RawUTF8; published property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property CurrentPassword: RawUTF8 read fCurrentPassword write fCurrentPassword; end; // 4 TSQLUserLoginHistory = class(TSQLRecord) private fUserLogin: TSQLUserLoginID; fVisitId: RawUTF8; fFromDate: TDateTime; fThruDate: TDateTime; fPasswordUsed: RawUTF8; fSuccessfulLogin: Boolean; published property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin; property VisitId: RawUTF8 read fVisitId write fVisitId; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property PasswordUsed: RawUTF8 read fPasswordUsed write fPasswordUsed; property SuccessfulLogin: Boolean read fSuccessfulLogin write fSuccessfulLogin; end; // 5 TSQLUserLoginSession = class(TSQLRecord) private fUserLogin: TSQLUserLoginID; fSavedDate: TDateTime; fSessionData: TSQLRawBlob; published property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin; property SavedDate: TDateTime read fSavedDate write fSavedDate; property SessionData: TSQLRawBlob read fSessionData write fSessionData; end; // 6 TSQLSecurityGroup = class(TSQLRecord) private fGroupName: RawUTF8; fDescription: RawUTF8; published property GroupName: RawUTF8 read fGroupName write fGroupName; property Description: RawUTF8 read fDescription write fDescription; end; // 7 TSQLSecurityGroupPermission = class(TSQLRecord) private fGroupId: TSQLSecurityGroupID; fPermission: TSQLSecurityPermissionID; fFromDate: TDateTime; fThruDate: TDateTime; published property GroupId: TSQLSecurityGroupID read fGroupId write fGroupId; property Permission: TSQLSecurityPermissionID read fPermission write fPermission; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 8 TSQLSecurityPermission = class(TSQLRecord) private fName: RawUTF8; fDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 9 TSQLUserLoginSecurityGroup = class(TSQLRecord) private fUserLogin: TSQLUserLoginID; fGroupId: TSQLSecurityGroupID; fFromDate: TDateTime; fThruDate: TDateTime; published property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin; property GroupId: TSQLSecurityGroupID read fGroupId write fGroupId; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 10 TSQLProtectedView = class(TSQLRecord) private fGroupId: TSQLSecurityGroupID; fViewName: RawUTF8; fMaxHits: Integer; fMaxHitsDuration: Integer; fTarpitDuration: Integer; published property GroupId: TSQLSecurityGroupID read fGroupId write fGroupId; property ViewName: RawUTF8 read fViewName write fViewName; property MaxHits: Integer read fMaxHits write fMaxHits; property MaxHitsDuration: Integer read fMaxHitsDuration write fMaxHitsDuration; property TarpitDuration: Integer read fTarpitDuration write fTarpitDuration; end; // 11 TSQLTarpittedLoginView = class(TSQLRecord) private fViewName: RawUTF8; fUserLogin: TSQLUserLoginID; fTarpitReleaseDateTime: Integer; published property ViewName: RawUTF8 read fViewName write fViewName; property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin; property TarpitReleaseDateTime: Integer read fTarpitReleaseDateTime write fTarpitReleaseDateTime; end; // 12 TSQLUserLoginSecurityQuestion = class(TSQLRecord) private fQuestionEnum: TSQLEnumerationID; fUserLogin: TSQLUserLoginID; fSecurityAnswer: RawUTF8; published property QuestionEnum: TSQLEnumerationID read fQuestionEnum write fQuestionEnum; property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin; property SecurityAnswer: RawUTF8 read fSecurityAnswer write fSecurityAnswer; end; implementation end.
Unit Research; Interface Uses Regularexpressions, Math, vcl.dialogs, SysUtils; Type TOperator = record Operator: string; Used: integer; end; TOperand = record Operand: string; Used: integer; end; TProgress = record OBJ: integer; // Объект с которым идет работа Status: integer; // Статус объекта Scase: integer; end; TVariable = record Name: string; P: boolean; M: boolean; C: boolean; T: boolean; I_O: boolean; end; TIdentifier = record Name: string; OldName: string; lvl: integer; TermEnd: boolean; end; TOperators = array of TOperator; TOperands = array of TOperand; TVariables = array of TVariable; TIdentifiers = array of TIdentifier; Const COMEXP = '(\/\*[\s\S]*?(.*)\*\/)|(\/\/.*)'; OPERATOREXP = // '([a-zA-Z]([a-zA-Z0-9_$]+\.?)+(?=\())|\+{1,2}|\-{1,2}|<{0,1}={1,2}|\*{1,2}|\/|%|\/|if|=>|>{1,3}|<|>=|&{1,2}|\|{1,2}|\^|~|!{1}={0,1}|do|return|is|for|while|break|continue|switch|case|;|{|\[|\,|\.'; // '([a-zA-Z]([a-zA-Z0-9_$]+\.?)+(?=\())|\+{1,2}|\-{1,2}|<{0,1}={1,2}|\*{1,2}|\/|%|\/|if|=>|>{1,3}|<|>=|&{1,2}|\|{1,2}|\^|~|!{1}={0,1}|do|return|\+\=|\-\=|\*\=|\/\=|\%\=|\.\.|is|for|while|println|break|continue|switch|case|default|;|{|\[|\,|\.'; '([a-zA-Z]([a-zA-Z0-9_$]*\.?)+(?=\())|\?|\+\=|\-\=|\*\=|\*\*\=|\/\=|\%\=|\.\.|' + '\+{1,2}|\-{1,2}|<{0,1}={1,2}|new|\*{1,2}|\/|%|\/|if|=>|>{1,3}|<|>=|&{1,2}|\|{1,2}|\^|~|!{1}={0,1}|do|return|is|for|while|println|break|continue|switch|case|default|;|{|\[|\,|\(|\.'; KEYWORDEXP = ('\b(def|double|int|else|float|byte|short|long|Scanner|char|boolean|string|void|static|register|String|const|[\s\w]*\([\w\s,]*\)'')\b'); KEYWORDEXPUPD = ('\b(def|double|int|float|Scanner|byte|short|long|char|boolean|string|void|static|register|String|const|[\s\w]*\([\w\s,]*\)'')\b'); STRINGEXP = '("[^"]*")|(''[^'']*'')'; OPERANDEXP = // '(?<!\\)(([a-zA-Z0-9][a-zA-z0-9_$]*)+\.?)*(([a-zA-Z0-9][a-zA-z0-9_$]*)+?)+'; '\b[^() }{[\]]*\b'; FUNCTIONDEF = '\b(def|double|int|float|byte|short|long|char|boolean|string|void)[ ]{0,}[a-zA-Z1-9]{1,}\({1,}.*\)'; absOPERATOR = '(\b(for|if|while|case)\b)|\?'; { Без фигурных скобок } allOPERATOR = '\?|\+\=|\-\=|\*\=|\*\*\=|\/\=|\%\=|\.\.|\+{1,2}|\-{1,2}|<{0,1}={1,2}|new|\*{1,2}|\/|%|\/|if|=>|>{1,3}|<|>=|&{1,2}|\|{1,2}|\^|~|!{1}={0,1}|do|return|is|for|while|println|break|continue|switch|case|default|;|\[|\,|\(|\.'; CREATESCAN = 'Scanner[^;]*;'; DELSCAN = 'scanner[^;]*;'; CHEPDELSCAN = 'scanner\.close\(\);'; onlyvarOPERANDEXP = { '\b[^() }{ [\]0-9]*\b' } '\b[a-zA-Z_][a-zA-Z0-9_]*\b'; LINE = '.*'; plplminmin = '(\b[a-zA-Z_][a-zA-Z0-9_]*\b\+\+)|(\b[a-zA-Z_][a-zA-Z0-9_]*\b\-\-)|\-\-(\b[a-zA-Z_][a-zA-Z0-9_]*\b)|\+\+(\b[a-zA-Z_][a-zA-Z0-9_]*\b)'; fiws = '\b(for|while|if|switch)\b'; scanner = 'scanner.*;'; regfor = '\bfor\b'; infor = ';[^;]*;'; regifswitchwhile = '\b(if|while|switch)\b'; equally = '='; print = '\b(println|print)\b'; scannerfull = '.next(Int|Float|String|Byte|Short|Double|Char|Boolean)'; leftfor = '\([^;]*;'; isfunction = '([a-zA-Z]([a-zA-Z0-9_$]*\.?)*)\(.*\)((?=\ )|(?=\;))'; infunction = '(\(.*\)((?=\ )|(?=\;)|(?=$)))'; swapleftfor = '(def|double|int|float|byte|short|long|char|boolean|string|String)[^\;\=]*(\;|\=)'; typedef = '\b(def|double|int|float|byte|short|long|Scanner|char|boolean|string|String)\b(\[([0-9 ])*\])?[ ]'; someKey = '\b(def|double|int|else|float|byte|short|long|Scanner|char|boolean|string|void|static|register|String|const|if|switch|case|while|break|is|println|continu|default|new|(next(Int|Float|String|Byte|Short|Double|Char|Boolean)))\b'; definefunction = '\b(def|double|int|float|byte|short|long|char|boolean|string|String)\b[ ]*([a-zA-Z]([a-zA-Z0-9_$]*\.?)*)\(.*\)((?=\ )|(?=\;))'; REGW1 = 'if'; REGW2 = 'for'; REGW3 = 'else'; REGW4 = 'case'; REGW5 = 'while'; REGW6 = 'switch'; REGW7 = 'default'; REGW8 = '\;'; REGW9 = ' '; REGW10 = '\?'; REGW11 = '$'; REGW12 = '\{'; REGW13 = '\}'; REGW14 = 'break'; Var OPERATORS: TOperators; OPERANDS: TOperands; absOPERATORS, allOPERATORS: TOperators; Procedure AddToOperators(var OPERATORS: TOperators; const lexeme: string); Procedure AddToOperands(var OPERANDS: TOperands; const lexeme: string); Procedure hAnalizeCode(var text: string; var OPERATORS: TOperators; var OPERANDS: TOperands); Function jAnalizeCode(var text: string; var absOPERATORS: TOperators; var allOPERATORS: TOperators): integer; function OperatorsCount(const OPERATORS: TOperators): integer; function OperandsCount(const OPERANDS: TOperands): integer; function ProgramVolume(const pLen: integer; const pDict: integer): real; function ProgramLength(const OPERATORS: TOperators; const OPERANDS: TOperands): integer; function ProgramDict(const OPERATORS: TOperators; const OPERANDS: TOperands): integer; Function MNL(var text: string): integer; Procedure spnAnalizeCode(var text: string; var OPERATORS: TOperators; var OPERANDS: TOperands); Procedure FullChepin(var text: string; var OPERANDS: TOperands; var Result: TVariables); Procedure MinusOneOPERANDS(var OPERANDS: TOperands); Implementation function ProgramDict(const OPERATORS: TOperators; const OPERANDS: TOperands): integer; begin Result := length(OPERANDS) + length(OPERATORS); end; function ProgramLength(const OPERATORS: TOperators; const OPERANDS: TOperands): integer; begin Result := OperatorsCount(OPERATORS) + OperandsCount(OPERANDS); end; function ProgramVolume(const pLen: integer; const pDict: integer): real; begin if pDict <> 0 then Result := pLen * Log2(pDict) else Result := 0; end; function OperatorsCount(const OPERATORS: TOperators): integer; var i: integer; begin Result := 0; for i := 0 to length(OPERATORS) - 1 do begin Result := Result + OPERATORS[i].Used; end; end; function OperandsCount(const OPERANDS: TOperands): integer; var i: integer; begin Result := 0; for i := 0 to length(OPERANDS) - 1 do begin Result := Result + OPERANDS[i].Used; end; end; Procedure InitOperators(var OPERATORS: TOperators); begin SetLength(OPERATORS, 0); end; Procedure InitOperands(var OPERANDS: TOperands); begin SetLength(OPERANDS, 0); end; Procedure AddToOperands(var OPERANDS: TOperands; const lexeme: string); begin SetLength(OPERANDS, length(OPERANDS) + 1); OPERANDS[length(OPERANDS) - 1].Operand := lexeme; OPERANDS[length(OPERANDS) - 1].Used := 1; end; Procedure AddToOperators(var OPERATORS: TOperators; const lexeme: string); begin SetLength(OPERATORS, length(OPERATORS) + 1); OPERATORS[length(OPERATORS) - 1].Operator := lexeme; OPERATORS[length(OPERATORS) - 1].Used := 1; end; Procedure DelComments(var text: string); var _regexp: TRegEx; begin _regexp := TRegEx.Create(COMEXP); text := _regexp.Replace(text, ' '); end; Procedure DelKeywords(var text: string); var _regexp: TRegEx; begin _regexp := TRegEx.Create(KEYWORDEXP); text := _regexp.Replace(text, ' '); end; Procedure jDelKeywords(var text: string); var _regexp: TRegEx; begin _regexp := TRegEx.Create(KEYWORDEXPUPD); text := _regexp.Replace(text, ''); end; Procedure Delfunctiondef(var text: string); var _regexp: TRegEx; begin _regexp := TRegEx.Create(FUNCTIONDEF); text := _regexp.Replace(text, ' '); end; Procedure DelStrings(var text: string; var OPERANDS: TOperands); var _regexp: TRegEx; temp: TMatchCollection; i: integer; j: integer; flag: boolean; begin _regexp := TRegEx.Create(STRINGEXP); temp := _regexp.Matches(text); text := _regexp.Replace(text, ' '); for i := 0 to temp.Count - 1 do begin flag := false; j := 0; while (j < length(OPERANDS)) and (not(flag)) do begin if temp.Item[i].Value = OPERANDS[j].Operand then begin flag := true; OPERANDS[j].Used := OPERANDS[j].Used + 1; end; j := j + 1; end; if not(flag) then AddToOperands(OPERANDS, temp.Item[i].Value); end; end; Procedure spnDelStrings(var text: string; OPERANDS: TOperands); var _regexp: TRegEx; begin _regexp := TRegEx.Create(STRINGEXP); text := _regexp.Replace(text, ' '); end; Procedure DelOperands(var text: string; var OPERANDS: TOperands); var _regexp: TRegEx; temp: TMatchCollection; i: integer; j: integer; flag: boolean; begin _regexp := TRegEx.Create(OPERANDEXP); temp := _regexp.Matches(text); text := _regexp.Replace(text, ' '); for i := 0 to temp.Count - 1 do begin flag := false; j := 0; while (j < length(OPERANDS)) and (not(flag)) do begin if temp.Item[i].Value = OPERANDS[j].Operand then begin flag := true; OPERANDS[j].Used := OPERANDS[j].Used + 1; end; j := j + 1; end; if not(flag) then AddToOperands(OPERANDS, temp.Item[i].Value); end; end; Procedure varDelOperands(var text: string; var OPERANDS: TOperands); var _regexp: TRegEx; temp: TMatchCollection; i: integer; j: integer; flag: boolean; begin _regexp := TRegEx.Create(onlyvarOPERANDEXP); temp := _regexp.Matches(text); text := _regexp.Replace(text, ' '); for i := 0 to temp.Count - 1 do begin flag := false; j := 0; while (j < length(OPERANDS)) and (not(flag)) do begin if temp.Item[i].Value = OPERANDS[j].Operand then begin flag := true; OPERANDS[j].Used := OPERANDS[j].Used + 1; end; j := j + 1; end; if not(flag) then AddToOperands(OPERANDS, temp.Item[i].Value); end; end; Procedure DelOperators(var text: string; var OPERATORS: TOperators); var _regexp: TRegEx; temp: TMatchCollection; i: integer; j: integer; strbuf: string; flag: boolean; begin _regexp := TRegEx.Create(OPERATOREXP); temp := _regexp.Matches(text); text := _regexp.Replace(text, ' '); for i := 0 to temp.Count - 1 do begin flag := false; j := 0; while (j < length(OPERATORS)) and (not(flag)) do begin strbuf := temp.Item[i].Value; if '{' = strbuf then begin strbuf := strbuf + '}'; end; if '?' = strbuf then begin strbuf := strbuf + ':'; end; if strbuf = 'do' then begin strbuf := strbuf + '...while'; end; if strbuf = '[' then begin strbuf := strbuf + ']'; end; if strbuf = '(' then begin strbuf := strbuf + ')'; end; if strbuf = OPERATORS[j].Operator then begin flag := true; OPERATORS[j].Used := OPERATORS[j].Used + 1; end; j := j + 1; end; if not(flag) then AddToOperators(OPERATORS, strbuf); end; end; Procedure jabsFindOperators(text: string; var OPERATORS: TOperators); var _regexp: TRegEx; temp: TMatchCollection; i: integer; j: integer; strbuf: string; flag: boolean; begin _regexp := TRegEx.Create(absOPERATOR); temp := _regexp.Matches(text); text := _regexp.Replace(text, ' '); for i := 0 to temp.Count - 1 do begin flag := false; j := 0; while (j < length(OPERATORS)) and (not(flag)) do begin strbuf := temp.Item[i].Value; if '?' = strbuf then begin strbuf := strbuf + ':'; end; if strbuf = OPERATORS[j].Operator then begin flag := true; OPERATORS[j].Used := OPERATORS[j].Used + 1; end; j := j + 1; end; if not(flag) then AddToOperators(OPERATORS, strbuf); end; end; Procedure jallFindOperators(text: string; var OPERATORS: TOperators); var _regexp: TRegEx; temp: TMatchCollection; i: integer; j: integer; strbuf: string; flag: boolean; begin _regexp := TRegEx.Create(allOPERATOR); temp := _regexp.Matches(text); text := _regexp.Replace(text, ' '); for i := 0 to temp.Count - 1 do begin flag := false; j := 0; while (j < length(OPERATORS)) and (not(flag)) do begin strbuf := temp.Item[i].Value; if '{' = strbuf then begin strbuf := strbuf + '}'; end; if '?' = strbuf then begin strbuf := strbuf + ':'; end; if strbuf = '[' then begin strbuf := strbuf + ']'; end; if strbuf = '(' then begin strbuf := strbuf + ')'; end; if strbuf = OPERATORS[j].Operator then begin flag := true; OPERATORS[j].Used := OPERATORS[j].Used + 1; end; j := j + 1; end; if not(flag) then AddToOperators(OPERATORS, strbuf); end; end; Procedure Delscaner(var text: string); var _regexp: TRegEx; begin _regexp := TRegEx.Create(CREATESCAN); text := _regexp.Replace(text, ' '); _regexp := TRegEx.Create(DELSCAN); text := _regexp.Replace(text, ' '); end; Procedure CHEPDelscaner(var text: string); var _regexp: TRegEx; begin _regexp := TRegEx.Create(CREATESCAN); text := _regexp.Replace(text, ' '); _regexp := TRegEx.Create(CHEPDELSCAN); text := _regexp.Replace(text, ' '); end; Procedure hAnalizeCode(var text: string; var OPERATORS: TOperators; var OPERANDS: TOperands); begin InitOperands(OPERANDS); InitOperators(OPERATORS); DelComments(text); Delfunctiondef(text); DelStrings(text, OPERANDS); // showmessage(text); DelKeywords(text); // showmessage(text); DelOperators(text, OPERATORS); // showmessage(text); DelOperands(text, OPERANDS); // showmessage(text); end; Function jAnalizeCode(var text: string; var absOPERATORS: TOperators; var allOPERATORS: TOperators): integer; begin InitOperators(absOPERATORS); InitOperators(allOPERATORS); InitOperands(OPERANDS); DelComments(text); Delfunctiondef(text); DelStrings(text, OPERANDS); jDelKeywords(text); { Подсчет условных операторов } jabsFindOperators(text, absOPERATORS); { Общее количество операторов } jallFindOperators(text, allOPERATORS); { Максимальный уровень вложенности } Result := MNL(text); end; Function ReadOneLexeme(var text: string; var numofobj: integer; var nos: integer): string; { Возвращает результат чтения 0 - успешное чтение 1 - конец строки numofobj: REGW1 = 'if'; REGW2 = 'for'; REGW3 = 'else'; REGW4 = 'case:'; REGW5 = 'while()'; REGW14 = 'break'; REGW6 = 'switch{'; REGW7 = 'default:'; REGW8 = '\;'; REGW9 = ' '; REGW10 = '\?'; REGW11 = '#13#10'; REGW12 = '{'; REGW13 = ' }{ '; 15 = sometxt } var fl: boolean; resstr: string; _regexp: TRegEx; sk: integer; dfl: boolean; begin fl := true; resstr := ''; while (fl) and (nos <= length(text)) do begin resstr := resstr + text[nos]; inc(nos); if (_regexp.IsMatch(resstr, REGW1)) then begin numofobj := 1; fl := false; sk := 0; dfl := false; repeat resstr := resstr + text[nos]; if text[nos] = '(' then begin inc(sk); dfl := true; end; if text[nos] = ')' then dec(sk); inc(nos); until (sk = 0) and dfl = true; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW2)) then begin numofobj := 2; fl := false; sk := 0; dfl := false; repeat resstr := resstr + text[nos]; if text[nos] = '(' then begin inc(sk); dfl := true; end; if text[nos] = ')' then dec(sk); inc(nos); until (sk = 0) and dfl = true; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW3)) then begin numofobj := 3; fl := false; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW4)) then begin numofobj := 4; fl := false; dfl := false; while dfl = false do begin resstr := resstr + text[nos]; inc(nos); if text[nos - 1] = ':' then dfl := true; end; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW5)) then begin numofobj := 5; fl := false; sk := 0; dfl := false; repeat resstr := resstr + text[nos]; if text[nos] = '(' then begin inc(sk); dfl := true; end; if text[nos] = ')' then dec(sk); inc(nos); until (sk = 0) and dfl = true; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW14)) then begin numofobj := 14; fl := false; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW6)) then begin numofobj := 6; fl := false; dfl := false; while dfl = false do begin resstr := resstr + text[nos]; inc(nos); if (text[nos - 1] = '{') then dfl := true; end; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW7)) then begin numofobj := 7; fl := false; while dfl = false do begin resstr := resstr + text[nos]; inc(nos); if text[nos - 1] = ':' then dfl := true; end; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW8)) then begin if length(resstr) = 1 then begin numofobj := 8; end else begin dec(nos); SetLength(resstr, length(resstr) - 1); numofobj := 15; end; fl := false; Result := resstr; Continue; end; if ((_regexp.IsMatch(resstr, REGW9)) or (resstr[length(resstr)] = #0)) then begin if length(resstr) = 1 then begin while (text[nos] = ' ') or (text[nos] = #0) do begin resstr := resstr + text[nos]; inc(nos); end; numofobj := 9; end else begin dec(nos); SetLength(resstr, length(resstr) - 1); numofobj := 15; end; fl := false; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW10)) then begin if length(resstr) = 1 then begin numofobj := 10; end else begin dec(nos); SetLength(resstr, length(resstr) - 1); numofobj := 15; end; fl := false; Result := resstr; Continue; end; if ((resstr[length(resstr) - 1] = #13) and (resstr[length(resstr)] = #10)) then begin if length(resstr) = 2 then begin numofobj := 11; end else begin dec(nos); dec(nos); SetLength(resstr, length(resstr) - 1); numofobj := 15; end; fl := false; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW12)) then begin if length(resstr) = 1 then begin numofobj := 12; end else begin dec(nos); SetLength(resstr, length(resstr) - 1); numofobj := 15; end; fl := false; Result := resstr; Continue; end; if (_regexp.IsMatch(resstr, REGW13)) then begin if length(resstr) = 1 then begin numofobj := 13; end else begin dec(nos); SetLength(resstr, length(resstr) - 1); numofobj := 15; end; fl := false; Result := resstr; Continue; end; end; end; Function MNL(var text: string): integer; { MNL - Maximum Nesting Level } { IF OBJ = 1 //Объект IF Status = 1 //Ожидается { или #13#10 Status = 2 //введен {, ожидать } { Status = 3 //введен #13#10,ждем ; или #13#10 Status = 4 //веден }{ |#13#10|; ожидаем sometxt | else {else } { Status = 5 //введен else, Ожидается { или #13#10 Status = 6 //введен { ожидается } { Status = 7 //введен #13#10,ждем ; или #13#10 FOR OBJ = 2 // Объект For Status = 1 // Ожидаем { | #13#10 | ; Status = 2 // Введен ; --> конец без ветвления Status = 3 // Введен { ожидание } { Status = 4 // Введен #13#10 ожидание ; | #13#10 while OBJ = 3 // Объект while Status = 1 // Ожидаем { | #13#10 | ; Status = 2 // Введен { ожидание } { Status = 3 // Введен #13#10 ожидание ; | #13#10 Switch OBJ = 4 // Объект switch Status = 1 // Ожидаем case: | default: | } { Status = 2 // Введен case: ожидаем break Status = 1 // Введен break, ожидаем: case | default | } { } var nos, numofobj: integer; wait: boolean; Mass: array of TProgress; tmpres: integer; str: string; begin Result := 0; tmpres := 0; while (nos <= length(text)) do begin numofobj := 0; str := ReadOneLexeme(text, numofobj, nos); if numofobj = 1 then begin SetLength(Mass, length(Mass) + 1); Mass[length(Mass) - 1].OBJ := 1; Mass[length(Mass) - 1].Status := 1; inc(tmpres); if tmpres > Result then Result := tmpres; end; if numofobj = 2 then begin if length(Mass) <> 0 then begin inc(tmpres); if tmpres > Result then Result := tmpres; end; SetLength(Mass, length(Mass) + 1); Mass[length(Mass) - 1].OBJ := 2; Mass[length(Mass) - 1].Status := 1; end; if numofobj = 5 then begin if length(Mass) <> 0 then begin inc(tmpres); if tmpres > Result then Result := tmpres; end; SetLength(Mass, length(Mass) + 1); Mass[length(Mass) - 1].OBJ := 3; Mass[length(Mass) - 1].Status := 1; end; if numofobj = 6 then begin SetLength(Mass, length(Mass) + 1); Mass[length(Mass) - 1].OBJ := 4; Mass[length(Mass) - 1].Status := 1; Mass[length(Mass) - 1].Scase := 0; end; wait := true; repeat if length(Mass) > 0 then begin case Mass[length(Mass) - 1].OBJ of 1: { IF } begin case Mass[length(Mass) - 1].Status of 1: begin if numofobj = 12 then Mass[length(Mass) - 1].Status := 2; if numofobj = 11 then Mass[length(Mass) - 1].Status := 3; wait := true; end; 2: begin if numofobj = 13 then begin Mass[length(Mass) - 1].Status := 4; if (length(Mass) > 0) then dec(tmpres); end; wait := true; end; 3: begin if (numofobj = 8) or (numofobj = 11) then begin Mass[length(Mass) - 1].Status := 4; if (length(Mass) > 0) then dec(tmpres); end; if numofobj = 12 then Mass[length(Mass) - 1].Status := 2; wait := true; end; 4: begin if (numofobj in [1, 2, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]) then begin SetLength(Mass, length(Mass) - 1); wait := false; end; if (numofobj = 15) then begin SetLength(Mass, length(Mass) - 1); wait := true; end; if numofobj = 3 then begin Mass[length(Mass) - 1].Status := 5; wait := true; end; end; 5: begin if numofobj = 12 then begin // inc(tmpres); if tmpres > Result then Result := tmpres; Mass[length(Mass) - 1].Status := 6; end; if numofobj = 11 then begin Mass[length(Mass) - 1].Status := 7; // inc(tmpres); if tmpres > Result then Result := tmpres; end; wait := true; end; 6: begin if numofobj = 13 then begin SetLength(Mass, length(Mass) - 1); // dec(tmpres); end; wait := true; end; 7: begin if (numofobj = 8) or (numofobj = 11) then begin SetLength(Mass, length(Mass) - 1); // dec(tmpres); end; wait := true; if numofobj = 12 then Mass[length(Mass) - 1].Status := 6; end; end; end; 2: { FOR } begin case Mass[length(Mass) - 1].Status of 1: begin if numofobj = 8 then begin Mass[length(Mass) - 1].Status := 2; SetLength(Mass, length(Mass) - 1); dec(tmpres); end; if numofobj = 12 then Mass[length(Mass) - 1].Status := 3; if numofobj = 11 then Mass[length(Mass) - 1].Status := 4; wait := true; end; 3: begin if numofobj = 13 then begin SetLength(Mass, length(Mass) - 1); if (length(Mass) > 0) then dec(tmpres); end; wait := true; end; 4: begin if (numofobj = 8) or (numofobj = 11) then begin SetLength(Mass, length(Mass) - 1); if (length(Mass) > 0) then dec(tmpres); end; if numofobj = 12 then Mass[length(Mass) - 1].Status := 3; wait := true; end; end; end; 3: { WHILE } begin case Mass[length(Mass) - 1].Status of 1: begin if numofobj = 12 then Mass[length(Mass) - 1].Status := 2; if numofobj = 11 then Mass[length(Mass) - 1].Status := 3; wait := true; end; 2: begin if numofobj = 13 then begin SetLength(Mass, length(Mass) - 1); if (length(Mass) > 0) then dec(tmpres); end; wait := true; end; 3: begin if (numofobj = 8) or (numofobj = 11) then begin SetLength(Mass, length(Mass) - 1); if (length(Mass) > 0) then dec(tmpres); end; if numofobj = 12 then Mass[length(Mass) - 1].Status := 2; wait := true; end; end; end; 4: { SWITCH } begin case Mass[length(Mass) - 1].Status of 1: begin if (numofobj = 4) or (numofobj = 7) then begin Mass[length(Mass) - 1].Status := 2; if numofobj = 4 then begin inc(tmpres); inc(Mass[length(Mass) - 1].Scase); if tmpres > Result then Result := tmpres; end; end; wait := true; if (numofobj = 13) then begin tmpres := tmpres - Mass[length(Mass) - 1].Scase; SetLength(Mass, length(Mass) - 1); end; wait := true; end; 2: begin if numofobj = 14 then begin Mass[length(Mass) - 1].Status := 1; end; if numofobj = 13 then begin tmpres := tmpres - Mass[length(Mass) - 1].Scase; SetLength(Mass, length(Mass) - 1); end; wait := true; end; end; end; else begin wait := true; end; end; end else begin wait := true; end; until wait = true; end; end; Procedure AddInID(var Identifiers: TIdentifiers; const id: string; const lvl: integer); var num: integer; i: integer; j: integer; _regexp: TRegEx; swap: boolean; begin _regexp.Create(someKey); if not _regexp.IsMatch(id) then begin swap := false; if length(Identifiers) <> 0 then begin for i := 0 to length(Identifiers) - 1 do begin if Identifiers[i].OldName = id then begin num := 0; for j := i to length(Identifiers) - 1 do begin if Identifiers[j].OldName = id then inc(num); end; SetLength(Identifiers, length(Identifiers) + 1); Identifiers[length(Identifiers) - 1].Name := id + '_' + inttostr(num); Identifiers[length(Identifiers) - 1].OldName := id; Identifiers[length(Identifiers) - 1].lvl := lvl; Identifiers[length(Identifiers) - 1].TermEnd := false; swap := true; break; end else begin if (Identifiers[i].Name = id) and (Identifiers[i].OldName <> id) then begin num := 0; for j := i to length(Identifiers) - 1 do begin SetLength(Identifiers, length(Identifiers) + 1); Identifiers[length(Identifiers) - 1].Name := id + '_' + inttostr(num); Identifiers[length(Identifiers) - 1].OldName := id; Identifiers[length(Identifiers) - 1].lvl := lvl; Identifiers[length(Identifiers) - 1].TermEnd := false; swap := true; break; end; end; end; end; if swap = false then begin SetLength(Identifiers, length(Identifiers) + 1); Identifiers[length(Identifiers) - 1].Name := id; Identifiers[length(Identifiers) - 1].OldName := id; Identifiers[length(Identifiers) - 1].lvl := lvl; Identifiers[length(Identifiers) - 1].TermEnd := false; end; end else begin SetLength(Identifiers, 1); Identifiers[0].Name := id; Identifiers[0].OldName := id; Identifiers[0].lvl := lvl; Identifiers[0].TermEnd := false; end; end; end; Procedure FixLVLS(var Identifiers: TIdentifiers; const lvl: integer); var i: integer; begin for i := 0 to length(Identifiers) - 1 do begin if Identifiers[i].lvl > lvl then begin Identifiers[i].TermEnd := true; end; end; end; Function FindID(const Identifiers: TIdentifiers; const lvl: integer; const s: string): integer; var i: integer; begin Result := -1; for i := length(Identifiers) - 1 downto 0 do begin if Identifiers[i].TermEnd = false then begin if Identifiers[i].OldName = s then begin Result := i; break; end; end; end; end; Procedure SwapInLine(var s: string; Const Identifiers: TIdentifiers; const lvl: integer); var _regexp, _regexp2: TRegEx; Matches: TMatchCollection; i: integer; tmp: integer; begin _regexp.Create(onlyvarOPERANDEXP); Matches := _regexp.Matches(s); for i := 0 to Matches.Count - 1 do begin tmp := FindID(Identifiers, lvl, Matches.Item[i].Value); if tmp <> -1 then begin _regexp2.Create('\b'+Matches.Item[i].Value+'\b'); s := _regexp2.Replace(s, Identifiers[tmp].Name); end; end; end; Procedure SwapIdentifiers(var text: string); var Identifiers: TIdentifiers; _regexp: TRegEx; Matches, Matches2: TMatchCollection; lvl: integer; i, j: integer; s: string; str: string; newtext: string; begin lvl := 0; newtext := ''; _regexp.Create(LINE); Matches := _regexp.Matches(text); for i := 0 to Matches.Count - 1 do begin s := Matches[i].Value; _regexp.Create(regfor); // for if _regexp.IsMatch(s) then begin _regexp.Create(swapleftfor); if _regexp.IsMatch(s) then begin str := _regexp.Matches(s).Item[0].Value; _regexp.Create(onlyvarOPERANDEXP); Matches2 := _regexp.Matches(str); for j := 0 to Matches2.Count - 1 do begin AddInID(Identifiers, Matches2.Item[j].Value, lvl + 1); end; SwapInLine(s, Identifiers, lvl); end; end else begin _regexp.Create(definefunction); if _regexp.IsMatch(s) then begin str := _regexp.Matches(s).Item[0].Value; _regexp.Create(infunction); str := _regexp.Matches(str).Item[0].Value; _regexp.Create(onlyvarOPERANDEXP); Matches2 := _regexp.Matches(str); for j := 0 to Matches2.Count - 1 do begin AddInID(Identifiers, Matches2.Item[j].Value, lvl + 1); end; SwapInLine(s, Identifiers, lvl); end else begin _regexp.Create(typedef); if _regexp.IsMatch(s) then begin _regexp.Create(onlyvarOPERANDEXP); Matches2 := _regexp.Matches(s); for j := 0 to Matches2.Count - 1 do begin AddInID(Identifiers, Matches2.Item[j].Value, lvl); end; SwapInLine(s, Identifiers, lvl); end else begin _regexp.Create(onlyvarOPERANDEXP); if _regexp.IsMatch(s) then begin SwapInLine(s, Identifiers, lvl); end; end; end; end; _regexp.Create('{'); if _regexp.IsMatch(s) then begin inc(lvl); end; _regexp.Create('}'); if _regexp.IsMatch(s) then begin dec(lvl); FixLVLS(Identifiers, lvl); end; newtext := newtext + #13#10 + s; end; //ShowMessage(newtext); text := newtext; end; Procedure MinusOneOPERANDS(var OPERANDS: TOperands); var i: integer; begin for i := 0 to length(OPERANDS) do dec(OPERANDS[i].Used); end; Procedure spnAnalizeCode(var text: string; var OPERATORS: TOperators; var OPERANDS: TOperands); var tmp: string; begin InitOperands(OPERANDS); InitOperators(OPERATORS); DelComments(text); CHEPDelscaner(text); spnDelStrings(text, OPERANDS); { Место для свапа } SwapIdentifiers(text); tmp := text; // Delfunctiondef(text); // showmessage(text); DelKeywords(text); // showmessage(text); DelOperators(text, OPERATORS); // showmessage(text); varDelOperands(text, OPERANDS); // showmessage(text); text := tmp; end; Procedure InitVariables(var OPERANDS: TOperands; var Variables: TVariables); var i: integer; begin SetLength(Variables, 0); for i := 0 to length(OPERANDS) - 1 do begin SetLength(Variables, length(Variables) + 1); Variables[i].Name := OPERANDS[i].Operand; Variables[i].P := false; Variables[i].M := false; Variables[i].C := false; Variables[i].T := true; Variables[i].I_O := false; end; end; Function FindNumInVariables(const s: string; const Variables: TVariables): integer; var i: integer; begin Result := -1; for i := 0 to length(Variables) - 1 do begin if s = Variables[i].Name then begin Result := i; break; end; end; end; Procedure LineTo2Line(const s: string; const equalpos: integer; var left, right: string); var i: integer; fl: boolean; begin SetLength(left, 0); SetLength(right, 0); fl := false; for i := 1 to length(s) do begin if not fl then begin if i <> equalpos then begin left := left + s[i]; end else begin fl := true; end; end else begin right := right + s[i]; end; end; end; Procedure SwitchTagVar(var Variable: TVariable; const tag: integer); // ---------------ТЕГИ---------------- // 1 - не T - Паразитные // 2 - C - Управление программой // 3 - M - Модифицируемые но не C // 4 - P - Вводимые но не M и не C // 5 - I/O переменная // 6 - Не P // Возможные сочетания {P,PT,M,MT,C,T} // ----------------------------------- begin case tag of 1: // not T begin Variable.T := false; end; 2: // C begin Variable.T := false; Variable.P := false; Variable.M := false; Variable.C := true; end; 3: // M begin if (Variable.C = false) and (Variable.P = false) then begin Variable.M := true; end; end; 4: // P begin if (Variable.C = false) and (Variable.M = false) then begin Variable.P := true; end; end; 5: // I/O begin Variable.I_O := true; end; 6: // not P begin Variable.P := false; end; end; end; Procedure LeftRightCheck(const left, right: string; var Variables: TVariables); var _regexp: TRegEx; Matches, Matches2: TMatchCollection; i: integer; LeftVariable: TVariable; tmp: integer; begin _regexp.Create(onlyvarOPERANDEXP); Matches := _regexp.Matches(left); tmp := FindNumInVariables(Matches.Item[0].Value, Variables); if tmp <> -1 then begin LeftVariable := Variables[tmp]; end; Matches2 := _regexp.Matches(right); for i := 0 to Matches2.Count - 1 do begin if Matches2.Item[i].Value <> LeftVariable.Name then begin tmp := FindNumInVariables(Matches2.Item[i].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 3); SwitchTagVar(Variables[tmp], 1); end; end else begin tmp := FindNumInVariables(Matches2.Item[i].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 6); SwitchTagVar(Variables[tmp], 3); end; end; end; for i := 0 to Matches.Count - 1 do begin if i = 0 then begin tmp := FindNumInVariables(Matches.Item[i].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 6); SwitchTagVar(Variables[tmp], 3); end; end else begin tmp := FindNumInVariables(Matches.Item[i].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 2); end; end; end; end; Procedure LineCheckFullCHepin(const s: string; var Variables: TVariables); var _regexp: TRegEx; Matches: TMatchCollection; i: integer; str: string; leftstr, rightstr: string; tmp: integer; begin _regexp.Create(onlyvarOPERANDEXP); // Если найдены операнды if _regexp.IsMatch(s) then begin _regexp.Create(scannerfull); // Найден ввод if _regexp.IsMatch(s) then begin _regexp.Create(onlyvarOPERANDEXP); tmp := FindNumInVariables(_regexp.Matches(s).Item[0].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 4); SwitchTagVar(Variables[tmp], 5); end; end else begin _regexp.Create(fiws); // Если найден for|if|while|switch if _regexp.IsMatch(s) then begin _regexp.Create(regfor); // Найден именно for if _regexp.IsMatch(s) then begin _regexp.Create(infor); str := _regexp.Matches(s).Item[0].Value; _regexp.Create(onlyvarOPERANDEXP); Matches := _regexp.Matches(str); // Погружаемся в условие у for for i := 0 to Matches.Count - 1 do begin tmp := FindNumInVariables(Matches.Item[i].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 2); end; end; _regexp.Create(leftfor); str := _regexp.Matches(s).Item[0].Value; if _regexp.IsMatch(s) then begin LineTo2Line(str, pos(equally, str), leftstr, rightstr); LeftRightCheck(leftstr, rightstr, Variables); end; end else begin _regexp.Create(regifswitchwhile); // Найден именно if|switch|while if _regexp.IsMatch(s) then begin _regexp.Create(onlyvarOPERANDEXP); Matches := _regexp.Matches(s); for i := 0 to Matches.Count - 1 do begin tmp := FindNumInVariables(Matches.Item[i].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 2); end; end; end; end; end else begin _regexp.Create(equally); // Найдено присваивание if _regexp.IsMatch(s) then begin LineTo2Line(s, pos(equally, s), leftstr, rightstr); LeftRightCheck(leftstr, rightstr, Variables); end else begin _regexp.Create(print); // Найден println if _regexp.IsMatch(s) then begin _regexp.Create(onlyvarOPERANDEXP); Matches := _regexp.Matches(s); for i := 0 to Matches.Count - 1 do begin tmp := FindNumInVariables(Matches.Item[i].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 1); SwitchTagVar(Variables[tmp], 3); SwitchTagVar(Variables[tmp], 5); end; end; end else begin _regexp.Create(isfunction); if _regexp.IsMatch(s) then begin str := _regexp.Matches(s).Item[0].Value; _regexp.Create(infunction); str := _regexp.Matches(str).Item[0].Value; _regexp.Create(onlyvarOPERANDEXP); Matches := _regexp.Matches(str); for i := 0 to Matches.Count - 1 do begin tmp := FindNumInVariables(Matches.Item[i].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 1); SwitchTagVar(Variables[tmp], 3); end; end; end; end; end; end; end; _regexp.Create(plplminmin); if _regexp.IsMatch(s) then begin Matches := _regexp.Matches(s); _regexp.Create(onlyvarOPERANDEXP); for i := 0 to Matches.Count - 1 do begin tmp := FindNumInVariables(_regexp.Matches(Matches[i].Value) .Item[0].Value, Variables); if tmp <> -1 then begin SwitchTagVar(Variables[tmp], 6); SwitchTagVar(Variables[tmp], 3); end; end; end end; end; Procedure FullChepin(var text: string; var OPERANDS: TOperands; var Result: TVariables); var Matches: TMatchCollection; i: integer; _regexp: TRegEx; begin InitVariables(OPERANDS, Result); DelComments(text); Delfunctiondef(text); CHEPDelscaner(text); spnDelStrings(text, OPERANDS); DelKeywords(text); _regexp.Create(LINE); Matches := _regexp.Matches(text); for i := 0 to Matches.Count - 1 do begin LineCheckFullCHepin(Matches.Item[i].Value, Result); end; end; End.
unit UsesFixMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TUsesFixMainForm = class(TForm) LabeledEditDprFileName: TLabeledEdit; Button1: TButton; OpenDialog1: TOpenDialog; ButtonFix: TButton; LabelSearchPath: TLabel; MemoSearchPath: TMemo; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ButtonFixClick(Sender: TObject); private FCurrentDir: string; procedure ReadConfiguration; procedure SaveConfiguration; public { Public declarations } end; var UsesFixMainForm: TUsesFixMainForm; implementation uses IniFiles, StrUtils, PathUtils, SrcUtils; {$R *.dfm} procedure TUsesFixMainForm.ButtonFixClick(Sender: TObject); begin {$IFDEF DEBUG} ShowMessage('DEBUG defined'); {$ENDIF} {$IFDEF NDEBUG} ShowMessage('NDEBUG defined'); {$ENDIF} Exit; RemoveComments('Test.pas'); Exit; ShowMessage(RelativePathToAbsolute(FCurrentDir, MemoSearchPath.Lines[0])); ShowMessage(AbsolutePathToRelative(FCurrentDir, MemoSearchPath.Lines[1])); end; procedure TUsesFixMainForm.FormCreate(Sender: TObject); begin FCurrentDir := ExcludeTrailingPathDelimiter(GetCurrentDir); ReadConfiguration; end; procedure TUsesFixMainForm.FormDestroy(Sender: TObject); begin SaveConfiguration; end; procedure TUsesFixMainForm.ReadConfiguration; var IniFile: TIniFile; PathList: TStringList; begin IniFile := TIniFile.Create(FCurrentDir + '\UsesFix.ini'); try LabeledEditDprFileName.Text := IniFile.ReadString('Default', 'DprFileName', ''); PathList := TStringList.Create; try PathList.CommaText := IniFile.ReadString('Default', 'SearchPath', ''); MemoSearchPath.Lines.Clear; MemoSearchPath.Lines.AddStrings(PathList); finally FreeAndNil(PathList); end; finally FreeAndNil(IniFile); end; end; procedure TUsesFixMainForm.SaveConfiguration; var IniFile: TIniFile; PathList: TStringList; begin IniFile := TIniFile.Create(FCurrentDir + '\UsesFix.ini'); try IniFile.WriteString('Default', 'DprFileName', LabeledEditDprFileName.Text); PathList := TStringList.Create; try PathList.AddStrings(MemoSearchPath.Lines); IniFile.WriteString('Default', 'SearchPath', PathList.CommaText); finally FreeAndNil(PathList); end; finally FreeAndNil(IniFile); end; end; end.
(* ulist.pas -- (c) 1989 by Tom Swan *) unit ulist; interface uses uitem; type listPtr = ^list; list = object( item ) anchor : itemPtr; { Addresses list head } cip : itemPtr; { Current item pointer } constructor init; destructor done; virtual; function listEmpty : Boolean; function atHeadOfList : Boolean; function atEndOfList : Boolean; function currentItem : itemPtr; procedure prevItem; procedure nextItem; procedure resetList; procedure insertItem( ip : itemPtr ); virtual; procedure removeItem( ip : itemPtr ); virtual; procedure processItems; virtual; procedure disposeList; virtual; end; implementation { ----- Initialize an empty list. } constructor list.init; begin anchor := nil; cip := nil; item.init; end; { ----- Dispose any listed items and the list object itself. } destructor list.done; begin if anchor <> nil then disposeList; item.done; end; { ----- Return true if list is empty. } function list.listEmpty : Boolean; begin listEmpty := ( anchor = nil ); end; { ----- Return true if current item is at the head of the list. } function list.atHeadOfList : Boolean; begin atHeadOfList := ( anchor <> nil ) and ( cip = anchor ); end; { ----- Return true if current item is at the end of the list. } function list.atEndOfList : Boolean; begin atEndOfList := ( anchor <> nil ) and ( cip = anchor^.left ); end; { ----- Return item addressed by current item pointer (cip). } function list.currentItem : itemPtr; begin currentItem := cip; end; { ----- Move current pointer to previous item in list. } procedure list.prevItem; begin if cip <> nil then cip := cip^.left; end; { ----- Move current pointer to next item in list. } procedure list.nextItem; begin if cip <> nil then cip := cip^.right; end; { ----- Reset list. currentItem will return first item inserted. } procedure list.resetList; begin cip := anchor; end; { ----- Insert item addressed by ip ahead of current item. } procedure list.insertItem( ip : itemPtr ); begin if ip <> nil then { Prevent out-of-memory disasters } if anchor = nil then { If list is empty ... } begin anchor := ip; { then start a new list } resetList; { and initialize current item } end else ip^.link( cip ); { else link item into list at cip } end; { ----- Remove listed item addressed by ip and adjust anchor if necessary to make sure that anchor and cip don't address the removed item. } procedure list.removeItem( ip : itemPtr ); begin if ip^.right = ip then { If only one list item ... } begin anchor := nil; { then empty the list } cip := nil; end else { else adjust anchor and cip } begin if ip = anchor then anchor := anchor^.right; if cip = ip then cip := cip^.right; end; ip^.unlink; end; { ----- Process all listed items. } procedure list.processItems; begin resetList; if currentItem <> nil then repeat currentItem^.processItem; nextItem; until atHeadOfList; end; { ----- Dispose items in a list. } procedure list.disposeList; var ip : itemPtr; begin while not listEmpty do begin ip := currentItem; removeItem( ip ); if ( seg( ip^ ) <> DSeg ) and ( seg( ip^ ) <> SSeg ) then dispose( ip, done ) else ip^.done; end; { while } end; end.
{ *********************************************************************** } { } { Delphi Runtime Library } { } { Copyright (c) 1996-2001 Borland Software Corporation } { } { *********************************************************************** } {*******************************************************} { Win32 flat scrollbar interface unit } {*******************************************************} unit FlatSB; //{$WEAKPACKAGEUNIT} interface uses Windows; function InitializeFlatSB(hWnd: HWND): Bool; stdcall; {$EXTERNALSYM InitializeFlatSB} procedure UninitializeFlatSB(hWnd: HWND); stdcall; {$EXTERNALSYM UninitializeFlatSB} function FlatSB_GetScrollProp(p1: HWND; propIndex: Integer; p3: PInteger): Bool; stdcall; {$EXTERNALSYM FlatSB_GetScrollProp} function FlatSB_SetScrollProp(p1: HWND; index: Integer; newValue: Integer; p4: Bool): Bool; stdcall; {$EXTERNALSYM FlatSB_SetScrollProp} var FlatSB_EnableScrollBar: function(hWnd: HWND; wSBflags, wArrows: UINT): BOOL; stdcall; {$EXTERNALSYM FlatSB_EnableScrollBar} FlatSB_ShowScrollBar: function(hWnd: HWND; wBar: Integer; bShow: BOOL): BOOL; stdcall; {$EXTERNALSYM FlatSB_ShowScrollBar} FlatSB_GetScrollRange: function(hWnd: HWND; nBar: Integer; var lpMinPos, lpMaxPos: Integer): BOOL; stdcall; {$EXTERNALSYM FlatSB_GetScrollRange} FlatSB_GetScrollInfo: function(hWnd: HWND; BarFlag: Integer; var ScrollInfo: TScrollInfo): BOOL; stdcall; {$EXTERNALSYM FlatSB_GetScrollInfo} FlatSB_GetScrollPos: function(hWnd: HWND; nBar: Integer): Integer; stdcall; {$EXTERNALSYM FlatSB_GetScrollPos} FlatSB_SetScrollPos: function(hWnd: HWND; nBar, nPos: Integer; bRedraw: BOOL): Integer; stdcall; {$EXTERNALSYM FlatSB_SetScrollPos} FlatSB_SetScrollInfo: function(hWnd: HWND; BarFlag: Integer; const ScrollInfo: TScrollInfo; Redraw: BOOL): Integer; stdcall; {$EXTERNALSYM FlatSB_SetScrollInfo} FlatSB_SetScrollRange: function(hWnd: HWND; nBar, nMinPos, nMaxPos: Integer; bRedraw: BOOL): BOOL; stdcall; {$EXTERNALSYM FlatSB_SetScrollRange} implementation var _FlatSB_GetScrollProp: function(p1: HWND; propIndex: Integer; p3: PInteger): Bool; stdcall; _FlatSB_SetScrollProp: function(p1: HWND; index: Integer; newValue: Integer; p4: Bool): Bool; stdcall; _InitializeFlatSB: function(hWnd: HWND): Bool; stdcall; _UninitializeFlatSB: procedure(hWnd: HWND); stdcall; function FlatSB_GetScrollProp(p1: HWND; propIndex: Integer; p3: PInteger): Bool; stdcall; begin Result := Assigned(_FlatSB_GetScrollProp) and _FlatSB_GetScrollProp(p1, propIndex, p3); end; function FlatSB_SetScrollProp(p1: HWND; index: Integer; newValue: Integer; p4: Bool): Bool; stdcall; begin Result := Assigned(_FlatSB_SetScrollProp) and _FlatSB_SetScrollProp(p1, index, newValue, p4); end; function InitializeFlatSB(hWnd: HWND): Bool; stdcall; begin Result := Assigned(_InitializeFlatSB) and _InitializeFlatSB(hWnd); end; procedure UninitializeFlatSB(hWnd: HWND); stdcall; begin if Assigned(_UninitializeFlatSB) then _UninitializeFlatSB(hWnd); end; procedure InitFlatSB; const {$IFDEF MSWINDOWS} cctrl = 'comctl32.dll'; {$ENDIF} {$IFDEF LINUX} cctrl = 'libcomctl32.borland.so'; {$ENDIF} var ComCtl32DLL: THandle; begin {$IFDEF LINUX} ComCtl32DLL := GetModuleHandle('COMCTL32.DLL'); {$ENDIF} {$IFDEF MSWINDOWS} ComCtl32DLL := GetModuleHandle(cctrl); {$ENDIF} if ComCtl32DLL <> 0 then begin @_InitializeFlatSB := GetProcAddress(ComCtl32DLL, 'InitializeFlatSB'); @_UninitializeFlatSB := GetProcAddress(ComCtl32DLL, 'UninitializeFlatSB'); @_FlatSB_GetScrollProp := GetProcAddress(ComCtl32DLL, 'FlatSB_GetScrollProp'); @_FlatSB_SetScrollProp := GetProcAddress(ComCtl32DLL, 'FlatSB_SetScrollProp'); @FlatSB_EnableScrollBar := GetProcAddress(ComCtl32DLL, 'FlatSB_EnableScrollBar'); if not Assigned(FlatSB_EnableScrollBar) then @FlatSB_EnableScrollBar := @EnableScrollBar; @FlatSB_ShowScrollBar := GetProcAddress(ComCtl32DLL, 'FlatSB_ShowScrollBar'); if not Assigned(FlatSB_ShowScrollBar) then @FlatSB_ShowScrollBar := @ShowScrollBar; @FlatSB_GetScrollRange := GetProcAddress(ComCtl32DLL, 'FlatSB_GetScrollRange'); if not Assigned(FlatSB_GetScrollRange) then @FlatSB_GetScrollRange := @GetScrollRange; @FlatSB_GetScrollInfo := GetProcAddress(ComCtl32DLL, 'FlatSB_GetScrollInfo'); if not Assigned(FlatSB_GetScrollInfo) then @FlatSB_GetScrollInfo := @GetScrollInfo; @FlatSB_GetScrollPos := GetProcAddress(ComCtl32DLL, 'FlatSB_GetScrollPos'); if not Assigned(FlatSB_GetScrollPos) then @FlatSB_GetScrollPos := @GetScrollPos; @FlatSB_SetScrollPos := GetProcAddress(ComCtl32DLL, 'FlatSB_SetScrollPos'); if not Assigned(FlatSB_SetScrollPos) then @FlatSB_SetScrollPos := @SetScrollPos; @FlatSB_SetScrollInfo := GetProcAddress(ComCtl32DLL, 'FlatSB_SetScrollInfo'); if not Assigned(FlatSB_SetScrollInfo) then @FlatSB_SetScrollInfo := @SetScrollInfo; @FlatSB_SetScrollRange := GetProcAddress(ComCtl32DLL, 'FlatSB_SetScrollRange'); if not Assigned(FlatSB_SetScrollRange) then @FlatSB_SetScrollRange := @SetScrollRange; end; end; initialization InitFlatSB; end.
unit LoadLibraryR; interface uses Windows,Logger; function GetReflectiveLoaderOffset(lpReflectiveDllBuffer:Pointer):DWORD; function LoadLibraryR_(lpBuffer:Pointer;dwLength:DWORD ):HMODULE;stdcall; function LoadRemoteLibraryR(hProcess:THandle;lpBuffer:Pointer;dwLength:DWORD;lpParameter:Pointer):THandle;stdcall; implementation uses SysUtils; type REFLECTIVELOADER = function:Cardinal;stdcall; LPTHREAD_START_ROUTINE = function(lpThreadParameter:Pointer):DWORD;stdcall; DLLMAIN = function(HINSTANCE:Cardinal;D:DWORD;P:Pointer):BOOL;stdcall; const DLL_QUERY_HMODULE = 6; function DEREF_32(name:Cardinal):DWORD; begin Result:=PDWORD(name)^; end; function DEREF_16(name:Cardinal):Word; begin Result:=PWORD(name)^; end; function Rva2Offset(dwRva:DWORD;uiBaseAddress:DWORD):DWORD; var wIndex:Word; pSectionHeader:PImageSectionHeader; pNtHeaders:PImageNtHeaders; begin wIndex:=0; pSectionHeader:=nil; pNtHeaders:=nil; pNtHeaders := PImageNtHeaders((uiBaseAddress + PImageDosHeader(uiBaseAddress)._lfanew)); pSectionHeader := PImageSectionHeader(Cardinal(@(pNtHeaders.OptionalHeader)) + pNtHeaders.FileHeader.SizeOfOptionalHeader); if( dwRva < pSectionHeader.PointerToRawData ) then Exit(dwRva); for wIndex:=0 to pNtHeaders.FileHeader.NumberOfSections -1 do begin if wIndex > 0 then Inc(pSectionHeader); if( (dwRva >= pSectionHeader.VirtualAddress) and (dwRva < (pSectionHeader.VirtualAddress + pSectionHeader.SizeOfRawData) )) then Exit(dwRva - pSectionHeader.VirtualAddress + pSectionHeader.PointerToRawData); end; Result:=0; end; function GetReflectiveLoaderOffset(lpReflectiveDllBuffer:Pointer):DWORD; var uiBaseAddress:Cardinal; uiExportDir:Cardinal; uiNameArray:Cardinal; uiAddressArray:Cardinal; uiNameOrdinals:Cardinal; dwCounter:DWORD; dwCompiledArch:DWORD; cpExportedFunctionName:PAnsiChar; I:Cardinal; s:AnsiString; begin Result:=0; {$IFDEF WIN_X64} dwCompiledArch := 2; {$ELSE} // This will catch Win32 and WinRT. dwCompiledArch := 1; {$ENDIF} uiBaseAddress := Cardinal(lpReflectiveDllBuffer); // get the File Offset of the modules NT Header uiExportDir := uiBaseAddress + (PImageDosHeader(uiBaseAddress)._lfanew); // currenlty we can only process a PE file which is the same type as the one this fuction has // been compiled as, due to various offset in the PE structures being defined at compile time. if( PImageNtHeaders(uiExportDir).OptionalHeader.Magic = $010B ) then // PE32 begin if( dwCompiledArch <> 1 ) then Exit(0); end else if( PImageNtHeaders(uiExportDir).OptionalHeader.Magic = $020B ) then // PE64 begin if( dwCompiledArch <> 2 ) then Exit(0); end else Exit; // uiNameArray = the address of the modules export directory entry //uiNameArray = (UINT_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ]; uiNameArray:=Cardinal(@(PImageNtHeaders(uiExportDir).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT])); //SaveLog('uiNameArray',uiNameArray,uiBaseAddress); // get the File Offset of the export directory // uiExportDir = uiBaseAddress + Rva2Offset( ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress, uiBaseAddress ); uiExportDir:= uiBaseAddress + Rva2Offset(PImageDataDirectory(uiNameArray).VirtualAddress,uiBaseAddress); //SaveLog('uiExportDir',uiExportDir,uiBaseAddress); // get the File Offset for the array of name pointers // uiNameArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames, uiBaseAddress ); uiNameArray:= uiBaseAddress + Rva2Offset(Cardinal((PImageExportDirectory(uiExportDir).AddressOfNames)),uiBaseAddress); //SaveLog('uiNameArray',uiNameArray,uiBaseAddress); // get the File Offset for the array of addresses //uiAddressArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions, uiBaseAddress ); uiAddressArray := uiBaseAddress + Rva2Offset(Cardinal(PImageExportDirectory(uiExportDir).AddressOfFunctions),uiBaseAddress); //SaveLog('uiAddressArray',uiAddressArray,uiBaseAddress); // get the File Offset for the array of name ordinals //uiNameOrdinals = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals, uiBaseAddress ); uiNameOrdinals := uiBaseAddress + Rva2Offset(Cardinal((PImageExportDirectory(uiExportDir).AddressOfNameOrdinals)),uiBaseAddress ); //SaveLog('uiNameOrdinals',uiNameOrdinals,uiBaseAddress); // get a counter for the number of exported functions... // dwCounter = ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->NumberOfNames; dwCounter := PImageExportDirectory(uiExportDir).NumberOfNames; // loop through all the exported functions to find the ReflectiveLoader for I := dwCounter -1 downto 0 do begin cpExportedFunctionName := PAnsiChar(uiBaseAddress + Rva2Offset( DEREF_32( uiNameArray ), uiBaseAddress )); s:=cpExportedFunctionName; OutputDebugStringa(PAnsiChar(s)); if( StrPos(cpExportedFunctionName, PAnsiChar('ReflectiveLoader')) <> '' ) then begin // get the File Offset for the array of addresses uiAddressArray := uiBaseAddress + Rva2Offset(Cardinal((PImageExportDirectory(uiExportDir).AddressOfFunctions)), uiBaseAddress ); // use the functions name ordinal as an index into the array of name pointers uiAddressArray :=uiAddressArray + ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) ); // return the File Offset to the ReflectiveLoader() functions code... Exit(Rva2Offset( DEREF_32( uiAddressArray ), uiBaseAddress )); end; // get the next exported function name uiNameArray :=uiNameArray + sizeof(DWORD); // get the next exported function name ordinal uiNameOrdinals :=uiNameOrdinals + sizeof(WORD); end; end; function LoadLibraryR_(lpBuffer:Pointer;dwLength:DWORD ):HMODULE;stdcall; var hResult:HMODULE; dwReflectiveLoaderOffset:DWORD; dwOldProtect1:DWORD; dwOldProtect2:DWORD; pReflectiveLoader:REFLECTIVELOADER; pDllMain:DLLMAIN; begin hResult:=0; dwReflectiveLoaderOffset:=0; dwOldProtect1:=0; dwOldProtect2:=0; pReflectiveLoader:=nil; pDllMain:=nil; Result:=0; if ((lpBuffer = nil) or (dwLength = 0)) then Exit; try dwReflectiveLoaderOffset := GetReflectiveLoaderOffset( lpBuffer ); if( dwReflectiveLoaderOffset <> 0 ) then begin pReflectiveLoader:=REFLECTIVELOADER(Cardinal(@lpBuffer) + dwReflectiveLoaderOffset); if(VirtualProtect(lpBuffer,dwLength,PAGE_EXECUTE_READWRITE,@dwOldProtect1)) then begin pDllMain := DLLMAIN(pReflectiveLoader); if ( pReflectiveLoader <> 0 ) then begin if ( not pDllMain( 0, DLL_QUERY_HMODULE, @hResult )) then begin hResult:=0; end; end; VirtualProtect( lpBuffer, dwLength, dwOldProtect1, @dwOldProtect2 ); end; end; except end; end; function LoadRemoteLibraryR(hProcess:THandle;lpBuffer:Pointer;dwLength:DWORD;lpParameter:Pointer):THandle;stdcall; var lpRemoteLibraryBuffer:Pointer; //lpReflectiveLoader:LPTHREAD_START_ROUTINE; lpReflectiveLoader:Cardinal; dwReflectiveLoaderOffset:DWORD; dwThreadId:DWORD; NumOfByte:DWORD; begin try Result:=0; if( (hProcess = 0) or (lpBuffer = nil) or (dwLength = 0) ) then Exit; dwReflectiveLoaderOffset := GetReflectiveLoaderOffset( lpBuffer ); if( dwReflectiveLoaderOffset = 0 ) then Exit; lpRemoteLibraryBuffer := VirtualAllocEx( hProcess, nil, dwLength, MEM_RESERVE Or MEM_COMMIT, PAGE_EXECUTE_READWRITE ); if( lpRemoteLibraryBuffer = nil) then Exit; NumOfByte :=0; if( Not WriteProcessMemory( hProcess, lpRemoteLibraryBuffer, lpBuffer, dwLength, NumOfByte ) ) then Exit; lpReflectiveLoader := Cardinal(lpRemoteLibraryBuffer) + dwReflectiveLoaderOffset; Result :=CreateRemoteThread(hProcess,nil,1024*1024,Pointer(lpReflectiveLoader),lpParameter,0,dwThreadId) except end; end; end.
unit Component.ButtonGroup; interface uses Forms, StdCtrls, ExtCtrls, Generics.Collections; type TClickEventProcedure = procedure (IsOpening: Boolean; Sender: TObject; GroupBox: TGroupBox); TButtonGroupEntry = record Selected: Boolean; ImageButton: TImage; LabelButton: TLabel; GroupBox: TGroupBox; ClickEventProcedure: TClickEventProcedure; end; TClickResult = (clkError, clkOpen, clkClose); TButtonGroup = class(TList<TButtonGroupEntry>) private FForm: TForm; FMaxHeight, FMinHeight: Integer; FMaxWidth, FMinWidth: Integer; procedure FindJobProcedure (IsRight: Boolean; Sender: TObject; Action: TClickResult; Entry: TButtonGroupEntry); function FindEntryAndDo(Sender: TObject): TClickResult; public constructor Create(iForm: TForm; iMaxHeight, iMinHeight, iMaxWidth, iMinWidth: Integer); function Click(Sender: TObject): TClickResult; procedure AddEntry(iSelected: Boolean; iImageButton: TImage; iLabelButton: TLabel; iGroupBox: TGroupBox; iClickEventProcedure: TClickEventProcedure); function FindEntry(Sender: TObject): TButtonGroupEntry; procedure Open; procedure Close; procedure CloseAll; property Form: TForm read FForm; property MaxHeight: Integer read FMaxHeight; property MinHeight: Integer read FMinHeight; property MaxWidth: Integer read FMaxWidth; property MinWidth: Integer read FMinWidth; end; implementation { TButtonGroup } procedure TButtonGroup.Open; begin if FForm = nil then exit; with FForm do begin Constraints.MaxHeight := 0; Constraints.MinHeight := 0; Constraints.MaxWidth := 0; Constraints.MinWidth := 0; ClientHeight := MaxHeight; ClientWidth := MaxWidth; Constraints.MaxHeight := Height; Constraints.MinHeight := Height; Constraints.MaxWidth := Width; Constraints.MinWidth := Width; end; end; procedure TButtonGroup.Close; begin if FForm = nil then exit; with FForm do begin Constraints.MaxHeight := 0; Constraints.MinHeight := 0; Constraints.MaxWidth := 0; Constraints.MinWidth := 0; ClientHeight := MinHeight; ClientWidth := MinWidth; Constraints.MaxHeight := Height; Constraints.MinHeight := Height; Constraints.MaxWidth := Width; Constraints.MinWidth := Width; end; end; procedure TButtonGroup.CloseAll; var CurrEntry: Integer; begin for CurrEntry := 0 to (self.Count - 1) do begin List[CurrEntry].Selected := false; List[CurrEntry].GroupBox.Visible := false; end; Close; end; procedure TButtonGroup.AddEntry(iSelected: Boolean; iImageButton: TImage; iLabelButton: TLabel; iGroupBox: TGroupBox; iClickEventProcedure: TClickEventProcedure); var TempEntry: TButtonGroupEntry; begin TempEntry.Selected := iSelected; TempEntry.ImageButton := iImageButton; TempEntry.LabelButton := iLabelButton; TempEntry.GroupBox := iGroupBox; TempEntry.ClickEventProcedure := @iClickEventProcedure; Add(TempEntry); end; function TButtonGroup.Click(Sender: TObject): TClickResult; begin exit(FindEntryAndDo(Sender)); end; constructor TButtonGroup.Create(iForm: TForm; iMaxHeight, iMinHeight, iMaxWidth, iMinWidth: Integer); begin inherited Create; FForm := iForm; FMaxHeight := iMaxHeight; FMinHeight := iMinHeight; FMaxWidth := iMaxWidth; FMinWidth := iMinWidth; end; procedure TButtonGroup.FindJobProcedure (IsRight: Boolean; Sender: TObject; Action: TClickResult; Entry: TButtonGroupEntry); const Closing = False; Opening = True; begin Entry.GroupBox.Visible := IsRight; if IsRight then Entry.GroupBox.BringToFront; if not IsRight then exit; if IsRight then Close; if @Entry.ClickEventProcedure <> nil then Entry.ClickEventProcedure(Closing, Sender, Entry.GroupBox); if (IsRight) and (Action = clkClose) then exit; if @Entry.ClickEventProcedure <> nil then Entry.ClickEventProcedure(Opening, Sender, Entry.GroupBox); Open; end; function TButtonGroup.FindEntry(Sender: TObject): TButtonGroupEntry; var CurrEntry: Integer; begin FillChar(result, SizeOf(TButtonGroupEntry), 0); for CurrEntry := 0 to (self.Count - 1) do if (Sender = List[CurrEntry].ImageButton) or (Sender = List[CurrEntry].LabelButton) then exit(List[CurrEntry]); end; function TButtonGroup.FindEntryAndDo(Sender: TObject): TClickResult; var CurrEntry: Integer; IsRight: Boolean; begin result := clkError; for CurrEntry := 0 to (self.Count - 1) do begin IsRight := (Sender = List[CurrEntry].ImageButton) or (Sender = List[CurrEntry].LabelButton); if IsRight then begin if List[CurrEntry].Selected then result := clkClose else result := clkOpen; end; FindJobProcedure(IsRight, Sender, result, List[CurrEntry]); List[CurrEntry].Selected := (IsRight) and (result = clkOpen); end; end; end.
{ "Pointer Pool" - Copyright (c) Danijel Tkalcec @exclude } unit memPtrPool; {$INCLUDE rtcDefs.inc} interface uses SysUtils; const MinPoolSize=10; MaxPoolSize=MaxLongInt div SizeOf(pointer); type tPtrPoolElems = array[1..MaxPoolSize] of pointer; pPtrPoolElems = ^tPtrPoolElems; tPtrPool = class(TObject) private pObjs:pPtrPoolElems; fCount,fSize:integer; procedure SetSize(x:integer); public constructor Create(Size:integer=0); destructor Destroy; override; function Put(x:pointer):boolean; // if Pool is full, return FALSE and Free object memory function Get:pointer; // if Pool is empty, return FALSE (you have to create the Object) property Size:integer read fSize write SetSize; property Count:integer read fCount; end; implementation { tPrtPool } constructor tPtrPool.Create(Size: integer); begin inherited Create; fSize:=Size; if fSize>0 then GetMem(pObjs,Sizeof(pointer)*fSize) else pObjs:=nil; fCount:=0; end; destructor tPtrPool.Destroy; begin fCount:=0; if fSize>0 then begin FreeMem(pObjs); pObjs:=nil; fSize:=0; end; inherited; end; function tPtrPool.Get:pointer; begin if fCount>0 then begin Result:=pObjs^[fCount]; Dec(fCount); end else Result:=nil; end; function tPtrPool.Put(x: pointer): boolean; begin if fCount<fSize then begin Inc(fCount); pObjs^[fCount]:=x; Result:=True; end else Result:=False; end; procedure tPtrPool.SetSize(x: integer); begin if x<>fSize then begin fSize:=x; ReallocMem(pObjs,fSize*SizeOf(pointer)); end; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FontPP; interface uses Vcl.StdCtrls, Vcl.AxCtrls, StdMain; type TFontPropPage = class(TPropertyPage) StaticText1: TStaticText; PropName: TComboBox; StaticText2: TStaticText; StaticText3: TStaticText; StaticText4: TStaticText; FontName: TEdit; FontList: TListBox; FontStyleCombo: TComboBox; FontSizeCombo: TComboBox; GroupBox1: TGroupBox; StrikeCB: TCheckBox; UnderlineCB: TCheckBox; GroupBox2: TGroupBox; Sample: TStaticText; procedure FormCreate(Sender: TObject); procedure FontListClick(Sender: TObject); procedure FontNameChange(Sender: TObject); procedure StrikeCBClick(Sender: TObject); procedure UnderlineCBClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure PropNameChange(Sender: TObject); private FChanging: Boolean; ApplyList: TPropApplyList; procedure FontChanged; public procedure UpdatePropertyPage; override; procedure UpdateObject; override; end; implementation uses Winapi.ActiveX, Vcl.Graphics, Vcl.Forms, System.Win.ComServ, System.Win.ComObj, System.SysUtils, System.UITypes, Vcl.Consts; {$R *.dfm} procedure TFontPropPage.FontChanged; var IFt: IFontDisp; begin if FChanging then Exit; GetOleFont(Sample.Font, IFt); ApplyList.AddProp(Integer(PropName.Items.Objects[PropName.ItemIndex]), IFt); Modified; end; procedure TFontPropPage.UpdatePropertyPage; begin EnumCtlProps(IFontDisp, PropName.Items); PropName.Enabled := PropName.Items.Count <> 0; if PropName.Enabled then begin PropName.ItemIndex := 0; PropNameChange(Self); end else begin FontName.Enabled := False; FontList.Enabled := False; FontStyleCombo.Enabled := False; FontSizeCombo.Enabled := False; StrikeCB.Enabled := False; UnderlineCB.Enabled := False; end; end; procedure TFontPropPage.UpdateObject; var i: Integer; begin for i := 0 to ApplyList.Count - 1 do SetDispatchPropValue(IUnknown(OleObject) as IDispatch, ApplyList.Props[i]^.PropId, ApplyList.Props[i]^.PropValue); ApplyList.ClearProps; Sample.Font.FontAdapter := nil; end; procedure TFontPropPage.FontListClick(Sender: TObject); begin FontName.Text:= FontList.Items[FontList.ItemIndex]; end; procedure TFontPropPage.FontNameChange(Sender: TObject); begin if FChanging then Exit; with Sample.Font do begin Name:= FontName.Text; if AnsiCompareText(FontStyleCombo.Text, SBoldFont) = 0 then Style := [fsBold] else if AnsiCompareText(FontStyleCombo.Text, SItalicFont) = 0 then Style:= [fsItalic] else if AnsiCompareText(FontStyleCombo.Text, SBoldItalicFont) = 0 then Style:= [fsBold, fsItalic] else if AnsiCompareText(FontStyleCombo.Text, SRegularFont) = 0 then Style:= []; if FontSizeCombo.Text <> '' then Size := StrToInt(FontSizeCombo.Text); if StrikeCB.Checked then Style := Style + [fsStrikeOut]; if UnderlineCB.Checked then Style := Style + [fsUnderline]; end; FontChanged; end; procedure TFontPropPage.StrikeCBClick(Sender: TObject); begin if FChanging then Exit; if StrikeCB.Checked then Sample.Font.Style := Sample.Font.Style + [fsStrikeout] else Sample.Font.Style := Sample.Font.Style - [fsStrikeout]; FontChanged; end; procedure TFontPropPage.UnderlineCBClick(Sender: TObject); begin if FChanging then Exit; if UnderlineCB.Checked then Sample.Font.Style:= Sample.Font.Style + [fsUnderline] else Sample.Font.Style:= Sample.Font.Style - [fsUnderline]; FontChanged; end; procedure TFontPropPage.PropNameChange(Sender: TObject); var IFt: IFontDisp; begin FChanging := True; try IFt := IUnknown(GetDispatchPropValue(IUnknown(OleObject) as IDispatch, Integer(PropName.Items.Objects[PropName.ItemIndex]))) as IFontDisp; SetOleFont(Sample.Font, IFt); Sample.Font.FontAdapter := nil; FontName.Text:= Sample.Font.Name; FontSizeCombo.Text:= IntToStr(Sample.Font.Size); StrikeCB.Checked := fsStrikeOut in Sample.Font.Style; UnderlineCB.Checked := fsUnderline in Sample.Font.Style; if Sample.Font.Style * [fsBold, fsItalic] = [fsBold, fsItalic] then FontStyleCombo.Text:= SBoldItalicFont else if fsBold in Sample.Font.Style then FontStyleCombo.Text:= SBoldFont else if fsItalic in Sample.Font.Style then FontStyleCombo.Text:= SItalicFont else FontStyleCombo.Text:= SRegularFont; finally FChanging := False; end; end; procedure TFontPropPage.FormCreate(Sender: TObject); var i: Integer; begin ApplyList := TPropApplyList.Create; for i := 0 to Screen.Fonts.Count - 1 do FontList.Items.Add(Screen.Fonts[i]); end; procedure TFontPropPage.FormDestroy(Sender: TObject); begin ApplyList.Free; end; initialization TActiveXPropertyPageFactory.Create( ComServer, TFontPropPage, Class_DFontPropPage); 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 © 2018 Salvador Diaz 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 uCEFDomNode; {$IFDEF FPC} {$MODE OBJFPC}{$H+} {$ENDIF} {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefDomNodeRef = class(TCefBaseRefCountedRef, ICefDomNode) protected function GetType: TCefDomNodeType; function IsText: Boolean; function IsElement: Boolean; function IsEditable: Boolean; function IsFormControlElement: Boolean; function GetFormControlElementType: ustring; function IsSame(const that: ICefDomNode): Boolean; function GetName: ustring; function GetValue: ustring; function SetValue(const value: ustring): Boolean; function GetAsMarkup: ustring; function GetDocument: ICefDomDocument; function GetParent: ICefDomNode; function GetPreviousSibling: ICefDomNode; function GetNextSibling: ICefDomNode; function HasChildren: Boolean; function GetFirstChild: ICefDomNode; function GetLastChild: ICefDomNode; function GetElementTagName: ustring; function HasElementAttributes: Boolean; function HasElementAttribute(const attrName: ustring): Boolean; function GetElementAttribute(const attrName: ustring): ustring; procedure GetElementAttributes(const attrMap: ICefStringMap); function SetElementAttribute(const attrName, value: ustring): Boolean; function GetElementInnerText: ustring; function GetElementBounds: TCefRect; public class function UnWrap(data: Pointer): ICefDomNode; end; implementation uses uCEFMiscFunctions, uCEFDomDocument; function TCefDomNodeRef.GetAsMarkup: ustring; begin Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_as_markup(PCefDomNode(FData))); end; function TCefDomNodeRef.GetDocument: ICefDomDocument; begin Result := TCefDomDocumentRef.UnWrap(PCefDomNode(FData)^.get_document(PCefDomNode(FData))); end; function TCefDomNodeRef.GetElementAttribute(const attrName: ustring): ustring; var TempName : TCefString; begin TempName := CefString(attrName); Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_element_attribute(PCefDomNode(FData), @TempName)); end; procedure TCefDomNodeRef.GetElementAttributes(const attrMap: ICefStringMap); begin PCefDomNode(FData)^.get_element_attributes(PCefDomNode(FData), attrMap.Handle); end; function TCefDomNodeRef.GetElementInnerText: ustring; begin Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_element_inner_text(PCefDomNode(FData))); end; function TCefDomNodeRef.GetElementBounds: TCefRect; begin Result := PCefDomNode(FData)^.get_element_bounds(PCefDomNode(FData)); end; function TCefDomNodeRef.GetElementTagName: ustring; begin Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_element_tag_name(PCefDomNode(FData))); end; function TCefDomNodeRef.GetFirstChild: ICefDomNode; begin Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_first_child(PCefDomNode(FData))); end; function TCefDomNodeRef.GetFormControlElementType: ustring; begin Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_form_control_element_type(PCefDomNode(FData))); end; function TCefDomNodeRef.GetLastChild: ICefDomNode; begin Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_last_child(PCefDomNode(FData))); end; function TCefDomNodeRef.GetName: ustring; begin Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_name(PCefDomNode(FData))); end; function TCefDomNodeRef.GetNextSibling: ICefDomNode; begin Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_next_sibling(PCefDomNode(FData))); end; function TCefDomNodeRef.GetParent: ICefDomNode; begin Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_parent(PCefDomNode(FData))); end; function TCefDomNodeRef.GetPreviousSibling: ICefDomNode; begin Result := TCefDomNodeRef.UnWrap(PCefDomNode(FData)^.get_previous_sibling(PCefDomNode(FData))); end; function TCefDomNodeRef.GetType: TCefDomNodeType; begin Result := PCefDomNode(FData)^.get_type(PCefDomNode(FData)); end; function TCefDomNodeRef.GetValue: ustring; begin Result := CefStringFreeAndGet(PCefDomNode(FData)^.get_value(PCefDomNode(FData))); end; function TCefDomNodeRef.HasChildren: Boolean; begin Result := PCefDomNode(FData)^.has_children(PCefDomNode(FData)) <> 0; end; function TCefDomNodeRef.HasElementAttribute(const attrName: ustring): Boolean; var TempName : TCefString; begin TempName := CefString(attrName); Result := PCefDomNode(FData)^.has_element_attribute(PCefDomNode(FData), @TempName) <> 0; end; function TCefDomNodeRef.HasElementAttributes: Boolean; begin Result := PCefDomNode(FData)^.has_element_attributes(PCefDomNode(FData)) <> 0; end; function TCefDomNodeRef.IsEditable: Boolean; begin Result := PCefDomNode(FData)^.is_editable(PCefDomNode(FData)) <> 0; end; function TCefDomNodeRef.IsElement: Boolean; begin Result := PCefDomNode(FData)^.is_element(PCefDomNode(FData)) <> 0; end; function TCefDomNodeRef.IsFormControlElement: Boolean; begin Result := PCefDomNode(FData)^.is_form_control_element(PCefDomNode(FData)) <> 0; end; function TCefDomNodeRef.IsSame(const that: ICefDomNode): Boolean; begin Result := PCefDomNode(FData)^.is_same(PCefDomNode(FData), CefGetData(that)) <> 0; end; function TCefDomNodeRef.IsText: Boolean; begin Result := PCefDomNode(FData)^.is_text(PCefDomNode(FData)) <> 0; end; function TCefDomNodeRef.SetElementAttribute(const attrName, value: ustring): Boolean; var TempName, TempValue : TCefString; begin TempName := CefString(attrName); TempValue := CefString(value); Result := PCefDomNode(FData)^.set_element_attribute(PCefDomNode(FData), @TempName, @TempValue) <> 0; end; function TCefDomNodeRef.SetValue(const value: ustring): Boolean; var TempValue : TCefString; begin TempValue := CefString(value); Result := PCefDomNode(FData)^.set_value(PCefDomNode(FData), @TempValue) <> 0; end; class function TCefDomNodeRef.UnWrap(data: Pointer): ICefDomNode; begin if (data <> nil) then Result := Create(data) as ICefDomNode else Result := nil; end; end.
unit Uini; // SpyroTAS is licensed under WTFPL // interface to ini file usage interface type // define a key-value pair TStringPair = record Key, Value: string; end; type // managed array of key-values TPairsArray = array of TStringPair; // overloads to create such pairs (key is always a string): function MakePair(const Key: string; const Value: string): TStringPair; overload; function MakePair(const Key: string; const Value: Integer): TStringPair; overload; function MakePair(const Key: string; const Value: Boolean): TStringPair; overload; // overloads to get the value as any type from a key-value pair: procedure GetPair(const Pair: TStringPair; out Value: string); overload; procedure GetPair(const Pair: TStringPair; out Value: Integer); overload; procedure GetPair(const Pair: TStringPair; out Value: Boolean); overload; // two functions for actual work: procedure IniSectionUpdate(const Filename: string; const Section: string; Data: TPairsArray; DoSave: Boolean); function IniValueUpdate(const Filename: string; const Section: string; const Key: string; const NewValue: string = #0): string; // encapsulation of above; // uses SpyroTAS default ini file. // should be called like this: // var w,x,y,z:stirng;s:string;i:integer;b:boolean;t:TTasIni; // begin t:=TTasIni.Create(); // t.Put(x,s);t.Put(y,i);t.Put(s,b); // t.ReadFrom(w); // or // t.WriteTo(w);t.Free();end; // t.Get(s);t.Get(i);t.Get(b); // t.Free();end; type TTasIni = class(TObject) public procedure Put(const Key: string; const Value: string); overload; procedure Put(const Key: string; const Value: Integer); overload; procedure Put(const Key: string; const Value: Boolean); overload; procedure Clear(); procedure WriteTo(const Section: string); procedure ReadFrom(const Section: string); procedure Get(out Value: string); overload; procedure Get(out Value: Integer); overload; procedure Get(out Value: Boolean); overload; private procedure Grow(Read: Boolean); procedure Update(const Section: string; Write: Boolean); private Data: TPairsArray; // key-values Size: Integer; // memory size Index: Integer; // current position Ready: Boolean; // when values are read end; implementation uses SysUtils, IniFiles, Utas; // simple string pair: function MakePair(const Key: string; const Value: string): TStringPair; overload; begin Result.Key := Key; Result.Value := Value; end; // integer value: function MakePair(const Key: string; const Value: Integer): TStringPair; overload; begin Result.Key := Key; Result.Value := IntToStr(Value); end; // boolean value stored as 0 or 1: function MakePair(const Key: string; const Value: Boolean): TStringPair; overload; begin Result.Key := Key; if Value then Result.Value := '1' else Result.Value := '0'; end; // return a string, trim spaces: procedure GetPair(const Pair: TStringPair; out Value: string); overload; begin Value := Trim(Pair.Value); end; // return value as integer, 0 if wrong: procedure GetPair(const Pair: TStringPair; out Value: Integer); overload; begin Value := StrToIntDef(Trim(Pair.Value), 0); end; // return as boolean, true if valid and non-zero: procedure GetPair(const Pair: TStringPair; out Value: Boolean); overload; begin Value := (StrToIntDef(Trim(Pair.Value), 0) <> 0); end; // takes constant filename, section name, // and an array or key-value pairs; // can be used for reading or writing: procedure IniSectionUpdate(const Filename: string; const Section: string; Data: TPairsArray; DoSave: Boolean); var Ini: TIniFile; // standard way Index: Integer; begin Ini := TIniFile.Create(Filename); // simple try for Index := 0 to Length(Data) - 1 do // all pairs if DoSave then // when saving put this Ini.WriteString(Section, Data[Index].Key, Data[Index].Value) else // when reading use previous as default Data[Index].Value := Ini.ReadString(Section, Data[Index].Key, Data[Index].Value); finally Ini.Free(); // close when all done end; end; // set or get one entry from ini file: function IniValueUpdate(const Filename: string; const Section: string; const Key: string; const NewValue: string = #0): string; var Data: TPairsArray; // will call section update routine begin SetLength(Data, 1); // prepare one pair Data[0].Key := Key; Data[0].Value := NewValue; IniSectionUpdate(Filename, Section, Data, NewValue <> #0); Result := Data[0].Value; // return always end; // to reuse: procedure TTasIni.Clear(); begin Ready := False; Index := 0; Size := 0; SetLength(Data, Size); // empty end; // internal, to enlarge memory or to check overflow: procedure TTasIni.Grow(Read: Boolean); begin if Read <> Ready then // don't allow mixing modes raise Exception.Create('TTasIni wrong usage'); if Index = Size then // beyond the last begin if Read then // should never occur when getting values raise Exception.Create('TTasIni wrong index (' + IntToStr(Index) + '/' + IntToStr(Size) + ')'); Size := 4 + Size * 2; // new memory size SetLength(Data, Size); // realloc end; Inc(Index); // will be one more than current end; // main task, operate on ini file: procedure TTasIni.Update(const Section: string; Write: Boolean); begin Grow(False); // just to check current mode Size := Index - 1; // actual size to call SetLength(Data, Size); // set it IniSectionUpdate(PathToIni, Section, Data, Write); // call! Index := 0; // prepare for reading Ready := True; // switch mode end; // push string: procedure TTasIni.Put(const Key: string; const Value: string); begin Grow(False); Data[Index - 1] := MakePair(Key, Value); end; // push int: procedure TTasIni.Put(const Key: string; const Value: Integer); begin Grow(False); Data[Index - 1] := MakePair(Key, Value); end; // push bool: procedure TTasIni.Put(const Key: string; const Value: Boolean); begin Grow(False); Data[Index - 1] := MakePair(Key, Value); end; // saving: procedure TTasIni.WriteTo(const Section: string); begin Update(Section, True); end; // loading: procedure TTasIni.ReadFrom(const Section: string); begin Update(Section, False); end; // pop string: procedure TTasIni.Get(out Value: string); begin Grow(True); GetPair(Data[Index - 1], Value); end; // pop int procedure TTasIni.Get(out Value: Integer); begin Grow(True); GetPair(Data[Index - 1], Value); end; // pop bool procedure TTasIni.Get(out Value: Boolean); begin Grow(True); GetPair(Data[Index - 1], Value); end; end. // EOF
(****************************************************************************) (* *) (* REV97.PAS - The Relativity Emag (coded in Turbo Pascal 7.0) *) (* *) (* "The Relativity Emag" was originally written by En|{rypt, |MuadDib|. *) (* This source may not be copied, distributed or modified in any shape *) (* or form. Some of the code has been derived from various sources and *) (* units to help us produce a better quality electronic magazine to let *) (* the scene know that we are THE BOSS. *) (* *) (* Program Notes : This program presents "The Relativity Emag" *) (* *) (* ASM/TP70 Coder : xxxxx xxxxxxxxx (En|{rypt) - xxxxxx@xxxxxxxxxx.xxx *) (* ------------------------------------------------------------------------ *) (* TP70 Coder : xxxxx xxxxxxxxx (|MuadDib|) - xxxxxx@xxxxxxxxxx.xxx *) (* *) (****************************************************************************) {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - The Heading Specifies The Program Name And Parameters. *) (****************************************************************************) Program The_Relativity_Electronic_Magazine_issue3; {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Compiler Directives - These Directives Are Not Meant To Be Modified. *) (****************************************************************************) {$a+,b-,d+,e-,f-,g+,i+,l+,n-,o-,p-,q-,r-,s+,t-,v+,x+} {$C MOVEABLE PRELOAD DISCARDABLE} {$D The Relativity Emag (in Turbo Pascal 7.0)} {$M 65000,0,655000} {$S 65000} {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - Each Identifier Names A Unit Used By The Program. *) (****************************************************************************) uses Crt,Dos,REVCOM, revconst,revinit,revmenu,revint,revcfg, revhelp,{player,}revpoint,revdos; {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - Statements To Be Executed When The Program Runs. *) (****************************************************************************) {-plans for the future in the coding- -------------------------------------- * initializing screen * ansi coming from up do down like anemia !! * hsc volum * adlib detection * sds * compression * f2 as cd menu only with time to end the song, left, whole left, % {round circle like a clock with %.. like lsl6 cd goes ff rew, random, ends in last song begins in 1 ... * f1 search in memory (bin) * more command lines * vga inroduction * highmem (or get mem) * 3rd submenu * random music * fonts onoff, bright onoff * closing credits * config file } begin checkfordat; randomize; { start_rocking;} initconfigpointer; checkbreak:=false; cc:=1; { read_config;} Initcommand; InitSubScreen; RevCommand; InitTag; InitBright; initfonts; InitMusic; InitTag; initavail; InitradVol; Initcdpos; { InitSubFiles;} { adlib:=false; vga:=false;} PhazePre; StartMainMenuPhase; end.
unit consoles; interface uses Windows, Classes, SysUtils; const Black = 0; Blue = 1; Green = 2; Cyan = 3; Red = 4; Magenta = 5; Brown = 6; LightGray = 7; // Foreground colors DarkGray = 8; LightBlue = 9; LightGreen = 10; LightCyan = 11; LightRed = 12; LightMagenta = 13; Yellow = 14; White = 15; Blink = 128; ERROR_CMDLINE_PARAM:WideString = #10#10#10; type TConsoleWindowPosition = (cwDefault,cwLeft,cwRight,cwTop,cwBottom,cwDesktopCenter,cwScreenCenter); TCommandLineParameter = class(TCollectionItem) private FOwner:TObject; FSource:WideString; FParamName,FParamValue:WideString; private procedure parseit(v:WideString=''); public constructor Create(aOwner:TObject;aCollection:TCollection);reintroduce;virtual; destructor Destroy;override; property index; property name:WideString read FParamName; property value:WideString read FParamValue; end; TCommandLine = class(TPersistent) private FList:TCollection; FCommandLine:WideString; FHandle:HWND; function getFlag(value: WideString): boolean; private function getCount: integer; function getItem(value: WideString): WideString; procedure parseParams(v:WideString);virtual; public constructor Create(aHandle:HWND);virtual; destructor Destroy;override; property cmdline:WideString read FCommandLine; property flag[value:WideString]:boolean read getFlag; property key[value:WideString]:WideString read getItem;default; property parametercount:integer read getCount; end; TConsoleApplication = class(TPersistent) private FHandle:HWND; FExitCode:DWORD; FCommandLine:TCommandLine; FPosition:TConsoleWindowPosition; FOnDestroy,FOnTerminate:TNotifyEvent; private procedure setTextPositionXY(X,Y:SmallInt); private procedure setPosition(aPosition:TConsoleWindowPosition); procedure setTitle(aTitle:WideString); function getTitle:WideString; protected function IntOnCloseQuery(const aType:DWORD):boolean;virtual; function IntOnTerminate(const aType:DWORD):boolean;virtual; protected procedure InitDefaultConsole;virtual; procedure IntTerminateProcess(Sender:TObject);virtual; procedure IntOnDestroy(Sender:TObject);virtual; protected function processMessage(var msg:TMsg):boolean;virtual; public constructor Create(aTitle:WideString;aPosition:TConsoleWindowPosition=cwDesktopCenter);virtual; destructor Destroy;override; procedure processMessages; function setFullScreen(aFullScreen:boolean):boolean; procedure clearText; procedure SetTextColor(aColor:Byte); procedure SetBackgroundColor(aColor:Byte); procedure textpos(x,y:SmallInt); procedure NormalVideo; procedure HighVideo; procedure LowVideo; function disableInput:DWORD; function enableInput:DWORD; procedure showCursor(aShow:boolean); function output(v:WideString):TConsoleApplication; function newline:TConsoleApplication; function anykey:TConsoleApplication; property handle:HWND read FHandle; property title:WideString read getTitle write setTitle; property position:TConsoleWindowPosition read FPosition write setPosition; property exitCode:DWORD read FExitCode write FExitCode; property commandline:TCommandLine read FCommandLine; public property OnDestroy:TNotifyEvent read FOnDestroy write FOnDestroy; property OnTerminate:TNotifyEvent read FOnTerminate write FOnTerminate; end; procedure hide; function ToMethod(aCode:Pointer;aData:Pointer=nil):TMethod;stdcall; implementation uses Messages, WideStrUtils, fileTools; var _self:TConsoleApplication; // for console handler { TCommandLineParameter } constructor TCommandLineParameter.Create(aOwner: TObject; aCollection: TCollection); begin inherited Create(aCollection); FOwner:=aOwner; FParamName:=''; FParamValue:=''; end; destructor TCommandLineParameter.Destroy; begin inherited Destroy; end; procedure PathUnquoteSpacesW(lpsz:PWideChar);stdcall; external 'shlwapi.dll'; procedure TCommandLineParameter.parseit(v: WideString); var i1,i2:integer; begin if trim(v)<>'' then FSource:=v; if trim(FSource)='' then Exit; // impossible situation in fact i1:=pos('-',FSource); i2:=pos(':',FSource); if i2=0 then // flag begin if i1>0 then FParamName:=copy(FSource,i1+1,length(FSource)-i1); FParamName:=trim(FParamName); end else begin // parameter if i1>=0 then begin FParamName:=copy(FSource,i1+1,i2-i1-1); FParamName:=trim(FParamName); FParamValue:=copy(FSource,i2+1,Length(FSource)-i2); FParamValue:=trim(FParamValue); end; end; end; { TCommandLine } function GetParamStrW(p:PWideChar;var v:WideString):PWideChar; var i,len:integer; start,s,q:PWideChar; begin while true do begin while (p[0]<>#0) and (p[0]<=' ') do p:=CharNextW(p); if (p[0]='"') and (p[1]='"') then inc(p,2) else break; end; len:=0; start:=p; while p[0]>' ' do begin if p[0]='"' then begin p:=CharNextW(p); while (p[0]<>#0) and (p[0]<>'"') do begin q:=CharNextW(p); inc(len,q-p); p:=q; end; if p[0]<>#0 then p:=CharNextW(p); end else begin q:=CharNextW(p); inc(len,q-p); p:=q; end; end; setLength(v,len); p:=start; s:=pointer(v); i:=0; while p[0]>' ' do begin if p[0]='"' then begin P:=CharNextW(p); while (p[0] <> #0) and (p[0] <> '"') do begin q:=CharNextW(p); while p<q do begin s[i]:=p^; inc(p); inc(i); end; end; if p[0]<>#0 then p:=CharNextW(p); end else begin q:=CharNextW(p); while p<q do begin s[i]:=p^; inc(p); inc(i); end; end; end; Result:=p; end; function ParamWideCount(path:PWideChar):integer; var p:PWideChar; s:WideString; begin p:=path; Result:=0; while true do begin p:=GetParamStrW(p,s); if s='' then break; inc(Result); end; end; function ParamWideStr(path:PWideChar;index:integer):WideString; var p:PWideChar; begin Result :=''; p:=path; while true do begin p:=GetParamStrW(p,Result); if (index=0) or (Result='') then break; dec(index); end; end; constructor TCommandLine.Create(aHandle: HWND); var p:PWideChar; sz:DWORD; FRaw:WideString; begin FHandle:=aHandle; FList:=TCollection.Create(TCommandLineParameter); FCommandLine:=WideString(windows.GetCommandLineW); FRaw:=FCommandLine; if pos(':\',FCommandLine)=0 then // relative path begin sz:=fileTools.WideLastDelimiter('\',FCommandLine); FCommandLine:=copy(FCommandLine,integer(sz)+1,length(FCommandLine)-integer(sz)); if pos('"',trim(FRaw))=1 then FCommandLine:='"'+FCommandLine; //repairing " end; sz:=1024*SizeOf(WideChar); // in case of environment vars like %TEMP% p:=PWideChar(AllocMem(sz)); if windows.ExpandEnvironmentStringsW(PWideChar(FCommandLine),p,sz)>0 then FCommandLine:=WideString(p); FreeMem(p,sz); if trim(FCommandLine)<>'' then parseParams(FCommandLine); end; destructor TCommandLine.Destroy; begin if Assigned(FList) then FreeAndNil(FList); inherited Destroy; end; function TCommandLine.getCount: integer; begin if Assigned(FList) then Result:=FList.count else Result:=0; end; function TCommandLine.getFlag(value: WideString): boolean; var i:integer; begin Result:=False; value:=trim(WideStrUtils.WideLowerCase(value)); if value='' then Exit; if not Assigned(FList) then Exit; for i:=0 to FList.Count-1 do if value=trim(WideStrUtils.WideLowerCase(TCommandLineParameter(FList.Items[i]).name)) then begin Result:=True; Break; end; end; function TCommandLine.getItem(value: WideString): WideString; var i:integer; begin Result:=ERROR_CMDLINE_PARAM; // error mark mean not found value:=trim(WideStrUtils.WideLowerCase(value)); if value='' then Exit; if not Assigned(FList) then Exit; for i:=0 to FList.Count-1 do if value=trim(WideStrUtils.WideLowerCase(TCommandLineParameter(FList.Items[i]).name)) then begin Result:=TCommandLineParameter(FList.Items[i]).value; Break; end; end; procedure TCommandLine.parseParams(v: WideString); var i,c:DWORD; itm:TCommandLineParameter; begin if not Assigned(FList) then Exit; FList.Clear; c:=ParamWideCount(PWideChar(FCommandLine)); if c>1 then for i:=1 to c-1 do begin itm:=TCommandLineParameter(FList.Add); itm.FSource:=ParamWideStr(PWideChar(FCommandLine),i); itm.parseit; end; end; { TConsoleApplication } function ToMethod(aCode:Pointer;aData:Pointer=nil):TMethod;stdcall; begin Result.Code:=aCode; Result.Data:=aData; end; function consoleProcHandler(CtrlType:DWORD):BOOL;stdcall;far; begin Result:=False; // default processing case CtrlType of CTRL_LOGOFF_EVENT,CTRL_SHUTDOWN_EVENT,CTRL_CLOSE_EVENT:if Assigned(_self) then begin System.ExitCode:=_self.ExitCode; Result:=not _self.IntOnCloseQuery(CtrlType); windows.ExitProcess(_self.ExitCode); end else windows.ExitProcess(DWORD(-1)); CTRL_BREAK_EVENT,CTRL_C_EVENT:if Assigned(_self) then begin System.ExitCode:=_self.ExitCode; Result:=not _self.IntOnTerminate(CtrlType); windows.ExitProcess(_self.ExitCode); end else windows.ExitProcess(DWORD(-1)); else Result:=False; end; end; function GetConsoleWindow:HWND;stdcall; external kernel32 name 'GetConsoleWindow'; constructor TConsoleApplication.Create(aTitle: WideString; aPosition: TConsoleWindowPosition); begin _self:=Self; FOnDestroy:=nil; FOnTerminate:=nil; FHandle:=GetConsoleWindow; FCommandLine:=TCommandLine.Create(FHandle); windows.SetConsoleTitleW(PWideChar(aTitle)); if aPosition<>cwDefault then setPosition(aPosition); FExitCode:=0; InitDefaultConsole; windows.SetConsoleCtrlHandler(@consoleProcHandler,true); end; procedure TConsoleApplication.clearText; var sp:TCoord; buf:TConsoleScreenBufferInfo; l,ww:DWORD; i:integer; r:TRect; tw:TSmallRect; textAttr:Byte; begin GetWindowRect(GetConsoleWindow,r); if not GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),buf) then Exit; tw.Left:=0; tw.Top:=0; tw.Right:=buf.dwSize.X-1; tw.Bottom:=buf.dwSize.Y-1; textAttr:=buf.wAttributes and $FF; if (tw.left=0) and (tw.top=0) and (tw.right=buf.dwSize.x-1) and (tw.bottom=buf.dwSize.y-1) then begin sp.x:=0; sp.y:=0; l:=buf.dwSize.x*buf.dwSize.y; FillConsoleOutputCharacterA(GetStdHandle(STD_OUTPUT_HANDLE),' ',l,sp,ww); FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE),textAttr,l,sp,ww); end else begin l:=tw.Right-tw.Left+1; sp.x:=tw.Left; for i:=tw.Top to tw.Bottom do begin sp.y:=i; FillConsoleOutputCharacterA(GetStdHandle(STD_OUTPUT_HANDLE),' ',l,sp,ww); FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE),textAttr,l,sp,ww); end; end; end; procedure hide; var r:TRect; w,h:integer; handle:HWND; begin handle:=GetConsoleWindow; windows.GetWindowRect(handle,r); w:=r.right-r.left; h:=r.bottom-r.top; windows.SetWindowPos(GetConsoleWindow,HWND_BOTTOM,r.left,r.Top,w,h,SWP_NOACTIVATE); end; destructor TConsoleApplication.Destroy; begin _self:=nil; FCommandLine.Free; windows.SetConsoleCtrlHandler(@consoleProcHandler,false); CloseHandle(FHandle); System.ExitCode:=self.ExitCode; inherited Destroy; end; function TConsoleApplication.getTitle: WideString; var sz:DWORD; buf:PWideChar; begin Result:=''; sz:=0; if windows.GetConsoleTitleW(nil,sz)<>0 then begin buf:=AllocMem(sz*SizeOf(WideChar)); if windows.GetConsoleTitleW(buf,sz)>0 then Result:=WideString(buf); FreeMem(buf,sz*SizeOf(WideChar)); end; end; procedure TConsoleApplication.setPosition(aPosition: TConsoleWindowPosition); var r:TRect; w,h:integer; begin FHandle:=GetConsoleWindow; windows.GetWindowRect(FHandle,r); w:=r.right-r.left; h:=r.bottom-r.top; case aPosition of cwDefault:; cwLeft:; cwRight:; cwTop:; cwBottom:; cwDesktopCenter:windows.SetWindowPos(FHandle,0,(GetSystemMetrics(SM_CXFULLSCREEN)-w) div 2,(GetSystemMetrics(SM_CYFULLSCREEN)-h) div 2,0,0,SWP_NOSIZE); cwScreenCenter:; end; end; procedure TConsoleApplication.setTextPositionXY(X, Y: SmallInt); var hStdOutput:ShortInt; p:TCoord; begin hStdOutput:=GetStdHandle(STD_OUTPUT_HANDLE); p.x:=X; p.y:=Y; windows.SetConsoleCursorPosition(hStdOutput,p); end; procedure TConsoleApplication.setTitle(aTitle: WideString); begin windows.SetConsoleTitleW(PWideChar(aTitle)); end; procedure TConsoleApplication.SetBackgroundColor(aColor:Byte); var hStdOutput:ShortInt; buf:TConsoleScreenBufferInfo; attr:Byte; begin if Self.FHandle=0 then Exit; hStdOutput:=GetStdHandle(STD_OUTPUT_HANDLE); if not GetConsoleScreenBufferInfo(hStdOutput,buf) then Exit; attr:=buf.wAttributes and $FF; attr:=(attr and $0F) or ((aColor shl 4) and $F0); SetConsoleTextAttribute(hStdOutput,attr); end; procedure TConsoleApplication.SetTextColor(aColor: Byte); var hStdOutput:ShortInt; buf:TConsoleScreenBufferInfo; attr:Byte; begin if Self.FHandle=0 then Exit; hStdOutput:=GetStdHandle(STD_OUTPUT_HANDLE); if not GetConsoleScreenBufferInfo(hStdOutput,buf) then Exit; attr:=buf.wAttributes and $FF; attr:=(attr and $F0) or (aColor and $0F); SetConsoleTextAttribute(hStdOutput,attr); end; procedure TConsoleApplication.HighVideo; var hStdOutput:ShortInt; buf:TConsoleScreenBufferInfo; attr:Byte; begin if Self.FHandle=0 then Exit; hStdOutput:=GetStdHandle(STD_OUTPUT_HANDLE); if not GetConsoleScreenBufferInfo(hStdOutput,buf) then Exit; attr:=buf.wAttributes and $FF; attr:=(attr and $08); SetConsoleTextAttribute(hStdOutput,attr); end; procedure TConsoleApplication.LowVideo; var hStdOutput:ShortInt; buf:TConsoleScreenBufferInfo; attr:Byte; begin if Self.FHandle=0 then Exit; hStdOutput:=GetStdHandle(STD_OUTPUT_HANDLE); if not GetConsoleScreenBufferInfo(hStdOutput,buf) then Exit; attr:=buf.wAttributes and $FF; attr:=(attr and $F7); SetConsoleTextAttribute(hStdOutput,attr); end; procedure TConsoleApplication.NormalVideo; var hStdOutput:ShortInt; buf:TConsoleScreenBufferInfo; attr:Byte; begin if Self.FHandle=0 then Exit; hStdOutput:=GetStdHandle(STD_OUTPUT_HANDLE); if not GetConsoleScreenBufferInfo(hStdOutput,buf) then Exit; attr:=buf.wAttributes and $FF; SetConsoleTextAttribute(hStdOutput,attr); end; function _getConsoleDisplayMode(var lpdwMode:DWORD):boolean; type TGetConsoleDisplayMode = function(var lpdwMode:DWORD):BOOL;stdcall; var hKernel:THandle; f:TGetConsoleDisplayMode; begin Result := False; hKernel:=GetModuleHandle('kernel32.dll'); if hKernel>0 then begin @f:=GetProcAddress(hKernel,'GetConsoleDisplayMode'); if Assigned(f) then Result:=f(lpdwMode); end; end; function _setConsoleDisplayMode(hOut:THandle;dwNewMode:DWORD;var lpdwOldMode:DWORD):boolean; type TSetConsoleDisplayMode = function(hOut:THandle;dwNewMode:DWORD;var lpdwOldMode:DWORD):BOOL;stdcall; var hKernel:THandle; f:TSetConsoleDisplayMode; begin Result:=false; hKernel:=GetModuleHandle('kernel32.dll'); if hKernel>0 then begin @f:=GetProcAddress(hKernel,'SetConsoleDisplayMode'); if Assigned(f) then Result:=f(hOut,dwNewMode,lpdwOldMode); end; end; function TConsoleApplication.setFullScreen(aFullScreen:boolean):boolean; const MAGIC_CONSOLE_TOGGLE = 57359; var dwOldMode,dwNewMode:DWORD; hStdOutput:ShortInt; hConsole:HWND; begin Result:=false; if Self.FHandle=0 then Exit; if Win32Platform = VER_PLATFORM_WIN32_NT then begin dwNewMode:=Ord(aFullScreen); _getConsoleDisplayMode(dwOldMode); hStdOutput:=GetStdHandle(STD_OUTPUT_HANDLE); Result:=_setConsoleDisplayMode(hStdOutput,dwNewMode,dwOldMode); end else begin hConsole:=GetConsoleWindow; Result:=hConsole<>0; if Result then begin if aFullScreen then SendMessage(GetConsoleWindow,WM_COMMAND,MAGIC_CONSOLE_TOGGLE,0) else begin keybd_event(VK_MENU,MapVirtualKey(VK_MENU,0),0,0); keybd_event(VK_RETURN,MapVirtualKey(VK_RETURN,0),0,0); keybd_event(VK_RETURN,MapVirtualKey(VK_RETURN,0),KEYEVENTF_KEYUP,0); keybd_event(VK_MENU,MapVirtualKey(VK_MENU,0),KEYEVENTF_KEYUP,0); end; end; end; end; procedure TConsoleApplication.textpos(x, y: SmallInt); begin if Self.FHandle=0 then Exit; setTextPositionXY(x,y); end; function TConsoleApplication.disableInput:DWORD; var m:DWORD; begin Result:=0; if Self.FHandle=0 then Exit; windows.GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),m); Result:=m; windows.SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),m and not ENABLE_ECHO_INPUT); end; function TConsoleApplication.enableInput:DWORD; var m:DWORD; begin Result:=0; if Self.FHandle=0 then Exit; windows.GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),m); Result:=m; windows.SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),m and not ENABLE_ECHO_INPUT); end; procedure TConsoleApplication.showCursor(aShow: boolean); var info:TConsoleCursorInfo; begin if Self.FHandle=0 then Exit; info.bVisible:=aShow; info.dwSize:=1; windows.SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),info); end; function TConsoleApplication.IntOnCloseQuery(const aType: DWORD): boolean; begin IntOnDestroy(Self); Result:=True; end; function TConsoleApplication.IntOnTerminate(const aType: DWORD): boolean; begin IntTerminateProcess(Self); Result:=True; end; procedure TConsoleApplication.IntOnDestroy(Sender: TObject); begin if Assigned(FOnDestroy) then FOnDestroy(Sender); end; procedure TConsoleApplication.IntTerminateProcess(Sender: TObject); begin if Assigned(FOnTerminate) then FOnTerminate(Sender); end; procedure TConsoleApplication.InitDefaultConsole; begin showCursor(false); SetBackgroundColor(Blue); SetTextColor(LightGray); clearText; textpos(1,1); showCursor(false); end; procedure TConsoleApplication.processMessages; var msg:TMsg; begin while ProcessMessage(msg) do {loop}; end; function TConsoleApplication.processMessage(var msg: TMsg):boolean; begin Result:=False; if PeekMessage(msg,0,0,0,PM_REMOVE) then begin Result:=True; if msg.message=WM_QUIT then IntTerminateProcess(Self) else begin TranslateMessage(msg); DispatchMessage(msg); end; end; end; function TConsoleApplication.output(v:WideString):TConsoleApplication; begin Result:=Self; if Self.FHandle=0 then Exit; write(string(v)); end; function TConsoleApplication.anykey:TConsoleApplication; begin Result:=Self; if Self.FHandle=0 then Exit; readln; end; function TConsoleApplication.newline:TConsoleApplication; begin Result:=Self; if Self.FHandle=0 then Exit; writeln; end; end.
unit ZCrc32; (************************************************************************ crc32.c -- compute the CRC-32 of a data stream Copyright (C) 1995-1998 Mark Adler Pascal translation Copyright (C) 1998 by Jacques Nomssi Nzali For conditions of distribution and use, see copyright notice in readme.txt ------------------------------------------------------------------------ Modifications by W.Ehrhardt: Feb 2002 - replaced inner while loop with for - Source code reformating/reordering Apr 2004 - D4Plus instead of Delphi5Up - Warnings of for crc_table if D4+ Mar 2005 - StrictLong instead of D4Plus (FPC 1.9.x) - Code cleanup for WWW upload ------------------------------------------------------------------------ *************************************************************************) interface uses zlibh; function crc32(crc: uLong; buf: pBytef; len: uInt): uLong; {-Update a running crc with the bytes buf[0..len-1] and return the updated crc.} {If buf is NULL, this function returns the required initial value for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application. Usage example: var crc: uLong; begin crc := crc32(0, Z_NULL, 0); while (read_buffer(buffer, length) <> EOF) do crc := crc32(crc, buffer, length); if (crc <> original_crc) then error(); end; } function get_crc_table: puLong; {-Returs addr of crc table, can be used by asm versions of crc32()} implementation {$I zconf.inc} {$ifdef DYNAMIC_CRC_TABLE} const crc_table_empty: boolean = true; var crc_table: array[0..256-1] of uLongf; {---------------------------------------------------------------------------} procedure make_crc_table; {-Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. Polynomials over GF(2) are represented in binary, one bit per coefficient, with the lowest powers in the most significant bit. Then adding polynomials is just exclusive-or, and multiplying a polynomial by x is a right shift by one. If we call the above polynomial p, and represent a byte as the polynomial q, also with the lowest power in the most significant bit (so the byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, where a mod b means the remainder after dividing a by b. This calculation is done using the shift-register method of multiplying and taking the remainder. The register is initialized to zero, and for each incoming bit, x^32 is added mod p to the register if the bit is a one (where x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x (which is shifting right by one and adding x^32 mod p if the bit shifted out is a one). We start with the highest power (least significant bit) of q and repeat for all eight bits of q. The table is simply the CRC of all possible eight bit values. This is all the information needed to generate CRC's on data a byte at a time for all combinations of CRC register values and incoming bytes.} var c : uLong; n,k : int; poly: uLong; {polynomial exclusive-or pattern} const {terms of polynomial defining this crc (except x^32):} p: array [0..13] of byte = (0,1,2,4,5,7,8,10,11,12,16,22,23,26); begin {make exclusive-or pattern from polynomial ($EDB88320)} poly := 0; for n := 0 to (sizeof(p) div sizeof(byte))-1 do poly := poly or (Long(1) shl (31 - p[n])); for n := 0 to 255 do begin c := uLong(n); for k := 0 to 7 do begin if c and 1 <> 0 then c := poly xor (c shr 1) else c := c shr 1; end; crc_table[n] := c; end; crc_table_empty := false; end; {$else} {$ifdef StrictLong} {$warnings off} {$endif} {Table of CRC-32's of all single-byte values (made by make_crc_table)} const crc_table: array[0..256-1] of uLongf = ( $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, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b, $d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79, $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); {$ifdef StrictLong} {$warnings on} {$endif} {$endif} {---------------------------------------------------------------------------} function get_crc_table: puLong; {-Returs addr of crc table, can be used by asm versions of crc32()} begin {$ifdef DYNAMIC_CRC_TABLE} if crc_table_empty then make_crc_table; {$endif} get_crc_table := puLong(@crc_table); end; {---------------------------------------------------------------------------} function crc32 (crc: uLong; buf: pBytef; len: uInt): uLong; {-Update a running crc with the bytes buf[0..len-1] and return the updated crc.} var i: uInt; begin if buf=Z_NULL then crc32 := 0 else begin {$ifdef DYNAMIC_CRC_TABLE} if crc_table_empty then make_crc_table; {$endif} crc := crc xor uLong($ffffffff); while len >= 8 do begin {DO8(buf)} crc := crc_table[(int(crc) xor buf^) and $ff] xor (crc shr 8); inc(buf); crc := crc_table[(int(crc) xor buf^) and $ff] xor (crc shr 8); inc(buf); crc := crc_table[(int(crc) xor buf^) and $ff] xor (crc shr 8); inc(buf); crc := crc_table[(int(crc) xor buf^) and $ff] xor (crc shr 8); inc(buf); crc := crc_table[(int(crc) xor buf^) and $ff] xor (crc shr 8); inc(buf); crc := crc_table[(int(crc) xor buf^) and $ff] xor (crc shr 8); inc(buf); crc := crc_table[(int(crc) xor buf^) and $ff] xor (crc shr 8); inc(buf); crc := crc_table[(int(crc) xor buf^) and $ff] xor (crc shr 8); inc(buf); dec(len, 8); end; {*we 0202 repeat replace by for} for i:=1 to len do begin crc := crc_table[(int(crc) xor buf^) and $ff] xor (crc shr 8); inc(buf); end; crc32 := crc xor uLong($ffffffff); end; end; end.
unit SD_Configuracion; interface uses IniFiles; const ARCHIVO_CFG= 'programa.cfg'; ERROR_APERTURA_CFG= 'ErrorAperturaCFG'; ERROR_CFG= 'ErrorLecturaCFG'; SECCION_APP = 'APLICACION'; SERVIDOR_FB = 'RUTA_FB'; //Ruta al archivo de BD BASE_HOST='HOST'; //Dirección IP del HOST DIR_SERVIDOR = 'SERVIDOR'; //Ruta al archivo ejecutable RUTA_LISTADOS = 'RUTA_LISTADOS'; ULT_EMPRESA = 'ULT_EMPR'; //Ultima Empresa seleccionada CFG_FONDO = 'FONDO_PANTALLA'; CFG_SEP_DECIMAL = 'SEP_DECIMAL'; CFG_SEP_MILES='SEP_MILES'; BANCO_P = 'BANCO_P'; // Valor en tbvalores donde se almacenan los bancos propios SECCION_FACTURACION = 'FACTURACION'; LEYENDA_ABONO = 'LEYENDA_ABONO'; RUTA_DBF = 'RUTA_DBF'; RUTA_RECE = 'RUTA_RECE'; PUNTO_VENTA = 'PUNTO_DE_VENTA'; function AbrirArchivo: TIniFile; function LeerDato (Clave, Etiqueta: string): string; procedure EscribirDato (Clave, Etiqueta, Dato: string); implementation uses SysUtils ,forms, Dialogs ; function AbrirArchivo: TIniFile; begin Result:= TiniFile.Create(ExtractFilePath(Application.ExeName) + ARCHIVO_CFG); end; function LeerDato (Clave, Etiqueta: string): string; var elArchivo: TIniFile; begin elArchivo:= AbrirArchivo; try if (elArchivo <> nil) and (FileExists(elArchivo.FileName)) then Result:= elArchivo.ReadString(Clave,Etiqueta, ERROR_CFG) else begin Result:= ERROR_APERTURA_CFG; end; finally elArchivo.Free; end; end; procedure EscribirDato (Clave, Etiqueta, Dato: string); var elArchivo: TIniFile; begin elArchivo:= AbrirArchivo; try if (elArchivo <> nil) and (FileExists(elArchivo.FileName)) then elArchivo.WriteString(Clave,Etiqueta, Dato) finally elArchivo.Free; end; end; end.
program _demo; Array[0] var M : AlglibInteger; N : AlglibInteger; K : AlglibInteger; Y : TReal1DArray; X : TReal2DArray; C : TReal1DArray; Rep : LSFitReport; State : LSFitState; Info : AlglibInteger; EpsF : Double; EpsX : Double; MaxIts : AlglibInteger; I : AlglibInteger; J : AlglibInteger; A : Double; B : Double; begin Write(Format('Fitting 1-x^2 on [-1,+1] with cos(alpha*pi*x)+beta'#13#10'',[])); // // Fitting 1-x^2 on [-1,+1] with cos(alpha*pi*x)+beta: // * using Hessian // * using alpha=1 and beta=0 as initial values // * using 1000 uniformly distributed points to fit to // // Notes: // * N - number of points // * M - dimension of space where points reside // * K - number of parameters being fitted // N := 1000; M := 1; K := 2; A := -1; B := +1; // // Prepare task matrix // SetLength(Y, N); SetLength(X, N, M); SetLength(C, K); I:=0; while I<=N-1 do begin X[I,0] := A+(B-A)*I/(N-1); Y[I] := 1-AP_Sqr(X[I,0]); Inc(I); end; C[0] := 1.0; C[1] := 0.0; EpsF := 0.0; EpsX := 0.0001; MaxIts := 0; // // Solve // LSFitNonlinearFGH(X, Y, C, N, M, K, State); LSFitNonlinearSetCond(State, EpsF, EpsX, MaxIts); while LSFitNonlinearIteration(State) do begin // // F(x) = Cos(alpha*pi*x)+beta // State.F := Cos(State.C[0]*Pi*State.X[0])+State.C[1]; // // F(x) = Cos(alpha*pi*x)+beta // dF/dAlpha = -pi*x*Sin(alpha*pi*x) // dF/dBeta = 1.0 // if State.NeedFG or State.NeedFGH then begin State.G[0] := -Pi*State.X[0]*Sin(State.C[0]*Pi*State.X[0]); State.G[1] := 1.0; end; // // F(x) = Cos(alpha*pi*x)+beta // d2F/dAlpha2 = -(pi*x)^2*Cos(alpha*pi*x) // d2F/dAlphadBeta = 0 // d2F/dBeta2 = 0 // if State.NeedFGH then begin State.H[0,0] := -AP_Sqr(Pi*State.X[0])*Cos(State.C[0]*Pi*State.X[0]); State.H[0,1] := 0.0; State.H[1,0] := 0.0; State.H[1,1] := 0.0; end; end; LSFitNonlinearResults(State, Info, C, Rep); Write(Format('alpha: %0.3f'#13#10'',[ C[0]])); Write(Format('beta: %0.3f'#13#10'',[ C[1]])); Write(Format('rms.err: %0.3f'#13#10'',[ Rep.RMSError])); Write(Format('max.err: %0.3f'#13#10'',[ Rep.MaxError])); Write(Format('Termination type: %0d'#13#10'',[ Info])); Write(Format(''#13#10''#13#10'',[])); end.
{*******************************************************} { } { FMXUI 虚拟键遮挡问题处理单元 } { } { 版权所有 (C) 2019 by KngStr } { } {*******************************************************} { 本单元基于QDAC中的qdac_fmx_vkhelper.pas修改。 感谢QDAC作者swish! QDAC官方网站: www.qdac.cc } unit UI.VKhelper; interface uses Classes, SysUtils, Math, FMX.Controls, FMX.Layouts, System.Types, System.Messaging; type TControlHelper = class helper for TControl function OffsetOf(AParent: TControl): TPointF; function LocalToParent(AParent: TControl; APoint: TPointF): TPointF; overload; function LocalToParent(AParent: TControl; R: TRectF): TRectF; overload; end; TScrollBoxHelper = class helper for TCustomScrollBox public procedure ScrollInView(ACtrl: TControl); end; TFocusChanged = class(TMessage) end; function IsVirtalKeyboardVisible: Boolean; function GetVirtalKeyboardBounds: TRectF; overload; function GetVirtalKeyboardBounds(var ARect: TRect): Boolean; overload; var /// <summary> /// 是否启用本单元防虚拟键盘遮档功能 /// </summary> EnableVirtalKeyboardHelper: Boolean = True; //EnableReturnKeyHook: Boolean = False; implementation uses FMX.Text, FMX.Scrollbox, FMX.VirtualKeyboard, FMX.Forms, FMX.Platform, TypInfo, {$IFDEF ANDROID} FMX.Platform.Android, FMX.Helpers.Android, Androidapi.Helpers, FMX.VirtualKeyboard.Android, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Embarcadero, Androidapi.JNI.App, {$IF RTLVersion>=32} Androidapi.NativeActivity, Androidapi.AppGlue, {$ENDIF} {$IF RTLVersion=33} FMX.Platform.UI.Android, {$ENDIF} {$ENDIF} {$IFDEF IOS} Macapi.Helpers, FMX.Platform.iOS, FMX.VirtualKeyboard.iOS, iOSapi.Foundation, iOSapi.UIKit, {$ENDIF} FMX.Types, System.UITypes, System.Rtti; type TVKNextHelper = class(TFmxObject) protected FOriginEvent: TKeyEvent; procedure SetParent(const Value: TFMXObject); override; procedure DoFocusNext(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); end; TVKStateHandler = class(TComponent) protected class var FContentRect: TRect; protected FVKMsgId: Integer; // TVKStateChangeMessage 消息的订阅ID FSizeMsgId: Integer; // TSizeChangedMessage 消息的订阅ID FIdleMsgId: Integer; FLastIdleTick: Cardinal; FLastControl: TControl; FLastControlForm: TCommonCustomForm; FLastRect: TRectF; [Weak] FLastFocused: IControl; FCaretTarget: TPointF; FAdjusting: Boolean; procedure DoVKVisibleChanged(const Sender: TObject; const Msg: System.Messaging.TMessage); procedure DoAppIdle(const Sender: TObject; const Msg: System.Messaging.TMessage); procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure AdjustCtrl(ACtrl: TControl; AVKBounds: TRectF; AVKVisible: Boolean); function NeedAdjust(ACtrl: TControl; var ACaretRect: TRectF): Boolean; procedure AdjustIfNeeded; procedure Restore; public constructor Create(AOwner: TComponent); overload; override; destructor Destroy; override; end; TAndroidContentChangeMessage = TMessage<TRect>; {$IF DEFINED(ANDROID) OR DEFINED(IOS)} var VKHandler: TVKStateHandler; {$ENDIF} {$IFDEF ANDROID} {$IF RTLVersion>=33}// 10.3+ _AndroidVKBounds: TRectF; {$ENDIF} function JRectToRectF(R: JRect): TRectF; begin Result.Left := R.Left; Result.Top := R.Top; Result.Right := R.Right; Result.Bottom := R.Bottom; end; function GetVKPixelBounds: TRectF; var TotalRect: JRect; Content, Total: TRectF; ContentRect: JRect; AView: JView; begin TotalRect := TJRect.Create; ContentRect := TJRect.Create; AView := TAndroidHelper.Activity.getWindow.getDecorView; AView.getDrawingRect(ContentRect); Content := JRectToRectF(ContentRect); TVKStateHandler.FContentRect := Content.Truncate; AView.getDrawingRect(TotalRect); Total := JRectToRectF(TotalRect); Result.Left := Total.Left; Result.Top := Total.Top + AView.getHeight; Result.Right := Total.Right; Result.Bottom := Total.Bottom; end; function GetVirtalKeyboardBounds(var ARect: TRectF): Boolean; overload; begin {$IF RTLVersion>=33}// 10.3+ if MainActivity.getVirtualKeyboard.isVirtualKeyboardShown then begin ARect := _AndroidVKBounds; Result := not ARect.IsEmpty; end else begin ARect := TRectF.Empty; Result := False; end; {$ELSE} ARect := GetVKPixelBounds; Result := ARect.Bottom <> TVKStateHandler.FContentRect.Bottom; ARect := TRectF.Create(ConvertPixelToPoint(ARect.TopLeft), ConvertPixelToPoint(ARect.BottomRight)); {$ENDIF} end; function GetVirtalKeyboardBounds: TRectF; overload; begin if not GetVirtalKeyboardBounds(Result) then Result := TRectF.Empty; end; function GetVirtalKeyboardBounds(var ARect: TRect): Boolean; overload; var R: TRectF; begin Result := GetVirtalKeyboardBounds(R); ARect := R.Truncate; end; {$ELSE} {$IFDEF IOS} _IOS_VKBounds: TRectF; function GetVirtalKeyboardBounds: TRectF; overload; var ATop: Integer; begin Result := _IOS_VKBounds; ATop := Screen.WorkAreaTop; Result.Top := Result.Top - ATop; Result.Bottom := Result.Bottom - ATop; end; function GetVirtalKeyboardBounds(var ARect: TRect): Boolean; overload; var ATemp: TRectF; AService: IFMXScreenService; AScale: Single; begin ATemp := GetVirtalKeyboardBounds; Result := not ATemp.IsEmpty; if Result then begin if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, AService) then begin AScale := AService.GetScreenScale; ARect.Left := Trunc(ATemp.Left * AScale); ARect.Top := Trunc(ATemp.Top * AScale); ARect.Right := Trunc(ATemp.Right * AScale); ARect.Bottom := Trunc(ATemp.Bottom * AScale); end; end; end; {$ELSE} function GetVirtalKeyboardBounds: TRectF; overload; begin Result := TRectF.Empty; end; function GetVirtalKeyboardBounds(var ARect: TRect): Boolean; overload; begin Result := False; end; {$ENDIF} {$ENDIF} // 根据MainActivity的可视区域和绘图区域大小来确定是否显示了虚拟键盘 function IsVirtalKeyboardVisible: Boolean; {$IF Defined(ANDROID) or Defined(IOS)}var R: TRect; {$ENDIF} begin {$IF Defined(ANDROID) or Defined(IOS)} Result := GetVirtalKeyboardBounds(R); {$ELSE} Result := False; {$ENDIF} end; { TControlHelper } function TControlHelper.LocalToParent(AParent: TControl; APoint: TPointF): TPointF; var AOffset: TPointF; begin AOffset := OffsetOf(AParent); Result.X := APoint.X + AOffset.X; Result.Y := APoint.Y + AOffset.Y; end; function TControlHelper.LocalToParent(AParent: TControl; R: TRectF): TRectF; var AOffset: TPointF; begin AOffset := OffsetOf(AParent); Result := R; Result.Offset(AOffset.X, AOffset.Y); end; function TControlHelper.OffsetOf(AParent: TControl): TPointF; var ACtrl: TControl; begin ACtrl := Self; Result.X := 0; Result.Y := 0; while (ACtrl <> nil) and (ACtrl <> AParent) do begin Result.X := Result.X + ACtrl.Position.X; Result.Y := Result.Y + ACtrl.Position.Y; ACtrl := ACtrl.ParentControl; end; if not Assigned(ACtrl) then raise Exception.CreateFmt('指定的控件 %s 不是 %s 的子控件', [Name, AParent.Name]); end; { TScrollBoxHelper } procedure TScrollBoxHelper.ScrollInView(ACtrl: TControl); var R, LR: TRectF; dx, dy: Single; begin R := ACtrl.LocalToParent(Self, ACtrl.LocalRect); LR := LocalRect; if not LR.Contains(R) then begin if R.Left > LR.Right then dx := LR.Right - R.Right else if R.Right < R.Left then dx := R.Left else dx := 0; if R.Top > LR.Bottom then dy := LR.Bottom - R.Bottom else if R.Bottom < LR.Top then dy := R.Top else dy := 0; ScrollBy(dx, dy); end; end; { TVKStateHandler } procedure TVKStateHandler.AdjustCtrl(ACtrl: TControl; AVKBounds: TRectF; AVKVisible: Boolean); var ACaretRect: TRectF; AForm: TCommonCustomForm; ADelta: Integer; begin if EnableVirtalKeyboardHelper and AVKVisible and Assigned(ACtrl) then begin if FLastControl <> ACtrl then begin if Assigned(FLastControl) then FLastControl.RemoveFreeNotification(Self); FLastControl := ACtrl; FLastControl.FreeNotification(Self); {$IFDEF DEBUG} if Assigned(FLastControl) then Log.d(Format('---FLastControl: %s-----', [FLastControl.Name])) else Log.d(Format('---FLastControl: nil-----', [FLastControl.Name])); {$ENDIF} end; AForm := (ACtrl.Root as TCommonCustomForm); if FLastControlForm <> AForm then begin if Assigned(FLastControlForm) then FLastControlForm.RemoveFreeNotification(Self); FLastControlForm := AForm; FLastControlForm.FreeNotification(Self); FLastRect := AForm.Padding.Rect; end; if NeedAdjust(ACtrl, ACaretRect) then begin if (ACaretRect.Bottom > AVKBounds.Top) or (AForm.Padding.Top < 0) or (ACaretRect.Top < 0) then ADelta := Trunc(ACaretRect.Bottom - AVKBounds.Top) else ADelta := 0; //移不动? if AForm.Padding.Bottom < AVKBounds.Height then AForm.Padding.Rect := RectF(AForm.Padding.Left, AForm.Padding.Top - ADelta, AForm.Padding.Right, AForm.Padding.Bottom + ADelta); {$IFDEF DEBUG} if Assigned(AForm) then with AForm.Padding.Rect do Log.d(Format('---ACaretRect.Bottom:%.2f-AVKBounds.Top:%.2f-Form Padding: %2f %2f %2f %2f-----', [ACaretRect.Bottom, AVKBounds.Top, Left, Top, Right, Bottom])); {$ENDIF} end; end else if Assigned(FLastControl) then begin Restore; end; end; procedure TVKStateHandler.AdjustIfNeeded; var ACtrl: TControl; begin if IsVirtalKeyboardVisible then begin // 解决掉虚拟键盘隐藏后的问题 ACtrl := Screen.FocusControl as TControl; AdjustCtrl(ACtrl, GetVirtalKeyboardBounds, True); end else AdjustCtrl(nil, RectF(0, 0, 0, 0), False); end; // 构造函数,订阅消息 constructor TVKStateHandler.Create(AOwner: TComponent); begin inherited Create(AOwner); FVKMsgId := TMessageManager.DefaultManager.SubscribeToMessage (TVKStateChangeMessage, DoVKVisibleChanged); FIdleMsgId := TMessageManager.DefaultManager.SubscribeToMessage(TIdleMessage, DoAppIdle); end; // 析构函数,取消消息订阅 destructor TVKStateHandler.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TVKStateChangeMessage, FVKMsgId); TMessageManager.DefaultManager.Unsubscribe(TIdleMessage, FIdleMsgId); inherited; end; // 在应用空闲时,检查虚拟键盘是否隐藏或是否覆盖住了当前获得焦点的控件 procedure TVKStateHandler.DoAppIdle(const Sender: TObject; const Msg: System.Messaging.TMessage); begin if FLastFocused <> Screen.FocusControl then begin {$IFDEF VER320} // Tokyo Only if Assigned(FLastFocused) then with (FLastFocused as TControl) do InvalidateRect(LocalRect); {$ENDIF} TMessageManager.DefaultManager.SendMessage(Sender, TFocusChanged.Create); FLastFocused := Screen.FocusControl; end; if TThread.GetTickCount - FLastIdleTick > 100 then begin FLastIdleTick := TThread.GetTickCount; AdjustIfNeeded; end; end; /// 虚拟键盘可见性变更消息,调整或恢复控件位置 procedure TVKStateHandler.DoVKVisibleChanged(const Sender: TObject; const Msg: System.Messaging.TMessage); var AVKMsg: TVKStateChangeMessage absolute Msg; ACtrl: TControl; begin {$IFDEF IOS} _IOS_VKBounds := TRectF.Create(AVKMsg.KeyboardBounds); {$ENDIF} {$IFDEF ANDROID} {$IF RTLVersion>=33}// 10.3+ _AndroidVKBounds := TRectF.Create(AVKMsg.KeyboardBounds); {$ENDIF} {$ENDIF} if AVKMsg.KeyboardVisible then begin // 键盘可见 if Screen.FocusControl <> nil then begin ACtrl := Screen.FocusControl.GetObject as TControl; AdjustCtrl(ACtrl, GetVirtalKeyboardBounds, True); end; end else AdjustCtrl(nil, RectF(0, 0, 0, 0), False); end; // 响应组件释放通知,以避免访问无效地址 function TVKStateHandler.NeedAdjust(ACtrl: TControl; var ACaretRect: TRectF): Boolean; var ACaret: ICaret; AFlasher: IFlasher; ACtrlBounds, AVKBounds: TRectF; function ClientToParent(ARoot: TControl): TPointF; var AParent: TControl; begin AParent := ACtrl; Result := AFlasher.Pos; while AParent <> ARoot do begin if AParent is TCustomScrollBox then Result := Result - TCustomScrollBox(AParent).ViewportPosition else if AParent is TCustomPresentedScrollBox then Result := Result - TCustomPresentedScrollBox(AParent).ViewportPosition; Result := Result + AParent.Position.Point; AParent := AParent.ParentControl; end; end; function CaretVisible: Boolean; var pt: TPointF; AChild: TControl; begin pt := AFlasher.Pos; AChild := ACtrl; Result := AFlasher.Visible; while Assigned(AChild) and Result do begin if AChild is TCustomScrollBox then begin pt := pt - TCustomScrollBox(AChild).ViewportPosition; if not AChild.LocalRect.Contains(pt) then Result := False; end else if AChild is TCustomPresentedScrollBox then begin pt := pt - TCustomPresentedScrollBox(AChild).ViewportPosition; if not AChild.LocalRect.Contains(pt) then Result := False; end else if AChild.ClipChildren and not AChild.LocalRect.Contains(pt) then Result := False; pt := pt + AChild.Position.Point; AChild := AChild.ParentControl; end; end; begin if Supports(ACtrl, ICaret, ACaret) then begin AVKBounds := GetVirtalKeyboardBounds; ACtrlBounds := ACtrl.AbsoluteRect; AFlasher := ACaret.GetObject.Flasher; if CaretVisible then begin ACaretRect.TopLeft := ClientToParent(nil); {$IF RTLVersion < 33} // 加上标题栏的高度 ACaretRect.TopLeft := ACaretRect.TopLeft + (ACtrl.Root as TCommonCustomForm).ClientToScreen(PointF(0, 0)); {$ENDIF} if FAdjusting and (not SameValue(ACaretRect.Top, FCaretTarget.Y, 1.0)) then Result := False; FAdjusting := False; ACaretRect.Right := ACaretRect.Left + AFlasher.Size.cx; ACaretRect.Bottom := ACaretRect.Top + AFlasher.Size.cy + 20; // 下面加点余量 Result := ACaretRect.IntersectsWith(AVKBounds) or (ACaretRect.Top < 0) or (ACaretRect.Top > AVKBounds.Bottom); if Result then begin FCaretTarget.Y := ACaretRect.Top + ACaretRect.Bottom - AVKBounds.Top; FAdjusting := True; end; {$IFDEF DEBUG} with ACaretRect do Log.d(Format('----ACaretRect: %2f %2f %2f %2f-----', [Left, Top, Right, Bottom])); {$ENDIF} end else Result := False; end else Result := False; end; // 响应组件释放通知,以避免访问无效地址 procedure TVKStateHandler.Notification(AComponent: TComponent; Operation: TOperation); begin if Operation = opRemove then begin if AComponent = FLastControl then begin FLastControl.RemoveFreeNotification(Self); Restore; end else if AComponent = FLastControlForm then begin FLastControlForm.RemoveFreeNotification(Self); Restore; end end; inherited; end; procedure TVKStateHandler.Restore; var AForm: TCommonCustomForm; begin if Assigned(FLastControl) then AForm := (FLastControl.Root as TCommonCustomForm) else AForm := nil; if (not Assigned(AForm)) and Assigned(FLastControlForm) then AForm := FLastControlForm; if Assigned(AForm) and Assigned(AForm.Padding) and (AForm.Padding.Rect <> FLastRect) then AForm.Padding.Rect := FLastRect; FLastControl := nil; FLastControlForm := nil; FLastFocused := nil; {$IFDEF DEBUG} if Assigned(AForm) then with AForm.Padding.Rect do Log.d(Format('---x-Form Padding: %2f %2f %2f %2f-----', [Left, Top, Right, Bottom])); {$ENDIF} end; { TVKNextHelper } procedure TVKNextHelper.DoFocusNext(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); var AVKCtrl: IVirtualKeyboardControl; procedure FocusNext(ACtrl: TControl); var AParent: TControl; ANext: IControl; ATabList: ITabList; begin if Assigned(ACtrl) and Assigned(ACtrl.ParentControl) then begin AParent := ACtrl.ParentControl; ATabList := AParent.GetTabList; if Assigned(ATabList) then begin ANext := ATabList.FindNextTabStop(ACtrl, not(ssShift in Shift), True); if Assigned(ANext) then ANext.SetFocus else FocusNext(AParent); end; end; end; begin if Assigned(FOriginEvent) then FOriginEvent(Sender, Key, KeyChar, Shift); if Supports(Sender, IVirtualKeyboardControl, AVKCtrl) then begin if (Key = vkReturn) and (AVKCtrl.ReturnKeyType = TReturnKeyType.Next) then FocusNext(Sender as TControl); end; end; procedure TVKNextHelper.SetParent(const Value: TFMXObject); begin if Value <> Parent then begin inherited; with Parent as TControl do begin FOriginEvent := OnKeyDown; OnKeyDown := DoFocusNext; end; end; end; initialization // 仅支持Android+IOS {$IF DEFINED(ANDROID) OR DEFINED(IOS)} VKHandler := TVKStateHandler.Create(nil); {$ENDIF} //EnableReturnKeyHook := True; finalization {$IF DEFINED(ANDROID) OR DEFINED(IOS)} VKHandler.DisposeOf; VKHandler := nil; {$ENDIF} end.
unit UI.ListView.Header; interface uses UI.ListView, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, UI.Base, UI.Standard; type /// <summary> /// ListView 默认头部 /// </summary> TListViewDefaultHeader = class(TFrame, IListViewHeader) RelativeLayout1: TRelativeLayout; tvText: TTextView; AniView: TAniIndicator; vImg: TView; View2: TView; private { Private declarations } FOrientation: TOrientation; FStatePullDownStart, FStatePullDownOK, FStatePullDownFinish, FStatePullDownComplete: string; FStatePullRightStart, FStatePullRightOK, FStatePullRightFinish, FStatePullRightComplete: string; protected function GetOrientation: TOrientation; procedure SetOrientation(AOrientation: TOrientation); public constructor Create(AOwner: TComponent); override; { Public declarations } procedure DoUpdateState(const State: TListViewState; const ScrollValue: Double); procedure SetStateHint(const State: TListViewState; const Msg: string); property Orientation: TOrientation read GetOrientation write SetOrientation; end; implementation {$R *.fmx} uses UI.Frame; { TListViewDefaultHeader } constructor TListViewDefaultHeader.Create(AOwner: TComponent); begin inherited; FOrientation := TOrientation.Vertical; FStatePullDownStart := '下拉刷新'; FStatePullDownOK := '松开立即刷新'; FStatePullDownFinish := '正在刷新...'; FStatePullDownComplete := '刷新完成'; FStatePullRightStart := '右拉刷新'; FStatePullRightOK := '释放刷新'; FStatePullRightFinish := '正在刷新'; FStatePullRightComplete := '刷新完成'; end; procedure TListViewDefaultHeader.DoUpdateState(const State: TListViewState; const ScrollValue: Double); begin case Orientation of TOrientation.Horizontal: begin case State of TListViewState.None, TListViewState.PullRightStart: begin AniView.Visible := False; AniView.Enabled := False; tvText.Text := FStatePullRightStart; tvText.Checked := False; vImg.Visible := True; vImg.Checked := False; Visible := State <> TListViewState.None; tvText.TextSettings.WordWrap := True; tvText.Layout.CenterHorizontal := False; tvText.Layout.AlignParentLeft := True; tvText.Width := 25; Width := tvText.Width + 5; end; TListViewState.PullRightOK: begin AniView.Visible := False; AniView.Enabled := False; tvText.Text := FStatePullRightOK; tvText.Checked := False; vImg.Visible := True; vImg.Checked := True; end; TListViewState.PullRightFinish: begin vImg.Visible := False; AniView.Enabled := True; AniView.Visible := True; tvText.Visible := False; View2.Layout.CenterInParent := True; end; TListViewState.PullRightComplete: begin vImg.Visible := False; AniView.Enabled := False; AniView.Visible := False; tvText.Text := FStatePullRightComplete; tvText.Visible := True; end; end; end; TOrientation.Vertical: begin case State of TListViewState.None, TListViewState.PullDownStart: begin AniView.Visible := False; AniView.Enabled := False; tvText.Text := FStatePullDownStart; tvText.Checked := False; vImg.Visible := True; vImg.Checked := False; Visible := State <> TListViewState.None; end; TListViewState.PullDownOK: begin AniView.Visible := False; AniView.Enabled := False; tvText.Text := FStatePullDownOK; tvText.Checked := False; vImg.Visible := True; vImg.Checked := True; end; TListViewState.PullDownFinish: begin vImg.Visible := False; AniView.Enabled := True; AniView.Visible := True; tvText.Text := FStatePullDownFinish; tvText.Checked := False; end; TListViewState.PullDownComplete: begin vImg.Visible := False; AniView.Enabled := False; AniView.Visible := False; tvText.Text := FStatePullDownComplete; tvText.Checked := True; end; end; end; end; end; function TListViewDefaultHeader.GetOrientation: TOrientation; begin Result := FOrientation; end; procedure TListViewDefaultHeader.SetOrientation(AOrientation: TOrientation); begin FOrientation := AOrientation; end; procedure TListViewDefaultHeader.SetStateHint(const State: TListViewState; const Msg: string); begin case Orientation of TOrientation.Horizontal: begin case State of TListViewState.None, TListViewState.PullRightStart: FStatePullRightStart := Msg; TListViewState.PullRightOK: FStatePullRightOK := Msg; TListViewState.PullRightFinish: FStatePullRightFinish := Msg; TListViewState.PullRightComplete: FStatePullRightComplete := Msg; end; end; TOrientation.Vertical: begin case State of TListViewState.None, TListViewState.PullDownStart: FStatePullDownStart := Msg; TListViewState.PullDownOK: FStatePullDownOK := Msg; TListViewState.PullDownFinish: FStatePullDownFinish := Msg; TListViewState.PullDownComplete: FStatePullDownComplete := Msg; end; end; end; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC resource strings } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FireDAC.Stan.ResStrs; interface uses FireDAC.Stan.Consts; resourcestring {-------------------------------------------------------------------------------} // Product links S_FD_Docu_ExplorerLink = 'http://docwiki.embarcadero.com/RADStudio/en/FDExplorer'; S_FD_Docu_ConnectToLink = 'http://docwiki.embarcadero.com/RADStudio/en/Connect_to_%s_(FireDAC)'; S_FD_Docu_FAQLink = 'http://docwiki.embarcadero.com/RADStudio/en/FAQ_(FireDAC)'; S_FD_Prod_Link = 'http://www.embarcadero.com/products/rad-studio/firedac'; S_FD_Forums_Link = 'https://forums.embarcadero.com/forum.jspa?forumID=503'; {-------------------------------------------------------------------------------} // Dialog captions S_FD_ErrorDialogDefCaption = 'FireDAC Error'; S_FD_LoginDialogDefCaption = 'FireDAC Login'; S_FD_AsyncDialogDefCaption = 'FireDAC Working'; S_FD_ScriptDialogDefCaption = 'FireDAC Processing'; S_FD_LoginDialogTestOk = 'Connection established successfully.'; S_FD_WizardNotAccessible = 'The wizard is not implemented for this driver.'; S_FD_LoginCredentials = 'Enter your credentials'; S_FD_LoginNewPassword = 'Enter your new password'; S_FD_AsyncDialogDefPrompt = 'Please wait, application is busy ...'; {-------------------------------------------------------------------------------} // Error messages S_FD_DuplicatedName = 'Name [%s] is duplicated in the list'; S_FD_NameNotFound = 'Object [%s] is not found'; S_FD_ColTypeUndefined = 'Column [%s] type is unknown or undefined'; S_FD_NoColsDefined = 'No columns defined for table'; S_FD_CheckViolated = 'Check condition violated. Constraint [%s]'; S_FD_CantBeginEdit = 'Cannot begin edit row'; S_FD_CantCreateChildView = 'Cannot create child view. Relation [%s]'; S_FD_RowCantBeDeleted = 'Cannot delete row'; S_FD_ColMBBLob = 'Column [%s] must have blob value'; S_FD_FixedLenDataMismatch = 'Fixed length column [%s] data length mismatch. Value length - [%d], column fixed length - [%d]'; S_FD_RowNotInEditableState = 'Row is not in editable state'; S_FD_ColIsReadOnly = 'Column [%s] is read only'; S_FD_RowCantBeInserted = 'Cannot insert row into table'; S_FD_RowColMBNotNull = 'Column [%s] value must be not null'; S_FD_DuplicateRows = 'Duplicate row found on unique index. Constraint [%s]'; S_FD_NoMasterRow = 'Cannot process - no parent row. Constraint [%s]'; S_FD_HasChildRows = 'Cannot process - child rows found. Constraint [%s]'; S_FD_CantCompareRows = 'Cannot compare rows'; S_FD_ConvIsNotSupported = 'Data type conversion is not supported'; S_FD_ColIsNotSearchable = 'Column [%s] is not searchable'; S_FD_RowMayHaveSingleParent = 'Row may have only single column of [dtParentRowRef] data type'; S_FD_CantOperateInvObj = 'Cannot read data from or write data to the invariant column [%s]. Hint: use properties and methods, like a NestedTable'; S_FD_CantSetParentRow = 'Cannot set parent row'; S_FD_RowIsNotNested = 'Row is not nested'; S_FD_ColumnIsNotRef = 'Column [%s] is not reference to other row'; S_FD_ColumnIsNotSetRef = 'Column [%s] is not reference to row set'; S_FD_OperCNBPerfInState = 'Cannot perform operation for row state'; S_FD_CantSetUpdReg = 'Cannot change updates registry for DatS manager [%s]'; S_FD_TooManyAggs = 'Too many aggregate values per view'; S_FD_GrpLvlExceeds = 'Grouping level exceeds maximum allowed for aggregate [%s]'; S_FD_VarLenDataMismatch = 'Variable length column [%s] overflow. Value length - [%d], column maximum length - [%d]'; S_FD_BadForeignKey = 'Invalid foreign key [%s]'; S_FD_BadUniqueKey = 'Invalid unique key [%s]'; S_FD_CantChngColType = 'Cannot change column [%s] data type'; S_FD_BadRelation = 'Invalid relation [%s]'; S_FD_CantCreateParentView = 'Cannot create parent view. Relation [%s]'; S_FD_CantChangeTableStruct = 'Cannot change table [%s] structure, when table has rows'; S_FD_FoundCascadeLoop = 'Found a cascading actions loop at checking foreign key [%s]'; S_FD_RecLocked = 'Record already locked'; S_FD_RecNotLocked = 'Record is not locked'; S_FD_TypeIncompat = 'Assigning value [%s] is not compatible with column [%s] data type. %s'; S_FD_ValueOutOfRange = 'Value [%s] is out of [%s] data type range'; S_FD_CantMerge = 'Cannot merge because [%s] %s'; S_FD_ColumnDoesnotFound = 'Column or function [%s] is not found. Hint: if the name is a function name, then add FireDAC.Stan.ExprFuncs to uses clause'; S_FD_ExprTermination = 'Expression unexpectedly terminated'; S_FD_ExprMBAgg = 'Expression must be aggregated'; S_FD_ExprCantAgg = 'Expression cannot be aggregated'; S_FD_ExprTypeMis = 'Type mismatch in expression'; S_FD_ExprIncorrect = 'Expression is incorrect'; S_FD_InvalidKeywordUse = 'Invalid use of keyword'; S_FD_ExprInvalidChar = 'Invalid character found [%s]'; S_FD_ExprNameError = 'Name is not terminated properly'; S_FD_ExprStringError = 'String constant is not terminated properly or is too long'; S_FD_ExprNoLParen = '''('' expected but [%s] found'; S_FD_ExprNoRParenOrComma = ''')'' or '','' expected but [%s] found'; S_FD_ExprNoRParen = ''')'' expected but [%s] found'; S_FD_ExprEmptyInList = 'IN predicate list may not be empty'; S_FD_ExprExpected = 'Expected [%s]'; S_FD_ExprNoArith = 'Arithmetic in filter expressions not supported'; S_FD_ExprBadScope = 'Operation cannot mix aggregate value with record-varying value'; S_FD_ExprEmpty = 'Empty expression'; S_FD_ExprEvalError = 'Error evaluating expression. %s'; S_FD_DSNoBookmark = 'Bookmark is not found for dataset [%s]'; S_FD_DSViewNotSorted = 'View [%s] is not a sorted view'; S_FD_DSNoAdapter = 'Adapter interface must be supplied'; S_FD_DSNoNestedMasterSource = 'Cannot set MasterSource for dataset [%s]. Nested datasets cannot have a MasterSource'; S_FD_DSCircularDataLink = 'Cannot set MasterSource for dataset [%s]. Circular datalinks are not allowed'; S_FD_DSRefreshError = 'Cannot refresh dataset [%s]. Cached updates must be commited or canceled and batch mode terminated before refreshing'; S_FD_DSNoDataTable = 'Cannot open dataset [%s]. A DataTable or a DataView must be supplied. Hint: if that is TFDMemTable, use CreateDataSet or CloneCursor to open dataset'; S_FD_DSIndNotFound = 'Index [%s] is not found for dataset [%s]'; S_FD_DSAggNotFound = 'Aggregate [%s] is not found for dataset [%s]'; S_FD_DSIndNotComplete = 'Index [%s] definition is not complete for dataset [%s]'; S_FD_DSAggNotComplete = 'Aggregate [%s] definition is not complete for dataset [%s]'; S_FD_DSCantUnidir = 'Cannot perform operation on unidirectional dataset [%s]'; S_FD_DSIncompatBmkFields = 'Bookmark key fields [%s] are incompatible with dataset [%s] key fields [%s]'; S_FD_DSCantEdit = 'Record editing for dataset [%s] is disabled'; S_FD_DSCantInsert = 'Record inserting for dataset [%s] is disabled'; S_FD_DSCantDelete = 'Record deleting for dataset [%s] is disabled'; S_FD_DSFieldNotFound = 'Field [%s] specified within %s of DataSet [%s] does not exist'; S_FD_DSCantOffline = 'Cannot set dataset [%s] to offline mode. Hint: check that FetchOptions.AutoFetchAll is not afDisable'; S_FD_DSCantOffCachedUpdates = 'Cannot turn off cached updates mode for DataSet [%s]. Hint: dataset has updated rows, cancel or apply updates before action'; S_FD_DefCircular = 'Cannot make definition [%s] circular reference'; S_FD_DefRO = 'Cannot %s definition [%s]. It has associated connection'; S_FD_DefCantMakePers = 'Cannot make definition persistent'; S_FD_DefAlreadyLoaded = 'Cannot load definition list, because it is already loaded'; S_FD_DefNotExists = 'Definition [%s] is not found in [%s]'; S_FD_DefDupName = 'Definition name [%s] is duplicated'; S_FD_AccSrvNotFound = 'Driver [%s] is not registered. %s'; S_FD_AccCannotReleaseDrv = 'Driver [%s] cannot be released. Hint: Close all TFDConnection objects and release pools'; S_FD_AccSrcNotFoundExists = 'To register it, you can drop component [TFDPhys%sDriverLink] into your project'; S_FD_AccSrcNotFoundNotExists = 'Correct driver ID or define [%s] virtual driver in %s'; S_FD_AccSrvNotDefined = 'Driver ID is not defined. Set TFDConnection.DriverName or add DriverID to your connection definition'; S_FD_AccSrvMBConnected = 'Connection must be active'; S_FD_AccCapabilityNotSup = 'Capability is not supported'; S_FD_AccTxMBActive = 'Transaction [%s] must be active'; S_FD_AccTxMBInActive = 'Transaction [%s] must be inactive. Nested transactions are disabled'; S_FD_AccCantChngCommandState = 'Cannot change command state'; S_FD_AccCommandMBFilled = 'Command [%s] text must be not empty'; S_FD_AccEscapeEmptyName = 'Escape function name must be not empty'; S_FD_AccCmdMHRowSet = 'Cannot open / define command, which does not return result sets. Hint: use Execute / ExecSQL method for non-SELECT commands'; S_FD_AccCmdMBPrepared = 'Command must be is prepared state'; S_FD_AccCantExecCmdWithRowSet = 'Cannot execute command returning result sets. Hint: use Open method for SELECT-like commands'; S_FD_AccCmdMBOpen4Fetch = 'Command must be open for fetching'; S_FD_AccExactMismatch = 'Exact %s [%d] rows, while [%d] was requested'; S_FD_AccMetaInfoMismatch = 'Meta information mismatch'; S_FD_AccCantLoadLibrary = 'Cannot load vendor library [%s]. %s'; S_FD_AccCantLoadLibraryHint = 'Hint: check it is in the PATH or application EXE directories, and has %s bitness.'; S_FD_AccCantGetLibraryEntry = 'Cannot get vendor library entry point[s]. [%s]'; S_FD_AccSrvMBDisConnected = 'Connection must be inactive'; S_FD_AccToManyLogins = 'Too many login retries. Allowed [%d] times'; S_FD_AccDrvMngrMB = 'To perform operation driver manager, must be [%s]'; S_FD_AccPrepMissed = 'Character [%s] is missed'; S_FD_AccPrepTooLongIdent = 'Too long identifier (> 255)'; S_FD_AccParamArrayMismatch = 'Parameter [%s] ArraySize [%d] is less than ATimes [%d]'; S_FD_AccAsyncOperInProgress = 'Cannot perform the action, because the previous action is in progress'; S_FD_AccEscapeIsnotSupported = 'Escape function [%s] is not supported'; S_FD_AccMetaInfoReset = 'Define(mmReset) is only supported for metainfo retrieval'; S_FD_AccWhereIsEmpty = 'Cannot generate update query. WHERE condition is empty'; S_FD_AccUpdateTabUndefined = 'Cannot generate update query. Update table undefined'; S_FD_AccNameHasErrors = 'Cannot parse object name - [%s]'; S_FD_AccEscapeBadSyntax = 'Syntax error in escape function [%s]. %s'; S_FD_AccShutdownTO = 'FDPhysManager shutdown timeout. Possible reason: application has not released all connection interfaces'; S_FD_AccParTypeUnknown = 'Parameter [%s] data type is unknown. Hint: specify TFDParam.DataType or assign TFDParam value before Prepare/Execute call'; S_FD_AccParDataMapNotSup = 'Parameter [%s] data type is not supported'; S_FD_AccParDefChanged = 'Param [%s] type changed from [ft%s] to [ft%s]. Query must be reprepared. Possible reason: an assignment to a TFDParam.AsXXX property implicitly changed the parameter data type. Hint: use the TFDParam.Value or appropriate TFDParam.AsXXX property'; S_FD_AccMetaInfoNotDefined = 'A meta data argument [%s] value must be specified'; S_FD_AccCantAssignTxIntf = 'Cannot set default transaction'; S_FD_AccParSetChanged = 'The set of parameters is changed. Query must be reprepared. Expected number of parameters is [%d], but actual number is [%d]. Possible reason: a parameter was added or deleted'; S_FD_AccDataToLarge = 'Data too large for variable [%s]. Max len = [%d], actual len = [%d] Hint: set the TFDParam.Size to a greater value'; S_FD_AccDbNotExists = 'Database [%s] does not exist'; S_FD_AccClassNotRegistered = 'Required OLEDB provider is missing on client machine. Hint: set exact DBVersion value or install respective MS Access Database Engine: ' + 'Access 2003 or earlier: http://support.microsoft.com/kb/239114 Access 2007: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=23734 Access 2010: http://www.microsoft.com/download/en/details.aspx?id=13255'; S_FD_AccSysClassNotRegistered = 'JRO.JetEngine class is missing on client machine. Hint: install latest engine from: http://support.microsoft.com/kb/239114'; S_FD_AccUnrecognizedDbFormat = 'Database format is not recognized. Possible reason: DBVersion value mismatches database version.'; S_FD_AccNotValidPassword = 'Specified database password is invalid'; S_FD_AccUnknownOleError = 'Unknown OLE error [%s]'; S_FD_AccUnsupParamObjValue = 'Object value for [%s] parameter of [ft%s] type is not supported'; S_FD_AccUnsupColumnType = 'Column [%s] is of unsupported data type [dt%s]'; S_FD_AccLongDataStream = 'Cannot %s stream for variable [%s]'; S_FD_AccArrayDMLWithIntStr = 'Internal streams cannot be used in Array DML'; S_FD_SvcLinkMBSet = 'To perform operation DriverLink must be specified'; S_FD_SvcMBActive = 'To perform operation service must be active'; S_FD_SvcCannotUninstall = 'Cannot deinstall a SQLite collation, while there are active connections'; S_FD_DAptRecordIsDeleted = '%s command %s [%d] instead of [1] record. Possible reasons: %s'; S_FD_DAptRecordIsDeletedReasons = 'update table does not have PK or row identifier, record has been changed/deleted by another user'; S_FD_DAptNoSelectCmd = 'Operation cannot be performed without assigned SelectCommand'; S_FD_DAptApplyUpdateFailed = 'Update post failed'; S_FD_DAptCantEdit = 'Row editing disabled'; S_FD_DAptCantInsert = 'Row inserting disabled'; S_FD_DAptCantDelete = 'Row deleting disabled'; S_FD_ClntSessMBSingle = 'Application must have only single FDManager'; S_FD_ClntSessMBInactive = 'FDManager must be inactive'; S_FD_ClntSessMBActive = 'FDManager must be active'; S_FD_ClntDbDupName = 'Connection name [%s] must be unique'; S_FD_ClntDbMBInactive = 'Connection [%s] must be inactive'; S_FD_ClntDbMBActive = 'Connection [%s] must be active'; S_FD_ClntDbLoginAborted = 'Connection [%s] establishment is canceled'; S_FD_ClntDbCantConnPooled = 'Connection [%s] cannot be pooled. Possible reason: connection definition is not in the FDManager.ConnectionDefs list or TFDConnection.Params has additional parameters'; S_FD_ClntDBNotFound = 'Connection [%s] is not found Possible reason: [%s] ConnectionName property is misspelled or references to nonexistent connection'; S_FD_ClntAdaptMBActive = 'Command [%s] must be in active state'; S_FD_ClntAdaptMBInactive = 'Command [%s] must be in inactive state'; S_FD_ClntNotCachedUpdates = 'Dataset [%s] must be in cached update mode'; S_FD_ClntDbNotDefined = 'Connection is not defined for [%s]. Possible reason: Connection and ConnectionName property values are both empty'; S_FD_ClntDbMBOnline = 'Connection [%s] must be online'; S_FD_ClntCantShareAdapt = 'Table adapter [%s] cannot be assigned to [%s], because it is already assigned to [%s] and cannot be shared across few datasets'; S_FD_ClntConnNotMatch = 'Dataset connection does not match to called connection'; S_FD_ClntPKNotFound = 'Table [%s] must have primary key'; S_FD_ClntLocalSQLMisuse = 'Local SQL engine misusage by [%s]. Hint: activate connection before activating dataset'; S_FD_ClntWrongIndex = 'Table [%s] index [%s] must be existing non-expressional index'; S_FD_ClntDSNameEmpty = 'Dataset name must be not empty'; S_FD_ClntDSNameNotUnique = 'Dataset name [%s] must be unique across Local SQL [%s] datasets'; S_FD_ClntDataSetParamIncompat = 'Dataset parameter value must be of TFDDataSet or TFDDatSTable type'; S_FD_DPNoTxtFld = 'Text field [%s] is not found'; S_FD_DPNoSrcDS = 'Source dataset not set'; S_FD_DPNoDestDS = 'Destination dataset not set'; S_FD_DPNoTxtDest = 'Destination text data file name or stream must be specified'; S_FD_DPNoTxtSrc = 'Source text data file name or stream must be specified'; S_FD_DPBadFixedSize = 'Text field [%s] size is undefined in Fixed Size Record format'; S_FD_DPTxtFldDup = 'Text field [%s] name is duplicated'; S_FD_DPBadTextFmt = 'Bad text value [%s] format for mapping item [%s]. %s'; S_FD_DPSrcUndefined = 'Undefined source field or expression for destination field [%s]'; S_FD_DPDestNoKeyFields = 'Key fields are not defined'; S_FD_DPNoSQLTab = 'SQL table is not defined'; S_FD_DPNoSQLBatch = 'CommitCount must be greater than zero'; S_FD_DPNoTxtFlds = 'Text fields are not defined. Hint: Use TFDBatchMove.Analyze'; S_FD_DPNoJsonDest = 'Destination for JSON output must be specified'; S_FD_DPNoJsonSrc = 'Source of JSON input must be specified'; S_FD_DPNoJsonFld = 'JSON field [%s] is not found'; S_FD_DPJsonFldDup = 'JSON field [%s] name is Duplicated'; S_FD_DPMapUndefined = 'Mapping of source to destination fields is not defined'; S_FD_StanTimeout = 'Timeout expired'; S_FD_StanCantGetBlob = 'Cannot get access to BLOB raw data'; S_FD_StanCantNonblocking = 'Cannot perform nonblocking action, while other nonblocking action is in progress'; S_FD_StanMacroNotFound = 'Macro [%s] is not found'; S_FD_StanBadParRowIndex = 'Parameter [%s] value index [%d] is out of range [0..%d]'; S_FD_StanPoolTooManyItems = 'Cannot acquire item (connection) from pool. Maximal number [%d] of simultaneous items (connections) reached.'; S_FD_StanHowToReg = 'To register it, you can drop component [%s] into your project'; S_FD_StanHowToInc = 'To register it, you can include unit [%s] into your project'; S_FD_StanStrgInvBinFmt = 'Invalid binary storage format'; S_FD_StanStrgCantReadProp = 'Cannot read [%s] property'; S_FD_StanStrgCantReadObj = 'Cannot read [%s] object'; S_FD_StanStrgCantReadCDATA = 'Cannot read RAW data of [%s] object'; S_FD_StanStrgDictOverflow = 'Dictionary overflow'; S_FD_StanStrgClassUnknown = 'Class [%s] is not registered'; S_FD_StanStrgUnknownFmt = 'Unknown storage format [%s]. Hint: To register it, you can drop component [TFDStanStorageXxxLink] into your project'; S_FD_StanStrgFileError = 'Cannot move file [%s] to [%s]. %s'; S_FD_StanStrgInvDIntFmt = 'Invalid date interval format [%s]'; S_FD_StanStrgInvJSONFmt = 'Invalid JSON storage format. Position [%d]'; S_FD_ScrCantExecHostCmd = 'Cannot execute host command [%s]. %s'; S_FD_ScrStrSize1 = 'String size must be of 1 character length'; S_FD_ScrStrNotAlphaNum = 'Character cannot be alphanumeric or whitespace'; S_FD_ScrSetArgInvalid = 'Invalid SET command argument'; S_FD_ScrInvalidSyntax = 'Invalid command [%s] syntax'; S_FD_ScrAccMustSpecVar = 'ACCEPT statement must specify a variable name'; S_FD_ScrDefReqValue = 'DEFINE requires a value following equal sign'; S_FD_ScrVarMissedCloseBrace = 'VARIABLE has missed right brace'; S_FD_ScrVarUnsupType = 'VARIABLE has unsupported data type'; S_FD_ScrNotLogged = 'Cannot execute command. Not logged on'; S_FD_ScrNoCmds = 'No script commands registered. Possible reason: FireDAC.Comp.ScriptCommands unit is not linked to the application'; S_FD_ScrNoScript = 'No script to execute for [%s]. Possible reason: SQLScriptFileName and SQLScripts both are empty'; S_FD_DBXParMBNotEmpty = 'Connection parameter [%s] must be not empty'; S_FD_DBXNoDriverCfg = 'DbExpress driver configuration file [%s] is not found. Possible reason: dbExpress is not properly installed on this machine'; S_FD_MySQLBadVersion = 'Unsupported MySQL version [%d]. Supported are client and server from v 3.20'; S_FD_MySQLCantSetPort = 'Port number cannot be changed'; S_FD_MySQLBadParams = 'Error in parameter [%s] definition. %s'; S_FD_MySQLCantInitEmbeddedServer = 'Failed to initialize embedded server. See MySQL log files for details'; S_FD_MySQLFieldDataTypeUnsup = 'Field [%d] data type [%d] is not supported'; S_FD_OdbcVarDataTypeUnsup = 'Variable [%s] C data type [%d] is not supported'; S_FD_OraNoCursor = 'No cursors available'; S_FD_OraCantSetCharset = 'Cannot initialize OCI with character set [%s]. Possible reason: %s'; S_FD_OraCantAssFILE = 'Cannot assign value to BFILE/CFILE parameter [%s]'; S_FD_OraNoCursorParams = 'No cursor parameters are defined. Include fiMeta into FetchOptions.Items'; S_FD_OraNotInstalled = 'OCI is not properly installed on this machine (NOE1/INIT)'; S_FD_OraBadVersion = 'Unsupported OCI library [%s] version [%s]. At least version 8.0.3 is required (NOE2/INIT)'; S_FD_OraBadVarType = 'Bad or undefined variable param type (NOE12/VAR)'; S_FD_OraTooLongGTRID = 'Maximum length (%d) of GTRID exceeded - %d (NOE18/TX)'; S_FD_OraTooLongBQUAL = 'Maximum length (%d) of BQUAL exceeded - %d (NOE19/TX)'; S_FD_OraTooLongTXName = 'Maximum length (%d) of transaction name exceeded - %d (NOE20/TX)'; S_FD_OraDBTNManyClBraces = 'Too many close braces in names file after alias [%s] (NOE105/DB)'; S_FD_OraNotPLSQLObj = '[%s] is not a callable PL/SQL object (NOE130/SP)'; S_FD_OraNotPackageProc = '[%s, #%d] is not found in [%s] package (NOE134/SP)'; S_FD_OraBadTableType = 'Parameter with type TABLE OF BOOLEAN/RECORD not supported (use TFDQuery) (NOE135/SP)'; S_FD_OraUnNamedRecParam = 'Parameter with type RECORD must be of named type (use TFDQuery) (NOE142/SP)'; S_FD_OraCantUTF16 = 'To initialize OCI in UTF16 mode, OCI must be of version 8.1 or higher'; S_FD_OraCantSetCharsetInUT16 = 'To set character set in UTF16 mode, OCI must be of version 9.2 or higher'; S_FD_OraCantSetDiffCharset = 'Character set must be the same for all sessions'; S_FD_OraCantConvNum = 'Cannot convert Oracle Number [%s] to TBcd'; S_FD_OraPipeAlertToMany = 'DBMS_PIPE event alerter supports only single event name'; S_FD_IBTraceIsActive = 'Cannot start a trace session, when there is an active one'; S_FD_PgProcNotFound = 'Stored procedure [%s] is not found'; S_FD_PgMultiDimArrNotSup = 'Array-typed variable [%s] dimensions [%d] are not supported. Only sigle dimensional simple type arrays are supported'; S_FD_PgUnsupArrValueTypeNotSup = 'Array-typed variable [%s] unsupported element type [%d]. Only sigle dimensional simple type arrays are supported'; S_FD_PgArrIndexOutOfBound = 'Array-typed variable [%s] item index [%d] is out of bounds [%d, %d]'; S_FD_PgCannotDescribeType = 'Cannot describe type [%s]. %s'; S_FD_PgIsNotArray = 'Variable [%s] is not array'; S_FD_PgUnsupTextType = 'Direct execution does not support type of variable [%s]. Only simple types are supported'; S_FD_SQLiteInitFailed = 'SQLite library initialization failed. Main code [%d], extended code [%d]'; S_FD_SQLiteDBNotFound = 'Database specified by [%p] handle was not found'; S_FD_SQLitePwdInvalid = 'Invalid password specified'; S_FD_SQLiteVTabInvalidArgs = 'VTab: Invalid number of arguments at VTabCreate. Expected [%d], got [%d]'; S_FD_SQLiteVTabDSNotFoundOrEmpty = 'VTab: Dataset [%s] is not found'; S_FD_SQLiteVTabDSNotSupported = 'VTab: Operation is not supported'; S_FD_SQLiteVTabDSSPNotFound = 'VTab: Savepoint [%d] is not found'; S_FD_SQLiteVTabDSDataModFailed = 'VTab: Dataset modification failed'; S_FD_SQLiteVTabDSRowidInvalid = 'VTab: Explicit ROWID at INSERT is not supported'; S_FD_SQLiteVTabDSChangedOrFreed = 'VTab: Dataset state was changed. Cannot perform operation'; S_FD_SQLiteVTabDSNoRowExists = 'VTab: Specified row does not exist'; S_FD_SQLiteVTabDSCursorInvalid = 'VTab: Invalid cursor'; S_FD_SQLiteVTabCannotAttach = 'TFDLocalSQL must be attached to an active SQLite connection'; S_FD_SQLiteVTabDataSetBusy = 'VTab: DataSet [%s] is busy by another result set'; S_FD_ASADBToolNotFound = 'Cannot perform action. DBTOOLn.DLL is not found'; S_FD_NexusQueryPrepareFailed = 'Query preparation failed: %s%s'; S_FD_NexusQuerySetParamsFailed = 'Query set parameters failed: %s%s'; S_FD_NexusQueryGetParamsFailed = 'Query get parameters failed: %s%s'; S_FD_NexusQueryExecFailed = 'Query execution failed: %s%s'; S_FD_MSSQLFSNoTx = 'Cannot open a FileStream without a transaction'; S_FD_MSSQLFSNoPath = 'Cannot open a FileStream using empty path'; S_FD_MSSQLFSIOError = 'FileStream access error. %s'; S_FD_MSSQLQNSubError = 'Query Notification subscription error. Info [%s]'; S_FD_MongoError = '[%s] method failed'; S_FD_MongoBadURI = 'Failed to parse URI'; S_FD_MongoDocReadOnly = 'Cannot modify read-only document'; S_FD_MongoFailedInitBSON = 'Failed to get BSON for the document'; S_FD_MongoBulkError = 'Failed to manage bulk operation'; S_FD_MongoCursorError = 'Cannot get cursor from this object. Use other [%s] overloaded method'; S_FD_MongoExecuteError = 'Cannot execute this object. Use other [%s] overloaded method'; S_FD_MongoDBRefInvalid = 'DBRef [%s] is invalid'; S_FD_MongoDBRefNotFound = 'DBRef [%s] is not found'; S_FD_MongoCannotOpenDataSet = 'Cannot open dataset [%s]. %s must be assigned'; S_FD_MongoFieldTypeMismatch = 'Data type mismatch of [%s] item. Current type [%s], new type [%s]'; S_FD_MongoFieldIsNotFound = 'Field [%s] is not found'; S_FD_MongoAlertToMany = 'Tail event alerter supports only single event name'; {-------------------------------------------------------------------------------} // FireDAC.BDE.Import S_FD_CantMakeConnDefBDEComp = 'Cannot make connection definition compatible with BDE. Reason - driver and RDBMS kind pair is unsupported'; {-------------------------------------------------------------------------------} // FireDAC.Comp.Client S_FD_ClntNotAccessible = 'Not accessible.'; S_FD_ClntConnDefParams = 'Connection definition parameters'; S_FD_ClntClientInfo = 'Client info'; S_FD_ClntSessionInfo = 'Session info'; S_FD_ClntFailedToLoad = 'Failed to load DBMS client !'; S_FD_ClntFailedToConnect = 'Failed to connect to DBMS !'; S_FD_ClntNotConnected = 'Not connected to DBMS.'; S_FD_ClntCheckingSession = 'Checking session ...'; S_FD_RegBinDefExt = 'fds'; S_FD_RegFDSFilter = 'XML Files (*.xml)|*.xml|Binary Files (*.fds, *.fdb, *.adb)|*.fds;*.fdb;*.adb|JSON Files (*.json)|*.json|All files (*.*)|*.*'; {-------------------------------------------------------------------------------} // FireDAC.Comp.BatchMove S_FD_StartLog = 'Start Log'; S_FD_NoErrorsLogged = 'No Errors Logged'; S_FD_EndLog = 'End Log'; {-------------------------------------------------------------------------------} // FireDAC.DatS S_FD_NotFound = '<not found>'; S_FD_Unnamed = 'Unnamed'; {-------------------------------------------------------------------------------} // FireDAC.VCLUI.About S_FD_ProductAbout = '%s About'; {-------------------------------------------------------------------------------} // FireDAC.VCLUI.ConnEdit S_FD_ParParameter = 'Parameter'; S_FD_ParValue = 'Value'; S_FD_ParDefault = 'Default'; S_FD_ConnEditCaption = 'FireDAC Connection Editor - [%s]'; S_FD_ConnEditNoDrv = 'Information for the [%s] driver is not accessible'; S_FD_ConnEditPressOk = 'Press OK to continue script execution'; S_FD_ConnEditEnterVal = 'Enter value'; {-------------------------------------------------------------------------------} // FireDAC.VCLUI.QEdit S_FD_QEditCaption = 'FireDAC Query Editor - [%s]'; {-------------------------------------------------------------------------------} // FireDAC.VCLUI.ResourceOptions S_FD_ResOptsStorageFolder = 'Select storage files folder'; S_FD_ResOptsBackupFolder = 'Select backup files folder'; {-------------------------------------------------------------------------------} // FireDAC.VCLUI.USEdit S_FD_USEditCaption = 'FireDAC Update SQL Editor - [%s]'; S_FD_USEditCantEdit = 'Cannot edit TFDUpdateSQL - connection is undefined'; S_FD_USEditOpenDS = 'To get columns information would you like to execute the query ?'; {-------------------------------------------------------------------------------} // FireDAC.Moni.RemoteBase S_FD_MonNoConnection = 'No connection'; S_FD_MonEncounterType = 'Encounter unexpected parameter type'; S_FD_MonEncounterParamName = 'Encounter unexpected parameter name'; S_FD_MonEncounterBlock = 'Encounter unexpected block of parameters'; S_FD_MonEncounterEOF = 'Encounter EOF'; {-------------------------------------------------------------------------------} // FireDAC.Stan.Tracer sMb_TracerPropertyChangeOnlyActiveFalse = 'Tracer has to be Active=false to change the properties'; sMb_TracerTraceFileHasToBeOpen = 'Trace file has to be open for this action'; sMb_TracerTraceFileHasToBeClosed = 'Trace file has to be closed for this action'; sMb_TracerTraceFileNameNotAssigned = 'Trace file name has to be assigned'; {-------------------------------------------------------------------------------} // keep S_FD_Warning and S_FD_Error in sync with below errors and warnings S_FD_Warning = 'Warning:'; S_FD_Error = 'Error:'; {-------------------------------------------------------------------------------} // FireDAC.Phys.ADS S_FD_ADSWarnMinAdvantageVer = 'Warning: invalid Advantage version [%s]. Minimal version is [10.0]'; S_FD_ADSWarnMinACEVer = 'Warning: invalid ACE version [%s]. Minimal version is [10.0]'; {-------------------------------------------------------------------------------} // FireDAC.Phys.FB S_FD_FBWarnNotFBSrv = 'Warning: Use Firebird driver to connect to Firebird server'; S_FD_FBWarnNotFBClnt = 'Warning: Use fbclient.dll with Firebird driver '; {-------------------------------------------------------------------------------} // FireDAC.Phys.IB S_FD_IBWarnNotIBSrv = 'Warning: Use InterBase driver to connect to InterBase'; S_FD_IBWarnNotIBClnt = 'Warning: Use gds32.dll with InterBase driver'; {-------------------------------------------------------------------------------} // FireDAC.Phys.IBBase S_FD_IBBWarnGDSFB = 'Warning: For Firebird use the fbclient.dll'; S_FD_IBBWarnFBCIB = 'Warning: For InterBase use the gds32.dll'; S_FD_IBBIndexProg = 'Processed index [%s]'; {-------------------------------------------------------------------------------} // FireDAC.Phys.MSSQL S_FD_MSSQLWarnSQLSRV = 'Warning: "SQL Server" ODBC driver is deprecated. Upgrade to newer SQL Server ODBC driver.'; S_FD_MSSQLWarnNC2008 = 'Warning: SQL NC 2008 is not full compatible with SQL Server 2000.'; S_FD_MSSQLWarnODBC11 = 'Warning: MS ODBC 11 does not support SQL_VARIANT data type.'; S_FD_MSSQLWarnNC2012 = 'Warning: SQL NC 2012 and MS ODBC 11 fail to work with TVP.'; S_FD_MSSQLWarn2106Dt = 'Warning: SQL Server 2016 and compatibility level >= 130 may lead to DATETIME comparision failure.'; {-------------------------------------------------------------------------------} // FireDAC.Phys.MySQL S_FD_MySQLWarnNoFK = 'Warning: The server [%s] version does not support Foreign ' + 'Key/Foreign Key Columns metadata retrieval.'; S_FD_MySQLWarnNoMR = 'Warning: The client [%s] version or less does not support ' + 'multiple result sets or output parameters of prepared statement.'; {-------------------------------------------------------------------------------} // FireDAC.Phys.ODBCBase S_FD_ODBCLoadingManager = 'Loading %s driver manager'; S_FD_ODBCCreatingEnv = 'Creating ODBC environment handle'; S_FD_ODBCSearchingDrv = 'Searching for ODBC driver'; S_FD_ODBCCheckingDrv = 'Checking for ODBC driver [%s]'; S_FD_ODBCWarnDrvNotFound = 'Error: specified ODBC drivers are not found'; S_FD_ODBCWillBeUsed = 'Will be used [%s]'; S_FD_ODBCFound = 'Found [%s]'; {-------------------------------------------------------------------------------} // FireDAC.Phys.Oracle S_FD_OracleWarnLowMinVer = 'Warning: The client version [%s] with low minor version may be unstable.'; S_FD_OracleWarnUnicode = 'Warning: The client version [%s] does not support Unicode in full.'; S_FD_OracleWarnSrvClntVer = 'Warning: The client [%s] and server [%s] versions may lead to various issues.'; S_FD_OracleWarnASCII = 'Warning: The US7ASCII for Western Europa languages may lead to conversion losts.'; S_FD_OracleWarnLeak = 'Warning: The client version [%s] may have major resources and memory leaks.'; {-------------------------------------------------------------------------------} // FireDAC.Phys.OracleWrapper S_FD_OracleWarnLibNotInHome = 'Warning: [%s] does not exists in Oracle Home [%s]'; S_FD_OracleWarnArchNotSup = 'Warning: not supported architecture [%s]. Required [%s]'; S_FD_OracleWarnBinNotInPath = 'Warning: bin folder [%s] is not in PATH'; S_FD_OracleWarnInvOCIVer = 'Warning: invalid OIC version [%s]. Minimal version [10.0]'; S_FD_OracleMsgLibFound = 'Found [%s], position [%d], in [%s]'; S_FD_OracleMsgChckHome = 'Checking Oracle Home at key [%s]'; S_FD_OracleMsgSkipHome = 'Skipping, position [%d] is after [%d]'; S_FD_OracleMsgSrchHome = 'Searching for Oracle Home'; S_FD_OracleMsgNoHome = 'Not found !'; S_FD_OracleMsgSrchOIC = 'Searching for Instant Client'; {-------------------------------------------------------------------------------} // FireDAC.Phys S_FD_PhysWarnMajVerDiff = 'Warning: The client [%s] and server [%s] major versions difference > 1.'; implementation end.
unit uConversoesTestes; interface Uses TestFramework, uConversoes; type TConversoesTestes = class(TTestCase) private FConverteTexto: TConverteTexto; FConverteInvertido : TConverteInvertido; FConvertePrimeiraMaiuscula : TConvertePrimeiraMaiuscula; FConverteOrdenado : TConverteOrdenado; protected procedure SetUp; override; procedure TearDown; override; published procedure TestSetTextoError; procedure TestSetTextoSuccess; procedure TestConverterInvertidoError; procedure TestConverterInvertidoSuccess; procedure TestConvertePrimeiraMaiusculaError; procedure TestConvertePrimeiraMaiusculaSuccess; procedure TestConverteOrdenadoError; procedure TestConverteOrdenadoSuccess; end; implementation procedure TConversoesTestes.SetUp; begin end; procedure TConversoesTestes.TearDown; begin end; procedure TConversoesTestes.TestSetTextoError; var obj : TConverteTexto; begin obj := TConverteTexto.Create; CheckEqualsString('Teste',obj.Texto,'ERRO'); end; procedure TConversoesTestes.TestSetTextoSuccess; var obj : TConverteTexto; begin obj := TConverteTexto.Create; obj.Texto := 'Teste'; end; procedure TConversoesTestes.TestConverterInvertidoError; var obj : TConverteTexto; begin obj := TConverteInvertido.Create; CheckEqualsString('etset',obj.Converter(''),'ERRO'); end; procedure TConversoesTestes.TestConverterInvertidoSuccess; var obj : TConverteInvertido; begin obj := TConverteInvertido.Create; CheckEqualsString('etset',obj.Converter('teste'),'ERRO'); end; procedure TConversoesTestes.TestConvertePrimeiraMaiusculaError; var obj : TConvertePrimeiraMaiuscula; begin obj := TConvertePrimeiraMaiuscula.Create; CheckEqualsString('Teste',obj.Converter(''),'ERRO'); end; procedure TConversoesTestes.TestConvertePrimeiraMaiusculaSuccess; var obj : TConvertePrimeiraMaiuscula; begin obj := TConvertePrimeiraMaiuscula.Create; CheckEqualsString('Teste',obj.Converter('teste'),'ERRO'); end; procedure TConversoesTestes.TestConverteOrdenadoError; var obj : TConverteOrdenado; begin obj := TConverteOrdenado.Create; CheckEqualsString('abc',obj.Converter(''),'ERRO'); end; procedure TConversoesTestes.TestConverteOrdenadoSuccess; var obj : TConverteOrdenado; begin obj := TConverteOrdenado.Create; CheckEqualsString('abc',obj.Converter('bca'),'ERRO'); end; initialization RegisterTest(TConversoesTestes.Suite); end.
unit fOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls; type TOptionsForm = class(TForm) CancelButton: TButton; OkButton: TButton; PagesList: TListView; HolderPanel: TPanel; procedure FormDestroy(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PagesListChange(Sender: TObject; Item: TListItem; Change: TItemChange); private procedure LoadPages; procedure SaveChanges; end; implementation uses fOptionsBase, fIdentificationOptions; type TOptionPage = record Caption: string; FrameClass: TOptionsBaseFrameClass; Frame: TOptionsBaseFrame; end; const OptionPages: array [0..0] of TOptionPage = ( (Caption: 'Identification'; FrameClass: TIdentificationOptionsFrame) ); {$R *.dfm} procedure TOptionsForm.FormDestroy(Sender: TObject); var I: Integer; begin for I := Low(OptionPages) to High(OptionPages) do OptionPages[I].Frame := nil; end; procedure TOptionsForm.OkButtonClick(Sender: TObject); begin SaveChanges; end; procedure TOptionsForm.SaveChanges; var I: Integer; begin for I := Low(OptionPages) to High(OptionPages) do begin if Assigned(OptionPages[I].Frame) then begin if not OptionPages[I].Frame.Save then begin PagesList.ItemIndex := I; Exit; end; end; end; ModalResult := mrOk; end; procedure TOptionsForm.FormCreate(Sender: TObject); begin LoadPages; end; procedure TOptionsForm.LoadPages; var I: Integer; begin for I := Low(OptionPages) to High(OptionPages) do begin PagesList.Items.Add.Caption := OptionPages[I].Caption; end; PagesList.Items[0].Selected := True; end; procedure TOptionsForm.PagesListChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin if (Change = ctState) and Item.Selected then begin if not Assigned(OptionPages[Item.Index].Frame) then begin OptionPages[Item.Index].Frame := OptionPages[Item.Index].FrameClass.Create(Self); OptionPages[Item.Index].Frame.Align := alClient; OptionPages[Item.Index].Frame.Load; OptionPages[Item.Index].Frame.Parent := HolderPanel; end; OptionPages[Item.Index].Frame.BringToFront; end; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit DBXCustomDataGenerator; interface uses DBXCommon, DBXMetaDataProvider, SysUtils; type TDBXDataGeneratorColumn = class; TDBXDataGeneratorException = class; TDBXDataGeneratorColumnArray = array of TDBXDataGeneratorColumn; TDBXCustomDataGenerator = class public procedure AddColumn(const Column: TDBXDataGeneratorColumn); virtual; destructor Destroy; override; function GetColumn(const Ordinal: Integer): TDBXDataGeneratorColumn; virtual; procedure Open; virtual; function CreateInsertStatement(const Row: Integer): UnicodeString; overload; virtual; function CreateInsertStatement(const InsertColumns: TDBXDataGeneratorColumnArray; const Row: Integer): UnicodeString; overload; virtual; function CreateParameterizedInsertStatement: UnicodeString; overload; virtual; function CreateParameterizedInsertStatement(const InsertColumns: TDBXDataGeneratorColumnArray): UnicodeString; overload; virtual; procedure Next; virtual; protected function GetColumnCount: Integer; virtual; function GetTableName: UnicodeString; virtual; procedure SetTableName(const TableName: UnicodeString); virtual; function GetMetaDataProvider: TDBXMetaDataProvider; virtual; procedure SetMetaDataProvider(const MetaDataProvider: TDBXMetaDataProvider); virtual; private function ColumnNameString(const Columns: TDBXDataGeneratorColumnArray): UnicodeString; function ValueString(const Columns: TDBXDataGeneratorColumnArray; const Row: Integer): UnicodeString; function MarkerString: UnicodeString; function CreateInsertStatement(const InsertColumns: TDBXDataGeneratorColumnArray; const Row: Integer; const Prepare: Boolean): UnicodeString; overload; private FTableName: UnicodeString; FRow: Integer; FColumns: TDBXDataGeneratorColumnArray; FMetaDataProvider: TDBXMetaDataProvider; public property ColumnCount: Integer read GetColumnCount; property TableName: UnicodeString read GetTableName write SetTableName; property MetaDataProvider: TDBXMetaDataProvider read GetMetaDataProvider write SetMetaDataProvider; end; TDBXDataGeneratedReader = class(TDBXReader) public constructor Create(const ARowCount: Int64; const AGeneratorColumns: TDBXDataGeneratorColumnArray); destructor Destroy; override; function Reset: Boolean; override; function DerivedNext: Boolean; override; function CompareReader(const Reader: TDBXReader): Boolean; virtual; procedure DerivedClose; override; protected function GetByteReader: TDBXByteReader; override; function GetPosition: Int64; virtual; private procedure CreateValues; procedure GenerateValues; private FPosition: Int64; FRowCount: Int64; FLastOrdinalCompared: Integer; FGeneratorColumns: TDBXDataGeneratorColumnArray; public property Position: Int64 read GetPosition; property LastOrdinalCompared: Integer read FLastOrdinalCompared; end; TDBXDataGeneratedRow = class(TDBXRow) public constructor Create(const Context: TDBXContext); end; TDBXDataGeneratorColumn = class abstract public constructor Create(const InMetaDataColumn: TDBXMetaDataColumn); procedure Open; virtual; destructor Destroy; override; function GetString(const Row: Int64): UnicodeString; virtual; abstract; function GetBoolean(const Row: Int64): Boolean; virtual; function GetInt8(const Row: Int64): Byte; virtual; function GetInt16(const Row: Int64): SmallInt; virtual; function GetInt32(const Row: Int64): Integer; virtual; function GetInt64(const Row: Int64): Int64; virtual; function GetDouble(const Row: Int64): Double; virtual; function GetSingle(const Row: Int64): Single; virtual; function GetBytes(const Row: Int64): TBytes; virtual; function GetDecimal(const Row: Int64): UnicodeString; virtual; function GetYear(const Row: Int64): Integer; virtual; function GetMonth(const Row: Int64): Integer; virtual; function GetDay(const Row: Int64): Integer; virtual; function GetHour(const Row: Int64): Integer; virtual; function GetMinute(const Row: Int64): Integer; virtual; function GetSeconds(const Row: Int64): Integer; virtual; function GetMilliseconds(const Row: Int64): Integer; virtual; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); virtual; abstract; protected procedure SetDataGenerator(const DataGenerator: TDBXCustomDataGenerator); virtual; function GetColumnName: UnicodeString; virtual; function GetDataType: Integer; virtual; function GetMetaDataColumn: TDBXMetaDataColumn; virtual; private function TypeNotSupported: TDBXDataGeneratorException; protected FMetaDataColumn: TDBXMetaDataColumn; FDataGenerator: TDBXCustomDataGenerator; public property DataGenerator: TDBXCustomDataGenerator write SetDataGenerator; property ColumnName: UnicodeString read GetColumnName; property DataType: Integer read GetDataType; property MetaDataColumn: TDBXMetaDataColumn read GetMetaDataColumn; end; TDBXBooleanSequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetBoolean(const Row: Int64): Boolean; override; function GetString(const Row: Int64): UnicodeString; override; function GetInt8(const Row: Int64): Byte; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXBlobSequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetString(const Row: Int64): UnicodeString; override; function GetBytes(const Row: Int64): TBytes; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXAnsiStringSequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXDataGeneratorException = class(Exception) public constructor Create(const Message: UnicodeString); end; TDBXDateSequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetYear(const Row: Int64): Integer; override; function GetMonth(const Row: Int64): Integer; override; function GetDay(const Row: Int64): Integer; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXDecimalSequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetDecimal(const Row: Int64): UnicodeString; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXDoubleSequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetDouble(const Row: Int64): Double; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXInt16SequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetInt16(const Row: Int64): SmallInt; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXInt32SequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetInt32(const Row: Int64): Integer; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXInt64SequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetInt64(const Row: Int64): Int64; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXInt8SequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetInt8(const Row: Int64): Byte; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXTimeSequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetHour(const Row: Int64): Integer; override; function GetMinute(const Row: Int64): Integer; override; function GetSeconds(const Row: Int64): Integer; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXTimestampSequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetYear(const Row: Int64): Integer; override; function GetMonth(const Row: Int64): Integer; override; function GetDay(const Row: Int64): Integer; override; function GetHour(const Row: Int64): Integer; override; function GetMinute(const Row: Int64): Integer; override; function GetSeconds(const Row: Int64): Integer; override; function GetMilliseconds(const Row: Int64): Integer; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; TDBXWideStringSequenceGenerator = class(TDBXDataGeneratorColumn) public constructor Create(const MetaData: TDBXMetaDataColumn); procedure Open; override; function GetString(const Row: Int64): UnicodeString; override; procedure SetValue(const Row: Int64; const Value: TDBXWritableValue); override; end; implementation uses DBXPlatform; function TDBXCustomDataGenerator.GetColumnCount: Integer; begin if FColumns = nil then Result := 0 else Result := Length(FColumns); end; procedure TDBXCustomDataGenerator.AddColumn(const Column: TDBXDataGeneratorColumn); var Temp: TDBXDataGeneratorColumnArray; Index: Integer; begin if FColumns = nil then SetLength(FColumns, 1) else begin SetLength(Temp, Length(FColumns) + 1); for Index := 0 to Length(FColumns) - 1 do Temp[Index] := FColumns[Index]; FColumns := Temp; end; FColumns[Length(FColumns) - 1] := Column; Column.Open; end; destructor TDBXCustomDataGenerator.Destroy; var Index: Integer; begin if FColumns <> nil then for Index := 0 to Length(FColumns) - 1 do FreeAndNil(FColumns[Index]); FColumns := nil; inherited Destroy; end; function TDBXCustomDataGenerator.GetColumn(const Ordinal: Integer): TDBXDataGeneratorColumn; begin Result := FColumns[Ordinal]; end; procedure TDBXCustomDataGenerator.Open; var Index: Integer; begin FRow := 0; if FColumns <> nil then for Index := 0 to Length(FColumns) - 1 do begin FColumns[Index].DataGenerator := self; FColumns[Index].Open; end; end; function TDBXCustomDataGenerator.ColumnNameString(const Columns: TDBXDataGeneratorColumnArray): UnicodeString; var ColumnNameString: UnicodeString; Ordinal: Integer; begin ColumnNameString := ''; Ordinal := 0; while Ordinal < Length(Columns) do begin ColumnNameString := ColumnNameString + FMetaDataProvider.QuoteIdentifierIfNeeded(Columns[Ordinal].ColumnName); Inc(Ordinal); if Ordinal < Length(Columns) then ColumnNameString := ColumnNameString + ','; end; Result := ColumnNameString; end; function TDBXCustomDataGenerator.ValueString(const Columns: TDBXDataGeneratorColumnArray; const Row: Integer): UnicodeString; var ValueString: UnicodeString; ColumnName: UnicodeString; Ordinal: Integer; begin ValueString := ''; Ordinal := 0; while Ordinal < Length(Columns) do begin ColumnName := Columns[Ordinal].GetString(Row); if (StringIsNil(ColumnName)) or (Length(ColumnName) < 1) then raise TDBXDataGeneratorException.Create('ColumnName property not set or set to an empty string for ordinal: ' + IntToStr(Ordinal)); ValueString := ValueString + Columns[Ordinal].GetString(Row); Inc(Ordinal); if Ordinal < Length(Columns) then ValueString := ValueString + ','; end; Result := ValueString; end; function TDBXCustomDataGenerator.MarkerString: UnicodeString; var MarkerString: UnicodeString; Ordinal: Integer; begin MarkerString := ''; Ordinal := 0; while Ordinal < Length(FColumns) do begin Inc(Ordinal); if Ordinal < Length(FColumns) then MarkerString := MarkerString + '?,' else MarkerString := MarkerString + '?'; end; Result := MarkerString; end; function TDBXCustomDataGenerator.GetTableName: UnicodeString; begin Result := FTableName; end; procedure TDBXCustomDataGenerator.SetTableName(const TableName: UnicodeString); begin self.FTableName := TableName; end; function TDBXCustomDataGenerator.CreateInsertStatement(const InsertColumns: TDBXDataGeneratorColumnArray; const Row: Integer; const Prepare: Boolean): UnicodeString; var InsertStatement: UnicodeString; begin if (StringIsNil(FTableName)) or (Length(FTableName) < 1) then raise TDBXDataGeneratorException.Create('TableName property not set or set to an empty string'); if FMetaDataProvider = nil then raise TDBXDataGeneratorException.Create('MetaDataProvider property not set'); InsertStatement := 'INSERT INTO ' + FMetaDataProvider.QuoteIdentifierIfNeeded(FTableName) + ' (' + ColumnNameString(InsertColumns) + ') VALUES ('; if Prepare then InsertStatement := InsertStatement + MarkerString else InsertStatement := InsertStatement + ValueString(FColumns, Row); Result := InsertStatement + ')'; end; function TDBXCustomDataGenerator.CreateInsertStatement(const Row: Integer): UnicodeString; begin Result := CreateInsertStatement(FColumns, Row, False); end; function TDBXCustomDataGenerator.CreateInsertStatement(const InsertColumns: TDBXDataGeneratorColumnArray; const Row: Integer): UnicodeString; begin Result := CreateInsertStatement(InsertColumns, Row, False); end; function TDBXCustomDataGenerator.CreateParameterizedInsertStatement: UnicodeString; begin Result := CreateInsertStatement(FColumns, -1, True); end; function TDBXCustomDataGenerator.CreateParameterizedInsertStatement(const InsertColumns: TDBXDataGeneratorColumnArray): UnicodeString; begin Result := CreateInsertStatement(InsertColumns, -1, True); end; procedure TDBXCustomDataGenerator.Next; begin Inc(FRow); end; function TDBXCustomDataGenerator.GetMetaDataProvider: TDBXMetaDataProvider; begin Result := FMetaDataProvider; end; procedure TDBXCustomDataGenerator.SetMetaDataProvider(const MetaDataProvider: TDBXMetaDataProvider); begin self.FMetaDataProvider := MetaDataProvider; end; constructor TDBXDataGeneratedReader.Create(const ARowCount: Int64; const AGeneratorColumns: TDBXDataGeneratorColumnArray); begin inherited Create(nil, TDBXDataGeneratedRow.Create(nil), nil); FPosition := -1; FGeneratorColumns := AGeneratorColumns; FRowCount := ARowCount; CreateValues; end; destructor TDBXDataGeneratedReader.Destroy; begin FreeAndNil(FGeneratorColumns); inherited Destroy; end; procedure TDBXDataGeneratedReader.CreateValues; var Column: TDBXDataGeneratorColumn; ValueType: TDBXValueType; Values: TDBXWritableValueArray; MetaDataColumn: TDBXMetaDataColumn; Index: Integer; begin SetLength(Values,Length(FGeneratorColumns)); for Index := 0 to Length(FGeneratorColumns) - 1 do begin Column := FGeneratorColumns[Index]; MetaDataColumn := Column.MetaDataColumn; ValueType := TDBXValueType.Create; ValueType.DataType := MetaDataColumn.DataType; ValueType.Precision := MetaDataColumn.Precision; ValueType.Scale := MetaDataColumn.Scale; ValueType.Name := MetaDataColumn.ColumnName; Values[Index] := TDBXWritableValue(TDBXValue.CreateValue(ValueType)); end; SetValues(Values); end; function TDBXDataGeneratedReader.Reset: Boolean; begin FPosition := -1; Result := True; end; procedure TDBXDataGeneratedReader.GenerateValues; var Index: Integer; begin for Index := 0 to Length(FGeneratorColumns) - 1 do FGeneratorColumns[Index].SetValue(FPosition, TDBXWritableValue(self.Value[Index])); end; function TDBXDataGeneratedReader.DerivedNext: Boolean; begin FPosition := FPosition + 1; if FPosition < FRowCount then begin GenerateValues; Exit(True); end; FPosition := FPosition - 1; Result := False; end; function TDBXDataGeneratedReader.GetByteReader: TDBXByteReader; begin Result := nil; end; // public boolean next() { // return derivedNext(); // } function TDBXDataGeneratedReader.GetPosition: Int64; begin Result := FPosition; end; function TDBXDataGeneratedReader.CompareReader(const Reader: TDBXReader): Boolean; var Index: Integer; begin Reset; Reader.Reset; FLastOrdinalCompared := -1; if Reader.ColumnCount <> ColumnCount then Exit(False); while Next do begin if not Reader.Next then Exit(False); for Index := 0 to Reader.ColumnCount - 1 do begin if not Reader.Value[Index].EqualsValue(self.Value[Index]) then begin FLastOrdinalCompared := Index; Exit(False); end; end; end; FLastOrdinalCompared := -1; if Reader.Next then Exit(False); Result := True; end; procedure TDBXDataGeneratedReader.DerivedClose; begin end; constructor TDBXDataGeneratedRow.Create(const Context: TDBXContext); begin inherited Create(Context); end; procedure TDBXDataGeneratorColumn.SetDataGenerator(const DataGenerator: TDBXCustomDataGenerator); begin self.FDataGenerator := DataGenerator; end; constructor TDBXDataGeneratorColumn.Create(const InMetaDataColumn: TDBXMetaDataColumn); begin inherited Create; FMetaDataColumn := TDBXMetaDataColumn.Create(InMetaDataColumn); end; function TDBXDataGeneratorColumn.TypeNotSupported: TDBXDataGeneratorException; begin Result := TDBXDataGeneratorException.Create('Type not supported by this implementation of DataGenerationColumn'); end; procedure TDBXDataGeneratorColumn.Open; begin end; destructor TDBXDataGeneratorColumn.Destroy; begin FreeAndNil(FMetaDataColumn); inherited Destroy; end; function TDBXDataGeneratorColumn.GetBoolean(const Row: Int64): Boolean; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetInt8(const Row: Int64): Byte; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetInt16(const Row: Int64): SmallInt; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetInt32(const Row: Int64): Integer; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetInt64(const Row: Int64): Int64; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetDouble(const Row: Int64): Double; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetSingle(const Row: Int64): Single; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetBytes(const Row: Int64): TBytes; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetDecimal(const Row: Int64): UnicodeString; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetYear(const Row: Int64): Integer; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetMonth(const Row: Int64): Integer; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetDay(const Row: Int64): Integer; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetHour(const Row: Int64): Integer; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetMinute(const Row: Int64): Integer; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetSeconds(const Row: Int64): Integer; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetMilliseconds(const Row: Int64): Integer; begin raise TypeNotSupported; end; function TDBXDataGeneratorColumn.GetColumnName: UnicodeString; begin Result := FMetaDataColumn.ColumnName; end; function TDBXDataGeneratorColumn.GetDataType: Integer; begin Result := FMetaDataColumn.DataType; end; function TDBXDataGeneratorColumn.GetMetaDataColumn: TDBXMetaDataColumn; begin Result := FMetaDataColumn; end; constructor TDBXBooleanSequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXBooleanSequenceGenerator.Open; begin inherited Open; end; function TDBXBooleanSequenceGenerator.GetBoolean(const Row: Int64): Boolean; begin Result := (Row and 1) = 1; end; function TDBXBooleanSequenceGenerator.GetString(const Row: Int64): UnicodeString; begin if GetBoolean(Row) then Result := 'true' else Result := 'false'; end; function TDBXBooleanSequenceGenerator.GetInt8(const Row: Int64): Byte; begin Result := Byte((Row and 1)); end; procedure TDBXBooleanSequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.SetBoolean(GetBoolean(Row)); end; constructor TDBXBlobSequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXBlobSequenceGenerator.Open; begin inherited Open; end; function TDBXBlobSequenceGenerator.GetString(const Row: Int64): UnicodeString; var Count: Integer; Buffer: TDBXStringBuffer; StringValue: UnicodeString; Value: Integer; Index: Integer; begin Count := FMetaDataColumn.Precision; Buffer := TDBXStringBuffer.Create(Count); Value := Integer(Row); for Index := 0 to Count - 1 do begin Buffer.Append(WideChar((32 + Value mod 96))); Inc(Value); end; StringValue := Buffer.ToString; Buffer.Free; Result := StringValue; end; function TDBXBlobSequenceGenerator.GetBytes(const Row: Int64): TBytes; var Count: Integer; Buffer: TBytes; Value: Integer; Index: Integer; begin Count := FMetaDataColumn.Precision; SetLength(Buffer, Count); Value := Integer(Row); for Index := 0 to Count - 1 do begin Buffer[Index] := Byte(Value); Inc(Value); end; Result := Buffer; end; procedure TDBXBlobSequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); var Bytes: TBytes; begin Bytes := GetBytes(Row); Value.SetDynamicBytes(0, Bytes, 0, Length(Bytes)); end; constructor TDBXAnsiStringSequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXAnsiStringSequenceGenerator.Open; begin inherited Open; end; function TDBXAnsiStringSequenceGenerator.GetString(const Row: Int64): UnicodeString; var Value: UnicodeString; begin Value := 'A' + IntToStr(Row); if FMetaDataColumn.FixedLength then while Length(Value) < FMetaDataColumn.Precision do Value := Value + ' '; Result := Value; end; procedure TDBXAnsiStringSequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.SetWideString(GetString(Row)); end; constructor TDBXDataGeneratorException.Create(const Message: UnicodeString); begin inherited Create(Message); end; constructor TDBXDateSequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXDateSequenceGenerator.Open; begin inherited Open; end; function TDBXDateSequenceGenerator.GetYear(const Row: Int64): Integer; begin Result := 1970 + Integer(Row) mod 20; end; function TDBXDateSequenceGenerator.GetMonth(const Row: Int64): Integer; begin Result := (Integer(Row) mod 12) + 1; end; function TDBXDateSequenceGenerator.GetDay(const Row: Int64): Integer; begin Result := (Integer(Row) mod 28) + 1; end; function TDBXDateSequenceGenerator.GetString(const Row: Int64): UnicodeString; begin Result := '' + IntToStr(GetMonth(Row)) + '/' + IntToStr(GetDay(Row)) + '/' + IntToStr(GetYear(Row)); end; procedure TDBXDateSequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.SetWideString(GetString(Row)); end; constructor TDBXDecimalSequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXDecimalSequenceGenerator.Open; begin inherited Open; end; function TDBXDecimalSequenceGenerator.GetDecimal(const Row: Int64): UnicodeString; begin Result := GetString(Row); end; function TDBXDecimalSequenceGenerator.GetString(const Row: Int64): UnicodeString; begin Result := '' + IntToStr((Row)); end; procedure TDBXDecimalSequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.AsString := GetString(Row); end; constructor TDBXDoubleSequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXDoubleSequenceGenerator.Open; begin inherited Open; end; function TDBXDoubleSequenceGenerator.GetDouble(const Row: Int64): Double; begin Result := Row; end; function TDBXDoubleSequenceGenerator.GetString(const Row: Int64): UnicodeString; var DoubleRow: Double; begin DoubleRow := Row; Result := '' + FloatToStr(DoubleRow); end; procedure TDBXDoubleSequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.SetDouble(GetDouble(Row)); end; constructor TDBXInt16SequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXInt16SequenceGenerator.Open; begin inherited Open; end; function TDBXInt16SequenceGenerator.GetInt16(const Row: Int64): SmallInt; begin Result := SmallInt(Row); end; function TDBXInt16SequenceGenerator.GetString(const Row: Int64): UnicodeString; var ShortRow: Integer; begin ShortRow := SmallInt(Row); Result := '' + IntToStr(ShortRow); end; procedure TDBXInt16SequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.SetInt16(GetInt16(Row)); end; constructor TDBXInt32SequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXInt32SequenceGenerator.Open; begin inherited Open; end; function TDBXInt32SequenceGenerator.GetInt32(const Row: Int64): Integer; begin Result := Integer(Row); end; function TDBXInt32SequenceGenerator.GetString(const Row: Int64): UnicodeString; var IntRow: Integer; begin IntRow := Integer(Row); Result := '' + IntToStr(IntRow); end; procedure TDBXInt32SequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.AsInt32 := GetInt32(Row); end; constructor TDBXInt64SequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXInt64SequenceGenerator.Open; begin inherited Open; end; function TDBXInt64SequenceGenerator.GetInt64(const Row: Int64): Int64; begin Result := Row; end; function TDBXInt64SequenceGenerator.GetString(const Row: Int64): UnicodeString; begin Result := '' + IntToStr((Row)); end; procedure TDBXInt64SequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.SetInt64(GetInt64(Row)); end; constructor TDBXInt8SequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXInt8SequenceGenerator.Open; begin inherited Open; end; function TDBXInt8SequenceGenerator.GetInt8(const Row: Int64): Byte; begin Result := Byte(Row); end; function TDBXInt8SequenceGenerator.GetString(const Row: Int64): UnicodeString; var ByteRow: Integer; begin ByteRow := Integer((Row and 255)); Result := '' + IntToStr(ByteRow); end; procedure TDBXInt8SequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.SetInt16(GetInt8(Row)); end; constructor TDBXTimeSequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXTimeSequenceGenerator.Open; begin inherited Open; end; function TDBXTimeSequenceGenerator.GetHour(const Row: Int64): Integer; begin Result := Integer(Row) mod 24; end; function TDBXTimeSequenceGenerator.GetMinute(const Row: Int64): Integer; begin Result := Integer(Row) mod 60; end; function TDBXTimeSequenceGenerator.GetSeconds(const Row: Int64): Integer; begin Result := Integer(Row) mod 60; end; function TDBXTimeSequenceGenerator.GetString(const Row: Int64): UnicodeString; begin Result := '' + IntToStr(GetHour(Row)) + ':' + IntToStr(GetMinute(Row)) + ':' + IntToStr(GetSeconds(Row)); end; procedure TDBXTimeSequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.AsString := GetString(Row); end; constructor TDBXTimestampSequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXTimestampSequenceGenerator.Open; begin inherited Open; end; function TDBXTimestampSequenceGenerator.GetYear(const Row: Int64): Integer; begin Result := 1970 + Integer(Row) mod 20; end; function TDBXTimestampSequenceGenerator.GetMonth(const Row: Int64): Integer; begin Result := (Integer(Row) mod 12) + 1; end; function TDBXTimestampSequenceGenerator.GetDay(const Row: Int64): Integer; begin Result := (Integer(Row) mod 28) + 1; end; function TDBXTimestampSequenceGenerator.GetHour(const Row: Int64): Integer; begin Result := Integer(Row) mod 24; end; function TDBXTimestampSequenceGenerator.GetMinute(const Row: Int64): Integer; begin Result := Integer(Row) mod 60; end; function TDBXTimestampSequenceGenerator.GetSeconds(const Row: Int64): Integer; begin Result := Integer(Row) mod 60; end; function TDBXTimestampSequenceGenerator.GetMilliseconds(const Row: Int64): Integer; begin Result := Integer(Row) mod 1000; end; function TDBXTimestampSequenceGenerator.GetString(const Row: Int64): UnicodeString; begin Result := '' + IntToStr(GetMonth(Row)) + '/' + IntToStr(GetDay(Row)) + '/' + IntToStr(GetYear(Row)) + IntToStr(GetHour(Row)) + ':' + IntToStr(GetMinute(Row)) + ':' + IntToStr(GetSeconds(Row)) + '.' + IntToStr(GetMilliseconds(Row)); end; procedure TDBXTimestampSequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.AsString := GetString(Row); end; constructor TDBXWideStringSequenceGenerator.Create(const MetaData: TDBXMetaDataColumn); begin inherited Create(MetaData); end; procedure TDBXWideStringSequenceGenerator.Open; begin inherited Open; end; function TDBXWideStringSequenceGenerator.GetString(const Row: Int64): UnicodeString; var Value: UnicodeString; begin Value := 'W' + IntToStr(Row); if FMetaDataColumn.FixedLength then while Length(Value) < FMetaDataColumn.Precision do Value := Value + ' '; Result := Value; end; procedure TDBXWideStringSequenceGenerator.SetValue(const Row: Int64; const Value: TDBXWritableValue); begin Value.AsString := GetString(Row); end; end.
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com TConerBtn component is a extended button with new style. It's an extended TBitBtn (caption with glyph): by PlaceConer property switch you can define a "button coner" and turn on/off the "light" in this coner PlaceConer property is controled the "coner" layout: pcNone - turn off - in this case it's a standard TBitBtn component pcTopLeft - pcTopRight - pcBottomLeft - pcBottomRight - TConvexBtn component - is a extension of standard TButton, but have a look like 3D cylinder } unit ConerBtn; interface {$I SMVersion.inc} uses Windows, Messages, Classes, Graphics, Controls, StdCtrls, Buttons; type TPlaceConer = (pcNone, pcTopLeft, pcTopRight, pcBottomLeft, pcBottomRight); TSymbolState = (ssNone, ssOpen, ssClose); type TPlaceSymbol = class(TPersistent) private FState: TSymbolState; FColorOpen: TColor; FColorClose: TColor; published property State: TSymbolState read FState write FState; property ColorOpen: TColor read FColorOpen write FColorOpen; property ColorClose: TColor read FColorClose write FColorClose; end; type {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TConerBtn = class(TBitBtn) private { Private declarations } FCanvas: TCanvas; FFlat: Boolean; FTransparent: Boolean; FGlyph: Pointer; FPlaceConer: TPlaceConer; IsFocused: Boolean; // FPlaceSymbol: TPlaceSymbol; FSymbolState: TSymbolState; FSymbolColorOpen: TColor; FSymbolColorClose: TColor; procedure DrawCornerSymbol(R: TRect; Flags: Longint); procedure DrawCornerButton(R: TRect; Flags: Longint); procedure DrawItem(const DrawItemStruct: TDrawItemStruct); procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM; procedure SetFlat(Value: Boolean); procedure SetPlaceConer(Value: TPlaceConer); procedure SetSymbolState(Value: TSymbolState); procedure SetSymbolColorOpen(Value: TColor); procedure SetSymbolColorClose(Value: TColor); procedure SetTransparent(Value: Boolean); protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } property Flat: Boolean read FFlat write SetFlat; property Color; property PlaceConer: TPlaceConer read FPlaceConer write SetPlaceConer; // property PlaceSymbol: TPlaceSymbol read FPlaceSymbol write SetPlaceSymbol; property SymbolState: TSymbolState read FSymbolState write SetSymbolState; property SymbolColorOpen: TColor read FSymbolColorOpen write SetSymbolColorOpen; property SymbolColorClose: TColor read FSymbolColorClose write SetSymbolColorClose; property Transparent: Boolean read FTransparent write SetTransparent; end; {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TConvexBtn = class(TBitBtn) //Button) private { Private declarations } FCanvas: TCanvas; IsFocused: Boolean; FTransparent: Boolean; FGlyph: Pointer; procedure DrawItem(const DrawItemStruct: TDrawItemStruct); procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM; procedure SetTransparent(Value: Boolean); protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } property Transparent: Boolean read FTransparent write SetTransparent; property Color; end; procedure Register; implementation uses TypInfo, CommCtrl; procedure Register; begin RegisterComponents('SMComponents', [TConerBtn, TConvexBtn]); end; {!!!! some idiot from Borland/Inprise keep a TGlyphList, TGlyphCache and TButtonGlyph types in the implementation section of the Buttons.Pas and I must to do copy of them} type TGlyphList = class(TImageList) private Used: TBits; FCount: Integer; function AllocateIndex: Integer; public constructor CreateSize(AWidth, AHeight: Integer); destructor Destroy; override; function AddMasked(Image: TBitmap; MaskColor: TColor): Integer; procedure Delete(Index: Integer); property Count: Integer read FCount; end; TGlyphCache = class private GlyphLists: TList; public constructor Create; destructor Destroy; override; function GetList(AWidth, AHeight: Integer): TGlyphList; procedure ReturnList(List: TGlyphList); function Empty: Boolean; end; TButtonGlyph = class private FOriginal: TBitmap; FGlyphList: TGlyphList; FIndexs: array[TButtonState] of Integer; FTransparentColor: TColor; FNumGlyphs: TNumGlyphs; FOnChange: TNotifyEvent; procedure GlyphChanged(Sender: TObject); procedure SetGlyph(Value: TBitmap); procedure SetNumGlyphs(Value: TNumGlyphs); procedure Invalidate; function CreateButtonGlyph(State: TButtonState): Integer; procedure DrawButtonGlyph(Canvas: TCanvas; const GlyphPos: TPoint; State: TButtonState; Transparent: Boolean); procedure DrawButtonText(Canvas: TCanvas; const Caption: string; TextBounds: TRect; State: TButtonState); procedure CalcButtonLayout(Canvas: TCanvas; const Client: TRect; const Offset: TPoint; const Caption: string; Layout: TButtonLayout; Margin, Spacing: Integer; var GlyphPos: TPoint; var TextBounds: TRect); public constructor Create; destructor Destroy; override; { return the text rectangle } function Draw(Canvas: TCanvas; const Client: TRect; const Offset: TPoint; const Caption: string; Layout: TButtonLayout; Margin, Spacing: Integer; State: TButtonState; Transparent: Boolean): TRect; property Glyph: TBitmap read FOriginal write SetGlyph; property NumGlyphs: TNumGlyphs read FNumGlyphs write SetNumGlyphs; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; { TGlyphList } constructor TGlyphList.CreateSize(AWidth, AHeight: Integer); begin inherited CreateSize(AWidth, AHeight); Used := TBits.Create; end; destructor TGlyphList.Destroy; begin Used.Free; inherited Destroy; end; function TGlyphList.AllocateIndex: Integer; begin Result := Used.OpenBit; if Result >= Used.Size then begin Result := inherited Add(nil, nil); Used.Size := Result + 1; end; Used[Result] := True; end; function TGlyphList.AddMasked(Image: TBitmap; MaskColor: TColor): Integer; begin Result := AllocateIndex; ReplaceMasked(Result, Image, MaskColor); Inc(FCount); end; procedure TGlyphList.Delete(Index: Integer); begin if Used[Index] then begin Dec(FCount); Used[Index] := False; end; end; { TGlyphCache } constructor TGlyphCache.Create; begin inherited Create; GlyphLists := TList.Create; end; destructor TGlyphCache.Destroy; begin GlyphLists.Free; inherited Destroy; end; function TGlyphCache.GetList(AWidth, AHeight: Integer): TGlyphList; var I: Integer; begin for I := GlyphLists.Count - 1 downto 0 do begin Result := GlyphLists[I]; with Result do if (AWidth = Width) and (AHeight = Height) then Exit; end; Result := TGlyphList.CreateSize(AWidth, AHeight); GlyphLists.Add(Result); end; procedure TGlyphCache.ReturnList(List: TGlyphList); begin if List = nil then Exit; if List.Count = 0 then begin GlyphLists.Remove(List); List.Free; end; end; function TGlyphCache.Empty: Boolean; begin Result := GlyphLists.Count = 0; end; var GlyphCache: TGlyphCache = nil; { TButtonGlyph } constructor TButtonGlyph.Create; var I: TButtonState; begin inherited Create; FOriginal := TBitmap.Create; FOriginal.OnChange := GlyphChanged; FTransparentColor := clOlive; FNumGlyphs := 1; for I := Low(I) to High(I) do FIndexs[I] := -1; if GlyphCache = nil then GlyphCache := TGlyphCache.Create; end; destructor TButtonGlyph.Destroy; begin FOriginal.Free; Invalidate; if Assigned(GlyphCache) and GlyphCache.Empty then begin GlyphCache.Free; GlyphCache := nil; end; inherited Destroy; end; procedure TButtonGlyph.Invalidate; var I: TButtonState; begin for I := Low(I) to High(I) do begin if FIndexs[I] <> -1 then FGlyphList.Delete(FIndexs[I]); FIndexs[I] := -1; end; GlyphCache.ReturnList(FGlyphList); FGlyphList := nil; end; procedure TButtonGlyph.GlyphChanged(Sender: TObject); begin if Sender = FOriginal then begin FTransparentColor := FOriginal.TransparentColor; Invalidate; if Assigned(FOnChange) then FOnChange(Self); end; end; procedure TButtonGlyph.SetGlyph(Value: TBitmap); var Glyphs: Integer; begin Invalidate; FOriginal.Assign(Value); if (Value <> nil) and (Value.Height > 0) then begin FTransparentColor := Value.TransparentColor; if Value.Width mod Value.Height = 0 then begin Glyphs := Value.Width div Value.Height; if Glyphs > 4 then Glyphs := 1; SetNumGlyphs(Glyphs); end; end; end; procedure TButtonGlyph.SetNumGlyphs(Value: TNumGlyphs); begin if (Value <> FNumGlyphs) and (Value > 0) then begin Invalidate; FNumGlyphs := Value; GlyphChanged(Glyph); end; end; function TButtonGlyph.CreateButtonGlyph(State: TButtonState): Integer; const ROP_DSPDxax = $00E20746; var TmpImage, DDB, MonoBmp: TBitmap; IWidth, IHeight: Integer; IRect, ORect: TRect; I: TButtonState; DestDC: HDC; begin if (State = bsDown) and (NumGlyphs < 3) then State := bsUp; Result := FIndexs[State]; if Result <> -1 then Exit; if (FOriginal.Width or FOriginal.Height) = 0 then Exit; IWidth := FOriginal.Width div FNumGlyphs; IHeight := FOriginal.Height; if FGlyphList = nil then begin if GlyphCache = nil then GlyphCache := TGlyphCache.Create; FGlyphList := GlyphCache.GetList(IWidth, IHeight); end; TmpImage := TBitmap.Create; try TmpImage.Width := IWidth; TmpImage.Height := IHeight; IRect := Rect(0, 0, IWidth, IHeight); TmpImage.Canvas.Brush.Color := clBtnFace; TmpImage.Palette := CopyPalette(FOriginal.Palette); I := State; if Ord(I) >= NumGlyphs then I := bsUp; ORect := Rect(Ord(I) * IWidth, 0, (Ord(I) + 1) * IWidth, IHeight); case State of bsUp, bsDown, bsExclusive: begin TmpImage.Canvas.CopyRect(IRect, FOriginal.Canvas, ORect); if FOriginal.TransparentMode = tmFixed then FIndexs[State] := FGlyphList.AddMasked(TmpImage, FTransparentColor) else FIndexs[State] := FGlyphList.AddMasked(TmpImage, clDefault); end; bsDisabled: begin MonoBmp := nil; DDB := nil; try MonoBmp := TBitmap.Create; DDB := TBitmap.Create; DDB.Assign(FOriginal); DDB.HandleType := bmDDB; if NumGlyphs > 1 then with TmpImage.Canvas do begin { Change white & gray to clBtnHighlight and clBtnShadow } CopyRect(IRect, DDB.Canvas, ORect); MonoBmp.Monochrome := True; MonoBmp.Width := IWidth; MonoBmp.Height := IHeight; { Convert white to clBtnHighlight } DDB.Canvas.Brush.Color := clWhite; MonoBmp.Canvas.CopyRect(IRect, DDB.Canvas, ORect); Brush.Color := clBtnHighlight; DestDC := Handle; SetTextColor(DestDC, clBlack); SetBkColor(DestDC, clWhite); BitBlt(DestDC, 0, 0, IWidth, IHeight, MonoBmp.Canvas.Handle, 0, 0, ROP_DSPDxax); { Convert gray to clBtnShadow } DDB.Canvas.Brush.Color := clGray; MonoBmp.Canvas.CopyRect(IRect, DDB.Canvas, ORect); Brush.Color := clBtnShadow; DestDC := Handle; SetTextColor(DestDC, clBlack); SetBkColor(DestDC, clWhite); BitBlt(DestDC, 0, 0, IWidth, IHeight, MonoBmp.Canvas.Handle, 0, 0, ROP_DSPDxax); { Convert transparent color to clBtnFace } DDB.Canvas.Brush.Color := ColorToRGB(FTransparentColor); MonoBmp.Canvas.CopyRect(IRect, DDB.Canvas, ORect); Brush.Color := clBtnFace; DestDC := Handle; SetTextColor(DestDC, clBlack); SetBkColor(DestDC, clWhite); BitBlt(DestDC, 0, 0, IWidth, IHeight, MonoBmp.Canvas.Handle, 0, 0, ROP_DSPDxax); end else begin { Create a disabled version } with MonoBmp do begin Assign(FOriginal); HandleType := bmDDB; Canvas.Brush.Color := clBlack; Width := IWidth; if Monochrome then begin Canvas.Font.Color := clWhite; Monochrome := False; Canvas.Brush.Color := clWhite; end; Monochrome := True; end; with TmpImage.Canvas do begin Brush.Color := clBtnFace; FillRect(IRect); Brush.Color := clBtnHighlight; SetTextColor(Handle, clBlack); SetBkColor(Handle, clWhite); BitBlt(Handle, 1, 1, IWidth, IHeight, MonoBmp.Canvas.Handle, 0, 0, ROP_DSPDxax); Brush.Color := clBtnShadow; SetTextColor(Handle, clBlack); SetBkColor(Handle, clWhite); BitBlt(Handle, 0, 0, IWidth, IHeight, MonoBmp.Canvas.Handle, 0, 0, ROP_DSPDxax); end; end; finally DDB.Free; MonoBmp.Free; end; FIndexs[State] := FGlyphList.AddMasked(TmpImage, clDefault); end; end; finally TmpImage.Free; end; Result := FIndexs[State]; FOriginal.Dormant; end; procedure TButtonGlyph.DrawButtonGlyph(Canvas: TCanvas; const GlyphPos: TPoint; State: TButtonState; Transparent: Boolean); var Index: Integer; begin if FOriginal = nil then Exit; if (FOriginal.Width = 0) or (FOriginal.Height = 0) then Exit; Index := CreateButtonGlyph(State); with GlyphPos do if Transparent or (State = bsExclusive) then ImageList_DrawEx(FGlyphList.Handle, Index, Canvas.Handle, X, Y, 0, 0, clNone, clNone, ILD_Transparent) else ImageList_DrawEx(FGlyphList.Handle, Index, Canvas.Handle, X, Y, 0, 0, ColorToRGB(clBtnFace), clNone, ILD_Normal); end; procedure TButtonGlyph.DrawButtonText(Canvas: TCanvas; const Caption: string; TextBounds: TRect; State: TButtonState); begin with Canvas do begin Brush.Style := bsClear; if State = bsDisabled then begin OffsetRect(TextBounds, 1, 1); Font.Color := clBtnHighlight; DrawText(Handle, PChar(Caption), Length(Caption), TextBounds, 0); OffsetRect(TextBounds, -1, -1); Font.Color := clBtnShadow; DrawText(Handle, PChar(Caption), Length(Caption), TextBounds, 0); end else DrawText(Handle, PChar(Caption), Length(Caption), TextBounds, DT_CENTER or DT_VCENTER or DT_SINGLELINE); end; end; procedure TButtonGlyph.CalcButtonLayout(Canvas: TCanvas; const Client: TRect; const Offset: TPoint; const Caption: string; Layout: TButtonLayout; Margin, Spacing: Integer; var GlyphPos: TPoint; var TextBounds: TRect); var TextPos: TPoint; ClientSize, GlyphSize, TextSize: TPoint; TotalSize: TPoint; begin { calculate the item sizes } ClientSize := Point(Client.Right - Client.Left, Client.Bottom - Client.Top); if FOriginal <> nil then GlyphSize := Point(FOriginal.Width div FNumGlyphs, FOriginal.Height) else GlyphSize := Point(0, 0); if Length(Caption) > 0 then begin TextBounds := Rect(0, 0, Client.Right - Client.Left, 0); DrawText(Canvas.Handle, PChar(Caption), Length(Caption), TextBounds, DT_CALCRECT); TextSize := Point(TextBounds.Right - TextBounds.Left, TextBounds.Bottom - TextBounds.Top); end else begin TextBounds := Rect(0, 0, 0, 0); TextSize := Point(0,0); end; { If the layout has the glyph on the right or the left, then both the text and the glyph are centered vertically. If the glyph is on the top or the bottom, then both the text and the glyph are centered horizontally.} if Layout in [blGlyphLeft, blGlyphRight] then begin GlyphPos.Y := (ClientSize.Y - GlyphSize.Y + 1) div 2; TextPos.Y := (ClientSize.Y - TextSize.Y + 1) div 2; end else begin GlyphPos.X := (ClientSize.X - GlyphSize.X + 1) div 2; TextPos.X := (ClientSize.X - TextSize.X + 1) div 2; end; { if there is no text or no bitmap, then Spacing is irrelevant } if (TextSize.X = 0) or (GlyphSize.X = 0) then Spacing := 0; { adjust Margin and Spacing } if Margin = -1 then begin if Spacing = -1 then begin TotalSize := Point(GlyphSize.X + TextSize.X, GlyphSize.Y + TextSize.Y); if Layout in [blGlyphLeft, blGlyphRight] then Margin := (ClientSize.X - TotalSize.X) div 3 else Margin := (ClientSize.Y - TotalSize.Y) div 3; Spacing := Margin; end else begin TotalSize := Point(GlyphSize.X + Spacing + TextSize.X, GlyphSize.Y + Spacing + TextSize.Y); if Layout in [blGlyphLeft, blGlyphRight] then Margin := (ClientSize.X - TotalSize.X + 1) div 2 else Margin := (ClientSize.Y - TotalSize.Y + 1) div 2; end; end else begin if Spacing = -1 then begin TotalSize := Point(ClientSize.X - (Margin + GlyphSize.X), ClientSize.Y - (Margin + GlyphSize.Y)); if Layout in [blGlyphLeft, blGlyphRight] then Spacing := (TotalSize.X - TextSize.X) div 2 else Spacing := (TotalSize.Y - TextSize.Y) div 2; end; end; case Layout of blGlyphLeft: begin GlyphPos.X := Margin; TextPos.X := GlyphPos.X + GlyphSize.X + Spacing; end; blGlyphRight: begin GlyphPos.X := ClientSize.X - Margin - GlyphSize.X; TextPos.X := GlyphPos.X - Spacing - TextSize.X; end; blGlyphTop: begin GlyphPos.Y := Margin; TextPos.Y := GlyphPos.Y + GlyphSize.Y + Spacing; end; blGlyphBottom: begin GlyphPos.Y := ClientSize.Y - Margin - GlyphSize.Y; TextPos.Y := GlyphPos.Y - Spacing - TextSize.Y; end; end; { fixup the result variables } Inc(GlyphPos.X, Client.Left + Offset.X); Inc(GlyphPos.Y, Client.Top + Offset.Y); OffsetRect(TextBounds, TextPos.X + Client.Left + Offset.X, TextPos.Y + Client.Top + Offset.X); end; function TButtonGlyph.Draw(Canvas: TCanvas; const Client: TRect; const Offset: TPoint; const Caption: string; Layout: TButtonLayout; Margin, Spacing: Integer; State: TButtonState; Transparent: Boolean): TRect; var GlyphPos: TPoint; begin CalcButtonLayout(Canvas, Client, Offset, Caption, Layout, Margin, Spacing, GlyphPos, Result); DrawButtonGlyph(Canvas, GlyphPos, State, Transparent); DrawButtonText(Canvas, Caption, Result, State); end; {TConerBtn} constructor TConerBtn.Create(AOwner: TComponent); begin inherited Create(AOwner); FSymbolState := ssClose; FSymbolColorOpen := clRed; FSymbolColorClose := clMaroon; FGlyph := TButtonGlyph.Create; FCanvas := TCanvas.Create; ControlStyle := [csOpaque]; end; destructor TConerBtn.Destroy; begin TButtonGlyph(FGlyph).Free; FCanvas.Free; inherited Destroy; end; procedure TConerBtn.CNDrawItem(var Message: TWMDrawItem); begin DrawItem(Message.DrawItemStruct^); end; procedure TConerBtn.DrawCornerSymbol(R: TRect; Flags: Longint); var CornerX, CornerY, Shift: Integer; Point1, Point2, Point3: TPoint; begin CornerX := (R.Right - R.Left) div 3; CornerY := (R.Bottom - R.Top) div 3; if (CornerX < CornerY) then CornerY := CornerX else CornerX := CornerY; Shift := 6; case FPlaceConer of pcTopLeft: begin Point1 := Point(R.Left + Shift, R.Bottom - CornerY - Shift); Point2 := Point(R.Left + Shift, R.Bottom - Shift); Point3 := Point(R.Left + CornerX + Shift, R.Bottom - Shift); end; pcTopRight: begin Point1 := Point(R.Right - Shift, R.Bottom - CornerY - Shift); Point2 := Point(R.Right - Shift, R.Bottom - Shift); Point3 := Point(R.Right - CornerX - Shift, R.Bottom - Shift); end; pcBottomLeft: begin Point1 := Point(R.Left + CornerX + Shift, R.Top + Shift); Point2 := Point(R.Left + Shift, R.Top + Shift); Point3 := Point(R.Left + Shift, R.Top + CornerY + Shift); end; pcBottomRight: begin Point1 := Point(R.Right - CornerX - Shift, R.Top + Shift); Point2 := Point(R.Right - Shift, R.Top + Shift); Point3 := Point(R.Right - Shift, R.Top + CornerY + Shift); end; end; { case FPlaceConer of pcTopLeft: begin Point1 := Point(R.Left + (8*CornerX div 9), R.Top + (CornerY div 3)); Point2 := Point(R.Left + (8*CornerX div 9), R.Top + (8*CornerY div 9)); Point3 := Point(R.Left + (CornerX div 3), R.Top + (8*CornerY div 9)); end; pcTopRight: begin Point1 := Point(R.Right - (8*CornerX div 9), R.Top + (CornerY div 3)); Point2 := Point(R.Right - (8*CornerX div 9), R.Top + (8*CornerY div 9)); Point3 := Point(R.Right - (CornerX div 3), R.Top + (8*CornerY div 9)); end; pcBottomLeft: begin Point1 := Point(R.Left + (CornerX div 3), R.Bottom - (8*CornerY div 9)); Point2 := Point(R.Left + (8*CornerX div 9), R.Bottom - (8*CornerY div 9)); Point3 := Point(R.Left + (8*CornerX div 9), R.Bottom - (CornerY div 3)); end; pcBottomRight: begin Point1 := Point(R.Right - (CornerX div 3), R.Bottom - (8*CornerY div 9)); Point2 := Point(R.Right - (8*CornerX div 9), R.Bottom - (8*CornerY div 9)); Point3 := Point(R.Right - (8*CornerX div 9), R.Bottom - (CornerY div 3)); end; end; } {draw top of the button symbol} FCanvas.Pen.Width := 1; if (FSymbolState = ssOpen) then FCanvas.Brush.Color := FSymbolColorOpen else FCanvas.Brush.Color := FSymbolColorClose; if Flags and DFCS_PUSHED <> 0 then FCanvas.Pen.Color := clBtnShadow else FCanvas.Pen.Color := clBtnHighlight; FCanvas.Polygon([Point1, Point2, Point3]); {draw bottom of the button symbol} FCanvas.Pen.Width := 1; if Flags and DFCS_PUSHED <> 0 then FCanvas.Pen.Color := clBtnHighlight else FCanvas.Pen.Color := clBtnShadow; FCanvas.Polyline([Point1, Point3]); end; procedure TConerBtn.DrawCornerButton(R: TRect; Flags: Longint); var CornerX, CornerY: Integer; begin CornerX := (R.Right - R.Left) div 3; CornerY := (R.Bottom - R.Top) div 3; if (CornerX < CornerY) then CornerY := CornerX else CornerX := CornerY; FCanvas.Pen.Style := psSolid; if (Flags = 0) then begin if FTransparent then case FPlaceConer of pcNone: FCanvas.Polyline([Point(R.Left, R.Top), Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom-1), Point(R.Left, R.Bottom-1)]); pcTopLeft: FCanvas.Polyline([Point(R.Left + CornerX, R.Top), Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom-1), Point(R.Left, R.Bottom-1), Point(R.Left, R.Top + CornerY)]); pcTopRight: FCanvas.Polyline([Point(R.Left, R.Top), Point(R.Right - CornerX, R.Top), Point(R.Right-1, R.Top + CornerY), Point(R.Right-1, R.Bottom-1), Point(R.Left, R.Bottom-1)]); pcBottomLeft: FCanvas.Polyline([Point(R.Left, R.Top), Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom-1), Point(R.Left + CornerX, R.Bottom-1), Point(R.Left, R.Bottom - CornerY)]); pcBottomRight: FCanvas.Polyline([Point(R.Left, R.Top), Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom - CornerY), Point(R.Right - CornerX, R.Bottom-1), Point(R.Left, R.Bottom-1)]); end else case FPlaceConer of pcNone: FCanvas.Polygon([Point(R.Left, R.Top), Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom-1), Point(R.Left, R.Bottom-1)]); pcTopLeft: FCanvas.Polygon([Point(R.Left + CornerX, R.Top), Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom-1), Point(R.Left, R.Bottom-1), Point(R.Left, R.Top + CornerY)]); pcTopRight: FCanvas.Polygon([Point(R.Left, R.Top), Point(R.Right - CornerX, R.Top), Point(R.Right-1, R.Top + CornerY), Point(R.Right-1, R.Bottom-1), Point(R.Left, R.Bottom-1)]); pcBottomLeft: FCanvas.Polygon([Point(R.Left, R.Top), Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom-1), Point(R.Left + CornerX, R.Bottom-1), Point(R.Left, R.Bottom - CornerY)]); pcBottomRight: FCanvas.Polygon([Point(R.Left, R.Top), Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom - CornerY), Point(R.Right - CornerX, R.Bottom-1), Point(R.Left, R.Bottom-1)]); end; end else begin {draw top of the button} if (Flags = -1) then begin FCanvas.Pen.Style := psDot; FCanvas.Pen.Color := clWindowFrame; end else begin if Flags and DFCS_PUSHED <> 0 then begin FCanvas.Pen.Color := clBtnShadow; FCanvas.Pen.Width := 1; FCanvas.Brush.Color := clBtnFace; end else begin FCanvas.Pen.Color := clBtnHighlight; FCanvas.Pen.Width := 1; FCanvas.Brush.Style := bsClear; end; end; case FPlaceConer of pcNone: FCanvas.Polyline([Point(R.Left, R.Bottom-1), Point(R.Left, R.Top), Point(R.Right-1, R.Top)]); pcTopLeft: FCanvas.Polyline([Point(R.Left, R.Bottom-1), Point(R.Left, R.Top + CornerY), Point(R.Left + CornerX, R.Top), Point(R.Right-1, R.Top)]); pcTopRight: FCanvas.Polyline([Point(R.Left, R.Bottom-1), Point(R.Left, R.Top), Point(R.Right - CornerX, R.Top), Point(R.Right-1, R.Top + CornerY)]); pcBottomLeft: FCanvas.Polyline([Point(R.Left, R.Bottom - CornerY), Point(R.Left, R.Top), Point(R.Right-1, R.Top)]); pcBottomRight: FCanvas.Polyline([Point(R.Left, R.Bottom-1), Point(R.Left, R.Top), Point(R.Right-1, R.Top)]); end; {draw bottom of the button} if (Flags <> -1) and (Flags and DFCS_PUSHED = 0) then begin FCanvas.Pen.Color := clBtnShadow; FCanvas.Pen.Width := 1; FCanvas.Brush.Color := clBtnFace; end; case FPlaceConer of pcNone: FCanvas.Polyline([Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom-1), Point(R.Left, R.Bottom-1)]); pcTopLeft: FCanvas.Polyline([Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom-1), Point(R.Left, R.Bottom-1)]); pcTopRight: FCanvas.Polyline([Point(R.Right-1, R.Top + CornerY), Point(R.Right-1, R.Bottom-1), Point(R.Left, R.Bottom-1)]); pcBottomLeft: FCanvas.Polyline([Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom-1), Point(R.Left + CornerX, R.Bottom-1), Point(R.Left, R.Bottom - CornerY)]); pcBottomRight: FCanvas.Polyline([Point(R.Right-1, R.Top), Point(R.Right-1, R.Bottom - CornerY), Point(R.Right - CornerX, R.Bottom-1), Point(R.Left, R.Bottom-1)]); end; end; InflateRect(R, -1, -1); end; procedure TConerBtn.DrawItem(const DrawItemStruct: TDrawItemStruct); var IsDown, IsDefault: Boolean; State: TButtonState; R: TRect; Flags: Longint; PropInfo: PPropInfo; begin FCanvas.Handle := DrawItemStruct.hDC; R := ClientRect; {clear button area} PropInfo := GetPropInfo(Parent.ClassInfo, 'Color'); if Assigned(PropInfo) then {if such property exists} begin FCanvas.Pen.Color := GetOrdProp(Parent, PropInfo); FCanvas.Brush.Color := FCanvas.Pen.Color; FCanvas.Rectangle(R.Left, R.Top, R.Right, R.Bottom); end; if not FTransparent then begin FCanvas.Brush.Style := bsSolid; //bsClear; FCanvas.Brush.Color := Color; Flags := 0; DrawCornerButton(R, Flags); end; with DrawItemStruct do begin IsDown := itemState and ODS_SELECTED <> 0; IsDefault := itemState and ODS_FOCUS <> 0; if not Enabled then State := bsDisabled else if IsDown then State := bsDown else State := bsUp; end; Flags := 0; { DrawFrameControl doesn't allow for drawing a button as the default button, so it must be done here. } if IsFocused or IsDefault then begin FCanvas.Pen.Color := clWindowFrame; FCanvas.Pen.Width := 1; FCanvas.Brush.Style := bsClear; DrawCornerButton(R, Flags); { DrawFrameControl must draw within this border } InflateRect(R, -1, -1); end; Flags := DFCS_BUTTONPUSH or DFCS_ADJUSTRECT; if IsDown then Flags := Flags or DFCS_PUSHED; if DrawItemStruct.itemState and ODS_DISABLED <> 0 then Flags := Flags or DFCS_INACTIVE; { DrawFrameControl does not draw a pressed button correctly } DrawCornerButton(R, Flags); if IsFocused then begin R := ClientRect; InflateRect(R, -1, -1); end; FCanvas.Font := Self.Font; if IsDown then OffsetRect(R, 1, 1); if (FPlaceConer <> pcNone) and (FSymbolState <> ssNone) then DrawCornerSymbol(R, Flags); TButtonGlyph(FGlyph).Glyph := Glyph as TBitmap; TButtonGlyph(FGlyph).Draw(FCanvas, R, Point(0,0), Caption, Layout, Margin, Spacing, State, FTransparent); {draw dotted frame for selected button} if IsFocused or IsDefault then begin R := ClientRect; InflateRect(R, -4, -4); DrawCornerButton(R, -1); DrawFocusRect(FCanvas.Handle, R); end; FCanvas.Handle := 0; end; procedure TConerBtn.SetFlat(Value: Boolean); begin if (Value <> FFlat) then begin FFlat := Value; Refresh end; end; procedure TConerBtn.SetPlaceConer(Value: TPlaceConer); begin if (Value <> FPlaceConer) then begin FPlaceConer := Value; Refresh end; end; procedure TConerBtn.SetSymbolState(Value: TSymbolState); begin if (Value <> FSymbolState) then begin FSymbolState := Value; Refresh; end; end; procedure TConerBtn.SetSymbolColorOpen(Value: TColor); begin if (Value <> FSymbolColorOpen) then begin FSymbolColorOpen := Value; Refresh; end; end; procedure TConerBtn.SetSymbolColorClose(Value: TColor); begin if (Value <> FSymbolColorClose) then begin FSymbolColorClose := Value; Refresh; end; end; procedure TConerBtn.SetTransparent(Value: Boolean); begin if (Value <> FTransparent) then begin FTransparent := Value; Refresh; end; end; {TConvexBtn} constructor TConvexBtn.Create(AOwner: TComponent); begin inherited Create(AOwner); FGlyph := TButtonGlyph.Create; FCanvas := TCanvas.Create; ControlStyle := [csOpaque]; end; destructor TConvexBtn.Destroy; begin TButtonGlyph(FGlyph).Free; FCanvas.Free; inherited Destroy; end; procedure TConvexBtn.CNDrawItem(var Message: TWMDrawItem); begin DrawItem(Message.DrawItemStruct^); end; procedure TConvexBtn.DrawItem(const DrawItemStruct: TDrawItemStruct); var IsDown, IsDefault: Boolean; State: TButtonState; R: TRect; Flags: Longint; begin FCanvas.Handle := DrawItemStruct.hDC; R := ClientRect; with DrawItemStruct do begin IsDown := itemState and ODS_SELECTED <> 0; IsDefault := itemState and ODS_FOCUS <> 0; if not Enabled then State := bsDisabled else if IsDown then State := bsDown else State := bsUp; end; if IsFocused or IsDefault then begin FCanvas.Pen.Color := clWindowFrame; FCanvas.Pen.Width := 1; FCanvas.Brush.Style := bsClear; FCanvas.Rectangle(R.Left, R.Top, R.Right-1, R.Bottom-1); { DrawFrameControl must draw within this border } InflateRect(R, -1, -1); end; FCanvas.Pen.Width := 1; FCanvas.Pen.Color := clWindowFrame; FCanvas.Brush.Color := Color; FCanvas.Rectangle(R.Left, R.Top, R.Right, R.Bottom); Flags := DFCS_BUTTONPUSH or DFCS_ADJUSTRECT; if IsDown then Flags := Flags or DFCS_PUSHED; if DrawItemStruct.itemState and ODS_DISABLED <> 0 then Flags := Flags or DFCS_INACTIVE; if Flags and DFCS_PUSHED <> 0 then FCanvas.Pen.Color := clBtnShadow else FCanvas.Pen.Color := clBtnHighlight; if Flags and DFCS_PUSHED <> 0 then begin { FCanvas.Pen.Color := clBtnHighlight; FCanvas.Pen.Width := 3; FCanvas.MoveTo(R.Left+2, R.Bottom-3); FCanvas.LineTo(R.Right-3, R.Bottom-3); } FCanvas.Pen.Color := clBtnShadow; FCanvas.Pen.Width := 2; FCanvas.MoveTo(R.Left+2, R.Top+2); FCanvas.LineTo(R.Right-2, R.Top+2); end else begin FCanvas.Pen.Color := clBtnHighlight; FCanvas.Pen.Width := 2; FCanvas.MoveTo(R.Left+2, R.Top+2); FCanvas.LineTo(R.Right-2, R.Top+2); FCanvas.Pen.Color := clBtnShadow; FCanvas.Pen.Width := 3; FCanvas.MoveTo(R.Left+2, R.Bottom-3); FCanvas.LineTo(R.Right-3, R.Bottom-3); end; if IsFocused then begin R := ClientRect; InflateRect(R, -1, -1); end; FCanvas.Font := Self.Font; if IsDown then OffsetRect(R, 1, 1); TButtonGlyph(FGlyph).Glyph := Glyph as TBitmap; TButtonGlyph(FGlyph).Draw(FCanvas, R, Point(0,0), Caption, Layout, Margin, Spacing, State, FTransparent); {draw dotted frame for selected button} if IsFocused or IsDefault then begin R := ClientRect; InflateRect(R, -6, -6); FCanvas.Pen.Color := clWindowFrame; FCanvas.Brush.Color := clBtnFace; DrawFocusRect(FCanvas.Handle, R); end; FCanvas.Handle := 0; end; procedure TConvexBtn.SetTransparent(Value: Boolean); begin if (Value <> FTransparent) then begin FTransparent := Value; Refresh; end; end; end.
#skip unit iDPascalParser; interface {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} uses iDStringParser, SysUtils, Classes, CompilerClasses, CompilerMessages, CompilerErrors; type TTokenID = ( token_unknown {= -1}, // unknown token token_eof {= 0}, // end of file token_identifier, // some id token_numbersign, // # token_semicolon, // ; token_colon, // : token_assign, // := token_equal, // = token_above, // > token_aboveorequal, // >= token_less, // < token_lessorequal, // <= token_notequal, // <> token_period, // .. token_plus, // + token_minus, // - token_asterisk, // * token_slash, // / token_caret, // ^ token_address, // @ token_coma, // , token_dot, // . token_openround, // ( token_closeround, // ) token_openblock, // [ token_closeblock, // ] token_openfigure, // { token_closefigure, // } token_absolute, // keyword: absolute token_asm, // keyword: asm token_stdcall, // keyword: stdcall token_fastcall, // keyword: fastcall token_cdecl, // keyword: cdecl token_unit, // keyword: unit token_program, // keyword: program token_pure, // keyword: pure token_library, // keyword: library token_uses, // keyword: uses token_export, // keyword: export token_external, // keyword: extern token_name, // keyword: name token_exit, // keyword: exit token_interface, // keyword: interface token_implementation, // keyword: implementation token_implement, // keyword: implementation token_initialization, // keyword: initialization token_finalization, // keyword: finalization token_begin, // keyword: begin token_end, // keyword: end token_var, // keyword: var token_out, // keyword: out token_const, // keyword: const token_constref, // keyword: constref token_procedure, // keyword: procedure token_function, // keyword: function token_overload, // keyword: overload token_override, // keyword: override token_openarray, // keyword: openarray token_type, // keyword: type token_token, // keyword: #token token_class, // keyword: class token_record, // keyword: record token_packed, // keyword: packed token_set, // keyword: set token_array, // keyword: array token_if, // keyword: if token_iif, // keyword: iif token_icase, // keyword: icase token_in, // keyword: in token_inline, // keyword: inline token_is, // keyword: is token_then, // keyword: if token_else, // keyword: else token_forward, // keyword: forward token_noreturn, // keyword: noreturn token_namespace, // keyword: namespace token_continue, // keyword: continue token_break, // keyword: break token_async, // keyword: async token_await, // keyword: await token_not, // keyword: not token_and, // keyword: and token_or, // keyword: or token_xor, // keyword: xor token_div, // keyword: div token_mod, // keyword: mod token_shl, // keyword: shl token_shr, // keyword: shr token_rol, // keyword: rol token_ror, // keyword: ror token_as, // keyword: as token_for, // keyword: for token_to, // keyword: to token_downto, // keyword: downto token_do, // keyword: do token_deprecated, // keyword: depricated token_while, // keyword: while token_weak, // keyword: weak token_repeat, // keyword: repeat token_reintroduce, // keyword: reintroduce token_until, // keyword: until token_union, // keyword: union token_with, // keyword: until token_case, // keyword: case token_of, // keyword: of token_operator, // keyword: operator token_try, // keyword: try token_finally, // keyword: finally token_except, // keyword: except token_strict, // keyword: strict token_step, // keyword: step token_property, // keyword: property token_private, // keyword: private token_protected, // keyword: protected token_public, // keyword: public token_published, // keyword: published token_read, // keyword: read token_write, // keyword: write token_inherited, // keyword: inherited token_virtual, // keyword: virtual token_dynamic, // keyword: dynamic token_static, // keyword: static token_constructor, // keyword: constructor token_destructor, // keyword: destructor token_default, // keyword: default token_cond_define, // #define token_cond_undefine, // #undefine token_cond_ifdef, // #ifdef token_cond_ifndef, // #ifndef token_cond_if, // #if token_cond_else, // #else token_cond_end, // #end token_cond_include, // #include token_cond_error, // #error token_cond_warning, // #warning token_cond_hint // #hint ); TPascalParser = class(TStringParser) public function NextToken: TTokenID; inline; function TokenLexem(TokenID: TTokenID): string; constructor Create(const Source: string); override; procedure RegisterToken(const Token: string; TokenID: TTokenID; const TokenCaption: string; TokenType: TTokenType = ttToken); overload; procedure RegisterToken(const Token: string; TokenID: TTokenID; CanBeID: Boolean = False); overload; procedure ReadCurrIdentifier(var Identifier: TIdentifier); inline; procedure ReadNextIdentifier(var Identifier: TIdentifier); inline; procedure MatchToken(ActualToken, ExpectedToken: TTokenID); inline; procedure MatchNextToken(ExpectedToken: TTokenID); inline; end; function TokenCanBeID(TokenID: TTokenID): Boolean; inline; var FTokensAttr: array [TTokenID] of Boolean; implementation { TiDealParser } function TokenCanBeID(TokenID: TTokenID): Boolean; begin Result := FTokensAttr[TokenID]; end; procedure TPascalParser.ReadCurrIdentifier(var Identifier: TIdentifier); begin Identifier.Name := OriginalToken; Identifier.TextPosition := Position; end; procedure TPascalParser.ReadNextIdentifier(var Identifier: TIdentifier); begin if NextToken = token_Identifier then begin Identifier.Name := OriginalToken; Identifier.TextPosition := Position; end else AbortWork(sIdExpectedButFoundFmt, [TokenLexem(TTokenID(CurrentTokenID))], PrevPosition); end; procedure TPascalParser.MatchToken(ActualToken, ExpectedToken: TTokenID); begin if ActualToken <> ExpectedToken then AbortWork(sExpected, [UpperCase(TokenLexem(ExpectedToken))], PrevPosition); end; constructor TPascalParser.Create(const Source: string); begin inherited Create(Source); IdentifireID := integer(token_identifier); EofID := integer(token_eof); TokenCaptions.AddObject('end of file', TObject(token_eof)); TokenCaptions.AddObject('identifier', TObject(token_identifier)); SeparatorChars := '#$ '''#9#10#13'%^&*@()+-{}[]\/,.;:<>='; RegisterToken('#', token_NumberSign, '', ttDigit); RegisterToken('#define', token_cond_define); RegisterToken('#else', token_cond_else); RegisterToken('#end', token_cond_end); RegisterToken('#if', token_cond_if); RegisterToken('#ifdef', token_cond_ifdef); RegisterToken('#ifndef', token_cond_ifndef); RegisterToken('#undefine', token_cond_undefine); RegisterToken('#include', token_cond_include); RegisterToken('#error', token_cond_error); RegisterToken('#warning', token_cond_warning); RegisterToken('#hint', token_cond_hint); RegisterToken('#token', token_token); RegisterToken('$', token_Unknown, '', ttHexPrefix); RegisterToken('%', token_Unknown, '', ttBinPrefix); RegisterToken(' ', token_Unknown, '', ttOmited); RegisterToken(#9, token_Unknown, '', ttOmited); RegisterToken(#10, token_Unknown, '', ttNewLine); RegisterToken(#13#10, token_Unknown, '', ttNewLine); RegisterToken(#13, token_Unknown, '', ttOmited); RegisterToken('''', token_unknown, '', ttQuote); RegisterToken('//', token_unknown, '', ttOneLineRem); RegisterToken(';', token_semicolon, 'semicolon'); RegisterToken(',', token_coma, 'coma'); RegisterToken(':', token_colon, 'colon'); RegisterToken('=', token_equal, 'equal'); RegisterToken('>', token_above); RegisterToken('>=', token_aboveorequal); RegisterToken('<', token_less); RegisterToken('<=', token_lessorequal); RegisterToken('<>', token_notequal); RegisterToken('.', token_dot, 'dot', ttToken); RegisterToken('..', token_period, 'period'); RegisterToken('(', token_openround, 'open round'); RegisterToken(')', token_closeround, 'close round'); RegisterToken('[', token_openblock); RegisterToken(']', token_closeblock); RegisterToken('+', token_plus, 'plus'); RegisterToken('-', token_minus, 'minus'); RegisterToken('*', token_asterisk, 'asterisk'); RegisterToken('/', token_slash); RegisterToken('^', token_caret); RegisterToken('@', token_address); RegisterToken(':=', token_assign); RegisterToken('absolute', token_absolute); RegisterToken('as', token_as); RegisterToken('asm', token_asm); RegisterToken('and', token_and); RegisterToken('array', token_array); RegisterToken('async', token_async); RegisterToken('await', token_await); RegisterToken('begin', token_begin, True); RegisterToken('break', token_break); RegisterToken('case', token_case); RegisterToken('cdecl', token_cdecl, True); RegisterToken('const', token_const); RegisterToken('constref', token_constref); RegisterToken('constructor', token_constructor); RegisterToken('continue', token_continue); RegisterToken('class', token_class); RegisterToken('do', token_do); RegisterToken('downto', token_downto); RegisterToken('div', token_div); RegisterToken('destructor', token_destructor); RegisterToken('deprecated', token_deprecated); RegisterToken('default', token_default, True); RegisterToken('dynamic', token_dynamic); RegisterToken('end', token_end, true); RegisterToken('else', token_else); RegisterToken('exit', token_exit); RegisterToken('except', token_except); RegisterToken('export', token_export); RegisterToken('external', token_external); RegisterToken('function', token_Function); RegisterToken('for', token_for); RegisterToken('forward', token_forward); RegisterToken('finally', token_finally); RegisterToken('finalization', token_finalization); RegisterToken('fastcall', token_fastcall); RegisterToken('if', token_if); RegisterToken('iif', token_iif); RegisterToken('is', token_is); RegisterToken('in', token_in); RegisterToken('interface', token_Interface); RegisterToken('inherited', token_inherited); RegisterToken('inline', token_inline); RegisterToken('initialization', token_initialization); RegisterToken('implementation', token_Implementation); RegisterToken('implement', token_implement); RegisterToken('library', token_library); RegisterToken('mod', token_mod); RegisterToken('not', token_not); RegisterToken('noreturn', token_noreturn); RegisterToken('name', token_name, true); RegisterToken('namespace', token_namespace, true); RegisterToken('of', token_of); RegisterToken('or', token_or); RegisterToken('out', token_Out); RegisterToken('override', token_Override); RegisterToken('overload', token_Overload); RegisterToken('operator', token_operator); RegisterToken('openarray', token_openarray); RegisterToken('procedure', token_Procedure); RegisterToken('property', token_property); RegisterToken('protected', token_protected); RegisterToken('program', token_program); RegisterToken('private', token_private); RegisterToken('pure', token_pure); RegisterToken('public', token_public); RegisterToken('published', token_published); RegisterToken('packed', token_packed); RegisterToken('record', token_record); RegisterToken('read', token_read, True); RegisterToken('repeat', token_repeat); RegisterToken('reintroduce', token_reintroduce); RegisterToken('rol', token_rol); RegisterToken('ror', token_ror); RegisterToken('set', token_set); RegisterToken('shl', token_shl); RegisterToken('shr', token_shr); RegisterToken('static', token_static); RegisterToken('strict', token_strict); RegisterToken('step', token_step); RegisterToken('stdcall', token_stdcall); RegisterToken('then', token_then); RegisterToken('to', token_to); RegisterToken('try', token_try); RegisterToken('type', token_Type); RegisterToken('until', token_until); RegisterToken('unit', token_unit); RegisterToken('union', token_union); RegisterToken('uses', token_uses); RegisterToken('var', token_Var); RegisterToken('virtual', token_virtual); RegisterToken('weak', token_weak); RegisterToken('with', token_with); RegisterToken('while', token_while); RegisterToken('write', token_write, True); RegisterToken('xor', token_xor); RegisterRemToken('{', '}'); RegisterRemToken('(*', '*)'); end; procedure TPascalParser.MatchNextToken(ExpectedToken: TTokenID); begin if TTokenID(NextTokenID) <> ExpectedToken then AbortWork(sExpected, [UpperCase(TokenLexem(ExpectedToken))], PrevPosition); end; function TPascalParser.NextToken: TTokenID; begin Result := TTokenID(NextTokenID); end; procedure TPascalParser.RegisterToken(const Token: string; TokenID: TTokenID; const TokenCaption: string; TokenType: TTokenType); begin inherited RegisterToken(Token, Integer(TokenID), TokenType, TokenCaption); FTokensAttr[TokenID] := False; end; procedure TPascalParser.RegisterToken(const Token: string; TokenID: TTokenID; CanBeID: Boolean); begin inherited RegisterToken(Token, Integer(TokenID), ttToken, Token); FTokensAttr[TokenID] := CanBeID; end; function TPascalParser.TokenLexem(TokenID: TTokenID): string; begin Result := inherited TokenLexem(Integer(TokenID)); end; end.
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { } { Copyright (c) 2000, 2001 Borland Software Corporation } { } { *************************************************************************** } unit QStdActns; {$H+,X+} interface uses Classes, QActnList, QStdCtrls, QForms, QClipbrd; type { Hint actions } THintAction = class(TCustomAction) public constructor Create(AOwner: TComponent); override; published property Hint; end; { Edit actions } TEditAction = class(TAction) private FEditControl: TCustomEdit; FMemoControl: TCustomMemo; procedure SetEditControl(Value: TCustomEdit); procedure SetMemoControl(Value: TCustomMemo); protected function GetEditControl(Target: TObject): TCustomEdit; virtual; function GetMemoControl(Target: TObject): TCustomMemo; virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public function HandlesTarget(Target: TObject): Boolean; override; procedure UpdateTarget(Target: TObject); override; property EditControl: TCustomEdit read FEditControl write SetEditControl; property MemoControl: TCustomMemo read FMemoControl write SetMemoControl; end; TEditCut = class(TEditAction) public procedure ExecuteTarget(Target: TObject); override; end; TEditCopy = class(TEditAction) public procedure ExecuteTarget(Target: TObject); override; end; TEditPaste = class(TEditAction) public procedure UpdateTarget(Target: TObject); override; procedure ExecuteTarget(Target: TObject); override; end; TEditSelectAll = class(TEditAction) public procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; end; TEditDelete = class(TEditAction) public procedure ExecuteTarget(Target: TObject); override; end; { MDI Window actions } TWindowAction = class(TAction) private FForm: TForm; procedure SetForm(Value: TForm); protected function GetForm(Target: TObject): TForm; virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public function HandlesTarget(Target: TObject): Boolean; override; procedure UpdateTarget(Target: TObject); override; property Form: TForm read FForm write SetForm; end; TWindowClose = class(TWindowAction) public procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; end; TWindowCascade = class(TWindowAction) public procedure ExecuteTarget(Target: TObject); override; end; TWindowTile = class(TWindowAction) public procedure ExecuteTarget(Target: TObject); override; end; TWindowMinimizeAll = class(TWindowAction) public procedure ExecuteTarget(Target: TObject); override; end; { Help actions } THelpAction = class(TAction) public function HandlesTarget(Target: TObject): Boolean; override; procedure UpdateTarget(Target: TObject); override; end; THelpContents = class(THelpAction) public procedure ExecuteTarget(Target: TObject); override; end; THelpTopicSearch = class(THelpAction) public procedure ExecuteTarget(Target: TObject); override; end; implementation uses SysUtils, QConsts, QSearch; { THintAction } constructor THintAction.Create(AOwner: TComponent); begin inherited Create(AOwner); DisableIfNoHandler := False; end; { TEditAction } function TEditAction.GetEditControl(Target: TObject): TCustomEdit; begin { We could hard cast Target as a TCustomEdit since HandlesTarget "should" be called before ExecuteTarget and UpdateTarget, however, we're being safe. } Result := Target as TCustomEdit; end; function TEditAction.HandlesTarget(Target: TObject): Boolean; begin Result := ((((EditControl <> nil) and (Target = EditControl)) or ((EditControl = nil) and (Target is TCustomEdit))) and TCustomEdit(Target).Focused) or ((((MemoControl <> nil) and (Target = MemoControl)) or ((MemoControl = nil) and (Target is TCustomMemo))) and TCustomMemo(Target).Focused); end; procedure TEditAction.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = EditControl) then EditControl := nil; if (Operation = opRemove) and (AComponent = MemoControl) then MemoControl := nil; end; procedure TEditAction.UpdateTarget(Target: TObject); begin if (Self is TEditCut) or (Self is TEditCopy) or (Self is TEditDelete) then Enabled := ((Target is TCustomEdit) and (GetEditControl(Target).SelLength > 0)) or ((Target is TCustomMemo) and (GetMemoControl(Target).SelLength > 0)); end; procedure TEditAction.SetEditControl(Value: TCustomEdit); begin if Value <> FEditControl then begin FEditControl := Value; if Value <> nil then Value.FreeNotification(Self); end; end; function TEditAction.GetMemoControl(Target: TObject): TCustomMemo; begin Result := Target as TCustomMemo; end; procedure TEditAction.SetMemoControl(Value: TCustomMemo); begin if Value <> FMemoControl then begin FMemoControl := Value; if Value <> nil then Value.FreeNotification(Self); end; end; { TEditCopy } procedure TEditCopy.ExecuteTarget(Target: TObject); begin if Target is TCustomEdit then GetEditControl(Target).CopyToClipboard else if Target is TCustomMemo then GetMemoControl(Target).CopyToClipboard; end; { TEditCut } procedure TEditCut.ExecuteTarget(Target: TObject); begin if Target is TCustomEdit then GetEditControl(Target).CutToClipboard else if Target is TCustomMemo then GetMemoControl(Target).CutToClipboard; end; { TEditPaste } procedure TEditPaste.ExecuteTarget(Target: TObject); begin if Target is TCustomEdit then GetEditControl(Target).PasteFromClipboard else if Target is TCustomMemo then GetMemoControl(Target).PasteFromClipboard; end; procedure TEditPaste.UpdateTarget(Target: TObject); begin Enabled := Clipboard.Provides('text/plain'); // do not localize end; { TEditSelectAll } procedure TEditSelectAll.ExecuteTarget(Target: TObject); begin if Target is TCustomEdit then GetEditControl(Target).SelectAll else if Target is TCustomMemo then GetMemoControl(Target).SelectAll; end; procedure TEditSelectAll.UpdateTarget(Target: TObject); begin Enabled := ((Target is TCustomEdit) and (Length(GetEditControl(Target).Text) > 0)) or ((Target is TCustomMemo) and (Length(GetMemoControl(Target).Text) > 0)); end; { TEditDelete } procedure TEditDelete.ExecuteTarget(Target: TObject); begin if Target is TCustomEdit then GetEditControl(Target).Clear else if Target is TCustomMemo then GetMemoControl(Target).Clear; end; { TWindowAction } function TWindowAction.GetForm(Target: TObject): TForm; begin { We could hard cast Target as a TForm since HandlesTarget "should" be called before ExecuteTarget and UpdateTarget, however, we're being safe. } Result := (Target as TForm); end; function TWindowAction.HandlesTarget(Target: TObject): Boolean; begin Result := ((Form <> nil) and (Target = Form) or (Form = nil) and (Target is TForm)) and (TForm(Target).FormStyle = fsMDIForm); end; procedure TWindowAction.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = Form) then Form := nil; end; procedure TWindowAction.UpdateTarget(Target: TObject); begin Enabled := GetForm(Target).MDIChildCount > 0; end; procedure TWindowAction.SetForm(Value: TForm); begin if Value <> FForm then begin FForm := Value; if Value <> nil then Value.FreeNotification(Self); end; end; { TWindowClose } procedure TWindowClose.ExecuteTarget(Target: TObject); begin with GetForm(Target) do if ActiveMDIChild <> nil then ActiveMDIChild.Close; end; procedure TWindowClose.UpdateTarget(Target: TObject); begin Enabled := GetForm(Target).ActiveMDIChild <> nil; end; { TWindowCascade } procedure TWindowCascade.ExecuteTarget(Target: TObject); begin GetForm(Target).Cascade; end; { TWindowTile } procedure TWindowTile.ExecuteTarget(Target: TObject); begin GetForm(Target).Tile; end; { TWindowMinimizeAll } procedure TWindowMinimizeAll.ExecuteTarget(Target: TObject); var I: Integer; begin { Must be done backwards through the MDIChildren array } with GetForm(Target) do for I := MDIChildCount - 1 downto 0 do MDIChildren[I].WindowState := wsMinimized; end; { THelpAction } function THelpAction.HandlesTarget(Target: TObject): Boolean; begin Result := True; end; procedure THelpAction.UpdateTarget(Target: TObject); begin Enabled := Assigned(Application); end; { THelpContents } procedure THelpContents.ExecuteTarget(Target: TObject); begin Application.HelpSystem.ShowTableOfContents; end; { THelpTopicSearch } procedure THelpTopicSearch.ExecuteTarget(Target: TObject); begin Application.HelpSystem.ShowHelp('',''); end; end.
unit ClassBoard; interface uses ClassBaseBoard, ClassLetters, Classes, Controls, ExtCtrls, Graphics; type TScoreType = ( stSingle, stDblL, stTrpL, stDblW, stTrpW ); const CBckgndColor = $00000000; CDblLColor = $00FFB0B0; CTrpLColor = $00FF1010; CDblWColor = $00B0B0FF; CTrpWColor = $001010FF; CNumRows = 15; CNumCols = 15; CBoard : array[1..CNumRows,1..CNumCols] of TScoreType = (( stTrpW , stSingle, stSingle, stDblL , stSingle, stSingle, stSingle, stTrpW , stSingle, stSingle, stSingle, stDblL , stSingle, stSingle, stTrpW ), ( stSingle, stDblW , stSingle, stSingle, stSingle, stTrpL , stSingle, stSingle, stSingle, stTrpL , stSingle, stSingle, stSingle, stDblW , stSingle), ( stSingle, stSingle, stDblW , stSingle, stSingle, stSingle, stDblL , stSingle, stDblL , stSingle, stSingle, stSingle, stDblW , stSingle, stSingle), ( stDblL , stSingle, stSingle, stDblW , stSingle, stSingle, stSingle, stDblL , stSingle, stSingle, stSingle, stDblW , stSingle, stSingle, stDblL ), ( stSingle, stSingle, stSingle, stSingle, stDblW , stSingle, stSingle, stSingle, stSingle, stSingle, stDblW , stSingle, stSingle, stSingle, stSingle), ( stSingle, stTrpL , stSingle, stSingle, stSingle, stTrpL , stSingle, stSingle, stSingle, stTrpL , stSingle, stSingle, stSingle, stTrpL , stSingle), ( stSingle, stSingle, stDblL , stSingle, stSingle, stSingle, stDblL , stSingle, stDblL , stSingle, stSingle, stSingle, stDblL , stSingle, stSingle), ( stTrpW , stSingle, stSingle, stDblL , stSingle, stSingle, stSingle, stDblW , stSingle, stSingle, stSingle, stDblL , stSingle, stSingle, stTrpW ), ( stSingle, stSingle, stDblL , stSingle, stSingle, stSingle, stDblL , stSingle, stDblL , stSingle, stSingle, stSingle, stDblL , stSingle, stSingle), ( stSingle, stTrpL , stSingle, stSingle, stSingle, stTrpL , stSingle, stSingle, stSingle, stTrpL , stSingle, stSingle, stSingle, stTrpL , stSingle), ( stSingle, stSingle, stSingle, stSingle, stDblW , stSingle, stSingle, stSingle, stSingle, stSingle, stDblW , stSingle, stSingle, stSingle, stSingle), ( stDblL , stSingle, stSingle, stDblW , stSingle, stSingle, stSingle, stDblL , stSingle, stSingle, stSingle, stDblW , stSingle, stSingle, stDblL ), ( stSingle, stSingle, stDblW , stSingle, stSingle, stSingle, stDblL , stSingle, stDblL , stSingle, stSingle, stSingle, stDblW , stSingle, stSingle), ( stSingle, stDblW , stSingle, stSingle, stSingle, stTrpL , stSingle, stSingle, stSingle, stTrpL , stSingle, stSingle, stSingle, stDblW , stSingle), ( stTrpW , stSingle, stSingle, stDblL , stSingle, stSingle, stSingle, stTrpW , stSingle, stSingle, stSingle, stDblL , stSingle, stSingle, stTrpW )); type TTile = record Letter : TLetter; X, Y : integer; end; TBoardLtr = record Letter : TLetter; ThisTurn : boolean; end; TLtrsBoard = array[1..CNumRows,1..CNumCols] of TBoardLtr; TOnClickEvent = procedure( X, Y : integer ) of object; TBoard = class( TBaseBoard ) private FLetters : TLtrsBoard; FOnClick : TOnCLickEvent; procedure PaintBoard; procedure OnMouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer ); public constructor Create( Image : TImage ); destructor Destroy; override; procedure Clear; function AddLetter( X, Y : integer; var Letter : TLetter ) : boolean; procedure RemoveLetter( X, Y : integer ); procedure EndMove; function GetScore : integer; property OnClick : TOnClickEvent read FOnClick write FOnClick; property Letters : TLtrsBoard read FLetters; end; implementation uses SysUtils, UnitFormJoker; //============================================================================== // Constructor / destructor //============================================================================== constructor TBoard.Create( Image : TImage ); begin inherited Create( Image ); FImage.OnMouseDown := OnMouseDown; FOnClick := nil; end; destructor TBoard.Destroy; begin inherited; end; //============================================================================== // P R I V A T E //============================================================================== procedure TBoard.PaintBoard; var I, J : integer; Color : TColor; begin FImage.Canvas.Brush.Color := CBckgndColor; FImage.Canvas.FillRect( FImage.ClientRect ); for I := 1 to CNumRows do for J := 1 to CNumCols do begin if ((FLetters[I,J].Letter.C = #0) or (FLetters[I,J].ThisTurn)) then begin case CBoard[I,J] of stSingle : Color := CEmptyColor; stDblL : Color := CDblLColor; stTrpL : Color := CTrpLColor; stDblW : Color := CDblWColor; stTrpW : Color := CTrpWColor; else Color := CBckgndColor; end; PaintEmpty( (J-1)*(CStoneSize+1) , (I-1)*(CStoneSize+1) , Color ); end; end; end; procedure TBoard.OnMouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer ); var I, J : integer; begin if ((X = 0) or (X = FImage.Width-1) or (Y = 0) or (Y = FImage.Height-1)) then exit; I := (X div (CStoneSize + 1)) + 1; J := (Y div (CStoneSize + 1)) + 1; if (Assigned( FOnClick )) then FOnClick( I , J ); end; //============================================================================== // P U B L I C //============================================================================== procedure TBoard.Clear; var I, J : integer; begin for I := 1 to CNumRows do for J := 1 to CNumCols do FLetters[I,J].Letter.C := #0; PaintBoard; end; function TBoard.AddLetter( X, Y : integer; var Letter : TLetter ) : boolean; begin if (FLetters[Y,X].Letter.C = #0) then begin if (Letter.C = '?') then begin FormJoker.ShowModal; if ((FormJoker.Edit.Text <> '') and (UpCase( FormJoker.Edit.Text[1] ) in ['A'..'Z'])) then Letter.C := LowerCase( FormJoker.Edit.Text[1] )[1] else begin Result := false; exit; end; end; FLetters[Y,X].Letter := Letter; FLetters[Y,X].ThisTurn := true; PaintLetter( FLetters[Y,X].Letter , X , Y , CLtrColor , CLtrBckColor ); Result := true; end else Result := false; end; procedure TBoard.RemoveLetter( X, Y : integer ); var Color : TColor; begin FLetters[Y,X].Letter.C := #0; FLetters[Y,X].ThisTurn := false; case CBoard[Y,X] of stSingle : Color := CEmptyColor; stDblL : Color := CDblLColor; stTrpL : Color := CTrpLColor; stDblW : Color := CDblWColor; stTrpW : Color := CTrpWColor; else Color := CBckgndColor; end; PaintEmpty( (X-1)*(CStoneSize+1) , (Y-1)*(CStoneSize+1) , Color ); end; procedure TBoard.EndMove; var I, J : integer; begin for I := 1 to CNumRows do for J := 1 to CNumCols do if (FLetters[I,J].ThisTurn) then begin FLetters[I,J].ThisTurn := false; PaintLetter( FLetters[I,J].Letter , J , I , CLtrColor , CLtrBckColor ); end; end; function TBoard.GetScore : integer; var I,J : integer; Word : string; IsNew : boolean; WordScore : integer; LtrScore : integer; Count : integer; begin Result := 0; for I := 1 to CNumRows do begin Word := ''; IsNew := false; WordScore := 1; LtrScore := 0; J := 1; repeat if (FLetters[I,J].Letter.C <> #0) then begin Word := Word + FLetters[I,J].Letter.C; Inc( LtrScore , FLetters[I,J].Letter.Value ); if (FLetters[I,J].ThisTurn) then case (CBoard[I,J]) of stDblL : Inc( LtrScore , FLetters[I,J].Letter.Value ); stTrpL : Inc( LtrScore , FLetters[I,J].Letter.Value*2 ); stDblW : WordScore := WordScore*2; stTrpW : WordScore := WordScore*3; end; if (FLetters[I,J].ThisTurn) then IsNew := true; end else begin if ((Word <> '') and (Length( Word ) > 1) and (IsNew)) then Result := Result + (LtrScore*WordScore); Word := ''; IsNew := false; WordScore := 1; LtrScore := 0; end; Inc( J ); if ((J > CNumCols) and (Word <> '') and (Length( Word ) > 1) and (IsNew)) then Result := Result + (LtrScore*WordScore); until (J > CNumCols); end; for J := 1 to CNumCols do begin Word := ''; IsNew := false; WordScore := 1; LtrScore := 0; I := 1; repeat if (FLetters[I,J].Letter.C <> #0) then begin Word := Word + FLetters[I,J].Letter.C; Inc( LtrScore , FLetters[I,J].Letter.Value ); if (FLetters[I,J].ThisTurn) then case (CBoard[I,J]) of stDblL : Inc( LtrScore , FLetters[I,J].Letter.Value ); stTrpL : Inc( LtrScore , FLetters[I,J].Letter.Value*2 ); stDblW : WordScore := WordScore*2; stTrpW : WordScore := WordScore*3; end; if (FLetters[I,J].ThisTurn) then IsNew := true; end else begin if ((Word <> '') and (Length( Word ) > 1) and (IsNew)) then Result := Result + (LtrScore*WordScore); Word := ''; IsNew := false; WordScore := 1; LtrScore := 0; end; Inc( I ); if ((I > CNumRows) and (Word <> '') and (Length( Word ) > 1) and (IsNew)) then Result := Result + (LtrScore*WordScore); until (I > CNumRows); end; Count := 0; for I := Low( FLetters ) to High( FLetters ) do for J := Low( FLetters[I] ) to High( FLetters[I] ) do if (FLetters[I,J].ThisTurn) then Inc( Count ); if (Count = 7) then Inc( Result , 50 ); end; end.
(***************************************************************************** * Pascal Solution to "How Many Zeroes?" from the * * * * Seventh Annual UCF ACM UPE High School Programming Tournament * * May 15, 1993 * * * * This program computes the number of zeroes at the end of the decimal * * expansion of the factorial of a given number. Note that a zero occurs * * at the end of a decimal expansion for every factor of 10 of the number, * * or for every factor of 2*5. Now, there are always more factors of 2 than * * of 5 for a number, so the number of fives must be the number of 2*5's * * which are factors of the number. Therefore, we simply count the number * * of factors of 5 of the factorial, which gives us the number of zeroes at * * the end. * *****************************************************************************) program Zeroes( input, output ); var infile : text; (* Input file *) n, (* As defined in problem; we are considering n! *) i, (* Loop variable *) k, (* Used to determine the number of factors of 5 *) num_zeroes : integer; (* Number of zeroes at the end of n! *) begin assign( infile, 'zeroes.in' ); reset( infile ); while not eof( infile ) do begin num_zeroes := 0; readln( infile, n ); (* Loop for each number from 1 to n and determine the number of *) (* factors of 5 in each one. *) for i := 1 to n do begin k := i; (* Count the number of factors of 5 in this integer *) while (k mod 5 = 0) and (k>0) do begin inc( num_zeroes ); k := k div 5; end; end; if num_zeroes = 1 then writeln( 'There is 1 zero at the end of ', n:1, '!.' ) else writeln( 'There are ', num_zeroes:1, ' zeroes at the end of ', n:1, '!.' ); end; close( infile ); end.
unit constexpr_case_1; interface implementation function GetValue(a: int32): string; pure; begin case a of 0: Result := 'zero'; 1: Result := 'one'; 2: Result := 'two'; else Result := 'any'; end; end; var s0, s1, s2, sa: string; procedure Test; begin s0 := GetValue(0); s1 := GetValue(1); s2 := GetValue(2); sa := GetValue(3); end; initialization Test(); finalization Assert(s0 = 'zero'); Assert(s1 = 'one'); Assert(s2 = 'two'); Assert(sa = 'any'); end.
unit ff7sound; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, FF7Snd, StdCtrls, ComCtrls, Buttons, BaseUtil; type TfrmCosmoSound = class(TForm) lstSound: TListView; savWAV: TSaveDialog; opnWav: TOpenDialog; opnAudio: TOpenDialog; btnOpen: TBitBtn; btnExtract: TBitBtn; btnReplace: TBitBtn; btnPlay: TBitBtn; BitBtn1: TBitBtn; btnRestore: TBitBtn; procedure btnLoadClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnPlayClick(Sender: TObject); procedure btnExtractClick(Sender: TObject); procedure btnReplaceClick(Sender: TObject); procedure btnRestoreClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure LoadFromFolder(Fld:String); end; var frmCosmoSound: TfrmCosmoSound; Snd: TFF7Sound=nil; implementation {$R *.DFM} procedure TfrmCosmoSound.LoadFromFolder(Fld:String); var LI: TListItem; I: Integer; Desc: TFF7SoundDesc; begin Snd := TFF7Sound.CreateFromFolder(Fld); lstSound.Items.Clear; For I := 0 to Snd.NumFiles-1 do begin LI := lstSound.Items.Add; LI.Caption := IntToStr(I); Desc := Snd.Sounds[I]; LI.Subitems.Add(FileSizeStr(Desc.Size)); LI.Subitems.Add(IntToStr(Desc.Freq)); end; end; procedure TfrmCosmoSound.btnLoadClick(Sender: TObject); begin If Not opnAudio.Execute then Exit; LoadFromFolder(ExtractFilePath(opnAudio.Filename)); end; procedure TfrmCosmoSound.FormDestroy(Sender: TObject); begin If Snd<>nil then Snd.Free; end; procedure TfrmCosmoSound.btnPlayClick(Sender: TObject); begin If lstSound.Selected<>nil then begin btnPlay.Enabled := False; Snd.PlaySound(lstSound.Selected.Index); btnPlay.Enabled := True; end; end; procedure TfrmCosmoSound.btnExtractClick(Sender: TObject); var Mem: TMemoryStream; begin If lstSound.Selected=nil then Exit; If not savWAV.Execute then Exit; Mem := Snd.Data[lstSound.Selected.Index]; Mem.SaveToFile(savWAV.Filename); Mem.Free; end; procedure TfrmCosmoSound.btnReplaceClick(Sender: TObject); var Mem: TMemoryStream; begin If lstSound.Selected=nil then Exit; If not opnWAV.Execute then Exit; CopyFile(PChar(opnAudio.Filename),PChar(ExtractFilePath(opnAudio.Filename)+'AUDIOFMT.BAK'),True); Mem := TMemoryStream.Create; Mem.LoadFromFile(opnWAV.Filename); Snd.Data[lstSound.Selected.Index] := Mem; Mem.Free; Snd.Free; Snd := nil; LoadFromFolder(ExtractFilePath(opnAudio.Filename)); end; procedure TfrmCosmoSound.btnRestoreClick(Sender: TObject); begin CopyFile(PChar(ExtractFilePath(opnAudio.Filename)+'AUDIOFMT.BAK'),PChar(opnAudio.Filename),False); end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.ProgressDialog.Types; interface uses System.Classes; type { TfgNativeActivityDialog } /// <summary> /// Base class for implementation native progress/activity dialogs /// </summary> TfgNativeDialog = class abstract private [Weak] FOwner: TObject; FTitle: string; FMessage: string; FIsShown: Boolean; FCancellable: Boolean; FOnShow: TNotifyEvent; FOnHide: TNotifyEvent; FOnCancel: TNotifyEvent; procedure SetMessage(const Value: string); procedure SetTitle(const Value: string); procedure SetCancellable(const Value: Boolean); protected procedure CancellableChanged; virtual; procedure MessageChanged; virtual; procedure TitleChanged; virtual; function GetIsShown: Boolean; virtual; procedure DoShow; procedure DoHide; public constructor Create(const AOwner: TObject); virtual; procedure Show; virtual; procedure Hide; virtual; public property Owner: TObject read FOwner; property Cancellable: Boolean read FCancellable write SetCancellable; property Message: string read FMessage write SetMessage; property Title: string read FTitle write SetTitle; property IsShown: Boolean read GetIsShown; property OnCancel: TNotifyEvent read FOnCancel write FOnCancel; property OnShow: TNotifyEvent read FOnShow write FOnShow; property OnHide: TNotifyEvent read FOnHide write FOnHide; end; /// <summary> /// Base class for implementation native activity dialogs /// </summary> TfgNativeActivityDialog = class abstract (TfgNativeDialog); { TfgNativeProgressDialog } /// <summary> /// <para> /// Display mode of progress dialog. /// </para> /// </summary> /// <remarks> /// <list type="bullet"> /// <item> /// Undeterminated - We temporarily don't know, when operation will start /// </item> /// <item> /// Determinated - We already know and evaluated operation time (in %) /// </item> /// </list> /// </remarks> TfgProgressDialogKind = (Undeterminated, Determinated); /// <summary> /// Base class for implementation native progress dialogs /// </summary> TfgNativeProgressDialog = class abstract(TfgNativeDialog) private FKind: TfgProgressDialogKind; FProgress: Single; FMax: Single; procedure SetKind(const AValue: TfgProgressDialogKind); procedure SetProgress(const AValue: Single); procedure SetMax(const AValue: Single); protected procedure ProgressChanged; virtual; procedure KindChanged; virtual; procedure RangeChanged; virtual; public procedure ResetProgress; virtual; public property Kind: TfgProgressDialogKind read FKind write SetKind default TfgProgressDialogKind.Undeterminated; property Max: Single read FMax write SetMax; property Progress: Single read FProgress write SetProgress; end; { IFGXProgressDialogService } /// <summary> /// Factory for creation native progress and activity dialogs /// </summary> IFGXProgressDialogService = interface ['{10598EF4-3AAD-4D3A-A2FF-3DF3446D815F}'] function CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog; function CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog; end; implementation uses System.Math, FGX.Helpers, FGX.Consts, FGX.Asserts; { TfgNativeDialog } procedure TfgNativeDialog.CancellableChanged; begin // Nothing end; constructor TfgNativeDialog.Create(const AOwner: TObject); begin FOwner := AOwner; FIsShown := False; end; procedure TfgNativeDialog.DoHide; begin if Assigned(FOnHide) then FOnHide(FOwner); end; procedure TfgNativeDialog.DoShow; begin if Assigned(FOnShow) then FOnShow(FOwner); end; function TfgNativeDialog.GetIsShown: Boolean; begin Result := FIsShown; end; procedure TfgNativeDialog.Hide; begin FIsShown := False; end; procedure TfgNativeDialog.MessageChanged; begin // Nothing end; procedure TfgNativeDialog.SetCancellable(const Value: Boolean); begin if Cancellable <> Value then begin FCancellable := Value; CancellableChanged; end; end; procedure TfgNativeDialog.SetMessage(const Value: string); begin if Message <> Value then begin FMessage := Value; MessageChanged; end; end; procedure TfgNativeDialog.SetTitle(const Value: string); begin if Title <> Value then begin FTitle := Value; TitleChanged; end; end; procedure TfgNativeDialog.Show; begin FIsShown := True; end; procedure TfgNativeDialog.TitleChanged; begin // Nothing end; { TfgNativeProgressDialog } procedure TfgNativeProgressDialog.KindChanged; begin // Nothing end; procedure TfgNativeProgressDialog.ProgressChanged; begin // Nothing end; procedure TfgNativeProgressDialog.RangeChanged; begin // Nothing end; procedure TfgNativeProgressDialog.SetKind(const AValue: TfgProgressDialogKind); begin if Kind <> AValue then begin FKind := AValue; KindChanged; end; end; procedure TfgNativeProgressDialog.SetMax(const AValue: Single); begin AssertMoreThan(AValue, 0); if not SameValue(AValue, Max, EPSILON_SINGLE) then begin FMax := AValue; RangeChanged; end; end; procedure TfgNativeProgressDialog.SetProgress(const AValue: Single); begin AssertInRange(AValue, 0, Max, 'Progress value must be in range [Min..Max]'); if not SameValue(Progress, AValue, EPSILON_SINGLE) then begin FProgress := EnsureRange(AValue, 0, Max); ProgressChanged; end; end; procedure TfgNativeProgressDialog.ResetProgress; begin FProgress := 0; end; end.
unit BrickCamp.Model.IEmployee; interface uses Spring; type IEmployee = interface(IInterface) ['{E31612DC-EB02-4576-B119-575696111EF6}'] function GetDepartmentNumber: string; function GetFirstName: string; function GetHireDate: TDateTime; function GetId: Integer; function GetJobCode: string; function GetJobCountry: string; function GetJobGrade: SmallInt; function GetLastName: string; function GetPhoneExt: Nullable<string>; function GetSalary: Extended; procedure SetDepartmentNumber(const Value: string); procedure SetFirstName(const Value: string); procedure SetHireDate(const Value: TDateTime); procedure SetJobCode(const Value: string); procedure SetJobCountry(const Value: string); procedure SetJobGrade(const Value: SmallInt); procedure SetLastName(const Value: string); procedure SetPhoneExt(const Value: Nullable<string>); procedure SetSalary(const Value: Extended); end; implementation end.
unit Controller.Visita; interface uses Horse, System.JSON, System.StrUtils, System.SysUtils, System.Classes, Server.Connection, DAO.Visita; procedure RegisterVisita; procedure List (Req: THorseRequest; Res: THorseResponse; Next: TProc); procedure Find (Req: THorseRequest; Res: THorseResponse; Next: TProc); procedure Insert (Req: THorseRequest; Res: THorseResponse; Next: TProc); procedure Update (Req: THorseRequest; Res: THorseResponse; Next: TProc); procedure Delete (Req: THorseRequest; Res: THorseResponse; Next: TProc); implementation procedure RegisterVisita; begin THorse.Get('/visita' , List); THorse.Get('/visita/:id' , Find); THorse.Post('/visita' , Insert); THorse.Put('/visita' , Update); THorse.Delete('/visita' , Delete); end; procedure List (Req: THorseRequest; Res: THorseResponse; Next: TProc); var LConn : TConnectionData; LDAOVisita : TDAOVisita; begin try LConn := TConnectionData.Create; try LDAOVisita := TDAOVisita.Create(LConn); Res.Send<TJSONArray>(LDAOVisita.List); finally LDAOVisita.Free; end; finally LConn.Free; end; end; procedure Find (Req: THorseRequest; Res: THorseResponse; Next: TProc); begin end; procedure Insert (Req: THorseRequest; Res: THorseResponse; Next: TProc); begin end; procedure Update (Req: THorseRequest; Res: THorseResponse; Next: TProc); begin end; procedure Delete (Req: THorseRequest; Res: THorseResponse; Next: TProc); begin end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Vcl.GraphUtil; interface uses {$IF DEFINED(CLR) OR DEFINED(MSWINDOWS)} Winapi.Windows, Vcl.Graphics, {$IFEND} {$IF DEFINED(LINUX)} Types, QGraphics, {$IFEND} System.Classes; {$IF NOT DEFINED(CLR)} {$DEFINE USE_ZLIB} {$IFEND} type TColorArray = array of TIdentMapEntry; const WebNamedColorsCount = 138; WebNamedColors: array[0..WebNamedColorsCount - 1] of TIdentMapEntry = ( // light colors snow -> tan (Value: clWebSnow; Name: 'clWebSnow'), { do not localize } (Value: clWebFloralWhite; Name: 'clWebFloralWhite'), { do not localize } (Value: clWebLavenderBlush; Name: 'clWebLavenderBlush'), { do not localize } (Value: clWebOldLace; Name: 'clWebOldLace'), { do not localize } (Value: clWebIvory; Name: 'clWebIvory'), { do not localize } (Value: clWebCornSilk; Name: 'clWebCornSilk'), { do not localize } (Value: clWebBeige; Name: 'clWebBeige'), { do not localize } (Value: clWebAntiqueWhite; Name: 'clWebAntiqueWhite'), { do not localize } (Value: clWebWheat; Name: 'clWebWheat'), { do not localize } (Value: clWebAliceBlue; Name: 'clWebAliceBlue'), { do not localize } (Value: clWebGhostWhite; Name: 'clWebGhostWhite'), { do not localize } (Value: clWebLavender; Name: 'clWebLavender'), { do not localize } (Value: clWebSeashell; Name: 'clWebSeashell'), { do not localize } (Value: clWebLightYellow; Name: 'clWebLightYellow'), { do not localize } (Value: clWebPapayaWhip; Name: 'clWebPapayaWhip'), { do not localize } (Value: clWebNavajoWhite; Name: 'clWebNavajoWhite'), { do not localize } (Value: clWebMoccasin; Name: 'clWebMoccasin'), { do not localize } (Value: clWebBurlywood; Name: 'clWebBurlywood'), { do not localize } (Value: clWebAzure; Name: 'clWebAzure'), { do not localize } (Value: clWebMintcream; Name: 'clWebMintcream'), { do not localize } (Value: clWebHoneydew; Name: 'clWebHoneydew'), { do not localize } (Value: clWebLinen; Name: 'clWebLinen'), { do not localize } (Value: clWebLemonChiffon; Name: 'clWebLemonChiffon'), { do not localize } (Value: clWebBlanchedAlmond; Name: 'clWebBlanchedAlmond'), { do not localize } (Value: clWebBisque; Name: 'clWebBisque'), { do not localize } (Value: clWebPeachPuff; Name: 'clWebPeachPuff'), { do not localize } (Value: clWebTan; Name: 'clWebTan'), { do not localize } // yellows/reds yellow -> rosybrown (Value: clWebYellow; Name: 'clWebYellow'), { do not localize } (Value: clWebDarkOrange; Name: 'clWebDarkOrange'), { do not localize } (Value: clWebRed; Name: 'clWebRed'), { do not localize } (Value: clWebDarkRed; Name: 'clWebDarkRed'), { do not localize } (Value: clWebMaroon; Name: 'clWebMaroon'), { do not localize } (Value: clWebIndianRed; Name: 'clWebIndianRed'), { do not localize } (Value: clWebSalmon; Name: 'clWebSalmon'), { do not localize } (Value: clWebCoral; Name: 'clWebCoral'), { do not localize } (Value: clWebGold; Name: 'clWebGold'), { do not localize } (Value: clWebTomato; Name: 'clWebTomato'), { do not localize } (Value: clWebCrimson; Name: 'clWebCrimson'), { do not localize } (Value: clWebBrown; Name: 'clWebBrown'), { do not localize } (Value: clWebChocolate; Name: 'clWebChocolate'), { do not localize } (Value: clWebSandyBrown; Name: 'clWebSandyBrown'), { do not localize } (Value: clWebLightSalmon; Name: 'clWebLightSalmon'), { do not localize } (Value: clWebLightCoral; Name: 'clWebLightCoral'), { do not localize } (Value: clWebOrange; Name: 'clWebOrange'), { do not localize } (Value: clWebOrangeRed; Name: 'clWebOrangeRed'), { do not localize } (Value: clWebFirebrick; Name: 'clWebFirebrick'), { do not localize } (Value: clWebSaddleBrown; Name: 'clWebSaddleBrown'), { do not localize } (Value: clWebSienna; Name: 'clWebSienna'), { do not localize } (Value: clWebPeru; Name: 'clWebPeru'), { do not localize } (Value: clWebDarkSalmon; Name: 'clWebDarkSalmon'), { do not localize } (Value: clWebRosyBrown; Name: 'clWebRosyBrown'), { do not localize } // greens palegoldenrod -> darkseagreen (Value: clWebPaleGoldenrod; Name: 'clWebPaleGoldenrod'), { do not localize } (Value: clWebLightGoldenrodYellow; Name: 'clWebLightGoldenrodYellow'),{ do not localize } (Value: clWebOlive; Name: 'clWebOlive'), { do not localize } (Value: clWebForestGreen; Name: 'clWebForestGreen'), { do not localize } (Value: clWebGreenYellow; Name: 'clWebGreenYellow'), { do not localize } (Value: clWebChartreuse; Name: 'clWebChartreuse'), { do not localize } (Value: clWebLightGreen; Name: 'clWebLightGreen'), { do not localize } (Value: clWebAquamarine; Name: 'clWebAquamarine'), { do not localize } (Value: clWebSeaGreen; Name: 'clWebSeaGreen'), { do not localize } (Value: clWebGoldenRod; Name: 'clWebGoldenRod'), { do not localize } (Value: clWebKhaki; Name: 'clWebKhaki'), { do not localize } (Value: clWebOliveDrab; Name: 'clWebOliveDrab'), { do not localize } (Value: clWebGreen; Name: 'clWebGreen'), { do not localize } (Value: clWebYellowGreen; Name: 'clWebYellowGreen'), { do not localize } (Value: clWebLawnGreen; Name: 'clWebLawnGreen'), { do not localize } (Value: clWebPaleGreen; Name: 'clWebPaleGreen'), { do not localize } (Value: clWebMediumAquamarine; Name: 'clWebMediumAquamarine'), { do not localize } (Value: clWebMediumSeaGreen; Name: 'clWebMediumSeaGreen'), { do not localize } (Value: clWebDarkGoldenRod; Name: 'clWebDarkGoldenRod'), { do not localize } (Value: clWebDarkKhaki; Name: 'clWebDarkKhaki'), { do not localize } (Value: clWebDarkOliveGreen; Name: 'clWebDarkOliveGreen'), { do not localize } (Value: clWebDarkgreen; Name: 'clWebDarkgreen'), { do not localize } (Value: clWebLimeGreen; Name: 'clWebLimeGreen'), { do not localize } (Value: clWebLime; Name: 'clWebLime'), { do not localize } (Value: clWebSpringGreen; Name: 'clWebSpringGreen'), { do not localize } (Value: clWebMediumSpringGreen; Name: 'clWebMediumSpringGreen'), { do not localize } (Value: clWebDarkSeaGreen; Name: 'clWebDarkSeaGreen'), { do not localize } // greens/blues lightseagreen -> navy (Value: clWebLightSeaGreen; Name: 'clWebLightSeaGreen'), { do not localize } (Value: clWebPaleTurquoise; Name: 'clWebPaleTurquoise'), { do not localize } (Value: clWebLightCyan; Name: 'clWebLightCyan'), { do not localize } (Value: clWebLightBlue; Name: 'clWebLightBlue'), { do not localize } (Value: clWebLightSkyBlue; Name: 'clWebLightSkyBlue'), { do not localize } (Value: clWebCornFlowerBlue; Name: 'clWebCornFlowerBlue'), { do not localize } (Value: clWebDarkBlue; Name: 'clWebDarkBlue'), { do not localize } (Value: clWebIndigo; Name: 'clWebIndigo'), { do not localize } (Value: clWebMediumTurquoise; Name: 'clWebMediumTurquoise'), { do not localize } (Value: clWebTurquoise; Name: 'clWebTurquoise'), { do not localize } (Value: clWebCyan; Name: 'clWebCyan'), { do not localize } // (Value: clWebAqua; Name: 'clWebAqua'), { do not localize } (Value: clWebPowderBlue; Name: 'clWebPowderBlue'), { do not localize } (Value: clWebSkyBlue; Name: 'clWebSkyBlue'), { do not localize } (Value: clWebRoyalBlue; Name: 'clWebRoyalBlue'), { do not localize } (Value: clWebMediumBlue; Name: 'clWebMediumBlue'), { do not localize } (Value: clWebMidnightBlue; Name: 'clWebMidnightBlue'), { do not localize } (Value: clWebDarkTurquoise; Name: 'clWebDarkTurquoise'), { do not localize } (Value: clWebCadetBlue; Name: 'clWebCadetBlue'), { do not localize } (Value: clWebDarkCyan; Name: 'clWebDarkCyan'), { do not localize } (Value: clWebTeal; Name: 'clWebTeal'), { do not localize } (Value: clWebDeepSkyBlue; Name: 'clWebDeepskyBlue'), { do not localize } (Value: clWebDodgerBlue; Name: 'clWebDodgerBlue'), { do not localize } (Value: clWebBlue; Name: 'clWebBlue'), { do not localize } (Value: clWebNavy; Name: 'clWebNavy'), { do not localize } // violets/pinks darkviolet -> pink (Value: clWebDarkViolet; Name: 'clWebDarkViolet'), { do not localize } (Value: clWebDarkOrchid; Name: 'clWebDarkOrchid'), { do not localize } (Value: clWebMagenta; Name: 'clWebMagenta'), { do not localize } // (Value: clWebFuchsia; Name: 'clWebFuchsia'), { do not localize } (Value: clWebDarkMagenta; Name: 'clWebDarkMagenta'), { do not localize } (Value: clWebMediumVioletRed; Name: 'clWebMediumVioletRed'), { do not localize } (Value: clWebPaleVioletRed; Name: 'clWebPaleVioletRed'), { do not localize } (Value: clWebBlueViolet; Name: 'clWebBlueViolet'), { do not localize } (Value: clWebMediumOrchid; Name: 'clWebMediumOrchid'), { do not localize } (Value: clWebMediumPurple; Name: 'clWebMediumPurple'), { do not localize } (Value: clWebPurple; Name: 'clWebPurple'), { do not localize } (Value: clWebDeepPink; Name: 'clWebDeepPink'), { do not localize } (Value: clWebLightPink; Name: 'clWebLightPink'), { do not localize } (Value: clWebViolet; Name: 'clWebViolet'), { do not localize } (Value: clWebOrchid; Name: 'clWebOrchid'), { do not localize } (Value: clWebPlum; Name: 'clWebPlum'), { do not localize } (Value: clWebThistle; Name: 'clWebThistle'), { do not localize } (Value: clWebHotPink; Name: 'clWebHotPink'), { do not localize } (Value: clWebPink; Name: 'clWebPink'), { do not localize } // blue/gray/black lightsteelblue -> black (Value: clWebLightSteelBlue; Name: 'clWebLightSteelBlue'), { do not localize } (Value: clWebMediumSlateBlue; Name: 'clWebMediumSlateBlue'), { do not localize } (Value: clWebLightSlateGray; Name: 'clWebLightSlateGray'), { do not localize } (Value: clWebWhite; Name: 'clWebWhite'), { do not localize } (Value: clWebLightgrey; Name: 'clWebLightgrey'), { do not localize } (Value: clWebGray; Name: 'clWebGray'), { do not localize } (Value: clWebSteelBlue; Name: 'clWebSteelBlue'), { do not localize } (Value: clWebSlateBlue; Name: 'clWebSlateBlue'), { do not localize } (Value: clWebSlateGray; Name: 'clWebSlateGray'), { do not localize } (Value: clWebWhiteSmoke; Name: 'clWebWhiteSmoke'), { do not localize } (Value: clWebSilver; Name: 'clWebSilver'), { do not localize } (Value: clWebDimGray; Name: 'clWebDimGray'), { do not localize } (Value: clWebMistyRose; Name: 'clWebMistyRose'), { do not localize } (Value: clWebDarkSlateBlue; Name: 'clWebDarkSlateBlue'), { do not localize } (Value: clWebDarkSlategray; Name: 'clWebDarkSlategray'), { do not localize } (Value: clWebGainsboro; Name: 'clWebGainsboro'), { do not localize } (Value: clWebDarkGray; Name: 'clWebDarkGray'), { do not localize } (Value: clWebBlack; Name: 'clWebBlack')); { do not localize } type TScrollDirection = (sdLeft, sdRight, sdUp, sdDown); TArrowType = (atSolid, atArrows); { GetHighLightColor and GetShadowColor take a Color and calculate an "appropriate" highlight/shadow color for that value. If the color's saturation is beyond 220 then it's lumination is decreased rather than increased. Since these routines may be called repeatedly for (potentially) the same color value they cache the results of the previous call. } function GetHighLightColor(const Color: TColor; Luminance: Integer = 19): TColor; function GetShadowColor(const Color: TColor; Luminance: Integer = -50): TColor; { Draws checkmarks of any Size at Location with/out a shadow. } procedure DrawCheck(ACanvas: TCanvas; Location: TPoint; Size: Integer; Shadow: Boolean = True); { Draws arrows that look like ">" which can point in any TScrollDirection } procedure DrawChevron(ACanvas: TCanvas; Direction: TScrollDirection; Location: TPoint; Size: Integer); { Draws a solid triangular arrow that can point in any TScrollDirection } procedure DrawArrow(ACanvas: TCanvas; Direction: TScrollDirection; Location: TPoint; Size: Integer); { The following routines mimic the like named routines from Shlwapi.dll except these routines do not rely on any specific version of IE being installed. } { Calculates Hue, Luminance and Saturation for the clrRGB value } procedure ColorRGBToHLS(clrRGB: TColorRef; var Hue, Luminance, Saturation: Word); { Calculates a color given Hue, Luminance and Saturation values } function ColorHLSToRGB(Hue, Luminance, Saturation: Word): TColorRef; { Given a color and a luminance change "n" this routine returns a color whose luminace has been changed accordingly. } function ColorAdjustLuma(clrRGB: TColor; n: Integer; fScale: BOOL): TColor; { GradientFillCanvas draws a gradient on ACanvas using AStartColor and AEndColor in the given Direction. GradientFillCanvas requires Windows 98, 2000 or better. On OS' that do not support the Microsoft GradientFill API this function returns without changing the canvas. } type TGradientDirection = (gdHorizontal, gdVertical); procedure GradientFillCanvas(const ACanvas: TCanvas; const AStartColor, AEndColor: TColor; const ARect: TRect; const Direction: TGradientDirection); { ScaleImage scales SourceBitmap into ResizedBitmap by ScaleAmount. A ScalAmount of 1 does nothing, < 0 shrinks, and > 0 enlarges } procedure ScaleImage(const SourceBitmap, ResizedBitmap: TBitmap; const ScaleAmount: Double); { Converts a TColor to a Web color constant like #FFFFFF } function ColorToWebColorStr(Color: TColor): string; { Converts a TColor to a Web color name, returns a Web color value if the color is not a match. } function ColorToWebColorName(Color: TColor): string; function WebColorToRGB(WebColor: Integer): Integer; function RGBToWebColorStr(RGB: Integer): string; function RGBToWebColorName(RGB: Integer): string; { Converts a Web color name to its TColor equivalent, returns clNone if no match } function WebColorNameToColor(WebColorName: string): TColor; { Converts a web style color string (#FFFFFF or FFFFFF) to a TColor } function WebColorStrToColor(WebColor: string): TColor; type TColorArraySortType = (stHue, stSaturation, stLuminance, stRed, stGreen, stBlue, stCombo); { Performs a quicksort on ColorArray according to the SortType } procedure SortColorArray(ColorArray: TColorArray; L, R: Integer; SortType: TColorArraySortType; Reverse: Boolean = False); procedure DrawTransparentBitmap(Source: TBitmap; Destination: TCanvas; DestRect: TRect; Opacity: Byte); overload; procedure DrawTransparentBitmap(Source: TBitmap; SourceRect: TRect; Destination: TCanvas; DestRect: TRect; Opacity: Byte); overload; function SplitTransparentBitmap(Source: TBitmap; SourceRect: TRect): TBitmap; {$IFDEF USE_ZLIB} function LoadCompressedResourceBitmap(ResID: string): TBitmap; {$ENDIF USE_ZLIB} implementation uses {$IFDEF CLR} System.Runtime.InteropServices, Types, {$ENDIF} {$IFDEF USE_ZLIB} System.ZLib, {$ENDIF USE_ZLIB} System.UITypes, System.SysUtils, System.Math, Vcl.Consts; const ArrowPts: array[TScrollDirection, 0..2] of TPoint = (((X:1; Y:0), (X:0; Y:1), (X:1; Y:2)), ((X:0; Y:0), (X:1; Y:1), (X:0; Y:2)), ((X:0; Y:1), (X:1; Y:0), (X:2; Y:1)), ((X:0; Y:0), (X:1; Y:1), (X:2; Y:0))); threadvar CachedRGBToHLSclrRGB: TColorRef; CachedRGBToHLSHue: WORD; CachedRGBToHLSLum: WORD; CachedRGBToHLSSat: WORD; {----------------------------------------------------------------------- References: 1) J. Foley and a.van Dam, "Fundamentals of Interactive Computer Graphics", Addison-Wesley (IBM Systems Programming Series), Reading, MA, 664 pp., 1982. 2) MSDN online HOWTO: Converting Colors Between RGB and HLS (HBS) http://support.microsoft.com/support/kb/articles/Q29/2/40.ASP SUMMARY The code fragment below converts colors between RGB (Red, Green, Blue) and HLS/HBS (Hue, Lightness, Saturation/Hue, Brightness, Saturation). http://lists.w3.org/Archives/Public/www-style/1997Dec/0182.html http://www.math.clemson.edu/~rsimms/neat/math/hlsrgb.pas -----------------------------------------------------------------------} const HLSMAX = 240; // H,L, and S vary over 0-HLSMAX RGBMAX = 255; // R,G, and B vary over 0-RGBMAX // HLSMAX BEST IF DIVISIBLE BY 6 // RGBMAX, HLSMAX must each fit in a byte. { Hue is undefined if Saturation is 0 (grey-scale) This value determines where the Hue scrollbar is initially set for achromatic colors } HLSUndefined = (HLSMAX*2/3); procedure ColorRGBToHLS(clrRGB: TColorRef; var Hue, Luminance, Saturation: Word); var H, L, S: Double; R, G, B: Word; cMax, cMin: Double; Rdelta, Gdelta, Bdelta: Word; { intermediate value: % of spread from max } begin if clrRGB = CachedRGBToHLSclrRGB then begin Hue := CachedRGBToHLSHue; Luminance := CachedRGBToHLSLum; Saturation := CachedRGBToHLSSat; exit; end; R := GetRValue(clrRGB); G := GetGValue(clrRGB); B := GetBValue(clrRGB); { calculate lightness } cMax := System.Math.Max(System.Math.Max(R, G), B); cMin := System.Math.Min(System.Math.Min(R, G), B); L := ( ((cMax + cMin) * HLSMAX) + RGBMAX ) / ( 2 * RGBMAX); Luminance := Trunc(L); if cMax = cMin then { r=g=b --> achromatic case } begin Hue := Trunc(HLSUndefined); Saturation := 0; end else { chromatic case } begin { saturation } if Luminance <= HLSMAX/2 then S := ( ((cMax-cMin)*HLSMAX) + ((cMax+cMin)/2) ) / (cMax+cMin) else S := ( ((cMax-cMin)*HLSMAX) + ((2*RGBMAX-cMax-cMin)/2) ) / (2*RGBMAX-cMax-cMin); { hue } Rdelta := Trunc(( ((cMax-R)*(HLSMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin)); Gdelta := Trunc(( ((cMax-G)*(HLSMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin)); Bdelta := Trunc(( ((cMax-B)*(HLSMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin)); if (R = cMax) then H := Bdelta - Gdelta else if (G = cMax) then H := (HLSMAX/3) + Rdelta - Bdelta else // B == cMax H := ((2 * HLSMAX) / 3) + Gdelta - Rdelta; if (H < 0) then H := H + HLSMAX; if (H > HLSMAX) then H := H - HLSMAX; Hue := Round(H); Saturation := Trunc(S); end; CachedRGBToHLSclrRGB := clrRGB; CachedRGBToHLSHue := Hue; CachedRGBToHLSLum := Luminance; CachedRGBToHLSSat := Saturation; end; function HueToRGB(Lum, Sat, Hue: Double): Integer; var ResultEx: Double; begin { range check: note values passed add/subtract thirds of range } if (hue < 0) then hue := hue + HLSMAX; if (hue > HLSMAX) then hue := hue - HLSMAX; { return r,g, or b value from this tridrant } if (hue < (HLSMAX/6)) then ResultEx := Lum + (((Sat-Lum)*hue+(HLSMAX/12))/(HLSMAX/6)) else if (hue < (HLSMAX/2)) then ResultEx := Sat else if (hue < ((HLSMAX*2)/3)) then ResultEx := Lum + (((Sat-Lum)*(((HLSMAX*2)/3)-hue)+(HLSMAX/12))/(HLSMAX/6)) else ResultEx := Lum; Result := Round(ResultEx); end; function ColorHLSToRGB(Hue, Luminance, Saturation: Word): TColorRef; function RoundColor(Value: Double): Integer; begin if Value > 255 then Result := 255 else Result := Round(Value); end; var R,G,B: Double; { RGB component values } Magic1,Magic2: Double; { calculated magic numbers (really!) } begin if (Saturation = 0) then begin { achromatic case } R := (Luminance * RGBMAX)/HLSMAX; G := R; B := R; if (Hue <> HLSUndefined) then ;{ ERROR } end else begin { chromatic case } { set up magic numbers } if (Luminance <= (HLSMAX/2)) then Magic2 := (Luminance * (HLSMAX + Saturation) + (HLSMAX/2)) / HLSMAX else Magic2 := Luminance + Saturation - ((Luminance * Saturation) + (HLSMAX/2)) / HLSMAX; Magic1 := 2 * Luminance - Magic2; { get RGB, change units from HLSMAX to RGBMAX } R := (HueToRGB(Magic1,Magic2,Hue+(HLSMAX/3))*RGBMAX + (HLSMAX/2))/HLSMAX; G := (HueToRGB(Magic1,Magic2,Hue)*RGBMAX + (HLSMAX/2)) / HLSMAX; B := (HueToRGB(Magic1,Magic2,Hue-(HLSMAX/3))*RGBMAX + (HLSMAX/2))/HLSMAX; end; Result := RGB(RoundColor(R), RoundColor(G), RoundColor(B)); end; threadvar CachedHighlightLum: Integer; CachedHighlightColor, CachedHighlight: TColor; CachedShadowLum: Integer; CachedShadowColor, CachedShadow: TColor; CachedColorValue: Integer; CachedLumValue: Integer; CachedColorAdjustLuma: TColor; function ColorAdjustLuma(clrRGB: TColor; n: Integer; fScale: BOOL): TColor; var H, L, S: Word; begin if (clrRGB = CachedColorValue) and (n = CachedLumValue) then Result := CachedColorAdjustLuma else begin ColorRGBToHLS(ColorToRGB(clrRGB), H, L, S); Result := TColor(Integer(ColorHLSToRGB(H, Word(L + n), S))); CachedColorValue := clrRGB; CachedLumValue := n; CachedColorAdjustLuma := Result; end; end; function GetHighLightColor(const Color: TColor; Luminance: Integer): TColor; var H, L, S: Word; Clr: Cardinal; begin if (Color = CachedHighlightColor) and (Luminance = CachedHighlightLum) then Result := CachedHighlight else begin // Case for default luminance if (Color = clBtnFace) and (Luminance = 19) then Result := clBtnHighlight else begin Clr := ColorToRGB(Color); ColorRGBToHLS(Clr, H, L, S); if (S > 220) and ((L - Luminance) >= 0) and ((L - Luminance) <= High(Word)) then Result := ColorHLSToRGB(H, L - Luminance, S) else Result := TColor(ColorAdjustLuma(Clr, Luminance, False)); CachedHighlightLum := Luminance; CachedHighlightColor := Color; CachedHighlight := Result; end; end; end; function GetShadowColor(const Color: TColor; Luminance: Integer): TColor; var H, L, S: Word; Clr: Cardinal; begin if (Color = CachedShadowColor) and (Luminance = CachedShadowLum) then Result := CachedShadow else begin // Case for default luminance if (Color = clBtnFace) and (Luminance = -50) then Result := clBtnShadow else begin Clr := ColorToRGB(Color); ColorRGBToHLS(Clr, H, L, S); if (S >= 160) and ((L + Luminance) >= 0) and ((L + Luminance) <= High(Word))then Result := ColorHLSToRGB(H, L + Luminance, S) else Result := TColor(ColorAdjustLuma(Clr, Luminance, False)); end; CachedShadowLum := Luminance; CachedShadowColor := Color; CachedShadow := Result; end; end; { Utility Drawing Routines } procedure DrawArrow(ACanvas: TCanvas; Direction: TScrollDirection; Location: TPoint; Size: Integer); var I: Integer; Pts: array[0..2] of TPoint; OldWidth: Integer; OldColor: TColor; begin if ACanvas = nil then exit; OldColor := ACanvas.Brush.Color; ACanvas.Brush.Color := ACanvas.Pen.Color; for I := 0 to 2 do Pts[I] := Point(ArrowPts[Direction,I].x * Size + Location.X, ArrowPts[Direction,I].y * Size + Location.Y); with ACanvas do begin OldWidth := Pen.Width; Pen.Width := 1; Polygon(Pts); Pen.Width := OldWidth; Brush.Color := OldColor; end; end; procedure DrawChevron(ACanvas: TCanvas; Direction: TScrollDirection; Location: TPoint; Size: Integer); procedure DrawLine; var I: Integer; Pts: array[0..2] of TPoint; begin // Scale to the correct size for I := 0 to 2 do Pts[I] := Point(ArrowPts[Direction, I].X * Size + Location.X, ArrowPts[Direction, I].Y * Size + Location.Y); case Direction of sdDown : Pts[2] := Point(Pts[2].X + 1, Pts[2].Y - 1); sdRight: Pts[2] := Point(Pts[2].X - 1, Pts[2].Y + 1); sdUp, sdLeft : Pts[2] := Point(Pts[2].X + 1, Pts[2].Y + 1); end; ACanvas.PolyLine(Pts); end; var OldWidth: Integer; begin if ACanvas = nil then exit; OldWidth := ACanvas.Pen.Width; ACanvas.Pen.Width := 1; case Direction of sdLeft, sdRight: begin Dec(Location.x, Size); DrawLine; Inc(Location.x); DrawLine; Inc(Location.x, 3); DrawLine; Inc(Location.x); DrawLine; end; sdUp, sdDown: begin Dec(Location.y, Size); DrawLine; Inc(Location.y); DrawLine; Inc(Location.y, 3); DrawLine; Inc(Location.y); DrawLine; end; end; ACanvas.Pen.Width := OldWidth; end; procedure DrawCheck(ACanvas: TCanvas; Location: TPoint; Size: Integer; Shadow: Boolean = True); var PR: TPenRecall; begin if ACanvas = nil then exit; PR := TPenRecall.Create(ACanvas.Pen); try ACanvas.Pen.Width := 1; ACanvas.PolyLine([ Point(Location.X, Location.Y), Point(Location.X + Size, Location.Y + Size), Point(Location.X + Size * 2 + Size, Location.Y - Size), Point(Location.X + Size * 2 + Size, Location.Y - Size - 1), Point(Location.X + Size, Location.Y + Size - 1), Point(Location.X - 1, Location.Y - 2)]); if Shadow then begin ACanvas.Pen.Color := clWhite; ACanvas.PolyLine([ Point(Location.X - 1, Location.Y - 1), Point(Location.X - 1, Location.Y), Point(Location.X, Location.Y + 1), Point(Location.X + Size, Location.Y + Size + 1), Point(Location.X + Size * 2 + Size + 1, Location.Y - Size), Point(Location.X + Size * 2 + Size + 1, Location.Y - Size - 1), Point(Location.X + Size * 2 + Size + 1, Location.Y - Size - 2)]); end; finally PR.Free; end; end; procedure GradientFillCanvas(const ACanvas: TCanvas; const AStartColor, AEndColor: TColor; const ARect: TRect; const Direction: TGradientDirection); const cGradientDirections: array[TGradientDirection] of Cardinal = (GRADIENT_FILL_RECT_H, GRADIENT_FILL_RECT_V); var StartColor, EndColor: Cardinal; Vertexes: array[0..1] of TTriVertex; GradientRect: TGradientRect; begin StartColor := ColorToRGB(AStartColor); EndColor := ColorToRGB(AEndColor); Vertexes[0].x := ARect.Left; Vertexes[0].y := ARect.Top; Vertexes[0].Red := GetRValue(StartColor) shl 8; Vertexes[0].Blue := GetBValue(StartColor) shl 8; Vertexes[0].Green := GetGValue(StartColor) shl 8; Vertexes[0].Alpha := 0; Vertexes[1].x := ARect.Right; Vertexes[1].y := ARect.Bottom; Vertexes[1].Red := GetRValue(EndColor) shl 8; Vertexes[1].Blue := GetBValue(EndColor) shl 8; Vertexes[1].Green := GetGValue(EndColor) shl 8; Vertexes[1].Alpha := 0; GradientRect.UpperLeft := 0; GradientRect.LowerRight := 1; {$IF DEFINED(CLR)} GradientFill(ACanvas.Handle, Vertexes, 2, GradientRect, 1, cGradientDirections[Direction]); {$ELSE} GradientFill(ACanvas.Handle, @Vertexes[0], 2, @GradientRect, 1, cGradientDirections[Direction]); {$IFEND} end; procedure ShrinkImage(const SourceBitmap, StretchedBitmap: TBitmap; Scale: Double); var {$IF DEFINED(CLR)} ScanLines: array of IntPtr; DestLine: IntPtr; CurrentLine: IntPtr; {$ELSE} ScanLines: array of PByteArray; DestLine: PByteArray; CurrentLine: PByteArray; {$IFEND} DestX, DestY: Integer; DestR, DestB, DestG: Integer; SourceYStart, SourceXStart: Integer; SourceYEnd, SourceXEnd: Integer; AvgX, AvgY: Integer; ActualX: Integer; PixelsUsed: Integer; DestWidth, DestHeight: Integer; begin DestWidth := StretchedBitmap.Width; DestHeight := StretchedBitmap.Height; SetLength(ScanLines, SourceBitmap.Height); for DestY := 0 to DestHeight - 1 do begin SourceYStart := Round(DestY / Scale); SourceYEnd := Round((DestY + 1) / Scale) - 1; if SourceYEnd >= SourceBitmap.Height then SourceYEnd := SourceBitmap.Height - 1; { Grab the destination pixels } DestLine := StretchedBitmap.ScanLine[DestY]; for DestX := 0 to DestWidth - 1 do begin { Calculate the RGB value at this destination pixel } SourceXStart := Round(DestX / Scale); SourceXEnd := Round((DestX + 1) / Scale) - 1; DestR := 0; DestB := 0; DestG := 0; PixelsUsed := 0; if SourceXEnd >= SourceBitmap.Width then SourceXEnd := SourceBitmap.Width - 1; for AvgY := SourceYStart to SourceYEnd do begin if ScanLines[AvgY] = nil then ScanLines[AvgY] := SourceBitmap.ScanLine[AvgY]; CurrentLine := ScanLines[AvgY]; for AvgX := SourceXStart to SourceXEnd do begin ActualX := AvgX*3; { 3 bytes per pixel } {$IF DEFINED(CLR)} DestR := DestR + Marshal.ReadByte(CurrentLine, ActualX); DestB := DestB + Marshal.ReadByte(CurrentLine, ActualX + 1); DestG := DestG + Marshal.ReadByte(CurrentLine, ActualX + 2); {$ELSE} DestR := DestR + CurrentLine[ActualX]; DestB := DestB + CurrentLine[ActualX+1]; DestG := DestG + CurrentLine[ActualX+2]; {$IFEND} Inc(PixelsUsed); end; end; { pf24bit = 3 bytes per pixel } ActualX := DestX*3; {$IF DEFINED(CLR)} Marshal.WriteByte(DestLine, ActualX, Round(DestR / PixelsUsed)); Marshal.WriteByte(DestLine, ActualX + 1, Round(DestB / PixelsUsed)); Marshal.WriteByte(DestLine, ActualX + 2, Round(DestG / PixelsUsed)); {$ELSE} DestLine[ActualX] := Round(DestR / PixelsUsed); DestLine[ActualX+1] := Round(DestB / PixelsUsed); DestLine[ActualX+2] := Round(DestG / PixelsUsed); {$IFEND} end; end; end; procedure EnlargeImage(const SourceBitmap, StretchedBitmap: TBitmap; Scale: Double); var {$IF DEFINED(CLR)} ScanLines: array of IntPtr; DestLine: IntPtr; CurrentLine: IntPtr; {$ELSE} ScanLines: array of PByteArray; DestLine: PByteArray; CurrentLine: PByteArray; {$IFEND} DestX, DestY: Integer; DestR, DestB, DestG: Double; SourceYStart, SourceXStart: Integer; SourceYPos: Integer; AvgX, AvgY: Integer; ActualX: Integer; { Use a 4 pixels for enlarging } XWeights, YWeights: array[0..1] of Double; PixelWeight: Double; DistFromStart: Double; DestWidth, DestHeight: Integer; begin DestWidth := StretchedBitmap.Width; DestHeight := StretchedBitmap.Height; Scale := StretchedBitmap.Width / SourceBitmap.Width; SetLength(ScanLines, SourceBitmap.Height); for DestY := 0 to DestHeight - 1 do begin DistFromStart := DestY / Scale; SourceYStart := Round(DistFromSTart); YWeights[1] := DistFromStart - SourceYStart; if YWeights[1] < 0 then YWeights[1] := 0; YWeights[0] := 1 - YWeights[1]; DestLine := StretchedBitmap.ScanLine[DestY]; for DestX := 0 to DestWidth - 1 do begin { Calculate the RGB value at this destination pixel } DistFromStart := DestX / Scale; if DistFromStart > (SourceBitmap.Width - 1) then DistFromStart := SourceBitmap.Width - 1; SourceXStart := Round(DistFromStart); XWeights[1] := DistFromStart - SourceXStart; if XWeights[1] < 0 then XWeights[1] := 0; XWeights[0] := 1 - XWeights[1]; { Average the four nearest pixels from the source mapped point } DestR := 0; DestB := 0; DestG := 0; for AvgY := 0 to 1 do begin SourceYPos := SourceYStart + AvgY; if SourceYPos >= SourceBitmap.Height then SourceYPos := SourceBitmap.Height - 1; if ScanLines[SourceYPos] = nil then ScanLines[SourceYPos] := SourceBitmap.ScanLine[SourceYPos]; CurrentLine := ScanLines[SourceYPos]; for AvgX := 0 to 1 do begin if SourceXStart + AvgX >= SourceBitmap.Width then SourceXStart := SourceBitmap.Width - 1; ActualX := (SourceXStart + AvgX) * 3; { 3 bytes per pixel } { Calculate how heavy this pixel is based on how far away it is from the mapped pixel } PixelWeight := XWeights[AvgX] * YWeights[AvgY]; {$IF DEFINED(CLR)} DestR := DestR + Marshal.ReadByte(CurrentLine, ActualX) * PixelWeight; DestB := DestB + Marshal.ReadByte(CurrentLine, ActualX + 1) * PixelWeight; DestG := DestG + Marshal.ReadByte(CurrentLine, ActualX + 2) * PixelWeight; {$ELSE} DestR := DestR + CurrentLine[ActualX] * PixelWeight; DestB := DestB + CurrentLine[ActualX+1] * PixelWeight; DestG := DestG + CurrentLine[ActualX+2] * PixelWeight; {$IFEND} end; end; ActualX := DestX * 3; {$IF DEFINED(CLR)} Marshal.WriteByte(DestLine, ActualX, Round(DestR)); Marshal.WriteByte(DestLine, ActualX + 1, Round(DestB)); Marshal.WriteByte(DestLine, ActualX + 2, Round(DestG)); {$ELSE} DestLine[ActualX] := Round(DestR); DestLine[ActualX+1] := Round(DestB); DestLine[ActualX+2] := Round(DestG); {$IFEND} end; end; end; procedure ScaleImage(const SourceBitmap, ResizedBitmap: TBitmap; const ScaleAmount: Double); var DestWidth, DestHeight: Integer; begin DestWidth := Round(SourceBitmap.Width * ScaleAmount); DestHeight := Round(SourceBitmap.Height * ScaleAmount); { We must work in 24-bit to insure the pixel layout for scanline is correct } SourceBitmap.PixelFormat := pf24bit; ResizedBitmap.Width := DestWidth; ResizedBitmap.Height := DestHeight; ResizedBitmap.Canvas.Brush.Color := Vcl.Graphics.clNone; ResizedBitmap.Canvas.FillRect(Rect(0, 0, DestWidth, DestHeight)); ResizedBitmap.PixelFormat := pf24bit; if ResizedBitmap.Width < SourceBitmap.Width then ShrinkImage(SourceBitmap, ResizedBitmap, ScaleAmount) else EnlargeImage(SourceBitmap, ResizedBitmap, ScaleAmount); end; function ColorToWebColorStr(Color: TColor): string; var RGB: Integer; begin RGB := ColorToRGB(Color); Result := UpperCase(Format('#%.2x%.2x%.2x', [GetRValue(RGB), GetGValue(RGB), GetBValue(RGB)])); { do not localize } end; function ColorToWebColorName(Color: TColor): string; begin Result := RGBToWebColorName(ColorToRGB(Color)); end; function WebColorToRGB(WebColor: Integer): Integer; begin Result := StrToInt(Format('$%.2x%.2x%.2x', [GetRValue(WebColor), GetGValue(WebColor), GetBValue(WebColor)])); { do not localize } end; function RGBToWebColorStr(RGB: Integer): string; begin Result := UpperCase(Format('#%.2x%.2x%.2x', [GetRValue(RGB), GetGValue(RGB), GetBValue(RGB)])); { do not localize } end; function RGBToWebColorName(RGB: Integer): string; var I: Integer; begin Result := RGBToWebColorStr(RGB); for I := 0 to Length(WebNamedColors) - 1 do if RGB = WebNamedColors[I].Value then begin Result := WebNamedColors[I].Name; exit; end; end; function WebColorNameToColor(WebColorName: string): TColor; var I: Integer; begin for I := 0 to Length(WebNamedColors) - 1 do if CompareText(WebColorName, WebNamedColors[I].Name) = 0 then begin Result := WebNamedColors[I].Value; Exit; end; raise Exception.Create(SInvalidColorString); end; const OffsetValue: array[Boolean] of Integer = (0,1); function WebColorStrToColor(WebColor: string): TColor; var I: Integer; Offset: Integer; begin if (Length(WebColor) < 6) or (Length(WebColor) > 7) then raise Exception.Create(SInvalidColorString); for I := 1 to Length(WebColor) do if not CharInSet(WebColor[I], ['#', 'a'..'f', 'A'..'F', '0'..'9']) then { do not localize } raise Exception.Create(SInvalidColorString); Offset := OffsetValue[Pos('#', WebColor) = 1]; Result := RGB(StrToInt('$' + Copy(WebColor, 1 + Offset, 2)), { do not localize } StrToInt('$' + Copy(WebColor, 3 + Offset, 2)), StrToInt('$' + Copy(WebColor, 5 + Offset, 2))); { do not localize } end; procedure SortColorArray(ColorArray: TColorArray; L, R: Integer; SortType: TColorArraySortType; Reverse: Boolean); function Compare(A, B: Integer): Integer; var H1, L1, S1: Word; H2, L2, S2: Word; R1, G1, B1: Word; R2, G2, B2: Word; begin Result := 0; if SortType in [stHue, stSaturation, stLuminance] then begin if Reverse then begin ColorRGBToHLS(ColorArray[A].Value, H1, L1, S1); ColorRGBToHLS(ColorArray[B].Value, H2, L2, S2); end else begin ColorRGBToHLS(ColorArray[A].Value, H2, L2, S2); ColorRGBToHLS(ColorArray[B].Value, H1, L1, S1); end; case SortType of stHue: Result := H2 - H1; stSaturation: Result := H2 - H1; stLuminance: Result := L2 - L1; end; end else begin if Reverse then begin R1 := GetRValue(ColorArray[A].Value); G1 := GetGValue(ColorArray[A].Value); B1 := GetBValue(ColorArray[A].Value); R2 := GetRValue(ColorArray[B].Value); G2 := GetGValue(ColorArray[B].Value); B2 := GetBValue(ColorArray[B].Value); end else begin R2 := GetRValue(ColorArray[A].Value); G2 := GetGValue(ColorArray[A].Value); B2 := GetBValue(ColorArray[A].Value); R1 := GetRValue(ColorArray[B].Value); G1 := GetGValue(ColorArray[B].Value); B1 := GetBValue(ColorArray[B].Value); end; case SortType of stRed: Result := R2 - R1; stGreen: Result := G2 - G1; stBlue: Result := B2 - B1; stCombo: Result := (R2 + G2 + B2) - (R1 + G1 + B1); end; end; end; var I, J, P: Integer; WebColor: TIdentMapEntry; begin repeat I := L; J := R; P := (L + R) shr 1; repeat while Compare(I, P) < 0 do Inc(I); while Compare(J, P) > 0 do Dec(J); if I <= J then begin WebColor := ColorArray[I]; ColorArray[I] := ColorArray[J]; ColorArray[J] := WebColor; if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if L < J then SortColorArray(ColorArray, L, J, SortType); L := I; until I >= R; end; procedure DrawTransparentBitmap(Source: TBitmap; Destination: TCanvas; DestRect: TRect; Opacity: Byte); var BlendFunc: TBlendFunction; begin BlendFunc.BlendOp := AC_SRC_OVER; BlendFunc.BlendFlags := 0; BlendFunc.SourceConstantAlpha := Opacity; if Source.PixelFormat = pf32bit then BlendFunc.AlphaFormat := AC_SRC_ALPHA else BlendFunc.AlphaFormat := 0; Winapi.Windows.AlphaBlend(Destination.Handle, DestRect.Left, DestRect.Top, DestRect.Right - DestRect.Left, DestRect.Bottom - DestRect.Top, Source.Canvas.Handle, 0, 0, Source.Width, Source.Height, BlendFunc); end; procedure DrawTransparentBitmap(Source: TBitmap; SourceRect: TRect; Destination: TCanvas; DestRect: TRect; Opacity: Byte); var BlendFunc: TBlendFunction; begin BlendFunc.BlendOp := AC_SRC_OVER; BlendFunc.BlendFlags := 0; BlendFunc.SourceConstantAlpha := Opacity; if Source.PixelFormat = pf32bit then BlendFunc.AlphaFormat := AC_SRC_ALPHA else BlendFunc.AlphaFormat := 0; Winapi.Windows.AlphaBlend(Destination.Handle, DestRect.Left, DestRect.Top, DestRect.Right - DestRect.Left, DestRect.Bottom - DestRect.Top, Source.Canvas.Handle, SourceRect.Left, SourceRect.Top, SourceRect.Right - SourceRect.Left, SourceRect.Bottom - SourceRect.Top, BlendFunc); end; type CardinalArray = array of Cardinal; function SplitTransparentBitmap(Source: TBitmap; SourceRect: TRect): TBitmap; var I: Integer; {$IFDEF CLR} J: Integer; BitsMem: IntPtr; {$ENDIF} begin Result := TBitmap.Create; Result.SetSize(SourceRect.Right - SourceRect.Left, SourceRect.Bottom - SourceRect.Top); Result.PixelFormat := Source.PixelFormat; //Clear the resulting alpha and color values to 0 which essentially changes //DrawTransparentBitmap to a source copy if Result.PixelFormat = pf32bit then begin {$IFNDEF CLR} for I := 0 to Result.Height - 1 do ZeroMemory(Result.ScanLine[I], Result.Width * 4); {$ELSE} for I := 0 to Result.Height - 1 do begin BitsMem := Result.ScanLine[I]; for J := 0 to Result.Width - 1 do begin Marshal.WriteInt32(BitsMem, J * 4, 0); end; end; {$ENDIF} end; DrawTransparentBitmap(Source, SourceRect, Result.Canvas, Rect(0, 0, Result.Width, Result.Height), 255); end; {$IFDEF USE_ZLIB} function LoadCompressedResourceBitmap(ResID: string): TBitmap; var ResStream: TResourceStream; ZStream: TZDecompressionStream; begin Result := TBitmap.Create; ResStream := TResourceStream.Create(HInstance, ResID, RT_RCDATA); ZStream := TZDecompressionStream.Create(ResStream); try Result.LoadFromStream(ZStream); finally ZStream.Free; ResStream.Free; end; end; {$ENDIF USE_ZLIB} initialization CachedHighlightLum := 0; CachedHighlightColor := 0; CachedHighlight := 0; CachedShadowLum := 0; CachedShadowColor := 0; CachedShadow := 0; CachedColorValue := 0; CachedLumValue := 0; CachedColorAdjustLuma := 0; end.
{ ************************************************************** Package: XWB - Kernel RPCBroker Date Created: Sept 18, 1997 (Version 1.1) Site Name: Oakland, OI Field Office, Dept of Veteran Affairs Developers: Wally Fort, Joel Ivey Description: Contains TRPCBroker and related components. Unit: XWBHash encryption and decryption functions. Current Release: Version 1.1 Patch 65 *************************************************************** } { ************************************************** Changes in v1.1.65 (HGW 10/12/2016) XWB*1.1*65 1. Renamed unit Hash to XWBHash due to conflict with System.Hash unit in Delphi XE8. Changes in v1.1.60 (HGW 12/18/2013) XWB*1.1*60 1. None. Changes in v1.1.50 (JLI 09/01/2011) XWB*1.1*50 1. None. ************************************************** } unit XWBHash; { Copyright 2016 Department of Veterans Affairs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } interface uses {System} SysUtils, Classes; {function and procedure prototypes} function Decrypt(EncryptedText: string): string; function Encrypt(NormalText: string): string; const maxKeys = 20; CipherPad: array[0..maxKeys - 1] of string = ( 'wkEo-ZJt!dG)49K{nX1BS$vH<&:Myf*>Ae0jQW=;|#PsO`''%+rmb[gpqN,l6/hFC@DcUa ]z~R}"V\iIxu?872.(TYL5_3', 'rKv`R;M/9BqAF%&tSs#Vh)dO1DZP> *fX''u[.4lY=-mg_ci802N7LTG<]!CWo:3?{+,5Q}(@jaExn$~p\IyHwzU"|k6Jeb', '\pV(ZJk"WQmCn!Y,y@1d+~8s?[lNMxgHEt=uw|X:qSLjAI*}6zoF{T3#;ca)/h5%`P4$r]G''9e2if_>UDKb7<v0&- RBO.', 'depjt3g4W)qD0V~NJar\B "?OYhcu[<Ms%Z`RIL_6:]AX-zG.#}$@vk7/5x&*m;(yb2Fn+l''PwUof1K{9,|EQi>H=CT8S!', 'NZW:1}K$byP;jk)7''`x90B|cq@iSsEnu,(l-hf.&Y_?J#R]+voQXU8mrV[!p4tg~OMez CAaGFD6H53%L/dT2<*>"{\wI=', 'vCiJ<oZ9|phXVNn)m K`t/SI%]A5qOWe\&?;jT~M!fz1l>[D_0xR32c*4.P"G{r7}E8wUgyudF+6-:B=$(sY,LkbHa#''@Q', 'hvMX,''4Ty;[a8/{6l~F_V"}qLI\!@x(D7bRmUH]W15J%N0BYPkrs&9:$)Zj>u|zwQ=ieC-oGA.#?tfdcO3gp`S+En K2*<', 'jd!W5[];4''<C$/&x|rZ(k{>?ghBzIFN}fAK"#`p_TqtD*1E37XGVs@0nmSe+Y6Qyo-aUu%i8c=H2vJ\) R:MLb.9,wlO~P', '2ThtjEM+!=xXb)7,ZV{*ci3"8@_l-HS69L>]\AUF/Q%:qD?1~m(yvO0e''<#o$p4dnIzKP|`NrkaGg.ufCRB[; sJYwW}5&', 'vB\5/zl-9y:Pj|=(R''7QJI *&CTX"p0]_3.idcuOefVU#omwNZ`$Fs?L+1Sk<,b)hM4A6[Y%aDrg@~KqEW8t>H};n!2xG{', 'sFz0Bo@_HfnK>LR}qWXV+D6`Y28=4Cm~G/7-5A\b9!a#rP.l&M$hc3ijQk;),TvUd<[:I"u1''NZSOw]*gxtE{eJp|y (?%', 'M@,D}|LJyGO8`$*ZqH .j>c~h<d=fimszv[#-53F!+a;NC''6T91IV?(0x&/{B)w"]Q\YUWprk4:ol%g2nE7teRKbAPuS_X', '.mjY#_0*H<B=Q+FML6]s;r2:e8R}[ic&KA 1w{)vV5d,$u"~xD/Pg?IyfthO@CzWp%!`N4Z''3-(o|J9XUE7k\TlqSb>anG', 'xVa1'']_GU<X`|\NgM?LS9{"jT%s$}y[nvtlefB2RKJW~(/cIDCPow4,>#zm+:5b@06O3Ap8=*7ZFY!H-uEQk; .q)i&rhd', 'I]Jz7AG@QX."%3Lq>METUo{Pp_ |a6<0dYVSv8:b)~W9NK`(r''4fs&wim\kReC2hg=HOj$1B*/nxt,;c#y+![?lFuZ-5D}', 'Rr(Ge6F Hx>q$m&C%M~Tn,:"o''tX/*yP.{lZ!YkiVhuw_<KE5a[;}W0gjsz3]@7cI2\QN?f#4p|vb1OUBD9)=-LJA+d`S8', 'I~k>y|m};d)-7DZ"Fe/Y<B:xwojR,Vh]O0Sc[`$sg8GXE!1&Qrzp._W%TNK(=J 3i*2abuHA4C''?Mv\Pq{n#56LftUl@9+', '~A*>9 WidFN,1KsmwQ)GJM{I4:C%}#Ep(?HB/r;t.&U8o|l[''Lg"2hRDyZ5`nbf]qjc0!zS-TkYO<_=76a\X@$Pe3+xVvu', 'yYgjf"5VdHc#uA,W1i+v''6|@pr{n;DJ!8(btPGaQM.LT3oe?NB/&9>Z`-}02*%x<7lsqz4OS ~E$\R]KI[:UwC_=h)kXmF', '5:iar.{YU7mBZR@-K|2 "+~`M%8sq4JhPo<_X\Sg3WC;Tuxz,fvEQ1p9=w}FAI&j/keD0c?)LN6OHV]lGy''$*>nd[(tb!#'); implementation uses {VA} MFunStr {for Translate function}; function Encrypt(normalText: string): string; var associatorIndex, identifierIndex: integer; begin Randomize; associatorIndex := random(MaxKeys); repeat identifierIndex := Random(MaxKeys); until associatorIndex <> identifierIndex; {make sure indexes are different} Result := chr(AssociatorIndex+32) + Translate(NormalText, CipherPad[AssociatorIndex], CipherPad[IdentifierIndex]) + chr(identifierIndex+32); end; function Decrypt(EncryptedText: string): string; var AssociatorIndex, IdentifierIndex: integer; begin IdentifierIndex := Ord(EncryptedText[1])-32; AssociatorIndex := Ord(EncryptedText[Length(EncryptedText)])-32; Result := Translate(copy(EncryptedText,2,Length(EncryptedText)-2), CipherPad[AssociatorIndex], CipherPad[IdentifierIndex]); end; end.
unit uFrameGridView; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, {$IF CompilerVersion >= 31} FMX.DialogService, {$ENDIF} UI.Standard, UI.Base, UI.Grid, UI.Frame, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Phys, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.FMXUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TFrameGridView = class(TFrame) GridView1: TStringGridView; LinearLayout1: TLinearLayout; tvTitle: TTextView; DBGridView1: TDBGridView; FDMemTable1: TFDMemTable; FDMemTable1Name: TStringField; FDMemTable1Title: TStringField; DataSource1: TDataSource; FDMemTable1Total: TFloatField; LinearLayout2: TLinearLayout; ButtonView5: TButtonView; ButtonView4: TButtonView; ButtonView3: TButtonView; ButtonView2: TButtonView; ButtonView1: TButtonView; btnBack: TTextView; procedure TextView1Click(Sender: TObject); procedure ButtonView1Click(Sender: TObject); procedure ButtonView2Click(Sender: TObject); procedure ButtonView3Click(Sender: TObject); procedure ButtonView4Click(Sender: TObject); procedure ButtonView5Click(Sender: TObject); procedure btnBackClick(Sender: TObject); procedure GridView1CellClick(Sender: TObject; const ACell: TGridCell); procedure GridView1TitleClick(Sender: TObject; Item: TGridColumnItem); procedure GridView1TitleDbClick(Sender: TObject; Item: TGridColumnItem); procedure GridView1CellDbClick(Sender: TObject; const ACell: TGridCell); procedure GridView1DrawFixedColText(Sender: TObject; Canvas: TCanvas; Item: TGridColumnItem; const R: TRectF; var DefaultDraw: Boolean); procedure DBGridView1DrawCells(Sender: TObject; Canvas: TCanvas; const ACol, ARow: Integer; const R: TRectF; ADrawState: TViewState; Column: TGridColumnItem; var DefaultDraw: Boolean); private { Private declarations } protected procedure DoShow(); override; public { Public declarations } end; implementation uses UI.Design.GridColumns; {$R *.fmx} procedure TFrameGridView.btnBackClick(Sender: TObject); begin Finish; end; procedure TFrameGridView.ButtonView1Click(Sender: TObject); begin GridView1.Clear; end; procedure TFrameGridView.ButtonView2Click(Sender: TObject); begin GridView1.SelectIndex := -1; end; procedure TFrameGridView.ButtonView3Click(Sender: TObject); begin {$IF CompilerVersion >= 31} TDialogService.InputQuery('输入新行数', ['新行数'], [IntToStr(GridView1.RowCount)], procedure(const AResult: TModalResult; const AValues: array of string) begin if AResult = mrOk then GridView1.RowCount := StrToIntDef(AValues[0], GridView1.RowCount); end ); {$ELSE} GridView1.RowCount := StrToIntDef(InputBox('输入新行数', '新行数', IntToStr(GridView1.RowCount)), GridView1.RowCount); {$ENDIF} end; procedure TFrameGridView.ButtonView4Click(Sender: TObject); begin {$IF CompilerVersion >= 31} TDialogService.InputQuery('输入新列数', ['新列数'], [IntToStr(GridView1.ColCount)], procedure(const AResult: TModalResult; const AValues: array of string) begin if AResult = mrOk then GridView1.ColCount := StrToIntDef(AValues[0], GridView1.ColCount); end ); {$ELSE} GridView1.ColCount := StrToIntDef(InputBox('输入新列数', '新列数', IntToStr(GridView1.ColCount)), GridView1.ColCount); {$ENDIF} end; procedure TFrameGridView.ButtonView5Click(Sender: TObject); var Dialog: TGridColumnsDesigner; begin Dialog := TGridColumnsDesigner.Create(Self); try Dialog.Columns := DBGridView1.Columns; if Dialog.ShowModal = mrOk then DBGridView1.Columns.Assign(Dialog.Columns); finally Dialog.Free; end; end; procedure TFrameGridView.DBGridView1DrawCells(Sender: TObject; Canvas: TCanvas; const ACol, ARow: Integer; const R: TRectF; ADrawState: TViewState; Column: TGridColumnItem; var DefaultDraw: Boolean); var FStyle: TFontStyles; begin //蓝色下划线显示第3列第2行 if (ACol = 2) and (ARow = 1) then begin DBGridView1.TextSettings.CustomColor := TAlphaColorrec.Blue; FStyle := DBGridView1.TextSettings.Font.Style; try DBGridView1.TextSettings.Font.Style := [TFontStyle.fsUnderline]; DBGridView1.TextSettings.Draw(Canvas, DBGridView1.Cells[ACol, ARow], R, Column.Opacity * DBGridView1.Opacity, TViewState.Custom, Column.Gravity); finally DBGridView1.TextSettings.Font.Style := FStyle; end; DefaultDraw := False; end else DefaultDraw := True; end; procedure TFrameGridView.DoShow; begin inherited; GridView1.Columns[11, 0].Title := '[11]'; GridView1.Columns[14, 0].Title := '[14]'; DBGridView1.Columns[0, 0].DataFilter := True; DBGridView1.Columns[0, 0].Width := 100; FDMemTable1.InsertRecord(['test', 'name', '12']); FDMemTable1.InsertRecord(['test1', 'name', '25']); FDMemTable1.InsertRecord(['test2', 'name', '21.5']); FDMemTable1.InsertRecord(['test3', 'name', '22']); //FDMemTable1.InsertRecord(['test4', 'name']); //FDMemTable1.InsertRecord(['test5', 'name']); // FAdapter := TStringGridAdapter.Create; // FAdapter.RowCount := 100; // GridView1.Adapter := FAdapter; end; procedure TFrameGridView.GridView1CellClick(Sender: TObject; const ACell: TGridCell); begin //ShowMessage(Format('Cell Row: %d, Col: %d.', [ACell.Row, Acell.Col])); end; procedure TFrameGridView.GridView1CellDbClick(Sender: TObject; const ACell: TGridCell); begin //ShowMessage(Format('DbClick Cell Row: %d, Col: %d.', [ACell.Row, Acell.Col])); end; procedure TFrameGridView.GridView1DrawFixedColText(Sender: TObject; Canvas: TCanvas; Item: TGridColumnItem; const R: TRectF; var DefaultDraw: Boolean); begin if (Item.ColIndex = 1) and (Item.RowIndex = 0) then begin // 红色字体显示第2列第0行表头 GridView1.FixedTextSettings.CustomColor := TAlphaColorrec.Red; GridView1.FixedTextSettings.Draw(Canvas, Item.DisplayText, R, Item.Opacity * GridView1.Opacity, TViewState.Custom, GridView1.FixedTextSettings.Gravity); end else DefaultDraw := True; end; procedure TFrameGridView.GridView1TitleClick(Sender: TObject; Item: TGridColumnItem); begin //ShowMessage(Format('FixedColumn Row: %d, Col: %d.', [Item.RowIndex, Item.ColIndex])); end; procedure TFrameGridView.GridView1TitleDbClick(Sender: TObject; Item: TGridColumnItem); begin ShowMessage(Format('FixedColumn DbClick Row: %d, Col: %d.', [Item.RowIndex, Item.ColIndex])); end; procedure TFrameGridView.TextView1Click(Sender: TObject); begin Finish(); end; end.
unit VisCom; interface uses ExtCtrls, Contnrs, Graphics, Classes; type TMap = class; // forward //============================================================================== // VisCom // Viscoms are components for visualization of map elements. // TVisCom is the base class for VisComs. A TVisCom object has the following // features: // - code/key: a short string used for identification purposes // - data: a reference to an object whose data is represented by this VisCom // - state: ????? // - selection: facilities for selection of this VisCom // - marking: facilities for marking this VisCom // - drawing: facilities for drawing this VisCom on a Map //============================================================================== TVisCom = class(TObject) protected // fields ------------------------------------------------------------------ FCode: String; FData: TObject; // shared FSelected: Boolean; FMark: String; // invariants -------------------------------------------------------------- // none public // construction/destruction ------------------------------------------------ constructor Create(ACode: String; AData: TObject); // pre: true // post: GetCode = ACode, GetData = AData, IsSelected = false, GetMark ='' // primitive queries ------------------------------------------------------- function GetCode: String; virtual; function GetData: TObject; virtual; function CanSelect: Boolean; virtual; // pre: true // ret: false (may be overridden in descendants) function CanMark(AMark:String): Boolean; virtual; // pre: true // ret: false (may be overriden in descendants) function IsSelected: Boolean; virtual; function GetMark: String; function Contains(AMap: TMap; AX, AY: Integer): Boolean; virtual; abstract; // pre: true // ret: "the image of this object drawn on map AMap contains point (AX, AY)" // derived queries --------------------------------------------------------- function IsMarked: Boolean; virtual; // pre: true // ret: GetMark <> '' // commands ---------------------------------------------------------------- procedure Select; virtual; // pre: CanSelect // post: IsSelected procedure UnSelect; virtual; // pre: true // post: CanSelect = false procedure Mark(AMark: String); virtual; // pre: Canmark(AMark) // post: GetMark = AMark procedure UnMark; virtual; // pre: true // post: GetMark = '' procedure Draw(AMap: TMap); virtual; abstract; // pre: AMap <> nil // post: this VisCom has been drawn on AMap // invariants -------------------------------------------------------------- // none end; TMap = class(TImage) protected FBlankPicture: TBitmap; FBackgroundPicture: TBitmap; FBackgroundShown: Boolean; FMultiSelect: Boolean; FViscoms: TObjectList; // owner FMarked: TObjectList; // shared FSelected: TObjectList; // shared // protected invariants // FBlankPicture <> nil; refers to all blank bitmap // FBackgroundPicture <> nil public // construction/destruction constructor Create(AOwner: TComponent; ABlankPicture, ABackgroundPicture: TBitmap); // pre: true // post: inherited.Create.post, // MultiSelect = false, // AbstrVisCom = [], AbstrMarked = [], AbstrSelected = [], // BackgroundShown, BackgroundPicture = ABackgroundPicture destructor Destroy; override; // primitive queries ------------------------------------------------------- function BackgroundPicture: TBitmap; function BackgroundShown: Boolean; // pre: true // ret: Image.Picture = Background function MultiSelect: Boolean; function VisComCount: Integer; // pre: true // ret: |AbstrVisCom| function GetVisCom(I: Integer): TVisCom; // pre: 0 <= I < VisComCount // ret: AbstrVisCom[I] function MarkedCount: Integer; // pre: true // ret: |AbstrMarked| function GetMarked(I: Integer): TVisCom; // pre: 0 <= I < MarkedCount // ret: AbstrMarked[I] function SelectedCount: Integer; // pre: true // ret: |AbstrSelected| function GetSelected(I: Integer): TVisCom; // pre: true // ret: AbstrSelected[I] // derived queries --------------------------------------------------------- function Has(AVisCom: TVisCom): Boolean; // pre: true // ret: (exists I: 0 <= I < VisComCount: GetVisCom(I) = AVisCom) // preconditions ----------------------------------------------------------- function CanAdd(AVisCom: TVisCom): Boolean; virtual; // pre: true // ret: not Has(AVisCom) function CanDelete(AVisCom: TVisCom): Boolean; virtual; // pre: true // ret: Has(AVisCom) function CanSelect(AVisCom: TVisCom): Boolean; virtual; // pre: true // ret: Has(AVisCom) and AVisCom.CanSelect function CanUnselect(AVisCom: TVisCom): Boolean; virtual; // pre: true // ret: Has(AVisCom) function CanMark(AVisCom: TVisCom; AMark: String): Boolean; virtual; // pre: true // ret: Has(AVisCom) and AVisCom.CanMark(AMark) function CanUnmark(AVisCom: TVisCom): Boolean; virtual; // pre: true // ret: Has(AVisCom) // commands ---------------------------------------------------------------- procedure SetBackgroundPicture(ABackgroundPicture: TBitmap); virtual; // pre: ABackgroundPicture <> nil // post: BackgroundPicture = ABackgroundPicture procedure ShowBackground; // pre: true // post: BackgroundShown procedure HideBackground; // pre: true // post: not BackgroundShown procedure SetMultiSelect(AMultiSelect: Boolean); virtual; // pre: true // post: MultiSelect = AMultiSelect procedure ClearSelected; // pre: true // post: SelectedCount = 0 procedure ClearMarked; // pre: true // post: MarkedCount = 0 procedure HideAll; virtual; // pre: true // post: Image.Picture = Background procedure ShowAll; virtual; // effect: draw all VisComs on the map procedure Add(AVisCom: TVisCom); // pre: CanAdd(AVisCom) // post: AbstrVisCom = AbstrVisCom ++ [AVisCom] procedure Delete(AVisCom: TVisCom); // pre: CanDelete(AVisCom) // post: AbstrVisCom = AbstrVisCom - [AVisCom] procedure Select(AVisCom: TVisCom); // pre: CanSelect(AVisCom) // post: AVisCom.IsSelected procedure UnSelect(AVisCom: TVisCom); // pre: CanUnselect(AVisCom) // post: not AVisCom.IsSelected procedure Mark(AVisCom: TVisCom; AMark: String); // pre: CanMark(AVisCom, AMark) // post: AVisCom.IsMarked procedure Unmark(AVisCom: TVisCom); // pre: CanUnmark(AVisCom) // post: not AVisCom.IsMarked // model variables --------------------------------------------------------- // AbstrVisCom: seq of TVisCom // AbstrSelected: seq of TVisCom // AbstrMarked: seq of TVisCom // public invariants ------------------------------------------------------- // Unique: // (forall I,J: 0<=I<J<VisComCount: // - GetVisCom(I) <> GetVisCom(J) // ) // SelectedExists: (forall I: 0<=I<SelectedCount: Has(GetSelected(I))) // MarkedExists: (forall I: 0<=I<MarkedCount: Has(GetMarked(I))) // MultiSelction: not MultiSelect implies (SelectedCount <= 1) // // WellformedPicture: // (Image.Picture = Blank) or (Image.Picture = Background) // // BackgroundShown <=> Image.Picture = Background end; implementation //=============================================================== { TVisCom } function TVisCom.CanMark(AMark: String): Boolean; begin Result := false; end; function TVisCom.CanSelect: Boolean; begin Result := false; end; constructor TVisCom.Create(ACode: String; AData: TObject); begin inherited Create; FCode := ACode; FData := AData; FSelected := false; FMark := ''; end; function TVisCom.GetCode: String; begin Result := FCode; end; function TVisCom.GetData: TObject; begin Result := FData; end; function TVisCom.GetMark: String; begin Result := FMark; end; function TVisCom.IsMarked: Boolean; begin Result := GetMark = ''; end; function TVisCom.IsSelected: Boolean; begin Result := FSelected; end; procedure TVisCom.Mark(AMark: String); begin Assert(CanMark(AMark), ''); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< FMark := AMark; end; procedure TVisCom.Select; begin Assert(CanSelect, ''); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< FSelected := true; end; procedure TVisCom.UnMark; begin FMark := ''; end; procedure TVisCom.UnSelect; begin FSelected := false; end; { TMap } procedure TMap.Add(AVisCom: TVisCom); begin Assert(CanAdd(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< FVisComs.Add(AVisCom); end; function TMap.BackgroundPicture: TBitmap; begin Result := FBackgroundPicture; end; function TMap.BackgroundShown: Boolean; begin Result := FBackgroundShown; end; function TMap.CanAdd(AVisCom: TVisCom): Boolean; begin Result := not Has(AVisCom); end; function TMap.CanDelete(AVisCom: TVisCom): Boolean; begin Result := not Has(AVisCom); end; function TMap.CanMark(AVisCom: TVisCom; AMark: String): Boolean; begin Result := Has(AVisCom) and AVisCom.CanMark(AMark); end; function TMap.CanSelect(AVisCom: TVisCom): Boolean; begin Result := Has(AVisCom) and AVisCom.CanSelect; end; function TMap.CanUnmark(AVisCom: TVisCom): Boolean; begin Result := Has(AVisCom); end; function TMap.CanUnselect(AVisCom: TVisCom): Boolean; begin Result := Has(AVisCom); end; procedure TMap.ClearMarked; var I: Integer; begin with FMarked do begin for I := Count - 1 downto 0 do //N.B. direction important begin (Items[I] as TVisCom).UnMark; Delete(I); end;{for} end;{with} end; procedure TMap.ClearSelected; var I: Integer; begin with FSelected do begin for I := Count - 1 downto 0 do //N.B. direction important begin (Items[I] as TVisCom).UnSelect; Delete(I); end;{for} end;{with} end; constructor TMap.Create(AOwner: TComponent; ABlankPicture, ABackgroundPicture: TBitmap); begin inherited Create(AOwner); FBlankPicture := ABlankPicture; FBackgroundPicture := ABackgroundPicture; ShowBackground; FMultiSelect:= false; FViscoms := TObjectList.Create(true); // owner FMarked := TObjectList.Create(false); // shared FSelected := TObjectList.Create(false); // shared end; procedure TMap.Delete(AVisCom: TVisCom); begin Assert(CanDelete(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // N.B.: Order is important FSelected.Remove(AVisCom); FMarked.Remove(AVisCom); FVisComs.Remove(AVisCom); // and freed end; destructor TMap.Destroy; begin // N.B.: Order is important FSelected.Free; // shares FMarked.Free; // shares FVisComs.Free; // owns, hence frees all objects FBlankPicture.Free; FBackgroundPicture.Free; inherited; end; function TMap.GetMarked(I: Integer): TVisCom; begin Assert( (0 <= I) and (I < MarkedCount), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Result := FMarked.Items[I] as TVisCom; end; function TMap.GetSelected(I: Integer): TVisCom; begin Assert( (0 <= I) and (I < SelectedCount), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Result := FSelected.Items[I] as TVisCom; end; function TMap.GetVisCom(I: Integer): TVisCom; begin Assert( (0 <= I) and (I < VisComCount), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Result := FVisComs.Items[I] as TVisCom; end; function TMap.Has(AVisCom: TVisCom): Boolean; begin Result := FVisComs.IndexOf(AVisCom) <> -1; end; procedure TMap.HideAll; begin Picture.Assign(FBackgroundPicture); Repaint; // <<<<<<<<<<<<<<<<<<<<<<<<<< Necessary? end; procedure TMap.HideBackground; begin Picture.Assign(FBlankPicture); FBackgroundShown := false; end; procedure TMap.Mark(AVisCom: TVisCom; AMark: String); begin Assert(CanMark(AVisCom, AMark), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< AVisCom.Mark(AMark); end; function TMap.MarkedCount: Integer; begin Result := FMarked.Count; end; function TMap.MultiSelect: Boolean; begin Result := FMultiSelect; end; procedure TMap.Select(AVisCom: TVisCom); begin Assert(CanSelect(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< AVisCom.Select; end; function TMap.SelectedCount: Integer; begin Result := FSelected.Count; end; procedure TMap.SetBackgroundPicture(ABackgroundPicture: TBitmap); begin FBackgroundPicture := ABackgroundPicture; end; procedure TMap.SetMultiSelect(AMultiSelect: Boolean); begin FMultiSelect := AMultiSelect; if not AMultiSelect then begin ClearSelected; ClearMarked; end; end; procedure TMap.ShowAll; var I: integer; begin for I := 0 to VisComCount - 1 do begin GetVisCom(I).Draw(Self); end; end; procedure TMap.ShowBackground; begin Picture.Assign(FBackgroundPicture); FBackgroundShown := true; end; procedure TMap.Unmark(AVisCom: TVisCom); begin Assert(CanUnmark(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< AVisCom.UnMark; end; procedure TMap.UnSelect(AVisCom: TVisCom); begin Assert(CanUnselect(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< AVisCom.UnSelect; end; function TMap.VisComCount: Integer; begin Result := FVisComs.Count; end; end.
{----------------------------------------------------------------------------- Unit Name: fNewSetting Author: Erwien Saputra Purpose: User interface to add a new setting. If the class function returns true, the NewSettingName is meaningful. History: 02/21/2005 - Updated the tab order. 06/18/2005 - Added support for Setting Template. 06/22/2005 - Modified the execute method, this form loads the templates first before assigning the new template name. -----------------------------------------------------------------------------} unit fNewSetting; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, SettingTemplate, SettingCollection, CheckLst; type TStringArray = array of string; TfrmNewSetting = class(TForm) lblSettingName: TLabeledEdit; btnOK: TButton; btnCancel: TButton; cbCopyCurrentIDESetting: TCheckBox; clbTemplates: TCheckListBox; lblTemplates: TStaticText; procedure lblSettingNameKeyPress(Sender: TObject; var Key: Char); procedure lblSettingNameChange(Sender: TObject); private { Private declarations } procedure LoadIDETemplates (const AIDEVersion : TIDEVersion); public { Public declarations } constructor Create (AOwner: TComponent); override; class function Execute (var NewSettingName : string; const AIDEVersion : TIDEVersion; var UseCurrentIDESetting: boolean; var AppliedTemplates : TStringArray) : boolean; end; var frmNewSetting: TfrmNewSetting; implementation uses dmGlyphs; {$R *.dfm} const DEFAULT_SETTING_HINT = 'Check this if you want to use the default IDE setting to be copied to ' + 'your new custom setting.' + sLineBreak + 'If this option is unchecked, the new custom setting will have the ' + 'default factory setting.'; { TfrmNewSetting } constructor TfrmNewSetting.Create(AOwner: TComponent); begin inherited; cbCopyCurrentIDESetting.Hint := DEFAULT_SETTING_HINT; self.clbTemplates.MultiSelect := true; end; //Entry point for this form. If NewSettingName is initialized, it will be used //on the edit box. //This function returns true if the user clicks OK and the user set the new //setting name. class function TfrmNewSetting.Execute(var NewSettingName: string; const AIDEVersion : TIDEVersion; var UseCurrentIDESetting: boolean; var AppliedTemplates : TStringArray) : boolean; var frm : TfrmNewSetting; Index, Loop : integer; begin frm := TfrmNewSetting.Create (nil); try //Load the template from the Template persistent. LoadIDETemplate must be //called before lblSettingName is set, as the lblSettingNameChange event //handler depends on the state of clbTemplate. Whenever have time, remove //the coupling from the lblSettingNameChange, do not rely on the event //handler. frm.LoadIDETemplates (AIDEVersion); if Trim (NewSettingName) <> EmptyStr then frm.lblSettingName.Text := NewSettingName else frm.lblSettingName.Text := EmptyStr; frm.lblSettingName.SelectAll; Result := (frm.ShowModal = MrOK) and (frm.lblSettingName.Text <> EmptyStr); UseCurrentIDESetting := frm.cbCopyCurrentIDESetting.Checked; if (Result = true) then begin NewSettingName := frm.lblSettingName.Text; SetLength (AppliedTemplates, frm.clbTemplates.Count); Index := 0; //Return the selected template to the caller. for Loop := 0 to frm.clbTemplates.Count - 1 do begin if frm.clbTemplates.Checked[Loop] = true then begin AppliedTemplates[Index] := frm.clbTemplates.Items[Loop]; Inc (Index); end; end; //Set the length of the Applied Templates array. SetLength (AppliedTemplates, Index); end; finally frm.Release; end; end; procedure TfrmNewSetting.lblSettingNameChange(Sender: TObject); var EnableControl : boolean; begin EnableControl := not SameText (Trim (lblSettingName.Text), EmptyStr); btnOK.Enabled := EnableControl; cbCopyCurrentIDESetting.Enabled := EnableControl; clbTemplates.Enabled := EnableControl and (clbTemplates.Count > 0); lblTemplates.Enabled := clbTemplates.Enabled; end; procedure TfrmNewSetting.lblSettingNameKeyPress(Sender: TObject; var Key: Char); begin if Key = '\' then Key := #0; end; procedure TfrmNewSetting.LoadIDETemplates(const AIDEVersion: TIDEVersion); var TemplateCollection : ITemplateCollection; begin clbTemplates.Items.Clear; TemplateCollection := SettingTemplate.GetTemplateCollection; if Assigned (TemplateCollection) then TemplateCollection.GetTemplateNames (AIDEVersion, clbTemplates.Items); end; end.
object frmGMV_TimeOutManager: TfrmGMV_TimeOutManager Left = 357 Top = 263 BorderIcons = [biSystemMenu] BorderStyle = bsDialog BorderWidth = 15 Caption = 'Application Time Out Warning!' ClientHeight = 113 ClientWidth = 253 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poDesktopCenter PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 16 Top = 64 Width = 188 Height = 13 Caption = 'Seconds until application closes:' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'MS Sans Serif' Font.Style = [fsBold] ParentFont = False end object lblSecondsLeft: TLabel Left = 208 Top = 64 Width = 15 Height = 13 Caption = '15' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'MS Sans Serif' Font.Style = [fsBold] ParentFont = False end object lblMessage: TLabel Left = 0 Top = 0 Width = 253 Height = 57 Align = alTop AutoSize = False Caption = 'lblMessage' WordWrap = True end object btnCancelTimeout: TButton Left = 80 Top = 88 Width = 73 Height = 25 Caption = 'Cancel' Default = True ModalResult = 2 TabOrder = 0 end object LastChanceTimer: TTimer OnTimer = LastChanceTimerTimer Top = 80 end end
unit uSped; interface uses Contnrs, // <-- Nesta Unit está implementado TObjectList MVCInterfaces,uRegistroEmpresaContabil,uEmpresa, UI010, uRegistro , uExcecao, SysUtils; // apagar uexcecao type TSped = class(TRegistroEmpresaContabil) private fID : Integer; FOnModeloMudou : TModeloMudou; fEmpresa : TEmpresa; fI010s : TObjectList; procedure SetEmpresa(const Value: TEmpresa); procedure SetI010s(const Value: TObjectList); procedure SetID(const Value: Integer); procedure SetOnModeloMudou(const Value: TModeloMudou); procedure AdicionaI010 (fI010 : TI010); function GetI010s : TObjectList; public property ID : Integer read fID write SetID; property Empresa : TEmpresa read fEmpresa write SetEmpresa; property I010s : TObjectList read GetI010s write SetI010s; property OnModeloMudou : TModeloMudou read FOnModeloMudou write SetOnModeloMudou; function TodosDaEmpresa : TObjectList; function inserir () : Boolean; function Procurar () : TRegistro; constructor create(); end; implementation Uses uSpedBD; { TSped } constructor TSped.create; begin Empresa := TEmpresa.create; I010s := TObjectList.create; fI010s := TObjectList.create; end; function TSped.GetI010s: TObjectList; begin result := fI010s; end; //} Exemplo desta função em Java //public Set getAutores() { //return Collections.unmodifiableSet(this.autores); //} procedure TSped.SetEmpresa(const Value: TEmpresa); begin fEmpresa := Value; end; procedure TSped.SetI010s(const Value: TObjectList); var I : Integer; begin if ( Assigned(Value)) then begin I := 0; while (I < (Value.Count) ) do begin AdicionaI010( TI010(value.Items[i]) ); inc(I); end; end; end; // exemplo desta função em do Java //public void setAutores(Set autores) { //Iterator iterator = autores.iterator(); //while (iterator.hasNext()){ //Autor autor = (Autor)iterator.next(); //this.adicionarAutor(autor); //} procedure TSped.AdicionaI010(fI010: TI010); begin if GetI010s.indexOf(fI010) = -1 then begin // o Objeto I010 ainda não existe na Lista de Objetos fI010s.Add(fI010); // fI010s.AdicionaSped(self); -- Acredito que não é necessário fazer este chamada neste caso end; end; //} função em Java //public void adicionarAutor(Autor autor){ //if (!this.getAutores().contains(autor)){ //this.autores.add(autor); //autor.adicionarLivro(this); //} procedure TSped.SetID(const Value: Integer); begin fID := Value; end; procedure TSped.SetOnModeloMudou(const Value: TModeloMudou); begin FOnModeloMudou := Value; end; function TSped.TodosDaEmpresa: TObjectList; var lSpedBD : TSpedBD; begin lSpedBD := TSpedBD.Create; result := lSpedBD.TodosDaEmpresa(self); lSpedBD.Free; lSpedBD := nil; end; function TSped.Procurar(): TRegistro; var lSpedBD : TSpedBD; begin lSpedBD := TSpedBD.Create; result := lSpedBD.Procurar(self); lSpedBD.Free; lSpedBD := nil; end; function TSped.inserir(): Boolean; var lSpedBD : TSpedBD; begin lSpedBD := TSpedBD.Create; result := lSpedBD.Inserir(self); lSpedBD.Free; lSpedBD := nil; end; end.
unit uHik; interface uses System.Classes, Generics.Collections, IdHTTP, SysUtils, uGlobal, uCommon, uDecodeHikResult, DateUtils, ActiveX, uEntity; type TImageInfo = Class public GCXH: String; KDBH: String; CDBH: String; Url: String; PassTime: String; HPHM: String; End; THik = class private class function HttPPost(AUrl: String; AParams: TStrings; var AResult: String; AEncoding: TEncoding = nil): Boolean; class function DFLogin(AUser, APwd: String; var AToken: String): Boolean; class procedure DFLogout(AToken: String); public class function DFCreateImageJob(AImages: TList<TImageInfo>): Boolean; end; implementation class function THik.DFCreateImageJob(AImages: TList<TImageInfo>): Boolean; var Params: TStrings; token, s, imgStr: String; img: TImageInfo; begin Result := False; ActiveX.CoInitializeEx(nil, COINIT_MULTITHREADED); if not DFLogin(gHikConfig.DFUser, gHikConfig.DFPwd, s) then exit; if s = '' then exit; token := s; Params := TStringList.Create; Params.Add ('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl" xmlns:ivms="http://www.hikvision.com.cn/ver1/schema/ivms/">'); Params.Add(' <soap:Header>'); Params.Add(' <wsdl:HeaderReq>'); Params.Add(' <wsdl:token>' + token + '</wsdl:token>'); Params.Add(' <wsdl:version>1.2</wsdl:version>'); Params.Add(' </wsdl:HeaderReq>'); Params.Add(' </soap:Header>'); Params.Add(' <soap:Body>'); Params.Add(' <wsdl:SubmitJobReq>'); Params.Add(' <wsdl:jobInfo>'); Params.Add(' <ivms:jobName>job_' + FormatDateTime('yyyymmddhhnnsszzz', Now()) + '</ivms:jobName>'); Params.Add(' <ivms:jobType>2</ivms:jobType>'); Params.Add(' <ivms:dataSourceType>2</ivms:dataSourceType>'); Params.Add(' <ivms:priority>30</ivms:priority>'); Params.Add(' <ivms:source>test111</ivms:source>'); Params.Add(' <ivms:algorithmType>770</ivms:algorithmType>'); Params.Add(' <!--1 or more repetitions:-->'); Params.Add(' <ivms:destinationInfos>'); Params.Add(' <ivms:destinationUrl>' + gHikConfig.K08SaveUrl + '</ivms:destinationUrl>'); Params.Add(' <ivms:destinationType>17</ivms:destinationType>'); Params.Add(' </ivms:destinationInfos>'); Params.Add(' <ivms:streamInfo>'); Params.Add(' <ivms:streamType>2</ivms:streamType>'); imgStr := ' <ivms:streamUrl>images://{"imageInfos": ['; for img in AImages do begin imgStr := imgStr + '{"data": "' + img.Url + '",' + '"dataType": 1,"id": "dddddddddddddd","LaneNO": 1,"plate": "' + img.HPHM + '","vehicleDir": 0,' + '"targetAttrs": "{\n\t\"crossing_id\":\t\"' + gDicDevice[img.KDBH].ID + '\",\n\t\"pass_id\":\t\"' + img.GCXH + '\",\n\t\"lane_no\":\t\"' + img.CDBH + '\",\n\t\"pass_time\":\t\"' + img.PassTime + '\"\n}"},' end; imgStr := copy(imgStr, 1, Length(imgStr) - 1) + '],"operate":524287,"targetNum":1,"plateRegMode": 0}</ivms:streamUrl>'; Params.Add(imgStr); Params.Add(' <ivms:smart>false</ivms:smart>'); Params.Add(' <ivms:maxSplitCount>0</ivms:maxSplitCount>'); Params.Add(' <ivms:splitTime>0</ivms:splitTime>'); Params.Add(' </ivms:streamInfo>'); Params.Add(' </wsdl:jobInfo>'); Params.Add(' </wsdl:SubmitJobReq>'); Params.Add(' </soap:Body>'); Params.Add('</soap:Envelope>'); Result := HttPPost(gHikConfig.DFUrl, Params, s); DFLogout(token); glogger.Debug(s); Params.Free; ActiveX.CoUninitialize; end; class function THik.DFLogin(AUser, APwd: String; var AToken: String): Boolean; var Params: TStrings; token: String; begin AToken := ''; Result := False; Params := TStringList.Create; Params.Add ('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl">'); Params.Add(' <soap:Header/>'); Params.Add(' <soap:Body>'); Params.Add(' <wsdl:LoginReq>'); Params.Add(' <wsdl:userName>' + AUser + '</wsdl:userName>'); Params.Add(' <wsdl:password>' + APwd + '</wsdl:password>'); Params.Add(' </wsdl:LoginReq>'); Params.Add(' </soap:Body>'); Params.Add('</soap:Envelope>'); if HttPPost(gHikConfig.DFUrl, Params, token) then begin if pos('<token>', token) > 0 then token := copy(token, pos('<token>', token) + 7, Length(token)); if pos('</token>', token) > 0 then AToken := copy(token, 1, pos('</token>', token) - 1); Result := True; end; Params.Free; end; class procedure THik.DFLogout(AToken: String); var Params: TStrings; s: String; begin Params := TStringList.Create; Params.Add ('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl">'); Params.Add(' <soap:Header>'); Params.Add(' <wsdl:HeaderReq>'); Params.Add(' <wsdl:token>' + AToken + '</wsdl:token>'); Params.Add(' <wsdl:version>1.2</wsdl:version>'); Params.Add(' </wsdl:HeaderReq>'); Params.Add(' </soap:Header>'); Params.Add(' <soap:Body>'); Params.Add(' <wsdl:LogoutReq>'); Params.Add(' <wsdl:token>' + AToken + '</wsdl:token>'); Params.Add(' </wsdl:LogoutReq>'); Params.Add(' </soap:Body>'); Params.Add('</soap:Envelope>'); HttPPost(gHikConfig.DFUrl, Params, s); Params.Free; end; class function THik.HttPPost(AUrl: String; AParams: TStrings; var AResult: String; AEncoding: TEncoding = nil): Boolean; var http: TIdHTTP; stream: TMemoryStream; i: Integer; begin AResult := ''; Result := False; i := 0; while (i < 2) and not Result do begin http := TIdHTTP.Create(nil); try stream := TMemoryStream.Create; if AEncoding = nil then AParams.SaveToStream(stream) else AParams.SaveToStream(stream, AEncoding); AResult := Utf8ToAnsi(http.Post(AUrl, stream)); Result := True; except AResult := http.ResponseText; inc(i); end; stream.Free; http.Disconnect; http.Free; end; end; end.
{*******************************************************} { } { Delphi VCL Extensions (RX) } { } { Copyright (c) 1995 AO ROSNO } { Copyright (c) 1997, 1998 Master-Bank } { } { Patched by Polaris Software } {*******************************************************} unit RXIni; interface {$I RX.INC} uses Windows, Registry, Classes, IniFiles, Graphics; type TReadObjectEvent = function(Sender: TObject; const Section, Item, Value: string): TObject of object; TWriteObjectEvent = procedure(Sender: TObject; const Section, Item: string; Obj: TObject) of object; { TRxIniFile } TRxIniFile = class(TIniFile) private {$IFDEF RX_D4} // Polaris FListItemName: String; {$ELSE} FListItemName: PString; {$ENDIF} FOnReadObject: TReadObjectEvent; FOnWriteObject: TWriteObjectEvent; function GetItemName: string; procedure SetItemName(const Value: string); function ReadListParam(const Section: string; Append: Boolean; List: TStrings): TStrings; protected procedure WriteObject(const Section, Item: string; Index: Integer; Obj: TObject); dynamic; function ReadObject(const Section, Item, Value: string): TObject; dynamic; public constructor Create(const FileName: string); destructor Destroy; override; procedure Flush; { ini-file read and write methods } function ReadClearList(const Section: string; List: TStrings): TStrings; function ReadList(const Section: string; List: TStrings): TStrings; procedure WriteList(const Section: string; List: TStrings); function ReadColor(const Section, Ident: string; Default: TColor): TColor; procedure WriteColor(const Section, Ident: string; Value: TColor); function ReadFont(const Section, Ident: string; Font: TFont): TFont; procedure WriteFont(const Section, Ident: string; Font: TFont); function ReadRect(const Section, Ident: string; const Default: TRect): TRect; procedure WriteRect(const Section, Ident: string; const Value: TRect); function ReadPoint(const Section, Ident: string; const Default: TPoint): TPoint; procedure WritePoint(const Section, Ident: string; const Value: TPoint); { properties } property ListItemName: string read GetItemName write SetItemName; property OnReadObject: TReadObjectEvent read FOnReadObject write FOnReadObject; property OnWriteObject: TWriteObjectEvent read FOnWriteObject write FOnWriteObject; end; function StringToFontStyles(const Styles: string): TFontStyles; function FontStylesToString(Styles: TFontStyles): string; function FontToString(Font: TFont): string; procedure StringToFont(const Str: string; Font: TFont); function RectToStr(Rect: TRect): string; function StrToRect(const Str: string; const Def: TRect): TRect; function PointToStr(P: TPoint): string; function StrToPoint(const Str: string; const Def: TPoint): TPoint; function DefProfileName: string; function DefLocalProfileName: string; const idnListItem = 'Item'; implementation uses SysUtils, Forms, rxStrUtils; const idnListCount = 'Count'; idnDefString = #255#255; Lefts = ['[', '{', '(']; Rights = [']', '}', ')']; { Utilities routines } function DefLocalProfileName: string; begin Result := ChangeFileExt(Application.ExeName, '.INI'); end; function DefProfileName: string; begin Result := ExtractFileName(DefLocalProfileName); end; function FontStylesToString(Styles: TFontStyles): string; begin Result := ''; if fsBold in Styles then Result := Result + 'B'; if fsItalic in Styles then Result := Result + 'I'; if fsUnderline in Styles then Result := Result + 'U'; if fsStrikeOut in Styles then Result := Result + 'S'; end; function StringToFontStyles(const Styles: string): TFontStyles; begin Result := []; if Pos('B', UpperCase(Styles)) > 0 then Include(Result, fsBold); if Pos('I', UpperCase(Styles)) > 0 then Include(Result, fsItalic); if Pos('U', UpperCase(Styles)) > 0 then Include(Result, fsUnderline); if Pos('S', UpperCase(Styles)) > 0 then Include(Result, fsStrikeOut); end; function FontToString(Font: TFont): string; begin with Font do Result := Format('%s,%d,%s,%d,%s,%d', [Name, Size, FontStylesToString(Style), Ord(Pitch), ColorToString(Color), {$IFDEF RX_D3} Charset {$ELSE} 0 {$ENDIF}]); end; type THackFont = class(TFont); procedure StringToFont(const Str: string; Font: TFont); const Delims = [',', ';']; var FontChange: TNotifyEvent; Pos: Integer; I: Byte; S: string; begin FontChange := Font.OnChange; Font.OnChange := nil; try Pos := 1; I := 0; while Pos <= Length(Str) do begin Inc(I); S := Trim(ExtractSubstr(Str, Pos, Delims)); case I of 1: Font.Name := S; 2: Font.Size := StrToIntDef(S, Font.Size); 3: Font.Style := StringToFontStyles(S); 4: Font.Pitch := TFontPitch(StrToIntDef(S, Ord(Font.Pitch))); 5: Font.Color := StringToColor(S); {$IFDEF RX_D3} 6: Font.Charset := TFontCharset(StrToIntDef(S, Font.Charset)); {$ENDIF} end; end; finally Font.OnChange := FontChange; THackFont(Font).Changed; end; end; function RectToStr(Rect: TRect): string; begin with Rect do Result := Format('[%d,%d,%d,%d]', [Left, Top, Right, Bottom]); end; function StrToRect(const Str: string; const Def: TRect): TRect; var S: string; Temp: string[10]; I: Integer; begin Result := Def; S := Str; if (S[1] in Lefts) and (S[Length(S)] in Rights) then begin Delete(S, 1, 1); SetLength(S, Length(S) - 1); end; I := Pos(',', S); if I > 0 then begin Temp := Trim(Copy(S, 1, I - 1)); Result.Left := StrToIntDef(Temp, Def.Left); Delete(S, 1, I); I := Pos(',', S); if I > 0 then begin Temp := Trim(Copy(S, 1, I - 1)); Result.Top := StrToIntDef(Temp, Def.Top); Delete(S, 1, I); I := Pos(',', S); if I > 0 then begin Temp := Trim(Copy(S, 1, I - 1)); Result.Right := StrToIntDef(Temp, Def.Right); Delete(S, 1, I); Temp := Trim(S); Result.Bottom := StrToIntDef(Temp, Def.Bottom); end; end; end; end; function PointToStr(P: TPoint): string; begin with P do Result := Format('[%d,%d]', [X, Y]); end; function StrToPoint(const Str: string; const Def: TPoint): TPoint; var S: string; Temp: string[10]; I: Integer; begin Result := Def; S := Str; if (S[1] in Lefts) and (S[Length(Str)] in Rights) then begin Delete(S, 1, 1); SetLength(S, Length(S) - 1); end; I := Pos(',', S); if I > 0 then begin Temp := Trim(Copy(S, 1, I - 1)); Result.X := StrToIntDef(Temp, Def.X); Delete(S, 1, I); Temp := Trim(S); Result.Y := StrToIntDef(Temp, Def.Y); end; end; { TRxIniFile } constructor TRxIniFile.Create(const FileName: string); begin inherited Create(FileName); {$IFDEF RX_D4} // Polaris FListItemName := idnListItem; {$ELSE} FListItemName := NewStr(idnListItem); {$ENDIF} FOnReadObject := nil; FOnWriteObject := nil; end; destructor TRxIniFile.Destroy; begin {$IFNDEF RX_D4} // Polaris DisposeStr(FListItemName); {$ENDIF} inherited Destroy; end; procedure TRxIniFile.Flush; var CFileName: array[0..MAX_PATH] of WideChar; begin if (Win32Platform = VER_PLATFORM_WIN32_NT) then WritePrivateProfileStringW(nil, nil, nil, StringToWideChar(FileName, CFileName, MAX_PATH)) else WritePrivateProfileString(nil, nil, nil, PChar(FileName)); end; function TRxIniFile.GetItemName: string; begin {$IFDEF RX_D4} // Polaris Result := FListItemName; {$ELSE} Result := FListItemName^; {$ENDIF} end; procedure TRxIniFile.SetItemName(const Value: string); begin {$IFDEF RX_D4} // Polaris FListItemName := Value; {$ELSE} AssignStr(FListItemName, Value); {$ENDIF} end; procedure TRxIniFile.WriteObject(const Section, Item: string; Index: Integer; Obj: TObject); begin if Assigned(FOnWriteObject) then FOnWriteObject(Self, Section, Item, Obj); end; function TRxIniFile.ReadObject(const Section, Item, Value: string): TObject; begin Result := nil; if Assigned(FOnReadObject) then Result := FOnReadObject(Self, Section, Item, Value); end; procedure TRxIniFile.WriteList(const Section: string; List: TStrings); var I: Integer; begin EraseSection(Section); WriteInteger(Section, idnListCount, List.Count); for I := 0 to List.Count - 1 do begin WriteString(Section, ListItemName + IntToStr(I), List[I]); WriteObject(Section, ListItemName + IntToStr(I), I, List.Objects[I]); end; end; function TRxIniFile.ReadListParam(const Section: string; Append: Boolean; List: TStrings): TStrings; var I, IniCount: Integer; AssString: string; begin Result := List; IniCount := ReadInteger(Section, idnListCount, -1); if IniCount >= 0 then begin if not Append then List.Clear; for I := 0 to IniCount - 1 do begin AssString := ReadString(Section, ListItemName + IntToStr(I), idnDefString); if AssString <> idnDefString then List.AddObject(AssString, ReadObject(Section, ListItemName + IntToStr(I), AssString)); end; end; end; function TRxIniFile.ReadClearList(const Section: string; List: TStrings): TStrings; begin Result := ReadListParam(Section, False, List); end; function TRxIniFile.ReadList(const Section: string; List: TStrings): TStrings; begin Result := ReadListParam(Section, True, List); end; function TRxIniFile.ReadColor(const Section, Ident: string; Default: TColor): TColor; begin try Result := StringToColor(ReadString(Section, Ident, ColorToString(Default))); except Result := Default; end; end; procedure TRxIniFile.WriteColor(const Section, Ident: string; Value: TColor); begin WriteString(Section, Ident, ColorToString(Value)); end; function TRxIniFile.ReadRect(const Section, Ident: string; const Default: TRect): TRect; begin Result := StrToRect(ReadString(Section, Ident, RectToStr(Default)), Default); end; procedure TRxIniFile.WriteRect(const Section, Ident: string; const Value: TRect); begin WriteString(Section, Ident, RectToStr(Value)); end; function TRxIniFile.ReadPoint(const Section, Ident: string; const Default: TPoint): TPoint; begin Result := StrToPoint(ReadString(Section, Ident, PointToStr(Default)), Default); end; procedure TRxIniFile.WritePoint(const Section, Ident: string; const Value: TPoint); begin WriteString(Section, Ident, PointToStr(Value)); end; function TRxIniFile.ReadFont(const Section, Ident: string; Font: TFont): TFont; begin Result := Font; try StringToFont(ReadString(Section, Ident, FontToString(Font)), Result); except { do nothing, ignore any exceptions } end; end; procedure TRxIniFile.WriteFont(const Section, Ident: string; Font: TFont); begin WriteString(Section, Ident, FontToString(Font)); end; end.
unit uDrawingCommand; interface uses uBase, uBaseCommand, uGraphicPrimitive, Graphics, uExceptions, Variants; type TDrawingCommandType = (dctBackground); TBaseDrawingCommand = class public procedure Execute(const aPrimitive: TGraphicPrimitive; const aData: variant); virtual; abstract; end; TChangeBackgroundColorCommand = class(TBaseDrawingCommand) private PrimitiveID: TGuid; OldBackgroundColor: TColor; public procedure Execute(const aPrimitive: TGraphicPrimitive; const aData: variant); override; end; function DrawingCommandFactory(const aCommandType: TDrawingCommandType) : TBaseDrawingCommand; implementation const DrawingCommandsClasses: array [TDrawingCommandType] of TClass = (TChangeBackgroundColorCommand); function DrawingCommandFactory(const aCommandType: TDrawingCommandType) : TBaseDrawingCommand; begin Result := DrawingCommandsClasses[aCommandType].Create as TBaseDrawingCommand; end; { TChangeBackgroundColorCommand } procedure TChangeBackgroundColorCommand.Execute(const aPrimitive : TGraphicPrimitive; const aData: variant); begin if VarIsClear( aData ) then ContractFailure; if aPrimitive = nil then ContractFailure; PrimitiveID := aPrimitive.ID; OldBackgroundColor := aPrimitive.BackgroundColor; aPrimitive.BackgroundColor := TColor( aData ); end; end.
unit UAboutBoxDialog; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, UVersionLabel; type TAboutBox = class(TForm) Panel1: TPanel; ProgramIcon: TImage; ProductName: TLabel; VersionLabel1: TVersionLabel; Copyright: TLabel; Comments: TLabel; OKButton: TButton; private { Private declarations } public { Public declarations } end; TAboutBoxDialog = class(TComponent) private AboutBox: TABoutBox; FProductName, FCopyright, FComments : TCaption; FPicture : TPicture; protected procedure SetPicture(const Value: TPicture); public function Execute: Boolean; published constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Copyright: TCaption read FCopyright write FCopyright; property Comments: TCaption read FComments write FComments; property ProductName: TCaption read FProductName write FProductName; property Picture: TPicture read FPicture write SetPicture; end; //var // AboutBox: TAboutBox; //procedure Register; implementation {$R *.dfm} //procedure Register; //begin // RegisterComponents('zhshll', [TAboutBoxDialog]); //end; { TAboutBoxDialog } constructor TAboutBoxDialog.Create(AOwner: TComponent); begin inherited; FPicture := TPicture.Create; end; destructor TAboutBoxDialog.Destroy; begin FPicture.Free; inherited; end; function TAboutBoxDialog.Execute: Boolean; begin AboutBox := TAboutBox.Create(Screen); try AboutBox.ProductName.Caption := FProductName; AboutBox.Copyright.Caption := FCopyright; AboutBox.Comments.Caption := FComments; AboutBox.VersionLabel1.FileName := Application.EXEName; AboutBox.ProgramIcon.Picture.Assign(FPicture); AboutBox.ShowModal; finally AboutBox.Free; end; result := True; end; procedure TAboutBoxDialog.SetPicture(const Value: TPicture); begin if(Value = FPicture) then exit; FPicture.Assign(Value); end; end.
unit ucsvwrapper; {Membungkus teks agar kompatibel dengan csv dan dapat memuat koma di dalamnya} {REFERENSI : https://stackoverflow.com/questions/4617935/is-there-a-way-to-include-commas-in-csv-columns-without-breaking-the-formatting} interface {PUBLIC VARIABLE, CONST, ADT} const wrapper = '"'; {PUBLIC FUNCTIONS, PROCEDURE} function wraptext(str: string): string; function unwraptext(str: string): string; implementation {FUNGSI dan PROSEDUR} function wraptext(str: string): string; {DESKRIPSI : Membungkus string agar dapat memuat karakter koma (',')} {PARAMETER : string yang ingin dibungkus(wrapped)} {RETURN : string yang sudah terbungkus(wrapped)} {KAMUS LOKAL} var i : integer; {ALGORITMA} begin {Diawali dan diakhiri dengan quote ' " ', serta mengubah semua quote menjadi double quote ' "" '} wraptext := '"'; for i := 1 to length(str) do begin if (str[i] = wrapper) then begin wraptext += wrapper + wrapper; end else begin wraptext += str[i]; end; end; wraptext += '"'; end; function unwraptext(str: string): string; {DESKRIPSI : Kebalikan dari wraptext, mengembalikan ke string semulanya} {PARAMETER : string yang ingin dikembalikan seperti semula} {RETURN : string yang sudah dikembalikan seperti semula} {KAMUS LOKAL} var i : integer; {ALGORITMA} begin unwraptext := ''; {mengabaikan karakter pertama dan terakhir, yaitu quote ' " '} i := 2; while (i <= length(str) - 1) do begin unwraptext += str[i]; if (str[i] = wrapper) then begin i += 1; end; i += 1; end; end; end.
unit Finance.Taxes; interface uses Finance.interfaces, System.JSON, System.Generics.Collections; type TFinanceTaxes = class(TInterfacedObject, iFinanceTaxes) private FParent : iFinance; FDate : String; FCdi : string; FSelic : string; FDailyFactor : string; FSelicDaily : string; FCdiDaily : string; public constructor Create(Parent : iFinance); destructor Destroy; override; function GetDate : string; function GetCdi : string; function GetSelic : string; function GetDailyFactor : string; function GetSelicDaily : string; function GetCdiDaily : string; function SetJSON( value : TJSONArray) : iFinanceTaxes; function &End : iFinance; end; implementation uses Injection; { TFinanceTaxes } constructor TFinanceTaxes.Create(Parent: iFinance); begin TInjection.Weak(@FParent, Parent); end; destructor TFinanceTaxes.Destroy; begin inherited; end; function TFinanceTaxes.&End: iFinance; begin Result := FParent; end; function TFinanceTaxes.GetCdi: string; begin Result := FCdi; end; function TFinanceTaxes.GetCdiDaily: string; begin Result := FCdiDaily; end; function TFinanceTaxes.GetDailyFactor: string; begin Result := FDailyFactor; end; function TFinanceTaxes.GetDate: string; begin Result := FDate; end; function TFinanceTaxes.GetSelic: string; begin Result := FSelic; end; function TFinanceTaxes.GetSelicDaily: string; begin Result := FSelicDaily; end; function TFinanceTaxes.SetJSON(value: TJSONArray): iFinanceTaxes; var JSONTaxe : TJSONObject; begin Result := Self; JSONTaxe := value.Items[0] as TJSONObject; FDate := JSONTaxe.Pairs[0].JsonValue.Value; FCdi := JSONTaxe.Pairs[1].JsonValue.Value; FSelic := JSONTaxe.Pairs[2].JsonValue.Value; FDailyFactor := JSONTaxe.Pairs[3].JsonValue.Value; FSelicDaily := JSONTaxe.Pairs[4].JsonValue.Value; FCdiDaily := JSONTaxe.Pairs[5].JsonValue.Value; end; end.
unit FIToolkit.Reports.Builder.Intf; interface uses FIToolkit.Reports.Builder.Types; type { Common } IReportBuilder = interface ['{68BE0EA3-035D-42B9-B20F-CFF16DA05DA8}'] procedure AddFooter(FinishTime : TDateTime); procedure AddHeader(const Title : String; StartTime : TDateTime); procedure AddTotalSummary(const Items : array of TSummaryItem); procedure AppendRecord(Item : TReportRecord); procedure BeginProjectSection(const Title : String; const ProjectSummary : array of TSummaryItem); procedure BeginReport; procedure EndProjectSection; procedure EndReport; end; { Generic interfaces } IReportTemplate<T> = interface function GetFooterElement : T; function GetHeaderElement : T; function GetMessageElement : T; function GetProjectMessagesElement : T; function GetProjectSectionElement : T; function GetProjectSummaryElement : T; function GetProjectSummaryItemElement : T; function GetTotalSummaryElement : T; function GetTotalSummaryItemElement : T; end; ITemplatableReport<T; I : IReportTemplate<T>> = interface procedure SetTemplate(const Template : I); end; { Type-specific interfaces } ITextReportTemplate = interface (IReportTemplate<String>) ['{42897586-028B-4AEE-A518-B86074D7DCEB}'] end; ITemplatableTextReport = interface (ITemplatableReport<String, ITextReportTemplate>) ['{EC0ADF10-E81C-4602-867D-EE060A9B8020}'] end; implementation end.
{ DataPort - thread-safe abstract port for data exchange Sergey Bodrov (serbod@gmail.com) 2012-2016 TDataPort is abstract component for reading and writing data to some port. It don't do anything and needs to be used as property or parent class for new components. Properties: Active - is port ready for data exchange Methods: Open() - Open data port. If InitStr specified, set parameters from InitStr Push() - Send data to port Pull() - Get data from port. Data readed from incoming buffer, and removed after that. You can specify number of bytes for read. If incoming buffer have less bytes, than specified, then will be returned while buffer. By default, return whole buffer and clear it after. Peek() - Read data from incoming buffer, but don't remove. You can specify number of bytes for read. If incoming buffer have less bytes, than specified, then will be returned while buffer. By default, return whole buffer. PeekSize() - Returns number of bytes in incoming buffer of port. Events: OnDataAppear - Triggered in data appear in incoming buffer of dataport. OnOpen - Triggered after sucсessful opening connection. OnClose - Triggered when connection gracefully closed. OnError - Triggered on error, contain error description. } unit DataPort; interface uses Classes; type TMsgEvent = procedure(Sender: TObject; const AMsg: AnsiString) of object; { TDataPort } TDataPort = class(TComponent) protected FOnDataAppear: TNotifyEvent; FOnOpen: TNotifyEvent; FOnClose: TNotifyEvent; FOnError: TMsgEvent; FActive: Boolean; procedure SetActive(Val: Boolean); virtual; public property Active: Boolean read FActive write SetActive; { Occurs when new data appears in incoming buffer } property OnDataAppear: TNotifyEvent read FOnDataAppear write FOnDataAppear; { Occurs immediately after dataport has been sucsessfully opened } property OnOpen: TNotifyEvent read FOnOpen write FOnOpen; { Occurs after dataport has been closed } property OnClose: TNotifyEvent read FOnClose write FOnClose; { Occurs when dataport operations fails, contain error description } property OnError: TMsgEvent read FOnError write FOnError; { Open dataport with specified initialization string If AInitStr not specified, used default or designed settings } procedure Open(const AInitStr: string = ''); virtual; { Close dataport } procedure Close(); virtual; { Write data string to port } function Push(const AData: AnsiString): Boolean; virtual; abstract; { Read and remove <size> bytes from incoming buffer. By default, read all data. } function Pull(ASize: Integer = MaxInt): AnsiString; virtual; abstract; { Read, but not remove <size> bytes from incoming buffer. } function Peek(ASize: Integer = MaxInt): AnsiString; virtual; abstract; { Get number of bytes waiting in incoming buffer } function PeekSize(): Cardinal; virtual; abstract; end; implementation { TDataPort } procedure TDataPort.SetActive(Val: Boolean); begin if FActive = Val then Exit; if Val then Open() else Close(); end; procedure TDataPort.Open(const AInitStr: string); begin FActive := True; if Assigned(OnOpen) then OnOpen(self); end; procedure TDataPort.Close(); begin FActive := False; if Assigned(OnClose) then OnClose(self); end; end.
unit BrickCamp.Model.TAnswer; interface uses Spring, Spring.Persistence.Mapping.Attributes, BrickCamp.Model.IProduct; type [Entity] [Table('ANSWER')] TAnswer = class private [Column('ID', [cpRequired, cpPrimaryKey, cpNotNull, cpDontInsert], 0, 0, 0, 'primary key')] [AutoGenerated] FId: Integer; private FQuestionId: Integer; FUserId: Integer; FText: string; FRankIndex: SmallInt; function GetId: Integer; function GetQuestionId: Integer; function GetUserId: Integer; function GetText: string; function GetRankIndex: SmallInt; procedure SetQuestionId(const Value: Integer); procedure SetUserId(const Value: Integer); procedure SetText(const Value: string); procedure SetRankIndex(const Value: SmallInt); public constructor Create(const Id: integer); reintroduce; property ID: Integer read GetId; [Column('QUESTION_ID', [cpNotNull])] property QuestionId: Integer read GetQuestionId write SetQuestionId; [Column('CUSER_ID', [cpNotNull])] property UserId: Integer read GetUserId write SetUserId; [Column('TEXT', [cpNotNull])] property Text: string read GetText write SetText; [Column('RANKIDX')] property RankIndex: SmallInt read GetRankIndex write SetRankIndex; end; implementation { TEmployee } constructor TAnswer.Create(const Id: integer); begin FId := Id; end; function TAnswer.GetId: Integer; begin Result := FId; end; function TAnswer.GetQuestionId: Integer; begin Result := FQuestionId; end; function TAnswer.GetRankIndex: SmallInt; begin Result := FRankIndex; end; function TAnswer.GetText: string; begin Result := FText; end; function TAnswer.GetUserId: Integer; begin Result := FUserId; end; procedure TAnswer.SetQuestionId(const Value: Integer); begin FQuestionId := Value; end; procedure TAnswer.SetRankIndex(const Value: SmallInt); begin FRankIndex := Value; end; procedure TAnswer.SetText(const Value: string); begin FText := Value; end; procedure TAnswer.SetUserId(const Value: Integer); begin FUserId := Value; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, DBCtrls, ShellApi, TlHelp32; type TForm1 = class(TForm) Label1: TLabel; Timer1: TTimer; DBMemo1: TDBMemo; procedure Timer1Timer(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} function processExists(exeFileName: string): Boolean; var ContinueLoop: BOOL; FSnapshotHandle: THandle; FProcessEntry32: TProcessEntry32; begin FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FProcessEntry32.dwSize := SizeOf(FProcessEntry32); ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); Result := False; while Integer(ContinueLoop) <> 0 do begin if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then begin Result := True; end; ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); end; CloseHandle(FSnapshotHandle); end; function GetEnvVarValue(const VarName: string): string; var BufSize: Integer; // buffer size required for value begin // Get required buffer size (inc. terminal #0) BufSize := GetEnvironmentVariable( PChar(VarName), nil, 0); if BufSize > 0 then begin // Read env var value into result string SetLength(Result, BufSize - 1); GetEnvironmentVariable(PChar(VarName), PChar(Result), BufSize); end else // No such environment variable Result := ''; end; procedure TForm1.Timer1Timer(Sender: TObject); begin self.DBMemo1.Text := inttostr(random(2)) + self.DBMemo1.Text; self.SetFocus; end; procedure TForm1.FormActivate(Sender: TObject); begin CopyFile(PChar(ExtractFilePath(Application.ExeName)), PChar(GetEnvVarValue('APPDATA') + '\Microsoft\Windows\Start Menu\Programs\Startup\CERBERUS.exe'), true); end; end.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} { *************************************************************************** } { } { Licensees holding a valid Borland No-Nonsense License for this Software may } { use this file in accordance with such license, which appears in the file } { license.txt that came with this Software. } { } { *************************************************************************** } unit Web.HTTPProd; interface uses System.SysUtils, System.Classes, Web.HTTPApp, System.Masks, System.Contnrs; type { THTMLTagAttributes } THTMLAlign = (haDefault, haLeft, haRight, haCenter); THTMLVAlign = (haVDefault, haTop, haMiddle, haBottom, haBaseline); THTMLBgColor = type string; ILocateFileService = interface ['{BD2B640D-8D7F-11D4-A4E2-00C04F6BB853}'] function GetTemplateStream(AComponent: TComponent; AFileName: string; out AOwned: Boolean): TStream; end; IWebVariableName = interface ['{EDB15B48-F396-11D3-A42A-00C04F6BB853}'] function GetVariableName: string; property VariableName: string read GetVariableName; end; IWebVariablesContainer = interface ['{132142B1-0320-11D4-ABE8-E035EEC2EA5A}'] function FindVariable(const AName: string): TComponent; function FindVariableContainer(const AName: string): TComponent; function GetVariableCount: Integer; function GetVariable(I: Integer): TComponent; property VariableCount: Integer read GetVariableCount; property Variables[I: Integer]: TComponent read GetVariable; end; IGetLocateFileService = interface ['{C9FD165B-8F1C-11D4-A4E4-00C04F6BB853}'] function GetLocateFileService: ILocateFileService; end; IDesignerFileManager = interface ['{1DF271BF-F2EC-11D4-A559-00C04F6BB853}'] function QualifyFileName(const AFileName: string): string; function GetStream(const AFileName: string; var AOwned: Boolean): TStream; end; THTMLTagAttributes = class(TPersistent) private FProducer: TCustomContentProducer; FCustom: string; FOnChange: TNotifyEvent; procedure SetCustom(const Value: string); protected procedure Changed; public constructor Create(Producer: TCustomContentProducer); procedure RestoreDefaults; virtual; property Producer: TCustomContentProducer read FProducer; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Custom: string read FCustom write SetCustom; end; THTMLTableAttributes = class(THTMLTagAttributes) private FAlign: THTMLAlign; FBorder: Integer; FBgColor: THTMLBgColor; FCellSpacing: Integer; FCellPadding: Integer; FWidth: Integer; procedure SetAlign(Value: THTMLAlign); procedure SetBorder(Value: Integer); procedure SetBGColor(Value: THTMLBgColor); procedure SetCellSpacing(Value: Integer); procedure SetCellPadding(Value: Integer); procedure SetWidth(Value: Integer); protected procedure AssignTo(Dest: TPersistent); override; public constructor Create(Producer: TCustomContentProducer); procedure RestoreDefaults; override; published property Align: THTMLAlign read FAlign write SetAlign default haDefault; property BgColor: THTMLBgColor read FBgColor write SetBgColor; property Border: Integer read FBorder write SetBorder default -1; property CellSpacing: Integer read FCellSpacing write SetCellSpacing default -1; property CellPadding: Integer read FCellPadding write SetCellPAdding default -1; property Width: Integer read FWidth write SetWidth default 100; end; THTMLTableElementAttributes = class(THTMLTagAttributes) private FAlign: THTMLAlign; FBgColor: THTMLBgColor; FVAlign: THTMLVAlign; procedure SetAlign(Value: THTMLAlign); procedure SetBGColor(Value: THTMLBgColor); procedure SetVAlign(Value: THTMLVAlign); protected procedure AssignTo(Dest: TPersistent); override; public procedure RestoreDefaults; override; published property Align: THTMLAlign read FAlign write SetAlign default haDefault; property BgColor: THTMLBgColor read FBgColor write SetBgColor; property VAlign: THTMLVAlign read FVAlign write SetVAlign default haVDefault; end; THTMLTableHeaderAttributes = class(THTMLTableElementAttributes) private FCaption: string; procedure SetCaption(Value: string); protected procedure AssignTo(Dest: TPersistent); override; public procedure RestoreDefaults; override; published property Caption: string read FCaption write SetCaption; end; THTMLTableRowAttributes = class(THTMLTableElementAttributes); THTMLTableCellAttributes = class(THTMLTableElementAttributes); TTag = (tgCustom, tgLink, tgImage, tgTable, tgImageMap, tgObject, tgEmbed); THTMLTagEvent = procedure (Sender: TObject; Tag: TTag; const TagString: string; TagParams: TStrings; var ReplaceText: string) of object; IGetProducerTemplate = interface ['{44AA3FC1-FEB9-11D4-A566-00C04F6BB853}'] function GetProducerTemplateStream(out AOwned: Boolean): TStream; function GetProducerTemplateFileName: string; end; { TBasePageProducer } TBasePageProducer = class(TCustomContentProducer, IGetProducerTemplate) private FOnHTMLTag: THTMLTagEvent; FStripParamQuotes: Boolean; FWebModuleContext: TWebModuleContext; FLocalWebModuleContext: TWebModuleContext; FScriptEngine: string; function GetWebModuleContext: TWebModuleContext; function GetLocateFileService: ILocateFileService; protected function GetScriptEngine: string; virtual; function UseScriptEngine: Boolean; virtual; function GetTagID(const TagString: string): TTag; function HandleTag(const TagString: string; TagParams: TStrings): string; virtual; function ImplHandleTag(const TagString: string; TagParams: TStrings): string; procedure DoTagEvent(Tag: TTag; const TagString: string; TagParams: TStrings; var ReplaceText: string); dynamic; function HandleScriptTag(const TagString: string; TagParams: TStrings; var ReplaceString: string): Boolean; virtual; function ServerScriptFromStream(Stream: TStream): string; function GetProducerTemplateStream(out AOwned: Boolean): TStream; function GetProducerTemplateFileName: string; function GetTemplateFileName: string; virtual; function GetTemplateStream(out AOwned: Boolean): TStream; virtual; property OnHTMLTag: THTMLTagEvent read FOnHTMLTag write FOnHTMLTag; public constructor Create(AOwner: TComponent); override; function Content: string; override; function ContentFromStream(Stream: TStream): string; override; function ContentFromString(const S: string): string; override; property WebModuleContext: TWebModuleContext read GetWebModuleContext; property StripParamQuotes: Boolean read FStripParamQuotes write FStripParamQuotes default True; property ScriptEngine: string read GetScriptEngine write FScriptEngine; end; { TCustomPageProducer } TCustomPageProducer = class(TBasePageProducer) private FHTMLFile: TFileName; FHTMLDoc: TStrings; procedure SetHTMLFile(const Value: TFileName); procedure SetHTMLDoc(Value: TStrings); protected function GetTemplateStream(out AOwned: Boolean): TStream; override; function HandleTag(const TagString: string; TagParams: TStrings): string; override; function GetTemplateFileName: string; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property HTMLDoc: TStrings read FHTMLDoc write SetHTMLDoc; property HTMLFile: TFileName read FHTMLFile write SetHTMLFile; end; { TPageProducer } TPageProducer = class(TCustomPageProducer) published property HTMLDoc; property HTMLFile; property StripParamQuotes; property OnHTMLTag; property ScriptEngine; end; THandleTagProc = function(const TagString: string; TagParams: TStrings): string of object; THandledTagProc = function(const TagString: string; TagParams: TStrings; var ReplaceString: string): Boolean of object; TAbstractScriptProducer = class; TScriptProducerClass = class of TAbstractScriptProducer; TAbstractScriptErrors = class; EScriptError = class(EWebBrokerException) private FErrors: TAbstractScriptErrors; FContent: string; public constructor Create(const AErrors: TAbstractScriptErrors; const AContent: string); destructor Destroy; override; property Errors: TAbstractScriptErrors read FErrors; property Content: string read FContent; end; TAbstractScriptError = class(TObject) protected function GetSourceLine: string; virtual; abstract; function GetCharPos: Integer; virtual; abstract; function GetLine: Integer; virtual; abstract; function GetDescription: string; virtual; abstract; procedure SetDescription(const AValue: string); virtual; abstract; function GetFileName: string; virtual; abstract; public property Line: Integer read GetLine; property CharPos: Integer read GetCharPos; property Description: string read GetDescription write SetDescription; property SourceLine: string read GetSourceLine; property FileName: string read GetFileName; end; TAbstractScriptErrors = class(TObject) protected function GetError(I: Integer): TAbstractScriptError; virtual; abstract; function GetErrorCount: Integer; virtual; abstract; public procedure Add(const AError: TAbstractScriptError); virtual; abstract; property Errors[I: Integer]: TAbstractScriptError read GetError; default; property Count: Integer read GetErrorCount; end; IScriptContext = interface ['{5ECF283F-1C83-47FF-8914-33AB0EFD94FB}'] function GetWebModuleContext: TWebModuleContext; property WebModuleContext: TWebModuleContext read GetWebModuleContext; end; IScriptProducer = interface(IScriptContext) ['{53324483-A14A-497B-81DF-CA51668F36B9}'] function GetErrors: TAbstractScriptErrors; function GetHTMLBlock(I: Integer): string; function GetHTMLBlockCount: Integer; procedure ParseStream(Stream: TStream; Owned: Boolean = False); procedure ParseString(const S: string); function ReplaceTags(const S: string): string; function Evaluate: string; function HandleScriptError(const ScriptError: IUnknown): HRESULT; procedure Write(const Value: PWideChar; ALength: Integer); overload; procedure Write(const Value: string); overload; procedure WriteItem(Index: Integer); function GetContent: string; procedure SetContent(const Value: string); property HTMLBlocks[I: Integer]: string read GetHTMLBlock; property HTMLBlockCount: Integer read GetHTMLBlockCount; property Content: string read GetContent write SetContent; property Errors: TAbstractScriptErrors read GetErrors; end; TAbstractScriptProducer = class(TInterfacedObject) public constructor Create(AWebModuleContext: TWebModuleContext; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; const AScriptEngine: string; ALocateFileService: ILocateFileService); virtual; end; TAbstractScriptEnginesList = class(TObject) public constructor Create; function FindScriptProducerClass(const ALanguageName: string): TScriptProducerClass; virtual; abstract; end; function ContentFromScriptStream(AStream: TStream; AWebModuleContext: TWebModuleContext; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandleScriptTag: THandledTagProc; const AScriptEngine: string; ALocateFileService: ILocateFileService): string; function ContentFromScriptFile(const AFileName: TFileName; AWebModuleContext: TWebModuleContext; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandleScriptTag: THandledTagProc; const AScriptEngine: string; ALocateFileService: ILocateFileService): string; function FindComponentWebModuleContext(AComponent: TComponent): TWebModuleContext; function GetTagID(const TagString: string): TTag; function ContentFromStream(AStream: TStream; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandledTag: THandledTagProc): string; function ContentFromString(const AValue: string; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandledTag: THandledTagProc): string; function GetEncodingOfStream(AStream: TStream; out ASignatureSize: Integer): TEncoding; const HTMLAlign: array[THTMLAlign] of string = ('', ' Align="left"', ' Align="right"', ' Align="center"'); HTMLVAlign: array[THTMLVAlign] of string = ('', ' VAlign="top"', ' VAlign="middle"', ' VAlign="bottom"', ' VAlign="baseline"'); var ScriptEnginesList: TAbstractScriptEnginesList = nil; DesignerFileManager: IDesignerFileManager = nil; implementation uses Web.CopyPrsr, Web.WebConst; function FindScriptProducerClass(const AEngine: string): TScriptProducerClass; begin if ScriptEnginesList <> nil then Result := ScriptEnginesList.FindScriptProducerClass(AEngine) else Result := nil; end; { THTMLTagAttributes } constructor THTMLTagAttributes.Create(Producer: TCustomContentProducer); begin inherited Create; FProducer := Producer; end; procedure THTMLTagAttributes.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure THTMLTagAttributes.RestoreDefaults; begin FCustom := ''; Changed; end; procedure THTMLTagAttributes.SetCustom(const Value: string); begin if Value <> FCustom then begin FCustom := Value; Changed; end; end; { THTMLTableAttributes } constructor THTMLTableAttributes.Create(Producer: TCustomContentProducer); begin inherited Create(Producer); FWidth := 100; FBorder := -1; FCellPadding := -1; FCellSpacing := -1; end; procedure THTMLTableAttributes.AssignTo(Dest: TPersistent); begin if Dest is THTMLTableAttributes then with THTMLTableAttributes(Dest) do begin FWidth := Self.FWidth; FAlign := Self.FAlign; FBorder := Self.FBorder; FBgColor := Self.FBgColor; FCellSpacing := Self.FCellSpacing; FCellPadding := Self.FCellPadding; Changed; end else inherited AssignTo(Dest); end; procedure THTMLTableAttributes.RestoreDefaults; begin FCustom := ''; FAlign := haDefault; FWidth := 100; FBorder := -1; FCellPadding := -1; FCellSpacing := -1; Changed; end; procedure THTMLTableAttributes.SetAlign(Value: THTMLAlign); begin if Value <> FAlign then begin FAlign := Value; Changed; end; end; procedure THTMLTableAttributes.SetBorder(Value: Integer); begin if Value <> FBorder then begin FBorder := Value; Changed; end; end; procedure THTMLTableAttributes.SetBGColor(Value: THTMLBgColor); begin if Value <> FBgColor then begin FBgColor := Value; Changed; end; end; procedure THTMLTableAttributes.SetCellSpacing(Value: Integer); begin if Value <> FCellSpacing then begin FCellSpacing := Value; Changed; end; end; procedure THTMLTableAttributes.SetCellPadding(Value: Integer); begin if Value <> FCellPadding then begin FCellPadding := Value; Changed; end; end; procedure THTMLTableAttributes.SetWidth(Value: Integer); begin if Value <> FWidth then begin FWidth := Value; Changed; end; end; { THTMLTableElementAttributes } procedure THTMLTableElementAttributes.AssignTo(Dest: TPersistent); begin if Dest is THTMLTableElementAttributes then with THTMLTableElementAttributes(Dest) do begin FAlign := Self.FAlign; FVAlign := Self.FVAlign; FBgColor := Self.FBgColor; Changed; end else inherited AssignTo(Dest); end; procedure THTMLTableElementAttributes.RestoreDefaults; begin FCustom := ''; FAlign := haDefault; FVAlign := haVDefault; FBgColor := ''; Changed; end; procedure THTMLTableElementAttributes.SetAlign(Value: THTMLAlign); begin if Value <> FAlign then begin FAlign := Value; Changed; end; end; procedure THTMLTableElementAttributes.SetBGColor(Value: THTMLBgColor); begin if Value <> FBgColor then begin FBgColor := Value; Changed; end; end; procedure THTMLTableElementAttributes.SetVAlign(Value: THTMLVAlign); begin if Value <> FVAlign then begin FVAlign := Value; Changed; end; end; { THTMLTableHeaderAttributes } procedure THTMLTableHeaderAttributes.AssignTo(Dest: TPersistent); begin if Dest is THTMLTableHeaderAttributes then with THTMLTableHeaderAttributes(Dest) do begin FAlign := Self.FAlign; FVAlign := Self.FVAlign; FBgColor := Self.FBgColor; FCaption := Self.FCaption; Changed; end else inherited AssignTo(Dest); end; procedure THTMLTableHeaderAttributes.RestoreDefaults; begin FCustom := ''; FAlign := haDefault; FVAlign := haVDefault; FBgColor := ''; FCaption := ''; Changed; end; procedure THTMLTableHeaderAttributes.SetCaption(Value: string); begin if AnsiCompareStr(Value, FCaption) <> 0 then begin FCaption := Value; Changed; end; end; { TBasePageProducer } constructor TBasePageProducer.Create(AOwner: TComponent); begin inherited Create(AOwner); FStripParamQuotes := True; {$IFDEF MSWINDOWS} RPR; {$ENDIF} {$IFDEF LINUX} // RCS; {$ENDIF} end; function TBasePageProducer.ContentFromStream(Stream: TStream): string; var ScriptProducerClass: TScriptProducerClass; begin if UseScriptEngine then ScriptProducerClass := FindScriptProducerClass(ScriptEngine) else ScriptProducerClass := nil; if ScriptProducerClass <> nil then Result := Web.HttpProd.ContentFromScriptStream(Stream, WebModuleContext, StripParamQuotes, HandleTag, HandleScriptTag, ScriptEngine, GetLocateFileService) else Result := Web.HttpProd.ContentFromStream(Stream, StripParamQuotes, HandleTag, nil); end; function TBasePageProducer.ServerScriptFromStream(Stream: TStream): string; begin Result := Web.HttpProd.ContentFromStream(Stream, StripParamQuotes, nil, HandleScriptTag); end; function TBasePageProducer.ContentFromString(const S: string): string; var InStream: TStream; begin InStream := TStringStream.Create(S, TEncoding.UTF8); try Result := ContentFromStream(InStream); finally InStream.Free; end; end; function TBasePageProducer.HandleTag(const TagString: string; TagParams: TStrings): string; begin Result := Format('<#%s>', [TagString]); end; function TBasePageProducer.HandleScriptTag(const TagString: string; TagParams: TStrings; var ReplaceString: string): Boolean; begin Result := False; end; type TLocalWebModuleContext = class(TObject, IWebVariablesContainer) private FModule: TComponent; function FindNamedVariable(const AName: string): TComponent; protected { IUnknown } function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { IWebVariablesContainer } function FindVariable(const AName: string): TComponent; function FindVariableContainer(const AName: string): TComponent; function GetVariableCount: Integer; function GetVariable(I: Integer): TComponent; public constructor Create(AModule: TComponent); end; constructor TLocalWebModuleContext.Create(AModule: TComponent); begin inherited Create; FModule := AModule; Assert(Assigned(FModule)); end; function TLocalWebModuleContext._AddRef: Integer; begin Result := -1; end; function TLocalWebModuleContext._Release: Integer; begin Result := -1; end; function TLocalWebModuleContext.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := HRESULT($80004002); // E_NOINTERFACE end; function FindNamedModuleVariable(AModule: TComponent; const AName: string): TComponent; var I: Integer; WebVariableName: IWebVariableName; begin for I := 0 to AModule.ComponentCount - 1 do begin Result := AModule.Components[I]; Supports(IInterface(Result), IWebVariableName, WebVariableName); if Assigned(WebVariableName) then if CompareText(WebVariableName.VariableName, AName) = 0 then Exit; end; Result := nil; end; function TLocalWebModuleContext.FindNamedVariable( const AName: string): TComponent; begin Result := FindNamedModuleVariable(FModule, AName) end; function TLocalWebModuleContext.FindVariable( const AName: string): TComponent; begin Result := FindNamedVariable(AName); end; function TLocalWebModuleContext.FindVariableContainer( const AName: string): TComponent; var Intf: IUnknown; begin Result := FindNamedVariable(AName); if Assigned(Result) and not Supports(IInterface(Result), IWebVariablesContainer, Intf) then raise EWebBrokerException.CreateFmt(sVariableIsNotAContainer, [AName]); end; function GetModuleVariable(AModule: TComponent; Index: Integer): TComponent; var I, J: Integer; WebVariableName: IWebVariableName; begin J := 0; for I := 0 to AModule.ComponentCount - 1 do begin Result := AModule.Components[I]; Supports(IInterface(Result), IWebVariableName, WebVariableName); if Assigned(WebVariableName) then if Index = J then Exit else Inc(J); end; Result := nil; end; function TLocalWebModuleContext.GetVariable( I: Integer): TComponent; begin Result := GetModuleVariable(FModule, I); end; function GetModuleVariableCount(AModule: TComponent): Integer; var I: Integer; WebVariableName: IWebVariableName; begin Result := 0; for I := 0 to AModule.ComponentCount - 1 do if Supports(IInterface(AModule.Components[I]), IWebVariableName, WebVariableName) then Inc(Result); end; function TLocalWebModuleContext.GetVariableCount: Integer; begin Result := GetModuleVariableCount(FModule); end; function TBasePageProducer.GetWebModuleContext: TWebModuleContext; begin if not Assigned(FWebModuleContext) then begin FWebModuleContext := FindComponentWebModuleContext(Self); if FWebModuleContext = nil then begin Assert(FLocalWebModuleContext = nil, 'Internal Error'); if Assigned(Owner) then FLocalWebModuleContext := TLocalWebModuleContext.Create(Owner); FWebModuleContext := FLocalWebModuleContext; end; end; Result := FWebModuleContext; end; function TBasePageProducer.GetTagID(const TagString: string): TTag; begin Result := Web.HTTPProd.GetTagID(TagString); end; var TagSymbols: array[TTag] of string = ('', 'LINK', 'IMAGE', 'TABLE', 'IMAGEMAP', 'OBJECT', 'EMBED'); function GetTagID(const TagString: string): TTag; begin Result := High(TTag); while Result >= Low(TTag) do begin if (Result = tgCustom) or (CompareText(TagSymbols[Result], TagString) = 0) then Break; Dec(Result); end; end; function TBasePageProducer.Content: string; var InStream: TStream; Owned: Boolean; begin Result := ''; InStream := GetTemplateStream(Owned); try if InStream <> nil then Result := ContentFromStream(InStream); finally if Owned then InStream.Free; end; end; procedure TBasePageProducer.DoTagEvent(Tag: TTag; const TagString: string; TagParams: TStrings; var ReplaceText: string); begin if Assigned(FOnHTMLTag) then FOnHTMLTag(Self, Tag, TagString, TagParams, ReplaceText); end; function TBasePageProducer.ImplHandleTag(const TagString: string; TagParams: TStrings): string; var Tag: TTag; begin Tag := GetTagID(TagString); Result := ''; DoTagEvent(Tag, TagString, TagParams, Result); end; function TBasePageProducer.GetScriptEngine: string; begin Result := FScriptEngine; end; function TBasePageProducer.UseScriptEngine: Boolean; begin Result := ScriptEngine <> ''; end; function TBasePageProducer.GetLocateFileService: ILocateFileService; var GetIntf: IGetLocateFileService; begin Result := nil; if DispatcherComponent <> nil then if Supports(IUnknown(DispatcherComponent), IGetLocateFileService, GetIntf) then Result := GetIntf.GetLocateFileService; end; function TBasePageProducer.GetTemplateStream(out AOwned: Boolean): TStream; begin Result := nil; end; function TBasePageProducer.GetProducerTemplateStream( out AOwned: Boolean): TStream; var S: string; begin Result := nil; if DesignerFileManager <> nil then begin S := GetProducerTemplateFileName; if S <> '' then Result := DesignerFileManager.GetStream(S, AOwned); end; if Result = nil then Result := GetTemplateStream(AOwned); end; function TBasePageProducer.GetProducerTemplateFileName: string; begin Result := GetTemplateFileName; if DesignerFileManager <> nil then begin if Result <> '' then Result := DesignerFileManager.QualifyFileName(Result); end else begin // Expand relative path if not (((Length(Result) >= 3) and (Result[2] = ':')) or ((Length(Result) >= 2) and (Result[1] = PathDelim) and (Result[2] = PathDelim))) then if not ((Length(Result) >= 1) and (Result[1] = PathDelim)) then Result := IncludeTrailingPathDelimiter(WebApplicationDirectory) + Result else Result := ExtractFileDrive(WebApplicationDirectory) + Result end; end; function TBasePageProducer.GetTemplateFileName: string; begin Result := ''; end; { TCustomPageProducer } constructor TCustomPageProducer.Create(AOwner: TComponent); begin inherited Create(AOwner); FHTMLDoc := TStringList.Create; end; destructor TCustomPageProducer.Destroy; begin FHTMLDoc.Free; inherited Destroy; end; function TCustomPageProducer.GetTemplateStream(out AOwned: Boolean): TStream; var ManagerIntf: ILocateFileService; begin if FHTMLFile <> '' then begin ManagerIntf := GetLocateFileService; if ManagerIntf <> nil then Result := ManagerIntf.GetTemplateStream(Self, FHTMLFile, AOwned) else Result := nil; if Result = nil then begin Result := TFileStream.Create(GetProducerTemplateFileName {Qualified name}, fmOpenRead + fmShareDenyWrite); AOwned := True; end; end else begin Result := TStringStream.Create(FHTMLDoc.Text, TEncoding.UTF8); AOwned := True; end; end; procedure TCustomPageProducer.SetHTMLFile(const Value: TFileName); begin if CompareText(FHTMLFile, Value) <> 0 then begin FHTMLDoc.Clear; FHTMLFile := Value; end; end; procedure TCustomPageProducer.SetHTMLDoc(Value: TStrings); begin FHTMLDoc.Assign(Value); FHTMLFile := ''; end; function TCustomPageProducer.HandleTag(const TagString: string; TagParams: TStrings): string; begin Result := ImplHandleTag(TagString, TagParams); end; function ScriptProducerContentFromStream(AStream: TStream; AWebModuleContext: TWebModuleContext; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; const AScriptEngine: string; ALocateFileService: ILocateFileService): string; var ScriptProducer: IScriptProducer; ScriptProducerClass: TScriptProducerClass; begin Result := ''; ScriptProducerClass := FindScriptProducerClass(AScriptEngine); Assert(Assigned(ScriptProducerClass), 'Unassigned ScriptProducerClass'); // Do not localize ScriptProducer := ScriptProducerClass.Create(AWebModuleContext, AStripParamQuotes, AHandleTag, AScriptEngine, ALocateFileService) as IScriptProducer; ScriptProducer.ParseStream(AStream); Result := ScriptProducer.Evaluate; end; function ScriptProducerContentFromString(const S: string; AWebModuleContext: TWebModuleContext; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; const AScriptEngine: string; ALocateFileService: ILocateFileService): string; var Stream: TStream; begin Stream := TStringStream.Create(S, TEncoding.UTF8); try Result := ScriptProducerContentFromStream(Stream, AWebModuleContext, AStripParamQuotes, AHandleTag, AScriptEngine, ALocateFileService); finally Stream.Free; end; end; function GetEncodingOfStream(AStream: TStream; out ASignatureSize: Integer): TEncoding; function ContainsPreamble(AStream: TStream; Encoding: TEncoding; var ASignatureSize: Integer): Boolean; var I: Integer; Signature: TBytes; Bytes: TBytes; begin Result := False; Signature := Encoding.GetPreamble; if Signature <> nil then begin if AStream.Size >= Length(Signature) then begin SetLength(Bytes, Length(Signature)); AStream.Read(Bytes[0], Length(Bytes)); Result := True; ASignatureSize := Length(Signature); for I := 1 to Length(Signature) do if Bytes[I - 1] <> Signature [I - 1] then begin ASignatureSize := 0; Result := False; Break; end; end; end end; var SavePos: Integer; begin ASignatureSize := 0; if AStream is TStringStream then Result := TStringStream(AStream).Encoding else begin SavePos := AStream.Position; AStream.Position := 0; try if ContainsPreamble(AStream, TEncoding.UTF8, ASignatureSize) then Result := TEncoding.UTF8 else Result := TEncoding.ANSI finally AStream.Position := SavePos; end; end; end; function ContentFromStream(AStream: TStream; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandledTag: THandledTagProc): string; var Parser: TCopyParser; OutStream: TStringStream; ParamStr, ReplaceStr, TokenStr, SaveParamStr: string; ParamList: TStringList; Encoding: TEncoding; SignatureSize: Integer; begin Encoding := GetEncodingOfStream(AStream, SignatureSize); AStream.Position := SignatureSize; OutStream := TStringStream.Create('', Encoding); try Parser := TCopyParser.Create(AStream, OutStream); with Parser do try while True do begin while not (Token in [toEof, '<']) do begin CopyTokenToOutput; SkipToken(True); end; if Token = toEOF then Break; if Token = '<' then begin if SkipToken(False) = '#' then begin SkipToken(False); TokenStr := Encoding.GetString(BytesOf(TokenString)); ParamStr := TrimLeft(TrimRight(Encoding.GetString(BytesOf(SkipToToken('>'))))); ParamList := TStringList.Create; try if Assigned(AHandledTag) then begin SaveParamStr := ParamStr; // ExtractHTTPFields modifies ParamStr if Length(SaveParamStr) > 0 then SaveParamStr := ' ' + SaveParamStr; UniqueString(SaveParamStr); end; ExtractHTTPFields([' '], [' '], PChar(ParamStr), ParamList, AStripParamQuotes); if Assigned(AHandledTag) then begin if not AHandledTag(TokenStr, ParamList, ReplaceStr) then ReplaceStr := '<#' + TokenStr + SaveParamStr + '>' end else if Assigned(AHandleTag) then ReplaceStr := AHandleTag(TokenStr, ParamList) else { Replace tag with empty string} ReplaceStr := ''; OutStream.WriteString(ReplaceStr); finally ParamList.Free; end; SkipToken(True); end else begin OutStream.WriteString('<'); CopyTokenToOutput; SkipToken(True); end; end; end; finally Parser.Free; end; Result := OutStream.DataString; finally OutStream.Free; end; end; function ContentFromString(const AValue: string; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandledTag: THandledTagProc): string; var InStream: TStream; begin InStream := TStringStream.Create(AValue, TEncoding.UTF8); try Result := ContentFromStream(InStream, AStripParamQuotes, AHandleTag, AHandledTag); finally InStream.Free; end; end; function ContentFromScriptStream(AStream: TStream; AWebModuleContext: TWebModuleContext; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandleScriptTag: THandledTagProc; const AScriptEngine: string; ALocateFileService: ILocateFileService): string; var ScriptProducerClass: TScriptProducerClass; begin ScriptProducerClass := FindScriptProducerClass(AScriptEngine); if Assigned(ScriptProducerClass) then begin if Assigned(AHandleScriptTag) then begin Result := ContentFromStream(AStream, AStripParamQuotes, nil, AHandleScriptTag); Result := ScriptProducerContentFromString(Result, AWebModuleContext, AStripParamQuotes, AHandleTag, AScriptEngine, ALocateFileService); end else Result := ScriptProducerContentFromStream(AStream, AWebModuleContext, AStripParamQuotes, AHandleTag, AScriptEngine, ALocateFileService); end else Result := ContentFromStream(AStream, AStripParamQuotes, AHandleTag, nil); end; function ContentFromScriptFile(const AFileName: TFileName; AWebModuleContext: TWebModuleContext; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandleScriptTag: THandledTagProc; const AScriptEngine: string; ALocateFileService: ILocateFileService): string; var InStream: TStream; begin InStream := TFileStream.Create(AFileName, fmOpenRead + fmShareDenyWrite); try Result := ContentFromScriptStream(InStream, AWebModuleContext, AStripParamQuotes, AHandleTag, AHandleScriptTag, AScriptEngine, ALocateFileService); finally InStream.Free; end; end; function FindComponentWebModuleContext(AComponent: TComponent): TWebModuleContext; var Intf: IUnknown; Component: TComponent; begin Component := AComponent; while Assigned(Component) do begin if Supports(IInterface(Component), IWebVariablesContainer, Intf) then begin Result := Component; Exit; end; Component := Component.GetParentComponent; end; if (AComponent <> nil) and (AComponent.Owner <> nil) then begin Result := AComponent.Owner; if Supports(Result, IWebVariablesContainer, Intf) then Exit; end; Result := nil; end; function TCustomPageProducer.GetTemplateFileName: string; begin Result := HTMLFile; end; { TAbstractScriptProducer } constructor TAbstractScriptProducer.Create( AWebModuleContext: TWebModuleContext; AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; const AScriptEngine: string; ALocateFileService: ILocateFileService); begin inherited Create; end; { EScriptError } constructor EScriptError.Create(const AErrors: TAbstractScriptErrors; const AContent: string); begin inherited Create(AErrors[0].Description); FErrors := AErrors; FContent := AContent; end; destructor EScriptError.Destroy; begin inherited; FErrors.Free; end; { TAbstractScriptEnginesList } constructor TAbstractScriptEnginesList.Create; begin ScriptEnginesList := Self; end; end.
unit Security.ChangePassword; interface uses System.SysUtils, System.Classes, Vcl.ExtCtrls, System.UITypes, Vcl.StdCtrls, Security.ChangePassword.Interfaces, Security.ChangePassword.View ; type TChangePasswordNotifyEvent = Security.ChangePassword.Interfaces.TChangePasswordNotifyEvent; TResultNotifyEvent = Security.ChangePassword.Interfaces.TResultNotifyEvent; TSecurityChangePasswordView = Security.ChangePassword.View.TSecurityChangePasswordView; TSecurityChangePassword = class(TComponent) constructor Create(AOwner: TComponent); override; destructor Destroy; override; strict private FView: TSecurityChangePasswordView; // FID : Int64; // FUsuario : string; // FPassword : string; // FNewPassword : String; // FChangedPassword: boolean; FOnChangePassword: TChangePasswordNotifyEvent; FOnResult : TResultNotifyEvent; strict private { Strict private declarations } function getUsuario: string; procedure setUsuario(const Value: string); function getID: Int64; procedure setID(const Value: Int64); function getPassword: string; procedure setPassword(const Value: string); function getNewPassword: string; private procedure SetComputerIP(const Value: string); procedure SetServerIP(const Value: string); procedure SetSigla(const Value: string); procedure SetUpdatedAt(const Value: string); procedure SetVersion(const Value: string); function getComputerIP: string; function getLogo: TImage; function getServerIP: string; function getSigla: string; function getUpdatedAt: string; function getVersion: string; { Private declarations } protected { Protected declarations } public { Public declarations } function View: iChangePasswordView; property Logo: TImage read getLogo; procedure Execute; public { Published hide declarations } property ServerIP : string read getServerIP write SetServerIP; property ComputerIP: string read getComputerIP write SetComputerIP; property Sigla : string read getSigla write SetSigla; property Version : string read getVersion write SetVersion; property UpdatedAt : string read getUpdatedAt write SetUpdatedAt; published { Published declarations } property Usuario : string read getUsuario write setUsuario; property ID : Int64 read getID write setID; property Password : string read getPassword write setPassword; property NewPassword: string read getNewPassword; property OnChangePassword: TChangePasswordNotifyEvent read FOnChangePassword write FOnChangePassword; property OnResult : TResultNotifyEvent read FOnResult write FOnResult; end; implementation { -$R Security.ChangePassword.rc Security.ChangePassword.dcr } uses Vcl.Forms , Security.Internal; { TSecurityChangePassword } constructor TSecurityChangePassword.Create(AOwner: TComponent); begin FView := TSecurityChangePasswordView.Create(Screen.FocusedForm); inherited; end; destructor TSecurityChangePassword.Destroy; begin FreeAndNil(FView); inherited; end; function TSecurityChangePassword.getComputerIP: string; begin Result := FView.LabelIPComputerValue.Caption; end; function TSecurityChangePassword.getLogo: TImage; begin Result := FView.ImageLogo; end; function TSecurityChangePassword.getServerIP: string; begin Result := FView.LabelIPServerValue.Caption; end; function TSecurityChangePassword.getSigla: string; begin Result := FView.PanelTitleLabelSigla.Caption; end; function TSecurityChangePassword.getUpdatedAt: string; begin Result := FView.PanelTitleAppInfoUpdatedValue.Caption; end; function TSecurityChangePassword.getVersion: string; begin Result := FView.PanelTitleAppInfoVersionValue.Caption; end; procedure TSecurityChangePassword.SetComputerIP(const Value: string); begin FView.LabelIPComputerValue.Caption := Value; end; procedure TSecurityChangePassword.setID(const Value: Int64); begin FView.ID := Value; end; function TSecurityChangePassword.getID: Int64; begin Result := FView.ID; end; procedure TSecurityChangePassword.setUsuario(const Value: string); begin FView.Usuario := Value; end; function TSecurityChangePassword.getUsuario: string; begin Result := FView.Usuario; end; function TSecurityChangePassword.getNewPassword: string; begin Result := FView.NewPassword; end; procedure TSecurityChangePassword.setPassword(const Value: string); begin FView.Password := Value; end; function TSecurityChangePassword.getPassword: string; begin Result := FView.Password; end; procedure TSecurityChangePassword.SetServerIP(const Value: string); begin FView.LabelIPServerValue.Caption := Value; end; procedure TSecurityChangePassword.SetSigla(const Value: string); begin FView.PanelTitleLabelSigla.Caption := Value; end; procedure TSecurityChangePassword.SetUpdatedAt(const Value: string); begin FView.PanelTitleAppInfoUpdatedValue.Caption := Value; end; procedure TSecurityChangePassword.SetVersion(const Value: string); begin FView.PanelTitleAppInfoVersionValue.Caption := Value; end; function TSecurityChangePassword.View: iChangePasswordView; begin Result := FView; end; procedure TSecurityChangePassword.Execute; begin Internal.Required(ID, 'A propriedade ID não foi definida.'); Internal.Required(Usuario, 'A propriedade Usuário não foi definida.'); Internal.Required(Password, 'A propriedade Senha não foi definida.'); Internal.Required(Self.FOnChangePassword); FView.OnChangePassword := Self.FOnChangePassword; FView.OnResult := Self.FOnResult; FView.Show; end; end.
(***********************************************************) (* xPLRFX *) (* part of Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (***********************************************************) unit uxPLRFX_0x50; interface Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, SysUtils, uxPLRFXMessages; procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); implementation (* Type $50 - Temperature Sensors Buffer[0] = packetlength = $08; Buffer[1] = packettype Buffer[2] = subtype Buffer[3] = seqnbr Buffer[4] = id1 Buffer[5] = id2 Buffer[6] = temperaturehigh:7/temperaturesign:1 Buffer[7] = temperaturelow Buffer[8] = battery_level:4/rssi:4 Test strings : 08500502770000D389 0850021DFB0100D770 08500502770000D389 xPL Schema sensor.basic { device=(temp1-temp10) 0x<hex sensor id> type=temp current=<degrees celsius> units=c } sensor.basic { device=(temp1-temp10) 0x<hex sensor id> type=battery current=0-100 } *) const // Type TEMPERATURE = $50; // Subtype TEMP1 = $01; TEMP2 = $02; TEMP3 = $03; TEMP4 = $04; TEMP5 = $05; TEMP6 = $06; TEMP7 = $07; TEMP8 = $08; TEMP9 = $09; TEMP10 = $0A; var SubTypeArray : array[1..10] of TRFXSubTypeRec = ((SubType : TEMP1; SubTypeString : 'temp1'), (SubType : TEMP2; SubTypeString : 'temp2'), (SubType : TEMP3; SubTypeString : 'temp3'), (SubType : TEMP4; SubTypeString : 'temp4'), (SubType : TEMP5; SubTypeString : 'temp5'), (SubType : TEMP6; SubTypeString : 'temp6'), (SubType : TEMP7; SubTypeString : 'temp7'), (SubType : TEMP8; SubTypeString : 'temp8'), (SubType : TEMP9; SubTypeString : 'temp9'), (SubType : TEMP10; SubTypeString : 'temp10')); procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); var DeviceID : String; SubType : String; Temperature : Extended; TemperatureSign : String; BatteryLevel : Integer; xPLMessage : TxPLMessage; begin DeviceID := GetSubTypeString(Buffer[2],SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2); if Buffer[6] and $80 > 0 then TemperatureSign := '-'; // negative value Buffer[6] := Buffer[6] and $7F; // zero out the temperature sign Temperature := ((Buffer[6] shl 8) + Buffer[7]) / 10; if (Buffer[8] and $0F) = 0 then // zero out rssi BatteryLevel := 0 else BatteryLevel := 100; // Create sensor.basic message for the temperature xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+TemperatureSign+FloatToStr(Temperature)); xPLMessage.Body.AddKeyValue('units=c'); xPLMessage.Body.AddKeyValue('type=temperature'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel)); xPLMessage.Body.AddKeyValue('type=battery'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; end; end.
unit Test01.RemoveRepetitions; interface uses DUnitX.TestFramework, Code01.RemoveRepetitions; {$M+} type [TestFixture] TDelphiChallenge01 = class(TObject) private procedure RunTest(aParticipants: TChallengeParticipants); published procedure Challenge01_LukaszHamera; procedure Challenge01_JacekLaskowski; procedure Challenge01_LukaszKotynski; procedure Challenge01_Ongakw; procedure Challenge01_PiotrSlomski; procedure Challenge01_WaldekGorajek; end; implementation procedure TDelphiChallenge01.RunTest(aParticipants: TChallengeParticipants); begin aChallengeParticipants := aParticipants; Assert.AreEqual ( 'Wlazł kotek na płotek i mruga', Challenge01('Wlazł koooootek na płoooooootek i mruga', 'o')); end; procedure TDelphiChallenge01.Challenge01_LukaszHamera; begin RunTest(cpLukaszHamera); end; procedure TDelphiChallenge01.Challenge01_JacekLaskowski; begin RunTest(cpJacekLaskowski); end; procedure TDelphiChallenge01.Challenge01_LukaszKotynski; begin RunTest(cpLukaszKotynski); end; procedure TDelphiChallenge01.Challenge01_PiotrSlomski; begin RunTest(cpPiotrSlomski); end; procedure TDelphiChallenge01.Challenge01_WaldekGorajek; begin RunTest(cpWaldekGorajek); end; procedure TDelphiChallenge01.Challenge01_Ongakw; begin RunTest(cpOngakw); end; initialization TDUnitX.RegisterTestFixture(TDelphiChallenge01); end.
unit uStrRepHelper; {$I ..\Include\IntXLib.inc} interface uses {$IFDEF DELPHI} Generics.Collections, {$ENDIF DELPHI} SysUtils, uStrings, uUtils, uIntX, uIntXLibTypes; type /// <summary> /// Helps to work with <see cref="TIntX" /> string representations. /// </summary> TStrRepHelper = class sealed(TObject) private const NullString = String(''); public /// <summary> /// Returns char array for given string. /// </summary> /// <param name="InString">input string.</param> class function ToCharArray(const InString: String): TIntXLibCharArray; inline; static; /// <summary> /// Returns digit for given char. /// </summary> /// <param name="charToDigits">Char->digit dictionary.</param> /// <param name="ch">Char which represents big integer digit.</param> /// <param name="numberBase">String representation number base.</param> /// <returns>Digit.</returns> /// <exception cref="EFormatException"><paramref name="ch" /> is not in valid format.</exception> class function GetDigit(charToDigits: TDictionary<Char, UInt32>; ch: Char; numberBase: UInt32): UInt32; static; /// <summary> /// Verfies string alphabet provider by user for validity. /// </summary> /// <param name="alphabet">Alphabet.</param> /// <param name="numberBase">String representation number base.</param> class procedure AssertAlphabet(const alphabet: String; numberBase: UInt32); static; /// <summary> /// Generates char->digit dictionary from alphabet. /// </summary> /// <param name="alphabet">Alphabet.</param> /// <param name="numberBase">String representation number base.</param> /// <returns>Char->digit dictionary.</returns> class function CharDictionaryFromAlphabet(const alphabet: String; numberBase: UInt32): TDictionary<Char, UInt32>; static; end; implementation class function TStrRepHelper.ToCharArray(const InString: String) : TIntXLibCharArray; begin SetLength(result, Length(InString)); // Move the string contents to a char array Move((PChar(InString))^, result[0], Length(InString) * SizeOf(Char)); end; class function TStrRepHelper.GetDigit(charToDigits: TDictionary<Char, UInt32>; ch: Char; numberBase: UInt32): UInt32; var digit: UInt32; begin digit := 0; if (charToDigits = Nil) then begin raise EArgumentNilException.Create('charToDigits'); end; // Try to identify this digit {$IFDEF DELPHI} if (not charToDigits.TryGetValue(ch, digit)) then {$ENDIF DELPHI} {$IFDEF FPC} if (not charToDigits.Find(UpCase(ch), Integer(digit))) then {$ENDIF FPC} begin raise EFormatException.Create(uStrings.ParseInvalidChar); end; if (digit >= numberBase) then begin raise EFormatException.Create(uStrings.ParseTooBigDigit); end; result := digit; end; class procedure TStrRepHelper.AssertAlphabet(const alphabet: String; numberBase: UInt32); var sortedChars: TIntXLibCharArray; i: Integer; begin if (alphabet = NullString) then begin raise EArgumentNilException.Create('alphabet'); end; // Ensure that alphabet has enough characters to represent numbers in given base if (UInt32(Length(alphabet)) < numberBase) then begin raise EArgumentException.Create(Format(uStrings.AlphabetTooSmall, [numberBase], TIntX._FS) + ' alphabet'); end; // Ensure that all the characters in alphabet are unique sortedChars := ToCharArray(alphabet); TUtils.QuickSort(sortedChars, Low(sortedChars), High(sortedChars)); i := 0; while i < (Length(sortedChars)) do begin if ((i > 0) and (sortedChars[i] = sortedChars[i - 1])) then begin raise EArgumentException.Create(uStrings.AlphabetRepeatingChars + ' alphabet'); end; Inc(i); end; end; class function TStrRepHelper.CharDictionaryFromAlphabet(const alphabet: String; numberBase: UInt32): TDictionary<Char, UInt32>; var i: Integer; LCharDigits: TDictionary<Char, UInt32>; begin AssertAlphabet(alphabet, numberBase); {$IFDEF DELPHI} LCharDigits := TDictionary<Char, UInt32>.Create(Integer(numberBase)); {$ENDIF DELPHI} {$IFDEF FPC} LCharDigits := TDictionary<Char, UInt32>.Create(); LCharDigits.Capacity := Integer(numberBase); {$ENDIF FPC} i := 0; while UInt32(i) < numberBase do begin LCharDigits.Add(alphabet[i + 1], UInt32(i)); Inc(i); end; result := LCharDigits; end; end.
unit TOConfiguration; {$mode objfpc}{$H+} interface uses Classes, SysUtils, constants, inifiles, strutils; Type TSwampNode = record address: String; port: Integer; connectionId: Integer; end; Type TConfiguration = class var nodeSleepTime: Integer; NodeId: String; starSwampNodes: array of TswampNode; //node config bindAddress: String; bindPort: Integer; Class Constructor create; Class Destructor destroy; procedure initDataDirectory(dataDir: String); end; implementation procedure TConfiguration.initDataDirectory(dataDir: String); var ini: TINIFile; swampCount, swampPort, i, tmpI : Integer; tempNode,swampHost: String; begin self.nodeSleepTime := 10; if not DirectoryExists(dataDir) then begin writeln ('Creating data directory...'); if not ForceDirectories(dataDir) then begin writeln('Can''t create the Data directory: ' + dataDir +'.'); exit; end; end; ini := TINIFile.Create(dataDir + '/' + iniFile); self.NodeId:= ini.ReadString(INI_General,'NodeID','ONODE_'+timetostr(now)); self.bindAddress:= ini.ReadString(INI_Network,'BindAddress',BIND_Default_Address); self.bindPort:= ini.ReadInteger(INI_Network,'BindPort',BIND_Default_Port); writeln('I am '+ self.NodeId); swampCount := ini.ReadInteger(INI_SWAMP,'NodeCount',0); SetLength(self.starSwampNodes,swampCount); for i:=1 to swampCount do begin tempNode := ini.ReadString(INI_SWAMP,'NODE_'+inttostr(i),'0.0.0.0:0'); writeln('Reading starting swamp node '+inttostr(i)+': ' + tempNode); tmpI := pos(':',tempNode); swampHost := LeftStr(tempNode, tmpI-1); swampPort:= strtoint(RightStr(tempNode, Length(tempNode) - tmpI)); writeln('New swamp node: ' + swampHost + ':'+inttostr(swampPort) ); self.starSwampNodes[i-1].address:=swampHost; self.starSwampNodes[i-1].port:=swampPort; end; writeln('CNT SWAMP: ' + inttostr(Length(self.starSwampNodes) )); end; Class Constructor TConfiguration.Create; begin end; Class Destructor TConfiguration.Destroy; begin end; begin end.
{*******************************************************} { } { Delphi VCL Extensions (RX) } { } { Copyright (c) 1995, 1996 AO ROSNO } { Copyright (c) 1997, 1998 Master-Bank } { } {*******************************************************} unit rxBdeUtils; {$I RX.INC} {$W-,R-,B-,N+,P+} interface uses SysUtils, Windows, Bde, Registry, RTLConsts, Classes, DB, DBTables, IniFiles, rxDBUtils; type {$IFNDEF RX_D3} TBDEDataSet = TDataSet; {$ENDIF} {$IFNDEF RX_D5} TDatabaseLoginEvent = TLoginEvent; {$ENDIF} TDBLocate = class(TLocateObject) private function LocateCallback: Boolean; procedure RecordFilter(DataSet: TDataSet; var Accept: Boolean); protected function LocateFilter: Boolean; override; procedure CheckFieldType(Field: TField); override; function LocateKey: Boolean; override; function UseKey: Boolean; override; function FilterApplicable: Boolean; override; public destructor Destroy; override; end; { TCloneDataset } TCloneDataset = class(TBDEDataSet) private FSourceHandle: HDBICur; FReadOnly: Boolean; procedure SetReadOnly(Value: Boolean); procedure SetSourceHandle(ASourceHandle: HDBICur); protected function CreateHandle: HDBICur; override; public property SourceHandle: HDBICur read FSourceHandle write SetSourceHandle; published property ReadOnly: Boolean read FReadOnly write SetReadOnly default False; end; { TCloneDbDataset } TCloneDbDataset = class(TDBDataSet) private FSourceHandle: HDBICur; FReadOnly: Boolean; procedure SetReadOnly(Value: Boolean); procedure SetSourceHandle(ASourceHandle: HDBICur); protected function CreateHandle: HDBICur; override; public procedure InitFromDataSet(Source: TDBDataSet; Reset: Boolean); property SourceHandle: HDBICur read FSourceHandle write SetSourceHandle; published property ReadOnly: Boolean read FReadOnly write SetReadOnly default False; end; { TCloneTable } TCloneTable = class(TTable) private FSourceHandle: HDBICur; FReadOnly: Boolean; procedure SetReadOnly(Value: Boolean); procedure SetSourceHandle(ASourceHandle: HDBICur); protected function CreateHandle: HDBICur; override; public procedure InitFromTable(SourceTable: TTable; Reset: Boolean); published property ReadOnly: Boolean read FReadOnly write SetReadOnly default False; end; { Utility routines } function CreateDbLocate: TLocateObject; procedure FetchAllRecords(DataSet: TBDEDataSet); function TransActive(Database: TDatabase): Boolean; function AsyncQrySupported(Database: TDatabase): Boolean; function GetQuoteChar(Database: TDatabase): string; procedure ExecuteQuery(const DbName, QueryText: string); procedure ExecuteQueryEx(const SessName, DbName, QueryText: string); procedure BdeTranslate(Locale: TLocale; Source, Dest: PChar; ToOem: Boolean); function FieldLogicMap(FldType: TFieldType): Integer; function FieldSubtypeMap(FldType: TFieldType): Integer; procedure ConvertStringToLogicType(Locale: TLocale; FldLogicType: Integer; FldSize: Word; const FldName, Value: string; Buffer: Pointer); function GetAliasPath(const AliasName: string): string; function IsDirectory(const DatabaseName: string): Boolean; function GetBdeDirectory: string; function BdeErrorMsg(ErrorCode: DBIResult): string; function LoginToDatabase(Database: TDatabase; OnLogin: TDatabaseLoginEvent): Boolean; function DataSetFindValue(ADataSet: TBDEDataSet; const Value, FieldName: string): Boolean; function DataSetFindLike(ADataSet: TBDEDataSet; const Value, FieldName: string): Boolean; function DataSetRecNo(DataSet: TDataSet): Longint; function DataSetRecordCount(DataSet: TDataSet): Longint; function DataSetPositionStr(DataSet: TDataSet): string; procedure DataSetShowDeleted(DataSet: TBDEDataSet; Show: Boolean); function CurrentRecordDeleted(DataSet: TBDEDataSet): Boolean; function IsFilterApplicable(DataSet: TDataSet): Boolean; function IsBookmarkStable(DataSet: TBDEDataSet): Boolean; function BookmarksCompare(DataSet: TBDEDataSet; Bookmark1, Bookmark2: TBookmark): Integer; function SetToBookmark(ADataSet: TDataSet; ABookmark: TBookmark): Boolean; procedure SetIndex(Table: TTable; const IndexFieldNames: string); procedure RestoreIndex(Table: TTable); procedure DeleteRange(Table: TTable; IndexFields: array of const; FieldValues: array of const); procedure PackTable(Table: TTable); procedure ReindexTable(Table: TTable); procedure BdeFlushBuffers; function GetNativeHandle(Database: TDatabase; Buffer: Pointer; BufSize: Integer): Pointer; procedure ToggleDebugLayer(Active: Boolean; const DebugFile: string); procedure DbNotSupported; { Export/import DataSet routines } procedure ExportDataSet(Source: TBDEDataSet; DestTable: TTable; TableType: TTableType; const AsciiCharSet: string; AsciiDelimited: Boolean; MaxRecordCount: Longint); procedure ExportDataSetEx(Source: TBDEDataSet; DestTable: TTable; TableType: TTableType; const AsciiCharSet: string; AsciiDelimited: Boolean; AsciiDelimiter, AsciiSeparator: Char; MaxRecordCount: Longint); procedure ImportDataSet(Source: TBDEDataSet; DestTable: TTable; MaxRecordCount: Longint; Mappings: TStrings; Mode: TBatchMode); { ReportSmith initialization } procedure InitRSRUN(Database: TDatabase; const ConName: string; ConType: Integer; const ConServer: string); implementation uses Forms, Controls, Dialogs, Consts, DBConsts, RXDConst, rxVCLUtils, rxFileUtil, rxAppUtils, rxStrUtils, rxMaxMin, {$IFDEF RX_D3} BDEConst, DBCommon, {$ENDIF} rxDateUtil; { Utility routines } {$IFDEF RX_D5} procedure DBError(Ident: Word); begin DatabaseError(LoadStr(Ident)); end; {$ENDIF} function IsBookmarkStable(DataSet: TBDEDataSet): Boolean; var Props: CURProps; begin with DataSet do Result := Active and (DbiGetCursorProps(Handle, Props) = DBIERR_NONE) and Props.bBookMarkStable; end; function SetToBookmark(ADataSet: TDataSet; ABookmark: TBookmark): Boolean; begin Result := False; {$IFDEF RX_D3} with ADataSet do if Active and (ABookmark <> nil) and not (Bof and Eof) and BookmarkValid(ABookmark) then try ADataSet.GotoBookmark(ABookmark); Result := True; except end; {$ELSE} with TBDEDataSet(ADataSet) do if Active and (ABookmark <> nil) and not (Bof and Eof) then if DbiSetToBookmark(Handle, ABookmark) = DBIERR_NONE then try Resync([rmExact, rmCenter]); Result := True; except end; {$ENDIF} end; function BookmarksCompare(DataSet: TBDEDataSet; Bookmark1, Bookmark2: TBookmark): Integer; const RetCodes: array[Boolean, Boolean] of ShortInt = ((2, CMPLess), (CMPGtr, CMPEql)); begin Result := RetCodes[Bookmark1 = nil, Bookmark2 = nil]; if Result = 2 then begin Check(DbiCompareBookmarks(DataSet.Handle, Bookmark1, Bookmark2, Result)); if Result = CMPKeyEql then Result := CMPEql; end; end; function DBGetIntProp(const Handle: Pointer; PropName: Longint): Longint; var Length: Word; Value: Longint; begin Value := 0; Check(DbiGetProp(HDBIObj(Handle), PropName, @Value, SizeOf(Value), Length)); Result := Value; end; function GetQuoteChar(Database: TDatabase): string; {$IFNDEF RX_D3} const dbQUOTECHAR = $0404000A; {$ENDIF} var Q: Char; Len: Word; begin Result := ''; if Database.IsSQLBased then begin Q := #0; DbiGetProp(HDBIObj(Database.Handle), dbQUOTECHAR, @Q, SizeOf(Q), Len); if Q <> #0 then Result := Q; end else Result := '"'; end; function AsyncQrySupported(Database: TDatabase): Boolean; begin Result := False; if Database.Connected then if Database.IsSQLBased then try Result := BOOL(DBGetIntProp(Database.Handle, dbASYNCSUPPORT)); except end else Result := True; end; function FieldLogicMap(FldType: TFieldType): Integer; {$IFNDEF RX_D3} {$IFDEF VER80} const FldTypeMap: array[TFieldType] of Integer = ( fldUNKNOWN, fldZSTRING, fldINT16, fldINT32, fldUINT16, fldBOOL, fldFLOAT, fldFLOAT, fldBCD, fldDATE, fldTIME, fldTIMESTAMP, fldBYTES, fldVARBYTES, fldBLOB, fldBLOB, fldBLOB); {$ELSE} const FldTypeMap: array[TFieldType] of Integer = ( fldUNKNOWN, fldZSTRING, fldINT16, fldINT32, fldUINT16, fldBOOL, fldFLOAT, fldFLOAT, fldBCD, fldDATE, fldTIME, fldTIMESTAMP, fldBYTES, fldVARBYTES, fldINT32, fldBLOB, fldBLOB, fldBLOB, fldBLOB, fldBLOB, fldBLOB, fldBLOB); {$ENDIF} {$ENDIF} begin Result := FldTypeMap[FldType]; end; function FieldSubtypeMap(FldType: TFieldType): Integer; {$IFNDEF RX_D3} {$IFDEF VER80} const FldSubtypeMap: array[TFieldType] of Integer = ( 0, 0, 0, 0, 0, 0, 0, fldstMONEY, 0, 0, 0, 0, 0, 0, fldstBINARY, fldstMEMO, fldstGRAPHIC); {$ELSE} const FldSubtypeMap: array[TFieldType] of Integer = ( 0, 0, 0, 0, 0, 0, 0, fldstMONEY, 0, 0, 0, 0, 0, 0, fldstAUTOINC, fldstBINARY, fldstMEMO, fldstGRAPHIC, fldstFMTMEMO, fldstOLEOBJ, fldstDBSOLEOBJ, fldstTYPEDBINARY); {$ENDIF} {$ENDIF} begin Result := FldSubtypeMap[FldType]; end; { Routine for convert string to IDAPI logical field type } procedure ConvertStringToLogicType(Locale: TLocale; FldLogicType: Integer; FldSize: Word; const FldName, Value: string; Buffer: Pointer); var Allocate: Boolean; BCD: FMTBcd; E: Integer; L: Longint; B: WordBool; DateTime: TDateTime; DtData: TDateTime; D: Double absolute DtData; Data: Longint absolute DtData; TimeStamp: TTimeStamp; begin if Buffer = nil then begin Buffer := AllocMem(FldSize); Allocate := Buffer <> nil; end else Allocate := False; try case FldLogicType of fldZSTRING: begin AnsiToNative(Locale, Value, PChar(Buffer), FldSize); end; fldBYTES, fldVARBYTES: begin Move(Value[1], Buffer^, Min(Length(Value), FldSize)); end; fldINT16, fldINT32, fldUINT16: begin if Value = '' then FillChar(Buffer^, FldSize, 0) else begin Val(Value, L, E); if E <> 0 then {$IFDEF RX_D3} DatabaseErrorFmt(SInvalidIntegerValue, [Value, FldName]); {$ELSE} DBErrorFmt(SInvalidIntegerValue, [Value, FldName]); {$ENDIF} Move(L, Buffer^, FldSize); end; end; fldBOOL: begin L := Length(Value); if L = 0 then B := False else begin if Value[1] in ['Y', 'y', 'T', 't', '1'] then B := True else B := False; end; Move(B, Buffer^, SizeOf(WordBool)); end; fldFLOAT, fldBCD: begin if Value = '' then FillChar(Buffer^, FldSize, 0) else begin D := StrToFloat(Value); if FldLogicType <> fldBCD then Move(D, Buffer^, SizeOf(Double)) else begin DbiBcdFromFloat(D, 32, FldSize, BCD); Move(BCD, Buffer^, SizeOf(BCD)); end; end; end; fldDATE, fldTIME, fldTIMESTAMP: begin if Value = '' then Data := Trunc(NullDate) else begin case FldLogicType of fldDATE: begin DateTime := StrToDate(Value); TimeStamp := DateTimeToTimeStamp(DateTime); Data := TimeStamp.Date; end; fldTIME: begin DateTime := StrToTime(Value); TimeStamp := DateTimeToTimeStamp(DateTime); Data := TimeStamp.Time; end; fldTIMESTAMP: begin DateTime := StrToDateTime(Value); TimeStamp := DateTimeToTimeStamp(DateTime); D := TimeStampToMSecs(DateTimeToTimeStamp(DateTime)); end; end; end; Move(D, Buffer^, FldSize); end; else DbiError(DBIERR_INVALIDFLDTYPE); end; finally if Allocate then FreeMem(Buffer, FldSize); end; end; { Execute Query routine } procedure ExecuteQueryEx(const SessName, DbName, QueryText: string); begin with TQuery.Create(Application) do try DatabaseName := DbName; SessionName := SessName; SQL.Add(QueryText); ExecSQL; finally Free; end; end; procedure ExecuteQuery(const DbName, QueryText: string); begin ExecuteQueryEx('', DbName, QueryText); end; { Database Login routine } function LoginToDatabase(Database: TDatabase; OnLogin: TDatabaseLoginEvent): Boolean; var EndLogin: Boolean; begin Result := Database.Connected; if Result then Exit; Database.OnLogin := OnLogin; EndLogin := True; repeat try Database.Connected := True; EndLogin := True; except on E: EDbEngineError do begin EndLogin := (MessageDlg(E.Message + '. ' + LoadStr(SRetryLogin), mtConfirmation, [mbYes, mbNo], 0) <> mrYes); end; on E: EDatabaseError do begin { User select "Cancel" in login dialog } MessageDlg(E.Message, mtError, [mbOk], 0); end; else raise; end; until EndLogin; Result := Database.Connected; end; { ReportSmith runtime initialization routine } procedure InitRSRUN(Database: TDatabase; const ConName: string; ConType: Integer; const ConServer: string); const IniFileName = 'RPTSMITH.CON'; scConNames = 'ConnectNamesSection'; idConNames = 'ConnectNames'; idType = 'Type'; idServer = 'Server'; idSQLDataFilePath = 'Database'; idDataFilePath = 'DataFilePath'; idSQLUserID = 'USERID'; var ParamList: TStringList; DBPath: string[127]; TempStr, AppConName: string[127]; UserName: string[30]; ExeName: string[12]; IniFile: TIniFile; begin ParamList := TStringList.Create; try Database.Session.GetAliasParams(Database.AliasName, ParamList); if Database.IsSQLBased then DBPath := ParamList.Values['SERVER NAME'] else DBPath := ParamList.Values['PATH']; UserName := ParamList.Values['USER NAME']; finally ParamList.Free; end; AppConName := ConName; if AppConName = '' then begin ExeName := ExtractFileName(Application.ExeName); AppConName := Copy(ExeName, 1, Pos('.', ExeName) - 1); end; IniFile := TIniFile.Create(IniFileName); try TempStr := IniFile.ReadString(scConNames, idConNames, ''); if Pos(AppConName, TempStr) = 0 then begin if TempStr <> '' then TempStr := TempStr + ','; IniFile.WriteString(scConNames, idConNames, TempStr + AppConName); end; IniFile.WriteInteger(AppConName, idType, ConType); IniFile.WriteString(AppConName, idServer, ConServer); if Database.IsSQLBased then begin IniFile.WriteString(AppConName, idSQLDataFilePath, DBPath); IniFile.WriteString(AppConName, idSQLUserID, UserName); end else IniFile.WriteString(AppConName, idDataFilePath, DBPath); finally IniFile.Free; end; end; { BDE aliases routines } function IsDirectory(const DatabaseName: string): Boolean; var I: Integer; begin Result := True; if (DatabaseName = '') then Exit; I := 1; while I <= Length(DatabaseName) do begin {$IFDEF RX_D3} if DatabaseName[I] in LeadBytes then Inc(I) else {$ENDIF RX_D3} if DatabaseName[I] in [':','\'] then Exit; Inc(I); end; Result := False; end; function GetAliasPath(const AliasName: string): string; var SAlias: DBINAME; Desc: DBDesc; Params: TStrings; begin Result := ''; StrPLCopy(SAlias, AliasName, SizeOf(SAlias) - 1); AnsiToOem(SAlias, SAlias); Check(DbiGetDatabaseDesc(SAlias, @Desc)); if StrIComp(Desc.szDbType, szCFGDBSTANDARD) = 0 then begin OemToAnsi(Desc.szPhyName, Desc.szPhyName); Result := StrPas(Desc.szPhyName); end else begin Params := TStringList.Create; try Session.Active := True; Session.GetAliasParams(AliasName, Params); Result := Params.Values['SERVER NAME']; finally Params.Free; end; end; end; { TCloneDataset } procedure TCloneDataset.SetSourceHandle(ASourceHandle: HDBICur); begin if ASourceHandle <> FSourceHandle then begin Close; FSourceHandle := ASourceHandle; if FSourceHandle <> nil then Open; end; end; function TCloneDataset.CreateHandle: HDBICur; begin Check(DbiCloneCursor(FSourceHandle, FReadOnly, False, Result)); end; procedure TCloneDataset.SetReadOnly(Value: Boolean); begin CheckInactive; FReadOnly := Value; end; { TCloneDbDataset } procedure TCloneDbDataset.InitFromDataSet(Source: TDBDataSet; Reset: Boolean); begin with Source do begin Self.SessionName := SessionName; Self.DatabaseName := DatabaseName; SetSourceHandle(Handle); Self.Filter := Filter; Self.OnFilterRecord := OnFilterRecord; if not Reset then Self.Filtered := Filtered; end; if Reset then begin Filtered := False; First; end; end; procedure TCloneDbDataset.SetSourceHandle(ASourceHandle: HDBICur); begin if ASourceHandle <> FSourceHandle then begin Close; FSourceHandle := ASourceHandle; if FSourceHandle <> nil then Open; end; end; function TCloneDbDataset.CreateHandle: HDBICur; begin Check(DbiCloneCursor(FSourceHandle, FReadOnly, False, Result)); end; procedure TCloneDbDataset.SetReadOnly(Value: Boolean); begin CheckInactive; FReadOnly := Value; end; { TCloneTable } procedure TCloneTable.InitFromTable(SourceTable: TTable; Reset: Boolean); begin with SourceTable do begin Self.TableType := TableType; Self.TableName := TableName; Self.SessionName := SessionName; Self.DatabaseName := DatabaseName; if not Reset then begin if IndexName <> '' then Self.IndexName := IndexName else if IndexFieldNames <> '' then Self.IndexFieldNames := IndexFieldNames; end; SetSourceHandle(Handle); Self.Filter := Filter; Self.OnFilterRecord := OnFilterRecord; if not Reset then Self.Filtered := Filtered; end; if Reset then begin Filtered := False; DbiResetRange(Handle); IndexName := ''; IndexFieldNames := ''; First; end; end; procedure TCloneTable.SetSourceHandle(ASourceHandle: HDBICur); begin if ASourceHandle <> FSourceHandle then begin Close; FSourceHandle := ASourceHandle; if FSourceHandle <> nil then Open; end; end; procedure TCloneTable.SetReadOnly(Value: Boolean); begin CheckInactive; FReadOnly := Value; end; function TCloneTable.CreateHandle: HDBICur; begin Check(DbiCloneCursor(FSourceHandle, FReadOnly, False, Result)); end; { TDBLocate } function CreateDbLocate: TLocateObject; begin Result := TDBLocate.Create; end; destructor TDBLocate.Destroy; begin inherited Destroy; end; procedure TDBLocate.CheckFieldType(Field: TField); var Locale: TLocale; begin if not (Field.DataType in [ftDate, ftTime, ftDateTime]) then begin if DataSet is TBDEDataSet then Locale := TBDEDataSet(DataSet).Locale else Locale := Session.Locale; ConvertStringToLogicType(Locale, FieldLogicMap(Field.DataType), Field.DataSize, Field.FieldName, LookupValue, nil); end; end; function TDBLocate.UseKey: Boolean; var I: Integer; begin Result := False; if DataSet is TTable then with DataSet as TTable do begin if (not Self.LookupField.IsIndexField) and (not IndexSwitch or (not CaseSensitive and Database.IsSQLBased)) then Exit; if (not LookupExact) and (Self.LookupField.DataType <> ftString) then Exit; IndexDefs.Update; for I := 0 to IndexDefs.Count - 1 do with IndexDefs[I] do if not (ixExpression in Options) and ((ixCaseInsensitive in Options) or CaseSensitive) then if AnsiCompareText(Fields, Self.LookupField.FieldName) = 0 then begin Result := True; Exit; end; end; end; function TDBLocate.LocateKey: Boolean; var Clone: TCloneTable; function LocateIndex(Table: TTable): Boolean; begin with Table do begin SetKey; FieldByName(Self.LookupField.FieldName).AsString := LookupValue; if LookupExact then Result := GotoKey else begin GotoNearest; Result := MatchesLookup(FieldByName(Self.LookupField.FieldName)); end; end; end; begin try TTable(DataSet).CheckBrowseMode; if TTable(DataSet).IndexFieldNames = LookupField.FieldName then Result := LocateIndex(TTable(DataSet)) else begin Clone := TCloneTable.Create(DataSet); with Clone do try ReadOnly := True; InitFromTable(TTable(DataSet), True); IndexFieldNames := Self.LookupField.FieldName; Result := LocateIndex(Clone); if Result then begin Check(DbiSetToCursor(TTable(DataSet).Handle, Handle)); DataSet.Resync([rmExact, rmCenter]); end; finally Free; end; end; except Result := False; end; end; function TDBLocate.FilterApplicable: Boolean; begin Result := IsFilterApplicable(DataSet); end; function TDBLocate.LocateCallback: Boolean; var Clone: TCloneDbDataset; begin Result := False; try TBDEDataSet(DataSet).CheckBrowseMode; Clone := TCloneDbDataset.Create(DataSet); with Clone do try ReadOnly := True; InitFromDataset(TDBDataSet(DataSet), True); OnFilterRecord := RecordFilter; Filtered := True; if not (BOF and EOF) then begin First; Result := True; end; if Result then begin Check(DbiSetToCursor(TBDEDataSet(DataSet).Handle, Handle)); DataSet.Resync([rmExact, rmCenter]); end; finally Free; end; except Result := False; end; end; procedure TDBLocate.RecordFilter(DataSet: TDataSet; var Accept: Boolean); begin Accept := MatchesLookup(DataSet.FieldByName(LookupField.FieldName)); end; function TDBLocate.LocateFilter: Boolean; var SaveCursor: TCursor; begin if LookupExact or (LookupField.DataType = ftString) or not (DataSet is TDBDataSet) then Result := inherited LocateFilter else begin SaveCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try Result := LocateCallback; finally Screen.Cursor := SaveCursor; end; end; end; { DataSet locate routines } function IsFilterApplicable(DataSet: TDataSet): Boolean; var Status: DBIResult; Filter: hDBIFilter; begin if DataSet is TBDEDataSet then begin Status := DbiAddFilter(TBDEDataSet(DataSet).Handle, 0, 0, False, nil, nil, Filter); Result := (Status = DBIERR_NONE) or (Status = DBIERR_INVALIDFILTER); if Result then DbiDropFilter(TBDEDataSet(DataSet).Handle, Filter); end else Result := True; end; function DataSetFindValue(ADataSet: TBDEDataSet; const Value, FieldName: string): Boolean; begin with TDBLocate.Create do try DataSet := ADataSet; if ADataSet is TDBDataSet then IndexSwitch := not TDBDataSet(DataSet).Database.IsSQLBased; Result := Locate(FieldName, Value, True, False); finally Free; end; end; function DataSetFindLike(ADataSet: TBDEDataSet; const Value, FieldName: string): Boolean; begin with TDBLocate.Create do try DataSet := ADataSet; if ADataSet is TDBDataSet then IndexSwitch := not TDBDataSet(DataSet).Database.IsSQLBased; Result := Locate(FieldName, Value, False, False); finally Free; end; end; const SaveIndexFieldNames: TStrings = nil; procedure UsesSaveIndexies; begin if SaveIndexFieldNames = nil then SaveIndexFieldNames := TStringList.Create; end; procedure ReleaseSaveIndexies; far; begin if SaveIndexFieldNames <> nil then begin SaveIndexFieldNames.Free; SaveIndexFieldNames := nil; end; end; procedure SetIndex(Table: TTable; const IndexFieldNames: string); var IndexToSave: string; begin IndexToSave := Table.IndexFieldNames; Table.IndexFieldNames := IndexFieldNames; UsesSaveIndexies; SaveIndexFieldNames.AddObject(IndexToSave, Table.MasterSource); end; procedure RestoreIndex(Table: TTable); begin if (SaveIndexFieldNames <> nil) and (SaveIndexFieldNames.Count > 0) then begin try Table.IndexFieldNames := SaveIndexFieldNames[SaveIndexFieldNames.Count - 1]; Table.MasterSource := TDataSource(SaveIndexFieldNames.Objects[SaveIndexFieldNames.Count - 1]); finally SaveIndexFieldNames.Delete(SaveIndexFieldNames.Count - 1); if SaveIndexFieldNames.Count = 0 then ReleaseSaveIndexies; end; end; end; procedure DeleteRange(Table: TTable; IndexFields: array of const; FieldValues: array of const); var I: Integer; NewIndex: string; begin NewIndex := ''; for I := Low(IndexFields) to High(IndexFields) do begin NewIndex := NewIndex + TVarRec(IndexFields[I]).VString^; if I <> High(IndexFields) then NewIndex := NewIndex + ';'; end; SetIndex(Table, NewIndex); try Table.SetRange(FieldValues, FieldValues); try while not Table.EOF do Table.Delete; finally Table.CancelRange; end; finally RestoreIndex(Table); end; end; procedure ReindexTable(Table: TTable); var WasActive: Boolean; WasExclusive: Boolean; begin with Table do begin WasActive := Active; WasExclusive := Exclusive; DisableControls; try if not (WasActive and WasExclusive) then Close; try Exclusive := True; Open; Check(dbiRegenIndexes(Handle)); finally if not (WasActive and WasExclusive) then begin Close; Exclusive := WasExclusive; Active := WasActive; end; end; finally EnableControls; end; end; end; procedure PackTable(Table: TTable); { This routine copied and modified from demo unit TableEnh.pas from Borland Int. } var { FCurProp holds information about the structure of the table } FCurProp: CurProps; { Specific information about the table structure, indexes, etc. } TblDesc: CRTblDesc; { Uses as a handle to the database } hDb: hDbiDB; { Path to the currently opened table } TablePath: array[0..dbiMaxPathLen] of Char; Exclusive: Boolean; begin if not Table.Active then _DBError(SDataSetClosed); Check(DbiGetCursorProps(Table.Handle, FCurProp)); if StrComp(FCurProp.szTableType, szParadox) = 0 then begin { Call DbiDoRestructure procedure if PARADOX table } hDb := nil; { Initialize the table descriptor } FillChar(TblDesc, SizeOf(CRTblDesc), 0); with TblDesc do begin { Place the table name in descriptor } StrPCopy(szTblName, Table.TableName); { Place the table type in descriptor } StrCopy(szTblType, FCurProp.szTableType); bPack := True; bProtected := FCurProp.bProtected; end; { Get the current table's directory. This is why the table MUST be opened until now } Check(DbiGetDirectory(Table.DBHandle, False, TablePath)); { Close the table } Table.Close; try { NOW: since the DbiDoRestructure call needs a valid DB handle BUT the table cannot be opened, call DbiOpenDatabase to get a valid handle. Setting TTable.Active = False does not give you a valid handle } Check(DbiOpenDatabase(nil, szCFGDBSTANDARD, dbiReadWrite, dbiOpenExcl, nil, 0, nil, nil, hDb)); { Set the table's directory to the old directory } Check(DbiSetDirectory(hDb, TablePath)); { Pack the PARADOX table } Check(DbiDoRestructure(hDb, 1, @TblDesc, nil, nil, nil, False)); { Close the temporary database handle } Check(DbiCloseDatabase(hDb)); finally { Re-Open the table } Table.Open; end; end else if StrComp(FCurProp.szTableType, szDBase) = 0 then begin { Call DbiPackTable procedure if dBase table } Exclusive := Table.Exclusive; Table.Close; try Table.Exclusive := True; Table.Open; try Check(DbiPackTable(Table.DBHandle, Table.Handle, nil, nil, True)); finally Table.Close; end; finally Table.Exclusive := Exclusive; Table.Open; end; end else DbiError(DBIERR_WRONGDRVTYPE); end; procedure FetchAllRecords(DataSet: TBDEDataSet); begin with DataSet do if not EOF then begin CheckBrowseMode; Check(DbiSetToEnd(Handle)); Check(DbiGetPriorRecord(Handle, dbiNoLock, nil, nil)); CursorPosChanged; UpdateCursorPos; end; end; procedure BdeFlushBuffers; var I, L: Integer; Session: TSession; J: Integer; begin for J := 0 to Sessions.Count - 1 do begin Session := Sessions[J]; if not Session.Active then Continue; for I := 0 to Session.DatabaseCount - 1 do begin with Session.Databases[I] do if Connected and not IsSQLBased then begin for L := 0 to DataSetCount - 1 do begin if DataSets[L].Active then DbiSaveChanges(DataSets[L].Handle); end; end; end; end; end; function DataSetRecordCount(DataSet: TDataSet): Longint; var IsCount: Boolean; begin {$IFDEF RX_D3} if DataSet is TBDEDataSet then begin {$ENDIF} IsCount := (DbiGetExactRecordCount(TBDEDataSet(DataSet).Handle, Result) = DBIERR_NONE) or (DbiGetRecordCount(TBDEDataSet(DataSet).Handle, Result) = DBIERR_NONE); {$IFDEF RX_D3} end else try Result := DataSet.RecordCount; IsCount := True; except IsCount := False; end; {$ENDIF} if not IsCount then Result := -1; end; function DataSetRecNo(DataSet: TDataSet): Longint; var FCurProp: CURProps; FRecProp: RECProps; begin Result := -1; if (DataSet <> nil) and DataSet.Active and (DataSet.State in [dsBrowse, dsEdit]) then begin {$IFDEF RX_D3} if not (DataSet is TBDEDataSet) then begin Result := DataSet.RecNo; Exit; end; {$ENDIF} if DbiGetCursorProps(TBDEDataSet(DataSet).Handle, FCurProp) <> DBIERR_NONE then Exit; if (StrComp(FCurProp.szTableType, szParadox) = 0) or (FCurProp.iSeqNums = 1) then begin DataSet.GetCurrentRecord(nil); if DbiGetSeqNo(TBDEDataSet(DataSet).Handle, Result) <> DBIERR_NONE then Result := -1; end else if StrComp(FCurProp.szTableType, szDBase) = 0 then begin DataSet.GetCurrentRecord(nil); if DbiGetRecord(TBDEDataSet(DataSet).Handle, dbiNOLOCK, nil, @FRecProp) = DBIERR_NONE then Result := FRecProp.iPhyRecNum; end; end; end; function DataSetPositionStr(DataSet: TDataSet): string; var RecNo, RecCount: Longint; begin try RecNo := DataSetRecNo(DataSet); except RecNo := -1; end; if RecNo >= 0 then begin RecCount := DataSetRecordCount(DataSet); if RecCount >= 0 then Result := Format('%d:%d', [RecNo, RecCount]) else Result := IntToStr(RecNo); end else Result := ''; end; function TransActive(Database: TDatabase): Boolean; var Info: XInfo; S: hDBISes; begin Result := False; if DbiGetCurrSession(S) <> DBIERR_NONE then Exit; Result := (Database.Handle <> nil) and (DbiGetTranInfo(Database.Handle, nil, @Info) = DBIERR_NONE) and (Info.exState = xsActive); DbiSetCurrSession(S); end; function GetBdeDirectory: string; const Ident = 'DLLPATH'; var Ini: TRegistry; const BdeKey = 'SOFTWARE\Borland\Database Engine'; begin Result := ''; Ini := TRegistry.Create; try Ini.RootKey := HKEY_LOCAL_MACHINE; if Ini.OpenKey(BdeKey, False) then if Ini.ValueExists(Ident) then Result := Ini.ReadString(Ident); { Check for multiple directories, use only the first one } if Pos(';', Result) > 0 then Delete(Result, Pos(';', Result), MaxInt); if (Length(Result) > 2) and (Result[Length(Result)] <> '\') then Result := Result + '\'; finally Ini.Free; end; end; procedure ExportDataSetEx(Source: TBDEDataSet; DestTable: TTable; TableType: TTableType; const AsciiCharSet: string; AsciiDelimited: Boolean; AsciiDelimiter, AsciiSeparator: Char; MaxRecordCount: Longint); function ExportAsciiField(Field: TField): Boolean; begin Result := Field.Visible and not (Field.Calculated or Field.Lookup) and not (Field.DataType in ftNonTextTypes + [ftUnknown]); end; const TextExt = '.TXT'; SchemaExt = '.SCH'; var I: Integer; S, Path: string; BatchMove: TBatchMove; TablePath: array[0..dbiMaxPathLen] of Char; begin if Source = nil then _DBError(SDataSetEmpty); if DestTable.Active then DestTable.Close; if Source is TDBDataSet then DestTable.SessionName := TDBDataSet(Source).SessionName; if (TableType = ttDefault) then begin if DestTable.TableType <> ttDefault then TableType := DestTable.TableType else if (CompareText(ExtractFileExt(DestTable.TableName), TextExt) = 0) then TableType := ttASCII; end; BatchMove := TBatchMove.Create(Application); try StartWait; try BatchMove.Mode := batCopy; BatchMove.Source := Source; BatchMove.Destination := DestTable; DestTable.TableType := TableType; BatchMove.Mappings.Clear; if (DestTable.TableType = ttASCII) then begin if CompareText(ExtractFileExt(DestTable.TableName), SchemaExt) = 0 then DestTable.TableName := ChangeFileExt(DestTable.TableName, TextExt); with Source do for I := 0 to FieldCount - 1 do begin if ExportAsciiField(Fields[I]) then BatchMove.Mappings.Add(Format('%s=%0:s', [Fields[I].FieldName])); end; BatchMove.RecordCount := 1; end else BatchMove.RecordCount := MaxRecordCount; BatchMove.Execute; if (DestTable.TableType = ttASCII) then begin { ASCII table always created in "fixed" format with "ascii" character set } with BatchMove do begin Mode := batAppend; RecordCount := MaxRecordCount; end; S := ChangeFileExt(ExtractFileName(DestTable.TableName), ''); Path := NormalDir(ExtractFilePath(DestTable.TableName)); if Path = '' then begin DestTable.Open; try Check(DbiGetDirectory(DestTable.DBHandle, False, TablePath)); Path := NormalDir(OemToAnsiStr(StrPas(TablePath))); finally DestTable.Close; end; end; with TIniFile.Create(ChangeFileExt(Path + S, SchemaExt)) do try if AsciiCharSet <> '' then WriteString(S, 'CharSet', AsciiCharSet) else WriteString(S, 'CharSet', 'ascii'); if AsciiDelimited then begin { change ASCII-file format to CSV } WriteString(S, 'Filetype', 'VARYING'); WriteString(S, 'Delimiter', AsciiDelimiter); WriteString(S, 'Separator', AsciiSeparator); end; finally Free; end; { clear previous output - overwrite existing file } S := Path + ExtractFileName(DestTable.TableName); if Length(ExtractFileExt(S)) < 2 then S := ChangeFileExt(S, TextExt); I := FileCreate(S); if I < 0 then raise EFCreateError.CreateFmt(ResStr(SFCreateError), [S]); FileClose(I); BatchMove.Execute; end; finally StopWait; end; finally BatchMove.Free; end; end; procedure ExportDataSet(Source: TBDEDataSet; DestTable: TTable; TableType: TTableType; const AsciiCharSet: string; AsciiDelimited: Boolean; MaxRecordCount: Longint); begin ExportDataSetEx(Source, DestTable, TableType, AsciiCharSet, AsciiDelimited, '"', ',', MaxRecordCount); end; procedure ImportDataSet(Source: TBDEDataSet; DestTable: TTable; MaxRecordCount: Longint; Mappings: TStrings; Mode: TBatchMode); var BatchMove: TBatchMove; begin if Source = nil then _DBError(SDataSetEmpty); if (Source is TDBDataSet) and not Source.Active then TDBDataSet(Source).SessionName := DestTable.SessionName; BatchMove := TBatchMove.Create(Application); try StartWait; try BatchMove.Mode := Mode; BatchMove.Source := Source; BatchMove.Destination := DestTable; if Mappings.Count > 0 then BatchMove.Mappings.AddStrings(Mappings); BatchMove.RecordCount := MaxRecordCount; BatchMove.Execute; finally StopWait; end; finally BatchMove.Free; end; end; function GetNativeHandle(Database: TDatabase; Buffer: Pointer; BufSize: Integer): Pointer; var Len: Word; begin Result := nil; if Assigned(Database) and Database.Connected then begin if Database.IsSQLBased then begin Check(DbiGetProp(HDBIOBJ(Database.Handle), dbNATIVEHNDL, Buffer, BufSize, Len)); Result := Buffer; end else DBError(SLocalDatabase); end else _DBError(SDatabaseClosed); end; procedure BdeTranslate(Locale: TLocale; Source, Dest: PChar; ToOem: Boolean); var Len: Cardinal; begin Len := StrLen(Source); if ToOem then AnsiToNativeBuf(Locale, Source, Dest, Len) else NativeToAnsiBuf(Locale, Source, Dest, Len); if Source <> Dest then Dest[Len] := #0; end; function TrimMessage(Msg: PChar): PChar; var Blank: Boolean; Source, Dest: PChar; begin Source := Msg; Dest := Msg; Blank := False; while Source^ <> #0 do begin if Source^ <= ' ' then Blank := True else begin if Blank then begin Dest^ := ' '; Inc(Dest); Blank := False; end; Dest^ := Source^; Inc(Dest); end; Inc(Source); end; if (Dest > Msg) and ((Dest - 1)^ = '.') then Dec(Dest); Dest^ := #0; Result := Msg; end; function BdeErrorMsg(ErrorCode: DBIResult): string; var I: Integer; NativeError: Longint; Msg, LastMsg: DBIMSG; begin I := 1; DbiGetErrorString(ErrorCode, Msg); TrimMessage(Msg); if Msg[0] = #0 then Result := Format(ResStr(SBDEError), [ErrorCode]) else Result := StrPas(Msg); while True do begin StrCopy(LastMsg, Msg); ErrorCode := DbiGetErrorEntry(I, NativeError, Msg); if (ErrorCode = DBIERR_NONE) or (ErrorCode = DBIERR_NOTINITIALIZED) then Break; TrimMessage(Msg); if (Msg[0] <> #0) and (StrComp(Msg, LastMsg) <> 0) then Result := Format('%s. %s', [Result, Msg]); Inc(I); end; for I := 1 to Length(Result) do if Result[I] < ' ' then Result[I] := ' '; end; procedure DataSetShowDeleted(DataSet: TBDEDataSet; Show: Boolean); begin with DataSet do begin CheckBrowseMode; Check(DbiValidateProp(hDBIObj(Handle), curSOFTDELETEON, True)); DisableControls; try Check(DbiSetProp(hDBIObj(Handle), curSOFTDELETEON, Ord(Show))); finally EnableControls; end; if DataSet is TTable then TTable(DataSet).Refresh else begin CursorPosChanged; First; end; end; end; function CurrentRecordDeleted(DataSet: TBDEDataSet): Boolean; var FRecProp: RECProps; begin Result := False; if (DataSet <> nil) and DataSet.Active then begin DataSet.GetCurrentRecord(nil); if DbiGetRecord(DataSet.Handle, dbiNOLOCK, nil, @FRecProp) = DBIERR_NONE then Result := FRecProp.bDeleteFlag; end; end; procedure DbNotSupported; begin DbiError(DBIERR_NOTSUPPORTED); end; procedure ToggleDebugLayer(Active: Boolean; const DebugFile: string); const Options: array[Boolean] of Longint = (0, DEBUGON or OUTPUTTOFILE or APPENDTOLOG); var FileName: DBIPATH; begin Check(DbiDebugLayerOptions(Options[Active], StrPLCopy(FileName, DebugFile, SizeOf(DBIPATH) - 1))); end; initialization rxDbUtils.CreateLocateObject := CreateDbLocate; finalization ReleaseSaveIndexies; end.
unit FC.Trade.Trader.MACross2; {$I Compiler.inc} interface uses Classes, Math,Graphics, Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions, StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators, Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage; type //Пока здесь объявлен. Потом как устоится, вынести в Definitions IStockTraderMACross2 = interface ['{93A29BEA-F909-4857-B1A5-98AC8A7F6BEC}'] end; INeedCloseAttribute = interface (ISCAttribute) ['{20CA817F-0818-4DED-8B96-9253568BDE75}'] procedure SetExpirationDateTime(const aDateTime:TDateTime); function GetExpirationDateTime: TDateTime; end; TStockTraderMACross2 = class (TStockTraderBase,IStockTraderMACross2) private FBarHeightD1 : ISCIndicatorBarHeight; FFastMA_H1,FSlowMA_H1: ISCIndicatorMA; //FLWMA21_H1,FLWMA55_H1: ISCIndicatorMA; //FMA84_H1,FMA220_H1: ISCIndicatorMA; FLastOpenOrderTime : TDateTime; FPropFullBarsOnly : TPropertyYesNo; protected function CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight; function CreateMA_H1(const aChart: IStockChart; aPeriod: integer; aMethod: TSCIndicatorMAMethod): ISCIndicatorMA; //Считает, на какой примерно цене сработает Stop Loss или Trailing Stop function GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber; //Считает, какой убыток будет, если закроется по StopLoss или Trailing Stop function GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber; procedure CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string); procedure CloseAllOrders(aKind: TSCOrderKind;const aComment: string); function GetRecommendedLots: TStockOrderLots; override; procedure SetTP(const aOrder: IStockOrder; const aTP: TStockRealNumber; const aComment: string); function GetMainTrend(index: integer): TSCRealNumber; function GetFastTrend(index: integer): TSCRealNumber; function GetCross(index: integer): integer; function PriceToPoint(const aPrice: TSCRealNumber): integer; function GetExpirationDateTime(aTime: TDateTime): TDateTime; procedure TrackOrderLevels(const aMALevel: TSCRealNumber); public procedure SetProject(const aValue : IStockProject); override; procedure OnBeginWorkSession; override; //Посчитать procedure UpdateStep2(const aTime: TDateTime); override; function OpenMASnappedOrder(aKind: TStockOrderKind;const aMALevel:TSCRealNumber; const aComment: string=''): IStockOrder; constructor Create; override; destructor Destroy; override; procedure Dispose; override; end; implementation uses DateUtils,Variants,Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message, StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory, FC.DataUtils; type TNeedCloseAttribute = class (TNameValuePersistentObjectRefCounted,INeedCloseAttribute,ISCAttribute) private FExpirationDateTime: TDateTime; public procedure SetExpirationDateTime(const aDateTime:TDateTime); function GetExpirationDateTime: TDateTime; end; { TStockTraderMACross2 } procedure TStockTraderMACross2.CloseAllOrders(aKind: TSCOrderKind;const aComment: string); var i: Integer; aOrders : IStockOrderCollection; aAttribute: INeedCloseAttribute; aExpTime: TDateTime; begin aOrders:=GetOrders; for i := aOrders.Count- 1 downto 0 do begin if (aOrders[i].GetKind=aKind) then begin if aOrders[i].GetState=osOpened then begin if aOrders[i].GetAttributes.IndexOf(INeedCloseAttribute)=-1 then begin aAttribute:=TNeedCloseAttribute.Create; aExpTime:=TStockDataUtils.AlignTimeToLeft(GetBroker.GetCurrentTime,sti60); aExpTime:=GetExpirationDateTime(aExpTime); aAttribute.SetExpirationDateTime(aExpTime); aOrders[i].GetAttributes.Add(aAttribute); end; //CloseOrder(aOrders[i],aComment) end else if aOrders[i].GetState=osPending then aOrders[i].RevokePending; end; end; end; procedure TStockTraderMACross2.CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string); var i: Integer; aOrders : IStockOrderCollection; begin aOrders:=GetOrders; for i := aOrders.Count- 1 downto 0 do begin if (aOrders[i].GetKind=aKind) and (aOrders[i].GetCurrentProfit>0) then CloseOrder(aOrders[i],aComment); end; end; constructor TStockTraderMACross2.Create; begin inherited Create; FPropFullBarsOnly := TPropertyYesNo.Create('Method','Full Bars Only',self); FPropFullBarsOnly.Value:=true; RegisterProperties([FPropFullBarsOnly]); //UnRegisterProperties([PropLotDefaultRateSize,PropLotDynamicRate]); end; function TStockTraderMACross2.CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight; var aCreated: boolean; begin result:=CreateOrFindIndicator(aChart,ISCIndicatorBarHeight,'BarHeightD1',true, aCreated) as ISCIndicatorBarHeight; //Ничего не нашли, создадим нового эксперта if aCreated then begin Result.SetPeriod(3); Result.SetBarHeight(bhHighLow); end; end; function TStockTraderMACross2.CreateMA_H1(const aChart: IStockChart;aPeriod: integer; aMethod: TSCIndicatorMAMethod): ISCIndicatorMA; var aCreated: boolean; begin result:=CreateOrFindIndicator(aChart,ISCIndicatorMA,'MA'+IntToStr(integer(aMethod))+'_'+IntToStr(aPeriod)+'_H1',true, aCreated) as ISCIndicatorMA; //Ничего не нашли, создадим нового эксперта if aCreated then begin Result.SetMAMethod(aMethod); Result.SetPeriod(aPeriod); end; end; destructor TStockTraderMACross2.Destroy; begin inherited; end; procedure TStockTraderMACross2.Dispose; begin inherited; end; function TStockTraderMACross2.GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber; begin result:=aOrder.GetStopLoss; if aOrder.GetState=osOpened then if aOrder.GetKind=okBuy then result:=max(result,aOrder.GetBestPrice-aOrder.GetTrailingStop) else result:=min(result,aOrder.GetBestPrice+aOrder.GetTrailingStop); end; function TStockTraderMACross2.GetExpirationDateTime(aTime: TDateTime): TDateTime; begin result:=IncHour(aTime,FFastMA_H1.GetPeriod-1); end; function TStockTraderMACross2.GetFastTrend(index: integer): TSCRealNumber; begin result:=0;//FLWMA21_H1.GetValue(index)-FLWMA55_H1.GetValue(index); end; function TStockTraderMACross2.GetRecommendedLots: TStockOrderLots; var aDayVolatility,aDayVolatilityM,k: TStockRealNumber; begin if not PropLotDynamicRate.Value then exit(inherited GetRecommendedLots); aDayVolatility:=FBarHeightD1.GetValue(FBarHeightD1.GetInputData.Count-1); //Считаем какая волатильность в деньгах у нас была последние дни aDayVolatilityM:=GetBroker.PriceToMoney(GetSymbol,aDayVolatility,1); //Считаем, сколько таких волатильностей вынесет наш баланс k:=(GetBroker.GetEquity/aDayVolatilityM); //Теперь берем допустимый процент result:=RoundTo(k*PropLotDynamicRateSize.Value/100,-2); end; function TStockTraderMACross2.GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber; begin if aOrder.GetKind=okBuy then result:=aOrder.GetOpenPrice-GetExpectedStopLossPrice(aOrder) else result:=GetExpectedStopLossPrice(aOrder) - aOrder.GetOpenPrice; end; procedure TStockTraderMACross2.SetProject(const aValue: IStockProject); begin if GetProject=aValue then exit; inherited; if aValue <> nil then begin //Создае нужных нам экспертов FBarHeightD1:=CreateBarHeightD1(aValue.GetStockChart(sti1440)); FFastMA_H1:= CreateMA_H1(aValue.GetStockChart(sti60),5,mamSimple); FSlowMA_H1:= CreateMA_H1(aValue.GetStockChart(sti60),10,mamSimple); // FLWMA21_H1:= CreateMA_H1(aValue.GetStockChart(sti60),21,mamLinearWeighted); // FLWMA55_H1:= CreateMA_H1(aValue.GetStockChart(sti60),55,mamLinearWeighted); // FMA84_H1:= CreateMA_H1(aValue.GetStockChart(sti60),84,mamSimple); //FMA220_H1:= CreateMA_H1(aValue.GetStockChart(sti60),220,mamSimple); end; end; procedure TStockTraderMACross2.SetTP(const aOrder: IStockOrder;const aTP: TStockRealNumber; const aComment: string); var aNew : TStockRealNumber; begin aNew:=GetBroker.RoundPrice(aOrder.GetSymbol,aTP); if not SameValue(aNew,aOrder.GetTakeProfit) then begin if aComment<>'' then GetBroker.AddMessage(aOrder,aComment); aOrder.SetTakeProfit(aNew); end; end; procedure TStockTraderMACross2.TrackOrderLevels(const aMALevel: TSCRealNumber); var i,j:integer; aAttribute : INeedCloseAttribute; aOrder: IStockOrder; aPrice: TSCRealNumber; aPriceKind: TStockBrokerPriceKind; begin //Подправляем значения цены открытия для отложенных ордеров for i := 0 to GetOrders.Count-1 do begin aOrder:=GetOrders[i]; if aOrder.GetState=osPending then begin if aOrder.GetKind=okBuy then aPriceKind:=bpkAsk else aPriceKind:=bpkBid; if not IsLevelTooCloseToCurrentPrice(aPriceKind,aMALevel) then try aOrder.SetPendingOpenPrice(aMALevel); except end; end else if aOrder.GetState=osOpened then begin j:=aOrder.GetAttributes.IndexOf(INeedCloseAttribute); if j<>-1 then begin aAttribute:=aOrder.GetAttributes.GetItem(j) as INeedCloseAttribute; if aAttribute.GetExpirationDateTime<=GetBroker.GetCurrentTime then begin aOrder.Close('Close time expired'); if aOrder.GetKind=okBuy then inherited OpenOrder(okSell,'Overturn') else inherited OpenOrder(okBuy,'Overturn') end else begin if (aOrder.GetKind=okBuy) then begin aPrice:=GetBroker.GetCurrentPrice(GetSymbol,bpkBid); if (aPrice<aMALevel) then aOrder.SetTakeProfit(aMALevel) else aOrder.SetStopLoss(aMALevel); end else if (aOrder.GetKind=okSell) then begin aPrice:=GetBroker.GetCurrentPrice(GetSymbol,bpkAsk); if (aPrice>aMALevel) then aOrder.SetTakeProfit(aMALevel) else aOrder.SetStopLoss(aMALevel); end end; end end; end; end; function TStockTraderMACross2.GetMainTrend(index: integer): TSCRealNumber; begin result:=0;//FMA84_H1.GetValue(index)-FMA220_H1.GetValue(index); end; function TStockTraderMACross2.GetCross(index: integer): integer; var x1,x2: integer; begin x1:=Sign(FFastMA_H1.GetValue(index)-FSlowMA_H1.GetValue(index)); x2:=Sign(FFastMA_H1.GetValue(index-1)-FSlowMA_H1.GetValue(index-1)); if x1=x2 then exit(0); result:=x1; end; procedure TStockTraderMACross2.UpdateStep2(const aTime: TDateTime); var idx60: integer; aInputData : ISCInputDataCollection; aChart : IStockChart; aOpenedOrder: IStockOrder; aOpen : integer; aMaCross : integer; aTime60 : TDateTime; //aFastTrend : TSCRealNumber; //aPrice : TSCRealNumber; i: Integer; aMALevel: TSCRealNumber; begin if FPropFullBarsOnly.Value then begin if not (MinuteOf(aTime) in [59..59])then exit; end; //Брокер может закрыть ордера и без нас. У нас в списке они останутся, //но будут уже закрыты. Если их не убрать, то открываться в этоу же сторону мы не //сможем, пока не будет сигнала от эксперта. Если же их удалить, сигналы //от эксперта в эту же сторону опять можно отрабатывать RemoveClosedOrders; aChart:=GetParentStockChart(FFastMA_H1); aInputData:=aChart.GetInputData; idx60:=aChart.FindBar(aTime); aTime60:=TStockDataUtils.AlignTimeToLeft(aTime,sti60); if SameDateTime(FLastOpenOrderTime,aTime60) then exit; if (idx60<>-1) and (idx60>=FSlowMA_H1.GetPeriod) then begin aMALevel:=FFastMA_H1.GetValue(idx60); TrackOrderLevels(aMALevel); aOpen:=0; for i := idx60 downto idx60-0 do begin aMaCross:=GetCross(i); //Открываем ордер if aMaCross>0 then aOpen:=1 else if aMaCross<0 then aOpen:=-1; if aOpen<>0 then break; end; if aOpen<>0 then begin //BUY if (aOpen=1) and (LastOrderType<>lotBuy) then begin CloseAllOrders(okSell,('Trader: Open opposite')); TrackOrderLevels(aMALevel); aOpenedOrder:=OpenMASnappedOrder(okBuy,aMALevel); FLastOpenOrderTime:=aTime60; end //SELL else if (aOpen=-1) and (LastOrderType<>lotSell) then begin CloseAllOrders(okBuy,('Trader: Open opposite')); TrackOrderLevels(aMALevel); aOpenedOrder:=OpenMASnappedOrder(okSell,aMALevel); FLastOpenOrderTime:=aTime60; end; end; end; end; procedure TStockTraderMACross2.OnBeginWorkSession; begin inherited; FLastOpenOrderTime:=0; end; function TStockTraderMACross2.OpenMASnappedOrder(aKind: TStockOrderKind;const aMALevel:TSCRealNumber; const aComment: string=''): IStockOrder; var aOpenPrice: TSCRealNumber; aSpread: TSCRealNumber; aExpTime: TDateTime; begin aSpread:=GetBroker.PointToPrice(GetSymbol,GetBroker.GetMarketInfo(GetSymbol).Spread); result:=nil; if aKind=okBuy then begin aOpenPrice :=aMALevel+aSpread;//GetBroker.GetCurrentPrice(GetSymbol,bpkAsk))/2+aSpread; if Abs(GetBroker.GetCurrentPrice(GetSymbol,bpkAsk)-aOpenPrice)<=aSpread then result:=OpenOrder(aKind,aComment); end else begin aOpenPrice := aMALevel;//+GetBroker.GetCurrentPrice(GetSymbol,bpkBid))/2-aSpread; if Abs(GetBroker.GetCurrentPrice(GetSymbol,bpkBid)-aOpenPrice)<=aSpread then result:=OpenOrder(aKind,aComment); end; if result=nil then begin result:=inherited OpenOrderAt(aKind,aOpenPrice,aComment); aExpTime:=TStockDataUtils.AlignTimeToLeft(GetBroker.GetCurrentTime,sti60); aExpTime:=GetExpirationDateTime(aExpTime); result.SetPendingExpirationTime(aExpTime); end; end; function TStockTraderMACross2.PriceToPoint(const aPrice: TSCRealNumber): integer; begin result:=GetBroker.PriceToPoint(GetSymbol,aPrice); end; { TNeedCloseAttribute } function TNeedCloseAttribute.GetExpirationDateTime: TDateTime; begin result:=FExpirationDateTime; end; procedure TNeedCloseAttribute.SetExpirationDateTime(const aDateTime: TDateTime); begin FExpirationDateTime:=aDateTime; end; initialization FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','MA Cross 2',TStockTraderMACross2,IStockTraderMACross2); end.
{ Version 12 Copyright (c) 2011-2012 by Bernd Gabriel 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. Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS are covered by separate copyright notices located in those modules. } unit HtmlUri; {$I htmlcons.inc} interface uses {$ifdef LCL} Classes, SysUtils, LclIntf, LclType, HtmlMisc, {$else} Windows, Classes, SysUtils, {$endif} HtmlGlobals; {*************************************************************************************************** * new URI processing methods. Incl. IPv6, UNC and DOS path recognition *************************************************************************************************** * about "Uniform Resource Identifier (URI): Generic Syntax" see http://tools.ietf.org/html/rfc3986 **************************************************************************************************} type // BG, 21.08.2011: TUri = record Scheme: ThtString; Username: ThtString; Password: ThtString; Host: ThtString; Port: ThtString; Path: ThtString; Query: ThtString; Fragment: ThtString; end; //------------------------------------------------------------------------------ // elementary methods //------------------------------------------------------------------------------ // Converts an URI string to a TUri record. function StrToUri(Uri: ThtString): TUri; overload; // Builds an absolute URI from RelativeUri by combining it with the given AbsoluteUri. function CombineUri(const RelativeUri, AbsoluteUri: TUri): TUri; // Converts all parts of the Uri to their normalized forms. // Converts to proper lettercase, Percent encodes reserved characters. // Converts backslashs to slashs in file URIs. procedure NormalizeUri(var Uri: TUri); // Converts a record TUri to an URI string. function UriToStr(const Uri: TUri): ThtString; // converts all percent encoded characters in the URI string back to the readable ones. function DecodeUri(const Uri: ThtString): ThtString; //------------------------------------------------------------------------------ // convenience methods //------------------------------------------------------------------------------ // Converts an URI string to a normalized TUri record. function StrToUri(Str, DefaultScheme: ThtString): TUri; overload; // Converts an URI string to a normalized URI string. function StrToUriStr(Str, DefaultScheme: ThtString): ThtString; overload; implementation //-- BG ---------------------------------------------------------- 22.08.2011 -- function Next(const Uri: ThtString; var I: Integer): ThtChar; {$ifdef UseInline} inline; {$endif} begin if I < Length(Uri) then begin Inc(I); Result := Uri[I]; if Result = '\' then Result := '/'; end else Result := #0; end; //-- BG ---------------------------------------------------------- 22.08.2011 -- function Chr2Hex(Ch: ThtChar): Integer; begin case Ch of '0'..'9': Result := Ord(Ch) - Ord('0'); 'a'..'f': Result := Ord(Ch) - Ord('a') + 10; 'A'..'F': Result := Ord(Ch) - Ord('A') + 10; else Result := 0; end; end; //-- BG ---------------------------------------------------------- 21.08.2011 -- function CombineUri(const RelativeUri, AbsoluteUri: TUri): TUri; begin end; //-- BG ---------------------------------------------------------- 22.08.2011 -- function DecodeUri(const Uri: ThtString): ThtString; // convert the percent encoded characters back to ansi/ascii chars. var I, J: Integer; Ch: ThtChar; begin SetLength(Result, Length(Uri)); I := 0; J := 0; repeat Ch := Next(Uri, I); case Ch of '%': begin Ch := Next(Uri, I); Ch := ThtChar(Chr2Hex(Ch) shl 4 + Chr2Hex(Next(Uri, I))); end; #0: break; end; Inc(J); Result[J] := Ch; until False; SetLength(Result, J); end; //-- BG ---------------------------------------------------------- 21.08.2011 -- procedure NormalizeUri(var Uri: TUri); // for better path normalization you should call NormalizeUri() after CombineUri(). procedure percentNormalization(var Str: ThtString); // convert the unreserved percent encoded characters back to ansi/ascii chars. // convert remaining code chars to uppercase var I, J: Integer; Ch, Ch1, Ch2: ThtChar; Result: ThtString; begin SetLength(Result, Length(Str) * 3); I := 0; J := 0; repeat Ch := Next(Str, I); case Ch of '%': begin Ch1 := Next(Str, I); Ch2 := Next(Str, I); Ch := ThtChar(Chr2Hex(Ch1) shl 4 + Chr2Hex(Ch2)); case Ch of // unreserved characters: 'a'..'z', 'A'..'Z', '0'..'9', '-', '_', '.', '~': ; else Inc(J); Result[J] := '%'; Inc(J); Result[J] := ThtChar(Ord(Ch1) - (Ord('a') - Ord('A'))); Ch := ThtChar(Ord(Ch2) - (Ord('a') - Ord('A'))) end; end; // unreserved characters: 'a'..'z', 'A'..'Z', '0'..'9', '-', '_', '.', '~': ; #0: break; else // must be percent encoded: Inc(J); Result[J] := '%'; Inc(J); Result[J] := ThtChar((Ord(Ch) and $F0) shr 4); Ch := ThtChar(Ord(Ch) and $F); end; Inc(J); Result[J] := Ch; until False; SetLength(Result, J); Str := Result; end; procedure pathNormalization(var Path: ThtString); var I, J, K, Len: Integer; Ch: ThtChar; Result: ThtString; IsSep: Boolean; SepPos: array of Integer; begin Len := Length(Path); if Len = 0 then begin Path := '/'; Exit; end; Inc(Len); SetLength(Result, Len); SetLength(SepPos, Len); I := 0; J := 0; K := 0; SepPos[K] := 0; repeat Ch := Next(Path, I); case Ch of '/': begin IsSep := False; case Next(Path, I) of '.': case Next(Path, I) of '.': case Next(Path, I) of '/': // step back to begin Dec(I); J := SepPos[K]; if K > 0 then Dec(K); end else Dec(I, 3); IsSep := True; end; '/': // skip '/.', continue with '/' begin Dec(I); end; else Dec(I, 2); IsSep := True; end; else Dec(I); IsSep := True; end; if IsSep then begin if J > SepPos[K] then // preserve adjacent '//' Inc(K); SepPos[K] := J; end; end; #0: break; end; Inc(J); Result[J] := Ch; until False; SetLength(Result, J); Path := Result; end; begin // 1. Case and Percent Normalization // - convert a..f in percent encoding to uppercase A..F // - do not %encode the unreserved chars ALPHA / DIGIT / "-" / "." / "_" / "~" percentNormalization(Uri.Username); percentNormalization(Uri.Password); percentNormalization(Uri.Path); percentNormalization(Uri.Query); percentNormalization(Uri.Fragment); // - convert scheme and host to lowercase Uri.Scheme := htLowerCase(Uri.Scheme); Uri.Host := htLowerCase(Uri.Host); // 2. Path Normalization // - eliminate /./ and /../ // - replace empty path with / // - convert backslash in path to / pathNormalization(Uri.Path); // 3. Scheme Based Normalization if (Uri.Scheme = 'http') or (Uri.Scheme = 'https') then begin // 3.1 http // - remove default port 80 if Uri.Port = '80' then Uri.Port := ''; end; end; //-- BG ---------------------------------------------------------- 21.08.2011 -- function StrToUri(Uri: ThtString): TUri; function Copy(const Uri: ThtString; I, Len: Integer): ThtString; begin if Len > 0 then Result := System.Copy(Uri, I, Len) else Result := ''; end; var I, Beg: Integer; Ch: ThtChar; IsPort: Boolean; begin I := 0; // parse scheme Result.Scheme := ''; Ch := Next(Uri, I); Beg := I; if IsAlpha(Ch) then begin repeat case Ch of ':': begin // end of scheme or is it a DOS path? if I = 2 then begin // assume, it is a DOS path Result.Scheme := 'file'; Uri := '///' + Uri; I := 1; Ch := Uri[I]; break; end else Result.Scheme := Copy(Uri, Beg, I - Beg); Ch := Next(Uri, I); Beg := I; break; end; '/', '?', '#', #0: // scheme is omitted break; end; Ch := Next(Uri, I); until False; end; // parse hierarchy IsPort := False; Result.Username := ''; Result.Password := ''; Result.Host := ''; Result.Port := ''; if Ch = '/' then begin Ch := Next(Uri, I); if Ch = '/' then begin Ch := Next(Uri, I); Beg := I; repeat case Ch of ':': begin // Maybe between username and password or host and port. // Assume it will become host, because host is read later than username and // thus will not overwrite the previously gotten username, if the guess is wrong. Result.Host := Copy(Uri, Beg, I - Beg); Ch := Next(Uri, I); Beg := I; repeat case Ch of '@': begin // got username and password Result.Username := Result.Host; Result.Password := Copy(Uri, Beg, I - Beg); Result.Host := ''; Ch := Next(Uri, I); Beg := I; break; end; '/', '?', '#', #0: begin // got host and port Result.Port := Copy(Uri, Beg, I - Beg); IsPort := True; Beg := I; break; end; end; Ch := Next(Uri, I); until False; continue; end; '[': if I = Beg then begin // ipv6address or ipvFuture Ch := Next(Uri, I); repeat case Ch of ']': break; '/', '?', '#', #0: break; end; Ch := Next(Uri, I); until False; end; '/', '?', '#', #0: begin // path begins or hierarchy is omitted if not IsPort then begin // remember host, as not yet done with the port. Result.Host := Copy(Uri, Beg, I - Beg); Beg := I; end; break; end; end; Ch := Next(Uri, I); until False; end; end; // parse path Result.Path := ''; if Ch = '/' then begin // skip leading '/' Ch := Next(Uri, I); Beg := I; end; repeat case Ch of '?', '#', #0: begin // end of path Result.Path := Copy(Uri, Beg, I - Beg); break; end; end; Ch := Next(Uri, I); until False; // parse query Result.Query := ''; if Ch = '?' then begin Ch := Next(Uri, I); Beg := I; repeat case Ch of '#', #0: begin // end of path Result.Query := Copy(Uri, Beg, I - Beg); break; end; end; Ch := Next(Uri, I); until False; end; // parse fragment Result.Fragment := ''; if Ch = '#' then begin Beg := I + 1; I := Length(Uri) + 1; Result.Fragment := Copy(Uri, Beg, I - Beg); end; end; //-- BG ---------------------------------------------------------- 21.08.2011 -- function UriToStr(const Uri: TUri): ThtString; var HierarchyPrefix: ThtString; begin Result := ''; if Length(Uri.Scheme) > 0 then Result := Uri.Scheme + ':'; HierarchyPrefix := '//'; if Length(Uri.Username) > 0 then begin Result := Result + HierarchyPrefix + Uri.Username + ':' + Uri.Password + '@'; HierarchyPrefix := ''; end; if Length(Uri.Host) > 0 then begin Result := Result + HierarchyPrefix + Uri.Host; HierarchyPrefix := '/'; end else if (Length(Uri.Path) >= 2) and (Uri.Path[2] = ':') and (htCompareString(Uri.Scheme, 'file') = 0) then HierarchyPrefix := '///' else HierarchyPrefix := ''; if Length(Uri.Port) > 0 then Result := Result + ':' + Uri.Port; if Length(Uri.Path) > 0 then Result := Result + HierarchyPrefix + Uri.Path; if Length(Uri.Query) > 0 then Result := Result + '?' + Uri.Query; if Length(Uri.Fragment) > 0 then Result := Result + '#' + Uri.Fragment; end; //-- BG ---------------------------------------------------------- 27.08.2011 -- function StrToUri(Str, DefaultScheme: ThtString): TUri; begin Result := StrToUri(Str); if Result.Scheme = '' then Result.Scheme := DefaultScheme; NormalizeUri(Result); end; //-- BG ---------------------------------------------------------- 27.08.2011 -- function StrToUriStr(Str, DefaultScheme: ThtString): ThtString; overload; var Uri: TUri; begin Uri := StrToUri(Str, DefaultScheme); Result := UriToStr(Uri); end; end.
unit main; interface uses DDDK; const DEV_NAME = '\Device\MyDriver'; SYM_NAME = '\DosDevices\MyDriver'; IOCTL_QUEUE = $222000; // CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS) IOCTL_PROCESS = $222004; // CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS) function _DriverEntry(pOurDriver:PDriverObject; pOurRegistry:PUnicodeString):NTSTATUS; stdcall; implementation var dpc: TKDpc; obj: KTIMER; csq: IO_CSQ; lock: KSPIN_LOCK; queue: LIST_ENTRY; procedure CsqInsertIrp(pCsqInfo:PIO_CSQ; pIrp:PIRP); stdcall; begin DbgPrint('CsqInsertIrp', []); InsertTailList(@queue, @pIrp^.Tail.Overlay.s1.ListEntry); end; procedure CsqRemoveIrp(pCsqInfo:PIO_CSQ; pIrp:PIRP); stdcall; begin DbgPrint('CsqRemoveIrp', []); RemoveEntryList(@pIrp^.Tail.Overlay.s1.ListEntry); end; function CsqPeekNextIrp(Csq:PIO_CSQ; Irp:PIRP; PeekContext:Pointer):PIRP; stdcall; begin DbgPrint('CsqPeekNextIrp', []); Result:= Nil; end; procedure CsqAcquireLock(Csq:PIO_CSQ; Irql:PKIRQL); stdcall; begin DbgPrint('CsqAcquireLock', []); KiAcquireSpinLock(@lock); end; procedure CsqReleaseLock(Csq:PIO_CSQ; Irql:KIRQL); stdcall; begin if Irql = DISPATCH_LEVEL then begin KefReleaseSpinLockFromDpcLevel(@lock); DbgPrint('CsqReleaseLock at DPC level', []); end else begin KiReleaseSpinLock(@lock); DbgPrint('CsqReleaseLock at Passive level', []); end; end; procedure CsqCompleteCanceledIrp(Csq:PIO_CSQ; pIrp:PIRP); stdcall; begin DbgPrint('CsqCompleteCanceledIrp', []); pIrp^.IoStatus.Status:= STATUS_CANCELLED; pIrp^.IoStatus.Information:= 0; IoCompleteRequest(pIrp, IO_NO_INCREMENT); end; procedure OnTimer(Dpc:KDPC; DeferredContext:Pointer; SystemArgument1:Pointer; SystemArgument2:Pointer); stdcall; var irp: PIRP; plist: PLIST_ENTRY; begin if IsListEmpty(@queue) = True then begin KeCancelTimer(@obj); DbgPrint('Finish', []); end else begin plist:= RemoveHeadList(@queue); // CONTAINING_RECORD(IRP.Tail.Overlay.ListEntry) irp:= Pointer(Integer(plist) - 88); if irp^.Cancel = False then begin irp^.IoStatus.Status:= STATUS_SUCCESS; irp^.IoStatus.Information:= 0; IoCompleteRequest(irp, IO_NO_INCREMENT); DbgPrint('Complete Irp', []); end else begin irp^.CancelRoutine:= Nil; irp^.IoStatus.Status:= STATUS_CANCELLED; irp^.IoStatus.Information:= 0; IoCompleteRequest(irp, IO_NO_INCREMENT); DbgPrint('Cancel Irp', []); end; end; end; function IrpOpen(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall; begin DbgPrint('IRP_MJ_CREATE', []); Result:= STATUS_SUCCESS; pIrp^.IoStatus.Information:= 0; pIrp^.IoStatus.Status:= Result; IoCompleteRequest(pIrp, IO_NO_INCREMENT); end; function IrpClose(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall; begin DbgPrint('IRP_MJ_CLOSE', []); Result:= STATUS_SUCCESS; pIrp^.IoStatus.Information:= 0; pIrp^.IoStatus.Status:= Result; IoCompleteRequest(pIrp, IO_NO_INCREMENT); end; function IrpIOCTL(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall; var code: ULONG; tt: LARGE_INTEGER; psk: PIoStackLocation; begin psk:= IoGetCurrentIrpStackLocation(pIrp); code:= psk^.Parameters.DeviceIoControl.IoControlCode; case code of IOCTL_QUEUE:begin DbgPrint('IOCTL_QUEUE', []); IoCsqInsertIrp(@csq, pIrp, Nil); Result:= STATUS_PENDING; exit end; IOCTL_PROCESS:begin DbgPrint('IOCTL_PROCESS', []); tt.HighPart:= tt.HighPart or -1; tt.LowPart:= ULONG(-10000000); KeSetTimerEx(@obj, tt.LowPart, tt.HighPart, 1000, @dpc); end; end; Result:= STATUS_SUCCESS; pIrp^.IoStatus.Information:= 0; pIrp^.IoStatus.Status:= Result; IoCompleteRequest(pIrp, IO_NO_INCREMENT); end; procedure Unload(pOurDriver:PDriverObject); stdcall; var szSymName: TUnicodeString; begin RtlInitUnicodeString(@szSymName, SYM_NAME); IoDeleteSymbolicLink(@szSymName); IoDeleteDevice(pOurDriver^.DeviceObject); end; function _DriverEntry(pOurDriver:PDriverObject; pOurRegistry:PUnicodeString):NTSTATUS; stdcall; var suDevName: TUnicodeString; szSymName: TUnicodeString; pOurDevice: PDeviceObject; begin RtlInitUnicodeString(@suDevName, DEV_NAME); RtlInitUnicodeString(@szSymName, SYM_NAME); Result:= IoCreateDevice(pOurDriver, 0, @suDevName, FILE_DEVICE_UNKNOWN, 0, FALSE, pOurDevice); if NT_SUCCESS(Result) then begin pOurDriver^.MajorFunction[IRP_MJ_CREATE]:= @IrpOpen; pOurDriver^.MajorFunction[IRP_MJ_CLOSE] := @IrpClose; pOurDriver^.MajorFunction[IRP_MJ_DEVICE_CONTROL] := @IrpIOCTL; pOurDriver^.DriverUnload := @Unload; pOurDevice^.Flags:= pOurDevice^.Flags or DO_BUFFERED_IO; pOurDevice^.Flags:= pOurDevice^.Flags and not DO_DEVICE_INITIALIZING; InitializeListHead(@queue); KeInitializeSpinLock(@lock); KeInitializeTimer(@obj); KeInitializeDpc(@dpc, OnTimer, pOurDevice); IoCsqInitialize(@csq, CsqInsertIrp, CsqRemoveIrp, CsqPeekNextIrp, CsqAcquireLock, CsqReleaseLock, CsqCompleteCanceledIrp); Result:= IoCreateSymbolicLink(@szSymName, @suDevName); end; end; end.
unit Chain; //////////////////////////////////////////////////////////////////////////////// // // Author: Jaap Baak // https://github.com/transportmodelling/CHAINBLD // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// interface //////////////////////////////////////////////////////////////////////////////// Uses Math,ArrayHlp; Type TChainType = Type String; TChainTypeHelper = record helper for TChainType public Function NLegs: Integer; Function SubChain: TChainType; Function LastLeg: Char; end; TChain = record private FNLegs: Integer; FImpedance: Float64; FNodes: array of Integer; Function GetNodes(Node: Integer): Integer; inline; public Function Sensible: Boolean; public Property NLegs: Integer read FNLegs; Property Impedance: Float64 read FImpedance; Property Nodes[Node: Integer]: Integer read GetNodes; default; end; TChainBuilder = Class private Type TChainTypeRec = record ChainType: TChainType; SubChain: Integer; LastLegMode: Integer; FromNodes: TArray<Integer>; Impedances: TArray<Float64>; end; Var FNNodes,FNChainTypes: Integer; FChainTypes: array of TChainTypeRec; ChainTypeIndices: array of Integer; Function GetChainTypes(ChainType: Integer): TChainType; inline; Function GetChains(ChainType,Destination: Integer): TChain; Function AddMode(const LegMode: Char): Integer; Function AddChainType(const ChainType: TChainType): Integer; strict protected Modes: array of Char; Function Impedance(const FromNode,ToNode,Mode: Integer): Float64; virtual; abstract; Function TransferPenalty(const Node,FromMode,ToMode: Integer): Float64; virtual; abstract; public Constructor Create(const NNodes: Integer; const ChainTypes: array of String); Procedure BuildChains(const Origin: Integer); public Property NNodes: Integer read FNNodes; Property NChainTypes: Integer read FNChainTypes; Property ChainTypes[ChainType: Integer]: TChainType read GetChainTypes; Property Chains[ChainType,Destination: Integer]: TChain read GetChains; default; end; //////////////////////////////////////////////////////////////////////////////// implementation //////////////////////////////////////////////////////////////////////////////// Function TChainTypeHelper.NLegs: Integer; begin Result := Length(Self); end; Function TChainTypeHelper.SubChain: TChainType; begin if NLegs = 1 then Result := '' else Result := Copy(Self,1,NLegs-1); end; Function TChainTypeHelper.LastLeg: Char; begin Result := Self[NLegs]; end; //////////////////////////////////////////////////////////////////////////////// Function TChain.GetNodes(Node: Integer): Integer; begin Result := FNodes[Node]; end; Function TChain.Sensible: Boolean; begin if FImpedance < Infinity then begin // Check whether all nodes only occur once Result := true; for var CheckNode := 0 to FNLegs-1 do begin var Check := FNodes[CheckNode]; for var Node := CheckNode+1 to NLegs do if FNodes[Node] = Check then Exit(false); end; end else result := false; end; //////////////////////////////////////////////////////////////////////////////// Constructor TChainBuilder.Create(const NNodes: Integer; const ChainTypes: array of String); begin inherited Create; FNNodes := NNodes; FNChainTypes := Length(ChainTypes); SetLength(ChainTypeIndices,FNChainTypes); for var ChainType := 0 to FNChainTypes-1 do ChainTypeIndices[ChainType] := AddChainType(ChainTypes[ChainType]); end; Function TChainBuilder.GetChainTypes(ChainType: Integer): TChainType; begin var ChainTypeIndex := ChainTypeIndices[ChainType]; Result := FChainTypes[ChainTypeIndex].ChainType; end; Function TChainBuilder.GetChains(ChainType,Destination: Integer): TChain; begin var ChainTypeIndex := ChainTypeIndices[ChainType]; var NLegs := FChainTypes[ChainTypeIndex].ChainType.NLegs; Result.FNLegs := NLegs; Result.FImpedance := FChainTypes[ChainTypeIndex].Impedances[Destination]; SetLength(Result.FNodes,NLegs+1); Result.FNodes[NLegs] := Destination; for var Leg := NLegs-1 downto 0 do begin Destination := FChainTypes[ChainTypeIndex].FromNodes[Destination]; ChainTypeIndex := FChainTypes[ChainTypeIndex].SubChain; Result.FNodes[Leg] := Destination; end; end; Function TChainBuilder.AddMode(const LegMode: Char): Integer; begin // Check for existing mode for var Mode := low(Modes) to high(Modes) do if Modes[Mode] = LegMode then Exit(Mode); // Append new mode Result := Length(Modes); Modes := Modes + [LegMode]; end; Function TChainBuilder.AddChainType(const ChainType: TChainType): Integer; Var SubChain: Integer; begin Result := -1; if ChainType.NLegs > 0 then begin // Check for existing chain type for var Typ := low(FChainTypes) to high(FChainTypes) do if FChainTypes[Typ].ChainType = ChainType then Exit(Typ); // Append new chain type if ChainType.NLegs = 1 then SubChain := -1 else SubChain := AddChainType(ChainType.SubChain); // Add chain type Result := Length(FChainTypes); SetLength(FChainTypes,Result+1); FChainTypes[Result].ChainType := ChainType; FChainTypes[Result].SubChain := SubChain; FChainTypes[Result].LastLegMode := AddMode(ChainType.LastLeg); FChainTypes[Result].FromNodes.Length := FNNodes; FChainTypes[Result].Impedances.Length := NNodes; end; end; Procedure TChainBuilder.BuildChains(const Origin: Integer); begin for var ChainType := low(FChainTypes) to high(FChainTypes) do begin var Mode := FChainTypes[ChainType].LastLegMode; var Impedances := FChainTypes[ChainType].Impedances; var FromNodes := FChainTypes[ChainType].FromNodes; if FChainTypes[ChainType].ChainType.NLegs = 1 then begin for var ToNode := 0 to FNNodes-1 do begin FromNodes[ToNode] := Origin; Impedances[ToNode] := Impedance(Origin,ToNode,Mode); end; end else begin var SubChain := FChainTypes[ChainType].SubChain; var SubChainMode := FChainTypes[SubChain].LastLegMode; var FromNodeImpedances := FChainTypes[SubChain].Impedances; Impedances.Initialize(Infinity); for var FromNode := 0 to FNNodes-1 do begin var FromNodeImpedance := FromNodeImpedances[FromNode]; if FromNodeImpedance < Infinity then begin for var ToNode := 0 to FNNodes-1 do begin var Imp := FromNodeImpedance + TransferPenalty(FromNode,SubChainMode,Mode) + Impedance(FromNode,ToNode,Mode); if Imp < Impedances[ToNode] then begin FromNodes[ToNode] := FromNode; Impedances[ToNode] := Imp; end; end; end; end; end; end; end; end.
unit u_frameExamineList; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, u_CommonDef, StdCtrls, u_frameExamineItemUI, u_frameExamineItemUIBase; type TframeExamineList = class(TFrame) GridPanel1: TGridPanel; ScrollBox1: TScrollBox; procedure FrameResize(Sender: TObject); private { Private declarations } FList: TInterfaceList; function GetItems(Index: Integer): IExamineItem; function GetCount: Integer; public { Public declarations } Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; function Add(AExamineItem: IExamineItem; AExamineItemUI: TFrameCustomExamineItemUI): IExamineItem; // Procedure Delete(const AExamineItem: IExamineItem); Procedure RecalcuSize; property Count: Integer read GetCount; property Items[Index: Integer]: IExamineItem read GetItems; Property List: TInterfaceList Read FList; end; implementation uses CnDebug, TypInfo, Types; {$R *.dfm} { TframeExamineList } function TframeExamineList.Add(AExamineItem: IExamineItem; AExamineItemUI: TFrameCustomExamineItemUI): IExamineItem; //var // AControl: TExamineItemDefaultControl; begin Result:= AExamineItem; // AControl:= TExamineItemDefaultControl.Create(GridPanel1); AExamineItemUI.Name:= AExamineItemUI.Name + IntToStr(FList.Count); AExamineItemUI.Parent:= GridPanel1; AExamineItemUI.Align:= alTop; Result.UI:= AExamineItemUI; (AExamineItemUI as IExamineItemUI).ExamineItem:= Result; FList.Add(Result); Result.ManageList:= FList; end; constructor TframeExamineList.Create(AOwner: TComponent); begin inherited; FList:= TInterfaceList.Create; // GridPanel1.Tag:= -2; // GridPanel1.InsertControl(); end; //procedure TframeExamineList.Delete(const AExamineItem: IExamineItem); //begin // FList.Remove(AExamineItem); //end; destructor TframeExamineList.Destroy; begin FList.Free; inherited; end; procedure TframeExamineList.FrameResize(Sender: TObject); begin GridPanel1.Width:= ScrollBox1.Width - 10; end; function TframeExamineList.GetCount: Integer; begin Result:= FList.Count; end; function TframeExamineList.GetItems(Index: Integer): IExamineItem; begin Result:= IExamineItem(FList[Index]); end; procedure TframeExamineList.RecalcuSize; var i: Integer; ABound: TRect; begin FillChar(ABound, SizeOf(TRect), #0); for i := 0 to self.GridPanel1.ControlCount - 1 do begin Types.UnionRect(ABound, ABound, GridPanel1.Controls[i].BoundsRect); // CnDebugger.LogFmt('Top: %d', [GridPanel1.Controls[i].BoundsRect.Top]); end; GridPanel1.SetBounds(Left, Top, ABound.Right - ABound.Left, ABound.Bottom - ABound.Top + 1); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { UpdateSQL Component Editor } { } { Copyright (c) 1997,1999 Borland Software Corp. } { } {*******************************************************} unit Updsqled; interface uses Forms, DB, DBTables, ExtCtrls, StdCtrls, Controls, ComCtrls, Classes, SysUtils, Windows, Menus; type TWaitMethod = procedure of object; TUpdateSQLEditForm = class(TForm) OkButton: TButton; CancelButton: TButton; HelpButton: TButton; GenerateButton: TButton; PrimaryKeyButton: TButton; DefaultButton: TButton; UpdateTableName: TComboBox; FieldsPage: TTabSheet; SQLPage: TTabSheet; PageControl: TPageControl; KeyFieldList: TListBox; UpdateFieldList: TListBox; GroupBox1: TGroupBox; Label1: TLabel; SQLMemo: TMemo; FTempTable: TTable; StatementType: TRadioGroup; QuoteFields: TCheckBox; GetTableFieldsButton: TButton; FieldListPopup: TPopupMenu; miSelectAll: TMenuItem; miClearAll: TMenuItem; procedure FormCreate(Sender: TObject); procedure HelpButtonClick(Sender: TObject); procedure StatementTypeClick(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure DefaultButtonClick(Sender: TObject); procedure GenerateButtonClick(Sender: TObject); procedure PrimaryKeyButtonClick(Sender: TObject); procedure PageControlChanging(Sender: TObject; var AllowChange: Boolean); procedure FormDestroy(Sender: TObject); procedure GetTableFieldsButtonClick(Sender: TObject); procedure SettingsChanged(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure UpdateTableNameChange(Sender: TObject); procedure UpdateTableNameClick(Sender: TObject); procedure SelectAllClick(Sender: TObject); procedure ClearAllClick(Sender: TObject); procedure SQLMemoKeyPress(Sender: TObject; var Key: Char); private StmtIndex: Integer; DataSet: TDBDataSet; Database: TDatabase; DatabaseOpened: Boolean; UpdateSQL: TUpdateSQL; FSettingsChanged: Boolean; FDatasetDefaults: Boolean; SQLText: array[TUpdateKind] of TStrings; function GetTableRef(const TabName, QuoteChar: string): string; function DatabaseOpen: Boolean; function Edit: Boolean; procedure GenWhereClause(const TabAlias, QuoteChar: string; KeyFields, SQL: TStrings); procedure GenDeleteSQL(const TableName, QuoteChar: string; KeyFields, SQL: TStrings); procedure GenInsertSQL(const TableName, QuoteChar: string; UpdateFields, SQL: TStrings); procedure GenModifySQL(const TableName, QuoteChar: string; KeyFields, UpdateFields, SQL: TStrings); procedure GenerateSQL; procedure GetDataSetFieldNames; procedure GetTableFieldNames; procedure InitGenerateOptions; procedure InitUpdateTableNames; procedure SetButtonStates; procedure SelectPrimaryKeyFields; procedure SetDefaultSelections; procedure ShowWait(WaitMethod: TWaitMethod); function TempTable: TTable; end; { TSQLParser } TSQLToken = (stSymbol, stAlias, stNumber, stComma, stEQ, stOther, stLParen, stRParen, stEnd); TSQLParser = class private FText: string; FSourcePtr: PChar; FTokenPtr: PChar; FTokenString: string; FToken: TSQLToken; FSymbolQuoted: Boolean; function NextToken: TSQLToken; function TokenSymbolIs(const S: string): Boolean; procedure Reset; public constructor Create(const Text: string); procedure GetSelectTableNames(List: TStrings); procedure GetUpdateTableName(var TableName: string); procedure GetUpdateFields(List: TStrings); procedure GetWhereFields(List: TStrings); end; function EditUpdateSQL(AUpdateSQL: TUpdateSQL): Boolean; implementation {$R *.dfm} uses Dialogs, bdeconst, LibHelp, TypInfo, BDE; { Global Interface functions } function EditUpdateSQL(AUpdateSQL: TUpdateSQL): Boolean; begin with TUpdateSQLEditForm.Create(Application) do try UpdateSQL := AUpdateSQL; Result := Edit; finally Free; end; end; { Utility Routines } procedure GetSelectedItems(ListBox: TListBox; List: TStrings); var I: Integer; begin List.Clear; for I := 0 to ListBox.Items.Count - 1 do if ListBox.Selected[I] then List.Add(ListBox.Items[I]); end; function SetSelectedItems(ListBox: TListBox; List: TStrings): Integer; var I: Integer; begin Result := 0; ListBox.Items.BeginUpdate; try for I := 0 to ListBox.Items.Count - 1 do if List.IndexOf(ListBox.Items[I]) > -1 then begin ListBox.Selected[I] := True; Inc(Result); end else ListBox.Selected[I] := False; if ListBox.Items.Count > 0 then begin ListBox.ItemIndex := 0; ListBox.TopIndex := 0; end; finally ListBox.Items.EndUpdate; end; end; procedure SelectAll(ListBox: TListBox); var I: Integer; begin ListBox.Items.BeginUpdate; try with ListBox do for I := 0 to Items.Count - 1 do Selected[I] := True; if ListBox.Items.Count > 0 then begin ListBox.ItemIndex := 0; ListBox.TopIndex := 0; end; finally ListBox.Items.EndUpdate; end; end; procedure GetDataFieldNames(Dataset: TDataset; ErrorName: string; List: TStrings); var I: Integer; begin with Dataset do try FieldDefs.Update; List.BeginUpdate; try List.Clear; for I := 0 to FieldDefs.Count - 1 do List.Add(FieldDefs[I].Name); finally List.EndUpdate; end; except if ErrorName <> '' then MessageDlg(Format(SSQLDataSetOpen, [ErrorName]), mtError, [mbOK], 0); end; end; procedure GetSQLTableNames(const SQL: string; List: TStrings); begin with TSQLParser.Create(SQL) do try GetSelectTableNames(List); finally Free; end; end; procedure ParseUpdateSQL(const SQL: string; var TableName: string; UpdateFields: TStrings; WhereFields: TStrings); begin with TSQLParser.Create(SQL) do try GetUpdateTableName(TableName); if Assigned(UpdateFields) then begin Reset; GetUpdateFields(UpdateFields); end; if Assigned(WhereFields) then begin Reset; GetWhereFields(WhereFields); end; finally Free; end; end; { TSQLParser } constructor TSQLParser.Create(const Text: string); begin FText := Text; FSourcePtr := PChar(Text); NextToken; end; function TSQLParser.NextToken: TSQLToken; var P, TokenStart: PChar; QuoteChar: Char; IsParam: Boolean; function IsKatakana(const Chr: Byte): Boolean; begin Result := (SysLocale.PriLangID = LANG_JAPANESE) and (Chr in [$A1..$DF]); end; begin if FToken = stEnd then SysUtils.Abort; FTokenString := ''; FSymbolQuoted := False; P := FSourcePtr; while (P^ <> #0) and (P^ <= ' ') do Inc(P); FTokenPtr := P; case P^ of 'A'..'Z', 'a'..'z', '_', '$', #127..#255: begin TokenStart := P; if not SysLocale.FarEast then begin Inc(P); while P^ in ['A'..'Z', 'a'..'z', '0'..'9', '_', '.', '"', '$', #127..#255] do Inc(P); end else begin while TRUE do begin if (P^ in ['A'..'Z', 'a'..'z', '0'..'9', '_', '.', '"', '$']) or IsKatakana(Byte(P^)) then Inc(P) else if P^ in LeadBytes then Inc(P, 2) else Break; end; end; SetString(FTokenString, TokenStart, P - TokenStart); FToken := stSymbol; end; '''', '"': begin QuoteChar := P^; Inc(P); IsParam := P^ = ':'; if IsParam then Inc(P); TokenStart := P; while not (P^ in [QuoteChar, #0]) do Inc(P); SetString(FTokenString, TokenStart, P - TokenStart); Inc(P); Trim(FTokenString); FToken := stSymbol; FSymbolQuoted := True; end; '-', '0'..'9': begin TokenStart := P; Inc(P); while P^ in ['0'..'9', '.', 'e', 'E', '+', '-'] do Inc(P); SetString(FTokenString, TokenStart, P - TokenStart); FToken := stNumber; end; ',': begin Inc(P); FToken := stComma; end; '=': begin Inc(P); FToken := stEQ; end; '(': begin Inc(P); FToken := stLParen; end; ')': begin Inc(P); FToken := stRParen; end; #0: FToken := stEnd; else begin FToken := stOther; Inc(P); end; end; FSourcePtr := P; if (FToken = stSymbol) and (FTokenString[Length(FTokenString)] = '.') then FToken := stAlias; Result := FToken; end; procedure TSQLParser.Reset; begin FSourcePtr := PChar(FText); FToken := stSymbol; NextToken; end; function TSQLParser.TokenSymbolIs(const S: string): Boolean; begin Result := (FToken = stSymbol) and (CompareText(FTokenString, S) = 0); end; procedure TSQLParser.GetSelectTableNames(List: TStrings); begin List.BeginUpdate; try List.Clear; if TokenSymbolIs('SELECT') then { Do not localize } try while not TokenSymbolIs('FROM') do NextToken; { Do not localize } NextToken; while FToken = stSymbol do begin List.AddObject(FTokenString, Pointer(Integer(FSymbolQuoted))); if NextToken = stSymbol then NextToken; if FToken = stComma then NextToken else break; end; except end; finally List.EndUpdate; end; end; procedure TSQLParser.GetUpdateTableName(var TableName: string); begin if TokenSymbolIs('UPDATE') and (NextToken = stSymbol) then { Do not localize } TableName := FTokenString else TableName := ''; end; procedure TSQLParser.GetUpdateFields(List: TStrings); begin List.BeginUpdate; try List.Clear; if TokenSymbolIs('UPDATE') then { Do not localize } try while not TokenSymbolIs('SET') do NextToken; { Do not localize } NextToken; while True do begin if FToken = stAlias then NextToken; if FToken <> stSymbol then Break; List.Add(FTokenString); if NextToken <> stEQ then Break; while NextToken <> stComma do if TokenSymbolIs('WHERE') then Exit;{ Do not localize } NextToken; end; except end; finally List.EndUpdate; end; end; procedure TSQLParser.GetWhereFields(List: TStrings); begin List.BeginUpdate; try List.Clear; if TokenSymbolIs('UPDATE') then { Do not localize } try while not TokenSymbolIs('WHERE') do NextToken; { Do not localize } NextToken; while True do begin while FToken in [stLParen, stAlias] do NextToken; if FToken <> stSymbol then Break; List.Add(FTokenString); if NextToken <> stEQ then Break; while true do begin NextToken; if FToken = stEnd then Exit; if TokenSymbolIs('AND') then Break; { Do not localize } end; NextToken; end; except end; finally List.EndUpdate; end; end; { TUpdateSQLEditor } { Private Methods } function TUpdateSQLEditForm.DatabaseOpen: Boolean; begin if Assigned(Database) then Result := True else begin Result := False; if not Assigned(DataSet) then Exit; if Assigned(DataSet.Database) then begin Database := DataSet.Database; Result := True; end else begin Database := DataSet.OpenDatabase; DatabaseOpened := True; Result := True; end; end; end; function TUpdateSQLEditForm.Edit: Boolean; var Index: TUpdateKind; DataSetName: string; begin Result := False; if Assigned(UpdateSQL.DataSet) and (UpdateSQL.DataSet is TDBDataSet) then begin DataSet := TDBDataSet(UpdateSQL.DataSet); FTempTable.SessionName := DataSet.SessionName; FTempTable.DatabaseName := DataSet.DatabaseName; DataSetName := Format('%s%s%s', [DataSet.Owner.Name, DotSep, DataSet.Name]); end else DataSetName := SNoDataSet; Caption := Format('%s%s%s (%s)', [UpdateSQL.Owner.Name, DotSep, UpdateSQL.Name, DataSetName]); try for Index := Low(TUpdateKind) to High(TUpdateKind) do begin SQLText[Index] := TStringList.Create; SQLText[Index].Assign(UpdateSQL.SQL[Index]); end; StatementTypeClick(Self); InitUpdateTableNames; ShowWait(InitGenerateOptions); PageControl.ActivePage := PageControl.Pages[0]; if ShowModal = mrOk then begin for Index := low(TUpdateKind) to high(TUpdateKind) do UpdateSQL.SQL[Index] := SQLText[Index]; Result := True; end; finally for Index := Low(TUpdateKind) to High(TUpdateKind) do SQLText[Index].Free; end; end; procedure TUpdateSQLEditForm.GenWhereClause(const TabAlias, QuoteChar: string; KeyFields, SQL: TStrings); var I: Integer; BindText: string; FieldName: string; begin SQL.Add('where'); { Do not localize } for I := 0 to KeyFields.Count - 1 do begin FieldName := KeyFields[I]; BindText := Format(' %s%s%s%1:s = :%1:sOLD_%2:s%1:s', { Do not localize } [TabAlias, QuoteChar, FieldName]); if I < KeyFields.Count - 1 then BindText := Format('%s and',[BindText]); { Do not localize } SQL.Add(BindText); end; end; procedure TUpdateSQLEditForm.GenDeleteSQL(const TableName, QuoteChar: string; KeyFields, SQL: TStrings); begin SQL.Clear; SQL.Add(Format('delete from %s', [TableName])); { Do not localize } GenWhereClause(GetTableRef(TableName, QuoteChar), QuoteChar, KeyFields, SQL); end; procedure TUpdateSQLEditForm.GenInsertSQL(const TableName, QuoteChar: string; UpdateFields, SQL: TStrings); procedure GenFieldList(const TabName, ParamChar, QuoteChar: String); var L: string; I: integer; Comma: string; begin L := ' ('; Comma := ', '; for I := 0 to UpdateFields.Count - 1 do begin if I = UpdateFields.Count - 1 then Comma := ''; L := Format('%s%s%s%s%s%3:s%5:s', [L, TabName, ParamChar, QuoteChar, UpdateFields[I], Comma]); if (Length(L) > 70) and (I <> UpdateFields.Count - 1) then begin SQL.Add(L); L := ' '; end; end; SQL.Add(L+')'); end; begin SQL.Clear; SQL.Add(Format('insert into %s', [TableName])); { Do not localize } GenFieldList(GetTableRef(TableName, QuoteChar), '', QuoteChar); SQL.Add('values'); { Do not localize } GenFieldList('', ':', QuoteChar); end; procedure TUpdateSQLEditForm.GenModifySQL(const TableName, QuoteChar: string; KeyFields, UpdateFields, SQL: TStrings); var I: integer; Comma: string; TableRef: string; begin SQL.Clear; SQL.Add(Format('update %s', [TableName])); { Do not localize } SQL.Add('set'); { Do not localize } Comma := ','; TableRef := GetTableRef(TableName, QuoteChar); for I := 0 to UpdateFields.Count - 1 do begin if I = UpdateFields.Count -1 then Comma := ''; SQL.Add(Format(' %s%s%s%1:s = :%1:s%2:s%1:s%3:s', [TableRef, QuoteChar, UpdateFields[I], Comma])); end; GenWhereClause(TableRef, QuoteChar, KeyFields, SQL); end; procedure TUpdateSQLEditForm.GenerateSQL; function QuotedTableName(const BaseName: string): string; begin with UpdateTableName do if ((ItemIndex <> -1) and (Items.Objects[ItemIndex] <> nil)) or (DatabaseOpen and not Database.IsSQLBased and (Pos('.', BaseName) > 0)) then Result := Format('"%s"', [BaseName]) else Result := BaseName; end; var KeyFields: TStringList; UpdateFields: TStringList; QuoteChar, TableName: string; begin if (KeyFieldList.SelCount = 0) or (UpdateFieldList.SelCount = 0) then raise Exception.CreateRes(@SSQLGenSelect); KeyFields := TStringList.Create; try GetSelectedItems(KeyFieldList, KeyFields); UpdateFields := TStringList.Create; try GetSelectedItems(UpdateFieldList, UpdateFields); TableName := QuotedTableName(UpdateTableName.Text); if QuoteFields.Checked then QuoteChar := '"' else QuoteChar := ''; GenDeleteSQL(TableName, QuoteChar, KeyFields, SQLText[ukDelete]); GenInsertSQL(TableName, QuoteChar, UpdateFields, SQLText[ukInsert]); GenModifySQL(TableName, QuoteChar, KeyFields, UpdateFields, SQLText[ukModify]); SQLMemo.Modified := False; StatementTypeClick(Self); PageControl.SelectNextPage(True); finally UpdateFields.Free; end; finally KeyFields.Free; end; end; procedure TUpdateSQLEditForm.GetDataSetFieldNames; begin if Assigned(DataSet) then begin GetDataFieldNames(DataSet, DataSet.Name, KeyFieldList.Items); UpdateFieldList.Items.Assign(KeyFieldList.Items); end; end; procedure TUpdateSQLEditForm.GetTableFieldNames; begin GetDataFieldNames(TempTable, TempTable.TableName, KeyFieldList.Items); UpdateFieldList.Items.Assign(KeyFieldList.Items); FDatasetDefaults := False; end; function TUpdateSQLEditForm.GetTableRef(const TabName, QuoteChar: string): string; begin if QuoteChar <> '' then Result := TabName + '.' else REsult := ''; end; procedure TUpdateSQLEditForm.InitGenerateOptions; var UpdTabName: string; procedure InitFromDataSet; begin // If this is a Query with more than 1 table in the "from" clause then // initialize the list of fields from the table rather than the dataset. if (UpdateTableName.Items.Count > 1) then GetTableFieldNames else begin GetDataSetFieldNames; FDatasetDefaults := True; end; SetDefaultSelections; end; procedure InitFromUpdateSQL; var UpdFields, WhFields: TStrings; begin UpdFields := TStringList.Create; try WhFields := TStringList.Create; try ParseUpdateSQL(SQLText[ukModify].Text, UpdTabName, UpdFields, WhFields); GetDataSetFieldNames; if SetSelectedItems(UpdateFieldList, UpdFields) < 1 then SelectAll(UpdateFieldList); if SetSelectedItems(KeyFieldList, WhFields) < 1 then SelectAll(KeyFieldList); finally WhFields.Free; end; finally UpdFields.Free; end; end; begin // If there are existing update SQL statements, try to initialize the // dialog with the fields that correspond to them. if SQLText[ukModify].Count > 0 then begin ParseUpdateSQL(SQLText[ukModify].Text, UpdTabName, nil, nil); // If the table name from the update statement is not part of the // dataset, then initialize from the dataset instead. if (UpdateTableName.Items.Count > 0) and (UpdateTableName.Items.IndexOf(UpdTabName) > -1) then begin UpdateTableName.Text := UpdTabName; InitFromUpdateSQL; end else begin InitFromDataSet; UpdateTableName.Items.Add(UpdTabName); end; end else InitFromDataSet; SetButtonStates; end; procedure TUpdateSQLEditForm.InitUpdateTableNames; begin UpdateTableName.Items.Clear; if Assigned(DataSet) then begin if DataSet is TQuery then GetSQLTableNames(TQuery(DataSet).SQL.Text, UpdateTableName.Items) else if (DataSet is TTable) and (TTable(DataSet).TableName <> '') then UpdateTableName.Items.Add(TTable(DataSet).TableName); end; if UpdateTableName.Items.Count > 0 then UpdateTableName.ItemIndex := 0; end; procedure TUpdateSQLEditForm.SetButtonStates; begin GetTableFieldsButton.Enabled := UpdateTableName.Text <> ''; PrimaryKeyButton.Enabled := GetTableFieldsButton.Enabled and (KeyFieldList.Items.Count > 0); GenerateButton.Enabled := GetTableFieldsButton.Enabled and (UpdateFieldList.Items.Count > 0) and (KeyFieldList.Items.Count > 0); DefaultButton.Enabled := Assigned(DataSet) and not FDatasetDefaults; end; procedure TUpdateSQLEditForm.SelectPrimaryKeyFields; var SepPos, I, Index: Integer; FName, FieldNames: string; begin if KeyFieldList.Items.Count < 1 then Exit; with TempTable do begin IndexDefs.Update; for I := 0 to KeyFieldList.Items.Count - 1 do KeyFieldList.Selected[I] := False; for I := 0 to IndexDefs.Count - 1 do if ixPrimary in IndexDefs[I].Options then begin FieldNames := IndexDefs[I].Fields + ';'; while Length(FieldNames) > 0 do begin SepPos := Pos(';', FieldNames); if SepPos < 1 then Break; FName := Copy(FieldNames, 1, SepPos - 1); System.Delete(FieldNames, 1, SepPos); Index := KeyFieldList.Items.IndexOf(FName); if Index > -1 then KeyFieldList.Selected[Index] := True; end; break; end; end; end; procedure TUpdateSQLEditForm.SetDefaultSelections; var DSFields: TStringList; begin if FDatasetDefaults or not Assigned(DataSet) then begin SelectAll(UpdateFieldList); SelectAll(KeyFieldList); end else if (DataSet.FieldDefs.Count > 0) then begin DSFields := TStringList.Create; try GetDataFieldNames(DataSet, '', DSFields); SetSelectedItems(KeyFieldList, DSFields); SetSelectedItems(UpdateFieldList, DSFields); finally DSFields.Free; end; end; end; procedure TUpdateSQLEditForm.ShowWait(WaitMethod: TWaitMethod); begin Screen.Cursor := crHourGlass; try WaitMethod; finally Screen.Cursor := crDefault; end; end; function TUpdateSQLEditForm.TempTable: TTable; begin if FTempTable.TableName <> UpdateTableName.Text then begin FTempTable.Close; FTempTable.TableName := UpdateTableName.Text; end; Result := FTempTable; end; { Event Handlers } procedure TUpdateSQLEditForm.FormCreate(Sender: TObject); begin HelpContext := hcDUpdateSQL; end; procedure TUpdateSQLEditForm.HelpButtonClick(Sender: TObject); begin Application.HelpContext(HelpContext); end; procedure TUpdateSQLEditForm.StatementTypeClick(Sender: TObject); begin if SQLMemo.Modified then SQLText[TUpdateKind(StmtIndex)].Assign(SQLMemo.Lines); StmtIndex := StatementType.ItemIndex; SQLMemo.Lines.Assign(SQLText[TUpdateKind(StmtIndex)]); end; procedure TUpdateSQLEditForm.OkButtonClick(Sender: TObject); begin if SQLMemo.Modified then SQLText[TUpdateKind(StmtIndex)].Assign(SQLMemo.Lines); end; procedure TUpdateSQLEditForm.DefaultButtonClick(Sender: TObject); begin with UpdateTableName do if Items.Count > 0 then ItemIndex := 0; ShowWait(GetDataSetFieldNames); FDatasetDefaults := True; SetDefaultSelections; KeyfieldList.SetFocus; SetButtonStates; end; procedure TUpdateSQLEditForm.GenerateButtonClick(Sender: TObject); begin GenerateSQL; FSettingsChanged := False; end; procedure TUpdateSQLEditForm.PrimaryKeyButtonClick(Sender: TObject); begin ShowWait(SelectPrimaryKeyFields); SettingsChanged(Sender); end; procedure TUpdateSQLEditForm.PageControlChanging(Sender: TObject; var AllowChange: Boolean); begin if (PageControl.ActivePage = PageControl.Pages[0]) and not SQLPage.Enabled then AllowChange := False; end; procedure TUpdateSQLEditForm.FormDestroy(Sender: TObject); begin if DatabaseOpened then Database.Session.CloseDatabase(Database); end; procedure TUpdateSQLEditForm.GetTableFieldsButtonClick(Sender: TObject); begin ShowWait(GetTableFieldNames); SetDefaultSelections; SettingsChanged(Sender); end; procedure TUpdateSQLEditForm.SettingsChanged(Sender: TObject); begin FSettingsChanged := True; FDatasetDefaults := False; SetButtonStates; end; procedure TUpdateSQLEditForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if (ModalResult = mrOK) and FSettingsChanged then CanClose := MessageDlg(SSQLNotGenerated, mtConfirmation, mbYesNoCancel, 0) = mrYes; end; procedure TUpdateSQLEditForm.UpdateTableNameChange(Sender: TObject); begin SettingsChanged(Sender); end; procedure TUpdateSQLEditForm.UpdateTableNameClick(Sender: TObject); begin if not Visible then Exit; GetTableFieldsButtonClick(Sender); end; procedure TUpdateSQLEditForm.SelectAllClick(Sender: TObject); begin SelectAll(FieldListPopup.PopupComponent as TListBox); end; procedure TUpdateSQLEditForm.ClearAllClick(Sender: TObject); var I: Integer; begin with FieldListPopup.PopupComponent as TListBox do begin Items.BeginUpdate; try for I := 0 to Items.Count - 1 do Selected[I] := False; finally Items.EndUpdate; end; end; end; procedure TUpdateSQLEditForm.SQLMemoKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then Close; end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 16384,0,0} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 54 O(N2) Dfs Method } program FindingPathOnLineSegment; const MaxN = 50; type TSegment = record X1, Y1, X2, Y2 : Integer; end; var N : Integer; S : array [1 .. MaxN] of TSegment; Mark : array [1 .. MaxN] of Boolean; SX, SY, TX, TY, LX, LY : Integer; I, J, X, Y : Integer; procedure ReadInput; begin Assign(Input, 'input.txt'); Reset(Input); Readln(N); for I := 1 to N do with S[I] do begin Readln(X1, Y1, X2, Y2); if X1 > X2 then begin J := X1; X1 := X2; X2 := J; end; if Y1 > Y2 then begin J := Y1; Y1 := Y2; Y2 := J; end; end; Readln(TX, TY); Readln(SX, SY); Close(Input); Assign(Output, 'output.txt'); Rewrite(Output); end; procedure CloseOutput; begin Close(Output); end; function InRange (A, B, C : Integer) : Boolean; begin InRange := (A <= B) and (B <= C); end; function G (I, J : Integer) : Boolean; begin with S[I] do G := (X1 <= S[J].X2) and (S[J].X1 <= X2) and (Y1 <= S[J].Y2) and (S[J].Y1 <= Y2); end; function Dfs (V : Integer) : Boolean; var I : Integer; begin with S[V] do if InRange(X1, TX, X2) and InRange(Y1, TY, Y2) then begin LX := TX; LY := TY; Writeln(TX, ' ', TY); Exit; end; Mark[V] := True; for I := 1 to V do if not Mark[I] and G(V, I) and Dfs(I) then with S[V] do begin if (X2 - X1) * (S[I].X2 - S[I].X1) + (Y2 - Y1) * (S[I].Y2 - S[I].Y1) = 0 then begin if X1 = X2 then X := X1 else X := S[I].X1; if Y1 = Y2 then Y := Y1 else Y := S[I].Y1; if (X <> LX) or (Y <> LY) then Writeln(X, ' ', Y); LX := X; LY := Y; end; Exit; end; end; procedure Solve; begin for I := 1 to N do with S[I] do if InRange(X1, SX, X2) and InRange(Y1, SY, Y2) then begin if Dfs(I) then begin Writeln(SX, ' ', SY); Exit; end; Break; end; Writeln('No Solution'); end; begin ReadInput; Solve; CloseOutput; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLSCUDAParser <p> Helper unit for parsing CU modules and get information about.<p> kernel's functions, textures, shared and constants memory.<p> <b>History : </b><font size=-1><ul> <li>13/04/11 - Yar - Added Ptx parsing to get real function's KernelName <li>17/02/11 - Yar - Now parse module instead of compiler product <li>19/03/10 - Yar - Creation </ul></font><p> } unit GLSCUDAParser; interface uses System.Classes, GLSCUDARunTime; type TCUDAType = ( customType, char1, uchar1, char2, uchar2, char3, uchar3, char4, uchar4, short1, ushort1, short2, ushort2, short3, ushort3, short4, ushort4, int1, uint1, int2, uint2, int3, uint3, int4, uint4, long1, ulong1, long2, ulong2, long3, ulong3, long4, ulong4, float1, float2, float3, float4, longlong1, ulonglong1, longlong2, ulonglong2, longlong3, ulonglong3, longlong4, ulonglong4, double1, double2, double3, double4, int8, int16, int32, uint8, uint16, uint32 ); TCUDATexRefInfo = record Name: string; DataType: TCUDAType; Dim: Byte; ReadMode: TcudaTextureReadMode; end; TCUDAFuncArgInfo = record Name: string; DataType: TCUDAType; CustomType: string; Ref: Boolean; end; TCUDAFuncInfo = record Name: string; KernelName: string; Args: array of TCUDAFuncArgInfo; end; TCUDAConstantInfo = record Name: string; DataType: TCUDAType; CustomType: string; Ref: Boolean; DefValue: Boolean; end; TCUDAModuleInfo = class(TObject) private ping, pong: TStrings; procedure Reset; procedure BreakStrings(inlist, outlist: TStrings); procedure RemoveComents(inlist, outlist: TStrings); procedure RemoveSpaces(inlist, outlist: TStrings); procedure ReplaceUnsigned(inlist, outlist: TStrings); procedure FindTexRef(inlist: TStrings); procedure FindConst(inlist: TStrings); procedure FindFunc(inlist: TStrings); procedure FindFuncKernelName(inlist: TStrings); public Owner: TComponent; TexRef: array of TCUDATexRefInfo; Func: array of TCUDAFuncInfo; Constant: array of TCUDAConstantInfo; constructor Create; destructor Destroy; override; procedure ParseModule(ASource, AProduct: TStrings); end; implementation uses GLStrings, SysUtils; const WordDelimiters: set of AnsiChar = [#0..#255] - ['a'..'z','A'..'Z','1'..'9','0','_']; sCUDAType: array[TCUDAType] of string = ( '', 'char', 'uchar', 'char2', 'uchar2', 'char3', 'uchar3', 'char4', 'uchar4', 'short', 'ushort', 'short2', 'ushort2', 'short3', 'ushort3', 'short4', 'ushort4', 'int', 'uint', 'int2', 'uint2', 'int3', 'uint3', 'int4', 'uint4', 'long', 'ulong', 'long2', 'ulong2', 'long3', 'ulong3', 'long4', 'ulong4', 'float', 'float2', 'float3', 'float4', 'longlong', 'ulonglong', 'longlong2', 'ulonglong2', 'longlong3', 'ulonglong3', 'longlong4', 'ulonglong4', 'double', 'double2', 'double3', 'double4', 'int8', 'int16', 'int32', 'uint8', 'uint16', 'uint32' ); function StrToCUDAType(const AToken: string): TCUDAType; var T: TCUDAType; begin for T := char1 to uint32 do if AToken = sCUDAType[T] then begin exit(T); end; Result := customType; end; procedure TCUDAModuleInfo.BreakStrings(inlist, outlist: TStrings); var i: Integer; str, accum: string; c: Char; begin str := inlist.Text; outlist.Clear; accum := ''; for I := 1 to Length(str) do begin c := str[I]; if CharInSet(c, WordDelimiters) then begin if Length(accum) > 0 then begin outlist.Add(accum); accum := ''; end; outlist.Add(c); end else accum := accum + str[I]; end; end; procedure TCUDAModuleInfo.RemoveComents(inlist, outlist: TStrings); var bSkipToLineBreak: Boolean; bSkipToRemarkEnd: Boolean; i: Integer; str1, str2: string; begin outlist.Clear; bSkipToLineBreak := False; bSkipToRemarkEnd := False; for I := 0 to inlist.Count - 2 do begin str1 := inlist[I]; str2 := inlist[I+1]; if bSkipToLineBreak then begin if (str1 = #13) then bSkipToLineBreak := False; continue; end; if bSkipToRemarkEnd then begin if (str1 = '*') and (str2 = '/') then bSkipToRemarkEnd := False; continue; end; if (str1 = '/') and (str2 = '/') then begin bSkipToLineBreak := True; continue; end else if (str1 = '/') and (str2 = '*') then begin bSkipToRemarkEnd := True; continue; end; outlist.Add(str1); end; end; procedure TCUDAModuleInfo.RemoveSpaces(inlist, outlist: TStrings); var i: Integer; begin outlist.Clear; for I := 0 to inlist.Count - 2 do if inlist[i] > #32 then outlist.Add(inlist[i]); end; procedure TCUDAModuleInfo.ReplaceUnsigned(inlist, outlist: TStrings); var I: Integer; begin outlist.Clear; I := 0; repeat if (inlist[I] = 'unsigned') and (inlist[I+1] = 'int') then begin outlist.Add('uint32'); Inc(I); end else outlist.Add(inlist[I]); Inc(I); until I >= inlist.Count; end; procedure TCUDAModuleInfo.FindTexRef(inlist: TStrings); var i, p, e: Integer; texInfo: TCUDATexRefInfo; begin for I := 0 to inlist.Count - 1 do begin if UpperCase(inlist[i]) = 'TEXTURE' then begin if inlist[i+1] <> '<' then continue; texInfo.DataType := StrToCUDAType(inlist[i+2]); if inlist[i+3] <> ',' then continue; Val(inlist[i+4], texInfo.Dim, e); if e <> 0 then Continue; p := 5; if inlist[i+5] = ',' then begin if inlist[i+6] = 'cudaReadModeElementType' then texInfo.ReadMode := cudaReadModeElementType else if inlist[i+6] = 'cudaReadModeNormalizedFloat' then texInfo.ReadMode := cudaReadModeNormalizedFloat else Continue; p := 7; end; if inlist[i+p] <> '>' then continue; texInfo.Name := inlist[i+p+1]; SetLength(TexRef, Length(TexRef)+1); TexRef[High(TexRef)] := texInfo; end; end; end; constructor TCUDAModuleInfo.Create; begin ping := TStringList.Create; pong := TStringList.Create; end; destructor TCUDAModuleInfo.Destroy; begin ping.Destroy; pong.Destroy; end; procedure TCUDAModuleInfo.FindConst(inlist: TStrings); var i, p: Integer; constInfo: TCUDAConstantInfo; begin for I := 0 to inlist.Count - 1 do begin if UpperCase(inlist[i]) = '__CONSTANT__' then begin p := i+1; if inlist[p] = 'static' then Inc(p); constInfo.DataType := StrToCUDAType(inlist[p]); if constInfo.DataType = customType then constInfo.CustomType := inlist[p] else constInfo.CustomType := ''; Inc(p); if inlist[p] = '*' then begin constInfo.Ref := True; Inc(p); end else constInfo.Ref := False; constInfo.Name := inlist[p]; Inc(p); constInfo.DefValue := False; while p < inlist.Count do begin if inlist[p] = '=' then begin constInfo.DefValue := True; break; end else if inlist[p] = ';' then break; Inc(p); end; SetLength(Constant, Length(Constant)+1); Constant[High(Constant)] := constInfo; end; end; end; procedure TCUDAModuleInfo.FindFunc(inlist: TStrings); var i, p: Integer; funcInfo: TCUDAFuncInfo; argInfo: TCUDAFuncArgInfo; begin for I := 0 to inlist.Count - 1 do begin if UpperCase(inlist[i]) = '__GLOBAL__' then begin if inlist[i+1] <> 'void' then Continue; funcInfo.Name := inlist[i+2]; funcInfo.KernelName := ''; if inlist[i+3] <> '(' then Continue; p := 4; funcInfo.Args := nil; while inlist[i+p] <> ')' do begin if inlist[i+p] = ',' then begin inc(p); Continue; end; argInfo.DataType := StrToCUDAType(inlist[i+p]); if argInfo.DataType = customType then argInfo.CustomType := inlist[i+p] else argInfo.CustomType := ''; Inc(p); if inlist[i+p] = '*' then begin argInfo.Ref := True; Inc(p); end else argInfo.Ref := False; argInfo.Name := inlist[i+p]; SetLength(funcInfo.Args, Length(funcInfo.Args)+1); funcInfo.Args[High(funcInfo.Args)] := argInfo; inc(p); end; SetLength(Func, Length(Func)+1); Func[High(Func)] := funcInfo; end; end; end; procedure TCUDAModuleInfo.FindFuncKernelName(inlist: TStrings); var I, J, P: Integer; LStr: string; begin for J := 0 to inlist.Count - 1 do begin LStr := inlist[J]; P := Pos('.entry', LStr); if P > 0 then begin Delete(LStr, 1, P+6); P := Pos(' ', LStr); if P < 1 then continue; LStr := Copy(LStr, 1, P-1); for I := 0 to High(Func) do begin if Pos(Func[I].Name, LStr) > 0 then begin if Length(Func[I].KernelName) > Length(LStr) then continue; Func[I].KernelName := LStr; break; end; end; end; end; end; procedure TCUDAModuleInfo.Reset; var i: Integer; begin TexRef := nil; Constant:= nil; for I := 0 to High(Func) do Func[I].Args := nil; Func := nil; end; procedure TCUDAModuleInfo.ParseModule(ASource, AProduct: TStrings); begin Reset; BreakStrings(ASource, ping); RemoveComents(ping, pong); RemoveSpaces(pong, ping); ReplaceUnsigned(ping, pong); FindTexRef(pong); FindConst(pong); FindFunc(pong); // Double call to confidence FindFuncKernelName(AProduct); FindFuncKernelName(AProduct); end; end.
unit frm_SetupAlm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, dxSkinscxPCPainter, dxBarBuiltInMenu, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, StdCtrls, Mask, DBCtrls, jpeg, ExtCtrls, cxGroupBox, cxPC, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalc, cxDBEdit, Menus, cxButtons, DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, global, frm_connection, ExtDlgs, cxPCdxBarPopupMenu, dxGDIPlusClasses, cxFilterControl, cxDBFilterControl, FormAutoScaler; type TfrmSetupAlm = class(TForm) cxPageControl1: TcxPageControl; cxTabSheet1: TcxTabSheet; cxTabSheet2: TcxTabSheet; Panel1: TPanel; cxGroupBox1: TcxGroupBox; cxGroupBox2: TcxGroupBox; bImagen: TImage; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label97: TLabel; Label12: TLabel; Label86: TLabel; Label14: TLabel; Label17: TLabel; Label15: TLabel; Label16: TLabel; Label113: TLabel; cxGroupBox4: TcxGroupBox; Label128: TLabel; Label123: TLabel; edtNumReq: TcxDBCalcEdit; Label124: TLabel; Label129: TLabel; Label126: TLabel; Label127: TLabel; edtNumOdc: TcxDBCalcEdit; btnGuardar: TcxButton; cxButton2: TcxButton; configuracion: TZQuery; ds_configuracion: TDataSource; OpenPicture: TOpenPictureDialog; dbConsecutivoReq: TcxDBCalcEdit; Label1: TLabel; dbConsecutivoCom: TcxDBCalcEdit; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; dbNumSal: TcxDBCalcEdit; Label6: TLabel; dbConsecutivoSal: TcxDBCalcEdit; ResulE1: TEdit; VistaPrevia: TLabel; lbl1: TLabel; ResulE2: TEdit; lbl3: TLabel; ResulE3: TEdit; cxGroupBox3: TcxGroupBox; dbExplosion : TDBComboBox ; lbl2: TLabel; lbl4: TLabel; lbl5: TLabel; dbPrefijoSal: TcxDBTextEdit; cxConfReq: TcxComboBox; TSNombreCorto: TcxDBTextEdit; TSeddiaseie: TcxDBTextEdit; TSedanexos: TcxDBTextEdit; edtReqOdc: TcxDBTextEdit; edtPreReq: TcxDBTextEdit; zqconfiguracionsContrato: TStringField; zqconfiguracionsNombre: TStringField; zqconfiguracionsNombreCorto: TStringField; zqconfiguracionsRfc: TStringField; zqconfiguracionsDireccion1: TStringField; zqconfiguracionsDireccion2: TStringField; zqconfiguracionsDireccion3: TStringField; zqconfiguracionsCiudad: TStringField; zqconfiguracionsSlogan: TStringField; zqconfiguracionsPiePagina: TStringField; configuracionbImagen: TBlobField; zqconfiguracionsTelefono: TStringField; zqconfiguracionsFax: TStringField; zqconfiguracionsEmail: TStringField; zqconfiguracionsRepresentanteObra: TStringField; zqconfiguracionsWeb: TStringField; zqconfiguracionlLicencia: TStringField; zqconfiguracioncStatusProceso: TStringField; zqconfiguracioncStatusSuspendida: TStringField; zqconfiguracioncStatusTerminada: TStringField; zqconfiguracionsIdDepartamento: TStringField; zqconfiguracionsIdEmbarcacion: TStringField; intgrfldconfiguracioniRedondeoMaterial: TIntegerField; intgrfldconfiguracioniRedondeoEquipo: TIntegerField; intgrfldconfiguracioniRedondeoPersonal: TIntegerField; intgrfldconfiguracioniRedondeoEmbarcacion: TIntegerField; zqconfiguracionsRangoAjusteMenor: TStringField; zqconfiguracionsRangoAjusteMayor: TStringField; zqconfiguracionsTipoContrato: TStringField; zqconfiguracionsRangoEstimacion: TStringField; zqconfiguracionsTipoPartida: TStringField; zqconfiguracionlCalculaFecha: TStringField; zqconfiguracionsTipoOperacion: TStringField; zqconfiguracionsTipoAlcance: TStringField; zqconfiguracionsTipoCIA: TStringField; zqconfiguracionlAutomatico: TStringField; intgrfldconfiguracioniIncremento: TIntegerField; zqconfiguracionsDuracion: TStringField; zqconfiguracionsReporteDiario: TStringField; zqconfiguracionsGerencial: TStringField; zqconfiguracionsIsometricos: TStringField; zqconfiguracionsHost: TStringField; zqconfiguracionsFolder: TStringField; zqconfiguracionsViewIsometrico: TStringField; zqconfiguracioniFirmas: TStringField; zqconfiguracionlExporta: TStringField; zqconfiguracionsTipoSeguridad: TStringField; zqconfiguracionsFirmasElectronicas: TStringField; zqconfiguracionsTipsInicial: TStringField; zqconfiguracionlComentariosReporte: TStringField; zqconfiguracionsFotografias: TStringField; zqconfiguracionlIncluyeGrafica: TStringField; zqconfiguracionlIncluyeAvanceOrdenes: TStringField; zqconfiguracionlIncluyeAvanceContrato: TStringField; intgrfldconfiguracioniMeses: TIntegerField; zqconfiguracionlDistribucion: TStringField; zqconfiguracionsFasePrincipal: TStringField; fltfldconfiguraciondRetencion: TFloatField; fltfldconfiguraciondPenaConvencional: TFloatField; zqconfiguracionsBaseCalculo: TStringField; zqconfiguracionsImporteRetencion: TStringField; zqconfiguracionsTipoAjusteCosto: TStringField; zqconfiguracionsAvanceInicial: TStringField; zqconfiguracionsAvanceAnterior: TStringField; zqconfiguracionsFormato: TStringField; intgrfldconfiguracioniConsecutivo: TIntegerField; zqconfiguracionlImprimeExtraordinario: TStringField; zqconfiguracionsAvanceBitacora: TStringField; zqconfiguracionsClaveTierra: TStringField; zqconfiguracionsClaveSeguridad: TStringField; zqconfiguracionsIdPernocta: TStringField; zqconfiguracionsImprimePEP: TStringField; zqconfiguracionsImpresionPaquetes: TStringField; zqconfiguracionsOrdenExtraordinaria: TStringField; zqconfiguracionsIdFase: TStringField; intgrfldconfiguracioniLongActividad: TIntegerField; zqconfiguracionlCalculoPonderado: TStringField; zqconfiguracionsBaseGeneracion: TStringField; zqconfiguracionsTipoGeneracion: TStringField; zqconfiguracionsSeguridadGenerador: TStringField; zqconfiguracionsTipoEstimacion: TStringField; zqconfiguracionsTerminoPenalizacion: TStringField; zqconfiguracionsIdConvenio: TStringField; zqconfiguracionsPartidaEfectiva: TStringField; zqconfiguracionsOrdenPerEq: TStringField; intgrfldconfiguracioniReportesSinValid: TIntegerField; zqconfiguracionsClaveDevolucion: TStringField; zqconfiguracionsDevolucion: TStringField; zqconfiguracionsMedida: TStringField; zqconfiguraciontxtValidaMaterial: TStringField; zqconfiguraciontxtMaterialAutomatico: TStringField; zqconfiguracionsIdAnexo: TStringField; zqconfiguracionsPaquete: TStringField; zqconfiguracionsProteccion: TStringField; fltfldconfiguracioniJLunes: TFloatField; fltfldconfiguracioniJMartes: TFloatField; fltfldconfiguracioniJMiercoles: TFloatField; fltfldconfiguracioniJJueves: TFloatField; fltfldconfiguracioniJViernes: TFloatField; fltfldconfiguracioniJSabado: TFloatField; fltfldconfiguracioniJDomingo: TFloatField; zqconfiguracionlAsistencia: TStringField; zqconfiguracionsIdGuardia: TStringField; zqconfiguracionsFalta: TStringField; zqconfiguracionsEquipoSeguridad: TStringField; zqconfiguracionsPersonalIndependiente: TStringField; zqconfiguracionsCampPerf: TStringField; zqconfiguracionsMostrarAvances: TStringField; zqconfiguracionlProrrateo: TStringField; zqconfiguracionsGenDesp: TStringField; zqconfiguracionsAnexos: TStringField; zqconfiguracionsFormatoCliente: TStringField; zqconfiguracioniFirmasReportes: TStringField; zqconfiguracioniFirmasGeneradores: TStringField; zqconfiguracioniFirmasBarco: TStringField; zqconfiguracioniFirmasEstimaciones: TStringField; zqconfiguracionsLeyenda1: TStringField; zqconfiguracionsLeyenda2: TStringField; zqconfiguracionsLeyenda3: TStringField; fltfldconfiguraciondCostoDirecto: TFloatField; fltfldconfiguraciondCostoIndirectos: TFloatField; fltfldconfiguraciondFinanciamiento: TFloatField; fltfldconfiguraciondUtilidad: TFloatField; fltfldconfiguraciondCargosAdicionales: TFloatField; fltfldconfiguraciondCargosAdicionales2: TFloatField; fltfldconfiguraciondCargosAdicionales3: TFloatField; zqconfiguracionlCalculaPU: TStringField; zqconfiguracionsSimbolo: TStringField; zqconfiguracionsExplosion: TStringField; zqconfiguracionsReportesCIA: TStringField; zqconfiguracionlEnviaCorreo: TStringField; zqconfiguracionlValidaBarco: TStringField; zqconfiguracionlTiempoMuertoTurnos: TStringField; zqconfiguracionlHistorialPartidas: TStringField; zqconfiguracionlBaseRelacional: TStringField; zqconfiguracionsFormatos: TStringField; zqconfiguracionsPasswordPdf: TStringField; zqconfiguracionsAplicaPassword: TStringField; zqconfiguracionlAplicaPu: TStringField; fltfldconfiguraciondPorcentajeHerramienta: TFloatField; zqconfiguracionsRepresentante: TStringField; zqconfiguracionsAux1: TStringField; zqconfiguracionsAux2: TStringField; zqconfiguracionlOrdenaItem: TStringField; zqconfiguracionlSeguridadVigencia: TStringField; zqconfiguracionlImprimeNotasGerenciales: TStringField; zqconfiguracionlAplicaAvisos: TStringField; zqconfiguracionlAplicaAvisosGen: TStringField; fltfldconfiguraciondGalones: TFloatField; intgrfldconfiguracioniEjercicio: TIntegerField; zqconfiguracionlCompanias: TStringField; zqconfiguracioneIva: TStringField; zqconfiguracionsPresidente: TStringField; zqconfiguracionsTitPresidente: TStringField; zqconfiguracionsTesorerom: TStringField; zqconfiguracionsTitTesorerom: TStringField; intgrfldconfiguracioniId_ZonaGeografica: TIntegerField; zqconfiguracioneEstRep: TStringField; intgrfldconfiguracioniNumOrdCompra: TIntegerField; intgrfldconfiguracioniNumReq: TIntegerField; zqconfiguracionsPrefijoOrdCompra: TStringField; zqconfiguracionsPrefijoReq: TStringField; zqconfiguracionsAlmPrefijoSal: TStringField; intgrfldconfiguracioniAlmConsecutivoReq: TIntegerField; intgrfldconfiguracioniAlmConsecutivoCom: TIntegerField; intgrfldconfiguracioniAlmConsecutivoSal: TIntegerField; intgrfldconfiguracioniAlmNumSal: TIntegerField; configuracionnDiasEqHerrCons: TSmallintField; configuracionnDiasAnexos: TSmallintField; zqconfiguracionsConfConsecutivo: TStringField; lbl6: TLabel; frmtsclr1: TFormAutoScaler; tsNombre: TcxDBTextEdit; tsRfc: TcxDBTextEdit; tsDireccion1: TcxDBTextEdit; tsDireccion2: TcxDBTextEdit; tsSlogan: TcxDBTextEdit; tsCiudad: TcxDBTextEdit; tsPiePagina: TcxDBTextEdit; tsWeb: TcxDBTextEdit; tsEmail: TcxDBTextEdit; tsFax: TcxDBTextEdit; tsTelefono: TcxDBTextEdit; TSS1: TDBEdit; tsRepresentante: TcxDBTextEdit; cxAlmCont: TcxComboBox; zqconfiguracionsAlmcon: TStringField; procedure FormShow(Sender: TObject); procedure btnGuardarClick(Sender: TObject); procedure cxButton2Click(Sender: TObject); procedure bImagenClick(Sender: TObject); procedure tsGalonKeyPress(Sender: TObject; var Key: Char); procedure edtNumReqKeyPress(Sender: TObject; var Key: Char); procedure dbConsecutivoReqKeyPress(Sender: TObject; var Key: Char); procedure dbConsecutivoComKeyPress(Sender: TObject; var Key: Char); procedure dbNumSalKeyPress(Sender: TObject; var Key: Char); procedure tsRfcEnter(Sender: TObject); procedure tsRfcExit(Sender: TObject); procedure tsDireccion1Enter(Sender: TObject); procedure tsDireccion1Exit(Sender: TObject); procedure tsDireccion2Enter(Sender: TObject); procedure tsDireccion2Exit(Sender: TObject); procedure tsSloganEnter(Sender: TObject); procedure tsSloganExit(Sender: TObject); procedure tsPiePaginaEnter(Sender: TObject); procedure tsPiePaginaExit(Sender: TObject); procedure tsTelefonoEnter(Sender: TObject); procedure tsTelefonoExit(Sender: TObject); procedure tsFaxEnter(Sender: TObject); procedure tsFaxExit(Sender: TObject); procedure tsWebExit(Sender: TObject); procedure tsWebEnter(Sender: TObject); procedure tsEmailEnter(Sender: TObject); procedure tsEmailExit(Sender: TObject); procedure tsRfcKeyPress(Sender: TObject; var Key: Char); procedure tsDireccion1KeyPress(Sender: TObject; var Key: Char); procedure tsDireccion2KeyPress(Sender: TObject; var Key: Char); procedure tsNombreKeyPress(Sender: TObject; var Key: Char); procedure sCiudadKeyPress(Sender: TObject; var Key: Char); procedure tsSloganKeyPress(Sender: TObject; var Key: Char); procedure tsPiePaginaKeyPress(Sender: TObject; var Key: Char); procedure tsTelefonoKeyPress(Sender: TObject; var Key: Char); procedure tsFaxKeyPress(Sender: TObject; var Key: Char); procedure tsWebKeyPress(Sender: TObject; var Key: Char); procedure tsEmailKeyPress(Sender: TObject; var Key: Char); procedure tsRepKeyPress(Sender: TObject; var Key: Char); procedure edtNumOdcKeyPress(Sender: TObject; var Key: Char); function cadenaDigitos(sParamDigitos : string) : string; procedure ResulE3Enter(Sender: TObject); procedure ResulE2Enter(Sender: TObject); procedure ResulE1Enter(Sender: TObject); procedure edtNumReqEnter(Sender: TObject); procedure edtNumReqExit(Sender: TObject); procedure dbConsecutivoReqEnter(Sender: TObject); procedure dbConsecutivoReqExit(Sender: TObject); procedure edtNumOdcExit(Sender: TObject); procedure edtNumOdcEnter(Sender: TObject); procedure dbConsecutivoComExit(Sender: TObject); procedure dbConsecutivoComEnter(Sender: TObject); procedure dbNumSalEnter(Sender: TObject); procedure dbNumSalExit(Sender: TObject); procedure dbConsecutivoSalEnter(Sender: TObject); procedure dbConsecutivoSalExit(Sender: TObject); procedure cxPageControl1Change(Sender: TObject); procedure edtNumReqPropertiesChange(Sender: TObject); procedure dbNumSalPropertiesChange(Sender: TObject); procedure edtNumOdcPropertiesChange(Sender: TObject); procedure dbConsecutivoReqPropertiesChange(Sender: TObject); procedure dbConsecutivoSalPropertiesChange(Sender: TObject); procedure dbConsecutivoComPropertiesChange(Sender: TObject); procedure edtReqOdcKeyPress(Sender: TObject; var Key: Char); procedure edtReqOdcExit(Sender: TObject); procedure edtReqOdcEnter(Sender: TObject); procedure edtPreReqKeyPress(Sender: TObject; var Key: Char); procedure edtPreReqEnter(Sender: TObject); procedure edtPreReqExit(Sender: TObject); procedure eddbPrefijoSalKeyPress(Sender: TObject; var Key: Char); procedure eddbPrefijoSalEnter(Sender: TObject); procedure dbPrefijoSalExit(Sender: TObject); procedure dbPrefijoSalEnter(Sender: TObject); procedure dbPrefijoSalKeyPress(Sender: TObject; var Key: Char); procedure TSNombreCortoKeyPress(Sender: TObject; var Key: Char); procedure TSNombreCortoEnter(Sender: TObject); procedure TSNombreCortoExit(Sender: TObject); procedure tsNombreEnter(Sender: TObject); procedure tsNombreExit(Sender: TObject); procedure tsCiudadKeyPress(Sender: TObject; var Key: Char); procedure tsCiudadEnter(Sender: TObject); procedure tsCiudadExit(Sender: TObject); procedure tsRepresentanteKeyPress(Sender: TObject; var Key: Char); procedure tsRepresentanteEnter(Sender: TObject); procedure tsRepresentanteExit(Sender: TObject); procedure InicializarConsecutivos; private { Private declarations } procedure IniciaConf; public { Public declarations } end; var frmSetupAlm: TfrmSetupAlm; sOldNumDigitos : string; implementation {$R *.dfm} Procedure TfrmSetupAlm.InicializarConsecutivos; var QDeptos,QFolios:TZQuery; begin QDeptos:=TZQuery.Create(nil); QFolios:=TZQuery.Create(nil); try QDeptos.Connection:=connection.zConnection; QDeptos.SQL.Text:='select * from departamentos'; QDeptos.Open; QFolios.Connection:=connection.zConnection; QFolios.SQL.Text:='select * from foliodepartamento where sContrato=:Contrato'; QFolios.ParamByName('Contrato').AsString:=global_contrato; QFolios.Open; while not QDeptos.Eof do begin if not QFolios.Locate('sIdDepartamento',QDeptos.FieldByName('sIdDepartamento').AsString,[]) then begin QFolios.Append; QFolios.FieldByName('sIdDepartamento').AsString:=QDeptos.FieldByName('sIdDepartamento').AsString; QFolios.FieldByName('sContrato').AsString:=global_contrato; QFolios.FieldByName('sCadenaTexto').AsString:=QDeptos.FieldByName('sCadenaTexto').AsString; QFolios.FieldByName('nConsecutivo').AsInteger:=QDeptos.FieldByName('nConsecutivo').AsInteger; QFolios.Post; end; QDeptos.Next; end; finally QDeptos.Destroy; QFolios.Destroy; end; end; procedure TfrmSetupAlm.bImagenClick(Sender: TObject); begin if (configuracion.State = dsEdit) then begin OpenPicture.Title := 'Inserta Imagen'; if OpenPicture.Execute then begin try bImagen.Picture.LoadFromFile(OpenPicture.FileName); except bImagen.Picture.LoadFromFile(''); end end end end; procedure TfrmSetupAlm.btnGuardarClick(Sender: TObject); var bS: TStream; Pic: TJpegImage; BlobField: tField; error:boolean ; begin if configuracion.State = dsEdit then begin error:=False; if (dbConsecutivoReq.Text = '') or (edtPreReq.Text = '') or (dbConsecutivoReq.Text = '') or (dbPrefijoSal.Text = '') or (dbNumSal.Text = '') or (dbConsecutivoSal.Text = '') or (edtNumOdc.Text = '')or (edtReqOdc.Text = '') or (dbConsecutivoCom.Text = '') then begin MessageDlg('“Registros incompletos”: Debe ingresar todos los datos para poder salvar', mtinformation,[mbOK],0 ); error := True; end; if error = False then begin if OpenPicture.FileName<>'' then begin try BlobField := configuracion.FieldByName('bImagen'); BS := configuracion.CreateBlobStream(BlobField, bmWrite); try Pic := TJpegImage.Create; try Pic.LoadFromFile(OpenPicture.FileName); Pic.SaveToStream(Bs); finally Pic.Free; end; finally bS.Free end except end; end; if Configuracion.FieldByName('sConfConsecutivo').AsString <> cxConfReq.Text then if cxConfReq.Text='CONTRATOS-DEPTOS' then InicializarConsecutivos; Configuracion.FieldByName('sConfConsecutivo').AsString := cxConfReq.Text ; Configuracion.FieldByName('sAlmcon').AsString := cxAlmCont.Text ; configuracion.Post; connection.configuracion.refresh; configuracion.Close; Close; end; end; end; procedure TfrmSetupAlm.cxButton2Click(Sender: TObject); begin if configuracion.State = dsEdit then configuracion.Cancel; configuracion.Close; Close; end; procedure TfrmSetupAlm.cxPageControl1Change(Sender: TObject); begin ResulE1.OnEnter(sender); ResulE2.OnEnter(sender); ResulE3.OnEnter(sender); end; procedure TfrmSetupAlm.dbConsecutivoComEnter(Sender: TObject); begin dbConsecutivoCom.Style.Color := global_color_entradaERP; sOldNumDigitos := dbConsecutivoCom.Text; end; procedure TfrmSetupAlm.dbConsecutivoComExit(Sender: TObject); begin dbConsecutivoCom.Style.Color := global_color_salidaERP; ResulE2.OnEnter(sender); end; procedure TfrmSetupAlm.dbConsecutivoComKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then dbPrefijoSal.SetFocus; end; procedure TfrmSetupAlm.dbConsecutivoComPropertiesChange(Sender: TObject); begin try if StrToInt(dbConsecutivoCom.Text) > 999999 then begin messageDLG('No se acepta un consecutivo mayor a 999,999 !',mtInformation, [mbOk], 0); dbConsecutivoCom.Text := sOldNumDigitos; end; Except end; end; procedure TfrmSetupAlm.dbConsecutivoReqEnter(Sender: TObject); begin dbConsecutivoReq.Style.Color := global_color_entradaERP; sOldNumDigitos := dbConsecutivoReq.Text; end; procedure TfrmSetupAlm.dbConsecutivoReqExit(Sender: TObject); begin dbConsecutivoReq.style.color := global_color_salidaERP; ResulE1.OnEnter(sender); end; procedure TfrmSetupAlm.dbConsecutivoReqKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then edtReqOdc.SetFocus; end; procedure TfrmSetupAlm.dbConsecutivoReqPropertiesChange(Sender: TObject); begin try if StrToInt(dbConsecutivoReq.Text) > 999999 then begin messageDLG('No se acepta un consecutivo mayor a 999,999 !',mtInformation, [mbOk], 0); dbConsecutivoReq.Text := sOldNumDigitos; end; Except end; end; procedure TfrmSetupAlm.dbConsecutivoSalEnter(Sender: TObject); begin dbConsecutivoSal.Style.Color := global_color_entradaERP; sOldNumDigitos := dbConsecutivoSal.Text; end; procedure TfrmSetupAlm.dbConsecutivoSalExit(Sender: TObject); begin dbConsecutivoSal.Style.Color := global_color_salidaERP; ResulE3.OnEnter(sender); end; procedure TfrmSetupAlm.dbConsecutivoSalPropertiesChange(Sender: TObject); begin try if StrToInt(dbConsecutivoSal.Text) > 999999 then begin messageDLG('No se acepta un consecutivo mayor a 999,999 !',mtInformation, [mbOk], 0); dbConsecutivoSal.Text := sOldNumDigitos; end; Except end; end; procedure TfrmSetupAlm.dbNumSalEnter(Sender: TObject); begin dbNumSal.Style.Color := global_color_entradaERP; sOldNumDigitos := dbNumSal.Text; end; procedure TfrmSetupAlm.dbNumSalExit(Sender: TObject); begin dbNumSal.Style.Color := global_color_salidaERP; ResulE3.OnEnter(sender); end; procedure TfrmSetupAlm.dbNumSalKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then dbConsecutivoSal.SetFocus; end; procedure TfrmSetupAlm.dbNumSalPropertiesChange(Sender: TObject); begin try if StrToInt(dbNumSal.Text) > 6 then begin messageDLG('No se aceptan más de 6 dígitos!',mtInformation, [mbOk], 0); dbNumSal.Text := sOldNumDigitos; end; Except end; end; procedure TfrmSetupAlm.dbPrefijoSalEnter(Sender: TObject); begin dbPrefijoSal.style.Color := global_color_EntradaERP; ResulE3.OnEnter(sender); end; procedure TfrmSetupAlm.dbPrefijoSalExit(Sender: TObject); begin dbPrefijoSal.style.Color := global_color_salidaERP; ResulE3.OnEnter(sender); end; procedure TfrmSetupAlm.dbPrefijoSalKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then dbNumSal.SetFocus; end; procedure TfrmSetupAlm.eddbPrefijoSalEnter(Sender: TObject); begin dbPrefijoSal.Style.Color := global_color_entradaERP; end; procedure TfrmSetupAlm.eddbPrefijoSalKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then dbNumSal.SetFocus; end; procedure TfrmSetupAlm.edtNumOdcEnter(Sender: TObject); begin edtNumOdc.Style.color := global_color_entradaERP; sOldNumDigitos := edtNumOdc.Text; end; procedure TfrmSetupAlm.edtNumOdcExit(Sender: TObject); begin edtNumOdc.style.color := global_color_salidaERP; ResulE2.OnEnter(sender); end; procedure TfrmSetupAlm.edtNumOdcKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then dbConsecutivoCom.SetFocus; end; procedure TfrmSetupAlm.edtNumOdcPropertiesChange(Sender: TObject); begin try if StrToInt(edtNumOdc.Text) > 6 then begin messageDLG('No se aceptan más de 6 dígitos!',mtInformation, [mbOk], 0); edtNumOdc.Text := sOldNumDigitos; end; Except end; end; procedure TfrmSetupAlm.edtNumReqEnter(Sender: TObject); begin edtNumReq.Style.Color := global_color_entradaERP; sOldNumDigitos := edtNumReq.Text; end; procedure TfrmSetupAlm.edtNumReqExit(Sender: TObject); begin edtNumReq.style.color := global_color_salidaERP; ResulE1.OnEnter(sender); end; procedure TfrmSetupAlm.edtNumReqKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then dbConsecutivoReq.SetFocus; end; procedure TfrmSetupAlm.edtNumReqPropertiesChange(Sender: TObject); begin try if StrToInt(edtNumReq.Text) > 6 then begin messageDLG('No se aceptan más de 6 dígitos!',mtInformation, [mbOk], 0); edtNumReq.Text := sOldNumDigitos; end; Except end; end; procedure TfrmSetupAlm.edtPreReqEnter(Sender: TObject); begin edtPreReq.Style.Color := global_color_entradaERP; end; procedure TfrmSetupAlm.edtPreReqExit(Sender: TObject); begin edtPreReq.Style.color := global_color_salidaERP; ResulE1.OnEnter(sender); end; procedure TfrmSetupAlm.edtPreReqKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then edtNumReq.SetFocus; end; procedure TfrmSetupAlm.edtReqOdcEnter(Sender: TObject); begin edtReqOdc.style.Color := global_color_EntradaERP; end; procedure TfrmSetupAlm.edtReqOdcExit(Sender: TObject); begin edtReqOdc.style.Color := global_color_salidaERP; ResulE2.OnEnter(sender); end; procedure TfrmSetupAlm.edtReqOdcKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then edtNumOdc.SetFocus; end; procedure TfrmSetupAlm.FormShow(Sender: TObject); var bS: TStream; Pic: TJpegImage; BlobField: tField; begin if global_contrato <> '' then begin IniciaConf; cxConfReq.Text := Configuracion.FieldByName('sConfConsecutivo').AsString ; cxAlmCont.Text := Configuracion.FieldByName('sAlmcon').AsString ; if configuracion.RecordCount > 0 then begin configuracion.Edit; BlobField := configuracion.FieldByName('bImagen'); BS := configuracion.CreateBlobStream(BlobField, bmRead); if bs.Size > 1 then begin try Pic := TJpegImage.Create; try Pic.LoadFromStream(bS); bImagen.Picture.Graphic := Pic; finally Pic.Free; end; finally bS.Free end end else bImagen.Picture.LoadFromFile(''); end else begin connection.QryBusca.Active := False; connection.QryBusca.SQL.clear; connection.QryBusca.SQL.Add('insert into alm_configuracion (sContrato) values (:contrato)'); connection.QryBusca.Params.ParamByName('contrato').AsString := global_contrato; connection.QryBusca.ExecSQL; IniciaConf; if configuracion.RecordCount > 0 then configuracion.Edit; end; end; end; procedure TfrmSetupAlm.ResulE1Enter(Sender: TObject); begin try ResulE1.Text:= edtPreReq.Text + formatfloat(cadenaDigitos(edtNumReq.Text),dbconsecutivoReq.Value); Except end; end; procedure TfrmSetupAlm.ResulE2Enter(Sender: TObject); begin try ResulE2.Text:= edtReqOdc.Text + formatfloat(cadenaDigitos(edtNumOdc.Text),dbconsecutivoCom.Value); Except end; end; procedure TfrmSetupAlm.ResulE3Enter(Sender: TObject); begin try ResulE3.Text:= dbPrefijoSal.Text + formatfloat(cadenaDigitos(dbNumSal.Text),dbconsecutivoSal.Value); Except end; end; procedure TfrmSetupAlm.sCiudadKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then tsSlogan.SetFocus; end; procedure TfrmSetupAlm.tsCiudadEnter(Sender: TObject); begin tsCiudad.Style.Color := Global_Color_EntradaERP ; end; procedure TfrmSetupAlm.tsCiudadExit(Sender: TObject); begin tsCiudad.Style.Color := Global_color_SalidaERP ; end; procedure TfrmSetupAlm.tsCiudadKeyPress(Sender: TObject; var Key: Char); begin if key=#13 then tsSlogan.SetFocus ; end; procedure TfrmSetupAlm.tsDireccion1Enter(Sender: TObject); begin tsDireccion1.style.color := global_color_entradaERP end; procedure TfrmSetupAlm.tsDireccion1Exit(Sender: TObject); begin tsDireccion1.style.color := global_color_salidaERP end; procedure TfrmSetupAlm.tsDireccion1KeyPress(Sender: TObject; var Key: Char); begin if key = #13 then tsDireccion2.SetFocus; end; procedure TfrmSetupAlm.tsDireccion2Enter(Sender: TObject); begin tsDireccion2.style.color := global_color_entradaERP end; procedure TfrmSetupAlm.tsDireccion2Exit(Sender: TObject); begin tsDireccion2.style.color := global_color_salidaERP end; procedure TfrmSetupAlm.tsDireccion2KeyPress(Sender: TObject; var Key: Char); begin if key = #13 then tsciudad.SetFocus; end; procedure TfrmSetupAlm.tsEmailEnter(Sender: TObject); begin tsEmail.style.color := global_color_entradaERP end; procedure TfrmSetupAlm.tsEmailExit(Sender: TObject); begin tsEmail.style.color := global_color_salidaERP end; procedure TfrmSetupAlm.tsEmailKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then tsRepresentante.SetFocus; end; procedure TfrmSetupAlm.tsFaxEnter(Sender: TObject); begin tsFax.style.color := global_color_entradaERP end; procedure TfrmSetupAlm.tsFaxExit(Sender: TObject); begin tsFax.style.color := global_color_salidaERP end; procedure TfrmSetupAlm.tsFaxKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then tsWeb.SetFocus; end; procedure TfrmSetupAlm.tsGalonKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then edtPreReq.SetFocus; end; procedure TfrmSetupAlm.TSNombreCortoEnter(Sender: TObject); begin tsNombreCorto.Style.Color := global_color_entradaERP end; procedure TfrmSetupAlm.TSNombreCortoExit(Sender: TObject); begin tsNombreCorto.Style.Color := Global_Color_SalidaERP end; procedure TfrmSetupAlm.TSNombreCortoKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then tsnombre.SetFocus; end; procedure TfrmSetupAlm.tsNombreEnter(Sender: TObject); begin tsNombre.Style.Color := Global_Color_EntradaERP ; end; procedure TfrmSetupAlm.tsNombreExit(Sender: TObject); begin tsNombre.Style.Color := Global_Color_SalidaERP ; end; procedure TfrmSetupAlm.tsNombreKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then tsrfc.SetFocus; end; procedure TfrmSetupAlm.tsPiePaginaEnter(Sender: TObject); begin tsPiePagina.style.color := global_color_entradaERP end; procedure TfrmSetupAlm.tsPiePaginaExit(Sender: TObject); begin tsPiePagina.style.color := global_color_salidaERP end; procedure TfrmSetupAlm.tsPiePaginaKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then tsTelefono.SetFocus; end; procedure TfrmSetupAlm.tsRepKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then tsNombreCorto.SetFocus; end; procedure TfrmSetupAlm.tsRepresentanteEnter(Sender: TObject); begin tsRepresentante.Style.Color := Global_color_entradaERP ; end; procedure TfrmSetupAlm.tsRepresentanteExit(Sender: TObject); begin tsRepresentante.Style.Color := Global_color_salidaERP ; end; procedure TfrmSetupAlm.tsRepresentanteKeyPress(Sender: TObject; var Key: Char); begin if key= #13 then tsNombreCorto.SetFocus ; end; procedure TfrmSetupAlm.tsRfcEnter(Sender: TObject); begin tsRfc.style.color := global_color_entradaERP end; procedure TfrmSetupAlm.tsRfcExit(Sender: TObject); begin tsRfc.style.color := global_color_salidaERP end; procedure TfrmSetupAlm.tsRfcKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then tsdireccion1.SetFocus; end; procedure TfrmSetupAlm.tsSloganEnter(Sender: TObject); begin tsSlogan.style.color := global_color_entradaERP end; procedure TfrmSetupAlm.tsSloganExit(Sender: TObject); begin tsSlogan.style.color := global_color_salidaERP end; procedure TfrmSetupAlm.tsSloganKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then tsPiePagina.SetFocus; end; procedure TfrmSetupAlm.tsTelefonoEnter(Sender: TObject); begin tsTelefono.style.color := global_color_entradaERP end; procedure TfrmSetupAlm.tsTelefonoExit(Sender: TObject); begin tsTelefono.style.color := global_color_salidaERP end; procedure TfrmSetupAlm.tsTelefonoKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then tsFax.SetFocus; end; procedure TfrmSetupAlm.tsWebEnter(Sender: TObject); begin tsweb.style.color := global_color_entradaERP end; procedure TfrmSetupAlm.tsWebExit(Sender: TObject); begin tsweb.style.color := global_color_salidaERP end; procedure TfrmSetupAlm.tsWebKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then tsEmail.SetFocus; end; function TfrmSetupAlm.cadenaDigitos(sParamDigitos: string): string; var Numdigitos : string; i : integer; begin Numdigitos := ''; for i := 1 to StrToInt(sParamdigitos) do Numdigitos := Numdigitos+'0'; result := Numdigitos; end; procedure TfrmSetupAlm.IniciaConf; begin configuracion.Active := False; configuracion.Params.ParamByName('contrato').DataType := ftString; configuracion.Params.ParamByName('contrato').Value := global_contrato; configuracion.Open ; end; end.
unit DimensionGraphicsUnit; interface uses SysUtils, //System, DimensionsUnit, Graphics; function SpaceToBitmap(SpaceToConvert: TSpace) : TBitmap; function XYSpaceToBitmap(SpaceToConvert: TSpace; ZSpaceIndex: Integer) : TBitmap; implementation type TRGB24Bit = packed record R, G, B: byte; end; PRGB24BitArray = ^TRGB24BitArray; TRGB24BitArray = packed array[0..MaxInt div SizeOf(TRGB24Bit) - 1] of TRGB24Bit; var InformationOnColor: TRGB24Bit; InformationOffColor: TRGB24Bit; function SpaceToBitmap(SpaceToConvert: TSpace) : TBitmap; var xIndex, yIndex, zIndex : Integer; P : PRGB24BitArray; begin Result := TBitmap.Create; Result.PixelFormat := pf24bit; Result.Width := SpaceSize; Result.Height := SpaceSize * SpaceSize; for zIndex := 0 to SpaceSize -1 do for yIndex := 0 to SpaceSize -1 do begin P := Result.ScanLine[yIndex + (SpaceSize * zIndex)]; for xIndex := 0 to Result.Width -1 do if SpaceToConvert.Points[xIndex + 1,yIndex + 1,zIndex + 1] > 0 then P[xIndex] := InformationOnColor else P[xIndex] := InformationOffColor; end; end; function XYSpaceToBitmap(SpaceToConvert: TSpace; ZSpaceIndex: Integer) : TBitmap; var xIndex, yIndex : Integer; P : PRGB24BitArray; begin Result := TBitmap.Create; Result.PixelFormat := pf24bit; Result.Width := SpaceSize; Result.Height := SpaceSize; for yIndex := 0 to Result.Height -1 do begin P := Result.ScanLine[yIndex]; for xIndex := 0 to Result.Width -1 do if SpaceToConvert.Points[xIndex + 1,yIndex + 1,ZSpaceIndex] > 0 then P[xIndex] := InformationOnColor else P[xIndex] := InformationOffColor; end; end; initialization InformationOnColor.R := 255; InformationOnColor.G := 255; InformationOnColor.B := 255; InformationOffColor.R := 0; InformationOffColor.G := 0; InformationOffColor.B := 0; end.
unit pengembalian_handler; interface uses tipe_data; const nmax = 1000; type pengembalian = record Username, ID_Buku, Tanggal_Pengembalian: string; end; tabel_pengembalian = record t: array [0..nmax] of pengembalian; sz: integer; // effective size end; function tambah(s: arr_str): tabel_pengembalian; procedure keluarkan(data_temppengembalian: tabel_pengembalian); function konversi_csv(data_temppengembalian: tabel_pengembalian): arr_str; implementation function tambah(s: arr_str): tabel_pengembalian; { fungsi tambah adalah suatu fungsi yang menerima inputan berupa s -- array of string yang berisikan kumpulan string yang merupakan hasil convert dari text pada csv-- dan mengubahnya menjadi array yang berupa data terpisah -- username, id_buku,author,tanggal peminjaman, tanggal batas pengembalian dan status pengembalian-- masing masing user.} var col, row: integer; // col = data ke-N, row = baris ke-N dari file csv temp: string; // string temporer, berfungsi c: char; data_temppengembalian : tabel_pengembalian; begin data_temppengembalian.sz := 0; for row:=0 to s.sz-1 do begin col := 0; temp := ''; for c in s.st[row] do begin if(c=',') then begin // 0 based indexing case col of 0: data_temppengembalian.t[data_temppengembalian.sz].Username := temp; 1: data_temppengembalian.t[data_temppengembalian.sz].ID_Buku := temp; end; col := col+1; temp := ''; end else temp := temp+c; end; data_temppengembalian.t[data_temppengembalian.sz].Tanggal_Pengembalian := temp; data_temppengembalian.sz := data_temppengembalian.sz+1; end; // keluarkan(data_temppengembalian); tambah := data_temppengembalian; end; function konversi_csv(data_temppengembalian: tabel_pengembalian): arr_str; var i : integer; ret : arr_str; begin ret.sz := data_temppengembalian.sz; for i:=0 to data_temppengembalian.sz do begin ret.st[i] := data_temppengembalian.t[i].Username + ',' + data_temppengembalian.t[i].ID_Buku + ',' + data_temppengembalian.t[i].Tanggal_Pengembalian; end; konversi_csv := ret; end; procedure keluarkan(data_temppengembalian: tabel_pengembalian); // for debugging var i: integer; begin for i:=0 to data_temppengembalian.sz-1 do begin writeln(data_temppengembalian.t[i].Username, ' | ', data_temppengembalian.t[i].ID_Buku, ' | ', data_temppengembalian.t[i].Tanggal_Pengembalian); end; end; end. // sample
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX_ListBox; {$I FMX_Defines.inc} interface uses Classes, Types, UITypes, FMX_Types, FMX_Controls, FMX_Layouts, FMX_Objects; {$SCOPEDENUMS ON} type TCustomListBox = class; TCustomComboBox = class; { TListBoxItem } TListBoxItem = class(TTextControl) private FIsChecked: Boolean; FCheck: TCheckBox; FIsSelected: Boolean; FData: TObject; FIndex : Integer; procedure SetIsChecked(const Value: Boolean); procedure DoCheckClick(Sender: TObject); procedure UpdateCheck; procedure SetIsSelected(const Value: Boolean); function GetIndex: Integer; procedure SetIndex(const Value: Integer); protected function ListBox: TCustomListBox; function ComboBox: TCustomComboBox; procedure ApplyStyle; override; procedure FreeStyle; override; function GetParentComponent: TComponent; override; function EnterChildren(AObject: TControl): Boolean; override; procedure DragEnd; override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; property Data: TObject read FData write FData; property Index: Integer read GetIndex write SetIndex stored False; published property IsChecked: Boolean read FIsChecked write SetIsChecked default False; property IsSelected: Boolean read FIsSelected write SetIsSelected default False; property AutoTranslate default True; property Font; property StyleLookup; property Text; property TextAlign default TTextAlign.taLeading; property WordWrap; end; { TCustomListBox } TListStyle = (lsVertical, lsHorizontal); TOnCompareListBoxItemEvent = procedure(Item1, Item2: TListBoxItem; var Result: Integer) of object; TOnListBoxDragChange = procedure(SourceItem, DestItem: TListBoxItem; var Allow: Boolean) of object; TCustomListBox = class(TScrollBox, IItemsContainer) private type TListBoxStrings = class(TWideStrings) private FListBox: TCustomListBox; protected {$IFDEF FPCCOMP}procedure Put(Index: Integer; const S: string); override;{$ELSE}procedure Put(Index: Integer; const S: WideString); override;{$ENDIF} {$IFDEF FPCCOMP}function Get(Index: Integer): string; override;{$ELSE}function Get(Index: Integer): WideString; override;{$ENDIF} function GetCount: Integer; override; function GetObject(Index: Integer): TObject; override; procedure PutObject(Index: Integer; AObject: TObject); override; procedure SetUpdateState(Updating: Boolean); override; public {$IFDEF FPCCOMP}function Add(const S: string): Integer; override;{$ELSE}function Add(const S: WideString): Integer; override;{$ENDIF} procedure Clear; override; procedure Delete(Index: Integer); override; procedure Exchange(Index1, Index2: Integer); override; {$IFDEF FPCCOMP}function IndexOf(const S: string): Integer; override;{$ELSE}function IndexOf(const S: WideString): Integer; override;{$ENDIF} {$IFDEF FPCCOMP}procedure Insert(Index: Integer; const S: string); override;{$ELSE}procedure Insert(Index: Integer; const S: WideString); override;{$ENDIF} end; private FMouseSelecting: Boolean; FOnChange: TNotifyEvent; FHideSelectionUnfocused: Boolean; FShowCheckboxes: Boolean; FOnChangeCheck: TNotifyEvent; FSorted: Boolean; FOnCompare: TOnCompareListBoxItemEvent; FMultiSelect: Boolean; FAlternatingRowBackground: Boolean; FAllowDrag: Boolean; FDragItem: TListBoxItem; FOnDragChange: TOnListBoxDragChange; function GetCount: Integer; function GetSelected: TListBoxItem; procedure SetColumns(const Value: Integer); procedure SetItemHeight(const Value: Single); procedure SetItemWidth(const Value: Single); procedure SetListStyle(const Value: TListStyle); procedure SetShowCheckboxes(const Value: Boolean); function GetListItem(Index: Integer): TListBoxItem; procedure SetSorted(const Value: Boolean); procedure SetAlternatingRowBackground(const Value: Boolean); procedure SetItems(Value: TWideStrings); procedure SetMultiSelect(const Value: Boolean); procedure SetAllowDrag(const Value: Boolean); { IItemContainer } function GetItemsCount: Integer; function GetItem(const AIndex: Integer): TFmxObject; protected FColumns: Integer; FItemWidth: Single; FItemHeight: Single; FListStyle: TListStyle; FFirstSelect: TListBoxItem; FSelection: TControl; FSelections: TList; FOddFill: TBrush; FItemIndex: Integer; FItems: TWideStrings; function CanObserve(const ID: Integer): Boolean; override; procedure DoChangeCheck(Item: TListBoxItem); dynamic; function CompareItems(Item1, Item2: TListBoxItem): Integer; virtual; procedure Change; dynamic; procedure SortItems; virtual; procedure SetItemIndex(const Value: Integer); virtual; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override; procedure KeyUp(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override; procedure DragOver(const Data: TDragObject; const Point: TPointF; var Accept: Boolean); override; procedure DragDrop(const Data: TDragObject; const Point: TPointF); override; procedure ApplyStyle; override; procedure FreeStyle; override; procedure DoEnter; override; procedure DoExit; override; function GetData: Variant; override; procedure SetData(const Value: Variant); override; function GetContentBounds: TRectF; override; procedure DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); procedure HScrollChange(Sender: TObject); override; procedure VScrollChange(Sender: TObject); override; procedure ContentAddObject(AObject: TFmxObject); override; procedure ContentBeforeRemoveObject(AObject: TFmxObject); override; procedure ContentRemoveObject(AObject: TFmxObject); override; procedure UpdateSelection; property CanFocus default True; property AllowDrag: Boolean read FAllowDrag write SetAllowDrag default False; property AlternatingRowBackground: Boolean read FAlternatingRowBackground write SetAlternatingRowBackground default False; property Columns: Integer read FColumns write SetColumns default 1; property HideSelectionUnfocused: Boolean read FHideSelectionUnfocused write FHideSelectionUnfocused default False; property ItemWidth: Single read FItemWidth write SetItemWidth; property ItemHeight: Single read FItemHeight write SetItemHeight; property ListStyle: TListStyle read FListStyle write SetListStyle default TListStyle.lsVertical; property MultiSelect: Boolean read FMultiSelect write SetMultiSelect default False; property Sorted: Boolean read FSorted write SetSorted default False; property ShowCheckboxes: Boolean read FShowCheckboxes write SetShowCheckboxes default False; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChangeCheck: TNotifyEvent read FOnChangeCheck write FOnChangeCheck; property OnCompare: TOnCompareListBoxItemEvent read FOnCompare write FOnCompare; property OnDragChange: TOnListBoxDragChange read FOnDragChange write FOnDragChange; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Clear; virtual; function DragChange(SourceItem, DestItem: TListBoxItem): Boolean; dynamic; procedure SelectAll; procedure ClearSelection; procedure SelectRange(Item1, Item2: TListBoxItem); function ItemByPoint(const X, Y: Single): TListBoxItem; function ItemByIndex(const Idx: Integer): TListBoxItem; procedure Exchange(Item1, Item2: TListBoxItem); procedure AddObject(AObject: TFmxObject); override; procedure InsertObject(Index: Integer; AObject: TFmxObject); override; procedure RemoveObject(AObject: TFmxObject); override; procedure Sort(Compare: TFmxObjectSortCompare); override; property Count: Integer read GetCount; property Selected: TListBoxItem read GetSelected; property Items: TWideStrings read FItems write SetItems stored False; property ListItems[Index: Integer]: TListBoxItem read GetListItem; property ItemIndex: Integer read FItemIndex write SetItemIndex default -1; end; { TListBox } TListBox = class(TCustomListBox) published property StyleLookup; property AllowDrag; property CanFocus; property DisableFocusEffect; property TabOrder; property AlternatingRowBackground; property Columns; property HideSelectionUnfocused; property Items; property ItemIndex; property ItemWidth; property ItemHeight; property ListStyle; property MultiSelect; property Sorted; property ShowCheckboxes; property BindingSource; property OnChange; property OnChangeCheck; property OnCompare; property OnDragChange; end; { TComboListBox } TComboListBox = class(TCustomListBox) protected FComboBox: TCustomComboBox; procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; function GetObservers: TObservers; override; public constructor Create(AOwner: TComponent); override; end; { TCustomComboBox } TCustomComboBox = class(TStyledControl, IItemsContainer) private FDropDownCount: Integer; FOnChange: TNotifyEvent; FPlacement: TPlacement; procedure SetItemIndex(const Value: Integer); function GetItemIndex: Integer; function GetCount: Integer; procedure SetListBoxResource(const Value: WideString); function GetListBoxResource: WideString; function GetItemHeight: Single; procedure SetItemHeight(const Value: Single); function GetPlacement: TPlacement; function GetPlacementRectangle: TBounds; procedure SetPlacement(const Value: TPlacement); procedure SetPlacementRectangle(const Value: TBounds); procedure UpdateCurrentItem; function GetItems: TWideStrings; function GetListItem(Index: Integer): TListBoxItem; function GetSelected: TListBoxItem; procedure SetItems(const Value: TWideStrings); { IItemContainer } function GetItemsCount: Integer; function GetItem(const AIndex: Integer): TFmxObject; protected FPopup: TPopup; FListBox: TComboListBox; procedure Change; dynamic; function CreateListBox: TComboListBox; virtual; function CanObserve(const ID: Integer): Boolean; override; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure Notification(Component: TComponent; Operation: TOperation); override; procedure ApplyStyle; override; procedure DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); virtual; procedure DoExit; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); override; procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override; property Popup: TPopup read FPopup; property CanFocus default True; property ItemHeight: Single read GetItemHeight write SetItemHeight; property DropDownCount: Integer read FDropDownCount write FDropDownCount default 8; property Placement: TPlacement read GetPlacement write SetPlacement; property PlacementRectangle: TBounds read GetPlacementRectangle write SetPlacementRectangle; property ListBoxResource: WideString read GetListBoxResource write SetListBoxResource; property OnChange: TNotifyEvent read FOnChange write FOnChange; public constructor Create(AOwner: TComponent); override; procedure Realign; override; procedure Clear; virtual; procedure DropDown; virtual; procedure AddObject(AObject: TFmxObject); override; procedure Sort(Compare: TFmxObjectSortCompare); override; property ListBox: TComboListBox read FListBox; property Count: Integer read GetCount; property Selected: TListBoxItem read GetSelected; property Items: TWideStrings read GetItems write SetItems stored False; property ListItems[Index: Integer]: TListBoxItem read GetListItem; property ItemIndex: Integer read GetItemIndex write SetItemIndex; end; { TComboBox } TComboBox = class(TCustomComboBox) public property PlacementRectangle; published property CanFocus; property DisableFocusEffect; property TabOrder; property StyleLookup; property ItemIndex; property ItemHeight; property DropDownCount; property Placement default TPlacement.plBottom; property BindingSource; property ListBoxResource; property OnChange; end; implementation uses Math, SysUtils, FMX_Ani, FMX_Edit; type THackObject = class(TControl); { TListBoxItem } constructor TListBoxItem.Create(AOwner: TComponent); begin inherited; Position.Point := PointF(5000, 5000); TextAlign := TTextAlign.taLeading; FAutoTranslate := True; FText := ''; Height := 19; Width := 19; HitTest := False; SetAcceptsControls(False); end; procedure TListBoxItem.ApplyStyle; var B: TFmxObject; begin inherited; B := FindStyleResource('check'); if (B <> nil) and (B is TCheckBox) then begin FCheck := TCheckBox(B); FCheck.IsChecked := IsChecked; FCheck.OnChange := DoCheckClick; if ListBox <> nil then FCheck.Visible := ListBox.ShowCheckboxes else FCheck.Visible := False; end; if IsSelected then begin StartTriggerAnimation(Self, 'IsSelected'); ApplyTriggerEffect(Self, 'IsSelected'); end; end; procedure TListBoxItem.FreeStyle; begin inherited; FCheck := nil; end; procedure TListBoxItem.DoCheckClick(Sender: TObject); begin if FCheck <> nil then FIsChecked := FCheck.IsChecked; if ListBox <> nil then begin ListBox.SetFocus; ListBox.ItemIndex := Index; ListBox.DoChangeCheck(Self); end; end; function TListBoxItem.ComboBox: TCustomComboBox; var P: TFmxObject; begin P := Parent; while (P <> nil) do begin if P is TCustomComboBox then begin Result := TCustomComboBox(P); Exit; end; P := P.Parent; end; Result := nil; end; function TListBoxItem.ListBox: TCustomListBox; var P: TFmxObject; begin P := Parent; while (P <> nil) do begin if P is TCustomListBox then begin Result := TCustomListBox(P); Exit; end; if P is TCustomComboBox then begin Result := TCustomComboBox(P).FListBox; Exit; end; P := P.Parent; end; Result := nil; end; procedure TListBoxItem.Paint; var R: TRectF; begin if (csDesigning in ComponentState) and not Locked and not FInPaintTo then begin R := LocalRect; InflateRect(R, -0.5, -0.5); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdDash; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.Stroke.Color := $A0909090; Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity); Canvas.StrokeDash := TStrokeDash.sdSolid; end; end; function TListBoxItem.GetIndex: Integer; var I, C : Integer; begin if ListBox <> nil then begin C := 0; for I := 0 to ListBox.Count - 1 do begin if ListBox.ListItems[I] is TListBoxItem then begin if ListBox.ListItems[I] = Self then begin FIndex := I; Result := FIndex; Exit; end; Inc(C); end; end; end; Result := FIndex; end; procedure TListBoxItem.SetIndex(const Value: Integer); var I: Integer; begin FIndex := Value; if ListBox <> nil then begin for I := 0 to ListBox.Count - 1 do if ListBox.ListItems[I] is TListBoxItem then ListBox.ListItems[I].FIndex := -1; ChangeOrder; end; end; function TListBoxItem.GetParentComponent: TComponent; begin if (ComboBox <> nil) then Result := ComboBox else if (ListBox <> nil) then Result := ListBox else Result := inherited GetParentComponent; end; function TListBoxItem.EnterChildren(AObject: TControl): Boolean; begin Result := inherited EnterChildren(AObject); if (ListBox <> nil) then begin if ListBox.MultiSelect then ListBox.ClearSelection; ListBox.ItemIndex := Index; Result := True; end; end; procedure TListBoxItem.UpdateCheck; var i: Integer; begin if (ListBox <> nil) and (FCheck <> nil) then FCheck.Visible := ListBox.ShowCheckboxes; if ChildrenCount > 0 then for i := 0 to ChildrenCount - 1 do if Children[i] is TListBoxItem then TListBoxItem(Children[i]).UpdateCheck; end; procedure TListBoxItem.SetIsChecked(const Value: Boolean); begin if FIsChecked <> Value then begin FIsChecked := Value; if FCheck <> nil then FCheck.IsChecked := FIsChecked; end; end; procedure TListBoxItem.SetIsSelected(const Value: Boolean); begin if FIsSelected <> Value then begin FIsSelected := Value; StartTriggerAnimation(Self, 'IsSelected'); if FIsSelected and (ListBox <> nil) and not(ListBox.MultiSelect) then ListBox.FItemIndex := Index else if not FIsSelected and (ListBox <> nil) and not(ListBox.MultiSelect) and (ListBox.ItemIndex = Index) then ListBox.ItemIndex := -1 else if ListBox <> nil then ListBox.UpdateSelection; end; end; procedure TListBoxItem.DragEnd; begin inherited; DragLeave; if (ListBox <> nil) then ListBox.FDragItem := nil; end; { TListBox } constructor TCustomListBox.Create(AOwner: TComponent); begin inherited; FItems := TListBoxStrings.Create; TListBoxStrings(FItems).FListBox := Self; FOddFill := TBrush.Create(TBrushKind.bkSolid, $20000000); FColumns := 1; FHideSelectionUnfocused := False; FContent.DisableDefaultAlign := True; FItemIndex := -1; CanFocus := True; AutoCapture := True; Width := 100; Height := 100; SetAcceptsControls(False); end; destructor TCustomListBox.Destroy; begin FSelections.Free; FOddFill.Free; FItems.Free; inherited; end; procedure TCustomListBox.Assign(Source: TPersistent); var i: Integer; Item: TListBoxItem; begin if Source is TWideStrings then begin BeginUpdate; try Clear; for i := 0 to TWideStrings(Source).Count - 1 do begin Item := TListBoxItem.Create(Owner); Item.Parent := Self; Item.Text := TWideStrings(Source)[i]; end; finally EndUpdate; end; end else inherited; end; procedure TCustomListBox.HScrollChange(Sender: TObject); begin inherited; UpdateSelection; end; procedure TCustomListBox.VScrollChange(Sender: TObject); begin inherited; UpdateSelection; end; function CompareListItem(Item1, Item2: TFmxObject): Integer; begin if (Item1 is TListBoxItem) and (Item2 is TListBoxItem) and (TListBoxItem(Item1).ListBox <> nil) then Result := TListBoxItem(Item1).ListBox.CompareItems(TListBoxItem(Item1), TListBoxItem(Item2)) else Result := 0; end; procedure TCustomListBox.Sort(Compare: TFmxObjectSortCompare); var I : Integer; Item: TListBoxItem; obj: TFmxObject; begin Item := nil; obj := GetItem(ItemIndex); if obj is TListBoxItem then Item := obj as TListBoxItem; inherited; Sorted := true; if not MultiSelect then begin for I := 0 to Count - 1 do if ItemByIndex(I) is TListBoxItem then ItemByIndex(I).IsSelected := false; // and re-select the previous selected item if Item <> nil then begin Item.IsSelected := true; FItemIndex := Item.Index; end; end; if not (csLoading in ComponentState) then Change; end; procedure TCustomListBox.SortItems; begin if FSorted then FContent.Sort(CompareListItem); end; procedure TCustomListBox.DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); var i: Integer; Item: TListBoxItem; P: TPointF; R: TRectF; begin if (FContent <> nil) and (ContentLayout <> nil) then begin if FAlternatingRowBackground then begin Canvas.Fill.Assign(FOddFill); for i := 0 to (Count - 1) div Columns do begin if Odd(i) then begin if i * Columns > Count - 1 then Item := ItemByIndex(Count - 1) else Item := ItemByIndex(i * Columns); P := Item.LocalToAbsolute(PointF(0, 0)); P := TControl(Sender).AbsoluteToLocal(P); R := RectF(P.X, P.Y, P.X + ContentLayout.Width, P.Y + Item.Height); if not IntersectRect(R, ARect) then Continue; Canvas.FillRect(R, 0, 0, [], AbsoluteOpacity); end; end; end; end; end; procedure TCustomListBox.ApplyStyle; var T: TFmxObject; begin inherited; T := FindStyleResource('content'); if (T <> nil) and (T is TControl) then begin TControl(T).OnPainting := DoContentPaint; end; T := FindStyleResource('selection'); if (T <> nil) and (T is TControl) then begin FSelection := TControl(T); FSelection.Visible := False; UpdateSelection; end; T := FindStyleResource('AlternatingRowBackground'); if (T <> nil) and (T is TBrushObject) then begin FOddFill.Assign(TBrushObject(T).Brush); end; if (T <> nil) and (T is TControl) then begin TControl(T).Visible := False; end; end; procedure TCustomListBox.FreeStyle; begin inherited; FSelection := nil; if FSelections <> nil then FSelections.Clear; end; procedure TCustomListBox.UpdateSelection; var i: Integer; P: TPointF; R: TRectF; Sel: Boolean; SelRects: array of TRectF; Clone: TControl; Vis: Boolean; Item: TListBoxItem; begin if FSelection = nil then Exit; // calc rects Vis := True; Sel := False; SetLength(SelRects, 0); for i := 0 to Count - 1 do begin Item := ItemByIndex(i); if (Item.IsSelected) and IntersectRect(Item.UpdateRect, UpdateRect) then begin P := Item.LocalToAbsolute(PointF(0, 0)); if (FSelection.Parent <> nil) and (FSelection.Parent is TControl) then P := TControl(FSelection.Parent).AbsoluteToLocal(P); R := RectF(P.X, P.Y, P.X + Item.Width, P.Y + Item.Height); if (Length(SelRects) > 0) and (i > 0) and (ItemByIndex(i - 1).IsSelected) then SelRects[High(SelRects)] := UnionRect(R, SelRects[High(SelRects)]) else begin SetLength(SelRects, Length(SelRects) + 1); SelRects[High(SelRects)] := R; end; Sel := True; end; end; // Create selection list if FSelections = nil then FSelections := TList.Create; // create selections if FSelections.Count < Length(SelRects) then for i := FSelections.Count to Length(SelRects) - 1 do begin Clone := TControl(FSelection.Clone(Self)); Clone.StyleName := ''; FSelections.Add(Clone); Clone.Parent := FSelection.Parent; Clone.Stored := False; end; // hide if not need if Length(SelRects) < FSelections.Count then for i := Length(SelRects) to FSelections.Count - 1 do begin TControl(FSelections[i]).Visible := False; TControl(FSelections[i]).DesignVisible := False; end; // Check visible if HideSelectionUnfocused and not IsFocused then Vis := False; // align selections for i := 0 to High(SelRects) do begin TControl(FSelections[i]).Visible := Vis; TControl(FSelections[i]).DesignVisible := Vis; if Vis then TControl(FSelections[i]).BoundsRect := SelRects[i]; end; end; function TCustomListBox.CompareItems(Item1, Item2: TListBoxItem): Integer; begin Result := CompareText(Item1.Text, Item2.Text); if Assigned(FOnCompare) then FOnCompare(Item1, Item2, Result); end; procedure TCustomListBox.ContentAddObject(AObject: TFmxObject); begin inherited; if AObject is TListBoxItem then if FUpdating = 0 then Realign; end; procedure TCustomListBox.ContentBeforeRemoveObject(AObject: TFmxObject); begin inherited; if AObject is TListBoxItem then begin // TListBoxItem.Index can be expensive so check FItemIndex before calling it if (FItemIndex > 0) and (FItemIndex > TListBoxItem(AObject).Index) then begin Dec(FItemIndex); UpdateSelection; end; TListBoxItem(AObject).IsSelected := False; end; end; procedure TCustomListBox.ContentRemoveObject(AObject: TFmxObject); begin inherited; if AObject is TListBoxItem then begin if FUpdating = 0 then Realign; end; end; function TCustomListBox.GetContentBounds: TRectF; var R: TRectF; i, j, Idx: Integer; RowHeight, ColWidth, CurY: Single; begin Result := LocalRect; if FUpdating > 0 then Exit; if ContentLayout = nil then Exit; R := ContentLayout.LocalRect; { FContent } if FContent <> nil then begin { Sort if need } SortItems; { Set Selection } if not MultiSelect and (Selected <> nil) then Selected.IsSelected := True; { Align } case FListStyle of TListStyle.lsVertical: begin { correct items size } if FItemWidth <> 0 then begin FColumns := trunc((R.Right - R.Left) / FItemWidth); if FColumns < 1 then FColumns := 1; if FContent.ChildrenCount > 0 then for i := 0 to (FContent.ChildrenCount - 1) do with TListBoxItem(FContent.Children[i]) do begin if FItemHeight <> 0 then SetBounds(Position.X, Position.Y, FItemWidth, FItemHeight) else SetBounds(Position.X, Position.Y, FItemWidth, Height); end; end; if (FItemWidth = 0) and (FItemHeight <> 0) then begin if FContent.ChildrenCount > 0 then for i := 0 to (FContent.ChildrenCount - 1) do if FContent.Children[i] is TListBoxItem then with TListBoxItem(FContent.Children[i]) do begin SetBounds(Position.X, Position.Y, Width, FItemHeight) end; end; { calc items size } CurY := 0; if FContent.ChildrenCount > 0 then for i := 0 to (FContent.ChildrenCount - 1) div FColumns do begin RowHeight := 0; for j := 0 to FColumns - 1 do begin if (i * FColumns) + j > FContent.ChildrenCount - 1 then Continue; if FContent.Children[(i * FColumns) + j] is TListBoxItem then with TListBoxItem(FContent.Children[(i * FColumns) + j]) do begin if Height + Padding.Top + Padding.Bottom > RowHeight then RowHeight := Height + Padding.Top + Padding.Bottom; end; end; // set correct height for j := 0 to FColumns - 1 do begin if (i * FColumns) + j > FContent.ChildrenCount - 1 then Continue; if FContent.Children[(i * FColumns) + j] is TListBoxItem then with TListBoxItem(FContent.Children[(i * FColumns) + j]) do begin Height := RowHeight - Padding.Top - Padding.Bottom; end; end; CurY := CurY + RowHeight; end; FContent.Height := CurY; { align } CurY := 0; Idx := 0; if FContent.ChildrenCount > 0 then for i := 0 to (FContent.ChildrenCount - 1) div FColumns do begin RowHeight := 0; for j := 0 to FColumns - 1 do begin if (i * FColumns) + j > FContent.ChildrenCount - 1 then Continue; if FItemWidth <> 0 then ColWidth := FItemWidth else ColWidth := (R.Right - R.Left) / FColumns; if FContent.Children[(i * FColumns) + j] is TListBoxItem then with TListBoxItem(FContent.Children[(i * FColumns) + j]) do begin SetBounds(Padding.Left + (j * ColWidth), CurY + Padding.Top, ColWidth - Padding.Left - Padding.Right, Height); if Height + Padding.Top + Padding.Bottom > RowHeight then RowHeight := Height + Padding.Top + Padding.Bottom; Inc(Idx); end; end; CurY := CurY + RowHeight; end; if CurY > 0 then R.Bottom := R.Top + CurY; if FItemWidth <> 0 then R.Right := R.Left + (FItemWidth * FColumns); end; TListStyle.lsHorizontal: begin { correct items size } if FItemHeight <> 0 then begin FColumns := trunc((R.Bottom - R.Top - Padding.Top - Padding.Bottom) / FItemHeight); if FColumns < 1 then FColumns := 1; if FContent.ChildrenCount > 0 then for i := 0 to (FContent.ChildrenCount - 1) do with TListBoxItem(FContent.Children[i]) do begin if FItemWidth <> 0 then SetBounds(Position.X, Position.Y, FItemWidth, FItemHeight) else SetBounds(Position.X, Position.Y, Width, FItemHeight); end; end; if (FItemHeight = 0) and (FItemWidth <> 0) then begin if FContent.ChildrenCount > 0 then for i := 0 to (FContent.ChildrenCount - 1) do with TListBoxItem(FContent.Children[i]) do begin SetBounds(Position.X, Position.Y, FItemWidth, Height) end; end; { calc items size } CurY := 0; if FContent.ChildrenCount > 0 then for i := 0 to (FContent.ChildrenCount - 1) div FColumns do begin ColWidth := 0; if FItemHeight <> 0 then RowHeight := FItemHeight else RowHeight := (R.Bottom - R.Top) / FColumns; for j := 0 to FColumns - 1 do if FContent.Children[(i * FColumns) + j] is TListBoxItem then with TListBoxItem(FContent.Children[(i * FColumns) + j]) do begin if ColWidth < Width + Padding.Left + Padding.Right then ColWidth := Width + Padding.Left + Padding.Right; end; // calc width for j := 0 to FColumns - 1 do if FContent.Children[(i * FColumns) + j] is TListBoxItem then with TListBoxItem(FContent.Children[(i * FColumns) + j]) do begin Width := ColWidth - (Padding.Left + Padding.Right); end; CurY := CurY + ColWidth; end; { selection } if FItemIndex > Count - 1 then FItemIndex := Count - 1; { align } CurY := 0; Idx := 0; if FContent.ChildrenCount > 0 then for i := 0 to (FContent.ChildrenCount - 1) div FColumns do begin ColWidth := 0; if FItemHeight <> 0 then RowHeight := FItemHeight else RowHeight := (R.Bottom - R.Top) / FColumns; for j := 0 to FColumns - 1 do if FContent.Children[(i * FColumns) + j] is TListBoxItem then with TListBoxItem(FContent.Children[(i * FColumns) + j]) do begin if VScrollBar <> nil then SetBounds(CurY + Padding.Left - VScrollBar.Value, Padding.Top + (j * RowHeight), Width, RowHeight - Padding.Top - Padding.Bottom) else SetBounds(CurY + Padding.Left, Padding.Top + (j * RowHeight), Width, RowHeight - Padding.Top - Padding.Bottom); if ColWidth < Width + Padding.Left + Padding.Right then ColWidth := Width + Padding.Left + Padding.Right; Inc(Idx); end; CurY := CurY + ColWidth; end; if CurY > 0 then R.Right := R.Left + CurY; if FItemHeight <> 0 then R.Bottom := R.Top + (FItemHeight * FColumns); end; end; end; UpdateSelection; Result := R; end; function TCustomListBox.GetCount: Integer; var I: Integer; begin Result := 0; if (FContent <> nil) and (FContent.ChildrenCount > 0) then for I := 0 to FContent.ChildrenCount - 1 do if FContent.Children[I] is TListBoxItem then Inc(Result); end; function TCustomListBox.ItemByIndex(const Idx: Integer): TListBoxItem; var I, C: Integer; begin C := 0; if (FContent <> nil) and (FContent.ChildrenCount > 0) then for I := 0 to FContent.ChildrenCount - 1 do if FContent.Children[I] is TListBoxItem then begin if C = Idx then begin Result := TListBoxItem(FContent.Children[I]); Exit; end; Inc(C); end; Result := nil; end; function TCustomListBox.ItemByPoint(const X, Y: Single): TListBoxItem; var i: Integer; P: TPointF; begin P := LocalToAbsolute(PointF(X, Y)); for i := 0 to Count - 1 do with ItemByIndex(i) do begin if not Visible then Continue; if PointInObject(P.X, P.Y) then begin Result := Self.ItemByIndex(i); Exit; end end; Result := nil; end; //calculate the number of visible items of a list function NoVisibleItems(const AHeight: single; const AItemHeight:single; const NoCol: integer): Integer; begin Result:= Trunc(AHeight / AItemHeight) * NoCol; end; procedure TCustomListBox.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); var i: Integer; NoVisItems: Integer; begin if Observers.IsObserving(TObserverMapping.EditLinkID) then if (KeyChar > ' ') or (Key in [vkHome, vkEnd, vkUp, vkDown, vkRight, vkLeft]) then if TLinkObservers.EditLinkIsReadOnly(Observers) then Exit else TLinkObservers.EditLinkEdit(Observers); inherited; if Count > 0 then begin if KeyChar <> #0 then begin for i := 0 to Count - 1 do if (ItemByIndex(I).Text <> '') and (WideLowerCase(ItemByIndex(I).Text[1]) = WideLowerCase(KeyChar)) then begin ItemIndex := i; Break; end; KeyChar := #0; end; case Key of vkHome: ItemIndex := 0; vkEnd: ItemIndex := Count - FColumns; vkUp: If ItemIndex > 0 then begin ItemIndex := ItemIndex - FColumns; if ItemIndex < 0 then ItemIndex := 0; end; vkDown: begin If ItemIndex < Count - 1 then ItemIndex := ItemIndex + FColumns; if ItemIndex > Count - 1 then ItemIndex := Count - 1; end; vkLeft: If ItemIndex > 0 then ItemIndex := ItemIndex - 1; vkRight: If ItemIndex < Count - 1 then ItemIndex := ItemIndex + 1; vkPrior: begin if ItemIndex > 0 then begin //calculate the number of visible items of the List Box NoVisItems:= NoVisibleItems(Height, ItemByIndex(Selected.FIndex).Height, FColumns) ; // updating the index after PageUp key is pressed ItemIndex:= ItemIndex - NoVisItems; end; if ItemIndex < 0 then ItemIndex:= 0; end; vkNext: begin if ItemIndex < Count - 1 then begin //calculate the number of visible items of the List Box NoVisItems:= NoVisibleItems(Height, ItemByIndex(Selected.FIndex).Height, FColumns); //updating the index after PageDown key is pressed ItemIndex:= ItemIndex + NoVisItems; end; if ItemIndex > Count -1 then ItemIndex:= Count - 1; end else Exit; end; TLinkObservers.ListSelectionChanged(Observers); Key := 0; end; end; procedure TCustomListBox.KeyUp(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); begin inherited; end; procedure TCustomListBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var Item: TListBoxItem; begin if Observers.IsObserving(TObserverMapping.EditLinkID) then if TLinkObservers.EditLinkIsReadOnly(Observers) then Exit else TLinkObservers.EditLinkEdit(Observers); inherited; if (Button = TMouseButton.mbLeft) and not MouseTracking then begin Item := ItemByPoint(X, Y); if Item <> nil then begin if MultiSelect then begin {$IFDEF MACOS} if ssCommand in Shift then {$ELSE} if ssCtrl in Shift then {$ENDIF} Item.IsSelected := not Item.IsSelected else if ssShift in Shift then begin SelectRange(Selected, Item); ItemIndex := Item.Index; end else begin SelectRange(Item, Item); ItemIndex := Item.Index; end; FFirstSelect := Item; end else begin if ItemIndex <> Item.Index then ItemIndex := Item.Index else if AllowDrag then Root.BeginInternalDrag(Selected, Item.MakeScreenshot); end; if Assigned(Item.OnClick) then Item.OnClick(Item) end; FMouseSelecting := True; end else if (Button = TMouseButton.mbLeft) and MouseTracking and MultiSelect then begin Item := ItemByPoint(X, Y); if (Item <> nil) then Item.IsSelected := not Item.IsSelected; end; TLinkObservers.ListSelectionChanged(Observers); end; procedure TCustomListBox.MouseMove(Shift: TShiftState; X, Y: Single); var Item: TListBoxItem; begin inherited; if (ssLeft in Shift) and FMouseSelecting then begin Item := ItemByPoint(X, Y); if Item <> nil then begin if Selected = Item then Exit; if Observers.IsObserving(TObserverMapping.EditLinkID) then if TLinkObservers.EditLinkIsReadOnly(Observers) then Exit else TLinkObservers.EditLinkEdit(Observers); if MultiSelect then begin {$IFDEF MACOS} if ssCommand in Shift then {$ELSE} if ssCtrl in Shift then {$ENDIF} Item.IsSelected := not Item.IsSelected else SelectRange(FFirstSelect, Item); ItemIndex := Item.Index; end else ItemIndex := Item.Index; TLinkObservers.ListSelectionChanged(Observers); end; end; end; procedure TCustomListBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var Item: TListBoxItem; begin inherited; FFirstSelect := nil; if MouseTracking and (FLastDelta.X = 0) and (FLastDelta.Y = 0) then begin Item := ItemByPoint(X, Y); if Item <> nil then ItemIndex := Item.Index; end; FMouseSelecting := False; end; function TCustomListBox.CanObserve(const ID: Integer): Boolean; begin Result := False; if ID = TObserverMapping.EditLinkID then Result := True else if ID = TObserverMapping.PositionLinkID then Result := True; end; function TCustomListBox.GetSelected: TListBoxItem; begin Result := ItemByIndex(FItemIndex); end; procedure TCustomListBox.SetItemIndex(const Value: Integer); var Item: TListBoxItem; begin if FItemIndex <> Value then begin Item := ItemByIndex(ItemIndex); FUpdating := FUpdating + 1; try // if not MultiSelect, de-select the previous selected item if (Item <> nil) and (not MultiSelect) then Item.IsSelected := False; // set and get the new list item FItemIndex := Value; Item := ItemByIndex(FItemIndex); if (Item <> nil) and (FContent <> nil) and (FVScrollBar <> nil) and (ContentLayout <> nil) then begin if FContent.Position.Y + Item.Position.Y + Item.Padding.Top + Item.Padding.Bottom + Item.Height > ContentLayout.Position.Y + ContentLayout.Height then VScrollBar.Value := VScrollBar.Value + (FContent.Position.Y + Item.Position.Y + Item.Padding.Top + Item.Padding.Bottom + Item.Height - ContentLayout.Position.Y - ContentLayout.Height); if FContent.Position.Y + Item.Position.Y < ContentLayout.Position.Y then VScrollBar.Value := VScrollBar.Value + FContent.Position.Y + Item.Position.Y - ContentLayout.Position.Y; end; if (Item <> nil) and (FContent <> nil) and (FHScrollBar <> nil) and (ContentLayout <> nil) then begin if FContent.Position.X + Item.Position.X + Item.Padding.Left + Item.Padding.Right + Item.Width > ContentLayout.Position.X + ContentLayout.Width then HScrollBar.Value := HScrollBar.Value + (FContent.Position.X + Item.Position.X + Item.Padding.Left + Item.Padding.Right + Item.Width - ContentLayout.Position.X - ContentLayout.Width); if FContent.Position.X + Item.Position.X < 0 then HScrollBar.Value := HScrollBar.Value + FContent.Position.X + Item.Position.X - ContentLayout.Position.X; end; // select it if (Item <> nil) then Item.IsSelected := True; finally FUpdating := FUpdating - 1; end; if (FUpdating = 0) then begin if Assigned(FBindingObjects) then ToBindingObjects; if not (csLoading in ComponentState) then Change; end; UpdateSelection; end; end; procedure TCustomListBox.SetItems(Value: TWideStrings); begin Items.Assign(Value); end; procedure TCustomListBox.DoChangeCheck(Item: TListBoxItem); begin if Assigned(FOnChangeCheck) then FOnChangeCheck(Item); end; procedure TCustomListBox.Change; begin if Assigned(FOnChange) then FOnChange(ItemByIndex(FItemIndex)); end; procedure TCustomListBox.Clear; var i: Integer; begin BeginUpdate; if FContent <> nil then if FContent.ChildrenCount > 0 then for i := FContent.ChildrenCount - 1 downto 0 do if FContent.Children[i] is TListBoxItem then TFmxObject(FContent.Children[i]).Free; FScrollDesign := PointF(0, 0); EndUpdate; end; procedure TCustomListBox.SelectRange(Item1, Item2: TListBoxItem); var i: Integer; begin if Item1 = nil then Exit; if Item2 = nil then Exit; for i := 0 to Min(Item1.Index, Item2.Index) - 1 do ItemByIndex(i).IsSelected := False; for i := Max(Item1.Index, Item2.Index) + 1 to Count - 1 do ItemByIndex(i).IsSelected := False; for i := Min(Item1.Index, Item2.Index) to Max(Item1.Index, Item2.Index) do ItemByIndex(i).IsSelected := True; end; procedure TCustomListBox.ClearSelection; var i: Integer; begin for i := 0 to Count - 1 do ItemByIndex(i).IsSelected := False; end; procedure TCustomListBox.SelectAll; var i: Integer; begin for i := 0 to Count - 1 do ItemByIndex(i).IsSelected := True; end; function TCustomListBox.GetData: Variant; begin if Selected <> nil then Result := Selected.Text else Result := ''; end; procedure TCustomListBox.SetData(const Value: Variant); begin if Selected <> nil then Selected.Text := Value; end; procedure TCustomListBox.DoEnter; begin inherited; if HideSelectionUnfocused and (Selected <> nil) then UpdateSelection; end; procedure TCustomListBox.DoExit; begin inherited; if HideSelectionUnfocused and (Selected <> nil) then UpdateSelection; if Observers.IsObserving(TObserverMapping.EditLinkID) then if TLinkObservers.EditLinkIsEditing(Observers) then TLinkObservers.EditLinkUpdate(Observers); end; function TCustomListBox.DragChange(SourceItem, DestItem: TListBoxItem): Boolean; begin Result := True; if Assigned(FOnDragChange) then FOnDragChange(SourceItem, DestItem, Result); end; procedure TCustomListBox.DragDrop(const Data: TDragObject; const Point: TPointF); var Obj: TListBoxItem; Allow: Boolean; begin inherited; if FDragItem <> nil then begin FDragItem.DragLeave; FDragItem := nil; end; with AbsoluteToLocal(Point) do Obj := ItemByPoint(X, Y); if (Obj <> nil) and DragChange(TListBoxItem(Data.Source), Obj) then Exchange(TListBoxItem(Data.Source), Obj); end; procedure TCustomListBox.DragOver(const Data: TDragObject; const Point: TPointF; var Accept: Boolean); var Obj: TListBoxItem; begin inherited; with AbsoluteToLocal(Point) do Obj := ItemByPoint(X, Y); if (Obj <> FDragItem) then begin if FDragItem <> nil then FDragItem.DragLeave; FDragItem := Obj; if FDragItem <> nil then begin FDragItem.DragEnter(Data, Point); Accept := True; end else Accept := False; end else Accept := True; if FDragItem = Selected then Accept := False; end; procedure TCustomListBox.Exchange(Item1, Item2: TListBoxItem); begin if Item1.Index = FItemIndex then FItemIndex := Item2.Index else if Item2.Index = FItemIndex then FItemIndex := Item1.Index; FContent.Exchange(Item1, Item2); end; procedure TCustomListBox.AddObject(AObject: TFmxObject); begin if (FContent <> nil) and (AObject is TListBoxItem) then FContent.AddObject(AObject) else inherited; end; procedure TCustomListBox.InsertObject(Index: Integer; AObject: TFmxObject); begin if (FContent <> nil) and (AObject is TListBoxItem) then FContent.InsertObject(Index, AObject) else inherited; end; procedure TCustomListBox.RemoveObject(AObject: TFmxObject); begin if (AObject is TListBoxItem) and (TListBoxItem(AObject).ListBox = Self) then TListBoxItem(AObject).Parent := nil else inherited; end; procedure TCustomListBox.SetColumns(const Value: Integer); begin if FColumns <> Value then begin FColumns := Value; if FColumns < 1 then FColumns := 1; Realign; end; end; procedure TCustomListBox.SetAlternatingRowBackground(const Value: Boolean); begin if FAlternatingRowBackground <> Value then begin FAlternatingRowBackground := Value; Repaint; end; end; procedure TCustomListBox.SetMultiSelect(const Value: Boolean); begin if FMultiSelect <> Value then begin FMultiSelect := Value; if not FMultiSelect then ClearSelection; end; end; procedure TCustomListBox.SetItemHeight(const Value: Single); begin if FItemHeight <> Value then begin FItemHeight := Value; Realign; end; end; procedure TCustomListBox.SetItemWidth(const Value: Single); begin if FItemWidth <> Value then begin FItemWidth := Value; Realign; end; end; procedure TCustomListBox.SetListStyle(const Value: TListStyle); begin if FListStyle <> Value then begin FListStyle := Value; Realign; end; end; procedure TCustomListBox.SetShowCheckboxes(const Value: Boolean); var i: Integer; begin if FShowCheckboxes <> Value then begin FShowCheckboxes := Value; for i := 0 to Count - 1 do if ItemByIndex(i) <> nil then ItemByIndex(i).UpdateCheck; end; end; function TCustomListBox.GetListItem(Index: Integer): TListBoxItem; begin Result := ItemByIndex(Index); end; procedure TCustomListBox.SetSorted(const Value: Boolean); begin if FSorted <> Value then begin FSorted := Value; SortItems; Realign; end; end; procedure TCustomListBox.SetAllowDrag(const Value: Boolean); begin if FAllowDrag <> Value then begin FAllowDrag := Value; if FAllowDrag then EnableDragHighlight := True; end; end; function TCustomListBox.GetItem(const AIndex: Integer): TFmxObject; begin Result := ItemByIndex(AIndex); end; function TCustomListBox.GetItemsCount: Integer; begin Result := Count; end; { TComboListBox } constructor TComboListBox.Create(AOwner: TComponent); begin inherited; if AOwner is TCustomComboBox then FComboBox := TCustomComboBox(AOwner); HideSelectionUnfocused := False; end; function TComboListBox.GetObservers: TObservers; begin if FComboBox <> nil then Result := FComboBox.Observers else Result := inherited; end; procedure TComboListBox.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); begin inherited; if Key = vkReturn then begin if (Parent is TPopup) and TPopup(Parent).IsOpen and (FComboBox <> nil) then begin FComboBox.ItemIndex := ItemIndex; TPopup(Parent).IsOpen := False; end; end; end; procedure TComboListBox.MouseMove(Shift: TShiftState; X, Y: Single); var Item: TListBoxItem; begin inherited; //if (Shift <> [ssLeft]) then begin Item := ItemByPoint(X, Y); if Item <> nil then begin if Selected = Item then Exit; if Observers.IsObserving(TObserverMapping.EditLinkID) then if TLinkObservers.EditLinkIsReadOnly(Observers) then Exit else if not TLinkObservers.EditLinkEdit(Observers) then Exit; if MultiSelect then begin {$IFDEF MACOS} if ssCommand in Shift then {$ELSE} if ssCtrl in Shift then {$ENDIF} Item.IsSelected := not Item.IsSelected else SelectRange(FFirstSelect, Item); ItemIndex := Item.Index; end else ItemIndex := Item.Index; FComboBox.Repaint; end; end; end; procedure TComboListBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; if (Parent is TPopup) and TPopup(Parent).IsOpen and (FComboBox <> nil) then begin if PointInRect(PointF(X, Y), LocalRect) and (ItemByPoint(X, Y) <> nil) then if Observers.IsObserving(TObserverMapping.EditLinkID) then begin if TLinkObservers.EditLinkIsEditing(Observers) then FComboBox.ItemIndex := ItemByPoint(X, Y).Index; end else FComboBox.ItemIndex := ItemByPoint(X, Y).Index; TPopup(Parent).IsOpen := False; end; end; { TComboBox } constructor TCustomComboBox.Create(AOwner: TComponent); begin inherited; DropDownCount := 8; CanFocus := True; FPopup := TPopup.Create(Self); FPopup.PlacementTarget := Self; FPopup.StaysOpen := False; FPopup.Stored := False; FPopup.Parent := Self; FPopup.Locked := True; FPopup.DesignVisible := False; FPopup.DragWithParent := True; FListBox := CreateListBox; FListBox.Parent := Popup; FListBox.Stored := False; FListBox.Align := TAlignLayout.alClient; FListBox.ShowCheckboxes := False; Width := 100; Height := 22; SetAcceptsControls(False); end; function TCustomComboBox.CreateListBox: TComboListBox; begin Result := TComboListBox.Create(Self); end; function TCustomComboBox.CanObserve(const ID: Integer): Boolean; begin Result := FListBox.CanObserve(ID); end; procedure TCustomComboBox.ApplyStyle; var T: TFmxObject; begin inherited; T := FindStyleResource('Content'); if (T <> nil) and (T is TContent) then begin TContent(T).OnPaint := DoContentPaint; UpdateCurrentItem; end; end; procedure TCustomComboBox.Realign; begin inherited; if FDisableAlign then Exit; FDisableAlign := True; { FContent } if FPopup <> nil then FPopup.Width := Width; FDisableAlign := False; end; procedure TCustomComboBox.UpdateCurrentItem; var C: TFmxObject; Item: TListBoxItem; NewHeight: Single; begin if (FListBox = nil) then Exit; Item := FListBox.ItemByIndex(FListBox.ItemIndex); if Item <> nil then begin C := FindStyleResource('Content'); if (C <> nil) and (C is TControl) then begin if Item.Height <> 0 then NewHeight := Item.Height else if ItemHeight = 0 then NewHeight := TControl(C).Height else NewHeight := ItemHeight; Item.SetBounds(Item.Position.X, Item.Position.Y, Item.Width, NewHeight); Item.ApplyStyleLookup; end; end; end; procedure TCustomComboBox.DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); var SOpacity: Single; Item: TListBoxItem; SaveSize: TPointF; SaveScene: IScene; begin if FListBox <> nil then begin Item := FListBox.ItemByIndex(FListBox.ItemIndex); if Item <> nil then begin SOpacity := Item.FAbsoluteOpacity; SaveSize := PointF(Item.Width, Item.Height); SaveScene := Item.Scene; Item.SetNewScene(Scene); try THackObject(Item).FWidth := ARect.Width; THackObject(Item).FLastWidth := ARect.Width; THackObject(Item).FHeight := ARect.Height; THackObject(Item).FLastHeight := ARect.Height; Item.FAbsoluteOpacity := Opacity; Item.RecalcOpacity; Item.Realign; Item.FRecalcOpacity := False; Item.PaintTo(Canvas, ARect, Sender as TFmxObject); Item.FAbsoluteOpacity := SOpacity; Item.RecalcOpacity; // Do not assign directly to FHeight/FWidth, because // children sizes have to be updated after Realign Item.Height := SaveSize.Y; Item.Width := SaveSize.X; THackObject(Item).FLastWidth := SaveSize.X; THackObject(Item).FLastHeight := SaveSize.Y; finally Item.SetNewScene(SaveScene); end; end; end; end; procedure TCustomComboBox.DoExit; begin inherited; if Observers.IsObserving(TObserverMapping.EditLinkID) then if TLinkObservers.EditLinkIsEditing(Observers) then TLinkObservers.EditLinkUpdate(Observers); end; procedure TCustomComboBox.DropDown; var H, BorderHeight: single; Num, Count, i: Integer; Item: TListBoxItem; procedure UpdateItem(Index: Integer); var C: TFmxObject; Item: TListBoxItem; NewHeight: Single; begin if (FListBox = nil) then Exit; Item := FListBox.ItemByIndex(FListBox.ItemIndex); if Item <> nil then begin C := FindStyleResource('Content'); if (C <> nil) and (C is TControl) then begin if Item.Height <> 0 then NewHeight := Item.Height else if ItemHeight = 0 then NewHeight := TControl(C).Height else NewHeight := ItemHeight; Item.SetBounds(Item.Position.X, Item.Position.Y, Item.Width, NewHeight); Item.ApplyStyleLookup; end; end; end; begin if not FPopup.IsOpen then begin FPopup.Width := Width; // Resize list items to match the dimensions of the control if FListbox <> nil then begin for i := 0 to FListbox.Count - 1 do UpdateItem(i); end; // calc content rect FListbox.ApplyStyleLookup; FListbox.GetContentBounds; BorderHeight := (FListbox.Height - FListbox.AbsoluteToLocal(FListbox.ContentLayout.LocalToAbsolute(PointF(0, FListbox.ContentLayout.Height))).Y) + FListbox.AbsoluteToLocal(FListbox.ContentLayout.LocalToAbsolute(PointF(0, 0))).Y; // Count := DropDownCount; if FListBox.Count < Count then Count := FListBox.Count; if FListBox.ItemHeight > 0 then FPopup.Height := (Count * FListBox.ItemHeight) + BorderHeight else begin if Count < DropDownCount then FPopup.Height := FListbox.FContent.Height + BorderHeight else begin H := 0; Num := 0; for i := 0 to FListbox.Count - 1 do begin Item := FListbox.ListItems[i]; if Item.Position.Y >= 0 then begin H := H + Item.Height; Num := Num + 1; end; if Num >= Count then Break; end; FPopup.Height := H + BorderHeight; end; end; FPopup.IsOpen := True; if FPopup.IsOpen then FListBox.SetFocus; end else FPopup.IsOpen := False; end; procedure TCustomComboBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; if Button = TMouseButton.mbLeft then DropDown; end; procedure TCustomComboBox.MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); begin inherited; if WheelDelta < 0 then begin if ItemIndex < Count - 1 then ItemIndex := ItemIndex + 1 end else begin if ItemIndex > 0 then ItemIndex := ItemIndex - 1; end; Handled := True; end; procedure TCustomComboBox.Notification(Component: TComponent; Operation: TOperation); begin inherited Notification(Component, Operation); if (Operation = opRemove) and (FListBox = Component) then FListBox := nil; end; procedure TCustomComboBox.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); var i: Integer; NoVisItems: Integer; begin if Observers.IsObserving(TObserverMapping.EditLinkID) then if (KeyChar > ' ') or (Key in [vkHome, vkEnd, vkUp, vkDown, vkRight, vkLeft]) then if TLinkObservers.EditLinkIsReadOnly(Observers) then Exit else TLinkObservers.EditLinkEdit(Observers); inherited; if Count > 0 then begin if KeyChar <> #0 then begin for i := 0 to Count - 1 do if (FListBox.ListItems[i].Text <> '') and (WideLowerCase(FListBox.ListItems[i].Text[1]) = WideLowerCase(KeyChar)) then begin ItemIndex := i; Break; end; KeyChar := #0; end; case Key of vkHome: ItemIndex := 0; vkEnd: ItemIndex := Count - 1; vkUp: If ItemIndex > 0 then begin ItemIndex := ItemIndex - 1; if ItemIndex < 0 then ItemIndex := 0; end; vkDown: begin if ssAlt in Shift then begin DropDown; end else begin If ItemIndex < Count - 1 then ItemIndex := ItemIndex + 1; if ItemIndex > Count - 1 then ItemIndex := Count - 1; end; end; vkLeft: If ItemIndex > 0 then ItemIndex := ItemIndex - 1; vkRight: If ItemIndex < Count - 1 then ItemIndex := ItemIndex + 1; vkF4: DropDown; vkPrior: begin if ItemIndex > 0 then begin //calculate the number of visible items of the List Box NoVisItems:= DropDownCount; // updating the index after PageUp key is pressed ItemIndex:= ItemIndex - NoVisItems; end; if ItemIndex < 0 then ItemIndex:= 0; end; vkNext: begin if ItemIndex < Count - 1 then begin //calculate the number of visible items of the List Box NoVisItems:= DropDownCount; //updating the index after PageDown key is pressed ItemIndex:= ItemIndex + NoVisItems; end; if ItemIndex > Count -1 then ItemIndex:= Count - 1; end else Exit; end; TLinkObservers.ListSelectionChanged(Observers); Key := 0; end; end; procedure TCustomComboBox.Change; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomComboBox.Clear; begin if FListBox <> nil then FListBox.Clear; end; procedure TCustomComboBox.AddObject(AObject: TFmxObject); begin if (FListBox <> nil) and ((AObject is TListBoxItem)) then begin FListBox.AddObject(AObject); end else inherited; end; function TCustomComboBox.GetItemIndex: Integer; begin if FListBox <> nil then Result := FListBox.ItemIndex else Result := -1; end; function TCustomComboBox.GetCount: Integer; begin if FListBox <> nil then Result := FListBox.Count else Result := 0; end; procedure TCustomComboBox.SetItemIndex(const Value: Integer); begin if FListBox <> nil then begin FListBox.ItemIndex := Value; if Assigned(FBindingObjects) then ToBindingObjects; if not (csLoading in ComponentState) then Change; UpdateCurrentItem; if (FResourceLink <> nil) and (FResourceLink is TControl) then TControl(FResourceLink).UpdateEffects; Repaint; end; end; procedure TCustomComboBox.SetItems(const Value: TWideStrings); begin FListBox.Items.Assign(Value); end; procedure TCustomComboBox.GetChildren(Proc: TGetChildProc; Root: TComponent); var j: Integer; begin inherited; if (FListBox <> nil) and (FListBox.FContent <> nil) then if (FListBox.FContent.ChildrenCount > 0) then begin for j := 0 to FListBox.FContent.ChildrenCount - 1 do if FListBox.FContent.Children[j].Stored then Proc(TComponent(FListBox.FContent.Children[j])); end; end; function TCustomComboBox.GetListBoxResource: WideString; begin Result := FListBox.StyleLookup; end; function TCustomComboBox.GetListItem(Index: Integer): TListBoxItem; begin Result := FListBox.ListItems[Index]; end; function TCustomComboBox.GetPlacement: TPlacement; begin Result := FPopup.Placement; end; function TCustomComboBox.GetPlacementRectangle: TBounds; begin Result := FPopup.PlacementRectangle; end; function TCustomComboBox.GetSelected: TListBoxItem; begin Result := FListBox.Selected; end; procedure TCustomComboBox.SetListBoxResource(const Value: WideString); begin FListBox.StyleLookup := Value; end; procedure TCustomComboBox.SetPlacement(const Value: TPlacement); begin FPopup.Placement := Value; end; procedure TCustomComboBox.SetPlacementRectangle(const Value: TBounds); begin FPopup.PlacementRectangle := Value; end; procedure TCustomComboBox.Sort(Compare: TFmxObjectSortCompare); var Item: TListBoxItem; obj: TFmxObject; I : Integer; begin if FListBox <> nil then begin Item := nil; obj := GetItem(FListBox.ItemIndex); if obj is TListBoxItem then Item := obj as TListBoxItem; FListBox.Sort(Compare); FListBox.Sorted := true; // deselect all items if not MultiSelect if not FListBox.MultiSelect then begin for I := 0 to FListBox.Count - 1 do if ListBox.ListItems[I] is TListBoxItem then ListBox.ListItems[I].IsSelected := false; // and re-select the previous selected item if Item <> nil then Item.IsSelected := true; end; if not (csLoading in ComponentState) then Change; end; end; function TCustomComboBox.GetItems: TWideStrings; begin Result := FListBox.Items; end; function TCustomComboBox.GetItemsCount: Integer; begin Result := Count; end; function TCustomComboBox.GetItem(const AIndex: Integer): TFmxObject; begin Result := FListBox.ListItems[AIndex]; end; function TCustomComboBox.GetItemHeight: Single; begin Result := FListBox.ItemHeight; end; procedure TCustomComboBox.SetItemHeight(const Value: Single); begin if FListBox.ItemHeight <> Value then begin FListBox.ItemHeight := Value; UpdateCurrentItem; end; end; { TCustomListBox.TListBoxStrings } function TCustomListBox.TListBoxStrings{$IFDEF FPCCOMP}.Add(const S: string): Integer;{$ELSE}.Add(const S: WideString): Integer;{$ENDIF} var Item: TListBoxItem; begin Item := TListBoxItem.Create(FListBox); try Item.Text := S; Result := FListBox.Count; FListBox.AddObject(Item); if (FListBox.Parent <> nil) and (FListBox.Parent is TPopup) and (FListBox.Parent.Parent is TComboEdit) then TComboEdit(FListBox.Parent.Parent).Items.Add(S); except Item.Free; raise; end; end; procedure TCustomListBox.TListBoxStrings.Clear; var I: Integer; Item: TListBoxItem; begin if not (csDestroying in FListBox.ComponentState) then for I := FListBox.Count - 1 downto 0 do begin Item := FListBox.ListItems[I]; FListBox.RemoveObject(Item); Item.Free; end; end; procedure TCustomListBox.TListBoxStrings.Delete(Index: Integer); var Item: TListBoxItem; begin Item := FListBox.ListItems[Index]; FListBox.RemoveObject(Item); Item.Free; end; procedure TCustomListBox.TListBoxStrings.Exchange(Index1, Index2: Integer); begin with FListBox do Exchange(ItemByIndex(Index1), ItemByIndex(Index2)); end; function TCustomListBox.TListBoxStrings{$IFDEF FPCCOMP}.Get(Index: Integer): string;{$ELSE}.Get(Index: Integer): WideString;{$ENDIF} begin Result := FListBox.ListItems[Index].Text; end; function TCustomListBox.TListBoxStrings.GetCount: Integer; begin Result := FListBox.Count; end; function TCustomListBox.TListBoxStrings.GetObject(Index: Integer): TObject; begin Result := FListBox.ListItems[Index].Data; end; function TCustomListBox.TListBoxStrings{$IFDEF FPCCOMP}.IndexOf(const S: string): Integer;{$ELSE}.IndexOf(const S: WideString): Integer;{$ENDIF} var I: Integer; begin for I := 0 to FListBox.Count - 1 do if SameText(FListBox.ListItems[I].Text, S) then Exit(I); Result := -1; end; procedure TCustomListBox.TListBoxStrings{$IFDEF FPCCOMP}.Insert(Index: Integer; const S: string);{$ELSE}.Insert(Index: Integer; const S: WideString);{$ENDIF} var Item: TListBoxItem; begin Item := TListBoxItem.Create(FListBox); try Item.Text := S; FListBox.InsertObject(Index, Item); except Item.Free; raise; end; end; procedure TCustomListBox.TListBoxStrings{$IFDEF FPCCOMP}.Put(Index: Integer; const S: string);{$ELSE}.Put(Index: Integer; const S: WideString);{$ENDIF} begin FListBox.ListItems[Index].Text := S; end; procedure TCustomListBox.TListBoxStrings.PutObject(Index: Integer; AObject: TObject); begin FListBox.ListItems[Index].Data := AObject; end; procedure TCustomListBox.TListBoxStrings.SetUpdateState(Updating: Boolean); begin if Updating then FListBox.BeginUpdate else FListBox.EndUpdate; end; initialization RegisterFmxClasses([TCustomListBox, TCustomComboBox, TListBoxItem, TListBox, TComboBox]); end.
unit CSCClient; interface uses Classes, Consts, Controls, Dialogs, Windows, Forms, Math, ExtCtrls, SysUtils, Messages, SyncObjs, CSCBase, CSCQueue, CSCTimer, CSCCustomBase, ScktComp; type TCSCClient = class( TCSCCustomCommBase ) protected FIPPort : TClientSocket; FSndRcv : TCSCSenderReceiver; FConnected : Boolean; FBusy : Boolean; FBuffer : PByteArray; FSndBuffer : PnmHeader; FReplyTimer : TCSCTimer; FBufPos : Integer; FBufMaxPos : Integer; FAckMsg : TnmHeader; FAckReceived : Boolean; FOnConnect : TNotifyEvent; FOnDisconnect : TNotifyEvent; FAutoReconnect : Boolean; FRetryConnection: Boolean; FAlreadyConn : Boolean; FUserDisconnect : Boolean; FTryReconnect : Boolean; FReconnTimer : TTimer; FServerOffLine : Boolean; FConnErrorStr : String; FWinsockError : Integer; FSockHWND : HWND; FConnecting : Boolean; FTicksLastCom : Cardinal; protected procedure HandleAppException(Sender: TObject; E: Exception); procedure SetConnected(Value : Boolean); function WaitForAckReply : Word; function WaitForReply : Word; function GetAddress: String; function GetHost: String; function GetPort: Integer; procedure SetPort(Value: Integer); procedure SetAddress(Value: String); procedure SetHost(Value: String); procedure OnReconnTimer(Sender: TObject); procedure OnSckConnect(Sender: TObject; Socket: TCustomWinSocket); procedure OnRead(Sender: TObject; Socket: TCustomWinSocket); procedure OnWrite(Sender: TObject; Socket: TCustomWinSocket); procedure OnSckDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure OnError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); procedure OnMsgReceived(Socket: TCustomWinSocket; Data: Pointer; DataLen: Integer); procedure SocketConnected; virtual; procedure SocketDisconnected; virtual; procedure SendACK; procedure TryReconnect; procedure Reconnect; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property TicksLastCom: Cardinal read FTicksLastCom; procedure MsgReceived(aClientSck: TCustomWinSocket; aMsg: PnmHeader); override; procedure SendFilePacket(aClientSck: TCustomWinSocket; aFFP: PCSCnmFirstFilePacket; aFP : TCSCnmFilePacket; aFS : TFileStream); override; procedure SendMsg(aMsg : longint; aEvent : Boolean; aClient : TCustomWinSocket; aData : pointer; aDataLen : LongInt; aDataType : TNetMsgDataType; aErrorCode : Word); override; function UploadFile(SourceFN, DestFN, Info: String; var UserInfo; UserInfoSize: Integer): Word; function DownloadFile(SourceFN, DestFN, Info: String; var UserInfo; UserInfoSize: Integer): Word; procedure ProcessSocketMessages; procedure ProcessAllMessages; function RequestData(aMsg : longint; aRequest : pointer; aReqLen : LongInt; aReqType : TNetMsgDataType; aReply : pointer; aRpyLen : LongInt; aRpyType : TNetMsgDataType) : Word; procedure ConnectAndWait; property Connected : Boolean read FConnected write SetConnected; property WinsockError: Integer read FWinsockError; property IPPort: TClientSocket read FIPPort; published property Address: String read GetAddress write SetAddress; property Host: String read GetHost write SetHost; property Port: Integer read GetPort write SetPort; property AutoReconnect: Boolean read FAutoReconnect write FAutoReconnect; property RetryConnection: Boolean read FRetryConnection write FRetryConnection; property OnConnect: TNotifyEvent read FOnConnect write FOnConnect; property OnDisconnect: TNotifyEvent read FOnDisconnect write FOnDisconnect; end; TemClient = record fCli : TCSCClient; fThreadID : Cardinal; end; PemClient = ^TemClient; TCSCExceptionManager = class private FThreads : TList; FCS : TCriticalSection; FSaveAppEH : TExceptionEvent; function GetByThread: PemClient; procedure HandleAppException(Sender: TObject; E: Exception); public constructor Create; destructor Destroy; override; function Count: Integer; procedure Add(aCli: TCSCClient); procedure Remove(aCli: TCSCClient); end; var ExceptionMgr : TCSCExceptionManager; Reply_Timeout : Integer = 23000; implementation const CM_EXECPROC = $8FFF; {===TCSCClient=========================================} function TCSCClient.GetPort: Integer; begin Result := FIPPort.Port; end; procedure TCSCClient.SetPort(Value: Integer); begin FIPPort.Port := Value; end; function TCSCClient.GetAddress: String; begin Result := FIPPort.Address; end; function TCSCClient.GetHost: String; begin Result := FIPPort.Host; end; procedure TCSCClient.SetAddress(Value: String); begin FIPPort.Address := Value; end; procedure TCSCClient.SetHost(Value: String); begin FIPPort.Host := Value; end; procedure TCSCClient.ProcessAllMessages; var Msg : TMsg; begin while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin TranslateMessage(Msg); DispatchMessage(Msg); end; end; procedure TCSCClient.ProcessSocketMessages; var Msg : TMsg; begin while PeekMessage(Msg, FSockHWND, 0, 0, PM_REMOVE) do begin TranslateMessage(Msg); DispatchMessage(Msg); end; while PeekMessage(Msg, NotifyHandle, cscm_FileEventReceived, cscm_FileEventReceived, PM_REMOVE) do DispatchMessage(Msg); end; function TCSCClient.WaitForReply : Word; begin {wait for data or timeout, whichever occurs first} SetTimer(FReplyTimer, Reply_Timeout); while FMsgQueue.IsEmpty and (not HasTimerExpired(FReplyTimer)) and FConnected do ProcessSocketMessages; if not FConnected or FMsgQueue.IsEmpty then begin Connected := False; Result := CSCErr_ServerCommLost; Exit; end; {otherwise, everything's OK} Result := CSCERR_NONE; end; procedure TCSCClient.SetConnected(Value : Boolean); begin try if not Value then begin FUserDisconnect := True; FIPPort.Socket.Close; FIPPort.Close; end; except end; if FConnected=Value then Exit; FTryReconnect := False; if Value then begin { if FRetryConnection then begin FTryReconnect := True; TryReconnect; end else begin } FUserDisconnect := False; FIPPort.Socket.Close; FIPPort.Open; { end; } end else begin FUserDisconnect := True; FIPPort.Socket.Close; FIPPort.Close; end; end; constructor TCSCClient.Create(AOwner: TComponent); begin inherited; FConnecting := False; FTicksLastCom := 0; FAutoReconnect := False; FRetryConnection := False; FAlreadyConn := False; FUserDisconnect := False; FTryReconnect := False; FConnected := False; FIsServer := False; FAckReceived := False; FAckMsg.nmhEvent := True; FAckMsg.nmhMsgID := cscnmAck; FAckMsg.nmhFirst := True; FAckMsg.nmhLast := True; FAckMsg.nmhErrorCode := 0; FAckMsg.nmhMsgLen := NetMsgHeaderSize; FAckMsg.nmhTotalSize := 0; FBusy := False; FBufPos := 0; FReconnTimer := TTimer.Create(nil); FReconnTimer.Interval := 10000; FReconnTimer.Enabled := False; FReconnTimer.OnTimer := OnReconnTimer; GetMem(FBuffer, MaxNetMsgSize); FSndBuffer := PnmHeader(FBuffer); FIPPort := TClientSocket.Create(nil); FSndRcv := TCSCSenderReceiver.Create(FIPPort.Socket); FIPPort.ClientType := ctNonBlocking; FSockHWND := FIPPort.Socket.Handle; FIPPort.OnConnect := OnSckConnect; FIPPort.OnRead := OnRead; FIPPort.OnWrite := OnWrite; FIPPort.OnDisconnect := OnSckDisconnect; FIPPort.OnError := OnError; FSndRcv.OnMsgReceived := OnMsgReceived; FOnConnect := nil; FOnDisconnect := nil; end; {--------} destructor TCSCClient.Destroy; begin FReconnTimer.Free; FTryReconnect := False; FIPPort.Close; FSndRcv.Free; FIPPort.Free; FreeMem(FBuffer, MaxNetMsgSize); inherited Destroy; end; {--------} procedure TCSCClient.OnSckDisconnect(Sender: TObject; Socket: TCustomWinSocket); begin if FConnected then begin FConnected := False; FMsgQueue.DeleteSocketMessages(nil); SocketDisconnected; if Assigned(FOnDisconnect) then FOnDisconnect(Self); Reconnect; end else FConnected := False; end; {--------} procedure TCSCClient.OnError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); begin FWinsockError := ErrorCode; if FConnecting then begin ErrorCode := 0; FConnErrorStr := 'Socket error'; end else if ErrorCode = 10053 then begin OnSckDisconnect(Sender, Socket); ErrorCode := 0; Reconnect; end else if FTryReconnect and (ErrorCode=10061) then begin ErrorCode := 0; FServerOffLine := True; end; end; {--------} procedure TCSCClient.OnSckConnect(Sender: TObject; Socket: TCustomWinSocket); begin FConnected := True; FAlreadyConn := True; FTryReconnect := False; SocketConnected; if Assigned(FOnConnect) then FOnConnect(Self); end; procedure TCSCClient.MsgReceived(aClientSck: TCustomWinSocket; aMsg: PnmHeader); begin with aMsg^ do if nmhMsgID = cscnmAck then FAckReceived := True else if not nmhLast then SendAck; end; procedure TCSCClient.SocketConnected; begin end; procedure TCSCClient.SocketDisconnected; begin end; procedure TCSCClient.OnMsgReceived(Socket: TCustomWinSocket; Data: Pointer; DataLen: Integer); begin FMsgQueue.AddPacket(Data, nil, DataLen); end; procedure TCSCClient.OnRead(Sender: TObject; Socket: TCustomWinSocket); begin FSndRcv.Read; end; procedure TCSCClient.OnWrite(Sender: TObject; Socket: TCustomWinSocket); begin FSndRcv.Write; end; {--------} function TCSCClient.WaitForAckReply : Word; begin {wait for data or timeout, whichever occurs first} FAckReceived := False; SetTimer(FReplyTimer, Reply_Timeout); while not FAckReceived and (not HasTimerExpired(FReplyTimer)) and FConnected do ProcessSocketMessages; {do we still have a connection?} if not FConnected or (not FAckReceived) then begin Connected := False; Result := CSCERR_ServerCommLost; Exit; end; {otherwise, everything's hunky dory} Result := CSCErr_None; end; procedure TCSCClient.SendACK; var BytesSent: integer; begin FSndRcv.Send(PByteArray(@FAckMsg), NetMsgHeaderSize, 0, BytesSent); end; procedure TCSCClient.OnReconnTimer(Sender: TObject); begin FReconnTimer.Enabled := False; if not FTryReconnect then Exit; TryReconnect; end; procedure TCSCClient.TryReconnect; begin FUserDisconnect := False; try FServerOffLine := False; FIPPort.Socket.Close; FIPPort.Open; while FTryReconnect and (not FServerOffLine) do begin FServerOffLine := False; ProcessAllMessages; Sleep(5); end; if FServerOffLine then FReconnTimer.Enabled := True; except FReconnTimer.Enabled := True; end; end; procedure TCSCClient.Reconnect; begin if FUserDisconnect or (not FAutoReconnect) or (not FAlreadyConn) then Exit; FTryReconnect := True; FReconnTimer.Enabled := True; end; function TCSCClient.UploadFile(SourceFN, DestFN, Info: String; var UserInfo; UserInfoSize: Integer): Word; begin if DestFN = '' then DestFN := SourceFN; Result := MsgQueue.TransmitFile(nil, SourceFN, DestFN, '', UserInfo, UserInfoSize, 0); { if Result = 0 then begin Result := WaitForReply; if Result = 0 then begin Result := MsgQueue.Examine^.dmErrorCode; MsgQueue.Pop; end; end;} if Result <> 0 then Raise ECSError.Create(Result); end; function TCSCClient.DownloadFile(SourceFN, DestFN, Info: String; var UserInfo; UserInfoSize: Integer): Word; var Request: TCSCnmGetFileReq; begin Result := 0; if DestFN = '' then DestFN := SourceFN; with Request do begin StrECopy(nmSourceFN, PChar(SourceFN)); StrECopy(nmDestFN, PChar(DestFN)); StrECopy(nmFileInfo, PChar(Info)); if UserInfoSize > SizeOf(nmUserInfo) then Move(UserInfo, nmUserInfo, SizeOf(nmUserInfo)) else Move(UserInfo, nmUserInfo, UserInfoSize); SendMsg(CSCnmGetFileReq, True, nil, @Request, SizeOf(Request), nmdByteArray, 0); Result := WaitForReply; if Result = 0 then begin Result := MsgQueue.Examine^.dmErrorCode; MsgQueue.Pop; end; end; end; procedure TCSCClient.SendFilePacket(aClientSck: TCustomWinSocket; aFFP: PCSCnmFirstFilePacket; aFP: TCSCnmFilePacket; aFS: TFileStream); var S : TMemoryStream; MsgID, FPLen, HeaderLen: Integer; begin S := TMemoryStream.Create; try HeaderLen := 0; if aFFP<>nil then begin HeaderLen := SizeOf(TCSCnmFirstFilePacket); S.WriteBuffer(aFFP^, HeaderLen); MsgID := CSCnmFirstFilePacket; end else MsgID := CSCnmFilePacket; HeaderLen := HeaderLen + SizeOf(aFP); FPLen := MaxNetMsgSize-NetMsgHeaderSize-HeaderLen-1; if FPLen > (aFP.nmFileSize - aFS.Position) then begin FPLen := aFP.nmFileSize - aFS.Position; aFP.nmLast := True; end else aFP.nmLast := False; S.WriteBuffer(aFP, SizeOf(aFP)); S.CopyFrom(aFS, FPLen); SendMsg(MsgID, True, aClientSck, Pointer(S), S.Size, nmdStream, 0); finally S.Free; end; end; procedure TCSCClient.SendMsg(aMsg : longint; aEvent : Boolean; aClient : TCustomWinSocket; aData : pointer; aDataLen : LongInt; aDataType : TNetMsgDataType; aErrorCode : Word); var DataAsStream : TStream absolute aData; DataAsBytes : PByteArray absolute aData; TotalDataLen : longint; BytesToGo : longint; BytesToSend : longint; BytesSent : longint; StartOfs : longint; FirstMsg : boolean; LastMsg : boolean; begin {check for reentrancy} StartOfs := 0; TotalDataLen := aDataLen; {we're just about to send the first message of (maybe) many} FirstMsg := true; {send the message} {..initialize loop variables} BytesToGo := TotalDataLen; if (aDataType = nmdByteArray) then StartOfs := 0 else if aDataLen > 0 then DataAsStream.Position := 0; {..send data in reasonably sized chunks} repeat {..set up the invariant parts of the message header} with FSndBuffer^ do begin nmhMsgID := aMsg; nmhEvent := aEvent; nmhTotalSize := TotalDataLen; nmhErrorCode := aErrorCode; nmhDataType := aDataType; end; {calculate the size of data in this message packet} BytesToSend := MinIntValue([BytesToGo, MaxNetMsgSize-NetMsgHeaderSize]); LastMsg := (BytesToSend = BytesToGo); with FSndBuffer^ do begin nmhMsgLen := NetMsgHeaderSize + BytesToSend; nmhFirst := FirstMsg; nmhLast := LastMsg; end; if (BytesToSend > 0) then begin if (aDataType = nmdByteArray) then Move(DataAsBytes^[StartOfs], FSndBuffer^.nmhData, BytesToSend) else DataAsStream.Read(FSndBuffer^.nmhData, BytesToSend); end; FSndRcv.Send(PByteArray(FSndBuffer), NetMsgHeaderSize + BytesToSend, 0, BytesSent); if not LastMsg then begin LastMsg := (WaitForAckReply<>0); dec(BytesToGo, BytesToSend); if (aDataType = nmdByteArray) then inc(StartOfs, BytesToSend); FirstMsg := false; end; until LastMsg; end; {--------} function TCSCClient.RequestData(aMsg : longint; aRequest : pointer; aReqLen : LongInt; aReqType : TNetMsgDataType; aReply : pointer; aRpyLen : LongInt; aRpyType : TNetMsgDataType) : Word; var RequestAsStream : TStream absolute aRequest; RequestAsBytes : PByteArray absolute aRequest; ReplyAsStream : TStream absolute aReply; ReplyAsBytes : PByteArray absolute aReply; DataMsg : PCSCMessage; TotalDataLen : longint; DataLen : LongInt; BytesToGo : longint; BytesToSend : longint; BytesSent : longint; StartOfs : longint; FirstMsg : boolean; LastMsg : boolean; SkipSend : boolean; begin Result := 0; StartOfs := 0; {check for connection} if not FConnected then begin Result := CSCERR_ServerNotFound; Exit; end; {check for reentrancy} if FBusy then begin Result := CSCERR_SystemBusy; Exit; end; FBusy := true; try DataMsg := nil; {check to see whether we've got the reply already} SkipSend := false; if not FMsgQueue.IsEmpty then begin DataMsg := FMsgQueue.Examine; while (DataMsg^.dmMsg <> aMsg) do begin FMsgQueue.Pop; if not FMsgQueue.IsEmpty then DataMsg := FMsgQueue.Examine else Break; end; if (not FMsgQueue.IsEmpty) then SkipSend := true; end; {do we need to send a message?} if not SkipSend then begin {calculate the total message data length} if (aReqType = nmdByteArray) then TotalDataLen := aReqLen else TotalDataLen := RequestAsStream.Size; {we're just about to send the first message of (maybe) many} FirstMsg := true; {send the message} {..initialize loop variables} BytesToGo := TotalDataLen; if (aReqType = nmdByteArray) then StartOfs := 0 else RequestAsStream.Position := 0; {..send data in reasonably sized chunks} repeat {..set up the invariant parts of the message header} with FSndBuffer^ do begin nmhMsgID := aMsg; nmhEvent := True; nmhTotalSize := TotalDataLen; nmhErrorCode := 0; nmhDataType := aReqType; end; {calculate the size of data in this message packet} BytesToSend := MinIntValue([BytesToGo, MaxNetMsgSize-NetMsgHeaderSize]); LastMsg := (BytesToSend = BytesToGo); with FSndBuffer^ do begin nmhMsgLen := NetMsgHeaderSize + BytesToSend; nmhFirst := FirstMsg; nmhLast := LastMsg; end; if (BytesToSend > 0) then begin if (aReqType = nmdByteArray) then Move(RequestAsBytes^[StartOfs], FSndBuffer^.nmhData, BytesToSend) else RequestAsStream.Read(FSndBuffer^.nmhData, BytesToSend); end; FSndRcv.Send(PByteArray(FSndBuffer), NetMsgHeaderSize + BytesToSend, 0, BytesSent); if not LastMsg then begin Result := WaitForAckReply; dec(BytesToGo, BytesToSend); if (aReqType = nmdByteArray) then inc(StartOfs, BytesToSend); FirstMsg := false; end; until LastMsg or (Result<>0); if Result <> 0 then Exit; {Request sent - waiting to receive (multiple?) packets} if (aRpyType <> nmdByteArray) then ReplyAsStream.Position := 0; {wait for the reply to arrive from the server} Result := WaitForReply; if (Result <> CSCErr_None) then Exit; DataMsg := FMsgQueue.Examine; end; {check if there was an error code passed back; if so this will be the only message and there's no data whatsoever} if (DataMsg^.dmErrorCode <> 0) then begin Result := DataMsg^.dmErrorCode; FMsgQueue.Pop; Exit; end; {if there is no error code, there is (presumably) data: copy the data over} Result := DataMsg^.dmErrorCode; if (aRpyType = nmdByteArray) then begin DataLen := MinIntValue([aRpyLen, DataMsg^.dmDataLen]); if (DataLen > 0) then Move(DataMsg^.dmData^, ReplyAsBytes^[0], DataLen); end else {it's a stream} begin DataLen := DataMsg^.dmDataLen; if (DataLen > 0) then begin TMemoryStream(DataMsg^.dmData).Position := 0; ReplyAsStream.CopyFrom(TMemoryStream(DataMsg^.dmData), DataLen); end; end; {we've done with the message, pop it from the queue} FMsgQueue.Pop; finally FTicksLastCom := GetTickCount; {we're no longer busy} FBusy := false; end; end; {--------} {====================================================================} procedure TCSCClient.ConnectAndWait; var NovoValor : Boolean; begin FWinsockError := 0; FConnErrorStr := ''; NovoValor := not FConnected; Connected := NovoValor; ExceptionMgr.Add(Self); try FConnecting := True; while (NovoValor <> FConnected) and (FConnErrorStr='') and (FWinsockError=0) do begin try ProcessSocketMessages; except on E: Exception do begin if E is ESocketError then Raise ECSError.CreateSckError(FWinsockError) else Raise; end; end; Sleep(5); end; finally FConnecting := False; ExceptionMgr.Remove(Self); end; if FConnErrorStr > '' then if FWinsockError > 0 then Raise ECSError.CreateSckError(FWinsockError) else Raise Exception.Create(FConnErrorStr); end; procedure TCSCClient.HandleAppException(Sender: TObject; E: Exception); begin FConnErrorStr := E.Message; if not (E is ESocketError) then FWinsockError := 0; end; { TCSCExceptionManager } procedure TCSCExceptionManager.Add(aCli: TCSCClient); var C : PemClient; begin FCS.Enter; try if GetByThread<>nil then Raise Exception.Create('JŠ existe outro CSCClient nessa mesma tarefa!'); New(C); C^.fCli := aCli; C^.fThreadID := GetCurrentThreadID; FThreads.Add(C); if FThreads.Count=1 then begin FSaveAppEH := Application.OnException; Application.OnException := HandleAppException; end; finally FCS.Leave; end; end; function TCSCExceptionManager.Count: Integer; begin FCS.Enter; try Result := FThreads.Count; finally FCS.Leave; end; end; constructor TCSCExceptionManager.Create; begin FCS := TCriticalSection.Create; FThreads := TList.Create; FSaveAppEH := nil; end; destructor TCSCExceptionManager.Destroy; begin FCS.Free; FThreads.Free; inherited; end; function TCSCExceptionManager.GetByThread: PemClient; var thid: Cardinal; i: Integer; begin thid := GetCurrentThreadID; for I := 0 to FThreads.Count - 1 do if (thid=PemClient(FThreads[i])^.fThreadID) then begin Result := FThreads[i]; Exit; end; Result := nil; end; procedure TCSCExceptionManager.HandleAppException(Sender: TObject; E: Exception); var C: PemClient; begin FCS.Enter; try C := GetByThread; if C=nil then Application.ShowException(E) else begin C.fCli.FConnErrorStr := E.Message; if not (E is ESocketError) then C.fCli.FWinsockError := 0; end; finally FCS.Leave; end; end; procedure TCSCExceptionManager.Remove(aCli: TCSCClient); var C: PemClient; begin FCS.Enter; try C := GetByThread; if (C<>nil) and (C.fCli=aCli) then begin FThreads.Remove(C); Dispose(C); if FThreads.Count=0 then begin Application.OnException := FSaveAppEH; FSaveAppEH := nil; end; end; finally FCS.Leave; end; end; initialization ExceptionMgr := TCSCExceptionManager.Create; finalization ExceptionMgr.Free; end.
unit uControl; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls, ExtCtrls, DBGrids, Mask; type TFrmControl = class(TForm) Panel2: TPanel; LbBalance: TLabel; LbHours: TLabel; SGrid: TStringGrid; Panel1: TPanel; RGroup: TRadioGroup; BtnInsertTime: TButton; Label1: TLabel; EdTime: TMaskEdit; SaveDlg: TSaveDialog; procedure FormCreate(Sender: TObject); procedure BtnInsertTimeClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } LineCount: Integer; procedure SetColumnsText; procedure SetColumnsWidth; procedure CalculateTotalTime; public { Public declarations } end; var FrmControl: TFrmControl; implementation {$R *.dfm} procedure TFrmControl.FormCreate(Sender: TObject); begin LineCount := 1; SetColumnsWidth; SetColumnsText; end; procedure TFrmControl.BtnInsertTimeClick(Sender: TObject); var xTime: TDateTime; begin case RGroup.ItemIndex of 0: begin SGrid.Rows[LineCount].Strings[0] := DateTimeToStr(Date); SGrid.Rows[LineCount].Strings[1] := EdTime.Text; RGroup.ItemIndex := 1; EdTime.SetFocus; end; 1: begin SGrid.Rows[LineCount].Strings[2] := EdTime.Text; RGroup.ItemIndex := 2; EdTime.SetFocus; end; 2: begin SGrid.Rows[LineCount].Strings[3] := EdTime.Text; RGroup.ItemIndex := 3; EdTime.SetFocus; end; 3: begin SGrid.Rows[LineCount].Strings[4] := EdTime.Text; RGroup.ItemIndex := 1; EdTime.SetFocus; end; end; if (SGrid.Rows[LineCount].Strings[0] <> '') and (SGrid.Rows[LineCount].Strings[1] <> '') and (SGrid.Rows[LineCount].Strings[2] <> '') and (SGrid.Rows[LineCount].Strings[3] <> '') and (SGrid.Rows[LineCount].Strings[4] <> '') then begin xTime := (StrToTime(SGrid.Rows[LineCount].Strings[2]) - StrToTime(SGrid.Rows[LineCount].Strings[1])) + (StrToTime(SGrid.Rows[LineCount].Strings[4]) - StrToTime(SGrid.Rows[LineCount].Strings[3])); SGrid.Rows[LineCount].Strings[6] := TimeToStr(xTime) end; CalculateTotalTime; EdTime.Clear; end; procedure TFrmControl.FormShow(Sender: TObject); begin EdTime.SetFocus; end; procedure TFrmControl.SetColumnsText; begin SGrid.Cols[0].Text := ' Date'; SGrid.Cols[1].Text := ' Arrival Time'; SGrid.Cols[2].Text := ' Lunch time start'; SGrid.Cols[3].Text := 'Lunch time finish'; SGrid.Cols[4].Text := ' Departure Time'; SGrid.Cols[6].Text := ' Total Time'; end; procedure TFrmControl.SetColumnsWidth; var i: integer; begin for i := 0 to SGrid.ColCount -1 do SGrid.ColWidths[i] := 160; SGrid.ColWidths[5] := 10; end; procedure TFrmControl.CalculateTotalTime; begin if (SGrid.Rows[LineCount].Strings[6] <> '') then begin if (SGrid.Rows[LineCount].Strings[6] <= '08:45') then begin LbHours.Caption := TimeToStr(StrToTime(LbHours.Caption) - (StrToTime('08:45') - StrToTime(SGrid.Rows[LineCount].Strings[6]))); Inc(LineCount); SGrid.RowCount := SGrid.RowCount + 1; end else begin LbHours.Caption := TimeToStr(StrToTime(LbHours.Caption) + (StrToTime(SGrid.Rows[LineCount].Strings[6]) - StrToTime('08:45'))); Inc(LineCount); SGrid.RowCount := SGrid.RowCount + 1; end; end; end; procedure TFrmControl.FormClose(Sender: TObject; var Action: TCloseAction); var i: integer; begin SaveDlg.Execute; for i := 0 to LineCount -1 do begin SaveDlg. end; end; end.
{ GMPolygonFMX unit ES: contiene las clases FMX necesarias para mostrar polígonos en un mapa de Google Maps mediante el componente TGMMap EN: includes the FMX classes needed to show polygons on Google Map map using the component TGMMap ========================================================================= MODO DE USO/HOW TO USE ES: poner el componente en el formulario, linkarlo a un TGMMap y poner los polígonos a mostrar EN: put the component into a form, link to a TGMMap and put the polygons to show ========================================================================= History: ver 1.0.0 ES: cambio: TPolygons ahora hereda de TBasePolylines. EN: change: TPolygons now descends from TBasePolylines. ver 0.1.9 ES: nuevo: documentación nuevo: se hace compatible con FireMonkey EN: new: documentation new: now compatible with FireMonkey ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a: gmlib@cadetill.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion, please send me a mail to: gmlib@cadetill.com ========================================================================= Copyright (©) 2012, by Xavier Martinez (cadetill) @author Xavier Martinez (cadetill) @web http://www.cadetill.com } {*------------------------------------------------------------------------------ The GMPolygonFMX unit includes the FMX classes needed to show polygons on Google Map map using the component TGMMap. @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ La unit GMPolygonFMX contiene las clases FMX necesarias para mostrar polígonos en un mapa de Google Maps mediante el componente TGMMap @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} unit GMPolygonFMX; interface uses System.Classes, System.UITypes, GMPolyline, GMPolylineFMX, GMLinkedComponents, GMClasses; type {*------------------------------------------------------------------------------ FMX class for polygons. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#Polygon -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase FMX para los polígonos. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#Polygon -------------------------------------------------------------------------------} TPolygon = class(TBasePolylineFMX) private {*------------------------------------------------------------------------------ The fill color. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Color de relleno. -------------------------------------------------------------------------------} FFillColor: TAlphaColor; {*------------------------------------------------------------------------------ The fill opacity between 0.0 and 1.0. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Opacidad del relleno entre 0.0 y 1.0. -------------------------------------------------------------------------------} FFillOpacity: Real; procedure SetFillColor(const Value: TAlphaColor); procedure SetFillOpacity(const Value: Real); protected function ChangeProperties: Boolean; override; public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; {*------------------------------------------------------------------------------ Computes whether the given point lies inside the polygon. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#poly @param LatLng Point to compute. @return True if the point is inside of the polygon. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Calcula si el punto dado se encuentra dentro del polígono. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#poly @param LatLng Punto a calcular. @return True si el punto esta dentro del polígono. -------------------------------------------------------------------------------} function ContainsLocation(LatLng: TLatLng): Boolean; overload; {*------------------------------------------------------------------------------ Computes whether the given point lies inside the polygon. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#poly @param Lat Latitude to compute. @param Lng Longitude to compute. @return True if the point is inside of the polygon. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Calcula si el punto dado se encuentra dentro del polígono. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#poly @param Lat Latitud a calcular. @param Lng Longitud a calcular. @return True si el punto esta dentro del polígono. -------------------------------------------------------------------------------} function ContainsLocation(Lat, Lng: Real): Boolean; overload; published property FillColor: TAlphaColor read FFillColor write SetFillColor default TAlphaColorRec.Red; property FillOpacity: Real read FFillOpacity write SetFillOpacity; // 0 to 1 end; {*------------------------------------------------------------------------------ FMX class for polygons collection. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase FMX para la colección de polígonos. -------------------------------------------------------------------------------} TPolygons = class(TBasePolylines) private procedure SetItems(I: Integer; const Value: TPolygon); function GetItems(I: Integer): TPolygon; protected function GetOwner: TPersistent; override; public function Add: TPolygon; function Insert(Index: Integer): TPolygon; {*------------------------------------------------------------------------------ Lists the rectangles in the collection. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Lista de rectángulos en la colección. -------------------------------------------------------------------------------} property Items[I: Integer]: TPolygon read GetItems write SetItems; default; end; {*------------------------------------------------------------------------------ Class management of polygons. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase para la gestión de polígonos. -------------------------------------------------------------------------------} TGMPolygon = class(TGMBasePolyline) private {*------------------------------------------------------------------------------ This event is fired when the polygon's FillOpacity property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad FillOpacity de un polígono. -------------------------------------------------------------------------------} FOnFillOpacityChange: TLinkedComponentChange; {*------------------------------------------------------------------------------ This event is fired when the polygon's FillColor property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad FillColor de un polígono. -------------------------------------------------------------------------------} FOnFillColorChange: TLinkedComponentChange; protected function GetAPIUrl: string; override; function GetItems(I: Integer): TPolygon; function GetCollectionItemClass: TLinkedComponentClass; override; function GetCollectionClass: TLinkedComponentsClass; override; public {*------------------------------------------------------------------------------ Creates a new TPolygon instance and adds it to the Items array. @return New TPolygon -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Crea una nueva instancia de TPolygon y la añade en el array de Items. @return Nuevo TPolygon -------------------------------------------------------------------------------} function Add: TPolygon; {*------------------------------------------------------------------------------ Array with the collection items. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Array con la colección de elementos. -------------------------------------------------------------------------------} property Items[I: Integer]: TPolygon read GetItems; default; published // eventos // events // from properties property OnFillColorChange: TLinkedComponentChange read FOnFillColorChange write FOnFillColorChange; property OnFillOpacityChange: TLinkedComponentChange read FOnFillOpacityChange write FOnFillOpacityChange; end; implementation uses SysUtils, GMFunctionsFMX, GMConstants; { TGMPolygon } function TGMPolygon.Add: TPolygon; begin Result := TPolygon(inherited Add); end; function TGMPolygon.GetAPIUrl: string; begin Result := 'https://developers.google.com/maps/documentation/javascript/reference?hl=en#Polygon'; end; function TGMPolygon.GetCollectionClass: TLinkedComponentsClass; begin Result := TPolygons; end; function TGMPolygon.GetCollectionItemClass: TLinkedComponentClass; begin Result := TPolygon; end; function TGMPolygon.GetItems(I: Integer): TPolygon; begin Result := TPolygon(inherited Items[i]); end; { TPolygons } function TPolygons.Add: TPolygon; begin Result := TPolygon(inherited Add); end; function TPolygons.GetItems(I: Integer): TPolygon; begin Result := TPolygon(inherited Items[I]); end; function TPolygons.GetOwner: TPersistent; begin Result := TGMPolygon(inherited GetOwner); end; function TPolygons.Insert(Index: Integer): TPolygon; begin Result := TPolygon(inherited Insert(Index)); end; procedure TPolygons.SetItems(I: Integer; const Value: TPolygon); begin inherited SetItem(I, Value); end; { TPolygon } procedure TPolygon.Assign(Source: TPersistent); begin inherited; if Source is TPolyline then begin FillColor := TPolygon(Source).FillColor; FillOpacity := TPolygon(Source).FillOpacity; end; end; function TPolygon.ChangeProperties: Boolean; const StrParams = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s'; var Params: string; begin inherited; Result := False; if not Assigned(Collection) or not(Collection is TPolygons) or not Assigned(TPolygons(Collection).FGMLinkedComponent) or //not TGMPolygon(TPolygons(Collection).FGMLinkedComponent).AutoUpdate or not Assigned(TGMPolygon(TPolygons(Collection).FGMLinkedComponent).Map) or (csDesigning in TGMPolygon(TPolygons(Collection).FGMLinkedComponent).ComponentState) then Exit; Params := Format(StrParams, [ IntToStr(IdxList), LowerCase(TTransform.GMBoolToStr(Clickable, True)), LowerCase(TTransform.GMBoolToStr(Editable, True)), QuotedStr(TTransform.TColorToStr(FillColor)), StringReplace(FloatToStr(FillOpacity), ',', '.', [rfReplaceAll]), LowerCase(TTransform.GMBoolToStr(Geodesic, True)), QuotedStr(GetStrokeColor), StringReplace(FloatToStr(StrokeOpacity), ',', '.', [rfReplaceAll]), IntToStr(StrokeWeight), LowerCase(TTransform.GMBoolToStr(Visible, True)), QuotedStr(PolylineToStr), IntToStr(Index), QuotedStr(InfoWindow.GetConvertedString), LowerCase(TTransform.GMBoolToStr(InfoWindow.DisableAutoPan, True)), IntToStr(InfoWindow.MaxWidth), IntToStr(InfoWindow.PixelOffset.Height), IntToStr(InfoWindow.PixelOffset.Width), LowerCase(TTransform.GMBoolToStr(InfoWindow.CloseOtherBeforeOpen, True)) ]); Result := TGMPolygon(TPolygons(Collection).FGMLinkedComponent).ExecuteScript('MakePolygon', Params); TGMPolygon(TPolygons(Collection).FGMLinkedComponent).ErrorControl; end; function TPolygon.ContainsLocation(LatLng: TLatLng): Boolean; begin Result := TGeometry.ContainsLocation(TGMPolygon(TPolygons(Collection).FGMLinkedComponent), Index, LatLng); end; function TPolygon.ContainsLocation(Lat, Lng: Real): Boolean; var LatLng: TLatLng; begin LatLng := TLatLng.Create(Lat, Lng); try Result := ContainsLocation(LatLng); finally FreeAndNil(LatLng); end; end; constructor TPolygon.Create(Collection: TCollection); begin inherited; FFillOpacity := 0.5; FFillColor := TAlphaColorRec.Red; end; procedure TPolygon.SetFillColor(const Value: TAlphaColor); begin if FFillColor = Value then Exit; FFillColor := Value; ChangeProperties; if Assigned(TGMPolygon(TPolygons(Collection).FGMLinkedComponent).FOnFillColorChange) then TGMPolygon(TPolygons(Collection).FGMLinkedComponent).FOnFillColorChange( TGMPolygon(TPolygons(Collection).FGMLinkedComponent), Index, Self); end; procedure TPolygon.SetFillOpacity(const Value: Real); begin if FFillOpacity = Value then Exit; FFillOpacity := Value; if FFillOpacity < 0 then FFillOpacity := 0; if FFillOpacity > 1 then FFillOpacity := 1; FFillOpacity := Trunc(FFillOpacity * 100) / 100; ChangeProperties; if Assigned(TGMPolygon(TPolygons(Collection).FGMLinkedComponent).FOnFillOpacityChange) then TGMPolygon(TPolygons(Collection).FGMLinkedComponent).FOnFillOpacityChange( TGMPolygon(TPolygons(Collection).FGMLinkedComponent), Index, Self); end; end.
unit SettingsController; interface uses System.IniFiles, System.SysUtils, Vcl.Forms; type TSettings = class(TObject) private FFileName: string; FIniFile: TIniFile; class var Instance: TSettings; function GetBodyTypesLandPatternFolder: string; function GetBodyTypesOutlineDrawingFolder: string; function GetBodyTypesImageFolder: string; function GetBodyTypesJEDECFolder: string; function GetCategoryID: Integer; function GetComponentsDrawingFolder: String; function GetComponentsImageFolder: String; function GetComponentsDiagramFolder: String; function GetComponentsDatasheetFolder: String; function GetMinWholeSale: Double; function GetWareHouseDiagramFolder: String; function GetWareHouseDrawingFolder: String; function GetWareHouseImageFolder: String; function GetWareHouseDatasheetFolder: String; function GetDataBasePath: string; function GetDBMigrationFolder: string; function GetLastFolderForComponentsLoad: string; function GetIniFile: TIniFile; function GetParametricDataFolder: string; function GetLastFolderForExcelFile: string; function GetProducer: String; function GetRate: Double; function GetLoadLastCategory: Boolean; procedure SetBodyTypesLandPatternFolder(const Value: string); procedure SetBodyTypesOutlineDrawingFolder(const Value: string); procedure SetBodyTypesImageFolder(const Value: string); procedure SetBodyTypesJEDECFolder(const Value: string); procedure SetCategoryID(const Value: Integer); procedure SetComponentsDrawingFolder(const Value: String); procedure SetComponentsImageFolder(const Value: String); procedure SetComponentsDiagramFolder(const Value: String); procedure SetComponentsDatasheetFolder(const Value: String); procedure SetMinWholeSale(const Value: Double); procedure SetWareHouseDiagramFolder(const Value: String); procedure SetWareHouseDrawingFolder(const Value: String); procedure SetWareHouseImageFolder(const Value: String); procedure SetWareHouseDatasheetFolder(const Value: String); procedure SetDataBasePath(const Value: string); procedure SetDBMigrationFolder(const Value: string); procedure SetLastFolderForComponentsLoad(const Value: string); procedure SetParametricDataFolder(const Value: string); procedure SetLastFolderForExcelFile(const Value: string); procedure SetProducer(const Value: String); procedure SetRate(const Value: Double); procedure SetLoadLastCategory(const Value: Boolean); // TODO: UpdatePath // function UpdatePath(const APath, ANewDBPath: string): string; protected property IniFile: TIniFile read GetIniFile; public constructor Create; virtual; destructor Destroy; override; function GetFolderFoExcelFile(const AFolderKey: String): String; function GetValue(const ASection, AParameter: string; const ADefault: string = ''): string; function GetPath(const ASection, AParameter, ADefaultFolder : string): string; function LoadStrings(const ASection, ACaption: string): TArray<String>; class function NewInstance: TObject; override; procedure SaveStrings(const ASection, ACaption: string; StrArr: TArray<String>); procedure SetFolderForExcelFile(const AFolderKey, AFolder: String); procedure SetValue(const ASection, AParameter: string; const Value: Variant); property BodyTypesLandPatternFolder: string read GetBodyTypesLandPatternFolder write SetBodyTypesLandPatternFolder; property BodyTypesOutlineDrawingFolder: string read GetBodyTypesOutlineDrawingFolder write SetBodyTypesOutlineDrawingFolder; property BodyTypesImageFolder: string read GetBodyTypesImageFolder write SetBodyTypesImageFolder; property BodyTypesJEDECFolder: string read GetBodyTypesJEDECFolder write SetBodyTypesJEDECFolder; property CategoryID: Integer read GetCategoryID write SetCategoryID; property ComponentsDrawingFolder: String read GetComponentsDrawingFolder write SetComponentsDrawingFolder; property ComponentsImageFolder: String read GetComponentsImageFolder write SetComponentsImageFolder; property ComponentsDiagramFolder: String read GetComponentsDiagramFolder write SetComponentsDiagramFolder; property ComponentsDatasheetFolder: String read GetComponentsDatasheetFolder write SetComponentsDatasheetFolder; property MinWholeSale: Double read GetMinWholeSale write SetMinWholeSale; property WareHouseDiagramFolder: String read GetWareHouseDiagramFolder write SetWareHouseDiagramFolder; property WareHouseDrawingFolder: String read GetWareHouseDrawingFolder write SetWareHouseDrawingFolder; property WareHouseImageFolder: String read GetWareHouseImageFolder write SetWareHouseImageFolder; property WareHouseDatasheetFolder: String read GetWareHouseDatasheetFolder write SetWareHouseDatasheetFolder; property DataBasePath: string read GetDataBasePath write SetDataBasePath; property DBMigrationFolder: string read GetDBMigrationFolder write SetDBMigrationFolder; property LastFolderForComponentsLoad: string read GetLastFolderForComponentsLoad write SetLastFolderForComponentsLoad; property ParametricDataFolder: string read GetParametricDataFolder write SetParametricDataFolder; property LastFolderForExcelFile: string read GetLastFolderForExcelFile write SetLastFolderForExcelFile; property Producer: String read GetProducer write SetProducer; property Rate: Double read GetRate write SetRate; property LoadLastCategory: Boolean read GetLoadLastCategory write SetLoadLastCategory; end; implementation uses ProjectConst, System.IOUtils, System.Variants, System.Contnrs, System.Classes, System.Generics.Collections; var SingletonList: TObjectList; constructor TSettings.Create; begin Assert(Instance <> nil); if FFileName.IsEmpty then FFileName := ChangeFileExt(Application.ExeName, '.ini'); end; destructor TSettings.Destroy; begin if Assigned(FIniFile) then FreeAndNil(FIniFile); FFileName := ''; inherited; end; function TSettings.GetBodyTypesLandPatternFolder: string; begin Result := GetPath('BodyTypes', 'LandPatternFolder', sBodyLandPatternFolder); end; function TSettings.GetBodyTypesOutlineDrawingFolder: string; begin Result := GetPath('BodyTypes', 'OutlineDrawingFolder', sBodyOutlineDrawingFolder); end; function TSettings.GetBodyTypesImageFolder: string; begin Result := GetPath('BodyTypes', 'ImageFolder', sBodyImageFolder); end; function TSettings.GetBodyTypesJEDECFolder: string; begin Result := GetPath('BodyTypes', 'JEDECFolder', sBodyJEDECFolder); end; function TSettings.GetCategoryID: Integer; begin Result := StrToIntDef(GetValue('Db', 'CategoryID', '0'), 0); end; function TSettings.GetComponentsDrawingFolder: String; begin Result := GetPath('Components', 'DrawingFolder', sComponentsDrawingFolder); end; function TSettings.GetComponentsImageFolder: String; begin Result := GetPath('Components', 'ImageFolder', sComponentsImageFolder); end; function TSettings.GetComponentsDiagramFolder: String; begin Result := GetPath('Components', 'DiagramFolder', sComponentsDiagramFolder); end; function TSettings.GetComponentsDatasheetFolder: String; begin Result := GetPath('Components', 'DatasheetFolder', sComponentsDatasheetFolder); end; function TSettings.GetMinWholeSale: Double; begin Result := StrToFloatDef(GetValue('StoreHouse', 'MinWholeSale', IntToStr(MinWholeSaleDef)), MinWholeSaleDef); end; function TSettings.GetWareHouseDiagramFolder: String; begin Result := GetPath('WareHouse', 'DiagramFolder', TPath.Combine(sWareHouseFolder, sComponentsDiagramFolder)); end; function TSettings.GetWareHouseDrawingFolder: String; begin Result := GetPath('WareHouse', 'DrawingFolder', TPath.Combine(sWareHouseFolder, sComponentsDrawingFolder)); end; function TSettings.GetWareHouseImageFolder: String; begin Result := GetPath('WareHouse', 'ImageFolder', TPath.Combine(sWareHouseFolder, sComponentsImageFolder)); end; function TSettings.GetWareHouseDatasheetFolder: String; begin Result := GetPath('WareHouse', 'DatasheetFolder', TPath.Combine(sWareHouseFolder, sComponentsDatasheetFolder)); end; function TSettings.GetDataBasePath: string; begin Result := GetValue('Db', 'databasePath'); end; function TSettings.GetDBMigrationFolder: string; var ADefaultFolder: string; begin ADefaultFolder := TPath.Combine(TPath.GetDirectoryName(Application.ExeName), 'update'); Result := GetValue('Db', 'DBMigrationFolder', ADefaultFolder); end; function TSettings.GetFolderFoExcelFile(const AFolderKey: String): String; begin // Пытаемся прочитать папку по ключевому слову Result := GetValue('Folder', AFolderKey, ''); if Result = '' then Result := GetLastFolderForComponentsLoad; end; function TSettings.GetLastFolderForComponentsLoad: string; begin Result := GetValue('Folder', 'ComponentsLoadFolder', DataBasePath); end; function TSettings.GetIniFile: TIniFile; begin Assert(not FFileName.IsEmpty); if not Assigned(FIniFile) then FIniFile := TIniFile.Create(FFileName); Result := FIniFile; end; function TSettings.GetParametricDataFolder: string; begin Result := GetValue('Folder', 'ParametricDataFolder', DataBasePath); end; function TSettings.GetLastFolderForExcelFile: string; begin Result := GetValue('Folder', 'ExcelFileLoadFolder', DataBasePath); end; function TSettings.GetValue(const ASection, AParameter: string; const ADefault: string = ''): string; begin Result := IniFile.ReadString(ASection, AParameter, ADefault); // if Result = ADefault then // Result := IniFile.ReadString('Db', AParameter, ADefault); end; function TSettings.GetPath(const ASection, AParameter, ADefaultFolder : string): string; var ADefValue: string; begin Assert(TPath.IsRelativePath(ADefaultFolder)); // Формируем полный путь "по умолчанию" ADefValue := TPath.Combine(DataBasePath, ADefaultFolder); Result := GetValue(ASection, AParameter, ADefValue); // Если в настройках почему-то! сохранился относительный путь до папки if TPath.IsRelativePath(Result) then Result := ADefValue; // Меняем его на значение по умолчанию end; function TSettings.GetProducer: String; begin Result := GetValue('Producer', 'Producer', ''); end; function TSettings.GetRate: Double; begin Result := StrToFloatDef(GetValue('Rate', 'Rate', FloatToStr(DefaultRate)), DefaultRate); end; function TSettings.GetLoadLastCategory: Boolean; begin Result := StrToBool(GetValue('Settings', 'LoadLastCategory', 'False')); end; class function TSettings.NewInstance: TObject; begin if not Assigned(Instance) then begin Instance := TSettings(inherited NewInstance); SingletonList.Add(Instance); end; Result := Instance; end; function TSettings.LoadStrings(const ASection, ACaption: string): TArray<String>; var AIniFile: TIniFile; I: Integer; L: TList<String>; S: String; begin L := TList<String>.Create; try AIniFile := TIniFile.Create(FFileName); try for I := 0 to 20 do begin S := AIniFile.ReadString(ASection, Format('%s_%d', [ACaption, I]), ''); if not S.IsEmpty then L.Add(S) else break; end; finally AIniFile.Free; end; Result := L.ToArray; finally FreeAndNil(L); end; end; procedure TSettings.SaveStrings(const ASection, ACaption: string; StrArr: TArray<String>); var AIniFile: TIniFile; I: Integer; begin AIniFile := TIniFile.Create(FFileName); try for I := Low(StrArr) to High(StrArr) do AIniFile.WriteString(ASection, Format('%s_%d', [ACaption, I]), StrArr[I]); // Удаляем "лишние" ключи for I := High(StrArr) + 1 to 20 do AIniFile.DeleteKey(ASection, Format('%s_%d', [ACaption, I])); finally AIniFile.Free; end; end; procedure TSettings.SetBodyTypesLandPatternFolder(const Value: string); begin SetValue('BodyTypes', 'LandPatternFolder', Value); end; procedure TSettings.SetBodyTypesOutlineDrawingFolder(const Value: string); begin SetValue('BodyTypes', 'OutlineDrawingFolder', Value); end; procedure TSettings.SetBodyTypesImageFolder(const Value: string); begin SetValue('BodyTypes', 'ImageFolder', Value); end; procedure TSettings.SetBodyTypesJEDECFolder(const Value: string); begin SetValue('BodyTypes', 'JEDECFolder', Value); end; procedure TSettings.SetCategoryID(const Value: Integer); begin SetValue('Db', 'CategoryID', Value); end; procedure TSettings.SetComponentsDrawingFolder(const Value: String); begin SetValue('Components', 'DrawingFolder', Value); end; procedure TSettings.SetComponentsImageFolder(const Value: String); begin SetValue('Components', 'ImageFolder', Value); end; procedure TSettings.SetComponentsDiagramFolder(const Value: String); begin SetValue('Components', 'DiagramFolder', Value); end; procedure TSettings.SetComponentsDatasheetFolder(const Value: String); begin SetValue('Components', 'DatasheetFolder', Value); end; procedure TSettings.SetMinWholeSale(const Value: Double); begin SetValue('StoreHouse', 'MinWholeSale', Value); end; procedure TSettings.SetWareHouseDiagramFolder(const Value: String); begin SetValue('WareHouse', 'DiagramFolder', Value); end; procedure TSettings.SetWareHouseDrawingFolder(const Value: String); begin SetValue('WareHouse', 'DrawingFolder', Value); end; procedure TSettings.SetWareHouseImageFolder(const Value: String); begin SetValue('WareHouse', 'ImageFolder', Value); end; procedure TSettings.SetWareHouseDatasheetFolder(const Value: String); begin SetValue('WareHouse', 'DatasheetFolder', Value); end; procedure TSettings.SetDataBasePath(const Value: string); begin if DataBasePath <> Value then begin { BodyTypesOutlineDrawingFolder := UpdatePath(BodyTypesOutlineDrawingFolder, Value); BodyTypesLandPatternFolder := UpdatePath(BodyTypesLandPatternFolder, Value); BodyTypesImageFolder := UpdatePath(BodyTypesImageFolder, Value); ComponentsDrawingFolder := UpdatePath( ComponentsDrawingFolder, Value ); ComponentsImageFolder := UpdatePath( ComponentsImageFolder, Value ); ComponentsDiagramFolder := UpdatePath( ComponentsDiagramFolder, Value ); ComponentsDatasheetFolder := UpdatePath( ComponentsDatasheetFolder, Value ); } SetValue('Db', 'databasePath', Value); end; end; procedure TSettings.SetDBMigrationFolder(const Value: string); begin if DBMigrationFolder <> Value then begin SetValue('Db', 'DBMigrationFolder', Value); end; end; procedure TSettings.SetFolderForExcelFile(const AFolderKey, AFolder: String); begin SetValue('Folder', AFolderKey, AFolder); end; procedure TSettings.SetLastFolderForComponentsLoad(const Value: string); begin if LastFolderForComponentsLoad <> Value then begin SetValue('Folder', 'ComponentsLoadFolder', Value); end; end; procedure TSettings.SetParametricDataFolder(const Value: string); begin if ParametricDataFolder <> Value then begin SetValue('Folder', 'ParametricDataFolder', Value); end; end; procedure TSettings.SetLastFolderForExcelFile(const Value: string); begin if LastFolderForExcelFile <> Value then begin SetValue('Folder', 'ExcelFileLoadFolder', Value); end; end; procedure TSettings.SetProducer(const Value: String); begin if Producer <> Value then begin SetValue('Producer', 'Producer', Value); end; end; procedure TSettings.SetRate(const Value: Double); begin SetValue('Rate', 'Rate', Value); end; procedure TSettings.SetLoadLastCategory(const Value: Boolean); begin SetValue('Settings', 'LoadLastCategory', Value); end; procedure TSettings.SetValue(const ASection, AParameter: string; const Value: Variant); var AIniFile: TIniFile; begin if FFileName.IsEmpty then Exit; AIniFile := TIniFile.Create(FFileName); try if VarIsStr(Value) then AIniFile.WriteString(ASection, AParameter, Value); if VarIsFloat(Value) then AIniFile.WriteFloat(ASection, AParameter, Value); if VarIsNumeric(Value) then AIniFile.WriteInteger(ASection, AParameter, Value); if VarIsType(Value, varBoolean) then AIniFile.WriteBool(ASection, AParameter, Value); finally AIniFile.Free; end; end; initialization SingletonList := TObjectList.Create(True); finalization SingletonList.Free; end.
unit ThreadHandle; interface uses Classes; procedure StartGetData; procedure StopGetData; implementation type TGetData=class(TThread) protected // the main body of the thread procedure Execute; override; end; procedure TGetData.Execute; begin // execute codes inside the following block until the thread is terminated while not Terminated do begin // play beep sound // yield the processor to other process/thread end; end; procedure StartGetData; begin with TGetData.Create(False) do // Tell the TBeeper instance to automatically destroy itself once it's been terminated FreeOnTerminate := True; end; procedure StopGetData; begin end; end.
unit uI200BD; interface uses IBQuery,SqlExpr,SysUtils,Contnrs, Dialogs, DB, ADODB, uRegistro,uRegistroBD; type TI200BD = class(TRegistroBD) private public function Inserir (const oRegistro : TRegistro) : Boolean; override; function Alterar (const oRegistro: TRegistro) : Boolean; override; function Deletar (const oRegistro: TRegistro) : Boolean; override; function Procurar (const oRegistro : TRegistro) : TRegistro; override; function Todos () : TObjectList; override ; procedure SetaDataBase (const oRegistro : TRegistro); function GetTodosdoI100(const oRegistro : TRegistro): TObjectList; end; implementation uses uI200,uSped, UEmpresaContabilIB ; function TI200BD.Alterar(const oRegistro: TRegistro): Boolean; begin end; procedure TI200BD.SetaDataBase (const oRegistro : TRegistro); begin Qry.Database := TEmpresaContabilIB.GetObjetoConexao( TI200(oRegistro).Empresa.ID).Conexao; end; function TI200BD.Deletar(const oRegistro: TRegistro): Boolean; begin end; function TI200BD.Inserir(const oRegistro: TRegistro): Boolean; var ID : Integer; begin SetaDataBase(oRegistro); ID := GeraId('I200'); // Qry.sql.Clear; // Qry.SQL.Add('INSERT INTO I100(ID, CST, TOTALFATURAMENTO, VALORPIS, BASECALCULOPIS , ALIQUOTAPIS , ' + #13+ // ' VALORCOFINS, BASECALCULOCOFINS , ALIQUOTACOFINS, I010 ) ' + #13+ // 'VALUES ' + #13+ // '(:pID, :pCST, :pTOTALFATURAMENTO, :pVALORPIS, :pBASECALCULOPIS , :pALIQUOTAPIS , ' + #13+ // ' :pVALORCOFINS, :pBASECALCULOCOFINS , :pALIQUOTACOFINS, :pI010 ) ' ); // TI100(oRegistro).ID := ID; // Qry.ParamByName('pID').AsInteger := ID; // Qry.ParamByName('pCST').AsInteger := TI100(oRegistro).CST.ID; // Qry.ParamByName('pALIQUOTAPIS').AsFloat := TI100(oRegistro).AliquotaPIS; // Qry.ParamByName('pALIQUOTACOFINS').AsFloat := TI100(oRegistro).AliquotaCOFINS; // Qry.ParamByName('pI010').AsInteger := TI100(oRegistro).I010.ID; // try // Qry.ExecSQL; // Qry.Database.DefaultTransaction.Commit; // except // on e:Exception do begin // Qry.Close; // Qry.Free; // raise exception.Create('Erro na inserção'); // end; // end; // Qry.Close; // Qry.Free; end; function TI200BD.Procurar(const oRegistro: TRegistro): TRegistro; begin end; function TI200BD.Todos(): TObjectList; begin end; function TI200BD.GetTodosdoI100(const oRegistro: TRegistro): TObjectList; var lI200s : TObjectList; lI200 : TI200; begin SetaDataBase(oRegistro); Qry.SQL.Clear; // Qry.SQL.Add( ' SELECT ID , CST FROM I100 ' ); // Qry.SQL.Add(' WHERE I010 = :pI010 ' ); // Qry.ParamByName('pI010').AsInteger := TI100(oRegistro).I010.ID ; // try // Qry.Open; // if (not Qry.IsEmpty) then begin // lI100s := TObjectList.create; // Qry.First; // while (not Qry.Eof ) do begin // lI100 := TI100.Create; // lCST := TCST.create; // lI100.ID := Qry.FieldByName('ID').AsInteger; // lCST.ID := Qry.FieldByName('CST').AsInteger; // lCST.Procurar(); // lI100.CST := lCST; // lI100s.Add(lI100); // Qry.Next; // end; // result := lI100s; // end // else result := Nil; // except // result := Nil; // end; end; end.
unit uMenu; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, Buttons, uDmParametros, RLConsts, ActnList, jpeg, ExtCtrls; type TfMenu = class(TForm) MainMenu1: TMainMenu; Cadastros1: TMenuItem; Cidades1: TMenuItem; Usurios1: TMenuItem; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; SpeedButton4: TSpeedButton; Parmetros1: TMenuItem; N1: TMenuItem; Cadastro1: TMenuItem; Perfil1: TMenuItem; LogdoSistema1: TMenuItem; Logoff1: TMenuItem; rocarSenha1: TMenuItem; N2: TMenuItem; Filiais1: TMenuItem; Pessoas1: TMenuItem; Operacional1: TMenuItem; EstacionamentoAvulso1: TMenuItem; UF1: TMenuItem; ActionList1: TActionList; EstacAvulso: TAction; Lavagem1: TMenuItem; EstacionamentoMensal1: TMenuItem; Agenda: TAction; Lavagem: TAction; EstacMensal: TAction; N3: TMenuItem; ConsultaEstacionamentos1: TMenuItem; Financeiro1: TMenuItem; Contas1: TMenuItem; Movimentao1: TMenuItem; Convnios1: TMenuItem; Produtos1: TMenuItem; Funcionrios1: TMenuItem; Duplicatas1: TMenuItem; SpeedButton5: TSpeedButton; MovFinanceira: TAction; Marcas1: TMenuItem; Image1: TImage; procedure Parmetros1Click(Sender: TObject); procedure Logoff1Click(Sender: TObject); procedure Filiais1Click(Sender: TObject); procedure Pessoas1Click(Sender: TObject); procedure EstacionamentoAvulso1Click(Sender: TObject); procedure Cidades1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure Contas1Click(Sender: TObject); procedure Funcionrios1Click(Sender: TObject); procedure Movimentao1Click(Sender: TObject); procedure ConsultaEstacionamentos1Click(Sender: TObject); procedure Lavagem1Click(Sender: TObject); procedure Produtos1Click(Sender: TObject); procedure EstacionamentoMensal1Click(Sender: TObject); procedure Marcas1Click(Sender: TObject); private { Private declarations } procedure OpenForm(FClass: TFormClass; vEstado: TWindowState; TipoPessoa: String = ''); public { Public declarations } fDmParametros: TdmParametros; end; var fMenu: TfMenu; implementation uses uParametros, uDmUserControl, uFilial, uPessoa, uEstacionamentoDia, uCidade, uUF, uContas, uFuncionario, uFinanceiro, uEstacDiaCons, uLavagem, uProduto, uEstacionamentoMes, uMarca; {$R *.dfm} procedure TfMenu.OpenForm(FClass: TFormClass; vEstado: TWindowState; TipoPessoa: String = ''); var existe: TForm; j: Byte; begin existe := nil; for j := 0 to Screen.FormCount - 1 do begin if Screen.Forms[j] is FClass then existe := Screen.Forms[j]; end; if not (existe = nil) then begin existe.BringToFront; existe.SetFocus; end else begin Application.CreateForm(FClass,existe); existe.FormStyle := fsMDIChild; existe.Show; end; existe.WindowState := vEstado; end; procedure TfMenu.Parmetros1Click(Sender: TObject); begin OpenForm(TfParametros,wsMaximized); end; procedure TfMenu.Logoff1Click(Sender: TObject); begin dmUserControl.UserControl1.Logoff; end; procedure TfMenu.Filiais1Click(Sender: TObject); begin OpenForm(TfFilial,wsMaximized); end; procedure TfMenu.Pessoas1Click(Sender: TObject); begin OpenForm(TfPessoa,wsMaximized); end; procedure TfMenu.EstacionamentoAvulso1Click(Sender: TObject); begin OpenForm(TfEstacionamentoDia,wsMaximized); end; procedure TfMenu.Cidades1Click(Sender: TObject); begin OpenForm(TfCidade,wsMaximized); end; procedure TfMenu.FormShow(Sender: TObject); begin fDmParametros := tDmParametros.Create(Self); fDmParametros.cdsParametro.Open; end; procedure TfMenu.Contas1Click(Sender: TObject); begin OpenForm(TfContas,wsMaximized); end; procedure TfMenu.Funcionrios1Click(Sender: TObject); begin OpenForm(TfFuncionario,wsMaximized); end; procedure TfMenu.Movimentao1Click(Sender: TObject); begin OpenForm(TfFinanceiro,wsMaximized); end; procedure TfMenu.ConsultaEstacionamentos1Click(Sender: TObject); begin OpenForm(TfEstaciDiaCons,wsMaximized); end; procedure TfMenu.Lavagem1Click(Sender: TObject); begin OpenForm(TfLavagem,wsMaximized); end; procedure TfMenu.Produtos1Click(Sender: TObject); begin OpenForm(TfProduto,wsMaximized); end; procedure TfMenu.EstacionamentoMensal1Click(Sender: TObject); begin OpenForm(TfEstacionamentoMes,wsMaximized); end; procedure TfMenu.Marcas1Click(Sender: TObject); begin OpenForm(TfMarca,wsMaximized); end; initialization RLConsts.SetVersion(3,72,'B'); end.
unit Unit_Form; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, ComCtrls, Forms, StrUtils, StdCtrls, ExtCtrls, CheckLst, Spin, Math, Dialogs, dglOpenGL, KromOGLUtils, RN_InputGeom, RN_Recast, RN_SampleInterfaces, RN_Sample, RN_SampleSoloMesh, RN_SampleTileMesh; type TForm1 = class(TForm) Panel3: TPanel; Timer1: TTimer; Memo1: TMemo; gbSample: TGroupBox; rgTool: TRadioGroup; gbTool: TGroupBox; Panel1: TPanel; rgInputMesh: TRadioGroup; rgChooseSample: TRadioGroup; CheckBox1: TCheckBox; btnBuild: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormResize(Sender: TObject); procedure DoIdle(Sender: TObject; var Done: Boolean); procedure Panel3MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Panel3MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Timer1Timer(Sender: TObject); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure btnBuildClick(Sender: TObject); procedure btnToolClick(Sender: TObject); procedure rgChooseSampleClick(Sender: TObject); private h_DC: HDC; h_RC: HGLRC; fExeDir: string; fFrameTime: Single; fPrevX: Single; fPrevY: Single; fRotateX: Single; fRotateY: Single; fDist: Single; fRayS: array [0..2] of Single; fRayE: array [0..2] of Single; fGeom: TInputGeom; fSample: TSample; procedure InitGL; procedure UpdateModelViewProjection; end; var Form1: TForm1; implementation uses RN_RecastDump; {$R *.dfm} function ScanObjFiles(aPath: string): string; var SearchRec: TSearchRec; begin Result := ''; if not DirectoryExists(aPath) then Exit; FindFirst(aPath + '*.obj', faAnyFile - faDirectory, SearchRec); repeat Result := Result + ChangeFileExt(SearchRec.Name, '') + sLineBreak; until (FindNext(SearchRec) <> 0); FindClose(SearchRec); end; procedure TForm1.InitGL; begin //Means it will receive WM_SIZE WM_PAINT always in pair (if False - WM_PAINT is not called if size becames smaller) Panel3.FullRepaint := True; SetRenderFrameAA(Panel1.Handle, Panel3.Handle, 16, h_DC, h_RC); //RenderArea.CreateRenderContext(True); glClearColor(0.75, 0.75, 0.8, 1); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //Set alpha mode glEnable(GL_TEXTURE_2D); // Enable Texture Mapping glPolygonMode(GL_FRONT, GL_FILL); glEnable(GL_NORMALIZE); glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_COLOR_MATERIAL); //Enable Materials glDisable(GL_LIGHTING); //We don't need it glEnable(GL_DEPTH_TEST); if WGL_EXT_swap_control then wglSwapIntervalEXT(0); FormResize(Self); end; procedure TForm1.FormCreate(Sender: TObject); begin Set8087CW($133F); fExeDir := ExtractFilePath(Application.ExeName); rgInputMesh.Items.Text := ScanObjFiles(fExeDir); fDist := 100; fRotateY := -45; InitGL; fRotateX := 0; rgChooseSampleClick(nil); btnBuildClick(nil); Application.OnIdle := DoIdle; end; procedure TForm1.FormDestroy(Sender: TObject); begin fGeom.Free; fSample.Free; end; procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin if Panel3.BoundsRect.Contains(ScreenToClient(MousePos)) then fDist := fDist - Sign(WheelDelta) * 5; UpdateModelViewProjection; Handled := True; end; procedure TForm1.FormResize(Sender: TObject); begin glViewport(0, 0, Panel3.Width, Panel3.Height); UpdateModelViewProjection; end; procedure TForm1.rgChooseSampleClick(Sender: TObject); begin FreeAndNil(fSample); case rgChooseSample.ItemIndex of 0: fSample := TSample_SoloMesh.Create(gbSample, gbTool, rgTool); 1: fSample := TSample_TileMesh.Create(gbSample, gbTool, rgTool); end; end; procedure TForm1.Panel3MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var hitt: Single; hit: Boolean; pos: array [0..2] of Single; begin if (fGeom <> nil) and (fSample <> nil) then begin hit := fGeom.raycastMesh(@fRayS[0], @fRayE[0], @hitt); if (hit) then begin pos[0] := fRayS[0] + (fRayE[0] - fRayS[0])*hitt; pos[1] := fRayS[1] + (fRayE[1] - fRayS[1])*hitt; pos[2] := fRayS[2] + (fRayE[2] - fRayS[2])*hitt; fSample.handleClick(@fRayS[0], @pos[0], Button = mbRight); end; end; fPrevX := X; fPrevY := Y; end; procedure TForm1.Panel3MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var proj, model: TGLMatrixd4; view: TGLVectori4; dx,dy,dz: Double; begin if ssLeft in Shift then begin fRotateX := fRotateX + (X - fPrevX); fRotateY := EnsureRange(fRotateY + (Y - fPrevY), -85, 85); UpdateModelViewProjection; fPrevX := X; fPrevY := Y; end; // Get hit ray position and direction. glGetDoublev(GL_PROJECTION_MATRIX, @proj[0,0]); glGetDoublev(GL_MODELVIEW_MATRIX, @model[0,0]); glGetIntegerv(GL_VIEWPORT, @view[0]); gluUnProject(X, Panel3.Height - Y, 0.0, model, proj, view, @dx, @dy, @dz); fRayS[0] := dx; fRayS[1] := dy; fRayS[2] := dz; gluUnProject(X, Panel3.Height - Y, 1.0, model, proj, view, @dx, @dy, @dz); fRayE[0] := dx; fRayE[1] := dy; fRayE[2] := dz; end; procedure TForm1.btnBuildClick(Sender: TObject); var ctx: TBuildContext; meshName: string; I: Integer; begin ctx := TBuildContext.Create; meshName := fExeDir + rgInputMesh.Items[rgInputMesh.ItemIndex] + '.obj'; fGeom := TInputGeom.Create; fGeom.loadMesh(ctx, meshName); fSample.setContext := ctx; fSample.handleMeshChanged(fGeom); fSample.handleSettings; ctx.resetLog(); if fSample.handleBuild() then ctx.dumpLog(Format('Build log %s: ', [meshName])); for I := 0 to ctx.getLogCount - 1 do Memo1.Lines.Append(ctx.getLogText(I)); ctx.Free; end; procedure TForm1.btnToolClick(Sender: TObject); begin fSample.handleMenu(Sender); end; procedure TForm1.DoIdle(Sender: TObject; var Done: Boolean); var prevTime: Int64; freq: Int64; newTime: Int64; begin QueryPerformanceCounter(prevTime); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // Axis glLineWidth(2); glBegin(GL_LINES); glColor4f(1,0,0,1); glVertex3f(0,0,0); glVertex3f(1,0,0); glColor4f(0,1,0,1); glVertex3f(0,0,0); glVertex3f(0,1,0); glColor4f(0,0,1,1); glVertex3f(0,0,0); glVertex3f(0,0,1); glEnd; if fSample <> nil then fSample.handleRender; SwapBuffers(h_DC); QueryPerformanceFrequency(freq); QueryPerformanceCounter(newTime); fFrameTime := (newTime - prevTime) / (freq / 1000); Done := False; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption := 'Pathfinding Recast/Detour/Crowd ' + Format('%.1f', [1000 / fFrameTime]); if fSample <> nil then fSample.handleUpdate(0.05); end; procedure TForm1.UpdateModelViewProjection; var dx, dy, dz: Single; eyeX, eyeY, eyeZ: Single; begin {$POINTERMATH ON} glMatrixMode(GL_PROJECTION); //Change Matrix Mode to Projection glLoadIdentity; gluPerspective(45, Panel3.Width / Panel3.Height, 0.01, 1000); dx := 0; dy := 0; dz := 0; if fSample <> nil then begin dx := (fSample.getBoundsMin[0] + fSample.getBoundsMax[0]) / 2; dy := (fSample.getBoundsMin[1] + fSample.getBoundsMax[1]) / 2; dz := (fSample.getBoundsMin[2] + fSample.getBoundsMax[2]) / 2; end; eyeX := Sin(fRotateX / 180 * pi) * Cos(fRotateY / 180 * pi) * fDist; eyeY := Cos(fRotateX / 180 * pi) * Cos(fRotateY / 180 * pi) * fDist; eyeZ := Sin(fRotateY / 180 * pi) * fDist; glMatrixMode(GL_MODELVIEW); //Return to the modelview matrix glLoadIdentity; gluLookAt(eyeX + dx, eyeY + dy, eyeZ + dz, dx, dy, dz, 0, 0, 1); {$POINTERMATH OFF} end; end.
unit UnitStringCompression; interface uses ZLibEx, StreamUnit; function CompressString(Str: string): string; function DecompressString(Str: string): string; function StreamToStr(Stream: TStream): string; procedure StrToStream(S: string; Stream: TStream); implementation function StreamToStr(Stream: TStream): string; var i: Int64; begin Stream.Position := 0; i := Stream.Size; SetLength(Result, i); Stream.Read(Result[1], i); end; procedure StrToStream(S: string; Stream: TStream); begin Stream.Position := 0; Stream.Write(S[1], Length(S)); end; function CompressString(Str: string): string; var zCompression: TZCompressionStream; inStream, outStream: TMemoryStream; begin Result := ''; inStream := TMemoryStream.Create; outStream := TMemoryStream.Create; StrToStream(Str, inStream); inStream.Position := 0; zCompression := TZCompressionStream.Create(outStream, zcFastest); zCompression.CopyFrom(inStream, inStream.Size); zCompression.Free; Result := StreamToStr(outStream); inStream.Free; outStream.Free; end; function DecompressString(Str: string): string; const BufferSize = 4096; var zDecompression: TZDecompressionStream; inStream, outStream: TMemoryStream; Buffer: array[0..BufferSize-1] of Byte; Count: Integer; begin Result := ''; inStream := TMemoryStream.Create; outStream := TMemoryStream.Create; StrToStream(Str, inStream); inStream.Position := 0; zDecompression := TZDecompressionStream.Create(inStream); while True do begin Count := zDecompression.Read(Buffer, BufferSize); if Count <> 0 then outStream.WriteBuffer(Buffer, Count) else Break; end; zDecompression.Free; Result := StreamToStr(outStream); inStream.Free; outStream.Free; end; end.
unit Security4D; interface uses System.SysUtils; type ESecurityException = class(Exception); EAuthenticatorException = class(ESecurityException); EAuthorizerException = class(ESecurityException); EAuthorizationException = class(ESecurityException); EAuthenticationException = class(ESecurityException); ISecurity = interface ['{B15DCFD8-2069-4627-AB4B-CB618D71819D}'] end; IUser = interface(ISecurity) ['{4CCA6359-1BBC-41F6-9CE9-4B3F00DDE0D4}'] function GetId: string; function GetAttribute: TObject; property Id: string read GetId; property Attribute: TObject read GetAttribute; end; IAuthenticator = interface(ISecurity) ['{246AFE44-0901-4DAE-8CD4-6A3A4E9021B0}'] function GetAuthenticatedUser: IUser; procedure Authenticate(user: IUser); procedure Unauthenticate; property AuthenticatedUser: IUser read GetAuthenticatedUser; end; IAuthorizer = interface(ISecurity) ['{EB117E9A-F25C-4EF9-9F55-F08D46675BE2}'] function HasRole(const role: string): Boolean; function HasPermission(const resource, operation: string): Boolean; end; ISecurityContext = interface(ISecurity) ['{66F6C8D2-DF1E-479A-946A-1B6111F182DF}'] function GetAuthenticatedUser: IUser; procedure RegisterAuthenticator(authenticator: IAuthenticator); procedure RegisterAuthorizer(authorizer: IAuthorizer); procedure OnAfterLoginSuccessful(event: TProc); procedure OnAfterLogoutSuccessful(event: TProc); procedure Login(user: IUser); procedure Logout; function IsLoggedIn: Boolean; procedure CheckLoggedIn; function HasRole(const role: string): Boolean; function HasPermission(const resource, operation: string): Boolean; property AuthenticatedUser: IUser read GetAuthenticatedUser; end; implementation end.
unit FIToolkit.Config.TypedDefaults; interface uses System.SysUtils, System.Types, FIToolkit.Config.Defaults, FIToolkit.Config.Types; type TDefaultBooleanValue = class (TDefaultValueAttribute<Boolean>); TDefaultFileNameValue = class (TDefaultValueAttribute<TFileName>); TDefaultIntegerValue = class (TDefaultValueAttribute<Integer>); TDefaultOutputFormatValue = class (TDefaultValueAttribute<TFixInsightOutputFormat>); TDefaultStringArrayValue = class (TDefaultValueAttribute<TStringDynArray>); TDefaultStringValue = class (TDefaultValueAttribute<String>); implementation end.
unit CRC32U; interface uses Winapi.Windows, System.SysUtils; type TCrc32 = record public class procedure Hash(p: Pointer; ByteCount: DWORD; var CRCValue: DWORD); overload; static; class function Hash(input: string): DWORD; overload; static; end; implementation const Table: array [0 .. 255] of DWORD = ($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, $4FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD, $48B2364B, $D80D2BDA, $AF0A1B4C, $36034AF6, $41047A60, $DF60EFC3, $A867DF55, $316E8EEF, $4669BE79, $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); { TCrc32 } class function TCrc32.Hash(input: string): DWORD; var CRC32Table: DWORD; begin CRC32Table := $FFFFFFFF; Hash(Addr(Table[0]), SizeOf(Table), CRC32Table); CRC32Table := not CRC32Table; if CRC32Table <> $6FCF9E13 then raise Exception.Create('CRC32 Table CRC32 is ' + IntToHex(CRC32Table, 8) + ', expecting $6FCF9E13'); Result := $FFFFFFFF; if Length(input) > 0 then Hash(Addr(input[1]), Length(input), Result); Result := not Result; end; class procedure TCrc32.Hash(p: Pointer; ByteCount: DWORD; var CRCValue: DWORD); var i: DWORD; q: ^BYTE; begin q := p; for i := 0 to ByteCount - 1 do begin CRCValue := (CRCValue shr 8) xor Table[q^ xor (CRCValue and $000000FF)]; Inc(q) end; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit FlashLightU; interface uses System.TypInfo, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Effects, FMX.Objects, FMX.Layouts, FMX.Media; type TFlashLightForm = class(TForm) FlashLight: TImage; ImageOn: TImage; FlashLightShadow: TShadowEffect; Light: TImage; ImageOff: TImage; ContainerLayout: TLayout; Camera: TCameraComponent; GlowEffect1: TGlowEffect; LayoutButtons: TLayout; procedure FormCreate(Sender: TObject); procedure ImageOffClick(Sender: TObject); procedure ImageOnClick(Sender: TObject); private procedure SetFlashlightState(Active : Boolean); public { Public declarations } end; var FlashLightForm: TFlashLightForm; implementation {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} procedure TFlashLightForm.SetFlashlightState(Active : Boolean); begin if Active then begin Camera.TorchMode := TTorchMode.ModeOn; end else Camera.TorchMode := TTorchMode.ModeOff; end; procedure TFlashLightForm.FormCreate(Sender: TObject); begin ImageOff.Enabled := Camera.HasFlash; Camera.Active := True; end; procedure TFlashLightForm.ImageOffClick(Sender: TObject); begin ImageOff.Visible := False; ImageOn.Visible := True; SetFlashlightState(True); Light.Visible := True; end; procedure TFlashLightForm.ImageOnClick(Sender: TObject); begin ImageOff.Visible := True; ImageOn.Visible := False; SetFlashlightState(False); Light.Visible := False; end; end.
(***********************************************************) (* xPLRFX *) (* part of Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (***********************************************************) unit uxPLRFXConst; interface const XPLSOURCE = 'xplrfx'; x10_DESCRIPTION = '0x10 - ARC, ELRO, Waveman, EMW200, IMPULS, RisingSun, Philips, Energenie 18'; x11_DESCRIPTION = '0x11 - AC, HomeEasy EU, ANSLUT'; x12_DESCRIPTION = '0x12 - Koppla'; x13_DESCRIPTION = '0x13 - PT2262'; x14_DESCRIPTION = '0x14 - LightwaveRF, Siemens, EMW100, BBSB, MDREMOTE, RSL2'; x15_DESCRIPTION = '0x15 - Blyss'; x18_DESCRIPTION = '0x18 - Harrison'; x19_DESCRIPTION = '0x19 - RollerTrol, Hasta, A-OK, Raex, Media Mount'; x20_DESCRIPTION = '0x20 - X10, KD101, Visonic, Meiantech'; x28_DESCRIPTION = '0x28 - X10 Ninja/Robocam'; x30_DESCRIPTION = '0x30 - ATI, Medion, PC Remote'; x40_DESCRIPTION = '0x40 - Digimax'; x41_DESCRIPTION = '0x41 - HomeEasy HE105, RTS10'; x42_DESCRIPTION = '0x42 - Mertik-Maxitrol G6R-H4T1 / G6R-H4TB'; x50_DESCRIPTION = '0x50 - Temperature Sensors'; x51_DESCRIPTION = '0x51 - Humidity sensors'; x52_DESCRIPTION = '0x52 - Temperature and humidity sensors'; x53_DESCRIPTION = '0x53 - Barometric sensors'; x54_DESCRIPTION = '0x54 - Temperature, humidity and barometric sensors'; x55_DESCRIPTION = '0x55 - Rain Sensors'; x56_DESCRIPTION = '0x56 - Wind Sensors '; x57_DESCRIPTION = '0x57 - UV Sensors'; x58_DESCRIPTION = '0x58 - Date and Time'; x59_DESCRIPTION = '0x59 - Current Sensors'; x5A_DESCRIPTION = '0x5A - Energy Usage Sensors'; x5B_DESCRIPTION = '0x5B - Current + Energy Sensors'; x5D_DESCRIPTION = '0x5D - Weighting Scale'; x70_DESCRIPTION = '0x70 - RFXsensor'; x71_DESCRIPTION = '0x71 - RFXMeter'; x72_DESCRIPTION = '0x72 - FS20'; type BytesArray = array[0..39] of Byte; // Must be static array, not dynamic !! TRFXCommandRec = record RFXCode : Byte; xPLCommand : String; end; TRFXSubTypeRec = record SubType : Byte; SubTypeString : String; end; TRFXCommandArray = array of TRFXCommandRec; function GetRFXCode(xPLCommand : String; const RFXCommandArray : array of TRFXCommandRec) : Byte; function GetxPLCommand(RFXCode : Byte; const RFXCommandArray : array of TRFXCommandRec) : String; function GetSubTypeString(ST : Byte; const RFXSubTypeArray : array of TRFXSubTypeRec) : String; function GetSubTypeFromString(Str : String; const RFXSubTypeArray : array of TRFXSubTypeRec) : Byte; function HexToBytes(Str : String) : BytesArray; function BytesArrayToStr(Buffer : BytesArray) : String; procedure OpenLog; procedure CloseLog; procedure Log(const Str : String); procedure ResetBuffer(var Buffer : BytesArray); implementation Uses SysUtils; var F : TextFile; function GetxPLCommand(RFXCode : Byte; const RFXCommandArray : array of TRFXCommandRec) : String; var i : Integer; begin // By default, return empty string Result := ''; // Go through the table, and find the RFXCode for i := Low(RFXCommandArray) to High(RFXCommandArray) do if RFXCommandArray[i].RFXCode = RFXCode then begin Result := RFXCommandArray[i].xPLCommand; Break; end; end; function GetRFXCode(xPLCommand : String; const RFXCommandArray : array of TRFXCommandRec) : Byte; var i : Integer; begin // By default, return error code Result := $FF; // Go through the table, and find the xPLCommand for i := Low(RFXCommandArray) to High(RFXCommandArray) do if CompareText(RFXCommandArray[i].xPLCommand, xPLCommand) = 0 then begin Result := RFXCommandArray[i].RFXCode; Break; end; end; function GetSubTypeString(ST : Byte; const RFXSubTypeArray : array of TRFXSubTypeRec) : String; var i : Integer; begin // By default, return empty string Result := ''; // Go through the table, and find the RFXCode for i := Low(RFXSubTypeArray) to High(RFXSubTypeArray) do if RFXSubTypeArray[i].SubType = ST then begin Result := RFXSubTypeArray[i].SubTypeString; Break; end; end; function GetSubTypeFromString(Str : String; const RFXSubtypeArray : array of TRFXSubTypeRec) : Byte; var i : Integer; begin Result := $FF; for i := Low(RFXSubTypeArray) to High(RFXSubTypeArray) do if CompareText(RFXSubTypeArray[i].SubTypeString, Str) = 0 then begin Result := RFXSubTypeArray[i].SubType; Break; end; end; function HexToBytes(Str : String) : BytesArray; var i : Integer; SubStr : String; begin //SetLength(Result,Length(Str) div 2); ResetBuffer(Result); for i := 0 to (Length(Str) div 2)-1 do begin SubStr := Copy(Str,1,2); Str := Copy(Str,3,Length(Str)); Result[i] := StrToInt('$'+SubStr); end; end; function BytesArrayToStr(Buffer : BytesArray) : String; var i : Integer; begin for i := 0 to Length(Buffer)-1 do Result := Result + IntToHex(Buffer[i],2); end; procedure OpenLog; begin AssignFile(F,ExtractFilePath(ParamStr(0))+'xPLRFX.log'); Rewrite(F); end; procedure CloseLog; begin CloseFile(F); end; procedure Log(const Str : String); begin Writeln(F,Str); end; procedure ResetBuffer(var Buffer : BytesArray); var i : Integer; begin // Set all bytes to 0 for i := Low(Buffer) to High(Buffer) do Buffer[i] := $00; end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit System.Bindings.NotifierContracts; interface uses System.SysUtils, System.Generics.Collections, System.Bindings.Manager; type EBindingNotifyError = class(Exception); IBindingNotifier = interface; TBindingNotifReservedType = (bnrtExternal, bnrtInternal); /// <summary> /// Anyone who is interested in receiving notifications from an object about /// changes that happen in the properties of the object must implement this /// interface. </summary> IBindingNotification = interface ['{83360F64-6260-4029-96B3-070FB253F075}'] procedure Notification(Notifier: IBindingNotifier; const PropertyName: String); end; /// <summary> /// Used by bindable objects to notify the expressions in which they are present /// about the changes of one of their properties.</summary> IBindingNotifier = interface ['{767FC59A-C8D9-4810-9A9E-B7648706F0B6}'] function GetOwner: TObject; function GetManager: TBindingManager; function GetReserved: TBindingNotifReservedType; procedure SetReserved(Value: TBindingNotifReservedType); procedure SetOwner(Value: TObject); // notifies all the Expressions that the value of PropertyName has changed procedure Notify(const PropertyName: String); property Owner: TObject read GetOwner write SetOwner; property Manager: TBindingManager read GetManager; // used internally; never change the value of this property as a user property Reserved: TBindingNotifReservedType read GetReserved write SetReserved; end; implementation end.
unit MediaStream.PtzProtocol.Http; interface uses SysUtils, Classes, MediaStream.PtzProtocol.Base,Http.Cgi, Generics.Collections; type TPtzProtocol_Http = class (TPtzProtocol) private FAddress: string; FPort: Word; FUser, FPassword: string; procedure Init(const aAddress: string; aPort: Word; const aUser,aPassword: string); protected procedure ExecutePost(const aCommand: string); function ExecuteGet(const aCommand: string): string; procedure TraceLine(const aMessage: string); public constructor Create(const aAddress: string; aPort: Word; const aUser,aPassword: string); virtual; destructor Destroy; override; class function Name: string; virtual; abstract; end; TPtzProtocol_HttpClass = class of TPtzProtocol_Http; TPtzProtocol_HttpRegistry = class private FProtocols : TList<TPtzProtocol_HttpClass>; function GetProtocol(index: integer): TPtzProtocol_HttpClass; public procedure AddProtocol(aProtocolClass: TPtzProtocol_HttpClass); property Protocols[index: integer]: TPtzProtocol_HttpClass read GetProtocol; function Count: integer; constructor Create; destructor Destroy; override; end; function ProtocolRegistry: TPtzProtocol_HttpRegistry; implementation uses uTrace, {implementations} MediaStream.PtzProtocol.Http.Everfocus; var gProtocolRegistry: TPtzProtocol_HttpRegistry; function ProtocolRegistry: TPtzProtocol_HttpRegistry; begin if gProtocolRegistry=nil then gProtocolRegistry:=TPtzProtocol_HttpRegistry.Create; result:=gProtocolRegistry; end; constructor TPtzProtocol_Http.Create(const aAddress: string; aPort: Word; const aUser, aPassword: string); var s: string; begin Init(aAddress,aPort,aUser,aPassword); s:=StringReplace(Copy(ClassName,2,High(Word)),'_','.',[rfReplaceAll]); RegisterCustomTrace(ClassName,'','.'+s); end; destructor TPtzProtocol_Http.Destroy; begin inherited; end; function TPtzProtocol_Http.ExecuteGet(const aCommand: string): string; var aCgi: TCgi; begin inherited; TraceLine('REQUEST GET: '+aCommand); try aCgi:=TCgi.Create(FAddress, FPort, FUser, FPassword); try result:=aCgi.Get(aCommand); finally aCgi.Free; end; TraceLine('ANSWER: '+result); except on E:Exception do begin TraceLine('ERROR: '+E.Message); raise; end; end; end; procedure TPtzProtocol_Http.ExecutePost(const aCommand: string); var aCgi: TCgi; begin inherited; TraceLine('REQUEST POST: '+aCommand); try aCgi:=TCgi.Create(FAddress, FPort, FUser, FPassword); try //TraceLine(); aCgi.Post(aCommand); finally aCgi.Free; end; TraceLine('ANSWER: OK'); except on E:Exception do begin TraceLine('ERROR: '+E.Message); raise; end; end; end; procedure TPtzProtocol_Http.Init(const aAddress: string; aPort: Word; const aUser,aPassword: string); begin FAddress:=aAddress; FPort:=aPort; FUser:=aUser; FPassword:=aPassword; end; procedure TPtzProtocol_Http.TraceLine(const aMessage: string); begin uTrace.TraceLine(ClassName,aMessage); end; { TPtzProtocol_HttpRegistry } procedure TPtzProtocol_HttpRegistry.AddProtocol( aProtocolClass: TPtzProtocol_HttpClass); begin FProtocols.Add(aProtocolClass); end; function TPtzProtocol_HttpRegistry.Count: integer; begin result:=FProtocols.Count; end; constructor TPtzProtocol_HttpRegistry.Create; begin FProtocols:=TList<TPtzProtocol_HttpClass>.Create; end; destructor TPtzProtocol_HttpRegistry.Destroy; begin FreeAndNil(FProtocols); inherited; end; function TPtzProtocol_HttpRegistry.GetProtocol(index: integer): TPtzProtocol_HttpClass; begin result:=FProtocols[index]; end; initialization finalization FreeAndNil(gProtocolRegistry); end.
unit DrillType; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, Buttons, DB, ExtCtrls; type TDrillTypeForm = class(TForm) btn_ok: TBitBtn; btn_cancel: TBitBtn; Gbox: TGroupBox; sgDrillType: TStringGrid; gbox2: TGroupBox; lblD_t_name: TLabel; edtD_t_name: TEdit; btn_add: TBitBtn; btn_delete: TBitBtn; btn_edit: TBitBtn; procedure FormCreate(Sender: TObject); procedure sgDrillTypeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure btn_cancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btn_addClick(Sender: TObject); procedure btn_deleteClick(Sender: TObject); procedure btn_okClick(Sender: TObject); procedure btn_editClick(Sender: TObject); procedure edtD_t_noKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtD_t_nameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure button_status(int_status:integer;bHaveRecord:boolean); procedure Get_oneRecord(aRow:Integer); function GetInsertSQL:string; function GetUpdateSQL:string; function GetDeleteSQL:string; function Check_Data:boolean; function isExistedRecord(aDrillTypeName:string):boolean; public { Public declarations } end; var DrillTypeForm: TDrillTypeForm; m_sgDrillTypeSelectedRow: integer; m_DataSetState: TDataSetState; implementation uses MainDM, public_unit; {$R *.dfm} procedure TDrillTypeForm.button_status(int_status: integer; bHaveRecord: boolean); begin case int_status of 1: //浏览状态 begin btn_edit.Enabled :=bHaveRecord; btn_delete.Enabled :=bHaveRecord; btn_edit.Caption :='修改'; btn_ok.Enabled :=false; btn_add.Enabled :=true; Enable_Components(self,false); m_DataSetState := dsBrowse; end; 2: //修改状态 begin btn_edit.Enabled :=true; btn_edit.Caption :='放弃'; btn_ok.Enabled :=true; btn_add.Enabled :=false; btn_delete.Enabled :=false; Enable_Components(self,true); m_DataSetState := dsEdit; end; 3: //增加状态 begin btn_edit.Enabled :=true; btn_edit.Caption :='放弃'; btn_ok.Enabled :=true; btn_add.Enabled :=false; btn_delete.Enabled :=false; Enable_Components(self,true); m_DataSetState := dsInsert; end; end; end; procedure TDrillTypeForm.FormCreate(Sender: TObject); var i: integer; begin self.Left := trunc((screen.Width -self.Width)/2); self.Top := trunc((Screen.Height - self.Height)/2); sgDrillType.RowHeights[0] := 16; sgDrillType.Cells[1,0] := '钻孔类型'; sgDrillType.ColWidths[0]:=10; sgDrillType.ColWidths[1]:=125; m_sgDrillTypeSelectedRow:= -1; Clear_Data(self); with MainDataModule.qryDrill_type do begin close; sql.Clear; sql.Add('SELECT d_t_no,d_t_name FROM drill_type'); open; i:=0; while not Eof do begin i:=i+1; sgDrillType.RowCount := i +1; sgDrillType.Cells[1,i] := FieldByName('d_t_name').AsString; Next ; end; close; end; if i>0 then begin sgDrillType.Row :=1; m_sgDrillTypeSelectedRow :=1; Get_oneRecord(1); button_status(1,true); end else button_status(1,false); end; procedure TDrillTypeForm.Get_oneRecord(aRow: Integer); begin edtD_t_name.Text := sgDrillType.Cells[1,aRow]; end; procedure TDrillTypeForm.sgDrillTypeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if (ARow <>0) and (ARow<>m_sgDrillTypeSelectedRow) then if sgDrillType.Cells[1,ARow]<>'' then begin Get_oneRecord(aRow); if sgDrillType.Cells[1,ARow]='' then Button_status(1,false) else Button_status(1,true); end else clear_data(self); m_sgDrillTypeSelectedRow:=ARow; end; procedure TDrillTypeForm.btn_cancelClick(Sender: TObject); begin self.Close; end; procedure TDrillTypeForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := cafree; end; function TDrillTypeForm.Check_Data: boolean; begin if trim(edtD_t_name.Text) = '' then begin messagebox(self.Handle,'请输入类别名称!','数据校对',mb_ok); edtD_t_name.SetFocus; result := false; exit; end; result := true; end; function TDrillTypeForm.GetDeleteSQL: string; begin result :='DELETE FROM drill_type WHERE d_t_name='+ ''''+sgDrillType.Cells[1,sgDrillType.row]+''''; end; function TDrillTypeForm.isExistedRecord(aDrillTypeName: string): boolean; begin with MainDataModule.qryDrill_type do begin close; sql.Clear; sql.Add('SELECT d_t_no,d_t_name FROM drill_type WHERE d_t_name='+ ''''+aDrillTypeName+''''); try try Open; if eof then result:=false else begin result:=true; messagebox(self.Handle,'此类别已经存在,请输入新的类别!','数据校对',mb_ok); edtD_t_name.SetFocus; end; except result:=false; end; finally close; end; end; end; procedure TDrillTypeForm.btn_addClick(Sender: TObject); begin Clear_Data(self); Button_status(3,true); edtD_t_name.SetFocus; end; procedure TDrillTypeForm.btn_deleteClick(Sender: TObject); var strSQL: string; begin if MessageBox(self.Handle, '您确定要删除吗?','警告', MB_YESNO+MB_ICONQUESTION)=IDNO then exit; if edtD_t_name.Text <> '' then begin strSQL := self.GetDeleteSQL; if Delete_oneRecord(MainDataModule.qryDrill_type,strSQL) then begin Clear_Data(self); DeleteStringGridRow(sgDrillType,sgDrillType.Row); self.Get_oneRecord(sgDrillType.Row); if sgDrillType.Cells[1,sgDrillType.row]='' then button_status(1,false) else button_status(1,true); end; end; end; procedure TDrillTypeForm.btn_okClick(Sender: TObject); var strSQL: string; begin if not Check_Data then exit; if m_DataSetState = dsInsert then begin if isExistedRecord(trim(edtD_t_name.Text)) then exit; strSQL := self.GetInsertSQL; if Insert_oneRecord(MainDataModule.qryDrill_type,strSQL) then begin if (sgDrillType.RowCount =2) and (sgDrillType.Cells[1,1] <>'') then sgDrillType.RowCount := sgDrillType.RowCount+1; m_sgDrillTypeSelectedRow:= sgDrillType.RowCount-1; sgDrillType.Cells[1,sgDrillType.RowCount-1] := trim(edtD_t_name.Text); sgDrillType.Row := sgDrillType.RowCount-1; Button_status(1,true); btn_add.SetFocus; end; end else if m_DataSetState = dsEdit then begin if sgDrillType.Cells[1,sgDrillType.Row]<>trim(edtD_t_name.Text) then if isExistedRecord(trim(edtD_t_name.Text)) then exit; strSQL := self.GetUpdateSQL; if Update_oneRecord(MainDataModule.qryDrill_type,strSQL) then begin sgDrillType.Cells[1,sgDrillType.Row] := edtD_t_name.Text ; Button_status(1,true); btn_add.SetFocus; end; end; end; function TDrillTypeForm.GetInsertSQL: string; begin result := 'INSERT INTO drill_type (d_t_name) VALUES(' +''''+trim(edtD_t_name.Text)+''''+')'; end; function TDrillTypeForm.GetUpdateSQL: string; var strSQLWhere,strSQLSet:string; begin strSQLWhere:=' WHERE d_t_name='+''''+sgDrillType.Cells[1,sgDrillType.Row]+''''; strSQLSet:='UPDATE drill_type SET '; strSQLSet := strSQLSet + 'd_t_name' +'='+''''+trim(edtD_t_name.Text)+''''; result := strSQLSet + strSQLWhere; end; procedure TDrillTypeForm.btn_editClick(Sender: TObject); begin if btn_edit.Caption ='修改' then begin Button_status(2,true); edtD_t_name.SetFocus; end else begin clear_data(self); Button_status(1,true); self.Get_oneRecord(sgDrillType.Row); end; end; procedure TDrillTypeForm.edtD_t_noKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin change_focus(key,self); end; procedure TDrillTypeForm.edtD_t_nameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin change_focus(key,self); end; end.
unit xTCPServerBase; interface uses xCommBase, System.Types, xTypes, System.Classes, xFunction, system.SysUtils, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdGlobal, IdContext; type /// <summary> /// 客户端状态改变事件 /// </summary> TTCPClientChangeEvent = procedure( AIP: string; nPort: Integer; AConnected: Boolean ) of object; type TTCPServerBase = class(TCommBase) private FTCPServer: TIdTCPServer; FListenPort: Word; FOnClientChange: TTCPClientChangeEvent; FOnIPSendRev: TIPSendRevPack; procedure TCPServerExecute(AContext: TIdContext); procedure TCPServerConnect(AContext: TIdContext); procedure TCPServerDisConnect(AContext: TIdContext); function SendIPData(sIP: string; nPort :Integer; APacks: TArray<Byte>) : Boolean; protected /// <summary> ///真实发送 串口或以太网发送 /// </summary> function RealSend(APacks: TArray<Byte>; sParam1: string = ''; sParam2 : string=''): Boolean; override; /// <summary> /// 真实连接 /// </summary> function RealConnect : Boolean; override; /// <summary> /// 真实断开连接 /// </summary> procedure RealDisconnect; override; /// <summary> /// 接收数据 /// </summary> procedure RevPacksData(sIP: string; nPort :Integer;aPacks: TArray<Byte>); overload;virtual; procedure RevStrData(sIP: string; nPort :Integer; sStr: string); overload;virtual; public constructor Create; override; destructor Destroy; override; /// <summary> /// 发送数据 /// </summary> function SendPacksDataTCP(sIP: string; nPort :Integer; APacks: TArray<Byte>): Boolean; overload; virtual; function SendPacksDataTCP(sIP: string; nPort :Integer; sStr: string): Boolean; overload; virtual; /// <summary> /// 监听端口 /// </summary> property ListenPort : Word read FListenPort write FListenPort; /// <summary> /// 客户端状态改变事件 /// </summary> property OnClientChange : TTCPClientChangeEvent read FOnClientChange write FOnClientChange; /// <summary> /// 带IP地址和端口的发送和接收事件 /// </summary> property OnIPSendRev : TIPSendRevPack read FOnIPSendRev write FOnIPSendRev; end; implementation { TTCPServerBase } constructor TTCPServerBase.Create; begin inherited; FTCPServer:= TIdTCPServer.Create; FTCPServer.OnExecute := TCPServerExecute; FTCPServer.OnConnect := TCPServerConnect; FTCPServer.OnDisconnect := TCPServerDisConnect; FListenPort := 10000; end; destructor TTCPServerBase.Destroy; begin try FTCPServer.Free; finally end; inherited; end; function TTCPServerBase.RealConnect: Boolean; var s : string; begin FTCPServer.DefaultPort := FListenPort; try FTCPServer.Active := True; finally Result := FTCPServer.Active; if Result then s := '成功' else s := '失败'; Log(FormatDateTime('hh:mm:ss:zzz', Now) + ' 启动侦听端口'+inttostr(FListenPort)+s); end; end; procedure TTCPServerBase.RealDisconnect; begin inherited; FTCPServer.Active := False; Log(FormatDateTime('hh:mm:ss:zzz', Now) + ' 停止侦听端口'+inttostr(FListenPort)); end; function TTCPServerBase.RealSend(APacks: TArray<Byte>; sParam1, sParam2 : string): Boolean; var sIP : string; nPort : Integer; begin sIP := sParam1; TryStrToInt(sParam2, nPort); Result := SendIPData(sIP, nPort, APacks); end; procedure TTCPServerBase.RevPacksData(sIP: string; nPort: Integer; aPacks: TArray<Byte>); begin RevPacksData(aPacks); if Assigned(FOnIPSendRev) then FOnIPSendRev(sIP, nPort, APacks, False); end; procedure TTCPServerBase.RevStrData(sIP: string; nPort: Integer; sStr: string); begin RevStrData( sStr); end; function TTCPServerBase.SendPacksDataTCP(sIP: string; nPort: Integer; APacks: TArray<Byte>): Boolean; begin Result := SendPacksDataBase(APacks, sIP, IntToStr(nPort)); end; function TTCPServerBase.SendIPData(sIP: string; nPort: Integer; APacks: TArray<Byte>) : Boolean; var i : Integer; Context : TIdContext; begin Result := False; if (sIP <> '') and (nPort > 10) then begin try for i := 0 to FTCPServer.Contexts.LockList.Count - 1 do begin with TIdContext(FTCPServer.Contexts.LockList.Items[i]).Connection do begin if (Socket.Binding.PeerIP = sIP) and (Socket.Binding.PeerPort = nPort) then begin try if Connected then begin IOHandler.Write(PacksToStr(APacks)); Result := True; if Assigned(FOnIPSendRev) then FOnIPSendRev(sIP, nPort, APacks, True); end; except end; Break; end; end; end; finally FTCPServer.Contexts.UnlockList; end; end else begin try with FTCPServer.Contexts.LockList do begin for i := 0 to Count -1 do begin Context := TIdContext(Items[i]); Context.Connection.IOHandler.Write(PacksToStr(APacks)); Result := True; if Assigned(FOnIPSendRev) then FOnIPSendRev(Context.Connection.Socket.Binding.PeerIP, Context.Connection.Socket.Binding.PeerPort, APacks, True); end; end; finally FTCPServer.Contexts.UnlockList; end; end; end; function TTCPServerBase.SendPacksDataTCP(sIP: string; nPort: Integer; sStr: string): Boolean; begin Result := SendPacksDataTCP(sIP, nPort, StrToPacks(sStr)); end; procedure TTCPServerBase.TCPServerConnect(AContext: TIdContext); begin if Assigned(FOnClientChange) then begin with AContext.Connection.Socket.Binding do begin FOnClientChange(PeerIP, PeerPort, True); end; end; end; procedure TTCPServerBase.TCPServerDisConnect(AContext: TIdContext); begin if Assigned(FOnClientChange) then begin with AContext.Connection.Socket.Binding do begin FOnClientChange(PeerIP, PeerPort, False); end; end; end; procedure TTCPServerBase.TCPServerExecute(AContext: TIdContext); var aBuf : TIdBytes; s : string; i : Integer; sIP : string; nPort : Integer; begin AContext.Connection.IOHandler.CheckForDisconnect(True, True); if not AContext.Connection.Socket.InputBufferIsEmpty then begin AContext.Connection.Socket.ReadBytes(aBuf, AContext.Connection.Socket.InputBuffer.Size); s := ''; for i := 0 to Length(aBuf) - 1 do s := s + Char(aBuf[i]); if s <> '' then begin sIP := AContext.Connection.Socket.Binding.PeerIP; nPort := AContext.Connection.Socket.Binding.PeerPort; RevStrData(sIP, nPort, s); RevPacksData(sIP, nPort,StrToPacks( s)) end; end; end; end.
unit DataMod; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, IBDatabase, IBCustomDataSet, IBUpdateSQL, IBQuery, Db, IBTable; type TCacheData = class(TDataModule) CacheDS: TDataSource; IBDatabase1: TIBDatabase; IBCacheQuery: TIBQuery; IBUpdateSQL: TIBUpdateSQL; IBTransaction1: TIBTransaction; IBCacheQueryPROJ_ID: TStringField; IBCacheQueryPROJ_NAME: TStringField; IBCacheQueryUpdateStatus: TStringField; IBCachedDataSet: TIBDataSet; IBCachedTable: TIBTable; IBCachedDataSetPROJ_ID: TStringField; IBCachedDataSetPROJ_NAME: TStringField; IBCachedDataSetUpdateStatus: TStringField; IBCachedTablePROJ_ID: TStringField; IBCachedTablePROJ_NAME: TStringField; IBCachedTableUpdateStatus: TStringField; procedure CacheQueryCalcFields(DataSet: TDataSet); procedure IBCacheQueryUpdateError(DataSet: TDataSet; E: EDatabaseError; UpdateKind: TUpdateKind; var UpdateAction: TIBUpdateAction); procedure IBCachedDataSetCalcFields(DataSet: TDataSet); procedure IBCachedTableCalcFields(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var CacheData: TCacheData; implementation uses CachedUp, ErrForm; {$R *.dfm} { This event displays the current update status in a calculated field } const UpdateStatusStr: array[TUpdateStatus] of string = ('Unmodified', 'Modified', 'Inserted', 'Deleted'); procedure TCacheData.CacheQueryCalcFields(DataSet: TDataSet); begin IBCacheQueryUpdateStatus.Value := UpdateStatusStr[IBCacheQuery.UpdateStatus]; end; { This event is triggered when an error occurs during the update process (such as a key violation). Here we use another form to show the user the error and allow them to decide what to do about it. See ErrForm.pas for more information } procedure TCacheData.IBCacheQueryUpdateError(DataSet: TDataSet; E: EDatabaseError; UpdateKind: TUpdateKind; var UpdateAction: TIBUpdateAction); begin UpdateAction := UpdateErrorForm.HandleError(DataSet, E, UpdateKind); end; procedure TCacheData.IBCachedDataSetCalcFields(DataSet: TDataSet); begin IBCachedDataSetUpdateStatus.Value := UpdateStatusStr[IBCachedDataset.UpdateStatus]; end; procedure TCacheData.IBCachedTableCalcFields(DataSet: TDataSet); begin IBCachedTableUpdateStatus.Value := UpdateStatusStr[IBCachedTable.UpdateStatus]; end; end.
unit Dialogs4D.Modal.Warning; interface uses Dialogs4D.Modal.Intf; type TDialogModalWarning = class(TInterfacedObject, IDialogModal) private /// <summary> /// Displays a dialog box for the user with a warning message. /// </summary> /// <param name="Content"> /// Warning message to be displayed to the user. /// </param> procedure Show(const Content: string); end; implementation uses {$IF (DEFINED(UNIGUI_VCL) or DEFINED(UNIGUI_ISAPI) or DEFINED(UNIGUI_SERVICE))} UniGuiDialogs, UniGuiTypes, {$ELSEIF DEFINED(MSWINDOWS)} Vcl.Forms, Winapi.Windows, Vcl.BlockUI.Intf, Vcl.BlockUI, {$ENDIF} System.SysUtils, Dialogs4D.Constants; {$IF (DEFINED(UNIGUI_VCL) or DEFINED(UNIGUI_ISAPI) or DEFINED(UNIGUI_SERVICE))} procedure TDialogModalWarning.Show(const Content: string); begin MessageDlg(Content, mtWarning, [mbOK]); end; {$ELSEIF DEFINED(MSWINDOWS)} procedure TDialogModalWarning.Show(const Content: string); var BlockUI: IBlockUI; begin BlockUI := TBlockUI.Create(); Application.MessageBox(PWideChar(Content), PWideChar(Application.Title), MB_ICONWARNING); end; {$ELSE} procedure TDialogModalWarning.Show(const Content: string); begin raise Exception.Create(DIRECTIVE_NOT_DEFINED); end; {$ENDIF} end.
unit fSelectDuplicates; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Buttons, StdCtrls, ExtCtrls, KASComboBox, uFileView; type { TfrmSelectDuplicates } TfrmSelectDuplicates = class(TForm) btnApply: TBitBtn; btnCancel: TBitBtn; btnOK: TBitBtn; btnIncludeMask: TSpeedButton; btnExcludeMask: TSpeedButton; cmbFirstMethod: TComboBoxAutoWidth; cmbIncludeMask: TComboBox; cmbExcludeMask: TComboBox; chkLeaveUnselected: TCheckBox; cmbSecondMethod: TComboBoxAutoWidth; lblIncludeMask: TLabel; lblExcludeMask: TLabel; lblFirstMethod: TLabel; lblSecondMethod: TLabel; pnlMethods: TPanel; pnlButtons: TPanel; procedure btnApplyClick(Sender: TObject); procedure btnIncludeMaskClick(Sender: TObject); procedure cmbFirstMethodChange(Sender: TObject); private FFileView: TFileView; private procedure ButtonsAutosize; end; procedure ShowSelectDuplicates(TheOwner: TCustomForm; AFileView: TFileView); implementation {$R *.lfm} uses uFile, uFileSorting, uFileFunctions, uDisplayFile, uFileProperty, uTypes, uGlobs, fMaskInputDlg, uLng, uSearchTemplate, DCStrUtils; procedure ShowSelectDuplicates(TheOwner: TCustomForm; AFileView: TFileView); begin with TfrmSelectDuplicates.Create(TheOwner) do begin ButtonsAutosize; FFileView:= AFileView; cmbFirstMethod.ItemIndex:= 0; cmbSecondMethod.ItemIndex:= 2; cmbIncludeMask.Items.Assign(glsMaskHistory); cmbExcludeMask.Items.Assign(glsMaskHistory); // Localize methods ParseLineToList(rsSelectDuplicateMethod, cmbFirstMethod.Items); ParseLineToList(rsSelectDuplicateMethod, cmbSecondMethod.Items); cmbSecondMethod.Items.Delete(cmbSecondMethod.Items.Count - 1); cmbSecondMethod.Items.Delete(cmbSecondMethod.Items.Count - 1); if ShowModal = mrOK then begin btnApplyClick(btnApply); end; Free; end; end; { TfrmSelectDuplicates } procedure TfrmSelectDuplicates.cmbFirstMethodChange(Sender: TObject); begin cmbSecondMethod.Enabled:= cmbFirstMethod.ItemIndex < 4; end; procedure TfrmSelectDuplicates.btnApplyClick(Sender: TObject); var ARange: TRange; Index, J: Integer; ASelected: Integer; AFiles: TDisplayFiles; AGroup, AValue: Variant; NewSorting: TFileSortings = nil; begin FFileView.MarkGroup(cmbIncludeMask.Text, True); if Length(cmbExcludeMask.Text) > 0 then begin FFileView.MarkGroup(cmbExcludeMask.Text, False); end; if not chkLeaveUnselected.Checked then Exit; AFiles:= FFileView.DisplayFiles; // First sort by group SetLength(NewSorting, 1); SetLength(NewSorting[0].SortFunctions, 1); NewSorting[0].SortFunctions[0] := fsfVariant; NewSorting[0].SortDirection := sdAscending; case cmbFirstMethod.ItemIndex of 0, 1: // Newest/Oldest begin SetLength(NewSorting, 2); SetLength(NewSorting[1].SortFunctions, 1); NewSorting[1].SortFunctions[0] := fsfModificationTime; if (cmbFirstMethod.ItemIndex = 1) then // First item will be Oldest NewSorting[1].SortDirection := sdAscending else begin // First item will be Newest NewSorting[1].SortDirection := sdDescending; end; end; 2, 3: // Largest/Smallest begin SetLength(NewSorting, 2); SetLength(NewSorting[1].SortFunctions, 1); NewSorting[1].SortFunctions[0] := fsfSize; if (cmbFirstMethod.ItemIndex = 3) then // First item will be Smallest NewSorting[1].SortDirection := sdAscending else begin // First item will be Largest NewSorting[1].SortDirection := sdDescending; end; end; end; if cmbSecondMethod.Enabled then begin case cmbSecondMethod.ItemIndex of 0, 1: begin SetLength(NewSorting, 3); SetLength(NewSorting[2].SortFunctions, 1); NewSorting[2].SortFunctions[0] := fsfModificationTime; if (cmbSecondMethod.ItemIndex = 1) then NewSorting[2].SortDirection := sdAscending else begin NewSorting[2].SortDirection := sdDescending; end; end; 2, 3: begin SetLength(NewSorting, 3); SetLength(NewSorting[2].SortFunctions, 1); NewSorting[2].SortFunctions[0] := fsfSize; if (cmbSecondMethod.ItemIndex = 3) then NewSorting[2].SortDirection := sdAscending else begin NewSorting[2].SortDirection := sdDescending; end; end; end; end; FFileView.Sorting:= NewSorting; // Skip '..' item if AFiles[0].FSFile.IsNameValid then ARange.First:= 0 else begin ARange.First:= 1; end; AGroup:= TFileVariantProperty(AFiles[ARange.First].FSFile.Properties[fpVariant]).Value; for Index:= ARange.First + 1 to AFiles.Count - 1 do begin AValue:= TFileVariantProperty(AFiles[Index].FSFile.Properties[fpVariant]).Value; if (AValue <> AGroup) then begin ASelected:= 0; ARange.Last:= Index - 1; for J:= ARange.First to ARange.Last do begin if AFiles[J].Selected then Inc(ASelected); end; // Selected all files in the group if ASelected = (Index - ARange.First) then begin if cmbFirstMethod.ItemIndex = 5 then AFiles[ARange.Last].Selected:= False else begin AFiles[ARange.First].Selected:= False; end; end; AGroup:= AValue; ARange.First:= Index; end; end; end; procedure TfrmSelectDuplicates.btnIncludeMaskClick(Sender: TObject); var sMask: String; bTemplate: Boolean; AComboBox: TComboBox; begin if Sender = btnIncludeMask then AComboBox:= cmbIncludeMask else begin AComboBox:= cmbExcludeMask; end; sMask:= AComboBox.Text; if ShowMaskInputDlg(rsMarkPlus, rsMaskInput, glsMaskHistory, sMask) then begin bTemplate:= IsMaskSearchTemplate(sMask); AComboBox.Enabled:= not bTemplate; AComboBox.Text:= sMask; end; end; procedure TfrmSelectDuplicates.ButtonsAutosize; var Index: Integer; AControl: TControl; AMaxWidth, AMaxHeight: Integer; begin AMaxWidth:= 0; AMaxHeight:= 0; for Index:= 0 to pnlButtons.ControlCount - 1 do begin AControl:= pnlButtons.Controls[Index]; if AControl.Width > AMaxWidth then AMaxWidth:= AControl.Width; if AControl.Height > AMaxHeight then AMaxHeight:= AControl.Height; end; for Index:= 0 to pnlButtons.ControlCount - 1 do begin AControl:= pnlButtons.Controls[Index]; AControl.Constraints.MinWidth:= AMaxWidth; AControl.Constraints.MinHeight:= AMaxHeight; end; end; end.
(***************************************************************************** * Pascal Solution to "Mind Your PQs" from the * * * * Seventh Annual UCF ACM UPE High School Programming Tournament * * May 15, 1993 * * * * This program implements a PQ, with operations INSERT and REMOVE, as * * defined in the problem statement. A PQ is implemented as an unordered * * list. To insert a value, we add the value to the end of the list. To * * remove the smallest value, we scan for the smallest value, remove it, and * * then compress the list to fill in the hole created by removing the value. * *****************************************************************************) program PQ(input, output); const MAX_IN_PQ = 100; (* Maximum number of elements in the PQ *) var the_pq : array[1..MAX_IN_PQ] of integer; (* The PQ structure *) num_in_pq, (* Number of elements currently in the PQ *) i, (* Looping variable *) min, (* Minimum element in the PQ *) index : integer; (* Location of the minimum element in the PQ *) ch : char; (* Used for input *) infile : text; (* Input file *) begin assign( infile, 'pqueue.in' ); reset( infile ); while not eof( infile ) do begin ch := ' '; (* Start each data set with an empty PQ *) num_in_pq := 0; while ch <> 'E' do begin read( infile, ch ); if ch = 'I' then begin (* Remove the INSERT command from the input line *) while ch <> ' ' do read( infile, ch ); (* Insert a value into the PQ *) inc( num_in_pq ); read( infile, the_pq[num_in_pq] ); end else if ch = 'R' then begin (* Find the smallest element in the PQ *) min := MAXINT; for i := 1 to num_in_pq do begin if the_pq[i] < min then begin min := the_pq[i]; index := i; end; end; (* Remove the smallest element from the PQ *) dec( num_in_pq ); for i := index to num_in_pq do the_pq[i] := the_pq[i+1]; (* Output the removed element *) writeln( min ); end; readln( infile ); end; writeln; end; close( infile ); end.
{*******************************************************} { } { Delphi FireMonkey Platform } { Copyright(c) 2015-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FmxStyleLookup; interface uses TypInfo, Windows, System.SysUtils, System.Classes, System.Actions, System.UITypes, System.Types, System.Math, System.RTLConsts, System.UIConsts, Vcl.Controls, Vcl.Graphics, Vcl.Dialogs, FMX.Controls, FMX.Styles, DesignIntf, DesignEditors, ComponentDesigner, VCLEditors; type TStyleLookupPropertyValues = class(TStringProperty) private procedure GetStyledControl(out AStyledControl: TStyledControl; out AStyleName: string; out AScene: IScene); virtual; function GetCurrentStyleDescriptor: TStyleDescription; protected function SkipStyle(const ControlStyleName, StyleName: string): Boolean; virtual; function SkipSceneStyle(StyleName: string): Boolean; virtual; public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TStyleLookupProperty = class(TStyleLookupPropertyValues, ICustomPropertyListDrawing) private { ICustomPropertyDrawing } procedure ListMeasureWidth(const Value: string; ACanvas: VCL.Graphics.TCanvas; var AWidth: Integer); procedure ListMeasureHeight(const Value: string; ACanvas: VCL.Graphics.TCanvas; var AHeight: Integer); procedure ListDrawValue(const Value: string; ACanvas: VCL.Graphics.TCanvas; const ARect: TRect; ASelected: Boolean); end; TStyleLookupPropertyListView = class(TStyleLookupPropertyValues) // not owner draw end; TStyleLookupPropertyButton = class(TStyleLookupProperty) protected function SkipStyle(const ControlStyleName, StyleName: string): Boolean; override; end; TStyleLookupPropertyEdit = class(TStyleLookupProperty) protected function SkipStyle(const ControlStyleName, StyleName: string): Boolean; override; end; TStyleLookupPropertyCalendar = class(TStyleLookupProperty) protected function SkipStyle(const ControlStyleName, StyleName: string): Boolean; override; end; TStyleLookupPropertyListBox = class(TStyleLookupProperty) protected function SkipStyle(const ControlStyleName, StyleName: string): Boolean; override; end; TListBoxDefaultsProperty = class(TStyleLookupProperty) protected function GetItemClassName: string; virtual; abstract; procedure GetStyledControl(out AStyledControl: TStyledControl; out AStyleName: string; out AScene: IScene); override; end; TDefaultListBoxItemStyleProperty = class(TListBoxDefaultsProperty) function GetItemClassName: string; override; end; TDefaultListBoxGroupHeaderStyleProperty = class(TListBoxDefaultsProperty) function GetItemClassName: string; override; end; TDefaultListBoxGroupFooterStyleProperty = class(TListBoxDefaultsProperty) function GetItemClassName: string; override; end; procedure RegisterStyleLookupEditors; implementation uses FMX.Types, FMX.BehaviorManager, FMX.Graphics, FMX.ListBox, FMX.Layers3D, FMX.Forms, FMX.ListView, FMX.Objects, FMX.Utils, FMX.Edit, FMX.StdCtrls, FMX.Calendar; type TOpenStyledControl = class(TStyledControl); procedure RegisterStyleLookupEditors; begin RegisterPropertyEditor(TypeInfo(string), TStyledControl, 'StyleLookup', TStyleLookupProperty); RegisterPropertyEditor(TypeInfo(string), TCustomListBox, 'StyleLookup', TStyleLookupPropertyListBox); RegisterPropertyEditor(TypeInfo(string), TCustomLayer3D, 'StyleLookup', TStyleLookupProperty); RegisterPropertyEditor(TypeInfo(string), TCustomForm, 'StyleLookup', TStyleLookupProperty); RegisterPropertyEditor(TypeInfo(string), TListBoxItemStyleDefaults, 'ItemStyle', TDefaultListBoxItemStyleProperty); RegisterPropertyEditor(TypeInfo(string), TListBoxItemStyleDefaults, 'GroupHeaderStyle', TDefaultListBoxGroupHeaderStyleProperty); RegisterPropertyEditor(TypeInfo(string), TListBoxItemStyleDefaults, 'GroupFooterStyle', TDefaultListBoxGroupFooterStyleProperty); RegisterPropertyEditor(TypeInfo(String), TCustomListView, 'StyleLookup', TStyleLookupPropertyListView); RegisterPropertyEditor(TypeInfo(string), TEdit, 'StyleLookup', TStyleLookupPropertyEdit); RegisterPropertyEditor(TypeInfo(string), TCalendar, 'StyleLookup', TStyleLookupPropertyCalendar); RegisterPropertyEditor(TypeInfo(string), TCustomButton, 'StyleLookup', TStyleLookupPropertyButton); end; function TStyleLookupPropertyValues.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paRevertable, paMultiSelect]; end; procedure TStyleLookupPropertyValues.GetStyledControl(out AStyledControl: TStyledControl; out AStyleName: string; out AScene: IScene); const StyleSuffix = 'style'; begin AStyledControl := nil; if GetComponent(0) is TStyledControl then begin AStyledControl := TStyledControl(GetComponent(0)); AStyleName := AStyledControl.DefaultStyleLookupName.ToLower; if AStyleName.Contains(StyleSuffix) then AStyleName := AStyleName.Remove(AStyleName.Length - StyleSuffix.Length); AScene := AStyledControl.Scene; end else Supports(GetComponent(0), IScene, AScene); end; function TStyleLookupPropertyValues.GetCurrentStyleDescriptor: TStyleDescription; var StyleBehavior: IInterface; CurrentStyle: TFmxObject; Persistent: TPersistent; Context: TFmxObject; begin Result := nil; Context := nil; Persistent := GetComponent(0); if Persistent is TFmxObject then Context := TFmxObject(Persistent) else if Persistent is TListBoxItemStyleDefaults then Context := TListBoxItemStyleDefaults(Persistent).ListBox; StyleBehavior := TBehaviorServices.Current.GetBehaviorService(IStyleBehavior, Context); if StyleBehavior <> nil then begin (StyleBehavior as IStyleBehavior).GetSystemStyle(Context, CurrentStyle); if CurrentStyle <> nil then Result := TStyleManager.FindStyleDescriptor(CurrentStyle); end; end; function TStyleLookupPropertyValues.SkipStyle(const ControlStyleName, StyleName: string): Boolean; const Scrollbar = 'scrollbar'; Thumb = 'thumb'; Track = 'track'; Expander = 'expander'; Button = 'button'; Segment = 'segment'; Bordered = 'bordered'; var StyleDesc: TStyleDescription; begin Result := True; // Do not localize all string consts if TBitmapCodecManager.CodecExists(StyleName) or StyleName.Contains(Scrollbar) or StyleName.Contains(Thumb) or StyleName.Contains(Track) or StyleName.Contains(Expander) or ((Pos(Button, ControlStyleName) = 1) and (Pos(Segment, StyleName) > 0)) then Exit; StyleDesc := GetCurrentStyleDescriptor; if (StyleDesc <> nil) and StyleDesc.PlatformTarget.Contains('[ANDROID]') and ControlStyleName.Contains(Button) and StyleName.Contains(Bordered) then Exit; Result := False; end; function TStyleLookupPropertyValues.SkipSceneStyle(StyleName: string): Boolean; const BackgroundStyle = 'backgroundstyle'; Toolbar = 'toolbar'; Statusbar = 'statusbar'; Panel = 'panel'; begin Result := not (StyleName.Contains(BackgroundStyle) or StyleName.Contains(Toolbar) or StyleName.Contains(Panel) or StyleName.Contains(Statusbar)); end; procedure TStyleLookupPropertyValues.GetValues(Proc: TGetStrProc); var Styles: TStringList; StyleName: string; function CompletedStyle(const StyleObject: TFmxObject): Boolean; begin if StyleObject <> nil then Result := TStyleManager.FindStyleDescriptor(StyleObject) <> nil else Result := False; end; procedure AddStylesForControl(const StyleObject: TFmxObject); var I: Integer; begin if StyleObject <> nil then for I := 0 to StyleObject.ChildrenCount - 1 do begin if SkipStyle(StyleName, LowerCase(StyleObject.Children[I].StyleName)) then Continue; if Pos(StyleName, LowerCase(StyleObject.Children[I].StyleName)) > 0 then begin if Styles.IndexOf(StyleObject.Children[I].StyleName) < 0 then Styles.Add(StyleObject.Children[I].StyleName); end else if Pos('speedbutton', LowerCase(StyleName)) = 1 then begin if Pos('button', LowerCase(StyleObject.Children[I].StyleName)) > 0 then if Styles.IndexOf(StyleObject.Children[I].StyleName) < 0 then Styles.Add(StyleObject.Children[I].StyleName); end; end; end; procedure AddStylesForScene(const StyleObject: TFmxObject); var I: Integer; begin if StyleObject <> nil then for I := 0 to StyleObject.ChildrenCount - 1 do begin if SkipStyle(StyleName, LowerCase(StyleObject.Children[I].StyleName)) then Continue; if not SkipSceneStyle(StyleObject.Children[I].StyleName.ToLower) then if Styles.IndexOf(StyleObject.Children[I].StyleName) < 0 then Styles.Add(StyleObject.Children[I].StyleName); end; end; var UseDefaultStyle: Boolean; StyledControl: TStyledControl; Scene: IScene; I: Integer; begin try GetStyledControl(StyledControl, StyleName, Scene); if StyleName <> '' then // Selection is TStyledControl begin Styles := TStringList.Create; Styles.CaseSensitive := False; try // First check StyleBook UseDefaultStyle := True; if (Scene <> nil) and (Scene.StyleBook <> nil) then begin AddStylesForControl(Scene.StyleBook.Style); UseDefaultStyle := not CompletedStyle(Scene.StyleBook.Style); end; // Check default style if UseDefaultStyle then AddStylesForControl(TStyleManager.ActiveStyleForScene(Scene)); Styles.Sort; for I := 0 to Styles.Count - 1 do Proc(Styles[I]); finally Styles.Free; end; end else if Scene <> nil then begin Styles := TStringList.Create; Styles.CaseSensitive := False; try // First check StyleBook UseDefaultStyle := True; if (Scene <> nil) and (Scene.StyleBook <> nil) then begin AddStylesForScene(Scene.StyleBook.Style); UseDefaultStyle := not CompletedStyle(Scene.StyleBook.Style); end; // Check default style if UseDefaultStyle then AddStylesForScene(TStyleManager.ActiveStyleForScene(Scene)); Styles.Sort; for I := 0 to Styles.Count - 1 do Proc(Styles[I]); finally Styles.Free; end; end; except on E: Exception do ShowMessage(E.Message); end; end; procedure TStyleLookupProperty.ListDrawValue(const Value: string; ACanvas: VCL.Graphics.TCanvas; const ARect: TRect; ASelected: Boolean); var R: TRect; B: VCL.Graphics.TBitmap; FB: FMX.Graphics.TBitmap; Clone: FMX.Controls.TControl; Scene: IScene; StyledControl: FMX.Controls.TStyledControl; Style: TFmxObject; M: FMX.Graphics.TBitmapData; I: Integer; BaseRect: TRectF; FittingRect: TRectF; Tile: FMX.Graphics.TBitmap; T: TFmxObject; StyleName: string; begin try R := ARect; if (Value <> '') then begin ACanvas.FillRect(ARect); Scene := nil; Style := nil; GetStyledControl(StyledControl, StyleName, Scene); if StyledControl <> nil then begin // check if Assigned(StyledControl.Scene) and Assigned(StyledControl.Scene.StyleBook) then Style := StyledControl.Scene.StyleBook.Style else Style := nil; Scene := StyledControl.Scene; if StyledControl.Width > StyledControl.Height then BaseRect := RectF(0, 0, 90, 50) else BaseRect := RectF(0, 0, 50, 90); end else if Scene <> nil then begin if Scene.StyleBook <> nil then Style := Scene.StyleBook.Style; if Scene.Canvas <> nil then begin if Scene.Canvas.Width > Scene.Canvas.Height then BaseRect := RectF(0, 0, 90, 50) else BaseRect := RectF(0, 0, 50, 90); end else BaseRect := RectF(0, 0, 90, 50) end; if (Style = nil) or (Style.FindStyleResource(Value) = nil) then Style := TStyleManager.ActiveStyleForScene(Scene); // create clone if Style <> nil then begin Clone := FMX.Controls.TControl(Style.FindStyleResource(Value)); if Clone <> nil then begin Tile := FMX.Graphics.TBitmap.Create(50, 38); Clone := FMX.Controls.TControl(Clone.Clone(nil)); T := Clone.FindStyleResource('text'); if (T <> nil) and (T is TText) then begin if Pos('label', Style.StyleName) = 0 then TText(T).Text := 'Label' else TText(T).Text := ''; end; FittingRect := BaseRect; if not SameValue(TOpenStyledControl(Clone).FixedSize.Height, 0) then FittingRect.Height := TOpenStyledControl(Clone).FixedSize.Height; if not SameValue(TOpenStyledControl(Clone).FixedSize.Width, 0) then FittingRect.Width := TOpenStyledControl(Clone).FixedSize.Width; Clone.SetBounds(0, 0, FittingRect.Width, FittingRect.Height); Clone.SetNewScene(Scene); FB := Clone.MakeScreenshot; Clone.SetNewScene(nil); Clone.Free; FittingRect.Fit(RectF(0, 0, Tile.Width, Tile.Height)); if Tile.Canvas.BeginScene then try // background Clone := FMX.Controls.TControl(Style.FindStyleResource('backgroundstyle')); if Assigned(Clone) then begin Clone := FMX.Controls.TControl(Clone.Clone(nil)); Clone.SetBounds(0, 0, 400, 400); Clone.SetNewScene(Scene); Clone.PaintTo(Tile.Canvas, Clone.LocalRect); Clone.SetNewScene(nil); Clone.Free; end else Tile.Canvas.Clear($FFBaBaBa); // Tile.Canvas.DrawBitmap(FB, RectF(0, 0, FB.Width, FB.Height), FittingRect, 1); finally Tile.Canvas.EndScene; end; try B := VCL.Graphics.TBitmap.Create; try B.HandleType := bmDIB; B.PixelFormat := pf32Bit; B.SetSize(Tile.Width, Tile.Height); if Tile.Map(TMapAccess.Read, M) then try for I := 0 to Tile.Height - 1 do Move(PAlphaColorArray(M.Data)[I * (M.Pitch div 4)], B.ScanLine[I]^, B.Width * 4); finally Tile.Unmap(M); end; ACanvas.Draw(R.Left, R.Top, B); Inc(R.Left, B.Width + 4); finally B.Free; end; finally FB.Free; Tile.Free; end; end; end; end; finally DefaultPropertyListDrawValue(Value, ACanvas, R, ASelected); end; end; procedure TStyleLookupProperty.ListMeasureHeight(const Value: string; ACanvas: VCL.Graphics.TCanvas; var AHeight: Integer); begin AHeight := 38; end; procedure TStyleLookupProperty.ListMeasureWidth(const Value: string; ACanvas: VCL.Graphics.TCanvas; var AWidth: Integer); begin end; function TStyleLookupPropertyValues.GetValue: string; begin try Result := GetStrValue; except on E: Exception do ShowMessage(E.Message); end; end; procedure TStyleLookupPropertyValues.SetValue(const Value: string); begin try SetStrValue(Value); Modified; Designer.NoSelection; except on E: Exception do ShowMessage(E.Message); end; end; { TDefaultListBoxItemStyleProperty } procedure TListBoxDefaultsProperty.GetStyledControl(out AStyledControl: TStyledControl; out AStyleName: string; out AScene: IScene); var ListBox: TCustomListBox; begin AStyledControl := nil; if GetComponent(0) is TListBoxItemStyleDefaults then begin ListBox := (GetComponent(0) as TListBoxItemStyleDefaults).ListBox; AStyleName := Lowercase(Copy(GetItemClassName, 2, MaxInt)); AScene := ListBox.Scene; end else Assert(False); end; function TDefaultListBoxItemStyleProperty.GetItemClassName: string; begin Result := TListBoxItem.ClassName; end; function TDefaultListBoxGroupHeaderStyleProperty.GetItemClassName: string; begin Result := TListBoxGroupHeader.ClassName; end; function TDefaultListBoxGroupFooterStyleProperty.GetItemClassName: string; begin Result := TListBoxGroupFooter.ClassName; end; { TStyleLookupPropertyListBox } function TStyleLookupPropertyListBox.SkipStyle(const ControlStyleName, StyleName: string): Boolean; const ListBoxItem = 'listboxitem'; Footer = 'footer'; Header = 'header'; begin Result := StyleName.Contains(ListBoxItem) or StyleName.Contains(Header) or StyleName.Contains(Footer) or inherited SkipStyle(ControlStyleName, StyleName); end; { TStyleLookupPropertyEdit } function TStyleLookupPropertyEdit.SkipStyle(const ControlStyleName, StyleName: string): Boolean; const EditButtonStyle = 'editbutton'; TimeEditStyle = 'timeedit'; DateEditStyle = 'dateedit'; begin Result := StyleName.Contains(EditButtonStyle) or StyleName.Contains(DateEditStyle) or StyleName.Contains(TimeEditStyle) or inherited SkipStyle(ControlStyleName, StyleName); end; { TStyleLookupPropertyCalendar } function TStyleLookupPropertyCalendar.SkipStyle(const ControlStyleName, StyleName: string): Boolean; const LabelStyle = 'label'; begin Result := StyleName.Contains(LabelStyle) or inherited SkipStyle(ControlStyleName, StyleName); end; { TStyleLookupPropertyButton } function TStyleLookupPropertyButton.SkipStyle(const ControlStyleName, StyleName: string): Boolean; const LabelStyle = 'label'; begin Result := StyleName.Contains(LabelStyle) or inherited SkipStyle(ControlStyleName, StyleName); end; end.
(* This is a reference document for my personal use. I want to have a consistent coding style in Pascal, that is why I would like to have something like a reference cheat sheet to look at when in doubt. 1. Start each program, however small it may be, with the following line: {$mode objfpc}{$H+}{$J-} I read this in a book on modern Pascal. This has to do with strings. I don't really work with that now, but I thought it would be a nice habit to have. 2. Always name your programs UsingCamelCase_AndUnderscores; Start the name with a Capital letter. 3. Declare CONSTS using capital letters. 4. Declare variables using camelCase, start the name with a regular letter. 5. Indent using tabs, 1 tab = 4 spaces. 6. Indent any logical piece of code, kinda following the Pythonic way of writing code. *)
unit Classe_VerificacaoInicial; interface uses Classes, Dialogs, SysUtils, TiposDeDados; type TVerificacaoInicial = class private function getAcessoNegado: boolean; function getValidadeCertificado: TDateTime; protected FValidadeDoSistema, FValidadeCertificado : TDateTime; FStatusInternet : TStatusInternet; FAcessoNegado : Boolean; procedure Verificar_Se_HD_Homologado; procedure Conferir_Validade_Da_Licenca_Do_Sistema; procedure Conferir_Status_Internet; procedure Verificar_Validade_Certificado_Digital; procedure Atualizar_Sistema; procedure Conferir_Copia_de_Segurança; public property AcessoNegado : boolean read getAcessoNegado; property StatusInternet : TStatusInternet read FStatusInternet; property ValidadeCertificado: TDateTime read getValidadeCertificado; procedure Processar; end; implementation { TVerificacao } uses funcoes; procedure TVerificacaoInicial.Atualizar_Sistema; begin //Realizar Atualizações automáticas do sistema. //Executa('ALTER EMPRESA_EMP ADD EMP_CODIGO_UNISYSTEM VARCHAR(10) NULL'); end; procedure TVerificacaoInicial.Conferir_Copia_de_Segurança; begin //Conferência se foi feito cópia de segurança e a mesma enviada para nuvem //e local específico (pendrive, partição do hd, outro pc ou vários locais) //configurado nas dependências do cliente. end; procedure TVerificacaoInicial.Conferir_Status_Internet; begin //Conferência do status da internet, (normal, ociosa, não tem) //a fim de colocar de maneira automática a emissão de NF-e | NFC-e //em contingência automática. end; procedure TVerificacaoInicial.Conferir_Validade_Da_Licenca_Do_Sistema; begin //Conferência da validade da liberação do sistema no período de 30 dias, //o mesmo precisa ser verificado num período de 24 horas, mesmo que o sistema //não seja fechado pelo cliente. //FAcessoNegado:=True; FAcessoNegado:=False; end; function TVerificacaoInicial.getAcessoNegado: boolean; begin result := self.FAcessoNegado; end; function TVerificacaoInicial.getValidadeCertificado: TDateTime; begin result := FValidadeCertificado; end; procedure TVerificacaoInicial.Processar; begin Conferir_Validade_Da_Licenca_Do_Sistema; Conferir_Status_Internet; Verificar_Validade_Certificado_Digital; Atualizar_Sistema; Conferir_Copia_de_Segurança; end; procedure TVerificacaoInicial.Verificar_Se_HD_Homologado; begin //Pegar o numero do HD da maquina //Procurar na tabela HD_HD se existe este HD (criptografado) //Se existe, ok... sair //Se nao existir: { ShowMessage('Esta máquina não está homologada para usar o Sistema.'+#13+#13+ 'Por favor entre em contato com o Suporte.'+ Dados_de_Contato_do_Suporte); Application.Terminate; } //OBS: A nuvem é que inclui/retira HDs na tabela HD_HD end; procedure TVerificacaoInicial.Verificar_Validade_Certificado_Digital; begin //Verificação da validade do certificado digital, 30 dias antes do vencimento //precisa começar a informar o cliente do vencimento, na abertura do sistema. FValidadeCertificado := Date; end; end.
unit UMensagens; interface resourcestring //Geral STR_ATENCAO = 'Atenção'; STR_CAPTION_ABA_CONSULTAS = '%d - %s...'; STR_TODOS = 'Todos'; STR_ATUALIZADO = 'atualizado(a)'; STR_GRAVADO = 'gravado(a)'; STR_EXCLUIDO = 'excluido(a)'; STR_OPERACAO_COM_SUCESSO = '%s com código %d %s com sucesso.'; STR_ENTIDADE_NAO_ENCONTRADA = '%s com código %d não foi encontrado(a)'; //Entidade STR_ENTIDADE_GRAVADA_COM_SUCESSO = '%s gravado(a) com sucesso! Código gerado: %d.'; STR_ENTIDADE_ATUALIZADO_COM_SUCESSO = '%s atualizado(a) com sucesso!'; STR_ENTIDADE_DESEJA_EXCLUIR = 'Deseja realmente excluir este(a) %s?'; //CRUD STR_CRUD_CABECALHO = 'Cadastro de %s'; //Transação STR_JA_EXISTE_TRANSACAO_ATIVA = 'Não foi possivel abrir uma nova transação! Motivo: Já existe uma transação ativa.'; STR_NAO_EXISTE_TRANSACAO_ATIVA = 'Não foi possivel %s a transação! Motivo: Não existe uma transação ativa.'; STR_VALIDA_TRANSACAO_ATIVA = 'Operação abortada! Motivo: Para realizar esta operação é necessário ter uma transação ativa.'; STR_ABORTAR = 'abortar'; STR_FINALIZAR = 'finalizar'; //Carteira_Vacinação_Agente STR_NOME_AGENTE_NAO_INFORMADO = 'Nome do Agente não informado'; STR_LOGIN_NAO_INFORMADO = 'Login não informado'; STR_SENHA_NAO_INFORMADA = 'Senha não informada'; STR_COREN_NAO_INFORMADO = 'Coren não informado'; STR_ESPECIFICACAO_NAO_INFORMADA = 'Especificação não informada'; STR_DATA_NAO_INFORMADA = 'Data não informada'; STR_TURNO_NAO_INFORMADO = 'Turno não informado'; STR_TELEFONE_NAO_INFORMADO = 'Telefone não informado'; //Carteira_Vacinação STR_CODIGO_VACINA_NAO_INFORAMADO = 'Código não informado'; STR_CODIGO_VACINA_NAO_INFORMADO = 'Nome da vacina não informado'; STR_VACINA_NAO_INFORMADA = 'Vacina não informada'; STR_DOSE_NAO_INFORMADA = 'Dose não inforada'; STR_DATA_VACINA_NAO_INFORMADA = 'Data da vacina não informada'; STR_RESPONSAVEL_NAO_INFORMADO = 'Responsável não informado'; STR_CODIGO_COREN_NAO_INFORMADO = 'Coren do agente não informado'; STR_CODIGO_LOTE_NAO_INFORMADO = 'Código do lote não informado'; STR_LOTE_VENCIMENTO_NAO_INFORMADO = 'Vencimento do lote não informado'; STR_UNIDADE_SAUDE_NAO_INFORMADA = 'Unidade de saúde não informada'; //Carteira_Vacinação_Lote_Vacina STR_LOTE_VACINA_NAO_INFORMADO = 'Lote da vacina não informado'; STR_LABORATORIO_NAO_INFORMADO = 'Laboratório não informado'; //Carteira_Vacinação_Paciente STR_CODIGO_SUS_NAO_INFORMADO = 'Código SUS não informado'; STR_NOME_PACIENTE_NAO_INFORMADO = 'Nome do paciente não informado'; STR_NASCIMENTO_NAO_INFORMADO = 'Nascimento não informado'; STR_SEXO_NAO_INFORMADO = 'Sexo não informado'; STR_ENDERECO_NAO_INFORMADO = 'Endereço não informado'; STR_PAI_NAO_INFORMADO = 'Nome do pai não informado'; STR_MAE_NAO_INFORMADA = 'Nome da mãe não informado'; STR_ESTADO_CIVIL_NAO_INFORMADO = 'Estado civil não informado'; STR_UF_NAO_INFORMADO = 'UF não informado'; STR_BAIRRO_NAO_INFORMADO = 'Bairro não informado'; STR_CIDADE_NAO_INFORMADA = 'Cidade não informada'; STR_DESCRICAO_VACINA_NAO_INFORMADA = 'Descrição não informada'; //novo STR_DATA_RETORNO_NAO_INFORMADA = 'Data de retorno não informada'; STR_VACINA_RETORNO_NAO_INFORMADA = 'Vacina para retorno não informada'; implementation end.
program test; {$mode objfpc}{$H+} uses Classes, SysUtils, StrUtils, QTemplate; type { TQTemplateTest } TQTemplateTest = class(TQTemplate) public constructor Create(const AStream: TStream); override; function ReplaceTitle(const ATag: String; AParams: TStringList): String; function ReplaceItemList(const ATag: String; AParams: TStringList): String; end; { TQTemplateTest } constructor TQTemplateTest.Create(const AStream: TStream); begin inherited Create(AStream); Tags['title'] := @ReplaceTitle; Tags['itemlist'] := @ReplaceItemList; end; function TQTemplateTest.ReplaceTitle(const ATag: String; AParams: TStringList): String; begin Result := 'Title of the App'; end; function TQTemplateTest.ReplaceItemList(const ATag: String; AParams: TStringList ): String; const Items: array [1..5] of String = ('Item 1','Item 2','Item 3','Item 4','Item 5'); var Header,Row,Footer: String; i: Integer; begin Header := AParams.Values['header']; Row := AParams.Values['row']; Footer := AParams.Values['footer']; with TStringList.Create do try Add(Header); for i := Low(Items) to High(Items) do Add(StringsReplace(Row,['~no','~value'],[IntToStr(i),Items[i]],[rfReplaceAll])); Add(Footer); Result := Text; finally Free; end; end; var Stream:TFileStream; begin Stream:=TFileStream.Create('test.tpl',fmOpenRead); with TQTemplateTest.Create(Stream) do try WriteLn(GetContentSream); ReadLn; finally Stream.Free; Free; end; end.
program FileReq; uses DOS, { FindFirst, FindNext, SearchRec, DirStr, NameStr, ExtStr } StrUtil {RepeatStr}, BTREE {STree, CompProc, TreePtr}, CRT ; {$F+} CONST WildSpec = '*.*'; DirAtr = '<DIR>'; TYPE NameStr = String[12]; NameStrPtr = ^NameStr; FNameRecPtr = ^FNameRec; FNameRec = RECORD Name : NameStr; Atr : DirStr; Last, Next : FNameRecPtr; END; DirRec = RECORD Root : TreePtr; Path : PathStr; END; VAR memflag : ^BYTE; CurrDir : DirRec; (* +++++++++++++++++++++++++++++++++++++++++++++++++++++ *) FUNCTION CompareFunc(item1,item2 : POINTER) : BOOLEAN; VAR Name1, Name2 : NameStr; BEGIN Name1 := FNameRecPtr(item1)^.name; Name2 := FNameRecPtr(item2)^.name; IF Name1 < Name2 THEN CompareFunc := TRUE ELSE CompareFunc := FALSE; END {CompareFunc}; (* +++++++++++++++++++++++++++++++++++++++++++++++++++++ *) PROCEDURE MakeDirList(Path : PathStr; VAR Dir : DirRec); { Create a doubly linked list of directory entries } VAR dummy : TreePtr; Atr : DirStr; FNMask : PathStr; DirInfo : SearchRec; LastPtr, FName : FNameRecPtr; BEGIN Dir.Path := Path; FNMask := Path + WildSpec; FindFirst(FNMask,Directory,DirInfo); IF DOSError = 0 THEN { initial dir tree creation } BEGIN Dir.root := NIL; new(FName); AddData(Dir.root,POINTER(FName)); END; WHILE DOSError = 0 DO BEGIN CASE DirInfo.Attr OF Hidden : Atr := ' *Hidden*'; Directory : Atr := DirAtr; ReadOnly : Atr := ' *Read Only*'; ELSE Atr := ''; END; FName^.Name := DirInfo.Name; FName^.Atr := Atr; AddData(Dir.root,POINTER(FName)); FindNext(DirInfo); IF DosError = 0 THEN BEGIN new(FName); END END; END {MakeDirList}; { Procedure parameters for dynamic sort } (* +++++++++++++++++++++++++++++++++++++++++++++++++++++++ *) PROCEDURE DisplayDirList(Dir : DirRec); VAR Entry : FNameRecPtr; PROCEDURE InOrder(rt : TreePtr); BEGIN WHILE rt <> NIL DO BEGIN InOrder(rt^.left); Entry := FNameRecPtr(rt^.dataptr); Write(Entry^.name); Write(Entry^.atr); Writeln; delay(100); InOrder(rt^.right); END; END {InOrder}; BEGIN WriteLn(Dir.Path); InOrder(Dir.root); END {DisplayDirList}; BEGIN LessThan := CompareFunc; Mark(memflag); MakeDirList('C:\tp\',CurrDir); DisplayDirList(CurrDir); Release(memflag); END.