text
stringlengths
14
6.51M
unit RCADOQuery; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, ADODb, uSQLFunctions, uVarianteFunctions, Variants; type TRCADOQuery = class(TADOQuery) private { Private declarations } FOriginalSQl : String; FKeyFields : String; function GetOriginalSQL : String; protected { Protected declarations } procedure DoAfterOpen; override; constructor Create(AOwner : TComponent); override; public { Public declarations } ChangeOriginalSQL : Boolean; function DeleteLine : Boolean; procedure Requery; property OriginalSQL : String read GetOriginalSQl write FOriginalSQl; published { Published declarations } property KeyFields : String read FKeyFields write FKeyFields; end; procedure Register; implementation uses uDataBaseFunctions; constructor TRCADOQuery.Create(AOwner : TComponent); begin inherited Create(AOwner); FKeyFields := ''; FOriginalSQl := ''; end; function TRCADOQuery.GetOriginalSQL : String; begin if FOriginalSQl = '' then FOriginalSQl := SQL.Text; Result := FOriginalSQl; end; procedure TRCADOQuery.DoAfterOpen; begin inherited DoAfterOpen; FOriginalSQL := SQL.Text; end; procedure TRCADOQuery.Requery; var OldPos : Variant; begin if FKeyFields <> '' then OldPos := FieldValues[FKeyFields]; Close; Open; if FKeyFields <> '' then Locate(FKeyFields, OldPos, []); end; function TRCADOQuery.DeleteLine : Boolean; var KeyList : Variant; i : integer; begin if FKeyFields = '' then raise exception.Create('VocÍ deve preencher os keyfields para o "DeleteLine" funcionar'); Result := True; with TADOQuery.Create(Self) do begin SQL.Text := 'DELETE FROM ' + GetSQLFirstTableName(Self.SQL.Text) + ' ' + 'WHERE '; KeyList := ConvVarArray(Self.KeyFields); if KeyList = Self.KeyFields then begin SQL.Text := SQL.Text + Self.KeyFields + ' = ' + ConvSQLValue(Self.FieldByName(Self.KeyFields), Self.FieldByName(Self.KeyFields).AsString); end else begin for i := 1 to VarArrayHighBound(KeyList, 1) do begin SQL.Text := SQL.Text + KeyList[1] + ' = ' + ConvSQLValue(Self.FieldByName(KeyList[1]), Self.FieldByName(KeyList[1]).AsString); if i < VarArrayHighBound(KeyList, 1) then SQL.Text := SQL.Text + ' AND '; end; end; try ExecSQL; Self.Requery; except Result := False; end; Free; end; end; procedure Register; begin RegisterComponents('NewPower', [TRCADOQuery]); end; end.
namespace RemObjects.Elements.EUnit; interface uses Sugar; type ConsoleTestListener = public class (IEventListener) private Offset: Integer; method StringOffset: String; method StateToString(State: TestState): String; protected method Output(Message: String); virtual; public method RunStarted(Test: ITest); virtual; method TestStarted(Test: ITest); virtual; method TestFinished(TestResult: ITestResult); virtual; method RunFinished(TestResult: ITestResult); virtual; UseAnsiColorOutput: Boolean; end; implementation method ConsoleTestListener.StateToString(State: TestState): String; begin case State of TestState.Untested: exit "Untested"; TestState.Skipped: exit "Skipped"; TestState.Failed: exit "Failed"; TestState.Succeeded: exit "Succeeded"; end; end; method ConsoleTestListener.TestFinished(TestResult: ITestResult); begin if TestResult.State = TestState.Skipped then exit; if TestResult.Test.Kind <> TestKind.Testcase then dec(Offset, 2); var Failed := "Failed"; var Succeeded := "Succeeded"; if UseAnsiColorOutput then begin Failed := #27"[1m"#27"[31mFailed"#27"[0m"; Succeeded := #27"[32mSucceded"#27"[0m"; end; var Message: String; if TestResult.State = TestState.Failed then Message := String.Format("{0}{1} finished. State: {2}. Message: {3}", StringOffset, TestResult.Name, Failed, TestResult.Message) else Message := String.Format("{0}{1} finished. State: {2}.", StringOffset, TestResult.Name, Succeeded); Output(Message); end; method ConsoleTestListener.RunStarted(Test: ITest); begin Offset := 0; end; method ConsoleTestListener.RunFinished(TestResult: ITestResult); begin Output("======================================"); var S := new Summary(TestResult, item -> (item.Test.Kind = TestKind.Testcase)); Output(String.Format("{0} succeeded, {1} failed, {2} skipped, {3} untested", S.Succeeded, S.Failed, S.Skipped, S.Untested)); end; method ConsoleTestListener.Output(Message: String); begin {$IFNDEF NETFX_CORE} writeLn(Message); {$ELSE} System.Diagnostics.Debug.WriteLine(Message); {$ENDIF} end; method ConsoleTestListener.TestStarted(Test: ITest); begin if (Test.Kind = TestKind.Testcase) or (Test.Skip) then exit; Output(String.Format("{0}{1} started", StringOffset, Test.Name)); inc(Offset, 2); end; method ConsoleTestListener.StringOffset: String; begin if Offset <= 0 then exit ""; exit new StringBuilder().Append(' ', Offset).ToString; end; end.
unit ExportarOrcamento.Controller; interface uses ExportarOrcamento.Controller.interf, Orcamento.Model.interf, TESTORCAMENTOITENS.Entidade.Model, Generics.Collections, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, 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.FBDef, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.IBBase, FireDAC.Phys.FB, Data.DB, FireDAC.Comp.Client, System.SysUtils, ConfiguracoesExportar.Model.interf; type TExportarOrcamento = class(TInterfacedObject, IExportarOrcamento) private FOrcamentoModel: IOrcamentoModel; FConfigExportacaoModel: IConfiguracoesExportarModel; FArquivoNome: String; FArquivo: TextFile; FCodigoSinap: string; FDescricao: string; FQtde: string; FUnidMedida: string; FPreco: string; FTotal: string; FCodigoOrcamento: string; FLista: TFDQuery; public constructor Create; destructor Destroy; override; class function New: IExportarOrcamento; function codigoOrcamento(AValue: string): IExportarOrcamento; function carregarItens: IExportarOrcamento; procedure exportar; end; implementation { TExportarOrcamento } uses FacadeModel, FacadeView, Tipos.Controller.Interf; function TExportarOrcamento.carregarItens: IExportarOrcamento; begin Result := self; FLista := FOrcamentoModel .queryItensOrcamento(FCodigoOrcamento); end; function TExportarOrcamento.codigoOrcamento(AValue: string): IExportarOrcamento; begin Result := Self; FCodigoOrcamento := AValue; end; constructor TExportarOrcamento.Create; begin FOrcamentoModel := TFacadeModel.New.ModulosFacadeModel. estoqueFactoryModel.orcamento; FConfigExportacaoModel := TFacadeModel.New.configuracoesFactoryModel.exportar; end; destructor TExportarOrcamento.Destroy; begin inherited; end; procedure TExportarOrcamento.exportar; var vLinha, vCabecalho, vOrcamento, vFornecedor: string; begin FArquivoNome := FConfigExportacaoModel.diretorioExportarOrcamentoCsv+'\Orcamento.csv'; AssignFile(FArquivo, FArquivoNome); Rewrite(FArquivo); vOrcamento := 'Orçamento;'+FCodigoOrcamento; Writeln(FArquivo, vOrcamento); Writeln(FArquivo, ''); Writeln(FArquivo, ''); vFornecedor := 'CNPJ:; INFORME SEU CNPJ AQUI (APENAS NÚMEROS)'; Writeln(FArquivo, vFornecedor); Writeln(FArquivo, ''); Writeln(FArquivo, ''); vCabecalho := 'Código Sinapi;Descrição;Unid. Medida;Qtde;Valor Unitário;Valor Total'; Writeln(FArquivo, vCabecalho); FLista.First; while not(FLista.Eof) do begin FCodigoSinap := FLista.FieldByName('Codigo_sinapi').AsString; FDescricao := FLista.FieldByName('Descricao').AsString; FUnidMedida := FLista.FieldByName('UnidMedida').AsString; FQtde := FLista.FieldByName('Qtde').AsString; FPreco := ' '; FTotal := ' '; vLinha := FCodigoSinap +';'+FDescricao+';'+FUnidMedida+';'+FQtde+';'+FPreco+';'+FTotal; Writeln(FArquivo, vLinha); FLista.Next; end; CloseFile(FArquivo); TFacadeView.New .MensagensFactory .exibirMensagem(tmInformacao) .mensagem(Format('Exportação concluída! Arquivo salvo em: %s ', [FArquivoNome])) .exibir; end; class function TExportarOrcamento.New: IExportarOrcamento; begin Result := Self.Create; end; end.
unit SynHighlighterMyGeneral; {$I SynEdit.inc} interface uses SysUtils, Windows, Messages, Classes, Controls, Graphics, SynEditTypes, SynEditHighlighter, SynHighLighterGeneral, JclStrings; type TtkTokenKind = (tkComment, tkIdentifier, tkKey, tkNull, tkNumber, tkPreprocessor, tkSpace, tkString, tkSymbol, tkUnknown, tkKey2, tkKey3, tkKey4, tkKey5); // DJLP 2000-06-18 TRangeState = (rsANil, rsBlockComment, rsMultilineString, rsUnKnown); TProcTableProc = procedure of object; type TSynMyGeneralSyn = class(TSynCustomHighlighter) private FLanguageName: string; fRange: TRangeState; fProcTable: array[#0..#255] of TProcTableProc; fTokenID: TtkTokenKind; fKeyAttri1: TSynHighlighterAttributes; fKeyAttri2: TSynHighlighterAttributes; fKeyAttri3: TSynHighlighterAttributes; fKeyAttri4: TSynHighlighterAttributes; fKeyAttri5: TSynHighlighterAttributes; fComments: TCommentStyles; fCommentAttri: TSynHighlighterAttributes; fIdentifierAttri: TSynHighlighterAttributes; fIdentChars: UnicodeString; fSpaceAttri: TSynHighlighterAttributes; fStringAttri: TSynHighlighterAttributes; fSymbolAttri: TSynHighlighterAttributes; fKeyWords1: TStrings; fKeyWords2: TStrings; fKeyWords3: TStrings; fKeyWords4: TStrings; fKeyWords5: TStrings; fNumConstChars: string; fNumBegChars: string; FLineComment: string; FCommentBeg: string; FCommentEnd: string; FLineCommentList: TStringList; FCommentBegList: TStringList; FCommentEndList: TStringList; FStrBegChars: string; FStrEndChars: string; FMultilineStrings: boolean; FNextStringEndChar: char; fPreprocessorAttri: TSynHighlighterAttributes; fNumberAttri: TSynHighlighterAttributes; fDetectPreprocessor: boolean; fStringDelimCh: WideChar; FSourceFileName: string; FDescription: string; FCaseSensitive: boolean; FCurrLineHighlighted: boolean; FOverrideTxtFgColor: boolean; FRightEdgeColorFg: TColor; FRightEdgeColorBg: TColor; FHelpFile: string; FIdentifierBegChars: string; FEscapeChar: char; FBlockAutoindent: boolean; FBlockBegStr: string; FBlockEndStr: string; procedure AsciiCharProc; function MatchComment(CommentList: TStringList; var CommentStr: string): boolean; procedure LineCommentProc; procedure CommentBegProc; procedure CommentEndProc; procedure StringBegProc; procedure StringEndProc; procedure SpaceProc; procedure UnknownProc; procedure SetKeyWords1(const Value: TStrings); procedure SetKeyWords2(const Value: TStrings); procedure SetKeyWords3(const Value: TStrings); procedure SetKeyWords4(const Value: TStrings); procedure SetKeyWords5(const Value: TStrings); function GetNumConstChars: string; function GetNumBegChars: string; procedure SetNumConstChars(const Value: string); procedure SetNumBegChars(const Value: string); procedure SetLanguageName(Value: string); procedure PrepareKeywordList(const Value: TStrings); procedure MyNumberProc; procedure MyIntegerProc; procedure MyCRProc; procedure MyLFProc; procedure MyNullProc; function GetIdentifierChars: UnicodeString; function GetStringDelim: TStringDelim; procedure SetDetectPreprocessor(const Value: boolean); procedure SetIdentifierChars(const Value: UnicodeString); procedure SetStringDelim(const Value: TStringDelim); procedure MyIdentProc; procedure SetComments(Value: TCommentStyles); function GetTokenID: TtkTokenKind; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetEol: Boolean; override; function IsKeyword(const AKeyword: String; const AKeywordList: TStrings): Boolean; reintroduce; function GetTokenPos: Integer; override; procedure Next; override; procedure SetRange(Value: Pointer); override; procedure ResetRange; override; procedure SetCommentStrings(LineComment, CommentBeg, CommentEnd: string); procedure GetCommentStrings(var LineComment, CommentBeg, CommentEnd: string); function GetTokenAttribute: TSynHighlighterAttributes; override; procedure SetStringParams(StrBegChars, StrEndChars: string; MultilineStrings: boolean); procedure MakeMethodTables; procedure AssignPropertiesTo(HL: TSynMyGeneralSyn); function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;override; function GetTokenKind: integer; override; class function GetLanguageName: string; override; published property LanguageName: string read FLanguageName write SetLanguageName; property NumConstChars: string read GetNumConstChars write SetNumConstChars; property NumBegChars: string read GetNumBegChars write SetNumBegChars; property CommentAttri: TSynHighlighterAttributes read fCommentAttri write fCommentAttri; property Comments: TCommentStyles read fComments write SetComments; property DetectPreprocessor: boolean read fDetectPreprocessor write SetDetectPreprocessor; property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri; property IdentifierChars: UnicodeString read GetIdentifierChars write SetIdentifierChars; property NumberAttri: TSynHighlighterAttributes read fNumberAttri write fNumberAttri; property PreprocessorAttri: TSynHighlighterAttributes read fPreprocessorAttri write fPreprocessorAttri; property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri; property StringAttri: TSynHighlighterAttributes read fStringAttri write fStringAttri; property SymbolAttri: TSynHighlighterAttributes read fSymbolAttri write fSymbolAttri; property StringDelim: TStringDelim read GetStringDelim write SetStringDelim default sdSingleQuote; property KeyAttri1: TSynHighlighterAttributes read fKeyAttri1 write fKeyAttri1; property KeyAttri2: TSynHighlighterAttributes read fKeyAttri2 write fKeyAttri2; property KeyAttri3: TSynHighlighterAttributes read fKeyAttri3 write fKeyAttri3; property KeyAttri4: TSynHighlighterAttributes read fKeyAttri4 write fKeyAttri4; property KeyAttri5: TSynHighlighterAttributes read fKeyAttri5 write fKeyAttri5; property KeyWords1: TStrings read fKeyWords1 write SetKeyWords1; property KeyWords2: TStrings read fKeyWords2 write SetKeyWords2; property KeyWords3: TStrings read fKeyWords3 write SetKeyWords3; property KeyWords4: TStrings read fKeyWords4 write SetKeyWords4; property KeyWords5: TStrings read fKeyWords5 write SetKeyWords5; property SourceFileName: string read FSourceFileName write FSourceFileName; property Description: string read FDescription write FDescription; property CaseSensitive: boolean read FCaseSensitive write FCaseSensitive; property CurrLineHighlighted: boolean read FCurrLineHighlighted write FCurrLineHighlighted; property OverrideTxtFgColor: boolean read FOverrideTxtFgColor write FOverrideTxtFgColor; property RightEdgeColorFg: TColor read FRightEdgeColorFg write FRightEdgeColorFg; property RightEdgeColorBg: TColor read FRightEdgeColorBg write FRightEdgeColorBg; property HelpFile: string read FHelpFile write FHelpFile; property IdentifierBegChars: string read FIdentifierBegChars write FIdentifierBegChars; property EscapeChar: char read FEscapeChar write FEscapeChar; property BlockAutoindent: boolean read FBlockAutoindent write FBlockAutoindent; property BlockBegStr: string read FBlockBegStr write FBlockBegStr; property BlockEndStr: string read FBlockEndStr write FBlockEndStr; end; procedure Register; implementation uses StrUtils, SynEditStrConst; const COMMENT_LIST_SEPARATOR = ' '; procedure Register; begin RegisterComponents(SYNS_HighlightersPage, [TSynMyGeneralSyn]); end; procedure TSynMyGeneralSyn.AssignPropertiesTo(HL: TSynMyGeneralSyn); begin HL.CurrLineHighlighted := CurrLineHighlighted; HL.OverrideTxtFgColor := OverrideTxtFgColor; HL.RightEdgeColorFg := RightEdgeColorFg; HL.RightEdgeColorBg := RightEdgeColorBg; HL.HelpFile := HelpFile; HL.CaseSensitive := CaseSensitive; HL.IdentifierBegChars := IdentifierBegChars; HL.IdentifierChars := IdentifierChars; HL.NumConstChars := NumConstChars; HL.NumBegChars := NumBegChars; HL.DetectPreprocessor := DetectPreprocessor; HL.SetCommentStrings(FLineComment, FCommentBeg, FCommentEnd); HL.SetStringParams(FStrBegChars, FStrEndChars, FMultilineStrings); HL.EscapeChar := EscapeChar; HL.BlockAutoindent := BlockAutoindent; HL.BlockBegStr := BlockBegStr; HL.BlockEndStr := BlockEndStr; if CaseSensitive then begin HL.Keywords1.Text := Keywords1.Text; HL.Keywords2.Text := Keywords2.Text; HL.Keywords3.Text := Keywords3.Text; HL.Keywords4.Text := Keywords4.Text; HL.Keywords5.Text := Keywords5.Text; end else begin HL.Keywords1.Text := UpperCase(Keywords1.Text); HL.Keywords2.Text := UpperCase(Keywords2.Text); HL.Keywords3.Text := UpperCase(Keywords3.Text); HL.Keywords4.Text := UpperCase(Keywords4.Text); HL.Keywords5.Text := UpperCase(Keywords5.Text); end; HL.MakeMethodTables; end; procedure TSynMyGeneralSyn.MakeMethodTables; var I: Char; n: integer; procedure CommentToProcTable(CommentList: TStringList; proc: TProcTableProc); var i: integer; s: string; begin for i := 0 to CommentList.Count - 1 do begin s := UpperCase(CommentList[i]); if (Length(s) > 0) then begin if Pos(s[1], IdentifierChars) > 0 then begin fProcTable[s[1]] := proc; fProcTable[LowerCase(s[1])[1]] := proc; CommentList[i] := s; end else fProcTable[s[1]] := proc; end; end; end; begin for I := #0 to #255 do begin fProcTable[I] := MyIdentProc; if (Pos(I, IdentifierBegChars) > 0) then begin fProcTable[I] := MyIdentProc; end else begin if Pos(I, fNumBegChars) > 0 then fProcTable[I] := MyNumberProc else begin case I of '#': fProcTable[I] := AsciiCharProc; #13: fProcTable[I] := MyCRProc; #10: fProcTable[I] := MyLFProc; #0: fProcTable[I] := MyNullProc; // '0'..'9': fProcTable[I] := NumberProc; #1..#9, #11, #12, #14..#32: fProcTable[I] := SpaceProc; else fProcTable[I] := UnknownProc; end; end; end; end; for n := 1 to Length(FStrBegChars) do fProcTable[FStrBegChars[n]] := StringBegProc; CommentToProcTable(FLineCommentList, LineCommentProc); CommentToProcTable(FCommentBegList, CommentBegProc); FCommentEnd := UpperCase(FCommentEnd); end; constructor TSynMyGeneralSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); FLineCommentList := TStringList.Create; FCommentBegList := TStringList.Create; FCommentEndList := TStringList.Create; fKeyWords1 := TStringList.Create; TStringList(fKeyWords1).Sorted := True; TStringList(fKeyWords1).Duplicates := dupIgnore; fKeyWords2 := TStringList.Create; TStringList(fKeyWords2).Sorted := True; TStringList(fKeyWords2).Duplicates := dupIgnore; fKeyWords3 := TStringList.Create; TStringList(fKeyWords3).Sorted := True; TStringList(fKeyWords3).Duplicates := dupIgnore; fKeyWords4 := TStringList.Create; TStringList(fKeyWords4).Sorted := True; TStringList(fKeyWords4).Duplicates := dupIgnore; fKeyWords5 := TStringList.Create; TStringList(fKeyWords5).Sorted := True; TStringList(fKeyWords5).Duplicates := dupIgnore; fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment, SYNS_FriendlyAttrComment); fCommentAttri.Style := [fsItalic]; AddAttribute(fCommentAttri); fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier, SYNS_FriendlyAttrIdentifier); AddAttribute(fIdentifierAttri); fNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber, SYNS_FriendlyAttrNumber); AddAttribute(fNumberAttri); fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace, SYNS_FriendlyAttrSpace); AddAttribute(fSpaceAttri); fStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString, SYNS_FriendlyAttrString); AddAttribute(fStringAttri); fSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrSymbol, SYNS_FriendlyAttrSymbol); AddAttribute(fSymbolAttri); fPreprocessorAttri := TSynHighlighterAttributes.Create(SYNS_AttrPreprocessor, SYNS_FriendlyAttrPreprocessor); AddAttribute(fPreprocessorAttri); fKeyAttri1 := TSynHighlighterAttributes.Create('Keywords 1', 'Keywords 1'); fKeyAttri1.Style := []; AddAttribute(fKeyAttri1); fKeyAttri2 := TSynHighlighterAttributes.Create('Keywords 2', 'Keywords 2'); fKeyAttri2.Style := []; AddAttribute(fKeyAttri2); fKeyAttri3 := TSynHighlighterAttributes.Create('Keywords 3', 'Keywords 3'); fKeyAttri3.Style := []; AddAttribute(fKeyAttri3); fKeyAttri4 := TSynHighlighterAttributes.Create('Keywords 4', 'Keywords 4'); fKeyAttri4.Style := []; AddAttribute(fKeyAttri4); fKeyAttri5 := TSynHighlighterAttributes.Create('Keywords 5', 'Keywords 5'); fKeyAttri5.Style := []; AddAttribute(fKeyAttri5); NumConstChars := '0123456789'; NumBegChars := '0123456789'; fRange := rsUnknown; end; procedure TSynMyGeneralSyn.MyCRProc; begin fTokenID := tkSpace; Inc(Run); if fLine[Run] = #10 then Inc(Run); end; { Create } destructor TSynMyGeneralSyn.Destroy; begin fKeyWords1.Free; fKeyWords2.Free; fKeyWords3.Free; fKeyWords4.Free; fKeyWords5.Free; FLineCommentList.Free; FCommentBegList.Free; FCommentEndList.Free; inherited Destroy; end; { Destroy } procedure TSynMyGeneralSyn.AsciiCharProc; begin if DetectPreprocessor then begin fTokenID := tkPreprocessor; repeat inc(Run); until CharInSet(fLine[Run], [#0, #10, #13]); end else begin fTokenID := tkSymbol; inc(Run); end; end; function TSynMyGeneralSyn.MatchComment(CommentList: TStringList; var CommentStr: string): boolean; var i: integer; len: integer; ok: boolean; j: integer; begin j := 0; ok := FALSE; while (j < CommentList.Count) do begin CommentStr := UpperCase(CommentList[j]); len := Length(CommentStr); ok := (len > 0); if ok then begin i := 1; while ok and (i <= len) do begin ok := (UpCase(FLine[Run + i - 1]) = CommentStr[i]); inc(i); end; ok := ok and (i - 1 = len); end; if ok and ContainsStr(CommentStr[1], IdentifierChars) then ok := not ContainsStr(FLine[Run + Length(CommentStr)], IdentifierChars); if ok then BREAK; inc(j); end; result := ok; end; procedure TSynMyGeneralSyn.MyLFProc; begin fTokenID := tkSpace; Inc(Run); if fLine[Run] = #10 then Inc(Run); end; procedure TSynMyGeneralSyn.LineCommentProc; var CommentStr: string; begin if MatchComment(FLineCommentList, CommentStr) then begin inc(Run, Length(CommentStr)); fTokenID := tkComment; while (FLine[Run] <> #0) do begin case FLine[Run] of #10, #13: BREAK; end; inc(Run); end; end else begin if (Length(CommentStr) > 0) and ContainsStr(CommentStr[1], IdentifierChars) then MyIdentProc else begin inc(Run); fTokenID := tkSymbol; end; end; end; procedure TSynMyGeneralSyn.CommentBegProc; var CommentStr: string; begin if MatchComment(FLineCommentList, CommentStr) then LineCommentProc else begin if MatchComment(FCommentBegList, CommentStr) then begin fTokenID := tkComment; fRange := rsBlockComment; inc(Run, Length(CommentStr)); while (FLine[Run] <> #0) do begin if MatchComment(FCommentEndList, CommentStr) then begin fRange := rsUnKnown; inc(Run, Length(CommentStr)); BREAK; end else begin case FLine[Run] of #10, #13: BREAK; else inc(Run); end; end; end; end else begin if (Length(CommentStr) > 0) and ContainsStr(CommentStr[1], IdentifierChars) then MyIdentProc else begin inc(Run); fTokenID := tkSymbol; end; end; end; end; procedure TSynMyGeneralSyn.CommentEndProc; var CommentStr: string; begin fTokenID := tkComment; case FLine[Run] of #0: begin MyNullProc; exit; end; #10: begin MyLFProc; exit; end; #13: begin MyCRProc; exit; end; end; while (FLine[Run] <> #0) do begin if MatchComment(FCommentEndList, CommentStr) then begin fRange := rsUnKnown; inc(Run, Length(CommentStr)); BREAK; end else begin case FLine[Run] of #10, #13: BREAK; else inc(Run); end; end; end; end; procedure TSynMyGeneralSyn.StringBegProc; var i: integer; begin fTokenID := tkString; i := Pos(FLine[Run], FStrBegChars); if (i > 0) and (i <= Length(FStrEndChars)) then FNextStringEndChar := FStrEndChars[i] else FNextStringEndChar := #00; repeat if (EscapeChar <> #0) and (FLine[Run] = EscapeChar) and (FLine[Run + 1] <> #0) then begin inc(Run); end else begin case FLine[Run] of #0, #10, #13: begin if FMultilineStrings then fRange := rsMultilineString; BREAK; end; end; end; inc(Run); until (FLine[Run] = FNextStringEndChar); if FLine[Run] <> #0 then inc(Run); end; procedure TSynMyGeneralSyn.StringEndProc; begin fTokenID := tkString; case FLine[Run] of #0: begin MyNullProc; EXIT; end; #10: begin MyLFProc; EXIT; end; #13: begin MyCRProc; EXIT; end; end; repeat if (EscapeChar <> #0) and (FLine[Run] = EscapeChar) and (FLine[Run + 1] <> #0) then begin inc(Run); end else begin case FLine[Run] of #0, #10, #13: BREAK; end; end; inc(Run); until (FLine[Run] = FNextStringEndChar); if (FLine[Run] = FNextStringEndChar) and (FNextStringEndChar <> #00) then fRange := rsUnKnown; if FLine[Run] <> #0 then inc(Run); end; procedure TSynMyGeneralSyn.SpaceProc; begin inc(Run); fTokenID := tkSpace; while CharInSet(FLine[Run], [#1..#9, #11, #12, #14..#32]) do inc(Run); end; procedure TSynMyGeneralSyn.UnknownProc; begin inc(Run); fTokenID := tkUnKnown; end; procedure TSynMyGeneralSyn.Next; begin fTokenPos := Run; case fRange of rsBlockComment: CommentEndProc; rsMultilineString: StringEndProc; else fProcTable[fLine[Run]]; end; inherited; end; procedure TSynMyGeneralSyn.MyNullProc; begin fTokenID := tkNull; inc(Run); end; procedure TSynMyGeneralSyn.MyNumberProc; function IsNumberChar: Boolean; begin case fLine[Run] of '0'..'9', '.', 'e', 'E', 'x': Result := True; else Result := False; end; end; begin inc(Run); fTokenID := tkNumber; while IsNumberChar do begin case FLine[Run] of 'x': begin // handle C style hex numbers MyIntegerProc; break; end; '.': if FLine[Run + 1] = '.' then break; end; inc(Run); end; end; function TSynMyGeneralSyn.GetTokenAttribute: TSynHighlighterAttributes; begin case fTokenID of tkComment: Result := CommentAttri; tkIdentifier: Result := IdentifierAttri; tkKey: Result := fKeyAttri1; tkKey2: Result := fKeyAttri2; tkKey3: Result := fKeyAttri3; tkKey4: Result := fKeyAttri4; tkKey5: Result := fKeyAttri5; tkNumber: Result := NumberAttri; tkPreprocessor: Result := PreprocessorAttri; // DJLP 2000-06-18 tkSpace: Result := SpaceAttri; tkString: Result := StringAttri; tkSymbol: Result := SymbolAttri; tkUnknown: Result := SymbolAttri; else Result := nil; end; end; function TSynMyGeneralSyn.GetTokenID: TtkTokenKind; begin result := fTokenID; end; function TSynMyGeneralSyn.GetTokenKind: integer; begin result := Ord(GetTokenID); end; procedure TSynMyGeneralSyn.MyIdentProc; var sToken : string; begin fTokenId := tkIdentifier; while (not GetEol) and IsIdentChar(fLine[Run]) do inc(Run); sToken := GetToken; if sToken <> '' then begin if IsKeyWord(sToken, fKeyWords1) then fTokenId := tkKey else if IsKeyWord(sToken, fKeyWords2) then fTokenId := tkKey2 else if IsKeyWord(sToken, fKeyWords3) then fTokenId := tkKey3 else if IsKeyWord(sToken, fKeyWords4) then fTokenId := tkKey4 else if IsKeyWord(sToken, fKeyWords5) then fTokenId := tkKey5; end; end; procedure TSynMyGeneralSyn.MyIntegerProc; function IsIntegerChar: Boolean; begin case fLine[Run] of '0'..'9', 'A'..'F', 'a'..'f': Result := True; else Result := False; end; end; begin inc(Run); fTokenID := tkNumber; while IsIntegerChar do inc(Run); end; function TSynMyGeneralSyn.IsKeyword(const AKeyword: String; const AKeywordList: TStrings): Boolean; var First, Last, I, Compare: Integer; Token: String; begin First := 0; Last := AKeywordList.Count - 1; Result := False; Token := UpperCase(AKeyword); while First <= Last do begin I := (First + Last) shr 1; Compare := WideCompareText(AKeywordList[i], Token); if Compare = 0 then begin Result := True; break; end else if Compare < 0 then First := I + 1 else Last := I - 1; end; end; function TSynMyGeneralSyn.GetTokenPos: Integer; begin Result := fTokenPos; end; procedure TSynMyGeneralSyn.ReSetRange; begin fRange := rsUnknown; end; procedure TSynMyGeneralSyn.SetRange(Value: Pointer); begin fRange := TRangeState(Value); end; procedure TSynMyGeneralSyn.PrepareKeywordList(const Value: TStrings); var i: Integer; begin if Value <> nil then begin Value.BeginUpdate; for i := 0 to Value.Count - 1 do begin if not CaseSensitive then Value[i] := UpperCase(Value[i]); end; Value.EndUpdate; end; end; procedure TSynMyGeneralSyn.SetKeyWords1(const Value: TStrings); begin PrepareKeywordList(Value); fKeyWords1.Assign(Value); DefHighLightChange(nil); end; procedure TSynMyGeneralSyn.SetKeyWords2(const Value: TStrings); begin PrepareKeywordList(Value); fKeyWords2.Assign(Value); DefHighLightChange(nil); end; procedure TSynMyGeneralSyn.SetKeyWords3(const Value: TStrings); begin PrepareKeywordList(Value); fKeyWords3.Assign(Value); DefHighLightChange(nil); end; procedure TSynMyGeneralSyn.SetKeyWords4(const Value: TStrings); begin PrepareKeywordList(Value); fKeyWords4.Assign(Value); DefHighLightChange(nil); end; procedure TSynMyGeneralSyn.SetKeyWords5(const Value: TStrings); begin PrepareKeywordList(Value); fKeyWords5.Assign(Value); DefHighLightChange(nil); end; class function TSynMyGeneralSyn.GetLanguageName: string; begin Result := SYNS_LangGeneral; end; procedure TSynMyGeneralSyn.SetComments(Value: TCommentStyles); begin if fComments <> Value then begin fComments := Value; DefHighLightChange(Self); end; end; procedure TSynMyGeneralSyn.SetCommentStrings(LineComment, CommentBeg, CommentEnd: string); begin FLineComment := LineComment; FCommentBeg := CommentBeg; FCommentEnd := CommentEnd; StrToStrings(LineComment, COMMENT_LIST_SEPARATOR, FLineCommentList); StrToStrings(CommentBeg, COMMENT_LIST_SEPARATOR, FCommentBegList); StrToStrings(CommentEnd, COMMENT_LIST_SEPARATOR, FCommentEndList); end; procedure TSynMyGeneralSyn.SetDetectPreprocessor(const Value: boolean); begin fDetectPreprocessor := Value; end; procedure TSynMyGeneralSyn.SetIdentifierChars(const Value: UnicodeString); begin fIdentChars := Value; end; procedure TSynMyGeneralSyn.GetCommentStrings(var LineComment, CommentBeg, CommentEnd: string); begin LineComment := StringsToStr(FLineCommentList, COMMENT_LIST_SEPARATOR); CommentBeg := StringsToStr(FCommentBegList, COMMENT_LIST_SEPARATOR); CommentEnd := StringsToStr(FCommentEndList, COMMENT_LIST_SEPARATOR); end; function TSynMyGeneralSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; begin case Index of SYN_ATTR_COMMENT: Result := fCommentAttri; SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri; SYN_ATTR_KEYWORD: Result := fKeyAttri1; SYN_ATTR_STRING: Result := fStringAttri; SYN_ATTR_WHITESPACE: Result := fSpaceAttri; SYN_ATTR_SYMBOL: Result := fSymbolAttri; else Result := nil; end; end; function TSynMyGeneralSyn.GetEol: Boolean; begin Result := Run > fLineLen; end; function TSynMyGeneralSyn.GetIdentifierChars: UnicodeString; begin Result := fIdentChars; end; procedure TSynMyGeneralSyn.SetStringDelim(const Value: TStringDelim); var newCh: WideChar; begin case Value of sdSingleQuote: newCh := ''''; else newCh := '"'; end; //case if newCh <> fStringDelimCh then fStringDelimCh := newCh; end; procedure TSynMyGeneralSyn.SetStringParams(StrBegChars, StrEndChars: string; MultilineStrings: boolean); var i: integer; begin FStrBegChars := StrBegChars; FStrEndChars := StrEndChars; FMultilineStrings := MultilineStrings; for i := 1 to Length(FStrBegChars) do fProcTable[FStrBegChars[i]] := StringBegProc; end; function TSynMyGeneralSyn.GetNumConstChars: string; var ch: char; s: string; begin s := ''; for ch := #0 to #255 do if ContainsStr(ch, fNumConstChars) then s := s + ch; Result := s; end; function TSynMyGeneralSyn.GetStringDelim: TStringDelim; begin if fStringDelimCh = '''' then Result := sdSingleQuote else Result := sdDoubleQuote; end; function TSynMyGeneralSyn.GetNumBegChars: string; var ch: char; s: string; begin s := ''; for ch := #0 to #255 do if ContainsStr(ch, fNumBegChars) then s := s + ch; Result := s; end; procedure TSynMyGeneralSyn.SetNumConstChars(const Value: string); var i: integer; begin fNumConstChars := ''; for i := 1 to Length(Value) do fNumConstChars := fNumConstChars + Value[i]; end; procedure TSynMyGeneralSyn.SetNumBegChars(const Value: string); var i: integer; begin fNumBegChars := ''; for i := 1 to Length(Value) do fNumBegChars := fNumBegChars + Value[i]; end; procedure TSynMyGeneralSyn.SetLanguageName(Value: string); begin FLanguageName := Value; end; initialization {$IFNDEF SYN_CPPB_1} //mh 2000-07-14 RegisterPlaceableHighlighter(TSynMyGeneralSyn); {$ENDIF} end.
unit Chapter09._07_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math, DeepStar.Utils; /// 416. Partition Equal Subset Sum /// https://leetcode.com/problems/partition-equal-subset-sum/description/ /// 记忆化搜索 /// 时间复杂度: O(len(nums) * O(sum(nums))) /// 空间复杂度: O(len(nums) * O(sum(nums))) type TSolution = class(TObject) public function CanPartition(nums: TArr_int): boolean; end; procedure Main; implementation procedure Main; begin with TSolution.Create do begin WriteLn(CanPartition([1, 5, 11, 5])); WriteLn(CanPartition([1, 2, 3, 5])); Free; end; end; { TSolution } function TSolution.CanPartition(nums: TArr_int): boolean; var // memo[i][c] 表示使用索引为[0...i]的这些元素,是否可以完全填充一个容量为c的背包 // -1 表示为未计算; 0 表示不可以填充; 1 表示可以填充 memo: TArr2D_int; // 使用nums[0...index], 是否可以完全填充一个容量为sum的背包 function __tryPartition__(index, sum: integer): boolean; begin if sum = 0 then Exit(true); if (sum < 0) or (index < 0) then Exit(false); if memo[index, sum] <> -1 then Exit(memo[index, sum] = 1); memo[index, sum] := IfThen(__tryPartition__(index - 1, sum) or __tryPartition__(index - 1, sum - nums[index]), 1, 0); Result := memo[index, sum] = 1; end; var sum, i: integer; begin sum := 0; for i := 0 to High(nums) do begin Assert(nums[i] > 0); sum += nums[i]; end; if sum mod 2 <> 0 then Exit(false); SetLength(memo, Length(nums), sum div 2 + 1); for i := 0 to High(memo) do TArrayUtils_int.FillArray(memo[i], -1); Result := __tryPartition__(High(nums), sum div 2); end; end.
(* * DGL(The Delphi Generic Library) * * Copyright (c) 2004 * HouSisong@gmail.com * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * *) //------------------------------------------------------------------------------ //DGLMap_Integer_TNotifyEvent //例子 //具现化Integer<->TNotifyEvent的map容器和其迭代器 // Create by HouSisong, 2005.02.21 //------------------------------------------------------------------------------ unit DGLMap_Integer_TNotifyEvent; interface uses SysUtils, Classes; {$I DGLCfg.inc_h} const _NULL_Value = nil; type _KeyType = Integer; _ValueType = TNotifyEvent; {$define _DGL_NotHashFunction} {$define _DGL_Compare} //比较函数 function _IsEqual(const a,b :_ValueType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a=b); function _IsLess(const a,b :_ValueType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则 {$I Map.inc_h} //"类"模版的声明文件 {$I HashMap.inc_h} //"类"模版的声明文件 //out type IIntEventMapIterator = _IMapIterator; IIntEventMap = _IMap; IIntEventMultiMap = _IMultiMap; TIntEventMap = _TMap; TIntEventMultiMap = _TMultiMap; TIntEventHashMap = _THashMap; TIntEventHashMultiMap = _THashMultiMap; implementation uses HashFunctions; {$I Map.inc_pas} //"类"模版的实现文件 {$I HashMap.inc_pas} //"类"模版的实现文件 function _IsEqual(const a,b :_ValueType):boolean; //result:=(a=b); begin result:=(PInt64(@@a)^)=PInt64(@@b)^; end; function _IsLess(const a,b :_ValueType):boolean; //result:=(a<b); 默认排序准则 begin result:=(PInt64(@@a)^)<PInt64(@@b)^; end; initialization Assert(sizeof(int64)=sizeof(_ValueType)); end.
unit MMBitmap; interface {$DEFINE ODS} uses Windows, { for HPalette } Classes, { for TStream } Graphics { for TBitmap} ; type TMMBitmap = class(TBitmap) private FCanvas: TCanvas; FIgnorePalette: Boolean; FTransparentMode: TTransparentMode; FFileName: string; FPalette : HPalette; FData : pointer; FBitmapWidth, FBitmapHeight, FColours : integer; FActive : boolean; FFileHeader : PBitmapFileHeader; FInfoHeader : PBitmapInfoHeader; FInfo : PBitmapInfo; FPixelStart : pointer; fPixelFormat : TPixelFormat; function GetCanvas: TCanvas; function GetHandle: HBITMAP; function GetHandleType: TBitmapHandleType; function GetMaskHandle: HBITMAP; function GetMonochrome: Boolean; function GetPixelFormat: TPixelFormat; function GetScanline(Row: Integer): Pointer; function GetTransparentColor: TColor; procedure SetHandle(Value: HBITMAP); procedure SetHandleType(Value: TBitmapHandleType); virtual; procedure SetMaskHandle(Value: HBITMAP); procedure SetMonochrome(Value: Boolean); procedure SetPixelFormat(Value: TPixelFormat); procedure SetTransparentColor(Value: TColor); procedure SetTransparentMode(Value: TTransparentMode); function TransparentColorStored: Boolean; procedure GetBitmapPalette; procedure MapFile; procedure UnmapFile; protected procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; procedure Changed(Sender: TObject); override; function GetEmpty: Boolean; override; function GetHeight: Integer; override; function GetPalette: HPALETTE; override; function GetWidth: Integer; override; procedure HandleNeeded; procedure MaskHandleNeeded; procedure PaletteNeeded; procedure ReadData(Stream: TStream); override; procedure SetHeight(Value: Integer); override; procedure SetPalette(Value: HPALETTE); override; procedure SetWidth(Value: Integer); override; procedure WriteData(Stream: TStream); override; public constructor Create; override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure FreeImage; function HandleAllocated: Boolean; procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); override; procedure LoadFromStream(Stream: TStream); override; procedure LoadFromResourceName(Instance: THandle; const ResName: String); procedure LoadFromResourceID(Instance: THandle; ResID: Integer); procedure Mask(TransparentColor: TColor); function ReleaseHandle: HBITMAP; function ReleaseMaskHandle: HBITMAP; function ReleasePalette: HPALETTE; procedure SaveToClipboardFormat(var Format: Word; var Data: THandle; var APalette: HPALETTE); override; procedure SaveToStream(Stream: TStream); override; property Canvas: TCanvas read GetCanvas; property Handle: HBITMAP read GetHandle write SetHandle; property HandleType: TBitmapHandleType read GetHandleType write SetHandleType; property IgnorePalette: Boolean read FIgnorePalette write FIgnorePalette; property MaskHandle: HBITMAP read GetMaskHandle write SetMaskHandle; property Monochrome: Boolean read GetMonochrome write SetMonochrome; property PixelFormat: TPixelFormat read GetPixelFormat write SetPixelFormat; property ScanLine[Row: Integer]: Pointer read GetScanLine; property TransparentColor: TColor read GetTransparentColor write SetTransparentColor stored TransparentColorStored; property TransparentMode: TTransparentMode read FTransparentMode write SetTransparentMode default tmAuto; procedure LoadFromFile(const FileName : string); override; end; implementation uses sysutils { for exception } ; const BitmapSignature = $4D42; { TRSIMMBitmap } resourcestring sNotImplementable = 'Feature cannot be implemented'#13#10'- sorry ;-)'; sNotImplementedYet = 'Feature not implemented yet '#13#10'- sorry ;-)'; sFailedOpen = 'Failed to open %s'; sFailedMap = 'Failed to map file'; sFailedMapView = 'Failed to map view of file'; sInvalidBitmap = 'Invalid Bitmap'; procedure TraceMessage(const Msg : string); begin {$IFDEF ODS} OutputDebugString(Pchar(Msg)); {$ENDIF} end; procedure TMMBitmap.Assign(Source: TPersistent); begin if not( Source is TMMBitmap) then inherited else begin { TODO : Maybe this could be improved by sharing the file mapping? } { however, this works, although multiple assigns could run the application out of memory space, if all the mappings get unique ranges } LoadFromFile(TMMBitmap(Source).fFileName); end; end; procedure TMMBitmap.Changed(Sender: TObject); begin { not going to happen} end; constructor TMMBitmap.Create; begin TraceMessage('Create'); inherited; end; destructor TMMBitmap.Destroy; begin TraceMessage('Destroy'); UnMapFile; if Assigned(fCanvas) then FreeAndNil(fCanvas); inherited; end; procedure TMMBitmap.Draw(ACanvas: TCanvas; const Rect: TRect); var OldMode : integer; OldPalette : HPalette; begin with ACanvas do begin if FPalette <> 0 then OldPalette := SelectPalette (Handle, FPalette, false) else OldPalette := 0; try RealizePalette (Handle); if FColours = 2 then OldMode := SetStretchBltMode (Handle, BLACKONWHITE) else OldMode := SetStretchBltMode (Handle, COLORONCOLOR); try StretchDIBits (Handle, Rect.Left, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top, 0, 0, FBitmapWidth, FBitmapHeight, FPixelStart, FInfo^, DIB_RGB_COLORS, SRCCOPY) finally SetStretchBltMode (Handle, OldMode) end finally if OldPalette <> 0 then SelectPalette (Handle, OldPalette, false) end end end; procedure TMMBitmap.FreeImage; begin { nothing here} end; function TMMBitmap.GetCanvas: TCanvas; begin if not Assigned(fCanvas) then fCanvas := TCanvas.Create; { the beauty of this is that TCanvas.CreateHandle is blank, so anyone trying to use the canvas will get a "Canvas does not allow drawing"} Result := FCanvas; end; function TMMBitmap.GetEmpty: Boolean; begin Result := not fActive; end; function TMMBitmap.GetHandle: HBITMAP; begin TraceMessage('Attempt to GetHandle'); raise Exception.Create(sNotImplementable); end; function TMMBitmap.GetHandleType: TBitmapHandleType; begin TraceMessage('Attempt to GetHandleType'); raise Exception.Create(sNotImplementable); end; function TMMBitmap.GetHeight: Integer; begin if FActive then Result := FBitmapHeight else Result := 0; end; function TMMBitmap.GetMaskHandle: HBITMAP; begin TraceMessage('Attempt to GetMaskHandle'); raise Exception.Create(sNotImplementable); end; function TMMBitmap.GetMonochrome: Boolean; begin Result := (FColours = 2); end; function TMMBitmap.GetPalette: HPALETTE; begin Result := fPalette; end; function TMMBitmap.GetPixelFormat: TPixelFormat; begin Result := fPixelFormat; end; function TMMBitmap.GetScanline(Row: Integer): Pointer; begin TraceMessage('Attempt to GetScanline'); raise Exception.Create(sNotImplementedYet); end; function TMMBitmap.GetTransparentColor: TColor; begin TraceMessage('Attempt to GetTransparentColor'); raise Exception.Create(sNotImplementedYet); end; function TMMBitmap.GetWidth: Integer; begin if FActive then Result := FBitmapWidth else Result := 0; end; function TMMBitmap.HandleAllocated: Boolean; begin Result := fActive; end; procedure TMMBitmap.HandleNeeded; begin { nothing } end; procedure TMMBitmap.LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); begin TraceMessage('Attempt to LoadFromClipboardFormat'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.LoadFromFile(const FileName: string); begin { override this to allow grabbing of the file to Memory Map } if not (FileExists(FileName)) then begin raise Exception.CreateFmt('File %s does not exist', [FileName]); end else begin if fActive then UnmapFile; FFileName := FileName; MapFile; end; end; procedure TMMBitmap.LoadFromResourceID(Instance: THandle; ResID: Integer); begin TraceMessage('Attempt to LoadFromResourceID'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.LoadFromResourceName(Instance: THandle; const ResName: String); begin TraceMessage('Attempt to LoadFromResourceName'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.LoadFromStream(Stream: TStream); begin TraceMessage('Attempt to LoadFromStream'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.Mask(TransparentColor: TColor); begin TraceMessage('Attempt to Mask'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.MaskHandleNeeded; begin {} end; procedure TMMBitmap.PaletteNeeded; begin {} end; procedure TMMBitmap.ReadData(Stream: TStream); begin TraceMessage('Attempt to ReadData'); raise Exception.Create(sNotImplementable); end; function TMMBitmap.ReleaseHandle: HBITMAP; begin TraceMessage('Attempt to ReleaseHandle'); raise Exception.Create(sNotImplementable); end; function TMMBitmap.ReleaseMaskHandle: HBITMAP; begin TraceMessage('Attempt to ReleaseMaskHandle'); raise Exception.Create(sNotImplementable); end; function TMMBitmap.ReleasePalette: HPALETTE; begin TraceMessage('Attempt to ReleasePalette'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SaveToClipboardFormat(var Format: Word; var Data: THandle; var APalette: HPALETTE); begin TraceMessage('Attempt to SaveToClipboardFormat'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SaveToStream(Stream: TStream); begin TraceMessage('Attempt to SaveToStream'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SetHandle(Value: HBITMAP); begin TraceMessage('Attempt to SetHandle'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SetHandleType(Value: TBitmapHandleType); begin TraceMessage('Attempt to SetHandleType'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SetHeight(Value: Integer); begin TraceMessage('Attempt to SetHeight'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SetMaskHandle(Value: HBITMAP); begin TraceMessage('Attempt to SetMaskHandle'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SetMonochrome(Value: Boolean); begin TraceMessage('Attempt to SetMonochrome'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SetPalette(Value: HPALETTE); begin TraceMessage('Attempt to SetPalette'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SetPixelFormat(Value: TPixelFormat); begin TraceMessage('Attempt to SetPixelFormat'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.SetTransparentColor(Value: TColor); begin TraceMessage('Attempt to SetTransparentColor'); raise Exception.Create(sNotImplementedYet); end; procedure TMMBitmap.SetTransparentMode(Value: TTransparentMode); begin TraceMessage('Attempt to SetTransparentMode'); raise Exception.Create(sNotImplementedYet); end; procedure TMMBitmap.SetWidth(Value: Integer); begin TraceMessage('Attempt to SetWidth'); raise Exception.Create(sNotImplementable); end; function TMMBitmap.TransparentColorStored: Boolean; begin TraceMessage('Attempt to SetTransparentColorStored'); raise Exception.Create(sNotImplementedYet); end; procedure TMMBitmap.WriteData(Stream: TStream); begin TraceMessage('Attempt to WriteData'); raise Exception.Create(sNotImplementable); end; procedure TMMBitmap.GetBitmapPalette; var SysPalSize, Loop, LogSize : integer; LogPalette : PLogPalette; DC : HDC; Focus : HWND; begin FPalette := 0; if FColours > 2 then begin LogSize := SizeOf (TLogPalette) + pred(FColours) * SizeOf(TPaletteEntry); LogPalette := AllocMem (LogSize); try with LogPalette^ do begin palNumEntries := FColours; palVersion := $0300; (* I prefer to test programs with $R+, but this section of the program must be compiled with $R-. This $IFOPT enables the restoration of $R+ condition later on, but only if set now. *) {$IFOPT R+} {$DEFINE R_PLUS} {$R-} {$ENDIF} Focus := GetFocus; DC := GetDC (Focus); try SysPalSize := GetDeviceCaps (DC, SIZEPALETTE); if (FColours = 16) and (SysPalSize >= 16) then begin GetSystemPaletteEntries (DC, 0, 8, palPalEntry); loop := 8; GetSystemPaletteEntries (DC, SysPalSize - loop, loop, palPalEntry[loop]) end else with FInfo^ do for loop := 0 to pred (FColours) do begin palPalEntry[loop].peRed := bmiColors[loop].rgbRed; palPalEntry[loop].peGreen := bmiColors[loop].rgbGreen; palPalEntry[loop].peBlue := bmiColors[loop].rgbBlue end finally ReleaseDC(Focus, DC) end {$IFDEF R_PLUS} {$R+} {$UNDEF R_PLUS} {$ENDIF} end; FPalette := CreatePalette (LogPalette^) finally FreeMem (LogPalette, LogSize) end end end; procedure TMMBitmap.MapFile; var FileHandle, MapHandle : THandle; begin TraceMessage('MapFile'); if (fActive) then exit; FileHandle := CreateFile(PChar(FFilename), GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0); if FileHandle = INVALID_HANDLE_VALUE then raise Exception.CreateFmt(sFailedOpen, [FFilename]); try MapHandle := CreateFileMapping (FileHandle, nil, PAGE_READONLY, 0, 0, nil); if MapHandle = 0 then raise Exception.Create(sFailedMap) finally CloseHandle (FileHandle) end; try FData := MapViewOfFile (MapHandle, FILE_MAP_READ, 0, 0, 0); if FData = nil then raise Exception.Create(sFailedMapView) finally CloseHandle (MapHandle) end; FFileHeader := FData; if FFileHeader^.bfType <> BitmapSignature then begin UnmapViewOfFile (FData); FData := nil; raise Exception.Create(sInvalidBitmap); end; FInfoHeader := pointer (integer (FData) + sizeof (TBitmapFileHeader)); FInfo := pointer (FInfoHeader); FPixelStart := pointer (Cardinal(FData) + FFileHeader^.bfOffBits); with FInfoHeader^ do if biClrUsed <> 0 then FColours := biClrUsed else case biBitCount of 1, 4, 8 : FColours := 1 shl biBitCount else FColours := 0 end; fPixelFormat := pfDevice; with FInfoHeader^ do case biBitCount of 1: fPixelFormat := pf1Bit; 4: fPixelFormat := pf4Bit; 8: fPixelFormat := pf8Bit; 16: case biCompression of BI_RGB : fPixelFormat := pf15Bit; end; 24: fPixelFormat := pf24Bit; 32: if biCompression = BI_RGB then fPixelFormat := pf32Bit; end; FBitmapHeight := FInfoHeader^.biHeight; FBitmapWidth := FInfoHeader^.biWidth; GetBitmapPalette; FActive := true; Changed(self); end; procedure TMMBitmap.UnMapFile; begin TraceMessage('UnMapFile'); FActive := false; begin if FData <> nil then begin UnmapViewOfFile(FData); FData := nil end; if FPalette <> 0 then begin DeleteObject(FPalette); FPalette := 0; end; end end; END.
unit FreeOTFEDLLCypherAPI; // API ported from FreeOTFE4PDACypherAPI.h interface uses OTFEFreeOTFE_DriverCypherAPI, Windows; //#define DLLEXPORT_CYPHER_IDENTIFYDRIVER TEXT("CypherIdentifyDriver") //typedef DWORD (* PCypherDLLFnIdentifyDriver)( // DIOC_CYPHER_IDENTIFYDRIVER* // ); const DLLEXPORT_CYPHER_IDENTIFYDRIVER = 'CypherIdentifyDriver'; type PCypherDLLFnIdentifyDriver = function(Buffer: PDIOC_CYPHER_IDENTIFYDRIVER): DWORD; CDECL; // Note: "_v1" missing to give backward compatibility //#define DLLEXPORT_CYPHER_IDENTIFYSUPPORTED_v1 TEXT("CypherIdentifySupported") ////#define DLLEXPORT_CYPHER_IDENTIFYSUPPORTED_v1 TEXT("CypherIdentifySupported_v1") //typedef DWORD (* PCypherDLLFnIdentifySupported_v1)( // unsigned int, // DIOC_CYPHER_IDENTIFYSUPPORTED_v1* // ); const DLLEXPORT_CYPHER_IDENTIFYSUPPORTED_v1 = 'CypherIdentifySupported'; type PCypherDLLFnIdentifySupported_v1 = function(BufferSize: Integer; // In bytes Buffer: PDIOC_CYPHER_IDENTIFYSUPPORTED_v1): DWORD; CDECL; //#define DLLEXPORT_CYPHER_IDENTIFYSUPPORTED_v3 TEXT("CypherIdentifySupported_v3") //typedef DWORD (* PCypherDLLFnIdentifySupported_v3)( // unsigned int, // DIOC_CYPHER_IDENTIFYSUPPORTED_v3* // ); const DLLEXPORT_CYPHER_IDENTIFYSUPPORTED_v3 = 'CypherIdentifySupported_v3'; type PCypherDLLFnIdentifySupported_v3 = function(BufferSize: Integer; // In bytes Buffer: PDIOC_CYPHER_IDENTIFYSUPPORTED_v3): DWORD; CDECL; // Note: "_v1" missing to give backward compatibility //#define DLLEXPORT_CYPHER_GETCYPHERDETAILS_v1 TEXT("CypherGetCypherDetails") ////#define DLLEXPORT_CYPHER_GETCYPHERDETAILS_v1 TEXT("CypherGetCypherDetails_v1") //typedef DWORD (* PCypherDLLFnGetCypherDetails_v1)( // GUID*, // CYPHER_v1* // ); const DLLEXPORT_CYPHER_GETCYPHERDETAILS_v1 = 'CypherGetCypherDetails'; type PCypherDLLFnGetCypherDetails_v1 = function(CypherGUID: PGUID; CypherDetails: PCYPHER_v1): DWORD; CDECL; //#define DLLEXPORT_CYPHER_GETCYPHERDETAILS_v3 TEXT("CypherGetCypherDetails_v3") //typedef DWORD (* PCypherDLLFnGetCypherDetails_v3)( // GUID*, // CYPHER_v3* // ); const DLLEXPORT_CYPHER_GETCYPHERDETAILS_v3 = 'CypherGetCypherDetails_v3'; type PCypherDLLFnGetCypherDetails_v3 = function(CypherGUID: PGUID; CypherDetails: PCYPHER_v3): DWORD; CDECL; //#define DLLEXPORT_CYPHER_ENCRYPT TEXT("CypherEncrypt") //typedef DWORD (* PCypherDLLFnEncrypt)( // DWORD, // DIOC_CYPHER_DATA_IN*, // DWORD, // DIOC_CYPHER_DATA_OUT* // ); const DLLEXPORT_CYPHER_ENCRYPT = 'CypherEncrypt'; type PCypherDLLFnEncrypt = function(BufferInLen: DWORD; BufferIn: PDIOC_CYPHER_DATA_IN; BufferOutLen: DWORD; BufferOut: PDIOC_CYPHER_DATA_OUT): DWORD; CDECL; //#define DLLEXPORT_CYPHER_ENCRYPTSECTOR TEXT("CypherEncryptSector") //typedef DWORD (* PCypherDLLFnEncryptSector)( // DWORD, // DIOC_CYPHER_SECTOR_DATA_IN*, // DWORD, // DIOC_CYPHER_DATA_OUT* // ); const DLLEXPORT_CYPHER_ENCRYPTSECTOR = 'CypherEncryptSector'; type PCypherDLLFnEncryptSector = function(BufferInLen: DWORD; BufferIn: PDIOC_CYPHER_SECTOR_DATA_IN; BufferOutLen: DWORD; BufferOut: PDIOC_CYPHER_DATA_OUT): DWORD; CDECL; //#define DLLEXPORT_CYPHER_ENCRYPTWITHASCII TEXT("CypherEncryptWithASCII") //typedef DWORD (* PCypherDLLFnEncryptWithASCII)( // IN GUID*, // IN int, // In bits // IN FREEOTFEBYTE*, // IN char*, // ASCII representation of "Key" // IN int, // In bits // IN FREEOTFEBYTE*, // IN int, // In bytes // IN FREEOTFEBYTE*, // OUT FREEOTFEBYTE* // ); const DLLEXPORT_CYPHER_ENCRYPTWITHASCII = 'CypherEncryptWithASCII'; type PCypherDLLFnEncryptWithASCII = function(CypherGUID: PGUID; KeyLength: Integer; // In bits Key: PByte; KeyASCII: PChar; // ASCII representation of "Key" IVLength: Integer; // In bits IV: PByte; PlaintextLength: Integer; // In bytes PlaintextData: PByte; CyphertextData: PByte): DWORD; CDECL; //#define DLLEXPORT_CYPHER_ENCRYPTSECTORWITHASCII TEXT("CypherEncryptSectorWithASCII") //typedef DWORD (* PCypherDLLFnEncryptSectorWithASCII)( // IN GUID*, // IN LARGE_INTEGER, // IN int, // IN int, // In bits // IN FREEOTFEBYTE*, // IN char*, // ASCII representation of "Key" // IN int, // In bits // IN FREEOTFEBYTE*, // IN int, // In bytes // IN FREEOTFEBYTE*, // OUT FREEOTFEBYTE* // ); const DLLEXPORT_CYPHER_ENCRYPTSECTORWITHASCII = 'CypherEncryptSectorWithASCII'; type PCypherDLLFnEncryptSectorWithASCII = function(CypherGUID: PGUID; SectorID: LARGE_INTEGER; SectorSize: Integer; KeyLength: Integer; // In bits Key: PByte; KeyASCII: PChar; // ASCII representation of "Key" IVLength: Integer; // In bits IV: PByte; PlaintextLength: Integer; // In bytes PlaintextData: PByte; CyphertextData: PByte): DWORD; CDECL; //#define DLLEXPORT_CYPHER_DECRYPT TEXT("CypherDecrypt") //typedef DWORD (* PCypherDLLFnDecrypt)( // DWORD, // DIOC_CYPHER_DATA_IN*, // DWORD, // DIOC_CYPHER_DATA_OUT* // ); const DLLEXPORT_CYPHER_DECRYPT = 'CypherDecrypt'; type PCypherDLLFnDecrypt = function(BufferInLen: DWORD; BufferIn: PDIOC_CYPHER_DATA_IN; BufferOutLen: DWORD; BufferOut: PDIOC_CYPHER_DATA_OUT): DWORD; CDECL; //#define DLLEXPORT_CYPHER_DECRYPTSECTOR TEXT("CypherDecryptSector") //typedef DWORD (* PCypherDLLFnDecryptSector)( // DWORD, // DIOC_CYPHER_SECTOR_DATA_IN*, // DWORD, // DIOC_CYPHER_DATA_OUT* // ); const DLLEXPORT_CYPHER_DECRYPTSECTOR = 'CypherDecryptSector'; type PCypherDLLFnDecryptSector = function(BufferInLen: DWORD; BufferIn: PDIOC_CYPHER_SECTOR_DATA_IN; BufferOutLen: DWORD; BufferOut: PDIOC_CYPHER_DATA_OUT): DWORD; CDECL; //#define DLLEXPORT_CYPHER_DECRYPTWITHASCII TEXT("CypherDecryptWithASCII") //typedef DWORD (* PCypherDLLFnDecryptWithASCII)( // IN GUID*, // IN int, // In bits // IN FREEOTFEBYTE*, // IN char*, // ASCII representation of "Key" // IN int, // In bits // IN FREEOTFEBYTE*, // IN int, // In bytes // IN FREEOTFEBYTE*, // OUT FREEOTFEBYTE* // ); const DLLEXPORT_CYPHER_DECRYPTWITHASCII = 'CypherDecryptWithASCII'; type PCypherDLLFnDecryptWithASCII = function(CypherGUID: PGUID; KeyLength: Integer; // In bits Key: PByte; KeyASCII: PChar; // ASCII representation of "Key" IVLength: Integer; // In bits IV: PByte; CyphertextLength: Integer; // In bytes CyphertextData: PByte; PlaintextData: PByte): DWORD; CDECL; //#define DLLEXPORT_CYPHER_DECRYPTSECTORWITHASCII TEXT("CypherDecryptSectorWithASCII") //typedef DWORD (* PCypherDLLFnDecryptSectorWithASCII)( // IN GUID*, // IN LARGE_INTEGER, // IN int, // IN int, // In bits // IN FREEOTFEBYTE*, // IN char*, // ASCII representation of "Key" // IN int, // In bits // IN FREEOTFEBYTE*, // IN int, // In bytes // IN FREEOTFEBYTE*, // OUT FREEOTFEBYTE* // ); const DLLEXPORT_CYPHER_DECRYPTSECTORWITHASCII = 'CypherDecryptSectorWithASCII'; type PCypherDLLFnDecryptSectorWithASCII = function(CypherGUID: PGUID; SectorID: LARGE_INTEGER; SectorSize: Integer; KeyLength: Integer; // In bits Key: PByte; KeyASCII: PChar; // ASCII representation of "Key" IVLength: Integer; // In bits IV: PByte; CyphertextLength: Integer; // In bytes CyphertextData: PByte; PlaintextData: PByte): DWORD; CDECL; implementation end.
unit uMetaData; interface uses classes, uAttributes, SysUtils; type TMetaDataItem = class(TCollectionItem) private FAttributeType: TAttributeType; FGridView: TObject; FParamName: string; FGroupID: integer; FColName: string; FParam1: integer; FParam2: integer; FCategoryName: string; FVisible: boolean; FIsForeignKey: boolean; FForeignTableLookupFieldName: string; FAttrID: integer; public property ColName: string read FColName write FColName; property ParamName: string read FParamName write FParamName; property CategoryName: string read FCategoryName write FCategoryName; property AttrType: TAttributeType read FAttributeType write FAttributeType; property Param1: integer read FParam1 write FParam1; property Param2: integer read FParam2 write FParam2; property GroupID: integer read FGroupID write FGroupID; property Visible: boolean read FVisible write FVisible; property IsForeignKey: boolean read FIsForeignKey write FIsForeignKey; property ForeignTableLookupFieldName: string read FForeignTableLookupFieldName write FForeignTableLookupFieldName; property AttrID: integer read FAttrID write FAttrID; property GridView: TObject read FGridView write FGridView; end; TMetaDataCollection = class(TCollection) private function GeItems(Index: integer): TMetaDataItem; public property Items[Index: integer]: TMetaDataItem read GeItems; default; function Add: TMetaDataItem; function FieldByParam(AParam: string): string; virtual; function ParamByField(AField: string): string; virtual; procedure CreateItems(ObjectName: string; WithObjectFields: boolean = false); virtual; end; implementation uses uCommonUtils, ADODB; { TMetaDataColection } function TMetaDataCollection.Add: TMetaDataItem; begin result:=TMetaDataItem(inherited Add); end; procedure TMetaDataCollection.CreateItems(ObjectName: string; WithObjectFields: boolean = false); procedure ParseParams(s: string; var p1, p2, p3, p4, p5, p6, p7, p8, p9: string); var i: integer; begin i:=pos('|', s); p1:=copy(s, 1, i-1); system.delete(s, 1, i); i:=pos('|', s); p2:=copy(s, 1, i-1); system.delete(s, 1, i); i:=pos('|', s); p3:=copy(s, 1, i-1); system.delete(s, 1, i); i:=pos('|', s); p4:=copy(s, 1, i-1); system.delete(s, 1, i); i:=pos('|', s); p5:=copy(s, 1, i-1); system.delete(s, 1, i); i:=pos('|', s); p6:=copy(s, 1, i-1); system.delete(s, 1, i); i:=pos('|', s); p7:=copy(s, 1, i-1); system.delete(s, 1, i); i:=pos('|', s); p8:=copy(s, 1, i-1); system.delete(s, 1, i); p9:=s; end; var i: TMetaDataItem; n: integer; qry: TAdoQuery; p1, p2, p3, p4, p5, p6, p7, p8, p9: string; sql: string; begin if not WithObjectFields then sql:='select * from [в_'+ObjectName+'_мета]' else sql:='select * from [в_'+ObjectName+'_мета] cross join [в_Учетная единица_для_объединения_мета]'; qry:=CreateQuery(sql); try qry.Open; for n:=0 to qry.FieldCount-1 do begin ParseParams(qry.Fields[n].Value, p1, p2, p3, p4, p5, p6, p7, p8, p9); i:=Add; i.ColName:=qry.Fields[n].DisplayName; i.ParamName:=p1; i.CategoryName:=p2; i.AttrType:=TAttributeType(StrToInt(p3)-1); i.Param1:=StrToInt(p4); i.Param2:=StrToInt(p5); i.GroupID:=StrToInt(p6); i.Visible:=p7='V'; i.IsForeignKey:=p8='FK'; if (p8<>'FK') and (p8<>'-') then i.ForeignTableLookupFieldName:=p8 else i.ForeignTableLookupFieldName:=''; i.AttrID:=StrToIntDef(p9, -1); end; finally qry.Free; end; end; function TMetaDataCollection.FieldByParam(AParam: string): string; var i: integer; begin result:=''; AParam:=AnsiLowerCase(AParam); for i:=0 to Count-1 do if AnsiLowerCase(Items[i].ParamName) = AParam then begin result:=Items[i].ColName; exit; end; end; function TMetaDataCollection.ParamByField(AField: string): string; var i: integer; begin result:=''; AField:=AnsiLowerCase(AField); for i:=0 to Count-1 do if AnsiLowerCase(Items[i].ColName ) = AField then begin result:=Items[i].ParamName; exit; end; end; function TMetaDataCollection.GeItems(Index: integer): TMetaDataItem; begin result:=TMetaDataItem(inherited Items[Index]); end; end.
unit ippsOver1; interface uses util1,ippdefs,ipps; (* ///////////////////////////////////////////////////////////////////////////// // Arithmetic functions; ///////////////////////////////////////////////////////////////////////////// *) (* //////////////////////////////////////////////////////////////////////////// // Names: ippsAdd, ippsSub, ippsMul // // Purpose: add, subtract and multiply operations upon every element of // the source vector // Arguments: // pSrc pointer to the source vector // pSrcDst pointer to the source/destination vector // pSrc1 pointer to the first source vector // pSrc2 pointer to the second source vector // pDst pointer to the destination vector // len length of the vectors // scaleFactor scale factor value // Return: // ippStsNullPtrErr pointer(s) to the data is NULL // ippStsSizeErr length of the vectors is less or equal zero // ippStsNoErr otherwise // Note: // AddC(X,v,Y) : Y[n] = X[n] + v // MulC(X,v,Y) : Y[n] = X[n] * v // SubC(X,v,Y) : Y[n] = X[n] - v // SubCRev(X,v,Y) : Y[n] = v - X[n] // Sub(X,Y) : Y[n] = Y[n] - X[n] // Sub(X,Y,Z) : Z[n] = Y[n] - X[n] *) function ippsAddC(val:Ipp16s;pSrcDst:PIpp16s;len:longint):IppStatus;overload; function ippsSubC(val:Ipp16s;pSrcDst:PIpp16s;len:longint):IppStatus;overload; function ippsMulC(val:Ipp16s;pSrcDst:PIpp16s;len:longint):IppStatus;overload; function ippsAddC(val:Ipp32f;pSrcDst:PIpp32f;len:longint):IppStatus;overload; function ippsAddC(val:Ipp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus;overload; function ippsSubC(val:Ipp32f;pSrcDst:PIpp32f;len:longint):IppStatus;overload; function ippsSubC(val:Ipp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus;overload; function ippsSubCRev(val:Ipp32f;pSrcDst:PIpp32f;len:longint):IppStatus;overload; function ippsSubCRev(val:Ipp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus;overload; function ippsMulC(val:Ipp32f;pSrcDst:PIpp32f;len:longint):IppStatus;overload; function ippsMulC(val:Ipp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus;overload; function ippsAddC(val:Ipp64f;pSrcDst:PIpp64f;len:longint):IppStatus;overload; function ippsAddC(val:Ipp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus;overload; function ippsSubC(val:Ipp64f;pSrcDst:PIpp64f;len:longint):IppStatus;overload; function ippsSubC(val:Ipp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus;overload; function ippsSubCRev(val:Ipp64f;pSrcDst:PIpp64f;len:longint):IppStatus;overload; function ippsSubCRev(val:Ipp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus;overload; function ippsMulC(val:Ipp64f;pSrcDst:PIpp64f;len:longint):IppStatus;overload; function ippsMulC(val:Ipp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp16s;len:longint):IppStatus;overload; function ippsAddC(val:Ipp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(val:Ipp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(val:Ipp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(val:Ipp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAddC(val:Ipp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(val:Ipp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(val:Ipp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAddC(val:Ipp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(val:Ipp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(val:Ipp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(val:Ipp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(val:Ipp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAddC(val:Ipp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAddC(val:Ipp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(val:Ipp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(val:Ipp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(val:Ipp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(val:Ipp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(val:Ipp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(val:Ipp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAddC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsAddC(pSrc:PIpp32fc;val:Ipp32fc;pDst:PIpp32fc;len:longint):IppStatus;overload; function ippsSubC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsSubC(pSrc:PIpp32fc;val:Ipp32fc;pDst:PIpp32fc;len:longint):IppStatus;overload; function ippsSubCRev(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsSubCRev(pSrc:PIpp32fc;val:Ipp32fc;pDst:PIpp32fc;len:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp32fc;val:Ipp32fc;pDst:PIpp32fc;len:longint):IppStatus;overload; function ippsAddC(pSrc:PIpp64f;val:Ipp64f;pDst:PIpp64f;len:longint):IppStatus;overload; function ippsAddC(pSrc:PIpp64fc;val:Ipp64fc;pDst:PIpp64fc;len:longint):IppStatus;overload; function ippsSubC(pSrc:PIpp64f;val:Ipp64f;pDst:PIpp64f;len:longint):IppStatus;overload; function ippsSubC(pSrc:PIpp64fc;val:Ipp64fc;pDst:PIpp64fc;len:longint):IppStatus;overload; function ippsSubCRev(pSrc:PIpp64f;val:Ipp64f;pDst:PIpp64f;len:longint):IppStatus;overload; function ippsSubCRev(pSrc:PIpp64fc;val:Ipp64fc;pDst:PIpp64fc;len:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp64f;val:Ipp64f;pDst:PIpp64f;len:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp64fc;val:Ipp64fc;pDst:PIpp64fc;len:longint):IppStatus;overload; function ippsAddC(pSrc:PIpp8u;val:Ipp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(pSrc:PIpp8u;val:Ipp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(pSrc:PIpp8u;val:Ipp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp8u;val:Ipp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAddC(pSrc:PIpp16s;val:Ipp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAddC(pSrc:PIpp16sc;val:Ipp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(pSrc:PIpp16s;val:Ipp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(pSrc:PIpp16sc;val:Ipp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(pSrc:PIpp16s;val:Ipp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(pSrc:PIpp16sc;val:Ipp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp16s;val:Ipp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp16sc;val:Ipp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAddC(pSrc:PIpp32s;val:Ipp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAddC(pSrc:PIpp32sc;val:Ipp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(pSrc:PIpp32s;val:Ipp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubC(pSrc:PIpp32sc;val:Ipp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(pSrc:PIpp32s;val:Ipp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSubCRev(pSrc:PIpp32sc;val:Ipp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp32s;val:Ipp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMulC(pSrc:PIpp32sc;val:Ipp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint):IppStatus;overload; function ippsSub(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint):IppStatus;overload; function ippsMul(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp32f;pSrcDst:PIpp32f;len:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus;overload; function ippsSub(pSrc:PIpp32f;pSrcDst:PIpp32f;len:longint):IppStatus;overload; function ippsSub(pSrc:PIpp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus;overload; function ippsMul(pSrc:PIpp32f;pSrcDst:PIpp32f;len:longint):IppStatus;overload; function ippsMul(pSrc:PIpp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp64f;pSrcDst:PIpp64f;len:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus;overload; function ippsSub(pSrc:PIpp64f;pSrcDst:PIpp64f;len:longint):IppStatus;overload; function ippsSub(pSrc:PIpp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus;overload; function ippsMul(pSrc:PIpp64f;pSrcDst:PIpp64f;len:longint):IppStatus;overload; function ippsMul(pSrc:PIpp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc:PIpp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc:PIpp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc:PIpp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc:PIpp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc:PIpp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc:PIpp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc:PIpp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc:PIpp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc:PIpp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp16u;len:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp16u;len:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp16u;pSrc2:PIpp16u;pDst:PIpp16u;len:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp32u;pSrc2:PIpp32u;pDst:PIpp32u;len:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp32f;pSrc2:PIpp32f;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp32fc;pSrc2:PIpp32fc;pDst:PIpp32fc;len:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp32f;pSrc2:PIpp32f;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp32fc;pSrc2:PIpp32fc;pDst:PIpp32fc;len:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp32f;pSrc2:PIpp32f;pDst:PIpp32f;len:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp32fc;pSrc2:PIpp32fc;pDst:PIpp32fc;len:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp64f;pSrc2:PIpp64f;pDst:PIpp64f;len:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp64fc;pSrc2:PIpp64fc;pDst:PIpp64fc;len:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp64f;pSrc2:PIpp64f;pDst:PIpp64f;len:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp64fc;pSrc2:PIpp64fc;pDst:PIpp64fc;len:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp64f;pSrc2:PIpp64f;pDst:PIpp64f;len:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp64fc;pSrc2:PIpp64fc;pDst:PIpp64fc;len:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp16sc;pSrc2:PIpp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp16sc;pSrc2:PIpp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp16sc;pSrc2:PIpp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp32s;pSrc2:PIpp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsAdd(pSrc1:PIpp32sc;pSrc2:PIpp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp32s;pSrc2:PIpp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsSub(pSrc1:PIpp32sc;pSrc2:PIpp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp32s;pSrc2:PIpp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp32sc;pSrc2:PIpp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp16u;pSrc2:PIpp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc:PIpp32s;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; function ippsMul(pSrc1:PIpp32s;pSrc2:PIpp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus;overload; implementation function ippsAddC(val:Ipp16s;pSrcDst:PIpp16s;len:longint):IppStatus; begin result:=ippsAddC_16s_I(val,pSrcDst,len); end; function ippsSubC(val:Ipp16s;pSrcDst:PIpp16s;len:longint):IppStatus; begin result:=ippsSubC_16s_I(val,pSrcDst,len); end; function ippsMulC(val:Ipp16s;pSrcDst:PIpp16s;len:longint):IppStatus; begin result:=ippsMulC_16s_I(val,pSrcDst,len); end; function ippsAddC(val:Ipp32f;pSrcDst:PIpp32f;len:longint):IppStatus; begin result:=ippsAddC_32f_I(val,pSrcDst,len); end; function ippsAddC(val:Ipp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsAddC_32fc_I(val,pSrcDst,len); end; function ippsSubC(val:Ipp32f;pSrcDst:PIpp32f;len:longint):IppStatus; begin result:=ippsSubC_32f_I(val,pSrcDst,len); end; function ippsSubC(val:Ipp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsSubC_32fc_I(val,pSrcDst,len); end; function ippsSubCRev(val:Ipp32f;pSrcDst:PIpp32f;len:longint):IppStatus; begin result:=ippsSubCRev_32f_I(val,pSrcDst,len); end; function ippsSubCRev(val:Ipp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsSubCRev_32fc_I(val,pSrcDst,len); end; function ippsMulC(val:Ipp32f;pSrcDst:PIpp32f;len:longint):IppStatus; begin result:=ippsMulC_32f_I(val,pSrcDst,len); end; function ippsMulC(val:Ipp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsMulC_32fc_I(val,pSrcDst,len); end; function ippsAddC(val:Ipp64f;pSrcDst:PIpp64f;len:longint):IppStatus; begin result:=ippsAddC_64f_I(val,pSrcDst,len); end; function ippsAddC(val:Ipp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsAddC_64fc_I(val,pSrcDst,len); end; function ippsSubC(val:Ipp64f;pSrcDst:PIpp64f;len:longint):IppStatus; begin result:=ippsSubC_64f_I(val,pSrcDst,len); end; function ippsSubC(val:Ipp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsSubC_64fc_I(val,pSrcDst,len); end; function ippsSubCRev(val:Ipp64f;pSrcDst:PIpp64f;len:longint):IppStatus; begin result:=ippsSubCRev_64f_I(val,pSrcDst,len); end; function ippsSubCRev(val:Ipp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsSubCRev_64fc_I(val,pSrcDst,len); end; function ippsMulC(val:Ipp64f;pSrcDst:PIpp64f;len:longint):IppStatus; begin result:=ippsMulC_64f_I(val,pSrcDst,len); end; function ippsMulC(val:Ipp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsMulC_64fc_I(val,pSrcDst,len); end; function ippsMulC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_32f16s_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsMulC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp16s;len:longint):IppStatus; begin result:=ippsMulC_Low_32f16s(pSrc,val,pDst,len); end; function ippsAddC(val:Ipp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_8u_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubC(val:Ipp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_8u_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubCRev(val:Ipp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_8u_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsMulC(val:Ipp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_8u_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsAddC(val:Ipp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_16s_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubC(val:Ipp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_16s_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsMulC(val:Ipp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_16s_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsAddC(val:Ipp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_16sc_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubC(val:Ipp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_16sc_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsMulC(val:Ipp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_16sc_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubCRev(val:Ipp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_16s_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubCRev(val:Ipp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_16sc_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsAddC(val:Ipp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_32s_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsAddC(val:Ipp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_32sc_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubC(val:Ipp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_32s_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubC(val:Ipp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_32sc_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubCRev(val:Ipp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_32s_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsSubCRev(val:Ipp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_32sc_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsMulC(val:Ipp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_32s_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsMulC(val:Ipp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_32sc_ISfs(val,pSrcDst,len,scaleFactor); end; function ippsAddC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsAddC_32f(pSrc,val,pDst,len); end; function ippsAddC(pSrc:PIpp32fc;val:Ipp32fc;pDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsAddC_32fc(pSrc,val,pDst,len); end; function ippsSubC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsSubC_32f(pSrc,val,pDst,len); end; function ippsSubC(pSrc:PIpp32fc;val:Ipp32fc;pDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsSubC_32fc(pSrc,val,pDst,len); end; function ippsSubCRev(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsSubCRev_32f(pSrc,val,pDst,len); end; function ippsSubCRev(pSrc:PIpp32fc;val:Ipp32fc;pDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsSubCRev_32fc(pSrc,val,pDst,len); end; function ippsMulC(pSrc:PIpp32f;val:Ipp32f;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsMulC_32f(pSrc,val,pDst,len); end; function ippsMulC(pSrc:PIpp32fc;val:Ipp32fc;pDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsMulC_32fc(pSrc,val,pDst,len); end; function ippsAddC(pSrc:PIpp64f;val:Ipp64f;pDst:PIpp64f;len:longint):IppStatus; begin result:=ippsAddC_64f(pSrc,val,pDst,len); end; function ippsAddC(pSrc:PIpp64fc;val:Ipp64fc;pDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsAddC_64fc(pSrc,val,pDst,len); end; function ippsSubC(pSrc:PIpp64f;val:Ipp64f;pDst:PIpp64f;len:longint):IppStatus; begin result:=ippsSubC_64f(pSrc,val,pDst,len); end; function ippsSubC(pSrc:PIpp64fc;val:Ipp64fc;pDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsSubC_64fc(pSrc,val,pDst,len); end; function ippsSubCRev(pSrc:PIpp64f;val:Ipp64f;pDst:PIpp64f;len:longint):IppStatus; begin result:=ippsSubCRev_64f(pSrc,val,pDst,len); end; function ippsSubCRev(pSrc:PIpp64fc;val:Ipp64fc;pDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsSubCRev_64fc(pSrc,val,pDst,len); end; function ippsMulC(pSrc:PIpp64f;val:Ipp64f;pDst:PIpp64f;len:longint):IppStatus; begin result:=ippsMulC_64f(pSrc,val,pDst,len); end; function ippsMulC(pSrc:PIpp64fc;val:Ipp64fc;pDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsMulC_64fc(pSrc,val,pDst,len); end; function ippsAddC(pSrc:PIpp8u;val:Ipp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_8u_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubC(pSrc:PIpp8u;val:Ipp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_8u_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubCRev(pSrc:PIpp8u;val:Ipp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_8u_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsMulC(pSrc:PIpp8u;val:Ipp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_8u_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsAddC(pSrc:PIpp16s;val:Ipp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_16s_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsAddC(pSrc:PIpp16sc;val:Ipp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_16sc_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubC(pSrc:PIpp16s;val:Ipp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_16s_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubC(pSrc:PIpp16sc;val:Ipp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_16sc_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubCRev(pSrc:PIpp16s;val:Ipp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_16s_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubCRev(pSrc:PIpp16sc;val:Ipp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_16sc_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsMulC(pSrc:PIpp16s;val:Ipp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_16s_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsMulC(pSrc:PIpp16sc;val:Ipp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_16sc_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsAddC(pSrc:PIpp32s;val:Ipp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_32s_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsAddC(pSrc:PIpp32sc;val:Ipp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAddC_32sc_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubC(pSrc:PIpp32s;val:Ipp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_32s_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubC(pSrc:PIpp32sc;val:Ipp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubC_32sc_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubCRev(pSrc:PIpp32s;val:Ipp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_32s_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsSubCRev(pSrc:PIpp32sc;val:Ipp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSubCRev_32sc_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsMulC(pSrc:PIpp32s;val:Ipp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_32s_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsMulC(pSrc:PIpp32sc;val:Ipp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMulC_32sc_Sfs(pSrc,val,pDst,len,scaleFactor); end; function ippsAdd(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint):IppStatus; begin result:=ippsAdd_16s_I(pSrc,pSrcDst,len); end; function ippsSub(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint):IppStatus; begin result:=ippsSub_16s_I(pSrc,pSrcDst,len); end; function ippsMul(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint):IppStatus; begin result:=ippsMul_16s_I(pSrc,pSrcDst,len); end; function ippsAdd(pSrc:PIpp32f;pSrcDst:PIpp32f;len:longint):IppStatus; begin result:=ippsAdd_32f_I(pSrc,pSrcDst,len); end; function ippsAdd(pSrc:PIpp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsAdd_32fc_I(pSrc,pSrcDst,len); end; function ippsSub(pSrc:PIpp32f;pSrcDst:PIpp32f;len:longint):IppStatus; begin result:=ippsSub_32f_I(pSrc,pSrcDst,len); end; function ippsSub(pSrc:PIpp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsSub_32fc_I(pSrc,pSrcDst,len); end; function ippsMul(pSrc:PIpp32f;pSrcDst:PIpp32f;len:longint):IppStatus; begin result:=ippsMul_32f_I(pSrc,pSrcDst,len); end; function ippsMul(pSrc:PIpp32fc;pSrcDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsMul_32fc_I(pSrc,pSrcDst,len); end; function ippsAdd(pSrc:PIpp64f;pSrcDst:PIpp64f;len:longint):IppStatus; begin result:=ippsAdd_64f_I(pSrc,pSrcDst,len); end; function ippsAdd(pSrc:PIpp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsAdd_64fc_I(pSrc,pSrcDst,len); end; function ippsSub(pSrc:PIpp64f;pSrcDst:PIpp64f;len:longint):IppStatus; begin result:=ippsSub_64f_I(pSrc,pSrcDst,len); end; function ippsSub(pSrc:PIpp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsSub_64fc_I(pSrc,pSrcDst,len); end; function ippsMul(pSrc:PIpp64f;pSrcDst:PIpp64f;len:longint):IppStatus; begin result:=ippsMul_64f_I(pSrc,pSrcDst,len); end; function ippsMul(pSrc:PIpp64fc;pSrcDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsMul_64fc_I(pSrc,pSrcDst,len); end; function ippsAdd(pSrc:PIpp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_8u_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsSub(pSrc:PIpp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_8u_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsMul(pSrc:PIpp8u;pSrcDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_8u_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsAdd(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_16s_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsAdd(pSrc:PIpp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_16sc_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsSub(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_16s_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsSub(pSrc:PIpp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_16sc_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsMul(pSrc:PIpp16s;pSrcDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_16s_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsMul(pSrc:PIpp16sc;pSrcDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_16sc_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsAdd(pSrc:PIpp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_32s_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsAdd(pSrc:PIpp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_32sc_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsSub(pSrc:PIpp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_32s_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsSub(pSrc:PIpp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_32sc_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsMul(pSrc:PIpp32s;pSrcDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_32s_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsMul(pSrc:PIpp32sc;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_32sc_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsAdd(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp16u;len:longint):IppStatus; begin result:=ippsAdd_8u16u(pSrc1,pSrc2,pDst,len); end; function ippsMul(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp16u;len:longint):IppStatus; begin result:=ippsMul_8u16u(pSrc1,pSrc2,pDst,len); end; function ippsAdd(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint):IppStatus; begin result:=ippsAdd_16s(pSrc1,pSrc2,pDst,len); end; function ippsSub(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint):IppStatus; begin result:=ippsSub_16s(pSrc1,pSrc2,pDst,len); end; function ippsMul(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint):IppStatus; begin result:=ippsMul_16s(pSrc1,pSrc2,pDst,len); end; function ippsAdd(pSrc1:PIpp16u;pSrc2:PIpp16u;pDst:PIpp16u;len:longint):IppStatus; begin result:=ippsAdd_16u(pSrc1,pSrc2,pDst,len); end; function ippsAdd(pSrc1:PIpp32u;pSrc2:PIpp32u;pDst:PIpp32u;len:longint):IppStatus; begin result:=ippsAdd_32u(pSrc1,pSrc2,pDst,len); end; function ippsAdd(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsAdd_16s32f(pSrc1,pSrc2,pDst,len); end; function ippsSub(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsSub_16s32f(pSrc1,pSrc2,pDst,len); end; function ippsMul(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsMul_16s32f(pSrc1,pSrc2,pDst,len); end; function ippsAdd(pSrc1:PIpp32f;pSrc2:PIpp32f;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsAdd_32f(pSrc1,pSrc2,pDst,len); end; function ippsAdd(pSrc1:PIpp32fc;pSrc2:PIpp32fc;pDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsAdd_32fc(pSrc1,pSrc2,pDst,len); end; function ippsSub(pSrc1:PIpp32f;pSrc2:PIpp32f;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsSub_32f(pSrc1,pSrc2,pDst,len); end; function ippsSub(pSrc1:PIpp32fc;pSrc2:PIpp32fc;pDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsSub_32fc(pSrc1,pSrc2,pDst,len); end; function ippsMul(pSrc1:PIpp32f;pSrc2:PIpp32f;pDst:PIpp32f;len:longint):IppStatus; begin result:=ippsMul_32f(pSrc1,pSrc2,pDst,len); end; function ippsMul(pSrc1:PIpp32fc;pSrc2:PIpp32fc;pDst:PIpp32fc;len:longint):IppStatus; begin result:=ippsMul_32fc(pSrc1,pSrc2,pDst,len); end; function ippsAdd(pSrc1:PIpp64f;pSrc2:PIpp64f;pDst:PIpp64f;len:longint):IppStatus; begin result:=ippsAdd_64f(pSrc1,pSrc2,pDst,len); end; function ippsAdd(pSrc1:PIpp64fc;pSrc2:PIpp64fc;pDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsAdd_64fc(pSrc1,pSrc2,pDst,len); end; function ippsSub(pSrc1:PIpp64f;pSrc2:PIpp64f;pDst:PIpp64f;len:longint):IppStatus; begin result:=ippsSub_64f(pSrc1,pSrc2,pDst,len); end; function ippsSub(pSrc1:PIpp64fc;pSrc2:PIpp64fc;pDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsSub_64fc(pSrc1,pSrc2,pDst,len); end; function ippsMul(pSrc1:PIpp64f;pSrc2:PIpp64f;pDst:PIpp64f;len:longint):IppStatus; begin result:=ippsMul_64f(pSrc1,pSrc2,pDst,len); end; function ippsMul(pSrc1:PIpp64fc;pSrc2:PIpp64fc;pDst:PIpp64fc;len:longint):IppStatus; begin result:=ippsMul_64fc(pSrc1,pSrc2,pDst,len); end; function ippsAdd(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_8u_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsSub(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_8u_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsMul(pSrc1:PIpp8u;pSrc2:PIpp8u;pDst:PIpp8u;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_8u_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsAdd(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_16s_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsAdd(pSrc1:PIpp16sc;pSrc2:PIpp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_16sc_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsSub(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_16s_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsSub(pSrc1:PIpp16sc;pSrc2:PIpp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_16sc_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsMul(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_16s_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsMul(pSrc1:PIpp16sc;pSrc2:PIpp16sc;pDst:PIpp16sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_16sc_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsMul(pSrc1:PIpp16s;pSrc2:PIpp16s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_16s32s_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsAdd(pSrc1:PIpp32s;pSrc2:PIpp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_32s_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsAdd(pSrc1:PIpp32sc;pSrc2:PIpp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsAdd_32sc_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsSub(pSrc1:PIpp32s;pSrc2:PIpp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_32s_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsSub(pSrc1:PIpp32sc;pSrc2:PIpp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsSub_32sc_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsMul(pSrc1:PIpp32s;pSrc2:PIpp32s;pDst:PIpp32s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_32s_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsMul(pSrc1:PIpp32sc;pSrc2:PIpp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_32sc_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsMul(pSrc1:PIpp16u;pSrc2:PIpp16s;pDst:PIpp16s;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_16u16s_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; function ippsMul(pSrc:PIpp32s;pSrcDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_32s32sc_ISfs(pSrc,pSrcDst,len,scaleFactor); end; function ippsMul(pSrc1:PIpp32s;pSrc2:PIpp32sc;pDst:PIpp32sc;len:longint;scaleFactor:longint):IppStatus; begin result:=ippsMul_32s32sc_Sfs(pSrc1,pSrc2,pDst,len,scaleFactor); end; procedure test; var p1,p2:Pointer; begin ippsAdd(Pdouble(p1),Pdouble(p2),100); end; end.
{//************************************************************//} {// Projeto MVCBr //} {// tireideletra.com.br / amarildo lacerda //} {//************************************************************//} {// Data: 03/03/2017 //} {//************************************************************//} unit oData.Interf; interface uses System.Classes, System.SysUtils, System.JSON; Type IODataDecodeParams = interface; IODataParse = interface; IODataDecode = interface ['{E9DA95A9-534F-495E-9293-2657D4330D4C}'] function Lock:IODataDecode; procedure UnLock; function GetParse:IODataParse; function This: TObject; procedure SetSelect(const Value: string); procedure SetFilter(const Value: string); procedure SetOrderBy(const Value: string); procedure SetSkip(const Value: integer); procedure SetExpand(const Value: string); procedure SetTop(const Value: integer); procedure SetFormat(const Value: string); procedure SetResource(const Value: string); procedure SetInLineCount(const Value: string); procedure SetSkipToken(const Value: string); function GetExpand: string; function GetFilter: string; function GetFormat: string; function GetInLineCount: string; function GetOrderBy: string; function GetResource: string; function GetSelect: string; function GetSkip: integer; function GetSkipToken: string; function GetTop: integer; procedure SetGroupBy(const Value: string); function GetGroupBy: string; function GetResourceParams: IODataDecodeParams; procedure SetSearch(const Value: string); function GetSearch: string; procedure Setdebug(const Value: string); function GetDebug: string; property Resource: string read GetResource write SetResource; property ResourceParams: IODataDecodeParams read GetResourceParams; function GetLevel(FLevel: integer;AAutoCreate:Boolean): IODataDecode; function hasChild: boolean; function Child: IODataDecode; function newChild: IODataDecode; function hasExpand:boolean; function ExpandItem(const idx:integer):IODataDecode; function newExpand( const ACollection:string):IODataDecode; function ExpandCount:integer; // define a list of fields property &Select: string read GetSelect write SetSelect; // define filter (aka where) property &Filter: string read GetFilter write SetFilter; property &Search:string read GetSearch write SetSearch; // define orderby property &OrderBy: string read GetOrderBy write SetOrderBy; property &GroupBy:string read GetGroupBy write SetGroupBy; // expands relation collections property &Expand: string read GetExpand write SetExpand; // format response (suport only json for now) property &Format: string read GetFormat write SetFormat; // pagination property &Skip: integer read GetSkip write SetSkip; property &Top: integer read GetTop write SetTop; property &SkipToken: string read GetSkipToken write SetSkipToken; property &Count: string read GetInLineCount write SetInLineCount; property &Debug:string read Getdebug write Setdebug; function ToString: string; end; IODataDecodeParams = interface ['{F03C7F83-F379-4D27-AFC5-C6D85FC56DE0}'] procedure AddPair(AKey: string;AValue: string); procedure AddOperator(const AOperator:string); procedure AddOperatorLink(const AOperatorLink:string); procedure Clear; function Count: integer; function ContainKey(AKey: string): boolean; function KeyOfIndex(const idx:integer):string; function OperatorOfIndex(const idx:integer):string; function OperatorLinkOfIndex(const idx: integer): string; function ValueOfIndex(const idx: integer): string; end; IODataDialect = interface ['{812DB60E-64D7-4290-99DB-F625EC52C6DA}'] function GetResource:IInterface;overload; function createGETQuery(AValue: IODataDecode; AFilter: string; const AInLineCount: boolean = false): string; function createDeleteQuery(oData: IODataDecode; AJsonBody:TJsonValue;AKeys:string): string; function CreatePostQuery(oData: IODataDecode; AJsonBody:TJsonValue):String; function createPATCHQuery(oData: IODataDecode; AJsonBody:TJsonValue;AKeys:string):String; function GetResource(AResource: string): IInterface;overload; function AfterCreateSQL(var SQL: string):boolean; end; IODataParse = interface ['{10893BDD-CE9A-4F31-BB2E-8DF18EA5A91B}'] procedure Parse(URL: string); function GetOData: IODataDecode; property oData: IODataDecode read GetOData; // write SetOData; end; IODataBase = interface ['{61D854AF-4773-4DD2-9648-AD93A4134F13}'] procedure DecodeODataURL(CTX: TObject); function This: TObject; function ExecuteGET(AJsonBody:TJsonValue;var JSONResponse: TJSONObject): TObject; function ExecuteDELETE(ABody:string; var JSONResponse: TJSONObject):Integer; function ExecutePOST(ABody:string;var JSON:TJSONObject):Integer; function ExecutePATCH(ABody:string;var JSON:TJSONObject):Integer; function ExecuteOPTIONS(var JSON:TJSONObject):Integer; procedure CreateExpandCollections(AQuery: TObject); function Collection: string; function GetInLineRecordCount: integer; procedure SetInLineRecordCount(const Value: integer); property InLineRecordCount: integer read GetInLineRecordCount Write SetInLineRecordCount; function GetParse: IODataParse; end; implementation end.
unit tal_uhistorysettings; {$mode delphi}{$H+} interface uses Classes, SysUtils, tal_ihistorysettings, Controls, StdCtrls, Forms, trl_irttibroker, trl_ipersist, trl_upersist, ExtCtrls, SynEditMiscClasses; type { THistoryData } THistoryData = class private fName: string; fID: string; published property Name: string read fName write fName; property ID: string read fID write fID; end; { THistoryDataPosition } THistoryDataPosition = class(THistoryData) private fTop: integer; fLeft: integer; fWidth: integer; fHeight: integer; published property Top: integer read fTop write fTop; property Left: integer read fLeft write fLeft; property Width: integer read fWidth write fWidth; property Height: integer read fHeight write fHeight; end; { THistoryDataTexts } THistoryDataTexts = class(THistoryData) private fTexts: IPersistManyStrings; public procedure AfterConstruction; override; published property Texts: IPersistManyStrings read fTexts; end; { THistoryDataCheckBoxState } THistoryDataCheckBoxState = class(THistoryData) private fCheckBoxState: TCheckBoxState; published property CheckBoxState: TCheckBoxState read fCheckBoxState write fCheckBoxState; end; { THistoryDataIntegers } THistoryDataIntegers = class(THistoryData) private fIntegers: IPersistManyIntegers; public procedure AfterConstruction; override; published property Integers: IPersistManyIntegers read fIntegers; end; { THistoryDataMemo } THistoryDataMemo = class(THistoryData) private fMemo: TMemoString; published property Memo: TMemoString read fMemo write fMemo; end; { TControlVisitor } TControlVisitor = class protected type TFinder<TDATA: THistoryData> = class public // temporarily instead of GetHistoryData class function GetHistoryData(const AStore: IPersistStore; const AName, AID: string; ACanCreate: Boolean): IRBData; end; protected const cMaxTexts = 10; protected fStore: IPersistStore; protected // it cause internal error when use TDATA type(like classname) //function GetHistoryData<TDATA: THistoryData>(const AName, AID: string; ACanCreate: Boolean): TDATA; public constructor Create(AStore: IPersistStore); procedure Visit(AControl: TControl; const AID: string); virtual; abstract; overload; procedure Visit(AControl: TCustomComboBox; const AID: string); virtual; abstract; overload; procedure Visit(AControl: TCustomForm; const AID: string); virtual; abstract; overload; procedure Visit(AControl: TCustomSplitter; const AID: string); virtual; abstract; overload; procedure Visit(AControl: TCustomCheckBox; const AID: string); virtual; abstract; overload; procedure Visit(AControl: TSynEditBase; const AID: string); virtual; abstract; overload; procedure Visit(AControl: TCustomEdit; const AID: string); virtual; abstract; overload; end; { TControlSaveVisitor } TControlSaveVisitor = class(TControlVisitor) public procedure Visit(AControl: TControl; const AID: string); override; overload; procedure Visit(AControl: TCustomComboBox; const AID: string); override; overload; procedure Visit(AControl: TCustomForm; const AID: string); override; overload; procedure Visit(AControl: TCustomSplitter; const AID: string); override; overload; procedure Visit(AControl: TCustomCheckBox; const AID: string); override; overload; procedure Visit(AControl: TSynEditBase; const AID: string); override; overload; procedure Visit(AControl: TCustomEdit; const AID: string); override; overload; end; { TControlLoadVisitor } TControlLoadVisitor = class(TControlVisitor) public procedure Visit(AControl: TControl; const AID: string); override; overload; procedure Visit(AControl: TCustomComboBox; const AID: string); override; overload; procedure Visit(AControl: TCustomForm; const AID: string); override; overload; procedure Visit(AControl: TCustomSplitter; const AID: string); override; overload; procedure Visit(AControl: TCustomCheckBox; const AID: string); override; overload; procedure Visit(AControl: TSynEditBase; const AID: string); override; overload; procedure Visit(AControl: TCustomEdit; const AID: string); override; overload; end; { THistorySettings } THistorySettings = class(TInterfacedObject, IHistorySettings) protected fStore: IPersistStore; protected procedure DispatchVisit(AControl: TControl; const AID: string; AVisitor: TControlVisitor); procedure AcceptVisitor(AControl: TWinControl; AVisitor: TControlVisitor; const AID: string; AInside: Boolean = True); overload; procedure AcceptVisitor(AControl: TControl; AVisitor: TControlVisitor; const AID: string; AInside: Boolean = True); overload; function GetHistoryData(const AID: string): IRBData; protected // IHistorySettings procedure Load(const ATopControl: TWinControl; AInside: Boolean = True); overload; procedure Load(const ATopControl: TWinControl; const AID: string; AInside: Boolean = True); overload; procedure Save(const ATopControl: TWinControl; AInside: Boolean = True); overload; procedure Save(const ATopControl: TWinControl; const AID: string; AInside: Boolean = True); overload; published property Store: IPersistStore read fStore write fStore; end; implementation { THistoryDataIntegers } procedure THistoryDataIntegers.AfterConstruction; begin inherited AfterConstruction; fIntegers := TPersistManyIntegers.Create; end; { TControlSaveVisitor } procedure TControlSaveVisitor.Visit(AControl: TControl; const AID: string); begin end; procedure TControlSaveVisitor.Visit(AControl: TCustomComboBox; const AID: string); var i: integer; mData: IRBData; mTexts: THistoryDataTexts; mComboText: string; begin mData := TFinder<THistoryDataTexts>.GetHistoryData(fStore, AControl.Name, AID, True); mTexts := mData.UnderObject as THistoryDataTexts; mComboText := AControl.Text; i := 0; while i <= mTexts.Texts.Count - 1 do if SameText(mComboText, mTexts.Texts[i]) then mTexts.Texts.Delete(i) else inc(i); mTexts.Texts.Count := mTexts.Texts.Count + 1; mTexts.Texts[mTexts.Texts.Count - 1] := mComboText; while mTexts.Texts.Count > cMaxTexts do mTexts.Texts.Delete(0); fStore.Save(mData); end; procedure TControlSaveVisitor.Visit(AControl: TCustomForm; const AID: string); var mData: IRBData; mPosition: THistoryDataPosition; begin mData := TFinder<THistoryDataPosition>.GetHistoryData(fStore, AControl.Name, AID, True); mPosition := mData.UnderObject as THistoryDataPosition; mPosition.Left := AControl.Left; mPosition.Top := AControl.Top; mPosition.Width := AControl.Width; mPosition.Height := AControl.Height; fStore.Save(mData); end; procedure TControlSaveVisitor.Visit(AControl: TCustomSplitter; const AID: string); var mData: IRBData; mIntegers: THistoryDataIntegers; begin mData := TFinder<THistoryDataIntegers>.GetHistoryData(fStore, AControl.Name, AID, True); mIntegers := mData.UnderObject as THistoryDataIntegers; mIntegers.Integers.Count := 1; if AControl.ResizeAnchor in [akLeft, akRight] then mIntegers.Integers[0] := Round(AControl.GetSplitterPosition * 10000 / AControl.Parent.Width) else mIntegers.Integers[0] := Round(AControl.GetSplitterPosition * 10000 / AControl.Parent.Height); fStore.Save(mData); end; procedure TControlSaveVisitor.Visit(AControl: TCustomCheckBox; const AID: string); var mData: IRBData; mCheckBoxState: THistoryDataCheckBoxState; begin mData := TFinder<THistoryDataCheckBoxState>.GetHistoryData(fStore, AControl.Name, AID, True); mCheckBoxState := mData.UnderObject as THistoryDataCheckBoxState; mCheckBoxState.CheckBoxState := AControl.State; fStore.Save(mData); end; procedure TControlSaveVisitor.Visit(AControl: TSynEditBase; const AID: string); var mData: IRBData; mMemo: THistoryDataMemo; begin mData := TFinder<THistoryDataMemo>.GetHistoryData(fStore, AControl.Name, AID, True); mMemo := mData.UnderObject as THistoryDataMemo; mMemo.Memo := AControl.Lines.Text; fStore.Save(mData); end; procedure TControlSaveVisitor.Visit(AControl: TCustomEdit; const AID: string); var mData: IRBData; mTexts: THistoryDataTexts; begin mData := TFinder<THistoryDataTexts>.GetHistoryData(fStore, AControl.Name, AID, True); mTexts := mData.UnderObject as THistoryDataTexts; mTexts.Texts.Count := 1; mTexts.Texts[0] := AControl.Text; fStore.Save(mData); end; { TControlLoadVisitor } procedure TControlLoadVisitor.Visit(AControl: TControl; const AID: string); begin end; procedure TControlLoadVisitor.Visit(AControl: TCustomComboBox; const AID: string); var mData: IRBData; i: integer; mTexts: THistoryDataTexts; begin mData := TFinder<THistoryDataTexts>.GetHistoryData(fStore, AControl.Name, AID, False); if mData = nil then Exit; mTexts := mData.UnderObject as THistoryDataTexts; AControl.Clear; for i := 0 to mTexts.Texts.Count - 1 do AControl.Items.Insert(0, mTexts.Texts[i]); if AControl.Items.Count > 0 then AControl.ItemIndex := 0; end; procedure TControlLoadVisitor.Visit(AControl: TCustomForm; const AID: string); var mData: IRBData; mPosition: THistoryDataPosition; begin mData := TFinder<THistoryDataPosition>.GetHistoryData(fStore, AControl.Name, AID, False); if mData = nil then Exit; mPosition := mData.UnderObject as THistoryDataPosition; AControl.Left := mPosition.Left; AControl.Top := mPosition.Top; AControl.Width := mPosition.Width; AControl.Height := mPosition.Height; end; procedure TControlLoadVisitor.Visit(AControl: TCustomSplitter; const AID: string); var mData: IRBData; mIntegers: THistoryDataIntegers; begin mData := TFinder<THistoryDataIntegers>.GetHistoryData(fStore, AControl.Name, AID, False); if mData = nil then Exit; mIntegers := mData.UnderObject as THistoryDataIntegers; if mIntegers.Integers.Count > 0 then begin if AControl.ResizeAnchor in [akLeft, akRight] then begin AControl.SetSplitterPosition((mIntegers.Integers[0] * AControl.Parent.Width) DIV 10000); if AControl.GetSplitterPosition < 0 then AControl.SetSplitterPosition(0) else if AControl.GetSplitterPosition > AControl.Parent.Width - 1 then AControl.SetSplitterPosition(AControl.Parent.Width - 1); end else begin AControl.SetSplitterPosition((mIntegers.Integers[0] * AControl.Parent.Height) DIV 10000); if AControl.GetSplitterPosition < 0 then AControl.SetSplitterPosition(0) else if AControl.GetSplitterPosition > AControl.Parent.Height - 1 then AControl.SetSplitterPosition(AControl.Parent.Height - 1); end; end; end; procedure TControlLoadVisitor.Visit(AControl: TCustomCheckBox; const AID: string); var mData: IRBData; mCheckBoxState: THistoryDataCheckBoxState; begin mData := TFinder<THistoryDataCheckBoxState>.GetHistoryData(fStore, AControl.Name, AID, False); if mData = nil then Exit; mCheckBoxState := mData.UnderObject as THistoryDataCheckBoxState; AControl.State := mCheckBoxState.CheckBoxState; end; procedure TControlLoadVisitor.Visit(AControl: TSynEditBase; const AID: string); var mData: IRBData; mMemo: THistoryDataMemo; begin mData := TFinder<THistoryDataMemo>.GetHistoryData(fStore, AControl.Name, AID, False); if mData = nil then Exit; mMemo := mData.UnderObject as THistoryDataMemo; AControl.Lines.Text := mMemo.Memo; end; procedure TControlLoadVisitor.Visit(AControl: TCustomEdit; const AID: string); var mData: IRBData; mTexts: THistoryDataTexts; begin mData := TFinder<THistoryDataTexts>.GetHistoryData(fStore, AControl.Name, AID, False); if mData = nil then Exit; mTexts := mData.UnderObject as THistoryDataTexts; if mTexts.Texts.Count > 0 then AControl.Text := mTexts.Texts[0]; end; { THistoryDataTexts } procedure THistoryDataTexts.AfterConstruction; begin inherited AfterConstruction; fTexts := TPersistManyStrings.Create; end; { THistorySettings } procedure THistorySettings.DispatchVisit(AControl: TControl; const AID: string; AVisitor: TControlVisitor); begin // because of helpers do not support virtual methods, dispatch to visitor methods // need to be done here staticaly if AControl is TCustomForm then AVisitor.Visit(AControl as TCustomForm, AID) else if AControl is TCustomComboBox then AVisitor.Visit(AControl as TCustomComboBox, AID) else if AControl is TCustomSplitter then AVisitor.Visit(AControl as TCustomSplitter, AID) else if AControl is TCustomCheckBox then AVisitor.Visit(AControl as TCustomCheckBox, AID) else if AControl is TSynEditBase then AVisitor.Visit(AControl as TSynEditBase, AID) else if AControl is TCustomEdit then AVisitor.Visit(AControl as TCustomEdit, AID) else AVisitor.Visit(AControl, AID); end; procedure THistorySettings.AcceptVisitor(AControl: TWinControl; AVisitor: TControlVisitor; const AID: string; AInside: Boolean = True); var i: integer; begin DispatchVisit(AControl, AID, AVisitor); if AInside then for i := 0 to AControl.ControlCount - 1 do AcceptVisitor(AControl.Controls[i], AVisitor, AID, AInside); end; procedure THistorySettings.AcceptVisitor(AControl: TControl; AVisitor: TControlVisitor; const AID: string; AInside: Boolean = True); begin if AControl is TWinControl then AcceptVisitor(AControl as TWinControl, AVisitor, AID, AInside) else DispatchVisit(AControl, AID, AVisitor); end; function THistorySettings.GetHistoryData(const AID: string): IRBData; var mList: IPersistRefList; i: integer; begin Result := nil; mList := (fStore as IPersistQuery).SelectClass('THistoryData'); for i := 0 to mList.Count - 1 do begin if mList.Data[i].ItemByName['ID'].AsString = AID then begin Result := mList.Data[i]; Break; end; end; if Result = nil then begin Result := fStore.New('THistoryData'); Result.ItemByName['ID'].AsString := AID; end; end; procedure THistorySettings.Load(const ATopControl: TWinControl; AInside: Boolean = True); begin Load(ATopControl, '',AInside); end; procedure THistorySettings.Load(const ATopControl: TWinControl; const AID: string; AInside: Boolean); var mLoadVisitor: TControlLoadVisitor; begin Store.Open; try mLoadVisitor := TControlLoadVisitor.Create(Store); try AcceptVisitor(ATopControl, mLoadVisitor, AID, AInside); finally mLoadVisitor.Free; end; finally Store.Close; end; end; procedure THistorySettings.Save(const ATopControl: TWinControl; AInside: Boolean = True); begin Save(ATopControl, '', AInside); end; procedure THistorySettings.Save(const ATopControl: TWinControl; const AID: string; AInside: Boolean); var mSaveVisitor: TControlSaveVisitor; begin Store.Open; try mSaveVisitor := TControlSaveVisitor.Create(Store); try AcceptVisitor(ATopControl, mSaveVisitor, AID, AInside); finally mSaveVisitor.Free; end; finally Store.Close; end; end; { TControlVisitor } //function TControlVisitor.GetHistoryData<TDATA>(const AName, AID: string; ACanCreate: Boolean): TDATA; //var // mList: IPersistRefList; // i: integer; //begin // Result := nil; // mList := (fStore as IPersistQuery).SelectClass(''{TDATA.ClassName}); // for i := 0 to mList.Count - 1 do begin // if (mList.Data[i].ItemByName['Name'].AsString = AName) // and (mList.Data[i].ItemByName['ID'].AsString = AID) // then begin // Result := mList.Data[i].UnderObject as TDATA; // Break; // end; // end; // if (Result = nil) and ACanCreate then begin // Result := fStore.New({TDATA.ClassName}'').UnderObject as TDATA; // //Result.Name := AName; // //Result.ID := AID; // end; //end; constructor TControlVisitor.Create(AStore: IPersistStore); begin fStore := AStore; end; class function TControlVisitor.TFinder<TDATA: THistoryData>.GetHistoryData(const AStore: IPersistStore; const AName, AID: string; ACanCreate: Boolean): IRBData; var mList: IPersistRefList; i: integer; begin Result := nil; mList := (AStore as IPersistQuery).SelectClass(TDATA.ClassName); for i := 0 to mList.Count - 1 do begin if (mList.Data[i].ItemByName['Name'].AsString = AName) and (mList.Data[i].ItemByName['ID'].AsString = AID) then begin Result := mList.Data[i]; Break; end; end; if (Result = nil) and ACanCreate then begin Result := AStore.New(TDATA.ClassName); Result.ItemByName['Name'].AsString := AName; Result.ItemByName['ID'].AsString := AID; end; end; end.
unit genlist; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TGenericList } generic TGenericList<_TGenItem> = class(TList) var private protected function GetItems(Index: Integer): _TGenItem; procedure SetItems(Index: Integer; AItem: _TGenItem); public function Add(AItem: _TGenItem): Integer; function Extract(AItem: _TGenItem): _TGenItem; function Remove(AItem: _TGenItem): Integer; function IndexOf(AItem: _TGenItem): Integer; function First: _TGenItem; function Last: _TGenItem; procedure Insert(Index: Integer; AItem: _TGenItem); property Items[Index: Integer]: _TGenItem read GetItems write SetItems; default; procedure FreeAllItems; end; implementation { TGenericList } function TGenericList.GetItems(Index: Integer): _TGenItem; begin Result := _TGenItem(inherited Items[Index]); end; procedure TGenericList.SetItems(Index: Integer; AItem: _TGenItem); begin inherited Items[Index] := AItem; end; function TGenericList.Add(AItem: _TGenItem): Integer; begin Result := inherited Add(AItem); end; function TGenericList.Extract(AItem: _TGenItem): _TGenItem; begin Result := _TGenItem(inherited Extract(AItem)); end; function TGenericList.Remove(AItem: _TGenItem): Integer; begin Result := inherited Remove(AItem); end; function TGenericList.IndexOf(AItem: _TGenItem): Integer; begin Result := inherited IndexOf(AItem); end; function TGenericList.First: _TGenItem; begin Result := _TGenItem(inherited First); end; function TGenericList.Last: _TGenItem; begin Result := _TGenItem(inherited Last); end; procedure TGenericList.Insert(Index: Integer; AItem: _TGenItem); begin inherited Insert(Index, AItem); end; procedure TGenericList.FreeAllItems; var i: integer; begin for i := 0 to count-1 do begin GetItems(i).Free; end; clear; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uMainForm; {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Dialogs, Vcl.Buttons, Winapi.Messages, Vcl.ExtCtrls, Vcl.ComCtrls; {$ELSE} Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Dialogs, Buttons, Messages, ExtCtrls, ComCtrls; {$ENDIF} const CEFBROWSER_CREATED = WM_APP + $100; CEFBROWSER_CHILDDESTROYED = WM_APP + $101; CEFBROWSER_DESTROY = WM_APP + $102; CEFBROWSER_INITIALIZED = WM_APP + $103; type TMainForm = class(TForm) ButtonPnl: TPanel; NewBtn: TSpeedButton; ExitBtn: TSpeedButton; NewContextChk: TCheckBox; procedure FormCreate(Sender: TObject); procedure NewBtnClick(Sender: TObject); procedure ExitBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); private // Variables to control when can we destroy the form safely FCanClose : boolean; // Set to True when all the child forms are closed FClosing : boolean; // Set to True in the CloseQuery event. procedure CreateMDIChild(const Name: string); procedure CloseAllChildForms; function GetChildClosing : boolean; protected procedure ChildDestroyedMsg(var aMessage : TMessage); message CEFBROWSER_CHILDDESTROYED; procedure CEFInitializedMsg(var aMessage : TMessage); message CEFBROWSER_INITIALIZED; public function CloseQuery: Boolean; override; property ChildClosing : boolean read GetChildClosing; end; var MainForm: TMainForm; procedure GlobalCEFApp_OnContextInitialized; implementation {$R *.dfm} uses uChildForm, uCEFApplication; // Destruction steps // ================= // 1. Destroy all child forms // 2. Wait until all the child forms are closed before closing the main form and terminating the application. procedure GlobalCEFApp_OnContextInitialized; begin if (MainForm <> nil) then PostMessage(MainForm.Handle, CEFBROWSER_INITIALIZED, 0, 0); end; procedure TMainForm.CreateMDIChild(const Name: string); var TempChild : TChildForm; begin TempChild := TChildForm.Create(Application); TempChild.Caption := Name; end; procedure TMainForm.CloseAllChildForms; var i : integer; begin i := pred(MDIChildCount); while (i >= 0) do begin if not(TChildForm(MDIChildren[i]).Closing) then PostMessage(MDIChildren[i].Handle, WM_CLOSE, 0, 0); dec(i); end; end; function TMainForm.GetChildClosing : boolean; var i : integer; begin Result := false; i := pred(MDIChildCount); while (i >= 0) do if TChildForm(MDIChildren[i]).Closing then begin Result := True; exit; end else dec(i); end; procedure TMainForm.FormCreate(Sender: TObject); begin FCanClose := False; FClosing := False; end; procedure TMainForm.NewBtnClick(Sender: TObject); begin CreateMDIChild('ChildForm' + IntToStr(MDIChildCount + 1)); end; procedure TMainForm.ExitBtnClick(Sender: TObject); begin ButtonPnl.Enabled := False; if (MDIChildCount = 0) then Close else CloseAllChildForms; end; procedure TMainForm.ChildDestroyedMsg(var aMessage : TMessage); begin // If there are no more child forms we can destroy the main form if (MDIChildCount = 0) then begin ButtonPnl.Enabled := False; FCanClose := True; PostMessage(Handle, WM_CLOSE, 0, 0); end; end; procedure TMainForm.CEFInitializedMsg(var aMessage : TMessage); begin Caption := 'MDI Browser'; ButtonPnl.Enabled := True; cursor := crDefault; end; procedure TMainForm.FormShow(Sender: TObject); begin if (GlobalCEFApp <> nil) and GlobalCEFApp.GlobalContextInitialized then begin Caption := 'MDI Browser'; ButtonPnl.Enabled := True; cursor := crDefault; end; end; function TMainForm.CloseQuery: Boolean; begin if FClosing or ChildClosing then Result := FCanClose else begin FClosing := True; if (MDIChildCount = 0) then Result := True else begin Result := False; CloseAllChildForms; end; end; end; end.
unit UfrTypes; {$ifdef FPC} {$mode DELPHI} {$endif} interface uses Windows; const //stPayNotEqualToPrice = 'Payment is not equal to the goods price'; errOk = 0; // без ошибок { универсальные ошибки инициализации 1-99 } errPortAlreadyUsed = 1; // порт уже используется errIllegalOS = 2; // не та OS errProtocolNotSupported = 3; // запрашиваемый протокол не поддерживается errFunctionNotSupported = 4; // функция драйвера не поддерживается данным фискальником errInvalidHandle = 5; // Недействительный дескриптор (handle) { универсальные ошибки низкого уровня 100-199 } errLowNotReady = 101; // устройство не готово принять команду, таймаут ожидания errLowSendError = 102; // устройство отвечает ошибкой приёма команды errLowAnswerTimeout = 103; // устройство не отвечает на команду errLowInactiveOnExec = 104; // устройство не отвечает на проверку работоспособности после отправки команды errLowBadAnswer = 105; // устройство отвечает мусором (и невозможно повторить или повтор не помог) { логические ошибки 200-299 } errLogicError = 200; // логическая ошибка прочего типа, см. статус: LogicError, LogicErrorText errLogic24hour = 201; // смена превысила максимальную продолжительность errLogicPrinterNotReady = 202; errLogicPaperOut = 203; // закончилась бумага во время печати. //При запросе статуса не надо возвращать эту ошибку. { Ошибки во входных данных, обнаруженные до отправки данных в ФР 300-399 } errAssertItemsPaysDifferent = 301; // В чеке не совпадают суммы по товарам и платежам errAssertInvalidXMLInitializationParams = 302; // ошибки в XML параметрах UFRInit errAssertInvalidXMLParams = 303; // ошибки в XML параметрах всех функций, кроме UFRInit errAssertInsufficientBufferSize = 304; // недостаточный размер буфера для получения данных { UFRGetOptions } FoText = $0001; // ФР поддерживает отдельную нефискальную печать (не в чеке) foZeroReceipt = $0002; // ФР поддерживает печать нулевого чека(с нулевой стоимостью) foDeleteReceipt = $0004; // ФР поддерживает удаление чека foZReport = $0008; // ФР поддерживает Z отчёт foMoneyInOut = $0010; // ФР поддерживает внесения-выдачи foXReport = $0020; // ФР поддерживает X отчёт foSpecialReport = $0040; // ФР поддерживает специальные отчёты foZeroSale = $0080; // ФР поддерживает продажи с нулевой ценой foProgram = $0100; // ФР поддерживает программирование foFullLastShift = $0200; // ФР поддерживает распечатку последней смены foAllMoneyOut = $0400; // ФР поддерживает изъятие всех денег foTextInReceipt = $0800; // ФР поддерживает нефискальную печать внутри чека (внутри <Header>) foBarCodeInNotFisc = $1000; // ФР поддерживает печать штрих-кода в нефискальной части чека foZClearMoney = $2000; // Z отчёт автоматически очищает остаток денег в кассе foCheckCopy = $4000; // фискальный документ - копия чека (пока только в Латвии) foTextInLine = $8000; // ФР поддерживает нефискальную печать внутри линии чека (внутри <Item> или <Payment> или <Discount>) foDepartments = $00010000; // ФР поддерживает отделы по блюдам foOnlyFixed = $00020000; // работа только с заранее запрограммированными блюдами (RK7 в этом случае использует блюда "итого" по отделам с кодами отделов и распечатывает "суммарные" чеки с такими блюдами) foTextOpenShift = $00040000; // признак, что нефискальная печать открывает фискальную смену foDrawerOpen = $00080000; // Может открывать ящик foDrawerState = $00100000; // Может возвращать состояние ящика foCustomerDisplay = $00200000; // Поддерживает вывод на дисплей покупателя foCalcChange = $00800000; // Поддерживает вычисление сдачи foZWhenClosedShift = $01000000; // Поддерживает печать Z-отчета при закрытой смене foAbsDiscountSum = $02000000; // ФР поддерживает абсолютные суммовые скидки/наценки foFiscInvoice = $04000000; // Поддерживает печать фискального чека как счет-фактуру foCashRegValue = $08000000; // ФР поддерживает возврат значения регистра кассовой наличности foFixedNames = $10000000; // ФР требует неизменности имён позиций в течении дня { значения маски FieldsNeeded для UFRGetStatus } fnNotCancelReceipt = $0001; // не отменять автоматически открытый чек fnBusy = $0002; // требуется заполнить Busy и NotReady fnUnfiscalPrint = $0004; // требуется заполнить CanNotPrintUnfiscal fnPrintQueue = $0008; // Длина очереди печати (для нефискальной печати) fnDrawerOpened = $0010; // Признак открытого ящика fnShiftState = $0100; // статус фискальной смены fnSerialNumber = $0200; // строка-идентификатор фискальника, кроме серийного номера можно прописать закодированную модель фискальника fnLastShiftNum = $0400; // номер последней закрытой(!) фискальной смены, если первая смена, то 0 fnLastDocNum = $0800; // последний номер документа (включая внесения-выдачи) fnLastReceiptNum = $1000; // последний номер фискального чека, может совпадать с номером документа fnSaledValue = $2000; // сумма продаж или за смену или глобально. Использовать только для проверки изменилась/не изменилась (прошёл или нет последний чек). //fnLogicError = $4000; // Запрос последней логической ошибки. fnCashRegValue = $8000; // Запрос значения регистра кассовой наличности в ФР { список функций Callback процедуры } cpfDialog = 1; // вызов диалога, структура tDialogInfo, см. Вызов диалога на станции cpfProgress = 2; // индикация прогресса, структура tProgressInfo, см. Иллюстрация прогресса cpfGetStringDialog = 3; // диалог запроса строки, структура tGetStringInfo, см. Вызов диалога запроса строки cpfRegisterSpecMenu = 4; // зарегистрировать специальное меню, структура tDriverMenuInfo см.Дополнительные функции (спец. меню, общее с другими драйверам) cpfLog = 5; // логирование { для логов } letError = 1; // Ошибка. letInitializing = 2; // В начале инициализации. Data - строка в кодировке UTF8 letInitialized = 3; // При успешной инициализации. Data - строка в кодировке UTF8 letFiscCommand = 4; // Текстовое и бинарное представление фискальной команды (в тексте номер, возможно, описание, возможно, параметр, в бинарном представлении пакет данных для отправки фискальнику). letFiscCommandComplete = 5; // Текстовое и бинарное представление ответа фискальника. В тексте может быть код ошибки, время выполнения фискальной команды, возможно, расшифровка содержательного ответа фискальника, например, на запрос статуса. В бинарном представлении пакет данных, полученный от фискальника. letTextCommand = 6; // Текстовое и бинарное представление команды вывода текста (нефискальная печать, вывод на дисплей покупателя), в бинарном представлении пакет данных для отправки фискальнику. letTextCommandComplete = 7; // Текстовое и бинарное представление ответа фискальника. В тексте может быть код ошибки, время выполнения фискальной команды, возможно, расшифровка содержательного ответа фискальника, например, статус печатающего стройства. В бинарном представлении пакет данных, полученный от фискальника. letBinInput = 8; // Бинарный системный вход (не описанный в letFiscCommandComplete, letTextCommandComplete). Например, подтверждение фискальником о получении пакета данных. letBinOut = 9; // Бинарный системный вывод (не описанный в letFiscCommand, letTextCommand). Например, подтверждение о получении пакета данных или подготовка фискальника к отправке команды. letOther = 10; // все остальное type TInterfaceCallbackProc = procedure(ModuleHandle: THandle; {хэнд модуля, который вызывает процедуру} Number: LongInt; {номер, который передали при регистрации} FuncID, ProtocolVersion: LongInt; FuncParams: Pointer {указатель на параметр, возможно структура, часть полей которой могут меняться(возврат)}); stdcall; TPropCallbackProc = procedure(XMLTag: PChar; // тип элемента, совпадает с тэгом, Для "Receipt"/"Receipt.Order"/"Receipt.Deletion"/"Receipt.Operator" идентификаторы не // нужны, для "Item""/"Discount"/"Pay" нужны (аттрибут Id) Identifier: PChar; // Идентификатор элемента PropName: PChar; // Имя свойства var PropValue: OpenString); stdcall; TShiftState = (ssShiftClosed, ssShiftOpened, ssShiftOpened24hoursExceeded); TUFRStatus = packed record Size: LongInt; // SizeOf(TUFRStatus) NotReady: Boolean; // Не готов Busy: Boolean; // Работает [занят] CannotPrintUnfiscal: Boolean; // Невозможно выполнить нефискальную печать QueueSize: LongInt; // Размер очереди для нефискальной печати // NOTE. По возможности, возвращать сумму // длин очередей драйвера и устройства DrawerOpened: Boolean; // Ящик открыт ShiftState: TShiftState; // Фискальная смена закрыта/открыта/открыта и прошло 24 часа SerialNum: String[35]; // Уникальный идентификатор ФР (с моделью) LastShiftNum: Word; // Последний номер Z отчёта // (номер закрытой смены) LastDocNum: LongInt; // Последний номер документа // (в том числе инкассации и т.п.) LastReceiptNum: LongInt; // Последний номер чека SaledValue: Int64; // Сумма продаж за смену, в копейках CashRegValue: Int64; // Сумма в кассе, в копейках end; TFRLog = Packed Record Size: LongInt; // sizeof(tFRLog) LogEventType: LongInt; // одна из констант, описанных ниже TextData: PChar; // строка в кодировке UTF8, заканчивающаяся 0 BinData: Pointer; BinDataSize: LongInt; end; TUFRLogicError = packed record Size: LongInt; // SizeOf(TUFRLogicError) LogicError: LongInt; // Внутренний код логической ошибки ФР LogicErrorText: ShortString; // Описание логической ошибки ФР (если есть) end; type TUFRMaxProtocolSupported = function(): Integer; stdcall; TUFRInit = function (ANumber: Integer; AXMLParams: PChar; AInterfaceCallback: TInterfaceCallbackProc; APropCallback: TPropCallbackProc): Integer; stdcall; TUFRDone = procedure (ANumber: Integer); stdcall; TUFRGetOptions = function (ANumber: Integer; var AOptions: Int64; var ADriverName: OpenString; var AVersionInfo: OpenString; var ADriverState: OpenString): Integer; stdcall; TUFRGetStatus = function (ANumber: Integer; var AStatus: TUFRStatus; AFieldsNeeded: Cardinal): Integer; stdcall; TUFRUnfiscalPrint = function (ANumber: Integer; AXMLBuffer: PChar; AFlags: Integer): Integer; stdcall; TUFRFiscalDocument = function (ANumber: Integer; AXMLDoc: PChar; var AStatus: TUFRStatus; var AFieldsFilled: Cardinal): Integer; stdcall; TUFRGetZReportData = function (ANumber: Integer; AXMLData: PChar; var AXMLDataSize: Integer): Integer; stdcall; TUFROpenDrawer = function (ANumber: Integer; ADrawerNum: Integer): Integer; stdcall; TUFRCustomerDisplay = function (ANumber: Integer; AXMLBuffer: PChar; AFlags: Integer): Integer; stdcall; TUFRProgram = function (ANumber: Integer; AXMLDoc: PChar): Integer; stdcall; TUFRGetLastLogicError = procedure (ANumber: Integer; var ALogicError: TUFRLogicError); stdcall; //псевдопроцедура, её не надо вызывать, достаточно написать вызов где то в невыполняемом месте //в итоге проверятся все типы procedure CheckFiscRegFuncTypes( fUFRMaxProtocolSupported: TUFRMaxProtocolSupported; fUFRInit: TUFRInit; fUFRDone: TUFRDone; fUFRGetOptions: TUFRGetOptions; fUFRGetStatus: TUFRGetStatus; fUFRUnfiscalPrint: TUFRUnfiscalPrint; fUFRFiscalDocument: TUFRFiscalDocument; fUFRGetZReportData: TUFRGetZReportData; fUFROpenDrawer: TUFROpenDrawer; fUFRCustomerDisplay: TUFRCustomerDisplay; fUFRProgram: TUFRProgram; fUFRGetLastLogicError: TUFRGetLastLogicError ); implementation procedure CheckFiscRegFuncTypes(); begin end; end.
unit values; {$MODE Delphi} interface uses Classes, SysUtils; type v_type=(vt_str,vt_int,vt_float,vt_flag,vt_ptr,vt_vect,vt_frame,vt_unk); tcog_type=(ct_unk,ct_ai,ct_cog,ct_key,ct_mat,ct_msg, ct_3do,ct_sec,ct_wav,ct_srf,ct_tpl,ct_thg, ct_int,ct_float,ct_vect); TAdjType=(at_unk,at_mat,at_cog,at_snd,at_pup,at_spr,at_par,at_3do,at_ai,at_tpl,at_frame); {ai cog flex float int keyframe material message model sector sound surface template thing vector} TValue=class Name:string; vtype:v_type; int:longint; float:double; s:string; Function AsString:String; Function Val(const s:string):boolean; Procedure Assign(v:TValue); end; TValues=class(TList) Function GetItem(n:integer):TValue; Procedure SetItem(n:integer;v:TValue); Function IndexOfName(const name:string):integer; Property Items[n:integer]:TValue read GetItem write SetItem; default; end; TCOGValue=class(TValue) cog_type:TCog_Type; local:boolean; desc:String; mask:longint; obj:TObject; Function AsString:String; Function AsJedString:String; Procedure Assign(cv:TCogValue); Function Val(const s:string):boolean; Function JedVal(const s:string):boolean; Procedure Resolve; end; TCOGValues=class(TValues) Function GetItem(n:integer):TCOGValue; Procedure SetItem(n:integer;v:TCOGValue); Property Items[n:integer]:TCOGValue read GetItem write SetItem; default; end; TTplValue=class(tvalue) atype:TAdjType; Procedure Assign(v:TTplValue); Procedure GetFrame(var x,y,z,pch,yaw,rol:double); Procedure SetFrame(x,y,z,pch,yaw,rol:double); end; TTPLValues=class(TValues) Function GetItem(n:integer):TTPLValue; Procedure SetItem(n:integer;v:TTPLValue); Property Items[n:integer]:TTPLValue read GetItem write SetItem; default; end; Function GetCogType(const stype:string):TCog_type; Function GetCogVType(const stype:string):v_type; Function GetVTypeFromCOGType(vtype:TCOG_Type):v_type; Function GetTplVType(const name:string):v_type; Function GetTplType(const name:string):TAdjtype; Procedure S2TPLVal(const s:string;v:TTPLValue); Procedure S2CogVal(const s:string;v:TCOGValue); Function GetCOGVal(const st:string;v:TCogValue):boolean; Function GetJedVal(const st:string;v:TCogValue):boolean; Function GetCogTypeName(ct:TCOG_type):String; Procedure InitValues; implementation uses Misc_utils, J_level; var CogTypes,CogVtypes,tplNames,TplVtypes:TStringList; Function GetCogTypeName(ct:TCOG_type):String; var n:integer; begin n:=CogTypes.IndexOfObject(TObject(ct)); if n=-1 then result:='unknown' else Result:=CogTypes[n]; end; Function GetCogType(const stype:string):TCog_type; var n:integer; begin n:=CogTypes.IndexOf(stype); if n=-1 then Result:=ct_unk else Result:=TCog_type(CogTypes.Objects[n]); end; Function GetVTypeFromCOGType(vtype:TCOG_Type):v_type; begin case vtype of ct_unk: result:=vt_unk; ct_ai,ct_cog,ct_key,ct_mat,ct_msg, ct_3do,ct_wav,ct_tpl: result:=vt_str; ct_sec,ct_srf,ct_thg: result:=vt_ptr; ct_int: result:=vt_int; ct_float: result:=vt_float; ct_vect: result:=vt_vect; else result:=vt_unk; end; end; Function GetCogVType(const stype:string):v_type; var n:integer; begin n:=CogVTypes.IndexOf(stype); if n=-1 then Result:=vt_unk else Result:=v_type(CogVTypes.Objects[n]); end; Function GetTplVType(const name:string):v_type; var n:integer; begin n:=TplVTypes.IndexOf(name); if n=-1 then Result:=vt_str else Result:=v_type(TplVTypes.Objects[n]); end; Function GetTplType(const name:string):TAdjtype; var n:integer; begin n:=tplNames.IndexOf(name); if n=-1 then Result:=at_unk else Result:=TAdjtype(TplNames.Objects[n]); end; Function GetCOGVal(const st:string;v:TCogValue):boolean; var w:string; p,pe:integer; begin Result:=false; p:=GetWord(st,1,w); if w='' then exit; v.vtype:=GetCogVType(w); v.cog_type:=GetCogType(w); p:=GetWord(st,p,w); pe:=Pos('=',w); if pe=0 then v.name:=w else begin v.name:=Copy(w,1,pe-1); v.Val(Copy(w,pe+1,length(w))); end; While p<Length(st) do begin p:=GetWord(st,p,w); if w='' then continue; if CompareText(w,'local')=0 then v.local:=true; end; end; Function GetJedVal(const st:string;v:TCogValue):boolean; var pe,ps:integer; w:string; begin ps:=pos(':',st); pe:=Pos('=',st); v.name:=Copy(st,1,ps-1); w:=Copy(st,ps+1,pe-ps-1); v.vtype:=GetCogVType(w); v.cog_type:=GetCogType(w); v.Val(Copy(st,pe+1,length(st))); end; Function TCOGValue.AsJedString:String; begin case cog_type of ct_srf: begin if obj=nil then begin Result:='-1'; exit; end; With TJKSUrface(obj) do Result:=Format('%d %d',[Sector.num,num]); exit; end; end; Result:=AsString; end; Function TCOGValue.AsString:String; begin case cog_type of ct_srf,ct_sec,ct_thg: if obj=nil then begin Result:='-1'; exit; end; end; case cog_type of ct_sec: Result:=IntToStr(TJKSector(obj).num); ct_srf: With TJKSurface(obj) do Result:=IntToStr(Sector.Level.GetGlobalSFN(Sector.Num,Sector.Surfaces.IndexOf(obj))); ct_thg: Result:=IntToStr(TJKThing(obj).num); else Result:=Inherited AsString; end; end; Procedure TCOGValue.Assign(cv:TCogValue); begin Name:=cv.Name; cog_type:=cv.cog_type; vtype:=cv.vtype; desc:=cv.desc; local:=cv.local; end; Procedure TCOGValue.Resolve; begin case cog_type of ct_sec: obj:=Level.GetSectorN(int); ct_srf: obj:=Level.GetSurfaceN(int); ct_thg: obj:=Level.GetThingN(int); else exit; end; if (obj=nil) and (int<>-1) then PanMessageFmt(mt_warning,'Cog parameter resolution failed: no %s num: %d', [GetCogTypeName(cog_type),int]); end; Function TCOGValue.Val(const s:string):boolean; var d:longint; begin Case cog_type of ct_sec,ct_srf,ct_thg: Result:=ValDword(s,Int); else Result:=Inherited Val(s); end; end; Function TCOGValue.JedVal(const s:string):boolean; var i,p:integer;w:string; begin Result:=false; case cog_type of ct_srf: begin p:=GetWord(s,1,w); Result:=ValInt(w,i); if not result then exit; if i<0 then begin obj:=nil; exit; end; GetWord(s,p,w); Result:=ValInt(w,p); if not result then exit; try obj:=Level.Sectors[i].Surfaces[p]; except On Exception do Result:=false; end; end; ct_sec,ct_thg: begin Result:=ValInt(s,I); if not Result then exit; if i<0 then begin obj:=nil; exit; end; case cog_type of ct_sec: begin if i<Level.Sectors.Count then obj:=Level.Sectors[i] else Result:=false; end; ct_thg: begin if i<Level.Things.Count then obj:=Level.Things[i] else Result:=false; end; end; end; else Result:=Val(s); end; end; Procedure TTplValue.Assign(v:TTplValue); begin Inherited Assign(v); atype:=v.atype; end; Procedure TTplValue.GetFrame(var x,y,z,pch,yaw,rol:double); var vs:string; i:integer; begin x:=0; y:=0; z:=0; pch:=0; yaw:=0; rol:=0; vs:=s; for i:=1 to length(vs) do if vs[i] in ['/',':','(',')'] then vs[i]:=' '; SScanf(vs,'%f %f %f %f %f %f',[@x,@y,@z,@pch,@yaw,@rol]); end; Procedure TTplValue.SetFrame(x,y,z,pch,yaw,rol:double); begin if CompareText(name,'frame')<>0 then exit; s:=Sprintf('(%.6f/%.6f/%.6f:%.6f/%.6f/%.6f)', [x,y,z,pch,yaw,rol]); end; Function TValue.AsString:String; begin case vtype of vt_str,vt_unk:result:=s; vt_vect,vt_frame: Result:=s; vt_int,vt_ptr:Result:=IntToStr(int); vt_float: Result:=FloatToStr(float); vt_flag: Result:=Format('0x%x',[int]); else Result:=''; end; end; Function TValue.Val(const s:string):boolean; begin Result:=true; case vtype of vt_str,vt_unk:self.s:=s; vt_vect,vt_frame: self.s:=s; vt_int,vt_ptr:Result:=ValDword(s,int); vt_float: Result:=ValDouble(s,float); vt_flag: Result:=ValHex(s,int); else Result:=false; end; end; Procedure TValue.Assign; begin Name:=v.Name; vtype:=v.vtype; int:=v.int; float:=v.float; s:=v.s; end; Function TValues.GetItem(n:integer):TValue; begin if (n<0) or (n>=count) then raise EListError.CreateFmt('Value Index is out of bounds: %d',[n]); Result:=TValue(List[n]); end; Procedure TValues.SetItem(n:integer;v:TValue); begin if (n<0) or (n>=count) then raise EListError.CreateFmt('Value Index is out of bounds: %d',[n]); List[n]:=v; end; Function TValues.IndexOfName(const name:string):integer; var i:integer; begin Result:=-1; for i:=0 to count-1 do begin if compareText(name,Items[i].Name)<>0 then continue; result:=i; break; end; end; Function TCOGValues.GetItem(n:integer):TCOGValue; begin if (n<0) or (n>=count) then raise EListError.CreateFmt('Value Index is out of bounds: %d',[n]); Result:=TCOGValue(List[n]); end; Procedure TCOGValues.SetItem(n:integer;v:TCOGValue); begin if (n<0) or (n>=count) then raise EListError.CreateFmt('Value Index is out of bounds: %d',[n]); List[n]:=v; end; Function TTPLValues.GetItem(n:integer):TTPLValue; begin if (n<0) or (n>=count) then raise EListError.CreateFmt('Value Index is out of bounds: %d',[n]); Result:=TTPLValue(List[n]); end; Procedure TTPLValues.SetItem(n:integer;v:TTPLValue); begin if (n<0) or (n>=count) then raise EListError.CreateFmt('Value Index is out of bounds: %d',[n]); List[n]:=v; end; Procedure S2TPLVal(const s:string;v:TTPLValue); var p:integer; begin p:=Pos('=',s); v.Name:=Copy(s,1,p-1); v.vtype:=GetTPLVtype(v.name); v.atype:=GetTPLtype(v.name); v.s:=Copy(s,p+1,length(s)); end; Procedure S2CogVal(const s:string;v:TCOGValue); var p:integer; begin p:=Pos('=',s); v.Name:=Copy(s,1,p-1); v.vtype:=vt_str; v.s:=Copy(s,p+1,length(s)); end; Procedure InitValues; begin CogTypes:=TStringList.Create; CogTypes.Sorted:=true; With CogTypes Do begin AddObject('ai',TObject(ct_ai)); AddObject('cog',TObject(ct_cog)); AddObject('keyframe',TObject(ct_key)); AddObject('material',TObject(ct_mat)); AddObject('message',TObject(ct_msg)); AddObject('model',TObject(ct_3do)); AddObject('sector',TObject(ct_sec)); AddObject('sound',TObject(ct_wav)); AddObject('surface',TObject(ct_srf)); AddObject('template',TObject(ct_tpl)); AddObject('thing',TObject(ct_thg)); AddObject('int',Tobject(ct_int)); AddObject('float',Tobject(ct_float)); AddObject('flex',Tobject(ct_float)); AddObject('vector',Tobject(ct_vect)); end; CogVTypes:=TStringList.Create; CogVTypes.Sorted:=true; With CogVTypes do begin AddObject('flex',TObject(vt_float)); AddObject('float',TObject(vt_float)); AddObject('vector',TObject(vt_vect)); AddObject('int',TObject(vt_int)); AddObject('ai',TObject(vt_str)); AddObject('cog',TObject(vt_int)); AddObject('keyframe',TObject(vt_str)); AddObject('material',TObject(vt_str)); AddObject('message',TObject(vt_str)); AddObject('model',TObject(vt_str)); AddObject('sector',TObject(vt_ptr)); AddObject('sound',TObject(vt_str)); AddObject('surface',TObject(vt_ptr)); AddObject('template',TObject(vt_str)); AddObject('thing',TObject(vt_ptr)); end; tplNames:=TStringList.Create; tplNames.Sorted:=true; With tplNames do begin AddObject('material',TObject(at_mat)); AddObject('cog',TObject(at_cog)); AddObject('soundclass',TObject(at_snd)); AddObject('puppet',TObject(at_pup)); AddObject('sprite',TObject(at_spr)); AddObject('particle',TObject(at_par)); AddObject('model3d',TObject(at_3do)); AddObject('aiclass',TObject(at_ai)); AddObject('creatething',TObject(at_tpl)); AddObject('explode',TObject(at_tpl)); AddObject('fleshhit',TObject(at_tpl)); AddObject('weapon',TObject(at_tpl)); AddObject('weapon2',TObject(at_tpl)); AddObject('debris',TObject(at_tpl)); AddObject('trailthing',TObject(at_tpl)); AddObject('frame',TObject(at_frame)); end; TplVtypes:=TStringList.Create; TplVtypes.Sorted:=true; With TplVtypes do begin AddObject('frame',TObject(vt_frame)); end; end; Initialization Finalization begin CogTypes.Free; CogVTypes.Free; TplNames.Free; end; end.
unit NSqlExceptions; {$I NSql.Inc} interface uses {$IFDEF NSQL_XE2UP} System.SysUtils; {$ELSE} SysUtils; {$ENDIF} type ENativeSqlException = class(Exception) private FMsg: UnicodeString; FExtendedInfo: UnicodeString; FErrorAtClass: UnicodeString; FIsNative: Boolean; public constructor Create(const AMsg: UnicodeString; Sender: TObject; const AExtendedInfo: UnicodeString; AIsNative: Boolean); virtual; property Msg: UnicodeString read FMsg; property ExtendedInfo: UnicodeString read FExtendedInfo; property ErrorAtClass: UnicodeString read FErrorAtClass; property IsNative: Boolean read FIsNative; end; ENativeSqlExceptionClass = class of ENativeSqlException; ENSConnectError = class(ENativeSqlException); ENSTransactionError = class(ENativeSqlException); ENSTransactionStartError = class(ENSTransactionError); ENSTransactionCommitError = class(ENSTransactionError); ENSTransactionRollbackError = class(ENSTransactionError); // ENSTransactionNotActive = class(ENSTransactionError); ENSTransactionIsDead = class(ENSTransactionError); ENSNotInTransaction = class(ENSTransactionError); ENSSqlPreParseError = class(ENativeSqlException); // ENSSqlPreParseErrorUnterminatedString = class(ENSSqlPreParseError); ENSInvalidParamCount = class(ENativeSqlException); ENSDuplicateParameterNameInSql = class(ENativeSqlException); ENSQueryError = class(ENativeSqlException); implementation { ENativeSqlException } constructor ENativeSqlException.Create(const AMsg: UnicodeString; Sender: TObject; const AExtendedInfo: UnicodeString; AIsNative: Boolean); var Msg: UnicodeString; begin FMsg := AMsg; FExtendedInfo := AExtendedInfo; FIsNative := AIsNative; if Assigned(Sender) then FErrorAtClass := Sender.ClassName; Msg := 'NativeSql Error'; if FIsNative then Msg := Msg + '[from DBEngine]'; if FErrorAtClass <> '' then Msg := Msg + ' (in ' + FErrorAtClass + ' class)'; Msg := Msg + ':' + sLineBreak + AMsg; if FExtendedInfo <> '' then Msg := Msg + sLineBreak + 'Extended Info:' + sLineBreak + AExtendedInfo; inherited Create(Msg); end; end.
unit uModTransferBarang; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModApp, uModGudang, uModBarang, uModUnit, uModSatuan, Datasnap.DBClient, System.Generics.Collections; type TModTransferBarangItem = class; TModTransferBarang = class(TModApp) private FTB_COLIE: Double; FTB_GUDANG_ASAL: TModGudang; FTB_GUDANG_TUJUAN: TModGudang; FTB_Keterangan: string; FTB_NO: string; FTB_REFERENSI: string; FTB_TANGGAL: TDateTime; FTB_TransferBarangItems: TOBjectList<TModTransferBarangItem>; FTB_Unit: TModUnit; function GetTB_TransferBarangItems: TOBjectList<TModTransferBarangItem>; public property TB_TransferBarangItems: TOBjectList<TModTransferBarangItem> read GetTB_TransferBarangItems write FTB_TransferBarangItems; published property TB_COLIE: Double read FTB_COLIE write FTB_COLIE; property TB_GUDANG_ASAL: TModGudang read FTB_GUDANG_ASAL write FTB_GUDANG_ASAL; property TB_GUDANG_TUJUAN: TModGudang read FTB_GUDANG_TUJUAN write FTB_GUDANG_TUJUAN; [AttributeOfSize('120')] property TB_Keterangan: string read FTB_Keterangan write FTB_Keterangan; [AttributeOfCode] property TB_NO: string read FTB_NO write FTB_NO; [AttributeOfSize('60')] property TB_REFERENSI: string read FTB_REFERENSI write FTB_REFERENSI; property TB_TANGGAL: TDATEtime read FTB_TANGGAL write FTB_TANGGAL; property TB_Unit: TModUnit read FTB_Unit write FTB_Unit; end; TModTransferBarangItem = class(TModApp) private FTBI_Barang: TModBarang; FTBI_Qty: Double; FTBI_TransferBarang: TModTransferBarang; FTBI_UOM: TModSatuan; published [AttributeofForeign] property TBI_Barang: TModBarang read FTBI_Barang write FTBI_Barang; property TBI_Qty: Double read FTBI_Qty write FTBI_Qty; [AttributeOfHeader] property TBI_TransferBarang: TModTransferBarang read FTBI_TransferBarang write FTBI_TransferBarang; [AttributeofForeign] property TBI_UOM: TModSatuan read FTBI_UOM write FTBI_UOM; end; implementation function TModTransferBarang.GetTB_TransferBarangItems: TOBjectList<TModTransferBarangItem>; begin if FTB_TransferBarangItems = nil then FTB_TransferBarangItems := TObjectList<TModTransferBarangItem>.Create(); Result := FTB_TransferBarangItems; end; initialization TModTransferBarang.RegisterRTTI; end.
unit uBoleto.Intf; interface type IContaBancaria = interface ['{1529D3A2-10E4-44DD-9259-DE0C9484B885}'] function GetCodigoBanco: UInt16; procedure SetCodigoBanco(const pCodigoBanco: UInt16); property CodigoBanco: UInt16 read GetCodigoBanco write SetCodigoBanco; end; ICedente = interface ['{BBC3AAEB-0C49-4787-8917-245FD37BD073}'] function GetNome: string; procedure SetNome(const pNome: string); function GetContaBancaria: IContaBancaria; property Nome: string read GetNome write SetNome; property ContaBancaria: IContaBancaria read GetContaBancaria; end; ISacado = interface ['{B207EDD2-F9C3-4DC6-B16E-ECD0CCFE43B8}'] function GetNome: string; procedure SetNome(const pNome: string); property Nome: string read GetNome write SetNome; end; IBoleto = interface ['{E6B224CD-E794-4995-835E-982F680DF5F6}'] function GetCedente: ICedente; function GetSacado: ISacado; property Cedente: ICedente read GetCedente; property Sacado: ISacado read GetSacado; end; implementation end.
unit uniteConsigneur; interface uses SysUtils; const //journalSucces est fichier texte conservant le nom de fichier acces.log. journalSucces= 'acces.log'; //journalErreur est fichier texte conservant le nom de fichier erreurs.log. journalErreur= 'erreurs.log'; type //Consigneur des messages ou des erreurs Consigneur = class private //repertoireJournaux représentant le nom du répertoire dans lequel les journaux sont conservés. repertoireJournaux: String; fichierAcces: TextFile; fichierErreur: TextFile; procedure ouvertureFichier( nomFichier: String; var fichier: TextFile ); public //creer l'objet consigneur // //@param unRepertoireJournaux où se trouvent les fichiers journaux. Il est de type string. // constructor create( unRepertoireJournaux:String ); virtual; //La procedure consigner reçoit un message à consigner et consigne un message de la forme : date [origine]: messageConsigner. // //@param origine la partie du serveur d'où origine la consignation de type string //@param messageConsigne le message de l'erreur à consigner de type string. // procedure consigner( origine: String; messageConsigne: String ); virtual; //La procédure consignerErreur reçoit un message à consigner et consigne un message de la forme : date[ERREUR – origine]: messageConsigner. // //@param origine est la partie du serveur d'où origine la consignation de type string //@param messageConsigne est le message de l'erreur à consigner de type string // procedure consignerErreur( origine: String; messageConsigne: String ); virtual; //La fonction getRepertoireJournaux sert à prendre repertoireJournaux et le retourne ensuite. // //@return le répertoire où il y a les journaux sous la forme d'un string. // function getRepertoireJournaux:String; //Le destructeur ferme les fichiers qui ont été ouverts. destructor destroy; end; implementation constructor Consigneur.create( unRepertoireJournaux: String ); begin repertoireJournaux:= unRepertoireJournaux; ouvertureFichier( journalSucces, fichierAcces ); ouvertureFichier( journalErreur, fichierErreur ); end; procedure Consigneur.ouvertureFichier( nomFichier: String; var fichier: TextFile ); begin assignFile( fichier, repertoireJournaux + nomFichier ); if FileExists( repertoireJournaux + nomFichier ) then begin try append( fichier ); except on e:Exception do begin raise exception.create( 'Incapable d''ouvrir le fichier ' + nomFichier + ' du répertoire ' + repertoireJournaux + '. Veuillez vérifier le chemin d''accès et les permissions.' ); end; end; end else begin try rewrite( fichier ); except on e:Exception do raise exception.create( 'Incapable de créer le fichier ' + nomFichier + ' du répertoire ' + repertoireJournaux + '.' ); end; end; end; procedure Consigneur.consigner( origine: String; messageConsigne: String ); var uneLigne: String; nomFichier: String; begin try uneLigne:=formatDateTime( 'YYYY-MM-DD HH:MM:SS', now ) + ' [' + origine + '] ' + messageConsigne; writeln( fichierAcces, uneLigne ); flush(fichierAcces); except on e: Exception do begin raise exception.create( 'Incapable d''ecrire dans le fichier ' + nomFichier + ' du répertoire ' + repertoireJournaux ); exit; end; end; end; procedure Consigneur.consignerErreur( origine:String;messageConsigne:String ); var uneLigne: String; nomFichier: String; begin try uneLigne:=formatDateTime('YYYY-MM-DD HH:MM:SS',now) + ' [ERREUR - ' + origine + '] ' + messageConsigne; writeln( fichierErreur, uneLigne ); flush(fichierErreur); except on e: Exception do begin raise exception.Create('Incapable d''ecrire dans le fichier ' + nomFichier + ' du répertoire ' + repertoireJournaux ); exit; end; end; end; function Consigneur.getRepertoireJournaux:String; begin result:=repertoireJournaux; end; destructor Consigneur.destroy; begin try close( fichierAcces ); except on e:Exception do begin raise exception.create( 'Incapable de fermer le fichier' + journalSucces + 'du répertoire' + repertoireJournaux ); exit; end; end; try close( fichierErreur ); except on e:Exception do begin raise exception.create( 'Incapable de fermer le fichier' + journalErreur + 'du répertoire' + repertoireJournaux ); exit; end; end; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2011 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // 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 SampleExpertsReg; interface uses ToolsAPI, SysUtils; procedure Register; implementation uses Classes, Windows, SampleExpertsCreatorsUnit, ExpertsRepository, SampleExpertsUIUnit, SampleExpertTypes, ExpertsProject, PlatformAPI ; const sSampleProjectWizardID = 'Embarcadero.SampleProjectWizard'; sAuthor = 'Embarcadero'; sSampleProjectIcon = 'IconOne'; sSampleFormIcon = 'IconTwo'; sSampleTextFileIcon = 'IconThree'; sSampleFormWizardID = 'Embarcadero.SampleFormWizard'; sSampleTextFileWizardID = 'Embarcadero.SampleTextFileWizard'; resourcestring rsSampleWizardPage = 'SampleWizardPage'; rsSampleProjectWizardName = 'SampleProjectWizardName'; rsSampleProjectWizardComment = 'SampleProjectWizardComment'; rsSampleFormWizardName = 'SampleFormWizardName'; rsSampleFormWizardComment = 'SampleFormWizardComment'; rsSampleTextFileWizardName = 'SampleTextFileWizardName'; rsSampleTextFileWizardComment = 'SampleTextFileWizardComment'; rsNotImplemented = 'Not implemented'; procedure Register; var LProjectTypes: Array[TSampleApplicationType] of TExpertsProjectType; begin Assert(Length(LProjectTypes) = 2); LProjectTypes[appVCl] := ptApplication; LProjectTypes[appConsole] := ptConsole; // Project wizards RegisterPackageWizard(TExpertsRepositoryProjectWizardWithProc.Create(sDelphiPersonality, rsSampleProjectWizardComment, rsSampleProjectWizardName, sSampleProjectWizardID, rsSampleWizardPage, sAuthor, procedure var LUIModule: TSampleExpertsUIModule; begin LUIModule := TSampleExpertsUIModule.Create(nil); try // TODO: flag to indicate that wizard should close or stay open when there is an error LUIModule.ExpertsProjectWizard1.Execute( procedure var LModule: TSampleExpertsModule; begin LModule := TSampleExpertsModule.Create(nil); try // Indicate which type of project to create LModule.ExpertsProject1.ProjectType := LProjectTypes[LUIModule.ApplicationType]; LModule.SelectedFeatures := LUIModule.SelectedFeatures; LModule.FormCaption := LUIModule.FormCaption; LModule.AddControls := LUIModule.AddControls; try LModule.ExpertsProject1.CreateProject(sDelphiPersonality); except ApplicationHandleException(nil); end; finally LModule.Free; end; end); finally LUIModule.Free; end; end, function: Cardinal begin Result := LoadIcon(HInstance, sSampleProjectIcon) end, TArray<string>.Create(cWin32Platform, cWin64Platform), TArray<string>.Create() ) as IOTAWizard); RegisterPackageWizard(TExpertsRepositoryProjectWizardWithProc.Create(sDelphiPersonality, rsSampleFormWizardComment, rsSampleFormWizardName, sSampleFormWizardID, rsSampleWizardPage, sAuthor, procedure var LUIModule: TSampleExpertsUIModule; begin LUIModule := TSampleExpertsUIModule.Create(nil); try // TODO: flag to indicate that wizard should close or stay open when there is an error LUIModule.ExpertsFormWizard1.Execute( procedure var LModule: TSampleExpertsModule; begin LModule := TSampleExpertsModule.Create(nil); try LModule.FormCaption := LUIModule.FormCaption; LModule.AddControls := LUIModule.AddControls; try LModule.ExpertsFormModule1.CreateModule(sDelphiPersonality); except ApplicationHandleException(nil); end; finally LModule.Free; end; end); finally LUIModule.Free; end; end, function: Cardinal begin Result := LoadIcon(hInstance, sSampleFormIcon) end ) as IOTAWizard); RegisterPackageWizard(TExpertsRepositoryModuleWizardWithProc.Create(sDelphiPersonality, rsSampleTextFileWizardComment, rsSampleTextFileWizardName, sSampleTextFileWizardID, rsSampleWizardPage, sAuthor, procedure var LModule: TSampleExpertsModule; begin LModule := TSampleExpertsModule.Create(nil); try LModule.ExpertsTextFile1.CreateModule; finally LModule.Free; end; end, function: Cardinal begin Result := LoadIcon(hInstance, sSampleTextFileIcon) end ) as IOTAWizard); end; end.
unit config; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IniFiles; type TConfigIndex = ( cfWindowX, cfWindowY, cfWindowW, cfWindowH, cfConsoleWindowX, cfConsoleWindowY, cfConsoleWindowW, cfConsoleWindowH ); function ConfigGetStr(I: TConfigIndex): String; function ConfigGetInt(I: TConfigIndex): Integer; procedure ConfigSetStr(I: TConfigIndex; Value: String); procedure ConfigSetInt(I: TConfigIndex; Value: Integer); procedure ConfigSave; implementation var Ini: TIniFile = nil; function GetSection(I: TConfigIndex): String; begin case I of cfWindowX, cfWindowY, cfWindowW, cfWindowH, cfConsoleWindowX, cfConsoleWindowY, cfConsoleWindowW, cfConsoleWindowH: Result := 'UI'; end; end; function GetKey(I: TConfigIndex): String; begin case I of cfWindowX: Result := 'WindowX'; cfWindowY: Result := 'WindowY'; cfWindowW: Result := 'WindowW'; cfWindowH: Result := 'WindowH'; cfConsoleWindowX: Result := 'ConsoleWindowX'; cfConsoleWindowY: Result := 'ConsoleWindowY'; cfConsoleWindowW: Result := 'ConsoleWindowW'; cfConsoleWindowH: Result := 'ConsoleWindowH'; end; end; function GetDefault(I: TConfigIndex): String; begin case I of cfWindowX: Result := '10'; cfWindowY: Result := '10'; cfWindowW: Result := '270'; cfWindowH: Result := '500'; cfConsoleWindowX: Result := '300'; cfConsoleWindowY: Result := '10'; cfConsoleWindowW: Result := '480'; cfConsoleWindowH: Result := '340'; end; end; function GetIniFileName: String; var Dir: String; begin Dir := GetUserDir + DirectorySeparator + '.config'; if not DirectoryExists(Dir) then CreateDir(Dir); Result := Dir + DirectorySeparator + 'gitexplorer.ini'; end; procedure ConfigLoad; begin if not Assigned(Ini) then begin Ini := TIniFile.Create(GetIniFileName); Ini.CacheUpdates := True; end; end; function ConfigGetStr(I: TConfigIndex): String; begin ConfigLoad; Result := Ini.ReadString(GetSection(I), GetKey(I), GetDefault(I)); end; function ConfigGetInt(I: TConfigIndex): Integer; begin ConfigLoad; Result := Ini.ReadInteger(GetSection(I), GetKey(I), StrToInt(GetDefault(I))); end; procedure ConfigSetStr(I: TConfigIndex; Value: String); begin Ini.WriteString(GetSection(I), GetKey(I), Value); end; procedure ConfigSetInt(I: TConfigIndex; Value: Integer); begin Ini.WriteInteger(GetSection(I), GetKey(I), Value); end; procedure ConfigSave; begin Ini.UpdateFile; end; finalization if Assigned(Ini) then begin Ini.UpdateFile; Ini.Free; end; end.
{ Esta unit serve pra manipular arquivo binário da lotofacil, pra a tabela lotofacil_num. A tabela lotofacil_num é composta por: ltf_id -> número identificador de cada combinação. ltf_qt -> a quantidade de bolas na combinação, valores válidos: 15, 16, 17, 18. b_1 até b_18 -> bolas que são daquela combinação, onde b_1 ser o campo com a menor bola. } unit ulotofacil_bolas_arquivo; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type // Registro que armazena o layout binário do arquivo. {$PACKRECORDS 1} TLotofacil_bolas_layout_arquivo = record ltf_id: cardinal; ltf_qt: byte; bolas: array[1..18] of byte; end; // Indica o status do processamento. TLotofacil_bolas_status = procedure(ltf_id: cardinal; ltf_qt: byte; ltf_bolas: array of byte) of object; TLotofacil_bolas_erro = procedure(erro: string) of object; { TLotofacil_bolas } type TLotofacil_bolas = class const ltf_qt_15_id_minimo = 1; ltf_qt_15_id_maximo = 32768760; ltf_qt_16_id_minimo = 32768761; private fstatus: TLotofacil_bolas_status; public property Status: TLotofacil_bolas_status read fstatus write fstatus; constructor Create; end; implementation { TLotofacil_bolas } constructor TLotofacil_bolas.Create; begin end; end.
unit uWmLabelEditBtn; interface uses Classes, Messages, StdCtrls, Controls, Graphics, Types, Windows, Forms, cxContainer, cxEdit, cxMaskEdit, cxButtonEdit, cxControls; type TLabelPosition = (lpLeftTop, lpLeftCenter, lpLeftBottom, lpTopLeft, lpBottomLeft, lpLeftTopLeft, lpLeftCenterLeft, lpLeftBottomLeft, lpTopCenter, lpBottomCenter, lpRightTop, lpRightCenter, lpRighBottom, lpTopRight, lpBottomRight); TEditLabel = class(TLabel) private FAlwaysEnable: boolean; procedure CMEnabledChanged(var Msg: TMessage); message CM_ENABLEDCHANGED; published property AlwaysEnable: boolean read FAlwaysEnable write FAlwaysEnable; end; TWmLabelEditBtn = class(TcxButtonEdit) private FLabel: TEditLabel; FLabelFont: TFont; FLabelPosition: TLabelPosition; FLabelMargin: Integer; FLabelTransparent: boolean; FLabelAlwaysEnabled: boolean; FOnLabelClick: TNotifyEvent; FOnLabelDblClick: TNotifyEvent; FParentFnt: boolean; FShowError: boolean; FFocusLabel: boolean; FLoadedHeight: Integer; procedure SetLabelCaption(const value: string); function GetLabelCaption: string; procedure SetLabelPosition(const value: TLabelPosition); procedure SetLabelMargin(const value: Integer); procedure SetLabelTransparent(const value: boolean); procedure SetLabelAlwaysEnabled(const value: boolean); procedure SetLabelFont(const value: TFont); function GetHeightEx: Integer; procedure UpdateLabel; procedure UpdateLabelPos; procedure CMParentFontChanged(var Message: TMessage); message CM_PARENTFONTCHANGED; procedure SetHeightEx(const Value: Integer); procedure WMSetFocus(var Msg: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Msg: TWMKillFocus); message WM_KILLFOCUS; protected function CreateLabel: TEditLabel; procedure LabelClick(Sender: TObject); procedure LabelDblClick(Sender: TObject); procedure Loaded; override; public constructor Create(aOwner: TComponent); override; destructor Destroy; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; published property Anchors; property AutoSize; property BeepOnEnter; property Constraints; property DragMode; property Enabled; property Height: Integer read GetHeightEx write SetHeightEx; property FocusLabel: boolean read FFocusLabel write FFocusLabel default false; property LabelCaption: string read GetLabelCaption write SetLabelCaption; property LabelPosition: TLabelPosition read FLabelPosition write SetLabelPosition default lpLeftCenter; property LabelMargin: Integer read FLabelMargin write SetLabelMargin default 4; property LabelTransparent: boolean read FLabelTransparent write SetLabelTransparent default false; property LabelAlwaysEnabled: boolean read FLabelAlwaysEnabled write SetLabelAlwaysEnabled default false; property LabelFont: TFont read FLabelFont write SetLabelFont; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property Properties; property ShowHint; property Style; property StyleDisabled; property StyleFocused; property StyleHot; property TabOrder; property TabStop; property Text; property Visible; property DragCursor; property DragKind; property ImeMode; property ImeName; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEditing; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnEndDock; property OnStartDock; property OnLabelClick: TNotifyEvent read FOnLabelClick write FOnLabelClick; property OnLabelDblClick: TNotifyEvent read FOnLabelDblClick write FOnLabelDblClick; property ShowError: boolean read FShowError write FShowError default false; end; implementation { TEditLabel } procedure TEditLabel.CMEnabledChanged(var Msg: TMessage); begin inherited; if AlwaysEnable and not Enabled then Enabled := true; end; { TWmLabelEditBtn } procedure TWmLabelEditBtn.CMParentFontChanged(var Message: TMessage); begin inherited; if Assigned(FLabel) and not ShowError and ParentFont then begin FLabel.Font.Assign(Font); UpdateLabel; end; end; constructor TWmLabelEditBtn.Create(aOwner: TComponent); begin inherited Create(aOwner); FLabelPosition := lpLeftCenter; FLabel := nil; FLabelMargin := 4; FLabelFont := TFont.Create; // FLabelFont.OnChange := LabelFontChange; FParentFnt := false; end; function TWmLabelEditBtn.CreateLabel: TEditLabel; begin Result := TEditLabel.Create(self); Result.Parent := Parent; Result.FocusControl := self; Result.Font.Assign(LabelFont); Result.OnClick := LabelClick; Result.OnDblClick := LabelDblClick; Result.ParentFont := ParentFont; end; destructor TWmLabelEditBtn.Destroy; begin if (FLabel <> nil) then begin FLabel.Parent := nil; FLabel.Free; FLabel := nil; end; FLabelFont.Free; inherited Destroy; end; function TWmLabelEditBtn.GetHeightEx: Integer; begin Result := inherited Height; end; function TWmLabelEditBtn.GetLabelCaption: string; begin if FLabel <> nil then Result := FLabel.Caption else Result := ''; end; procedure TWmLabelEditBtn.LabelClick(Sender: TObject); begin if Assigned(FOnLabelClick) then FOnLabelClick(self); end; procedure TWmLabelEditBtn.LabelDblClick(Sender: TObject); begin if Assigned(FOnLabelDblClick) then FOnLabelDblClick(self); end; procedure TWmLabelEditBtn.Loaded; begin inherited Loaded; if not (csDesigning in ComponentState) then if FLabel <> nil then UpdateLabel; Height := FLoadedHeight; SetBounds(Left, Top, Width, Height); if not LabelAlwaysEnabled and Assigned(FLabel) then begin FLabel.Enabled := Enabled; FLabel.AlwaysEnable := LabelAlwaysEnabled; end; if (FLabel <> nil) then UpdateLabel; if ParentFont and not ShowError and Assigned(FLabel) then begin FLabel.Font.Assign(Font); end; FParentFnt := ParentFont; if (FLabel <> nil) then UpdateLabel; end; procedure TWmLabelEditBtn.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin if Assigned(FLabel) then begin case LabelPosition of lpLeftTop, lpLeftCenter, lpLeftBottom: begin if (Align in [alTop, alClient, alBottom]) then begin AWidth := AWidth - (FLabel.Width + LabelMargin); ALeft := ALeft + (FLabel.Width + LabelMargin); end; end; lpRightTop, lpRightCenter, lpRighBottom: begin if (Align in [alTop, alClient, alBottom]) then AWidth := AWidth - (FLabel.Width + LabelMargin); end; lpTopLeft, lpTopCenter, lpTopRight: begin if (Align in [alTop, alClient, alRight, alLeft]) then ATop := ATop + FLabel.Height; end; end; end; inherited SetBounds(ALeft, ATop, AWidth, AHeight); if (FLabel <> nil) then begin if (FLabel.Parent <> nil) then UpdateLabel; end; end; procedure TWmLabelEditBtn.SetHeightEx(const Value: Integer); begin if (csLoading in ComponentState) then FLoadedHeight := Value; inherited Height := Value; end; procedure TWmLabelEditBtn.SetLabelAlwaysEnabled(const value: boolean); begin FLabelAlwaysEnabled := value; if Assigned(FLabel) then begin if value then FLabel.Enabled := true; FLabel.AlwaysEnable := value; end; Invalidate; end; procedure TWmLabelEditBtn.SetLabelCaption(const value: string); begin if FLabel = nil then FLabel := CreateLabel; FLabel.Caption := value; UpdateLabel; end; procedure TWmLabelEditBtn.SetLabelFont(const value: TFont); begin FLabelFont := value; end; procedure TWmLabelEditBtn.SetLabelMargin(const value: Integer); begin FLabelMargin := Value; if FLabel <> nil then UpdateLabel; end; procedure TWmLabelEditBtn.SetLabelPosition(const value: TLabelPosition); begin FLabelPosition := Value; if FLabel <> nil then UpdateLabel; end; procedure TWmLabelEditBtn.SetLabelTransparent(const value: boolean); begin FLabelTransparent := Value; if FLabel <> nil then UpdateLabel; end; procedure TWmLabelEditBtn.UpdateLabel; begin if Assigned(FLabel.Parent) then begin FLabel.Transparent := FLabelTransparent; if not FParentFnt or ShowError then begin FLabel.Font.Assign(FLabelFont); end else FLabel.Font.Assign(Font); if FocusLabel then begin if Focused then FLabel.Font.Style := FLabel.Font.Style + [fsBold] else FLabel.Font.Style := FLabel.Font.Style - [fsBold]; end; if FLabel.Parent.HandleAllocated then UpdateLabelPos; end; end; procedure TWmLabelEditBtn.UpdateLabelPos; var tw, brdr: Integer; r: TRect; begin r := Rect(0, 0, 1000, 255); DrawText(FLabel.Canvas.Handle, PChar(FLabel.Caption), Length(FLabel.Caption), r, DT_HIDEPREFIX or DT_CALCRECT); tw := r.Right; brdr := 0; if BorderStyle = cxcbsNone then brdr := 2; case FLabelPosition of lpLeftTop: begin FLabel.Top := self.Top; FLabel.Left := self.Left - tw - FLabelMargin; end; lpLeftCenter: begin if self.Height > FLabel.Height then FLabel.Top := Top + ((Height - brdr - FLabel.Height) div 2) else FLabel.Top := Top - ((FLabel.Height - Height + brdr) div 2); FLabel.Left := Left - tw - FLabelMargin; end; lpLeftBottom: begin FLabel.Top := self.Top + self.Height - FLabel.Height; FLabel.Left := self.Left - tw - FLabelMargin; end; lpTopLeft: begin FLabel.Top := self.Top - FLabel.Height - FLabelMargin; FLabel.Left := self.Left; end; lpTopRight: begin FLabel.Top := self.Top - FLabel.Height - FLabelMargin; FLabel.Left := self.Left + self.Width - FLabel.Width; end; lpTopCenter: begin FLabel.Top := self.Top - FLabel.Height - FLabelMargin; if self.Width - FLabel.Width > 0 then FLabel.Left := self.Left + ((self.Width - FLabel.Width) div 2) else FLabel.Left := self.Left - ((FLabel.Width - self.Width) div 2) end; lpBottomLeft: begin FLabel.Top := self.Top + self.Height + FLabelMargin; FLabel.Left := self.Left; end; lpBottomCenter: begin FLabel.Top := self.Top + self.Height + FLabelMargin; if self.Width - FLabel.Width > 0 then FLabel.Left := self.Left + ((self.Width - FLabel.Width) div 2) else FLabel.Left := self.Left - ((FLabel.Width - self.Width) div 2) end; lpBottomRight: begin FLabel.Top := self.Top + self.Height + FLabelMargin; FLabel.Left := self.Left + self.Width - FLabel.Width; end; lpLeftTopLeft: begin FLabel.Top := self.Top; FLabel.Left := self.Left - FLabelMargin; end; lpLeftCenterLeft: begin if self.Height > FLabel.Height then FLabel.Top := self.Top + ((Height - brdr - FLabel.Height) div 2) else FLabel.Top := self.Top - ((FLabel.Height - Height + brdr) div 2); FLabel.Left := self.Left - FLabelMargin; end; lpLeftBottomLeft: begin FLabel.Top := self.Top + self.Height - FLabel.Height; FLabel.Left := self.Left - FLabelMargin; end; lpRightTop: begin FLabel.Top := self.Top; FLabel.Left := self.Left + self.Width + FLabelMargin; end; lpRightCenter: begin if self.Height > FLabel.Height then FLabel.Top := Top + ((Height - brdr - FLabel.Height) div 2) else FLabel.Top := Top - ((FLabel.Height - Height + brdr) div 2); FLabel.Left := self.Left + self.Width + FLabelMargin; end; lpRighBottom: begin FLabel.Top := self.Top + self.Height - FLabel.Height; FLabel.Left := self.Left + self.Width + FLabelMargin; end; end; FLabel.Visible := Visible; end; procedure TWmLabelEditBtn.WMKillFocus(var Msg: TWMKillFocus); begin if (csLoading in ComponentState) then Exit; if FFocusLabel and (FLabel <> nil) then begin FLabel.Font.Style := FLabel.Font.Style - [fsBold]; UpdateLabelPos; end; inherited; end; procedure TWmLabelEditBtn.WMSetFocus(var Msg: TWMSetFocus); begin if csLoading in ComponentState then Exit; inherited; if FFocusLabel and (FLabel <> nil) then begin FLabel.Font.Style := FLabel.Font.Style + [fsBold]; UpdateLabelPos; end; 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/. -------------------------------------------------------------------------------} {=============================================================================== Simple timer Non visual variant of TTimer component ©František Milt 2018-10-22 Version 1.1.2 Dependencies: AuxTypes - github.com/ncs-sniper/Lib.AuxTypes AuxClasses - github.com/ncs-sniper/Lib.AuxClasses UtilityWindow - github.com/ncs-sniper/Lib.UtilityWindow MulticastEvent - github.com/ncs-sniper/Lib.MulticastEvent WndAlloc - github.com/ncs-sniper/Lib.WndAlloc ===============================================================================} unit SimpleTimer; {$IF not(defined(WINDOWS) or defined(MSWINDOWS))} {$MESSAGE FATAL 'Unsupported operating system.'} {$IFEND} {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Windows, Messages, Classes, UtilityWindow, AuxTypes, AuxClasses; type TSimpleTimer = class(TCustomObject) private fWindow: TUtilityWindow; fTimerID: PtrUInt; fOwnsWindow: Boolean; fInterval: UInt32; fEnabled: Boolean; fTag: Integer; fOnTimer: TNotifyEvent; Function GetWindowHandle: HWND; procedure SetInterval(Value: UInt32); procedure SetEnabled(Value: Boolean); protected procedure SetupTimer; procedure MessagesHandler(var Msg: TMessage; var Handled: Boolean); public constructor Create(Window: TUtilityWindow = nil; TimerID: PtrUInt = 1); destructor Destroy; override; procedure ProcessMassages; property WindowHandle: HWND read GetWindowHandle; property Window: TUtilityWindow read fWindow; property TimerID: PtrUInt read fTimerID; property OwnsWindow: Boolean read fOwnsWindow; property Interval: UInt32 read fInterval write SetInterval; property Enabled: Boolean read fEnabled write SetEnabled; property Tag: Integer read fTag write fTag; property OnTimer: TNotifyEvent read fOnTimer write fOnTimer; end; implementation uses SysUtils; {=== TSimpleTimer // Private methods ==========================================} Function TSimpleTimer.GetWindowHandle: HWND; begin Result := fWindow.WindowHandle; end; //------------------------------------------------------------------------------ procedure TSimpleTimer.SetInterval(Value: UInt32); begin fInterval := Value; SetupTimer; end; //------------------------------------------------------------------------------ procedure TSimpleTimer.SetEnabled(Value: Boolean); begin fEnabled := Value; SetupTimer; end; {=== TSimpleTimer // Protected methods ========================================} procedure TSimpleTimer.SetupTimer; begin KillTimer(WindowHandle,fTimerID); If (fInterval > 0) and fEnabled then If SetTimer(WindowHandle,fTimerID,fInterval,nil) = 0 then raise EOutOfResources.Create('Not enough timers available.'); end; //------------------------------------------------------------------------------ procedure TSimpleTimer.MessagesHandler(var Msg: TMessage; var Handled: Boolean); begin If (Msg.Msg = WM_TIMER) and (PtrUInt(Msg.wParam) = fTimerID) then begin If Assigned(fOnTimer) then fOnTimer(Self); Msg.Result := 0; Handled := True; end else Handled := False; end; {=== TSimpleTimer // Public methods ===========================================} constructor TSimpleTimer.Create(Window: TUtilityWindow = nil; TimerID: PtrUInt = 1); begin inherited Create; If Assigned(Window) then begin fWindow := Window; fOwnsWindow := False; end else begin fWindow := TUtilityWindow.Create; fOwnsWindow := True; end; fTimerID := TimerID; fWindow.OnMessage.Add(MessagesHandler); fInterval := 1000; fEnabled := False; end; //------------------------------------------------------------------------------ destructor TSimpleTimer.Destroy; begin fEnabled := False; SetupTimer; If fOwnsWindow then fWindow.Free else fWindow.OnMessage.Remove(MessagesHandler); inherited; end; //------------------------------------------------------------------------------ procedure TSimpleTimer.ProcessMassages; begin fWindow.ProcessMessages(False); end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clCookies; interface {$I clVer.inc} uses Classes; type TclCookieItem = class(TCollectionItem) private FSecure: Boolean; FValue: string; FExpires: string; FName: string; FDomain: string; FPath: string; FCookieData: string; public procedure Assign(Source: TPersistent); override; published property Name: string read FName write FName; property Value: string read FValue write FValue; property Expires: string read FExpires write FExpires; property Domain: string read FDomain write FDomain; property Path: string read FPath write FPath; property Secure: Boolean read FSecure write FSecure; property CookieData: string read FCookieData write FCookieData; end; TclCookieList = class(TOwnedCollection) private function GetItem(Index: Integer): TclCookieItem; procedure SetItem(Index: Integer; const Value: TclCookieItem); procedure RemoveCookies(ARequestHeader: TStrings); protected function BuildRequestCookie(ACookieItem: TclCookieItem): string; virtual; procedure ParseResponseCookie(const ACookieData: string); virtual; public procedure SetRequestCookies(ARequestHeader: TStrings); virtual; procedure GetResponseCookies(AResponseHeader: TStrings); virtual; function Add: TclCookieItem; function AddCookie(const AName, AValue: string): TclCookieItem; function CookieByName(const AName: string): TclCookieItem; property Items[Index: Integer]: TclCookieItem read GetItem write SetItem; default; end; implementation uses SysUtils, clUtils; { TclCookieList } function TclCookieList.Add: TclCookieItem; begin Result := TclCookieItem(inherited Add()); end; function TclCookieList.AddCookie(const AName, AValue: string): TclCookieItem; begin Result := Add(); Result.Name := AName; Result.Value := AValue; end; function TclCookieList.CookieByName(const AName: string): TclCookieItem; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i]; if SameText(Result.Name, AName) then Exit; end; Result := nil; end; function TclCookieList.GetItem(Index: Integer): TclCookieItem; begin Result := TclCookieItem(inherited GetItem(Index)); end; procedure TclCookieList.GetResponseCookies(AResponseHeader: TStrings); procedure ProcessCookies(AResponseHeader, AFieldList: TStrings; const AFieldName: string); var i: Integer; begin for i := 0 to AFieldList.Count - 1 do begin if SameText(AFieldName, AFieldList[i]) then begin ParseResponseCookie(GetHeaderFieldValue(AResponseHeader, AFieldList, i)); end; end; end; var fieldList: TStrings; begin Clear(); fieldList := TStringList.Create(); try GetHeaderFieldList(0, AResponseHeader, fieldList); if GetHeaderFieldValue(AResponseHeader, fieldList, 'set-cookie2') <> '' then begin ProcessCookies(AResponseHeader, fieldList, 'set-cookie2'); end else begin ProcessCookies(AResponseHeader, fieldList, 'set-cookie'); end; finally fieldList.Free(); end; end; procedure TclCookieList.SetItem(Index: Integer; const Value: TclCookieItem); begin inherited SetItem(Index, Value); end; procedure TclCookieList.RemoveCookies(ARequestHeader: TStrings); var i: Integer; fieldList: TStrings; begin fieldList := TStringList.Create(); try GetHeaderFieldList(0, ARequestHeader, fieldList); for i := fieldList.Count - 1 downto 0 do begin if SameText('cookie', fieldList[i]) then begin RemoveHeaderField(ARequestHeader, fieldList, i); end; end; finally fieldList.Free(); end; end; procedure TclCookieList.SetRequestCookies(ARequestHeader: TStrings); const cookieDelimiter = '; '; var i: Integer; s: string; begin RemoveCookies(ARequestHeader); //check URL path s := ''; for i := 0 to Count - 1 do begin s := s + BuildRequestCookie(Items[i]) + cookieDelimiter; end; if (s <> '') then begin SetLength(s, Length(s) - Length(cookieDelimiter)); end; AddHeaderField(ARequestHeader, 'Cookie', s); end; function TclCookieList.BuildRequestCookie(ACookieItem: TclCookieItem): string; begin Result := ACookieItem.Name + '=' + ACookieItem.Value; end; procedure TclCookieList.ParseResponseCookie(const ACookieData: string); function GetExpires(const ACookieData: string): string; const lexem = 'expires='; var ind: Integer; begin ind := system.Pos(lexem, LowerCase(ACookieData)); if (ind > 0) then begin Result := system.Copy(ACookieData, ind + Length(lexem), Length(ACookieData)); Result := StringReplace(Result, ',', '==', [rfReplaceAll]); Result := GetHeaderFieldValueItem(Result, ''); Result := StringReplace(Result, '==', ',', [rfReplaceAll]); end else begin Result := ''; end; end; var ind: Integer; item: TclCookieItem; name, value: string; begin if (ACookieData = '') then Exit; ind := system.Pos('=', ACookieData); if (ind > 0) then begin name := system.Copy(ACookieData, 1, ind - 1); value := GetHeaderFieldValueItem(ACookieData, LowerCase(name) + '='); end else begin name := ACookieData; value := ''; end; if (CookieByName(name) = nil) then begin item := Add(); item.Name := name; item.Value := value; item.Expires := GetExpires(ACookieData); item.Domain := GetHeaderFieldValueItem(ACookieData, 'domain='); item.Path := GetHeaderFieldValueItem(ACookieData, 'path='); item.Secure := (system.Pos('secure', LowerCase(ACookieData)) > 0); item.CookieData := ACookieData; end; end; { TclCookieItem } procedure TclCookieItem.Assign(Source: TPersistent); var item: TclCookieItem; begin if (Source is TclCookieItem) then begin item := (Source as TclCookieItem); Name := item.Name; Value := item.Value; Expires := item.Expires; Domain := item.Domain; Path := item.Path; Secure := item.Secure; CookieData := item.CookieData; end else begin inherited Assign(Source); end; end; end.
//--------------------------------------------------------------------------- // Copyright (c) 2016 Embarcadero Technologies, Inc. All rights reserved. // // This software is the copyrighted property of Embarcadero Technologies, Inc. // ("Embarcadero") and its licensors. You may only use this software if you // are an authorized licensee of Delphi, C++Builder or RAD Studio // (the "Embarcadero Products"). This software is subject to Embarcadero's // standard software license and support agreement that accompanied your // purchase of the Embarcadero Products and is considered a Redistributable, // as such term is defined thereunder. Your use of this software constitutes // your acknowledgement of your agreement to the foregoing software license // and support agreement. //--------------------------------------------------------------------------- unit MusicPlayer.iOS; interface {$IFDEF IOS} uses MusicPlayer.Utils, FMX.Graphics, FMX.Types, System.SysUtils, System.Classes, System.Types, System.IoUtils, iOSApi.MediaPlayer, iOSApi.Foundation, iOSApi.UIKit, FMX.Helpers.iOS, Macapi.Helpers; type TMusicPlayer = class private type TProcessThread = class (TThread) private [weak] FMusicPlayer: TMusicPlayer; FLastItem: TMPSong; FOnProcessPlay: TOnProcessPlayEvent; procedure ProcessPlay; public constructor Create(CreateSuspended: Boolean; AMusicPlayer: TMusicPlayer; processHandler: TOnProcessPlayEvent); destructor Destroy; override; procedure Execute; override; end; protected class var FInstance: TMusicPlayer; private FCurrentIndex: Integer; FPlaylist: TArray<TMPSong>; FAlbums: TArray<TMPAlbum>; FMusicPlayer: MPMusicPlayerController; FDefaultAlbumImage: TBitmap; FOnSongChange: TOnSongChangeEvent; FOnProcessPlay: TOnProcessPlayEvent; constructor Create(AType: TMPControllerType = TMPControllerType.App); procedure DoOnSongChange(newIndex: Integer); procedure DoOnProcessPlay(newPos: Single); procedure SetVolume(const Value: Single); procedure SetTime(const Value: Single); procedure SetRepeatMode(const Value: TMPRepeatMode); procedure SetShuffleMode(const Value: Boolean); function GetVolume: Single; function GetTime: Single; function GetRepeatMode: TMPRepeatMode; function GetDuration: Single; function GetPlaybackState: TMPPlaybackState; function GetShuffleMode: Boolean; public class procedure SetPlayerType(AType: TMPControllerType); class function DefaultPlayer: TMusicPlayer; destructor Destroy; override; property CurrentIndex: Integer read FCurrentIndex; property Volume: Single read GetVolume write SetVolume; property Time: Single read GetTime write SetTime; property Duration: Single read GetDuration; property PlaybackState: TMPPlaybackState read GetPlaybackState; property ShuffleMode: Boolean read GetShuffleMode write SetShuffleMode; property RepeatMode: TMPRepeatMode read GetRepeatMode write SetRepeatMode; property Playlist: TArray<TMPSong> read FPlaylist; property Albums: TArray<TMPAlbum> read FAlbums; property DefaultAlbumImage: TBitmap read FDefaultAlbumImage write FDefaultAlbumImage; property OnSongChange: TOnSongChangeEvent read FOnSongChange write FOnSongChange; property OnProcessPlay: TOnProcessPlayEvent read FOnProcessPlay write FOnProcessPlay; function IndexOfNowPlayingItem: Integer; function GetAlbums: TArray<string>; function GetSongs: TArray<string>; function GetSongsInAlbum(AName: string): TArray<string>; function CanSkipBack: Boolean; function CanSkipForward: Boolean; procedure PlayByIndex(Index: Integer); procedure Play; procedure Stop; procedure Pause; procedure Next; procedure Previous; end; {$ENDIF} implementation {$IFDEF IOS} { TMusicPlayer } function TMusicPlayer.CanSkipBack: Boolean; begin Result := (Length(FPlaylist) > 0) and (FCurrentIndex > 0) and (TMPPlaybackState(FMusicPlayer.playbackState) in [TMPPlaybackState.Playing, TMPPlaybackState.Paused]); end; function TMusicPlayer.CanSkipForward: Boolean; begin Result := False; if (Length(FPlaylist) = 0) or not (TMPPlaybackState(FMusicPlayer.playbackState) in [TMPPlaybackState.Playing, TMPPlaybackState.Paused]) then Exit(Result); case RepeatMode of TMPRepeatMode.One: Result := (Low(FPlaylist) <= FCurrentIndex) and (FCurrentIndex <= High(FPlaylist)); TMPRepeatMode.Default, TMPRepeatMode.None: Result := (Low(FPlaylist) <= FCurrentIndex) and (FCurrentIndex <= (High(FPlaylist) - 1)); TMPRepeatMode.All: Result := True; end; end; procedure TMusicPlayer.Pause; begin FMusicPlayer.pause; end; constructor TMusicPlayer.Create(AType: TMPControllerType); var LAlbumImageFile: string; begin case AType of TMPControllerType.App: FMusicPlayer := TMPMusicPlayerController.Wrap (TMPMusicPlayerController.OCClass.applicationMusicPlayer); TMPControllerType.Ipod: FMusicPlayer := TMPMusicPlayerController.Wrap (TMPMusicPlayerController.OCClass.iPodMusicPlayer); end; LAlbumImageFile := TPath.Combine(TPath.GetDocumentsPath, 'MusicNote.png'); if FileExists(LAlbumImageFile) then FDefaultAlbumImage := TBitmap.CreateFromFile(LAlbumImageFile); TProcessThread.Create(True,self,DoOnProcessPlay).Start; end; class function TMusicPlayer.DefaultPlayer: TMusicPlayer; begin if not Assigned(FInstance) then FInstance := TMusicPlayer.Create; Result := FInstance; end; destructor TMusicPlayer.Destroy; begin FMusicPlayer.release; inherited; end; procedure TMusicPlayer.DoOnSongChange(newIndex: Integer); begin if Assigned(FOnSongChange) then TThread.Queue(TThread.CurrentThread, procedure begin FOnSongChange(newIndex); end); end; procedure TMusicPlayer.DoOnProcessPlay(newPos: Single); begin if Assigned(FOnProcessPlay) then TThread.Queue(TThread.CurrentThread, procedure begin FOnProcessPlay(newPos); end); end; function TMusicPlayer.GetAlbums: TArray<string>; var query: MPMediaQuery; i: Integer; Item: MPMediaItemCollection; artwork: MPMediaItemArtwork; art_img: UIImage; art_size: NSSize; pt: Pointer; bounds: TSizeF; begin query := TMPMediaQuery.Wrap(TMPMediaQuery.OCClass.albumsQuery); SetLength(Result, query.collections.count); SetLength(FAlbums, query.collections.count + 1); FAlbums[query.collections.count] := TMPAlbum.AllMusicAlbum; for i := 0 to query.collections.count - 1 do begin Item := TMPMediaItemCollection.Wrap(query.collections.objectAtIndex(i)); FAlbums[i].Name := NSStrToStr(TNSString.Wrap (Item.representativeItem.valueForProperty(MPMediaItemPropertyAlbumTitle))); FAlbums[i].Artist := NSStrToStr(TNSString.Wrap (Item.representativeItem.valueForProperty(MPMediaItemPropertyArtist))); FAlbums[i].Album_ID := i; pt := Item.representativeItem.valueForProperty(MPMediaItemPropertyArtwork); if pt <> nil then begin try artwork := TMPMediaItemArtwork.Wrap(pt); bounds := artwork.bounds.ToSizeF; art_size.width := bounds.cx; art_size.height := bounds.cy; art_img := artwork.imageWithSize(art_size); if art_img <> nil then FAlbums[i].Artwork := UIImageToBitmap(art_img,0, TSize.Create(Trunc(art_size.width), Trunc(art_size.height))); except end; end; if FAlbums[i].Artwork = nil then FAlbums[i].Artwork := FDefaultAlbumImage; Result[i] := FAlbums[i].Name; end; end; function TMusicPlayer.GetDuration: Single; begin Result := TNSNumber.Wrap(FMusicPlayer.nowPlayingItem.valueForProperty(MPMediaItemPropertyPlaybackDuration)).floatValue; end; function TMusicPlayer.GetPlaybackState: TMPPlaybackState; begin Result := TMPPlayBackState(FMusicPlayer.playbackState); end; function TMusicPlayer.GetRepeatMode: TMPRepeatMode; begin Result := TMPRepeatMode(FMusicPlayer.repeatMode); end; function TMusicPlayer.GetShuffleMode: Boolean; begin Result := (FMusicPlayer.shuffleMode = MPMusicShuffleModeSongs) or (FMusicPlayer.shuffleMode = MPMusicShuffleModeAlbums); end; function TMusicPlayer.GetSongs: TArray<string>; var query: MPMediaQuery; i: Integer; begin query := TMPMediaQuery.Wrap(TMPMediaQuery.OCClass.songsQuery); FMusicPlayer.setQueueWithQuery(query); SetLength(Result, query.items.count); SetLength(FPlaylist, query.items.count); for i := 0 to query.items.count - 1 do begin FPlaylist[i] := TMPSong.FromMediaItem(TMPMediaItem.Wrap(query.items.objectAtIndex(i))); Result[i] := Format('[%s]-[%s]', [FPlaylist[i].Artist, FPlaylist[i].Title]); end; end; function TMusicPlayer.GetSongsInAlbum(AName: string): TArray<string>; var query: MPMediaQuery; i: Integer; predicate: MPMediaPropertyPredicate; begin if AName = TMPAlbum.AllMusicAlbum.Name then begin Result := GetSongs; Exit; end; query := TMPMediaQuery.Wrap(TMPMediaQuery.Alloc.init); predicate :=TMPMediaPropertyPredicate.Wrap(TMPMediaPropertyPredicate.OCClass.predicateWithValue(TNSString.OCClass.stringWithString(StrToNSStr(AName)), MPMediaItemPropertyAlbumTitle)); query.addFilterPredicate(predicate); query.setGroupingType(MPMediaGroupingAlbum); FMusicPlayer.setQueueWithQuery(query); SetLength(Result,query.items.count); SetLength(FPlaylist, query.items.count); for i := 0 to query.items.count - 1 do begin FPlaylist[i] := TMPSong.FromMediaItem(TMPMediaItem.Wrap(query.items.objectAtIndex(i))); Result[i] := Format('[%s]-[%s]', [FPlaylist[i].Artist, FPlaylist[i].Title]); end; end; function TMusicPlayer.GetTime: Single; begin Result := FMusicPlayer.currentPlaybackTime; end; function TMusicPlayer.GetVolume: Single; begin Result := FMusicPlayer.volume; end; function TMusicPlayer.IndexOfNowPlayingItem: Integer; var i: Integer; begin Result := Result.MaxValue; for i := 0 to Length(FPlaylist) -1 do begin if FPlaylist[i].Equals(TMPSong.FromMediaItem(FMusicPlayer.nowPlayingItem)) then begin Result := i; FCurrentIndex := i; Exit; end; end; end; procedure TMusicPlayer.Next; begin FMusicPlayer.skipToNextItem; DoOnSongChange(IndexOfNowPlayingItem); end; procedure TMusicPlayer.Play; begin if FMusicPlayer.playbackState = Ord(TMPPlaybackState.Stopped) then FMusicPlayer.setNowPlayingItem(FPlaylist[FCurrentIndex].MPItem); FMusicPlayer.play; end; procedure TMusicPlayer.PlayByIndex(Index: Integer); begin Stop; if (Index >= 0) and (Index < Length(FPlaylist)) then begin FMusicPlayer.setNowPlayingItem(FPlaylist[Index].MPItem); FCurrentIndex := Index; Play; DoOnSongChange(Index); end; end; procedure TMusicPlayer.Previous; begin FMusicPlayer.skipToPreviousItem; DoOnSongChange(IndexOfNowPlayingItem); end; class procedure TMusicPlayer.SetPlayerType(AType: TMPControllerType); begin if Assigned(FInstance) then FInstance.DisposeOf; FInstance := TMusicPlayer.Create(AType); end; procedure TMusicPlayer.SetRepeatMode(const Value: TMPRepeatMode); begin FMusicPlayer.SetRepeatMode(Ord(Value)); end; procedure TMusicPlayer.SetShuffleMode(const Value: Boolean); begin if Value then FMusicPlayer.setShuffleMode(MPMusicShuffleModeSongs) else FMusicPlayer.setShuffleMode(MPMusicShuffleModeOff); end; procedure TMusicPlayer.SetTime(const Value: Single); begin FMusicPlayer.setCurrentPlaybackTime(Value); end; procedure TMusicPlayer.SetVolume(const Value: Single); begin FMusicPlayer.SetVolume(Value); end; procedure TMusicPlayer.Stop; begin FMusicPlayer.pause; DoOnProcessPlay(0); end; { TMusicPlayer.TProcessThread } constructor TMusicPlayer.TProcessThread.Create(CreateSuspended: Boolean; AMusicPlayer: TMusicPlayer; processHandler: TOnProcessPlayEvent); begin inherited Create(CreateSuspended); FMusicPlayer := AMusicPlayer; FLastItem := TMPSong.EmptySong; FOnProcessPlay := processHandler; end; destructor TMusicPlayer.TProcessThread.Destroy; begin FMusicPlayer := nil; inherited; end; procedure TMusicPlayer.TProcessThread.Execute; begin inherited; while Assigned(FMusicPlayer) do begin case FMusicPlayer.PlaybackState of TMPPlaybackState.Playing: ProcessPlay; TMPPlaybackState.Stopped, TMPPlaybackState.Paused, TMPPlaybackState.Interrupted, TMPPlaybackState.SeekingForward, TMPPlaybackState.SeekingBackward: sleep(100); end; end; end; procedure TMusicPlayer.TProcessThread.ProcessPlay; begin if Assigned(FOnProcessPlay) then if FMusicPlayer.Duration > 0 then FOnProcessPlay((FMusicPlayer.Time/FMusicPlayer.Duration) * 100); if FLastItem.Equals(TMPSong.EmptySong) then begin FLastItem := FMusicPlayer.Playlist[FMusicPlayer.CurrentIndex]; end else begin if (FMusicPlayer.IndexOfNowPlayingItem <> -1) and (not FLastItem.Equals(FMusicPlayer.Playlist[FMusicPlayer.IndexOfNowPlayingItem])) then begin FLastItem := FMusicPlayer.Playlist[FMusicPlayer.CurrentIndex]; FMusicPlayer.DoOnSongChange(FMusicPlayer.CurrentIndex); sleep(100); end else begin Sleep(100); end; end; end; {$ENDIF} end.
Unit DataParsers; Interface Uses Classes, Windows, Generics.Collections, IRPMonDll, AbstractRequest; Const DATA_PARSER_INIT_ROUTINE = 'DataParserInit'; IRPMON_DATA_PARSER_VERSION_1 = 1; Type _DP_REQUEST_EXTRA_INFO = Record DriverName : PWideChar; DeviceName : PWideChar; FileName : PWideChar; ProcessName : PWideChar; Format : ERequestLogFormat; end; DP_REQUEST_EXTRA_INFO = _DP_REQUEST_EXTRA_INFO; PDP_REQUEST_EXTRA_INFO = ^DP_REQUEST_EXTRA_INFO; TDataParserParseRoutine = Function (AHeader:PREQUEST_HEADER; Var AExtraInfo:DP_REQUEST_EXTRA_INFO; Var AHandled:ByteBool; Var ANames:PPWideChar; Var AValues:PPWideChar; Var ARowCount:NativeUInt):Cardinal; Cdecl; TDataParserFreeRoutine = Procedure (ANames:PPWideChar; AValues:PPWideChar; ACount:NativeUInt); Cdecl; _IRPMON_DATA_PARSER = Record Version : Cardinal; Size : Cardinal; Name : PWideChar; Description : PWideChar; MajorVersion : Cardinal; MinorVersion : Cardinal; BuildVersion : Cardinal; Priority : Cardinal; ParseRoutine : TDataParserParseRoutine; FreeRoutine : TDataParserFreeRoutine; end; IRPMON_DATA_PARSER = _IRPMON_DATA_PARSER; PIRPMON_DATA_PARSER = ^IRPMON_DATA_PARSER; TDataParserInitRoutine = Function (ARequestedVersion:Cardinal; Var AParser:PIRPMON_DATA_PARSER):Cardinal; Cdecl; TDataParser = Class Private FLibraryHandle : THandle; FLibraryName : WideString; FName : WideString; FDescription : WideString; FParseRoutine : TDataParserParseRoutine; FFreeRoutine : TDataParserFreeRoutine; FPriority : Cardinal; FMajorVersion : Cardinal; FMinorVersion : Cardinal; FBuildNumber : Cardinal; Public Constructor Create(ALibraryHandle:THandle; ALibraryName:WideString; Var ARaw:IRPMON_DATA_PARSER); Reintroduce; Destructor Destroy; Override; Class Function CreateForLibrary(ALibraryName:WideString; Var AError:Cardinal):TDataParser; Class Procedure AddFromDirectory(ADirectory:WideString; AList:TObjectList<TDataParser>); Class Function AddFromFile(AFileName:WideString; AList:TObjectList<TDataParser>):Cardinal; Class Procedure FreeInfo(Var AInfo:IRPMON_DATA_PARSER); Function Parse(AFormat:ERequestLogFormat; ARequest:TGeneralRequest; Var AHandled:ByteBool; ANames:TStrings; AValues:TStrings):Cardinal; Function QueryInfo(Var AInfo:IRPMON_DATA_PARSER):Cardinal; Property Name : WideString Read FName; Property Description : WideString Read FDescription; Property LibraryName : WideString Read FLibraryName; Property Priority : Cardinal Read FPriority; Property MajorVersion : Cardinal Read FMajorVersion; Property MinorVersion : Cardinal Read FMinorVersion; Property BuildNumber : Cardinal Read FBuildNumber; end; Implementation Uses SysUtils; Constructor TDataParser.Create(ALibraryHandle:THandle; ALibraryName:WideString; Var ARaw:IRPMON_DATA_PARSER); begin Inherited Create; FParseRoutine := ARaw.ParseRoutine; FFreeRoutine := ARaw.FreeRoutine; FName := WideCharToString(ARaw.Name); FDescription := WideCharToString(ARaw.Description); FPriority := ARaw.Priority; FMajorVersion := ARaw.MajorVersion; FMinorVersion := ARaw.MinorVersion; FBuildNumber := ARaw.BuildVersion; FLibraryName := ALibraryName; FLibraryHandle := ALibraryHandle; end; Destructor TDataParser.Destroy; begin If FLibraryHandle <> 0 Then FreeLibrary(FLibraryHandle); Inherited Destroy; end; Function TDataParser.Parse(AFormat:ERequestLogFormat; ARequest:TGeneralRequest; Var AHandled:ByteBool; ANames:TStrings; AValues:TStrings):Cardinal; Var I : Integer; _handled : ByteBool; _ns : PPWideChar; _vs : PPWideChar; _rsCount : NativeUInt; n : PPWideChar; v : PPWideChar; ei : DP_REQUEST_EXTRA_INFO; begin AHandled := False; ei.DriverName := PWideChar(ARequest.DriverName); ei.DeviceName := PWideChar(ARequest.DeviceName); ei.FileName := PWideChar(ARequest.FileName); ei.ProcessName := PWideChar(ARequest.ProcessName); ei.Format := AFormat; Result := FParseRoutine(ARequest.Raw, ei, _handled, _ns, _vs, _rsCount); If (Result = 0) And (_handled) Then begin AHandled := True; n := _ns; v := _vs; For I := 0 To _rsCount - 1 Do begin If Assigned(n) Then begin ANames.Add(WideCharToString(n^)); Inc(n); end; AValues.Add(WideCharToString(v^)); Inc(v); end; FFreeRoutine(_ns, _vs, _rsCount); end; end; Function TDataParser.QueryInfo(Var AInfo:IRPMON_DATA_PARSER):Cardinal; begin Result := 0; FillChar(AInfo, SizeOf(AInfo), 0); AInfo.Name := StrAlloc(Length(FName)); If Assigned(AInfo.Name) Then begin StringToWideChar(FName, AInfo.Name, Length(FName) + 1); AInfo.Description := StrAlloc(Length(FDescription)); If Assigned(AInfo.Description) Then begin StringToWideChar(FDescription, AInfo.Description, Length(FDescription) + 1); AInfo.Size := SizeOf(AInfo); AInfo.MajorVersion := FMajorVersion; AInfo.MinorVersion := FMinorVersion; AInfo.BuildVersion := FBuildNumber; AInfo.Priority := FPriority; AInfo.ParseRoutine := FParseRoutine; AInfo.FreeRoutine := FFreeRoutine; end; If Result <> 0 Then StrDispose(AInfo.Name); end Else Result := ERROR_NOT_ENOUGH_MEMORY; end; Class Procedure TDataParser.FreeInfo(Var AInfo:IRPMON_DATA_PARSER); begin If Assigned(AInfo.Description) Then StrDispose(AInfo.Description); If Assigned(AInfo.Name) Then StrDispose(AInfo.Name); end; Class Function TDataParser.CreateForLibrary(ALibraryName:WideString; Var AError:Cardinal):TDataParser; Var p : PIRPMON_DATA_PARSER; initRoutine : TDataParserInitRoutine; lh : THandle; begin p := Nil; Result := Nil; initRoutine := Nil; lh := LoadLibraryExW(PWideChar(ALibraryName), 0, DONT_RESOLVE_DLL_REFERENCES); If lh <> 0 Then begin initRoutine := GetProcAddress(lh, DATA_PARSER_INIT_ROUTINE); FreeLibrary(lh); end; If Assigned(initRoutine) Then begin lh := LoadLibraryW(PWideChar(ALibraryName)); If lh <> 0 Then begin initRoutine := GetProcAddress(lh, DATA_PARSER_INIT_ROUTINE); If Assigned(initRoutine) Then begin AError := initRoutine(IRPMON_DATA_PARSER_VERSION_1, p); If AError = ERROR_SUCCESS Then begin Try Result := TDataParser.Create(lh, ALibraryName, p^); Except Result := Nil; end; HeapFree(GetProcessHeap, 0, p); end; end; end; If Not Assigned(Result) Then FreeLibrary(lh); end; end; Class Procedure TDataParser.AddFromDirectory(ADirectory:WideString; AList:TObjectList<TDataParser>); Var mask : WideString; hSearch : THandle; d : WIN32_FIND_DATAW; dp : TDataParser; e : Cardinal; begin If ADirectory[Length(ADirectory)] = '\' Then Delete(ADirectory, Length(ADirectory), 1); mask := ADirectory + '\*.dll'; hSearch := FIndFirstFileW(PWideChar(mask), d); If hSearch <> INVALID_HANDLE_VALUE THen begin Repeat If ((d.dwFileAttributes And FILE_ATTRIBUTE_DIRECTORY) = 0) Then begin dp := TDataParser.CreateForLibrary(ADirectory + '\' + d.cFileName, e); If Assigned(dp) THen AList.Add(dp); end; Until Not FindNextFileW(hSearch, d); Windows.FindClose(hSearch); end; end; Class Function TDataParser.AddFromFile(AFileName:WideString; AList:TObjectList<TDataParser>):Cardinal; Var dp : TDataParser; err : Cardinal; begin Result := 0; dp := TDataParser.CreateForLibrary(AFileName, err); If Assigned(dp) Then begin Try AList.Add(dp); Except dp.Free; end; end Else Result := err; end; End.
unit GLDAxisFrame; interface uses Classes, Controls, Forms, StdCtrls, GLDTypes; type TGLDAxisFrame = class(TFrame) GB_Axis: TGroupBox; RB_X: TRadioButton; RB_Y: TRadioButton; RB_Z: TRadioButton; procedure AxisChange(Sender: TObject); private FOnAxisChange: TNotifyEvent; function GetAxis: TGLDAxis; procedure SetAxis(Value: TGLDAxis); public constructor Create(AOwner: TComponent); override; property Axis: TGLDAxis read GetAxis write SetAxis; property OnAxisChange: TNotifyEvent read FOnAxisChange write FOnAxisChange; end; implementation {$R *.dfm} constructor TGLDAxisFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FOnAxisChange := nil; end; procedure TGLDAxisFrame.AxisChange(Sender: TObject); begin if Assigned(FOnAxisChange) then FOnAxisChange(Sender); end; function TGLDAxisFrame.GetAxis: TGLDAxis; begin if RB_X.Checked then Result := GLD_AXIS_X else if RB_Y.Checked then Result := GLD_AXIS_Y else if RB_Z.Checked then Result := GLD_AXIS_Z; end; procedure TGLDAxisFrame.SetAxis(Value: TGLDAxis); begin RB_X.Checked := Value = GLD_AXIS_X; RB_Y.Checked := Value = GLD_AXIS_Y; RB_Z.Checked := Value = GLD_AXIS_Z; end; end.
(* Task: given a square with angles at (1,0), (0,1), (-1,0), and (0,-1), determine whether a point belongs to it or not. Solution: rotate the point by 45 degrees and see whether it belongs to the rotated square. The diagonal of the original square (or the side of the rotated one) is sqrt(2). *) program ex3a; type Point = record x: Double; y: Double; end; // Rotate a 'Point' clockwise. function rotateCW(p: Point; angle: Integer): Point; var x, y: Double; begin x := p.x * cos(-angle) - p.y * sin(-angle); y := p.y * cos(-angle) + p.x * sin(-angle); p.x := x; p.y := y; Result := p; end; // Check whether a 'Point' is in bounds or not. function inBounds(p: Point): Boolean; // Half of the diagonal of the original square (or half of the side of the // rotated one). var a: Double; begin a := sqrt(2) / 2; if ((-a <= p.x) and (p.x <= a) and (-a <= p.y) and (p.y <= a)) then Result := True else Result := False; end; procedure inBounds_(p: Point); begin if inBounds(p) then WriteLn('In bounds') else WriteLn('Out of bounds'); end; var p: Point; begin Writeln('Enter two real numbers:'); Write('x: '); Readln(p.x); Write('y: '); Readln(p.y); inBounds_(rotateCW(p, 45)); end.
unit uSistemInfo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TFrmError = class(TForm) btnClose: TButton; memSummary: TMemo; procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } function Start(Value:string):Boolean; end; implementation {$R *.DFM} function TFrmError.Start(Value:string):Boolean; begin memSummary.Clear; memSummary.Lines.Add(Value); memSummary.SelLength := 0; memSummary.SelStart := 0; ShowModal; end; procedure TFrmError.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
unit stmMatBuffer1; interface {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses util1,IPPdefs17; { TmatBuffer implémente une matrice rudimentaire analogue à Tmatrix . Elle ne doit être utilisée que dans les calculs internes. } type TmatBuffer=class tb:pointer; tpNum:typetypeG; istart,iend,jstart,jend:integer; tpSize:integer; Icount,Jcount:integer; constructor create(tp:typetypeG;i1,i2,j1,j2:integer); destructor destroy;override; function getP(i,j:integer):pointer; function stepIPP:integer; function sizeIPP:IPPIsize;overload; function sizeIPP(n1,n2:integer):IPPIsize;overload; function rectIPP(x1,y1,w1,h1:integer):IPPIrect; end; implementation { TmatBuffer } constructor TmatBuffer.create(tp: typetypeG; i1, i2, j1, j2: integer); begin tpNum:=tp; istart:=i1; iend:=i2; jstart:=j1; jend:=j2; Icount:=i2-i1+1; Jcount:=j2-j1+1; tpSize:=tailleTypeG[tpNum]; getmem(tb,tpSize*Icount*Jcount); fillchar(tb^,tpSize*Icount*Jcount,0); end; destructor TmatBuffer.destroy; begin freemem(tb); inherited; end; function TmatBuffer.getP(i, j:integer): pointer; begin result:=@PtabOctet(tb)^[(Jcount*(i-Istart)+j-Jstart)*tpSize]; end; function TmatBuffer.rectIPP(x1, y1, w1, h1: integer): IPPIrect; begin with result do begin x:=y1; y:=x1; width:=h1; height:=w1; end; end; function TmatBuffer.sizeIPP(n1, n2: integer): IPPIsize; begin with result do begin width:=n2; height:=n1; end; end; function TmatBuffer.sizeIPP: IPPIsize; begin result.width:=Jcount; result.height:=Icount; end; function TmatBuffer.stepIPP: integer; begin result:=Jcount*tpSize; end; end.
unit DataSet.Model; interface uses System.SysUtils, Data.DB, FireDac.DApt, FireDac.Comp.Client, DataSet.Types; type TDataSet_Model = class private { Private declarations } FTableName: string; FTableIndex: string; FDTable1: TFDTable; protected function GetDataSet: TDataSet; function GetIsOpen: Boolean; function GetRowCount: Integer; procedure SetTableName(const ATableName: String); procedure SetConnection(AConnection: TFDConnection); procedure SetTableIndex(const ATableIndex: string); public { Public declarations } constructor Create; overload; constructor Create(const ATableName: string; AConnection: TFDConnection = nil); overload; destructor Destroy; override; procedure Open; procedure Close; function GetRows(const AFields: TFieldsToGet): TFieldConverters; procedure AppendRow(const AFields: TFieldConverters); procedure UpdateActiveRow(const AFields: TFieldConverters); procedure Edit; procedure Append; procedure Post; procedure Cancel; procedure Delete; property RowCount: Integer read GetRowCount; property TableIndex: string read FTableIndex write SetTableIndex; property Connection: TFDConnection write SetConnection; property TableName: string read FTableName write SetTableName; property IsOpen: Boolean read GetIsOpen; property DataSet: TDataSet read GetDataSet; end; implementation uses System.IOUtils, Spring, MVVM.Core; { TDataSet_Model } procedure TDataSet_Model.AppendRow(const AFields: TFieldConverters); var I: Integer; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for AppendRow'); FDTable1.Append; try for I := Low(AFields) to High(AFields) do begin FDTable1.FieldByName(AFields[I].FieldName).AssignValue(AFields[I].FieldValue.AsVarRec); end; FDTable1.Post; except on E: Exception do begin FDTable1.Cancel; raise; end; end; end; procedure TDataSet_Model.Cancel; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsEdit, TDataSetState.dsInsert], 'Wrong state for Cancel'); FDTable1.Cancel; end; procedure TDataSet_Model.Close; begin FDTable1.Active := False; end; constructor TDataSet_Model.Create(const ATableName: string; AConnection: TFDConnection); begin Create; if Assigned(AConnection) then FDTable1.Connection := AConnection; TableName := ATableName; end; constructor TDataSet_Model.Create; begin inherited Create; FDTable1 := TFDTable.Create(nil); FDTable1.TableName := ''; end; procedure TDataSet_Model.Delete; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for Delete'); FDTable1.Delete end; destructor TDataSet_Model.Destroy; begin FDTable1.Free; inherited; end; procedure TDataSet_Model.Edit; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsEdit, TDataSetState.dsInsert], 'Wrong state for Edit'); FDTable1.Edit; end; function TDataSet_Model.GetDataSet: TDataSet; begin Result := FDTable1; end; function TDataSet_Model.GetIsOpen: Boolean; begin Result := FDTable1.Active end; function TDataSet_Model.GetRowCount: Integer; begin Result := FDTable1.RecordCount; end; function TDataSet_Model.GetRows(const AFields: TFieldsToGet): TFieldConverters; var I: Integer; LObject: TObject; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for GetRows'); for I := Low(AFields) to High(AFields) do begin case FDTable1.FieldByName(AFields[I].FieldName).DataType of ftGuid: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsGuid); ftString, ftFixedChar, ftWideString, ftFixedWideChar: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsString); ftAutoInc, ftInteger: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftLongWord: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsLongWord); ftShortint: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftByte: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftSmallInt: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftWord: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsInteger); ftBoolean: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsBoolean); ftFloat, ftCurrency: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsFloat); ftMemo, ftWideMemo: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsWideString); ftBlob: begin if AFields[I].isBitmap then begin LObject := MVVMCore.PlatformServices.LoadBitmap(DataSet.FieldByName(AFields[I].FieldName).AsBytes); Result.AddData(AFields[I].FieldName, LObject); end else Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsWideString); end; ftInterface: begin // end; ftIDispatch: begin // end; ftGraphic: // por validar begin LObject := MVVMCore.PlatformServices.LoadBitmap(DataSet.FieldByName(AFields[I].FieldName).AsBytes); Result.AddData(AFields[I].FieldName, LObject); end; ftVariant: Result.AddData(AFields[I].FieldName, TValue.FromVariant(FDTable1.FieldByName(AFields[I].FieldName).AsVariant)); ftDate, ftTime, ftDateTime: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsDateTime); ftFMTBCD: begin // end; ftBCD: begin // end; ftBytes, ftVarBytes: begin // end; ftLargeInt: Result.AddData(AFields[I].FieldName, FDTable1.FieldByName(AFields[I].FieldName).AsLargeInt); end; end; end; procedure TDataSet_Model.Open; begin FDTable1.Active := True; end; procedure TDataSet_Model.Post; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsEdit, TDataSetState.dsInsert], 'Wrong state for post'); FDTable1.Post; end; procedure TDataSet_Model.SetConnection(AConnection: TFDConnection); begin FDTable1.Connection := AConnection; end; procedure TDataSet_Model.SetTableIndex(const ATableIndex: string); begin FDTable1.IndexFieldNames := ATableIndex; end; procedure TDataSet_Model.SetTableName(const ATableName: String); var LWasOpen: Boolean; begin if FTableName <> ATableName then begin LWasOpen := IsOpen; if LWasOpen then Close; FTableName := ATableName; FDTable1.TableName := FTableName; if LWasOpen then Open; end; end; procedure TDataSet_Model.UpdateActiveRow(const AFields: TFieldConverters); var I: Integer; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for UpdateActiveRow'); FDTable1.Edit; try for I := Low(AFields) to High(AFields) do begin FDTable1.FieldByName(AFields[I].FieldName).AssignValue(AFields[I].FieldValue.AsVarRec); end; FDTable1.Post; except on E: Exception do begin FDTable1.Cancel; raise; end; end; end; procedure TDataSet_Model.Append; begin Spring.Guard.CheckTrue(FDTable1.State in [TDataSetState.dsBrowse], 'Wrong state for Append'); FDTable1.Append end; end.
{Objectif : 8- algo + pascal : Le jeu de loie le joueur est caractériser par un nombre nommé "place" compris entre 0 et 66 qui situe sa position sur le jeu de loie sachant qu'après le jet des 2 dés on applique les règles suivantes : on avance du nombre de case i ndiqué par la somme des dés. SI on arrive juste sur la case 66 le jeu est terminé sinon on recule du nombre de points sup a 66. Une oie toute les 9 cases (9 - 18 - 27 ...) sauf en 63 double le déplacement (Fonction entier aléatoire : RANDOM (regarder dans documentation pascal)) une tête de mort à la case 58 renvoie à la position de depart (case 0) le jeu se joue SEUL. On s'éfforceras d'utiliser au maximum l'emploie de constante Vous devez produire un algorithme et un code lisible et clair (avec espaces, commentaires). il est conseillé d'utiliser l'opérateur MODULO pour tester si une case est un multiple de 9. ALGORITHME : JeuDELoie //BUT Jeu de L'Oie solo //ENTREE le joueur appuie sur entrée //SORTIE Affichage du placement de la l'oie et affichage du nombre de cases avancer CONST depart <- 0 fin <- 66 double <- 9 nondouble <- 63 mort <- 58 alea <- 11 VAR place,des : ENTIER DEBUT place <- 0 des <- 0 REPETER ECRIRE "Vous etes sur la case ",place," Veuillez lancer votre des en appuyant sur Entrer" //On dit a l'utilisateur comment avancer et sur qu'elle case il se trouve actuellement. LIRE des <- (ALEATOIRE(alea)+2) //On lance un dés à 11 faces (de 2 à 12 pour correspondre aux deux dés a 6 faces demandé) SI (((place + des) MOD double = 0) ET ((place + des) <> nondouble)) ALORS //Si l'emplacement ou le joueur devrais être est un multiple de 9 différent de 63 le joueurs vois ses points doublés ECRIRE "Bonus x2 ! : Vous avancer de ",des," cases, X2 donc de ",(des * 2)," cases et vous vous trouver donc sur la case ",((place) + (des * 2))) place <- ((place) + (des*2)) SINON ECRIRE "Vous avancer de ",(des)," cases et vous vous trouver donc sur la case ",(place + des) //Sinon il avance simplement du nombre de cases normal (que le dés indiquent) place <- (place + des) FINSI SI ((place) = (mort)) ALORS //Si le joueur arrive sur la case 58 il retourne à la case depart ECRIRE "Malus tete de mort ! : Vous retournez a la case depart" place <- depart FINSI SI (place > fin) ALORS //Si sa place actuelle + les points acquis le déplace sur un emplacement plus grand que 66 on lui indique que ses points sont trop élevés ECRIRE "Votre place est plus eleve que 66 donc vous reculez de : ",(place - fin)," cases en partant de 66" //On lui indique donc de combien de cases il recule et par la boucle on lui indique sa nouvelle position. place <- (fin - (place - fin)) FINSI JUSQUA (place = fin) //La partie se termine donc quand le joueur atteint 66 points ECRIRE "Fin de la partie." FIN } PROGRAM JeuDELoie; USES crt; CONST depart = 0; fin = 66; double = 9; nondouble = 63; mort = 58; alea = 11; VAR place,des :INTEGER; BEGIN clrscr; place := 0; des := 0; REPEAT WRITELN('Vous etes sur la case ',place,' Veuillez lancer votre des en appuyant sur Entrer'); READLN; RANDOMIZE; des := (RANDOM(alea)+2); clrscr; IF (((place + des) MOD double = 0) AND ((place + des) <> nondouble)) THEN BEGIN WRITELN('Bonus x2 ! : Vous avancer de ',des,' cases, X2 donc de ',(des * 2),' cases et vous vous trouver donc sur la case ',((place) + (des * 2))); place := ((place) + (des*2)) END ELSE BEGIN WRITELN('Vous avancer de ',(des),' cases et vous vous trouver donc sur la case ',(place + des)); place := (place + des); END; IF ((place) = (mort)) THEN BEGIN WRITELN('Malus tete de mort ! : Vous retournez a la case depart'); place := depart; END; IF (place > fin) THEN BEGIN WRITELN('Votre place est plus eleve que 66 donc vous reculez de : ',(place - fin),' cases en partant de 66'); place := (fin - (place - fin)); END; UNTIL (place = fin); WRITELN('Fin de la partie.'); readln; END.
unit TPedido; interface {$IF VER330} REST.JSON.Types; {$ENDIF} {$M+} type TPedidoJson = class private FnomeSepardor: String; Fcodigo: String; [JSONMarshalledAttribute(false)] FvalorTotal: Double; procedure Setcodigo(const Value: String); procedure SetnomeSepardor(const Value: String); procedure SetvalorTotal(const Value: Double); public published property codigo: String read Fcodigo write Setcodigo; property nomeSepardor: String read FnomeSepardor write SetnomeSepardor; property valorTotal: Double read FvalorTotal write SetvalorTotal; end; implementation { TPedidoJson } procedure TPedidoJson.Setcodigo(const Value: String); begin Fcodigo := Value; end; procedure TPedidoJson.SetnomeSepardor(const Value: String); begin FnomeSepardor := Value; end; procedure TPedidoJson.SetvalorTotal(const Value: Double); begin FvalorTotal := Value; end; end.
// Fast Fourier Transform demo program {$APPTYPE CONSOLE} program FFT; const DataLength = 256; type Complex = record Re, Im: Real; end; TData = array [0..DataLength - 1] of Real; TComplexData = array [0..DataLength - 1] of Complex; PData = ^TData; var x, S: TData; Twiddle: TComplexData; function CAdd(var a, b: Complex): Complex; begin Result.Re := a.Re + b.Re; Result.Im := a.Im + b.Im; end; function CSub(var a, b: Complex): Complex; begin Result.Re := a.Re - b.Re; Result.Im := a.Im - b.Im; end; function CMul(var a, b: Complex): Complex; begin Result.Re := a.Re * b.Re - a.Im * b.Im; Result.Im := a.Re * b.Im + a.Im * b.Re; end; function CAbs(var a: Complex): Real; begin CAbs := sqrt(a.Re * a.Re + a.Im * a.Im); end; function GetFFT(var x: TData; Depth: Integer): TComplexData; var k, HalfLen, Step: Integer; FFTEven, FFTOdd: TComplexData; FFTOddTwiddled: Complex; begin HalfLen := DataLength shr (Depth + 1); Step := 1 shl Depth; if HalfLen = 0 then begin Result[0].Re := x[0]; Result[0].Im := 0; end else begin FFTEven := GetFFT(x, Depth + 1); FFTOdd := GetFFT(PData(@x[Step])^, Depth + 1); for k := 0 to HalfLen - 1 do begin FFTOddTwiddled := CMul(FFTOdd[k], Twiddle[k * Step]); Result[k] := CAdd(FFTEven[k], FFTOddTwiddled); Result[k + HalfLen] := CSub(FFTEven[k], FFTOddTwiddled); end; // for end; // else end; function Spectrum(var x: TData): TData; var FFT: TComplexData; i: Integer; begin for i := 0 to DataLength - 1 do begin Twiddle[i].Re := cos(2 * Pi * i / DataLength); Twiddle[i].Im := -sin(2 * Pi * i / DataLength); end; FFT := GetFFT(x, 0); for i := 0 to DataLength - 1 do Result[i] := CAbs(FFT[i]); end; var Mag, Period: array [0..4] of Real; Phase: Real; i, j: Integer; begin Randomize; // Four random sinusoids and a constant bias for j := 0 to 4 do begin Mag[j] := (Random - 0.5) * 100; Period[j] := 2 + abs(Random - 0.5) * 40; end; for i := 0 to DataLength - 1 do begin Phase := 2 * Pi * i; x[i] := Mag[0] / 2; for j := 1 to 4 do x[i] := x[i] + Mag[j] * sin(Phase / Period[j]); end; // for // FFT S := Spectrum(x); for i := 0 to DataLength shr 1 - 1 do WriteLn('Freq ', i: 5, ' Mag ', S[i] * 2 / DataLength: 10: 4); ReadLn; end.
unit uptext; { Insert and translate uptext } interface procedure initUptext; procedure clearUptext; function uptextLineNo(voice: integer): integer; procedure setUptextLineNo(voice, lno: integer); procedure addUptext(voice: integer; var no_uptext: boolean; var pretex: string); implementation uses globals, strings, mtxline, utility; type uptext_info = record uptext, uptext_adjust, uptext_lcz: integer; uptext_font: string; end; var U: array[voice_index] of uptext_info; function uptextLineNo(voice: integer): integer; begin uptextLineNo := U[voice].uptext; end; procedure setUptextLineNo(voice, lno: integer); begin U[voice].uptext := lno; end; procedure clearUptext; var voice: voice_index; begin for voice:=1 to nvoices do U[voice].uptext:=0; end; procedure initUptext; var voice: voice_index; begin for voice:=1 to nvoices do with U[voice] do begin uptext_adjust:=0; uptext_lcz:=3; uptext_font:=''; end; end; procedure textTranslate(var uptext, font: string); var k: integer; begin if uptext='' then exit; repeat k := pos1('%',uptext); if k>0 then uptext:= substr(uptext,1,k-1)+'{\mtxFlat}'+substr(uptext,k+1,length(uptext)-k); until k=0; repeat k := pos1('#',uptext); if k>0 then uptext:= substr(uptext,1,k-1)+'{\mtxSharp}'+substr(uptext,k+1,length(uptext)-k); until k=0; case uptext[1] of '<': if uptext='<' then uptext:='\mtxIcresc' else if uptext='<.' then uptext:='\mtxTcresc' else begin predelete(uptext,1); uptext:='\mtxCresc{'+uptext+'}' end; '>': if uptext='>' then uptext:='\mtxIdecresc' else if uptext='>.' then uptext:='\mtxTdecresc' else begin predelete(uptext,1); uptext:='\mtxDecresc{'+uptext+'}' end; else for k:=1 to length(uptext) do if pos1(uptext[k],'mpfzrs~')=0 then exit; end; font:='\mtxPF'; end; procedure addUptext(voice: integer; var no_uptext: boolean; var pretex: string); var w, font: string; adj: integer; const default = 10; under = -14; lcz: string[3] = 'lcz'; procedure adjustUptext; var letter: char; force: boolean; begin delete1(w,1); force:=false; while w<>'' do with U[voice] do begin letter:=w[1]; delete1(w,1); with U[voice] do case letter of '<': if uptext_lcz>1 then dec(uptext_lcz); '>': if uptext_lcz<3 then inc(uptext_lcz); '^': uptext_adjust:=0; 'v': uptext_adjust:=under; '=': force:=true; '+','-': begin if w<>'' then getNum(w,adj) else adj:=0; if letter = '-' then adj := -adj; if force then uptext_adjust := adj else inc(uptext_adjust,adj); w:=''; end; else error3(voice,'Unknown uptext adjustment'); end; end; w:='!'; end; begin with U[voice] do begin if uptext=0 then no_uptext := true; if no_uptext then exit; repeat w := GetNextWord(P[uptext],blank,dummy); if (w=barsym) or (w='') then no_uptext:=true; if (w=tilde) or no_uptext then exit; if w[1]='!' then begin uptext_font:=w; uptext_font[1]:='\'; end; if w[1]='@' then adjustUptext; until w[1]<>'!'; { ! is a kludge, will get me in trouble later } font:=uptext_font; textTranslate(w,font); if font<>'' then w:=font+'{'+w+'}'; case lcz[uptext_lcz] of 'l': w:='\mtxLchar{' + toString(default+uptext_adjust) + '}{' + w + '}'; 'c': w:='\mtxCchar{' + toString(default+uptext_adjust) + '}{' + w + '}'; 'z': w:='\mtxZchar{' + toString(default+uptext_adjust) + '}{' + w + '}'; end; pretex:=pretex+w; end; end; end.
unit debugger; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, Windows, Forms, svm_mem; type TInstructionPointer = cardinal; TMemory = array of pointer; PMemory = ^TMemory; TByteArr = array of byte; PByteArr = ^TByteArr; TConstSection = object constants: array of variant; end; PConstSection = ^TConstSection; PImportSection = pointer; TCallBackStack = object items: array of TInstructionPointer; end; PCallBackStack = ^TCallBackStack; TTRBlock = record CatchPoint, EndPoint: TInstructionPointer; end; PTRBlock = ^TTRBlock; TTRBlocks = object trblocks: array of TTRBlock; end; PTRBlocks = ^TTRBlocks; TGrabber = object tasks: array of pointer; end; PGrabber = ^TGrabber; TStack = object public items: array of pointer; procedure push(p: pointer); function peek: pointer; procedure pop; function popv: pointer; procedure swp; end; PStack = ^TStack; TSVM = object mainclasspath: string; mem: PMemory; stack: TStack; cbstack: TCallBackStack; bytes: PByteArr; ip, end_ip: TInstructionPointer; grabber: TGrabber; consts: PConstSection; extern_methods: PImportSection; try_blocks: TTRBlocks; end; PSVM = ^TSVM; type THelpThread = class(TThread) public constructor Create; destructor Destroy; override; procedure Execute; override; end; function SVM_Create: PSVM; stdcall; external 'svmlib.dll' Name '_SVM_CREATE'; procedure SVM_Free(SVM: PSVM); stdcall; external 'svmlib.dll' Name '_SVM_FREE'; procedure SVM_SetDbgCallBack(SVM: PSVM; DbgCB: Pointer); stdcall; external 'svmlib.dll' Name '_SVM_DEBUGCALLBACK'; procedure SVM_RegAPI(SVM: PSVM; ExtFunc: Pointer); stdcall; external 'svmlib.dll' Name '_SVM_REGAPI'; procedure SVM_LoadExeFromFile(SVM: PSVM; MainClassPath: PString); stdcall; external 'svmlib.dll' Name '_SVM_LOADEXEFROMFILE'; procedure SVM_Run(SVM: PSVM); stdcall; external 'svmlib.dll' Name '_SVM_RUN'; procedure SVM_CheckErr(SVM: PSVM; E: Exception); stdcall; external 'svmlib.dll' Name '_SVM_CHECKERR'; procedure SVM_Continue(SVM: PSVM); stdcall; external 'svmlib.dll' Name '_SVM_CONTINUE'; procedure DebugFile(Form: TForm; svmexe, debuginfo: string); var DebuggingInProcess: boolean = False; ExecutionBreaked: boolean = False; Frm: TForm; EnableDebugInfoUsing: boolean = False; DebugInfoVars: TStringList; DbgStopIt: boolean = False; HelpThread: THelpThread; codefile: string; codeline: cardinal; implementation uses MainForm; {** Stack **} procedure TStack.push(p: pointer); begin SetLength(Self.Items, Length(Self.Items) + 1); Self.Items[Length(Self.Items) - 1] := p; end; function TStack.peek: pointer; begin Result := Self.Items[Length(Self.Items) - 1]; end; procedure TStack.pop; begin SetLength(Self.Items, Length(Self.Items) - 1); end; function TStack.popv: pointer; begin Result := Self.Items[Length(Self.Items) - 1]; SetLength(Self.Items, Length(Self.Items) - 1); end; procedure TStack.swp; var p: Pointer; begin p := Self.Items[Length(Self.Items) - 2]; Self.Items[Length(Self.Items) - 2] := Self.Items[Length(Self.Items) - 1]; Self.Items[Length(Self.Items) - 1] := p; end; function FrmStrWidth(s: string; nw: cardinal): string; begin nw := nw - Length(s); if nw < 0 then s := copy(s, 1, nw - 3) + '...' else while nw > 0 do begin s := s + ' '; Dec(nw); end; Result := s; end; {** Debugger **} constructor THelpThread.Create; begin FreeOnTerminate := False; inherited Create(False); end; destructor THelpThread.Destroy; begin inherited Destroy; end; procedure THelpThread.Execute; begin while not Terminated do begin Application.ProcessMessages; Sleep(1); end; end; procedure BreakPointProc(vm: PSVM); cdecl; var c: cardinal; s, bf: string; begin try while DbgStopIt do begin Application.ProcessMessages; Sleep(1); end; if not EnableDebugInfoUsing then begin DebugInfoVars.Clear; c := Length(vm^.mem^); while c > 0 do begin DebugInfoVars.Insert(0, '#' + IntToStr(c)); Dec(c); end; end; codeline := TSVMMem(vm^.stack.popv).GetW; codefile := TSVMMem(vm^.stack.popv).GetS; TMainFrm(Frm).DebuggerFrame1.DbgVarsLB.Items.BeginUpdate; TMainFrm(Frm).DebuggerFrame1.DbgVarsLB.Items.Clear; TMainFrm(Frm).DebuggerFrame1.DbgVarsLB.Items.Add( 'Full name / Num.: Addr: Value:' ); c := 0; while c < Length(vm^.mem^) do begin s := FrmStrWidth(DebugInfoVars[c], 32) + ' '; if cardinal(vm^.mem^[c]) <> 0 then s := s + '0x' + IntToHex(cardinal(vm^.mem^[c]), 8) + ' ' else s := s + '<null> '; try bf := TSVMMem(vm^.mem^[c]).GetS; except bf := '?'; end; s := s + bf; TMainFrm(Frm).DebuggerFrame1.DbgVarsLB.Items.Add(s); Inc(c); end; TMainFrm(Frm).DebuggerFrame1.DbgVarsLB.Items.EndUpdate; TMainFrm(Frm).DebuggerFrame1.DbgVarsLB.Update; TMainFrm(Frm).DebuggerFrame1.DbgStackLB.Items.BeginUpdate; TMainFrm(Frm).DebuggerFrame1.DbgStackLB.Items.Clear; TMainFrm(Frm).DebuggerFrame1.DbgStackLB.Items.Add( 'Num: Addr: Value:' ); c := 0; while c < Length(vm^.stack.items) do begin s := FrmStrWidth(IntToStr(c) + '.', 6) + '0x' + IntToHex(cardinal(vm^.stack.items[c]), 8) + ' '; try bf := TSVMMem(vm^.stack.items[c]).GetS; except bf := '?'; end; s := s + bf; TMainFrm(Frm).DebuggerFrame1.DbgStackLB.Items.Add(s); Inc(c); end; TMainFrm(Frm).DebuggerFrame1.DbgStackLB.Items.EndUpdate; TMainFrm(Frm).DebuggerFrame1.DbgStackLB.Update; with TMainFrm(Frm).DebuggerFrame1 do begin Label1.Caption := 'CIP: 0x' + IntToHex(vm^.ip, 8) + '.'; Label2.Caption := 'CIA: 0x' + IntToHex(cardinal(vm^.bytes), 8) + ' + 0x' + IntToHex(vm^.ip, 8) + '.'; Label3.Caption := 'CIV: 0x' + IntToHex(PByte(cardinal(vm^.bytes) + vm^.ip)^, 2) + '.'; Label6.Caption := 'Table: ' + IntToStr(Length(vm^.mem^)) + ' bl.'; Label4.Caption := 'Stack: ' + IntToStr(Length(vm^.stack.items)) + ' bl.'; Label5.Caption := 'CB-Stack: ' + IntToStr(Length(vm^.cbstack.items)) + ' jumps.'; Label8.Caption := 'GC-Stack: ' + IntToStr(Length(vm^.grabber.tasks)) + ' bl.'; Label9.Caption := 'Thread ID: ' + IntToStr(GetCurrentThreadId) + '.'; end; Application.ProcessMessages; finally end; end; procedure DebugFile(Form: TForm; svmexe, debuginfo: string); var vm: PSVM; s: string; c, x: cardinal; fs: TFileStream; ExceptFlag: boolean; begin TMainFrm(Form).DebuggerPanel.Width := 385; Frm := Form; if DebuggingInProcess then begin MessageBox(0, 'The debugger already working!', 'Mash debugger error!', MB_OK + MB_ICONERROR); Exit; end; if not FileExists(svmexe) then begin MessageBox(0, 'File for debugging does not exists!', 'Mash debugger error!', MB_OK + MB_ICONERROR); Exit; end; EnableDebugInfoUsing := False; if FileExists(debuginfo) then EnableDebugInfoUsing := True else MessageBox(0, 'File with debugging information does not exists!'#13#10'Debugger should be launched without it!', 'Mash debugger warning!', MB_OK + MB_ICONWARNING); if EnableDebugInfoUsing then begin DebugInfoVars := TStringList.Create; fs := TFileStream.Create(debuginfo, fmOpenRead); fs.Read(c, sizeof(c)); while c > 0 do begin fs.Read(x, sizeof(x)); SetLength(s, x); fs.Read(s[1], x); DebugInfoVars.Add(s); Dec(c); end; FreeAndNil(fs); end; SetErrorMode(SEM_FAILCRITICALERRORS); DebuggingInProcess := True; try vm := SVM_Create; SVM_SetDbgCallBack(vm, @BreakPointProc); SVM_LoadExeFromFile(vm, @svmexe); HelpThread := THelpThread.Create; AllocConsole; SetConsoleTitle('Mash IDE debugger std I/O thread.'); try SVM_Run(vm); except on E: Exception do begin if E.ClassName <> 'EAccessViolation' then case MessageBox(0, PChar('Exception catched!' + sLineBreak + sLineBreak + 'Exception type: ' + E.ClassName + '.' + sLineBreak + 'Exception message: ' + E.Message + '.' + sLineBreak + sLineBreak + 'Last successfully debugged:' + sLineBreak + '- Code file: "' + codefile + '".' + sLineBreak + '- Line: ' + IntToStr(codeline) + '.' + sLineBreak + sLineBreak + 'Handle exception and resume code execution?'), 'Mash IDE debugger', MB_YESNO) of idYes: ExceptFlag := True; idNo: ExceptFlag := False; end; while ExceptFlag do begin try SVM_Continue(vm); ExceptFlag := False; except on E: Exception do if E.ClassName <> 'EAccessViolation' then case MessageBox(0, PChar('Exception catched!' + sLineBreak + sLineBreak + 'Exception type: ' + E.ClassName + '.' + sLineBreak + 'Exception message: ' + E.Message + '.' + sLineBreak + sLineBreak + 'Last successfully debugged:' + sLineBreak + '- Code file: "' + codefile + '".' + sLineBreak + '- Line: ' + IntToStr(codeline) + '.' + sLineBreak + sLineBreak + 'Handle exception and resume code execution?'), 'Mash IDE debugger', MB_YESNO) of idYes: ExceptFlag := True; idNo: ExceptFlag := False; end; end; end; end; end; FreeConsole; FreeAndNil(HelpThread); //SVM_Free(vm); finally SVM_Free(vm); end; DebuggingInProcess := False; end; end.
unit uComments_AE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMemo, StdCtrls, cxControls, cxGroupBox, cxButtons, cnConsts; type Tfrm_comments_ae = class(TForm) OkButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; Comment_label: TLabel; Memo1: TcxMemo; procedure CancelButtonClick(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure FormIniLanguage; private { Private declarations } public PLanguageIndex : Byte; constructor Create(AOwner:TComponent; LanguageIndex : byte);reintroduce; end; var frm_comments_ae: Tfrm_comments_ae; implementation {$R *.dfm} constructor Tfrm_comments_ae.Create(AOwner:TComponent; LanguageIndex : byte); begin Screen.Cursor:=crHourGlass; inherited Create(AOwner); PLanguageIndex:= LanguageIndex; FormIniLanguage(); Screen.Cursor:=crDefault; end; procedure Tfrm_comments_ae.FormIniLanguage; begin OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex]; CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex]; end; procedure Tfrm_comments_ae.CancelButtonClick(Sender: TObject); begin ModalResult:=mrCancel; end; procedure Tfrm_comments_ae.OkButtonClick(Sender: TObject); begin ModalResult:=mrOk; end; end.
unit uCreateFile; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, Buttons, ExtCtrls, StdCtrls, Grids, PaiDeForms, Db, DBTables, PowerADOQuery, Mask, ADODb, siComp, siLangRT, siDialog, LblEffct; type TFrmCreateFile = class(TFrmParentForms) Panel1: TPanel; Panel2: TPanel; EspacamentoInferior: TPanel; Panel3: TPanel; LbTotal: TLabel; Label2: TLabel; SbMoveDates: TSpeedButton; SbOpen: TSpeedButton; LbPath: TLabel; Label1: TLabel; PanelPO: TPanel; Label3: TLabel; IDVendor: TLabel; LbVendorName: TLabel; PBar: TProgressBar; StringGrid1: TStringGrid; OD: TsiOpenDialog; btClose: TButton; procedure FormCreate(Sender: TObject); procedure SbOpenClick(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure SbMoveDatesClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } Lista : TStringList; sModel, sDesc, sCost : String; function RetirarErro(sTexto:String):String; procedure PreencherGrid; public { Public declarations } procedure Start(Query,SaveQuery:TPowerADOQuery; QueryComper:TADOQuery); end; var FrmCreateFile: TFrmCreateFile; sFileName : string; quTemp, quSave : TPowerADOQuery; quComper : TADOQuery; implementation uses uFchCotation, uMsgBox, uMsgConstant, uDMGlobal, uDM; {$R *.DFM} function TFrmCreateFile.RetirarErro(sTexto:String):String; var x,y:integer; begin x := 0; y := Length(sTexto); While x <= y do begin If not (sTexto[x] in ['0'..'9','.',',']) then Delete(sTexto,x,1); inc(x); end; Result := sTexto; end; procedure TFrmCreateFile.Start(Query,SaveQuery:TPowerADOQuery; QueryComper:TADOQuery); begin quTemp := Query; quSave := SaveQuery; quTemp.Open; quComper := QueryComper; end; procedure TFrmCreateFile.FormCreate(Sender: TObject); begin inherited; Case DMGlobal.IDLanguage of LANG_ENGLISH : begin sModel := 'Model'; sDesc := 'Description'; sCost := 'Cost Price'; end; LANG_PORTUGUESE : begin sModel := 'Modelo'; sDesc := 'Descrição'; sCost := 'Preço de Custo'; end; LANG_SPANISH : begin sModel := 'Modelo'; sDesc := 'Descripción'; sCost := 'Precio de Costo'; end; end; LbPath.Caption := ''; Label1.Visible := False; Lista := TStringList.Create; StringGrid1.Cells[0,0] := sModel; StringGrid1.Cells[1,0] := sDesc; StringGrid1.Cells[2,0] := sCost; end; procedure TFrmCreateFile.SbOpenClick(Sender: TObject); begin OD.Execute; If OD.FileName <> '' then begin Lista.Clear; Lista.LoadFromFile(OD.FileName); PreencherGrid; LbPath.Caption := OD.FileName; Label1.Visible := true; //Botoes SbMoveDates.Enabled := True; PanelPO.Visible := True; end; end; procedure TFrmCreateFile.btCloseClick(Sender: TObject); begin Close; end; procedure TFrmCreateFile.SbMoveDatesClick(Sender: TObject); var x,y : integer; begin //Passa os Params quSave.Parameters.ParamByName('IDCotacao').Value := quTemp.Fields[2].AsInteger; quSave.Parameters.ParamByName('IDFornecedor').Value := StrToInt(IDVendor.Caption); //Abro a query quSave.Open; If quSave.RecordCount = 0 then begin MsgBox(MSG_CRT_QUOTE, vbCritical + vbOkOnly); exit; end; //ProccessBar PBar.Visible := True; PBar.Max := quSave.RecordCount; //First Register quComper.Open; Try qucomper.DisableControls; quSave.DisableControls; x := 1; While x <= quSave.RecordCount do begin //Copiar da Celula y := 1; quSave.First; quComper.First; While y <= quSave.RecordCount do begin If Trim(quComper.FieldByName('Model').AsString) = Trim(StringGrid1.Cells[0,x]) then begin quSave.Edit; try DecimalSeparator := '.'; quSave.FieldByName('Cost').AsCurrency := StrToCurr(RetirarErro(Trim(StringGrid1.Cells[2,x]))); except try DecimalSeparator := ','; quSave.FieldByName('Cost').AsCurrency := StrToCurr(RetirarErro(Trim(StringGrid1.Cells[2,x]))); except MsgBox('erro', vbCritical + vbOkOnly); exit; end; end; quSave.Post; Break; end; inc(y); quComper.Next; quSave.Next; end; inc(x); PBar.StepBy(x); end; Finally //Botoes qucomper.EnableControls; quSave.EnableControls; Close; end; end; procedure TFrmCreateFile.FormClose(Sender: TObject; var Action: TCloseAction); begin quTemp.Close; quSave.Close; Lista.Free; end; procedure TFrmCreateFile.PreencherGrid; Var sCampo, sLines: String; x, y : integer; begin sLines := Lista.Text; y := 1; quComper.Open; StringGrid1.RowCount := quComper.RecordCount+1; //Nao esta pegando todos os regitros While y <= quComper.RecordCount do begin x := Pos('->', sLines)+2; If x = 2 then Break; sLines := Copy(sLines,x,length(sLines)); StringGrid1.Cells[0,y] := Trim(Copy(sLines,0,(Pos('|', sLines)-1))); sLines := Copy(sLines,(Pos('|', sLines)+1),length(sLines)); x := Pos('|', sLines); StringGrid1.Cells[1,y] := Trim(Copy(sLines,0,(Pos('|', sLines)-1))); sLines := Copy(sLines,(Pos('|', sLines)+1),length(sLines)); x := Pos('|', sLines); StringGrid1.Cells[2,y] := RetirarErro(Trim(Copy(sLines,0,(Pos('|', sLines)-1)))); sLines := Copy(sLines,(Pos('|', sLines)+1),length(sLines)); inc(y); end; quComper.Close; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Nodes are used to describe lines, polygons + more. } unit VXS.Nodes; interface uses System.Classes, System.SysUtils, System.Math, VXS.OpenGL, VXS.VectorGeometry, VXS.Context, VXS.BaseClasses, VXS.Coordinates, VXS.Spline, VXS.VectorTypes, VXS.XOpenGL; {$I VXScene.inc} type TVXNode = class(TCollectionItem) private FCoords: TVector; FTagObject: TObject; procedure SetAsVector(const Value: TVector); procedure SetAsAffineVector(const Value: TAffineVector); function GetAsAffineVector: TAffineVector; procedure SetCoordinate(AIndex: Integer; AValue: Single); function GetCoordinate(const Index: Integer): Single; protected function StoreCoordinate(AIndex: Integer): Boolean; function GetDisplayName: string; override; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function AsAddress: PGLFloat; { The coordinates viewed as a vector. Assigning a value to this property will trigger notification events, if you don't want so, use DirectVector instead. } property AsVector: TVector read FCoords write SetAsVector; { The coordinates viewed as an affine vector. Assigning a value to this property will trigger notification events, if you don't want so, use DirectVector instead. The W component is automatically adjustes depending on style. } property AsAffineVector: TAffineVector read GetAsAffineVector write SetAsAffineVector; property W: Single index 3 read GetCoordinate write SetCoordinate stored StoreCoordinate; property TagObject: TObject read FTagObject write FTagObject; published property X: Single index 0 read GetCoordinate write SetCoordinate stored StoreCoordinate; property Y: Single index 1 read GetCoordinate write SetCoordinate stored StoreCoordinate; property Z: Single index 2 read GetCoordinate write SetCoordinate stored StoreCoordinate; end; TVXNodes = class(TOwnedCollection) protected procedure SetItems(Index: Integer; const Val: TVXNode); function GetItems(Index: Integer): TVXNode; procedure Update(Item: TCollectionItem); override; public constructor Create(AOwner: TPersistent; AItemClass: TCollectionItemClass = nil); function CreateCopy(AOwner: TPersistent): TVXNodes; function Add: TVXNode; function FindItemID(ID: Integer): TVXNode; property Items[index: Integer]: TVXNode read GetItems write SetItems; default; function First: TVXNode; function Last: TVXNode; procedure NotifyChange; virtual; procedure EndUpdate; override; procedure AddNode(const Coords: TVXCustomCoordinates); overload; procedure AddNode(const X, Y, Z: Single); overload; procedure AddNode(const Value: TVector); overload; procedure AddNode(const Value: TAffineVector); overload; procedure AddXYArc(XRadius, YRadius: Single; StartAngle, StopAngle: Single; NbSegments: Integer; const Center: TAffineVector); // Calculates and returns the barycenter of the nodes function Barycenter: TAffineVector; { Computes normal based on the 1st three nodes. Returns NullVector if there are less than 3 nodes. } function Normal: TAffineVector; // Returns normalized vector Nodes[i+1]-Nodes[i] function Vector(I: Integer): TAffineVector; { Calculates the extents of the nodes (min-max for all coordinates). The returned values are also the two corners of the axis-aligned bounding box. } procedure GetExtents(var Min, Max: TAffineVector); // Translate all nodes procedure Translate(const Tv: TAffineVector); // Scale all node coordinates procedure Scale(const Fv: TAffineVector); overload; // Scale all node coordinates procedure Scale(F: Single); overload; // Rotate nodes around Y axis by the given angle (degrees) procedure RotateAroundX(Angle: Single); // Rotate nodes around Y axis by the given angle (degrees) procedure RotateAroundY(Angle: Single); // Rotate nodes around Y axis by the given angle (degrees) procedure RotateAroundZ(Angle: Single); procedure RenderTesselatedPolygon(ATextured: Boolean; ANormal: PAffineVector = nil; ASplineDivisions: Integer = 1; AInvertNormals: Boolean = False); function CreateNewCubicSpline: TCubicSpline; end; TVXNodesClass = class of TVXNodes; //----------------------------------------------------- implementation //----------------------------------------------------- // ------------------ // ------------------ TVXNode ------------------ // ------------------ constructor TVXNode.Create(ACollection: TCollection); begin inherited Create(ACollection); // nothing, yet end; destructor TVXNode.Destroy; begin // nothing, yet inherited Destroy; end; procedure TVXNode.Assign(Source: TPersistent); begin if Source is TVXNode then begin FCoords := TVXNode(Source).FCoords; end else inherited; end; function TVXNode.GetDisplayName: string; begin Result := Format('%.4f; %.4f; %.4f', [X, Y, Z]); end; function TVXNode.AsAddress: PGLFloat; begin Result := @FCoords; end; procedure TVXNode.SetAsVector(const Value: TVector); begin FCoords := Value; (Collection as TVXNodes).NotifyChange; end; procedure TVXNode.SetAsAffineVector(const Value: TAffineVector); begin SetVector(FCoords, Value); (Collection as TVXNodes).NotifyChange; end; function TVXNode.GetAsAffineVector: TAffineVector; begin SetVector(Result, FCoords); end; function TVXNode.GetCoordinate(const Index: Integer): Single; begin Result := FCoords.V[Index]; end; procedure TVXNode.SetCoordinate(AIndex: Integer; AValue: Single); begin FCoords.V[AIndex] := AValue; (Collection as TVXNodes).NotifyChange; end; function TVXNode.StoreCoordinate(AIndex: Integer): Boolean; begin Result := (FCoords.V[AIndex] <> 0); end; // ------------------ // ------------------ TVXNodes ------------------ // ------------------ constructor TVXNodes.Create(AOwner: TPersistent; AItemClass: TCollectionItemClass = nil); begin if not Assigned(AItemClass) then inherited Create(AOwner, TVXNode) else inherited Create(AOwner, AItemClass); end; function TVXNodes.CreateCopy(AOwner: TPersistent): TVXNodes; begin if Self <> nil then begin Result := TVXNodesClass(Self.ClassType).Create(AOwner); Result.Assign(Self); end else Result := nil; end; procedure TVXNodes.SetItems(Index: Integer; const Val: TVXNode); begin inherited Items[index] := Val; end; function TVXNodes.GetItems(Index: Integer): TVXNode; begin Result := TVXNode(inherited Items[index]); end; function TVXNodes.First: TVXNode; begin if Count > 0 then Result := TVXNode(inherited Items[0]) else Result := nil; end; function TVXNodes.Last: TVXNode; var N: Integer; begin N := Count - 1; if N >= 0 then Result := TVXNode(inherited Items[N]) else Result := nil; end; procedure TVXNodes.Update(Item: TCollectionItem); begin inherited; NotifyChange; end; function TVXNodes.Add: TVXNode; begin Result := (inherited Add) as TVXNode; end; function TVXNodes.FindItemID(ID: Integer): TVXNode; begin Result := (inherited FindItemID(ID)) as TVXNode; end; procedure TVXNodes.NotifyChange; begin if (UpdateCount = 0) and (GetOwner <> nil) and (GetOwner is TVXUpdateAbleComponent) then TVXUpdateAbleComponent(GetOwner).NotifyChange(Self); end; procedure TVXNodes.EndUpdate; begin inherited EndUpdate; // Workaround for a bug in VCL's EndUpdate if UpdateCount = 0 then NotifyChange; end; procedure TVXNodes.AddNode(const Coords: TVXCustomCoordinates); begin Add.AsVector := Coords.AsVector; end; procedure TVXNodes.AddNode(const X, Y, Z: Single); begin Add.AsVector := PointMake(X, Y, Z); end; procedure TVXNodes.AddNode(const Value: TVector); begin Add.AsVector := Value; end; procedure TVXNodes.AddNode(const Value: TAffineVector); begin Add.AsAffineVector := Value; end; procedure TVXNodes.AddXYArc(XRadius, YRadius: Single; StartAngle, StopAngle: Single; NbSegments: Integer; const Center: TAffineVector); var I: Integer; F: Single; S, C: Single; begin BeginUpdate; try StartAngle := DegToRadian(StartAngle); StopAngle := DegToRadian(StopAngle); F := (StopAngle - StartAngle) / NbSegments; for I := 0 to NbSegments do begin SinCosine(I * F + StartAngle, S, C); SetVector(Add.FCoords, Center.X + XRadius * C, Center.Y + YRadius * S, Center.Z, 1); end; finally EndUpdate; end; end; function TVXNodes.Barycenter: TAffineVector; var I: Integer; begin Result := NullVector; if Count > 0 then begin for I := 0 to Count - 1 do AddVector(Result, PAffineVector(Items[I].AsAddress)^); ScaleVector(Result, 1.0 / Count); end; end; function TVXNodes.Normal: TAffineVector; begin if Count >= 3 then CalcPlaneNormal(Items[0].FCoords, Items[1].FCoords, Items[2].FCoords, Result) else Result := NullVector; end; function TVXNodes.Vector(I: Integer): TAffineVector; procedure CalcUsingPrev; forward; procedure CalcUsingNext; begin if I < Count - 1 then VectorSubtract(Items[I].AsVector, Items[I + 1].AsVector, Result) else CalcUsingPrev; end; procedure CalcUsingPrev; begin if I > 0 then VectorSubtract(Items[I - 1].AsVector, Items[I].AsVector, Result) else CalcUsingNext; end; var J: Integer; Vecnull: Boolean; begin Assert((I >= 0) and (I < Count)); if I = 0 then if I = Count - 1 then SetVector(Result, NullVector) else VectorSubtract(Items[I + 1].AsVector, Items[I].AsVector, Result) else if I = Count - 1 then VectorSubtract(Items[I].AsVector, Items[I - 1].AsVector, Result) else VectorSubtract(Items[I + 1].AsVector, Items[I - 1].AsVector, Result); if VectorNorm(Result) < 1E-5 then begin // avoid returning null vector which generates display bugs in geometry J := 1; Vecnull := True; while (I + J < Count) and (Vecnull) do begin VectorSubtract(Items[I + J].AsVector, Items[I].AsVector, Result); if (VectorNorm(Result) > 1E-5) then Vecnull := False else Inc(J); end; J := 1; while (I - J > 0) and (Vecnull) do begin VectorSubtract(Items[I].AsVector, Items[I - J].AsVector, Result); if (VectorNorm(Result) > 1E-5) then Vecnull := False else Inc(J); end; if Vecnull then SetVector(Result, NullVector) else NormalizeVector(Result); end else NormalizeVector(Result); end; procedure TVXNodes.GetExtents(var Min, Max: TAffineVector); var I, K: Integer; F: Single; const CBigValue: Single = 1E50; CSmallValue: Single = -1E50; begin SetVector(Min, CBigValue, CBigValue, CBigValue); SetVector(Max, CSmallValue, CSmallValue, CSmallValue); for I := 0 to Count - 1 do begin for K := 0 to 2 do begin F := PAffineVector(Items[I].AsAddress)^.V[K]; if F < Min.V[K] then Min.V[K] := F; if F > Max.V[K] then Max.V[K] := F; end; end; end; procedure TVXNodes.Translate(const Tv: TAffineVector); var I: Integer; begin for I := 0 to Count - 1 do AddVector(PAffineVector(Items[I].AsAddress)^, Tv); NotifyChange; end; procedure TVXNodes.Scale(const Fv: TAffineVector); var I: Integer; begin for I := 0 to Count - 1 do ScaleVector(PAffineVector(Items[I].AsAddress)^, Fv); NotifyChange; end; procedure TVXNodes.Scale(F: Single); var I: Integer; begin for I := 0 to Count - 1 do ScaleVector(PAffineVector(Items[I].AsAddress)^, F); NotifyChange; end; procedure TVXNodes.RotateAroundX(Angle: Single); var I: Integer; C, S, V2: Single; V: PAffineVector; begin SinCosine(CPIDiv180 * Angle, S, C); for I := 0 to Count - 1 do begin V := PAffineVector(Items[I].AsAddress); V2 := V^.Z; V^.Y := C * V^.Y + S * V2; V^.Z := C * V2 - S * V^.Y; end; NotifyChange; end; procedure TVXNodes.RotateAroundY(Angle: Single); var I: Integer; C, S, V0: Single; V: PAffineVector; begin SinCosine(CPIDiv180 * Angle, S, C); for I := 0 to Count - 1 do begin V := PAffineVector(Items[I].AsAddress); V0 := V^.X; V^.X := C * V0 + S * V^.Z; V^.Z := C * V^.Z - S * V0; end; NotifyChange; end; procedure TVXNodes.RotateAroundZ(Angle: Single); var I: Integer; C, S, V1: Single; V: PAffineVector; begin SinCosine(CPIDiv180 * Angle, S, C); for I := 0 to Count - 1 do begin V := PAffineVector(Items[I].AsAddress); V1 := V^.Y; V^.Y := C * V1 + S * V^.X; V^.X := C * V^.X - S * V1; end; NotifyChange; end; function TVXNodes.CreateNewCubicSpline: TCubicSpline; var I: Integer; Xa, Ya, Za: PFloatArray; begin GetMem(Xa, SizeOf(Single) * Count); GetMem(Ya, SizeOf(Single) * Count); GetMem(Za, SizeOf(Single) * Count); for I := 0 to Count - 1 do with Items[I] do begin Xa^[I] := X; Ya^[I] := Y; Za^[I] := Z; end; Result := TCubicSpline.Create(Xa, Ya, Za, nil, Count); FreeMem(Xa); FreeMem(Ya); FreeMem(Za); end; var NbExtraVertices: Integer; NewVertices: PAffineVectorArray; function AllocNewVertex: PAffineVector; begin Inc(NbExtraVertices); Result := @NewVertices[NbExtraVertices - 1]; end; procedure TessError(Errno: GLEnum); {$IFDEF Win32} stdcall; {$ENDIF}{$IFDEF UNIX} cdecl; {$ENDIF} begin Assert(False, IntToStr(Errno) + ': ' + string(GluErrorString(Errno))); end; procedure TessIssueVertex(VertexData: Pointer); {$IFDEF Win32} stdcall; {$ENDIF}{$IFDEF UNIX} cdecl; {$ENDIF} begin glTexCoord2fv(VertexData); glVertex3fv(VertexData); end; procedure TessCombine(Coords: PDoubleVector; Vertex_data: Pointer; Weight: PGLFloat; var OutData: Pointer); {$IFDEF Win32} stdcall; {$ENDIF}{$IFDEF UNIX} cdecl; {$ENDIF} begin OutData := AllocNewVertex; SetVector(PAffineVector(OutData)^, Coords^[0], Coords^[1], Coords^[2]); end; procedure TVXNodes.RenderTesselatedPolygon(ATextured: Boolean; ANormal: PAffineVector = nil; ASplineDivisions: Integer = 1; AInvertNormals: Boolean = False); var I: Integer; Tess: PGLUTesselator; DblVector: TAffineDblVector; Spline: TCubicSpline; SplinePos: PAffineVector; F: Single; begin if Count > 2 then begin // Create and initialize the GLU tesselator Tess := gluNewTess; gluTessCallback(Tess, GLU_TESS_BEGIN, @glBegin); if ATextured then gluTessCallback(Tess, GLU_TESS_VERTEX, @TessIssueVertex) else gluTessCallback(Tess, GLU_TESS_VERTEX, @glVertex3fv); gluTessCallback(Tess, GLU_TESS_END, @glEnd); gluTessCallback(Tess, GLU_TESS_ERROR, @TessError); gluTessCallback(Tess, GLU_TESS_COMBINE, @TessCombine); NbExtraVertices := 0; // Issue normal if Assigned(ANormal) then begin glNormal3fv(PGLFloat(ANormal)); gluTessNormal(Tess, ANormal^.X, ANormal^.Y, ANormal^.Z); end; // Issue polygon gluTessBeginPolygon(Tess, nil); gluTessBeginContour(Tess); if ASplineDivisions <= 1 then begin // no spline, use direct coordinates GetMem(NewVertices, Count * SizeOf(TAffineVector)); if AInvertNormals then begin for I := Count - 1 downto 0 do begin SetVector(DblVector, PAffineVector(Items[I].AsAddress)^); gluTessVertex(Tess, DblVector, Items[I].AsAddress); end; end else begin for I := 0 to Count - 1 do begin SetVector(DblVector, PAffineVector(Items[I].AsAddress)^); gluTessVertex(Tess, DblVector, Items[I].AsAddress); end; end; end else begin // cubic spline GetMem(NewVertices, 2 * ASplineDivisions * Count * SizeOf(TAffineVector)); Spline := CreateNewCubicSpline; F := 1.0 / ASplineDivisions; if AInvertNormals then begin for I := ASplineDivisions * (Count - 1) downto 0 do begin SplinePos := AllocNewVertex; Spline.SplineAffineVector(I * F, SplinePos^); SetVector(DblVector, SplinePos^); gluTessVertex(Tess, DblVector, SplinePos); end; end else begin for I := 0 to ASplineDivisions * (Count - 1) do begin SplinePos := AllocNewVertex; Spline.SplineAffineVector(I * F, SplinePos^); SetVector(DblVector, SplinePos^); gluTessVertex(Tess, DblVector, SplinePos); end; end; Spline.Free; end; gluTessEndContour(Tess); gluTessEndPolygon(Tess); // release stuff if Assigned(NewVertices) then FreeMem(NewVertices); gluDeleteTess(Tess); end; end; end.
unit uPrintRepairCliReceipt; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Db, DBTables, ComCtrls, ADODB, siComp, siLangRT, PaiDeForms, PaidePrinter; type TPrintRepairCliReceipt = class(TFrmParentPrint) lblPrint: TLabel; pnlPrinter: TPanel; AniPrint: TAnimate; btOk: TButton; quRepair: TADOQuery; quRepairCustomer: TStringField; quRepairAddress: TStringField; quRepairReceiveDate: TDateTimeField; quRepairModel: TStringField; quRepairDescription: TStringField; quRepairOBSReceive: TStringField; quRepairIDRepair: TIntegerField; quRepairSysUser: TStringField; quRepairSerialNumber: TStringField; quRepairOBSLine1: TStringField; quRepairOBSLine2: TStringField; quRepairOBSLine3: TStringField; quRepairOBSLine4: TStringField; quRepairTicketHeader: TMemoField; quRepairQty: TFloatField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } sHeader, sRepairN, sDate, sTime, sReceivedBy, sModel, sSerial, sDesc, sQty, sCustomer, sAddress, sOBS, sFooter, sRecImpresso, sClickOK : String; MyIDLancamento : Integer; Quit : Boolean; public { Public declarations } procedure Start(IDRepairCli : Integer); end; implementation uses uDM, uPassword, xBase, uMsgBox, uMsgConstant, uDMGlobal; {$R *.DFM} procedure TPrintRepairCliReceipt.Start(IDRepairCli : Integer); var NotOk: Boolean; begin Quit := False; with quRepair do begin Parameters.ParambyName('IDRepairCli').Value := IDRepairCLi; Open; end; Show; Update; NotOk := True; Application.ProcessMessages; while NotOk do begin try DM.PrinterStart; NotOk := False; except if MsgBox(MSG_CRT_ERROR_PRINTING, vbCritical + vbYesNo) = vbYes then NotOk := True else begin Exit; end; end; end; ImpMemoDBInfo(quRepairTicketHeader.AsString); DM.PrintLine(''); DM.PrintLine(sHeader); DM.PrintLine(' ----------------------------------'); DM.PrintLine(''); DM.PrintLine(sRepairN + quRepairIDRepair.AsString); DM.PrintLine(sDate + DateToStr(quRepairReceiveDate.AsDateTime)); DM.PrintLine(sTime + TimeToStr(Now)); DM.PrintLine(sReceivedBy + quRepairSysUser.AsString); DM.PrintLine(''); DM.PrintLine(sModel + quRepairModel.AsString); DM.PrintLine(sSerial + quRepairSerialNumber.AsString); DM.PrintLine(sDesc + quRepairDescription.AsString); DM.PrintLine(sQty + quRepairQty.AsString); DM.PrintLine(''); DM.PrintLine(sCustomer + quRepairCustomer.AsString); DM.PrintLine(sAddress + quRepairAddress.AsString); DM.PrintLine(''); DM.PrintLine(sOBS + quRepairOBSLine1.AsString); DM.PrintLine(' ' + quRepairOBSLine2.AsString); DM.PrintLine(' ' + quRepairOBSLine3.AsString); DM.PrintLine(' ' + quRepairOBSLine4.AsString); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(sFooter); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine('.'); DM.PrintLine(Chr(27)+Chr(12)); DM.PrinterStop; lblPrint.Caption := sRecImpresso; btOk.Visible := True; AniPrint.Active := False; AniPrint.Visible := False; pnlPrinter.Caption := sClickOK; quRepair.Close; Close; end; procedure TPrintRepairCliReceipt.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TPrintRepairCliReceipt.FormShow(Sender: TObject); begin AniPrint.Active := True; btOk.Visible := False; end; procedure TPrintRepairCliReceipt.btOkClick(Sender: TObject); begin Close; end; procedure TPrintRepairCliReceipt.FormCreate(Sender: TObject); begin inherited; Case DMGlobal.IDLanguage of LANG_ENGLISH : begin sHeader := ' R E P A I R R E C E I P T'; sRepairN := 'Repair # '; sDate := 'Date : '; sTime := 'Time : '; sReceivedBy := 'Returned by: '; sModel := 'Model : '; sSerial := 'Serial # : '; sDesc := 'Description: '; sQty := 'Qty : '; sCustomer := 'Customer : '; sAddress := 'Address : '; sOBS := 'OBS : '; sFooter := '===============END OF TICKET============'; sRecImpresso:= 'Receipt Printed'; sClickOK := 'Click OK to continue'; end; LANG_PORTUGUESE : begin sHeader := ' R E C I B O D E R E P A R O '; sRepairN := 'N. Reparo '; sDate := 'Data : '; sTime := 'Hora : '; sReceivedBy := 'Usuário : '; sModel := 'Modelo : '; sSerial := 'N. Série : '; sDesc := 'Descrição : '; sQty := 'Qtd : '; sCustomer := 'Cliente : '; sAddress := 'Endereço : '; sOBS := 'OBS : '; sFooter := '===============FINAL DO RECIBO=========='; sRecImpresso:= 'Recibo Impresso'; sClickOK := 'Clique OK para continuar'; end; LANG_SPANISH : begin sHeader := 'R E C I B O D E R E P A R A C I O N'; sRepairN := 'N. Reparación '; sDate := 'Fecha : '; sTime := 'Hora : '; sReceivedBy := 'Usuario : '; sModel := 'Modelo : '; sSerial := 'N. Série : '; sDesc := 'Descripción: '; sQty := 'Ctd : '; sCustomer := 'Cliente : '; sAddress := 'Dirección : '; sOBS := 'OBS : '; sFooter := '===============FINAL DEL RECIBO=========='; sRecImpresso:= 'Recibo Imprimido'; sClickOK := 'Clic OK para continuar'; end; end; end; end.
unit CamPlayer_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, LibVlc, ExtCtrls; const VLC_TIMEOUT = 500; MSG_FULLSCREEN = WM_USER + 100; type TCamPlayer = class(TFrame) Button1: TButton; Panel1: TPanel; procedure FrameResize(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Panel1DblClick(Sender: TObject); private { Private declarations } public fIndex: integer; fUrl: string; procedure Init(aIndex: integer; aUrl: string); procedure reinit; procedure replay; destructor Destroy; override; end; implementation {$R *.dfm} { TCamPlayer } procedure TCamPlayer.Init(aIndex: integer; aUrl: string); var url: string; begin fIndex := aIndex; fUrl := aUrl; reinit; end; procedure TCamPlayer.FrameResize(Sender: TObject); begin if (ClientWidth > Screen.Width * 2 div 3) then begin Button1.Left := ClientWidth - Button1.Width - 10; Button1.Top := Screen.Height - Button1.Height - 50; end else begin Button1.Left := ClientWidth - Button1.Width - 5; Button1.Top := ClientHeight - Button1.Height - 5; end; end; destructor TCamPlayer.Destroy; begin libvlc.play(fIndex, fUrl, -1); inherited; end; procedure TCamPlayer.Button1Click(Sender: TObject); begin if (Button1.Tag = 0) then begin Button1.Tag := 1; Button1.Caption := 'HIGH'; end else begin Button1.Tag := 0; Button1.Caption := 'LOW'; end; replay; end; procedure TCamPlayer.Panel1DblClick(Sender: TObject); begin PostMessage(Parent.Handle, MSG_FULLSCREEN, fIndex, 0); end; procedure TCamPlayer.reinit; begin libvlc.init(fIndex, Panel1.Handle); replay; end; procedure TCamPlayer.replay; var url: string; begin if (Button1.Tag = 1) then begin url := StringReplace(fUrl, '1.sdp', '0.sdp', [rfReplaceAll]); libvlc.play(fIndex, url, VLC_TIMEOUT); end else begin libvlc.play(fIndex, fUrl, VLC_TIMEOUT); end; end; end.
unit MeshPluginBase; interface uses GlConstants, ShaderBank; type PMeshPluginBase = ^TMeshPluginBase; TSetShaderAttributesFunc = procedure (const _ShaderBank: PShaderBank; _VertexID: integer; const _PPlugin: PMeshPluginBase) of object; TMeshPluginBase = class protected FPluginType : integer; procedure DoRender(); virtual; procedure DoUpdate(_MeshAddress: Pointer); virtual; function GetPluginType: integer; public AllowUpdate: boolean; AllowRender: boolean; // Constructors and destructors constructor Create; destructor Destroy; override; procedure Initialize(); virtual; procedure Clear(); virtual; procedure Reset(); // Rendering functions procedure Render(); procedure Update(_MeshAddress: Pointer); // Copy procedure Assign(const _Source: TMeshPluginBase); virtual; // properties property PluginType: integer read GetPluginType; end; TAMeshPluginBase = array of TMeshPluginBase; PAMeshPluginBase = array of PMeshPluginBase; implementation // Constructors and destructors constructor TMeshPluginBase.Create; begin FPluginType := C_MPL_BASE; end; destructor TMeshPluginBase.Destroy; begin Clear; inherited Destroy; end; procedure TMeshPluginBase.Initialize; begin AllowUpdate := true; AllowRender := true; end; procedure TMeshPluginBase.Clear; begin // do nothing end; procedure TMeshPluginBase.Reset; begin Clear; Initialize; end; // Rendering functions procedure TMeshPluginBase.Render; begin if AllowRender then begin DoRender; end; end; procedure TMeshPluginBase.DoRender; begin // do nothing end; procedure TMeshPluginBase.Update(_MeshAddress: Pointer); begin if AllowUpdate then begin DoUpdate(_MeshAddress); end; end; procedure TMeshPluginBase.DoUpdate(_MeshAddress: Pointer); begin // do nothing end; function TMeshPluginBase.GetPluginType: integer; begin Result := FPluginType; end; // Copy procedure TMeshPluginBase.Assign(const _Source: TMeshPluginBase); begin AllowUpdate := _Source.AllowUpdate; AllowRender := _Source.AllowRender; end; end.
unit ExZmodm1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, StdCtrls, ExtCtrls, Apax1_TLB; type TForm1 = class(TForm) Panel1: TPanel; Label1: TLabel; edtTapiNumber: TEdit; OpenDialog1: TOpenDialog; Apax1: TApax; procedure Apax1TapiConnect(Sender: TObject); procedure Apax1TapiPortClose(Sender: TObject); procedure FormActivate(Sender: TObject); procedure Apax1TapiGetNumber(Sender: TObject; var PhoneNum: WideString); procedure Apax1SendButtonClick(Sender: TObject; var Default: WordBool); procedure Apax1ReceiveButtonClick(Sender: TObject; var Default: WordBool); procedure Apax1ProtocolFinish(Sender: TObject; ErrorCode: Integer); procedure Apax1ProtocolAccept(Sender: TObject; var Accept: WordBool; var FName: WideString); procedure Apax1ListenButtonClick(Sender: TObject; var Default: WordBool); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormActivate(Sender: TObject); begin edtTapiNumber.Text := Apax1.TapiNumber; end; procedure TForm1.Apax1TapiConnect(Sender: TObject); begin Caption := 'Connected'; Apax1.ShowProtocolButtons := True; end; procedure TForm1.Apax1TapiPortClose(Sender: TObject); begin Apax1.ShowProtocolButtons := False; Caption := 'ExZmodem - File Transfer Sender/Receiver'; end; procedure TForm1.Apax1TapiGetNumber(Sender: TObject; var PhoneNum: WideString); begin PhoneNum := edtTapiNumber.Text; end; procedure TForm1.Apax1SendButtonClick(Sender: TObject; var Default: WordBool); begin Default := False; if OpenDialog1.Execute then begin Apax1.SendFileName := OpenDialog1.FileName; Apax1.TerminalActive := False; Apax1.TerminalWriteString('sending ' + OpenDialog1.FileName); Apax1.StartTransmit; end; end; procedure TForm1.Apax1ReceiveButtonClick(Sender: TObject; var Default: WordBool); begin Apax1.TerminalActive := False; Default := True; end; procedure TForm1.Apax1ProtocolFinish(Sender: TObject; ErrorCode: Integer); begin if (ErrorCode = 0) then Apax1.TerminalWriteStringCRLF(' - Ok') else Apax1.TerminalWriteStringCRLF(' - Error ' + IntToStr(ErrorCode)); Apax1.TerminalActive := True; end; procedure TForm1.Apax1ProtocolAccept(Sender: TObject; var Accept: WordBool; var FName: WideString); begin Apax1.TerminalWriteString('receiving ' + FName); Accept := True; end; procedure TForm1.Apax1ListenButtonClick(Sender: TObject; var Default: WordBool); begin Default := True; Caption := 'Ready to answer incoming calls'; end; end.
unit Unit17; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, DragDrop, DropTarget, DragDropFile, o_DragAndDropDataAdapter, o_ObjOutlookDrop; type TForm17 = class(TForm) grd: TStringGrid; DataFormatAdapterTarget: TDataFormatAdapter; DropFileTarget1: TDropFileTarget; procedure FormCreate(Sender: TObject); procedure DropFileTarget1Drop(Sender: TObject; ShiftState: TShiftState; APoint: TPoint; var Effect: Integer); procedure FormDestroy(Sender: TObject); private fPfad: string; fDragAndDropAdapter: TDragAndDropDataAdapter; fOutlookDrop: TObjOutlookDrop; public end; var Form17: TForm17; implementation {$R *.dfm} uses DragDropGraphics; procedure TForm17.FormCreate(Sender: TObject); begin grd.ColWidths[0] := 10; grd.ColWidths[1] := 200; grd.ColWidths[2] := 200; fPfad := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); DropFileTarget1.Target := grd; fDragAndDropAdapter := TDragAndDropDataAdapter.Create; DataFormatAdapterTarget.Enabled := true; { fOutlookDrop := TObjOutlookDrop.Create; if fOutlookDrop.canUse then fOutlookDrop.DataFormatAdapterOutlook := DataFormatAdapterOutlook; DataFormatAdapterOutlook.Enabled := fOutlookDrop.canUse; } end; procedure TForm17.FormDestroy(Sender: TObject); begin FreeAndNil(fDragAndDropAdapter); FreeAndNil(fOutlookDrop); end; procedure TForm17.DropFileTarget1Drop(Sender: TObject; ShiftState: TShiftState; APoint: TPoint; var Effect: Integer); var BitmapData: TBitmapDataFormat; begin // if (TVirtualFileStreamDataFormat(DataFormatAdapterTarget.DataFormat).FileNames.Count > 0) then begin fDragAndDropAdapter.SaveVirtualFileStream(TVirtualFileStreamDataFormat(DataFormatAdapterTarget.DataFormat), fPfad); exit; end; { if (DataFormatAdapterBitmap.DataFormat <> nil) then begin if (DataFormatAdapterBitmap.DataFormat as TBitmapDataFormat).HasData then begin BitmapData := TBitmapDataFormat(DataFormatAdapterBitmap.DataFormat); ShowMessage('Bitmap'); exit; end; if (DataFormatAdapterOutlook.DataFormat <> nil) then begin fOutlookDrop.Dropped; if fOutlookDrop.OutlookDropMessages.Count > 0 then begin exit; end; end; end; } end; end.
unit MeshSmoothVertexNormals; interface uses MeshProcessingBase, Mesh, BasicMathsTypes, BasicDataTypes, NeighborDetector, LOD; {$INCLUDE source/Global_Conditionals.inc} type TMeshSmoothVertexNormals = class (TMeshProcessingBase) protected procedure MeshSmoothVertexNormalsOperation(var _Normals: TAVector3f; const _Vertices: TAVector3f; _NumVertices: integer; const _Neighbors : TNeighborDetector; const _VertexEquivalences: auint32); procedure DoMeshProcessing(var _Mesh: TMesh); override; public DistanceFunction: TDistanceFunc; constructor Create(var _LOD: TLOD); override; end; implementation uses MeshPluginBase, GLConstants, NeighborhoodDataPlugin, MeshBRepGeometry, Math3d, DistanceFormulas; constructor TMeshSmoothVertexNormals.Create(var _LOD: TLOD); begin inherited Create(_LOD); DistanceFunction := GetLinearDistance; end; procedure TMeshSmoothVertexNormals.DoMeshProcessing(var _Mesh: TMesh); var Neighbors : TNeighborDetector; NeighborhoodPlugin : PMeshPluginBase; NumVertices : integer; VertexEquivalences: auint32; begin // Setup Neighbors. NeighborhoodPlugin := _Mesh.GetPlugin(C_MPL_NEIGHBOOR); _Mesh.Geometry.GoToFirstElement; if (High(_Mesh.Normals) > 0) then begin if NeighborhoodPlugin <> nil then begin Neighbors := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexNeighbors; NumVertices := TNeighborhoodDataPlugin(NeighborhoodPlugin^).InitialVertexCount; if TNeighborhoodDataPlugin(NeighborhoodPlugin^).UseEquivalenceFaces then begin VertexEquivalences := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexEquivalences; end else begin VertexEquivalences := nil; end; end else begin Neighbors := TNeighborDetector.Create; Neighbors.BuildUpData((_Mesh.Geometry.Current^ as TMeshBRepGeometry).Faces,(_Mesh.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,High(_Mesh.Vertices)+1); _Mesh.Geometry.GoToFirstElement; NumVertices := High(_Mesh.Vertices)+1; VertexEquivalences := nil; end; MeshSmoothVertexNormalsOperation(_Mesh.Normals,_Mesh.Vertices,NumVertices,Neighbors,VertexEquivalences); // Free memory if NeighborhoodPlugin = nil then begin Neighbors.Free; end; _Mesh.ForceRefresh; end; end; procedure TMeshSmoothVertexNormals.MeshSmoothVertexNormalsOperation(var _Normals: TAVector3f; const _Vertices: TAVector3f; _NumVertices: integer; const _Neighbors : TNeighborDetector; const _VertexEquivalences: auint32); var i,Value : integer; NormalsHandicap : TAVector3f; Counter : integer; Distance: single; begin // Setup Normals Handicap. SetLength(NormalsHandicap,High(_Normals)+1); for i := Low(NormalsHandicap) to High(NormalsHandicap) do begin NormalsHandicap[i].X := 0; NormalsHandicap[i].Y := 0; NormalsHandicap[i].Z := 0; end; // Main loop goes here. for i := Low(_Vertices) to (_NumVertices - 1) do begin Counter := 0; Value := _Neighbors.GetNeighborFromID(i); // Get vertex neighbor from vertex while Value <> -1 do begin Distance := _Vertices[Value].X - _Vertices[i].X; if Distance <> 0 then NormalsHandicap[i].X := NormalsHandicap[i].X + (_Normals[Value].X * DistanceFunction(Distance)); Distance := _Vertices[Value].Y - _Vertices[i].Y; if Distance <> 0 then NormalsHandicap[i].Y := NormalsHandicap[i].Y + (_Normals[Value].Y * DistanceFunction(Distance)); Distance := _Vertices[Value].Z - _Vertices[i].Z; if Distance <> 0 then NormalsHandicap[i].Z := NormalsHandicap[i].Z + (_Normals[Value].Z * DistanceFunction(Distance)); inc(Counter); Value := _Neighbors.GetNextNeighbor; end; if Counter > 0 then begin _Normals[i].X := _Normals[i].X + (NormalsHandicap[i].X / Counter); _Normals[i].Y := _Normals[i].Y + (NormalsHandicap[i].Y / Counter); _Normals[i].Z := _Normals[i].Z + (NormalsHandicap[i].Z / Counter); Normalize(_Normals[i]); end; end; i := _NumVertices; while i <= High(_Vertices) do begin Value := GetEquivalentVertex(i,_NumVertices,_VertexEquivalences); _Normals[i].X := _Normals[Value].X; _Normals[i].Y := _Normals[Value].Y; _Normals[i].Z := _Normals[Value].Z; inc(i); end; // Free memory SetLength(NormalsHandicap,0); end; end.
unit ImageZoomU; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Gestures; type TPinchZoom = class(TForm) GestureManager1: TGestureManager; Image1: TImage; ToolBar1: TToolBar; Label1: TLabel; procedure FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var FLastDistance : Integer; PinchZoom: TPinchZoom; implementation {$R *.fmx} procedure TPinchZoom.Button1Click(Sender: TObject); var I : Integer; Start, Stop : TTime; begin Start := Now; for I := 1 to 1000 do begin while Image1.Scale.X < 2 do begin Image1.Position.X := ClientWidth/2 - (Image1.Width * Image1.Scale.X)/2; Image1.Position.Y := ClientHeight - ClientWidth/2 - (Image1.Height * Image1.Scale.Y)/2; Image1.Scale.X := Image1.Scale.X + 0.1; Image1.Scale.Y := Image1.Scale.Y + 0.1; end; Image1.Scale.X := 0; Image1.Scale.Y := 0; end; Stop := Now; ShowMessage(FormatDateTime('nn:ss.zzz',Stop-Start)+ ' for 1000 non visual zooms'); end; procedure TPinchZoom.Button2Click(Sender: TObject); var I : Integer; Start, Stop : TTime; begin Start := Now; for I := 1 to 10 do begin while Image1.Scale.X < 2 do begin Image1.Position.X := ClientWidth/2 - (Image1.Width * Image1.Scale.X)/2; Image1.Position.Y := ClientHeight - ClientWidth/2 - (Image1.Height * Image1.Scale.Y)/2; Image1.Scale.X := Image1.Scale.X + 0.1; Image1.Scale.Y := Image1.Scale.Y + 0.1; Application.ProcessMessages; end; Image1.Scale.X := 0; Image1.Scale.Y := 0; end; Stop := Now; ShowMessage(FormatDateTime('nn:ss.zzz',Stop-Start)+ ' for 10 visual zooms'); end; procedure TPinchZoom.FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); var LObj: IControl; image: TImage; begin LObj := Self.ObjectAtPoint(ClientToScreen(EventInfo.Location)); if LObj is TImage then begin if not(TInteractiveGestureFlag.gfBegin in EventInfo.Flags) and (not(TInteractiveGestureFlag.gfEnd in EventInfo.Flags)) then begin image := TImage(LObj.GetObject); image.Width := image.Width + 2*((EventInfo.Distance - FLastDIstance)/3); image.Height := image.Height + 2*((EventInfo.Distance - FLastDIstance)/3); image.Position.X := image.Position.X - (EventInfo.Distance - FLastDIstance)/3; image.Position.Y := image.Position.Y - (EventInfo.Distance - FLastDIstance)/3; end; FLastDistance := EventInfo.Distance; end; end; end.
unit DivOpNewtonTest; {$mode objfpc}{$H+} interface uses SysUtils, fpcunit, testregistry, Math, TestHelper, uEnums, uIntXLibTypes, uIntX; type { TTestDivOpNewton } TTestDivOpNewton = class(TTestCase) private F_length: integer; function GetAllOneDigits(mlength: integer): TIntXLibUInt32Array; function GetRandomDigits(out digits2: TIntXLibUInt32Array): TIntXLibUInt32Array; procedure NextBytes(var bytes: TBytes); procedure Inner(); procedure InnerTwo(); const StartLength = integer(1024); LengthIncrement = integer(101); RepeatCount = integer(10); RandomStartLength = integer(1024); RandomEndLength = integer(2048); RandomRepeatCount = integer(25); published procedure CompareWithClassic(); procedure CompareWithClassicRandom(); protected procedure SetUp; override; end; implementation procedure TTestDivOpNewton.CompareWithClassic; var InnerMethod: TRunMethod; begin InnerMethod := @Inner; TTestHelper.Repeater(RepeatCount, InnerMethod); end; procedure TTestDivOpNewton.CompareWithClassicRandom; var InnerMethod: TRunMethod; begin InnerMethod := @InnerTwo; TTestHelper.Repeater(RandomRepeatCount, InnerMethod); end; function TTestDivOpNewton.GetAllOneDigits(mlength: integer): TIntXLibUInt32Array; var i: integer; begin SetLength(Result, mlength); for i := 0 to Pred(Length(Result)) do begin Result[i] := $FFFFFFFF; end; end; function TTestDivOpNewton.GetRandomDigits(out digits2: TIntXLibUInt32Array): TIntXLibUInt32Array; var bytes: TBytes; i: integer; begin SetLength(Result, RandomRange(RandomStartLength, RandomEndLength)); SetLength(digits2, Length(Result) div 2); SetLength(bytes, 4); for i := 0 to Pred(Length(Result)) do begin NextBytes(bytes); Result[i] := PCardinal(@bytes[0])^; if (i < Length(digits2)) then begin NextBytes(bytes); digits2[i] := PCardinal(@bytes[0])^; end; end; end; procedure TTestDivOpNewton.NextBytes(var bytes: TBytes); var i, randValue: integer; begin for i := 0 to Pred(Length(bytes)) do begin randValue := RandomRange(2, 30); if (randValue and 1) <> 0 then bytes[i] := byte((randValue shr 1) xor $25) else bytes[i] := byte(randValue shr 1); end; end; procedure TTestDivOpNewton.SetUp; begin inherited SetUp; F_length := StartLength; Randomize; end; procedure TTestDivOpNewton.Inner(); var x, x2, classicMod, fastMod, classic, fast: TIntX; begin x := TIntX.Create(GetAllOneDigits(F_length), True); x2 := TIntX.Create(GetAllOneDigits(F_length div 2), True); classic := TIntX.DivideModulo(x, x2, classicMod, TDivideMode.dmClassic); fast := TIntX.DivideModulo(x, x2, fastMod, TDivideMode.dmAutoNewton); AssertTrue(classic = fast); AssertTrue(classicMod = fastMod); F_length := F_length + LengthIncrement; end; procedure TTestDivOpNewton.InnerTwo(); var x, x2, classicMod, fastMod, classic, fast: TIntX; digits2: TIntXLibUInt32Array; begin x := TIntX.Create(GetRandomDigits(digits2), False); x2 := TIntX.Create(digits2, False); classic := TIntX.DivideModulo(x, x2, classicMod, TDivideMode.dmClassic); fast := TIntX.DivideModulo(x, x2, fastMod, TDivideMode.dmAutoNewton); AssertTrue(classic = fast); AssertTrue(classicMod = fastMod); end; initialization RegisterTest(TTestDivOpNewton); end.
unit uDischargeAdd; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, uSpravControl, uDateControl, uFControl, uLabeledFControl, uCharControl, uIntControl, uFormControl, uInvisControl, uBoolControl, AccMgmt, BaseTypes, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet; type TfrmAddDischarge = class(TForm) GroupBox1: TGroupBox; DateDismission: TqFDateControl; DismissionReason: TqFCharControl; NameDismission: TqFSpravControl; ProfkomNote: TqFCharControl; cbAll: TqFBoolControl; btnOk: TBitBtn; btnCancel: TBitBtn; NotUsedEdit: TqFIntControl; notWorkedEdit: TqFIntControl; DataSet: TpFIBDataSet; NoteEdit: TqFCharControl; procedure NameDismissionOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation uses uCommonSp, uDischarge, qfTools, uUnivSprav, RXMemDS; {$R *.dfm} procedure TfrmAddDischarge.NameDismissionOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); var sp: TSprav; Params: TUnivParams; OutPut: TRxMemoryData; begin { Params.FormCaption := 'Довідник підстав роботи'; Params.ShowMode := fsmSelect; Params.ShowButtons := [fbExit]; Params.TableName := 'SP_DISMISSION'; Params.Fields := 'NAME_DISMISSION,KZOT_ST,ID_DISMISSION'; Params.FieldsName := 'Назва підстави,Статья КЗОТ'; Params.KeyField := 'ID_DISMISSION'; Params.ReturnFields := 'NAME_DISMISSION,ID_DISMISSION,KZOT_ST'; Params.DBHandle := Integer(TfrmDischargeOrder(owner).Database.Handle); OutPut := TRxMemoryData.Create(self); if GetUnivSprav(Params, OutPut) then begin value := output['ID_DISMISSION']; DisplayText := VarToStr(output['Name_Dismission']); end; } // создать справочник sp := GetSprav('asup\SpDismission'); if sp <> nil then begin // заполнить входные параметры sp.Input.Append; sp.Input.FieldValues['DBHandle'] := Integer(TfrmDischargeOrder(owner).Database.Handle); sp.Input.FieldValues['FormStyle'] := fsNormal; sp.Input.Post; // показать справочник и проанализировать результат (выбор одного подр.) sp.Show; if (sp.Output <> nil) and not sp.Output.IsEmpty then begin Value := sp.Output['Id_Dismission']; DisplayText := sp.Output['Name_Dismission']; if not VarIsNull(sp.Output['Kzot_St']) then DisplayText := DisplayText + ' ' + sp.Output['Kzot_St']; end; sp.Free; end; end; procedure TfrmAddDischarge.FormCreate(Sender: TObject); begin DateDismission.Value := date; end; procedure TfrmAddDischarge.FormShow(Sender: TObject); var CheckHolDays, CheckNotWorkDays: Integer; IdServer: Integer; begin DataSet.Close; DataSet.SQLs.SelectSQL.Text := 'select id_server from pub_sys_data'; DataSet.Open; IdServer := DataSet['Id_Server']; if ((IdServer = 99) or (IdServer = 91)) then begin CheckHolDays := fibCheckPermission('/ROOT/Up_order_system/DISMIS_COMPENS_DAYS', 'Edit'); CheckNotWorkDays := fibCheckPermission('/ROOT/Up_order_system/DISM_NOT_WORK_DAYS', 'Edit'); end; if ((IdServer = 95) or (IdServer = 97) or (IdServer = 93)) then begin CheckHolDays := fibCheckPermission('/ROOT/UP_VER2_ORDERS/DISMIS_COMPENS_DAYS', 'Edit'); CheckNotWorkDays := fibCheckPermission('/ROOT/UP_VER2_ORDERS/DISM_NOT_WORK_DAYS', 'Edit'); end; case CheckHolDays of 0: NotUsedEdit.Blocked := False; -1: NotUsedEdit.Blocked := True; end; case CheckNotWorkDays of 0: notWorkedEdit.Blocked := False; -1: notWorkedEdit.Blocked := True; end; DismissionReason.SetFocus; end; procedure TfrmAddDischarge.btnOkClick(Sender: TObject); begin if TfrmDischargeOrder(Owner).Input['mode'] = 3 then Close; if qFCheckAll(Self) then ModalResult := mrOk; end; end.
unit SyntaxHighlight_Reg; interface uses Classes,SyntaxHighlighter,SyntaxHighlightMemo,TextEditorFooter,DesignEditors,DesignIntf,Menus, SysUtils,ShortCutCollection,Windows; type TShortCutProperty=class(TPropertyEditor) public function GetValue:string;override; procedure SetValue(const Value:string);override; procedure GetProperties(Proc: TGetPropProc); override; function GetAttributes:TPropertyAttributes;override; end; TNestedShiftStateProperty = class(TNestedProperty) protected FParent:TShortCutProperty; public constructor Create(Parent: TPropertyEditor); function GetAttributes: TPropertyAttributes; override; function GetName: string; override; procedure GetProperties(Proc: TGetPropProc); override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TShift=ssShift..ssDouble; TNestedShiftProperty = class(TNestedProperty) protected FParent:TShortCutProperty; FShift:TShift; public constructor Create(Parent: TPropertyEditor; AShift: TShift); function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TNestedKeyProperty=class(TNestedProperty) protected FParent:TShortCutProperty; public constructor Create(Parent: TPropertyEditor); function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TSyntaxHighlightMemoEditor=class(TComponentEditor) public procedure Edit;override; procedure ExecuteVerb(Index:Integer);override; function GetVerb(Index:Integer):string;override; function GetVerbCount:Integer;override; end; const GShiftNames:array[ssShift..ssDouble] of string=( 'Shift','Alt','Ctrl','LeftButton','RightButton','MiddleButton','DoubleButton' ); GKeys:array[0..106] of Integer=( 0, VK_BACK, VK_TAB, VK_CLEAR, VK_RETURN, VK_SHIFT, VK_CONTROL, VK_MENU, VK_PAUSE, VK_CAPITAL, VK_ESCAPE, VK_SPACE, VK_PRIOR, VK_NEXT, VK_END, VK_HOME, VK_LEFT,VK_UP,VK_RIGHT,VK_DOWN, VK_SELECT, VK_PRINT, VK_EXECUTE, VK_SNAPSHOT, VK_INSERT, VK_DELETE, VK_HELP, Ord('0'),Ord('1'),Ord('2'),Ord('3'),Ord('4'),Ord('5'),Ord('6'),Ord('7'),Ord('8'),Ord('9'), Ord('A'),Ord('B'),Ord('C'),Ord('D'),Ord('E'),Ord('F'),Ord('G'),Ord('H'),Ord('I'),Ord('J'),Ord('K'),Ord('L'),Ord('M'), Ord('N'),Ord('O'),Ord('P'),Ord('Q'),Ord('R'),Ord('S'),Ord('T'),Ord('U'),Ord('V'),Ord('W'),Ord('X'),Ord('Y'),Ord('Z'), VK_LWIN, VK_RWIN, VK_APPS, VK_NUMPAD0,VK_NUMPAD1,VK_NUMPAD2,VK_NUMPAD3,VK_NUMPAD4,VK_NUMPAD5,VK_NUMPAD6,VK_NUMPAD7,VK_NUMPAD8,VK_NUMPAD9, VK_MULTIPLY,VK_ADD,VK_SEPARATOR,VK_SUBTRACT,VK_DECIMAL,VK_DIVIDE, VK_F1,VK_F2,VK_F3,VK_F4,VK_F5,VK_F6,VK_F7,VK_F8,VK_F9,VK_F10,VK_F11,VK_F12, VK_F13,VK_F14,VK_F15,VK_F16,VK_F17,VK_F18,VK_F19,VK_F20,VK_F21,VK_F22,VK_F23,VK_F24, VK_NUMLOCK ); GKeyNames:array[0..106] of string=( '<none>', 'BACK', 'TAB', 'CLEAR', 'RETURN', 'SHIFT', 'CONTROL', 'MENU', 'PAUSE', 'CAPITAL', 'ESCAPE', 'SPACE', 'PRIOR', 'NEXT', 'END', 'HOME', 'LEFT','UP','RIGHT','DOWN', 'SELECT', 'PRINT', 'EXECUTE', 'SNAPSHOT', 'INSERT', 'DELETE', 'HELP', '0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'LWIN', 'RWIN', 'APPS', 'NUMPAD0','NUMPAD1','NUMPAD2','NUMPAD3','NUMPAD4','NUMPAD5','NUMPAD6','NUMPAD7','NUMPAD8','NUMPAD9', 'MULTIPLY','ADD','SEPARATOR','SUBTRACT','DECIMAL','DIVIDE', 'F1','F2','F3','F4','F5','F6','F7','F8','F9','F10','F11','F12', 'F13','F14','F15','F16','F17','F18','F19','F20','F21','F22','F23','F24', 'NUMLOCK' ); procedure Register; implementation uses TypInfo; {$R SyntaxHighlight.dcr} procedure Register; begin RegisterComponents('Editors',[TSyntaxHighlighter, TSyntaxHighlightMemo, TTextEditorFooter]); RegisterPropertyEditor(TypeInfo(TShortCut),nil,'',TShortCutProperty); RegisterComponentEditor(TCustomSyntaxHighlightMemo,TSyntaxHighlightMemoEditor); end; { TShortCutProperty } function TShortCutProperty.GetAttributes: TPropertyAttributes; begin Result:=[paSubProperties,paReadOnly]; end; procedure TShortCutProperty.GetProperties(Proc: TGetPropProc); begin Proc(TNestedShiftStateProperty.Create(Self)); Proc(TNestedKeyProperty.Create(Self)); end; function TShortCutProperty.GetValue: string; begin Result:=ShortCutToText(GetOrdValue); end; procedure TShortCutProperty.SetValue(const Value: string); begin ; end; { TNestedShiftStateProperty } constructor TNestedShiftStateProperty.Create(Parent: TPropertyEditor); begin inherited Create(Parent); FParent:=Parent as TShortCutProperty; end; function TNestedShiftStateProperty.GetAttributes: TPropertyAttributes; begin Result:=[paSubProperties,paValueList,paSortList]; end; function TNestedShiftStateProperty.GetName: string; begin Result:='ShiftState'; end; procedure TNestedShiftStateProperty.GetProperties(Proc: TGetPropProc); var u:TShift; begin for u:=ssShift to ssDouble do Proc(TNestedShiftProperty.Create(Self,u)); end; function TNestedShiftStateProperty.GetValue: string; var k:Word; s:TShiftState; u:TShift; begin Result:=''; ShortCutToKey(FParent.GetOrdValue,k,s); if s=[] then Result:='<none>' else for u:=ssShift to ssDouble do if u in s then begin if Result<>'' then Result:=Result+'+'; Result:=Result+GShiftNames[u]; end; end; procedure TNestedShiftStateProperty.GetValues(Proc: TGetStrProc); begin Proc('<None>'); Proc('Shift'); Proc('Alt'); Proc('Ctrl'); Proc('Alt+Ctrl'); Proc('Alt+Shift'); Proc('Shift+Ctrl'); Proc('Shift+Alt+Ctrl'); end; procedure TNestedShiftStateProperty.SetValue(const Value: string); var u:TShift; s,t:TShiftState; k:Word; begin s:=[]; for u:=ssShift to ssDouble do if Pos(AnsiLowerCase(GShiftNames[u]),AnsiLowerCase(Value))>0 then Include(s,u); ShortCutToKey(FParent.GetOrdValue,k,t); FParent.SetOrdValue(ShortCut(k,s)); end; { TNestedShiftProperty } constructor TNestedShiftProperty.Create(Parent: TPropertyEditor; AShift: TShift); begin inherited Create(Parent); FParent:=(Parent as TNestedShiftStateProperty).FParent; FShift:=AShift; end; function TNestedShiftProperty.GetAttributes: TPropertyAttributes; begin Result:=[paValueList,paSortList]; end; function TNestedShiftProperty.GetName: string; begin Result:=GShiftNames[FShift]; end; function TNestedShiftProperty.GetValue: string; var k:Word; s:TShiftState; begin ShortCutToKey(FParent.GetOrdValue,k,s); if FShift in s then Result:='True' else Result:='False'; end; procedure TNestedShiftProperty.GetValues(Proc: TGetStrProc); begin Proc('True'); Proc('False'); end; procedure TNestedShiftProperty.SetValue(const Value: string); var k:Word; s:TShiftState; begin ShortCutToKey(FParent.GetOrdValue,k,s); if AnsiLowerCase(Value)='true' then Include(s,FShift) else Exclude(s,FShift); FParent.SetOrdValue(ShortCut(k,s)); end; { TNestedKeyProperty } constructor TNestedKeyProperty.Create(Parent: TPropertyEditor); begin inherited Create(Parent); FParent:=Parent as TShortCutProperty; end; function TNestedKeyProperty.GetAttributes: TPropertyAttributes; begin Result:=[paValueList,paSortList]; end; function TNestedKeyProperty.GetName: string; begin Result:='Key'; end; function TNestedKeyProperty.GetValue: string; var k:Word; s:TShiftState; a:Integer; begin ShortCutToKey(FParent.GetOrdValue,k,s); Result:='0x'+IntToHex(k,2); for a:=0 to High(GKeys) do if GKeys[a]=k then Result:=GKeyNames[a]; end; procedure TNestedKeyProperty.GetValues(Proc: TGetStrProc); var a:Integer; begin for a:=0 to High(GKeyNames) do Proc(GKeyNames[a]); end; function HexToInt(s:string):Cardinal; var a:Integer; u:Cardinal; begin Result:=0; s:=LowerCase(s); u:=1; for a:=Length(s) downto 1 do begin case s[a] of '0'..'9':Result:=Result+u*(Cardinal(Ord(s[a]))-Cardinal(Ord('0'))); 'a'..'f':Result:=Result+u*(10+Cardinal(Ord(s[a]))-Cardinal(Ord('a'))); else raise Exception.Create('"'+s+'" is not a valid hexadecimal value'); end; u:=u*16; end; end; procedure TNestedKeyProperty.SetValue(const Value: string); var k:Word; s:TShiftState; a:Integer; t:Boolean; begin t:=False; ShortCutToKey(FParent.GetOrdValue,k,s); for a:=0 to High(GKeys) do if LowerCase(GKeyNames[a])=LowerCase(Value) then begin k:=GKeys[a]; t:=True; end; if not t then begin if LowerCase(Copy(Value,1,2))<>'0x' then raise EConvertError.Create('Unrecognized key: "'+Value+'"'); k:=HexToInt(Copy(Value,3,Length(Value))); end; FParent.SetOrdValue(ShortCut(k,s)); end; { TSyntaxHighlightMemoEditor } procedure TSyntaxHighlightMemoEditor.Edit; begin TCustomSyntaxHighlightMemo(Component).Customize; end; procedure TSyntaxHighlightMemoEditor.ExecuteVerb(Index: Integer); begin TCustomSyntaxHighlightMemo(Component).Customize; end; function TSyntaxHighlightMemoEditor.GetVerb(Index: Integer): string; begin Result:='Customize'; end; function TSyntaxHighlightMemoEditor.GetVerbCount: Integer; begin Result:=1; end; end.
unit ZPrintReport; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, frxClass, frxDBSet, cxLookAndFeelPainters, ExtCtrls, StdCtrls, cxButtons, cxDropDownEdit, cxFontNameComboBox, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit, cxLabel, cxPropertiesStore, Registry, ActnList; type FieldInfo = record fieldname: string; caption: string; alignment: TAlignment; order: short; width: single; aggregative_function: string; end; TPrintReport = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; cxLabel1: TcxLabel; cxLabel2: TcxLabel; cxLabel3: TcxLabel; cxLabel4: TcxLabel; GroupBox1: TGroupBox; GroupBox2: TGroupBox; GroupBox4: TGroupBox; cxComboBox1: TcxComboBox; cxFontNameComboBox1: TcxFontNameComboBox; cxSpinEdit1: TcxSpinEdit; cxSpinEdit2: TcxSpinEdit; cxSpinEdit3: TcxSpinEdit; cxSpinEdit4: TcxSpinEdit; cxButton1: TcxButton; cxButton2: TcxButton; Panel1: TPanel; cxPropertiesStore1: TcxPropertiesStore; ActionList1: TActionList; Enter: TAction; Esc: TAction; procedure Panel1Click(Sender: TObject); procedure OnKeyPress(Sender: TObject; var Key: Char); procedure ReportCreate ({ FIBDataSet: TpFIBDataSet; frxReport: TfrxReport; frxDBDataSet: TfrxDBDataSet; strTitle: string; // TableName: string; n,m: short; FieldstoOrder: array of FieldInfo; OtherFields: array of FieldInfo; Margins: array of short; pageorient: boolean = false; FontType: string = 'Arial'; FontSize: short = 10}); procedure cxButton1Click(Sender: TObject); procedure cxButton2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure EnterExecute(Sender: TObject); procedure EscExecute(Sender: TObject); private public FIBDataSet: TpFIBDataSet; frxReport: TfrxReport; frxDBDataSet: TfrxDBDataSet; strTitle: string; n,m: short; FieldstoOrder: array of FieldInfo; OtherFields: array of FieldInfo; Margins: array of short; PageOrient: boolean; FontType: string; FontSize: short; inquiry: string; end; implementation {$R *.dfm} procedure TPrintReport.FormCreate(Sender: TObject); var Reg:TRegistry; begin PageOrient:=false; FontType:=cxFontNameComboBox1.FontName; cxFontNameComboBox1.FontName:='Times New Roman'; Reg:=TRegistry.Create; Reg.RootKey:=HKEY_CURRENT_USER; try Reg.OpenKey ('\Software\cxPropertiesStore',false); if Reg.ValueExists ('PageOrient') then PageOrient:=Reg.ReadBool('PageOrient'); if Reg.ValueExists ('PageFontName') then cxFontNameComboBox1.FontName:=Reg.ReadString('PageFontName'); finally Reg.Free; End; if PageOrient then begin panel1.Caption:='Альбомна'; panel1.Top:=181; panel1.Left:=51; panel1.Height:=70; panel1.Width:=96; end else begin panel1.Caption:='Портретна'; panel1.Top:=168; panel1.Left:=64; panel1.Height:=96; panel1.Width:=70; end; end; procedure TPrintReport.FormClose(Sender: TObject; var Action: TCloseAction); var Reg:TRegistry; begin Reg:=TRegistry.Create; Reg.RootKey:=HKEY_CURRENT_USER; try Reg.OpenKey ('\Software\cxPropertiesStore',true); Reg.WriteBool ('PageOrient',PageOrient); Reg.WriteString ('PageFontName',cxFontNameComboBox1.FontName); finally Reg.Free; end; end; procedure TPrintReport.cxButton2Click(Sender: TObject); begin ModalResult:=mrcancel; end; procedure TPrintReport.Panel1Click(Sender: TObject); var t: short; begin if (not PageOrient) then begin PageOrient:=true; panel1.Caption:='Альбомна'; panel1.Top:=181; panel1.Left:=51; end else begin PageOrient:=false; panel1.Caption:='Портретна'; panel1.Top:=168; panel1.Left:=64; end; t:=panel1.Height; panel1.Height:=panel1.Width; panel1.Width:=t; end; procedure TPrintReport.OnKeyPress(Sender: TObject; var Key: Char); begin if not (key in ['0'..'9',#8]) then begin key := #0; beep; end; end; procedure TPrintReport.cxButton1Click(Sender: TObject); begin //Showmessage('2134'); if Length(cxComboBox1.Text)>2 then begin FontSize:=12; cxComboBox1.Text:='12'; end else FontSize:=strtoint(cxComboBox1.Text); if FontSize>72 then begin FontSize:=72; cxComboBox1.Text:='72'; end; if FontSize<5 then begin FontSize:=5; cxComboBox1.Text:='5'; end; SetLength(Margins,4); if (cxSpinEdit1.Value<1) or (cxSpinEdit1.Value>20) then begin ShowMessage('Відступ має бути більш ніж 0 та меньш ніж 20.'); cxSpinEdit1.Value:=15; exit; end; if (cxSpinEdit2.Value<1) or (cxSpinEdit2.Value>20) then begin ShowMessage('Відступ має бути більш ніж 0 та меньш ніж 20.'); cxSpinEdit2.Value:=15; exit; end; if (cxSpinEdit3.Value<1) or (cxSpinEdit3.Value>20) then begin ShowMessage('Відступ має бути більш ніж 0 та меньш ніж 20.'); cxSpinEdit3.Value:=15; exit; end; if (cxSpinEdit4.Value<1) or (cxSpinEdit4.Value>20) then begin ShowMessage('Відступ має бути більш ніж 0 та меньш ніж 20.'); cxSpinEdit4.Value:=15; exit; end; Margins[0]:=cxSpinEdit2.Value; Margins[1]:=cxSpinEdit1.Value; Margins[2]:=cxSpinEdit4.Value; Margins[3]:=cxSpinEdit3.Value; FontType:=cxFontNameComboBox1.FontName; ReportCreate; end; procedure TPrintReport.ReportCreate( {FIBDataSet: TpFIBDataSet; frxReport: TfrxReport; frxDBDataSet: TfrxDBDataSet; strTitle: string; // TableName: string; n,m: short; FieldstoOrder: array of FieldInfo; OtherFields: array of FieldInfo; Margins: array of short; PageOrient: boolean; FontType: string; FontSize: short}); var Page: TfrxReportPage; RepSummary: TfrxReportSummary; DataBand: TfrxMasterData; Band: TfrxBand; PageHeader: TfrxPageHeader; Memo: TfrxMemoView; line: TfrxLineView; b1gh: TfrxGroupHeader; b1gf: TfrxGroupFooter; i,j,k,l,colwidth: short; str,str1: string; pagewidth: extended; f: single; ADESC: array [0..1] of string[5]; colswidth: array of short; begin if (FontSize>72) or (FontSize<5) then begin ShowMessage('Будь ласка введіть правильний розмір шрифту'); exit; end; for i:=0 to m-1 do begin str:=OtherFields[i].aggregative_function; if str<>'' then begin for j:=0 to length(str) do str[j]:=UpCase(str[j]); OtherFields[i].aggregative_function:=str; end; if (str<>'')and(str<>'SUM')and(str<>'MAX')and(str<>'MIN')and(str<>'AVG')and(str<>'COUNT') then begin ShowMessage('Field '+OtherFields[i].fieldname+' has wrong aggregative function'); OtherFields[i].aggregative_function:=''; end; end; SetLength(colswidth,n+m); adesc[0]:=' desc'; adesc[1]:=' asc'; { str:='select '; for j:=0 to n+m-1 do begin if j<n then str:=str+FieldstoOrder[j].fieldname+',' else str:=str+OtherFields[j-n].fieldname+','; end; SetLength(str,Length(str)-1); str:=str+' from '+TableName; } str:=''; if n>0 then begin str:=' order by '+FieldstoOrder[0].fieldname+adesc[FieldstoOrder[0].order]; for j:=1 to n-1 do str:=str+','+FieldstoOrder[j].fieldname+adesc[FieldstoOrder[j].order]; end; FIBDataSet.Close; FIBDataSet.SQLs.SelectSQL.Text:=inquiry+str; FIBDataSet.Open; frxReport.Clear; frxReport.DataSets.Add(frxDBDataSet); Page := TfrxReportPage.Create(frxReport); Page.CreateUniqueName; Page.SetDefaults; if FontType<>'' then Page.Font.Name:=FontType; if FontSize<>0 then Page.Font.Size:=FontSize; Page.Orientation:=TPrinterOrientation(PageOrient); Page.LeftMargin:=Margins[0]; Page.TopMargin:=Margins[1]; Page.RightMargin:=Margins[2]; Page.BottomMargin:=Margins[3]; f:=0; k:=0; pagewidth:=Page.Width-3.85*(Margins[0]+Margins[2]); for i:=0 to n+m-1 do begin if i<n then begin if FieldstoOrder[i].width>0.0 then begin f:=f+FieldstoOrder[i].width; k:=k+1; end; end else if OtherFields[i-n].width>0.0 then begin f:=f+OtherFields[i-n].width; k:=k+1; end; end; if f>1.0 then begin ShowMessage('wrong columns width'); exit; end; if (m+n)>k then begin colwidth:=trunc(pagewidth*(1-f)/(m+n-k)); for i:=0 to n+m-1 do begin if i<n then begin if FieldstoOrder[i].width=0 then colswidth[i]:=colwidth else colswidth[i]:=trunc(FieldstoOrder[i].width*pagewidth); end else begin if OtherFields[i-n].width=0 then colswidth[i]:=colwidth else colswidth[i]:=trunc(OtherFields[i-n].width*pagewidth); end; end; end else begin for i:=0 to n+m-1 do begin if i<n then colswidth[i]:=trunc(FieldstoOrder[i].width*pagewidth) else colswidth[i]:=trunc(OtherFields[i-n].width*pagewidth); end; end; Memo:=TfrxMemoView.Create(Band); Memo.StretchMode:=smMaxHeight; Memo.Font.Size:=6; Memo.Text:='[<Date>] [<Time>]'; Memo.SetBounds(0,0,80,10); Band:=TfrxReportTitle.Create(Page); Band.CreateUniqueName; Band.Stretched:=true; Band.SetBounds(10,0,pagewidth,20); Memo:=TfrxMemoView.Create(Band); Memo.StretchMode:=smMaxHeight; Memo.Text:=strTitle; Memo.Font.Size:=trunc(FontSize*1.5); Memo.HAlign:=haCenter; Memo.Font.Style:=[fsbold]; Memo.SetBounds(0,0,pagewidth,20); pagewidth:=0; for i:=0 to n+m-1 do pagewidth:=pagewidth+colswidth[i]; PageHeader:=TfrxPageHeader.Create(Page); PageHeader.Top:=0; PageHeader.Stretched:=true; PageHeader.Height:=10; PageHeader.Stretched:=true; l:=0; k:=Page.Font.Size; for j:=0 to n+m-1 do begin Memo:=TfrxMemoView.Create(PageHeader); Memo.CreateUniqueName; Memo.StretchMode:=smMaxHeight; Memo.SetBounds(l,10,colswidth[j],25); l:=l+colswidth[j]; if j<n then begin Memo.Text:=Fieldstoorder[j].caption; Memo.Font.Size:=k+n-j; end else begin Memo.Text:=OtherFields[j-n].caption; Memo.Font.Size:=k; end; Memo.Font.Style:=[fsBold]; Memo.HAlign:=haCenter; Memo.VAlign:=TfrxVAlign(vaCenter); Memo.Frame.Style:=fsSolid; Memo.Frame.Typ:=[ftLeft, ftRight, ftTop, ftBottom]; end; l:=0;i:=0; for j:=0 to n-1 do begin b1gh := TfrxGroupHeader.Create(Page); b1gh.CreateUniqueName; b1gh.Stretched:=true; b1gh.Condition:=frxDBDataSet.Name+'."'+fieldstoorder[j].fieldname+'"'; b1gh.Top:=j*10; b1gh.Height:=10; Memo := TfrxMemoView.Create(b1gh); Memo.CreateUniqueName; Memo.StretchMode:=smMaxHeight; Memo.SetBounds(l, 0, trunc(pagewidth)-l, 10); Memo.Color:=RGB(235+j*2,235+j*2,170+(20-j*2)*j); Memo := TfrxMemoView.Create(b1gh); Memo.CreateUniqueName; Memo.StretchMode:=smMaxHeight; Memo.DataSet := frxDBDataSet; Memo.DataField := fieldstoorder[j].fieldname; Memo.SetBounds(l, 0, trunc(pagewidth)-l, 10); l:=l+colswidth[j]; Memo.HAlign := haLeft; Memo.Frame.Typ:=[ftLeft, ftRight, ftTop]; i:=0; for k:=0 to j do begin line:=TfrxLineView.Create(b1gh); line.StretchMode:=smMaxHeight; line.Left:=i; i:=i+colswidth[k]; line.Top:=0; line.Height:=10; line.Width:=0; end; end; DataBand := TfrxMasterData.Create(Page); DataBand.CreateUniqueName; DataBand.Stretched:=true; DataBand.DataSet := frxDBDataSet; DataBand.Top := n*10; DataBand.Height := 10; Memo := TfrxMemoView.Create(DataBand); Memo.CreateUniqueName; Memo.StretchMode:=smMaxHeight; Memo.Highlight.Condition:='<Line> mod 2 = 1'; Memo.Highlight.Color:=RGB(245,245,245); Memo.SetBounds(l, 0, trunc(pagewidth)-l, 10); Memo.Frame.Typ:=[ftLeft, ftRight, ftTop, ftBottom]; l:=0; for j:=0 to m-1 do begin Memo := TfrxMemoView.Create(DataBand); Memo.CreateUniqueName; Memo.StretchMode:=smMaxHeight; Memo.DataSet := frxDBDataSet; Memo.DataField :=OtherFields[j].fieldname; Memo.SetBounds(i+l, 0, colswidth[j+n], 10); l:=l+colswidth[j+n]; if OtherFields[j].alignment=taLeftJustify then Memo.HAlign := haLeft else if OtherFields[j].alignment=taRightJustify then Memo.HAlign := haRight else Memo.HAlign := haCenter; Memo.Frame.Typ:=[ftLeft]; end; l:=0; for i:=0 to n-1 do l:=l+colswidth[i]; for j:=n-1 downto 0 do begin b1gf:=TfrxGroupFooter.Create(Page); b1gf.CreateUniqueName; b1gf.Stretched:=true; b1gf.Top:=10*(2*n-j+2); b1gf.Height:=0; if j=n-1 then begin k:=0; for i:=0 to m-1 do begin if length(OtherFields[i].aggregative_function)>0 then begin b1gf.Height:=10; Memo:=TfrxMemoView.Create(b1gf); Memo.CreateUniqueName; Memo.StretchMode:=smMaxHeight; str:='['+OtherFields[i].aggregative_function+'('; if OtherFields[i].aggregative_function<>'COUNT' then Memo.Text:=str+'<'+frxDBDataSet.Name+'."'+OtherFields[i].fieldname+'">,'+DataBand.Name+')]' else Memo.Text:=str+DataBand.Name+')]'; Memo.Font.Style:=[fsBold]; Memo.HAlign:=haRight; Memo.SetBounds(l+k,0,colswidth[n+i],10); Memo.Frame.Typ:=[ftLeft, ftRight, ftTop, ftBottom]; end; k:=k+colswidth[n+i]; end; k:=0; if b1gf.Height=10 then begin for i:=0 to n-2 do begin line:=TfrxLineView.Create(b1gf); line.StretchMode:=smMaxHeight; line.Left:=k; line.Top:=0; line.Height:=10; line.Width:=0; k:=k+colswidth[i]; end; if n>=2 then begin line:=TfrxLineView.Create(b1gf); line.StretchMode:=smMaxHeight; line.Left:=pagewidth; line.Top:=0; line.Height:=10; line.Width:=0; end; end; end; l:=l-colswidth[j]; line:=TfrxLineView.Create(b1gf); line.Left:=l; line.Top:=0; line.Height:=0; if j<>0 then line.Width:=colswidth[j] else line.Width:=pagewidth; line:=TfrxLineView.Create(DataBand); line.StretchMode:=smMaxHeight; line.Left:=l; line.Top:=0; line.Height:=10; line.Width:=0; end; if n=0 then begin RepSummary:=TfrxReportSummary.Create(Page); RepSummary.Height:=10; k:=0; for i:=0 to m-1 do begin if OtherFields[i].aggregative_function<>'' then begin Memo:=TfrxMemoView.Create(RepSummary); Memo.CreateUniqueName; Memo.StretchMode:=smMaxHeight; str:='['+OtherFields[i].aggregative_function+'('; if OtherFields[i].aggregative_function<>'COUNT' then Memo.Text:=str+'<'+frxDBDataSet.Name+'."'+OtherFields[i].fieldname+'">,'+DataBand.Name+')]' else Memo.Text:=str+DataBand.Name+')]'; Memo.Font.Style:=[fsBold]; Memo.SetBounds(l+k,0,colswidth[n+i],10); Memo.Frame.Typ:=[ftLeft, ftRight, ftTop, ftBottom]; end; k:=k+colswidth[n+i]; end; end; Band:=TfrxPageFooter.Create(Page); Band.CreateUniqueName; Band.SetBounds(0,0,pagewidth,20); Memo:=TfrxMemoView.Create(Band); Memo.Text:='[Page]'; Memo.Font.Size:=12; Memo.HAlign:=haRight; Memo.SetBounds(pagewidth-40,0,40,20); Memo:=TfrxMemoView.Create(Band); Memo.StretchMode:=smMaxHeight; Memo.Font.Size:=6; Memo.Text:='[<Date>] [<Time>]'; Memo.SetBounds(0,10,80,10); frxReport.ShowReport(); end; procedure TPrintReport.EnterExecute(Sender: TObject); begin cxButton1Click(self); end; procedure TPrintReport.EscExecute(Sender: TObject); begin ModalResult:=mrcancel; end; end.
unit nsErrRestoreFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, nsGlobals, nsTypes, StrUtils; type TfrmErrorRestore = class(TForm) btnYes: TButton; Image1: TImage; Label1: TLabel; Label6: TLabel; Label4: TLabel; cbEncryption: TComboBox; lblPassword: TLabel; edtPassword: TEdit; chkMask1: TCheckBox; btnYesToAll: TButton; btnIgnore: TButton; btnAbort: TButton; pbFile: TLabel; procedure chkMask1Click(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } FileName: string; procedure GetSettings(AProject: TNSProject; AItem: TNSItem); public { Public declarations } end; function ErrorRestoreDialog(AOwner: TForm; AProject: TNSProject; AItem: TNSItem; out AMethod: TEncryptionMethod; out APassword: string): TModalResult; implementation uses nsUtils; {$R *.dfm} function ErrorRestoreDialog(AOwner: TForm; AProject: TNSProject; AItem: TNSItem; out AMethod: TEncryptionMethod; out APassword: string): TModalResult; begin with TfrmErrorRestore.Create(AOwner) do try if AOwner <> nil then AOwner.Hide; GetSettings(AProject, AItem); Result := ShowModal; AMethod := TEncryptionMethod(cbEncryption.ItemIndex); APassword := edtPassword.Text; finally if AOwner <> nil then AOwner.Show; Free; end; end; { TErrorRestoreForm } procedure TfrmErrorRestore.FormShow(Sender: TObject); begin UpdateVistaFonts(Self); end; procedure TfrmErrorRestore.GetSettings(AProject: TNSProject; AItem: TNSItem); var Method: TEncryptionMethod; begin Image1.Picture.Icon.Handle := LoadIcon(GetModuleHandle('User32.dll'), PChar(101)); for Method := Low(TEncryptionMethod) to High(TEncryptionMethod) do cbEncryption.Items.Add(Encryptions[Method]^); cbEncryption.ItemIndex := Ord(g_Encryption); FileName := AItem.GetPathOnMedia + AItem.DisplayName; pbFile.Caption := FileName; end; procedure TfrmErrorRestore.chkMask1Click(Sender: TObject); begin if chkMask1.Checked then edtPassword.PasswordChar := #42 else edtPassword.PasswordChar := #0; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083210 //////////////////////////////////////////////////////////////////////////////// unit android.webkit.ConsoleMessage_MessageLevel; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JConsoleMessage_MessageLevel = interface; JConsoleMessage_MessageLevelClass = interface(JObjectClass) ['{4FB5C02B-4BCC-4A14-8240-D92E67E198DA}'] function _GetDEBUG : JConsoleMessage_MessageLevel; cdecl; // A: $4019 function _GetERROR : JConsoleMessage_MessageLevel; cdecl; // A: $4019 function _GetLOG : JConsoleMessage_MessageLevel; cdecl; // A: $4019 function _GetTIP : JConsoleMessage_MessageLevel; cdecl; // A: $4019 function _GetWARNING : JConsoleMessage_MessageLevel; cdecl; // A: $4019 function valueOf(&name : JString) : JConsoleMessage_MessageLevel; cdecl; // (Ljava/lang/String;)Landroid/webkit/ConsoleMessage$MessageLevel; A: $9 function values : TJavaArray<JConsoleMessage_MessageLevel>; cdecl; // ()[Landroid/webkit/ConsoleMessage$MessageLevel; A: $9 property DEBUG : JConsoleMessage_MessageLevel read _GetDEBUG; // Landroid/webkit/ConsoleMessage$MessageLevel; A: $4019 property ERROR : JConsoleMessage_MessageLevel read _GetERROR; // Landroid/webkit/ConsoleMessage$MessageLevel; A: $4019 property LOG : JConsoleMessage_MessageLevel read _GetLOG; // Landroid/webkit/ConsoleMessage$MessageLevel; A: $4019 property TIP : JConsoleMessage_MessageLevel read _GetTIP; // Landroid/webkit/ConsoleMessage$MessageLevel; A: $4019 property WARNING : JConsoleMessage_MessageLevel read _GetWARNING; // Landroid/webkit/ConsoleMessage$MessageLevel; A: $4019 end; [JavaSignature('android/webkit/ConsoleMessage_MessageLevel')] JConsoleMessage_MessageLevel = interface(JObject) ['{D132D393-7443-4B07-B43D-3690A6C6EE43}'] end; TJConsoleMessage_MessageLevel = class(TJavaGenericImport<JConsoleMessage_MessageLevelClass, JConsoleMessage_MessageLevel>) end; implementation end.
Unit uutama; Interface Uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ShellAPI, FileCtrl, XPMan, ComCtrls, StdCtrls; Type Tf0 = Class(TForm) c0: TLabel; c1: TDriveComboBox; c2: TButton; c3: TGroupBox; c4: TLabel; c5: TProgressBar; Procedure c2Click(Sender: TObject); Private { Deklarasi hanya untuk penggunaan dalam unit ini saja } Public { Deklarasi untuk penggunaan ke semua unit yang terintegerasi } va: longint; vb: String; End; (* Program : Simple Wiper Pengembang awal : Arachmadi Putra Pambudi Deskripsi : Membersihkan jejak (sisa) file yang sudah terhapus dalam sebuah drive / partisi Catatan : Tools ini dibuat sesederhana mungkin sehingga anda dapat mempelajari dan mengembangkannya Metode yang digunakan sangat sederhana yaitu mengisi space kosong pada drive dengan file random Anda dapat mengubah file random tersebut, file bernama wiper.raw Sebaiknya gunakan single-char copy supaya proses penindihan lebih efektif Penamaan variabel sengaja di minimalkan agar anda juga turut mempelajari alur setiap prosedur dan fungsi yang ada di proyek ini Lisensi : Gratis - Perangkat Lunak Sumber Terbuka *) Var f0: Tf0; Implementation {$R *.dfm} //template tweaked by : Araachmadi Putra Pambudi Function fa(a: Char): longint; Var b: String; c, d, e, f: DWord; Begin b := a + ':\'; GetDiskFreeSpace(PChar(b), c, d, e, f); Result := d * c * e; End; Function fb(a: Integer): String; Var b: String; Begin Randomize; b := 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234509876'; Result := ''; Repeat Result := Result + b[Random(Length(b)) + 1]; Until (Length(Result) = a) End; Function fc(a: String): boolean; Var b: TSHFileOpStruct; Begin ZeroMemory(@b, SizeOf(b)); With b Do Begin wFunc := FO_DELETE; fFlags := FOF_SILENT Or FOF_NOCONFIRMATION; pFrom := PChar(a + #0); End; Result := (0 = SHFileOperation(b)); End; Procedure Tf0.c2Click(Sender: TObject); Begin Try c2.Enabled := false; c3.Caption := 'Proses : menganalisa disk...'; va := fa(c1.Drive); c5.Max := (va Div (1024 * 1024)) - 4; c4.Caption := '0 MB dari ' + inttostr(va Div 1024) + ' MB'; vb := c1.Drive + ':\' + fb(32); MkDir(PChar(vb)); c3.Caption := 'Proses : menghancurkan sisa sektor...'; Repeat CopyFile(PChar(ExtractFilePath(Application.ExeName) + '\wiper.raw'), PChar(vb + '\' + fb(64)), true); Application.ProcessMessages; c5.Position := c5.Position + 4; c4.Caption := IntToStr(c5.Position) + ' MB dari ' + inttostr(va Div (1024 * 1024)) + ' MB'; Until fa(c1.Drive) < 4096000; c3.Caption := 'Proses : menyelesaikan...'; fc(vb); Application.ProcessMessages; ShowMessage('Drive anda berhasil dibersihkan !'); Finally c5.Position := 0; c4.Caption := '0 b dari 0 b'; c3.Caption := 'Proses : siap'; c2.Enabled := true; End; End; End.
unit ufrmPopupGrid; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, cxControls, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxButtons; type TfrmPopupGrid = class(TForm) PnlFooter: TPanel; pnlFooterBtn: TPanel; btnClose: TcxButton; pnlSortCut: TPanel; pnlBody: TPanel; pnlHeader: TPanel; lblHeader: TLabel; lblTopHeader: TLabel; cxGrid: TcxGrid; cxGridView: TcxGridDBTableView; cxlvMaster: TcxGridLevel; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure advclmngrdCanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); private FSQL: string; procedure SetData; { Private declarations } public procedure Init(aSql: string; aCaptionHeader: string=''); { Public declarations } end; var frmPopupGrid: TfrmPopupGrid; implementation uses uRetnoUnit; {$R *.dfm} procedure TfrmPopupGrid.Init(aSql: string; aCaptionHeader: string=''); begin FSQL := aSql; if aCaptionHeader = '' then begin pnlHeader.Visible := False; end else lblHeader.Caption := aCaptionHeader; end; procedure TfrmPopupGrid.SetData; var i: Integer; aColWidth: Integer; aRowHight: integer; begin {cQueryToGrid(FSQL, clmngrd); aColWidth := 0; //cek apakah ada data if advclmngrd.Cells[1, clmngrd.RowCount - 1] <> '' then begin for i := 0 to advclmngrd.ColCount - 1 do begin advclmngrd.AutoSizeCol(i); aColWidth := aColWidth + advclmngrd.ColWidths[i]; end; if Self.Width < aColWidth then begin if Screen.Width - 100 < aColWidth then Self.Width := Screen.Width - 100 else Self.Width := aColWidth + 20; end; aRowHight := 0; for i := 0 to advclmngrd.RowCount - 1 do begin aRowHight := aRowHight + advclmngrd.RowHeights[i]; end; if Self.Height < aRowHight then begin if Screen.Height - 50 < aRowHight then Self.Height := Screen.Height - 50 else Self.Width := aRowHight + 20 + pnlHeader.Height + PnlFooter.Height; end; end; } end; procedure TfrmPopupGrid.FormShow(Sender: TObject); begin SetData; end; procedure TfrmPopupGrid.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmPopupGrid.FormDestroy(Sender: TObject); begin frmPopupGrid := nil; end; procedure TfrmPopupGrid.advclmngrdCanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); begin CanEdit := False; end; end.
program SearchRndElementInRndArray; uses Crt; const Arrlen = 10; var Arr: Array [1..Arrlen] of integer; Key: integer; IsFound: boolean; i: integer; begin randomize; for i := 1 to Arrlen do begin Arr[i] := Random(15); end; writeln('Filled random Array: '); for i := 1 to Arrlen do begin write(Arr[i], ' '); end; Key := Random(15); IsFound := False; for i:=1 to Arrlen do begin if Arr[i] = Key then begin IsFound := True; break; end; end; if IsFound then begin writeln('Element ', Key, ' is found!'); end else begin writeln('Element ', Key, ' not found'); end; end.
{ Syn Copyright © 2003-2004, Danail Traichev. All rights reserved. neum@developer.bg, The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is uParams.pas, released Thu, 27 Mar 2003 10:22:27 UTC. The Initial Developer of the Original Code is Danail Traichev. Portions created by Danail Traichev are Copyright © 2003-2004 Danail Traichev. All Rights Reserved. Contributor(s): . Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. You may retrieve the latest version of this file at the home page, located at http://syn.sourceforge.net $Id: uParams.pas,v 1.12 2004/06/07 23:03:48 neum Exp $ } unit uParams; interface Uses Classes; (* parameters, valid for current Windows configuration *) procedure RegisterStandardParametersAndModifiers; procedure UnRegisterStandardParametersAndModifiers; procedure RegisterCustomParams; procedure UnRegisterCustomParams; Var CustomParams : TStringList; implementation uses Windows, SysUtils, Dialogs, Clipbrd, ComCtrls, jclFileUtils, jclDateTime, jclStrings, JclSysInfo, cParameters, Registry, uEditAppIntfs, JvBrowseFolder, dmCommands, VarPyth, SynRegExpr, uCommonFunctions, frmPyIDEMain, StringResources; function GetActiveDoc: string; Var Editor : IEditor; begin Result:= ''; Editor := PyIDEMainForm.GetActiveEditor; if Assigned(Editor) then Result:= Editor.GetFileNameOrTitle; end; function GetModFiles: string; var i: integer; begin Result:= ''; if Assigned(GI_EditorFactory) then begin with GI_EditorFactory do for i := 0 to GetEditorCount - 1 do with Editor[i] do if GetModified and (GetFileName <> '') then Result := Concat(Result, ' ', ExtractShortPathName(GetFileName)); Delete(Result, 1, 1); end; end; function GetOpenFiles: string; var i: integer; begin Result:= ''; if Assigned(GI_EditorFactory) then begin with GI_EditorFactory do for i := 0 to GetEditorCount - 1 do with Editor[i] do if GetFileName <> '' then Result := Concat(Result, ' ', ExtractShortPathName(GetFileName)); Delete(Result, 1, 1); end; end; function GetCurWord(const AFileName: string): string; var AEditor: IEditor; begin Result:= ''; if (AFileName = '') or SameText('ActiveDoc', AFileName) then AEditor:= GI_ActiveEditor else AEditor := GI_EditorFactory.GetEditorByName(AFileName); if Assigned(AEditor) then Result:= AEditor.GetSynEdit.WordAtCursor; end; function GetCurLine(const AFileName: string): string; var AEditor: IEditor; begin Result:= ''; if (AFileName = '') or SameText('ActiveDoc', AFileName) then AEditor:= GI_ActiveEditor else AEditor:= GI_EditorFactory.GetEditorByName(AFileName); if Assigned(AEditor) then Result:= AEditor.GetSynEdit.LineText; end; function GetSelText(const AFileName: string): string; var AEditor: IEditor; begin Result:= ''; if (AFileName = '') or SameText('ActiveDoc', AFileName) then AEditor:= GI_ActiveEditor else AEditor:= GI_EditorFactory.GetEditorByName(AFileName); if Assigned(AEditor) then Result:= AEditor.GetSynEdit.SelText; end; function SelectFile(const ATitle: string): string; var SaveTitle: string; begin with CommandsDataModule.dlgFileOpen do begin Filter := SFilterAllFiles; SaveTitle:= Title; if ATitle <> '' then Title:= ATitle else Title := 'Select File'; if Execute then begin Result:= FileName; Parameters.ChangeParameter('SelectedFile', FileName); end; Title:= SaveTitle; end; end; function SelectDir(const ATitle: string): string; begin if BrowseDirectory(Result, ATitle, 0) then Parameters.ChangeParameter('SelectedDir', Result); end; function StrDefQuote(const AText: string): string; begin Result:= StrQuote(AText, '"'); end; function GetDateTime: string; begin Result:= DateTimeToStr(Now); end; function GetDate(const AText: string): string; begin Result:= DateToStr(StrToDateTime(AText)); end; function GetTime(const AText: string): string; begin Result:= TimeToStr(StrToDateTime(AText)); end; function GetFileDate(const AFileName: string): string; begin Result:= ''; if FileExists(AFileName) then Result:= DateTimeToStr(FileDateToDateTime(FileAge(AFileName))); end; function GetFileDateCreate(const AFileName: string): string; begin Result:= ''; if FileExists(AFileName) then Result:= DateTimeToStr(FileTimeToDateTime(GetFileCreation(AFileName))); end; function GetFileDateWrite(const AFileName: string): string; begin Result:= ''; if FileExists(AFileName) then Result:= DateTimeToStr(FileTimeToDateTime(GetFileLastWrite(AFileName))); end; function GetFileDateAccess(const AFileName: string): string; begin Result:= ''; if FileExists(AFileName) then Result:= DateTimeToStr(FileTimeToDateTime(GetFileLastAccess(AFileName))); end; function GetDateFormated(const AText: string): string; var // i: Integer; RegExpr : TRegExpr; begin RegExpr := TRegExpr.Create; try RegExpr.Expression := '([^'']+)-''([^'']+)'''; if RegExpr.Exec(AText)then Result:= FormatDateTime(RegExpr.Match[2], StrToDateTime(RegExpr.Match[1])) else raise EParameterError.CreateFmt(Translate(SInvalidParameterFormat), [Concat(AText, '-', 'DateFormat')]); finally RegExpr.Free; end; end; function GetExe: string; begin Result:= ParamStr(0); end; function GetParam(const AIndex: string): string; (* Returns the commandline argument *) var ix: integer; begin Result := ''; if StrConsistsOfNumberChars(AIndex) then begin ix := StrToInt(AIndex); if ix <= ParamCount then Result := ParamStr(ix); end; end; function GetClipboard: string; (* returns clipboard as text *) begin Result:= Clipboard.AsText; end; function GetFileExt(const AFileName: string): string; (* returns extension without . *) begin Result:= ExtractFileExt(AFileName); if Result <> '' then Delete(Result, 1, 1); end; function GetReg(const ARegKey: string): string; (* returns registry key value *) var Info: TRegDataInfo; AName: string; i: Integer; Buff: Pointer; begin with TRegistry.Create(KEY_READ and not KEY_NOTIFY) do try Result:= ''; if ARegKey = '' then Exit; i:= Pos('\', ARegKey); (* read root key *) if i > 1 then begin AName:= Copy(ARegKey, 1, i-1); if (AName = 'HKCU') or (AName = 'HKEY_CURRENT_USER') then RootKey:= HKEY_CURRENT_USER else if (AName = 'HKLM') or (AName = 'HKEY_LOCAL_MACHINE') then RootKey:= HKEY_LOCAL_MACHINE else if (AName = 'HKCR') or (AName = 'HKEY_CLASSES_ROOT') then RootKey:= HKEY_CLASSES_ROOT else if (AName = 'HKU') or (AName = 'HKEY_USERS') then RootKey:= HKEY_USERS else if (AName = 'HKPD') or (AName = 'HKEY_PERFORMANCE_DATA') then RootKey:= HKEY_PERFORMANCE_DATA else if (AName = 'HKCC') or (AName = 'HKEY_CURRENT_CONFIG') then RootKey:= HKEY_CURRENT_CONFIG else if (AName = 'HKDD') or (AName = 'HKEY_DYN_DATA') then RootKey:= HKEY_DYN_DATA; AName:= Copy(ARegKey, i, MaxInt); end else AName:= ARegKey; (* if key exists, read key data *) if OpenKeyReadOnly(ExtractFilePath(AName)) then begin AName:= ExtractFileName(ARegKey); if not GetDataInfo(AName, Info) then Info.RegData:= rdUnknown; (* convert value to string *) case Info.RegData of rdString, rdExpandString: Result:= ReadString(AName); rdInteger: Result:= IntToStr(ReadInteger(AName)); rdUnknown, rdBinary: begin GetMem(Buff, Info.DataSize); try ReadBinaryData(AName, Buff^, Info.DataSize); SetLength(Result, 2 * Info.DataSize); BinToHex(Buff, PChar(Result), Info.DataSize); finally FreeMem(Buff); end; end; end; end; finally Free; end; end; function GetFileText(const AFileName: string): string; (* returns file text (searches editor and project enviroment too) *) var AEditor: IEditor; begin Result:= ''; // look in open files AEditor:= GI_EditorFactory.GetEditorByNameOrTitle(AFileName); if Assigned(AEditor) then Result:= AEditor.GetSynEdit.Text else begin if FileExists(AFileName) then Result:= FileToStr(AFileName); end; end; function GetShortFileName(const APath: string): string; (* returns short file name even for nonexisting files *) begin if APath = '' then Result:= '' else begin Result:= PathGetShortName(APath); // if different - function is working if (Result = '') or (Result = APath) and not FileExists(PathRemoveSeparator(APath)) then begin Result:= ExtractFilePath(APath); // we are up to top level if (Result = '') or (Result[Length(Result)] = ':') then Result:= APath else Result:= Concat(GetShortFileName(PathRemoveSeparator(Result)), PathDelim, ExtractFileName(APath)); end; end; end; function GetActivePythonDir : string; begin Result := IncludeTrailingPathDelimiter(SysModule.prefix); end; function GetPythonDir (VersionString : string) : string; {$IFDEF MSWINDOWS} var key : String; AllUserInstall : Boolean; {$ENDIF} begin Result := ''; // Python provides for All user and Current user installations // All User installations place the Python DLL in the Windows System directory // and write registry info to HKEY_LOCAL_MACHINE // Current User installations place the DLL in the install path and // the registry info in HKEY_CURRENT_USER. // Hence, for Current user installations we need to try and find the install path // since it may not be on the system path. AllUserInstall := False; key := Format('\Software\Python\PythonCore\%s\InstallPath', [VersionString]); try with TRegistry.Create do try RootKey := HKEY_LOCAL_MACHINE; if OpenKey(Key, False) then Result := ReadString(''); finally Free; end; except // under WinNT, with a user without admin rights, the access to the // LocalMachine keys would raise an exception. end; // We do not seem to have an All User Python Installation. // Check whether we have a current user installation if not AllUserInstall then with TRegistry.Create do try RootKey := HKEY_CURRENT_USER; if OpenKey(Key, False) then Result := ReadString(''); finally Free; end; if Result <> '' then Result := IncludeTrailingPathDelimiter(Result); end; function GetPythonVersion: string; begin Result := SysModule.version; end; procedure RegisterStandardParametersAndModifiers; begin with Parameters do begin (* parameters, valid for current Windows configuration *) // Python Paths etc. RegisterParameter('Python23Dir', GetPythonDir('2.3'), nil); RegisterParameter('Python24Dir', GetPythonDir('2.4'), nil); RegisterParameter('Python25Dir', GetPythonDir('2.5'), nil); RegisterParameter('Python23Exe', '$[PYTHON23DIR]python.exe', nil); RegisterParameter('Python24Exe', '$[PYTHON24DIR]python.exe', nil); RegisterParameter('Python25Exe', '$[PYTHON25DIR]python.exe', nil); RegisterParameter('PythonDir', 'Directory of active python version', GetActivePythonDir); RegisterParameter('PythonExe', '$[PYTHONDIR]python.exe', nil); RegisterParameter('PythonVersion', 'Version of active Python', GetPythonVersion); // register system paths and parameters RegisterParameter('ProgramFiles', 'Program Files directory', GetProgramFilesFolder); RegisterParameter('CommonFiles', 'Common Files directory', GetCommonFilesFolder); RegisterParameter('Windows', 'Windows installation directory', GetWindowsFolder); RegisterParameter('WindowsSystem', 'Windows System directory', GetWindowsSystemFolder); RegisterParameter('WindowsTemp', 'Windows Temp Directory', GetWindowsTempFolder); RegisterParameter('MyDocuments', 'MyDocuments directory', GetPersonalFolder); RegisterParameter('Desktop', 'Desktop Directory', GetDesktopDirectoryFolder); // register parameters RegisterParameter('Paste', 'Clipboard As Text', GetClipboard); RegisterParameter('UserName', 'User Name', GetLocalUserName); RegisterParameter('CurrentDir', 'Current Directory', GetCurrentFolder); RegisterParameter('Exe', 'Executable Name', GetExe); // register parameter modifiers RegisterModifier('Path', 'Path of file', ExtractFilePath); RegisterModifier('Dir', 'Path without delimeter', ExtractFileDir); RegisterModifier('Name', 'File name', ExtractFileName); RegisterModifier('Ext', 'File Extension', ExtractFileExt); RegisterModifier('ExtOnly', 'File extension without "."', GetFileExt); RegisterModifier('NoExt', 'File name without extension', PathRemoveExtension); RegisterModifier('Drive', 'File drive', ExtractFileDrive); RegisterModifier('Full', 'Expanded file name', ExpandFileName); RegisterModifier('UNC', 'Expanded UNC file name', ExpandUNCFileName); RegisterModifier('Long', 'Long file name', GetLongFileName); RegisterModifier('Short', 'Short file name', GetShortFileName); RegisterModifier('Sep', 'Path with separator added', PathAddSeparator); RegisterModifier('NoSep', 'Path with final separator removed', PathRemoveSeparator); RegisterModifier('Type', 'File type', FileGetTypeName); RegisterModifier('Text', 'Contents of text file', FileToStr); RegisterModifier('Param', 'Command line parameter', GetParam); RegisterModifier('Reg', 'Value of registry key', GetReg); RegisterModifier('Env', 'Value of environment variable', GetEnvironmentVariable); RegisterModifier('UpperCase', 'Upper case of string', AnsiUpperCase); RegisterModifier('LowerCase', 'Lpper case of string', AnsiLowerCase); RegisterModifier('Quote', 'Quoted string', StrDefQuote); RegisterModifier('UnQuote', 'Unquoted string', StrUnquote); (* parameters, specific for PyScripter *) RegisterParameter('SelectFile', '$[-SelectFile]', nil); RegisterParameter('SelectedFile', '', nil); RegisterParameter('SelectDir', '$[-SelectDir]', nil); RegisterParameter('SelectedDir', '', nil); RegisterParameter('DateTime', 'Current Date and Time', GetDateTime); RegisterModifier('SelectFile', 'Select file', SelectFile); RegisterModifier('SelectDir', 'Select directory', SelectDir); RegisterModifier('Date', 'Date of a datetime value', GetDate); RegisterModifier('Time', 'Time of a datetime value', GetTime); RegisterModifier('FileDate', 'Date of a file', GetFileDate); RegisterModifier('DateCreate', 'Creation date of a file', GetFileDateCreate); RegisterModifier('DateWrite', 'Last modification date of a file', GetFileDateWrite); RegisterModifier('DateAccess', 'Last access date of a file', GetFileDateAccess); RegisterModifier('DateFormat', 'Formatted date', GetDateFormated); (* parameters, that change often in one syn session *) (* editor related *) RegisterParameter('ActiveDoc', 'Active Document Name', GetActiveDoc); RegisterParameter('ModFiles', 'Modified Files', GetModFiles); RegisterParameter('OpenFiles', 'Open Files', GetOpenFiles); RegisterParameter('CurWord', '$[-CurWord]', nil); RegisterParameter('CurLine', '$[-CurLine]', nil); RegisterParameter('SelText', '$[-SelText]', nil); RegisterModifier('EdText', 'Text of the active document or a file', GetFileText); RegisterModifier('CurWord', 'Current word in the active document', GetCurWord); RegisterModifier('CurLine', 'Current line in the active document', GetCurLine); RegisterModifier('SelText', 'Selected text in the active document', GetSelText); end; end; procedure UnRegisterStandardParametersAndModifiers; begin // unregister parameter modifiers with Parameters do begin (* parameters, valid for current Windows configuration *) // Python Paths etc. UnRegisterParameter('Python24Dir'); UnRegisterParameter('Python23Dir'); UnRegisterParameter('Python24Exe'); UnRegisterParameter('Python23Exe'); UnRegisterParameter('PythonDir'); UnRegisterParameter('PythonExe'); UnRegisterParameter('PythonVersion'); // unregister system paths and parameters UnRegisterParameter('ProgramFiles'); UnRegisterParameter('CommonFiles'); UnRegisterParameter('Windows'); UnRegisterParameter('WindowsSystem'); UnRegisterParameter('WindowsTemp'); UnRegisterParameter('MyDocuments'); UnRegisterParameter('Desktop'); // unregister parameters UnRegisterParameter('Paste'); UnRegisterParameter('UserName'); UnRegisterParameter('CurrentDir'); UnRegisterParameter('Exe'); // unregister modifiers UnRegisterModifier('Path'); UnRegisterModifier('Dir'); UnRegisterModifier('Name'); UnRegisterModifier('Ext'); UnRegisterModifier('ExtOnly'); UnRegisterModifier('NoExt'); UnRegisterModifier('Drive'); UnRegisterModifier('Full'); UnRegisterModifier('UNC'); UnRegisterModifier('Long'); UnRegisterModifier('Short'); UnRegisterModifier('Sep'); UnRegisterModifier('NoSep'); UnRegisterModifier('Type'); UnRegisterModifier('Text'); UnRegisterModifier('Param'); UnRegisterModifier('Reg'); UnRegisterModifier('Env'); UnRegisterModifier('UpperCase'); UnRegisterModifier('LowerCase'); UnRegisterModifier('Quote'); UnRegisterModifier('UnQuote'); (* parameters, specific for syn *) UnRegisterParameter('SelectFile'); UnRegisterParameter('SelectedFile'); UnRegisterParameter('SelectDir'); UnRegisterParameter('SelectedDir'); UnRegisterParameter('DateTime'); UnRegisterModifier('SelectFile'); UnRegisterModifier('SelectDir'); UnRegisterModifier('Date'); UnRegisterModifier('Time'); UnRegisterModifier('FileDate'); UnRegisterModifier('DateCreate'); UnRegisterModifier('DateWrite'); UnRegisterModifier('DateAccess'); UnRegisterModifier('DateFormat'); (* parameters, that change often in one syn session *) (* editor related *) UnRegisterParameter('ActiveDoc'); UnRegisterParameter('ModFiles'); UnRegisterParameter('OpenFiles'); UnRegisterParameter('CurWord'); UnRegisterParameter('CurLine'); UnRegisterParameter('SelText'); UnRegisterModifier('EdText'); UnRegisterModifier('CurWord'); UnRegisterModifier('CurLine'); UnRegisterModifier('SelText'); end; end; procedure RegisterCustomParams; Var i : integer; ParamName : string; begin with Parameters do begin Clear; Modifiers.Clear; RegisterStandardParametersAndModifiers; for i := 0 to CustomParams.Count - 1 do begin ParamName := CustomParams.Names[i]; if ParamName <> '' then RegisterParameter(ParamName, CustomParams.Values[ParamName], nil); end; Sort; end; CommandsDataModule.PrepareParameterCompletion; end; procedure UnRegisterCustomParams; begin Parameters.Clear; Parameters.Modifiers.Clear; RegisterStandardParametersAndModifiers; Parameters.Sort; end; initialization CustomParams := TStringList.Create; RegisterStandardParametersAndModifiers; Parameters.Sort; finalization FreeAndNil(CustomParams); end.
unit MeshVxt; // Mesh with Westwood Voxel Support (for Voxel Section Editor III) interface {$INCLUDE source/Global_Conditionals.inc} {$ifdef VOXEL_SUPPORT} uses dglOpenGL, GLConstants, Voxel, Normals, BasicMathsTypes, BasicDataTypes, BasicRenderingTypes, Palette, SysUtils, ShaderBank, MeshGeometryList, MeshGeometryBase, Mesh; type TGetCardinalAttr = function: cardinal of object; TMeshVxt = class (TMesh) protected // I/O procedure LoadFromVoxel(const _Voxel : TVoxelSection; const _Palette : TPalette); procedure LoadFromVisibleVoxels(const _Voxel : TVoxelSection; const _Palette : TPalette); procedure LoadTrisFromVisibleVoxels(const _Voxel : TVoxelSection; const _Palette : TPalette); procedure LoadManifoldsFromVisibleVoxels(const _Voxel : TVoxelSection; const _Palette : TPalette); procedure CommonVoxelLoadingActions(const _Voxel : TVoxelSection); public NumVoxels : longword; // for statistic purposes. // Constructors And Destructors constructor Create(const _Mesh : TMeshVxt); overload; constructor CreateFromVoxel(_ID : longword; const _Voxel : TVoxelSection; const _Palette : TPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED); destructor Destroy; override; procedure Clear; // I/O procedure RebuildVoxel(const _Voxel : TVoxelSection; const _Palette : TPalette; _Quality: integer = C_QUALITY_CUBED); // Copies procedure Assign(const _Mesh : TMesh); override; end; PMeshVxt = ^TMeshVxt; {$endif} implementation {$ifdef VOXEL_SUPPORT} uses GlobalVars, VoxelMeshGenerator, NormalsMeshPlugin, NeighborhoodDataPlugin, MeshBRepGeometry, BumpMapDataPlugin, BasicConstants, BasicFunctions, NeighborDetector, StopWatch; constructor TMeshVxt.Create(const _Mesh : TMeshVxt); begin Assign(_Mesh); GetNumVertices := GetNumVerticesCompressed; GetLastVertex := GetLastVertexCompressed; end; constructor TMeshVxt.CreateFromVoxel(_ID : longword; const _Voxel : TVoxelSection; const _Palette : TPalette; _ShaderBank: PShaderBank; _Quality: integer = C_QUALITY_CUBED); var c : integer; begin ShaderBank := _ShaderBank; Geometry := CMeshGeometryList.Create; Clear; ColoursType := C_COLOURS_PER_FACE; ColourGenStructure := C_COLOURS_PER_FACE; ID := _ID; TransparencyLevel := C_TRP_OPAQUE; NumVoxels := 0; c := 1; while (c <= 16) and (_Voxel.Header.Name[c] <> #0) do begin Name := Name + _Voxel.Header.Name[c]; inc(c); end; case _Quality of C_QUALITY_CUBED: begin LoadFromVoxel(_Voxel,_Palette); end; C_QUALITY_VISIBLE_CUBED: begin LoadFromVisibleVoxels(_Voxel,_Palette); end; C_QUALITY_VISIBLE_TRIS: begin LoadTrisFromVisibleVoxels(_Voxel,_Palette); end; C_QUALITY_VISIBLE_MANIFOLD: begin LoadManifoldsFromVisibleVoxels(_Voxel,_Palette); end; C_QUALITY_LANCZOS_QUADS: begin LoadFromVisibleVoxels(_Voxel,_Palette); // MeshLanczosSmooth; end; C_QUALITY_2LANCZOS_4TRIS: begin LoadFromVisibleVoxels(_Voxel,_Palette); // MeshLanczosSmooth; // RebuildFaceNormals; // SetVertexNormals; // ConvertFaceToVertexColours; // ConvertQuadsTo48Tris; end; C_QUALITY_LANCZOS_TRIS: begin LoadFromVisibleVoxels(_Voxel,_Palette); // MeshLanczosSmooth; // ConvertQuadsToTris; // RebuildFaceNormals; // SetVertexNormals; // ConvertFaceToVertexColours; end; C_QUALITY_SMOOTH_MANIFOLD: begin LoadManifoldsFromVisibleVoxels(_Voxel,_Palette); // SetVertexNormals; // ConvertFaceToVertexColours; end; end; IsColisionEnabled := false; // Temporarily, until colision is implemented. IsVisible := true; IsSelected := false; Next := -1; Son := -1; GetNumVertices := GetNumVerticesCompressed; GetLastVertex := GetLastVertexCompressed; end; destructor TMeshVxt.Destroy; begin Clear; inherited Destroy; end; procedure TMeshVxt.Clear; begin FOpened := false; ForceRefresh; SetLength(Vertices,0); SetLength(Colours,0); SetLength(Normals,0); SetLength(TexCoords,0); Geometry.Clear; ClearMaterials; ClearPlugins; end; // I/O; procedure TMeshVxt.RebuildVoxel(const _Voxel : TVoxelSection; const _Palette : TPalette; _Quality: integer = C_QUALITY_CUBED); var HasNormalsMeshPlugin: boolean; begin HasNormalsMeshPlugin := IsPluginEnabled(C_MPL_NORMALS); Clear; ColourGenStructure := C_COLOURS_PER_FACE; if ColoursType <> C_COLOURS_PER_FACE then begin SetColoursType(C_COLOURS_PER_FACE); end; case _Quality of C_QUALITY_CUBED: begin LoadFromVoxel(_Voxel,_Palette); end; C_QUALITY_VISIBLE_CUBED: begin LoadFromVisibleVoxels(_Voxel,_Palette); end; C_QUALITY_VISIBLE_TRIS: begin LoadTrisFromVisibleVoxels(_Voxel,_Palette); end; C_QUALITY_VISIBLE_MANIFOLD: begin LoadManifoldsFromVisibleVoxels(_Voxel,_Palette); end; C_QUALITY_LANCZOS_QUADS: begin LoadFromVisibleVoxels(_Voxel,_Palette); // MeshLanczosSmooth; end; C_QUALITY_2LANCZOS_4TRIS: begin LoadFromVisibleVoxels(_Voxel,_Palette); // MeshLanczosSmooth; // RebuildFaceNormals; // SetVertexNormals; // ConvertFaceToVertexColours; // ConvertQuadsTo48Tris; end; C_QUALITY_LANCZOS_TRIS: begin LoadFromVisibleVoxels(_Voxel,_Palette); // MeshLanczosSmooth; // ConvertQuadsToTris; // RebuildFaceNormals; // SetVertexNormals; // ConvertFaceToVertexColours; end; C_QUALITY_SMOOTH_MANIFOLD: begin LoadManifoldsFromVisibleVoxels(_Voxel,_Palette); // SetVertexNormals; // ConvertFaceToVertexColours; end; end; if HasNormalsMeshPlugin then begin AddNormalsPlugin; end; OverrideTransparency; end; procedure TMeshVxt.LoadFromVoxel(const _Voxel : TVoxelSection; const _Palette : TPalette); var MeshGen: TVoxelMeshGenerator; {$ifdef SPEED_TEST} StopWatch : TStopWatch; {$endif} begin {$ifdef SPEED_TEST} StopWatch := TStopWatch.Create(true); {$endif} SetNormalsType(C_NORMALS_PER_FACE); Geometry.Add(C_GEO_BREP4); // Geometry.Current^ := TMeshBRepGeometry.Create(0,4,ColoursType,NormalsType); // This is the complex part of the thing. We'll map all vertices and faces // and make a model out of it. MeshGen := TVoxelMeshGenerator.Create; MeshGen.LoadFromVoxels(_Voxel,_Palette,Vertices,TexCoords,Geometry,NumVoxels); NumFaces := Geometry.Current^.NumFaces; MeshGen.Free; CommonVoxelLoadingActions(_Voxel); {$ifdef SPEED_TEST} StopWatch.Stop; GlobalVars.SpeedFile.Add('LoadFromVoxels for ' + Name + ' takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.'); StopWatch.Free; {$endif} end; procedure TMeshVxt.LoadFromVisibleVoxels(const _Voxel : TVoxelSection; const _Palette : TPalette); var MeshGen: TVoxelMeshGenerator; {$ifdef SPEED_TEST} StopWatch : TStopWatch; {$endif} begin {$ifdef SPEED_TEST} StopWatch := TStopWatch.Create(true); {$endif} SetNormalsType(C_NORMALS_PER_FACE); Geometry.Add(C_GEO_BREP4); // This is the complex part of the thing. We'll map all vertices and faces // and make a model out of it. MeshGen := TVoxelMeshGenerator.Create; MeshGen.LoadFromVisibleVoxels(_Voxel,_Palette,Vertices,TexCoords,Geometry,NumVoxels); NumFaces := Geometry.Current^.NumFaces; MeshGen.Free; AddNeighborhoodPlugin; CommonVoxelLoadingActions(_Voxel); {$ifdef SPEED_TEST} StopWatch.Stop; GlobalVars.SpeedFile.Add('LoadFromVisibleVoxels for ' + Name + ' takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.'); StopWatch.Free; {$endif} end; procedure TMeshVxt.LoadManifoldsFromVisibleVoxels(const _Voxel : TVoxelSection; const _Palette : TPalette); var MeshGen: TVoxelMeshGenerator; {$ifdef SPEED_TEST} StopWatch : TStopWatch; {$endif} begin {$ifdef SPEED_TEST} StopWatch := TStopWatch.Create(true); {$endif} SetNormalsType(C_NORMALS_PER_FACE); Geometry.Add(C_GEO_BREP4); // This is the complex part of the thing. We'll map all vertices and faces // and make a model out of it. MeshGen := TVoxelMeshGenerator.Create; MeshGen.LoadManifoldsFromVisibleVoxels(_Voxel,_Palette,Vertices,Geometry,TexCoords,NumVoxels); NumFaces := Geometry.Current^.NumFaces; MeshGen.Free; CommonVoxelLoadingActions(_Voxel); {$ifdef SPEED_TEST} StopWatch.Stop; GlobalVars.SpeedFile.Add('LoadManifoldsFromVisibleVoxels for ' + Name + ' takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.'); StopWatch.Free; {$endif} end; procedure TMeshVxt.LoadTrisFromVisibleVoxels(const _Voxel : TVoxelSection; const _Palette : TPalette); var MeshGen: TVoxelMeshGenerator; {$ifdef SPEED_TEST} StopWatch : TStopWatch; {$endif} begin {$ifdef SPEED_TEST} StopWatch := TStopWatch.Create(true); {$endif} SetNormalsType(C_NORMALS_PER_FACE); Geometry.Add(C_GEO_BREP3); // This is the complex part of the thing. We'll map all vertices and faces // and make a model out of it. MeshGen := TVoxelMeshGenerator.Create; MeshGen.LoadTrianglesFromVisibleVoxels(_Voxel,_Palette,Vertices,TexCoords,Geometry,NumVoxels); NumFaces := Geometry.Current^.NumFaces; MeshGen.Free; CommonVoxelLoadingActions(_Voxel); {$ifdef SPEED_TEST} StopWatch.Stop; GlobalVars.SpeedFile.Add('LoadTrisFromVisibleVoxels for ' + Name + ' takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.'); StopWatch.Free; {$endif} end; procedure TMeshVxt.CommonVoxelLoadingActions(const _Voxel : TVoxelSection); begin // The rest SetLength(Normals,0); SetLength(Colours,0); SetLength(TexCoords,0); BoundingBox.Min.X := _Voxel.Tailer.MinBounds[1]; BoundingBox.Min.Y := _Voxel.Tailer.MinBounds[2]; BoundingBox.Min.Z := _Voxel.Tailer.MinBounds[3]; BoundingBox.Max.X := _Voxel.Tailer.MaxBounds[1]; BoundingBox.Max.Y := _Voxel.Tailer.MaxBounds[2]; BoundingBox.Max.Z := _Voxel.Tailer.MaxBounds[3]; AddMaterial; BoundingScale.X := (BoundingBox.Max.X - BoundingBox.Min.X) / _Voxel.Tailer.XSize; BoundingScale.Y := (BoundingBox.Max.Y - BoundingBox.Min.Y) / _Voxel.Tailer.YSize; BoundingScale.Z := (BoundingBox.Max.Z - BoundingBox.Min.Z) / _Voxel.Tailer.ZSize; Scale.X := _Voxel.Tailer.Det; Scale.Y := _Voxel.Tailer.Det; Scale.Z := _Voxel.Tailer.Det; FOpened := true; end; // Copies procedure TMeshVxt.Assign(const _Mesh : TMesh); begin NumVoxels := (_Mesh as TMeshVxt).NumVoxels; inherited Assign(_Mesh); end; {$endif} end.
(* ABSSPELL.PAS - Copyright (c) 1995-1996, Eminent Domain Software *) unit AbsSpell; {-Abstract Spell Checking Dialog Form} {$D-} {$L-} interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Menus, ExtCtrls, EDSUtil, SpellGbl; const {Modal Results for Spell Dialog and CheckWord} mrReplace = 20; mrAdd = 21; mrSkipOnce = 22; mrSkipAll = 23; mrReplaceAll = 24; mrSuggest = 25; type TAccents = (acSpanish); TAccentSet = Set of TAccents; TAbsSpellDialog = class (TForm) private { Private declarations } FSuggestions: Byte; {number of words to suggest} // FAccents: TAccentSet; {set of accents to display on dialog} FLanguage: TLanguages; {current label language} procedure CreateParams (var Params: TCreateParams); override; procedure SetLanguage (ToLanguage: TLanguages); {-calls SetLabelLanguage (used for property)} public { Public declarations } SpellDlgResult: Integer; constructor Create (AOwner: TComponent); override; destructor Destroy; override; {--- Labels and Prompts ----} procedure SetNotFoundPrompt (ToString: String); dynamic; abstract; {-sets the not found prompt} procedure SetNotFoundCaption (ToString: String); dynamic; abstract; {-sets the not found caption} procedure SetEditWord (ToWord: String); dynamic; abstract; {-sets the edit word string} function GetEditWord: String; dynamic; abstract; {-gets the edit word} procedure SetEditAsActive; dynamic; abstract; {-sets activecontrol the edit control} procedure SetLabelLanguage; dynamic; {-sets labels and buttons to a the language} {--- Buttons ---} procedure RemoveGlyphs; virtual; {-removes the glyphs from the buttons} procedure EnableSkipButtons; dynamic; abstract; {-enables the Skip and Skip All buttons} {-or Ignore and Ignore All} procedure DisableSkipButtons; dynamic; abstract; {-disables the Skip and Skip All buttons} {-or Ignore and Ignore All} {--- Accented Buttons ---} procedure SetAccentSet (Accents: TAccentSet); dynamic; abstract; {-sets the accented buttons to be displayed} {--- Suggest List ----} procedure ClearSuggestList; dynamic; abstract; {-clears the suggest list} procedure MakeSuggestions; dynamic; abstract; {-sets the suggest list} property Suggestions: Byte read FSuggestions write FSuggestions; property Language: TLanguages read FLanguage write SetLanguage; end; { TAbsSpellDialog } implementation constructor TAbsSpellDialog.Create (AOwner: TComponent); begin inherited Create (AOwner); end; { TAbsSpellDialog.Create } procedure TAbsSpellDialog.CreateParams (var Params: TCreateParams); begin inherited CreateParams (Params); if Parent {Application.MainForm} <> nil then Params.WndParent := Parent{Application.MainForm}.Handle; end; { TAbsSpellDialog.CreateParams } procedure TAbsSpellDialog.SetLabelLanguage; {-sets labels and buttons to a the language} begin if not (FLanguage in [lgEnglish {$IFDEF SupportBritish} ,lgBritish {$ENDIF} ]) then Caption := SpellTitle[FLanguage]; end; { TAbsSpellDialog.SetLabelLanguage } procedure TAbsSpellDialog.SetLanguage (ToLanguage: TLanguages); {-sets labels and buttons to a the language} begin FLanguage := ToLanguage; SetLabelLanguage; end; { TAbsSpellDialog.SetLanguage } procedure TAbsSpellDialog.RemoveGlyphs; {-removes the glyphs from the buttons} var i: integer; begin for i := 0 to ComponentCount - 1 do begin if (Components[i] is TBitBtn) then with Components[i] as TBitBtn do begin if not Glyph.Empty then begin {free bitmap} Glyph := nil; end; { if... } end; { with } end; { next i } end; { TAbsSpellDialog.RemoveGlyphs } destructor TAbsSpellDialog.Destroy; begin inherited Destroy; end; { TAbsSpellDialog.Destroy } end. { AbsSpell }
unit Roles; {$mode objfpc}{$H+} interface uses DecConsts,Field; type TRoleFunc=procedure(num: integer); type TRole=(roleIdle, roleKeeper, roleKeeperDefendPenalty, roleKeeperPassive, roleAtackerKicker, roleAtackerReceiver, roleReceivePass, roleMamao, roleAtackerSupporter, roleLastDefender, roleOtherDefender, roleRoundLastDefender, roleRoundOtherDefender, roleFreeKick, roleKickOff, rolePenaltyKick, roleScorePenaltyKick, roleStayBack, roleBarrierMain, roleBarrierAux, roleBarrierInterceptor, roleWaitForKickOff, roleRobotRobotDefender, roleDefend3, roleWingmanL, roleWingmanR , roleWaitForFreeKick, roleWaitToThrowIn, roleThrowIn, roleWaitForCornerKick, roleCornerKick, roleWaitOurGoalKick, roleWaitDroppedBall, roleMidfield, roleMidOfMidfield,roleMidOfMidfieldRight,roleMidOfMidfieldLeft,roleGoPosStart, roleGoPosStop, roleNavigateToLocalize, roleFurtiveAtackerKicker, roleTest, roleGoSearch1, roleGoSearch2, roleGoSearch3, roleGoSearch4, //TIAGO TESE roleGoSearch, roleGoSearchFollower, roleDoFormation ); type TRoleDef = record name: string; func: TRoleFunc; is_keeper_role: boolean; end; var deltadist,deltateta:double; procedure RoleIdleRules(num: integer); procedure RoleGoPosStartRules(num: integer); procedure RoleGoPosStopRules(num: integer); procedure RoleKeeperRules(num: integer); procedure RoleKeeperDefendPenaltyRules(num: integer); procedure RoleKeeperPassiveRules(num: integer); procedure roleAtackerKickerRules(num: integer); procedure roleAtackerKicker2Rules(num: integer); procedure roleAtackerReceiverRules(num: integer); procedure roleReceivePassRules(num: integer); procedure roleLastDefenderRules(num: integer); procedure RoleFreeKickRules(num: integer); procedure RoleKickOffRules(num: integer); procedure RolePenaltyKickRules(num: integer); procedure RoleScorePenaltyKickRules(num: integer); procedure RoleStayBackRules(num: integer); procedure RoleMamaoRules(num: integer); procedure RoleGoSearchRules1(num: integer); procedure RoleGoSearchRules2(num: integer); procedure RoleGoSearchRules3(num: integer); procedure RoleGoSearchRules4(num: integer); procedure RoleBarrierMainRules(num: integer); procedure roleWaitForKickOffRules(num: integer); procedure RoleWaitForFreeKickRules(num: integer); procedure RoleWaitToThrowInRules(num: integer); procedure RoleThrowInRules(num: integer); procedure RoleWaitForCornerKickRules(num: integer); procedure RoleCornerKickRules(num: integer); procedure RoleWaitOurGoalLickRules(num: integer); procedure RoleOurGoalLickRules(num: integer); procedure RoleWaitDroppedBallRules(num:integer); procedure RoleMidfieldRules(num: integer); procedure RoleMidOfMidfieldRules(num: integer); procedure RoleMidOfMidfieldRightRules(num: integer); procedure RoleMidOfMidfieldLeftRules(num: integer); procedure RoleNavigateToLocalizeRules(num:integer); procedure RoleFurtiveAtackerKickerRules(num:integer); ////// procedure roleOtherDefenderRules(num: integer); procedure RoleRoundLastDefenderRules(num: integer); procedure RoleRoundOtherDefenderRules(num: integer); procedure RoleAtackerSupporterRules(num: integer); procedure GetBarrierPosition(offset: double; var bx, by, teta: double); procedure roleBarrierAuxRules(num: integer); procedure roleBarrierInterceptorRules(num: integer); procedure roleRobotRobotDefenderRules(num: integer); procedure RoleDefend3Rules(num: integer); procedure RoleWingmanRRules(num: integer); procedure RoleWingmanLRules(num: integer); //TIAGO TESE procedure RoleTestRules(num: integer); procedure RoleDoFormationRules(num: integer); procedure RoleGoSearchRules(num: integer); procedure RoleGoSearchFollowerRules(num: integer); procedure GetReceiverPosition(offset: double; var bx, by, teta: double); const RoleDefs: array[low(TRole) .. High(TRole)] of TRoleDef = ( ( name:'roleIdle'; func: @RoleIdleRules ), ( name:'roleKeeper'; func: @RoleKeeperRules; is_keeper_role:true ), ( name:'roleKeeperDefendPenalty'; func: @roleKeeperDefendPenaltyRules; is_keeper_role:true ), ( name:'roleKeeperPassive'; func: @roleKeeperPassiveRules; is_keeper_role:true ), ( name:'roleAtackerKicker'; func: @roleAtackerKickerRules ), ( name:'roleAtackerReceiver'; func: @roleAtackerReceiverRules ), ( name:'roleReceivePass'; func: @roleReceivePassRules ), ( name:'roleMamao'; func: @roleMamaoRules ), ( name:'roleAtackerSupporter'; func: @roleAtackerSupporterRules ), ( name:'roleLastDefender'; func: @roleLastDefenderRules ), ( name:'roleOtherDefender'; func: @roleOtherDefenderRules ), ( name:'roleRoundLastDefender'; func: @roleRoundLastDefenderRules ), ( name:'roleRoundOtherDefender'; func: @roleRoundOtherDefenderRules ), ( name:'roleFreeKick'; func: @roleFreeKickRules ), ( name:'roleKickOff'; func: @roleKickOffRules ), ( name:'rolePenaltyKick'; func: @rolePenaltyKickRules ), ( name:'roleScorePenaltyKick'; func: @roleScorePenaltyKickRules ), ( name:'roleStayBack'; func: @roleStayBackRules ), ( name:'roleBarrierMain'; func: @roleBarrierMainRules ), ( name:'roleBarrierAux'; func: @roleBarrierAuxRules ), ( name:'roleBarrierInterceptor'; func: @roleBarrierInterceptorRules ), ( name:'roleWaitForKickOff'; func: @roleWaitForKickOffRules ), ( name:'roleRobotRobotDefender'; func: @roleRobotRobotDefenderRules ), ( name:'roleDefend3'; func: @roleDefend3Rules ), ( name:'roleWingmanR'; func: @roleWingmanRRules ), ( name:'roleWingmanL'; func: @roleWingmanLRules ), ( name:'roleWaitForFreeKick'; func: @roleWaitForFreeKickRules ), ( name:'roleWaitToThrowIn'; func: @roleWaitToThrowInRules ), ( name:'roleThrowIn'; func: @roleThrowInRules ), ( name:'roleWaitForCornerKick'; func: @roleWaitForCornerKickRules ), ( name:'roleCornerKick'; func: @roleCornerKickRules ), ( name:'roleWaitOurGoalKick'; func: @roleWaitOurGoalLickRules), ( name:'roleWaitDroppedBall'; func: @RoleWaitDroppedBallRules), ( name:'RoleMidfield'; func: @RoleMidfieldRules), ( name:'RoleMidOfMidfield'; func: @RoleMidOfMidfieldRules), ( name:'roleMidOfMidfieldLeft'; func: @RoleMidOfMidfieldLeftRules), ( name:'roleMidOfMidfieldRight'; func: @RoleMidOfMidfieldRightRules), ( name:'roleGoPosStart'; func: @RoleGoPosStartRules), ( name:'roleGoPosStop'; func: @RoleGoPosStopRules), ( name:'roleNavigateToLocalize'; func: @RoleNavigateToLocalizeRules), ( name:'roleFurtiveAtackerKicker'; func: @RoleFurtiveAtackerKickerRules), ( name:'roleTest'; func: @roleTestRules ), ( name:'roleGoSearch1'; func: @roleGoSearchRules1 ), ( name:'roleGoSearch2'; func: @roleGoSearchRules2 ), ( name:'roleGoSearch3'; func: @roleGoSearchRules3 ), ( name:'roleGoSearch4'; func: @roleGoSearchRules4 ), //TIAGO TESE ( name:'roleGoSearchFollower'; func: @roleGoSearchFollowerRules ), ( name:'roleGoSearch'; func: @roleGoSearchRules ), ( name:'roleDoFormation'; func: @RoleDoFormationRules) ); implementation uses Main, Tasks, Actions, Tactic, Param, Utils, Analyser, Math, ObsAvoid, {Unit_RolesAux,}MPC; //---------------------------------------------------------------------- // Role Rules //---------------------------------------------------------------------- procedure RoleIdleRules(num: integer); begin RobotInfo[num].task:=taskIdle; end; function BallNearCorner(c: double): boolean; var ang: double; begin ang:=ATan2(Abs(BallState.y)-(-0.25),BallState.x-(-FieldLength*0.5)); result:=(Abs(BallState.y)>0.48-0.1*c) and (not (ang<0)) and (ang>(Pi/2-(30*Pi/180)*c)); end; procedure RoleGoPosStartRules(num: integer); begin with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin x1 := Xstart; y1:= Ystart; teta := 0; speed := 2; end; deltadist:=0.09; deltateta:=5; task:=taskGoToGoodPosition; end; end; procedure RoleGoPosStopRules(num: integer); begin with RobotInfo[num], TaskPars[num] do begin x1 := Xstop; y1:= Ystop; teta := 0; speed := SpeedMax*0.5; deltadist:=0.09; deltateta:=5; if (Dist(x1-RobotState[num].x,y1-RobotState[num].y)<0.2) then task:=taskIdle else task:=taskGoToGoodPosition; end; end; procedure RoleKeeperRules(num: integer); var time_to_goal, target_y,target_x, dist_ball_area,otherTeta: double; begin if ((abs(BallState.y)>FieldDims.AreaWidth/2) or (BallState.x>-FieldDims.FieldDepth/2+FieldDims.AreaDepth) or (BallState.quality<=500)) then begin deltadist:=0.04; deltateta:=5; RobotInfo[num].task:=taskKeepGoalSafe; end; if ((abs(BallState.y)<=FieldDims.AreaWidth/2) and (BallState.x<=-FieldDims.FieldDepth/2+FieldDims.AreaDepth) and (BallState.x>=-FieldDims.FieldDepth/2) and (BallState.quality>=500)) then begin deltadist:=0.04; deltateta:=5; RobotInfo[num].task:=taskGetRidOfBall end; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleKeeperDefendPenaltyRules(num: integer); begin RobotInfo[num].task:=taskDefendPenalty; end; procedure RoleKeeperPassiveRules(num: integer); begin RobotInfo[num].task:=taskKeepGoalSafe; end; procedure roleAtackerKicker2Rules(num: integer); var d,ang,ang_ball,tgx,tgy,rob_dist,BSv,Bx,By: double; begin // with RobotInfo[num] do begin GetTargetForGoal(tgx,tgy,0); // state rules TaskPars[num].x1 := tgx; TaskPars[num].y1 := tgy; speedontgt:=0.1; // case RobotInfo[num].task of taskCatchBall: begin if RobotState[num].withball=true then begin task:=taskdribleForGoal; end; end; taskdribleForGoal: begin if (RobotState[num].withball=false) then begin task:=taskCatchBall; end; end; else task:=taskCatchBall; end; if ((abs(BallState.x)>(FieldDims.FieldDepth/2)) or (abs(BallState.y)>(FieldDims.FieldWidth/2))or ((BallState.x>(FieldDims.FieldDepth/2)-(FieldDims.KeeperAreaDepth)) and (abs(BallState.y)<(FieldDims.KeeperAreaWidth/2)))) then begin task:=taskIdle; end; end; end; procedure roleAtackerKickerRules(num: integer); var d,ang,ang_ball,tgx,tgy,rob_dist,BSv,Bx,By: double; begin with RobotInfo[num] do begin GetTargetForGoal(tgx,tgy,0); // angulo do robo em relacao ao angulo de vector bola baliza ang:=DiffAngle(RobotState[num].teta,Atan2(tgy - BallState.y, tgx - BallState.x)) * 180 / Pi; // distancia em relacao à bola d := Dist(RobotState[num].x - BallState.x, RobotState[num].y - BallState.y); // angulo do robo em relacao ao angulo de vector bola ang_ball := DiffAngle(Atan2(BallState.y - RobotState[num].y, BallState.x - RobotState[num].x),RobotState[num].teta) * 180 / Pi; // state rules TaskPars[num].x1 := tgx; TaskPars[num].y1 := tgy; speedontgt:=0.1; // case task of taskGoToBall: begin if ((abs(ang)<5) and (abs(ang_ball)<6) and (RobotState[num].w<0.1) and (d<(tkToBallDist+0.08))) then begin task:=taskdribleForGoal; end; end; taskdribleForGoal: begin if (((abs(ang)>10)or(d>=tkToBallDist+0.10)or(ang_ball>20))) then begin task:=taskGoToBall; end; end; else task:=taskGoToBall; end; if ((abs(BallState.x)>(FieldDims.FieldDepth/2)) or (abs(BallState.y)>(FieldDims.FieldWidth/2))or ((BallState.x>(FieldDims.FieldDepth/2)-(FieldDims.KeeperAreaDepth)) and (abs(BallState.y)<(FieldDims.KeeperAreaWidth/2)))) then begin task:=taskIdle; end; end; end; procedure roleAtackerReceiverRules(num: integer); begin with RobotInfo[num] do begin with TaskPars[num] do begin StopDistance:=ReceiverDistance; x1 := BallState.x; // if BallState.y >1 then y1 := BallState.y - StopDistance else if BallState.y<=0.1 then y1 := BallState.y + StopDistance; // teta := -ATan2(y1-BallState.y,x1-BallState.x); speed := SpeedMax; end; deltadist:=0.04; deltateta:=2; task:=taskGoToGoodPosition; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin task:=taskIdle; end; end; end; procedure roleReceivePassRules(num: integer); var d: double; begin with RobotInfo[num] do begin // distancia em relacao à bola d := Dist(RobotState[num].x - BallState.x, RobotState[num].y - BallState.y); with TaskPars[num] do begin StopDistance:=ReceiverDistance; x1 := BallState.x; if BallState.y >1 then y1 := BallState.y - ReceiverDistance else if BallState.y<0.5 then y1 := BallState.y + ReceiverDistance; teta := -ATan2(y1-BallState.y,x1-BallState.x); speed := SpeedMax; end; deltadist:=0.05; deltateta:=2; task:=taskGoToGoodPosition; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin task:=taskIdle; end; end; end; procedure roleLastDefenderRules(num: integer); var target_y, time_to_goal: double; bx, by,d:double; begin PredictIncomingBallToGoal(time_to_goal, target_y, LastDefenderLine+0.08,2); deltadist:=0.09; deltateta:=5; RobotInfo[num].task:=taskDefendLineAngle; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure roleOtherDefenderRules(num: integer); begin deltadist:=0.09; deltateta:=5; RobotInfo[num].task:=taskDefendAngle; end; procedure RoleRoundLastDefenderRules(num: integer); var rx, ry, target, radius: double; begin with RobotInfo[num], TaskPars[num] do begin target := 0.5; radius := AreaWidth + 1.5; if VectorCircleIntersection( BallState.x, BallState.y, OurGoalX - BallState.x, target - BallState.y, OurGoalX, target, radius, rx, ry) then begin x1 := rx; y1 := ry; end; teta := RobotCalcData[num].ball_teta; speed := SpeedMax; avoid_is_set := true; avoid := [avoidRobot, avoidOurArea]; task:=taskGoToGoodPosition; end; end; procedure RoleRoundOtherDefenderRules(num: integer); var rx, ry, target, radius: double; begin with RobotInfo[num], TaskPars[num] do begin target := -0.015; radius := AreaWidth + 0.58; if VectorCircleIntersection( BallState.x, BallState.y, OurGoalX - BallState.x, target - BallState.y, OurGoalX, target, radius, rx, ry) then begin x1 := rx; y1 := ry; end; teta := RobotCalcData[num].ball_teta; speed := SpeedMax; avoid_is_set := true; avoid := [avoidRobot, avoidOponent, avoidOurArea]; task:=taskGoToGoodPosition; end; end; procedure CommonGoalKickRules(num: integer; wait_for_it: boolean); var d,ang,ang_ball,tgx,tgy,rob_dist: double; begin with RobotInfo[num], TaskPars[num] do begin tgx :=TheirGoalX; tgy := 0; speedontgt:=0; // diferenca entre a angulo target/robo e o angulo fo robo ang:=DiffAngle(RobotState[num].teta, Atan2(tgy - BallState.y, tgx - BallState.x)) * 180 / Pi; d := Dist(RobotState[num].x - BallState.x, RobotState[num].y - BallState.y); // diferenca entre angulo do robo e angulo com abola ang_ball := DiffAngle( Atan2(BallState.y - RobotState[num].y, BallState.x - RobotState[num].x), RobotState[num].teta) * 180 / Pi; TaskPars[num].x1 := tgx; TaskPars[num].y1 := tgy; case RobotInfo[num].task of taskBehindBall: begin if (not wait_for_it) and (abs(ang)<4) and (RobotState[num].w<0.1) and (d<tkToBallDist+0.03) and (abs(ang_ball)<10) then begin task:=taskScoreFreeKick; end; end; taskScoreFreeKick: begin if (abs(ang)>50) or (d>tkToBallDist+0.08) or (ang_ball>50) then begin task:=taskBehindBall; end; end; else task:=taskBehindBall; end; end; end; procedure CommonCornerKickRules(num: integer; wait_for_it: boolean); var d,ang,ang_ball,tgx,tgy,rob_dist: double; begin with RobotInfo[num], TaskPars[num] do begin tgx :=TheirGoalX-FieldDims.AreaDepth; tgy := 0; speedontgt:=0; // diferenca entre a angulo target/robo e o angulo fo robo ang:=DiffAngle(RobotState[num].teta, Atan2(tgy - BallState.y, tgx - BallState.x)) * 180 / Pi; d := Dist(RobotState[num].x - BallState.x, RobotState[num].y - BallState.y); // diferenca entre angulo do robo e angulo com abola ang_ball := DiffAngle( Atan2(BallState.y - RobotState[num].y, BallState.x - RobotState[num].x), RobotState[num].teta) * 180 / Pi; TaskPars[num].x1 := tgx; TaskPars[num].y1 := tgy; case RobotInfo[num].task of taskBehindBall: begin if (not wait_for_it) and (abs(ang)<4) and (RobotState[num].w<0.1) and (d<tkToBallDist+0.03) and (abs(ang_ball)<10) then begin task:=taskScoreFreeKick; end; end; taskScoreFreeKick: begin if (abs(ang)>50) or (d>tkToBallDist+0.08) or (ang_ball>50) then begin task:=taskBehindBall; end; end; else task:=taskBehindBall; end; end; end; procedure CommonPenaltyKickRules(num: integer; wait_for_it: boolean); var d,ang,ang_ball,tgx,tgy,rob_dist: double; randSide:integer; begin with RobotInfo[num], TaskPars[num] do begin randSide:=round(Random+0.5); tgy := FieldDims.KeeperAreaWidth/3; tgx := TheirGoalX; speedontgt:=0; // diferenca entre a angulo target/robo e o angulo fo robo ang:=DiffAngle(RobotState[num].teta, Atan2(tgy - BallState.y, tgx - BallState.x)) * 180 / Pi; d := Dist(RobotState[num].x - BallState.x, RobotState[num].y - BallState.y); // diferenca entre angulo do robo e angulo com abola ang_ball := DiffAngle( Atan2(BallState.y - RobotState[num].y, BallState.x - RobotState[num].x), RobotState[num].teta) * 180 / Pi; TaskPars[num].x1 := tgx; TaskPars[num].y1 := tgy; case RobotInfo[num].task of taskBehindBall: begin if (not wait_for_it) and (abs(ang)<5) and (RobotState[num].w<0.1) and (d<tkToBallDist+0.03) and (abs(ang_ball)<10) then begin task:=taskScoreFreeKick; end; end; taskScoreFreeKick: begin if (abs(ang)>50) or (d>tkToBallDist+0.08) or (ang_ball>50) then begin task:=taskBehindBall; end; end; else task:=taskBehindBall; end; end; end; procedure CommonFreeKickRules(num: integer; wait_for_it: boolean); var d,ang,ang_ball,tgx,tgy,rob_dist: double; begin with RobotInfo[num] do begin rob_num := WhoIs(roleAtackerReceiver); if (rob_num<>-1) then begin tgx := BallState.x; if BallState.y>1 then tgy := -0.5+BallState.y else if BallState.y<0.5 then tgy := +0.5+BallState.y; end else begin tgx:=BallState.x+0.5*cos(Atan2(0-BallState.y,TheirGoalX-BallState.x)); tgy:=BallState.y+0.5*sin(Atan2(0-BallState.y,TheirGoalX-BallState.x)); end; speedontgt:=0; // diferenca entre a angulo target/robo e o angulo do robo ang:=DiffAngle(RobotState[num].teta,Atan2(tgy - BallState.y, tgx - BallState.x)) * 180 / Pi; d := Dist(RobotState[num].x - BallState.x, RobotState[num].y - BallState.y); // diferenca entre angulo do robo e angulo com abola ang_ball := DiffAngle(Atan2(BallState.y - RobotState[num].y, BallState.x - RobotState[num].x), RobotState[num].teta) * 180 / Pi; // state rules TaskPars[num].x1 := tgx; TaskPars[num].y1 := tgy; case RobotInfo[num].task of taskBehindBall: begin if (not wait_for_it) and (abs(ang)<4) and (RobotState[num].w<0.1) and (abs(ang_ball)<10) then begin deltadist:=0.02; deltateta:=2; task:=taskScoreFreeKick; end; end; taskScoreFreeKick: begin if (abs(ang)>50) or (ang_ball>50) or (d>0.4) then begin deltadist:=0.09; deltateta:=5; task:=taskBehindBall; end; end; else task:=taskBehindBall; end; end; end; procedure RoleFreeKickRules(num: integer); begin CommonFreeKickRules(num, false); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleWaitForKickOffRules(num: integer); begin CommonFreeKickRules(num, true); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure roleRobotRobotDefenderRules(num: integer); var best_oponent: integer; zonex, zoney: double; d,vx,vy: double; begin zonex := -1.15; zoney := -Sign(BallState.y) * 0.90; // TODO : oponent best_oponent := -1; vx := zonex; vy := zoney; with RobotInfo[num] do begin with TaskPars[num] do begin x1 := vx; y1 := vy; teta := RobotCalcData[num].ball_teta; speed := SpeedMax; end; task:=taskGoToGoodPosition; end; end; procedure RoleScorePenaltyKickRules(num: integer); begin CommonPenaltyKickRules(num, false); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RolePenaltyKickRules(num: integer); begin CommonPenaltyKickRules(num,true); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleStayBackRules(num: integer); begin deltadist:=0.09; deltateta:=5; RobotInfo[num].task:=taskStayBack; end; procedure CommonMamaoRules(num: integer; offset: double); begin with RobotInfo[num] do begin with TaskPars[num] do begin x1 := TheirGoalX - FieldDims.FieldDepth/4; y1 :=0; teta := RobotCalcData[num].ball_teta; speed := SpeedMax; end; task:=taskGoToGoodPosition; end; end; procedure RoleMamaoRules(num: integer); begin deltadist:=0.09; deltateta:=5; CommonMamaoRules(num, 0.4); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleGoSearchRules1(num: integer); var X1Loc,Y1Loc,X2Loc,Y2Loc,X3Loc,Y3Loc,X4Loc,Y4Loc,val:double; begin // // X1Loc:=FieldDims.FieldDepth/4; // Y1Loc:=-FieldDims.FieldWidth/4; // X2Loc:=-FieldDims.FieldDepth/4; // Y2Loc:=-FieldDims.FieldWidth/4; // X3Loc:=-FieldDims.FieldDepth/4; // Y3Loc:=FieldDims.FieldWidth/4; // X4Loc:=FieldDims.FieldDepth/4; // Y4Loc:=FieldDims.FieldWidth/4; // TaskPars[num].teta:=0; // TaskPars[num].speed:=0.7; // val:=0.2; // with RobotInfo[num], TaskPars[num] do begin // with TaskPars[num] do begin // if (((xold<>X1loc)and(yold<>Y1loc))and((xold<>X2loc)and(yold<>Y2loc))and((xold<>X3loc)and(yold<>Y3loc)))or // ((xold=X4loc)and(yold=Y4loc)) then begin // x1 := X1Loc; // y1 := Y1Loc; // if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and // ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin // xold:=X1loc; // yold:=Y1loc; // end; // end else if ((xold=X1loc)and(yold=Y1loc)) then begin // x1 := X2loc; // y1 := Y2loc; // if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and // ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin // xold:=X2loc; // yold:=Y2loc; // end; // end else if ((xold=X2loc)and(yold=Y2loc)) then begin // x1 := X3loc; // y1 := Y3loc; // if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and // ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin // xold:=X3loc; // yold:=Y3loc; // end; // end else if ((xold=X3loc)and(yold=Y3loc)) then begin // x1 := X4loc; // y1 := Y4loc; // if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and // ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin // xold:=X4loc; // yold:=Y4loc; // end; // end; // end; // deltateta:=5; // task:=taskGoToGoodPosition; // end; with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin x1 := -(FieldDims.FieldDepth/4); y1:= 0; teta := 0; speed := 2.5; end; deltadist:=0.04; deltateta:=5; task:=taskGoToGoodPosition; end; end; procedure RoleGoSearchRules2(num: integer); begin with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin //x1 := 0; x1 := 2.5; //y1:= -(FieldDims.FieldWidth/4); y1:=-2.3; teta := 0; speed := 2; end; deltadist:=0.04; deltateta:=5; task:=taskGoToGoodPosition; end; end; procedure RoleGoSearchRules3(num: integer); begin with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin x1 := 0; y1:= (FieldDims.FieldWidth/4); teta := 0; speed := 2; end; deltadist:=0.04; deltateta:=5; task:=taskGoToGoodPosition; end; end; procedure RoleGoSearchRules4(num: integer); begin with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin x1 := (FieldDims.FieldDepth/4); y1:= 0; teta := 0; speed := 2; end; deltadist:=0.04; deltateta:=5; task:=taskGoToGoodPosition; end; end; procedure RoleMamao2Rules(num: integer); begin deltadist:=0.09; deltateta:=5; CommonMamaoRules(num, 0); end; procedure RoleMidfieldRules(num: integer); begin with RobotInfo[num] do begin with TaskPars[num] do begin x1 :=-3; y1 :=0; teta := RobotCalcData[num].ball_teta; speed := SpeedMax; end; deltadist:=0.09; deltateta:=5; task:=taskGoToGoodPosition; end; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleMidOfMidfieldRules(num: integer); begin with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin x1 := -FieldDims.FieldDepth/4; y1:=0; teta := RobotCalcData[num].ball_teta; speed := SpeedMax; end; deltadist:=0.09; deltateta:=5; task:=taskGoToGoodPosition; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin task:=taskIdle; end; end; end; procedure RoleMidOfMidfieldRightRules(num: integer); begin with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin x1 := -FieldDims.FieldDepth/4; y1:=FieldDims.FieldWidth/4; teta := RobotCalcData[num].ball_teta; speed := SpeedMax; end; deltadist:=0.09; deltateta:=5; task:=taskGoToGoodPosition; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin task:=taskIdle; end; end; end; procedure RoleMidOfMidfieldLeftRules(num: integer); begin with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin x1 := -FieldDims.FieldDepth/4; y1:=-FieldDims.FieldWidth/4; teta := RobotCalcData[num].ball_teta; speed := SpeedMax; end; deltadist:=0.09; deltateta:=5; task:=taskGoToGoodPosition; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin task:=taskIdle; end; end; end; procedure RoleNavigateToLocalizeRules(num: integer); begin with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin task:=taskAdvisedSpeed; end; end; end; procedure RoleFurtiveAtackerKickerRules(num: integer); var v,xNext,yNext,cx,cy:double; targetdir,angVehGoal,distBall:double; error:double; begin with RobotInfo[num], TaskPars[num] do begin x1 := BallState.x_next; y1 := BallState.y_next; teta := ATan2(BallState.y_next-RobotState[num].y,BallState.x_next-RobotState[num].x); distBall:=Dist(BallState.x_n,BallState.y_n); task:=taskGoToPnt; if (RobotState[num].withball) then begin sumError:=0; targetdir := DiffAngle(ATan2(0-RobotState[num].y,FieldDims.FieldDepth/2-RobotState[num].x),RobotState[num].teta); if abs(targetdir)<degtorad(5) then begin speed:=SpeedMax; speed_on_target:=0.3; x1 :=TheirGoalX; y1 := BallState.y_next; task:=taskdribleForGoal end else begin task:=taskRotateToTargWithBall; end; end else begin if ((abs(DiffAngle(ATan2(BallState.y_next-RobotState[num].y,BallState.x_next-RobotState[num].x),RobotState[num].teta))<30*pi/180) and (Dist(BallState.x_n,BallState.y_n)<3))then begin if distBall<1.5 then speed:=0.5*SpeedMax else speed :=SpeedMax; error :=(BallState.vx_n-vxnTarget); sumError:=sumError+error; speed_on_target:=0.3; //speed_on_target:=error*0.25+sumError*0.01; //limitar a velocidade ao speed maximo if (speed_on_target>SpeedMax) then speed_on_target:=0.5*SpeedMax; end else begin sumError:=0; speed:=SpeedMax; speed_on_target:=0.2; end; end; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin task:=taskIdle; end; end; end; procedure RoleAtackerSupporterRules(num: integer); begin with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin x1 := BallState.x - ReceiverDistance; y1 := BallState.y; teta := 0; speed := SpeedMax; end; task:=taskGoToGoodPosition; if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin task:=taskIdle; end; end; end; procedure RoleKickOffRules(num: integer); begin CommonFreeKickRules(num, false); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure GetBarrierPosition(offset: double; var bx, by, teta: double); var ang, vx, vy,offsetInc: double; begin vx := OurGoalX - ballstate.x; vy := 0 - ballstate.y; NormalizeVector(vx, vy); ang := pi + offset * Pi / 180; TranslateAndRotate(vx,vy,0,0,-vx,-vy,ang); teta := ATan2(-vy, -vx); if ((BallState.x < (-FieldDims.FieldDepth/2+StopDistance+FieldDims.AreaDepth+0.25)) and (BallState.x > -FieldDims.FieldDepth/2+FieldDims.AreaDepth+0.25) and (offset=0)) then begin bx:=-FieldDims.FieldDepth/2+FieldDims.AreaDepth-0.25; by:=FieldDims.AreaDepth*tan(teta); end else if ((BallState.x < -FieldDims.FieldDepth/2+FieldDims.AreaDepth+0.25)and(offset=0)) then begin if BallState.y>0 then begin by:=FieldDims.AreaWidth/2-0.25; if teta*180/pi>angCornerDefence then begin bx:=-FieldDims.FieldDepth/2+by/tan(angCornerDefence*pi/180); end else begin bx:=-FieldDims.FieldDepth/2+by/tan(teta); end; end else begin by:=-FieldDims.AreaWidth/2+0.25; if teta*180/pi<-angCornerDefence then begin bx:=-FieldDims.FieldDepth/2+by/tan(-angCornerDefence*pi/180); end else begin bx:=-FieldDims.FieldDepth/2+by/tan(teta); end; end; end else begin offsetInc:=offset; bx := BallState.x + vx * StopDistance; by := BallState.y + vy * StopDistance; If (not (abs(offset)<20)) then begin while((abs(bx)>FieldDims.FieldDepth/2-FieldDims.AreaDepth-0.30))do begin // and (abs(by)<FieldDims.FieldWidth/2-StopDistance))do begin offsetInc:=offsetInc+Sign(offsetInc)*3; vx := OurGoalX - ballstate.x; vy := 0 - ballstate.y; NormalizeVector(vx, vy); ang := pi + offsetInc * Pi / 180; TranslateAndRotate(vx,vy,0,0,-vx,-vy,ang); bx := BallState.x + vx * StopDistance; by := BallState.y + vy * StopDistance; end; end; end; end; procedure GetReceiverPosition(offset: double; var bx, by, teta: double); var ang, vx, vy,offsetInc: double; begin bx := BallState.x - 1; by := BallState.y + sqrt(ReceiverDistance*ReceiverDistance-1); end; procedure RoleBarrierMainRules(num: integer); var vx,vy,ang: double; begin with RobotInfo[num] do begin with TaskPars[num] do begin StopDistance:= 2; teta := RobotCalcData[num].ball_teta; vx:=BallState.x-(-FieldDims.FieldDepth/2); vy:=BallState.y; // NormalizeVector(vx,vy); // ang:=ATan2(vy,vx); x1:=BallState.x-StopDistance*cos(ang); y1:=BallState.y-StopDistance*sin(ang); if(y1<-FieldDims.FieldDepth/2+FieldDims.AreaDepth+0.1) then y1:=-FieldDims.FieldDepth/2+FieldDims.AreaDepth+0.1; speed := SpeedMax; end; task:=taskGoToGoodPosition; end; end; procedure roleBarrierAuxRules(num: integer); var offset: double; otherbarrier:integer; begin otherbarrier:=WhoIs(roleBarrierInterceptor); with RobotInfo[num] do begin with TaskPars[num] do begin StopDistance:=2; if (otherbarrier<>-1) then begin offset := BarrierAngle; end else begin if BallState.y<1 then begin offset := -BarrierAngle; end else if BallState.y>1 then begin offset := BarrierAngle; end else begin offset := BarrierAngle; end; end; GetBarrierPosition(offset, x1, y1, teta); speed := SpeedMax; avoid_is_set:=false; deltadist:=0.09; deltateta:=5; task:=taskGoToGoodPosition; end; end; end; procedure roleBarrierInterceptorRules(num: integer); var offset: double; begin with RobotInfo[num] do begin with TaskPars[num] do begin StopDistance:=2; offset := -BarrierAngle; GetBarrierPosition(offset, x1, y1, teta); speed := SpeedMax ; avoid_is_set:=false; end; deltadist:=0.09; deltateta:=5; task:=taskGoToGoodPosition; end; end; procedure RoleAtacker2Rules(num: integer); begin with RobotInfo[num] do begin task:=taskGoToGoodPosition; end end; procedure RoleDefend3Rules(num: integer); begin RobotInfo[num].task:=taskDefendPass; end; procedure RoleUnderStressRules(num: integer); begin RobotInfo[num].task:=taskUnderStress; end; procedure RoleWingmanRRules(num: integer); begin RobotInfo[num].task:=taskWingman; end; procedure RoleWingmanLRules(num: integer); begin RobotInfo[num].task:=taskWingman; end; //Tese Tiago procedure RoleTestRules(num: integer); var xaux,yaux,val,X1Loc,Y1Loc,X2Loc,Y2Loc,X3Loc,Y3Loc:double; begin //TaskPars[num].teta:=0; TaskPars[num].speed:=2; val:=0.2; X1Loc:=2.5; Y1Loc:=-2.3; X2Loc:=4.3; Y2Loc:=-2.3; X3Loc:=4.3; Y3Loc:=-1.4; with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin if (((xold<>X1loc)and(yold<>Y1loc))and((xold<>X2loc)and(yold<>Y2loc))) then begin x1 := X1Loc; y1 := Y1Loc; teta:=0; if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin xold:=X1loc; yold:=Y1loc; end; end else if ((xold=X1loc)and(yold=Y1loc)) then begin x1 := X2loc; y1 := Y2loc; teta:=0; if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin xold:=X2loc; yold:=Y2loc; end; end else if ((xold=X2loc)and(yold=Y2loc)) then begin x1 := X3loc; y1 := Y3loc; teta:=90*pi/180; //teta:=0; if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin xold:=X3loc; yold:=Y3loc; end; end; end; deltateta:=1; task:=taskGoToGoodPosition; end; end; procedure RoleDoFormationRules(num: integer); begin with TaskPars[num] do begin speed := staticSpeed; end; with RobotInfo[num] do begin if FormationSettings.active then task:=taskDoFormation else task := taskIdle end; end; procedure RoleGoSearchFollowerRules(num: integer); begin with TaskPars[num] do begin speed := staticSpeed; end; with RobotInfo[num] do begin if FormationSettings.active then task:=taskDoFormationFollower else task := taskIdle end; end; procedure RoleGoSearchRules(num: integer); var X1Loc,Y1Loc,X2Loc,Y2Loc,X3Loc,Y3Loc,X4Loc,Y4Loc,val:double; begin X1Loc:=FieldDims.FieldDepth/4; Y1Loc:=-FieldDims.FieldWidth/4; X2Loc:=-FieldDims.FieldDepth/4; Y2Loc:=-FieldDims.FieldWidth/4; X3Loc:=-FieldDims.FieldDepth/4; Y3Loc:=FieldDims.FieldWidth/4; X4Loc:=FieldDims.FieldDepth/4; Y4Loc:=FieldDims.FieldWidth/4; TaskPars[num].speed:=1; val:=0.2; with RobotInfo[num], TaskPars[num] do begin with TaskPars[num] do begin if (((xold<>X1loc)and(yold<>Y1loc))and((xold<>X2loc)and(yold<>Y2loc))and((xold<>X3loc)and(yold<>Y3loc)))or ((xold=X4loc)and(yold=Y4loc)) then begin x1 := X1Loc; y1 := Y1Loc; teta:=270*pi/180; if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin xold:=X1loc; yold:=Y1loc; end; end else if ((xold=X1loc)and(yold=Y1loc)) then begin x1 := X2loc; y1 := Y2loc; teta:=180*pi/180; if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin xold:=X2loc; yold:=Y2loc; end; end else if ((xold=X2loc)and(yold=Y2loc)) then begin x1 := X3loc; y1 := Y3loc; teta:=90*pi/180; if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin xold:=X3loc; yold:=Y3loc; end; end else if ((xold=X3loc)and(yold=Y3loc)) then begin x1 := X4loc; y1 := Y4loc; teta:=0; if (((RobotState[num].x)<x1+val)and((RobotState[num].x)>x1-val)and ((RobotState[num].y)<y1+val)and((RobotState[num].y)>y1-val)) then begin xold:=X4loc; yold:=Y4loc; end; end; end; deltateta:=1; task:=taskGoToGoodPosition; end; end; procedure RoleWaitForFreeKickRules(num: integer); begin //RobotInfo[num].task:=taskBehindBall; CommonFreeKickRules(num, true); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleWaitToThrowInRules(num: integer); begin //RobotInfo[num].task:=taskBehindBall; CommonFreeKickRules(num, true); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleThrowInRules(num: integer); begin //RobotInfo[num].task := taskScoreFreeKick; CommonFreeKickRules(num, false); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleWaitForCornerKickRules(num: integer); begin CommonCornerKickRules(num, true); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleCornerKickRules(num: integer); begin CommonCornerKickRules(num, false); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleWaitOurGoalLickRules(num: integer); begin CommonGoalKickRules(num, true); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleOurGoalLickRules(num: integer); begin CommonGoalKickRules(num, false); if ((abs(BallState.x)>FieldDims.FieldDepth/2) or (abs(BallState.y)>FieldDims.FieldWidth/2)) then begin RobotInfo[num].task:=taskIdle; end; end; procedure RoleWaitDroppedBallRules(num: integer); var ang,vx,vy,vnorm: double; begin with RobotInfo[num] do begin with TaskPars[num] do begin StopDistance:=ReceiverDistance-1; teta := RobotCalcData[num].ball_teta; vx:=FieldDims.FieldDepth/2-BallState.x; vy:=0-BallState.y; // NormalizeVector(vx,vy); // ang:=ATan2(vy,vx); x1:=BallState.x-cos(ang); y1:=BallState.y-sin(ang); speed := SpeedMax; end; task:=taskGoToGoodPosition; end; end; end.
unit ibSHUserManagerFrm; interface uses SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, ExtCtrls, VirtualTrees, Menus, ImgList, AppEvnts, ActnList; type TibSHUserManagerForm = class(TibBTComponentForm) Tree: TVirtualStringTree; private { Private declarations } FUserManagerIntf: IibSHUserManager; FIntUser: TSHComponent; FIntUserIntf: IibSHUser; { Tree } procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); procedure TreeIncrementalSearch(Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); procedure TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TreeDblClick(Sender: TObject); procedure TreeGetPopupMenu(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; const P: TPoint; var AskParent: Boolean; var PopupMenu: TPopupMenu); procedure TreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure SetTreeEvents(ATree: TVirtualStringTree); procedure DoOnGetData; protected { ISHRunCommands } function GetCanCreate: Boolean; override; function GetCanAlter: Boolean; override; function GetCanDrop: Boolean; override; function GetCanRefresh: Boolean; override; procedure ICreate; override; procedure Alter; override; procedure Drop; override; procedure Refresh; override; procedure SetStatusBar(Value: TStatusBar); override; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; procedure RefreshData; property UserManager: IibSHUserManager read FUserManagerIntf; end; var ibSHUserManagerForm: TibSHUserManagerForm; implementation uses ibSHConsts, ibSHMessages, ibSHValues; {$R *.dfm} type PTreeRec = ^TTreeRec; TTreeRec = record NormalText: string; StaticText: string; ClassIID: TGUID; ImageIndex: Integer; Number: string; UserName: string; FirstName: string; MiddleName: string; LastName: string; AC: string; end; { TibSHUserManagerForm } constructor TibSHUserManagerForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); var vComponentClass: TSHComponentClass; begin inherited Create(AOwner, AParent, AComponent, ACallString); Supports(Component, IibSHUserManager, FUserManagerIntf); FocusedControl := Tree; SetTreeEvents(Tree); RefreshData; if not Assigned(UserManager.BTCLDatabase) then Tree.Header.Columns[5].Options := Tree.Header.Columns[5].Options - [coVisible]; vComponentClass := Designer.GetComponent(IibSHUser); if Assigned(vComponentClass) then begin FIntUser := vComponentClass.Create(Self); Supports(FIntUser, IibSHUser, FIntUserIntf); end; end; destructor TibSHUserManagerForm.Destroy; begin FIntUserIntf := nil; FreeAndNil(FIntUser); inherited Destroy; end; procedure TibSHUserManagerForm.SetTreeEvents(ATree: TVirtualStringTree); begin ATree.Images := Designer.ImageList; ATree.OnGetNodeDataSize := TreeGetNodeDataSize; ATree.OnFreeNode := TreeFreeNode; ATree.OnGetImageIndex := TreeGetImageIndex; ATree.OnGetText := TreeGetText; ATree.OnPaintText := TreePaintText; ATree.OnIncrementalSearch := TreeIncrementalSearch; ATree.OnDblClick := TreeDblClick; ATree.OnKeyDown := TreeKeyDown; ATree.OnGetPopupMenu := TreeGetPopupMenu; ATree.OnCompareNodes := TreeCompareNodes; end; procedure TibSHUserManagerForm.DoOnGetData; var I: Integer; Node: PVirtualNode; NodeData: PTreeRec; begin Tree.BeginUpdate; Tree.Clear; if Assigned(UserManager) then begin UserManager.DisplayUsers; for I := 0 to Pred(UserManager.GetUserCount) do begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.ImageIndex := Designer.GetImageIndex(IibSHUser); NodeData.NormalText := UserManager.GetUserName(I); NodeData.Number := IntToStr(I + 1); NodeData.UserName := UserManager.GetUserName(I); NodeData.FirstName := UserManager.GetFirstName(I); NodeData.MiddleName := UserManager.GetMiddleName(I); NodeData.LastName := UserManager.GetLastName(I); NodeData.AC := IntToStr(UserManager.GetConnectCount(NodeData.UserName)); end; end; Node := Tree.GetFirst; if Assigned(Node) then begin Tree.FocusedNode := Node; Tree.Selected[Tree.FocusedNode] := True; end; Tree.EndUpdate; end; procedure TibSHUserManagerForm.RefreshData; begin try Screen.Cursor := crHourGlass; DoOnGetData; Designer.UpdateObjectInspector; finally Screen.Cursor := crDefault; end; end; function TibSHUserManagerForm.GetCanCreate: Boolean; begin Result := True; end; function TibSHUserManagerForm.GetCanAlter: Boolean; begin Result := Assigned(Tree.FocusedNode); end; function TibSHUserManagerForm.GetCanDrop: Boolean; begin Result := GetCanAlter; end; function TibSHUserManagerForm.GetCanRefresh: Boolean; begin Result := True; end; procedure TibSHUserManagerForm.ICreate; var Node: PVirtualNode; NodeData: PTreeRec; begin FIntUserIntf.UserName := Format('%s', ['NEW_USER']); FIntUserIntf.Password := Format('%s', [SDefaultPassword]); FIntUserIntf.FirstName := Format('%s', [EmptyStr]); FIntUserIntf.MiddleName := Format('%s', [EmptyStr]); FIntUserIntf.LastName := Format('%s', [EmptyStr]); FIntUser.MakePropertyVisible('UserName'); if IsPositiveResult(Designer.ShowModal(FIntUser, SCallUser)) then begin if UserManager.AddUser( FIntUserIntf.UserName, FIntUserIntf.Password, FIntUserIntf.FirstName, FIntUserIntf.MiddleName, FIntUserIntf.LastName) then begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.ImageIndex := Designer.GetImageIndex(IibSHUser); NodeData.NormalText := FIntUserIntf.UserName; NodeData.Number := IntToStr(Tree.RootNodeCount); NodeData.UserName := FIntUserIntf.UserName; NodeData.FirstName := FIntUserIntf.FirstName; NodeData.MiddleName := FIntUserIntf.MiddleName; NodeData.LastName := FIntUserIntf.LastName; NodeData.AC := IntToStr(UserManager.GetConnectCount(NodeData.UserName)); Tree.FocusedNode := Node; Tree.Selected[Tree.FocusedNode] := True; if Tree.CanFocus then Tree.SetFocus; end; end; end; procedure TibSHUserManagerForm.Alter; var NodeData: PTreeRec; begin NodeData := nil; if Assigned(Tree.FocusedNode) then NodeData := Tree.GetNodeData(Tree.FocusedNode); if Assigned(NodeData) then begin FIntUserIntf.UserName := NodeData.UserName; FIntUserIntf.Password := Format('%s', [SDefaultPassword]); FIntUserIntf.FirstName := NodeData.FirstName; FIntUserIntf.MiddleName := NodeData.MiddleName; FIntUserIntf.LastName := NodeData.LastName; FIntUser.MakePropertyInvisible('UserName'); if IsPositiveResult(Designer.ShowModal(FIntUser, SCallUser)) then begin if UserManager.ModifyUser( FIntUserIntf.UserName, FIntUserIntf.Password, FIntUserIntf.FirstName, FIntUserIntf.MiddleName, FIntUserIntf.LastName) then begin NodeData.FirstName := FIntUserIntf.FirstName; NodeData.MiddleName := FIntUserIntf.MiddleName; NodeData.LastName := FIntUserIntf.LastName; end; end; end; end; procedure TibSHUserManagerForm.Drop; var Node: PVirtualNode; NodeData: PTreeRec; begin NodeData := nil; if Assigned(Tree.FocusedNode) then NodeData := Tree.GetNodeData(Tree.FocusedNode); if Assigned(NodeData) then begin FIntUserIntf.UserName := NodeData.UserName; if Designer.ShowMsg(Format(SDeleteUser, [FIntUserIntf.UserName]), mtConfirmation) then begin if UserManager.DeleteUser(FIntUserIntf.UserName) then begin Node := Tree.FocusedNode.NextSibling; if not Assigned(Node) then Node := Tree.FocusedNode.PrevSibling; Tree.DeleteNode(Tree.FocusedNode); if Assigned(Node) then begin Tree.FocusedNode := Node; Tree.Selected[Tree.FocusedNode] := True; if Tree.CanFocus then Tree.SetFocus; end; end; end; end; end; procedure TibSHUserManagerForm.Refresh; begin RefreshData; end; procedure TibSHUserManagerForm.SetStatusBar(Value: TStatusBar); begin inherited SetStatusBar(Value); if Assigned(StatusBar) then StatusBar.Visible := False; end; { Tree } procedure TibSHUserManagerForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TTreeRec); end; procedure TibSHUserManagerForm.TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Assigned(Data) then Finalize(Data^); end; procedure TibSHUserManagerForm.TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); ImageIndex := -1; if (Kind = ikNormal) or (Kind = ikSelected) then begin case Column of 1: ImageIndex := Data.ImageIndex; else ImageIndex := -1; end; end; end; procedure TibSHUserManagerForm.TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if TextType = ttNormal then begin case Column of 0: CellText := Data.Number; 1: CellText := Data.UserName; 2: CellText := Data.FirstName; 3: CellText := Data.MiddleName; 4: CellText := Data.LastName; 5: CellText := Data.AC; end; end; end; procedure TibSHUserManagerForm.TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); //var // Data: PTreeRec; begin // Data := Sender.GetNodeData(Node); end; procedure TibSHUserManagerForm.TreeIncrementalSearch(Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Pos(AnsiUpperCase(SearchText), AnsiUpperCase(Data.NormalText)) <> 1 then Result := 1; end; procedure TibSHUserManagerForm.TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then Alter; end; procedure TibSHUserManagerForm.TreeDblClick(Sender: TObject); begin Alter; end; procedure TibSHUserManagerForm.TreeGetPopupMenu(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; const P: TPoint; var AskParent: Boolean; var PopupMenu: TPopupMenu); begin // end; procedure TibSHUserManagerForm.TreeCompareNodes( Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var Data1, Data2: PTreeRec; begin Data1 := Sender.GetNodeData(Node1); Data2 := Sender.GetNodeData(Node2); Result := CompareStr(Data1.NormalText, Data2.NormalText); end; end.
unit SDUDialogs; // Note: In order to use this, need XP Manifest in your application // See also: TaskDialogIndirect(...) and TASKDIALOGCONFIG!!! // msg boxes fns moved to lcDialogs interface uses Dialogs, Windows; (* const // Consts for use with Vista TaskDialogs // Taken from CommCtrl.h, Vista SDK SDVISTA_TDCBF_OK_BUTTON = $0001; SDVISTA_TDCBF_YES_BUTTON = $0002; SDVISTA_TDCBF_NO_BUTTON = $0004; SDVISTA_TDCBF_CANCEL_BUTTON = $0008; SDVISTA_TDCBF_RETRY_BUTTON = $0010; SDVISTA_TDCBF_CLOSE_BUTTON = $0020; // Taken from WinUser.h, Vista SDK: // #define MAKEINTRESOURCEW(i) ((LPWSTR)((ULONG_PTR)((WORD)(i)))) // Note: We do ***NOT*** use MAKEINTRESOURCE here as Delphi's version of this // doesn't cast to a WORD (16 bit), hence doesn't truncate it before // converting to PWChar - we manually expand out the C version's macro // Taken from CommCtrl.h, Vista SDK // #define TD_WARNING_ICON MAKEINTRESOURCEW(-1) SDVISTA_TD_WARNING_ICON = PWChar(WORD(-1)); // #define TD_ERROR_ICON MAKEINTRESOURCEW(-2) SDVISTA_TD_ERROR_ICON = PWChar(WORD(-2)); // #define TD_INFORMATION_ICON MAKEINTRESOURCEW(-3) SDVISTA_TD_INFORMATION_ICON = PWChar(WORD(-3)); // #define TD_SHIELD_ICON MAKEINTRESOURCEW(-4) SDVISTA_TD_SHIELD_ICON = PWChar(WORD(-4)); SDVISTA_TD_ICON_BLANK = PWChar(WORD(0)); SDVISTA_TD_ICON_WARNING = SDVISTA_TD_WARNING_ICON; SDVISTA_TD_ICON_QUESTION = PWChar(IDI_QUESTION); // Not official! // Not in the Vista SDK! SDVISTA_TD_ICON_ERROR = SDVISTA_TD_ERROR_ICON; SDVISTA_TD_ICON_INFORMATION = SDVISTA_TD_INFORMATION_ICON; // SDVISTA_TD_ICON_BLANK_AGAIN = MAKEINTRESOURCEW(0); SDVISTA_TD_ICON_SHIELD = SDVISTA_TD_SHIELD_ICON; { // Consts from: http://weblogs.foxite.com/stuartdunkeld/archive/2006/05/23/1570.aspx SDVISTA_TD_ICON_BLANK = 100; SDVISTA_TD_ICON_WARNING = 101; SDVISTA_TD_ICON_QUESTION = 102; SDVISTA_TD_ICON_ERROR = 103; SDVISTA_TD_ICON_INFORMATION = 104; SDVISTA_TD_ICON_BLANK_AGAIN = 105; SDVISTA_TD_ICON_SHIELD = 106; } { // Consts from: http://www.delphi-forum.de/viewtopic.php?p=404545 SDVISTA_TD_ICON_BLANK = PWChar(32512); SDVISTA_TD_ICON_WARNING = PWChar(32515); SDVISTA_TD_ICON_QUESTION = PWChar(32514); SDVISTA_TD_ICON_ERROR = PWChar(32513); SDVISTA_TD_ICON_INFORMATION = PWChar(32516); SDVISTA_TD_ICON_BLANK_AGAIN = PWChar(32517); SDVISTA_TD_ICON_SHIELD = PWChar(32518); } *) type {these dialogs just don't change working dir if PreserveCWD is set} TSDUOpenDialog = class(TOpenDialog) private FPreserveCWD: boolean; public function Execute(): boolean; override; published property PreserveCWD: boolean read FPreserveCWD write FPreserveCWD default TRUE; end; TSDUSaveDialog = class(TSaveDialog) private FPreserveCWD: boolean; public function Execute(): boolean; override; published property PreserveCWD: boolean read FPreserveCWD write FPreserveCWD default TRUE; end; procedure Register; //var // // If set, then any messages displayed will have any single CRLFs stripped // // out, while double CRLFs (SDU_CRLF+SDUCRLF) will be preserved under // // Windows Vista and later // // This allows messages to have CRLFs included in them for pre-Vista systems, // // in order to break up long lines - but on Vista, which does more sensible // // word wrapping, such CRLFs will be removed // SDUDialogsStripSingleCRLF: boolean = TRUE; // set to true to suppress all dialogs (ege for testing) // G_SuppressDialogs : boolean = False; (* // Display confirmation dialog with OK/Cancel or Yes/No buttons. // Returns TRUE if the user selects OK or Yes. function SDUConfirmOK(msg: string): boolean; function SDUConfirmYN(msg: string): boolean; function SDUWarnOK(msg: string): boolean; function SDUWarnYN(msg: string): boolean; function SDUErrorOK(msg: string): boolean; function SDUErrorYN(msg: string): boolean; // function MessageBox(hWnd: HWND; lpText, lpCaption: PChar; uType: UINT): Integer; stdcall; function SDUMessageBox( hWnd: HWND; Content: string; WindowTitle: string; Flags: longint ): integer; // function MessageDlg(const Msg: string; DlgType: TMsgDlgType; // Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer; function SDUMessageDlg( Content: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint ): integer; overload; function SDUMessageDlg( Content: string; DlgType: TMsgDlgType ): integer; overload; function SDUMessageDlg( Content: string ): integer; overload; function SDUVistaTaskDialog( WindowTitle: WideString; MainInstruction: WideString; Content: WideString; CommonButtons: integer; Icon: PWChar ): integer; overload; function SDUVistaTaskDialog( hWndParent: HWND; WindowTitle: WideString; MainInstruction: WideString; Content: WideString; CommonButtons: integer; Icon: PWChar ): integer; overload; function SDUVistaTaskDialog( hWndParent: HWND; hInst: THandle; WindowTitle: WideString; MainInstruction: WideString; Content: WideString; CommonButtons: integer; Icon: PWChar ): integer; overload; *) implementation uses Classes, Controls, // Required for mrXXX // Consts, // RTLConsts, Forms, // Required for Application SDUGeneral, SysUtils; // Required for StringReplace (* resourcestring // Ugly hack to prevent: // [Pascal Error] E2201 Need imported data reference ($G) to access 'SMsgDlgInformation' from unit 'SDUDialogs' // compiler error; copy of consts from "Consts.pas" SDU_SMsgDlgWarning = 'Warning'; SDU_SMsgDlgError = 'Error'; SDU_SMsgDlgInformation = 'Information'; SDU_SMsgDlgConfirm = 'Confirm'; // These are included, just so that they get included in any .mo // (translation) file. Otherwise these are not used anywhere - Delphi's // "Consts.pas" holds the ones actually used, but they don't get extracted // to .mo files; hence including a copy here SDU_SMsgDlgYes = '&Yes'; SDU_SMsgDlgNo = '&No'; SDU_SMsgDlgOK = 'OK'; SDU_SMsgDlgCancel = 'Cancel'; SDU_SMsgDlgHelp = '&Help'; SDU_SMsgDlgHelpNone = 'No help available'; SDU_SMsgDlgHelpHelp = 'Help'; SDU_SMsgDlgAbort = '&Abort'; SDU_SMsgDlgRetry = '&Retry'; SDU_SMsgDlgIgnore = '&Ignore'; SDU_SMsgDlgAll = '&All'; SDU_SMsgDlgNoToAll = 'N&o to All'; SDU_SMsgDlgYesToAll = 'Yes to &All'; const // The filename of the DLL COMCTL32_LIB_DLL = 'COMCTL32.DLL'; DLL_FUNCTIONNAME_TaskDialog = 'TaskDialog'; *) (* type // Library function definition // From CommCtrl.h, Vista SDK // WINCOMMCTRLAPI HRESULT WINAPI TaskDialog( // __in_opt HWND hwndParent, // __in_opt HINSTANCE hInstance, // __in_opt PCWSTR pszWindowTitle, // __in_opt PCWSTR pszMainInstruction, // __in_opt PCWSTR pszContent, // TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons, // __in_opt PCWSTR pszIcon, // __out_opt int *pnButton // ); TFnTaskDialog = function( hWndParent: HWND; hInstance: THandle; pszWindowTitle: PWChar; pszMainInstruction: PWChar; pszContent: PWChar; CommonButtons: Integer; pszIcon: PWChar; pnButton: PInteger ): HRESULT; stdcall; var _SDUTaskDialog_hLib: THandle; _SDUTaskDialog_lib_TaskDialog: TFnTaskDialog; // Forward declarations... function _SDUTaskDialog_LoadDLL(): boolean; forward; function _SDUTaskDialog_GetDLLProcAddresses(): boolean; forward; procedure _SDUTaskDialog_UnloadDLL(); forward; function _SDUDialogs_StripSingleNewlines(msg: string): string; forward; *) // ---------------------------------------------------------------------------- procedure Register; begin RegisterComponents('SDeanUtils', [TSDUOpenDialog]); RegisterComponents('SDeanUtils', [TSDUSaveDialog]); end; (* // ---------------------------------------------------------------------------- function _SDUTaskDialog_LoadDLL(): boolean; begin result := FALSE; // If the lib is already loaded, just return TRUE if (_SDUTaskDialog_hLib <> 0) then begin result := TRUE; end else begin _SDUTaskDialog_hLib := LoadLibrary(COMCTL32_LIB_DLL); if (_SDUTaskDialog_hLib <> 0) then begin // DLL loaded, get function addresses result := _SDUTaskDialog_GetDLLProcAddresses(); if not(result) then begin // Unload DLL; there was a problem _SDUTaskDialog_UnloadDLL(); end; end; end; end; // ---------------------------------------------------------------------------- procedure _SDUTaskDialog_UnloadDLL(); begin if (_SDUTaskDialog_hLib <> 0) then begin FreeLibrary(_SDUTaskDialog_hLib); _SDUTaskDialog_hLib := 0; end; end; // ---------------------------------------------------------------------------- function _SDUTaskDialog_GetDLLProcAddresses(): boolean; begin result := TRUE; if (_SDUTaskDialog_hLib = 0) then begin result := FALSE; end; if (result) then begin @_SDUTaskDialog_lib_TaskDialog := GetProcAddress(_SDUTaskDialog_hLib, ''+DLL_FUNCTIONNAME_TaskDialog+''); result := (@_SDUTaskDialog_lib_TaskDialog <> nil); end; end; // ---------------------------------------------------------------------------- function SDUVistaTaskDialog( WindowTitle: WideString; MainInstruction: WideString; Content: WideString; CommonButtons: integer; Icon: PWChar ): integer; overload; begin Result := SDUVistaTaskDialog( 0, WindowTitle, MainInstruction, Content, CommonButtons, Icon ); end; // ---------------------------------------------------------------------------- function SDUVistaTaskDialog( hWndParent: HWND; WindowTitle: WideString; MainInstruction: WideString; Content: WideString; CommonButtons: integer; Icon: PWChar ): integer; overload; begin Result := SDUVistaTaskDialog( 0, 0, // Application.Handle - We use zero here // to allow use of the standard predefined // icons WindowTitle, MainInstruction, Content, CommonButtons, Icon ); end; // ---------------------------------------------------------------------------- function SDUVistaTaskDialog( hWndParent: HWND; hInst: THandle; WindowTitle: WideString; MainInstruction: WideString; Content: WideString; CommonButtons: integer; Icon: PWChar ): integer; overload; var allOK: boolean; olderMsgDlgType: TMsgDlgType; olderMsgDlgButtons: TMsgDlgButtons; ansistrContent: string; title: WideString; begin result := 0; allOK := _SDUTaskDialog_LoadDLL(); if SDUDialogsStripSingleCRLF then begin Content := _SDUDialogs_StripSingleNewlines(Content); end; if (allOK) then begin // Use application title if title not supplied title := WindowTitle; if (title = '') then begin title := Application.Title; end; _SDUTaskDialog_lib_TaskDialog( hWndParent, hInst, PWChar(title), PWChar(MainInstruction), PWChar(Content), CommonButtons, Icon, @result ); _SDUTaskDialog_UnloadDLL(); end else begin // Degrade gracefully on non-Vista systems... // Degrade icon... if (Icon = SDVISTA_TD_ICON_BLANK) then begin olderMsgDlgType := mtCustom; end else if (Icon = SDVISTA_TD_ICON_WARNING) then begin olderMsgDlgType := mtWarning; end else if (Icon = SDVISTA_TD_ICON_QUESTION) then begin olderMsgDlgType := mtConfirmation; end else if (Icon = SDVISTA_TD_ICON_ERROR) then begin olderMsgDlgType := mtError; end else if (Icon = SDVISTA_TD_ICON_INFORMATION) then begin olderMsgDlgType := mtInformation; end // else if (Icon = SDVISTA_TD_ICON_BLANK_AGAIN) then // begin // olderMsgDlgType := mtCustom; // end; else if (Icon = SDVISTA_TD_ICON_SHIELD) then begin olderMsgDlgType := mtInformation; end else begin olderMsgDlgType := mtCustom; end; // Degrade buttons... olderMsgDlgButtons:= []; if ((CommonButtons and SDVISTA_TDCBF_OK_BUTTON) = SDVISTA_TDCBF_OK_BUTTON) then begin olderMsgDlgButtons := olderMsgDlgButtons + [mbOK]; end else if ((CommonButtons and SDVISTA_TDCBF_YES_BUTTON) = SDVISTA_TDCBF_YES_BUTTON) then begin olderMsgDlgButtons := olderMsgDlgButtons + [mbYes]; end else if ((CommonButtons and SDVISTA_TDCBF_NO_BUTTON) = SDVISTA_TDCBF_NO_BUTTON) then begin olderMsgDlgButtons := olderMsgDlgButtons + [mbNo]; end else if ((CommonButtons and SDVISTA_TDCBF_CANCEL_BUTTON) = SDVISTA_TDCBF_CANCEL_BUTTON) then begin olderMsgDlgButtons := olderMsgDlgButtons + [mbCancel]; end else if ((CommonButtons and SDVISTA_TDCBF_RETRY_BUTTON) = SDVISTA_TDCBF_RETRY_BUTTON) then begin olderMsgDlgButtons := olderMsgDlgButtons + [mbRetry]; end else if ((CommonButtons and SDVISTA_TDCBF_CLOSE_BUTTON) = SDVISTA_TDCBF_CLOSE_BUTTON) then begin olderMsgDlgButtons := olderMsgDlgButtons + [mbAbort]; // Should be cancel? end; ansistrContent:= Content; result := MessageDlg(ansistrContent, olderMsgDlgType, olderMsgDlgButtons, 0); // Map buttonpress... case result of mrOk: begin result := IDOK; end; mrCancel: begin result := IDCANCEL; end; mrYes: begin result := IDYES; end; mrNo: begin result := IDNO; end; mrAbort: begin result := IDABORT; end; mrRetry: begin result := IDRETRY; end; mrIgnore: begin result := IDIGNORE; end; mrAll: begin result := IDOK; // No real mapping... end; mrNoToAll: begin result := IDNO; end; mrYesToAll: begin result := IDYES; end; else begin result := 0; end; end; end; end; // ---------------------------------------------------------------------------- function SDUMessageBox( hWnd: HWND; Content: string; WindowTitle: string; Flags: longint ): integer; var allOK: boolean; buttons: integer; icon: PWChar; widestrWindowTitle: WideString; widestrContent: WideString; begin allOK := _SDUTaskDialog_LoadDLL(); if SDUDialogsStripSingleCRLF then begin Content := _SDUDialogs_StripSingleNewlines(Content); end; if (allOK) then begin // Map buttons... buttons := 0; if ((Flags and MB_ABORTRETRYIGNORE) = MB_ABORTRETRYIGNORE) then begin // No "Abort" or "Ignore", we just use the closest here... buttons := ( SDVISTA_TDCBF_CANCEL_BUTTON or SDVISTA_TDCBF_RETRY_BUTTON or SDVISTA_TDCBF_OK_BUTTON ); end else if ((Flags and MB_OK) = MB_OK) then begin buttons := SDVISTA_TDCBF_OK_BUTTON; end else if ((Flags and MB_OKCANCEL) = MB_OKCANCEL) then begin buttons := SDVISTA_TDCBF_OK_BUTTON or SDVISTA_TDCBF_CANCEL_BUTTON; end else if ((Flags and MB_RETRYCANCEL) = MB_RETRYCANCEL) then begin buttons := SDVISTA_TDCBF_RETRY_BUTTON or SDVISTA_TDCBF_CANCEL_BUTTON; end else if ((Flags and MB_YESNO) = MB_YESNO) then begin buttons := SDVISTA_TDCBF_YES_BUTTON or SDVISTA_TDCBF_NO_BUTTON; end else if ((Flags and MB_YESNOCANCEL) = MB_YESNOCANCEL) then begin buttons := ( SDVISTA_TDCBF_YES_BUTTON or SDVISTA_TDCBF_NO_BUTTON or SDVISTA_TDCBF_CANCEL_BUTTON ); end; // Map icon... icon := SDVISTA_TD_ICON_BLANK; if ((Flags and MB_ICONWARNING) = MB_ICONWARNING) then begin icon := SDVISTA_TD_ICON_WARNING; end else if ((Flags and MB_ICONERROR) = MB_ICONERROR) then begin icon := SDVISTA_TD_ICON_ERROR; end else if ((Flags and MB_ICONINFORMATION) = MB_ICONINFORMATION) then begin icon := SDVISTA_TD_ICON_INFORMATION; end else if ((Flags and MB_ICONQUESTION) = MB_ICONQUESTION) then begin icon := SDVISTA_TD_ICON_QUESTION; end else if ((Flags and MB_ICONEXCLAMATION) = MB_ICONEXCLAMATION) then begin icon := SDVISTA_TD_ICON_INFORMATION; // Nearest we've got end else if ((Flags and MB_ICONHAND) = MB_ICONHAND) then begin icon := SDVISTA_TD_ICON_ERROR; // Nearest we've got... end else if ((Flags and MB_ICONASTERISK) = MB_ICONASTERISK) then begin icon := SDVISTA_TD_ICON_INFORMATION; // Nearest we've got... end else if ((Flags and MB_ICONSTOP) = MB_ICONSTOP) then begin icon := SDVISTA_TD_ICON_ERROR; // Nearest we've got... end else if ((Flags and MB_USERICON) = MB_USERICON) then begin icon := SDVISTA_TD_ICON_BLANK; // Not supported by MessageBox(...) anyway... end; // Convert to widestrings... widestrWindowTitle := WindowTitle; widestrContent := Content; result := SDUVistaTaskDialog( hWnd, widestrWindowTitle, '', widestrContent, buttons, icon ); // No need to map return value; MessageBox uses IDOK, IDCANCEL, etc anyway _SDUTaskDialog_UnloadDLL(); end else begin // Fallback... result := MessageBox(hWnd, PChar(Content), PChar(WindowTitle), Flags); end; end; // ---------------------------------------------------------------------------- function SDUMessageDlg( Content: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint ): integer; const // This taken from CreateMessageDialog(...) in Dialogs.pas SDCaptions: array[TMsgDlgType] of Pointer = (@SDU_SMsgDlgWarning, @SDU_SMsgDlgError, @SDU_SMsgDlgInformation, @SDU_SMsgDlgConfirm, nil); var allOK: boolean; widestrWindowTitle: WideString; widestrContent: WideString; TDButtons: integer; TBIcon: PWChar; begin // if G_SuppressDialogs then exit; allOK := _SDUTaskDialog_LoadDLL(); if SDUDialogsStripSingleCRLF then begin Content := _SDUDialogs_StripSingleNewlines(Content); end; if (allOK) then begin // Map buttons... TDButtons := 0; if (mbYes in Buttons) then begin TDButtons := TDButtons or SDVISTA_TDCBF_YES_BUTTON; end; if (mbNo in Buttons) then begin TDButtons := TDButtons or SDVISTA_TDCBF_NO_BUTTON; end; if (mbOK in Buttons) then begin TDButtons := TDButtons or SDVISTA_TDCBF_OK_BUTTON; end; if (mbCancel in Buttons) then begin TDButtons := TDButtons or SDVISTA_TDCBF_CANCEL_BUTTON; end; if (mbAbort in Buttons) then begin TDButtons := TDButtons or SDVISTA_TDCBF_CLOSE_BUTTON; // Should be cancel? end; if (mbRetry in Buttons) then begin TDButtons := TDButtons or SDVISTA_TDCBF_RETRY_BUTTON; end; if (mbIgnore in Buttons) then begin // Not supported end; if (mbAll in Buttons) then begin // Not supported end; if (mbNoToAll in Buttons) then begin // Not supported end; if (mbYesToAll in Buttons) then begin // Not supported end; if (mbHelp in Buttons) then begin // Not supported end; // Map icon... case DlgType of mtWarning: begin TBIcon := SDVISTA_TD_ICON_WARNING; end; mtError: begin TBIcon := SDVISTA_TD_ICON_ERROR; end; mtInformation: begin TBIcon := SDVISTA_TD_ICON_INFORMATION; end; mtConfirmation: begin TBIcon := SDVISTA_TD_ICON_QUESTION; end; mtCustom: begin TBIcon := SDVISTA_TD_ICON_BLANK; end; else begin TBIcon := SDVISTA_TD_ICON_BLANK; end; end; // Convert to widestrings... widestrContent := Content; // This taken from CreateMessageDialog(...) in Dialogs.pas if DlgType <> mtCustom then begin widestrWindowTitle := LoadResString(SDCaptions[DlgType]) end else begin widestrWindowTitle := Application.Title; end; result := SDUVistaTaskDialog( 0, widestrWindowTitle, '', widestrContent, TDButtons, TBIcon ); // No need to map return value; MessageBox uses IDOK, IDCANCEL, etc anyway _SDUTaskDialog_UnloadDLL(); end else begin // Fallback... result := MessageDlg(Content, DlgType, Buttons, HelpCtx); end; end; // ---------------------------------------------------------------------------- function SDUMessageDlg( Content: string; DlgType: TMsgDlgType ): integer; begin Result := SDUMessageDlg(Content, DlgType, [mbOK], 0); end; // ---------------------------------------------------------------------------- function SDUMessageDlg( Content: string ): integer; begin Result := SDUMessageDlg(Content, mtInformation, [mbOK], 0); end; // ---------------------------------------------------------------------------- // Convert CRLFs to spaces (or just strip them out), while preserving // CRLF+CRLFs function _SDUDialogs_StripSingleNewlines(msg: string): string; const DBLCRLF_MARKER = #13; begin if SDUOSVistaOrLater() then begin // Replace double-CRLFs with a special flag marker to preserve them msg := StringReplace(msg, SDUCRLF+SDUCRLF, DBLCRLF_MARKER, [rfReplaceAll]); // Replace any remaining CRLFs with a space character, unless they were // already next to a space character, in which case just strip the CRLF out. msg := StringReplace(msg, SDUCRLF+' ', ' ', [rfReplaceAll]); msg := StringReplace(msg, ' '+SDUCRLF, ' ', [rfReplaceAll]); msg := StringReplace(msg, SDUCRLF, ' ', [rfReplaceAll]); // Revert double-CRLFs msg := StringReplace(msg, DBLCRLF_MARKER, SDUCRLF+SDUCRLF, [rfReplaceAll]); end; Result := msg; end; // ---------------------------------------------------------------------------- // Display confirmation dialog with OK/Cancel // Returns TRUE if the user selects OK function SDUConfirmOK(msg: string): boolean; begin Result := (SDUMessageDlg(msg, mtConfirmation, [mbOK, mbCancel], 0) = mrOK); end; // ---------------------------------------------------------------------------- // Display confirmation dialog with Yes/No buttons. // Returns TRUE if the user selects Yes. function SDUConfirmYN(msg: string): boolean; begin Result := (SDUMessageDlg(msg, mtConfirmation, [mbYes, mbNo], 0) = mrYes); end; // ---------------------------------------------------------------------------- // Display confirmation dialog with OK/Cancel // Returns TRUE if the user selects OK function SDUWarnOK(msg: string): boolean; begin Result := (SDUMessageDlg(msg, mtWarning, [mbOK, mbCancel], 0) = mrOK); end; // ---------------------------------------------------------------------------- // Display confirmation dialog with Yes/No buttons. // Returns TRUE if the user selects Yes. function SDUWarnYN(msg: string): boolean; begin Result := (SDUMessageDlg(msg, mtWarning, [mbYes, mbNo], 0) = mrYes); end; // ---------------------------------------------------------------------------- // Display confirmation dialog with OK/Cancel // Returns TRUE if the user selects OK function SDUErrorOK(msg: string): boolean; begin Result := (SDUMessageDlg(msg, mtError, [mbOK, mbCancel], 0) = mrOK); end; // ---------------------------------------------------------------------------- // Display confirmation dialog with Yes/No buttons. // Returns TRUE if the user selects Yes. function SDUErrorYN(msg: string): boolean; begin Result := (SDUMessageDlg(msg, mtError, [mbYes, mbNo], 0) = mrYes); end; *) // ---------------------------------------------------------------------------- function TSDUOpenDialog.Execute(): boolean; var oldCWD: string; begin oldCWD := SDUGetCWD(); Result := inherited Execute(); if PreserveCWD then begin SDUSetCWD(oldCWD); end; end; // ---------------------------------------------------------------------------- function TSDUSaveDialog.Execute(): boolean; var oldCWD: string; begin oldCWD := SDUGetCWD(); Result := inherited Execute(); if PreserveCWD then begin SDUSetCWD(oldCWD); end; end; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- END.
// // postprocess.h header binding for the Free Pascal Compiler aka FPC // // Binaries and demos available at http://www.djmaster.com/ // (* * Copyright (C) 2001-2003 Michael Niedermayer (michaelni@gmx.at) * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) unit postprocess; {$mode objfpc}{$H+} interface uses ctypes; const LIB_POSTPROCESS = 'postproc-54.dll'; // #ifndef POSTPROC_POSTPROCESS_H // #define POSTPROC_POSTPROCESS_H (** * @file * @ingroup lpp * external API header *) (** * @defgroup lpp libpostproc * Video postprocessing library. * * @{ *) #include "libpostproc/version.h" (** * Return the LIBPOSTPROC_VERSION_INT constant. *) function postproc_version(): cunsigned; cdecl; external LIB_POSTPROCESS; (** * Return the libpostproc build-time configuration. *) function postproc_configuration(): pchar; cdecl; external LIB_POSTPROCESS; (** * Return the libpostproc license. *) function postproc_license(): pchar; cdecl; external LIB_POSTPROCESS; const PP_QUALITY_MAX = 6; {$if FF_API_QP_TYPE} QP_STORE_T = cint8_t; //deprecated {$endif} #include <inttypes.h> typedef void pp_context; typedef void pp_mode; {$if LIBPOSTPROC_VERSION_INT < (52 shl 16)} typedef pp_context pp_context_t; typedef pp_mode pp_mode_t; extern const pchar const pp_help; ///< a simple help text #else extern const char pp_help[]; ///< a simple help text {$endif} procedure pp_postprocess(const src: array[0..2] of pcuint8_t; const srcStride: array[0..2] of cint; dst: array[0..2] of pcuint8_t; const dstStride: array[0..2] of cint; horizontalSize: cint; verticalSize: cint; const QP_store: pcint8_t; QP_stride: cint; mode: Ppp_mode; ppContext: Ppp_context; pict_type: cint); cdecl; external LIB_POSTPROCESS; (** * Return a pp_mode or NULL if an error occurred. * * @param name the string after "-pp" on the command line * @param quality a number from 0 to PP_QUALITY_MAX *) function pp_get_mode_by_name_and_quality(const name: pchar; quality: cint): Ppp_mode; cdecl; external LIB_POSTPROCESS; procedure pp_free_mode(mode: Ppp_mode); cdecl; external LIB_POSTPROCESS; function pp_get_context(width: cint; height: cint; flags: cint): Ppp_context; cdecl; external LIB_POSTPROCESS; procedure pp_free_context(ppContext: Ppp_context); cdecl; external LIB_POSTPROCESS; const PP_CPU_CAPS_MMX = $80000000; PP_CPU_CAPS_MMX2 = $20000000; PP_CPU_CAPS_3DNOW = $40000000; PP_CPU_CAPS_ALTIVEC = $10000000; PP_CPU_CAPS_AUTO = $00080000; PP_FORMAT = $00000008; PP_FORMAT_420 = ($00000011 or PP_FORMAT); PP_FORMAT_422 = ($00000001 or PP_FORMAT); PP_FORMAT_411 = ($00000002 or PP_FORMAT); PP_FORMAT_444 = ($00000000 or PP_FORMAT); PP_FORMAT_440 = ($00000010 or PP_FORMAT); PP_PICT_TYPE_QP2 = $00000010; ///< MPEG2 style QScale (** * @} *) // #endif (* POSTPROC_POSTPROCESS_H *) implementation end.
unit GLAntiZFightShaderDemo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.Jpeg, GLScene, GLSkydome, GLWin32Viewer, GLObjects, GLTexture, GLGeomObjects, GLMaterial, GLCoordinates, GLCrossPlatform, GLBaseClasses, GLAntiZFightShader; type TForm1 = class(TForm) GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCamera1: TGLCamera; GLSkyDome1: TGLSkyDome; DummyTarget: TGLDummyCube; YellowSphere: TGLSphere; BlueSphere: TGLSphere; GLLightSource1: TGLLightSource; CheckBox1: TCheckBox; GLCylinder1: TGLCylinder; GLDummyCube1: TGLDummyCube; GLDummyCube2: TGLDummyCube; GLDummyCube3: TGLDummyCube; GLCube1: TGLCube; CheckBox2: TCheckBox; GLMaterialLibrary1: TGLMaterialLibrary; procedure FormCreate(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure CheckBox1Click(Sender: TObject); procedure CheckBox2Click(Sender: TObject); public mx, my: Integer; AntiZFightShader: TGLAntiZFightShader; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var TempLibMaterial: TGLLibMaterial; i: Integer; begin Form1.Top := round((screen.Height / 2) - (Form1.Height / 2)); Form1.left := round((screen.width / 2) - (Form1.width / 2)); GLSkyDome1.stars.addrandomstars(5000, RGB(255, 255, 255), false); { Run-time creation of the shader object } AntiZFightShader := TGLAntiZFightShader.Create(Self); { For now, this is simply a value that the user provides to compensate for the overall dimensions of a scene. I have no easy answer for what numbers are good yet: use trial and error. Basically, if your scene is very large, use a large number, and vice versa } AntiZFightShader.Modifier := 200000000; { Assign the shader to the appropriate materials } for i := 0 to 3 do begin GLMaterialLibrary1.Materials[i].Shader := AntiZFightShader; end; { Turn off GLScene's object depth sorting, as it doesn't take into account manipulations of the projection matrix } GLDummyCube2.ObjectStyle := GLDummyCube2.ObjectStyle + [osIgnoreDepthBuffer]; GLDummyCube3.ObjectStyle := GLDummyCube3.ObjectStyle + [osIgnoreDepthBuffer]; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mx := X; my := Y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if Shift <> [] then GLCamera1.MoveAroundTarget(my - Y, mx - X); mx := X; my := Y; end; procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta / -300)); end; procedure TForm1.CheckBox1Click(Sender: TObject); begin AntiZFightShader.Enabled := CheckBox1.Checked; GLSceneViewer1.Refresh; end; procedure TForm1.CheckBox2Click(Sender: TObject); begin if CheckBox2.Checked then begin GLDummyCube2.ObjectStyle := GLDummyCube2.ObjectStyle + [osIgnoreDepthBuffer]; GLDummyCube3.ObjectStyle := GLDummyCube3.ObjectStyle + [osIgnoreDepthBuffer]; end else begin GLDummyCube2.ObjectStyle := GLDummyCube2.ObjectStyle - [osIgnoreDepthBuffer]; GLDummyCube3.ObjectStyle := GLDummyCube3.ObjectStyle - [osIgnoreDepthBuffer]; end; GLSceneViewer1.Refresh; end; end.
unit Magento.Stock_Item; interface uses Magento.Interfaces, System.JSON; type TMagentoStock_Item = class (TInterfacedObject, iMagentoStock_Item) private FParent : iMagentoExtensionAttributes; FJSON : TJSONObject; public constructor Create(Parent : iMagentoExtensionAttributes); destructor Destroy; override; class function New(Parent : iMagentoExtensionAttributes) : iMagentoStock_Item; function Qty(value : integer) : iMagentoStock_Item; function Is_in_stock(value : boolean) : iMagentoStock_Item; function &End : iMagentoExtensionAttributes; end; implementation { TMagentoStock_Item } uses Magento.Factory; function TMagentoStock_Item.&End: iMagentoExtensionAttributes; begin FParent.Stock_item(FJSON); Result := FParent; end; constructor TMagentoStock_Item.Create(Parent : iMagentoExtensionAttributes); begin FJSON := TJSONObject.Create; FParent := Parent; end; destructor TMagentoStock_Item.Destroy; begin // FJSON.DisposeOf; inherited; end; function TMagentoStock_Item.Is_in_stock(value: boolean): iMagentoStock_Item; begin Result := Self; FJSON.AddPair('is_in_stock', TJSONBool.Create(value)); end; class function TMagentoStock_Item.New(Parent : iMagentoExtensionAttributes) : iMagentoStock_Item; begin Result := self.Create(Parent); end; function TMagentoStock_Item.Qty(value: integer): iMagentoStock_Item; begin Result := Self; FJSON.AddPair('qty',TJSONNumber.Create(value)); end; end.
unit MeshColourCalculator; interface uses BasicMathsTypes, BasicDataTypes, NeighborDetector, MeshGeometryList, Mesh; type TMeshColourCalculator = class private function GetEquivalentVertex(_VertexID,_MaxVertexID: integer; const _VertexEquivalences: auint32): integer; public DistanceFunction: TDistanceFunc; constructor Create; procedure FindMeshVertexColours(var _Mesh: TMesh); procedure FindMeshFaceColours(var _Mesh: TMesh); procedure FilterAndFixColours(var _Colours: TAVector4f); procedure GetVertexColoursFromFaces(var _VertColours: TAVector4f; const _FaceColours: TAVector4f; const _Vertices: TAVector3f; _NumVertices: integer; const _Faces: auint32; _VerticesPerFace: integer; const _NeighborDetector: TNeighborDetector; const _VertexEquivalences: auint32; _DistanceFunction : TDistanceFunc); overload; procedure GetVertexColoursFromFaces(var _VertColours: TAVector4f; const _Geometry: CMeshGeometryList; const _Vertices: TAVector3f; _NumVertices: integer; const _VertexEquivalences: auint32; _DistanceFunction : TDistanceFunc); overload; procedure GetFaceColoursFromVertexes(const _VertColours: TAVector4f; var _FaceColours: TAVector4f; const _Faces: auint32; _VerticesPerFace: integer); procedure BackupColourVector(const _Source: TAVector4f; var _Destination: TAVector4f); end; implementation uses MeshGeometryBase, MeshBRepGeometry, Math, MeshPluginBase, GLConstants, NeighborhoodDataPlugin, DistanceFormulas; constructor TMeshColourCalculator.Create; begin DistanceFunction := GetLinearDistance; inherited Create; end; procedure TMeshColourCalculator.FindMeshVertexColours(var _Mesh: TMesh); var NeighborDetector : TNeighborDetector; NeighborhoodPlugin: PMeshPluginBase; VertexEquivalences: auint32; MyFaces: auint32; MyFaceColours, OriginalColours: TAVector4f; NumVertices: integer; begin if High(_Mesh.Colours) <= 0 then begin SetLength(_Mesh.Colours,High(_Mesh.Vertices)+1); end; NeighborhoodPlugin := _Mesh.GetPlugin(C_MPL_NEIGHBOOR); if NeighborhoodPlugin <> nil then begin VertexEquivalences := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexEquivalences; NumVertices := TNeighborhoodDataPlugin(NeighborhoodPlugin^).InitialVertexCount; if TNeighborhoodDataPlugin(NeighborhoodPlugin^).UseQuadFaces then begin NeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaceNeighbors; MyFaces := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaces; MyFaceColours := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaceColours; SetLength(OriginalColours,High(MyFaceColours)+1); BackupColourVector(MyFaceColours,OriginalColours); _Mesh.Geometry.GoToFirstElement; GetVertexColoursFromFaces(_Mesh.Colours,OriginalColours,_Mesh.Vertices,NumVertices,MyFaces,(_Mesh.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,NeighborDetector,VertexEquivalences,DistanceFunction); SetLength(OriginalColours,0); end else begin GetVertexColoursFromFaces(_Mesh.Colours,_Mesh.Geometry,_Mesh.Vertices,NumVertices,VertexEquivalences,DistanceFunction); end; end else begin VertexEquivalences := nil; NumVertices := High(_Mesh.Vertices)+1; GetVertexColoursFromFaces(_Mesh.Colours,_Mesh.Geometry,_Mesh.Vertices,NumVertices,VertexEquivalences,DistanceFunction); end; end; procedure TMeshColourCalculator.FindMeshFaceColours(var _Mesh: TMesh); var CurrentGeometry: PMeshGeometryBase; begin _Mesh.Geometry.GoToFirstElement; CurrentGeometry := _Mesh.Geometry.Current; while CurrentGeometry <> nil do begin GetFaceColoursFromVertexes(_Mesh.Colours,(CurrentGeometry^ as TMeshBRepGeometry).Colours,(CurrentGeometry^ as TMeshBRepGeometry).Faces,(CurrentGeometry^ as TMeshBRepGeometry).VerticesPerFace); _Mesh.Geometry.GoToNextElement; CurrentGeometry := _Mesh.Geometry.Current; end; end; function TMeshColourCalculator.GetEquivalentVertex(_VertexID,_MaxVertexID: integer; const _VertexEquivalences: auint32): integer; begin Result := _VertexID; while Result > _MaxVertexID do begin Result := _VertexEquivalences[Result]; end; end; procedure TMeshColourCalculator.GetVertexColoursFromFaces(var _VertColours: TAVector4f; const _FaceColours: TAVector4f; const _Vertices: TAVector3f; _NumVertices: integer; const _Faces: auint32; _VerticesPerFace: integer; const _NeighborDetector: TNeighborDetector; const _VertexEquivalences: auint32; _DistanceFunction : TDistanceFunc); var HitCounter: single; i,f,v,v1 : integer; MaxVerticePerFace: integer; MidPoint : TAVector3f; Distance: single; begin MaxVerticePerFace := _VerticesPerFace - 1; // Let's check the mid point of every face. SetLength(MidPoint,(High(_Faces)+1) div _VerticesPerFace); f := 0; i := 0; while (f < High(_Faces)) do begin // find central position of the face. MidPoint[i].X := 0; MidPoint[i].Y := 0; MidPoint[i].Z := 0; for v := 0 to MaxVerticePerFace do begin v1 := f + v; MidPoint[i].X := MidPoint[i].X + _Vertices[_Faces[v1]].X; MidPoint[i].Y := MidPoint[i].Y + _Vertices[_Faces[v1]].Y; MidPoint[i].Z := MidPoint[i].Z + _Vertices[_Faces[v1]].Z; end; MidPoint[i].X := MidPoint[i].X / _VerticesPerFace; MidPoint[i].Y := MidPoint[i].Y / _VerticesPerFace; MidPoint[i].Z := MidPoint[i].Z / _VerticesPerFace; inc(i); inc(f,_VerticesPerFace); end; // Now, let's check each vertex and find its colour. for v := Low(_VertColours) to (_NumVertices - 1) do begin HitCounter := 0; _VertColours[v].X := 0; _VertColours[v].Y := 0; _VertColours[v].Z := 0; _VertColours[v].W := 0; f := _NeighborDetector.GetNeighborFromID(v); // get face neighbor from vertex. while f <> -1 do begin Distance := sqrt(Power(MidPoint[f].X - _Vertices[v].X,2) + Power(MidPoint[f].Y - _Vertices[v].Y,2) + Power(MidPoint[f].Z - _Vertices[v].Z,2)); Distance := _DistanceFunction(Distance); _VertColours[v].X := _VertColours[v].X + (_FaceColours[f].X * Distance); _VertColours[v].Y := _VertColours[v].Y + (_FaceColours[f].Y * Distance); _VertColours[v].Z := _VertColours[v].Z + (_FaceColours[f].Z * Distance); _VertColours[v].W := _VertColours[v].W + (_FaceColours[f].W * Distance); HitCounter := HitCounter + Distance; f := _NeighborDetector.GetNextNeighbor; end; if HitCounter > 0 then begin _VertColours[v].X := (_VertColours[v].X / HitCounter); _VertColours[v].Y := (_VertColours[v].Y / HitCounter); _VertColours[v].Z := (_VertColours[v].Z / HitCounter); _VertColours[v].W := (_VertColours[v].W / HitCounter); end; end; v := _NumVertices; while v <= High(_Vertices) do begin v1 := GetEquivalentVertex(v,_NumVertices,_VertexEquivalences); _VertColours[v].X := _VertColours[v1].X; _VertColours[v].Y := _VertColours[v1].Y; _VertColours[v].Z := _VertColours[v1].Z; _VertColours[v].W := _VertColours[v1].W; end; SetLength(MidPoint,0); end; procedure TMeshColourCalculator.GetVertexColoursFromFaces(var _VertColours: TAVector4f; const _Geometry: CMeshGeometryList; const _Vertices: TAVector3f; _NumVertices: integer; const _VertexEquivalences: auint32; _DistanceFunction : TDistanceFunc); var CurrentGeometry: PMeshGeometryBase; HitCounter: array of single; i,f,v,v1 : integer; MaxVerticePerFace,VerticesPerFace: integer; MidPoint : TAVector3f; Distance: single; begin // Initialize _VertsColours and HitCounter SetLength(HitCounter,_NumVertices); for v := Low(_VertColours) to (_NumVertices - 1) do begin HitCounter[v] := 0; _VertColours[v].X := 0; _VertColours[v].Y := 0; _VertColours[v].Z := 0; _VertColours[v].W := 0; end; // Check each geometry support. _Geometry.GoToFirstElement; CurrentGeometry := _Geometry.Current; while CurrentGeometry <> nil do begin VerticesPerFace := (CurrentGeometry^ as TMeshBRepGeometry).VerticesPerFace; MaxVerticePerFace := VerticesPerFace - 1; SetLength(MidPoint,(High((CurrentGeometry^ as TMeshBRepGeometry).Faces)+1) div VerticesPerFace); // Let's check the mid point of every face. f := 0; i := 0; while (f < (CurrentGeometry^ as TMeshBRepGeometry).NumFaces) do begin // find central position of the face. MidPoint[i].X := 0; MidPoint[i].Y := 0; MidPoint[i].Z := 0; for v := 0 to MaxVerticePerFace do begin v1 := (CurrentGeometry^ as TMeshBRepGeometry).Faces[f + v]; MidPoint[i].X := MidPoint[i].X + _Vertices[v1].X; MidPoint[i].Y := MidPoint[i].Y + _Vertices[v1].Y; MidPoint[i].Z := MidPoint[i].Z + _Vertices[v1].Z; end; MidPoint[i].X := MidPoint[i].X / VerticesPerFace; MidPoint[i].Y := MidPoint[i].Y / VerticesPerFace; MidPoint[i].Z := MidPoint[i].Z / VerticesPerFace; inc(i); inc(f,VerticesPerFace); end; // Let's add the face colours into the vertexes. f := 0; i := 0; while (i < (CurrentGeometry^ as TMeshBRepGeometry).NumFaces) do begin for v := 0 to MaxVerticePerFace do begin v1 := (CurrentGeometry^ as TMeshBRepGeometry).Faces[f + v]; Distance := sqrt(Power(MidPoint[i].X - _Vertices[v1].X,2) + Power(MidPoint[i].Y - _Vertices[v1].Y,2) + Power(MidPoint[i].Z - _Vertices[v1].Z,2)); Distance := _DistanceFunction(Distance); _VertColours[v1].X := _VertColours[v1].X + ((CurrentGeometry^ as TMeshBRepGeometry).Colours[i].X * Distance); _VertColours[v1].Y := _VertColours[v1].Y + ((CurrentGeometry^ as TMeshBRepGeometry).Colours[i].Y * Distance); _VertColours[v1].Z := _VertColours[v1].Z + ((CurrentGeometry^ as TMeshBRepGeometry).Colours[i].Z * Distance); _VertColours[v1].W := _VertColours[v1].W + ((CurrentGeometry^ as TMeshBRepGeometry).Colours[i].W * Distance); HitCounter[v1] := HitCounter[v1] + Distance; end; inc(i); inc(f,VerticesPerFace); end; // Move to next geometry _Geometry.GoToNextElement; CurrentGeometry := _Geometry.Current; end; // Now, let's find the final colour of each vertex. for v := Low(_VertColours) to (_NumVertices - 1) do begin if HitCounter[v] > 0 then begin _VertColours[v].X := (_VertColours[v].X / HitCounter[v]); _VertColours[v].Y := (_VertColours[v].Y / HitCounter[v]); _VertColours[v].Z := (_VertColours[v].Z / HitCounter[v]); _VertColours[v].W := (_VertColours[v].W / HitCounter[v]); end; end; // Ensure the correct colour value for _VertexEquivalences. if (_VertexEquivalences <> nil) then begin v := _NumVertices; while v <= High(_Vertices) do begin v1 := GetEquivalentVertex(v,_NumVertices,_VertexEquivalences); _VertColours[v].X := _VertColours[v1].X; _VertColours[v].Y := _VertColours[v1].Y; _VertColours[v].Z := _VertColours[v1].Z; _VertColours[v].W := _VertColours[v1].W; end; end; // Free memory. SetLength(MidPoint,0); SetLength(HitCounter,0); end; procedure TMeshColourCalculator.GetFaceColoursFromVertexes(const _VertColours: TAVector4f; var _FaceColours: TAVector4f; const _Faces: auint32; _VerticesPerFace: integer); var f,v,fpos,MaxVerticePerFace : integer; begin // Define face colours. MaxVerticePerFace := _VerticesPerFace - 1; f := 0; fpos := 0; while fpos < High(_Faces) do begin // average all colours from all vertexes from the face. _FaceColours[f].X := 0; _FaceColours[f].Y := 0; _FaceColours[f].Z := 0; _FaceColours[f].W := 0; for v := 0 to MaxVerticePerFace do begin _FaceColours[f].X := _FaceColours[f].X + _VertColours[_Faces[fpos]].X; _FaceColours[f].Y := _FaceColours[f].Y + _VertColours[_Faces[fpos]].Y; _FaceColours[f].Z := _FaceColours[f].Z + _VertColours[_Faces[fpos]].Z; _FaceColours[f].W := _FaceColours[f].W + _VertColours[_Faces[fpos]].W; inc(fpos); end; // Get result _FaceColours[f].X := (_FaceColours[f].X / _VerticesPerFace); _FaceColours[f].Y := (_FaceColours[f].Y / _VerticesPerFace); _FaceColours[f].Z := (_FaceColours[f].Z / _VerticesPerFace); _FaceColours[f].W := (_FaceColours[f].W / _VerticesPerFace); inc(f); end; end; procedure TMeshColourCalculator.FilterAndFixColours(var _Colours: TAVector4f); var i : integer; begin for i := Low(_Colours) to High(_Colours) do begin // Avoid problematic colours: if _Colours[i].X < 0 then _Colours[i].X := 0 else if _Colours[i].X > 1 then _Colours[i].X := 1; if _Colours[i].Y < 0 then _Colours[i].Y := 0 else if _Colours[i].Y > 1 then _Colours[i].Y := 1; if _Colours[i].Z < 0 then _Colours[i].Z := 0 else if _Colours[i].Z > 1 then _Colours[i].Z := 1; if _Colours[i].W < 0 then _Colours[i].W := 0 else if _Colours[i].W > 1 then _Colours[i].W := 1; end; end; procedure TMeshColourCalculator.BackupColourVector(const _Source: TAVector4f; var _Destination: TAVector4f); var i : integer; begin for i := Low(_Source) to High(_Source) do begin _Destination[i].X := _Source[i].X; _Destination[i].Y := _Source[i].Y; _Destination[i].Z := _Source[i].Z; _Destination[i].W := _Source[i].W; end; end; end.
unit uFPGListView; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ComCtrls, ClipBrd, IntfGraphics, uFPG, uLoadImage, uMAPGraphic, utools; type TFPGListView = class(TListView) private { Private declarations } FrepaintNumber : Integer ; ffpg: TFPG; fnotClipboardImage : String; protected { Protected declarations } public { Public declarations } constructor Create(TheOwner: TComponent); override; procedure Load_Images(progressBar: TProgressBar); procedure Insert_Images(lImages: TStrings; progressBar: TProgressBar); procedure Insert_Imagescb(var progressBar: TProgressBar); procedure add_items(index: word); procedure replace_item(index: word); procedure DrawProportional( var bmp_src : TBitMap; var bmp_dst: TBitMap ); published { Published declarations } property Fpg: TFpg read Ffpg write Ffpg; property repaintNumber: Integer read FrepaintNumber write FrepaintNumber; property notClipboardImage: String read fnotClipboardImage write fnotClipboardImage; end; procedure Register; implementation procedure Register; begin {$I uFPGListView_icon.lrs} RegisterComponents('FPG Editor', [TFPGListView]); end; constructor TFPGListView.Create(TheOwner: TComponent); begin inherited Create(TheOwner); ffpg:=TFpg.Create; with ffpg do SetSubComponent(True); end; procedure TFPGListView.Load_Images(progressBar: TProgressBar); var Count: integer; begin //Limpiamos la lista de imagenes LargeImages.Clear; Items.Clear; progressBar.Position := 0; progressBar.Show; progressBar.Repaint; for Count := 1 to Fpg.Count do begin with Fpg.images[Count] do begin add_items(Count); if (Count mod FrepaintNumber) = 0 then begin progressBar.Position := (Count * 100) div Fpg.Count; progressBar.Repaint; end; end; end; progressBar.Hide; end; procedure TFPGListView.Insert_Images(lImages: TStrings; progressBar: TProgressBar); var i : Integer; code : Word; bmp_src : TMAPGraphic; filename: String; begin // Creamos el bitmap tipografía y destino bmp_src := TMAPGraphic.Create; // Se inializa la barra de progresión progressBar.Position := 0; progressBar.Show; progressBar.Repaint; for i := 0 to lImages.Count - 1 do begin code := Fpg.indexOfCode(Fpg.lastcode); if code <> 0 then begin if MessageDlg('El código: ' + IntToStr(Fpg.lastcode) + ' ya existe. ¿Desea sobrescribirlo?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then continue; end; filename := ExtractFileName(lImages.Strings[i]);; // Se carga la imagen loadImageFile(bmp_src, lImages.Strings[i] ); // ver como meter fpgeditor3.1 if code <> 0 then begin fpg.replace_bitmap(code, ChangeFileExt(filename, ''), ChangeFileExt(filename, ''), bmp_src); replace_item(code); end else begin Fpg.Count := Fpg.Count + 1; fpg.add_bitmap(Fpg.Count, ChangeFileExt(filename, ''), ChangeFileExt(filename, ''), bmp_src); add_items(Fpg.Count); end; Fpg.lastcode := Fpg.lastcode + 1; //bmp_src.FreeImage; progressBar.Position := ((i + 1) * 100) div lImages.Count; progressBar.Repaint; end; Fpg.lastcode := Fpg.lastcode - 1; bmp_src.Free; Fpg.update := True; Repaint; progressBar.Hide; end; procedure TFPGListView.Insert_Imagescb(var progressBar: TProgressBar); var bmp_src: TMAPGraphic; begin // Se inializa la barra de progresión progressBar.Position := 50; progressBar.Show; progressBar.Repaint; bmp_src := TMAPGraphic.Create; bmp_src.PixelFormat := pf32bit; try bmp_src.LoadFromClipBoardFormat(cf_BitMap); except bmp_src.Destroy; progressBar.Hide; MessageDlg(notClipboardImage, mtError, [mbOK], 0); Exit; end; // Se incrementa el código de la imagen Fpg.lastcode := Fpg.lastcode + 1; // Busca hasta que encuentre un código libre while Fpg.CodeExists(Fpg.lastcode) do Fpg.lastcode := Fpg.lastcode + 1; // ver como meter fpgeditor3.1 Fpg.Count := Fpg.Count + 1; fpg.add_bitmap(Fpg.Count, 'ClipBoard', 'ClipBoard', bmp_src); add_items(Fpg.Count); progressBar.Hide; bmp_src.Destroy; Fpg.update := True; end; procedure TFPGListView.add_items(index: word); var list_bmp: TListItem; bmp_dst: TBitMap; begin // Pintamos el icono DrawProportional(TBitmap(Fpg.images[index]), bmp_dst); list_bmp := Items.Add; list_bmp.ImageIndex := LargeImages.add(bmp_dst, nil); // Se establece el código del FPG list_bmp.Caption := Format('%.3d',[Fpg.images[index].code]); //NumberTo3Char(Fpg.images[index].graph_code); // Se añaden los datos de la imagen a la lista list_bmp.SubItems.Add(Fpg.images[index].fpname); list_bmp.SubItems.Add(Fpg.images[index].Name); list_bmp.SubItems.Add(IntToStr(Fpg.images[index].Width)); list_bmp.SubItems.Add(IntToStr(Fpg.images[index].Height)); list_bmp.SubItems.Add(IntToStr(Fpg.images[index].CPointsCount)); end; procedure TFPGListView.replace_item(index: word); var list_bmp: TListItem; bmp_dst: TBitMap; begin // Pintamos el icono DrawProportional(TBitmap(Fpg.images[index]), bmp_dst); list_bmp := Items.Item[index - 1]; LargeImages.Replace(index - 1, bmp_dst, nil); //list_bmp.ImageIndex := // Se añaden los datos de la imagen a la lista list_bmp.Caption := Format('%.3d',[Fpg.images[index].code]); list_bmp.SubItems.Strings[0] := Fpg.images[index].fpname; list_bmp.SubItems.Strings[1] := Fpg.images[index].Name; list_bmp.SubItems.Strings[2] := IntToStr(Fpg.images[index].Width); list_bmp.SubItems.Strings[3] := IntToStr(Fpg.images[index].Height); // list_bmp.SubItems.Strings[4]:=IntToStr(Fpg.images[index].ncpoints); end; procedure TFPGListView.DrawProportional( var bmp_src : TBitMap; var bmp_dst: TBitMap ); var x, y, finalWidth, finalHeight : integer; bitmap1 : TBitmap; begin bmp_dst := TBitmap.Create; bmp_dst.PixelFormat:= pf32bit; bitmap1 := TBitmap.Create; bitmap1.PixelFormat:= pf32bit; bmp_dst.SetSize(LargeImages.Width,LargeImages.Height); setAlpha(bmp_dst,0,Rect(0, 0, LargeImages.Width , LargeImages.Height)); x := 0; y := 0; finalWidth := bmp_dst.Width; finalHeight := bmp_dst.Height; if bmp_src <> nil then begin if bmp_src.Width > bmp_src.Height then begin finalHeight := (bmp_src.Height * LargeImages.Width) div bmp_src.Width; y := (LargeImages.Height - finalHeight) div 2; end else begin finalWidth := (bmp_src.Width * LargeImages.Height) div bmp_src.Height; x := (LargeImages.Width - finalWidth) div 2; end; bitmap1.SetSize(finalWidth,finalHeight); bitmap1.Canvas.StretchDraw( Rect(0, 0, finalWidth , finalHeight ), bmp_src ); copyPixels(bmp_dst,bitmap1,x,y); if countAlphas(bitmap1,0) >= finalWidth*finalHeight then setAlpha(bmp_dst,255,Rect(x, y, x+finalWidth , y+finalHeight)); bitmap1.Free; end; end; end.
unit ufrmGoodReceiving; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialogBrowse, StdCtrls, ExtCtrls, SUIButton, Grids, BaseGrid, AdvGrid, ufraFooter5Button, JclStrings, Mask, JvToolEdit, JvEdit, ActnList, DateUtils, AdvObj, JvExStdCtrls, JvValidateEdit, JvExMask, AdvUtil, System.Actions, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, Vcl.Menus, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, cxCurrencyEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxButtons, ufraFooterDialog3Button, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid; type TfrmGoodsReceiving = class(TfrmMasterDialogBrowse) pnlTop: TPanel; lbl1: TLabel; edtPONo: TEdit; btn1: TcxButton; lbl5: TLabel; lbl6: TLabel; lbl7: TLabel; lbl8: TLabel; dtDatePO: TcxDateEdit; dtDateSO: TcxDateEdit; edtSONo: TEdit; edtSuplierCode: TEdit; edtSuplierName: TEdit; edtDONo: TEdit; lbl2: TLabel; dtDateDO: TcxDateEdit; lbl4: TLabel; edtNP: TEdit; lbl9: TLabel; lbl10: TLabel; jvcuredtSubTotal: TcxCurrencyEdit; jvcuredtPPN: TcxCurrencyEdit; lbl13: TLabel; jvcuredtPPNBM: TcxCurrencyEdit; lbl14: TLabel; lbl12: TLabel; jvcuredtDiscount: TcxCurrencyEdit; jvcuredtTotalBeli: TcxCurrencyEdit; lbl11: TLabel; lbl3: TLabel; lbl15: TLabel; edtjfBonus: TcxCurrencyEdit; lbl16: TLabel; edtjfTotalColie: TcxCurrencyEdit; edtjfRecvBonus: TcxCurrencyEdit; lbl17: TLabel; pnl2: TPanel; lbl18: TLabel; lbl19: TLabel; lbl20: TLabel; lbl21: TLabel; lbl22: TLabel; lbl23: TLabel; edtProductName: TEdit; lbl24: TLabel; edtjfTotalOrder: TcxCurrencyEdit; edtjfDisc1: TcxCurrencyEdit; edtjfDisc2: TcxCurrencyEdit; jvcuredtNilaiDisc: TcxCurrencyEdit; jvcuredtTotalDisc: TcxCurrencyEdit; jvcuredtSellPrice: TcxCurrencyEdit; btn2: TcxButton; lblStatusPO: TLabel; btnCetakNP: TcxButton; procedure actCancelExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure strgGridCanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); procedure strgGridCellValidate(Sender: TObject; ACol, ARow: Integer; var Value: String; var Valid: Boolean); procedure btn1Click(Sender: TObject); procedure btn2Click(Sender: TObject); procedure edtPONoChange(Sender: TObject); procedure edtDONoKeyPress(Sender: TObject; var Key: Char); procedure strgGridGetEditorType(Sender: TObject; ACol, ARow: Integer; var AEditor: TEditorType); procedure edtPONoKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure strgGridGetCellColor(Sender: TObject; ARow, ACol: Integer; AState: TGridDrawState; ABrush: TBrush; AFont: TFont); procedure strgGridClick(Sender: TObject); procedure strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); procedure strgGridCheckBoxClick(Sender: TObject; ACol, ARow: Integer; State: Boolean); procedure FormActivate(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure strgGridGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); procedure strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String); procedure strgGridKeyPress(Sender: TObject; var Key: Char); procedure btn2Enter(Sender: TObject); procedure btn2Exit(Sender: TObject); procedure btn1Exit(Sender: TObject); procedure btn1Enter(Sender: TObject); procedure btnCetakNPEnter(Sender: TObject); procedure btnCetakNPExit(Sender: TObject); private FValidDate: TDate; FStatusPO: string; FTOP: Integer; FCommon,FAssgros,FTrader: Real; FHargaDisc: Real; function SaveData: Boolean; function CheckIsPOExist(ANoPO:string): Boolean; function SumColStringGrid(StrGrid:TAdvStringGrid;Col,RowStart,RowEnd:Integer):Real; function CekChekBoxInGrid: Boolean; procedure ShowDetailPO(ANoPO:string); procedure FormulaDisconPerRow(Row:Integer; QTYReceive:Real); procedure SetHeaderGrid; procedure SetClearValue; procedure ClearForm; procedure AllocatedStock(Receive: Real; var FCommon,FAssgros,FTrader: Real); public { Public declarations } end; var frmGoodsReceiving: TfrmGoodsReceiving; ParamList: TStringList; implementation uses uGTSUICommonDlg,suithemes, uConstanta, ufrmSearchPO, uConn, uDeliveryOrder, DB, udmReport, VarUtils, ufrmReprintNP; {$R *.dfm} procedure TfrmGoodsReceiving.actCancelExecute(Sender: TObject); begin inherited; SetClearValue; end; procedure TfrmGoodsReceiving.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; // frmMain.DestroyMenu((Sender as TForm)); Action := caFree; end; procedure TfrmGoodsReceiving.FormulaDisconPerRow(Row:Integer; QTYReceive:Real); var Total, Price, Disc1, Disc2, Disc3, TotalDiscTemp, TotalDisc: Real; begin Price:= StrToFloat(strgGrid.Cells[2,Row]); Disc1:= StrToFloat(strgGrid.Cells[9,Row]); Disc2:= StrToFloat(strgGrid.Cells[10,Row]); Disc3:= StrToFloat(strgGrid.Cells[11,Row]); //TotalDisc = Total Harga setelah discount Total := Price * QTYReceive; TotalDiscTemp := ((100-Disc1)/100) * Total; TotalDisc := (((100-Disc2)/100) * TotalDiscTemp) - (Disc3* QTYReceive); strgGrid.Cells[18,Row]:= FormatFloat('##0.00',TotalDisc); //Nilai dicountnya strgGrid.Cells[31,Row]:= FormatFloat('##0.00',TOTAL - TotalDisc); //strgGrid.Cells[18,Row]:= FormatFloat('##0.00',Total-StrToFloat(strgGrid.Cells[15,Row])); end; procedure TfrmGoodsReceiving.AllocatedStock (Receive: Real; var FCommon,FAssgros,FTrader: Real); var sisa, AllocCommon, AllocAssgros, AllocTrader: Real; begin AllocAssgros:= 0; AllocTrader:= 0; sisa:= Receive - FCommon; if sisa <= 0 then AllocCommon:= Receive else begin AllocCommon:= FCommon; Receive:= sisa; sisa:= Receive - FTrader; if sisa <= 0 then AllocTrader:= Receive else begin AllocTrader:= FTrader; AllocAssgros:= sisa; end; end; FCommon:= AllocCommon; FAssgros:= AllocAssgros; FTrader:= AllocTrader; end; function TfrmGoodsReceiving.CekChekBoxInGrid: Boolean; var i: Integer; hasil: Boolean; begin hasil:= True; i:=1; while(hasil)and(i<=strgGrid.RowCount-1)do begin strgGrid.GetCheckBoxState(7,i,hasil); Inc(i); end; Result:= hasil; end; function TfrmGoodsReceiving.SaveData: Boolean; var arrParam: TArr; Hasil: Boolean; i: Integer; Receive,DOId: Real; begin try Screen.Cursor:= crHourGlass; Hasil:= False; if not assigned(DeliveryOrder) then DeliveryOrder := TDeliveryOrder.Create; if lblStatusPO.Font.Color=clRed then begin //Set Status PO to Expired SetLength(arrParam,3); arrParam[0].tipe:= ptString; arrParam[0].data:= PO_DESCRIPTION_EXPIRED; arrParam[1].tipe:= ptInteger; arrParam[1].data:= FLoginId; arrParam[2].tipe:= ptString; arrParam[2].data:= edtPONo.Text; Hasil:= DeliveryOrder.SetPOExpired(arrParam); end else if lblStatusPO.Font.Color=clBlack then begin //Set Status PO to Received SetLength(arrParam,4); arrParam[0].tipe:= ptDateTime; arrParam[0].data:= dtDateDO.Date; arrParam[1].tipe:= ptString; arrParam[1].data:= PO_DESCRIPTION_RECEIVED; arrParam[2].tipe:= ptInteger; arrParam[2].data:= FLoginId; arrParam[3].tipe:= ptString; arrParam[3].data:= edtPONo.Text; Hasil:= DeliveryOrder.SetPOOrdered(arrParam); if not Hasil then begin Result:= Hasil; Exit; end; //Insert Data to DO SetLength(arrParam,25); arrParam[0].tipe := ptString; arrParam[0].data := edtNP.Text; arrParam[1].tipe := ptString; arrParam[1].data := edtPONo.Text; arrParam[2].tipe := ptDateTime; arrParam[2].data := dtDateDO.Date; arrParam[3].tipe := ptCurrency; arrParam[3].data := 0; //hitung sama triger - jvcuredtSubTotal.Value; arrParam[4].tipe := ptCurrency; arrParam[4].data := 0; //hitung sama triger arrParam[5].tipe := ptCurrency; arrParam[5].data := 0; //hitung sama triger arrParam[6].tipe := ptCurrency; arrParam[6].data := 0; //hitung sama triger arrParam[7].tipe := ptInteger; arrParam[7].data := 0; arrParam[8].tipe := ptDateTime; arrParam[8].data := Now + FTOP; arrParam[9].tipe := ptInteger; arrParam[9].data := 0; arrParam[10].tipe:= ptString; arrParam[10].data:= DO_DESCRIPTION_RECEIVED; arrParam[11].tipe:= ptInteger; arrParam[11].data:= 0; arrParam[12].tipe:= ptInteger; arrParam[12].data:= 0; arrParam[13].tipe:= ptInteger; arrParam[13].data:= 0; arrParam[14].tipe:= ptCurrency; arrParam[14].data:= edtjfTotalOrder.Value; arrParam[15].tipe:= ptCurrency; arrParam[15].data:= edtjfBonus.Value; arrParam[16].tipe:= ptCurrency; arrParam[16].data:= edtjfTotalColie.Value; arrParam[17].tipe:= ptCurrency; arrParam[17].data:= edtjfRecvBonus.Value; arrParam[18].tipe:= ptInteger; arrParam[18].data:= 1; arrParam[19].tipe:= ptInteger; arrParam[19].data:= 0; arrParam[20].tipe:= ptInteger; arrParam[20].data:= 0; arrParam[21].tipe:= ptString; arrParam[21].data:= edtDONo.Text; arrParam[22].tipe:= ptInteger; arrParam[22].data:= FLoginId; arrParam[23].tipe:= ptCurrency; arrParam[23].data:= edtjfBonus.Value; arrParam[24].tipe:= ptCurrency; arrParam[24].data:= edtjfRecvBonus.Value; Hasil:= DeliveryOrder.InputDO(arrParam); if not Hasil then begin Result:= Hasil; Exit; end; //Insert Data to DO Detil for i:=1 to strgGrid.RowCount-1 do begin DOId:= DeliveryOrder.GetDODID; SetLength(arrParam,21); arrParam[0].tipe := ptString; arrParam[0].data := edtDONo.Text; arrParam[1].tipe := ptInteger; arrParam[1].data := StrToInt(strgGrid.Cells[19,i]); arrParam[2].tipe := ptCurrency; arrParam[2].data := StrToFloat(strgGrid.Cells[3,i]); arrParam[3].tipe := ptCurrency; arrParam[3].data := StrToFloat(strgGrid.Cells[4,i]); Receive:= StrToFloat(strgGrid.Cells[4,i]); FCommon:= StrToFloat(strgGrid.Cells[20,i]); FAssgros:= StrToFloat(strgGrid.Cells[21,i]); FTrader:= StrToFloat(strgGrid.Cells[22,i]); AllocatedStock(Receive,FCommon,FAssgros,FTrader); arrParam[4].tipe := ptCurrency; arrParam[4].data := StrToFloat(strgGrid.Cells[20,i]); arrParam[5].tipe := ptCurrency; arrParam[5].data := StrToFloat(strgGrid.Cells[21,i]); arrParam[6].tipe := ptCurrency; arrParam[6].data := StrToFloat(strgGrid.Cells[22,i]); arrParam[7].tipe := ptCurrency; arrParam[7].data := FCommon; arrParam[8].tipe := ptCurrency; arrParam[8].data := FTrader; arrParam[9].tipe := ptCurrency; arrParam[9].data := FAssgros; arrParam[10].tipe := ptString; arrParam[10].data := strgGrid.Cells[5,i]; arrParam[11].tipe := ptCurrency; arrParam[11].data := StrToFloat(strgGrid.Cells[2,i]); //harga arrParam[12].tipe := ptCurrency; arrParam[12].data := StrToFloat(strgGrid.Cells[9,i]); //disc1 arrParam[13].tipe := ptCurrency; arrParam[13].data := StrToFloat(strgGrid.Cells[10,i]); //disc2 arrParam[14].tipe := ptCurrency; arrParam[14].data := StrToFloat(strgGrid.Cells[11,i]); //disc3 arrParam[15].tipe := ptCurrency; arrParam[15].data := StrToFloat(strgGrid.Cells[29,i]); //PPN PERSEN >> PPN = BY TRIGGER arrParam[16].tipe := ptCurrency; arrParam[16].data := StrToFloat(strgGrid.Cells[30,i]); //PPNBM PERSEN >> PPNBM = BY TRIGGER arrParam[17].tipe:= ptInteger; arrParam[17].data:= FLoginId; arrParam[18].tipe := ptCurrency; arrParam[18].data := StrToFloat(strgGrid.Cells[4,i]); arrParam[19].tipe := ptCurrency; arrParam[19].data := StrToFloat(strgGrid.Cells[3,i]) - StrToFloat(strgGrid.Cells[4,i]); arrParam[20].tipe := ptInteger; arrParam[20].data := DOId; Hasil:= DeliveryOrder.InputDOStokDetil(arrParam); if not Hasil then begin Result:= Hasil; ADConn.Rollback; Exit; end; // Update Barang Transaksi Set Cogs (HPP) And Last Cost and stok in order SetLength(arrParam, 6); arrParam[0].tipe := ptCurrency; arrParam[0].data := StrToFloat(strgGrid.Cells[28,i]); arrParam[1].tipe := ptCurrency; arrParam[1].data := StrToFloat(strgGrid.Cells[2,i]); arrParam[2].tipe := ptVariant; arrParam[2].data := StrToFloat(strgGrid.Cells[33,i]) - StrToFloat(strgGrid.Cells[3,i]); arrParam[3].tipe := ptInteger; arrParam[3].data := FLoginId; arrParam[4].tipe := ptString; arrParam[4].data := strgGrid.Cells[1,i]; arrParam[5].tipe := ptInteger; arrParam[5].data := DeliveryOrder.GetUnitId; Hasil := DeliveryOrder.UpdateBarangTransaksiSetCogsAndLastCostByBrgCode(arrParam); { Update Barang Transaksi Set Cogs (HPP) Untuk barang bonus} if StrToInt(strgGrid.Cells[24,i])>0 then begin SetLength(arrParam, 4); arrParam[0].tipe := ptCurrency; arrParam[0].data := StrToFloat(strgGrid.Cells[24,i]) * StrToFloat(strgGrid.Cells[32,i]); //QTY Bonus Sales arrParam[1].tipe := ptInteger; arrParam[1].data := FLoginId; arrParam[2].tipe := ptString; arrParam[2].data := strgGrid.Cells[25,i]; //Code Barang Bonus arrParam[3].tipe := ptInteger; arrParam[3].data := DeliveryOrder.GetUnitId; Hasil := DeliveryOrder.UpdateCOGSForBonus(arrParam); end; if(StrToInt(strgGrid.Cells[6,i])>0)then begin //Insert data to"DO_Bonus" SetLength(arrParam,6); arrParam[0].tipe := ptInteger; arrParam[0].data := DOId; arrParam[1].tipe := ptString; arrParam[1].data := strgGrid.Cells[25,i]; //Code Barang Bonus arrParam[2].tipe := ptCurrency; if strgGrid.Cells[23,i]='' then strgGrid.Cells[23,i]:='0'; arrParam[2].data := StrToFloat(strgGrid.Cells[23,i]); //QTY Bonus CS arrParam[3].tipe := ptCurrency; if strgGrid.Cells[24,i]='' then strgGrid.Cells[24,i]:='0'; arrParam[3].data := StrToFloat(strgGrid.Cells[24,i]); //QTY Bonus Sales arrParam[4].tipe := ptInteger; arrParam[4].data := FLoginId; arrParam[5].tipe := ptInteger; arrParam[5].data := FLoginId; Hasil:= DeliveryOrder.InsertBonusDO(arrParam); if not Hasil then begin Result:= Hasil; Exit; end; end; if not Hasil then begin Result := Hasil; Exit; end; end; end; Result:= Hasil; finally Screen.Cursor:= crDefault; end; end; function TfrmGoodsReceiving.SumColStringGrid(StrGrid:TAdvStringGrid;Col,RowStart,RowEnd:Integer):Real; var i: Integer; hasil: Real; begin hasil:= 0; for i:= RowStart to RowEnd do hasil:= hasil+StrToFloat(StrGrid.Cells[Col,i]); Result:= hasil; end; procedure TfrmGoodsReceiving.ClearForm; begin edtSONo.Clear; edtSuplierCode.Clear; edtSuplierName.Clear; edtDONo.Clear; edtNP.Clear; edtProductName.Clear; dtDatePO.Clear; dtDateSO.Clear; dtDateDO.Clear; edtjfBonus.Value:=0; edtjfTotalColie.Value:=0; edtjfTotalOrder.Value:=0; edtjfRecvBonus.Value:=0; edtjfDisc1.Value:=0; edtjfDisc2.Value:=0; jvcuredtSubTotal.Value:=0; jvcuredtPPN.Value:=0; jvcuredtPPNBM.Value:=0; jvcuredtDiscount.Value:=0; jvcuredtTotalBeli.Value:=0; jvcuredtNilaiDisc.Value:=0; jvcuredtTotalDisc.Value:=0; FHargaDisc:=0; jvcuredtSellPrice.Value; lblStatusPO.Caption:=''; SetHeaderGrid; //strgGrid.Enabled:= False; fraFooter5Button1.btnAdd.Enabled:= False; end; procedure TfrmGoodsReceiving.FormCreate(Sender: TObject); begin inherited; dtDatePO.Date := now; dtDateSO.Date := now; dtDateDO.Date := now; lblHeader.Caption := 'GOOD RECEIVING'; lbl24.Visible := true; ClearForm; end; procedure TfrmGoodsReceiving.FormDestroy(Sender: TObject); begin inherited; frmDeliveryOrder := nil; end; procedure TfrmGoodsReceiving.ShowDetailPO(ANoPO: string); var data: TResultDataSet; i: Integer; begin SetHeaderGrid; if not Assigned(DeliveryOrder) then DeliveryOrder:= TDeliveryOrder.Create; if lblStatusPO.Caption='Status PO : RECEIVED' then data:= DeliveryOrder.GetListDataDODetil(ANoPO) else data:= DeliveryOrder.GetListDataPODetil(ANoPO); strgGrid.RowCount:= data.RecordCount+1; i:=1; with data do if not IsEmpty then begin while not Eof do begin strgGrid.Cells[0,i]:= IntToStr(i); strgGrid.Alignments[0,i] := taCenter; strgGrid.Cells[1,i]:= fieldbyname('BRG_CODE').AsString; strgGrid.Cells[2,i]:= FloatToStr(fieldbyname('PRICE').AsFloat); strgGrid.Alignments[2,i] := taRightJustify; strgGrid.Cells[3,i]:= FloatToStr(fieldbyname('QTY_ORDER').AsFloat); strgGrid.Alignments[3,i] := taRightJustify; //Cell 6 buat hitung qty bonus strgGrid.Cells[6,i]:= FloatToStr(fieldbyname('QTY_CS').AsFloat+ fieldbyname('QTY_SALES').AsFloat); //QTY Bonus PO if lblStatusPO.Caption='Status PO : RECEIVED' then begin strgGrid.Cells[4,i]:= fieldbyname('DOD_QTY_ORDER_RECV').AsString; //QTY Receive DO strgGrid.AddCheckBox(7,i,True,True); strgGrid.SetCheckBoxState(7,i,True); end else begin strgGrid.Cells[4,i]:= '0'; //QTY Receive strgGrid.AddCheckBox(7,i,False,False); if strgGrid.Cells[6,i] = '0' then strgGrid.SetCheckBoxState(7,i,True) else strgGrid.SetCheckBoxState(7,i,False); end; strgGrid.Cells[5,i]:= fieldbyname('SAT_CODE_ORDER').AsString; strgGrid.Alignments[4,i] := taRightJustify; strgGrid.Alignments[5,i] := taCenter; strgGrid.Alignments[7,i]:= taCenter; strgGrid.Cells[8,i]:= fieldbyname('BRG_NAME').AsString; strgGrid.Cells[9,i]:= FloatToStr(fieldbyname('DISC1').AsFloat); strgGrid.Cells[10,i]:= FloatToStr(fieldbyname('DISC2').AsFloat); strgGrid.Cells[11,i]:= FloatToStr(fieldbyname('DISC3').AsFloat); if lblStatusPO.Caption='Status PO : RECEIVED' then begin strgGrid.Cells[12,i]:= FloatToStr(fieldbyname('TOTAL_DISC').AsFloat); strgGrid.Cells[13,i]:= FloatToStr(fieldbyname('PPN').AsFloat); strgGrid.Cells[14,i]:= FloatToStr(fieldbyname('PPNBM').AsFloat); strgGrid.Cells[15,i]:= FloatToStr(fieldbyname('SUB_TOTAL').AsFloat); strgGrid.Cells[16,i]:= FloatToStr(fieldbyname('PPN').AsFloat);//FloatToStr(StrToFloat(strgGrid.Cells[13,i])*StrToFloat(strgGrid.Cells[4,i])); //(POD_PPN * QTY Receive)} strgGrid.Cells[17,i]:= FloatToStr(fieldbyname('PPNBM').AsFloat);//FloatToStr(StrToFloat(strgGrid.Cells[14,i])*StrToFloat(strgGrid.Cells[4,i])); //(POD_PPNBM * QTY Receive) end else begin strgGrid.Cells[12,i]:= '0'; //FloatToStr(fieldbyname('TOTAL_DISC').AsFloat); strgGrid.Cells[13,i]:= '0'; //FloatToStr(fieldbyname('PPN').AsFloat); strgGrid.Cells[14,i]:= '0'; //FloatToStr(fieldbyname('PPNBM').AsFloat); strgGrid.Cells[15,i]:= '0'; //FloatToStr(fieldbyname('SUB_TOTAL').AsFloat); strgGrid.Cells[16,i]:= '0'; //FloatToStr(StrToFloat(strgGrid.Cells[13,i])*StrToFloat(strgGrid.Cells[4,i])); //(POD_PPN * QTY Receive)} strgGrid.Cells[17,i]:= '0'; //FloatToStr(StrToFloat(strgGrid.Cells[14,i])*StrToFloat(strgGrid.Cells[4,i])); //(POD_PPNBM * QTY Receive) end; FormulaDisconPerRow(i,StrToFloat(strgGrid.Cells[4,i])); strgGrid.Cells[19,i]:= IntToStr(fieldbyname('BRGSUP_ID').AsInteger); strgGrid.Cells[20,i]:= FloatToStr(fieldbyname('COMMON').AsFloat); strgGrid.Cells[21,i]:= FloatToStr(fieldbyname('ASSGROS').AsFloat); strgGrid.Cells[22,i]:= FloatToStr(fieldbyname('TRADER').AsFloat); strgGrid.Cells[23,i]:= FloatToStr(fieldbyname('QTY_CS').AsFloat); //QTY Bonus CS strgGrid.Cells[24,i]:= FloatToStr(fieldbyname('QTY_SALES').AsFloat); //QTY Bonus Sales strgGrid.Cells[25,i]:= fieldbyname('BNS_BRG_CODE').AsString; //Code Barang Bonus strgGrid.Cells[26,i]:= FloatToStr(fieldByname('HPP_OLD').AsFloat); // Nilai HPP Lama (Added By Luqman) strgGrid.Cells[27,i]:= FloatToStr(fieldbyname('BRGT_STOCK').AsFloat); // Stok Barang Lama (Added By Luqman) strgGrid.Cells[28,i]:= '0'; // HPP dihitung saat on validate qty receive strgGrid.Cells[29,i]:= FloatToStr(fieldByname('PPN_PERSEN').AsFloat); // PPN PERSEN strgGrid.Cells[30,i]:= FloatToStr(fieldbyname('PPNBM_PERSEN').AsFloat); // PPNBM PERSEN if lblStatusPO.Caption='Status PO : RECEIVED' then begin strgGrid.Cells[32,i] := '1'; strgGrid.Cells[33,i] := '0'; strgGrid.Cells[34,i] := ''; end else begin strgGrid.Cells[32,i] := FloatToStr(fieldbyname('KONVSAT_SCALE').AsFloat); strgGrid.Cells[33,i] := FloatToStr(fieldbyname('BRGT_STOCK_IN_ORDER').AsFloat); strgGrid.Cells[34,i] := fieldbyname('KONVSAT_SAT_CODE_FROM').AsString; end; Inc(i); Next; end; edtjfTotalColie.Value:= SumColStringGrid(strgGrid,4,1,strgGrid.RowCount-1); edtjfBonus.Value:= SumColStringGrid(strgGrid,6,1,strgGrid.RowCount-1); jvcuredtSubTotal.Value:= SumColStringGrid(strgGrid,15,1,strgGrid.RowCount-1); jvcuredtPPN.Value:= SumColStringGrid(strgGrid,16,1,strgGrid.RowCount-1); jvcuredtPPNBM.Value:= SumColStringGrid(strgGrid,17,1,strgGrid.RowCount-1); jvcuredtDiscount.Value:= SumColStringGrid(strgGrid,31,1,strgGrid.RowCount-1); edtjfTotalOrder.Value:= SumColStringGrid(strgGrid,3,1,strgGrid.RowCount-1); FHargaDisc:= SumColStringGrid(strgGrid,18,1,strgGrid.RowCount-1); end else begin strgGrid.RowCount:=2; strgGrid.ClearRows(1,1); edtjfTotalColie.Value:= 0; edtjfBonus.Value:= 0; jvcuredtSubTotal.Value:= 0; jvcuredtPPN.Value:= 0; jvcuredtPPNBM.Value:= 0; jvcuredtDiscount.Value:= 0; edtjfTotalOrder.Value:= 0; FHargaDisc:= 0; end; jvcuredtTotalBeli.Value:= FHargaDisc + jvcuredtPPN.Value + jvcuredtPPNBM.Value; //jvcuredtSubTotal.Value + if lblStatusPO.Caption='Status PO : RECEIVED' then edtjfRecvBonus.Value:= edtjfBonus.Value else edtjfRecvBonus.Value:= 0; strgGrid.FixedRows := 1; strgGrid.AutoSize := true; end; function TfrmGoodsReceiving.CheckIsPOExist(ANoPO: string): boolean; var data: TResultDataSet; begin if not Assigned(DeliveryOrder) then DeliveryOrder:= TDeliveryOrder.Create; data:= DeliveryOrder.GetListDataPOByNo(ANoPO); with data do if not IsEmpty then begin dtDatePO.Date:= fieldbyname('PO_DATE').AsDateTime; edtSONo.Text:= fieldbyname('SO_NO').AsString; dtDateSO.Date:= fieldbyname('SO_DATE').AsDateTime; edtSuplierCode.Text:= fieldbyname('SUPMG_CODE').AsString; edtSuplierName.Text:= fieldbyname('SUP_NAME').AsString; FStatusPO := UpperCase(fieldbyname('STAPO_NAME').AsString); lblStatusPO.Caption:= 'Status PO : ' + FStatusPO; FValidDate:= fieldbyname('PO_VALID_DATE').AsDateTime; FTOP:= fieldbyname('SUPMG_TOP').AsInteger; edtDONo.Text:= ANoPO; dtDateDO.Date:= Now; ShowDetailPO(ANoPO); result := true; end else result := false; end; procedure TfrmGoodsReceiving.strgGridCanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); begin if lblStatusPO.Font.Color=clBlack then begin if (ACol in [4,7])and(strgGrid.Cells[3,ARow]<>'')then CanEdit := True else CanEdit := False; end else CanEdit := False; end; procedure TfrmGoodsReceiving.strgGridCellValidate(Sender: TObject; ACol, ARow: Integer; var Value: String; var Valid: Boolean); begin if (ACol = 4) then begin if(strgGrid.Cells[3,ARow])='' then Exit; if Value='' then Value:='0'; if (StrToFloat(Value) > StrToFloat(strgGrid.Cells[3,ARow])) then Value:= '0'; if Value<>'0' then edtjfTotalColie.Value:= SumColStringGrid(strgGrid,ACol,1,strgGrid.RowCount-1); strgGrid.Cells[12,ARow]:= FloatToStr(StrToFloat(strgGrid.Cells[2,ARow])*StrToFloat(Value)); //TOTAL_DISC strgGrid.Cells[13,ARow]:= FloatToStr(StrToFloat(strgGrid.Cells[2,ARow])*StrToFloat(Value)); //PPN strgGrid.Cells[14,ARow]:= FloatToStr(StrToFloat(strgGrid.Cells[2,ARow])*StrToFloat(Value)); //PPNBM FormulaDisconPerRow(ARow,StrToIntSafe(Value)); strgGrid.Cells[15,ARow]:= FloatToStr(StrToFloat(strgGrid.Cells[2,ARow])*StrToFloat(Value)); //SUBTOTAL SETELAH DISC strgGrid.Cells[16,ARow]:= FloatToStr(StrToFloat(strgGrid.Cells[29,ARow])/100*StrToFloat(strgGrid.Cells[18,ARow])); //PPN persen * qty recv * price strgGrid.Cells[17,ARow]:= FloatToStr(StrToFloat(strgGrid.Cells[30,ARow])/100*StrToFloat(strgGrid.Cells[18,ARow])); //PPNBM persen * qty recv * price // Perhitungan HPP, Diskon belum diperhitungkan (Added By Luqman) if (StrToFloat(strgGrid.Cells[27,ARow]) + StrToFloat(Value)) <> 0 then begin strgGrid.Cells[28,ARow]:= FloatToStr((StrToFloat(strgGrid.Cells[26,ARow]) * StrToFloat(strgGrid.Cells[27,ARow]) + (StrToFloat(strgGrid.Cells[2, ARow]) / StrToInt(strgGrid.Cells[32,ARow])) * (StrToFloat(Value) * StrToInt(strgGrid.Cells[32,ARow]))) / (StrToFloat(strgGrid.Cells[27,ARow]) + StrToFloat(Value) * StrToInt(strgGrid.Cells[32, ARow]))); end else strgGrid.Cells[28,ARow]:= '0'; // End Of Perhitungan HPP FormulaDisconPerRow(ARow,StrToFloat(Value)); jvcuredtSubTotal.Value:= SumColStringGrid(strgGrid,15,1,strgGrid.RowCount-1); //harga setelah discount jvcuredtPPN.Value:= SumColStringGrid(strgGrid,16,1,strgGrid.RowCount-1); jvcuredtPPNBM.Value:= SumColStringGrid(strgGrid,17,1,strgGrid.RowCount-1); jvcuredtDiscount.Value:= SumColStringGrid(strgGrid,31,1,strgGrid.RowCount-1); FHargaDisc:= SumColStringGrid(strgGrid,18,1,strgGrid.RowCount-1); jvcuredtTotalBeli.Value:= FHargaDisc + jvcuredtPPN.Value + jvcuredtPPNBM.Value; //jvcuredtSubTotal.Value + if(StrToFloat(Value)>0)then strgGrid.Col:= 7; end; strgGrid.SetFocus; end; procedure TfrmGoodsReceiving.SetHeaderGrid; begin with strgGrid do begin Clear; ColCount := 8; //ColCount := 35; RowCount := 2; Cells[0,0] := 'NO.'; Cells[1,0] := 'CODE'; Cells[2,0] := 'PRICE (Rp.)'; Cells[3,0] := 'QTY ORDER'; Cells[4,0] := 'QTY RECEIVE'; Cells[5,0] := 'UOM'; Cells[6,0] := 'BONUS'; //QTY Bonus PO Cells[7,0] := 'BONUS RECEIVE'; //checkbox //added by putut utk debugging. Harus di hide nantinya Cells[8,0]:= '8.BRG_NAME'; Cells[9,0]:= '9DISC1'; Cells[10,0]:= '10DISC2'; Cells[11,0]:= '11DISC3'; Cells[12,0]:= '12TOTAL_DISC_PO'; Cells[13,0]:= '13PPN PO'; Cells[14,0]:= '14PPNBM PO'; Cells[15,0]:= '15SUB_TOTAL'; Cells[16,0]:= '16POD_PPN * QTY Receive'; Cells[17,0]:= '17POD_PPNBM * QTY Receive'; Cells[18,0]:= '18TotalDiscPerBrg'; Cells[19,0]:= '19BRGSUP_ID'; Cells[20,0]:= '20COMMON'; Cells[21,0]:= '21ASSGROS'; Cells[22,0]:= '22TRADER'; Cells[23,0]:= '23QTY_CS'; //QTY Bonus CS Cells[24,0]:= '24QTY_SALES'; //QTY Bonus Sales Cells[25,0]:= '25BNS_BRG_CODE'; //Code Barang Bonus Cells[26,0]:= '26HPP_OLD'; // N0la0 HPP Lama (Added By Luqman) Cells[27,0]:= '27BRGT_STOCK'; // Stok Barang Lama (Added By Luqman) Cells[28,0]:= '28HPP'; // HPP BARU (Added By Luqman) Cells[29,0]:= '29PPN PERSEN'; // N0la0 HPP Lama (Added By Luqman) Cells[30,0]:= '30PPNBM PERSEN'; // Stok Barang Lama (Added By Luqman) Cells[31,0]:= '31DISCOUNT TOTAL'; // Nilai discon total FixedRows := 1; AutoSize := true; end; end; procedure TfrmGoodsReceiving.SetClearValue; var i: integer; begin for i:=1 to strgGrid.RowCount-1 do begin strgGrid.Cells[4,i] := '0'; strgGrid.Colors[4,i] := clWindow; strgGrid.Cells[13,i]:= '0'; strgGrid.Cells[14,i]:= '0'; strgGrid.Cells[15,i]:= '0'; strgGrid.Cells[16,i]:= '0'; edtjfTotalColie.Value:= 0; jvcuredtSubTotal.Value:= 0; jvcuredtPPN.Value:= 0; jvcuredtPPNBM.Value:= 0; jvcuredtDiscount.Value:= 0; end; end; procedure TfrmGoodsReceiving.btn1Click(Sender: TObject); begin if not Assigned(frmDialogSearchPO) then Application.CreateForm(TfrmDialogSearchPO, frmDialogSearchPO); frmDialogSearchPO.frmSuiMasterDialog.Caption := 'Search PO...'; frmDialogSearchPO.Modul:= tmDeliveryOrder; frmDialogSearchPO.ShowModal; if (frmDialogSearchPO.IsProcessSuccessfull) then begin edtPONo.Text := frmDialogSearchPO.strgGrid.Cells[2,frmDialogSearchPO.strgGrid.Row]; edtPONo.SetFocus; end; frmDialogSearchPO.Free; end; procedure TfrmGoodsReceiving.btn2Click(Sender: TObject); var SeparatorDate: Char; i: Integer; colieRcv, bonus: Real; begin if CommonDlg.Confirm('Are you sure you wish to print NP?')= mrNo then Exit; SeparatorDate:= FormatSettings.DateSeparator; try FormatSettings.DateSeparator:= '/'; bonus:= 0; colieRcv:= 0; if strgGrid.RowCount > 1 then for i:= 1 to (strgGrid.RowCount-1) do begin bonus:= bonus + StrToFloat(strgGrid.Cells[6,i]); colieRcv:= colieRcv + StrToFloat(strgGrid.Cells[4,i]); end; if not Assigned(ParamList) then ParamList := TStringList.Create; ParamList.Add(edtNP.Text); //0 ParamList.Add(edtPONo.Text); //1 ParamList.Add(FloatToStr(colieRcv)); //2 ParamList.Add(FloatToStr(bonus)); //3 ParamList.Add(FLoginUsername); //4 ParamList.Add(MasterNewUnit.Nama); //5 with dmReport do begin Params := ParamList; pMainReport.LoadFromFile(ExtractFilePath(Application.ExeName) + '/template/frCetakNP.fr3'); pMainReport.PrepareReport(True); pMainReport.Print; //ShowReport(True); end; finally FormatSettings.DateSeparator:= SeparatorDate; if Assigned(ParamList) then FreeAndNil(ParamList); end; end; procedure TfrmGoodsReceiving.edtPONoChange(Sender: TObject); begin inherited; lbl24.Visible := True; btn2.Visible := False; btnCetakNP.Visible:= False; ClearForm; end; procedure TfrmGoodsReceiving.edtDONoKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key=#13 then begin strgGrid.Col:= 4; if strgGrid.Enabled then strgGrid.SetFocus; end else if(not(Key in['0'..'9',Chr(VK_BACK)]))then Key:=#0; end; procedure TfrmGoodsReceiving.strgGridGetEditorType(Sender: TObject; ACol, ARow: Integer; var AEditor: TEditorType); begin inherited; case ACol of // 4: AEditor:= edNumeric; 7: AEditor:= edCheckBox; end; end; procedure TfrmGoodsReceiving.edtPONoKeyPress(Sender: TObject; var Key: Char); var data: TResultDataSet; NewNPNumber: Integer; arrParam: TArr; begin inherited; if Key=#13 then begin edtPONo.Text := StrPadLeft(edtPONo.Text, 10, '0'); edtDONo.ReadOnly:= False; if not CheckIsPOExist(edtPONo.Text) then CommonDlg.ShowError(ER_PO_IS_NOT_EXIST) else begin if FStatusPO = 'EXPIRED' then lblStatusPO.Caption:= 'Status PO : ' + 'EXPIRED'; if lblStatusPO.Caption='Status PO : ORDERED' then lblStatusPO.Font.Color:= clBlack else if lblStatusPO.Caption='Status PO : EXPIRED' then lblStatusPO.Font.Color:= clRed else lblStatusPO.Font.Color:= clBlue; if lblStatusPO.Font.Color=clRed then begin fraFooter5Button1.btnAdd.Enabled:= True; end else if lblStatusPO.Font.Color=clBlack then begin strgGrid.Enabled:= True; fraFooter5Button1.btnAdd.Enabled:= True; if not Assigned(DeliveryOrder) then DeliveryOrder:= TDeliveryOrder.Create; // data:= DeliveryOrder.GetNNP; edtNP.Text:= StrPadLeft(data.Fields[0].AsVariant,10,'0'); SetLength(arrParam, 2); arrParam[0].tipe := ptDateTime; arrParam[0].data := dtDateDO.Date; arrParam[1].tipe := ptInteger; arrParam[1].data := MasterNewUnit.ID; NewNPNumber := DeliveryOrder.GetNewNPNumber(arrParam); edtNP.Text := 'M' + FormatDateTime('yymmdd', dtDateDO.Date) + StrPadLeft(IntToStr(NewNPNumber + 1),3,'0'); end else begin if lblStatusPO.Caption='Status PO : RECEIVED' then begin if not Assigned(DeliveryOrder) then DeliveryOrder:= TDeliveryOrder.Create; data:= DeliveryOrder.GetNPFromDO(edtPONo.Text); edtNP.Text:= StrPadLeft(data.Fieldbyname('DO_NP').AsVariant,10,'0'); edtDONo.Text:= data.Fieldbyname('DO_NO').AsString; edtDONo.ReadOnly:= True; lbl24.Visible:= False; end; end; edtDONo.SetFocus; end; end else if(not(Key in['0'..'9',Chr(VK_BACK)]))then Key:=#0; end; procedure TfrmGoodsReceiving.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if(Key = VK_F2) then btn1.Click; if(Key = VK_F5)and(ssctrl in Shift) then GetAndRunButton('btnRefresh'); if((Key = Ord('D'))and(ssctrl in Shift))and btn2.Visible then btn2Click(self); if((Key = Ord('P'))and(ssctrl in Shift))and btnCetakNP.Visible then btnCetakNP.Click; if((Key = Ord('S'))and(ssctrl in Shift))and fraFooter5Button1.btnAdd.Enabled then GetAndRunButton('btnAdd'); end; procedure TfrmGoodsReceiving.strgGridGetCellColor(Sender: TObject; ARow, ACol: Integer; AState: TGridDrawState; ABrush: TBrush; AFont: TFont); begin inherited; if(ACol = 4)and(ARow > 0)and (strgGrid.Cells[ACol,ARow]<>'')and (StrToFloat(strgGrid.Cells[ACol,ARow]) <> StrToFloat(strgGrid.Cells[3,ARow])) then AFont.Color:= clRed else AFont.Color:= clBlack; end; procedure TfrmGoodsReceiving.strgGridClick(Sender: TObject); begin inherited; if(strgGrid.Cells[0,strgGrid.Row]<>'')then begin edtProductName.Text:= strgGrid.Cells[8,strgGrid.Row]; edtjfDisc1.Value:= StrToFloat(strgGrid.Cells[9,strgGrid.Row]); edtjfDisc2.Value:= StrToFloat(strgGrid.Cells[10,strgGrid.Row]); jvcuredtNilaiDisc.Value:= StrToFloat(strgGrid.Cells[11,strgGrid.Row]); jvcuredtTotalDisc.Value:= StrToFloat(strgGrid.Cells[31,strgGrid.Row]); //jvcuredtTotalDisc.Value:= StrToFloat(strgGrid.Cells[12,strgGrid.Row]); //jvcuredtSellPrice.Value:= ????; (komponen di hidden) end; end; procedure TfrmGoodsReceiving.strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); begin inherited; strgGridClick(Self); end; procedure TfrmGoodsReceiving.strgGridCheckBoxClick(Sender: TObject; ACol, ARow: Integer; State: Boolean); begin inherited; if (ACol = 7) then begin if State then edtjfRecvBonus.Value:= edtjfRecvBonus.Value+ StrToInt(strgGrid.Cells[6,ARow]) else edtjfRecvBonus.Value:= edtjfRecvBonus.Value-StrToInt(strgGrid.Cells[6,ARow]); end; end; procedure TfrmGoodsReceiving.FormActivate(Sender: TObject); begin inherited; frmDeliveryOrder.Caption := 'GOOD RECEIVING'; // frmMain.CreateMenu((Sender as TForm)); end; procedure TfrmGoodsReceiving.actSaveExecute(Sender: TObject); begin inherited; if not CekChekBoxInGrid then begin CommonDlg.ShowError(ER_DO_BONUS); Exit; end; if SaveData then begin if lblStatusPO.Font.Color=clBlack then begin CommonDlg.ShowConfirmGlobal(SAVE_DO_SUCCESSFULLY); btnCetakNP.Click; // frmMain.actReprintNPExecute(Self); // frmReprintNP.edt1.Text:= edtPONo.Text; btn2.Visible := True; btnCetakNP.Visible := True; fraFooter5Button1.btnAdd.Enabled := False; end else CommonDlg.ShowConfirmGlobal(SAVE_DO_EXPIRED) end else CommonDlg.ShowConfirmGlobal(ER_SAVE_DO); SetHeaderGrid; lbl24.Visible := False; end; procedure TfrmGoodsReceiving.strgGridGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); begin inherited; if ARow=0 then HAlign:= taCenter; end; procedure TfrmGoodsReceiving.strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String); begin inherited; FloatFormat := '%.2n'; if ACol in [2, 11..17] then begin IsFloat := True; end else IsFloat := False; end; procedure TfrmGoodsReceiving.strgGridKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = #13 then if strgGrid.Col = 7 then begin strgGrid.Col := 4; if strgGrid.Row <> strgGrid.RowCount - 1 then strgGrid.Row := strgGrid.Row + 1; end; end; procedure TfrmGoodsReceiving.btn2Enter(Sender: TObject); begin inherited; (Sender as TcxButton).UIStyle := DeepBlue; end; procedure TfrmGoodsReceiving.btn2Exit(Sender: TObject); begin inherited; (Sender as TcxButton).UIStyle := BlueGlass; end; procedure TfrmGoodsReceiving.btn1Exit(Sender: TObject); begin inherited; (Sender as TcxButton).UIStyle := BlueGlass; end; procedure TfrmGoodsReceiving.btn1Enter(Sender: TObject); begin inherited; (Sender as TcxButton).UIStyle := DeepBlue; end; procedure TfrmGoodsReceiving.btnCetakNPEnter(Sender: TObject); begin inherited; (Sender as TcxButton).UIStyle := DeepBlue; end; procedure TfrmGoodsReceiving.btnCetakNPExit(Sender: TObject); begin inherited; (Sender as TcxButton).UIStyle := BlueGlass; end; end.
unit BsReportFilter; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, cxLabel, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxSpinEdit, uCommon_Messages, cxCheckBox, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxMemo, uCommon_Funcs, DateUtils; type TfrmReportFilter = class(TForm) MainPanel: TPanel; btnPanel: TPanel; btnOk: TcxButton; btnCancel: TcxButton; lblFrom: TcxLabel; lblTo: TcxLabel; procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); private DateBeg, DateEnd:TcxDateEdit; YearBox:TcxSpinEdit; MonthBox:TcxComboBox; public IdFunc:SmallInt; {0 - Период, 1 - на дату, 2 - Месяц, 3 - год} ResFilter:Variant; constructor Create(AOwner:TComponent; NameFunc, FormCaption:String);reintroduce; end; var frmReportFilter: TfrmReportFilter; implementation {$R *.dfm} constructor TfrmReportFilter.Create(AOwner:TComponent; NameFunc, FormCaption:String); begin try inherited Create(AOwner); if NameFunc='PERIOD' then begin IdFunc:=0; Self.Caption:=FormCaption; lblFrom.Caption:='З'; lblFrom.Width:=15; DateBeg:=TcxDateEdit.Create(Self); DateBeg.Name:='DateBeg'; DateBeg.Parent:=Self; DateBeg.Top:=lblFrom.Top; DateBeg.Left:=lblFrom.Left+lblFrom.Width+5; DateBeg.Width:=90; DateBeg.Date:=Date; lblTo.Left:=DateBeg.Left+DateBeg.Width+8; lblTo.Caption:='По'; lblTo.Width:=23; DateEnd:=TcxDateEdit.Create(Self); DateEnd.Name:='DateEnd'; DateEnd.Parent:=Self; DateEnd.Top:=lblFrom.Top; DateEnd.Left:=lblTo.Left+lblTo.Width+5; DateEnd.Width:=90; DateEnd.Date:=Date; end else if NameFunc='DATE' then begin IdFunc:=1; Self.Caption:=FormCaption; lblFrom.Caption:='На дату'; lblFrom.Width:=60; DateBeg:=TcxDateEdit.Create(Self); DateBeg.Name:='DateBeg'; DateBeg.Parent:=Self; DateBeg.Top:=lblFrom.Top; DateBeg.Left:=lblFrom.Left+lblFrom.Width+5; DateBeg.Width:=90; lblTo.Visible:=False; DateBeg.Date:=Date; end else if NameFunc='MONTH' then begin IdFunc:=2; Self.Caption:=FormCaption; MonthBox:=TcxComboBox.Create(Self); MonthBox.Name:='MonthBox'; MonthBox.Parent:=Self; lblFrom.Caption:='Місяць'; lblFrom.Width:=50; MonthBox.Top:=lblFrom.Top; MonthBox.Left:=lblFrom.Left+lblFrom.Width+5; MonthBox.Width:=150; lblTo.Visible:=False; MonthBox.Properties.Items.Add('Січень'); MonthBox.Properties.Items.Add('Лютий'); MonthBox.Properties.Items.Add('Березень'); MonthBox.Properties.Items.Add('Квітень'); MonthBox.Properties.Items.Add('Травень'); MonthBox.Properties.Items.Add('Червень'); MonthBox.Properties.Items.Add('Липень'); MonthBox.Properties.Items.Add('Серпень'); MonthBox.Properties.Items.Add('Вересень'); MonthBox.Properties.Items.Add('Жовтень'); MonthBox.Properties.Items.Add('Листопад'); MonthBox.Properties.Items.Add('Грудень'); MonthBox.ItemIndex:=MonthOf(Date)-1; end else if NameFunc='YEAR' then begin IdFunc:=3; Self.Caption:=FormCaption; YearBox:=TcxSpinEdit.Create(Self); YearBox.Name:='YearBox'; YearBox.Parent:=Self; lblFrom.Caption:='Рік'; lblFrom.Width:=30; YearBox.Top:=lblFrom.Top; YearBox.Left:=lblFrom.Left+lblFrom.Width+5; YearBox.Width:=100; lblTo.Visible:=False; YearBox.Value:=YearOf(Date); end; except On E:Exception do begin bsShowMessage('Увага!', E.Message, mtInformation, [mbOK]); end; end; end; procedure TfrmReportFilter.btnOkClick(Sender: TObject); begin case IdFunc of 0: begin ResFilter:=VarArrayCreate([0, 1], varVariant); ResFilter[0]:=GetValueByNameComponent(Self, 'DateBeg'); ResFilter[1]:=GetValueByNameComponent(Self, 'DateEnd'); end; 1: begin ResFilter:=GetValueByNameComponent(Self, 'DateBeg'); end; 2: begin ResFilter:=GetValueByNameComponent(Self, 'MonthBox')+1; end; 3: begin ResFilter:=GetValueByNameComponent(Self, 'YearBox'); end; end; ModalResult:=mrOk; end; procedure TfrmReportFilter.btnCancelClick(Sender: TObject); begin ModalResult:=mrCancel; end; initialization RegisterClass(TfrmReportFilter); end.
namespace wireframeviewerapplet; // Sample applet project by Brian Long (http://blong.com) // Translated from Michael McGuffin's WireframeViewer applet // from http://profs.etsmtl.ca/mmcguffin/learn/java/11-3d interface uses java.applet.*, java.awt.*, java.awt.event.*; type Point3D = class public var x, y, z: Integer; constructor(xCoord, yCoord, zCoord: Integer); end; Edge = class public var a, b: Integer; constructor(vertexA, vertexB: Integer); end; WireFrameViewerApplet = public class(Applet, MouseListener, MouseMotionListener) private var width, height: Integer; var mx, my: Integer; // the most recently recorded mouse coordinates var backbuffer: Image; var backg: Graphics; var azimuth: Integer := 35; var elevation: Integer := 30; var vertices: array of Point3D; var edges: array of Edge; public method init(); override; method paint(g: Graphics); override; method update(g: Graphics); override; method mouseEntered(e: MouseEvent); method mouseExited(e: MouseEvent); method mouseClicked(e: MouseEvent); method mousePressed(e: MouseEvent); method mouseReleased(e: MouseEvent); method mouseMoved(e: MouseEvent); method mouseDragged(e: MouseEvent); method drawWireFrame(g: Graphics); end; implementation constructor Point3D(xCoord, yCoord, zCoord: Integer); begin x := xCoord; y := yCoord; z := zCoord; end; constructor Edge(vertexA, vertexB: Integer); begin a := vertexA; b := vertexB; end; method WireFrameViewerApplet.init(); begin width := Size.width; height := Size.height; vertices := new Point3D[8]; vertices[0] := new Point3D(-1, -1, -1); vertices[1] := new Point3D(-1, -1, 1); vertices[2] := new Point3D(-1, 1, -1); vertices[3] := new Point3D(-1, 1, 1); vertices[4] := new Point3D(1, -1, -1); vertices[5] := new Point3D(1, -1, 1); vertices[6] := new Point3D(1, 1, -1); vertices[7] := new Point3D(1, 1, 1); edges := new Edge[12]; edges[0] := new Edge(0, 1); edges[1] := new Edge(0, 2); edges[2] := new Edge(0, 4); edges[3] := new Edge(1, 3); edges[4] := new Edge(1, 5); edges[5] := new Edge(2, 3); edges[6] := new Edge(2, 6); edges[7] := new Edge(3, 7); edges[8] := new Edge(4, 5); edges[9] := new Edge(4, 6); edges[10] := new Edge(5, 7); edges[11] := new Edge(6, 7); backbuffer := createImage(width, height); backg := backbuffer.Graphics; drawWireFrame(backg); addMouseListener(self); addMouseMotionListener(self) end; method WireFrameViewerApplet.mouseEntered(e: MouseEvent); begin end; method WireFrameViewerApplet.mouseExited(e: MouseEvent); begin end; method WireFrameViewerApplet.mouseClicked(e: MouseEvent); begin end; method WireFrameViewerApplet.mousePressed(e: MouseEvent); begin mx := e.X; my := e.Y; end; method WireFrameViewerApplet.mouseReleased(e: MouseEvent); begin end; method WireFrameViewerApplet.mouseMoved(e: MouseEvent); begin end; method WireFrameViewerApplet.mouseDragged(e: MouseEvent); begin // get the latest mouse position var new_mx := e.X; var new_my := e.Y; // adjust angles according to the distance travelled by the mouse // since the last event azimuth := azimuth - (new_mx - mx); elevation := elevation + (new_my - my); // update the backbuffer drawWireFrame( backg ); // update our data mx := new_mx; my := new_my; repaint; e.consume; end; method WireFrameViewerApplet.paint(g: Graphics); begin update(g) end; method WireFrameViewerApplet.update(g: Graphics); begin g.drawImage( backbuffer, 0, 0, Self ); showStatus("Elev: " + elevation + " deg, Azim: " + azimuth + " deg"); end; method WireFrameViewerApplet.drawWireFrame(g: Graphics); const near: Single = 3; // distance from eye to near plane const nearToObj: Single = 1.5; // distance from near plane to center of object begin // compute coefficients for the projection var theta: Double := Math.PI * azimuth / 180.0; var phi: Double := Math.PI * elevation / 180.0; var cosT := Single(Math.cos( theta )); var sinT := Single(Math.sin( theta )); var cosP := Single(Math.cos( phi )); var sinP := Single(Math.sin( phi )); var cosTcosP := cosT*cosP; var cosTsinP := cosT*sinP; var sinTcosP := sinT*cosP; var sinTsinP := sinT*sinP; // project vertices onto the 2D viewport var points := new Point[ vertices.length ]; var scaleFactor := width/4; for j: Integer := 0 to vertices.length - 1 do begin var x0 := vertices[j].x; var y0 := vertices[j].y; var z0 := vertices[j].z; // compute an orthographic projection var x1 := cosT*x0 + sinT*z0; var y1 := -sinTsinP*x0 + cosP*y0 + cosTsinP*z0; // now adjust things to get a perspective projection var z1 := cosTcosP*z0 - sinTcosP*x0 - sinP*y0; x1 := x1*near / (z1+near+nearToObj); y1 := y1*near / (z1+near+nearToObj); // the 0.5 is to round off when converting to int points[j] := new Point( Integer(width / 2 + scaleFactor*x1 + 0.5), Integer(height / 2 - scaleFactor*y1 + 0.5) ); end; // draw the wireframe g.Color := Color.BLACK; g.fillRect( 0, 0, width, height ); g.Color := Color.WHITE; for j: Integer := 0 to edges.length - 1 do g.drawLine( points[ edges[j].a ].x, points[ edges[j].a ].y, points[ edges[j].b ].x, points[ edges[j].b ].y ); end; end.
namespace proholz.xsdparser; interface type XsdExtensionVisitor = public class(AttributesVisitor) private // * // * The {@link XsdExtension} instance which owns this {@link XsdExtensionVisitor} instance. This way this visitor // * instance can perform changes in the {@link XsdExtension} object. // // var owner: XsdExtension; public constructor(aowner: XsdExtension); method visit(element: XsdMultipleElements); override; method visit(element: XsdGroup); override; end; implementation constructor XsdExtensionVisitor(aowner: XsdExtension); begin inherited constructor(aowner); self.owner := aowner; end; method XsdExtensionVisitor.visit(element: XsdMultipleElements); begin inherited visit(element); owner.setChildElement(ReferenceBase.createFromXsd(element)); end; method XsdExtensionVisitor.visit(element: XsdGroup); begin inherited visit(element); owner.setChildElement(ReferenceBase.createFromXsd(element)); end; end.
unit NFSEditProp; interface uses Classes, SysUtils, Contnrs, Controls, StdCtrls, ExtCtrls, Graphics, Vcl.Mask; type TnfsEditProp = class(TPersistent) private fOnChanged: TNotifyEvent; fAlignment: TAlignment; fEdit: TMaskEdit; fFont: TFont; fEnabled: Boolean; procedure setAlignment(const Value: TAlignment); procedure setFont(const Value: TFont); procedure setText(const Value: string); procedure FontChanged(Sender: TObject); procedure setEnabled(const Value: Boolean); function getText: string; function getReadOnly: Boolean; procedure setReadOnly(const Value: Boolean); function getColor: TColor; procedure setColor(const Value: TColor); protected public constructor Create; destructor Destroy; override; property Edit: TMaskEdit read fEdit write fEdit; published property Alignment: TAlignment read fAlignment write setAlignment; property Font: TFont read fFont write setFont; property Text: string read getText write setText; property OnChanged: TNotifyEvent read fOnChanged write fOnChanged; property Enabled: Boolean read fEnabled write setEnabled default true; property ReadOnly: Boolean read getReadOnly write setReadOnly default true; property Color: TColor read getColor write setColor default clWindow; end; implementation { TnfsEditProp } constructor TnfsEditProp.Create; begin fFont := TFont.Create; fFont.OnChange := FontChanged; fEnabled := true; end; destructor TnfsEditProp.Destroy; begin FreeAndNil(fFont); inherited; end; procedure TnfsEditProp.FontChanged(Sender: TObject); begin if Assigned(fOnChanged) then fOnChanged(self); end; function TnfsEditProp.getColor: TColor; begin Result := fEdit.Color; end; function TnfsEditProp.getReadOnly: Boolean; begin Result := fEdit.ReadOnly; end; function TnfsEditProp.getText: string; begin Result := fEdit.Text; end; procedure TnfsEditProp.setAlignment(const Value: TAlignment); begin fAlignment := Value; fEdit.Alignment := Value; end; procedure TnfsEditProp.setColor(const Value: TColor); begin fEdit.Color := Value; if Assigned(fOnChanged) then fOnChanged(Self); end; procedure TnfsEditProp.setEnabled(const Value: Boolean); begin fEnabled := Value; fEdit.Enabled := Value; fEdit.Invalidate; end; procedure TnfsEditProp.setFont(const Value: TFont); begin fFont.Assign(Value); fEdit.Font.Assign(fFont); fEdit.Font.Color := fFont.Color; end; procedure TnfsEditProp.setReadOnly(const Value: Boolean); begin fEdit.ReadOnly := Value; end; procedure TnfsEditProp.setText(const Value: string); begin fEdit.Text := Value; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019-2021 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Utils.Files; interface type TFileUtils = class public //TODO : Improve this!! class function AreSameFiles(const fileA, fileB : string ) : boolean; end; implementation uses WinApi.Windows, System.IOUtils, System.SysUtils; { TFileUtils } class function TFileUtils.AreSameFiles(const fileA, fileB: string): boolean; var fatA: TWin32FileAttributeData; fatB: TWin32FileAttributeData; verInfoSizeA : DWORD; verInfoSizeB : DWORD; dummy : DWORD; bufferA : array of byte; bufferB : array of byte; PVerInfoA: Pointer; PVerInfoB: Pointer; PVerValueA: PVSFixedFileInfo; PVerValueB: PVSFixedFileInfo; begin result := false; if not GetFileAttributesEx(PChar(fileA), GetFileExInfoStandard, @fatA) then RaiseLastOSError; if not GetFileAttributesEx(PChar(fileB), GetFileExInfoStandard, @fatB) then RaiseLastOSError; //check the file size first, if not equal then we are done. if fatA.nFileSizeHigh <> fatB.nFileSizeHigh then exit; if fatA.nFileSizeLow <> fatB.nFileSizeLow then exit; //size is equal, but we are not sure, so test the version info verInfoSizeA := GetFileVersionInfoSize(PChar(fileA), Dummy); verInfoSizeB := GetFileVersionInfoSize(PChar(fileB), Dummy); //if the size of the version info is different then the files are not the same. if verInfoSizeA <> verInfoSizeB then exit; //we have version info. if (verInfoSizeA <> 0) then begin Setlength(bufferA,verInfoSizeA ); PVerInfoA := @bufferA[0]; if not GetFileVersionInfo(PChar(fileA), 0, verInfoSizeA, PVerInfoA) then exit; Setlength(bufferB,verInfoSizeB ); PVerInfoB := @bufferB[0]; if not GetFileVersionInfo(PChar(fileB), 0, verInfoSizeB, PVerInfoB) then exit; if not VerQueryValue(PVerInfoA, '\', Pointer(PVerValueA), dummy) then exit; if not VerQueryValue(PVerInfoB, '\', Pointer(PVerValueB), dummy) then exit; //major if HiWord(PVerValueA.dwFileVersionMS) <> HiWord(PVerValueA.dwFileVersionMS) then exit; //minor if LoWord(PVerValueA.dwFileVersionMS) <> LoWord(PVerValueA.dwFileVersionMS) then exit; //release if HiWord(PVerValueA.dwFileVersionLS) <> HiWord(PVerValueA.dwFileVersionLS) then exit; //build if LoWord(PVerValueA.dwFileVersionLS) <> LoWord(PVerValueA.dwFileVersionLS) then exit; exit(true); end; //if we get here, the file sizes match but there is no version info, so we cannot be sure. //ideally we would hash the files and compare hashes, but that might be slow (compared to copying files again). //so for now, we assume they are not equal. result := false; end; end.
unit uAnimationHelper; interface uses System.Math, Winapi.Windows, Vcl.Graphics, Vcl.ExtCtrls, Dmitry.Utils.System, GIFImage, uConstants, uAnimatedJPEG; type TDrawProcedure = reference to procedure; type TAnimationHelper = class helper for TGraphic public function ValidFrameCount: Integer; function IsTransparentAnimation: Boolean; function GetFirstFrameNumber: Integer; function GetNextFrameNumber(CurrentFrameNumber: Integer): Integer; function GetPreviousFrameNumber(CurrentFrameNumber: Integer): Integer; procedure ProcessNextFrame(AnimatedBuffer: TBitmap; var CurrentFrameNumber: Integer; BackgrondColor: TColor; Timer: TTimer; DrawCallBack: TDrawProcedure); end; implementation function TAnimationHelper.GetFirstFrameNumber: Integer; var I: Integer; begin Result := 0; if ValidFrameCount = 0 then Result := 0 else begin if (Self is TGIFImage) then begin for I := 0 to (Self as TGIFImage).Images.Count - 1 do if not(Self as TGIFImage).Images[I].Empty then begin Result := I; Break; end; end else if (Self is TAnimatedJPEG) then begin Result := 0; end; end; end; function TAnimationHelper.GetNextFrameNumber(CurrentFrameNumber: Integer): Integer; var Im: TGIFImage; begin if CurrentFrameNumber = -1 then Exit(GetFirstFrameNumber); Result := 0; if ValidFrameCount = 0 then Result := 0 else begin if (Self is TGIFImage) then begin Im := (Self as TGIFImage); Result := CurrentFrameNumber; Inc(Result); if Result >= Im.Images.Count then Result := 0; if Im.Images[Result].Empty then Result := GetNextFrameNumber(Result); end else if (Self is TAnimatedJPEG) then begin //onle 2 slides Result := IIF(CurrentFrameNumber = 1, 0, 1); end; end; end; function TAnimationHelper.GetPreviousFrameNumber(CurrentFrameNumber: Integer): Integer; var Im: TGIFImage; begin Result := 0; if ValidFrameCount = 0 then Result := 0 else begin if (Self is TGIFImage) then begin Im := (Self as TGIFImage); Result := CurrentFrameNumber; Dec(Result); if Result < 0 then Result := Im.Images.Count - 1; if Im.Images[Result].Empty then Result := GetPreviousFrameNumber(Result); end else if (Self is TAnimatedJPEG) then begin //onle 2 slides Result := IIF(CurrentFrameNumber = 1, 0, 1); end; end; end; function TAnimationHelper.IsTransparentAnimation: Boolean; var I: Integer; Gif: TGifImage; begin Result := False; if Self is TGIFImage then begin Gif := (Self as TGIFImage); for I := 0 to Gif.Images.Count - 1 do if Gif.Images[I].Transparent then Exit(True); end; end; function TAnimationHelper.ValidFrameCount: Integer; var I: Integer; Gif: TGifImage; begin Result := 0; if Self is TGIFImage then begin Gif := (Self as TGIFImage); for I := 0 to Gif.Images.Count - 1 do begin if not Gif.Images[I].Empty then Inc(Result); end; end else if Self is TAnimatedJPEG then Result := TAnimatedJPEG(Self).Count; end; procedure TAnimationHelper.ProcessNextFrame(AnimatedBuffer: TBitmap; var CurrentFrameNumber: Integer; BackgrondColor: TColor; Timer: TTimer; DrawCallBack: TDrawProcedure); var C, PreviousNumber: Integer; R, Bounds_: TRect; Im: TGifImage; DisposalMethod: TDisposalMethod; Del, Delta: Integer; TimerEnabled: Boolean; Gsi: TGIFSubImage; TickCountStart: Cardinal; begin Timer.Enabled := False; TickCountStart := GetTickCount; Del := 100; TimerEnabled := False; CurrentFrameNumber := Self.GetNextFrameNumber(CurrentFrameNumber); if Self is TGIFImage then begin Im := Self as TGIFImage; R := Im.Images[CurrentFrameNumber].BoundsRect; TimerEnabled := False; PreviousNumber := Self.GetPreviousFrameNumber(CurrentFrameNumber); if (Im.Animate) and (Im.Images.Count > 1) then begin Gsi := Im.Images[CurrentFrameNumber]; if Gsi.Empty then Exit; if Im.Images[PreviousNumber].Empty then DisposalMethod := DmNone else begin if Im.Images[PreviousNumber].GraphicControlExtension <> nil then DisposalMethod := Im.Images[PreviousNumber].GraphicControlExtension.Disposal else DisposalMethod := DmNone; end; if Im.Images[CurrentFrameNumber].GraphicControlExtension <> nil then Del := Im.Images[CurrentFrameNumber].GraphicControlExtension.Delay * 10; if Del = 10 then Del := 100; if Del = 0 then Del := 100; TimerEnabled := True; end else DisposalMethod := DmNone; if (DisposalMethod = DmBackground) then begin Bounds_ := Im.Images[PreviousNumber].BoundsRect; AnimatedBuffer.Canvas.Pen.Color := BackgrondColor; AnimatedBuffer.Canvas.Brush.Color := BackgrondColor; AnimatedBuffer.Canvas.Rectangle(Bounds_); end; if DisposalMethod = DmPrevious then begin C := CurrentFrameNumber; Dec(C); if C < 0 then C := Im.Images.Count - 1; Im.Images[C].StretchDraw(AnimatedBuffer.Canvas, R, Im.Images[CurrentFrameNumber].Transparent, False); end; Im.Images[CurrentFrameNumber].StretchDraw(AnimatedBuffer.Canvas, R, Im.Images[CurrentFrameNumber].Transparent, False); end else if Self is TAnimatedJPEG then begin TimerEnabled := TAnimatedJPEG(Self).Count > 1; if not TimerEnabled then CurrentFrameNumber := 0; AnimatedBuffer.Assign(TAnimatedJPEG(Self).Images[CurrentFrameNumber]); Del := Animation3DDelay; end; DrawCallBack; Delta := Integer(GetTickCount - TickCountStart); Timer.Interval := Max(Del div 2, Del - Delta); Timer.Enabled := TimerEnabled; end; end.
// Generated from XML data unit NtOrdinalData; interface implementation uses SysUtils, NtOrdinal, NtPattern; // Many European languages use just period to indicate an ordinal number function GetPeriodShort(ordinal: TOrdinal; plural: TPlural; gender: TGender): String; begin Result := IntToStr(ordinal) + '.'; end; // English function GetEnglishShort(ordinal: TOrdinal; plural: TPlural; gender: TGender): String; var str: String; begin if (ordinal mod 10 = 1) and (ordinal mod 100 <> 11) then str := 'st' else if (ordinal mod 10 = 2) and (ordinal mod 100 <> 12) then str := 'nd' else if (ordinal mod 10 = 3) and (ordinal mod 100 <> 13) then str := 'rd' else str := 'th'; Result := IntToStr(ordinal) + str; end; function GetEnglishLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const VALUES: TOrdinalArray = ( 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth' ); begin Result := VALUES[ordinal]; end; // German function GetGermanLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const VALUES: TOrdinalArray = ( 'erstens', 'zweitens', 'drittens', 'viertens', 'fünftens', 'sechstens', 'siebtens', 'achtens', 'neuntens', 'zehntens' ); begin if ordinal = 1 then begin if plural = pfOther then Result := 'ersten' else if gender = geNeutral then Result := 'erstes' else if gender = geFemale then Result := 'erste' else if gender = geMale then Result := 'erster' else Result := VALUES[ordinal]; end else if ordinal = 2 then begin if plural = pfOther then Result := 'zweiten' else if gender = geNeutral then Result := 'zweites' else if gender = geFemale then Result := 'zweite' else if gender = geMale then Result := 'zweiter' else Result := VALUES[ordinal]; end else if ordinal = 3 then begin if plural = pfOther then Result := 'dritten' else if gender = geNeutral then Result := 'drittes' else if gender = geFemale then Result := 'dritte' else if gender = geMale then Result := 'dritter' else Result := VALUES[ordinal]; end else Result := VALUES[ordinal]; end; // Dutch function GetDutchShort(ordinal: TOrdinal; plural: TPlural; gender: TGender): String; begin Result := IntToStr(ordinal) + 'e'; end; function GetDutchLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const VALUES: TOrdinalArray = ( 'eerste', 'tweede', 'derde', 'vierde', 'vijfde', 'zesde', 'zevende', 'achtste', 'negende', 'tiende' ); begin Result := VALUES[ordinal]; end; // French function GetFrenchShort(ordinal: TOrdinal; plural: TPlural; gender: TGender): String; var str: String; begin if ordinal = 1 then begin if gender = geMale then str := 'er' else str := 're' end else str := 'e'; Result := IntToStr(ordinal) + str; end; function GetFrenchLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const VALUES: TOrdinalArray = ( 'premier', 'deuxième', 'troisième', 'quatrième', 'cinquième', 'sixième', 'septième', 'huitième', 'neuvième', 'dixième' ); begin if ordinal = 1 then begin if gender = geMale then Result := 'premier' else Result := 'première' end else Result := VALUES[ordinal]; end; // Finnish function GetFinnishLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const SINGULARS: TOrdinalArray = ( 'ensimmäinen', 'toinen', 'kolmas', 'neljäs', 'viides', 'kuudes', 'seitsemäs', 'kahdeksas', 'yhdeksäs', 'kymmenes' ); PLURALS: TOrdinalArray = ( 'ensimmäiset', 'toiset', 'kolmannet', 'neljännet', 'viidennet', 'kuudennet', 'seitsemännet', 'kahdeksannet', 'yhdeksännet', 'kymmenennet' ); begin if plural = pfOne then Result := SINGULARS[ordinal] else Result := PLURALS[ordinal] end; // Estonian, TODO: plural forms function GetEstonianLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const SINGULARS: TOrdinalArray = ( 'esimene', 'teine', 'kolmas', 'neljas', 'viies', 'kuues', 'seitsmes', 'kaheksas', 'üheksas', 'kümnes' ); begin Result := SINGULARS[ordinal]; end; // Danish function GetDanishLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const VALUES: TOrdinalArray = ( 'første', 'anden', 'tredje', 'fjerde', 'femte', 'sjette', 'syvende', 'ottende', 'niende', 'tiende' ); begin Result := VALUES[ordinal]; end; // Swedish function GetSwedishLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const VALUES: TOrdinalArray = ( 'första', 'andra', 'tredje', 'fjärde', 'femte', 'sjätte', 'sjunde', 'åttonde', 'nionde', 'tionde' ); begin Result := VALUES[ordinal]; end; // Norwegian, Bokmål function GetNorwegianBokmalLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const VALUES: TOrdinalArray = ( 'første', 'annen', 'tredje', 'fjerde', 'femte', 'sjette', 'sjuende', 'åttende', 'niende', 'tiende' ); begin Result := VALUES[ordinal]; end; // Norwegian, Nynorsk function GetNorwegianNynorskLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const VALUES: TOrdinalArray = ( 'første', 'andre', 'tredje', 'fjerde', 'femte', 'sjette', 'sjuande', 'åttande', 'niande', 'tiande' ); begin Result := VALUES[ordinal]; end; // Icelandic function GetIcelandicLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const ICELANDIC: TOrdinalArray = ( 'fyrsti', 'annar', 'þriðji', 'fjórði', 'fimmti', 'sjötti', 'sjöundi', 'áttundi', 'níundi', 'tíundi' ); begin Result := ICELANDIC[ordinal]; end; // Japanese function GetJapaneseLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const JAPANESE: TOrdinalArray = ( '一つ目', '二つ目', '三つ目', '四つ目', '五つ目', '六つ目', '七つ目', '八つ目', '九つ目', '十' ); begin Result := JAPANESE[ordinal]; end; function GetJapaneseShort(ordinal: TOrdinal; plural: TPlural; gender: TGender): String; begin if TNtOrdinal.IsShortOrdinal(ordinal) then Result := GetJapaneseLong(TSmallOrdinal(ordinal), plural, gender) else Result := IntToStr(ordinal) + '目'; end; // Korean function GetKoreanLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const KOREAN: TOrdinalArray = ( '첫째', '둘째', '셋째', '넷째', '다섯째', '여섯째', '일곱째', '여덟째', '아홉째', '열째' ); begin Result := KOREAN[ordinal]; end; function GetKoreanShort(ordinal: TOrdinal; plural: TPlural; gender: TGender): String; begin if TNtOrdinal.IsShortOrdinal(ordinal) then Result := GetKoreanLong(TSmallOrdinal(ordinal), plural, gender) else Result := IntToStr(ordinal) + '째'; end; // Simplified Chinese function GetSimplifiedChineseLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; const CHINESE: TOrdinalArray = ( '第一', '第二', '第三', '第四', '第五', '第六', '第七', '第八', '第九', '第十' ); begin Result := CHINESE[ordinal]; end; function GetSimplifiedChineseShort(ordinal: TOrdinal; plural: TPlural; gender: TGender): String; begin if TNtOrdinal.IsShortOrdinal(ordinal) then Result := GetSimplifiedChineseLong(TSmallOrdinal(ordinal), plural, gender) else Result := '第' + IntToStr(ordinal); end; initialization TNtOrdinal.Register('en', @GetEnglishLong, @GetEnglishShort); TNtOrdinal.Register('de', @GetGermanLong, @GetPeriodShort); TNtOrdinal.Register('nl', @GetDutchLong, @GetDutchShort); TNtOrdinal.Register('fr', @GetFrenchLong, @GetFrenchShort); TNtOrdinal.Register('fi', @GetFinnishLong, @GetPeriodShort); TNtOrdinal.Register('et', @GetEstonianLong, @GetPeriodShort); TNtOrdinal.Register('sv', @GetSwedishLong, @GetPeriodShort); TNtOrdinal.Register('da', @GetDanishLong, @GetPeriodShort); TNtOrdinal.Register('no', @GetNorwegianBokmalLong, @GetPeriodShort); TNtOrdinal.Register('nb', @GetNorwegianBokmalLong, @GetPeriodShort); TNtOrdinal.Register('nn', @GetNorwegianNynorskLong, @GetPeriodShort); TNtOrdinal.Register('is', @GetIcelandicLong, @GetPeriodShort); TNtOrdinal.Register('ja', @GetJapaneseLong, @GetJapaneseShort); TNtOrdinal.Register('ko', @GetKoreanLong, @GetKoreanShort); TNtOrdinal.Register('zh', @GetSimplifiedChineseLong, @GetSimplifiedChineseShort); TNtOrdinal.Register('zh-Hans', @GetSimplifiedChineseLong, @GetSimplifiedChineseShort); end.
{*******************************************************} { } { 基于HCView的电子病历程序 作者:荆通 } { } { 此代码仅做学习交流使用,不可用于商业目的,由此引发的 } { 后果请使用者承担,加入QQ群 649023932 来获取更多的技术 } { 交流。 } { } {*******************************************************} { } { 插件功能ID定义部分 } { 注意:Function的ID第1位必须是1 } { } {*******************************************************} unit FunctionConst; interface const /// <summary> 业务插件主窗体显示 </summary> FUN_BLLFORMSHOW = '{1E5DBC75-B7CE-49D4-9897-9B8D65E51764}'; FUN_BLLFORMSHOW_NAME = '显示业务窗体'; /// <summary> 业务插件主窗体关闭 </summary> FUN_BLLFORMDESTROY = '{1DC8CC53-E029-4437-87DD-8240BF6EBA6E}'; FUN_BLLFORMDESTROY_NAME = '关闭业务窗体'; /// <summary> 主窗体显示 </summary> FUN_MAINFORMSHOW = '{1D9750FD-DD19-411B-B078-52A2C9B8A37C}'; /// <summary> 主窗体隐藏 </summary> FUN_MAINFORMHIDE = '{1E10987C-3332-4A6F-97EA-0112AF8C824E}'; /// <summary> Application.OnMessage消息循环 </summary> FUN_APPONMESSAGE = '{186BB780-7FF5-40C8-9B4D-828738BAB752}'; /// <summary> 登录身份验证 </summary> FUN_LOGINCERTIFCATE = '{1B1DAA31-082F-41B9-8CD1-5070659DEA6E}'; /// <summary> 用户信息 </summary> FUN_USERINFO = '{15FB3FE4-19DD-406C-B543-CF60FE364E88}'; /// <summary> 获取客户端缓存对象 </summary> FUN_CLIENTCACHE = '{1DF659CE-7108-4027-BF3F-1020CBD82075}'; /// <summary> 重新获取客户端缓存数据 </summary> FUN_REFRESHCLIENTCACHE = '{1BC0FA9B-146F-4847-9F6F-4F62B82C4743}'; // // /// <summary> 获取消息服务端地址、端口 </summary> // FUN_MSGSERVERINFO = '{134282C1-2555-4552-8DBD-C2A0AC796C8F}'; // // /// <summary> 获取升级服务端地址、端口 </summary> // FUN_UPDATESERVERINFO = '{1629791C-CA99-44EF-A403-8963B1ADC5C0}'; /// <summary> 获取本地数据库操作模块 </summary> FUN_LOCALDATAMODULE = '{16DC5603-5ECD-4DF7-827E-5F85DDC9FB89}'; /// <summary> 传递特定对象 </summary> FUN_OBJECT = '{1A820E87-FE39-43F1-8EFF-8D08F0716378}'; /// <summary> 交互业务对象 </summary> FUN_OBJECT_BLL = '{1E24BDC4-4541-49B5-B147-405BE1BE3ECA}'; implementation end.
// файл figureUnit.pas unit figureUnit; interface uses vectorUnit, colorUnit; //----------------------------------- type Tfigure = class protected center : Tvector; // центр фигуры; normal : Tvector; // нормаль; reflected : Tvector; // отражённый луч; color : Tcvet; // цвет; n_spec : double; // показатель отражения; v_spec : double; // коэффициент отражения; procedure set_normal( point: Tvector ); virtual; abstract; procedure set_reflected( incident, p: Tvector ); public function get_reflected( incident, p: Tvector ): Tvector; function get_diff( p, light_direction: Tvector ): double; function get_spec( p, ray_direction: Tvector; light_direction: Tvector ): double; function get_value_spec: double; function get_color: Tcvet; constructor birth( center0: Tvector; color0: Tcvet; n_spec0, v_spec0: double ); end; //----------------------------------- implementation //----------------------------------- // определяет отражённый в т. p луч, incident - падающий луч //----------------------------------- procedure Tfigure.set_reflected( incident, p: Tvector); var scalar : double; tmp : Tvector; begin set_normal( p ); scalar := dot_product( normal, incident ); tmp := mult_on_scal( -2.0*scalar, normal ); reflected := summ_vectors( incident, tmp ); tmp.Free; end; //----------------------------------- // возвращает отражённый в т. p луч, incident - падающий луч //----------------------------------- function Tfigure.get_reflected(incident, p: Tvector): Tvector; begin set_reflected( incident, p ); result := reflected; end; //----------------------------------- // возвращает коэффициент диффузии в т. p при направлении // на осветитель light_direction //----------------------------------- function Tfigure.get_diff(p, light_direction: Tvector): double; begin set_normal( p ); result := dot_product( light_direction, normal ); end; //----------------------------------- // возвращает коэффициент отражения в т. p при направлениях // на осветитель light_direction, из камеры -- ray_direction //----------------------------------- function Tfigure.get_spec( p : Tvector; ray_direction : Tvector; light_direction: Tvector ): double; var scalar : double; begin scalar := dot_product( reflected, light_direction ); if ( scalar < 0.0 ) then result := 0.0 else result := v_spec*exp( n_spec*ln( scalar ) ); end; //----------------------------------- function Tfigure.get_value_spec: double; begin result := v_spec; end; //----------------------------------- function Tfigure.get_color: Tcvet; begin result := color; end; //----------------------------------- constructor Tfigure.birth( center0: Tvector; color0: Tcvet; n_spec0, v_spec0 : double ); begin center := center0; color := color0; n_spec := n_spec0; v_spec := v_spec0; normal := Tvector.birth( 0, 0, 0 ); reflected := Tvector.birth( 0, 0, 0 ); end; end. // конец файла figureUnit.pas
unit SDUDropFiles; // File/Directory Drag Drop component // Set "DropControl" as appropriate, and then set Active to TRUE. // Note: If DropControl is set to nil, the parent control (e.g. frame/form) // will become the drop target) // !!! WARNING !!! // Not guaranteed to work correctly if multiple instances of this component // are used in different threads; SetWindowsHookEx(...) uses GetCurrentThread // to setup a hook for the thread - but it only has one SDFileDropHook interface uses Classes, Controls, Messages, Windows, ShellAPI; type TNotifyFileDirectoryDropEvent = procedure (Sender: TObject; DropItem: string; DropPoint: TPoint) of object; TNotifyItemsDropEvent = procedure (Sender: TObject; DropItems: TStringList; DropPoint: TPoint) of object; TSDUDropFilesThreadCallback = procedure (DropItems: TStringList; DropPoint: TPoint) of object; TSDUDropFilesThread = class(TThread) protected procedure SyncMethod(); public ItemsDropped: TStringList; DropPoint: TPoint; Callback: TSDUDropFilesThreadCallback; procedure AfterConstruction(); override; destructor Destroy(); override; procedure Execute(); override; end; TSDUDropFiles = class(TComponent) private FActive: boolean; FDropControl: TWinControl; FOnItemsDrop: TNotifyItemsDropEvent; FOnFileDrop: TNotifyFileDirectoryDropEvent; FOnDirectoryDrop: TNotifyFileDirectoryDropEvent; protected procedure ResetDropControlHandle(); procedure DoOnItemsDrop(items: TStringList; dropPoint: TPoint); procedure DoOnFileDrop(filename: string; dropPoint: TPoint); procedure DoOnDirectoryDrop(dirname: string; dropPoint: TPoint); procedure KickOffThread(itemsDropped: TStringList; dropPoint: TPoint); procedure ThreadCallback(itemsDropped: TStringList; dropPoint: TPoint); public // Cached DropControl.Handle required as the DropControl may be destroyed // before we are! // Exposed as public to allow the hook callback to check it DropControlHandle: THandle; constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure SetActive(newActive: boolean); procedure SetControl(newControl: TWinControl); function WMDropFiles(var msg: TMsg): boolean; procedure BeforeDestruction(); override; published property Active: boolean read FActive write SetActive; property DropControl: TWinControl read FDropControl write SetControl; // property Hook: HHOOK read FHook; // This event is called *once* for all items dropped // This even will be fired *before* OnFileDrop/OnDirectoryDrop. // The TStringList it gets passed can be modified to add/remove/modify // the calls made to OnFileDrop/OnDirectoryDrop property OnItemsDrop: TNotifyItemsDropEvent read FOnItemsDrop write FOnItemsDrop; // These events are called once for *each* item dropped property OnFileDrop: TNotifyFileDirectoryDropEvent read FOnFileDrop write FOnFileDrop; property OnDirectoryDrop: TNotifyFileDirectoryDropEvent read FOnDirectoryDrop write FOnDirectoryDrop; end; function WMDropFilesHook(nCode: Integer; wParam: Longint; var Msg: TMsg): Longint; stdcall; // Clear and populate "Filenames" with the filenames associated with hDrop procedure DropFilenamesToList(hDrop: HDROP; DropFilenames: TStringList); procedure Register; implementation uses Contnrs, SDUGeneral, SysUtils; var SDFileDropHook: HHOOK; SDFileDropObjs: TObjectList; // ---------------------------------------------------------------------------- procedure Register; begin RegisterComponents('SDeanUtils', [TSDUDropFiles]); end; // ---------------------------------------------------------------------------- // Clear and populate "Filenames" with the filenames associated with hDrop procedure DropFilenamesToList(hDrop: HDROP; DropFilenames: TStringList); var i: integer; cntDropped: integer; filenameLen: integer; filename: string; begin DropFilenames.Clear(); cntDropped := DragQueryFile( hDrop, $FFFFFFFF, nil, 0 ); for i:=0 to (cntDropped - 1) do begin filenameLen := DragQueryFile( hDrop, i, nil, 0 ); // Increment filenameLen to allow for terminating NULL inc(filenameLen); filename := StringOfChar(#0, filenameLen); filenameLen := DragQueryFile( hDrop, i, PChar(filename), filenameLen ); // Strip off the terminating NULL filename := Copy(filename, 1, filenameLen); DropFilenames.Add(filename); end; end; // ---------------------------------------------------------------------------- constructor TSDUDropFiles.Create(AOwner: TComponent); begin inherited; FActive:= FALSE; FDropControl:= nil; DropControlHandle := 0; FOnFileDrop := nil; FOnDirectoryDrop := nil; FOnItemsDrop := nil; end; // ---------------------------------------------------------------------------- destructor TSDUDropFiles.Destroy(); begin inherited; end; // ---------------------------------------------------------------------------- procedure TSDUDropFiles.BeforeDestruction(); begin Active := FALSE; inherited; end; // ---------------------------------------------------------------------------- function WMDropFilesHook(nCode: Integer; wParam: Longint; var Msg: TMsg): Longint; stdcall; var i: integer; retval: Longint; currDropObj: TSDUDropFiles; begin if (nCode = HC_ACTION) then begin if (wParam <> PM_REMOVE) then begin if (Msg.message = WM_DROPFILES) then begin for i:=0 to (SDFileDropObjs.count - 1) do begin currDropObj := TSDUDropFiles(SDFileDropObjs[i]); if (msg.hWnd = currDropObj.DropControlHandle) then begin currDropObj.WMDropFiles(msg); break; end; end; end; end; end; retval := CallNextHookEx( SDFileDropHook, nCode, wParam, Longint(@Msg) ); Result := retval; end; // ---------------------------------------------------------------------------- procedure TSDUDropFiles.SetActive(newActive: boolean); begin if (Active <> newActive) then begin if (DropControl = nil) then begin if (self.Owner is TWinControl) then begin DropControl := TWinControl(self.Owner); end; end; if (DropControl <> nil) then begin if newActive then begin // Update DropControlHandle - the handle could have been changed since // the control was assigned ResetDropControlHandle(); SDFileDropObjs.Add(self); // If the thread's hook hasn't been setup yet; set it up now if (SDFileDropHook = 0) then begin SDFileDropHook := SetWindowsHookEx( WH_GETMESSAGE, @WMDropFilesHook, 0, GetCurrentThreadID ); end; DragAcceptFiles(DropControlHandle, TRUE); end else begin DragAcceptFiles(DropControlHandle, FALSE); SDFileDropObjs.Delete(SDFileDropObjs.IndexOf(self)); if (SDFileDropObjs.Count <= 0) then begin UnhookWindowsHookEx(SDFileDropHook); SDFileDropHook := 0; end; end; end; FActive := newActive; end; end; // ---------------------------------------------------------------------------- procedure TSDUDropFiles.SetControl(newControl: TWinControl); var prevActive: boolean; begin prevActive := Active; Active := FALSE; FDropControl := newControl; ResetDropControlHandle(); Active := prevActive; end; // ---------------------------------------------------------------------------- procedure TSDUDropFiles.ResetDropControlHandle(); begin if (FDropControl = nil) then begin DropControlHandle:= 0; end else begin // Reset active to new control. DropControlHandle:= FDropControl.Handle; end; end; // ---------------------------------------------------------------------------- // Returns TRUE if handled, otherwise FALSE function TSDUDropFiles.WMDropFiles(var msg: TMsg): boolean; var dropPoint: TPoint; itemsDropped: TStringList; begin itemsDropped:= TStringList.Create(); try DropFilenamesToList(msg.wParam, itemsDropped); DragQueryPoint(msg.wParam, dropPoint); DragFinish(msg.wParam); // Because we're still handling the Windows message, we kick off pass // the list of files/dirs dropped over to a thread, and complete // handling the WM. // The thread simply sync's back with us, passing back the list of // files/dirs dropped, and we fire off events as appropriate // This is more complex that you'd expect, but if we call the events // directly from here, and those events carry out actions such as // displaying messageboxes to the user, things start to crash and the // user's application will do "odd things" KickOffThread(itemsDropped, dropPoint); finally itemsDropped.Free(); end; Result := TRUE; end; procedure TSDUDropFiles.KickOffThread(itemsDropped: TStringList; dropPoint: TPoint); var thread: TSDUDropFilesThread; begin thread:= TSDUDropFilesThread.Create(TRUE); thread.ItemsDropped.Assign(itemsDropped); thread.DropPoint:= dropPoint; thread.Callback:= ThreadCallback; thread.FreeOnTerminate := TRUE; thread.Resume(); end; procedure TSDUDropFiles.ThreadCallback(itemsDropped: TStringList; dropPoint: TPoint); var i: integer; begin // Fire event with all items DoOnItemsDrop(itemsDropped, dropPoint); // Fire event with each individual item in turn for i:=0 to (itemsDropped.Count - 1) do begin if DirectoryExists(itemsDropped[i]) then begin DoOnDirectoryDrop(itemsDropped[i], dropPoint); end else if FileExists(itemsDropped[i]) then begin DoOnFileDrop(itemsDropped[i], dropPoint); end; end; end; // ---------------------------------------------------------------------------- procedure TSDUDropFiles.DoOnItemsDrop(items: TStringList; dropPoint: TPoint); begin if assigned(FOnItemsDrop) then begin FOnItemsDrop(self, items, dropPoint); end; end; // ---------------------------------------------------------------------------- procedure TSDUDropFiles.DoOnFileDrop(filename: string; dropPoint: TPoint); begin if assigned(FOnFileDrop) then begin FOnFileDrop(self, filename, dropPoint); end; end; // ---------------------------------------------------------------------------- procedure TSDUDropFiles.DoOnDirectoryDrop(dirname: string; dropPoint: TPoint); begin if assigned(FOnDirectoryDrop) then begin FOnDirectoryDrop(self, dirname, dropPoint); end; end; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- procedure TSDUDropFilesThread.SyncMethod(); begin if Assigned(Callback) then begin Callback(ItemsDropped, DropPoint); end; end; procedure TSDUDropFilesThread.AfterConstruction(); begin inherited; ItemsDropped:= TStringList.Create(); Callback := nil; end; destructor TSDUDropFilesThread.Destroy(); begin ItemsDropped.Free(); inherited; end; procedure TSDUDropFilesThread.Execute(); begin Synchronize(SyncMethod); end; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- initialization SDFileDropHook := 0; SDFileDropObjs:= TObjectList.Create(); SDFileDropObjs.OwnsObjects := FALSE; finalization SDFileDropObjs.Free(); END.
unit VOpDivRecType10Form; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, VCustomRecordForm, ToolEdit, CurrEdit, StdCtrls, Mask, ExtCtrls, COpDivSystemRecord, COpDivRecType10, Menus, Buttons; type TOpDivRecType10Form = class(TCustomRecordForm) Label1: TLabel; OrdenanteReembolsoEdit: TMaskEdit; DescReembolsoLabel: TLabel; Label2: TLabel; ConceptoReembolsoEdit: TMaskEdit; ConceptoDescLabel: TLabel; Label3: TLabel; conceptoComplementaEdit: TEdit; Label4: TLabel; IndicadorResidenciaEdit: TMaskEdit; Label5: TLabel; Label6: TLabel; procedure OrdenanteReembolsoEditExit(Sender: TObject); procedure ConceptoReembolsoEditExit(Sender: TObject); procedure conceptoComplementaEditExit(Sender: TObject); procedure IndicadorResidenciaEditExit(Sender: TObject); private { Private declarations } protected procedure onGeneralChange( SystemRecord: TOpDivSystemRecord ); override; public { Public declarations } end; var OpDivRecType10Form: TOpDivRecType10Form; implementation {$R *.DFM} (************* MÉTODOS PROTEGIDOS *************) procedure TOpDivRecType10Form.onGeneralChange( SystemRecord: TOpDivSystemRecord ); begin inherited; with TOpDivRecType10( SystemRecord ) do begin OrdenanteReembolsoEdit.Text := OrdenanteReembolso; DescReembolsoLabel.Caption := OrdenanteDescripcion; ConceptoReembolsoEdit.Text := ConceptoReembolso; ConceptoDescLabel.Caption := ConceptoDescripcion; IndicadorResidenciaEdit.Text := IndicadorResidencia; end; end; (************* EVENTOS *************) procedure TOpDivRecType10Form.OrdenanteReembolsoEditExit(Sender: TObject); begin inherited; TOpDivRecType10( FSystemRecord ).OrdenanteReembolso := TEdit( Sender ).Text ; end; procedure TOpDivRecType10Form.ConceptoReembolsoEditExit(Sender: TObject); begin inherited; TOpDivRecType10( FSystemRecord ).ConceptoReembolso := TEdit( Sender ).Text ; end; procedure TOpDivRecType10Form.conceptoComplementaEditExit(Sender: TObject); begin inherited; TOpDivRecType10( FSystemRecord ).ConceptoComplementa := TEdit( Sender ).Text ; end; procedure TOpDivRecType10Form.IndicadorResidenciaEditExit(Sender: TObject); begin inherited; TOpDivRecType10( FSystemRecord ).IndicadorResidencia := TEdit( Sender ).Text ; end; end.
unit unFrmCadDetailBase; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, unFrmBase, unControllerBase, unModelBase, LCLType; type CadOperation = (view, insert, edit, filter); { TUpdater } TUpdater = class(TAggregatedObject, IObserverCurrent) private FPointer: Pointer; FFrm: TForm; FController: TAbstractController; public procedure UpdateCurrent(ACurrent: TModelBase); constructor Create(AFrm: TForm; AController: TAbstractController); destructor Destroy; override; end; { TFrmCadDetailBase } TFrmCadDetailBase = class(TFrmBase) BtnRefresh: TBitBtn; BtnClose: TBitBtn; BtnOk: TBitBtn; BtnFirst: TBitBtn; BtnPrior: TBitBtn; BtnNext: TBitBtn; BtnLast: TBitBtn; ImageList1: TImageList; Panel1: TPanel; PnlNavigator: TPanel; procedure BtnFirstClick(Sender: TObject); procedure BtnPriorClick(Sender: TObject); procedure BtnNextClick(Sender: TObject); procedure BtnLastClick(Sender: TObject); procedure BtnCloseClick(Sender: TObject); procedure BtnOkClick(Sender: TObject); procedure BtnRefreshClick(Sender: TObject); procedure FormShow(Sender: TObject); private FUpdater: TUpdater; protected FController: TAbstractController; FOperation: CadOperation; procedure UpdateScreen(AModel: TModelBase); virtual; function GetModelFromScreenFields: TModelBase; virtual; abstract; procedure SetFilterParams; virtual; abstract; public constructor Create(TheOwner: TComponent; AController: TAbstractController; AOperation: CadOperation); destructor Destroy; override; end; var FrmCadDetailBase: TFrmCadDetailBase; implementation {$R *.lfm} { TUpdater } procedure TUpdater.UpdateCurrent(ACurrent: TModelBase); begin if (ACurrent = nil) then begin exit; end; TFrmCadDetailBase(FFrm).UpdateScreen(ACurrent); end; constructor TUpdater.Create(AFrm: TForm; AController: TAbstractController); begin inherited Create(AFrm); FFrm := AFrm; FController := AController; FPointer := FController.AtachObserverCurrent(self); end; destructor TUpdater.Destroy; begin FController.UnAtachObserverCurrent(FPointer); FFrm := nil; FController := nil; inherited Destroy; end; { TFrmCadDetailBase } procedure TFrmCadDetailBase.FormShow(Sender: TObject); begin UpdateScreen(FController.Current); case (FOperation) of insert, filter: begin PnlNavigator.Visible := False; BtnRefresh.Visible:= False; end; edit: begin PnlNavigator.Visible:= False; BtnRefresh.Visible:= True; end; view: begin PnlNavigator.Visible:= True; BtnRefresh.Visible:= False; BtnOk.Visible:= False; end; end; end; procedure TFrmCadDetailBase.UpdateScreen(AModel: TModelBase); begin BtnFirst.Enabled:= FController.CurrentIndex > 0 ; BtnPrior.Enabled:= FController.CurrentIndex > 0; BtnLast.Enabled:= FController.CurrentIndex < FController.Itens.Count -1; BtnNext.Enabled:= FController.CurrentIndex < FController.Itens.Count -1; end; procedure TFrmCadDetailBase.BtnOkClick(Sender: TObject); var model: TModelBase; begin try case FOperation of Insert: begin FController.Insert(GetModelFromScreenFields()); Close(); end; Edit: begin model := GetModelFromScreenFields(); model.Id := FController.Current.id; FController.Update(model); Close(); end; filter: begin SetFilterParams; FController.GetByFilter; Close(); end; end; except on e: EValidationError do begin Application.MessageBox(PChar(FController.Errors.Text), 'Erros de validação', MB_ICONERROR + MB_OK); end; end; end; procedure TFrmCadDetailBase.BtnRefreshClick(Sender: TObject); begin case FOperation of Insert: begin end; Edit: begin FController.Get(FController.Current.Id); UpdateScreen(FController.Current); end; end; end; procedure TFrmCadDetailBase.BtnCloseClick(Sender: TObject); begin Close(); end; procedure TFrmCadDetailBase.BtnFirstClick(Sender: TObject); begin FController.First; end; procedure TFrmCadDetailBase.BtnPriorClick(Sender: TObject); begin FController.Prior; end; procedure TFrmCadDetailBase.BtnNextClick(Sender: TObject); begin FController.Next; end; procedure TFrmCadDetailBase.BtnLastClick(Sender: TObject); begin FController.Last; end; constructor TFrmCadDetailBase.Create(TheOwner: TComponent; AController: TAbstractController; AOperation: CadOperation); begin inherited Create(TheOwner); FController := AController; FOperation := AOperation; FUpdater := TUpdater.Create(self, FController); end; destructor TFrmCadDetailBase.Destroy; begin FUpdater.Free; FUpdater := nil; inherited Destroy; end; end.
unit PrintForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, DB, FIBDataSet, pFIBDataSet, FR_DSet, FR_DBSet, FR_Class, ExtCtrls, StdCtrls, cxButtons, MainForm, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, frxClass, frxDBSet, cxSpinEdit, cxCheckBox, DateUtils, pFIBDatabase, cxLabel, Un_R_file_Alex; type TfmMode = (Jornal4, Edit, Sp, SpEdit); TfmPrintForm = class(TForm) cxButtonClose: TcxButton; cxButtonPrint: TcxButton; Bevel1: TBevel; frReport1: TfrReport; frDBDataSet1: TfrDBDataSet; PrintDialog1: TPrintDialog; cxCheckBox1: TcxCheckBox; cxSpinEdit1: TcxSpinEdit; cxComboBoxMonth: TcxComboBox; cxComboBoxJornal: TcxComboBox; DataSetJornal: TpFIBDataSet; DataSet: TpFIBDataSet; frxDBDataset1: TfrxDBDataset; DataSetSUMMA_DEBET: TFIBBCDField; DataSetSCH_TITLE: TFIBStringField; DataSetDATE_PROV_DEBET: TFIBDateField; DataSetNAME_RECVIZITI_DEBET: TFIBStringField; DataSetNAME_RECVIZITI_KREDIT: TFIBStringField; DataSetDATE_PROV_KREDIT: TFIBDateField; DataSetFAMILIA: TFIBStringField; DataSetIMYA: TFIBStringField; DataSetOTCHESTVO: TFIBStringField; DataSetBIRTHDAY: TFIBDateField; DataSetTIN: TFIBStringField; DataSetNUM_DOC_DEBET: TFIBStringField; DataSetNUM_DOC_KREDIT: TFIBStringField; DataSetDEBET_SCH: TFIBStringField; DataSetKREDIT_SCH: TFIBStringField; DataSetOST_ALL_DEBET: TFIBBCDField; DataSetOST_ALL_KREDIT: TFIBBCDField; DataSetOST_DEBET: TFIBBCDField; DataSetOST_KREDIT: TFIBBCDField; DataSetFLAG_FIO: TFIBIntegerField; DataSetFIO: TFIBStringField; DataSetOSN_SCH: TFIBStringField; DataSetSUMMA_KREDIT: TFIBBCDField; Report3: TfrxReport; cxLabel1: TcxLabel; cxLabel2: TcxLabel; procedure cxButtonCloseClick(Sender: TObject); procedure cxButtonPrintClick(Sender: TObject); private n : TfmMode; Ind1 : array [1..2] of array of Variant; public id_jornal : int64; constructor Create(m : TfmMode; db : TpFIBDatabase; Tr : TpFIBTransaction); reintroduce; overload; destructor Destroy; override; end; implementation {$R *.dfm} constructor TfmPrintForm.Create(m : TfmMode; db : TpFIBDatabase; Tr : TpFIBTransaction); var i : integer; begin inherited Create(nil); n := m; DataSetJornal.Database := db; DataSetJornal.Transaction := Tr; DataSetJornal.StartTransaction; DataSet.Database := db; DataSet.Transaction := Tr; DataSet.StartTransaction; if m = Jornal4 then begin {загрузка журнала} DataSetJornal.Close; DataSetJornal.SQLs.SelectSQL.Text := ' SELECT * FROM J4_SP_JO '; DataSetJornal.open; If DataSetJornal.IsEmpty then begin MessageBox(Handle, PChar('Не _снує журналу завантаження! Система автоматично закриється. Зверниться до системного адм_н_стратору.'), PChar('Увага!!!'), 16); close; end; DataSetSelectSystem.FetchAll; SetLength(Ind1[1], DataSetJornal.RecordCount); SetLength(Ind1[2], DataSetJornal.RecordCount); DataSetJornal.First; cxComboBoxJornal.Properties.Items.Clear; i := 0; While not DataSetJornal.Eof do begin Ind1[1, DataSetJornal.RecNo - 1] := DataSetJornal.FieldByName('ID_J4_SP_JO').AsVariant; Ind1[2, DataSetJornal.RecNo - 1] := DataSetJornal.FieldByName('DATA_OPEN').AsDateTime; if DataSetJornal.FieldByName('SYSTEM_OPEN').Asinteger = 1 then begin i := DataSetJornal.RecNo - 1; id_jornal := DataSetJornal.FieldByName('ID_J4_SP_JO').AsVariant; cxSpinEdit1.Properties.MinValue := YearOf(DataSetJornal.FieldByName('DATA_OPEN').AsDateTime); end; cxComboBoxJornal.Properties.Items.Insert(DataSetJornal.RecNo - 1, DataSetJornal.FieldByName('SHORT_NAME').AsString); DataSetJornal.Next; end; DataSetJornal.Close; DataSetJornal.Transaction.Commit; cxSpinEdit1.Value := YearOf(date); cxComboBoxMonth.ItemIndex := MonthOf(date)-1; cxComboBoxJornal.ItemIndex := i; end; cxLabel1.Caption := Un_R_file_Alex.J4_PRINT_SLECT_JORNAL; cxButtonClose.Caption := Un_R_file_Alex.MY_BUTTON_CLOSE; cxButtonPrint.Caption := Un_R_file_Alex.MY_BUTTON_PRINT; Caption := Un_R_file_Alex.KASSA_PRINT_CAPTION; cxCheckBox1.Properties.Caption := Un_R_file_Alex.KASSA_PRINT_SELMONTH; cxLabel2.Caption := Un_R_file_Alex.J4_OSTATOK_FORM_YEAR; end; destructor TfmPrintForm.Destroy; begin inherited; end; procedure TfmPrintForm.cxButtonCloseClick(Sender: TObject); begin Close; end; procedure TfmPrintForm.cxButtonPrintClick(Sender: TObject); var d : TDate; i : integer; begin if n = Jornal4 then begin if cxComboBoxMonth.ItemIndex < 10 then d := StrToDate('01.0'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)) else d := StrToDate('01.'+IntTostr(cxComboBoxMonth.ItemIndex+1)+'.'+IntToStr(cxSpinEdit1.Value)); DataSet.Close; DataSet.SQLs.SelectSQL.Text := 'SELECT * FROM J4_OTCHET_MONTH('''+ DateToStr(d) +''', '+intToStr(id_jornal)+')'; DataSet.Open; // DataSet.First; // While not DataSetSelectPap.Eof do // begin // frVariables['ini_ruk'] := Copy(DataSetSelectPap.FieldByName('I_RUKOVODITEL').AsString,1,1)+'.'+Copy(DataSetSelectPap.FieldByName('O_RUKOVODITEL').AsString,1,1)+'.'; // frVariables['ini_pod'] := Copy(DataSetSelectPap.FieldByName('I_PODPISAL').AsString,1,1)+'.'+Copy(DataSetSelectPap.FieldByName('O_PODPISAL').AsString,1,1)+'.'; // frVariables['fio_dog'] := fio; // frVariables['zarplata_pis'] := '('+AllChislo(FloatToStr(DataSetSelectPap.FieldByName('SUMMA_ZARABOTKA').AsFloat)) +')'; // if DataSetSelectPap['YEAR_DOGOVOR'] <> null { Report3.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Avance\Otchet\j4_jo_4.fr3'); Report3.PrepareReport(true); Report3.ShowReport; // else Report.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'BPL\Otchet\Work_dogovor_all_not_year.frf'); // Report.PrepareReport; // if not cxCheckBoxEdit.Checked then // begin // if not cxCheckBoxShow.Checked then // Report.PrintPreparedReport(IntToStr(PrintDialog1.FromPage) + '-' + IntTostr(PrintDialog1.ToPage), // PrintDialog1.Copies, // PrintDialog1.Collate, // frAll) {else} // end else Report.DesignReport; // DataSetSelectPap.Next; // end; frReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Avance\Otchet\№4.frf'); // frReport1.PrepareReport; frReport1.ShowReport; DataSet.Close; end; DataSet.Transaction.Commit; end; end.
//****************************************************************************** // Проект "Контракты" // Кредит // Чернявский А.Э. 2007г. //****************************************************************************** unit Credit_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dxBar, dxBarExtItems, ImgList, cxGraphics, cxContainer, cxEdit, cxProgressBar, dxStatusBar, cxControls, IBase, DM_cr, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxClasses, cxTextEdit, cn_Common_Funcs, cnConsts, cxCurrencyEdit, frxClass, frxDBSet, frxDesgn, frxExportPDF, frxExportXLS, frxExportHTML, frxExportRTF, ActnList, ExtCtrls, Credit_AE, cnConsts_Messages, cn_Common_Messages, Credit_AddAll_Unit, cn_Common_Types, cn_Common_Loader, mcmImage, mcmImageDB, mcmPrinter, frmRangeUnit; type TfrmCredit = class(TForm) Splitter1: TSplitter; Grid: TcxGrid; GridView: TcxGridDBTableView; NAME_DOCUM: TcxGridDBColumn; DATE_DOCUM: TcxGridDBColumn; GridLevel1: TcxGridLevel; Grid2: TcxGrid; Grid2View: TcxGridDBTableView; Facul_Col: TcxGridDBColumn; FIO_Col: TcxGridDBColumn; Summa_Col: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; StatusBar: TdxStatusBar; dxBarManager1: TdxBarManager; AddButton: TdxBarLargeButton; EditButton: TdxBarLargeButton; DeleteButton: TdxBarLargeButton; RefreshButton: TdxBarLargeButton; ExitButton: TdxBarLargeButton; SelectButton: TdxBarLargeButton; ViewButton: TdxBarLargeButton; AddPfioButton: TdxBarLargeButton; DeletePfioButton: TdxBarLargeButton; EditPfioButton: TdxBarLargeButton; AddListPfioButton: TdxBarLargeButton; dxBarLargeButton1: TdxBarLargeButton; Search_Button: TdxBarLargeButton; dxBarButton1: TdxBarButton; dxBarButton2: TdxBarButton; dxBarButton3: TdxBarButton; dxBarButton4: TdxBarButton; AddAllAvto_Btn: TdxBarLargeButton; PrintButton: TdxBarLargeButton; BarStatic: TdxBarStatic; DeleteAll_Btn: TdxBarLargeButton; ActionList1: TActionList; AddAction: TAction; EditAction: TAction; DeleteAction: TAction; RefreshAction: TAction; ExitAction: TAction; ViewAction: TAction; DebugPrintAction: TAction; LargeImages: TImageList; DisabledLargeImages: TImageList; PopupMenu1: TdxBarPopupMenu; PopupImageList: TImageList; dxBarPopupMenu1: TdxBarPopupMenu; Styles: TcxStyleRepository; BackGround: TcxStyle; FocusedRecord: TcxStyle; Header: TcxStyle; DesabledRecord: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; Default_StyleSheet: TcxGridTableViewStyleSheet; DevExpress_Style: TcxGridTableViewStyleSheet; frxRTFExport1: TfrxRTFExport; frxHTMLExport1: TfrxHTMLExport; frxXLSExport1: TfrxXLSExport; frxPDFExport1: TfrxPDFExport; frxDesigner1: TfrxDesigner; frxDBDataset: TfrxDBDataset; frxDBDataset2: TfrxDBDataset; clnSumma: TcxGridDBColumn; clnNUM_DOG: TcxGridDBColumn; frxReport: TfrxReport; btnPrintList: TdxBarButton; btnPrintImage: TdxBarButton; btnScan: TdxBarLargeButton; db_imgPicture: TmcmImageDB; mcmPrinter: TmcmPrinter; btnView: TdxBarLargeButton; btnPrintOptions: TdxBarButton; PrinterSetupDialog: TPrinterSetupDialog; clnSummaDog: TcxGridDBColumn; btnPrintRange: TdxBarButton; procedure ExitButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure AddButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure DeletePfioButtonClick(Sender: TObject); procedure DeleteAll_BtnClick(Sender: TObject); procedure AddAllAvto_BtnClick(Sender: TObject); procedure DebugPrintActionExecute(Sender: TObject); procedure PrintButtonClick(Sender: TObject); procedure btnPrintListClick(Sender: TObject); procedure GridViewDblClick(Sender: TObject); procedure btnScanClick(Sender: TObject); procedure PrintImageEx(Sender: TObject; IsRange: Boolean; Rbeg:Integer; Rend: Integer; PrintValue: Integer); procedure btnViewClick(Sender: TObject); procedure btnPrintOptionsClick(Sender: TObject); procedure btnPrintRangeClick(Sender: TObject); procedure btnPrintImageClick(Sender: TObject); private PLanguageIndex: byte; DM, DM_Detail_1 :TDM_C; procedure FormIniLanguage; public res:Variant; constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE);reintroduce; end; var designer_rep:Integer; implementation uses FIBQuery; {$R *.dfm} constructor TfrmCredit.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE); begin Screen.Cursor:=crHourGlass; inherited Create(AOwner); designer_rep:=0; DM:=TDM_C.Create(Self); DM.DataSet.SQLs.SelectSQL.Text := 'select * from CN_DT_CREDIT_S'; DM.DB.Handle:=DB_Handle; DM.DataSet.Open; GridView.DataController.DataSource := DM.DataSource; DM_Detail_1:=TDM_C.Create(Self); DM_Detail_1.DataSet.SQLs.SelectSQL.Text := 'SELECT * FROM CN_DT_CREDIT_LIST_S(?ID_CREDIT) order by FIO'; DM_Detail_1.DataSet.DataSource:= DM.DataSource; DM_Detail_1.DB.Handle:=DB_Handle; DM_Detail_1.DataSet.Open; Grid2View.DataController.DataSource := DM_Detail_1.DataSource; FormIniLanguage(); Screen.Cursor:=crDefault; end; procedure TfrmCredit.FormIniLanguage; begin PLanguageIndex:= cn_Common_Funcs.cnLanguageIndex(); Caption:= cnConsts.cn_Credit_Caption[PLanguageIndex]; //названия кнопок AddButton.Caption := cnConsts.cn_InsertBtn_Caption[PLanguageIndex]; EditButton.Caption := cnConsts.cn_EditBtn_Caption[PLanguageIndex]; DeleteButton.Caption := cnConsts.cn_DeleteBtn_Caption[PLanguageIndex]; RefreshButton.Caption := cnConsts.cn_RefreshBtn_Caption[PLanguageIndex]; SelectButton.Caption := cnConsts.cn_Execution[PLanguageIndex]; ExitButton.Caption := cnConsts.cn_ExitBtn_Caption[PLanguageIndex]; ViewButton.Caption := cnConsts.cn_ViewShort_Caption[PLanguageIndex]; PrintButton.Caption:= cnConsts.cn_Print_Caption[PLanguageIndex]; btnView.Hint:= cnConsts.cn_Sort[PLanguageIndex]; DeleteAll_Btn.Hint:= cn_DelAll_Caption[PLanguageIndex]; //статусбар StatusBar.Panels[0].Text:= cnConsts.cn_InsertBtn_ShortCut[PLanguageIndex] + cnConsts.cn_InsertBtn_Caption[PLanguageIndex]; StatusBar.Panels[1].Text:= cnConsts.cn_EditBtn_ShortCut[PLanguageIndex] + cnConsts.cn_EditBtn_Caption[PLanguageIndex]; StatusBar.Panels[2].Text:= cnConsts.cn_DeleteBtn_ShortCut[PLanguageIndex] + cnConsts.cn_DeleteBtn_Caption[PLanguageIndex]; StatusBar.Panels[3].Text:= cnConsts.cn_RefreshBtn_ShortCut[PLanguageIndex] + cnConsts.cn_RefreshBtn_Caption[PLanguageIndex]; StatusBar.Panels[4].Text:= cnConsts.cn_EnterBtn_ShortCut[PLanguageIndex] + cnConsts.cn_SelectBtn_Caption[PLanguageIndex]; StatusBar.Panels[5].Text:= cnConsts.cn_ExitBtn_ShortCut[PLanguageIndex] + cnConsts.cn_ExitBtn_Caption[PLanguageIndex]; AddPfioButton.Caption := cn_InsertBtn_Caption[PLanguageIndex]; AddPfioButton.Hint := cn_InsertBtn_Caption[PLanguageIndex]; EditPfioButton.Caption := cn_EditBtn_Caption[PLanguageIndex]; EditPfioButton.Hint := cn_EditBtn_Caption[PLanguageIndex]; DeletePfioButton.Caption := cn_DeleteBtn_Caption[PLanguageIndex]; DeletePfioButton.Hint := cn_DeleteBtn_Caption[PLanguageIndex]; AddListPfioButton.Caption := cn_Add_List[PLanguageIndex]; AddListPfioButton.Hint := cn_Add_List[PLanguageIndex]; AddAllAvto_Btn.Hint := cn_RaportAvto[PLanguageIndex]; btnPrintList.Caption := cn_Reestr[PLanguageIndex]; btnPrintImage.Caption := cn_Image[PLanguageIndex]; btnScan.Caption := cn_Image[PLanguageIndex]; //btnPrintRange.Caption := cn_PrintRangeImage[PLanguageIndex]; btnPrintRange.Caption := cn_Image[PLanguageIndex]; // grid's NAME_DOCUM.Caption := cn_FiltrByNum[PLanguageIndex]; DATE_DOCUM.Caption := cn_Date_Opl_Column[PLanguageIndex]; clnSumma.Caption := cn_Summa_Column[PLanguageIndex]; Facul_Col.Caption := cn_footer_Faculty[PLanguageIndex]; clnSummaDog.Caption := cn_DogSum[PLanguageIndex]; FIO_Col.Caption := cn_grid_FIO_Column[PLanguageIndex]; Summa_Col.Caption := cn_Summa_Column[PLanguageIndex]; clnNUM_DOG.Caption := cn_grid_Num_Dog_Column[PLanguageIndex]; end; procedure TfrmCredit.ExitButtonClick(Sender: TObject); begin close; end; procedure TfrmCredit.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormStyle = fsMDIChild then action:=caFree else DM.Free; end; procedure TfrmCredit.AddButtonClick(Sender: TObject); var ViewForm : TfrmCredit_AE; location : int64; begin ViewForm := TfrmCredit_AE.create(self, PLanguageIndex, DM.DB.Handle); ViewForm.Caption := cn_InsertBtn_Caption[PLanguageIndex]; ViewForm.Date_Create_Edit.Date := Now; if ViewForm.ShowModal = mrOk then begin with DM.StProc do begin try StoredProcName := 'CN_DT_CREDIT_I'; Transaction.StartTransaction; ParamByName('NUM_CREDIT').AsString := ViewForm.Num_Credit_Edit.Text; ParamByName('DATE_START_CALC').AsDate := ViewForm.DateStartCalc_Edit.Date; ParamByName('DATE_CREDIT').AsDate := ViewForm.Date_Credit_Edit.Date; ParamByName('SUMMA').AsCurrency := ViewForm.SummaEdit.Value; ParamByName('NOTE').AsString := ViewForm.Note_Edit.Text; ParamByName('CUSTOMER').AsString := ViewForm.Customer_Edit.Text; ParamByName('LIMIT_SUM').AsCurrency := ViewForm.LimitSum_Edit.Value; ParamByName('LIMIT_DOGS').AsCurrency := ViewForm.LimitDog_Edit.Value; ParamByName('IMAGE_PRIORITY').AsInteger:= Integer(ViewForm.ckbxImagePriority.Checked); ParamByName('COMMENTS').AsString := ViewForm.ord_ae_Comments.Text; ParamByName('ID_STATUS').AsInt64 := ViewForm.Id_Status; Prepare; ExecProc; location := ParamByName('ID_CREDIT').AsInt64; Transaction.Commit; Close; except Transaction.Rollback; ShowMessage('Error in stored procedure CN_DT_CREDIT_I'); raise; exit; end; end; DM.DataSet.CloseOpen(true); DM.DataSet.Locate('ID_CREDIT',location,[] ); DM_Detail_1.DataSet.CloseOpen(true); end; end; procedure TfrmCredit.EditButtonClick(Sender: TObject); var ViewForm : TfrmCredit_AE; locateID : int64; begin if GridView.DataController.RecordCount = 0 then exit; ViewForm := TfrmCredit_AE.create(self, PLanguageIndex, DM.DB.Handle); ViewForm.Caption := cn_EditBtn_Caption[PLanguageIndex]; ViewForm.Num_Credit_Edit.Text := DM.DataSet['NUM_CREDIT']; ViewForm.DateStartCalc_Edit.Date := DM.DataSet['DATE_START_CALC']; ViewForm.Date_Credit_Edit.Date := DM.DataSet['DATE_CREDIT']; ViewForm.Date_Create_Edit.Date := DM.DataSet['DATE_CREATE']; ViewForm.SummaEdit.Value := DM.DataSet['SUMMA']; ViewForm.Note_Edit.Text := DM.DataSet['NOTE']; ViewForm.Customer_Edit.Text := DM.DataSet['CUSTOMER']; ViewForm.LimitSum_Edit.Value := DM.DataSet['LIMIT_SUM']; ViewForm.LimitDog_Edit.Value := DM.DataSet['LIMIT_DOGS']; ViewForm.ckbxImagePriority.Checked := Boolean(DM.DataSet['IMAGE_PRIORITY']); ViewForm.ord_ae_Comments.Text := DM.DataSet['COMMENTS']; ViewForm.Id_Status := DM.DataSet['ID_STATUS']; ViewForm.StatusEdit.Text := DM.DataSet['NAME_STATUS']; if DM_Detail_1.DataSet.RecordCount > 0 then begin ViewForm.Date_Credit_Edit.Properties.ReadOnly := True; ViewForm.Date_Credit_Edit.Style.Color := $00F8E4D8; ViewForm.DateStartCalc_Edit.Properties.ReadOnly := True; ViewForm.DateStartCalc_Edit.Style.Color := $00F8E4D8; ViewForm.LimitSum_Edit.Properties.ReadOnly := True; ViewForm.LimitSum_Edit.Style.Color := $00F8E4D8; ViewForm.LimitDog_Edit.Properties.ReadOnly := True; ViewForm.LimitDog_Edit.Style.Color := $00F8E4D8; ViewForm.ckbxImagePriority.Properties.ReadOnly := True; end; if ViewForm.ShowModal = mrOk then begin with DM.StProc do begin try StoredProcName := 'CN_DT_CREDIT_U'; Transaction.StartTransaction; ParamByName('ID_CREDIT').AsInt64 := DM.Dataset['ID_CREDIT']; locateID := DM.Dataset['ID_CREDIT']; ParamByName('NUM_CREDIT').AsString := ViewForm.Num_Credit_Edit.Text; ParamByName('DATE_START_CALC').AsDate := ViewForm.DateStartCalc_Edit.Date; ParamByName('DATE_CREDIT').AsDate := ViewForm.Date_Credit_Edit.Date; ParamByName('SUMMA').AsCurrency := ViewForm.SummaEdit.Value; ParamByName('NOTE').AsString := ViewForm.Note_Edit.Text; ParamByName('CUSTOMER').AsString := ViewForm.Customer_Edit.Text; ParamByName('DATE_CREATE').AsDate := ViewForm.Date_Create_Edit.Date; ParamByName('LIMIT_SUM').AsCurrency := ViewForm.LimitSum_Edit.Value; ParamByName('LIMIT_DOGS').AsCurrency := ViewForm.LimitDog_Edit.Value; ParamByName('IMAGE_PRIORITY').AsInteger:= Integer(ViewForm.ckbxImagePriority.Checked); ParamByName('COMMENTS').AsString := ViewForm.ord_ae_Comments.Text; ParamByName('ID_STATUS').AsInt64 := ViewForm.Id_Status; Prepare; ExecProc; Transaction.Commit; Close; except Transaction.Rollback; ShowMessage('Error in stored procedure CN_DT_CREDIT_U'); raise; exit; end; end; DM.DataSet.CloseOpen(true); DM_Detail_1.DataSet.CloseOpen(true); DM.DataSet.Locate('ID_CREDIT',locateID, []); end; end; procedure TfrmCredit.DeleteButtonClick(Sender: TObject); var i: byte; begin if GridView.DataController.RecordCount = 0 then Exit; if DM_Detail_1.DataSet.RecordCount > 0 then begin showmessage(cnConsts_Messages.cn_NonDeleteDependet[PLanguageIndex]); exit; end; i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts_Messages.cn_warning_Delete[PLanguageIndex], mtConfirmation, [mbYes, mbNo]); if ((i = 7) or (i= 2)) then exit else begin with DM.StProc do try Transaction.StartTransaction; StoredProcName := 'CN_DT_CREDIT_D'; Prepare; ParamByName('ID_CREDIT').AsInt64 := DM.DataSet['ID_CREDIT']; ExecProc; Transaction.Commit; except on E:Exception do begin Transaction.Rollback; end; end; DM.DataSet.CloseOpen(True); DM_Detail_1.DataSet.CloseOpen(True); end; end; procedure TfrmCredit.RefreshButtonClick(Sender: TObject); begin DM.DataSet.CloseOpen(True); DM_Detail_1.DataSet.CloseOpen(True); end; procedure TfrmCredit.DeletePfioButtonClick(Sender: TObject); var i: byte; id_Locator, id_Locator_master : Int64; begin if Grid2View.DataController.RecordCount = 0 then exit; i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts_Messages.cn_warning_Delete[PLanguageIndex], mtConfirmation, [mbYes, mbNo]); if ((i = 7) or (i= 2)) then exit else begin Screen.Cursor := crHourGlass; id_Locator:= Grid2View.DataController.FocusedRecordIndex; id_Locator_master := DM.DataSet['ID_CREDIT']; with DM.StProc do try Transaction.StartTransaction; StoredProcName := 'CN_DT_CREDIT_LIST_D'; Prepare; ParamByName('ID_PK').AsInt64 := DM_Detail_1.DataSet['ID_PK']; ExecProc; Transaction.Commit; except on E:Exception do begin cnShowMessage('Error in CN_DT_CREDIT_LIST_D',e.Message,mtError,[mbOK]); Transaction.Rollback; raise; end; end; DM_Detail_1.DataSet.CloseOpen(true); with DM.StProc do try Transaction.StartTransaction; // здесь апдейт суммы по кредиту суммой SummaAllCredit StoredProcName := 'CN_DT_CREDIT_UPDATE_SUMMA'; Prepare; ParamByName('ID_CREDIT').AsInt64 := DM.DataSet['ID_CREDIT']; ParamByName('SUMMA').AsCurrency := StrToFloat(Grid2View.DataController.Summary.FooterSummaryValues[0]); ExecProc; Transaction.Commit; except on E:Exception do begin cnShowMessage('Error in CN_DT_CREDIT_UPDATE_SUMMA',e.Message,mtError,[mbOK]); Transaction.Rollback; raise; end; end; DM.DataSet.CloseOpen(true); DM_Detail_1.DataSet.CloseOpen(true); Grid2View.DataController.FocusedRecordIndex := id_Locator -1; DM.DataSet.Locate('ID_CREDIT', id_Locator_master ,[] ); Screen.Cursor := crDefault; end; end; procedure TfrmCredit.DeleteAll_BtnClick(Sender: TObject); var i: byte; begin if Grid2View.DataController.RecordCount = 0 then exit; i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts_Messages.cn_warning_Execute[PLanguageIndex], mtConfirmation, [mbYes, mbNo]); if ((i = 7) or (i= 2)) then exit else begin with DM.StProc do try Transaction.StartTransaction; StoredProcName := 'CN_DT_CREDIT_LIST_D_ALL'; Prepare; ParamByName('ID_CREDIT').AsInt64 := DM.DataSet['ID_CREDIT']; ExecProc; Transaction.Commit; except on E:Exception do begin cnShowMessage('Error in CN_DT_CREDIT_LIST_D_ALL',e.Message,mtError,[mbOK]); Transaction.Rollback; raise; end; end; with DM.StProc do try Transaction.StartTransaction; // здесь апдейт суммы по кредиту суммой SummaAllCredit StoredProcName := 'CN_DT_CREDIT_UPDATE_SUMMA'; Prepare; ParamByName('ID_CREDIT').AsInt64 := DM.DataSet['ID_CREDIT']; ParamByName('SUMMA').AsCurrency := 0; ExecProc; Transaction.Commit; except on E:Exception do begin cnShowMessage('Error in CN_DT_CREDIT_UPDATE_SUMMA',e.Message,mtError,[mbOK]); Transaction.Rollback; raise; end; end; DM.DataSet.CloseOpen(true); DM_Detail_1.DataSet.CloseOpen(true); end; end; procedure TfrmCredit.AddAllAvto_BtnClick(Sender: TObject); var ViewForm : TfrmAddAll; begin if GridView.DataController.RecordCount = 0 then exit; ViewForm := TfrmAddAll.Create(self,DM.DB.Handle, PLanguageIndex, Dm.DataSet['ID_CREDIT']); ViewForm.Caption := cn_InsertBtn_Caption[PLanguageIndex]; ViewForm.DATE_START_CALC := Dm.DataSet['DATE_START_CALC']; ViewForm.DATE_CREDIT := Dm.DataSet['DATE_CREDIT']; ViewForm.IS_IMAGE_PRIOR := Dm.DataSet['IMAGE_PRIORITY']; ViewForm.LIMIT_SUM := DM.DataSet['LIMIT_SUM']; ViewForm.LIMIT_DOGS := DM.DataSet['LIMIT_DOGS']; ViewForm.ShowModal; DM.DataSet.CloseOpen(true); DM_Detail_1.DataSet.CloseOpen(true); ViewForm.Free; end; procedure TfrmCredit.DebugPrintActionExecute(Sender: TObject); begin if designer_rep=0 then begin designer_rep:=1; BarStatic.Caption:='Режим отладки отчетов'; end else begin designer_rep:=0; BarStatic.Caption:=''; end; end; procedure TfrmCredit.PrintButtonClick(Sender: TObject); var ID_NAMEREP : int64; begin frxReport.Clear; frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Contracts\'+'cn_che_CreditList'+'.fr3'); frxReport.Variables.Clear; frxReport.Variables['CUSTOMER']:= ''''+ DM.DataSet['CUSTOMER']+''''; frxReport.Variables['NOTE'] := ''''+ DM.DataSet['NOTE']+''''; frxReport.Variables['SUMMA'] := ''''+ vartostr(DM.DataSet['LIMIT_SUM'])+''''; frxReport.Variables['DATE_CREDIT'] := ''''+ vartostr(DM.DataSet['DATE_CREDIT'])+''''; frxReport.Variables['DATE_START_CALC'] := ''''+ vartostr(DM.DataSet['DATE_START_CALC'])+''''; frxReport.Variables['SUMMARY'] := ''''+ vartostr(Grid2View.DataController.Summary.FooterSummaryValues[0])+''''; Dm.ReadDataSet.Close; Dm.ReadDataSet.SelectSQL.Clear; Dm.ReadDataSet.SelectSQL.Text := 'select CN_NAMEZVIT_CREDIT from PUB_SYS_DATA'; Dm.ReadDataSet.Open; if Dm.ReadDataSet['CN_NAMEZVIT_CREDIT'] <> null then ID_NAMEREP := Dm.ReadDataSet['CN_NAMEZVIT_CREDIT']; Dm.ReadDataSet.Close; Dm.ReadDataSet.Close; Dm.ReadDataSet.SelectSQL.Clear; Dm.ReadDataSet.SelectSQL.Text := 'select * from CN_FR_GET_SIGNATURES(' + inttostr(ID_NAMEREP) + ')'; Dm.ReadDataSet.Open; Dm.ReadDataSet.FetchAll; frxDBDataset.DataSet := DM_Detail_1.DataSet; frxDBDataset2.DataSet := DM.ReadDataSet; frxReport.PrepareReport(true); frxReport.ShowReport; if designer_rep=1 then begin frxReport.DesignReport; end; Dm.ReadDataSet.Close; end; procedure TfrmCredit.btnPrintListClick(Sender: TObject); begin PrintButtonClick(Sender); end; procedure TfrmCredit.GridViewDblClick(Sender: TObject); begin EditButtonClick(Sender); end; procedure TfrmCredit.btnScanClick(Sender: TObject); var AParameter : TcnSimpleParamsEx; begin if Grid2View.DataController.RecordCount = 0 then exit; AParameter:= TcnSimpleParamsEx.Create; AParameter.Owner:=self; AParameter.Db_Handle:= DM.DB.Handle; AParameter.Formstyle:=fsNormal; AParameter.cnParamsToPakage.ID_DOG := DM_Detail_1.Dataset['ID_DOG']; AParameter.cnParamsToPakage.FIO := DM_Detail_1.DataSet['FIO']; AParameter.WaitPakageOwner:= self; RunFunctionFromPackage(AParameter, 'Contracts\cn_Scan.bpl','cnLoadTwain'); AParameter.Free; Screen.Cursor := crDefault; end; procedure TfrmCredit.PrintImageEx(Sender: TObject; IsRange: Boolean; Rbeg:Integer; Rend: Integer; PrintValue: Integer); var i, CN_IMAGE_PRINT_PAGE_LIMIT: Integer; DM2 :TDM_C; Id_session: int64; AddToPrint : Boolean; k: Integer; begin if (not Boolean(DM.DataSet['IMAGE_PRIORITY'])) then exit; if PrinterSetupDialog.Execute then begin mcmPrinter.RefreshProperties; InvalidateRect(Handle, Nil, True); end else exit; mcmPrinter.Clear; DM2:=TDM_C.Create(Self); DM2.DB.Handle:= Dm.DB.Handle; // проверяю Кол-во страниц печати образов DM2.ReadDataSet.SelectSQL.Text := 'SELECT CN_IMAGE_PRINT_PAGE_LIMIT FROM CN_GET_CN_IMAGE_PRINT_PAGE_LIM'; DM2.ReadDataSet.Open; CN_IMAGE_PRINT_PAGE_LIMIT:= DM2.ReadDataSet['CN_IMAGE_PRINT_PAGE_LIMIT']; DM2.ReadDataSet.Close; // проверяю подключаться ли к другой базе DM2.ReadDataSet.SelectSQL.Text := 'SELECT CN_IMAGE_IN_OTHER_DB FROM CN_PUB_SYS_DATA_GET_ALL'; DM2.ReadDataSet.Open; if DM2.ReadDataSet['CN_IMAGE_IN_OTHER_DB'] =1 then begin DM2.ReadDataSet.Close; ReadIniFileImage(DM2.DB); end; if DM2.ReadDataSet.Active then DM2.ReadDataSet.Close; // генерирую сессию для печати with DM2.StProc do try Transaction.StartTransaction; StoredProcName := 'CN_TMP_SCAN_GEN_SESSION'; Prepare; ExecProc; Id_session := ParamByName('ID_SESSION').AsInt64; Transaction.Commit; except on E:Exception do begin ShowMessage('Error in CN_TMP_SCAN_GEN_SESSION'); Transaction.Rollback; raise; end; end; // заполнение временной таблицы печати DM_Detail_1.DataSet.First; for i := 0 to DM_Detail_1.DataSet.RecordCount-1 do begin AddToPrint := False; if IsRange then if ((i >= Rbeg-1) and (i<= Rend-1)) then AddToPrint := True; if not IsRange then AddToPrint := True; if AddToPrint then with DM2.StProc do try Transaction.StartTransaction; StoredProcName := 'CN_TMP_SCAN_PRINT_ALL_I'; ParamByName('ID_SESSION').AsInt64 := Id_session; ParamByName('ID_DOG').AsInt64 := DM_Detail_1.DataSet['ID_DOG']; Prepare; ExecProc; Transaction.Commit; except on E:Exception do begin ShowMessage('Error in CN_TMP_SCAN_PRINT_ALL_I'); Transaction.Rollback; break; raise; end; end; DM_Detail_1.DataSet.Next; end; // отбор данных печати DM2.DataSet.SQLs.SelectSQL.Text := 'select * from CN_TMP_SCAN_PRINT_SELECT(' + inttostr(Id_session) + ',' + inttostr(CN_IMAGE_PRINT_PAGE_LIMIT) +')'; db_imgPicture.DataSource := DM2.DataSource; DM2.DataSet.Open; DM2.DataSet.FetchAll; DM2.DataSet.First; k:=0; for i:= 0 to DM2.DataSet.RecordCount-1 do begin case PrintValue of 0: begin mcmPrinter.AddPage; mcmPrinter.Pages[i].Assign(db_imgPicture.Image); end; 2: if ( DM2.DataSet['NUM_PAGE'] mod 2 = 0) then begin mcmPrinter.AddPage; mcmPrinter.Pages[k].Assign(db_imgPicture.Image); k:=k+1; end; 1: if ( DM2.DataSet['NUM_PAGE'] mod 2 <> 0) then begin mcmPrinter.AddPage; mcmPrinter.Pages[k].Assign(db_imgPicture.Image); k:=k+1; end; end; DM2.DataSet.Next; end; // удаляю сессию with DM2.StProc do try Transaction.StartTransaction; StoredProcName := 'CN_TMP_SCAN_PRINT_ALL_D'; ParamByName('ID_SESSION').AsInt64 := Id_session; Prepare; ExecProc; Transaction.Commit; except on E:Exception do begin ShowMessage('Error in CN_TMP_SCAN_PRINT_ALL_D'); Transaction.Rollback; raise; end; end; if (mcmPrinter.PageCount > 0) then begin mcmPrinter.ImageFitToPage := True; mcmPrinter.ImageCenter := True; mcmPrinter.ForceMargin := true; mcmPrinter.MarginLeft := 0; mcmPrinter.MarginTop := 0; mcmPrinter.MarginRight := 0; mcmPrinter.MarginBottom := 0; mcmPrinter.Print; end; end; procedure TfrmCredit.btnViewClick(Sender: TObject); begin Facul_Col.GroupIndex := StrToInt(BoolToStr(not StrToBool(IntToStr(Facul_Col.GroupIndex)))); end; procedure TfrmCredit.btnPrintOptionsClick(Sender: TObject); begin // Access printer set-up dialogue. if PrinterSetupDialog.Execute then mcmPrinter.RefreshProperties; InvalidateRect(Handle, Nil, True); end; procedure TfrmCredit.btnPrintRangeClick(Sender: TObject); var frmRange: TfrmRange; PrintValue : Integer; begin frmRange := TfrmRange.Create(self); frmRange.PLanguageIndex := PLanguageIndex; frmRange.OKButton.Caption := cn_Accept[PLanguageIndex]; frmRange.CancelButton.Caption := cn_Cancel[PLanguageIndex]; frmRange.Caption := cn_PrintRangeImage[PLanguageIndex]; frmRange.radAll.Caption := cn_PrintAllPages[PLanguageIndex]; frmRange.radChet.Caption := cn_PrintChetPages[PLanguageIndex]; frmRange.radNechet.Caption := cn_PrintNeChetPages[PLanguageIndex]; frmRange.REndEdit.Value := Grid2View.DataController.Summary.FooterSummaryValues[1]; if frmRange.ShowModal = mrOk then begin if frmRange.radAll.Checked then PrintValue := 0; // 'all'; if frmRange.radChet.Checked then PrintValue := 2; //'chet'; if frmRange.radNechet.Checked then PrintValue := 1; // 'nechet'; PrintImageEx(Self, True, StrToInt(frmRange.RBegEdit.Text) , StrToInt(frmRange.REndEdit.Text), PrintValue); end; end; procedure TfrmCredit.btnPrintImageClick(Sender: TObject); begin PrintImageEx(Self, false,0,0,0); end; end.
unit SortForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Menus, InflatablesList_Types, InflatablesList_Manager; type TfSortForm = class(TForm) lblProfiles: TLabel; lbProfiles: TListBox; btnProfileLoad: TButton; btnLoadDefault: TButton; btnClear: TButton; btnProfileSave: TButton; pmnProfiles: TPopupMenu; pmi_PR_Add: TMenuItem; pmi_PR_Remove: TMenuItem; pmi_PR_Rename: TMenuItem; N1: TMenuItem; pmi_PR_MoveUp: TMenuItem; pmi_PR_MoveDown: TMenuItem; lblSortBy: TLabel; lbSortBy: TListBox; lblAvailable: TLabel; lbAvailable: TListBox; btnMoveUp: TButton; btnAdd: TButton; btnToggleOrder: TButton; btnRemove: TButton; btnMoveDown: TButton; bvlSplitter: TBevel; cbSortCase: TCheckBox; cbSortRev: TCheckBox; btnSort: TButton; btnClose: TButton; procedure FormCreate(Sender: TObject); procedure lbProfilesClick(Sender: TObject); procedure lbProfilesDblClick(Sender: TObject); procedure lbProfilesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure btnProfileLoadClick(Sender: TObject); procedure btnLoadDefaultClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnProfileSaveClick(Sender: TObject); procedure pmnProfilesPopup(Sender: TObject); procedure pmi_PR_AddClick(Sender: TObject); procedure pmi_PR_RenameClick(Sender: TObject); procedure pmi_PR_RemoveClick(Sender: TObject); procedure pmi_PR_MoveUpClick(Sender: TObject); procedure pmi_PR_MoveDownClick(Sender: TObject); procedure lbSortByDblClick(Sender: TObject); procedure btnMoveUpClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnToggleOrderClick(Sender: TObject); procedure btnRemoveClick(Sender: TObject); procedure btnMoveDownClick(Sender: TObject); procedure lbAvailableDblClick(Sender: TObject); procedure cbSortCaseClick(Sender: TObject); procedure cbSortRevClick(Sender: TObject); procedure btnSortClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); private { Private declarations } fInitializing: Boolean; fILManager: TILManager; fLocalSortSett: TILSortingSettings; fSorted: Boolean; protected procedure FillSortByList(Init: Boolean); procedure UpdateNumbers; public { Public declarations } procedure Initialize(ILManager: TILManager); procedure Finalize; Function ShowSortingSettings: Boolean; end; var fSortForm: TfSortForm; implementation uses PromptForm, InflatablesList_Utils; {$R *.dfm} procedure TfSortForm.FillSortByList(Init: Boolean); var OldIndex: Integer; i: Integer; begin OldIndex := lbSortBy.ItemIndex; lbSortBy.Items.BeginUpdate; try lbSortBy.Clear; For i := 0 to Pred(fLocalSortSett.Count) do lbSortBy.Items.Add(fILManager.SortingItemStr(fLocalSortSett.Items[i])); finally lbSortBy.Items.EndUpdate; end; If lbSortBy.Count > 0 then begin If (OldIndex >= lbSortBy.Count) or (OldIndex < 0) or Init then lbSortBy.ItemIndex := 0 else lbSortBy.ItemIndex := OldIndex; end; UpdateNumbers; end; //------------------------------------------------------------------------------ procedure TfSortForm.UpdateNumbers; begin lblSortBy.Caption := IL_Format('Sort by values (%d/30):',[fLocalSortSett.Count]); end; //============================================================================== procedure TfSortForm.Initialize(ILManager: TILManager); var i: TILItemValueTag; begin fInitializing := False; fILManager := ILManager; // fill list of available values lbAvailable.Items.BeginUpdate; try lbAvailable.Clear; For i := Low(TILItemValueTag) to High(TILItemValueTag) do lbAvailable.Items.Add(fILManager.DataProvider.GetItemValueTagString(i)); finally lbAvailable.Items.EndUpdate; end; If lbAvailable.Count > 0 then lbAvailable.ItemIndex := 0; end; //------------------------------------------------------------------------------ procedure TfSortForm.Finalize; begin // nothing to do here end; //------------------------------------------------------------------------------ Function TfSortForm.ShowSortingSettings: Boolean; var i: Integer; begin fLocalSortSett := fILManager.ActualSortingSettings; fSorted := False; // fill list of profiles lbProfiles.Items.BeginUpdate; try lbProfiles.Clear; For i := 0 to Pred(fILManager.SortingProfileCount) do lbProfiles.Items.Add(IL_Format('%s (%d)', [fILManager.SortingProfiles[i].Name,fILManager.SortingProfiles[i].Settings.Count])); finally lbProfiles.Items.EndUpdate; end; If lbProfiles.Count > 0 then lbProfiles.ItemIndex := 0; lbProfiles.OnClick(nil); // fill list of used FillSortByList(True); fInitializing := True; try cbSortCase.Checked := fILManager.CaseSensitiveSort; cbSortRev.Checked := fILManager.ReversedSort; finally fInitializing := False; end; // show the window ShowModal; fILManager.ActualSortingSettings := fLocalSortSett; Result := fSorted; end; //============================================================================== procedure TfSortForm.FormCreate(Sender: TObject); begin pmi_PR_MoveUp.ShortCut := ShortCut(VK_UP,[ssShift]); pmi_PR_MoveDown.ShortCut := ShortCut(VK_DOWN,[ssShift]); end; //------------------------------------------------------------------------------ procedure TfSortForm.lbProfilesClick(Sender: TObject); begin btnProfileLoad.Enabled := lbProfiles.ItemIndex >= 0; btnProfileSave.Enabled := lbProfiles.ItemIndex >= 0; end; //------------------------------------------------------------------------------ procedure TfSortForm.lbProfilesDblClick(Sender: TObject); begin If lbProfiles.ItemIndex >= 0 then btnProfileLoad.OnClick(nil); end; //------------------------------------------------------------------------------ procedure TfSortForm.lbProfilesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Index: Integer; begin If Button = mbRight then begin Index := lbProfiles.ItemAtPos(Point(X,Y),True); If Index >= 0 then begin lbProfiles.ItemIndex := Index; lbProfiles.OnClick(nil); end; end; end; //------------------------------------------------------------------------------ procedure TfSortForm.btnProfileLoadClick(Sender: TObject); begin If lbProfiles.ItemIndex >= 0 then begin fLocalSortSett := fILManager.SortingProfiles[lbProfiles.ItemIndex].Settings; FillSortByList(False); end; end; //------------------------------------------------------------------------------ procedure TfSortForm.btnLoadDefaultClick(Sender: TObject); begin fLocalSortSett := fILManager.DefaultSortingSettings; FillSortByList(False); end; //------------------------------------------------------------------------------ procedure TfSortForm.btnClearClick(Sender: TObject); var i: Integer; begin fLocalSortSett.Count := 0; For i := Low(fLocalSortSett.Items) to High(fLocalSortSett.Items) do begin fLocalSortSett.Items[i].ItemValueTag := ilivtNone; fLocalSortSett.Items[i].Reversed := False; end; FillSortByList(False); end; //------------------------------------------------------------------------------ procedure TfSortForm.btnProfileSaveClick(Sender: TObject); var Temp: TILSortingProfile; CanContinue: Boolean; begin If lbProfiles.ItemIndex >= 0 then begin Temp := fILManager.SortingProfiles[lbProfiles.ItemIndex]; If Temp.Settings.Count > 0 then begin If not IL_SameSortingSettings(Temp.Settings,fLocalSortSett) then CanContinue := MessageDlg(IL_Format('Overwrite sorting settings in profile "%s"?', [Temp.Name]),mtConfirmation,[mbYes,mbNo],0) = mrYes else CanContinue := False; // do not save the same data... end else CanContinue := True; // empty profile, just save without asking If CanContinue then begin Temp.Settings := fLocalSortSett; fILManager.SortingProfiles[lbProfiles.ItemIndex] := Temp; lbProfiles.Items[lbProfiles.ItemIndex] := IL_Format('%s (%d)',[Temp.Name,Temp.Settings.Count]); end; end; end; //------------------------------------------------------------------------------ procedure TfSortForm.pmnProfilesPopup(Sender: TObject); begin pmi_PR_Rename.Enabled := lbProfiles.ItemIndex >= 0; pmi_PR_Remove.Enabled := lbProfiles.ItemIndex >= 0; pmi_PR_MoveUp.Enabled := lbProfiles.ItemIndex > 0; pmi_PR_MoveDown.Enabled := (lbProfiles.Count > 0) and (lbProfiles.ItemIndex < Pred(lbProfiles.Count)); end; //------------------------------------------------------------------------------ procedure TfSortForm.pmi_PR_AddClick(Sender: TObject); var ProfileName: String; begin If IL_InputQuery('Sorting profile name','Enter name for the new sorting profile:',ProfileName) then begin If Length(ProfileName) > 0 then begin fILManager.SortingProfileAdd(ProfileName); lbProfiles.Items.Add(IL_Format('%s (%d)', [ProfileName,fILManager.SortingProfiles[Pred(fILManager.SortingProfileCount)].Settings.Count])); lbProfiles.ItemIndex := Pred(lbProfiles.Count); lbProfiles.OnClick(nil); end else MessageDlg('Empty name not allowed.',mtError,[mbOK],0); end; end; //------------------------------------------------------------------------------ procedure TfSortForm.pmi_PR_RenameClick(Sender: TObject); var ProfileName: String; begin If lbProfiles.ItemIndex >= 0 then begin ProfileName := fILManager.SortingProfiles[lbProfiles.ItemIndex].Name; If IL_InputQuery('Sorting profile name','Enter new sorting profile name:',ProfileName) then begin If Length(ProfileName) > 0 then begin fILManager.SortingProfileRename(lbProfiles.ItemIndex,ProfileName); lbProfiles.Items[lbProfiles.ItemIndex] := IL_Format('%s (%d)', [ProfileName,fILManager.SortingProfiles[lbProfiles.ItemIndex].Settings.Count]); end else MessageDlg('Empty name not allowed.',mtError,[mbOK],0); end; end; end; //------------------------------------------------------------------------------ procedure TfSortForm.pmi_PR_RemoveClick(Sender: TObject); var Index: Integer; begin If lbProfiles.ItemIndex >= 0 then If MessageDlg(IL_Format('Are you sure you want to remove the sorting profile "%s"?', [fILManager.SortingProfiles[lbProfiles.ItemIndex].Name]), mtConfirmation,[mbYes,mbNo],0) = mrYes then begin Index := lbProfiles.ItemIndex; If lbProfiles.ItemIndex < Pred(lbProfiles.Count) then lbProfiles.ItemIndex := lbProfiles.ItemIndex + 1 else If lbProfiles.ItemIndex > 0 then lbProfiles.ItemIndex := lbProfiles.ItemIndex - 1 else lbProfiles.ItemIndex := -1; lbProfiles.OnClick(nil); lbProfiles.Items.Delete(Index); fILManager.SortingProfileDelete(Index); end; end; //------------------------------------------------------------------------------ procedure TfSortForm.pmi_PR_MoveUpClick(Sender: TObject); var Index: Integer; begin If lbProfiles.ItemIndex > 0 then begin Index := lbProfiles.ItemIndex; lbProfiles.Items.Exchange(Index,Index - 1); fILManager.SortingProfileExchange(Index,Index - 1); lbProfiles.ItemIndex := Index - 1; lbProfiles.OnClick(nil); end; end; //------------------------------------------------------------------------------ procedure TfSortForm.pmi_PR_MoveDownClick(Sender: TObject); var Index: Integer; begin If (lbProfiles.Count > 0) and (lbProfiles.ItemIndex < Pred(lbProfiles.Count)) then begin Index := lbProfiles.ItemIndex; lbProfiles.Items.Exchange(Index,Index + 1); fILManager.SortingProfileExchange(Index,Index + 1); lbProfiles.ItemIndex := Index + 1; lbProfiles.OnClick(nil); end; end; //------------------------------------------------------------------------------ procedure TfSortForm.lbSortByDblClick(Sender: TObject); begin btnRemove.OnClick(nil); end; //------------------------------------------------------------------------------ procedure TfSortForm.btnMoveUpClick(Sender: TObject); var Temp: TILSortingItem; begin If (lbSortBy.ItemIndex > 0) then begin Temp := fLocalSortSett.Items[lbSortBy.ItemIndex]; fLocalSortSett.Items[lbSortBy.ItemIndex] := fLocalSortSett.Items[lbSortBy.ItemIndex - 1]; fLocalSortSett.Items[lbSortBy.ItemIndex - 1] := Temp; lbSortBy.Items[lbSortBy.ItemIndex] := fILManager.SortingItemStr(fLocalSortSett.Items[lbSortBy.ItemIndex]); lbSortBy.Items[lbSortBy.ItemIndex - 1] := fILManager.SortingItemStr(fLocalSortSett.Items[lbSortBy.ItemIndex - 1]); lbSortBy.ItemIndex := lbSortBy.ItemIndex - 1; end; end; //------------------------------------------------------------------------------ procedure TfSortForm.btnAddClick(Sender: TObject); begin If (lbAvailable.ItemIndex > 0) and (fLocalSortSett.Count < Length(fLocalSortSett.Items)) then begin fLocalSortSett.Items[fLocalSortSett.Count].ItemValueTag := TILItemValueTag(lbAvailable.ItemIndex); fLocalSortSett.Items[fLocalSortSett.Count].Reversed := False; lbSortBy.Items.Add(fILManager.SortingItemStr(fLocalSortSett.Items[fLocalSortSett.Count])); lbSortBy.ItemIndex := Pred(lbSortBy.Count); Inc(fLocalSortSett.Count); UpdateNumbers; end; end; //------------------------------------------------------------------------------ procedure TfSortForm.btnToggleOrderClick(Sender: TObject); begin If (lbSortBy.ItemIndex >= 0) then begin fLocalSortSett.Items[lbSortBy.ItemIndex].Reversed := not fLocalSortSett.Items[lbSortBy.ItemIndex].Reversed; lbSortBy.Items[lbSortBy.ItemIndex] := fILManager.SortingItemStr(fLocalSortSett.Items[lbSortBy.ItemIndex]); end; end; //------------------------------------------------------------------------------ procedure TfSortForm.btnRemoveClick(Sender: TObject); var i,Index: Integer; begin If (lbSortBy.ItemIndex >= 0) then begin For i := lbSortBy.ItemIndex to (fLocalSortSett.Count - 2) do fLocalSortSett.Items[i] := fLocalSortSett.Items[i + 1]; Dec(fLocalSortSett.Count); Index := lbSortBy.ItemIndex; If lbSortBy.ItemIndex < Pred(lbSortBy.Count) then lbSortBy.ItemIndex := lbSortBy.ItemIndex + 1 else If lbSortBy.ItemIndex > 0 then lbSortBy.ItemIndex := lbSortBy.ItemIndex - 1 else lbSortBy.ItemIndex := -1; lbSortBy.Items.Delete(Index); UpdateNumbers; end; end; //------------------------------------------------------------------------------ procedure TfSortForm.btnMoveDownClick(Sender: TObject); var Temp: TILSortingItem; begin If (lbSortBy.ItemIndex < Pred(lbSortBy.Count)) then begin Temp := fLocalSortSett.Items[lbSortBy.ItemIndex]; fLocalSortSett.Items[lbSortBy.ItemIndex] := fLocalSortSett.Items[lbSortBy.ItemIndex + 1]; fLocalSortSett.Items[lbSortBy.ItemIndex + 1] := Temp; lbSortBy.Items[lbSortBy.ItemIndex] := fILManager.SortingItemStr(fLocalSortSett.Items[lbSortBy.ItemIndex]); lbSortBy.Items[lbSortBy.ItemIndex + 1] := fILManager.SortingItemStr(fLocalSortSett.Items[lbSortBy.ItemIndex + 1]); lbSortBy.ItemIndex := lbSortBy.ItemIndex + 1; end; end; //------------------------------------------------------------------------------ procedure TfSortForm.lbAvailableDblClick(Sender: TObject); begin btnAdd.OnClick(nil); end; //------------------------------------------------------------------------------ procedure TfSortForm.cbSortCaseClick(Sender: TObject); begin If not fInitializing then fILManager.CaseSensitiveSort := cbSortCase.Checked; end; //------------------------------------------------------------------------------ procedure TfSortForm.cbSortRevClick(Sender: TObject); begin If not fInitializing then fILManager.ReversedSort := cbSortRev.Checked; end; //------------------------------------------------------------------------------ procedure TfSortForm.btnSortClick(Sender: TObject); begin Screen.Cursor := crHourGlass; try fSorted := True; fILManager.ActualSortingSettings := fLocalSortSett; fILManager.ItemSort; finally Screen.Cursor := crDefault; end; Close; end; //------------------------------------------------------------------------------ procedure TfSortForm.btnCloseClick(Sender: TObject); begin Close; end; end.
unit CCJAL_CreateUserMsg; {*********************************************** * © PgkSoft 05.10.2015 * Журнал интернет заказов * Механизм <Центр уведомлений> * Создание пользовательского уведомления ***********************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ToolWin, ComCtrls, ActnList, DB, ADODB; type TfrmCCJAL_CreateUserMsg = class(TForm) pnlTop: TPanel; pnlControl: TPanel; pnlControl_Tool: TPanel; pnlControl_Show: TPanel; pnlParm: TPanel; ActionList: TActionList; tbarControl: TToolBar; rgrpWhom: TRadioGroup; lblWhom: TLabel; lblTopic: TLabel; lblContent: TLabel; edWhom: TEdit; edTopic: TEdit; edContent: TMemo; aChooseUser: TAction; aChooseTopic: TAction; aCreate: TAction; aExit: TAction; tbtnControl_Create: TToolButton; tbtnControl_Exit: TToolButton; btnChooseUser: TButton; btnChooseTopic: TButton; spCreate: TADOStoredProc; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure rgrpWhomClick(Sender: TObject); procedure edWhomChange(Sender: TObject); procedure edTopicChange(Sender: TObject); procedure edContentChange(Sender: TObject); procedure aChooseUserExecute(Sender: TObject); procedure aChooseTopicExecute(Sender: TObject); procedure edWhomDblClick(Sender: TObject); procedure edTopicDblClick(Sender: TObject); procedure aCreateExecute(Sender: TObject); procedure aExitExecute(Sender: TObject); private { Private declarations } ISignActivate : integer; NUSER : integer; SUSER : string; NChooseUser : integer; NChooseTopic : integer; procedure ShowGets; public { Public declarations } procedure SetUser(NParm : integer; SParm : string); end; var frmCCJAL_CreateUserMsg: TfrmCCJAL_CreateUserMsg; implementation uses UMain, UCCenterJournalNetZkz, UReference; {$R *.dfm} procedure TfrmCCJAL_CreateUserMsg.FormCreate(Sender: TObject); begin ISignActivate := 0; NChooseUser := 0; NChooseTopic := 0; end; procedure TfrmCCJAL_CreateUserMsg.FormActivate(Sender: TObject); begin if ISignActivate = 0 then begin { Иконка формы } FCCenterJournalNetZkz.imgMain.GetIcon(322,self.Icon); { Инициализация } pnlTop.Caption := 'От пользователя: ' + SUSER; { Форма активна } ISignActivate := 1; ShowGets; end; end; procedure TfrmCCJAL_CreateUserMsg.ShowGets; procedure Whom(Enb : boolean); begin lblWhom.Enabled := Enb; edWhom.Enabled := Enb; aChooseUser.Enabled := Enb; btnChooseUser.Enabled := Enb; if not Enb then begin edWhom.Text := ''; NChooseUser := 0; end; end; begin if ISignActivate = 1 then begin { Доступ к выбору конкретного пользователя } if rgrpWhom.ItemIndex = 0 then Whom(true) else Whom(False); { Доступ к созданию нового уведомления } if ( (rgrpWhom.ItemIndex <> 0) and ( (length(edContent.Text) = 0) or (length(edTopic.Text) = 0) ) ) or ( (rgrpWhom.ItemIndex = 0) and ( (length(edContent.Text) = 0) or (length(edTopic.Text) = 0) or (length(edWhom.Text) = 0) ) ) then tbtnControl_Create.Enabled := false else tbtnControl_Create.Enabled := true; end; end; procedure TfrmCCJAL_CreateUserMsg.SetUser(NParm : integer; SParm : string); begin NUSER := NParm; SUSER := SPArm; end; procedure TfrmCCJAL_CreateUserMsg.rgrpWhomClick(Sender: TObject); begin ShowGets; end; procedure TfrmCCJAL_CreateUserMsg.edWhomChange(Sender: TObject); begin ShowGets; end; procedure TfrmCCJAL_CreateUserMsg.edTopicChange(Sender: TObject); begin ShowGets; end; procedure TfrmCCJAL_CreateUserMsg.edContentChange(Sender: TObject); begin ShowGets; end; procedure TfrmCCJAL_CreateUserMsg.aChooseUserExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFReferenceUserAva); frmReference.SetReadOnly(cFReferenceYesReadOnly); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then begin edWhom.Text := DescrSelect; NChooseUser := frmReference.GetRowIDSelect; end; finally frmReference.Free; end; except end; end; procedure TfrmCCJAL_CreateUserMsg.aChooseTopicExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFRefAlertUserType); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then begin edTopic.Text := DescrSelect; NChooseTopic := frmReference.GetRowIDSelect; end; finally frmReference.Free; end; except end; end; procedure TfrmCCJAL_CreateUserMsg.edWhomDblClick(Sender: TObject); begin if aChooseUser.Enabled then aChooseUser.Execute; end; procedure TfrmCCJAL_CreateUserMsg.edTopicDblClick(Sender: TObject); begin if aChooseTopic.Enabled then aChooseTopic.Execute; end; procedure TfrmCCJAL_CreateUserMsg.aCreateExecute(Sender: TObject); var IErr : integer; SErr : string; begin if MessageDLG('Подтвердите выполнение операции.',mtConfirmation,[mbYes,mbNo],0) = mrNo then exit; IErr := 0; SErr := ''; try spCreate.Parameters.ParamValues['@UserFrom'] := NUSER; if rgrpWhom.ItemIndex = 0 then spCreate.Parameters.ParamValues['@UserWhom'] := NChooseUser; spCreate.Parameters.ParamValues['@SignWhom'] := rgrpWhom.ItemIndex; spCreate.Parameters.ParamValues['@UserTopic'] := NChooseTopic; spCreate.Parameters.ParamValues['@Content'] := edContent.Text; spCreate.ExecProc; IErr := spCreate.Parameters.ParamValues['@RETURN_VALUE']; if IErr <> 0 then begin SErr := spCreate.Parameters.ParamValues['@SErr']; ShowMessage(SErr); end else self.Close; except on e:Exception do begin ShowMessage('Сбой при выполнении операции.' + chr(10) + e.Message); end; end; end; procedure TfrmCCJAL_CreateUserMsg.aExitExecute(Sender: TObject); begin Self.Close; end; end.
unit Invoice.Model.Windows; interface uses Invoice.Model.Windows.Interfaces, Winapi.Windows, Winapi.Messages, Vcl.Dialogs, Vcl.Forms, System.SysUtils, System.Variants, System.Classes, System.UITypes, System.IniFiles; type TModelWindows = class(TInterfacedObject, iModelWindows) constructor Create; destructor Destroy; override; class function New: iModelWindows; function GetWindowsUserName: String; function GetWindowsComputerName: String; function GetAppInfo(AppInfo: String): String; function FileINI(FileName: String; Sector: String; Key: String; Value: String): String; end; implementation function TModelWindows.GetWindowsComputerName: String; var Name: Array [0 .. 255] of Char; NameSize: Dword; begin NameSize := SizeOf(Name); if not GetUserName(Name, NameSize) then Name[0] := #0; result := UpperCase(StrPas(Name)); end; function TModelWindows.GetWindowsUserName: String; var Name: Array [0 .. 255] of Char; NameSize: Dword; begin NameSize := SizeOf(Name); if not GetUserName(Name, NameSize) then Name[0] := #0; result := UpperCase(StrPas(Name)); end; class function TModelWindows.New: iModelWindows; begin Result := Self.Create; end; function TModelWindows.GetAppInfo(AppInfo: String): String; var ExeApp: String; SizeOf: Integer; Buf: pchar; Value: pchar; Tmp1, Tmp2: Dword; begin { 'CompanyName', 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright', 'LegalTradeMarks', 'OriginalFilename', 'ProductName', 'ProductVersion', 'Comments' } ExeApp := Application.ExeName; SizeOf := GetFileVersionInfoSize(pchar(ExeApp), Tmp1); result := ''; if (SizeOf > 0) then begin Buf := AllocMem(SizeOf); // if GetFileVersionInfo(pchar(ExeApp), 0, SizeOf, Buf) then if VerQueryValue(Buf, pchar('StringFileInfo\041604E4\' + AppInfo), pointer(Value), Tmp2) then result := Value else if VerQueryValue(Buf, pchar('StringFileInfo\040904E4\' + AppInfo), pointer(Value), Tmp2) then result := Value else result := ''; // FreeMem(Buf, SizeOf); end; end; constructor TModelWindows.Create; begin // end; destructor TModelWindows.Destroy; begin inherited; end; function TModelWindows.FileINI(FileName: String; Sector: String; Key: String; Value: String): String; var MyIniFile: TIniFile; InputString: string; begin MyIniFile := Nil; // try MyIniFile := TIniFile.Create(FileName); // if not MyIniFile.ValueExists(Sector, Key) then begin InputString := InputBox('Key of Record [' + Sector + ']', Key, Value); // MyIniFile.WriteString(Sector, Key, InputString); end; // try result := Trim(MyIniFile.ReadString(Sector, Key, '')); except result := ''; end; finally MyIniFile.Free; end; end; end.
unit ShopsForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, Spin, Menus, ShopFrame, InflatablesList_Item, InflatablesList_Manager; const LI_WM_USER_LVITEMSELECTED = WM_USER + 234; type TfShopsForm = class(TForm) lblShops: TLabel; lblLegend: TLabel; lvShops: TListView; gbShopDetails: TGroupBox; lePriceLowest: TLabeledEdit; lePriceSelected: TLabeledEdit; btnUpdateAll: TButton; btnUpdateHistory: TButton; btnClose: TButton; pmnShops: TPopupMenu; mniSH_Add: TMenuItem; mniSH_AddFromSub: TMenuItem; mniSH_AddFromTemplate: TMenuItem; mniSH_Remove: TMenuItem; mniSH_RemoveAll: TMenuItem; N1: TMenuItem; mniSH_MoveUp: TMenuItem; mniSH_MoveDown: TMenuItem; frmShopFrame: TfrmShopFrame; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure lvShopsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure lvShopsDblClick(Sender: TObject); procedure pmnShopsPopup(Sender: TObject); procedure mniSH_AddCommon; procedure mniSH_AddClick(Sender: TObject); procedure mniSH_AddFromSubClick(Sender: TObject); procedure mniSH_AddFromTemplateClick(Sender: TObject); procedure mniSH_RemoveClick(Sender: TObject); procedure mniSH_RemoveAllClick(Sender: TObject); procedure mniSH_MoveUpClick(Sender: TObject); procedure mniSH_MoveDownClick(Sender: TObject); procedure btnUpdateAllClick(Sender: TObject); procedure btnUpdateHistoryClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); private fWndCaption: String; fILManager: TILManager; fCurrentItem: TILItem; protected // item event handlers (manager) procedure ItemShopListUpdateHandler(Sender: TObject; Item: TObject); procedure ItemValuesUpdateHandler(Sender: TObject; Shop: TObject); // shop event handlers (manager) procedure ShopListItemUpdateHandler(Sender: TObject; Item: TObject; Shop: TObject; Index: Integer); // shop frame event handlers procedure TemplateChangeHandler(Sender: TObject); // other methods procedure BuildAddFromSubMenu; procedure ShopListSelect(ItemIndex: Integer); procedure UpdateCurrentListItem; procedure UpdateShopCounts; procedure UpdateShopIndex; procedure ListViewItemSelected(var Msg: TMessage); overload; message LI_WM_USER_LVITEMSELECTED; procedure ListViewItemSelected; overload; public procedure Initialize(ILManager: TILManager); procedure Finalize; procedure ShowShops(Item: TILItem); end; var fShopsForm: TfShopsForm; implementation uses AuxTypes, TemplatesForm, UpdateForm, InflatablesList_Types, InflatablesList_Utils, InflatablesList_LocalStrings; {$R *.dfm} procedure TfShopsForm.ItemShopListUpdateHandler(Sender: TObject; Item: TObject); var i: Integer; begin If Assigned(fCurrentItem) and (Item = fCurrentItem) then begin lvShops.Items.BeginUpdate; try // adjust count If lvShops.Items.Count > fCurrentItem.ShopCount then begin For i := Pred(lvShops.Items.Count) downto fCurrentItem.ShopCount do lvShops.Items.Delete(i); end else If lvShops.Items.Count < fCurrentItem.ShopCount then begin For i := Succ(lvShops.Items.Count) to fCurrentItem.ShopCount do with lvShops.Items.Add do begin Caption := ''; SubItems.Add(''); SubItems.Add(''); SubItems.Add(''); SubItems.Add(''); end; end; // fill items For i := fCurrentItem.ShopLowIndex to fCurrentItem.ShopHighIndex do ShopListItemUpdateHandler(nil,fCurrentItem,nil,i); finally lvShops.Items.EndUpdate; end; end; UpdateShopCounts; end; //------------------------------------------------------------------------------ procedure TfShopsForm.ItemValuesUpdateHandler(Sender: TObject; Shop: TObject); begin If Assigned(fCurrentItem) and (Shop = fCurrentItem) then begin // show prices If fCurrentItem.UnitPriceLowest > 0 then lePriceLowest.Text := IL_Format('%d %s',[fCurrentItem.UnitPriceLowest,IL_CURRENCY_SYMBOL]) else lePriceLowest.Text := '-'; If fCurrentItem.UnitPriceSelected > 0 then begin lePriceSelected.Text := IL_Format('%d %s',[fCurrentItem.UnitPriceSelected,IL_CURRENCY_SYMBOL]); If (fCurrentItem.UnitPriceSelected <> fCurrentItem.UnitPriceLowest) and (fCurrentItem.UnitPriceLowest > 0) then lePriceSelected.Color := clYellow else lePriceSelected.Color := clWindow; end else begin lePriceSelected.Text := '-'; lePriceSelected.Color := clWindow; end; UpdateShopCounts; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.ShopListItemUpdateHandler(Sender: TObject; Item: TObject; Shop: TObject; Index: Integer); begin If Assigned(fCurrentItem) and (Item = fCurrentItem) and (Index >= 0) and (Index < lvShops.Items.Count) then with lvShops.Items[Index] do begin Caption := IL_Format('%s%s%s',[ IL_BoolToStr(fCurrentItem.Shops[Index].Selected,'','*'), IL_BoolToStr(fCurrentItem.Shops[Index].Untracked,'','^'), IL_BoolToStr((fCurrentItem.Shops[Index].LastUpdateRes >= fCurrentItem.ShopsWorstUpdateResult) and (fCurrentItem.Shops[Index].LastUpdateRes <> ilisurSuccess),'','!')]); SubItems[0] := fCurrentItem.Shops[Index].Name; SubItems[1] := fCurrentItem.Shops[Index].ItemURL; // avail If fCurrentItem.Shops[Index].Available < 0 then SubItems[2] := IL_Format('more than %d',[Abs(fCurrentItem.Shops[Index].Available)]) else If fCurrentItem.Shops[Index].Available > 0 then SubItems[2] := IL_Format('%d',[Abs(fCurrentItem.Shops[Index].Available)]) else SubItems[2] := '-'; // price If fCurrentItem.Shops[Index].Price > 0 then SubItems[3] := IL_Format('%d %s',[fCurrentItem.Shops[Index].Price,IL_CURRENCY_SYMBOL]) else SubItems[3] := '-'; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.TemplateChangeHandler(Sender: TObject); begin BuildAddFromSubMenu; end; //------------------------------------------------------------------------------ procedure TfShopsForm.BuildAddFromSubMenu; var i: Integer; Temp: TMenuItem; begin // first clear the submenu For i := Pred(mniSH_AddFromSub.Count) downto 0 do If mniSH_AddFromSub[i].Tag >= 0 then begin Temp := TMenuItem(mniSH_AddFromSub[i]); mniSH_AddFromSub.Delete(i); FreeAndNil(Temp); end; // recreate the menu For i := 0 to Pred(fILManager.ShopTemplateCount) do begin Temp := TMenuItem.Create(Self); Temp.Name := IL_Format('mniSH_AS_Template%d',[i]); Temp.Caption := fILManager.ShopTemplates[i].Name; Temp.OnClick := mniSH_AddFromSubClick; Temp.Tag := i; If (Pred(fILManager.ShopTemplateCount) - i) <= 9 then Temp.ShortCut := ShortCut(Ord('0') + (((Pred(fILManager.ShopTemplateCount) - i) + 1) mod 10),[ssCtrl]); mniSH_AddFromSub.Add(Temp); end; mniSH_AddFromSub.Enabled := mniSH_AddFromSub.Count > 0; end; //------------------------------------------------------------------------------ procedure TfShopsForm.ShopListSelect(ItemIndex: Integer); begin If (ItemIndex >= 0) and (ItemIndex < lvShops.Items.Count) then begin with lvShops.Items[ItemIndex] do begin Focused := True; Selected := True; end; lvShops.ItemIndex := ItemIndex; end else lvShops.ItemIndex := -1; end; //------------------------------------------------------------------------------ procedure TfShopsForm.UpdateCurrentListItem; begin If lvShops.ItemIndex >= 0 then ShopListItemUpdateHandler(nil,fCurrentItem,nil,lvShops.ItemIndex); UpdateShopCounts; end; //------------------------------------------------------------------------------ procedure TfShopsForm.UpdateShopCounts; begin If Assigned(fCurrentItem) then begin If fCurrentItem.ShopCount > 0 then Caption := IL_Format('%s (%s)',[fWndCaption,fCurrentItem.ShopsCountStr]) else Caption := fWndCaption; end else Caption := fWndCaption; end; //------------------------------------------------------------------------------ procedure TfShopsForm.UpdateShopIndex; begin If lvShops.ItemIndex < 0 then begin If lvShops.Items.Count > 0 then lblShops.Caption := IL_Format('Shops (%d):',[lvShops.Items.Count]) else lblShops.Caption := 'Shops:'; end else lblShops.Caption := IL_Format('Shops (%d/%d):',[lvShops.ItemIndex + 1,lvShops.Items.Count]); end; //------------------------------------------------------------------------------ procedure TfShopsForm.ListViewItemSelected(var Msg: TMessage); begin If Msg.Msg = LI_WM_USER_LVITEMSELECTED then ListViewItemSelected; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TfShopsForm.ListViewItemSelected; begin If Assigned(fCurrentItem) then begin If (lvShops.ItemIndex >= 0) then begin frmShopFrame.SetItemShop(fCurrentItem.Shops[lvShops.ItemIndex],True); lvShops.Selected.MakeVisible(False); end else frmShopFrame.SetItemShop(nil,True); end; UpdateShopIndex; end; //============================================================================== procedure TfShopsForm.Initialize(ILManager: TILManager); begin fILManager := ILManager; // shop events fILManager.OnShopListItemUpdate := ShopListItemUpdateHandler; // item events fILManager.OnItemShopListUpdate := ItemShopListUpdateHandler; fILManager.OnItemShopListValuesUpdate := ItemValuesUpdateHandler; frmShopFrame.Initialize(fILManager); frmShopFrame.OnTemplatesChange := TemplateChangeHandler; BuildAddFromSubMenu; end; //------------------------------------------------------------------------------ procedure TfShopsForm.Finalize; begin frmShopFrame.OnTemplatesChange := nil; fILManager.OnShopListItemUpdate := nil; fILManager.OnItemShopListUpdate := nil; fILManager.OnItemShopListValuesUpdate := nil; frmShopFrame.Finalize; end; //------------------------------------------------------------------------------ procedure TfShopsForm.ShowShops(Item: TILItem); var OldAvail: Int32; OldPrice: UInt32; OldFlags: TILItemFlags; begin If Assigned(Item) then begin OldAvail := Item.AvailableSelected; OldPrice := Item.UnitPriceSelected; OldFlags := Item.Flags; fCurrentItem := Item; fWndCaption := fCurrentItem.TitleStr + ' - Shops'; // fill list ItemShopListUpdateHandler(nil,fCurrentItem); ShopListSelect(0); ListViewItemSelected; ItemValuesUpdateHandler(nil,fCurrentItem); ShowModal; // <---- frmShopFrame.SetItemShop(nil,True); // manage flags If not(ilifPriceChange in OldFlags) then fCurrentItem.SetFlagValue(ilifPriceChange,False); If not(ilifAvailChange in OldFlags) then fCurrentItem.SetFlagValue(ilifAvailChange,False); If not(ilifNotAvailable in OldFlags) then fCurrentItem.SetFlagValue(ilifNotAvailable,False); fCurrentItem.GetAndFlagPriceAndAvail(OldPrice,OldAvail); end; end; //============================================================================== procedure TfShopsForm.FormCreate(Sender: TObject); begin lvShops.DoubleBuffered := True; mniSH_MoveUp.ShortCut := Shortcut(VK_UP,[ssShift]); mniSH_MoveDown.ShortCut := Shortcut(VK_Down,[ssShift]); end; //------------------------------------------------------------------------------ procedure TfShopsForm.FormShow(Sender: TObject); begin lvShops.SetFocus; end; //------------------------------------------------------------------------------ procedure TfShopsForm.lvShopsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin //this deffers reaction to change and prevents flickering PostMessage(Handle,LI_WM_USER_LVITEMSELECTED,Ord(Selected),0); end; //------------------------------------------------------------------------------ procedure TfShopsForm.lvShopsDblClick(Sender: TObject); begin If (lvShops.ItemIndex >= 0) and Assigned(fCurrentItem) then begin frmShopFrame.Save; fCurrentItem[lvShops.ItemIndex].Selected := True; frmShopFrame.Load; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.pmnShopsPopup(Sender: TObject); begin mniSH_Remove.Enabled := lvShops.ItemIndex >= 0; mniSH_RemoveAll.Enabled := lvShops.Items.Count > 0; mniSH_MoveUp.Enabled := lvShops.ItemIndex > 0; mniSH_MoveDown.Enabled := (lvShops.ItemIndex >= 0) and (lvShops.ItemIndex < Pred(lvShops.Items.Count)); end; //------------------------------------------------------------------------------ procedure TfShopsForm.mniSH_AddCommon; var Index: Integer; begin If Assigned(fCurrentItem) then begin Index := fCurrentItem.ShopAdd; // this will also update the listing ShopListSelect(Index); ListViewItemSelected; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.mniSH_AddClick(Sender: TObject); begin mniSH_AddCommon; frmShopFrame.leShopName.SetFocus; end; //------------------------------------------------------------------------------ procedure TfShopsForm.mniSH_AddFromSubClick(Sender: TObject); begin If Assigned(fCurrentItem) and (Sender is TMenuItem) then begin mniSH_AddCommon; If lvShops.ItemIndex >= 0 then begin // copy the settings from template fILManager.ShopTemplates[TMenuItem(Sender).Tag].CopyTo( fCurrentItem.Shops[lvShops.ItemIndex]); frmShopFrame.Load; frmShopFrame.leShopItemURL.SetFocus; end; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.mniSH_AddFromTemplateClick(Sender: TObject); var Index: Integer; begin If Assigned(fCurrentItem) then begin Index := fTemplatesForm.ShowTemplates(nil); frmShopFrame.Load(True); // only refill templates list BuildAddFromSubMenu; If Index >= 0 then begin mniSH_AddCommon; If lvShops.ItemIndex >= 0 then // should be valid after mniSH_AddCommon, but to be sure begin fILManager.ShopTemplates[Index].CopyTo(fCurrentItem.Shops[lvShops.ItemIndex]); frmShopFrame.Load; frmShopFrame.leShopItemURL.SetFocus; end; end; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.mniSH_RemoveClick(Sender: TObject); var Index: Integer; begin If Assigned(fCurrentItem) and (lvShops.ItemIndex >= 0) then If MessageDlg(IL_Format('Are you sure you want to remove shop "%s"?', [fCurrentItem.Shops[lvShops.ItemIndex].Name]), mtConfirmation,[mbYes,mbNo],0) = mrYes then begin If lvShops.ItemIndex < Pred(lvShops.Items.Count) then Index := lvShops.ItemIndex else If lvShops.ItemIndex > 0 then Index := lvShops.ItemIndex - 1 else Index := -1; frmShopFrame.SetItemShop(nil,False); fCurrentItem.ShopDelete(lvShops.ItemIndex); ShopListSelect(Index); ListViewItemSelected; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.mniSH_RemoveAllClick(Sender: TObject); begin If Assigned(fCurrentItem) and (lvShops.Items.Count > 0) then If MessageDlg('Are you sure you want to remove all shops?',mtWarning,[mbYes,mbNo],0) = mrYes then begin frmShopFrame.SetItemShop(nil,False); fCurrentItem.ShopClear; lvShops.Items.Clear; ShopListSelect(-1); ListViewItemSelected; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.mniSH_MoveUpClick(Sender: TObject); var Index: Integer; begin If Assigned(fCurrentItem) and (lvShops.ItemIndex > 0) then begin Index := lvShops.ItemIndex; fCurrentItem.ShopExchange(Index,Index - 1); ShopListSelect(Index - 1); ListViewItemSelected; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.mniSH_MoveDownClick(Sender: TObject); var Index: Integer; begin If Assigned(fCurrentItem) and (lvShops.ItemIndex >= 0) and (lvShops.ItemIndex < Pred(lvShops.Items.Count)) then begin Index := lvShops.ItemIndex; fCurrentItem.ShopExchange(Index,Index + 1); ShopListSelect(Index + 1); ListViewItemSelected; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.btnUpdateAllClick(Sender: TObject); var i: Integer; Temp: TILItemShopUpdateList; begin If Assigned(fCurrentItem) then begin If fCurrentItem.ShopCount > 0 then begin frmShopFrame.Save; SetLength(Temp,fCurrentItem.ShopCount); For i := Low(Temp) to High(Temp) do begin Temp[i].Item := fCurrentItem; Temp[i].ItemTitle := IL_Format('[#%d] %s',[fCurrentItem.Index + 1,fCurrentItem.TitleStr]); Temp[i].ItemShop := fCurrentItem.Shops[i]; Temp[i].Done := False; end; fUpdateForm.ShowUpdate(Temp); end else MessageDlg('No shop to update.',mtInformation,[mbOK],0); end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.btnUpdateHistoryClick(Sender: TObject); var i: Integer; begin If Assigned(fCurrentItem) then If fCurrentItem.ShopCount > 0 then begin frmShopFrame.Save; For i := fCurrentItem.ShopLowIndex to fCurrentItem.ShopHighIndex do fCurrentItem.Shops[i].UpdateAvailAndPriceHistory; end; end; //------------------------------------------------------------------------------ procedure TfShopsForm.btnCloseClick(Sender: TObject); begin Close; end; end.
//------------------------------------------------------------------------------ //QueryBase UNIT //------------------------------------------------------------------------------ // What it does- // Base class for query collections // // Changes - // February 11th, 2008 // //------------------------------------------------------------------------------ unit QueryBase; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} {Project} {3rd Party} ZConnection, ZSqlUpdate, ZDataset ; type //------------------------------------------------------------------------------ //TQueryBase CLASS //------------------------------------------------------------------------------ TQueryBase = class(TObject) protected Connection : TZConnection; public Constructor Create( AConnection : TZConnection ); Destructor Destroy ( );override; Procedure Query( ADataSet : TZQuery; const AQuery : String ); Procedure QueryNoResult( ADataSet : TZQuery; const AQuery : String ); function LastID( const Field : String; const Table : String; const Append : String = '' ):LongWord; end; //------------------------------------------------------------------------------ implementation uses {RTL/VCL} SysUtils, Classes, Globals {Project} {3rd Party} //none ; //------------------------------------------------------------------------------ //Create CONSTRUCTOR //------------------------------------------------------------------------------ // What it does- // Builds our object. // // Changes - // February 11th, 2008 - RaX - Created // //------------------------------------------------------------------------------ Constructor TQueryBase.Create( AConnection : TZConnection ); Begin Inherited Create; Connection := AConnection; End;{Create} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Destroy DESTRUCTOR //------------------------------------------------------------------------------ // What it does- // Frees up our custom properties. // // Changes - // February 11th, 2008 - RaX - Created. // //------------------------------------------------------------------------------ Destructor TQueryBase.Destroy( ); begin Inherited; end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Query PROCEDURE //------------------------------------------------------------------------------ // What it does- // Queries the database // // Changes - // February 11th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ Procedure TQueryBase.Query( ADataSet : TZQuery; const AQuery : String ); var Pinged : Boolean; begin try Pinged := Connection.Ping; except Pinged := TRUE; end; if NOT Pinged then begin try Connection.Connect; except Connection.Disconnect; end; end; if Connection.Connected then begin ADataSet.Connection := Connection; ADataSet.SQL.Add(AQuery); try ADataSet.ExecSQL; ADataSet.Open; except on E : Exception do begin Console.Message('Query error :: '+E.Message, 'Database', MS_WARNING); end; end; end; end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //QueryNoResult PROCEDURE //------------------------------------------------------------------------------ // What it does- // Queries the database with no result // // Changes - // February 11th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ Procedure TQueryBase.QueryNoResult( ADataSet : TZQuery; const AQuery : String ); var Pinged : Boolean; begin try Pinged := Connection.Ping; except Pinged := TRUE; end; if NOT Pinged then begin try Connection.Connect; except Connection.Disconnect; end; end; if Connection.Connected then begin ADataSet.Connection := Connection; ADataSet.SQL.Add(AQuery); try ADataSet.ExecSQL; except on E : Exception do begin Console.Message('Query error :: '+E.Message, 'Database', MS_WARNING); end; end; end; end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //LastID FUNCTION //------------------------------------------------------------------------------ // What it does- // Get "last insert ID" by finx max // // Changes - // [2008/09/20] Aeomin - Created // //------------------------------------------------------------------------------ function TQueryBase.LastID( const Field : String; const Table : String; const Append : String = '' ):LongWord; var AQuery : String; ADataSet : TZQuery; begin Result := 0; AQuery := 'SELECT MAX('+Field+') FROM '+Table+' '+Append + ';'; ADataSet := TZQuery.Create(nil); try Query(ADataSet, AQuery); ADataSet.First; if NOT ADataSet.Eof then begin Result := ADataSet.Fields[0].AsInteger; end; finally ADataSet.Free; end; end;{LastID} //------------------------------------------------------------------------------ end.
unit TextureAtlasExtractor; interface uses GLConstants, BasicMathsTypes, BasicDataTypes, Geometry, NeighborDetector, LOD, IntegerList, Math, VertexTransformationUtils, NeighborhoodDataPlugin, MeshPluginBase, SysUtils, GeometricAlgebra, Multivector, TextureAtlasExtractorBase; {$INCLUDE source/Global_Conditionals.inc} // This is the Texture Atlas Extraction Method published in SBGames 2010. type CTextureAtlasExtractor = class(CTextureAtlasExtractorBase) private FTextureAngle: single; // Seeds function MakeNewSeed(_ID,_MeshID,_StartingFace: integer; var _Vertices : TAVector3f; var _FaceNormals,_VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; var _TextCoords: TAVector2f; var _FaceSeeds,_VertsSeed: aint32; const _FaceNeighbors: TNeighborDetector; var _NeighborhoodPlugin: PMeshPluginBase; _VerticesPerFace,_MaxVerts: integer; var _VertsLocation : aint32; var _CheckFace: abool): TTextureSeed; // Angle stuff function GetVectorAngle(_Vec1, _Vec2: TVector3f): single; public // Constructors and Destructors constructor Create(var _LOD: TLOD); overload; constructor Create(var _LOD: TLOD; _TextureAngle: single); overload; // Executes procedure Execute(); override; procedure ExecuteWithDiffuseTexture(_Size: integer); override; function GetTextureCoordinates(var _Vertices : TAVector3f; var _FaceNormals, _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; var _NeighborhoodPlugin: PMeshPluginBase; _VerticesPerFace: integer): TAVector2f; // Texture atlas buildup: step by step. function GetMeshSeeds(_MeshID: integer; var _Vertices : TAVector3f; var _FaceNormals,_VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; _VerticesPerFace: integer; var _Seeds: TSeedSet; var _VertsSeed : aint32; var _NeighborhoodPlugin: PMeshPluginBase): TAVector2f; override; end; implementation uses Math3d, GlobalVars, TextureGeneratorBase, DiffuseTextureGenerator, StopWatch, MeshBRepGeometry; constructor CTextureAtlasExtractor.Create(var _LOD: TLOD); begin FLOD := _LOD; FTextureAngle := C_TEX_MIN_ANGLE; Initialize; end; constructor CTextureAtlasExtractor.Create(var _LOD: TLOD; _TextureAngle : single); begin FLOD := _LOD; FTextureAngle := _TextureAngle; Initialize; end; procedure CTextureAtlasExtractor.Execute(); var i : integer; Seeds: TSeedSet; VertsSeed : TInt32Map; NeighborhoodPlugin: PMeshPluginBase; begin // First, we'll build the texture atlas. SetLength(VertsSeed,High(FLOD.Mesh)+1); SetLength(Seeds,0); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); NeighborhoodPlugin := FLOD.Mesh[i].GetPlugin(C_MPL_NEIGHBOOR); FLOD.Mesh[i].Geometry.GoToFirstElement; FLOD.Mesh[i].TexCoords := GetMeshSeeds(i,FLOD.Mesh[i].Vertices,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Normals,FLOD.Mesh[i].Normals,FLOD.Mesh[i].Colours,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Faces,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,Seeds,VertsSeed[i],NeighborhoodPlugin); if NeighborhoodPlugin <> nil then begin TNeighborhoodDataPlugin(NeighborhoodPlugin^).DeactivateQuadFaces; end; end; MergeSeeds(Seeds); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin GetFinalTextureCoordinates(Seeds,VertsSeed[i],FLOD.Mesh[i].TexCoords); end; // Free memory. for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); end; SetLength(VertsSeed,0); end; procedure CTextureAtlasExtractor.ExecuteWithDiffuseTexture(_Size: integer); var i : integer; Seeds: TSeedSet; VertsSeed : TInt32Map; TexGenerator: CTextureGeneratorBase; NeighborhoodPlugin: PMeshPluginBase; begin // First, we'll build the texture atlas. SetLength(VertsSeed,High(FLOD.Mesh)+1); SetLength(Seeds,0); TexGenerator := CDiffuseTextureGenerator.Create(FLOD,_Size,0,0); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); NeighborhoodPlugin := FLOD.Mesh[i].GetPlugin(C_MPL_NEIGHBOOR); FLOD.Mesh[i].Geometry.GoToFirstElement; FLOD.Mesh[i].TexCoords := GetMeshSeeds(i,FLOD.Mesh[i].Vertices,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Normals,FLOD.Mesh[i].Normals,FLOD.Mesh[i].Colours,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Faces,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,Seeds,VertsSeed[i],NeighborhoodPlugin); if NeighborhoodPlugin <> nil then begin TNeighborhoodDataPlugin(NeighborhoodPlugin^).DeactivateQuadFaces; end; end; MergeSeeds(Seeds); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin GetFinalTextureCoordinates(Seeds,VertsSeed[i],FLOD.Mesh[i].TexCoords); end; // Now we build the diffuse texture. TexGenerator.Execute(); // Free memory. for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); end; SetLength(VertsSeed,0); TexGenerator.Free; end; // Angle operations function CTextureAtlasExtractor.GetVectorAngle(_Vec1, _Vec2: TVector3f): single; begin Result := (_Vec1.X * _Vec2.X) + (_Vec1.Y * _Vec2.Y) + (_Vec1.Z * _Vec2.Z); end; // Executes function CTextureAtlasExtractor.GetMeshSeeds(_MeshID: integer; var _Vertices : TAVector3f; var _FaceNormals,_VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; _VerticesPerFace: integer; var _Seeds: TSeedSet; var _VertsSeed : aint32; var _NeighborhoodPlugin: PMeshPluginBase): TAVector2f; var i, MaxVerts,NumSeeds: integer; VertsLocation,FaceSeed : aint32; FacePriority: AFloat; FaceOrder : auint32; CheckFace: abool; FaceNeighbors: TNeighborDetector; begin SetLength(VertsLocation,High(_Vertices)+1); SetupMeshSeeds(_Vertices,_FaceNormals,_Faces,_VerticesPerFace,_Seeds,_VertsSeed,FaceNeighbors,Result,MaxVerts,FaceSeed,FacePriority,FaceOrder,CheckFace); // Let's build the seeds. NumSeeds := High(_Seeds)+1; SetLength(_Seeds,NumSeeds + High(FaceSeed)+1); for i := Low(FaceSeed) to High(FaceSeed) do begin if FaceSeed[FaceOrder[i]] = -1 then begin // Make new seed. _Seeds[NumSeeds] := MakeNewSeed(NumSeeds,_MeshID,FaceOrder[i],_Vertices,_FaceNormals,_VertsNormals,_VertsColours,_Faces,Result,FaceSeed,_VertsSeed,FaceNeighbors,_NeighborhoodPlugin,_VerticesPerFace,MaxVerts,VertsLocation,CheckFace); inc(NumSeeds); end; end; SetLength(_Seeds,NumSeeds); // Re-align vertexes and seed bounds to start at (0,0) ReAlignSeedsToCenter(_Seeds,_VertsSeed,FaceNeighbors,Result,FacePriority,FaceOrder,CheckFace,_NeighborhoodPlugin); SetLength(VertsLocation,0); end; function CTextureAtlasExtractor.MakeNewSeed(_ID,_MeshID,_StartingFace: integer; var _Vertices : TAVector3f; var _FaceNormals, _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; var _TextCoords: TAVector2f; var _FaceSeeds,_VertsSeed: aint32; const _FaceNeighbors: TNeighborDetector; var _NeighborhoodPlugin: PMeshPluginBase; _VerticesPerFace,_MaxVerts: integer; var _VertsLocation : aint32; var _CheckFace: abool): TTextureSeed; const C_MIN_ANGLE = 0.001; // approximately cos 90' var v,f,Value,vertex,FaceIndex : integer; List : CIntegerList; Angle: single; VertexUtil : TVertexTransformationUtils; begin VertexUtil := TVertexTransformationUtils.Create; // Setup neighbor detection list List := CIntegerList.Create; List.UseFixedRAM((High(_CheckFace) + 1)); // Setup VertsLocation for v := Low(_VertsLocation) to High(_VertsLocation) do begin _VertsLocation[v] := -1; end; // Avoid unlimmited loop for f := Low(_CheckFace) to High(_CheckFace) do _CheckFace[f] := false; // Add starting face List.Add(_StartingFace); _CheckFace[_StartingFace] := true; Result.TransformMatrix := VertexUtil.GetRotationMatrixFromVector(_FaceNormals[_StartingFace]); Result.MinBounds.U := 999999; Result.MaxBounds.U := -999999; Result.MinBounds.V := 999999; Result.MaxBounds.V := -999999; Result.MeshID := _MeshID; // Neighbour Face Scanning starts here. while List.GetValue(Value) do begin // Add face here // Add the face and its vertexes _FaceSeeds[Value] := _ID; FaceIndex := Value * _VerticesPerFace; for v := 0 to _VerticesPerFace - 1 do begin vertex := _Faces[FaceIndex+v]; if _VertsSeed[vertex] <> -1 then begin if _VertsLocation[vertex] = -1 then begin // this vertex was used by a previous seed, therefore, we'll clone it SetLength(_Vertices,High(_Vertices)+2); SetLength(_VertsSeed,High(_Vertices)+1); _VertsSeed[High(_VertsSeed)] := _ID; _VertsLocation[vertex] := High(_Vertices); _Faces[FaceIndex+v] := _VertsLocation[vertex]; _Vertices[High(_Vertices)].X := _Vertices[vertex].X; _Vertices[High(_Vertices)].Y := _Vertices[vertex].Y; _Vertices[High(_Vertices)].Z := _Vertices[vertex].Z; SetLength(_VertsNormals,High(_Vertices)+1); _VertsNormals[High(_Vertices)].X := _VertsNormals[vertex].X; _VertsNormals[High(_Vertices)].Y := _VertsNormals[vertex].Y; _VertsNormals[High(_Vertices)].Z := _VertsNormals[vertex].Z; SetLength(_VertsColours,High(_Vertices)+1); _VertsColours[High(_Vertices)].X := _VertsColours[vertex].X; _VertsColours[High(_Vertices)].Y := _VertsColours[vertex].Y; _VertsColours[High(_Vertices)].Z := _VertsColours[vertex].Z; _VertsColours[High(_Vertices)].W := _VertsColours[vertex].W; // Get temporarily texture coordinates. SetLength(_TextCoords,High(_Vertices)+1); _TextCoords[High(_Vertices)] := VertexUtil.GetUVCoordinates(_Vertices[vertex],Result.TransformMatrix); // Now update the bounds of the seed. if _TextCoords[High(_Vertices)].U < Result.MinBounds.U then Result.MinBounds.U := _TextCoords[High(_Vertices)].U; if _TextCoords[High(_Vertices)].U > Result.MaxBounds.U then Result.MaxBounds.U := _TextCoords[High(_Vertices)].U; if _TextCoords[High(_Vertices)].V < Result.MinBounds.V then Result.MinBounds.V := _TextCoords[High(_Vertices)].V; if _TextCoords[High(_Vertices)].V > Result.MaxBounds.V then Result.MaxBounds.V := _TextCoords[High(_Vertices)].V; end else begin // This vertex is already used by this seed. _Faces[FaceIndex+v] := _VertsLocation[vertex]; end; end else begin // This seed is the first seed to use this vertex. _VertsSeed[vertex] := _ID; _VertsLocation[vertex] := vertex; // Get temporary texture coordinates. _TextCoords[vertex] := VertexUtil.GetUVCoordinates(_Vertices[vertex],Result.TransformMatrix); // Now update the bounds of the seed. if _TextCoords[vertex].U < Result.MinBounds.U then Result.MinBounds.U := _TextCoords[vertex].U; if _TextCoords[vertex].U > Result.MaxBounds.U then Result.MaxBounds.U := _TextCoords[vertex].U; if _TextCoords[vertex].V < Result.MinBounds.V then Result.MinBounds.V := _TextCoords[vertex].V; if _TextCoords[vertex].V > Result.MaxBounds.V then Result.MaxBounds.V := _TextCoords[vertex].V; end; end; // Check if other neighbors are elegible for this partition/seed. f := _FaceNeighbors.GetNeighborFromID(Value); while f <> -1 do begin // do some verification here if not _CheckFace[f] then begin if (_FaceSeeds[f] = -1) then begin // check if angle (which actually receives a cosine) is less than FTextureAngle Angle := GetVectorAngle(_FaceNormals[_StartingFace],_FaceNormals[f]); if Angle >= FTextureAngle then begin List.Add(f); // end // else // begin // ShowMessage('Starting Face: (' + FloatToStr(_FaceNormals[_StartingFace].X) + ', ' + FloatToStr(_FaceNormals[_StartingFace].Y) + ', ' + FloatToStr(_FaceNormals[_StartingFace].Z) + ') and Current Face is (' + FloatToStr(_FaceNormals[f].X) + ', ' + FloatToStr(_FaceNormals[f].Y) + ', ' + FloatToStr(_FaceNormals[f].Z) + ') and the angle is ' + FloatToStr(Angle)); end; end; _CheckFace[f] := true; end; f := _FaceNeighbors.GetNextNeighbor; end; end; if _NeighborhoodPlugin <> nil then begin TNeighborhoodDataPlugin(_NeighborhoodPlugin^).UpdateEquivalences(_VertsLocation); end; List.Free; VertexUtil.Free; end; // Deprecated... function CTextureAtlasExtractor.GetTextureCoordinates(var _Vertices : TAVector3f; var _FaceNormals,_VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; var _NeighborhoodPlugin: PMeshPluginBase; _VerticesPerFace: integer): TAVector2f; var i, x, MaxVerts, Current, Previous: integer; VertsLocation,FaceSeed,VertsSeed : aint32; FacePriority: AFloat; FaceOrder,UOrder,VOrder : auint32; CheckFace: abool; FaceNeighbors: TNeighborDetector; UMerge,VMerge,UMax,VMax,PushValue: real; HiO,HiS: integer; Seeds: TSeedSet; SeedTree : TSeedTree; List : CIntegerList; SeedSeparatorSpace: single; begin // Get the neighbours of each face. if _NeighborhoodPlugin <> nil then begin FaceNeighbors := TNeighborhoodDataPlugin(_NeighborhoodPlugin^).FaceFaceNeighbors; end else begin FaceNeighbors := TNeighborDetector.Create(C_NEIGHBTYPE_FACE_FACE_FROM_EDGE); FaceNeighbors.BuildUpData(_Faces,_VerticesPerFace,High(_Vertices)+1); end; // Setup FaceSeed, FaceOrder and FacePriority. SetLength(FaceSeed,High(_FaceNormals)+1); SetLength(FaceOrder,High(FaceSeed)+1); SetLength(FacePriority,High(FaceSeed)+1); SetLength(VertsLocation,High(_Vertices)+1); SetLength(CheckFace,High(_FaceNormals)+1); for i := Low(FaceSeed) to High(FaceSeed) do begin FaceSeed[i] := -1; FaceOrder[i] := i; FacePriority[i] := Max(Max(abs(_FaceNormals[i].X),abs(_FaceNormals[i].Y)),abs(_FaceNormals[i].Z)); end; QuickSortPriority(Low(FaceOrder),High(FaceOrder),FaceOrder,FacePriority); // Setup VertsSeed. MaxVerts := High(_Vertices)+1; SetLength(VertsSeed,MaxVerts); for i := Low(VertsSeed) to High(VertsSeed) do begin VertsSeed[i] := -1; end; // Setup Seeds. SetLength(Seeds,0); // Setup Texture Coordinates (Result) SetLength(Result,MaxVerts); // Let's build the seeds. for i := Low(FaceSeed) to High(FaceSeed) do begin if FaceSeed[FaceOrder[i]] = -1 then begin // Make new seed. SetLength(Seeds,High(Seeds)+2); Seeds[High(Seeds)] := MakeNewSeed(High(Seeds),0,FaceOrder[i],_Vertices,_FaceNormals,_VertsNormals,_VertsColours,_Faces,Result,FaceSeed,VertsSeed,FaceNeighbors,_NeighborhoodPlugin,_VerticesPerFace,MaxVerts,VertsLocation,CheckFace); end; end; // Re-align vertexes and seed bounds to start at (0,0) for i := Low(VertsSeed) to High(VertsSeed) do begin Result[i].U := Result[i].U - Seeds[VertsSeed[i]].MinBounds.U; Result[i].V := Result[i].V - Seeds[VertsSeed[i]].MinBounds.V; end; for i := Low(Seeds) to High(Seeds) do begin Seeds[i].MaxBounds.U := Seeds[i].MaxBounds.U - Seeds[i].MinBounds.U; Seeds[i].MinBounds.U := 0; Seeds[i].MaxBounds.V := Seeds[i].MaxBounds.V - Seeds[i].MinBounds.V; Seeds[i].MinBounds.V := 0; end; // Now, we need to setup two lists: one ordered by u and another ordered by v. HiO := High(Seeds); // That's the index for the last useful element of the U and V order buffers SetLength(UOrder,HiO+1); SetLength(VOrder,HiO+1); for i := Low(UOrder) to High(UOrder) do begin UOrder[i] := i; VOrder[i] := i; end; QuickSortSeeds(Low(UOrder),HiO,UOrder,Seeds,CompareU); QuickSortSeeds(Low(VOrder),HiO,VOrder,Seeds,CompareV); HiS := HiO; // That's the index for the last useful seed and seed tree item. SetLength(Seeds,(2*HiS)+1); // Let's calculate the required space to separate one seed from others. // Get the smallest dimension of the smallest partitions. SeedSeparatorSpace := 0.03 * max(Seeds[VOrder[Low(VOrder)]].MaxBounds.V - Seeds[VOrder[Low(VOrder)]].MinBounds.V,Seeds[UOrder[Low(UOrder)]].MaxBounds.U - Seeds[UOrder[Low(UOrder)]].MinBounds.U); // Then, we start a SeedTree, which we'll use to ajust the bounds from seeds // inside bigger seeds. SetLength(SeedTree,High(Seeds)+1); for i := Low(SeedTree) to High(SeedTree) do begin SeedTree[i].Left := -1; SeedTree[i].Right := -1; end; // Setup seed tree detection list List := CIntegerList.Create; List.UseSmartMemoryManagement(true); // We'll now start the main loop. We merge the smaller seeds into bigger seeds until we only have on seed left. while HiO > 0 do begin // Select the last two seeds from UOrder and VOrder and check which merge // uses less space. UMerge := ( (Seeds[UOrder[HiO]].MaxBounds.U - Seeds[UOrder[HiO]].MinBounds.U) + SeedSeparatorSpace + (Seeds[UOrder[HiO-1]].MaxBounds.U - Seeds[UOrder[HiO-1]].MinBounds.U) ) * max((Seeds[UOrder[HiO]].MaxBounds.V - Seeds[UOrder[HiO]].MinBounds.V),(Seeds[UOrder[HiO-1]].MaxBounds.V - Seeds[UOrder[HiO-1]].MinBounds.V)); VMerge := ( (Seeds[VOrder[HiO]].MaxBounds.V - Seeds[VOrder[HiO]].MinBounds.V) + SeedSeparatorSpace + (Seeds[VOrder[HiO-1]].MaxBounds.V - Seeds[VOrder[HiO-1]].MinBounds.V) ) * max((Seeds[VOrder[HiO]].MaxBounds.U - Seeds[VOrder[HiO]].MinBounds.U),(Seeds[VOrder[HiO-1]].MaxBounds.U - Seeds[VOrder[HiO-1]].MinBounds.U)); UMax := max(( (Seeds[UOrder[HiO]].MaxBounds.U - Seeds[UOrder[HiO]].MinBounds.U) + SeedSeparatorSpace + (Seeds[UOrder[HiO-1]].MaxBounds.U - Seeds[UOrder[HiO-1]].MinBounds.U) ),max((Seeds[UOrder[HiO]].MaxBounds.V - Seeds[UOrder[HiO]].MinBounds.V),(Seeds[UOrder[HiO-1]].MaxBounds.V - Seeds[UOrder[HiO-1]].MinBounds.V))); VMax := max(( (Seeds[VOrder[HiO]].MaxBounds.V - Seeds[VOrder[HiO]].MinBounds.V) + SeedSeparatorSpace + (Seeds[VOrder[HiO-1]].MaxBounds.V - Seeds[VOrder[HiO-1]].MinBounds.V) ),max((Seeds[VOrder[HiO]].MaxBounds.U - Seeds[VOrder[HiO]].MinBounds.U),(Seeds[VOrder[HiO-1]].MaxBounds.U - Seeds[VOrder[HiO-1]].MinBounds.U))); inc(HiS); Seeds[HiS].MinBounds.U := 0; Seeds[HiS].MinBounds.V := 0; if IsVLower(UMerge,VMerge,UMax,VMax) then begin // So, we'll merge the last two elements of VOrder into a new sector. // ----------------------- // Finish the creation of the new seed. Seeds[HiS].MaxBounds.U := max((Seeds[VOrder[HiO]].MaxBounds.U - Seeds[VOrder[HiO]].MinBounds.U),(Seeds[VOrder[HiO-1]].MaxBounds.U - Seeds[VOrder[HiO-1]].MinBounds.U)); Seeds[HiS].MaxBounds.V := (Seeds[VOrder[HiO]].MaxBounds.V - Seeds[VOrder[HiO]].MinBounds.V) + SeedSeparatorSpace + (Seeds[VOrder[HiO-1]].MaxBounds.V - Seeds[VOrder[HiO-1]].MinBounds.V); // Insert the last two elements from VOrder at the new seed tree element. SeedTree[HiS].Left := VOrder[HiO-1]; SeedTree[HiS].Right := VOrder[HiO]; // Now we translate the bounds of the element in the 'right' down, where it // belongs, and do it recursively. PushValue := (Seeds[VOrder[HiO-1]].MaxBounds.V - Seeds[VOrder[HiO-1]].MinBounds.V) + SeedSeparatorSpace; List.Add(SeedTree[HiS].Right); while List.GetValue(i) do begin Seeds[i].MinBounds.V := Seeds[i].MinBounds.V + PushValue; Seeds[i].MaxBounds.V := Seeds[i].MaxBounds.V + PushValue; if SeedTree[i].Left <> -1 then List.Add(SeedTree[i].Left); if SeedTree[i].Right <> -1 then List.Add(SeedTree[i].Right); end; // Remove the last two elements of VOrder from UOrder and add the new seed. i := 0; x := 0; while i <= HiO do begin if (UOrder[i] = VOrder[HiO]) or (UOrder[i] = VOrder[HiO-1]) then inc(x) else UOrder[i - x] := UOrder[i]; inc(i); end; dec(HiO); Current := HiO div 2; SeedBinarySearch(HiS,0,HiO-1,UOrder,Seeds,CompareU,Current,Previous); i := HiO; while i > (Previous+1) do begin UOrder[i] := UOrder[i-1]; dec(i); end; UOrder[Previous+1] := HiS; // Now we remove the last two elements from VOrder and add the new seed. Current := HiO div 2; SeedBinarySearch(HiS,0,HiO-1,VOrder,Seeds,CompareV,Current,Previous); i := HiO; while i > (Previous+1) do begin VOrder[i] := VOrder[i-1]; dec(i); end; VOrder[Previous+1] := HiS; end else // UMerge <= VMerge begin // So, we'll merge the last two elements of UOrder into a new sector. // ----------------------- // Finish the creation of the new seed. Seeds[HiS].MaxBounds.U := (Seeds[UOrder[HiO]].MaxBounds.U - Seeds[UOrder[HiO]].MinBounds.U) + SeedSeparatorSpace + (Seeds[UOrder[HiO-1]].MaxBounds.U - Seeds[UOrder[HiO-1]].MinBounds.U); Seeds[HiS].MaxBounds.V := max((Seeds[UOrder[HiO]].MaxBounds.V - Seeds[UOrder[HiO]].MinBounds.V),(Seeds[UOrder[HiO-1]].MaxBounds.V - Seeds[UOrder[HiO-1]].MinBounds.V)); // Insert the last two elements from UOrder at the new seed tree element. SeedTree[HiS].Left := UOrder[HiO-1]; SeedTree[HiS].Right := UOrder[HiO]; // Now we translate the bounds of the element in the 'right' to the right, // where it belongs, and do it recursively. PushValue := (Seeds[UOrder[HiO-1]].MaxBounds.U - Seeds[UOrder[HiO-1]].MinBounds.U) + SeedSeparatorSpace; List.Add(SeedTree[HiS].Right); while List.GetValue(i) do begin Seeds[i].MinBounds.U := Seeds[i].MinBounds.U + PushValue; Seeds[i].MaxBounds.U := Seeds[i].MaxBounds.U + PushValue; if SeedTree[i].Left <> -1 then List.Add(SeedTree[i].Left); if SeedTree[i].Right <> -1 then List.Add(SeedTree[i].Right); end; // Remove the last two elements of UOrder from VOrder and add the new seed. i := 0; x := 0; while i <= HiO do begin if (VOrder[i] = UOrder[HiO]) or (VOrder[i] = UOrder[HiO-1]) then inc(x) else VOrder[i - x] := VOrder[i]; inc(i); end; dec(HiO); Current := HiO div 2; SeedBinarySearch(HiS,0,HiO-1,VOrder,Seeds,CompareV,Current,Previous); i := HiO; while i > (Previous+1) do begin VOrder[i] := VOrder[i-1]; dec(i); end; VOrder[Previous+1] := HiS; // Now we remove the last two elements from UOrder and add the new seed. Current := HiO div 2; SeedBinarySearch(HiS,0,HiO-1,UOrder,Seeds,CompareU,Current,Previous); i := HiO; while i > (Previous+1) do begin UOrder[i] := UOrder[i-1]; dec(i); end; UOrder[Previous+1] := HiS; end; end; // The texture must be a square, so we'll centralize the smallest dimension. if (Seeds[High(Seeds)].MaxBounds.U > Seeds[High(Seeds)].MaxBounds.V) then begin PushValue := (Seeds[High(Seeds)].MaxBounds.U - Seeds[High(Seeds)].MaxBounds.V) / 2; for i := Low(Seeds) to (High(Seeds)-1) do begin Seeds[i].MinBounds.V := Seeds[i].MinBounds.V + PushValue; Seeds[i].MaxBounds.V := Seeds[i].MaxBounds.V + PushValue; end; Seeds[High(Seeds)].MaxBounds.V := Seeds[High(Seeds)].MaxBounds.U; end else if (Seeds[High(Seeds)].MaxBounds.U < Seeds[High(Seeds)].MaxBounds.V) then begin PushValue := (Seeds[High(Seeds)].MaxBounds.V - Seeds[High(Seeds)].MaxBounds.U) / 2; for i := Low(Seeds) to (High(Seeds)-1) do begin Seeds[i].MinBounds.U := Seeds[i].MinBounds.U + PushValue; Seeds[i].MaxBounds.U := Seeds[i].MaxBounds.U + PushValue; end; Seeds[High(Seeds)].MaxBounds.U := Seeds[High(Seeds)].MaxBounds.V; end; // Let's get the final texture coordinates for each vertex now. for i := Low(Result) to High(Result) do begin Result[i].U := (Seeds[VertsSeed[i]].MinBounds.U + Result[i].U) / Seeds[High(Seeds)].MaxBounds.U; Result[i].V := (Seeds[VertsSeed[i]].MinBounds.V + Result[i].V) / Seeds[High(Seeds)].MaxBounds.V; end; // Clean up memory. SetLength(SeedTree,0); SetLength(Seeds,0); SetLength(FaceSeed,0); SetLength(VertsSeed,0); SetLength(UOrder,0); SetLength(VOrder,0); SetLength(FacePriority,0); SetLength(FaceOrder,0); SetLength(CheckFace,0); SetLength(VertsLocation,0); List.Free; if _NeighborhoodPlugin = nil then FaceNeighbors.Free; end; end.
unit Unit1; { Source: https://rosettacode.org/wiki/Pi#Delphi } interface uses Classes, Controls, Forms, StdCtrls; type TForm1 = class(TForm) memScreen: TMemo; btnStartStop: TButton; procedure btnStartStopClick(Sender: TObject); procedure FormCreate(Sender: TObject); private fLineBuffer: string; procedure ClearText(); procedure AddText(const s: string); procedure FlushText(); procedure CalcPi(); const fScreenWidth = 80; end; var Form1: TForm1; Working: Boolean; implementation {$R *.dfm} uses SysUtils; // Button clicked to run algorithm procedure TForm1.btnStartStopClick(Sender: TObject); begin Working := not Working; if not Working then btnStartStop.Caption := 'Calculate Pi!' else begin btnStartStop.Caption := 'Stop!'; CalcPi(); end; end; {=========================== Auxiliary routines ===========================} // Form created procedure TForm1.FormCreate(Sender: TObject); begin Working := False; end; procedure TForm1.CalcPi(); var // BBC Basic variables. Delphi longint is 32 bits. B: array of longint; A, C, D, E, I, L, M, P: longint; // Added for Delphi version temp: string; h, j, t: integer; begin ClearText(); M := 5368709; // floor( (2^31 - 1)/400 ) // DIM B%(M%) in BBC Basic declares an array [0..M%], i.e. M% + 1 elements SetLength(B, M + 1); for I := 0 to M do B[I] := 20; E := 0; L := 2; // FOR C% = M% TO 14 STEP -7 // In Delphi (or at least Delphi 7) the step size in a for loop has to be 1. // So the BBC Basic FOR loop has been replaced by a repeat loop. C := M; repeat D := 0; A := C * 2 - 1; for P := C downto 1 do begin D := D * P + B[P] * $64; // hex notation copied from BBC version B[P] := D mod A; D := D div A; dec(A, 2); end; // The BBC CASE statement here amounts to a series of if ... else if (D = 99) then begin E := E * 100 + D; inc(L, 2); end else if (C = M) then begin AddText(SysUtils.Format('%2.1f', [1.0 * (D div 100) / 10.0])); E := D mod 100; end else begin // PRINT RIGHT$(STRING$(L%,"0") + STR$(E% + D% DIV 100),L%); // This can't be done so concisely in Delphi 7 SetLength(temp, L); for j := 1 to L do temp[j] := '0'; temp := temp + IntToStr(E + D div 100); t := Length(temp); AddText(Copy(temp, t - L + 1, L)); E := D mod 100; L := 2; end; dec(C, 7); //Me: added to allow interrupting calculation Application.ProcessMessages; until (C < 14) or not Working; FlushText(); // Delphi addition: Write screen output to a file for checking h := FileCreate('PiDigits.txt'); // h = file handle for j := 0 to memScreen.Lines.Count - 1 do FileWrite(h, memScreen.Lines[j][1], Length(memScreen.Lines[j])); FileClose(h); end; // This Delphi version builds each screen line in a buffer and puts // the line into the TMemo when the buffer is full. // This is faster than writing to the TMemo a few characters at a time, // but note that the buffer must be flushed at the end of the program. procedure TForm1.ClearText(); begin memScreen.Lines.Clear(); fLineBuffer := ''; end; procedure TForm1.AddText(const s: string); var nrChars, nrLeft: integer; begin nrChars := Length(s); nrLeft := fScreenWidth - Length(fLineBuffer); // nr chars left in line if (nrChars <= nrLeft) then fLineBuffer := fLineBuffer + s else begin fLineBuffer := fLineBuffer + Copy(s, 1, nrLeft); memScreen.Lines.Add(fLineBuffer); //Make sure to enable Extended syntax in project options! fLineBuffer := Copy(s, nrLeft + 1, nrChars - nrLeft); end; end; procedure TForm1.FlushText(); begin if (Length(fLineBuffer) > 0) then begin memScreen.Lines.Add(fLineBuffer); fLineBuffer := ''; end; end; end.
(* Copyright (c) 2016 Darian Miller All rights reserved. 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, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. As of January 2016, latest version available online at: https://github.com/darianmiller/dxLib_Tests *) unit dxLib_Test_ClassPropertyArray; interface {$I '..\Dependencies\dxLib\Source\dxLib.inc'} uses TestFramework, {$IFDEF DX_UnitScopeNames} System.Classes, System.TypInfo, {$ELSE} Classes, TypInfo, {$ENDIF} dxLib_ClassPropertyArray; type TExampleClassWithPublishedProperties = Class(TPersistent) private fExamplePublic:String; fExamplePublished:String; fAnotherPublished:Integer; public property ExamplePublic:String read fExamplePublic write fExamplePublic; published property ExamplePublished:String read fExamplePublished write fExamplePublished; property AnotherPublished:Integer read fAnotherPublished write fAnotherPublished; end; TestTdxClassPropertyArray = class(TTestCase) private fExampleClass:TExampleClassWithPublishedProperties; protected procedure SetUp(); override; procedure TearDown(); override; published procedure TestGetPublishedPropertyByName; procedure TestGetPublicPropertyFail; procedure TestPropertyFilter; end; const EXPECTED_PUBLISHED_PROPERTY_COUNT = 2; EXPECTED_PUBLISHED_INTEGER_PROPERTY_COUNT = 1; implementation procedure TestTdxClassPropertyArray.SetUp(); begin inherited; fExampleClass := TExampleClassWithPublishedProperties.Create(); end; procedure TestTdxClassPropertyArray.TearDown(); begin fExampleClass.Free(); inherited; end; //Array should contain published properties procedure TestTdxClassPropertyArray.TestGetPublishedPropertyByName; const TEST_PROPERTY_NAME = 'AnotherPublished'; var vArray:TdxClassPropertyArray; vPReturnValue:PPropInfo; begin vArray := TdxClassPropertyArray.Create(fExampleClass); try vPReturnValue := vArray.GetPropertyByName(TEST_PROPERTY_NAME); if Assigned(vPReturnValue) then begin Check(vPReturnValue.Name = TEST_PROPERTY_NAME); end else begin Fail('Property Not Found'); end; Check(vArray.Count = EXPECTED_PUBLISHED_PROPERTY_COUNT); finally vArray.Free(); end; end; //Array does not contain public properties procedure TestTdxClassPropertyArray.TestGetPublicPropertyFail; const TEST_PROPERTY_NAME = 'ExamplePublic'; var vArray:TdxClassPropertyArray; vPReturnValue:PPropInfo; begin vArray := TdxClassPropertyArray.Create(fExampleClass); try vPReturnValue := vArray.GetPropertyByName(TEST_PROPERTY_NAME); CheckFalse(Assigned(vPReturnValue)); finally vArray.Free(); end; end; procedure TestTdxClassPropertyArray.TestPropertyFilter; var vArray:TdxClassPropertyArray; begin vArray := TdxClassPropertyArray.Create(fExampleClass, [tkInteger]); try Check(vArray.Count = EXPECTED_PUBLISHED_INTEGER_PROPERTY_COUNT); finally vArray.Free(); end; end; initialization RegisterTest(TestTdxClassPropertyArray.Suite); end.
unit fGridColors; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.UITypes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons, uGlobal; type TGridColorsForm = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; xyRed: TTrackBar; xyGreen: TTrackBar; xyBlue: TTrackBar; xyAlpha: TTrackBar; GroupBox2: TGroupBox; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; xzRed: TTrackBar; xzGreen: TTrackBar; xzBlue: TTrackBar; xzAlpha: TTrackBar; GroupBox3: TGroupBox; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; yzRed: TTrackBar; yzGreen: TTrackBar; yzBlue: TTrackBar; yzAlpha: TTrackBar; GroupBox4: TGroupBox; Label13: TLabel; Label14: TLabel; Label15: TLabel; Label16: TLabel; BoxRed: TTrackBar; BoxGreen: TTrackBar; BoxBlue: TTrackBar; BoxAlpha: TTrackBar; BackColorBtn: TSpeedButton; BitBtn1: TBitBtn; ColorDialog: TColorDialog; procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure xyRedChange(Sender: TObject); procedure xyGreenChange(Sender: TObject); procedure xyBlueChange(Sender: TObject); procedure xyAlphaChange(Sender: TObject); procedure xzRedChange(Sender: TObject); procedure xzGreenChange(Sender: TObject); procedure xzBlueChange(Sender: TObject); procedure xzAlphaChange(Sender: TObject); procedure yzRedChange(Sender: TObject); procedure yzGreenChange(Sender: TObject); procedure yzBlueChange(Sender: TObject); procedure yzAlphaChange(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure BackColorBtnClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BoxRedChange(Sender: TObject); procedure BoxGreenChange(Sender: TObject); procedure BoxBlueChange(Sender: TObject); procedure BoxAlphaChange(Sender: TObject); private { Private declarations } public procedure ShowGridColorData; end; var GridColorsForm: TGridColorsForm; //================================================================== implementation //================================================================== uses fMain; {$R *.dfm} procedure TGridColorsForm.BackColorBtnClick(Sender: TObject); begin ColorDialog.Color := ViewData.BackColor; if ColorDialog.Execute then begin ViewData.BackColor := ColorDialog.Color; ViewForm.GLSViewer.Buffer.BackgroundColor := Viewdata.BackColor; Altered := True; end; end; procedure TGridColorsForm.BitBtn1Click(Sender: TObject); begin Close; end; procedure TGridColorsForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if GridColorsAltered then begin case MessageDlg('The current graph''s color data has been altered.'+ #13#10'Do you wish to save the alterations ?', mtConfirmation, [mbYes, mbNo, mbCancel], 0) of mrYes: Altered := Altered or GridColorsAltered; mrCancel: begin CanClose := False; Exit; end; end; end; end; procedure TGridColorsForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TGridColorsForm.FormShow(Sender: TObject); begin ShowGridColorData; GridColorsAltered := False; end; procedure TGridColorsForm.xyRedChange(Sender: TObject); begin ViewForm.GLxyGrid.LineColor.Red := xyRed.Position/255; ViewData.xyGrid.Color.X := ViewForm.GLxyGrid.LineColor.Red; GridColorsAltered := True; end; { TGridColorsForm.xyRedChange } procedure TGridColorsForm.xyGreenChange(Sender: TObject); begin ViewForm.GLxyGrid.LineColor.Green := xyGreen.Position/255; ViewData.xyGrid.Color.Y := ViewForm.GLxyGrid.LineColor.Green; GridColorsAltered := True; end; { TGridColorsForm.xyGreenChange } procedure TGridColorsForm.xyBlueChange(Sender: TObject); begin ViewForm.GLxyGrid.LineColor.Blue := xyBlue.Position/255; ViewData.xyGrid.Color.Z := ViewForm.GLxyGrid.LineColor.Blue; GridColorsAltered := True; end; { TGridColorsForm.xyBlueChange } procedure TGridColorsForm.xyAlphaChange(Sender: TObject); begin ViewForm.GLxyGrid.LineColor.Alpha := xyAlpha.Position/1000; ViewData.xyGrid.Color.W := ViewForm.GLxyGrid.LineColor.Alpha; GridColorsAltered := True; end; { TGridColorsForm.xyAlphaChange } procedure TGridColorsForm.xzRedChange(Sender: TObject); begin ViewForm.GLxzGrid.LineColor.Red := xzRed.Position/255; ViewData.xzGrid.Color.X := ViewForm.GLxzGrid.LineColor.Red; GridColorsAltered := True; end; { TGridColorsForm.xzRedChange } procedure TGridColorsForm.xzGreenChange(Sender: TObject); begin ViewForm.GLxzGrid.LineColor.Green := xzGreen.Position/255; ViewData.xzGrid.Color.Y := ViewForm.GLxzGrid.LineColor.Green; GridColorsAltered := True; end; { TGridColorsForm.xzGreenChange } procedure TGridColorsForm.xzBlueChange(Sender: TObject); begin ViewForm.GLxzGrid.LineColor.Blue := xzBlue.Position/255; ViewData.xzGrid.Color.Z := ViewForm.GLxzGrid.LineColor.Blue; GridColorsAltered := True; end; { TGridColorsForm.xzBlueChange } procedure TGridColorsForm.xzAlphaChange(Sender: TObject); begin ViewForm.GLxzGrid.LineColor.Alpha := xzAlpha.Position/1000; ViewData.xzGrid.Color.W := ViewForm.GLxzGrid.LineColor.Alpha; GridColorsAltered := True; end; { TGridColorsForm.xzAlphaChange } procedure TGridColorsForm.yzRedChange(Sender: TObject); begin ViewForm.GLyzGrid.LineColor.Red := yzRed.Position/255; ViewData.yzGrid.Color.X := ViewForm.GLyzGrid.LineColor.Red; GridColorsAltered := True; end; { TGridColorsForm.yzRedChange } procedure TGridColorsForm.yzGreenChange(Sender: TObject); begin ViewForm.GLyzGrid.LineColor.Green := yzGreen.Position/255; ViewData.yzGrid.Color.Y := ViewForm.GLyzGrid.LineColor.Green; GridColorsAltered := True; end; { TGridColorsForm.yzGreenChange } procedure TGridColorsForm.yzBlueChange(Sender: TObject); begin ViewForm.GLyzGrid.LineColor.Blue := yzBlue.Position/255; ViewData.yzGrid.Color.Z := ViewForm.GLyzGrid.LineColor.Blue; GridColorsAltered := True; end; { TGridColorsForm.yzBlueChange } procedure TGridColorsForm.yzAlphaChange(Sender: TObject); begin ViewForm.GLyzGrid.LineColor.Alpha := yzAlpha.Position/1000; ViewData.yzGrid.Color.W := ViewForm.GLyzGrid.LineColor.Alpha; GridColorsAltered := True; end; { TGridColorsForm.yzAlphaChange } procedure TGridColorsForm.BoxRedChange(Sender: TObject); begin ViewForm.BoxLine1.LineColor.Red := BoxRed.Position/255; ViewForm.BoxLine2.LineColor := ViewForm.BoxLine1.LineColor; ViewForm.BoxLine3.LineColor := ViewForm.BoxLine1.LineColor; ViewForm.BoxLine4.LineColor := ViewForm.BoxLine1.LineColor; ViewData.BoxLnColor.X := ViewForm.BoxLine1.LineColor.Red; GridColorsAltered := True; end; { TGridColorsForm.BoxRedChange } procedure TGridColorsForm.BoxGreenChange(Sender: TObject); begin ViewForm.BoxLine1.LineColor.Green := BoxGreen.Position/255; ViewForm.BoxLine2.LineColor := ViewForm.BoxLine1.LineColor; ViewForm.BoxLine3.LineColor := ViewForm.BoxLine1.LineColor; ViewForm.BoxLine4.LineColor := ViewForm.BoxLine1.LineColor; ViewData.BoxLnColor.Y := ViewForm.BoxLine1.LineColor.Green; GridColorsAltered := True; end; { TGridColorsForm.BoxGreenChange } procedure TGridColorsForm.BoxBlueChange(Sender: TObject); begin ViewForm.BoxLine1.LineColor.Blue := BoxBlue.Position/255; ViewForm.BoxLine2.LineColor := ViewForm.BoxLine1.LineColor; ViewForm.BoxLine3.LineColor := ViewForm.BoxLine1.LineColor; ViewForm.BoxLine4.LineColor := ViewForm.BoxLine1.LineColor; ViewData.BoxLnColor.Z := ViewForm.BoxLine1.LineColor.Blue; GridColorsAltered := True; end; { TGridColorsForm.BoxBlueChange } procedure TGridColorsForm.BoxAlphaChange(Sender: TObject); begin ViewForm.BoxLine1.LineColor.Alpha := BoxAlpha.Position/1000; ViewData.BoxLnColor.W := ViewForm.BoxLine1.LineColor.Alpha; ViewForm.BoxLine2.LineColor := ViewForm.BoxLine1.LineColor; ViewForm.BoxLine3.LineColor := ViewForm.BoxLine1.LineColor; ViewForm.BoxLine4.LineColor := ViewForm.BoxLine1.LineColor; GridColorsAltered := True; end; { TGridColorsForm.BoxAlphaChange } { Public declarations } procedure TGridColorsForm.ShowGridColorData; begin Caption := GraphFName; GridColorsAltered := False; with ViewForm.GLxyGrid.LineColor do begin xyRed.Position := round(Red*255); xyGreen.Position := round(Green*255); xyBlue.Position := round(Blue*255); xyAlpha.Position := round(Alpha*1000); end; with ViewForm.GLxzGrid.LineColor do begin xzRed.Position := round(Red*255); xzGreen.Position := round(Green*255); xzBlue.Position := round(Blue*255); xzAlpha.Position := round(Alpha*1000); end; with ViewForm.GLyzGrid.LineColor do begin yzRed.Position := round(Red*255); yzGreen.Position := round(Green*255); yzBlue.Position := round(Blue*255); yzAlpha.Position := round(Alpha*1000); end; with ViewForm do begin BoxRed.Position := round(BoxLine1.LineColor.Red*255); BoxGreen.Position := round(BoxLine1.LineColor.Green*255); BoxBlue.Position := round(BoxLine1.LineColor.Blue*255); BoxAlpha.Position := round(BoxLine1.LineColor.Alpha*1000); end; end; end.
unit MultiVector; interface uses BasicDataTypes, Math, GAConstants, GABasicFunctions, Debug, SysUtils; type TMultiVector = class private FData: array of Single; FDimension: Cardinal; FSize: Cardinal; protected // Gets function GetDimension: Cardinal; function GetData(_x: Cardinal): single; function QuickGetData(_x: Cardinal): single; function GetMaxElement: Cardinal; overload; // Sets procedure SetDimension(_Dimension: cardinal); procedure SetData(_x: Cardinal; _Value: single); procedure QuickSetData(_x: Cardinal; _Value: single); public // Constructors and Destructors constructor Create(_Dimension: integer); overload; constructor Create(const _Source: TMultiVector); overload; destructor Destroy; override; procedure ClearValues; // Gets function GetTheFirstNonZeroBitmap: cardinal; function GetTheNextNonZeroBitmap(_Current: cardinal): cardinal; function GetMaxElementForGrade(_MaxGrade: cardinal): Cardinal; overload; // Clone/Copy/Assign procedure Assign(const _Source: TMultiVector); // Debug procedure Debug(var _DebugFile: TDebugFile); overload; procedure Debug(var _DebugFile: TDebugFile; const _VectorName: string); overload; // Properties property Dimension: cardinal read GetDimension write SetDimension; property MaxElement: cardinal read GetMaxElement; property Data[_x:Cardinal]:single read GetData write SetData; property UnsafeData[_x:Cardinal]:single read QuickGetData write QuickSetData; end; implementation // Constructors and Destructors constructor TMultiVector.Create(_Dimension: Integer); begin FDimension := 0; Dimension := _Dimension; // SetDimension(_Dimension); end; constructor TMultiVector.Create(const _Source: TMultiVector); begin FDimension := 0; Assign(_Source); end; destructor TMultiVector.Destroy; begin SetLength(FData,0); inherited Destroy; end; procedure TMultiVector.ClearValues; var i: integer; begin for i := 0 to High(FData) do begin FData[i] := 0; end; end; // Gets function TMultiVector.GetDimension: cardinal; begin Result := FDimension; end; function TMultiVector.GetMaxElement: cardinal; begin Result := FSize - 1; end; function TMultiVector.GetMaxElementForGrade(_MaxGrade: cardinal): Cardinal; begin if _MaxGrade < FDimension then begin Result := (1 shl _MaxGrade) - 1; end else begin Result := FSize - 1; end; end; function TMultiVector.GetData(_x: Cardinal): single; begin if (_x < FSize) then begin Result := FData[_x]; end else begin Result := 0; end; end; function TMultiVector.QuickGetData(_x: Cardinal): single; begin Result := FData[_x]; end; function TMultiVector.GetTheFirstNonZeroBitmap: cardinal; begin Result := 0; while (Result < FSize) do begin if (UnsafeData[Result] <> 0) then begin exit; end; inc(Result); end; Result := C_INFINITY; end; function TMultiVector.GetTheNextNonZeroBitmap(_Current: Cardinal): cardinal; begin Result := _Current + 1; while (Result < FSize) do begin if (UnsafeData[Result] <> 0) then begin exit; end; inc(Result); end; Result := C_INFINITY; end; // Sets procedure TMultiVector.SetDimension(_Dimension: cardinal); var NewSize,i : cardinal; begin if FDimension > 0 then begin NewSize := 1 shl _Dimension; SetLength(FData,NewSize); for i := Min(FSize,NewSize) to High(FData) do begin FData[i] := 0; end; FDimension := _Dimension; FSize := NewSize; end else begin FDimension := _Dimension; FSize := 1 shl _Dimension; SetLength(FData,FSize); for i := 0 to FSize - 1 do begin FData[i] := 0; end; end; end; procedure TMultiVector.SetData(_x: Cardinal; _Value: single); begin if (_x < FSize) then begin FData[_x] := _Value; end; end; procedure TMultiVector.QuickSetData(_x: Cardinal; _Value: single); begin FData[_x] := _Value; end; // Clone/Copy/Assign procedure TMultiVector.Assign(const _Source: TMultiVector); var i : cardinal; begin Dimension := _Source.Dimension; for i := 0 to FSize - 1 do begin QuickSetData(i,_Source.QuickGetData(i)); end; end; // Debug procedure TMultiVector.Debug(var _DebugFile: TDebugFile); begin Debug(_DebugFile,'MultiVector'); end; procedure TMultiVector.Debug(var _DebugFile: TDebugFile; const _VectorName: string); var i,countElem,countBitmap,bitmap,numBase : cardinal; temp: string; begin temp := _VectorName + ' contents: '; countElem := 0; for i := 0 to MaxElement do begin if UnsafeData[i] <> 0 then begin if countElem <> 0 then begin temp := temp + ' + '; end; // Write value. temp := temp + FloatToStr(UnsafeData[i]); // Write bases. countBitmap := 0; numBase := 1; bitmap := 1; while i >= bitmap do begin if (i and bitmap) <> 0 then begin if countBitmap = 0 then begin temp := temp + ' e' + IntToStr(NumBase); end else begin temp := temp + '^e' + IntToStr(NumBase); end; inc(countBitmap); end; bitmap := bitmap shl 1; inc(numBase); end; inc(countElem); end; end; if countElem = 0 then begin temp := temp + '0'; end; _DebugFile.Add(temp); end; end.
(* W96SPELL.PAS - Copyright (c) 1995-1996, Eminent Domain Software *) unit W96Spell; {-WordPro 96 style spell dialog for EDSSpell component} interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, StdCtrls, EDSUtil, {$IFDEF Win32} {$IFDEF Ver100} LexDCTD3, {$ELSE} LexDCT32, {$ENDIF} {$ELSE} LexDCT, {$ENDIF} AbsSpell, SpellGbl; {$I SpellDef.PAS} type TW96Labels = (tlblSpellCheck, tlblFound, tlblNotFound, tbtnReplace, tbtnReplaceAll, tbtnAdd, tbtnSkip, tbtnSkipAll, tbtnClose); TLabelArray = array[TW96Labels] of string[20]; const cLabels : array[TLanguages] of TLabelArray = ( {$IFDEF SupportEnglish} {English} ('Spell Check', 'Word Found:', 'Word in Question:', '&Replace', 'Replace All', '&Add', 'Skip &Once', 'Skip &Always', '&Done') {$ENDIF} {$IFDEF SupportSpanish} {Spanish} ,('Verificar', 'Encontrado', 'No Encontrado', 'Cambiar', 'Cambiarlos', 'Añadir', 'Saltar', 'Ignorar', 'Cerrar') {$ENDIF} {$IFDEF SupportBritish} {British} ,('Spell Check', 'Word Found:', 'Word in Question:', '&Replace', 'Replace All', '&Add', 'Skip &Once', 'Skip &Always', '&Done') {$ENDIF} {$IFDEF SupportItalian} {Italian} ,('Verificar', 'Trovato', 'Non Trovato', 'Sostituisci', 'Sostituisci Tutti', 'Aggiungi', 'Salta', 'Salta Tutti', 'Cancella') {$ENDIF} {$IFDEF SupportFrench} {French} ,('Vérification', 'Mot Trouve:', 'Mot:', '&Remplacar', 'Remplacar &Par', '&Ajouter', '&Ignorer', 'Ignorer &Toujours', '&Fermer') {$ENDIF} {$IFDEF SupportGerman} {German} ,('Rechtschreibprüfung', 'Gefundenes Wort:', 'Fragliches Wor:', '&Ersetze', '&Immer Ersetze', '&Einfügen', 'Ü&berspringe', 'Immer Übe&rspringe', '&Schließen') {$ENDIF} {$IFDEF SupportDutch} {Dutch} ,('Spellingcontrole', 'Gevonden:', 'Niet gevonden:', 'Vervang', 'Volledig vervangen', 'Toevoegen', 'Negeer', 'Totaal negeren', 'Annuleren') {$ENDIF} ); type TW96SpellDlg = class(TAbsSpellDialog) Panel1: TPanel; lblFound: TLabel; SpeedButton1: TSpeedButton; Shape1: TShape; lblSpellChk: TLabel; Shape2: TShape; Panel2: TPanel; edtWord: TEnterEdit; lstSuggest: TNewListBox; pnlIcons: TPanel; btnA: TSpeedButton; btnE: TSpeedButton; btnI: TSpeedButton; btnO: TSpeedButton; btnU: TSpeedButton; btnN: TSpeedButton; btnN2: TSpeedButton; btnReplace: TBitBtn; btnAdd: TBitBtn; btnSkip: TBitBtn; btnSkipAll: TBitBtn; btnClose: TBitBtn; btnReplaceAll: TBitBtn; procedure edtWordExit(Sender: TObject); procedure lstSuggestChange(Sender: TObject); procedure lstSuggestDblClick(Sender: TObject); procedure AccentClick(Sender: TObject); procedure btnSuggestClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnReplaceClick(Sender: TObject); procedure btnReplaceAllClick(Sender: TObject); procedure btnSkipClick(Sender: TObject); procedure btnSkipAllClick(Sender: TObject); procedure QuickSuggest(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } constructor Create (AOwner: TComponent); override; {--- Extensions of TAbsSpellDialog ---} {--- Labels and Prompts ----} procedure SetNotFoundPrompt (ToString: String); override; {-sets the not found prompt} procedure SetNotFoundCaption (ToString: String); override; {-sets the not found caption} procedure SetEditWord (ToWord: String); override; {-sets the edit word string} function GetEditWord: String; override; {-gets the edit word} procedure SetEditAsActive; override; {-sets activecontrol the edit control} procedure SetLabelLanguage; override; {-sets labels and buttons to a the language} {--- Buttons ---} procedure EnableSkipButtons; override; {-enables the Skip and Skip All buttons} {-or Ignore and Ignore All} procedure DisableSkipButtons; override; {-disables the Skip and Skip All buttons} {-or Ignore and Ignore All} {--- Accented Buttons ---} procedure SetAccentSet (Accents: TAccentSet); override; {-sets the accented buttons to be displayed} {--- Suggest List ----} procedure ClearSuggestList; override; {-clears the suggest list} procedure MakeSuggestions; override; {-sets the suggest list} end; var W96SpellDlg: TW96SpellDlg; implementation {$R *.DFM} constructor TW96SpellDlg.Create (AOwner: TComponent); begin inherited Create (AOwner); end; { TW96SpellDlg.Create } {--- Extensions of TAbsSpellDialog ---} {--- Labels and Prompts ----} procedure TW96SpellDlg.SetNotFoundPrompt (ToString: String); {-sets the not found prompt} begin lblFound.Caption := ToString; end; { TMSSpellDlg.SetNotFoundPrompt } procedure TW96SpellDlg.SetNotFoundCaption (ToString: String); {-sets the not found caption} begin {edtCurWord.Text := ToString;} end; { TSpellDlg.SetNotFoundCaption } procedure TW96SpellDlg.SetEditWord (ToWord: String); {-sets the edit word string} begin edtWord.Text := ToWord; end; { TMSSpellDlg.SetEditWord } function TW96SpellDlg.GetEditWord: String; {-gets the edit word} begin Result := edtWord.Text; end; { TMSSpellDlg.GetEditWord } procedure TW96SpellDlg.SetEditAsActive; {-sets activecontrol the edit control} begin ActiveControl := btnReplace; ActiveControl := edtWord; end; { TMSSpellDlg.SetEditAsActive } procedure TW96SpellDlg.SetLabelLanguage; {-sets labels and buttons to a the language} begin inherited SetLabelLanguage; lblSpellChk.Caption := cLabels[Language][tlblSpellCheck]; lblFound.Caption := cLabels[Language][tlblFound]; btnReplace.Caption := cLabels[Language][tbtnReplace]; btnReplaceAll.Caption := cLabels[Language][tbtnReplaceAll]; btnAdd.Caption := cLabels[Language][tbtnAdd]; btnSkip.Caption := cLabels[Language][tbtnSkip]; btnSkipAll.Caption := cLabels[Language][tbtnSkipAll]; btnClose.Caption := cLabels[Language][tbtnClose]; end; { TW96SpellDlg.SetLabelLanguage } {--- Buttons ---} procedure TW96SpellDlg.EnableSkipButtons; {-enables the Skip and Skip All buttons} {-or Ignore and Ignore All} begin btnSkip.Enabled := TRUE; btnSkipAll.Enabled := TRUE; end; { TW96SpellDlg.EnableSjipButtons } procedure TW96SpellDlg.DisableSkipButtons; {-disables the Skip and Skip All buttons} {-or Ignore and Ignore All} begin btnSkip.Enabled := FALSE; btnSkipAll.Enabled := FALSE; end; { TW96SpellDlg.DisableSkipButtons } {--- Accented Buttons ---} procedure TW96SpellDlg.SetAccentSet (Accents: TAccentSet); {-sets the accented buttons to be displayed} begin lstSuggest.Height := 48; pnlIcons.Visible := FALSE; if acSpanish in Accents then pnlIcons.Visible := TRUE else lstSuggest.Height := lstSuggest.Height + pnlIcons.Height; end; { TMSSpellDlg.SetAccentSet } {--- Suggest List ----} procedure TW96SpellDlg.ClearSuggestList; {-clears the suggest list} begin lstSuggest.Clear; end; { TMSSpellDlg.ClearSuggestList } procedure TW96SpellDlg.MakeSuggestions; {-sets the suggest list} var TempList: TStringList; SaveCursor: TCursor; begin SaveCursor := Screen.Cursor; Screen.Cursor := crHourglass; Application.ProcessMessages; TempList := DCT.SuggestWords (edtWord.Text, Suggestions); lstSuggest.Items.Assign (TempList); TempList.Free; if lstSuggest.Items.Count > 0 then SetEditWord (lstSuggest.Items[0]); ActiveControl := btnReplace; Screen.Cursor := SaveCursor; end; { TMSSpellDlg.MakeSuggestions } procedure TW96SpellDlg.edtWordExit(Sender: TObject); var ChkWord: String; begin if ActiveControl is TBitBtn then exit; ChkWord := edtWord.Text; if DCT.InDictionary (ChkWord) then begin lblFound.Caption := cLabels[Language][tlblFound]; ActiveControl := btnReplace; end {:} else begin lblFound.Caption := cLabels[Language][tlblNotFound]; end; { else } end; procedure TW96SpellDlg.lstSuggestChange(Sender: TObject); begin if lstSuggest.ItemIndex<>-1 then edtWord.Text := lstSuggest.Items[lstSuggest.ItemIndex]; end; procedure TW96SpellDlg.lstSuggestDblClick(Sender: TObject); begin if lstSuggest.ItemIndex<>-1 then edtWord.Text := lstSuggest.Items[lstSuggest.ItemIndex]; btnReplaceClick (Sender); end; procedure TW96SpellDlg.AccentClick(Sender: TObject); begin if Sender is TSpeedButton then edtWord.SelText := TSpeedButton (Sender).Caption[1]; end; procedure TW96SpellDlg.btnSuggestClick(Sender: TObject); begin MakeSuggestions; end; procedure TW96SpellDlg.btnCloseClick(Sender: TObject); begin SpellDlgResult := mrCancel; end; procedure TW96SpellDlg.btnAddClick(Sender: TObject); begin SpellDlgResult := mrAdd; end; procedure TW96SpellDlg.btnReplaceClick(Sender: TObject); begin SpellDlgResult := mrReplace; end; procedure TW96SpellDlg.btnReplaceAllClick(Sender: TObject); begin SpellDlgResult := mrReplaceAll; end; procedure TW96SpellDlg.btnSkipClick(Sender: TObject); begin SpellDlgResult := mrSkipOnce; end; procedure TW96SpellDlg.btnSkipAllClick(Sender: TObject); begin SpellDlgResult := mrSkipAll; end; procedure TW96SpellDlg.QuickSuggest(Sender: TObject; var Key: Word; Shift: TShiftState); var TempList: TStringList; begin if (Shift = []) and (Char (Key) in ValidChars) then begin if edtWord.Text <> '' then begin TempList := DCT.QuickSuggest (edtWord.Text, Suggestions); lstSuggest.Items.Assign (TempList); TempList.Free; end {:} else lstSuggest.Clear; end; { if... } end; end.
unit fre_system; { (§LIC) (c) Autor,Copyright Dipl.-Ing. Helmut Hartl, Dipl.-Ing. Franz Schober, Dipl.-Ing. Christian Koch FirmOS Business Solutions GmbH www.openfirmos.org New Style BSD Licence (OSI) Copyright (c) 2001-2009, FirmOS Business Solutions GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <FirmOS Business Solutions GmbH> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (§LIC_END) } {$mode objfpc}{$H+} {$codepage UTF8} {$modeswitch nestedprocvars} {$modeswitch advancedrecords} interface uses sysutils,classes; { TFRE_DB_GUID } type TStringArray = Array of String; TFRE_DB_GUID_String = string[32]; { hex & lowercase} TFRE_DBO_DUMP_FORMAT = (sdf_Binary,sdf_DBODump,sdf_JSON,sdf_JSON_Encoded,sdf_JSON_SHORT); TFRE_DB_GUID = packed record D: Array [0..15] of Byte; function AsHexString : TFRE_DB_GUID_String; function AsBinaryString : ShortString; procedure ClearGuid ; procedure SetFromHexString (const hexs:TFRE_DB_GUID_String); function TrySetFromHexString (const hexs:TFRE_DB_GUID_String):boolean; procedure SetFromRFCISOString (const isoguid:shortstring); function IsNullGuid : Boolean; end; TFRE_DB_GUID_Access = packed record case byte of 0: ( Part1 : QWord; Part2 : QWord; ); 1: ( GUID_LOW : QWord; // 8 Byte G_PAD_1 : DWORD; // 4 Byte G_PAD_2 : Word ; // 2 Byte GUID_MODE : Byte ; // 1 Byte NODE_ID : Byte ; // 1 Byte FOS_NODE_ID = 0 Non Unique GUID ); end; { TFOS_MAC_ADDR } TFOS_MAC_ADDR = record D : Array [0..5] of Byte; function SetFromString (const mac : shortstring):boolean; function SetFromStringR (const mac : shortstring):TFOS_MAC_ADDR; function GetAsString : ShortString; procedure GenerateRandom (const universalvalid:boolean=false ; const groupaddr:boolean=false); function GetPointer : PByte; end; var cFRE_CONFIG_BINARY_ROOT :string = '/ecf/fre'; cFRE_SYSZONE_INSTALL_SRC :string = '/ecf/bootxtra/ecf_syszone_fre/'; { trailing slash is essential (rsync) } cFRE_GLOBAL_INI_DIRECTORY :string = '/opt/local/fre'; { where to find the global .ini file, Order: 1 current, 2 GLOBAL, 3 cFRE_SERVER_DEFAULT } cFRE_SERVER_DEFAULT_DIR :string = ''; { gets replaced ny CFG or NRM } cFRE_SERVER_DEFAULT_DIR_CFG :string = '/tmp/ecf/fre'; { use $ to specify paths relative to cFRE_SERVER_DEFAULT_DIR } cFRE_SERVER_DEFAULT_DIR_NRM :string = '~/fre'; { use ~ to specify paths relative to user home, } cFRE_OVERRIDE_DEFAULT_DIR :string = ''; { override the server default dir from cmdline, unconditional } cFRE_SERVER_FLEX_UX_SOCKET :string = '#/flexux'; { use # to specify path is relative to cFRE_CONFIG_BINARY_ROOT (configmode) or cFRE_SERVER_DEFAULT_DIR } cFRE_SERVER_DEFAULT_SSL_DIR :string = '#/ssl/server_files/'; cFRE_SERVER_WWW_ROOT_DIR :string = '#/www'; cFRE_SERVER_WWW_ROOT_DYNAMIC :string = '#/wwwvar'; cFRE_PS_LAYER_UXSOCK_NAME :string = 'plsrv'; cFRE_UX_SOCKS_DIR :string = ''; { override for standard server path/sockets/file} cFRE_SAFEJOB_BIN :string = '#/bin/fre_safejob'; { default location for install } cFRE_PS_LAYER_IP :string = ''; cFRE_PS_LAYER_PORT :string = ''; cFRE_PS_LAYER_HOST :string = ''; cFRE_PS_LAYER_USE_EMBEDDED :boolean= false; cFRE_HAL_CFG_DIR :string = ''; cFRE_TMP_DIR :string = ''; cFRE_JOB_RESULT_DIR :string = ''; //cFRE_JOB_PROGRESS_DIR :string = ''; cFRE_JOB_ARCHIVE_DIR :string = ''; cFRE_PID_LOCK_DIR :string = ''; cFRE_SERVER_WWW_ROOT_FILENAME :string = 'FREROOT.html'; cFRE_SERVER_DEFAULT_TIMEZONE :string = 'Europe/Vienna'; cFRE_WebServerLocation_HixiedWS :string = '127.0.0.1:44000'; cFRE_SSL_CERT_FILE :string = 'server_cert.pem'; cFRE_SSL_PRIVATE_KEY_FILE :string = 'server_key.pem'; cFRE_SSL_ROOT_CA_FILE :string = 'ca_cert.pem'; cG_OVERRIDE_USER :string = ''; { used for web autologin } cG_OVERRIDE_PASS :string = ''; cFRE_ADMIN_USER :string = 'admin@system'; cFRE_ADMIN_PASS :string = 'admin'; cFRE_PL_ADMIN_USER :string = 'sysdba'; cFRE_PL_ADMIN_PASS :string = 'sysdba'; cFRE_TASKER_PASS :string = 'tasker'; cFRE_MONITORING_HOST :string = ''; cFRE_MONITORING_USER :string = ''; cFRE_MONITORING_KEY_FILE :string = 'monitoring_id'; cFRE_MONITORING_DEST_DIR :string = ''; cFRE_ALERTING_CONFIG_FILE :string = ''; cFRE_ALERTING_STATUS_FILE :string = ''; cFRE_REMOTE_USER :string = ''; cFRE_REMOTE_HOST :string = ''; cFRE_REMOTE_SSL_ID_FILE :string = '/root/.ssh/id_rsa'; cFRE_REMOTE_SSL_PORT :integer= 22; cFRE_Feed_User :string = ''; cFRE_Feed_Pass :string = ''; cFRE_MWS_IP :string = ''; { connect the MWS non standard over a set IP } cFRE_MWS_UX :string = ''; { if set, connect the MWS over special unix socket } cFRE_SUBFEEDER_IP :string = ''; // use an IP connect for all subfeeders (portmapping is static subfeederdefined) cFRE_ToolsPath :string = '/usr'; cFRE_FORCE_CLEAR_HTTP_META :boolean=false; cFRE_FORCE_CLEAN_ZIP_HTTP_FILES :boolean=false; cFRE_BUILD_ZIP_HTTP_FILES :boolean=true; cFRE_USE_STATIC_CACHE :boolean=true; cFRE_STATIC_HTTP_CACHE_EXTS :string = '.js,.css,.html,.htm,.xhtml'; // comma seperated,lowercase (!!) cFRE_DEPLOY_CONTENT_EXTS :string = '.js,.css'; // comma seperated,lowercase (!!) cFRE_DC_NAME :string = 'DC'; //Default Datacenter for standalone box cFRE_MACHINE_NAME :string = 'CoreBox'; //Default Machine Name cFRE_MACHINE_MAC :string = ''; cFRE_MACHINE_CONFIG :pointer=nil; cFRE_MACHINE_UID :TFRE_DB_GUID; cFRE_CONFIG_SYSTEM_VERSION :string = '1.0'; cFRE_CONFIG_MODE :boolean=false; cFRE_MACHINE_IP :string = '192.168.10.42'; cFRE_DEFAULT_DOMAIN :string = 'system'; cFRE_DB_ALLOWED_APPS :string = ''; cFRE_DB_ALLOW_WEAKMEDIATORS :boolean=true; { register weak mediators for unknown classes automatically when streaming } cFRE_DB_RESET_ADMIN :boolean=false; cFRE_DB_CACHETAG :ShortString=''; cFRE_CMDLINE_DEBUG :ShortString=''; cFRE_WEAK_CLASSES_ALLOWED :boolean= false; { if false then the creation of a weak class fails } cFRE_WEB_STYLE :string = 'firmos'; cFRE_LOGIN_OVERRIDE :string = ''; cFRE_TITLE_OVERRIDE :string = ''; cFRE_JS_DEBUG :Boolean= false; cFRE_PL_ADMINS :string='sysdba'; cFRE_PL_ADMINS_PWS :String='e1NTSEF9THV4UGIzeUJqMUZ5eUl4dy82NkUrWStELzl0SU0wcExNVlZwVFE9PQ=='; cFRE_FAKE_POOL_DEVS_DIR :string='/fakepooldevs'; G_DEBUG_TRIGGER_1 :boolean=false; G_DEBUG_TRIGGER_2 :boolean=false; G_DEBUG_TRIGGER_3 :boolean=false; G_DEBUG_TRIGGER_4 :boolean=false; G_DEBUG_TRIGGER_5 :boolean=false; G_DEBUG_COUNTER :NativeInt = 0; G_DEBUG_RUNONLY_MS :NativeInt = 0; const CFRE_DB_NullGUID : TFRE_DB_GUID = ( D : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) ); CFRE_DB_DefaultDomain : TFRE_DB_GUID = ( D : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1) ); CFRE_DB_SystemDomain : TFRE_DB_GUID = ( D : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2) ); CFRE_DB_MaxGUID : TFRE_DB_GUID = ( D : ($FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF ) ); type EFRE_Exception=class(Exception) end; TFRE_LogMsg = procedure (msg:String) of object; TFRE_LogMsgN = procedure (msg:String) is nested; function GET_FOS_CACHE_TAG:ShortString;inline; function POS_FOS_CACHE_TAG(const url:string):NativeInt;inline; function RB_Guid_Compare(const d1, d2: TFRE_DB_GUID): NativeInt; inline; operator< (g1, g2: TFRE_DB_GUID) b : boolean; operator> (g1, g2: TFRE_DB_GUID) b : boolean; operator= (g1, g2: TFRE_DB_GUID) b : boolean; implementation function RB_Guid_Compare(const d1, d2: TFRE_DB_GUID): NativeInt; begin if (TFRE_DB_GUID_Access(d1).Part1=TFRE_DB_GUID_Access(d2).Part1) then begin if (TFRE_DB_GUID_Access(d1).Part2=TFRE_DB_GUID_Access(d2).Part2) then begin result := 0; end else if (TFRE_DB_GUID_Access(d1).Part2>TFRE_DB_GUID_Access(d2).Part2) then begin result := 1; end else begin result := -1; end; end else if (TFRE_DB_GUID_Access(d1).Part1>TFRE_DB_GUID_Access(d2).Part1) then begin result := 1; end else begin result := -1; end; end; operator<(g1, g2: TFRE_DB_GUID)b: boolean; begin b := RB_Guid_Compare(g1,g2) = -1; end; operator>(g1, g2: TFRE_DB_GUID)b: boolean; begin b := RB_Guid_Compare(g1,g2) = 1; end; operator=(g1, g2: TFRE_DB_GUID)b: boolean; begin b := RB_Guid_Compare(g1,g2) = 0; end; function GET_FOS_CACHE_TAG: ShortString; begin result :='.*FCT'+cFRE_DB_CACHETAG; end; function POS_FOS_CACHE_TAG(const url: string): NativeInt; begin result := Pos('.*FCT',url); end; { TFRE_DB_GUID } const cG_Digits: array[0..15] of ansichar = '0123456789abcdef'; function TFRE_DB_GUID.AsHexString: TFRE_DB_GUID_String; var n, k, h: integer; b: byte; begin SetLength(result,32); k := 16; n := 0 ; h := 0; while h < k do begin b := D[h]; Result[n + 2] := cG_Digits[b and 15]; b := b shr 4; Result[n + 1] := cG_Digits[b]; Inc(n, 2); Inc(h); end; end; function TFRE_DB_GUID.AsBinaryString: ShortString; begin SetLength(result,16); move(d[0],result[1],16); end; procedure TFRE_DB_GUID.ClearGuid; begin FillByte(d,16,0); end; procedure TFRE_DB_GUID.SetFromHexString(const hexs: TFRE_DB_GUID_String); begin if not TrySetFromHexString(hexs) then raise Exception.Create('a uid hexstring must be 32 chars and contain only vaild chars [0..9,a..f,A..F]'); end; function TFRE_DB_GUID.TrySetFromHexString(const hexs: TFRE_DB_GUID_String): boolean; var i,j : NativeInt; v1,v2 : integer; function _dig2int(const dig:ansichar):integer;inline; begin result:=0; case dig of '0','1','2','3','4','5','6','7','8','9': begin result:=ord(dig)-48; end; 'A','B','C','D','E','F':begin result:=ord(dig)-55; end; 'a','b','c','d','e','f': begin result:=ord(dig)-87; end else result := -1; end; end; begin i := Length(hexs); if i<>32 then exit(false); i:=1 ; j:=0; while i<32 do begin v1 := _dig2int(hexs[i]); if v1=-1 then exit(false); v2 := _dig2int(hexs[i+1]); if v2=-1 then exit(false); D[j] := v1*16+v2; // conservative inc(i,2);inc(j); end; result := true; end; procedure TFRE_DB_GUID.SetFromRFCISOString(const isoguid: shortstring); var p: PChar; function rb: Byte; var hb: Byte; begin case p^ of '0'..'9': hb := Byte(p^) - Byte('0'); 'a'..'f': hb := Byte(p^) - Byte('a') + 10; 'A'..'F': hb := Byte(p^) - Byte('A') + 10; else raise Exception.Create('invalid char in iso uid: '+p^); end; Inc(p); case p^ of '0'..'9': Result := Byte(p^) - Byte('0'); 'a'..'f': Result := Byte(p^) - Byte('a') + 10; 'A'..'F': Result := Byte(p^) - Byte('A') + 10; else raise Exception.Create('invalid char in iso uid: '+p^); end; Inc(p); Result := hb shl 4 or Result; end; procedure nextChar(c: Char); inline; begin if p^ <> c then raise Exception.Create('invalid nextchar in iso uid: '+p^+', should be '+c); Inc(p); end; begin if Length(isoguid)<>38 then raise Exception.Create('a iso uid must be 38 chars not '+inttostr(Length(isoguid))+' chars'); p := PChar(@isoguid[1]); nextChar('{'); D[0] := rb; D[1] := rb; D[2] := rb; D[3] := rb; nextChar('-'); D[4] := rb; D[5] := rb; nextChar('-'); D[6] := rb; D[7] := rb; nextChar('-'); D[8] := rb; D[9] := rb; nextChar('-'); D[10] := rb; D[11] := rb; D[12] := rb; D[13] := rb; D[14] := rb; D[15] := rb; nextChar('}'); end; function TFRE_DB_GUID.IsNullGuid: Boolean; begin result := self=CFRE_DB_NullGUID; end; { TFOS_MAC_ADDR } function TFOS_MAC_ADDR.SetFromString(const mac: shortstring): boolean; var conv : ShortString; bytes : string; len : NativeInt; begin if length(mac)<>17 then exit(false); conv := StringReplace(mac,':','',[rfReplaceAll]); if Length(conv)<>12 then exit(false); len := HexToBin(@conv[1],@D[0],6); result := len=6; end; function TFOS_MAC_ADDR.SetFromStringR(const mac: shortstring): TFOS_MAC_ADDR; begin if not SetFromString(mac) then raise Exception.Create('bad mac address format'); result := self; end; function FRESYS_Mem2HexStr(const Value : PByte; const len: integer): ansistring; var n, k, h: integer; b: byte; begin Result := ''; k := len; setlength(Result, k * 2); n := 0; h := 0; while h < k do begin b := byte(Value[h]); Result[n + 2] := cG_Digits[b and 15]; b := b shr 4; Result[n + 1] := cG_Digits[b]; Inc(n, 2); Inc(h); end; end; function TFOS_MAC_ADDR.GetAsString: ShortString; var h:string; begin result := FRESYS_Mem2HexStr(@D[0],1)+':'+ FRESYS_Mem2HexStr(@D[1],1)+':'+ FRESYS_Mem2HexStr(@D[2],1)+':'+ FRESYS_Mem2HexStr(@D[3],1)+':'+ FRESYS_Mem2HexStr(@D[4],1)+':'+ FRESYS_Mem2HexStr(@D[5],1); end; procedure TFOS_MAC_ADDR.GenerateRandom(const universalvalid: boolean; const groupaddr: boolean); begin D[0] := Random(255); D[1] := Random(255); D[2] := Random(255); D[3] := Random(255); D[4] := Random(255); D[5] := Random(255); if groupaddr then D[0] := D[0] OR 1 else D[0] := D[0] AND $FE; if universalvalid then D[0] := D[0] AND $FD else D[0] := D[0] OR $02; end; function TFOS_MAC_ADDR.GetPointer: PByte; begin result := @D[0]; end; initialization G_DEBUG_RUNONLY_MS := StrToIntDef(GetEnvironmentVariable('FOS_DBG_RUNONLY_MS'),0); end.
unit uUserUtils; interface uses System.SysUtils, System.Classes, Winapi.Windows, Winapi.ShellApi, Dmitry.Utils.System, uMemory, uAppUtils; function RunAsAdmin(hWnd: HWND; FileName: string; Parameters: string; IsCurrentUserAdmin: Boolean): THandle; function RunAsUser(ExeName, ParameterString, WorkDirectory: string; Wait: Boolean): THandle; procedure ProcessCommands(FileName: string); procedure UserAccountService(FileName: string; IsCurrentUserAdmin : Boolean); implementation function GetTempDirectory: string; var TempFolder: array[0..MAX_PATH] of Char; begin GetTempPath(MAX_PATH, @tempFolder); Result := StrPas(TempFolder); end; function GetTempFileName: TFileName; var TempFileName: array [0..MAX_PATH-1] of char; begin if Winapi.Windows.GetTempFileName(PChar(GetTempDirectory), '~', 0, TempFileName) = 0 then raise Exception.Create(SysErrorMessage(GetLastError)); Result := TempFileName; end; procedure UserAccountService(FileName: string; IsCurrentUserAdmin: Boolean); var InstallHandle: THandle; CommandsFileName: string; ExitCode: Cardinal; begin CommandsFileName := GetTempFileName; CloseHandle(CreateFile(PChar(CommandsFileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL or FILE_ATTRIBUTE_NOT_CONTENT_INDEXED, 0)); try InstallHandle := RunAsAdmin(0, FileName, '/admin /commands "' + CommandsFileName + '"', IsCurrentUserAdmin); if InstallHandle <> 0 then begin if InstallHandle > 0 then begin repeat Sleep(100); ProcessCommands(CommandsFileName); GetExitCodeProcess(InstallHandle, ExitCode); until ExitCode <> STILL_ACTIVE; end; end; finally DeleteFile(PChar(CommandsFileName)); end; end; function RunAsAdmin(hWnd: HWND; FileName: string; Parameters: string; IsCurrentUserAdmin: Boolean): THandle; { See Step 3: Redesign for UAC Compatibility (UAC) http://msdn.microsoft.com/en-us/library/bb756922.aspx } var sei: TShellExecuteInfo; begin ZeroMemory(@sei, SizeOf(sei)); sei.cbSize := SizeOf(TShellExecuteInfo); sei.Wnd := hwnd; sei.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI or SEE_MASK_NOCLOSEPROCESS; if not IsCurrentUserAdmin then sei.lpVerb := PChar('runas') else sei.lpVerb := PChar('open'); sei.lpFile := PChar(FileName); // PAnsiChar; if parameters <> '' then sei.lpParameters := PChar(parameters); // PAnsiChar; sei.nShow := SW_SHOWNORMAL; //Integer; Result := 0; if ShellExecuteEx(@sei) then Result := sei.hProcess; end; function RunAsUser(ExeName, ParameterString, WorkDirectory: string; Wait: Boolean): THandle; var FS: TFileStream; SW: TStreamWriter; SR: TStreamReader; StartTime: Cardinal; Res: Integer; CommandFileName: string; begin CommandFileName := GetParamStrDBValue('/commands'); Result := 0; try FS := TFileStream.Create(CommandFileName, fmOpenWrite); try FS.Size := 0; SW := TStreamWriter.Create(FS); try SW.Write(ExeName); SW.WriteLine; SW.Write(ParameterString); SW.WriteLine; SW.Write(WorkDirectory); SW.WriteLine; SW.Write(IIF(Wait, '1', '0')); SW.WriteLine; finally F(SW); end; finally F(FS); end; except Exit; end; StartTime := GetTickCount; while GetTickCount - StartTime < 1000 * 30 do begin Sleep(1000); try FS := TFileStream.Create(CommandFileName, fmOpenRead or fmShareDenyNone); try SR := TStreamReader.Create(FS); try Res := StrToIntDef(SR.ReadLine, -1); if Res >= 0 then begin Result := Res; Break; end; finally F(SR); end; finally F(FS); end; except Continue; end; end; end; procedure ProcessCommands(FileName: string); var StartInfo: TStartupInfo; ProcInfo: TProcessInformation; FS: TFileStream; SR: TStreamReader; SW: TStreamWriter; ExeFileName, ExeParams, ExeDirectory: string; WaitProgram: Boolean; procedure WritePID(PID: Integer); begin try FS := TFileStream.Create(FileName, fmOpenWrite); try FS.Size := 0; SW := TStreamWriter.Create(FS); try SW.Write(IntToStr(PID)); finally F(SW); end; finally F(FS); end; except Exit; end; end; begin try FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone); try SR := TStreamReader.Create(FS); try ExeFileName := SR.ReadLine; ExeParams := SR.ReadLine; ExeDirectory := SR.ReadLine; WaitProgram := SR.ReadLine = '1'; finally F(SR); end; finally F(FS); end; except Exit; end; if (ExeFileName <> '') and (ExeFileName = ExeParams) and (ExeFileName = ExeDirectory) then begin ShellExecute(0, 'open', PWideChar(ExeFileName), nil, nil, SW_NORMAL); WritePID(0); end; if FileExists(ExeFileName) and (ExeParams <> '') and (ExeDirectory <> '') then begin { fill with known state } FillChar(StartInfo, SizeOf(TStartupInfo), #0); FillChar(ProcInfo, SizeOf(TProcessInformation), #0); try with StartInfo do begin cb := SizeOf(StartInfo); dwFlags := STARTF_USESHOWWINDOW; wShowWindow := SW_NORMAL; end; CreateProcess(nil, PChar('"' + ExeFileName + '"' + ' ' + ExeParams), nil, nil, False, CREATE_DEFAULT_ERROR_MODE or NORMAL_PRIORITY_CLASS, nil, PChar(ExcludeTrailingPathDelimiter(ExeDirectory)), StartInfo, ProcInfo); if WaitProgram then WaitForSingleObject(ProcInfo.hProcess, 30000); WritePID(ProcInfo.hProcess); finally CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end; end; end; end.
{ Copyright (c) 2016 by Albert Molina Copyright (c) 2017 by BlaiseCoin developers Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. This unit is a part of BlaiseCoin, a P2P crypto-currency. } unit upcdaemon; {$mode objfpc}{$H+} interface uses Classes, SysUtils, SyncObjs, IniFiles, daemonapp, UOpenSSL, UCrypto, UNode, UFileStorage, UFolderHelper, UWalletKeys, UConst, ULog, UNetProtocol, UThread, URPC, UPoolMining, UAccounts; Const CT_INI_SECTION_GLOBAL = 'GLOBAL'; CT_INI_IDENT_SAVELOGS = 'SAVELOGS'; CT_INI_IDENT_RPC_PORT = 'RPC_PORT'; CT_INI_IDENT_RPC_WHITELIST = 'RPC_WHITELIST'; CT_INI_IDENT_RPC_SAVELOGS = 'RPC_SAVELOGS'; CT_INI_IDENT_RPC_SERVERMINER_PORT = 'RPC_SERVERMINER_PORT'; CT_INI_IDENT_MINER_B58_PUBLICKEY = 'RPC_SERVERMINER_B58_PUBKEY'; CT_INI_IDENT_MINER_NAME = 'RPC_SERVERMINER_NAME'; CT_INI_IDENT_MINER_MAX_CONNECTIONS = 'RPC_SERVERMINER_MAX_CONNECTIONS'; Type { TPCDaemonThread } TPCDaemonThread = class(TPCThread) private FIniFile : TIniFile; protected procedure BCExecute; override; public constructor Create; destructor Destroy; override; end; { TPCDaemon } TPCDaemon = class(TCustomDaemon) private FThread : TPCDaemonThread; procedure ThreadStopped (Sender : TObject); public function Start : Boolean; override; function Stop : Boolean; override; function Pause : Boolean; override; function Continue : Boolean; override; function Execute : Boolean; override; function ShutDown : Boolean; override; function Install : Boolean; override; function UnInstall: boolean; override; end; { TPCDaemonMapper } TPCDaemonMapper = class(TCustomDaemonMapper) private FLog : TLog; procedure OnPascalCoinInThreadLog(logtype : TLogType; Time : TDateTime; AThreadID : Cardinal; Const sender, logtext : AnsiString); protected procedure DoOnCreate; override; procedure DoOnDestroy; override; public end; implementation var _FLog : TLog; { TPCDaemonThread } constructor TPCDaemonThread.Create; begin inherited Create(True); FIniFile := TIniFile.Create( ExtractFileDir(Application.ExeName) + PathDelim + 'blaisecoin_daemon.ini'); if FIniFile.ReadBool(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_SAVELOGS, True) then begin _FLog.SaveTypes := CT_TLogTypes_ALL; _FLog.FileName := TFolderHelper.GetPascalCoinDataFolder + PathDelim + 'blaisecoin_' + FormatDateTime('yyyymmddhhnn', Now) + '.log'; FIniFile.WriteBool(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_SAVELOGS, True); end else begin FIniFile.WriteBool(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_SAVELOGS, False); end; end; destructor TPCDaemonThread.Destroy; begin FreeAndNil(FIniFile); inherited Destroy; end; procedure TPCDaemonThread.BCExecute; var FNode : TNode; FWalletKeys : TWalletKeysExt; FRPC : TRPCServer; FMinerServer : TPoolMiningServer; procedure InitRPCServer; var port : Integer; Begin port := FIniFile.ReadInteger(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_RPC_PORT, -1); if port <= 0 then begin FIniFile.WriteInteger(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_RPC_PORT, CT_JSONRPC_Port); port := CT_JSONRPC_Port; TLog.NewLog(ltInfo, ClassName, 'Saving RPC server port to IniFile: ' + IntToStr(port)); end; FRPC := TRPCServer.Create; FRPC.WalletKeys := FWalletKeys; FRPC.Port:=port; FRPC.Active:=True; FRPC.ValidIPs := FIniFile.ReadString(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_RPC_WHITELIST, '127.0.0.1;'); TLog.NewLog(ltInfo, ClassName, 'RPC server is active on port ' + IntToStr(port)); if FIniFile.ReadBool(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_RPC_SAVELOGS, True) then begin FIniFile.WriteBool(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_RPC_SAVELOGS, True); FRPC.LogFileName := TFolderHelper.GetPascalCoinDataFolder + PathDelim + 'blaisecoin_rpc.log'; TLog.NewLog(ltInfo, ClassName, 'Writing RPC log to file ' + FRPC.LogFileName); end else begin FIniFile.WriteBool(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_RPC_SAVELOGS, False); TLog.NewLog(ltInfo, ClassName, 'Not writing RPC log to file'); end; end; procedure InitRPCMinerServer; var i, port, maxconnections : Integer; s : String; pubkey : TAccountKey; errors : AnsiString; ECPK : TECPrivateKey; begin i := FIniFile.ReadInteger(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_RPC_SERVERMINER_PORT, -1); if i < 0 then i := CT_JSONRPCMinerServer_Port; if i > 0 then begin port := i; FIniFile.WriteInteger(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_RPC_SERVERMINER_PORT, port); pubkey := CT_TECDSA_Public_Nul; s := Trim(FIniFile.ReadString(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_MINER_B58_PUBLICKEY, '')); if (s = '') or (not TAccountComp.AccountKeyFromImport(s, pubkey, errors)) then begin if s <> '' then TLog.NewLog(lterror, Classname, 'Invalid INI file public key: ' + errors); i := 0; while (i<FWalletKeys.Count) and (pubkey.EC_OpenSSL_NID = CT_TECDSA_Public_Nul.EC_OpenSSL_NID) do begin if FWalletKeys.Key[i].CryptedKey <> '' then pubkey := FWalletKeys[i].AccountKey else inc(i); end; if (pubkey.EC_OpenSSL_NID = CT_TECDSA_Public_Nul.EC_OpenSSL_NID) then begin // New key ECPK := TECPrivateKey.Create; try ECPK.GenerateRandomPrivateKey(CT_Default_EC_OpenSSL_NID); FWalletKeys.AddPrivateKey('RANDOM NEW BY DAEMON ' + FormatDateTime('yyyy-mm-dd hh:nn:dd', now), ECPK); pubkey := ECPK.PublicKey; FIniFile.WriteString(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_MINER_B58_PUBLICKEY, TAccountComp.AccountKeyToExport(pubkey)); TLog.NewLog(ltInfo, ClassName, 'Generated new pubkey for miner: ' + TAccountComp.AccountKeyToExport(pubkey)); finally ECPK.Free; end; end; end else begin // pubkey is mine? if FWalletKeys.IndexOfAccountKey(pubkey) < 0 then begin TLog.NewLog(lterror, classname, 'WARNING: Using a public key without private key in wallet! ' + TAccountComp.AccountKeyToExport(pubkey)); end; end; i := FWalletKeys.IndexOfAccountKey(pubkey); s := Trim(FIniFile.ReadString(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_MINER_NAME, '')); if SameText(s, 'TIME') then begin s := FormatDateTime('yyyy-mm-dd', Now); TLog.NewLog(ltInfo, ClassName, 'Generated new miner name: ' + s); end; maxconnections := FIniFile.ReadInteger(CT_INI_SECTION_GLOBAL, CT_INI_IDENT_MINER_MAX_CONNECTIONS, 1000); TLog.NewLog(ltinfo, ClassName, Format('Activating RPC Miner Server on port %d, name "%s", max conections %d and public key %s', [port, s, maxconnections, TAccountComp.AccountKeyToExport(pubkey)])); FMinerServer := TPoolMiningServer.Create; FMinerServer.UpdateAccountAndPayload(pubkey, s); FMinerServer.Port:=port; FMinerServer.Active:=True; FMinerServer.MaxConnections:=maxconnections; end else begin TLog.NewLog(ltinfo, ClassName, 'RPC Miner Server NOT ACTIVE (Ini file is ' + CT_INI_IDENT_RPC_SERVERMINER_PORT + '=0)'); end; end; begin FMInerServer := nil; TLog.NewLog(ltinfo, Classname, 'START BlaiseCoin Server'); try try FWalletKeys := TWalletKeysExt.Create(nil); // Load Node // Check OpenSSL dll if not LoadSSLCrypt then begin WriteLn('Cannot load ' + SSL_C_LIB); WriteLn('To use this software make sure this file is available on you system or reinstall the application'); raise Exception.Create('Cannot load ' + SSL_C_LIB + #10 + 'To use this software make sure this file is available on you system or reinstall the application'); end; TCrypto.InitCrypto; FWalletKeys.WalletFileName := TFolderHelper.GetPascalCoinDataFolder + PathDelim + 'WalletKeys.dat'; // Creating Node: FNode := TNode.Node; // RPC Server InitRPCServer; try // Check Database FNode.Bank.StorageClass := TFileStorage; TFileStorage(FNode.Bank.Storage).DatabaseFolder := TFolderHelper.GetPascalCoinDataFolder + PathDelim + 'Data'; // Reading database FNode.Node.Bank.DiskRestoreFromOperations(CT_MaxBlock); FWalletKeys.SafeBox := FNode.Node.Bank.SafeBox; FNode.Node.AutoDiscoverNodes(CT_Discover_IPs); FNode.Node.NetServer.Active := True; // RPC Miner Server InitRPCMinerServer; try repeat Sleep(100); until Terminated; finally FreeAndNil(FMinerServer); end; finally FreeAndNil(FRPC); end; FNode.NetServer.Active := False; TNetData.NetData.Free; FreeAndNil(FNode); except on e:Exception do begin TLog.NewLog(lterror, Classname, 'Exception ' + E.Classname + ': ' + E.Message); end; end; finally TLog.NewLog(ltinfo, Classname, 'EXIT BlaiseCoin Server'); end; end; { TPCDaemon } procedure TPCDaemon.ThreadStopped(Sender: TObject); begin FreeAndNil(FThread); end; function TPCDaemon.Start: Boolean; begin Result:=inherited Start; TLog.NewLog(ltinfo, ClassName, 'Daemon Start ' + BoolToStr(Result)); FThread := TPCDaemonThread.Create; FThread.OnTerminate := @ThreadStopped; FThread.FreeOnTerminate := False; FThread.Resume; end; function TPCDaemon.Stop: Boolean; begin Result := inherited Stop; TLog.NewLog(ltinfo, ClassName, 'Daemon Stop: ' + BoolToStr(Result)); FThread.Terminate; end; function TPCDaemon.Pause: Boolean; begin Result := inherited Pause; TLog.NewLog(ltinfo, ClassName, 'Daemon pause: ' + BoolToStr(Result)); FThread.Suspend; end; function TPCDaemon.Continue: Boolean; begin Result := inherited Continue; TLog.NewLog(ltinfo, ClassName, 'Daemon continue: ' + BoolToStr(Result)); FThread.Resume; end; function TPCDaemon.Execute: Boolean; begin Result := inherited Execute; TLog.NewLog(ltinfo, ClassName, 'Daemon execute: ' + BoolToStr(Result)); end; function TPCDaemon.ShutDown: Boolean; begin Result := inherited ShutDown; TLog.NewLog(ltinfo, ClassName, 'Daemon Shutdown: ' + BoolToStr(Result)); FThread.Terminate; end; function TPCDaemon.Install: Boolean; begin Result := inherited Install; TLog.NewLog(ltinfo, ClassName, 'Daemon Install: ' + BoolToStr(Result)); end; function TPCDaemon.UnInstall: boolean; begin Result := inherited UnInstall; TLog.NewLog(ltinfo, ClassName, 'Daemon UnInstall: ' + BoolToStr(Result)); end; { TPCDaemonMapper } procedure TPCDaemonMapper.DoOnCreate; var D : TDaemonDef; begin inherited DoOnCreate; WriteLn(''); WriteLn(formatDateTime('dd/mm/yyyy hh:nn:ss.zzz', now) + ' Starting BlaiseCoin server'); FLog := TLog.Create(Nil); FLog.OnInThreadNewLog := @OnPascalCoinInThreadLog; _FLog := FLog; D := DaemonDefs.Add as TDaemonDef; D.DisplayName := 'BlaiseCoin Daemon'; D.Name := 'BlaiseCoinDaemon'; D.DaemonClassName := 'TPCDaemon'; D.WinBindings.ServiceType := stWin32; end; procedure TPCDaemonMapper.DoOnDestroy; begin if Assigned(FLog) then begin FLog.OnInThreadNewLog := nil; FreeAndNil(FLog); end; inherited DoOnDestroy; end; procedure TPCDaemonMapper.OnPascalCoinInThreadLog(logtype: TLogType; Time: TDateTime; AThreadID: Cardinal; const sender, logtext: AnsiString); var s : AnsiString; begin // if not SameText(sender, TPCDaemonThread.ClassName) then exit; if logtype in [lterror, ltinfo] then begin if AThreadID = MainThreadID then s := ' MAIN:' else s := ' TID:'; WriteLn(formatDateTime('dd/mm/yyyy hh:nn:ss.zzz', Time) + s + IntToHex(AThreadID, 8) + ' [' + CT_LogType[Logtype] + '] <' + sender + '> ' + logtext); end; end; end.
// // Generated by JavaToPas v1.4 20140515 - 181007 //////////////////////////////////////////////////////////////////////////////// unit javax.net.ssl.SSLEngineResult_HandshakeStatus; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JSSLEngineResult_HandshakeStatus = interface; JSSLEngineResult_HandshakeStatusClass = interface(JObjectClass) ['{644E4710-630B-4AE3-BAA8-27CC0717BB6B}'] function _GetFINISHED : JSSLEngineResult_HandshakeStatus; cdecl; // A: $4019 function _GetNEED_TASK : JSSLEngineResult_HandshakeStatus; cdecl; // A: $4019 function _GetNEED_UNWRAP : JSSLEngineResult_HandshakeStatus; cdecl; // A: $4019 function _GetNEED_WRAP : JSSLEngineResult_HandshakeStatus; cdecl; // A: $4019 function _GetNOT_HANDSHAKING : JSSLEngineResult_HandshakeStatus; cdecl; // A: $4019 function valueOf(&name : JString) : JSSLEngineResult_HandshakeStatus; cdecl;// (Ljava/lang/String;)Ljavax/net/ssl/SSLEngineResult$HandshakeStatus; A: $9 function values : TJavaArray<JSSLEngineResult_HandshakeStatus>; cdecl; // ()[Ljavax/net/ssl/SSLEngineResult$HandshakeStatus; A: $9 property FINISHED : JSSLEngineResult_HandshakeStatus read _GetFINISHED; // Ljavax/net/ssl/SSLEngineResult$HandshakeStatus; A: $4019 property NEED_TASK : JSSLEngineResult_HandshakeStatus read _GetNEED_TASK; // Ljavax/net/ssl/SSLEngineResult$HandshakeStatus; A: $4019 property NEED_UNWRAP : JSSLEngineResult_HandshakeStatus read _GetNEED_UNWRAP;// Ljavax/net/ssl/SSLEngineResult$HandshakeStatus; A: $4019 property NEED_WRAP : JSSLEngineResult_HandshakeStatus read _GetNEED_WRAP; // Ljavax/net/ssl/SSLEngineResult$HandshakeStatus; A: $4019 property NOT_HANDSHAKING : JSSLEngineResult_HandshakeStatus read _GetNOT_HANDSHAKING;// Ljavax/net/ssl/SSLEngineResult$HandshakeStatus; A: $4019 end; [JavaSignature('javax/net/ssl/SSLEngineResult_HandshakeStatus')] JSSLEngineResult_HandshakeStatus = interface(JObject) ['{10310557-2FB4-41F5-A361-8AD243EFBEC2}'] end; TJSSLEngineResult_HandshakeStatus = class(TJavaGenericImport<JSSLEngineResult_HandshakeStatusClass, JSSLEngineResult_HandshakeStatus>) end; implementation end.
unit Tests.TCommandFactory; interface uses DUnitX.TestFramework, System.Classes, System.SysUtils, Vcl.Pattern.Command; {$TYPEINFO ON} { Requred for old RTTI metadata form published section } type [TestFixture] TFactoryNoInjectionTest = class(TObject) strict private FOwnerComponent: TComponent; FCommandA: TCommand; public [Setup] procedure Setup; [TearDown] procedure TearDown; published procedure TestAdhocExecuteCommand; procedure TestCreateCommandProperType; procedure TestCreateCommandAndDestroyOwner; procedure TestExecuteCommandAndCheckActive; procedure TestNotExecuteCommand_CounterZero; procedure TestCounter_ExecuteCommand2x; end; [TestFixture] TFactoryWithOneInjectionTest = class(TObject) strict private FStrings: TStringList; FOwnerComponent: TComponent; private public [Setup] procedure Setup; [TearDown] procedure TearDown; published procedure TestInjection_AssertOneInjection; procedure TestInjection_ExecuteAndCheckLinesCount; procedure NoRequiredInjectionException; end; [TestFixture] TFactoryWithMoreInjectionsTest = class(TObject) strict private FStrings1: TStringList; FStrings2: TStringList; FSampleComponent: TComponent; FOwnerComponent: TComponent; private public [Setup] procedure Setup; [TearDown] procedure TearDown; published procedure InjectDependencies; procedure VerifiyDependenciesAfterExecute; end; implementation // ------------------------------------------------------------------------ // class TCommandA // ------------------------------------------------------------------------ {$REGION 'class TCommandA'} type TCommandA = class(TCommand) strict private FActive: boolean; FCount: integer; protected procedure Guard; override; public class var IsExecuted: boolean; class var IsDestroyed: boolean; procedure Execute; override; destructor Destroy; override; property Active: boolean read FActive write FActive; property Count: integer read FCount write FCount; end; procedure TCommandA.Guard; begin end; destructor TCommandA.Destroy; begin IsDestroyed := True; inherited; end; procedure TCommandA.Execute; begin Active := True; IsExecuted := True; Count := Count + 1; end; {$ENDREGION} // ------------------------------------------------------------------------ // class TCommandStringList // ------------------------------------------------------------------------ {$REGION 'class TCommandStringList'} type TCommandStringList = class(TCommand) strict private FCount: integer; FLines: TStringList; protected procedure Guard; override; public procedure Execute; override; property Count: integer read FCount write FCount; published property Lines: TStringList read FLines write FLines; end; procedure TCommandStringList.Guard; begin System.Assert(Lines <> nil); end; procedure TCommandStringList.Execute; begin inherited; Count := Count + 1; Lines.Add(Format('%.3d', [Count])); end; {$ENDREGION} // ------------------------------------------------------------------------ // class TCommandMore // ------------------------------------------------------------------------ {$REGION 'class TCommandMore'} type TCommandMore = class(TCommand) strict private FCount: integer; FEvenLines: TStringList; FOddLines: TStringList; FComponent: TComponent; protected procedure Guard; override; public procedure Execute; override; property Count: integer read FCount write FCount; published property OddLines: TStringList read FOddLines write FOddLines; property Component: TComponent read FComponent write FComponent; property EvenLines: TStringList read FEvenLines write FEvenLines; end; procedure TCommandMore.Guard; begin System.Assert(EvenLines <> nil); System.Assert(OddLines <> nil); System.Assert(Component <> nil); end; procedure TCommandMore.Execute; begin inherited; Count := Count + 1; if Odd(Count) then begin OddLines.Add(Format('%.3d - %s', [Count, Component.Name])); Component.Name := 'A' + Component.Name; end else EvenLines.Add(Format('%.3d', [Count])); end; {$ENDREGION} // ------------------------------------------------------------------------ // TFactoryNoInjectionTest: TCommandA // ------------------------------------------------------------------------ {$REGION 'TCommandFactoryTests: TCommandA - no injection'} procedure TFactoryNoInjectionTest.Setup; begin FOwnerComponent := TComponent.Create(nil); // used as Owner for TCommand-s FCommandA := TCommandVclFactory.CreateCommand<TCommandA>(FOwnerComponent, []); TCommandA.IsExecuted := False; end; procedure TFactoryNoInjectionTest.TearDown; begin FOwnerComponent.Free; // FCommandA destroyed by Owner TCommandA.IsExecuted := False; end; procedure TFactoryNoInjectionTest.TestAdhocExecuteCommand; begin TCommandVclFactory.ExecuteCommand<TCommandA>([]); Assert.IsTrue(TCommandA.IsExecuted, 'TCommandA not executed'); end; procedure TFactoryNoInjectionTest.TestCreateCommandProperType; var cmd: TCommandA; begin cmd := TCommandVclFactory.CreateCommand<TCommandA>(FOwnerComponent, []); Assert.InheritsFrom(cmd.ClassType, TCommandA); end; procedure TFactoryNoInjectionTest.TestCreateCommandAndDestroyOwner; var AOwner: TComponent; begin TCommandA.IsDestroyed := False; AOwner := TComponent.Create(nil); TCommandVclFactory.CreateCommand<TCommandA>(AOwner, []); AOwner.Free; Assert.IsTrue(TCommandA.IsDestroyed); end; procedure TFactoryNoInjectionTest.TestExecuteCommandAndCheckActive; begin FCommandA.Execute; Assert.IsTrue((FCommandA as TCommandA).Active, 'TCommanndA.Active property expected True'); end; procedure TFactoryNoInjectionTest.TestNotExecuteCommand_CounterZero; begin Assert.AreEqual(0, (FCommandA as TCommandA).Count); end; procedure TFactoryNoInjectionTest.TestCounter_ExecuteCommand2x; begin FCommandA.Execute; FCommandA.Execute; Assert.AreEqual(2, (FCommandA as TCommandA).Count); end; {$ENDREGION} // ------------------------------------------------------------------------ // TFactoryWithInjectionTest: TStringList one injection // ------------------------------------------------------------------------ {$REGION 'TCommandFactoryTests: TCommandStringList - check injection'} procedure TFactoryWithOneInjectionTest.Setup; begin FOwnerComponent := TComponent.Create(nil); // used as Owner for TCommand-s FStrings := TStringList.Create(); end; procedure TFactoryWithOneInjectionTest.TearDown; begin FOwnerComponent.Free; FreeAndNil(FStrings); end; procedure TFactoryWithOneInjectionTest.TestInjection_AssertOneInjection; begin TCommandVclFactory.ExecuteCommand<TCommandStringList>([FStrings]); Assert.Pass; // Fine is there was any exception above - correct injection end; procedure TFactoryWithOneInjectionTest.TestInjection_ExecuteAndCheckLinesCount; var cmd: TCommandStringList; begin cmd := TCommandVclFactory.CreateCommand<TCommandStringList>(FOwnerComponent, [FStrings]); cmd.Execute; cmd.Execute; cmd.Lines.Delete(0); Assert.AreEqual(1, cmd.Lines.Count); end; procedure TFactoryWithOneInjectionTest.NoRequiredInjectionException; begin Assert.WillRaiseDescendant( procedure begin TCommandVclFactory.ExecuteCommand<TCommandStringList>([]); end, EAssertionFailed); end; {$ENDREGION} // ------------------------------------------------------------------------ // CommandFactory tests factory methods with more injection // * 2x TStringList, 1x TComponent // ------------------------------------------------------------------------ {$REGION 'TFactoryWithMoreInjectionTest: check more injection'} procedure TFactoryWithMoreInjectionsTest.Setup; begin FStrings1 := TStringList.Create; FStrings2 := TStringList.Create; FSampleComponent := TComponent.Create(nil); FSampleComponent.Name := 'NothingBox'; // have to see Mark Gungor in action: https://www.youtube.com/watch?v=SWiBRL-bxiA FOwnerComponent := TComponent.Create(nil); end; procedure TFactoryWithMoreInjectionsTest.TearDown; begin FreeAndNil(FStrings1); FreeAndNil(FStrings2); FreeAndNil(FSampleComponent); FreeAndNil(FOwnerComponent); end; procedure TFactoryWithMoreInjectionsTest.InjectDependencies; begin Assert.WillNotRaise( procedure begin TCommandVclFactory.ExecuteCommand<TCommandMore>([FStrings1, FStrings2, FSampleComponent]); end); end; procedure TFactoryWithMoreInjectionsTest.VerifiyDependenciesAfterExecute; begin TCommandVclFactory.ExecuteCommand<TCommandMore> ([FStrings1, FStrings2, FSampleComponent]); Assert.AreEqual(1, FStrings1.Count); Assert.AreEqual(0, FStrings2.Count); Assert.AreEqual('ANothingBox', FSampleComponent.Name); end; {$ENDREGION} // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ initialization TDUnitX.RegisterTestFixture(TFactoryNoInjectionTest); TDUnitX.RegisterTestFixture(TFactoryWithOneInjectionTest); TDUnitX.RegisterTestFixture(TFactoryWithMoreInjectionsTest); end.
program pacmanmodif; uses keyboard, crt, SysUtils, MMSystem; const MAX = 100; type Maze = Array[1..MAX, 1..MAX] of char; function readChoice(): Integer; var choice : Integer; begin write('Please type your choice: '); readln(choice); readChoice := choice; end; function readMapFilename(): string; var choice : Integer; begin clrscr(); TextColor(Yellow); writeln('----------------------------------------------------------'); Writeln(' Available pistes: ''INSA'' and ''STPI'''); writeln('----------------------------------------------------------'); Writeln(' 1. INSA' ); Writeln(' 2. STPI' ); choice := readChoice(); case (choice) of 1: readMapFilename := 'insa.txt'; 2: readMapFilename := 'stpi.txt'; end; end; procedure victory(score: Integer); begin PlaySound('pacman_beginning.wav',0, SND_ASYNC); TextColor(LightGreen); writeln('----------------------------------------------------------'); writeln(' VICTORY'); writeln('----------------------------------------------------------'); writeln(''); writeln('Your score is: ', score); writeln(''); writeln('Press enter to go back to main menu'); writeln(''); readln(); end; function loadMaze(filename: String; var m: Maze; var width: Integer; var height: Integer; var dots : Integer; var pX: Integer; var pY: Integer): Boolean; var fp: Text; lig, col: Integer; line: String; begin if (not FileExists(filename)) then // check that file exists begin writeln('File not found. Aborting load'); loadMaze := false; Exit(); end; writeln('Opening file ... '); Assign(fp, filename); // assign {$i-} reset(fp); // open file {$i+} if (IOResult <> 0) then // check that file is accessible begin writeln('Access denied.'); loadMaze := false; Exit(); end; writeln('Loading maze ... please wait ...'); read(fp, width); // load dimensions readln(fp, height); writeln(' Width: ', width); writeln(' Height: ', height); if (width < 1) or (width > MAX) or (height < 1) or (height > MAX) then begin writeln('Dimensions out of range'); // check dimensions loadMaze := false; Exit(); end; // load maze for lig := 1 to height do // for each byte in line begin readln(fp, line); // read a line for col := 1 to width do // for each byte in line begin if (line[col]= 'o')then begin pX:= col; pY:= lig; end else m[col][lig] := line[col]; if (line[col]= '.')or(line[col]= '*') then dots:=dots+1; end; end; // close file Close(fp); end; procedure printMaze(m: Maze; width: Integer; height: Integer); var col, lig: Integer; begin ClrScr(); for col := 1 to width + 2 do begin TextColor(Red); write('_'); end; writeln(); for lig := 1 to height do begin TextColor(Red); write('I'); for col := 1 to width do case (m[col][lig]) of '#': begin TextColor(Blue); Write(m[col][lig]); end; '.': begin TextColor(Yellow); Write(m[col][lig]); end; '*': begin TextColor(Magenta); Write(m[col][lig]); end; end; TextColor(Red); writeln('I'); end; TextColor(Red); write('I'); for col := 1 to width do Write('-'); writeln('I'); end; function initialize(var m: Maze; var width: Integer; var height: Integer; var dots : Integer; var pX: Integer; var pY: Integer) : boolean; var mapfileName : string; begin dots:=0; mapfileName := readMapFilename(); initialize := loadMaze(mapfileName, m, width, height, dots, pX, pY); end; procedure navigate(var m: Maze; maxX, maxY: Integer; var dots : Integer; var pX: Integer; var pY: Integer;var score: Integer; var lifes: Integer); var posX, posY: Integer; K: TKeyEvent; begin posX := pX; posY := pY; gotoXY(posX + 1, posY + 1); write('o'); K := GetKeyEvent(); K := TranslateKeyEvent(K); gotoXY(posX + 1, posY + 1); write(' '); if (KeyEventToString(K) = 'Right') and (posX < maxX) and (m[posX + 1][posY] <> '#') then posX := posX + 1 else if (KeyEventToString(K) = 'Left') and (posX > 1) and (m[posX - 1][posY] <> '#') then posX := posX - 1 else if (KeyEventToString(K) = 'Up') and (posY > 1) and (m[posX][posY - 1] <> '#') then posY := posY - 1 else if (KeyEventToString(K) = 'Down') and (posY < maxY) and (m[posX][posY + 1] <> '#') then posY := posY + 1; if m[posX][posY]='.' then begin PlaySound('pacman_chomp.wav',0, SND_ASYNC); m[posX][posY]:=' '; score:=score+5; dots:=dots-1; end; if m[posX][posY]='*' then begin PlaySound('pacman_eatfruit.wav',0, SND_ASYNC); m[posX][posY]:=' '; score:=score+15; dots:=dots-1; end; pX:= posX; pY:= posY; gotoXY(posX + 1, posY + 1); write('o'); end; { deplacement } procedure play(); var width, height, dots: Integer; m: Maze; success : boolean; lifes: integer; score: integer; pX,pY : integer; begin lifes:=3; score:=0; success := initialize(m, width, height, dots, pX, pY); if (success) then begin PlaySound('pacman_beginning.wav',0, SND_ASYNC); printMaze(m, width, height); Delay(4000); InitKeyBoard(); // enable low level keyboard I/O repeat Navigate(m, width, height, dots, pX, pY, score, lifes); // navigate(m, width, height); until (dots=0)or(lifes=0); DoneKeyBoard(); // disable low level keyboard I/O if dots=0 then begin clrscr; victory(score); end; end; end; procedure scoreboard(); begin writeln('*** scoreboard' ); end; procedure printMenu(); begin clrscr; TextColor(Yellow); writeln('----------------------------------------------------------'); writeln(' Pac-Man '); writeln('----------------------------------------------------------'); writeln(' 1. Play'); writeln(' 2. Scoreboard'); writeln(' 3. Quit'); end; procedure executeChoice(choice : Integer); begin case (choice) of 1: play(); 2: scoreboard(); end; end; var c : Integer; begin repeat printMenu(); c := readChoice(); executeChoice(c); until (c = 3); end.