text
stringlengths
14
6.51M
unit TextEditor.Language; interface resourcestring { TextEditor } STextEditorScrollInfoTopLine = 'Top line: %d'; STextEditorScrollInfo = '%d - %d'; STextEditorSearchStringNotFound = 'Search string ''%s'' not found'; STextEditorSearchMatchNotFound = 'Search match not found.%sRestart search from the beginning of the file?'; STextEditorRightMarginPosition = 'Position: %d'; STextEditorSearchEngineNotAssigned = 'Search engine has not been assigned'; { TextEditor.CompletionProposal } STextEditorSnippet = 'Snippet'; STextEditorKeyword = 'Keyword'; STextEditorText = 'Text'; { TextEditor.KeyCommands } STextEditorDuplicateShortcut = 'Shortcut already exists'; { TextEditor.MacroRecorder } STextEditorCannotRecord = 'Cannot record macro; already recording or playing'; STextEditorCannotPlay = 'Cannot playback macro; already playing or recording'; STextEditorCannotPause = 'Can only pause when recording'; STextEditorCannotResume = 'Can only resume when paused'; STextEditorShortcutAlreadyExists = 'Shortcut already exists'; { TextEditor.Lines } {$IFDEF TEXTEDITOR_RANGE_CHECKS} STextEditorListIndexOutOfBounds = 'Invalid list index %d'; {$ENDIF} STextEditorInvalidCapacity = 'List capacity cannot be smaller than count'; { TextEditor.Highlighter.Import.JSON } STextEditorErrorInHighlighterParse = 'JSON parse error on line %d column %d: %s'; STextEditorErrorInHighlighterImport = 'Error in highlighter import: %s'; { TextEditor.Search } STextEditorPatternIsEmpty = 'Pattern is empty'; { TextEditor.PaintHelper } STextEditorValueMustBeSpecified = 'SetBaseFont: ''Value'' must be specified.'; {$IFDEF TEXT_EDITOR_SPELL_CHECK} { Spell check } STextEditorSpellCheckEngineCantLoadLibrary = 'Can''t load spell check dynamic link library (DLL).' + sLineBreak + sLineBreak + 'Check the DLL version - 32-bit application can''t work with 64-bit version and vice versa.'; STextEditorSpellCheckEngineCantInitialize = 'Can''t initialize spell check engine.'; STextEditorHunspellHandleNeeded = 'Operation requires a dictionary to be loaded first'; STextEditorContainsInvalidChars = 'Invalid word: ''%s'' contains characters that cannot be represented in the loaded dictionary''s codepage'; {$ENDIF} { JSON parser } STextEditorUnsupportedFileEncoding = 'File encoding is not supported'; STextEditorUnexpectedEndOfFile = 'Unexpected end of file where %s was expected'; STextEditorUnexpectedToken = 'Expected %s but found %s'; STextEditorInvalidStringCharacter = 'Invalid character in string'; STextEditorStringNotClosed = 'String not closed'; STextEditorTypeCastError = 'Cannot cast %s into %s'; STextEditorInvalidJSONPath = 'Invalid JSON path "%s"'; STextEditorJSONPathContainsNullValue = 'JSON path contains null value ("%s")'; STextEditorJSONPathIndexError = 'JSON path index out of bounds (%d) "%s"'; implementation end.
program CharacterMoving; uses SwinGame, sgTypes; const CIRCLE_RADIUS = 150; procedure Main(); var x, y: Single; begin x := 400; y := 300; OpenGraphicsWindow('Character Moving', 800, 600); repeat ProcessEvents(); if KeyDown(RightKey) = true and (x + CIRCLE_RADIUS < ScreenWidth()) then x := x - 1; if KeyDown(UpKey) = true and (y + CIRCLE_RADIUS < ScreenHeight()) then y := y - 1; if KeyDown(LeftKey) = true and (x < CIRCLE_RADIUS) then x := x + 1; if KeyDown(UpKey) = true and (y < CIRCLE_RADIUS) then y := y + 1; ClearScreen(ColorWhite); FillCircle(ColorGreen, x, y, CIRCLE_RADIUS); RefreshScreen(60); until WindowCloseRequested(); end; begin Main(); end.
unit ULogin; interface uses dao.Usuario, dao.Loja, dao.Configuracao, Web.HttpApp, System.Json, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.TabControl, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Edit, System.Actions, FMX.ActnList; type TFrmLogin = class(TForm) imageRodape: TImage; TabControl: TTabControl; TabLogin: TTabItem; TabCadastro: TTabItem; labelLinkRodape: TLabel; layoutLogin: TLayout; imageLogin: TImage; layoutEmail: TLayout; rectangleEmail: TRectangle; StyleBookApp: TStyleBook; editEmail: TEdit; layoutSenha: TLayout; rectangleSenha: TRectangle; editSenha: TEdit; layoutAcessar: TLayout; rectangleAcessar: TRectangle; labelAcessar: TLabel; labelEsqueciSenha: TLabel; labelTituloLogin: TLabel; labelTituloNovaConta: TLabel; layoutCadastro: TLayout; imageCadastro: TImage; layoutEmailCad: TLayout; rectangleEmailCad: TRectangle; editEmailCad: TEdit; layoutSenhaCad: TLayout; rectangleSenhaCad: TRectangle; editSenhaCad: TEdit; layoutCriarConta: TLayout; rectangleCriarConta: TRectangle; labelCriarConta: TLabel; layoutNomeCad: TLayout; rectangleNomeCad: TRectangle; editNomeCad: TEdit; ActionList: TActionList; ChangeTabLogin: TChangeTabAction; ChangeTabCadastro: TChangeTabAction; procedure DoExecutarLink(Sender: TObject); procedure DoAcessar(Sender: TObject); procedure DoCriarConta(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } FDao : TUsuarioDao; procedure DefinirLink; function Autenticar : Boolean; function CriarConta : Boolean; function RecuperarDadosEmpresa : Boolean; public { Public declarations } property Dao : TUsuarioDao read FDao write FDao; end; var FrmLogin: TFrmLogin; procedure CadastrarNovaConta; procedure EfetuarLogin(const IsMain : Boolean = FALSE); implementation {$R *.fmx} uses app.Funcoes, UDM, UMensagem, UInicial, UPrincipal; procedure CadastrarNovaConta; begin Application.CreateForm(TFrmLogin, FrmLogin); Application.RealCreateForms; try FrmLogin.Dao := TUsuarioDao.GetInstance; FrmLogin.TabControl.ActiveTab := FrmLogin.TabCadastro; FrmLogin.ShowModal; finally FrmLogin.DisposeOf; end; end; procedure EfetuarLogin(const IsMain : Boolean = FALSE); begin Application.CreateForm(TFrmLogin, FrmLogin); Application.RealCreateForms; try FrmLogin.Dao := TUsuarioDao.GetInstance; FrmLogin.TabControl.ActiveTab := FrmLogin.TabLogin; FrmLogin.Show; finally if IsMain then Application.MainForm := FrmLogin; end; end; function TFrmLogin.Autenticar: Boolean; var aID : TGUID; aUser : TUsuarioDao; aLoja : TLojaDao; aJson , aEmpr : TJSONObject; aRetorno : String; begin try aUser := TUsuarioDao.GetInstance; aUser.Model.Email := editEmail.Text; aUser.Model.Senha := editSenha.Text; aJson := DM.GetValidarLogin; if Assigned(aJson) then begin aRetorno := StrClearValueJson(HTMLDecode(aJson.Get('retorno').JsonValue.ToString)); Result := (aRetorno.ToUpper = 'OK'); if not Result then ExibirMsgAlerta(aRetorno) else begin aID := StringToGUID( StrClearValueJson(HTMLDecode(aJson.Get('id').JsonValue.ToString)) ); if aUser.Find(aID, AnsiLowerCase(Trim(editEmail.Text)), False) then begin aUser.Model.Nome := StrClearValueJson(HTMLDecode(aJson.Get('nome').JsonValue.ToString)); aUser.Model.Ativo := True; aUser.Ativar(); end else begin aUser.Model.ID := StringToGUID( StrClearValueJson(HTMLDecode(aJson.Get('id').JsonValue.ToString)) ); aUser.Model.Nome := StrClearValueJson(HTMLDecode(aJson.Get('nome').JsonValue.ToString)); aUser.Model.Email := AnsiLowerCase(Trim(editEmail.Text)); aUser.Model.Senha := AnsiLowerCase(Trim(editSenha.Text)); aUser.Model.Ativo := True; aUser.Insert(); end; // Recuperar dados da empresa aEmpr := aJson.Get('empresa').JsonValue as TJSONObject; with aUser.Model do begin Empresa.ID := StringToGUID(StrClearValueJson(HTMLDecode(aEmpr.Get('id').JsonValue.ToString))); Empresa.Codigo := StrToCurr(StrClearValueJson(HTMLDecode(aEmpr.Get('codigo').JsonValue.ToString))); Empresa.Nome := StrClearValueJson(HTMLDecode(aEmpr.Get('nome').JsonValue.ToString)); Empresa.Fantasia := StrClearValueJson(HTMLDecode(aEmpr.Get('fantasia').JsonValue.ToString)); Empresa.CpfCnpj := StrClearValueJson(HTMLDecode(aEmpr.Get('cpf_cnpj').JsonValue.ToString)); end; // Gravar dados da empresa retornada aLoja := TLojaDao.GetInstance(); aLoja.Limpar(); if (aUser.Model.Empresa.Codigo > 0) then begin aID := StringToGUID( StrClearValueJson(HTMLDecode(aEmpr.Get('id').JsonValue.ToString)) ); if aLoja.Find(aId, aUser.Model.Empresa.CpfCnpj, False) then begin aLoja.Model := aUser.Model.Empresa; aLoja.Update(); end else begin aLoja.Model := aUser.Model.Empresa; aLoja.Insert(); end; TConfiguracaoDao.GetInstance().SetValue('empresa_padrao', aLoja.Model.ID.ToString); end; end; end else Result := False; except On E : Exception do begin ExibirMsgErro('Erro ao tentar autenticar usuário/senha.' + #13 + E.Message); Result := False; end; end; end; function TFrmLogin.CriarConta: Boolean; var aID : TGUID; aUser : TUsuarioDao; aLoja : TLojaDao; aJson , aEmpr : TJSONObject; aRetorno : String; begin try aUser := TUsuarioDao.GetInstance; aUser.Model.ID := GUID_NULL; aUser.Model.Nome := editNomeCad.Text; aUser.Model.Email := editEmailCad.Text; aUser.Model.Senha := editSenhaCad.Text; aUser.Model.Cpf := EmptyStr; aUser.Model.Celular := EmptyStr; aUser.Model.TokenID := EmptyStr; aUser.Model.Ativo := False; aJson := DM.GetCriarNovaCOnta; if Assigned(aJson) then begin aRetorno := StrClearValueJson(HTMLDecode(aJson.Get('retorno').JsonValue.ToString)); Result := (aRetorno.ToUpper = 'OK'); if not Result then ExibirMsgAlerta(aRetorno); end else Result := False; except On E : Exception do begin ExibirMsgErro('Erro ao tentar criar nova conta.' + #13 + E.Message); Result := False; end; end; end; procedure TFrmLogin.DefinirLink; begin if (TabControl.ActiveTab = TabLogin) then labelLinkRodape.Text := 'Não tem cadastro? Criar nova conta.' else if (TabControl.ActiveTab = TabCadastro) then labelLinkRodape.Text := 'Já tem um cadastro? Faça o login aqui.'; end; procedure TFrmLogin.DoAcessar(Sender: TObject); begin DM.ConectarDB; if Autenticar then begin RecuperarDadosEmpresa; if Assigned(FrmInicial) then FrmInicial.Hide; CriarForm(TFrmPrincipal, FrmPrincipal); // Ajustas manual para correção de bug if (Application.MainForm = Self) then begin Application.MainForm := FrmPrincipal; FrmPrincipal.Show; end; Self.Close; end; end; procedure TFrmLogin.DoCriarConta(Sender: TObject); begin DM.ConectarDB; if CriarConta then begin editEmail.Text := editEmailCad.Text; editSenha.Text := editSenhaCad.Text; // Autenticar para trazer dados adicionais do Usuário do servidor web. Autenticar; if Assigned(FrmInicial) then FrmInicial.Hide; CriarForm(TFrmPrincipal, FrmPrincipal); Self.Close; end; end; procedure TFrmLogin.DoExecutarLink(Sender: TObject); begin if (TabControl.ActiveTab = TabLogin) then ChangeTabCadastro.ExecuteTarget(Sender) else if (TabControl.ActiveTab = TabCadastro) then ChangeTabLogin.ExecuteTarget(Sender); DefinirLink; end; procedure TFrmLogin.FormCreate(Sender: TObject); begin TabControl.ActiveTab := TabLogin; TabControl.TabPosition := TTabPosition.None; FDao := TUsuarioDao.GetInstance; end; procedure TFrmLogin.FormShow(Sender: TObject); begin DefinirLink; end; function TFrmLogin.RecuperarDadosEmpresa: Boolean; var I : Integer; aID : TGUID; aLoja : TLojaDao; aLista : TJSONArray; aJson , aEmpr : TJSONObject; aCnpj , aRetorno : String; begin try aJson := DM.GetListarLojas; if Assigned(aJson) then begin aRetorno := StrClearValueJson(HTMLDecode(aJson.Get('retorno').JsonValue.ToString)); Result := (aRetorno.ToUpper = 'OK'); if Result then begin // Recuperar dados da empresa aLoja := TLojaDao.GetInstance(); aLista := aJson.Get('empresas').JsonValue as TJSONArray; for I := 0 to aLista.Count - 1 do begin aEmpr := aLista.Items[I] as TJSONObject; aID := StringToGUID( StrClearValueJson(HTMLDecode(aEmpr.Get('id').JsonValue.ToString)) ); aCnpj := StrClearValueJson(HTMLDecode(aEmpr.Get('cpf_cnpj').JsonValue.ToString)); with aLoja.Model do begin ID := StringToGUID(StrClearValueJson(HTMLDecode(aEmpr.Get('id').JsonValue.ToString))); Codigo := StrToCurr(StrClearValueJson(HTMLDecode(aEmpr.Get('codigo').JsonValue.ToString))); Nome := StrClearValueJson(HTMLDecode(aEmpr.Get('nome').JsonValue.ToString)); Fantasia := StrClearValueJson(HTMLDecode(aEmpr.Get('fantasia').JsonValue.ToString)); CpfCnpj := StrClearValueJson(HTMLDecode(aEmpr.Get('cpf_cnpj').JsonValue.ToString)); end; if aLoja.Find(aId, aCnpj, False) then aLoja.Update() else aLoja.Insert(); if (TConfiguracaoDao.GetInstance().GetValue('empresa_padrao').Trim = EmptyStr) then TConfiguracaoDao.GetInstance().SetValue('empresa_padrao', aLoja.Model.ID.ToString); end; end; end else Result := False; except On E : Exception do begin ExibirMsgErro('Erro ao tentar recuperar dados da(s) empresa(s) do usuário.' + #13 + E.Message); Result := False; end; end; end; end.
unit UCommon; interface const BDS_KEY = 'Software\Embarcadero\BDS'; var AppDir: string; function HasInList(const Item, List: string): Boolean; function NormalizeAndRemoveFirstDir(Path: string): string; implementation uses System.SysUtils; function HasInList(const Item, List: string): Boolean; const SEP = ';'; begin //returns if Item is contained in the List splited by SEP character Result := Pos(SEP+Item+SEP, SEP+List+SEP)>0; end; function NormalizeAndRemoveFirstDir(Path: string): string; var I: Integer; begin Path := Path.Replace('/', '\'); I := Path.IndexOf('\'); if I=-1 then raise Exception.Create('First directory separator not found'); Result := Path.Remove(0, I+1); end; end.
(* * Copyright (c) 2010, Ciobanu Alexandru * 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 <organization> 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 AUTHOR ''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 AUTHOR 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. *) {$I ../Library/src/DeHL.Defines.inc} unit Tests.Bytes; interface uses SysUtils, Variants, Tests.Utils, TestFramework, DeHL.Base, DeHL.Exceptions, DeHL.WideCharSet, DeHL.Collections.List, DeHL.Types, DeHL.Bytes; type TTestBuffer = class(TDeHLTestCase) published procedure Test_Create_Bytes; procedure Test_Create_String; procedure Test_GetEnumerator; procedure Test_AsCollection; procedure Test_Length_Get; procedure Test_Bytes; procedure Test_IsEmpty; procedure Test_Ref; procedure Test_ToRawByteString; procedure Test_ToBytes; procedure Test_Contains_Buffer; procedure Test_Contains_Byte; procedure Test_Contains_String; procedure Test_IndexOf_Buffer; procedure Test_IndexOf_Byte; procedure Test_IndexOf_String; procedure Test_LastIndexOf_Buffer; procedure Test_LastIndexOf_Byte; procedure Test_LastIndexOf_String; procedure Test_StartsWith_Buffer; procedure Test_StartsWith_Byte; procedure Test_StartsWith_String; procedure Test_EndsWith_Buffer; procedure Test_EndsWith_Byte; procedure Test_EndsWith_String; procedure Test_Copy_Count; procedure Test_Copy; procedure Test_CopyTo_Start_Count; procedure Test_CopyTo_Start; procedure Test_CopyTo; procedure Test_Append_Buffer; procedure Test_Append_Byte; procedure Test_Append_String; procedure Test_Insert_Buffer; procedure Test_Insert_Byte; procedure Test_Insert_String; procedure Test_Replace_Buffer; procedure Test_Replace_Byte; procedure Test_Replace_String; procedure Test_Remove_Count; procedure Test_Remove; procedure Test_Reverse; procedure Test_Clear; procedure Test_Compare; procedure Test_CompareTo; procedure Test_Equal; procedure Test_EqualsWith; procedure Test_Empty; procedure Test_Op_Implicit_ToString; procedure Test_Op_Implicit_ToBuffer; procedure Test_Op_Implicit_ToVariant; procedure Test_Op_Add_Buffer; procedure Test_Op_Add_Byte; procedure Test_Op_Equal; procedure Test_Op_NotEqual; procedure Test_GetType; procedure Test_TypeSupport; end; implementation { TTestBuffer } procedure TTestBuffer.Test_Append_Buffer; var LBuffer: TBuffer; begin LBuffer.Append(TBuffer.Create('One')); CheckEquals('One', LBuffer.ToRawByteString); LBuffer.Append(TBuffer.Create('')); CheckEquals('One', LBuffer.ToRawByteString); LBuffer.Append(LBuffer); CheckEquals('OneOne', LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_Append_Byte; var LBuffer: TBuffer; begin LBuffer.Append(32); CheckEquals(#32, LBuffer.ToRawByteString); LBuffer.Append(#0); CheckEquals(#32#0, LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_Append_String; var LBuffer: TBuffer; begin LBuffer.Append('One'); CheckEquals('One', LBuffer.ToRawByteString); LBuffer.Append(''); CheckEquals('One', LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_AsCollection; var LStr: string; V: Char; begin LStr := ''; for V in TBuffer.Create('abc').AsCollection.Op.Cast<Char> do LStr := LStr + V; CheckEquals('abc', LStr); end; procedure TTestBuffer.Test_Bytes; var LBuffer: TBuffer; begin LBuffer := TBuffer.Create(#22#23#24); CheckEquals(22, LBuffer[0]); CheckEquals(23, LBuffer[1]); CheckEquals(24, LBuffer[2]); LBuffer[0] := 55; LBuffer[1] := 56; LBuffer[2] := 57; CheckEquals(55, LBuffer[0]); CheckEquals(56, LBuffer[1]); CheckEquals(57, LBuffer[2]); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin if LBuffer[-1] = 1 then; end, 'EArgumentOutOfRangeException not thrown in LBuffer[-1].' ); CheckException(EArgumentOutOfRangeException, procedure() begin if LBuffer[3] = 1 then; end, 'EArgumentOutOfRangeException not thrown in LBuffer[3].' ); {$ENDIF} end; procedure TTestBuffer.Test_Clear; var LBuffer: TBuffer; begin LBuffer := ''; LBuffer.Clear; CheckTrue(LBuffer.IsEmpty); LBuffer := 'Caca maca'; LBuffer.Clear; CheckTrue(LBuffer.IsEmpty); LBuffer := 'C'; LBuffer.Clear; CheckTrue(LBuffer.IsEmpty); end; procedure TTestBuffer.Test_Compare; var L1, L2: TBuffer; begin L1 := ''; L2 := ''; CheckEquals(0, TBuffer.Compare(L1, L2)); L1 := 'HAHA'; L2 := ''; CheckTrue(TBuffer.Compare(L1, L2) > 0); L1 := ''; L2 := 'HAHA'; CheckTrue(TBuffer.Compare(L1, L2) < 0); L1 := '123456'; L2 := '12345'; CheckTrue(TBuffer.Compare(L1, L2) > 0); L1 := '123456'; L2 := '1234567'; CheckTrue(TBuffer.Compare(L1, L2) < 0); L1 := 'HAHA'; L2 := 'HAHB'; CheckTrue(TBuffer.Compare(L1, L2) < 0); L1 := 'HAHA'; L2 := 'HAHB'; CheckTrue(TBuffer.Compare(L2, L1) > 0); L1 := 'BlahBlah'; L2 := 'BlahBlah'; CheckTrue(TBuffer.Compare(L1, L2) = 0); CheckTrue(TBuffer.Compare(L2, L1) = 0); CheckTrue(TBuffer.Compare(L1, L1) = 0); CheckTrue(TBuffer.Compare(L2, L2) = 0); end; procedure TTestBuffer.Test_CompareTo; var L1, L2: TBuffer; begin L1 := ''; L2 := ''; CheckEquals(0, L1.CompareTo(L2)); L1 := 'HAHA'; L2 := ''; CheckTrue(L1.CompareTo(L2) > 0); L1 := ''; L2 := 'HAHA'; CheckTrue(L1.CompareTo(L2) < 0); L1 := '123456'; L2 := '12345'; CheckTrue(L1.CompareTo(L2) > 0); L1 := '123456'; L2 := '1234567'; CheckTrue(L1.CompareTo(L2) < 0); L1 := 'HAHA'; L2 := 'HAHB'; CheckTrue(L1.CompareTo(L2) < 0); L1 := 'HAHA'; L2 := 'HAHB'; CheckTrue(L2.CompareTo(L1) > 0); L1 := 'BlahBlah'; L2 := 'BlahBlah'; CheckTrue(L2.CompareTo(L1) = 0); CheckTrue(L2.CompareTo(L2) = 0); CheckTrue(L1.CompareTo(L1) = 0); CheckTrue(L1.CompareTo(L2) = 0); end; procedure TTestBuffer.Test_Contains_Buffer; var LW, LB1, LB2: TBuffer; begin LW := 'Hello'; LB1 := ''; LB2 := 'Hello World!'; CheckTrue(LW.Contains(LW)); CheckFalse(LW.Contains(LB1)); CheckFalse(LW.Contains(LB2)); CheckFalse(LB1.Contains(LW)); CheckFalse(LB1.Contains(LB1)); CheckFalse(LB1.Contains(LB2)); CheckTrue(LB2.Contains(LW)); CheckFalse(LB2.Contains(LB1)); CheckTrue(LB2.Contains(LB2)); end; procedure TTestBuffer.Test_Contains_Byte; var LB1, LB2: TBuffer; begin LB1 := ''; LB2 := 'Hello World!'; CheckFalse(LB1.Contains(33)); CheckFalse(LB1.Contains(Ord('!'))); CheckTrue(LB2.Contains(33)); CheckTrue(LB2.Contains(Ord('!'))); end; procedure TTestBuffer.Test_Contains_String; var LB1, LB2: TBuffer; begin LB1 := ''; LB2 := 'Hello World!'; CheckFalse(LB1.Contains('Hello')); CheckTrue(LB2.Contains('Hello')); CheckFalse(LB2.Contains('hello')); end; procedure TTestBuffer.Test_Copy; var LBuffer, LCopy: TBuffer; begin LBuffer := 'Hello World!'; LCopy := LBuffer.Copy(0); CheckEquals('Hello World!', LCopy.ToRawByteString); LCopy := LBuffer.Copy(1); CheckEquals('ello World!', LCopy.ToRawByteString); LCopy := LBuffer.Copy(11); CheckEquals('!', LCopy.ToRawByteString); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('').Copy(0); end, 'EArgumentOutOfRangeException not thrown in Copy(0).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Copy(-1); end, 'EArgumentOutOfRangeException not thrown in Copy(-1).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Copy(12) end, 'EArgumentOutOfRangeException not thrown in Copy(12).' ); {$ENDIF} end; procedure TTestBuffer.Test_CopyTo; var LBuffer1, LBuffer2: TBuffer; begin LBuffer1 := 'Hello World!'; LBuffer2 := '------------'; LBuffer1.CopyTo(LBuffer2.Ref); CheckEquals('Hello World!', LBuffer2.ToRawByteString); LBuffer1 := ''; {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer1.CopyTo(LBuffer1.Ref); end, 'EArgumentOutOfRangeException not thrown in CopyTo().' ); {$ENDIF} end; procedure TTestBuffer.Test_CopyTo_Start; var LBuffer1, LBuffer2: TBuffer; begin LBuffer1 := 'Hello World!'; LBuffer2 := '------'; LBuffer1.CopyTo(LBuffer2.Ref, 6); CheckEquals('World!', LBuffer2.ToRawByteString); LBuffer1.CopyTo(LBuffer2.Ref, 11); CheckEquals('!orld!', LBuffer2.ToRawByteString); LBuffer1.CopyTo(LBuffer2.Ref, 10); CheckEquals('d!rld!', LBuffer2.ToRawByteString); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer1.CopyTo(LBuffer2.Ref, -1); end, 'EArgumentOutOfRangeException not thrown in CopyTo(-1).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer1.CopyTo(LBuffer2.Ref, 12); end, 'EArgumentOutOfRangeException not thrown in CopyTo(12).' ); LBuffer1 := ''; CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer1.CopyTo(LBuffer2.Ref, 0); end, 'EArgumentOutOfRangeException not thrown in e/CopyTo(0).' ); {$ENDIF} end; procedure TTestBuffer.Test_CopyTo_Start_Count; var LBuffer1, LBuffer2: TBuffer; begin LBuffer1 := 'Hello World!'; LBuffer2 := '------'; LBuffer1.CopyTo(LBuffer2.Ref, 6, 6); CheckEquals('World!', LBuffer2.ToRawByteString); LBuffer1.CopyTo(LBuffer2.Ref, 11, 1); CheckEquals('!orld!', LBuffer2.ToRawByteString); LBuffer1.CopyTo(LBuffer2.Ref, 10, 1); CheckEquals('dorld!', LBuffer2.ToRawByteString); LBuffer1.CopyTo(LBuffer2.Ref, 10, 2); CheckEquals('d!rld!', LBuffer2.ToRawByteString); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer1.CopyTo(LBuffer2.Ref, -1, 5); end, 'EArgumentOutOfRangeException not thrown in CopyTo(-1, 5).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer1.CopyTo(LBuffer2.Ref, 12, 1); end, 'EArgumentOutOfRangeException not thrown in CopyTo(12, 1).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer1.CopyTo(LBuffer2.Ref, 0, 13); end, 'EArgumentOutOfRangeException not thrown in CopyTo(0, 13).' ); LBuffer1 := ''; CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer1.CopyTo(LBuffer2.Ref, 0, 1); end, 'EArgumentOutOfRangeException not thrown in e/CopyTo(0, 1).' ); {$ENDIF} end; procedure TTestBuffer.Test_Copy_Count; var LBuffer, LCopy: TBuffer; begin LBuffer := 'Hello World!'; LCopy := LBuffer.Copy(0, 1); CheckEquals('H', LCopy.ToRawByteString); LCopy := LBuffer.Copy(0, 12); CheckEquals('Hello World!', LCopy.ToRawByteString); LCopy := LBuffer.Copy(1, 11); CheckEquals('ello World!', LCopy.ToRawByteString); LCopy := LBuffer.Copy(11, 1); CheckEquals('!', LCopy.ToRawByteString); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('').Copy(0, 0); end, 'EArgumentOutOfRangeException not thrown in Copy(0, 0).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Copy(-1, 0); end, 'EArgumentOutOfRangeException not thrown in Copy(-1, 0).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Copy(-1, 10); end, 'EArgumentOutOfRangeException not thrown in Copy(-1, 10).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Copy(1, 13); end, 'EArgumentOutOfRangeException not thrown in Copy(1, 13).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Copy(11, 2) end, 'EArgumentOutOfRangeException not thrown in Copy(11, 2).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Copy(12, 0) end, 'EArgumentOutOfRangeException not thrown in Copy(12, 0).' ); {$ENDIF} end; procedure TTestBuffer.Test_Create_Bytes; var LBuffer: TBuffer; begin LBuffer := TBuffer.Create([]); CheckEquals(0, LBuffer.Length); LBuffer := TBuffer.Create([1, 2, 3]); CheckEquals(3, LBuffer.Length); CheckEquals(1, LBuffer[0]); CheckEquals(2, LBuffer[1]); CheckEquals(3, LBuffer[2]); end; procedure TTestBuffer.Test_Create_String; var LBuffer: TBuffer; begin LBuffer := TBuffer.Create(''); CheckEquals(0, LBuffer.Length); LBuffer := TBuffer.Create('abc'#0'd'); CheckEquals(5, LBuffer.Length); CheckEquals(Ord('a'), LBuffer[0]); CheckEquals(Ord('b'), LBuffer[1]); CheckEquals(Ord('c'), LBuffer[2]); CheckEquals(0, LBuffer[3]); CheckEquals(Ord('d'), LBuffer[4]); end; procedure TTestBuffer.Test_Empty; begin CheckTrue(TBuffer.Empty.IsEmpty); TBuffer.Empty.Append('HA'); CheckTrue(TBuffer.Empty.IsEmpty); CheckTrue(TBuffer.Empty.ToRawByteString = ''); end; procedure TTestBuffer.Test_EndsWith_Buffer; var LW1, LW2, LB1, LB2: TBuffer; begin LW1 := 'World!'; LW2 := 'World'; LB1 := ''; LB2 := 'Hello World!'; CheckTrue (LW1.EndsWith(LW1)); CheckFalse(LW1.EndsWith(LW2)); CheckFalse(LW1.EndsWith(LB1)); CheckFalse(LW1.EndsWith(LB2)); CheckTrue (LW2.EndsWith(LW2)); CheckFalse(LW2.EndsWith(LW1)); CheckFalse(LW2.EndsWith(LB1)); CheckFalse(LW2.EndsWith(LB2)); CheckFalse(LB1.EndsWith(LW1)); CheckFalse(LB1.EndsWith(LW2)); CheckFalse(LB1.EndsWith(LB1)); CheckFalse(LB1.EndsWith(LB2)); CheckTrue (LB2.EndsWith(LW1)); CheckFalse(LB2.EndsWith(LW2)); CheckFalse(LB2.EndsWith(LB1)); CheckTrue (LB2.EndsWith(LB2)); end; procedure TTestBuffer.Test_EndsWith_Byte; var LB1, LB2: TBuffer; begin LB1 := ''; LB2 := 'Hello World!'; CheckFalse(LB1.EndsWith(Ord('d'))); CheckFalse(LB1.EndsWith(Ord('!'))); CheckFalse(LB2.EndsWith(Ord('d'))); CheckTrue(LB2.EndsWith(Ord('!'))); end; procedure TTestBuffer.Test_EndsWith_String; var LW1, LW2: RawByteString; LB1, LB2: TBuffer; begin LW1 := 'World!'; LW2 := 'World'; LB1 := ''; LB2 := 'Hello World!'; CheckTrue (LB2.EndsWith(LB2.ToRawByteString)); CheckFalse(LB1.EndsWith(LW1)); CheckFalse(LB1.EndsWith(LW2)); CheckTrue (LB2.EndsWith(LW1)); CheckFalse(LB2.EndsWith(LW2)); end; procedure TTestBuffer.Test_Equal; var L1, L2: TBuffer; begin L1 := ''; L2 := ''; CheckTrue(TBuffer.Equal(L1, L2)); L1 := 'HAHA'; L2 := ''; CheckFalse(TBuffer.Equal(L1, L2)); L1 := ''; L2 := 'HAHA'; CheckFalse(TBuffer.Equal(L1, L2)); L1 := '123456'; L2 := '12345'; CheckFalse(TBuffer.Equal(L1, L2)); L1 := '123456'; L2 := '1234567'; CheckFalse(TBuffer.Equal(L1, L2)); L1 := 'HAHA'; L2 := 'HAHB'; CheckFalse(TBuffer.Equal(L1, L2)); L1 := 'HAHA'; L2 := 'HAHB'; CheckFalse(TBuffer.Equal(L2, L1)); L1 := 'BlahBlah'; L2 := 'BlahBlah'; CheckTrue(TBuffer.Equal(L1, L2)); CheckTrue(TBuffer.Equal(L2, L1)); CheckTrue(TBuffer.Equal(L1, L1)); CheckTrue(TBuffer.Equal(L2, L2)); end; procedure TTestBuffer.Test_EqualsWith; var L1, L2: TBuffer; begin L1 := ''; L2 := ''; CheckTrue(L1.EqualsWith(L2)); L1 := 'HAHA'; L2 := ''; CheckFalse(L1.EqualsWith(L2)); L1 := ''; L2 := 'HAHA'; CheckFalse(L1.EqualsWith(L2)); L1 := '123456'; L2 := '12345'; CheckFalse(L1.EqualsWith(L2)); L1 := '123456'; L2 := '1234567'; CheckFalse(L1.EqualsWith(L2)); L1 := 'HAHA'; L2 := 'HAHB'; CheckFalse(L1.EqualsWith(L2)); L1 := 'HAHA'; L2 := 'HAHB'; CheckFalse(TBuffer.Equal(L2, L1)); L1 := 'BlahBlah'; L2 := 'BlahBlah'; CheckTrue(L1.EqualsWith(L2)); CheckTrue(L2.EqualsWith(L1)); CheckTrue(L1.EqualsWith(L1)); CheckTrue(L2.EqualsWith(L2)); end; procedure TTestBuffer.Test_GetEnumerator; var LEnum: IEnumerator<Byte>; begin LEnum := TBuffer.Create('').GetEnumerator; CheckFalse(LEnum.MoveNext); LEnum := TBuffer.Create('abc'#0).GetEnumerator; CheckTrue(LEnum.MoveNext); CheckEquals(Ord('a'), LEnum.Current); CheckTrue(LEnum.MoveNext); CheckEquals(Ord('b'), LEnum.Current); CheckTrue(LEnum.MoveNext); CheckEquals(Ord('c'), LEnum.Current); CheckTrue(LEnum.MoveNext); CheckEquals(0, LEnum.Current); CheckFalse(LEnum.MoveNext); end; procedure TTestBuffer.Test_GetType; begin CheckTrue(TBuffer.GetType <> nil); CheckEquals('TBuffer', TBuffer.GetType.Name); CheckTrue(TBuffer.GetType.TypeInfo = TypeInfo(TBuffer)); end; procedure TTestBuffer.Test_IndexOf_Buffer; var LW, LB1, LB2: TBuffer; begin LW := 'llo'; LB1 := ''; LB2 := 'Hello World!'; CheckEquals( 0, LW.IndexOf(LW)); CheckEquals(-1, LW.IndexOf(LB1)); CheckEquals(-1, LW.IndexOf(LB2)); CheckEquals(-1, LB1.IndexOf(LW)); CheckEquals(-1, LB1.IndexOf(LB1)); CheckEquals(-1, LB1.IndexOf(LB2)); CheckEquals( 2, LB2.IndexOf(LW)); CheckEquals(-1, LB2.IndexOf(LB1)); CheckEquals( 0, LB2.IndexOf(LB2)); end; procedure TTestBuffer.Test_IndexOf_Byte; var LW: Byte; LB1, LB2: TBuffer; begin LW := Ord('l'); LB1 := ''; LB2 := 'Hello World!'; CheckEquals(-1, LB1.IndexOf(LW)); CheckEquals(-1, LB1.IndexOf(LB1)); CheckEquals(-1, LB1.IndexOf(LB2)); CheckEquals( 2, LB2.IndexOf(LW)); CheckEquals(-1, LB2.IndexOf(LB1)); CheckEquals( 0, LB2.IndexOf(LB2)); end; procedure TTestBuffer.Test_IndexOf_String; var LB1, LB2: TBuffer; begin LB1 := ''; LB2 := 'Hello World!'; CheckEquals(-1, LB1.IndexOf('Hello')); CheckEquals( 1, LB2.IndexOf('ello')); CheckEquals( 2, LB2.IndexOf('llo ')); end; procedure TTestBuffer.Test_Insert_Buffer; var LBuffer: TBuffer; begin LBuffer := TBuffer.Create(''); LBuffer.Insert(0, TBuffer.Create('Haha')); CheckEquals('Haha', LBuffer.ToRawByteString); LBuffer := TBuffer.Create('one'); LBuffer.Insert(2, TBuffer.Create('--')); CheckEquals('on--e', LBuffer.ToRawByteString); LBuffer := TBuffer.Create('one'); LBuffer.Insert(1, TBuffer.Create('..')); CheckEquals('o..ne', LBuffer.ToRawByteString); LBuffer := TBuffer.Create('one'); LBuffer.Insert(3, TBuffer.Create('...')); CheckEquals('one...', LBuffer.ToRawByteString); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('one').Insert(- 1, TBuffer.Create('')); end, 'EArgumentOutOfRangeException not thrown in -1.' ); CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('one').Insert(4, TBuffer.Create('...')); end, 'EArgumentOutOfRangeException not thrown in 4.' ); {$ENDIF} end; procedure TTestBuffer.Test_Insert_Byte; var LBuffer: TBuffer; begin LBuffer := TBuffer.Create(''); LBuffer.Insert(0, Ord('H')); CheckEquals('H', LBuffer.ToRawByteString); LBuffer := TBuffer.Create('one'); LBuffer.Insert(2, Ord('-')); CheckEquals('on-e', LBuffer.ToRawByteString); LBuffer := TBuffer.Create('one'); LBuffer.Insert(1, Ord('.')); CheckEquals('o.ne', LBuffer.ToRawByteString); LBuffer := TBuffer.Create('one'); LBuffer.Insert(3, Ord('.')); CheckEquals('one.', LBuffer.ToRawByteString); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('one').Insert(- 1, Ord('=')); end, 'EArgumentOutOfRangeException not thrown in -1.' ); CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('one').Insert(4, Ord('.')); end, 'EArgumentOutOfRangeException not thrown in 4.' ); {$ENDIF} end; procedure TTestBuffer.Test_Insert_String; var LBuffer: TBuffer; begin LBuffer := TBuffer.Create(''); LBuffer.Insert(0, 'Haha'); CheckEquals('Haha', LBuffer.ToRawByteString); LBuffer := TBuffer.Create('one'); LBuffer.Insert(2, '--'); CheckEquals('on--e', LBuffer.ToRawByteString); LBuffer := TBuffer.Create('one'); LBuffer.Insert(1, '..'); CheckEquals('o..ne', LBuffer.ToRawByteString); LBuffer := TBuffer.Create('one'); LBuffer.Insert(3, '...'); CheckEquals('one...', LBuffer.ToRawByteString); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('one').Insert(- 1, ''); end, 'EArgumentOutOfRangeException not thrown in -1.' ); CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('one').Insert(4, '...'); end, 'EArgumentOutOfRangeException not thrown in 4.' ); {$ENDIF} end; procedure TTestBuffer.Test_IsEmpty; var LBuffer: TBuffer; begin CheckTrue(LBuffer.IsEmpty); LBuffer := 'Hello World'; CheckFalse(LBuffer.IsEmpty); LBuffer.Clear; CheckTrue(LBuffer.IsEmpty); end; procedure TTestBuffer.Test_LastIndexOf_Buffer; var LW, LB1, LB2: TBuffer; begin LW := 'l'; LB1 := ''; LB2 := 'Hello World!'; CheckEquals( 0, LW.LastIndexOf(LW)); CheckEquals(-1, LW.LastIndexOf(LB1)); CheckEquals(-1, LW.LastIndexOf(LB2)); CheckEquals(-1, LB1.LastIndexOf(LW)); CheckEquals(-1, LB1.LastIndexOf(LB1)); CheckEquals(-1, LB1.LastIndexOf(LB2)); CheckEquals( 9, LB2.LastIndexOf(LW)); CheckEquals(-1, LB2.LastIndexOf(LB1)); CheckEquals( 0, LB2.LastIndexOf(LB2)); end; procedure TTestBuffer.Test_LastIndexOf_Byte; var LB1, LB2: TBuffer; begin LB1 := ''; LB2 := 'Hello World!'; CheckEquals(-1, LB1.LastIndexOf(Ord('l'))); CheckEquals( 9, LB2.LastIndexOf(Ord('l'))); CheckEquals( 1, LB2.LastIndexOf(Ord('e'))); end; procedure TTestBuffer.Test_LastIndexOf_String; var LB1, LB2: TBuffer; begin LB1 := ''; LB2 := 'Hello World!'; CheckEquals(-1, LB1.LastIndexOf('l')); CheckEquals(-1, LB1.LastIndexOf('')); CheckEquals(-1, LB2.LastIndexOf('')); CheckEquals( 9, LB2.LastIndexOf('l')); CheckEquals( 2, LB2.LastIndexOf('ll')); end; procedure TTestBuffer.Test_Length_Get; var LBuffer: TBuffer; begin CheckEquals(0, LBuffer.Length); LBuffer := TBuffer.Create([1]); CheckEquals(1, LBuffer.Length); LBuffer.Append(2); CheckEquals(2, LBuffer.Length); end; procedure TTestBuffer.Test_Op_Add_Buffer; var LBuffer: TBuffer; begin LBuffer := LBuffer + LBuffer; CheckTrue(LBuffer.IsEmpty); LBuffer := LBuffer + TBuffer.Create('---'); CheckEquals('---', LBuffer.ToRawByteString); LBuffer := LBuffer + LBuffer; CheckEquals('------', LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_Op_Add_Byte; var LBuffer: TBuffer; begin LBuffer := LBuffer + 0; CheckEquals(0, LBuffer[0]); LBuffer := LBuffer + 45; CheckEquals(0, LBuffer[0]); CheckEquals(45, LBuffer[1]); end; procedure TTestBuffer.Test_Op_Equal; var L1, L2: TBuffer; begin L1 := ''; L2 := ''; CheckTrue(L1 = L2); L1 := 'HAHA'; L2 := ''; CheckFalse(L1 = L2); L1 := ''; L2 := 'HAHA'; CheckFalse(L1 = L2); L1 := '123456'; L2 := '12345'; CheckFalse(L1 = L2); L1 := '123456'; L2 := '1234567'; CheckFalse(L1 = L2); L1 := 'HAHA'; L2 := 'HAHB'; CheckFalse(L1 = L2); L1 := 'HAHA'; L2 := 'HAHB'; CheckFalse(L2 = L1); L1 := 'BlahBlah'; L2 := 'BlahBlah'; CheckTrue(L1 = L2); CheckTrue(L2 = L1); CheckTrue(L1 = L1); CheckTrue(L2 = L2); end; procedure TTestBuffer.Test_Op_Implicit_ToBuffer; var LBuffer: TBuffer; begin LBuffer := ''; CheckTrue(LBuffer.IsEmpty); LBuffer := 'Hahaha'; CheckEquals('Hahaha', LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_Op_Implicit_ToString; var LBuffer: TBuffer; LS: RawByteString; begin LS := LBuffer; CheckEquals('', LS); LBuffer := 'Hello World!'; LS := LBuffer; CheckEquals('Hello World!', LS); end; procedure TTestBuffer.Test_Op_Implicit_ToVariant; var LBuffer: TBuffer; LVar: Variant; begin LVar := LBuffer; CheckTrue(VarType(LVar) <> (varArray and varByte)); CheckEquals(1, VarArrayDimCount(LVar)); CheckEquals(0, VarArrayLowBound(LVar, 1)); CheckEquals(-1, VarArrayHighBound(LVar, 1)); LBuffer := #45#46#0; LVar := LBuffer; CheckTrue(VarType(LVar) <> (varArray and varByte)); CheckEquals(1, VarArrayDimCount(LVar)); CheckEquals(0, VarArrayLowBound(LVar, 1)); CheckEquals(2, VarArrayHighBound(LVar, 1)); CheckTrue(LVar[0] = 45); CheckTrue(LVar[1] = 46); CheckTrue(LVar[2] = 0); end; procedure TTestBuffer.Test_Op_NotEqual; var L1, L2: TBuffer; begin L1 := ''; L2 := ''; CheckFalse(L1 <> L2); L1 := 'HAHA'; L2 := ''; CheckTrue(L1 <> L2); L1 := ''; L2 := 'HAHA'; CheckTrue(L1 <> L2); L1 := '123456'; L2 := '12345'; CheckTrue(L1 <> L2); L1 := '123456'; L2 := '1234567'; CheckTrue(L1 <> L2); L1 := 'HAHA'; L2 := 'HAHB'; CheckTrue(L1 <> L2); L1 := 'HAHA'; L2 := 'HAHB'; CheckTrue(L2 <> L1); L1 := 'BlahBlah'; L2 := 'BlahBlah'; CheckFalse(L1 <> L2); CheckFalse(L2 <> L1); CheckFalse(L1 <> L1); CheckFalse(L2 <> L2); end; procedure TTestBuffer.Test_Ref; var LBuffer, LBuffer2: TBuffer; begin LBuffer := 'Hello World!'; LBuffer2 := LBuffer; LBuffer2.Ref^ := Ord('_'); CheckEquals('Hello World!', LBuffer.ToRawByteString); CheckEquals('_ello World!', LBuffer2.ToRawByteString); end; procedure TTestBuffer.Test_Remove; var LBuffer: TBuffer; begin LBuffer := 'Hello World!'; LBuffer.Remove(0); CheckEquals('', LBuffer.ToRawByteString); LBuffer := 'Hello World!'; LBuffer.Remove(1); CheckEquals('H', LBuffer.ToRawByteString); LBuffer := 'Hello World!'; LBuffer.Remove(11); CheckEquals('Hello World', LBuffer.ToRawByteString); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('').Remove(0); end, 'EArgumentOutOfRangeException not thrown in Remove(0).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Remove(-1); end, 'EArgumentOutOfRangeException not thrown in Remove(-1).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Remove(12) end, 'EArgumentOutOfRangeException not thrown in Remove(12).' ); {$ENDIF} end; procedure TTestBuffer.Test_Remove_Count; var LBuffer: TBuffer; begin LBuffer := 'Hello World!'; LBuffer.Remove(0, 1); CheckEquals('ello World!', LBuffer.ToRawByteString); LBuffer := 'Hello World!'; LBuffer.Remove(0, 12); CheckEquals('', LBuffer.ToRawByteString); LBuffer := 'Hello World!'; LBuffer.Remove(1, 11); CheckEquals('H', LBuffer.ToRawByteString); LBuffer := 'Hello World!'; LBuffer.Remove(0, 11); CheckEquals('!', LBuffer.ToRawByteString); {$IFDEF TBUFFER_CHECK_RANGES} CheckException(EArgumentOutOfRangeException, procedure() begin TBuffer.Create('').Remove(0, 0); end, 'EArgumentOutOfRangeException not thrown in Remove(0, 0).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Remove(-1, 0); end, 'EArgumentOutOfRangeException not thrown in Remove(-1, 0).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Remove(-1, 10); end, 'EArgumentOutOfRangeException not thrown in Remove(-1, 10).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Remove(1, 13); end, 'EArgumentOutOfRangeException not thrown in Remove(1, 13).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Remove(11, 2) end, 'EArgumentOutOfRangeException not thrown in Remove(11, 2).' ); CheckException(EArgumentOutOfRangeException, procedure() begin LBuffer.Remove(12, 0) end, 'EArgumentOutOfRangeException not thrown in Remove(12, 0).' ); {$ENDIF} end; procedure TTestBuffer.Test_Replace_Buffer; var LBuffer: TBuffer; begin LBuffer.Replace(TBuffer.Create('Hello'), TBuffer.Create('--')); CheckEquals('', LBuffer.ToRawByteString); LBuffer := 'Hello World'; LBuffer.Replace(TBuffer.Create('Hello'), TBuffer.Create('--')); CheckEquals('-- World', LBuffer.ToRawByteString); LBuffer.Replace(TBuffer.Create('-'), TBuffer.Create('--')); CheckEquals('---- World', LBuffer.ToRawByteString); LBuffer.Replace(TBuffer.Create(''), TBuffer.Create('')); CheckEquals('---- World', LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_Replace_Byte; var LBuffer: TBuffer; begin LBuffer.Replace(0, 10); CheckEquals('', LBuffer.ToRawByteString); LBuffer := 'Hello World'; LBuffer.Replace(Ord('l'), Ord('-')); CheckEquals('He--o Wor-d', LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_Replace_String; var LBuffer: TBuffer; begin LBuffer.Replace('Hello', '--'); CheckEquals('', LBuffer.ToRawByteString); LBuffer := 'Hello World'; LBuffer.Replace('Hello', '--'); CheckEquals('-- World', LBuffer.ToRawByteString); LBuffer.Replace('-', '--'); CheckEquals('---- World', LBuffer.ToRawByteString); LBuffer.Replace('', ''); CheckEquals('---- World', LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_Reverse; var LBuffer: TBuffer; begin LBuffer.Reverse; CheckEquals('', LBuffer.ToRawByteString); LBuffer := 'Hello World!'; LBuffer.Reverse; CheckEquals('!dlroW olleH', LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_StartsWith_Buffer; var LW, LB1, LB2: TBuffer; begin LW := 'Hello'; LB1 := ''; LB2 := 'Hello World!'; CheckTrue(LW.StartsWith(LW)); CheckFalse(LW.StartsWith(LB1)); CheckFalse(LW.StartsWith(LB2)); CheckFalse(LB1.StartsWith(LW)); CheckFalse(LB1.StartsWith(LB1)); CheckFalse(LB1.StartsWith(LB2)); CheckTrue(LB2.StartsWith(LW)); CheckFalse(LB2.StartsWith(LB1)); CheckTrue(LB2.StartsWith(LB2)); end; procedure TTestBuffer.Test_StartsWith_Byte; var LB1, LB2: TBuffer; begin LB1 := ''; LB2 := 'Hello World!'; CheckFalse(LB1.StartsWith(Ord('e'))); CheckFalse(LB1.StartsWith(Ord('H'))); CheckFalse(LB2.StartsWith(Ord('e'))); CheckTrue(LB2.StartsWith(Ord('H'))); end; procedure TTestBuffer.Test_StartsWith_String; var LB1, LB2: TBuffer; begin LB1 := ''; LB2 := 'Hello World!'; CheckFalse(LB1.StartsWith('Hello')); CheckFalse(LB1.StartsWith('')); CheckTrue(LB2.StartsWith('Hello')); CheckTrue(LB2.StartsWith('H')); CheckFalse(LB2.StartsWith('')); CheckTrue(LB2.StartsWith(LB2.ToRawByteString)); end; procedure TTestBuffer.Test_ToBytes; var LBuffer: TBuffer; begin CheckEquals(0, Length(LBuffer.ToBytes)); LBuffer := TBuffer.Create([1, 2, 3]); CheckEquals(3, Length(LBuffer.ToBytes)); CheckEquals(1, LBuffer.ToBytes()[0]); CheckEquals(2, LBuffer.ToBytes()[1]); CheckEquals(3, LBuffer.ToBytes()[2]); end; procedure TTestBuffer.Test_ToRawByteString; var LBuffer: TBuffer; begin CheckEquals('', LBuffer.ToRawByteString); LBuffer := 'Hello World!'; CheckEquals('Hello World!', LBuffer.ToRawByteString); end; procedure TTestBuffer.Test_TypeSupport; var LType: IType<TBuffer>; V: TBuffer; begin LType := TType<TBuffer>.Default; { Default } Check(LType.Compare('AA', 'AB') < 0, '(Default) Expected AA < AB'); Check(LType.Compare('AB', 'AA') > 0, '(Default) Expected AB > AA'); Check(LType.Compare('AA', 'AA') = 0, '(Default) Expected AA = AA'); Check(LType.Compare('aa', 'AA') > 0, '(Default) Expected aa > AA'); Check(LType.AreEqual('abc', 'abc'), '(Default) Expected abc eq abc'); Check(not LType.AreEqual('abc', 'ABC'), '(Default) Expected abc neq ABC'); Check(LType.GenerateHashCode('ABC') <> LType.GenerateHashCode('abc'), '(Default) Expected hashcode ABC neq abc'); Check(LType.GenerateHashCode('abcd') = LType.GenerateHashCode('abcd'), '(Default) Expected hashcode abcd eq abcd'); Check(LType.Management() = tmCompiler, 'Type support = tmCompiler'); Check(LType.Name = 'TBuffer', 'Type Name = "TBuffer"'); Check(LType.Size = 4, 'Type Size = 4'); Check(LType.TypeInfo = TypeInfo(TBuffer), 'Type information provider failed!'); Check(LType.Family = tfString, 'Type Family = tfString'); V := 'Hello'; Check(LType.GetString(V) = '(5 Elements)', '(Default) Expected GetString() = "(5 Elements)"'); end; initialization TestFramework.RegisterTest(TTestBuffer.Suite); end.
unit rt_objects; INTERFACE uses crt,rt_math; type RT_colorproc = procedure (obnr:integer; p:rt_point; var c:RT_color); RT_camera = OBJECT cop:RT_point; vrz:RT_point; view:RT_rect; minmax:RT_rect; xs,ys,xh,yh:real; ca,sa,cb,sb,alpha,beta:real; destructor done; constructor init(icop,ivrz:RT_point; ia,ib:real; ivp:RT_rect; imm:RT_rect); procedure compute_ray(x,y:integer; var ray:RT_ray); end; RT_object_pointer = ^RT_object; rt_OList_p = ^rt_olist; RT_OList = OBJECT next:rt_olist_p; prev:rt_olist_p; nr:integer; o:rt_object_pointer; constructor init; destructor done; procedure setobj(io:rt_object_pointer); procedure setnr(inr:integer); function addnext : rt_olist_p; function getnext:rt_olist_p; function getit:rt_object_pointer; end; RT_object = OBJECT ka,kd,ks:real; color:RT_color; specular_color:RT_color; phong_value:real; ior:real; reflection_value,refraction_value:real; texture:integer; destructor done; procedure initmat(c1,c2:RT_color; k1,k2,k3,p,refl,refr:real; iior:real; itext:integer); procedure compute_normal( intersection:RT_point; var normal:RT_normal) ; virtual; function intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; virtual; procedure transform(alpha,beta,gamma:real; d:rt_vector; s:real); virtual; END; RT_obj_kugel_p = ^RT_obj_kugel; RT_obj_Kugel = OBJECT (RT_object) center:RT_point; radius,square_radius:real; destructor done; constructor init(icentr:RT_point; r:real; c1,c2:RT_color; refl,refr,ika,ikd,iks,phongv,iior:real; itext:integer); procedure compute_normal( intersection:RT_point; var normal:RT_normal) ; virtual; function intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; virtual; procedure transform(alpha,beta,gamma:real; d:rt_vector; s:real); virtual; end; RT_obj_plane4_p =^rt_obj_plane4; RT_obj_plane4 = OBJECT (RT_Object) hilf1,hilf2,hilf3:real; a,b,c:rt_vector; normale:RT_vector; constructor init(ia,ib,ic:rt_vector; c1,c2:RT_color; refl,refr,ika,ikd,iks,phongv,iior:real; itext:integer); procedure compute_normal( intersection:RT_point; var normal:RT_normal) ; virtual; function intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; virtual; procedure transform(alpha,beta,gamma:real; d:rt_vector; s:real); virtual; end; RT_obj_para_p =^rt_obj_para; RT_obj_para = OBJECT (RT_obj_plane4) function intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; virtual; end; RT_obj_dreieck_p =^rt_obj_dreieck; RT_obj_dreieck = OBJECT (RT_obj_plane4) function intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; virtual; end; RT_obj_kreis_p =^rt_obj_kreis; RT_obj_kreis = OBJECT (RT_obj_plane4) function intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; virtual; end; IMPLEMENTATION { LISTEN_prozeduren } constructor rt_OList.init; begin prev:=nil; next:=nil; o:=nil; nr:=-1; end; destructor rt_OList.done; begin if next<>nil then begin writeln('->'); next^.done; writeln('KILL next'); dispose(next); end; writeln('KILL obj'); dispose(o); end; function rt_OList.addnext: rt_olist_p; begin next:=new(rt_olist_p,init); next^.prev:=@self; addnext:=next; end; procedure rt_OList.setnr(inr:integer); begin nr:=inr end; procedure rt_OList.setobj(io:rt_object_pointer); begin o:=io end; function rt_OList.getnext:rt_OList_p; begin getnext:=next; end; function rt_OList.getit:rt_object_pointer; begin getit:=o; end; { OBJECT_prozeduren } destructor RT_camera.done; begin end; constructor RT_camera.init( icop,ivrz:RT_point; ia,ib:real; ivp:RT_rect; imm:RT_rect); begin alpha:=ia; beta:=ib; ca:=cos(alpha*RAD); sa:=sin(alpha*RAD); sb:=sin(beta*RAD); cb:=cos(beta*RAD); cop:=icop; vrz:=ivrz; view:=ivp; minmax:=imm; xs:=(view.p2.x-view.p1.x)/(minmax.p2.x-minmax.p1.x); ys:=(view.p2.y-view.p1.y)/(minmax.p2.y-minmax.p1.y); xh:=xs*(minmax.p2.x-minmax.p1.x)/2; yh:=ys*(minmax.p2.y-minmax.p1.y)/2; end; procedure rt_camera.compute_ray(x,y:integer; var ray:RT_ray); var p:RT_point; begin p.x:=(x*xs-xh)+vrz.x; p.y:=(y*ys-yh)+vrz.y; p.z:=vrz.z; p2ray(cop,p,ray); end; destructor RT_object.done; begin Writeln('Fehler: RT_object.done(); wurde aufgerufen!'); halt(10); end; procedure rt_object.initmat; begin color:=c1; specular_color:=c2; ka:=k1; kd:=k2; ks:=k3; phong_value:=p; refraction_value:=refr; reflection_value:=refl; ior:=iior; texture:=itext; end; procedure RT_object.compute_normal( intersection:RT_point; var normal:RT_normal); begin end; function RT_object.intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; begin end; procedure rt_object.transform; begin end; { KUGEL } constructor RT_obj_kugel.init; begin center:=icentr; radius:=r; square_radius:=radius*radius; initmat(c1,c2,ika,ikd,iks,phongv,refl,refr,iior,itext); end; destructor RT_obj_kugel.done; begin end; procedure RT_obj_kugel.compute_normal( intersection:RT_point; var normal:RT_normal); begin p2vector(center,intersection,normal); vnorm(normal,normal); end; procedure rt_obj_kugel.transform; begin trans(center,alpha,beta,gamma,center); vadd(d,rt_vector(center),rt_vector(center)); square_radius:=sqr(sqrt(square_radius)*s); end; function RT_obj_kugel.intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; var t1,t2:real; hilf:RT_vector; a,b,c:real; begin vsub(RT_vector(ray.q),RT_vector(center),hilf); a:=sqr(ray.v.x)+sqr(ray.v.y)+sqr(ray.v.z); b:=2*(ray.v.x*(ray.q.x-center.x)+ ray.v.y*(ray.q.y-center.y)+ ray.v.z*(ray.q.z-center.z));; c:= sqr(ray.q.x-center.x)+ sqr(ray.q.y-center.y)+ sqr(ray.q.z-center.z)- square_radius;; if RT_solve_qglabc(a,b,c,t1,t2) then begin t1:=min3real(t1,t2,INFINITY_HIGH); intersect:=true; vmul(t1,ray.v,hilf); vadd(RT_vector(ray.q),hilf,RT_vector(p)); t:=errepsilon(t1); if t=0 then begin intersect:=false; end; end else begin intersect:=false; t:=0; end; end; { b ^ a...ortsvektor a | b...spannt ebene auf EBENE4 ----->*-->c c... -- " -- laut buch } constructor rt_obj_plane4.init; var h1,h2:RT_Vector; begin hilf1:=det2( ib.y,ic.y, ib.z,ic.z); hilf2:=det2( ib.x,ic.x, ib.z,ic.z); hilf3:=det2( ib.x,ic.x, ib.y,ic.y); a:=ia; b:=ib; c:=ic; vcross(b,c,normale); (*vnorm(inorm,normale);*) initmat(c1,c2,ika,ikd,iks,phongv,refl,refr,iior,itext); end; procedure rt_obj_plane4.transform; begin trans(rt_point(a),alpha,beta,gamma,rt_point(a)); trans(rt_point(b),alpha,beta,gamma,rt_point(b)); trans(rt_point(c),alpha,beta,gamma,rt_point(c)); vadd (d,a,a); vmul (s,a,a); vcross(b,c,normale); vnorm(normale,normale); end; procedure rt_obj_plane4.compute_normal( intersection:RT_point; var normal:RT_normal); begin normal:=normale; end; function rt_obj_plane4.intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; var d:real; begin intersect:=false; d:=ray.v.y*hilf2-ray.v.x*hilf1-ray.v.z*hilf3; d:=errepsilon(d); if d<>0 then begin t:=((ray.q.x-a.x)*hilf1-(ray.q.y-a.y)*hilf2+(ray.q.z-a.z)*hilf3)/d; t:=errepsilon(t); intersect:=(t>0); ray2point(ray,t,p); end else begin t:=-1; end; end; function rt_obj_para.intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; var d:real; r,s:real; Q,V:rt_vector; begin q:=rt_vector(ray.q); v:=rt_vector(ray.v); intersect:=false; d:=v.y*hilf2-v.x*hilf1-v.z*hilf3; d:=errepsilon(d); if d<>0 then begin t:=((q.x-a.x)*hilf1-(q.y-a.y)*hilf2+(q.z-a.z)*hilf3)/d; t:=errepsilon(t); intersect:=(t>0); ray2point(ray,t,p); r:=det3( q.x-a.x,c.x,-v.x, q.y-a.y,c.y,-v.y, q.y-a.y,c.y,-v.y)/d; s:=det3( c.x,q.x-a.x,-v.x, c.y,q.y-a.y,-v.y, c.z,q.z-a.z,-v.z)/d; if (r<0) or (s<0) or (r>1) or (s>1) then intersect:=false; end else begin t:=-1; end; end; function rt_obj_dreieck.intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; var d:real; r,s:real; Q,V:rt_vector; begin q:=rt_vector(ray.q); v:=rt_vector(ray.v); intersect:=false; d:=v.y*hilf2-v.x*hilf1-v.z*hilf3; d:=errepsilon(d); if d<>0 then begin t:=((q.x-a.x)*hilf1-(q.y-a.y)*hilf2+(q.z-a.z)*hilf3)/d; t:=errepsilon(t); intersect:=(t>0); ray2point(ray,t,p); r:=det3( q.x-a.x,c.x,-v.x, q.y-a.y,c.y,-v.y, q.y-a.y,c.y,-v.y)/d; s:=det3( c.x,q.x-a.x,-v.x, c.y,q.y-a.y,-v.y, c.z,q.z-a.z,-v.z)/d; if (r<0) or (s<0) or (r>1) or (s>1) or (r+s>1) then intersect:=false; end else begin t:=-1; end; end; function rt_obj_kreis.intersect(ray:RT_ray; tiefe:integer; var p:RT_point; var t:real):boolean; var d:real; r,s:real; Q,V:rt_vector; begin q:=rt_vector(ray.q); v:=rt_vector(ray.v); intersect:=false; d:=v.y*hilf2-v.x*hilf1-v.z*hilf3; d:=errepsilon(d); if d<>0 then begin t:=((q.x-a.x)*hilf1-(q.y-a.y)*hilf2+(q.z-a.z)*hilf3)/d; t:=errepsilon(t); intersect:=(t>0); ray2point(ray,t,p); r:=det3( q.x-a.x,c.x,-v.x, q.y-a.y,c.y,-v.y, q.y-a.y,c.y,-v.y)/d; s:=det3( c.x,q.x-a.x,-v.x, c.y,q.y-a.y,-v.y, c.z,q.z-a.z,-v.z)/d; if (r*r+s*s>1) then intersect:=false; end else begin t:=-1; end; end; begin end.
unit uvectors; {$mode objfpc}{$H+} interface uses SysUtils, math; type TVector = array of double; operator + (a,b: TVector) z: TVector; operator + (a: double; b:TVector) z: TVector; operator + (a: TVector; b: double) z: TVector; operator - (a,b: TVector) z: TVector; operator - (a: double; b:TVector) z: TVector; operator - (a: TVector; b: double) z: TVector; operator - (a: TVector) z: TVector; operator * (a,b: TVector) z: double; operator * (a: double; b:TVector) z: TVector; operator * (a: TVector; b: double) z: TVector; operator / (a: double; b:TVector) z: TVector; operator / (a: TVector; b: double) z: TVector; operator / (a,b:TVector)z: TVector; operator mod(a,b: TVector)z: TVector; function mulVectors(a,b: TVector): TVector; function vectorToStr(v: TVector): string; implementation const e = 0.0001; function vectorToStr(v: TVector): string; var i:integer; sett: TFormatSettings; begin if not assigned(v) then exit(''); sett.DecimalSeparator := '.'; result := '{'; for i := 0 to length(v) - 1 do if i < length(v) - 1 then result += floatToStr(v[i], sett) + ',' else result += floatToStr(v[i], sett); result += '}' end; operator+(a, b: TVector)z: TVector; var i: integer; begin z := nil; if not (assigned(a) and assigned(b)) then exit; SetLength(z, length(a)); for i := 0 to length(z) - 1 do z[i] := a[i] + b[i] end; operator+(a: double; b: TVector)z: TVector; begin z := b + a end; operator+(a: TVector; b: double)z: TVector; var i: integer; begin if not assigned(a) then exit; SetLength(z, length(a)); for i := 0 to length(z) - 1 do z[i] := a[i] + b end; operator-(a, b: TVector)z: TVector; var i: integer; begin if not (assigned(a) and assigned(b)) then exit; SetLength(z, length(a)); for i := 0 to length(z) - 1 do z[i] := a[i] - b[i] end; operator-(a: double; b: TVector)z: TVector; var i: integer; begin if not assigned(b) then exit; SetLength(z, length(b)); for i := 0 to length(z) - 1 do z[i] := a - b[i] end; operator-(a: TVector; b: double)z: TVector; var i: integer; begin if not assigned(a) then exit; SetLength(z, length(a)); for i := 0 to length(z) - 1 do z[i] := a[i] - b end; operator-(a: TVector)z: TVector; var i: integer; begin if not assigned(a) then exit; SetLength(z, length(a)); for i := 0 to length(z) - 1 do z[i] := -a[i]; end; operator*(a, b: TVector)z: double; var i: integer; begin z := 0; if not (assigned(a) and assigned(b)) then exit; for i := 0 to length(a) - 1 do z := z + (a[i] * b[i]) end; operator*(a: double; b: TVector)z: TVector; begin z := b * a; end; operator*(a: TVector; b: double)z: TVector; var i: integer; begin if not assigned(a) then exit; SetLength(z, length(a)); for i := 0 to length(z) - 1 do z[i] := a[i] * b end; operator/(a: double; b: TVector)z: TVector; var i: integer; begin if not assigned(b) then exit; SetLength(z, length(b)); for i := 0 to length(z) - 1 do begin // b[i] = 0 if abs(b[i]) < e then z[i] := infinity else z[i] := a / b[i]; end; end; operator/(a: TVector; b: double)z: TVector; var i: integer; begin if not assigned(a) then exit; SetLength(z, length(a)); for i := 0 to length(z) - 1 do begin // b[i] = 0 if abs(b) < e then z[i] := infinity else z[i] := a[i] / b; end; end; operator/(a, b: TVector)z: TVector; var i: integer; begin if not (assigned(a) and assigned(b)) then exit; SetLength(z, length(a)); for i := 0 to length(z) - 1 do if abs(b[i]) < e then z[i] := infinity else z[i] := a[i] / b[i]; end; operator mod(a, b: TVector)z: TVector; var i: integer; begin if not (assigned(a) and assigned(b)) then exit; SetLength(z, length(a)); for i := 0 to length(z) - 1 do if abs(b[i]) < e then z[i] := infinity else z[i] := frac(a[i] / b[i]) * b[i]; end; function mulVectors(a, b: TVector): TVector; begin if not (assigned(a) and assigned(b)) then exit; SetLength(result, length(a)); result[0] := (a[1] * b[2]) - (a[2] * b[1]); result[1] := (a[2] * b[0]) - (a[0] * b[2]); result[2] := (a[0] * b[1]) - (a[1] * b[0]); end; end.
unit StringBuilder; interface type HCkBinData = Pointer; HCkStringBuilder = Pointer; HCkByteData = Pointer; HCkString = Pointer; function CkStringBuilder_Create: HCkStringBuilder; stdcall; procedure CkStringBuilder_Dispose(handle: HCkStringBuilder); stdcall; function CkStringBuilder_getIntValue(objHandle: HCkStringBuilder): Integer; stdcall; procedure CkStringBuilder_putIntValue(objHandle: HCkStringBuilder; newPropVal: Integer); stdcall; function CkStringBuilder_getIsBase64(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_getLastMethodSuccess(objHandle: HCkStringBuilder): wordbool; stdcall; procedure CkStringBuilder_putLastMethodSuccess(objHandle: HCkStringBuilder; newPropVal: wordbool); stdcall; function CkStringBuilder_getLength(objHandle: HCkStringBuilder): Integer; stdcall; function CkStringBuilder_Append(objHandle: HCkStringBuilder; value: PWideChar): wordbool; stdcall; function CkStringBuilder_AppendBd(objHandle: HCkStringBuilder; binData: HCkBinData; charset: PWideChar; offset: Integer; numBytes: Integer): wordbool; stdcall; function CkStringBuilder_AppendEncoded(objHandle: HCkStringBuilder; binaryData: HCkByteData; encoding: PWideChar): wordbool; stdcall; function CkStringBuilder_AppendInt(objHandle: HCkStringBuilder; value: Integer): wordbool; stdcall; function CkStringBuilder_AppendInt64(objHandle: HCkStringBuilder; value: Int64): wordbool; stdcall; function CkStringBuilder_AppendLine(objHandle: HCkStringBuilder; value: PWideChar; crlf: wordbool): wordbool; stdcall; function CkStringBuilder_AppendSb(objHandle: HCkStringBuilder; sb: HCkStringBuilder): wordbool; stdcall; procedure CkStringBuilder_Clear(objHandle: HCkStringBuilder); stdcall; function CkStringBuilder_Contains(objHandle: HCkStringBuilder; str: PWideChar; caseSensitive: wordbool): wordbool; stdcall; function CkStringBuilder_ContainsWord(objHandle: HCkStringBuilder; word: PWideChar; caseSensitive: wordbool): wordbool; stdcall; function CkStringBuilder_ContentsEqual(objHandle: HCkStringBuilder; str: PWideChar; caseSensitive: wordbool): wordbool; stdcall; function CkStringBuilder_ContentsEqualSb(objHandle: HCkStringBuilder; sb: HCkStringBuilder; caseSensitive: wordbool): wordbool; stdcall; function CkStringBuilder_Decode(objHandle: HCkStringBuilder; encoding: PWideChar; charset: PWideChar): wordbool; stdcall; function CkStringBuilder_Encode(objHandle: HCkStringBuilder; encoding: PWideChar; charset: PWideChar): wordbool; stdcall; function CkStringBuilder_EndsWith(objHandle: HCkStringBuilder; substr: PWideChar; caseSensitive: wordbool): wordbool; stdcall; function CkStringBuilder_EntityDecode(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_GetAfterBetween(objHandle: HCkStringBuilder; searchAfter: PWideChar; beginMark: PWideChar; endMark: PWideChar; outStr: HCkString): wordbool; stdcall; function CkStringBuilder__getAfterBetween(objHandle: HCkStringBuilder; searchAfter: PWideChar; beginMark: PWideChar; endMark: PWideChar): PWideChar; stdcall; function CkStringBuilder_GetAsString(objHandle: HCkStringBuilder; outStr: HCkString): wordbool; stdcall; function CkStringBuilder__getAsString(objHandle: HCkStringBuilder): PWideChar; stdcall; function CkStringBuilder_GetBetween(objHandle: HCkStringBuilder; beginMark: PWideChar; endMark: PWideChar; outStr: HCkString): wordbool; stdcall; function CkStringBuilder__getBetween(objHandle: HCkStringBuilder; beginMark: PWideChar; endMark: PWideChar): PWideChar; stdcall; function CkStringBuilder_GetDecoded(objHandle: HCkStringBuilder; encoding: PWideChar; outData: HCkByteData): wordbool; stdcall; function CkStringBuilder_GetEncoded(objHandle: HCkStringBuilder; encoding: PWideChar; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkStringBuilder__getEncoded(objHandle: HCkStringBuilder; encoding: PWideChar; charset: PWideChar): PWideChar; stdcall; function CkStringBuilder_GetNth(objHandle: HCkStringBuilder; index: Integer; delimiterChar: PWideChar; exceptDoubleQuoted: wordbool; exceptEscaped: wordbool; outStr: HCkString): wordbool; stdcall; function CkStringBuilder__getNth(objHandle: HCkStringBuilder; index: Integer; delimiterChar: PWideChar; exceptDoubleQuoted: wordbool; exceptEscaped: wordbool): PWideChar; stdcall; function CkStringBuilder_LastNLines(objHandle: HCkStringBuilder; numLines: Integer; bCrlf: wordbool; outStr: HCkString): wordbool; stdcall; function CkStringBuilder__lastNLines(objHandle: HCkStringBuilder; numLines: Integer; bCrlf: wordbool): PWideChar; stdcall; function CkStringBuilder_LoadFile(objHandle: HCkStringBuilder; path: PWideChar; charset: PWideChar): wordbool; stdcall; function CkStringBuilder_Prepend(objHandle: HCkStringBuilder; value: PWideChar): wordbool; stdcall; function CkStringBuilder_PunyDecode(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_PunyEncode(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_Replace(objHandle: HCkStringBuilder; value: PWideChar; replacement: PWideChar): Integer; stdcall; function CkStringBuilder_ReplaceAfterFinal(objHandle: HCkStringBuilder; marker: PWideChar; replacement: PWideChar): wordbool; stdcall; function CkStringBuilder_ReplaceAllBetween(objHandle: HCkStringBuilder; beginMark: PWideChar; endMark: PWideChar; replacement: PWideChar; replaceMarks: wordbool): wordbool; stdcall; function CkStringBuilder_ReplaceBetween(objHandle: HCkStringBuilder; beginMark: PWideChar; endMark: PWideChar; value: PWideChar; replacement: PWideChar): Integer; stdcall; function CkStringBuilder_ReplaceI(objHandle: HCkStringBuilder; value: PWideChar; replacement: Integer): Integer; stdcall; function CkStringBuilder_ReplaceWord(objHandle: HCkStringBuilder; value: PWideChar; replacement: PWideChar): Integer; stdcall; procedure CkStringBuilder_SecureClear(objHandle: HCkStringBuilder); stdcall; function CkStringBuilder_SetNth(objHandle: HCkStringBuilder; index: Integer; value: PWideChar; delimiterChar: PWideChar; exceptDoubleQuoted: wordbool; exceptEscaped: wordbool): wordbool; stdcall; function CkStringBuilder_SetString(objHandle: HCkStringBuilder; value: PWideChar): wordbool; stdcall; function CkStringBuilder_StartsWith(objHandle: HCkStringBuilder; substr: PWideChar; caseSensitive: wordbool): wordbool; stdcall; function CkStringBuilder_ToCRLF(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_ToLF(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_ToLowercase(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_ToUppercase(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_Trim(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_TrimInsideSpaces(objHandle: HCkStringBuilder): wordbool; stdcall; function CkStringBuilder_WriteFile(objHandle: HCkStringBuilder; path: PWideChar; charset: PWideChar; emitBom: wordbool): wordbool; stdcall; function CkStringBuilder_WriteFileIfModified(objHandle: HCkStringBuilder; path: PWideChar; charset: PWideChar; emitBom: wordbool): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkStringBuilder_Create; external DLLName; procedure CkStringBuilder_Dispose; external DLLName; function CkStringBuilder_getIntValue; external DLLName; procedure CkStringBuilder_putIntValue; external DLLName; function CkStringBuilder_getIsBase64; external DLLName; function CkStringBuilder_getLastMethodSuccess; external DLLName; procedure CkStringBuilder_putLastMethodSuccess; external DLLName; function CkStringBuilder_getLength; external DLLName; function CkStringBuilder_Append; external DLLName; function CkStringBuilder_AppendBd; external DLLName; function CkStringBuilder_AppendEncoded; external DLLName; function CkStringBuilder_AppendInt; external DLLName; function CkStringBuilder_AppendInt64; external DLLName; function CkStringBuilder_AppendLine; external DLLName; function CkStringBuilder_AppendSb; external DLLName; procedure CkStringBuilder_Clear; external DLLName; function CkStringBuilder_Contains; external DLLName; function CkStringBuilder_ContainsWord; external DLLName; function CkStringBuilder_ContentsEqual; external DLLName; function CkStringBuilder_ContentsEqualSb; external DLLName; function CkStringBuilder_Decode; external DLLName; function CkStringBuilder_Encode; external DLLName; function CkStringBuilder_EndsWith; external DLLName; function CkStringBuilder_EntityDecode; external DLLName; function CkStringBuilder_GetAfterBetween; external DLLName; function CkStringBuilder__getAfterBetween; external DLLName; function CkStringBuilder_GetAsString; external DLLName; function CkStringBuilder__getAsString; external DLLName; function CkStringBuilder_GetBetween; external DLLName; function CkStringBuilder__getBetween; external DLLName; function CkStringBuilder_GetDecoded; external DLLName; function CkStringBuilder_GetEncoded; external DLLName; function CkStringBuilder__getEncoded; external DLLName; function CkStringBuilder_GetNth; external DLLName; function CkStringBuilder__getNth; external DLLName; function CkStringBuilder_LastNLines; external DLLName; function CkStringBuilder__lastNLines; external DLLName; function CkStringBuilder_LoadFile; external DLLName; function CkStringBuilder_Prepend; external DLLName; function CkStringBuilder_PunyDecode; external DLLName; function CkStringBuilder_PunyEncode; external DLLName; function CkStringBuilder_Replace; external DLLName; function CkStringBuilder_ReplaceAfterFinal; external DLLName; function CkStringBuilder_ReplaceAllBetween; external DLLName; function CkStringBuilder_ReplaceBetween; external DLLName; function CkStringBuilder_ReplaceI; external DLLName; function CkStringBuilder_ReplaceWord; external DLLName; procedure CkStringBuilder_SecureClear; external DLLName; function CkStringBuilder_SetNth; external DLLName; function CkStringBuilder_SetString; external DLLName; function CkStringBuilder_StartsWith; external DLLName; function CkStringBuilder_ToCRLF; external DLLName; function CkStringBuilder_ToLF; external DLLName; function CkStringBuilder_ToLowercase; external DLLName; function CkStringBuilder_ToUppercase; external DLLName; function CkStringBuilder_Trim; external DLLName; function CkStringBuilder_TrimInsideSpaces; external DLLName; function CkStringBuilder_WriteFile; external DLLName; function CkStringBuilder_WriteFileIfModified; external DLLName; end.
unit LogStandardConfig; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LogManager, LogItem, ConsoleLogWriter, DefaultLogTextFormat; type { TLogStandardConfig } TLogStandardConfig = class public class function CreateLogManager(const aOwner: TComponent): TLogManager; class procedure CreateIt(const aOwner: TComponent; out aManager: TLogManager); class procedure CreateIt(out aManager: TLogManager); class function CreateConsoleLogger(const aOwner: TComponent): TConsoleLogWriter; class procedure CreateIt(const aOwner: TComponent; out aWriter: TConsoleLogWriter); end; implementation { TLogStandardConfig } class function TLogStandardConfig.CreateLogManager(const aOwner: TComponent ): TLogManager; begin result := TLogManager.Create(aOwner); result.StandardLogTagToString := TStandardLogTagToString.Create; end; class procedure TLogStandardConfig.CreateIt(const aOwner: TComponent; out aManager: TLogManager); begin aManager := CreateLogManager(aOwner); end; class procedure TLogStandardConfig.CreateIt(out aManager: TLogManager); begin aManager := CreateLogManager(nil); end; class function TLogStandardConfig.CreateConsoleLogger(const aOwner: TComponent ): TConsoleLogWriter; begin result := TConsoleLogWriter.Create(aOwner); result.Format := TDefaultLogTextFormat.Create; result.Name := 'DefaultConsoleLogger'; end; class procedure TLogStandardConfig.CreateIt(const aOwner: TComponent; out aWriter: TConsoleLogWriter); begin aWriter := CreateConsoleLogger(aOwner); end; end.
unit MsgRetrieveForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Winshoes, WinshoeMessage, NNTPWinshoe, FolderList; type TformMsgRetrieve = class(TForm) butnCancel: TButton; pbarNewsgroup: TProgressBar; pbarMessage: TProgressBar; lablHost: TLabel; lablNewsgroup: TLabel; lablStatus: TLabel; lablNewsgroupCount: TLabel; lablMsgNumbers: TLabel; NNTP: TWinshoeNNTP; wsMSG: TWinshoeMessage; procedure butnCancelClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure NNTPStatus(Sender: TComponent; const sOut: String); private FTreeNode: TTreeNode; FUserAbort: Boolean; procedure SetHostData(HostData: THostData); procedure ResetDisplay; protected procedure RetrieveMsgsPrim(NewsItem: TTreeNode); procedure RetrieveNewsMsgs(NewsItem: TTreeNode); procedure RetrieveHostMsgs(HostItem: TTreeNode); procedure RetrieveAllMsgs(RootItem: TTreeNode); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property TreeNode: TTreeNode read FTreeNode write FTreeNode; end; implementation uses Datamodule, MainForm; {$R *.DFM} constructor TformMsgRetrieve.Create(AOwner: TComponent); begin inherited Create(AOwner); dataMain.tablAuthor.Open; dataMain.tablArticle.Open; ResetDisplay; end; destructor TformMsgRetrieve.Destroy; begin dataMain.tablAuthor.Close; dataMain.tablArticle.Close; inherited Destroy; end; procedure TformMsgRetrieve.butnCancelClick(Sender: TObject); begin FUserAbort := True; end; procedure TformMsgRetrieve.ResetDisplay; begin lablHost.Caption := ''; lablNewsgroupCount.Caption := ''; lablNewsgroup.Caption := ''; lablMsgNumbers.Caption := ''; pbarNewsgroup.Position := 0; pbarMessage.Position := 0; Self.Refresh; end; procedure TformMsgRetrieve.SetHostData(HostData: THostData); begin NNTP.Host := HostData.HostName; NNTP.Port := HostData.Port; NNTP.UserID := HostData.UserID; NNTP.Password := HostData.Password; lablHost.Caption := HostData.HostName; lablHost.Update; end; procedure TformMsgRetrieve.RetrieveMsgsPrim(NewsItem: TTreeNode); var NewsData: TNewsgroupData; ArticleNo: Integer; begin NewsData := TNewsgroupData(NewsItem.Data); pbarNewsgroup.Position := Succ(pbarNewsgroup.Position); lablNewsgroup.Caption := NewsData.NewsgroupName; lablNewsgroup.Update; NNTP.SelectGroup(NewsData.NewsgroupName); lablMsgNumbers.Caption := Format('(%d of %d)', [NewsData.HiMsg, NNTP.MsgHigh]); lablMsgNumbers.Update; {-Check to see if any new messages have been posted} if NewsData.HiMsg < NNTP.MsgHigh then begin try {-Adjust low message number if needed} if NewsData.HiMsg < Pred(NNTP.MsgLow) then begin NewsData.HiMsg := Pred(NNTP.MsgLow); end; with dataMain do begin pbarMessage.Max := NNTP.MsgHigh - NewsData.HiMsg; pbarMessage.Position := 0; {-Attempt to retrieve all message numbers since last run} for ArticleNo := Succ(NewsData.HiMsg) to NNTP.MsgHigh do begin try pbarMessage.Position := Succ(pbarMessage.Position); lablMsgNumbers.Caption := Format('(%d of %d)', [ArticleNo, NNTP.MsgHigh]); lablMsgNumbers.Update; {-Retrieve message from server} if NNTP.GetHeader(ArticleNo, '', wsMSG) then begin {-Add new Author name if not found} if not tablAuthor.FindKey([wsMSG.ExtractReal(wsMSG.From)]) then begin tablAuthor.Append; tablAuthorAuthor_Name.Value := wsMSG.ExtractReal(wsMSG.From); tablAuthorReply_To.Value := wsMSG.ExtractAddr(wsMSG.From); tablAuthor.Post; end; {-Post message information for subsequent stat analysis} tablArticle.Append; tablArticleArticle_No.Value := ArticleNo; tablArticleAuthor_ID.Value := tablAuthorAuthor_ID.Value; tablArticleArticle_Date.Value := wsMSG.Date; tablArticleHost_ID.Value := NewsData.HostID; tablArticleNewsgroup_ID.Value := NewsData.NewsgroupID; tablArticle.Post; end; except {-Absorbs missing articles from server} end; {-Check to see if user cancelled} Application.ProcessMessages; if FUserAbort or not NNTP.Connected then Break; end; end; NewsData.HiMsg := ArticleNo; finally NewsData.Save; {-Post changes} end; end; end; procedure TformMsgRetrieve.RetrieveNewsMsgs(NewsItem: TTreeNode); begin SetHostData(THostData(NewsItem.Parent.Data)); pbarNewsgroup.Max := 1; pbarNewsgroup.Position := 0; lablNewsgroupCount.Caption := ''; lablNewsgroupCount.Update; NNTP.Connect; try RetrieveMsgsPrim(NewsItem); finally NNTP.Disconnect; end; end; procedure TformMsgRetrieve.RetrieveHostMsgs(HostItem: TTreeNode); var NewsItem: TTreeNode; begin SetHostData(THostData(HostItem.Data)); pbarNewsgroup.Max := HostItem.Count; pbarNewsgroup.Position := 0; lablNewsgroupCount.Caption := Format('Subscribed: %d', [HostItem.Count]); lablNewsgroupCount.Update; NNTP.Connect; try NewsItem := HostItem.GetFirstChild; while Assigned(NewsItem) and not FUserAbort and NNTP.Connected do begin RetrieveMsgsPrim(NewsItem); NewsItem := NewsItem.GetNextChild(NewsItem); end; finally NNTP.Disconnect; end; end; procedure TformMsgRetrieve.RetrieveAllMsgs(RootItem: TTreeNode); var HostItem: TTreeNode; begin HostItem := formMain.lstvFolders.Items.GetFirstNode.GetFirstChild; while Assigned(HostItem) and not FUserAbort do begin ResetDisplay; if THostData(HostItem.Data).IncludeDuringScan then begin RetrieveHostMsgs(HostItem); end; HostItem := HostItem.GetNextChild(HostItem); end; end; procedure TformMsgRetrieve.FormActivate(Sender: TObject); begin Refresh; if TObject(TreeNode.Data) is TFolderData then RetrieveAllMsgs(TreeNode) else if TObject(TreeNode.Data) is THostData then RetrieveHostMsgs(TreeNode) else if TObject(TreeNode.Data) is TNewsgroupData then RetrieveNewsMsgs(TreeNode); end; procedure TformMsgRetrieve.NNTPStatus(Sender: TComponent; const sOut: String); begin lablStatus.Caption := Trim(sOut); lablStatus.Update; end; end.
{----------------------------------------------------------------------------- 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/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvBaseDBLogonDialog.pas, released on 2006-07-21 The Initial Developer of the Original Code is Jens Fudickar All Rights Reserved. Contributor(s): You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id: JvBaseDBDialog.pas 13413 2012-09-08 11:02:21Z ahuser $ unit JvBaseDBDialog; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} JvDynControlEngine, Windows, Classes, JvBaseDlg, JvAppStorage, Forms, Controls; type TJvBaseDBDialog = class(TJvCommonDialog) private FAppStorage: TJvCustomAppStorage; FAppStoragePath: string; FDBDialog: TForm; FDynControlEngine: TJvDynControlEngine; FSession: TComponent; FParentWnd: HWND; function GetDynControlEngine: TJvDynControlEngine; protected function CreateForm: TForm; virtual; procedure CreateFormControls(aForm: TForm); virtual; procedure AfterCreateFormControls(aForm: TForm); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetAppStorage(Value: TJvCustomAppStorage); virtual; procedure SetAppStoragePath(Value: string); virtual; procedure SetSession(const Value: TComponent); virtual; property AppStorage: TJvCustomAppStorage read FAppStorage write SetAppStorage; property AppStoragePath: string read FAppStoragePath write SetAppStoragePath; public function Execute(ParentWnd: HWND): Boolean; overload; override; function SessionIsConnected: Boolean; virtual; property DBDialog: TForm read FDBDialog ; property Session: TComponent read FSession write SetSession; published property DynControlEngine: TJvDynControlEngine read GetDynControlEngine write FDynControlEngine; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvBaseDBDialog.pas $'; Revision: '$Revision: 13413 $'; Date: '$Date: 2012-09-08 13:02:21 +0200 (sam. 08 sept. 2012) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation uses SysUtils, Types, JvJCLUtils, // SetWindowLongPtr for older Delphi versions JvJVCLUtils; function TJvBaseDBDialog.CreateForm: TForm; begin Result := TForm(DynControlEngine.CreateForm('', '')); CreateFormControls(Result); if FParentWnd <> 0 then SetWindowLongPtr(Result.Handle, GWL_HWNDPARENT, LONG_PTR(FParentWnd)); end; procedure TJvBaseDBDialog.CreateFormControls(aForm: TForm); begin end; procedure TJvBaseDBDialog.AfterCreateFormControls(aForm: TForm); begin end; function TJvBaseDBDialog.Execute(ParentWnd: HWND): Boolean; begin if not Assigned(Session) then Abort; FParentWnd := ParentWnd; FDBDialog := CreateForm; try AfterCreateFormControls(FDBDialog); FDBDialog.ShowModal; Result := FDBDialog.ModalResult = mrOk; finally FreeAndNil(FDBDialog); end; end; function TJvBaseDBDialog.GetDynControlEngine: TJvDynControlEngine; begin if Assigned(FDynControlEngine) then Result := FDynControlEngine else Result := DefaultDynControlEngine; end; procedure TJvBaseDBDialog.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) then if (AComponent = FAppStorage) then FAppStorage := nil else if (AComponent = FSession) then FSession := nil else if (AComponent = FDBDialog) then FDBDialog := nil; end; function TJvBaseDBDialog.SessionIsConnected: Boolean; begin Result := False; end; procedure TJvBaseDBDialog.SetAppStorage(Value: TJvCustomAppStorage); begin ReplaceComponentReference(Self, Value, TComponent(FAppStorage)); end; procedure TJvBaseDBDialog.SetAppStoragePath(Value: string); begin if Value <> AppStoragePath then FAppStoragePath := Value; end; procedure TJvBaseDBDialog.SetSession(const Value: TComponent); begin ReplaceComponentReference(Self, Value, FSession); end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ImgList; type TFmSimpleReplace = class(TForm) BtGo: TButton; BtSelectDirectory: TButton; CbxCaseInsensitivity: TCheckBox; CbxConfirmation: TCheckBox; CbxReplaceText: TCheckBox; CbxSubfolders: TCheckBox; CmbFileType: TComboBox; CmbFolder: TComboBox; CmbReplaceText: TComboBox; CmbSearchText: TComboBox; GbxSearchContext: TGroupBox; GbxText: TGroupBox; ImageList: TImageList; LbFileType: TLabel; LbFolder: TLabel; LblSearchText: TLabel; ProgressBar: TProgressBar; StatusBar: TStatusBar; TvwResults: TTreeView; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure TvwResultsAdvancedCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); procedure BtGoClick(Sender: TObject); procedure BtSelectDirectoryClick(Sender: TObject); procedure CmbFolderChange(Sender: TObject); procedure CmbSearchTextChange(Sender: TObject); procedure CmbSearchTextKeyPress(Sender: TObject; var Key: Char); procedure CmbReplaceTextKeyPress(Sender: TObject; var Key: Char); private FIniFileName: TFileName; FGlobalLineCount: Integer; procedure CheckGoPossible; procedure UpdateComboBoxes; public procedure ProcessFile(FileName: TFileName); end; var FmSimpleReplace: TFmSimpleReplace; implementation {$R *.dfm} uses FileCtrl, Inifiles; function GetNextExtension(var FileMask: string): string; var DelimiterPos: Integer; begin DelimiterPos := Pos(';', FileMask); if DelimiterPos = 0 then begin Result := Trim(FileMask); FileMask := ''; end else begin Result := Trim(Copy(FileMask, 1, DelimiterPos - 1)); Delete(FileMask, 1, DelimiterPos); end; end; function LowerCaseFileMask(FileName: TFileName): TFileName; begin Result := '*' + LowerCase(ExtractFileExt(FileName)); end; procedure FindFiles(FilesList: TStringList; StartDir, FileMask: string); var SR : TSearchRec; DirList: TStringList; Index : Integer; Temp : string; CurMask: string; const COptions: Integer = FaAnyFile - FaDirectory; begin if StartDir[Length(StartDir)] <> '\' then StartDir := StartDir + '\'; Temp := FileMask; repeat CurMask := GetNextExtension(Temp); if (CurMask <> '') and (FindFirst(StartDir + CurMask, COptions, SR) = 0) then try repeat if LowerCaseFileMask(StartDir + SR.Name) = LowerCase(CurMask) then FilesList.Add(StartDir + SR.Name); until FindNext(SR) <> 0; finally FindClose(SR); end; until Temp = ''; // Build a list of subdirectories DirList := TStringList.Create; try if FindFirst(StartDir + '*.*', FaAnyFile, SR) = 0 then try repeat if ((SR.Attr and FaDirectory) <> 0) and (SR.Name[1] <> '.') then DirList.Add(StartDir + SR.Name); until FindNext(SR) <> 0; finally FindClose(SR); end; // Scan the list of subdirectories for index := 0 to DirList.Count - 1 do FindFiles(FilesList, DirList[index], FileMask); finally FreeAndNil(DirList); end; end; { TFmSimpleReplace } procedure TFmSimpleReplace.FormCreate(Sender: TObject); begin FIniFileName := ChangeFileExt(ParamStr(0), '.ini'); end; procedure TFmSimpleReplace.FormShow(Sender: TObject); var Index: Integer; ItemNames: TStringList; RecentString: string; begin with TIniFile.Create(FIniFileName) do try ItemNames := TStringList.Create; try ReadSection('Recent Search Text', ItemNames); for Index := 0 to ItemNames.Count - 1 do begin RecentString := ReadString('Recent Search Text', ItemNames[Index], ''); if RecentString <> '' then CmbSearchText.Items.Add(RecentString); end; ReadSection('Recent Replace Text', ItemNames); for Index := 0 to ItemNames.Count - 1 do begin RecentString := ReadString('Recent Replace Text', ItemNames[Index], ''); if RecentString <> '' then CmbReplaceText.Items.Add(RecentString); end; ReadSection('Recent Folders', ItemNames); for Index := 0 to ItemNames.Count - 1 do begin RecentString := ReadString('Recent Folders', ItemNames[Index], ''); if RecentString <> '' then CmbFolder.Items.Add(RecentString); end; ReadSection('Recent File Type', ItemNames); if ItemNames.Count > 0 then CmbFileType.Items.Clear; for Index := 0 to ItemNames.Count - 1 do begin RecentString := ReadString('Recent File Type', ItemNames[Index], ''); if RecentString <> '' then CmbFileType.Items.Add(RecentString); end; finally FreeAndNil(ItemNames); end; CmbSearchText.Text := ReadString('Recent', 'Search Text', CmbSearchText.Text); CmbReplaceText.Text := ReadString('Recent', 'Replace Text', CmbReplaceText.Text); CmbFolder.Text := ReadString('Recent', 'Folder', CmbFolder.Text); CmbFileType.Text := ReadString('Recent', 'File Type', CmbFileType.Text); CbxReplaceText.Checked := ReadBool('Settings', 'Replace Text', CbxReplaceText.Checked); CbxCaseInsensitivity.Checked := ReadBool('Settings', 'Case Insensitivity', CbxCaseInsensitivity.Checked); CbxConfirmation.Checked := ReadBool('Settings', 'Confirmation', CbxConfirmation.Checked); CbxSubfolders.Checked := ReadBool('Settings', 'Subfolders', CbxSubfolders.Checked); finally Free; end; CheckGoPossible; end; procedure TFmSimpleReplace.FormClose(Sender: TObject; var Action: TCloseAction); var Index: Integer; begin with TIniFile.Create(FIniFileName) do try EraseSection('Recent Search Text'); for Index := 1 to CmbSearchText.Items.Count do begin WriteString('Recent Search Text', 'Item #' + IntToStr(Index), CmbSearchText.Items[Index]); end; EraseSection('Recent Replace Text'); for Index := 1 to CmbReplaceText.Items.Count do begin WriteString('Recent Replace Text', 'Item #' + IntToStr(Index), CmbReplaceText.Items[Index]); end; EraseSection('Recent Folders'); for Index := 1 to CmbFolder.Items.Count do begin WriteString('Recent Folders', 'Item #' + IntToStr(Index), CmbFolder.Items[Index]); end; EraseSection('Recent File Type'); for Index := 1 to CmbFileType.Items.Count do begin WriteString('Recent File Type', 'Item #' + IntToStr(Index), CmbFileType.Items[Index]); end; WriteString('Recent', 'Search Text', CmbSearchText.Text); WriteString('Recent', 'Replace Text', CmbReplaceText.Text); WriteString('Recent', 'Folder', CmbFolder.Text); WriteString('Recent', 'File Type', CmbFileType.Text); WriteBool('Settings', 'Replace Text', CbxReplaceText.Checked); WriteBool('Settings', 'Case Insensitivity', CbxCaseInsensitivity.Checked); WriteBool('Settings', 'Confirmation', CbxConfirmation.Checked); WriteBool('Settings', 'Subfolders', CbxSubfolders.Checked); finally Free; end; end; procedure TFmSimpleReplace.ProcessFile(FileName: TFileName); var Current : TStringList; SearchText : string; CompareString: string; LineIndex : Integer; ReplaceFlags : TReplaceFlags; Node : TTreeNode; begin if CbxCaseInsensitivity.Checked then SearchText := CmbSearchText.Text else SearchText := LowerCase(CmbSearchText.Text); ReplaceFlags := [rfReplaceAll]; if not CbxCaseInsensitivity.Checked then ReplaceFlags := ReplaceFlags + [rfIgnoreCase]; Node := nil; with TStringList.Create do try LoadFromFile(FileName); for LineIndex := 0 to Count - 1 do begin if CbxCaseInsensitivity.Checked then CompareString := Strings[LineIndex] else CompareString := LowerCase(Strings[LineIndex]); if Pos(SearchText, CompareString) > 0 then begin if Node = nil then begin Node := TvwResults.Items.AddChild(nil, FileName); Node.ImageIndex := 0; Node.SelectedIndex := 0; end; if CbxReplaceText.Checked then begin Strings[LineIndex] := StringReplace(Strings[LineIndex], SearchText, CmbReplaceText.Text, ReplaceFlags); end; with TvwResults.Items.AddChild(Node, ' ' + IntToStr(LineIndex) + ': ' + Strings[LineIndex]) do begin ImageIndex := 1; SelectedIndex := 1; Inc(FGlobalLineCount); end; if CbxConfirmation.Checked then Node.Expand(True); (* if CbxConfirmation.Checked then case MessageDlg('Replace current text', mtConfirmation, [mbYes, mbNo, mbCancel], 0) of mrYes : Strings[LineIndex] := CompareString; mrCancel: Exit; end else Strings[LineIndex] := CompareString; *) end; end; if CbxReplaceText.Checked and Assigned(Node) then SaveToFile(FileName); finally Free; end; end; procedure TFmSimpleReplace.TvwResultsAdvancedCustomDrawItem (Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); begin with Sender.Canvas do if Node.Level = 0 then Font.Style := Font.Style + [FsBold] else Font.Style := Font.Style - [FsBold]; end; procedure TFmSimpleReplace.UpdateComboBoxes; begin if CmbSearchText.Items.IndexOf(CmbSearchText.Text) < 0 then begin CmbSearchText.Items.Insert(0, CmbSearchText.Text); if CmbSearchText.Items.Count > 9 then CmbSearchText.Items.Delete(9); end; if CmbReplaceText.Items.IndexOf(CmbReplaceText.Text) < 0 then begin CmbReplaceText.Items.Insert(0, CmbReplaceText.Text); if CmbReplaceText.Items.Count > 9 then CmbReplaceText.Items.Delete(9); end; if CmbFolder.Items.IndexOf(CmbFolder.Text) < 0 then begin CmbFolder.Items.Insert(0, CmbFolder.Text); if CmbFolder.Items.Count > 9 then CmbFolder.Items.Delete(9); end; if CmbFileType.Items.IndexOf(CmbFileType.Text) < 0 then begin CmbFileType.Items.Insert(0, CmbFileType.Text); if CmbFileType.Items.Count > 9 then CmbFileType.Items.Delete(9); end; end; procedure TFmSimpleReplace.BtGoClick(Sender: TObject); var FilesList: TStringList; FileIndex: Integer; begin TvwResults.Items.Clear; ProgressBar.Position := 0; FGlobalLineCount := 0; UpdateComboBoxes; FilesList := TStringList.Create; try FindFiles(FilesList, CmbFolder.Text, CmbFileType.Text); ProgressBar.Max := FilesList.Count; for FileIndex := 0 to FilesList.Count - 1 do begin ProcessFile(FilesList[FileIndex]); ProgressBar.StepIt; end; finally FreeAndNil(FilesList); end; StatusBar.Panels[0].Text := 'Line Count: ' + IntToStr(FGlobalLineCount); end; procedure TFmSimpleReplace.BtSelectDirectoryClick(Sender: TObject); var ChosenDirectory: string; begin // Ask the user to select a required directory, starting with C: if SelectDirectory('Select a directory', 'C:\', ChosenDirectory) then CmbFolder.Text := ChosenDirectory; end; procedure TFmSimpleReplace.CmbFolderChange(Sender: TObject); begin CheckGoPossible; end; procedure TFmSimpleReplace.CmbReplaceTextKeyPress(Sender: TObject; var Key: Char); begin case Key of #13 : begin if BtGo.Enabled then BtGo.Click; end; end; end; procedure TFmSimpleReplace.CmbSearchTextChange(Sender: TObject); begin CheckGoPossible; end; procedure TFmSimpleReplace.CmbSearchTextKeyPress(Sender: TObject; var Key: Char); begin case Key of #13 : begin CmbReplaceText.Text := CmbSearchText.Text; CmbReplaceText.SetFocus; if CmbSearchText.Items.IndexOf(CmbSearchText.Text) < 0 then begin CmbSearchText.Items.Insert(0, CmbSearchText.Text); if CmbSearchText.Items.Count > 9 then CmbSearchText.Items.Delete(9); end; end; end; end; procedure TFmSimpleReplace.CheckGoPossible; begin BtGo.Enabled := (CmbSearchText.Text <> '') and SysUtils.DirectoryExists(CmbFolder.Text); end; end.
unit model.Cliente; interface uses UConstantes, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants; type TCliente = class(TObject) private aID : TGUID; aCodigo : Currency; aTipo : TTipoCliente; aNome , aCpfCnpj , aContato , aTelefone , aCelular , aEmail , aEndereco , aObservacao : String; aAtivo , aSincronizado : Boolean; aReferencia : TGUID; aDataUltimaCompra : TDateTime; aValorUltimaCompra : Currency; procedure SetTelefone(Value : String); procedure SetEmail(Value : String); procedure SetNome(Value : String); public constructor Create; overload; property ID : TGUID read aID write aID; property Codigo : Currency read aCodigo write aCodigo; property Tipo : TTipoCliente read aTipo write aTipo; property Nome : String read aNome write SetNome; property CpfCnpj : String read aCpfCnpj write aCpfCnpj; property Contato : String read aContato write aContato; property Telefone : String read aTelefone write SetTelefone; property Celular : String read aCelular write aCelular; property Email : String read aEmail write SetEmail; property Endereco : String read aEndereco write aEndereco; property Observacao : String read aObservacao write aObservacao; property Ativo : Boolean read aAtivo write aAtivo; property Sincronizado : Boolean read aSincronizado write aSincronizado; property Referencia : TGUID read aReferencia write aReferencia; property DataUltimaCompra : TDateTime read aDataUltimaCompra write aDataUltimaCompra; property ValorUltimaCompra : Currency read aValorUltimaCompra write aValorUltimaCompra; procedure NewID; function ToString : String; override; end; TClientes = Array of TCliente; implementation { TCliente } constructor TCliente.Create; begin inherited Create; aId := GUID_NULL; aCodigo := 0; aTipo := tcPessoaFisica; aNome := EmptyStr; aContato := EmptyStr; aCpfCnpj := EmptyStr; aAtivo := True; aSincronizado := False; aEmail := EmptyStr; aEndereco := EmptyStr; aObservacao := EmptyStr; aReferencia := GUID_NULL; aDataUltimaCompra := StrToDate(EMPTY_DATE); aValorUltimaCompra := 0.0; end; procedure TCliente.NewID; var aGuid : TGUID; begin CreateGUID(aGuid); aId := aGuid; end; procedure TCliente.SetEmail(Value: String); begin aEmail := AnsiLowerCase(Trim(Value)); end; procedure TCliente.SetNome(Value: String); begin aNome := Value.Trim.ToUpper; end; procedure TCliente.SetTelefone(Value: String); begin aTelefone := Trim(Value); end; function TCliente.ToString: String; begin Result := 'Cliente #' + FormatFloat('##000', aCodigo); end; end.
unit UPostKey; interface uses Windows // SendMessage ,Messages // WM_COMMAND ,Classes // TShiftstate ; type TShiftKeyInfo = record shift: Byte; vkey: Byte; end; byteset = set of 0..7; const shiftkeys: array [1..3] of TShiftKeyInfo = ((shift: Ord(ssCtrl); vkey: VK_CONTROL), (shift: Ord(ssShift); vkey: VK_SHIFT), (shift: Ord(ssAlt); vkey: VK_MENU)); procedure PostKeyExHWND(hWindow: HWnd; key: Word; const shift: TShiftState; specialkey: Boolean); implementation procedure PostKeyExHWND(hWindow: HWnd; key: Word; const shift: TShiftState; specialkey: Boolean); {************************************************************ * Procedure PostKeyEx * * Parameters: * hWindow: target window to be send the keystroke * key : virtual keycode of the key to send. For printable * keys this is simply the ANSI code (Ord(character)). * shift : state of the modifier keys. This is a set, so you * can set several of these keys (shift, control, alt, * mouse buttons) in tandem. The TShiftState type is * declared in the Classes Unit. * specialkey: normally this should be False. Set it to True to * specify a key on the numeric keypad, for example. * If this parameter is true, bit 24 of the lparam for * the posted WM_KEY* messages will be set. * Description: * This procedure sets up Windows key state array to correctly * reflect the requested pattern of modifier keys and then posts * a WM_KEYDOWN/WM_KEYUP message pair to the target window. Then * Application.ProcessMessages is called to process the messages * before the keyboard state is restored. * Error Conditions: * May fail due to lack of memory for the two key state buffers. * Will raise an exception in this case. * NOTE: * Setting the keyboard state will not work across applications * running in different memory spaces on Win32 unless AttachThreadInput * is used to connect to the target thread first. *Created: 02/21/96 16:39:00 by P. Below ************************************************************} type TBuffers = array [0..1] of TKeyboardState; var pKeyBuffers: ^TBuffers; lParam: LongInt; begin (* check if the target window exists *) if IsWindow(hWindow) then begin (* set local variables to default values *) pKeyBuffers := nil; lParam := MakeLong(0, MapVirtualKey(key, 0)); (* modify lparam if special key requested *) if specialkey then lParam := lParam or $1000000; (* allocate space for the key state buffers *) New(pKeyBuffers); try (* Fill buffer 1 with current state so we can later restore it. Null out buffer 0 to get a "no key pressed" state. *) GetKeyboardState(pKeyBuffers^[1]); FillChar(pKeyBuffers^[0], SizeOf(TKeyboardState), 0); (* set the requested modifier keys to "down" state in the buffer*) if ssShift in shift then pKeyBuffers^[0][VK_SHIFT] := $80; if ssAlt in shift then begin (* Alt needs special treatment since a bit in lparam needs also be set *) pKeyBuffers^[0][VK_MENU] := $80; lParam := lParam or $20000000; end; if ssCtrl in shift then pKeyBuffers^[0][VK_CONTROL] := $80; if ssLeft in shift then pKeyBuffers^[0][VK_LBUTTON] := $80; if ssRight in shift then pKeyBuffers^[0][VK_RBUTTON] := $80; if ssMiddle in shift then pKeyBuffers^[0][VK_MBUTTON] := $80; (* make out new key state array the active key state map *) SetKeyboardState(pKeyBuffers^[0]); (* post the key messages *) if ssAlt in Shift then begin PostMessage(hWindow, WM_SYSKEYDOWN, key, lParam); PostMessage(hWindow, WM_SYSKEYUP, key, lParam or $C0000000); end else begin PostMessage(hWindow, WM_KEYDOWN, key, lParam); PostMessage(hWindow, WM_KEYUP, key, lParam or $C0000000); end; (* process the messages *) // Application.ProcessMessages; (* restore the old key state map *) SetKeyboardState(pKeyBuffers^[1]); finally (* free the memory for the key state buffers *) if pKeyBuffers <> nil then Dispose(pKeyBuffers); end; { If } end; end; { PostKeyEx } end.
unit Core.BowlingGame; interface uses System.SysUtils , System.Classes , System.Rtti {Spring} , Spring , Spring.Collections , Spring.DesignPatterns {BowlingGame} , Core.BaseInterfaces , Core.Interfaces , Core.ScoreCard ; type TGameConfig = Class(TInterfacedObject, IGameConfig) strict private FMaxFrameCount: Integer; FNonLastFrameMaxRollCount: Integer; FLastFrameMaxRollCount: Integer; FMaxPinCountPerRoll: Integer; function GetMaxFrameCount: Integer; function GetLastFrameMaxRollCount: Integer; function GetNonLastFrameMaxRollCount: Integer; function GetMaxPinCountPerRoll: Integer; public constructor Create(const AMaxCount, ANonLastFrameMaxRollCount, ALastFrameMaxRollCount, AMaxPinCountPerRoll: Integer); property MaxFrameCount: Integer read GetMaxFrameCount; property NonLastFrameMaxRollCount: Integer read GetNonLastFrameMaxRollCount; property LastFrameMaxRollCount: Integer read GetLastFrameMaxRollCount; property MaxPinCountPerRoll: Integer read GetMaxPinCountPerRoll; end; TBowlingGame = Class(TInterfacedObject, IBowlingGame) strict private FScoreCard: IScoreCard; public Constructor Create; Destructor Destroy; override; procedure StartGame(const APlayerName: String); procedure RollBall(const APins: Integer); function GetScoreByFrame(const AFrameNo: Integer): TFrameInfo; function GetTotalScore: Integer; procedure RegisterObserver(AObserver: IGameObserver); procedure UnregisterObserver(AObserver: IGameObserver); end; implementation uses Spring.Services ; { TBowlingGame } constructor TBowlingGame.Create; begin inherited Create; FScoreCard := ServiceLocator.GetService< IScoreCard >; end; destructor TBowlingGame.Destroy; begin inherited; end; function TBowlingGame.GetScoreByFrame(const AFrameNo: Integer): TFrameInfo; begin Result := FScoreCard.GetFrameInfoByFrameNo( AFrameNo ) end; function TBowlingGame.GetTotalScore: Integer; begin Result := FScoreCard.GetTotalScore; end; procedure TBowlingGame.RegisterObserver(AObserver: IGameObserver); begin FScoreCard.RegisterObserver( AObserver ); end; procedure TBowlingGame.UnregisterObserver(AObserver: IGameObserver); begin FScoreCard.UnregisterObserver( AObserver ); end; procedure TBowlingGame.StartGame(const APlayerName: String); begin FScoreCard.ResetScoreCard( APlayerName ); end; procedure TBowlingGame.RollBall(const APins: Integer); begin FScoreCard.RollBall( APins ); end; { TGameConfig } constructor TGameConfig.Create(const AMaxCount, ANonLastFrameMaxRollCount, ALastFrameMaxRollCount, AMaxPinCountPerRoll: Integer); begin inherited Create; FMaxFrameCount := AMaxCount; FNonLastFrameMaxRollCount := ANonLastFrameMaxRollCount; FLastFrameMaxRollCount := ALastFrameMaxRollCount; FMaxPinCountPerRoll := AMaxPinCountPerRoll; end; function TGameConfig.GetMaxFrameCount: Integer; begin Result := FMaxFrameCount; end; function TGameConfig.GetMaxPinCountPerRoll: Integer; begin Result := FMaxPinCountPerRoll; end; function TGameConfig.GetLastFrameMaxRollCount: Integer; begin Result := FLastFrameMaxRollCount; end; function TGameConfig.GetNonLastFrameMaxRollCount: Integer; begin Result := FNonLastFrameMaxRollCount; end; end.
program forLoop; var a: integer; begin (* For loop example: Write out every integer in a certain range *) for a := 1 to 5 do begin writeln(a); end; end.
unit teste.helper.db; interface uses SysUtils, Classes, db; type TFieldHelper = class helper for TField public function AsDataInvertidaCorrigida: TDateTime; function AsStringSoNumeros(RemoverZerosEsquerda: Boolean = True): String; function AsStringSemAcentos: String; function AsInteiro(Defaul: Integer = 0): Integer; end; implementation function SoNumeros(Text: string): string; var i: Integer; begin result := ''; if Text = '' then exit; for i := 0 to length(Text) do begin if Text[i] in ['0' .. '9'] then result := result + Text[i]; end; end; function doRemoverZerosEsquerda(const Value: String): String; var aux: String; i: Integer; begin aux := Trim(Value); for i := 0 to length(aux) do begin if (length(aux) >= 1) then if aux[1] <> '0' then Break; aux := Copy(aux, 2, length(aux)); end; result := aux; end; function RemoverAcentos(const Value: String): String; const ComAcento = 'àèìòùâêîôûãõáéíóúäëïöüçÀÂÊÔÛÃÕÁÉÍÓÚÇÜ'; SemAcento = 'aeiouaeiouaoaeiouaeioucAAEOUAOAEIOUCU'; var strAux: String; i, j: Integer; begin; j := 0; strAux := Trim(Value); for i := 1 to length(strAux) do begin j := Pos(strAux[i], ComAcento); if j <> 0 then strAux[i] := SemAcento[j]; end; result := strAux; end; { TFieldHelper } function TFieldHelper.AsDataInvertidaCorrigida: TDateTime; var DataInvertida: String; begin DataInvertida := AsString; result := StrToDateDef(Copy(DataInvertida, 9, 2) + '/' + Copy(DataInvertida, 6, 2) + '/' + Copy(DataInvertida, 1, 4), StrToDate('01/01/1900')); end; function TFieldHelper.AsStringSemAcentos: String; begin result := RemoverAcentos(AsString); end; function TFieldHelper.AsStringSoNumeros(RemoverZerosEsquerda: Boolean): String; var strAux: String; begin strAux := Trim(AsString); strAux := SoNumeros(strAux); if RemoverZerosEsquerda then strAux := doRemoverZerosEsquerda(strAux); result := strAux; end; function TFieldHelper.AsInteiro(Defaul: Integer): Integer; begin result := StrToIntDef(AsString, Defaul); end; end.
program lista1ex2; (* Exercício 2 da Lista 1 de ALgorítmos. Autor: Henrique Colodetti Escanferla *) var C, F: real; (* Para que o algoritmo aceite qualquer valor específico com varias casas decimais foi utilizado variáveis reais. C => Temperatura em Celsius, F => Temperatura em Farenheit. *) begin (* Começo do processo de conversão Celsius-Farenheit. *) writeln('Este algoritmo fornecerá uma temperatura em Farenheit a partir de um valor em Celsius.'); (* Apresentação do algoritmo e sua função. *) write('Digite o valor da temperatura em Celsius: '); (* Aqui é fornecido a temperatura em Celsius. *) readln(C); (* Leitura da variável Celsius. *) F := 9*C/5+ 32; (* Fórmula inversa da fornecida que convertia Farenheit para Celsius. Foi isolado o F e obtida a fórmula usada aqui. *) writeln('O valor correspondente à temperatura em Celsius fornecida é de: ',F:4:2,' F°'); (* Fornecimento do resultado para o usuário *) end. (* Fim do algoritmo *)
unit DUS.Main.Data; interface uses System.SysUtils, System.Classes, Data.FMTBcd, Data.DB, Data.SqlExpr, Datasnap.DBClient, SimpleDS, Datasnap.Provider, Data.DbxSqlite; type TDUSMainData = class(TDataModule) SQLConnection1: TSQLConnection; private procedure CreateTables; public procedure Open; end; var DUSMainData: TDUSMainData; implementation { %CLASSGROUP 'Vcl.Controls.TControl' } {$R *.dfm} { TDUSMainData } procedure TDUSMainData.CreateTables; var dts: TSQLQuery; begin dts := TSQLQuery.Create(nil); try dts.SQLConnection := SQLConnection1; dts.SQL.Clear; dts.SQL.Add('CREATE TABLE IF NOT EXISTS test( '); dts.SQL.Add('id INTEGER PRIMARY KEY, '); dts.SQL.Add('title VARCHAR(200), '); dts.SQL.Add(' content MEDIUMTEXT, '); dts.SQL.Add(' count DECIMAL(10,2), '); dts.SQL.Add(' up_date DATETIME );'); dts.ExecSQL(); dts.SQL.Clear; dts.SQL.Add('INSERT OR REPLACE INTO test VALUES (1, ''test'', ''test'', 10.2, ''2016-01-01'') '); dts.ExecSQL(); finally dts.Free; end; end; procedure TDUSMainData.Open; var dbFile: string; begin dbFile := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.db'; SQLConnection1.Params.Values['Database'] := dbFile; if not FileExists(dbFile) then begin SQLConnection1.Params.Values['FailIfMissing'] := 'False'; end; SQLConnection1.Open; CreateTables; end; end.
unit ufrmDialogMaintenancePassword; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, StdCtrls, System.Actions, Vcl.ActnList, ufraFooterDialog3Button; type TFormMode = (fmAdd, fmEdit); TfrmDialogMaintenancePassword = class(TfrmMasterDialog) lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; edtUserName: TEdit; edtFullname: TEdit; cbbLevel: TComboBox; edtPasswd: TEdit; chkStatus: TCheckBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure footerDialogMasterbtnSaveClick(Sender: TObject); procedure edtUserNameKeyPress(Sender: TObject; var Key: Char); procedure btnDeleteClick(Sender: TObject); private FIsProcessSuccessfull: boolean; FFormMode: TFormMode; procedure SetFormMode(const Value: TFormMode); procedure SetIsProcessSuccessfull(const Value: boolean); { Private declarations } public { Public declarations } User_ID: Integer; published property FormMode: TFormMode read FFormMode write SetFormMode; property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull; end; var frmDialogMaintenancePassword: TfrmDialogMaintenancePassword; implementation uses uTSCommonDlg; {$R *.dfm} procedure TfrmDialogMaintenancePassword.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmDialogMaintenancePassword.FormDestroy(Sender: TObject); begin inherited; frmDialogMaintenancePassword := nil; end; procedure TfrmDialogMaintenancePassword.SetFormMode( const Value: TFormMode); begin FFormMode := Value; end; procedure TfrmDialogMaintenancePassword.SetIsProcessSuccessfull( const Value: boolean); begin FIsProcessSuccessfull := Value; end; procedure TfrmDialogMaintenancePassword.footerDialogMasterbtnSaveClick( Sender: TObject); var intStatus: SmallInt; levelID: Integer; begin inherited; IsProcessSuccessfull := False; if edtUserName.Text = '' then begin CommonDlg.ShowErrorEmpty('Cashier ID'); edtUserName.SetFocus; Exit; end else begin if chkStatus.Checked then intStatus := 1 else intStatus := 0; {levelID mengacu pada table aut$grup idgrup supervisorPos & operatorPos } If cbbLevel.ItemIndex = 0 then levelID := 10 else levelID := 11; { if not Assigned(MaintenancePasswd) then MaintenancePasswd := TMaintenancePasswd.Create; if FormMode = fmAdd then begin IsProcessSuccessfull := MaintenancePasswd.InputDataMaintenancePasswd(edtUserName.Text, edtFullname.Text, edtPasswd.Text, intStatus, levelID); end // end fmadd else begin IsProcessSuccessfull := MaintenancePasswd.UpdateDataMaintenancePasswd(edtUserName.Text, edtFullname.Text, edtPasswd.Text, intStatus, User_ID); end; //end fmedit } end; //end = '' Close; end; procedure TfrmDialogMaintenancePassword.btnDeleteClick(Sender: TObject); var delStatue: Boolean; begin inherited; {if strgGrid.Cells[5,strgGrid.Row] = '0' then Exit; if (CommonDlg.Confirm('Are you sure you wish to delete Cashier (Cashier Id: '+ strgGrid.Cells[1,strgGrid.Row] +')?') = mrYes) then begin if not Assigned(MaintenancePasswd) then MaintenancePasswd := TMaintenancePasswd.Create; delStatue := MaintenancePasswd.DeleteDataMaintenancePasswd(StrToInt(strgGrid.Cells[6,strgGrid.Row]), masternewunit.id); if delStatue then begin actRefreshMaintenancePasswdExecute(Self); CommonDlg.ShowConfirmSuccessfull(atDelete); end; end; } end; procedure TfrmDialogMaintenancePassword.edtUserNameKeyPress( Sender: TObject; var Key: Char); begin //if not (Key in ['0'..'9', Chr(VK_RETURN), Chr(VK_DELETE), Chr(VK_BACK)]) then //Key := #0; end; end.
program catacomb_music; Uses SPKlib; Const dupa = 'cycki'; Type soundtype = (nosnd,blockedsnd,itemsnd,treasuresnd,bigshotsnd,shotsnd, tagwallsnd,tagmonsnd,tagplayersnd,killmonsnd,killplayersnd,opendoorsnd, potionsnd,spellsnd,noitemsnd,gameoversnd,highscoresnd,leveldonesnd, foundsnd); Procedure Paralign; Var state: record case boolean of true: (p: pointer); false: (offset,segment:word); End; Begin mark (state.p); If state.offset>0 then Begin state.offset:=0; inc(state.segment); release (state.p); end; end; Procedure PlaySound (soundnum: soundtype); Begin PlaySound1 (integer(soundnum)); End; function Bload (filename: string): pointer; var iofile: file; len: longint; allocleft,recs: word; into,second: pointer; begin Assign (iofile,filename); Reset (iofile,1); If ioresult<>0 then Begin writeln ('File not found: ',filename); halt; End; len:=filesize(iofile); paralign; if len>$fff0 then {do this crap because getmem can only give $FFF0} begin getmem (into,$fff0); BlockRead (iofile,into^,$FFF0,recs); allocleft:=len-$fff0; while allocleft > $fff0 do begin getmem (second,$fff0); BlockRead (iofile,second^,$FFF0,recs); allocleft:=allocleft-$fff0; end; getmem (second,allocleft); BlockRead (iofile,second^,$FFF0,recs); end else begin getmem (into,len); BlockRead (iofile,into^,len,recs); end; Close (iofile); bload:=into; end; Procedure LoadSounds; Begin SoundData:=Bload ('SOUNDS.CAT'); End; Begin writeln(dupa); LoadSounds; StartupSound; playsound (nosnd); waitendsound; playsound (blockedsnd); waitendsound; playsound (itemsnd); waitendsound; playsound (treasuresnd); waitendsound; playsound (bigshotsnd); waitendsound; playsound (shotsnd); waitendsound; playsound (tagwallsnd); waitendsound; playsound (tagmonsnd); waitendsound; playsound (tagplayersnd); waitendsound; playsound (killmonsnd); waitendsound; playsound (killplayersnd); waitendsound; playsound (opendoorsnd); waitendsound; playsound (potionsnd); waitendsound; playsound (spellsnd); waitendsound; playsound (noitemsnd); waitendsound; playsound (gameoversnd); waitendsound; playsound (highscoresnd); waitendsound; playsound (leveldonesnd); waitendsound; playsound (foundsnd); waitendsound; playsound (highscoresnd); waitendsound; playsound (highscoresnd); waitendsound; playsound (highscoresnd); waitendsound; playsound (highscoresnd); waitendsound; ShutdownSound; End.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.SignedDistanceField2D; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses SysUtils, Classes, Math, PUCU, PasMP, Vulkan, PasVulkan.Types, PasVulkan.Math, PasVulkan.Collections, PasVulkan.Framework, PasVulkan.VectorPath; type TpvSignedDistanceField2DVariant= ( SDF=0, // Mono SDF SSAASDF=1, // Supersampling Antialiased SDF GSDF=2, // Gradient SDF MSDF=3, // Multi Channel SDF Default=1 // SSAASDF as default ); PpvSignedDistanceField2DVariant=^TpvSignedDistanceField2DVariant; TpvSignedDistanceField2DPixel=packed record r,g,b,a:TpvUInt8; end; PpvSignedDistanceField2DPixel=^TpvSignedDistanceField2DPixel; TpvSignedDistanceField2DPixels=array of TpvSignedDistanceField2DPixel; TpvSignedDistanceField2D=record Width:TpvInt32; Height:TpvInt32; Pixels:TpvSignedDistanceField2DPixels; end; PpvSignedDistanceField2D=^TpvSignedDistanceField2D; TpvSignedDistanceField2DArray=array of TpvSignedDistanceField2D; TpvSignedDistanceField2DPathSegmentSide= ( Left=-1, On=0, Right=1, None=2 ); PpvSignedDistanceField2DPathSegmentSide=^TpvSignedDistanceField2DPathSegmentSide; TpvSignedDistanceField2DDataItem=record SquaredDistance:TpvFloat; Distance:TpvFloat; DeltaWindingScore:TpvInt32; end; PpvSignedDistanceField2DDataItem=^TpvSignedDistanceField2DDataItem; TpvSignedDistanceField2DData=array of TpvSignedDistanceField2DDataItem; TpvSignedDistanceField2DDoublePrecisionAffineMatrix=array[0..5] of TpvDouble; PpvSignedDistanceField2DDoublePrecisionAffineMatrix=^TpvSignedDistanceField2DDoublePrecisionAffineMatrix; TpvSignedDistanceField2DPathSegmentType= ( Line, QuadraticBezierCurve ); PpvSignedDistanceField2DPathSegmentType=^TpvSignedDistanceField2DPathSegmentType; TpvSignedDistanceField2DBoundingBox=record Min:TpvVectorPathVector; Max:TpvVectorPathVector; end; PpvSignedDistanceField2DBoundingBox=^TpvSignedDistanceField2DBoundingBox; TpvSignedDistanceField2DPathSegmentPoints=array[0..2] of TpvVectorPathVector; PpvSignedDistanceField2DPathSegmentPoints=^TpvSignedDistanceField2DPathSegmentPoints; TpvSignedDistanceField2DPathSegment=record Type_:TpvSignedDistanceField2DPathSegmentType; Points:TpvSignedDistanceField2DPathSegmentPoints; P0T,P2T:TpvVectorPathVector; XFormMatrix:TpvSignedDistanceField2DDoublePrecisionAffineMatrix; ScalingFactor:TpvDouble; SquaredScalingFactor:TpvDouble; NearlyZeroScaled:TpvDouble; SquaredTangentToleranceScaled:TpvDouble; BoundingBox:TpvSignedDistanceField2DBoundingBox; end; PpvSignedDistanceField2DPathSegment=^TpvSignedDistanceField2DPathSegment; TpvSignedDistanceField2DPathSegments=array of TpvSignedDistanceField2DPathSegment; PpvSignedDistanceField2DPathContour=^TpvSignedDistanceField2DPathContour; TpvSignedDistanceField2DPathContour=record PathSegments:TpvSignedDistanceField2DPathSegments; CountPathSegments:TpvInt32; end; TpvSignedDistanceField2DPathContours=array of TpvSignedDistanceField2DPathContour; TpvSignedDistanceField2DShape=record Contours:TpvSignedDistanceField2DPathContours; CountContours:TpvInt32; end; PpvSignedDistanceField2DShape=^TpvSignedDistanceField2DShape; TpvSignedDistanceField2DRowDataIntersectionType= ( NoIntersection, VerticalLine, TangentLine, TwoPointsIntersect ); PpvSignedDistanceField2DRowDataIntersectionType=^TpvSignedDistanceField2DRowDataIntersectionType; TpvSignedDistanceField2DRowData=record IntersectionType:TpvSignedDistanceField2DRowDataIntersectionType; QuadraticXDirection:TpvInt32; ScanlineXDirection:TpvInt32; YAtIntersection:TpvFloat; XAtIntersection:array[0..1] of TpvFloat; end; PpvSignedDistanceField2DRowData=^TpvSignedDistanceField2DRowData; TpvSignedDistanceField2DPointInPolygonPathSegment=record Points:array[0..1] of TpvVectorPathVector; end; PpvSignedDistanceField2DPointInPolygonPathSegment=^TpvSignedDistanceField2DPointInPolygonPathSegment; TpvSignedDistanceField2DPointInPolygonPathSegments=array of TpvSignedDistanceField2DPointInPolygonPathSegment; EpvSignedDistanceField2DMSDFGenerator=class(Exception); { TpvSignedDistanceField2DMSDFGenerator } TpvSignedDistanceField2DMSDFGenerator=class public const PositiveInfinityDistance=1e240; NegativeInfinityDistance=-1e240; type { TSignedDistance } TSignedDistance=record public Distance:TpvDouble; Dot:TpvDouble; constructor Create(const aDistance,aDot:TpvDouble); class function Empty:TSignedDistance; static; class operator Equal(const a,b:TSignedDistance):boolean; class operator NotEqual(const a,b:TSignedDistance):boolean; class operator LessThan(const a,b:TSignedDistance):boolean; class operator LessThanOrEqual(const a,b:TSignedDistance):boolean; class operator GreaterThan(const a,b:TSignedDistance):boolean; class operator GreaterThanOrEqual(const a,b:TSignedDistance):boolean; end; { TMultiSignedDistance } TMultiSignedDistance=record public r:TpvDouble; g:TpvDouble; b:TpvDouble; Median:TpvDouble; end; { TBounds } TBounds=record public l:TpvDouble; b:TpvDouble; r:TpvDouble; t:TpvDouble; procedure PointBounds(const p:TpvVectorPathVector); end; TEdgeColor= ( BLACK=0, RED=1, GREEN=2, YELLOW=3, BLUE=4, MAGENTA=5, CYAN=6, WHITE=7 ); TEdgeType= ( LINEAR=0, QUADRATIC=1, CUBIC=2 ); const TOO_LARGE_RATIO=1e12; MSDFGEN_CUBIC_SEARCH_STARTS=8; MSDFGEN_CUBIC_SEARCH_STEPS=8; type { TEdgeSegment } TEdgeSegment=record public Points:array[0..3] of TpvVectorPathVector; Color:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor; Type_:TpvSignedDistanceField2DMSDFGenerator.TEdgeType; constructor Create(const aP0,aP1:TpvVectorPathVector;const aColor:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.WHITE); overload; constructor Create(const aP0,aP1,aP2:TpvVectorPathVector;const aColor:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.WHITE); overload; constructor Create(const aP0,aP1,aP2,aP3:TpvVectorPathVector;const aColor:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.WHITE); overload; function Point(const aParam:TpvDouble):TpvVectorPathVector; function Direction(const aParam:TpvDouble):TpvVectorPathVector; function MinSignedDistance(const aOrigin:TpvVectorPathVector;var aParam:TpvDouble):TpvSignedDistanceField2DMSDFGenerator.TSignedDistance; procedure DistanceToPseudoDistance(var aDistance:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance;const aOrigin:TpvVectorPathVector;const aParam:TpvDouble); procedure Bounds(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds); procedure SplitInThirds(out aPart1,aPart2,aPart3:TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment); end; PEdgeSegment=^TEdgeSegment; TEdgeSegments=array of TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment; { TContour } TContour=record public Edges:TpvSignedDistanceField2DMSDFGenerator.TEdgeSegments; Count:TpvSizeInt; CachedWinding:TpvSizeInt; MultiSignedDistance:TMultiSignedDistance; class function Create:TContour; static; function AddEdge({$ifdef fpc}constref{$else}const{$endif} aEdge:TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment):TpvSignedDistanceField2DMSDFGenerator.PEdgeSegment; procedure Bounds(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds); procedure BoundMiters(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds;const aBorder,aMiterLimit:TpvDouble;const aPolarity:TpvSizeInt); function Winding:TpvSizeInt; end; PContour=^TContour; TContours=array of TpvSignedDistanceField2DMSDFGenerator.TContour; { TShape } TShape=record Contours:TContours; Count:TpvSizeInt; InverseYAxis:boolean; class function Create:TShape; static; function AddContour:TpvSignedDistanceField2DMSDFGenerator.PContour; function Validate:boolean; procedure Normalize; procedure Bounds(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds); procedure BoundMiters(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds;const aBorder,aMiterLimit:TpvDouble;const aPolarity:TpvSizeInt); function GetBounds(const aBorder:TpvDouble=0.0;const aMiterLimit:TpvDouble=0;const aPolarity:TpvSizeInt=0):TpvSignedDistanceField2DMSDFGenerator.TBounds; end; PShape=^TShape; TShapes=array of TpvSignedDistanceField2DMSDFGenerator.TShape; TPixel=record r:TpvDouble; g:TpvDouble; b:TpvDouble; a:TpvDouble; end; PPixel=^TPixel; TPixels=array of TPixel; TPixelArray=array[0..65535] of TPixel; PPixelArray=^TPixelArray; TImage=record Width:TpvSizeInt; Height:TpvSizeInt; Pixels:TPixels; end; PImage=^TImage; public class function Median(a,b,c:TpvDouble):TpvDouble; static; class function Sign(n:TpvDouble):TpvInt32; static; class function NonZeroSign(n:TpvDouble):TpvInt32; static; class function SolveQuadratic(out x0,x1:TpvDouble;const a,b,c:TpvDouble):TpvSizeInt; static; class function SolveCubicNormed(out x0,x1,x2:TpvDouble;a,b,c:TpvDouble):TpvSizeInt; static; class function SolveCubic(out x0,x1,x2:TpvDouble;const a,b,c,d:TpvDouble):TpvSizeInt; static; class function Shoelace(const a,b:TpvVectorPathVector):TpvDouble; static; class procedure AutoFrame({$ifdef fpc}constref{$else}const{$endif} aShape:TpvSignedDistanceField2DMSDFGenerator.TShape;const aWidth,aHeight:TpvSizeInt;const aPixelRange:TpvDouble;out aTranslate,aScale:TpvVectorPathVector); static; class function IsCorner(const aDirection,bDirection:TpvVectorPathVector;const aCrossThreshold:TpvDouble):boolean; static; class procedure SwitchColor(var aColor:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor;var aSeed:TpvUInt64;const aBanned:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.BLACK); static; class procedure EdgeColoringSimple(var aShape:TpvSignedDistanceField2DMSDFGenerator.TShape;const aAngleThreshold:TpvDouble;aSeed:TpvUInt64); static; class procedure GenerateDistanceFieldPixel(var aImage:TpvSignedDistanceField2DMSDFGenerator.TImage;{$ifdef fpc}constref{$else}const{$endif} aShape:TpvSignedDistanceField2DMSDFGenerator.TShape;const aRange:TpvDouble;const aScale,aTranslate:TpvVectorPathVector;const aX,aY:TpvSizeInt); static; class procedure GenerateDistanceField(var aImage:TpvSignedDistanceField2DMSDFGenerator.TImage;{$ifdef fpc}constref{$else}const{$endif} aShape:TpvSignedDistanceField2DMSDFGenerator.TShape;const aRange:TpvDouble;const aScale,aTranslate:TpvVectorPathVector;const aPasMPInstance:TPasMP=nil); static; class function DetectClash({$ifdef fpc}constref{$else}const{$endif} a,b:TpvSignedDistanceField2DMSDFGenerator.TPixel;const aThreshold:TpvDouble):boolean; static; class procedure ErrorCorrection(var aImage:TpvSignedDistanceField2DMSDFGenerator.TImage;const aThreshold:TpvVectorPathVector); static; end; { TpvSignedDistanceField2DGenerator } TpvSignedDistanceField2DGenerator=class private const DistanceField2DMagnitudeValue=VulkanDistanceField2DSpreadValue; DistanceField2DPadValue=VulkanDistanceField2DSpreadValue; DistanceField2DScalar1Value=1.0; DistanceField2DCloseValue=DistanceField2DScalar1Value/16.0; DistanceField2DCloseSquaredValue=DistanceField2DCloseValue*DistanceField2DCloseValue; DistanceField2DNearlyZeroValue=DistanceField2DScalar1Value/int64(1 shl 18); DistanceField2DTangentToleranceValue=DistanceField2DScalar1Value/int64(1 shl 11); DistanceField2DRasterizerToScreenScale=1.0; CurveTessellationTolerance=0.125; CurveTessellationToleranceSquared=CurveTessellationTolerance*CurveTessellationTolerance; CurveRecursionLimit=16; type TMSDFMatches=array of TpvInt8; private fPointInPolygonPathSegments:TpvSignedDistanceField2DPointInPolygonPathSegments; fVectorPathShape:TpvVectorPathShape; fScale:TpvDouble; fOffsetX:TpvDouble; fOffsetY:TpvDouble; fDistanceField:PpvSignedDistanceField2D; fVariant:TpvSignedDistanceField2DVariant; fShape:TpvSignedDistanceField2DShape; fDistanceFieldData:TpvSignedDistanceField2DData; fColorChannelIndex:TpvSizeInt; fMSDFShape:TpvSignedDistanceField2DMSDFGenerator.PShape; fMSDFImage:TpvSignedDistanceField2DMSDFGenerator.PImage; fMSDFAmbiguous:boolean; fMSDFMatches:TMSDFMatches; protected function Clamp(const Value,MinValue,MaxValue:TpvInt64):TpvInt64; overload; function Clamp(const Value,MinValue,MaxValue:TpvDouble):TpvDouble; overload; function VectorMap(const p:TpvVectorPathVector;const m:TpvSignedDistanceField2DDoublePrecisionAffineMatrix):TpvVectorPathVector; procedure GetOffset(out oX,oY:TpvDouble); procedure ApplyOffset(var aX,aY:TpvDouble); overload; function ApplyOffset(const aPoint:TpvVectorPathVector):TpvVectorPathVector; overload; function BetweenClosedOpen(const a,b,c:TpvDouble;const Tolerance:TpvDouble=0.0;const XFormToleranceToX:boolean=false):boolean; function BetweenClosed(const a,b,c:TpvDouble;const Tolerance:TpvDouble=0.0;const XFormToleranceToX:boolean=false):boolean; function NearlyZero(const Value:TpvDouble;const Tolerance:TpvDouble=DistanceField2DNearlyZeroValue):boolean; function NearlyEqual(const x,y:TpvDouble;const Tolerance:TpvDouble=DistanceField2DNearlyZeroValue;const XFormToleranceToX:boolean=false):boolean; function SignOf(const Value:TpvDouble):TpvInt32; function IsColinear(const Points:array of TpvVectorPathVector):boolean; function PathSegmentDirection(const PathSegment:TpvSignedDistanceField2DPathSegment;const Which:TpvInt32):TpvVectorPathVector; function PathSegmentCountPoints(const PathSegment:TpvSignedDistanceField2DPathSegment):TpvInt32; function PathSegmentEndPoint(const PathSegment:TpvSignedDistanceField2DPathSegment):PpvVectorPathVector; function PathSegmentCornerPoint(const PathSegment:TpvSignedDistanceField2DPathSegment;const WhichA,WhichB:TpvInt32):PpvVectorPathVector; procedure InitializePathSegment(var PathSegment:TpvSignedDistanceField2DPathSegment); procedure InitializeDistances; function AddLineToPathSegmentArray(var Contour:TpvSignedDistanceField2DPathContour;const Points:array of TpvVectorPathVector):TpvInt32; function AddQuadraticBezierCurveToPathSegmentArray(var Contour:TpvSignedDistanceField2DPathContour;const Points:array of TpvVectorPathVector):TpvInt32; function CubeRoot(Value:TpvDouble):TpvDouble; function CalculateNearestPointForQuadraticBezierCurve(const PathSegment:TpvSignedDistanceField2DPathSegment;const XFormPoint:TpvVectorPathVector):TpvDouble; procedure PrecomputationForRow(out RowData:TpvSignedDistanceField2DRowData;const PathSegment:TpvSignedDistanceField2DPathSegment;const PointLeft,PointRight:TpvVectorPathVector); function CalculateSideOfQuadraticBezierCurve(const PathSegment:TpvSignedDistanceField2DPathSegment;const Point,XFormPoint:TpvVectorPathVector;const RowData:TpvSignedDistanceField2DRowData):TpvSignedDistanceField2DPathSegmentSide; function DistanceToPathSegment(const Point:TpvVectorPathVector;const PathSegment:TpvSignedDistanceField2DPathSegment;const RowData:TpvSignedDistanceField2DRowData;out PathSegmentSide:TpvSignedDistanceField2DPathSegmentSide):TpvDouble; procedure ConvertShape(const DoSubdivideCurvesIntoLines:boolean); function ConvertShapeToMSDFShape:TpvSignedDistanceField2DMSDFGenerator.TShape; procedure CalculateDistanceFieldDataLineRange(const FromY,ToY:TpvInt32); procedure CalculateDistanceFieldDataLineRangeParallelForJobFunction(const Job:PPasMPJob;const ThreadIndex:TPasMPInt32;const Data:TpvPointer;const FromIndex,ToIndex:TPasMPNativeInt); function PackDistanceFieldValue(Distance:TpvDouble):TpvUInt8; function PackPseudoDistanceFieldValue(Distance:TpvDouble):TpvUInt8; procedure ConvertToPointInPolygonPathSegments; function GetWindingNumberAtPointInPolygon(const Point:TpvVectorPathVector):TpvInt32; function GenerateDistanceFieldPicture(const DistanceFieldData:TpvSignedDistanceField2DData;const Width,Height,TryIteration:TpvInt32):boolean; public constructor Create; reintroduce; destructor Destroy; override; procedure Execute(var aDistanceField:TpvSignedDistanceField2D;const aVectorPathShape:TpvVectorPathShape;const aScale:TpvDouble=1.0;const aOffsetX:TpvDouble=0.0;const aOffsetY:TpvDouble=0.0;const aVariant:TpvSignedDistanceField2DVariant=TpvSignedDistanceField2DVariant.Default;const aProtectBorder:boolean=false); class procedure Generate(var aDistanceField:TpvSignedDistanceField2D;const aVectorPathShape:TpvVectorPathShape;const aScale:TpvDouble=1.0;const aOffsetX:TpvDouble=0.0;const aOffsetY:TpvDouble=0.0;const aVariant:TpvSignedDistanceField2DVariant=TpvSignedDistanceField2DVariant.Default;const aProtectBorder:boolean=false); static; end; implementation { TpvSignedDistanceField2DMSDFGenerator.TSignedDistance } constructor TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Create(const aDistance,aDot:TpvDouble); begin Distance:=aDistance; Dot:=aDot; end; class function TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Empty:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance; begin result.Distance:=TpvSignedDistanceField2DMSDFGenerator.NegativeInfinityDistance; result.Dot:=1.0; end; class operator TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Equal(const a,b:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance):boolean; begin result:=SameValue(a.Distance,b.Distance) and SameValue(a.Dot,b.Dot); end; class operator TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.NotEqual(const a,b:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance):boolean; begin result:=(not SameValue(a.Distance,b.Distance)) or (not SameValue(a.Dot,b.Dot)); end; class operator TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.LessThan(const a,b:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance):boolean; begin result:=(abs(a.Distance)<abs(b.Distance)) or (SameValue(a.Distance,b.Distance) and (a.Dot<b.Dot)); end; class operator TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.LessThanOrEqual(const a,b:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance):boolean; begin result:=(abs(a.Distance)<abs(b.Distance)) or (SameValue(a.Distance,b.Distance) and ((a.Dot<=b.Dot) or SameValue(a.Dot,b.Dot))); end; class operator TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.GreaterThan(const a,b:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance):boolean; begin result:=(abs(a.Distance)>abs(b.Distance)) or (SameValue(a.Distance,b.Distance) and (a.Dot>b.Dot)); end; class operator TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.GreaterThanOrEqual(const a,b:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance):boolean; begin result:=(abs(a.Distance)>abs(b.Distance)) or (SameValue(a.Distance,b.Distance) and ((a.Dot>=b.Dot) or SameValue(a.Dot,b.Dot))); end; { TpvSignedDistanceField2DMSDFGenerator.TBounds } procedure TpvSignedDistanceField2DMSDFGenerator.TBounds.PointBounds(const p:TpvVectorPathVector); begin if p.x<l then begin l:=p.x; end; if p.y<b then begin b:=p.y; end; if p.x>r then begin r:=p.x; end; if p.y>t then begin t:=p.y; end; end; { TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment } constructor TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(const aP0,aP1:TpvVectorPathVector;const aColor:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor); begin Points[0]:=aP0; Points[1]:=aP1; Color:=aColor; Type_:=TpvSignedDistanceField2DMSDFGenerator.TEdgeType.LINEAR; end; constructor TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(const aP0,aP1,aP2:TpvVectorPathVector;const aColor:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor); begin Points[0]:=aP0; if (aP0=aP1) or (aP1=aP2) then begin Points[1]:=aP0.Lerp(aP2,0.5); end else begin Points[1]:=aP1; end; Points[2]:=aP2; Color:=aColor; Type_:=TpvSignedDistanceField2DMSDFGenerator.TEdgeType.QUADRATIC; end; constructor TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(const aP0,aP1,aP2,aP3:TpvVectorPathVector;const aColor:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor); begin Points[0]:=aP0; Points[1]:=aP1; Points[2]:=aP2; Points[3]:=aP3; Color:=aColor; Type_:=TpvSignedDistanceField2DMSDFGenerator.TEdgeType.CUBIC; end; function TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Point(const aParam:TpvDouble):TpvVectorPathVector; var p12:TpvVectorPathVector; begin case Type_ of TpvSignedDistanceField2DMSDFGenerator.TEdgeType.LINEAR:begin result:=Points[0].Lerp(Points[1],aParam); end; TpvSignedDistanceField2DMSDFGenerator.TEdgeType.QUADRATIC:begin result:=(Points[0].Lerp(Points[1],aParam)).Lerp(Points[1].Lerp(Points[2],aParam),aParam); end; else {TpvSignedDistanceField2DMSDFGenerator.TEdgeType.CUBIC:}begin p12:=Points[1].Lerp(Points[2],aParam); result:=((Points[0].Lerp(Points[1],aParam)).Lerp(p12,aParam)).Lerp(p12.Lerp(Points[2].Lerp(Points[3],aParam),aParam),aParam); end; end; end; function TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Direction(const aParam:TpvDouble):TpvVectorPathVector; begin case Type_ of TpvSignedDistanceField2DMSDFGenerator.TEdgeType.LINEAR:begin result:=Points[1]-Points[0]; end; TpvSignedDistanceField2DMSDFGenerator.TEdgeType.QUADRATIC:begin result:=(Points[1]-Points[0]).Lerp(Points[2]-Points[1],aParam); if IsZero(result.x) and IsZero(result.y) then begin result:=Points[2]-Points[0]; end; end; else {TpvSignedDistanceField2DMSDFGenerator.TEdgeType.CUBIC:}begin result:=((Points[1]-Points[0]).Lerp(Points[2]-Points[1],aParam)).Lerp((Points[2]-Points[1]).Lerp(Points[3]-Points[2],aParam),aParam); if IsZero(result.x) and IsZero(result.y) then begin if SameValue(aParam,0) then begin result:=Points[2]-Points[0]; end else if SameValue(aParam,1) then begin result:=Points[3]-Points[1]; end; end; end; end; end; function TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.MinSignedDistance(const aOrigin:TpvVectorPathVector;var aParam:TpvDouble):TpvSignedDistanceField2DMSDFGenerator.TSignedDistance; var aq,ab,eq,qa,br,epDir,qe,sa,d1,d2:TpvVectorPathVector; EndPointDistance,OrthoDistance,a,b,c,d,MinDistance,Distance,Time:TpvDouble; t:array[0..3] of TpvDouble; Solutions,Index,Step:TpvSizeInt; begin case Type_ of TpvSignedDistanceField2DMSDFGenerator.TEdgeType.LINEAR:begin aq:=aOrigin-Points[0]; ab:=Points[1]-Points[0]; aParam:=aq.Dot(ab)/ab.Dot(ab); eq:=Points[ord(aParam>0.5) and 1]-aOrigin; EndPointDistance:=eq.Length; if (aParam>0.0) and (aParam<1.0) then begin OrthoDistance:=ab.OrthoNormal.Dot(aq); if abs(OrthoDistance)<EndPointDistance then begin result:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Create(OrthoDistance,0.0); exit; end; end; result:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Create(TpvSignedDistanceField2DMSDFGenerator.NonZeroSign(aq.Cross(ab))*EndPointDistance,abs(ab.Normalize.Dot(eq.Normalize))); end; TpvSignedDistanceField2DMSDFGenerator.TEdgeType.QUADRATIC:begin qa:=Points[0]-aOrigin; ab:=Points[1]-Points[0]; br:=(Points[2]-Points[1])-ab; a:=br.Dot(br); b:=3.0*ab.Dot(br); c:=(2.0*ab.Dot(ab))+qa.Dot(br); d:=qa.Dot(ab); Solutions:=SolveCubic(t[0],t[1],t[2],a,b,c,d); epDir:=Direction(0); MinDistance:=TpvSignedDistanceField2DMSDFGenerator.NonZeroSign(epDir.Cross(qa))*qa.Length; aParam:=-(qa.Dot(epDir)/epDir.Dot(epDir)); epDir:=Direction(1); Distance:=TpvSignedDistanceField2DMSDFGenerator.NonZeroSign(epDir.Cross(Points[2]-aOrigin))*((Points[2]-aOrigin).Length); if abs(Distance)<abs(MinDistance) then begin MinDistance:=Distance; aParam:=(aOrigin-Points[1]).Dot(epDir)/epDir.Dot(epDir); end; for Index:=0 to Solutions-1 do begin if (t[Index]>0.0) and (t[Index]<1.0) then begin qe:=(qa+(ab*(2.0*t[Index])))+(br*sqr(t[Index])); Distance:=TpvSignedDistanceField2DMSDFGenerator.NonZeroSign((ab+(br*t[Index])).Cross(qe))*qe.Length; if abs(Distance)<abs(MinDistance) then begin MinDistance:=Distance; aParam:=t[Index]; end; end; end; if (aParam>=0.0) and (aParam<=1.0) then begin result:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Create(MinDistance,0.0); end else if aParam<0.5 then begin result:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Create(MinDistance,abs(Direction(0).Normalize.Dot(qa.Normalize))); end else begin result:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Create(MinDistance,abs(Direction(1).Normalize.Dot((Points[2]-aOrigin).Normalize))); end; end; else {TpvSignedDistanceField2DMSDFGenerator.TEdgeType.CUBIC:}begin qa:=Points[0]-aOrigin; ab:=Points[1]-Points[0]; br:=(Points[2]-Points[1])-ab; sa:=((Points[3]-Points[2])-(Points[2]-Points[1]))-br; epDir:=Direction(0); MinDistance:=TpvSignedDistanceField2DMSDFGenerator.NonZeroSign(epDir.Cross(qa))*qa.Length; aParam:=-qa.Dot(epDir)/epDir.Dot(epDir); begin epDir:=Direction(1); Distance:=TpvSignedDistanceField2DMSDFGenerator.NonZeroSign(epDir.Cross(Points[3]-aOrigin))*(Points[3]-aOrigin).Length; aParam:=-qa.Dot(epDir)/epDir.Dot(epDir); if abs(Distance)<abs(MinDistance) then begin MinDistance:=Distance; aParam:=(epDir-(Points[3]-aOrigin)).Dot(epDir)/epDir.Dot(epDir); end; end; for Index:=0 to TpvSignedDistanceField2DMSDFGenerator.MSDFGEN_CUBIC_SEARCH_STARTS-1 do begin Time:=Index/TpvSignedDistanceField2DMSDFGenerator.MSDFGEN_CUBIC_SEARCH_STARTS; qe:=(((Points[0]+(ab*(3.0*Time)))+(br*(3.0*sqr(Time))))+(sa*(sqr(Time)*Time)))-aOrigin; for Step:=0 to TpvSignedDistanceField2DMSDFGenerator.MSDFGEN_CUBIC_SEARCH_STEPS-1 do begin d1:=((ab*3.0)+(br*(6.0*Time)))+(sa*(sqr(Time)*3.0)); d2:=(br*6.0)+(sa*(6.0*Time)); Time:=Time-(qe.Dot(d1)/(d1.Dot(d1)+qe.Dot(d2))); if (Time>0.0) and (Time<1.0) then begin qe:=(((Points[0]+(ab*(3.0*Time)))+(br*(3.0*sqr(Time))))+(sa*(sqr(Time)*Time)))-aOrigin; Distance:=TpvSignedDistanceField2DMSDFGenerator.NonZeroSign(d1.Cross(qe))*qe.Length(); if abs(Distance)<abs(MinDistance) then begin MinDistance:=Distance; aParam:=Time; end; end else begin break; end; end; end; if (aParam>=0.0) and (aParam<=1.0) then begin result:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Create(MinDistance,0.0); end else if aParam<0.5 then begin result:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Create(MinDistance,abs(Direction(0).Normalize.Dot(qa.Normalize))); end else begin result:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Create(MinDistance,abs(Direction(1).Normalize.Dot((Points[3]-aOrigin).Normalize))); end; end; end; end; procedure TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.DistanceToPseudoDistance(var aDistance:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance;const aOrigin:TpvVectorPathVector;const aParam:TpvDouble); var dir,aq,bq:TpvVectorPathVector; ts,PseudoDistance:TpvDouble; begin if aParam<0.0 then begin dir:=Direction(0).Normalize; aq:=aOrigin-Point(0); ts:=aq.Dot(dir); if ts<0.0 then begin PseudoDistance:=aq.Cross(dir); if abs(PseudoDistance)<=abs(aDistance.Distance) then begin aDistance.Distance:=PseudoDistance; aDistance.Dot:=0.0; end; end; end else if aParam>1.0 then begin dir:=Direction(1).Normalize; bq:=aOrigin-Point(1); ts:=bq.Dot(dir); if ts<0.0 then begin PseudoDistance:=bq.Cross(dir); if abs(PseudoDistance)<=abs(aDistance.Distance) then begin aDistance.Distance:=PseudoDistance; aDistance.Dot:=0.0; end; end; end; end; procedure TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Bounds(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds); var b,a0,a1,a2:TpvVectorPathVector; Param:TpvDouble; Params:array[0..1] of TpvDouble; Solutions:TpvSizeInt; begin case Type_ of TpvSignedDistanceField2DMSDFGenerator.TEdgeType.LINEAR:begin aBounds.PointBounds(Points[0]); aBounds.PointBounds(Points[1]); end; TpvSignedDistanceField2DMSDFGenerator.TEdgeType.QUADRATIC:begin aBounds.PointBounds(Points[0]); aBounds.PointBounds(Points[2]); b:=(Points[1]-Points[0])-(Points[2]-Points[1]); if not IsZero(b.x) then begin Param:=(Points[1].x-Points[0].x)/b.x; if (Param>0.0) and (Param<1.0) then begin aBounds.PointBounds(Point(Param)); end; end; if not IsZero(b.y) then begin Param:=(Points[1].y-Points[0].y)/b.y; if (Param>0.0) and (Param<1.0) then begin aBounds.PointBounds(Point(Param)); end; end; end; else {TpvSignedDistanceField2DMSDFGenerator.TEdgeType.CUBIC:}begin aBounds.PointBounds(Points[0]); aBounds.PointBounds(Points[3]); a0:=Points[1]-Points[0]; a1:=((Points[2]-Points[1])-a0)*2.0; a2:=((Points[3]-(Points[2]*3.0))+(Points[1]*3.0))-Points[0]; Solutions:=SolveQuadratic(Params[0],Params[1],a2.x,a1.x,a0.x); if (Solutions>0) and ((Params[0]>0.0) and (Params[0]<1.0)) then begin aBounds.PointBounds(Point(Params[0])); end; if (Solutions>1) and ((Params[1]>0.0) and (Params[1]<1.0)) then begin aBounds.PointBounds(Point(Params[1])); end; Solutions:=SolveQuadratic(Params[0],Params[1],a2.y,a1.y,a0.y); if (Solutions>0) and ((Params[0]>0.0) and (Params[0]<1.0)) then begin aBounds.PointBounds(Point(Params[0])); end; if (Solutions>1) and ((Params[1]>0.0) and (Params[1]<1.0)) then begin aBounds.PointBounds(Point(Params[1])); end; end; end; end; procedure TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.SplitInThirds(out aPart1,aPart2,aPart3:TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment); begin case Type_ of TpvSignedDistanceField2DMSDFGenerator.TEdgeType.LINEAR:begin aPart1:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Points[0],Point(1.0/3.0),Color); aPart2:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Point(2.0/3.0),Point(2.0/3.0),Color); aPart3:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Point(2.0/3.0),Points[1],Color); end; TpvSignedDistanceField2DMSDFGenerator.TEdgeType.QUADRATIC:begin aPart1:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Points[0],Points[0].Lerp(Points[1],1.0/3.0),Point(1.0/3.0),Color); aPart2:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Point(1.0/3.0),(Points[0].Lerp(Points[1],5.0/9.0)).Lerp(Points[1].Lerp(Points[2],4.0/9.0),0.5),Point(2.0/3.0),Color); aPart3:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Point(2.0/3.0),Points[1].Lerp(Points[2],2.0/3.0),Points[2],Color); end; else {TpvSignedDistanceField2DMSDFGenerator.TEdgeType.CUBIC:}begin if Points[0]=Points[1] then begin aPart1:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Points[0],(Points[0].Lerp(Points[1],1.0/3.0)).Lerp(Points[1].Lerp(Points[2],1.0/3.0),1.0/3.0),Point(1.0/3.0),Color); end else begin aPart1:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Points[0].Lerp(Points[1],1.0/3.0),(Points[0].Lerp(Points[1],1.0/3.0)).Lerp(Points[1].Lerp(Points[2],1.0/3.0),1.0/3.0),Point(1.0/3.0),Color); end; aPart2:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Point(1.0/3.0), ((Points[0].Lerp(Points[1],1.0/3.0)).Lerp(Points[1].Lerp(Points[2],1.0/3.0),1.0/3.0)).Lerp(((Points[1].Lerp(Points[2],1.0/3.0)).Lerp(Points[2].Lerp(Points[3],1.0/3.0),1.0/3.0)),2.0/3.0), ((Points[0].Lerp(Points[1],2.0/3.0)).Lerp(Points[1].Lerp(Points[2],2.0/3.0),2.0/3.0)).Lerp(((Points[1].Lerp(Points[2],2.0/3.0)).Lerp(Points[2].Lerp(Points[3],2.0/3.0),2.0/3.0)),1.0/3.0), Point(2.0/3.0), Color); if Points[2]=Points[3] then begin aPart3:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Point(2.0/3.0), (Points[1].Lerp(Points[2],2.0/3.0)).Lerp(Points[2].Lerp(Points[3],2.0/3.0),2.0/3.0), Points[3], Points[3], Color); end else begin aPart3:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(Point(2.0/3.0), (Points[1].Lerp(Points[2],2.0/3.0)).Lerp(Points[2].Lerp(Points[3],2.0/3.0),2.0/3.0), Points[2].Lerp(Points[3],2.0/3.0), Points[3], Color); end; end; end; end; { TpvSignedDistanceField2DMSDFGenerator.TContour } class function TpvSignedDistanceField2DMSDFGenerator.TContour.Create:TpvSignedDistanceField2DMSDFGenerator.TContour; begin result.Edges:=nil; result.Count:=0; result.CachedWinding:=Low(TpvSizeInt); end; function TpvSignedDistanceField2DMSDFGenerator.TContour.AddEdge({$ifdef fpc}constref{$else}const{$endif} aEdge:TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment):TpvSignedDistanceField2DMSDFGenerator.PEdgeSegment; begin if Count>=length(Edges) then begin SetLength(Edges,(Count+1)+((Count+1) shr 1)); // Grow factor 1.5 end; Edges[Count]:=aEdge; result:=@Edges[Count]; inc(Count); end; procedure TpvSignedDistanceField2DMSDFGenerator.TContour.Bounds(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds); var Index:TpvSizeInt; begin for Index:=0 to Count-1 do begin Edges[Index].Bounds(aBounds); end; end; procedure TpvSignedDistanceField2DMSDFGenerator.TContour.BoundMiters(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds;const aBorder,aMiterLimit:TpvDouble;const aPolarity:TpvSizeInt); var Index:TpvSizeInt; PreviousDirection,Direction,Miter:TpvVectorPathVector; Edge:TpvSignedDistanceField2DMSDFGenerator.PEdgeSegment; MiterLength,q:TpvDouble; begin if Count>0 then begin PreviousDirection:=Edges[Count-1].Direction(1).Normalize; for Index:=0 to Count-1 do begin Edge:=@Edges[Index]; Direction:=-Edge^.Direction(0).Normalize; if (aPolarity*PreviousDirection.Cross(Direction))>=0.0 then begin MiterLength:=aMiterLimit; q:=(1.0-PreviousDirection.Dot(Direction))*0.5; if q>0.0 then begin MiterLength:=Min(1.0/sqrt(q),aMiterLimit); end; Miter:=Edge^.Point(0)+((PreviousDirection+Direction).Normalize*(aBorder*MiterLength)); aBounds.PointBounds(Miter); end; PreviousDirection:=Edge^.Direction(1).Normalize; end; end; end; function TpvSignedDistanceField2DMSDFGenerator.TContour.Winding:TpvSizeInt; var Total:TpvDouble; Index:TpvSizeInt; Edge:TpvSignedDistanceField2DMSDFGenerator.PEdgeSegment; a,b,c,d,Previous,Current:TpvVectorPathVector; begin if CachedWinding=Low(TpvSizeInt) then begin if Count>0 then begin Total:=0.0; case Count of 1:Begin a:=Edges[0].Point(0.0); b:=Edges[0].Point(1.0/3.0); c:=Edges[0].Point(2.0/3.0); Total:=Total+TpvSignedDistanceField2DMSDFGenerator.Shoelace(a,b); Total:=Total+TpvSignedDistanceField2DMSDFGenerator.Shoelace(b,c); Total:=Total+TpvSignedDistanceField2DMSDFGenerator.Shoelace(c,a); end; 2:begin a:=Edges[0].Point(0.0); b:=Edges[0].Point(0.5); c:=Edges[1].Point(0.0); d:=Edges[1].Point(0.5); Total:=Total+TpvSignedDistanceField2DMSDFGenerator.Shoelace(a,b); Total:=Total+TpvSignedDistanceField2DMSDFGenerator.Shoelace(b,c); Total:=Total+TpvSignedDistanceField2DMSDFGenerator.Shoelace(c,d); Total:=Total+TpvSignedDistanceField2DMSDFGenerator.Shoelace(d,a); end; else begin Previous:=Edges[Count-1].Point(0.0); for Index:=0 to Count-1 do begin Edge:=@Edges[Index]; Current:=Edge^.Point(0.0); Total:=Total+TpvSignedDistanceField2DMSDFGenerator.Shoelace(Previous,Current); Previous:=Current; end; end; end; result:=TpvSignedDistanceField2DMSDFGenerator.Sign(Total); end else begin result:=0; end; CachedWinding:=result; end else begin result:=CachedWinding; end; end; { TpvSignedDistanceField2DMSDFGenerator.TShape } class function TpvSignedDistanceField2DMSDFGenerator.TShape.Create:TpvSignedDistanceField2DMSDFGenerator.TShape; begin result.Contours:=nil; result.Count:=0; result.InverseYAxis:=false; end; function TpvSignedDistanceField2DMSDFGenerator.TShape.AddContour:TpvSignedDistanceField2DMSDFGenerator.PContour; begin if Count>=length(Contours) then begin SetLength(Contours,(Count+1)+((Count+1) shr 1)); // Grow factor 1.5 end; result:=@Contours[Count]; inc(Count); result^:=TContour.Create; result^.CachedWinding:=Low(TpvSizeInt); end; function TpvSignedDistanceField2DMSDFGenerator.TShape.Validate:boolean; var ContourIndex,EdgeIndex:TpvSizeInt; Contour:TpvSignedDistanceField2DMSDFGenerator.PContour; Edge:TpvSignedDistanceField2DMSDFGenerator.PEdgeSegment; Corner:TpvVectorPathVector; begin for ContourIndex:=0 to Count-1 do begin Contour:=@Contours[ContourIndex]; if Contour^.Count>0 then begin Corner:=Contour^.Edges[Contour^.Count-1].Point(1); for EdgeIndex:=0 to Contour^.Count-1 do begin Edge:=@Contour^.Edges[EdgeIndex]; if Edge^.Point(0)<>Corner then begin result:=false; exit; end; Corner:=Edge^.Point(1); end; end; end; result:=true; end; procedure TpvSignedDistanceField2DMSDFGenerator.TShape.Normalize; var ContourIndex:TpvSizeInt; Contour:TpvSignedDistanceField2DMSDFGenerator.PContour; Part1,Part2,Part3:TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment; begin for ContourIndex:=0 to Count-1 do begin Contour:=@Contours[ContourIndex]; if Contour^.Count=1 then begin Contour^.Edges[0].SplitInThirds(Part1,Part2,Part3); Contour^.Edges:=nil; SetLength(Contour^.Edges,3); Contour^.Count:=3; Contour^.Edges[0]:=Part1; Contour^.Edges[1]:=Part2; Contour^.Edges[2]:=Part3; end; end; end; procedure TpvSignedDistanceField2DMSDFGenerator.TShape.Bounds(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds); var ContourIndex:TpvSizeInt; Contour:TpvSignedDistanceField2DMSDFGenerator.PContour; begin for ContourIndex:=0 to Count-1 do begin Contour:=@Contours[ContourIndex]; Contour^.Bounds(aBounds); end; end; procedure TpvSignedDistanceField2DMSDFGenerator.TShape.BoundMiters(var aBounds:TpvSignedDistanceField2DMSDFGenerator.TBounds;const aBorder,aMiterLimit:TpvDouble;const aPolarity:TpvSizeInt); var ContourIndex:TpvSizeInt; Contour:TpvSignedDistanceField2DMSDFGenerator.PContour; begin for ContourIndex:=0 to Count-1 do begin Contour:=@Contours[ContourIndex]; Contour^.BoundMiters(aBounds,aBorder,aMiterLimit,aPolarity); end; end; function TpvSignedDistanceField2DMSDFGenerator.TShape.GetBounds(const aBorder:TpvDouble;const aMiterLimit:TpvDouble;const aPolarity:TpvSizeInt):TpvSignedDistanceField2DMSDFGenerator.TBounds; begin result.l:=MaxDouble; result.b:=MaxDouble; result.r:=-MaxDouble; result.t:=-MaxDouble; Bounds(result); if aBorder>0.0 then begin result.l:=result.l-aBorder; result.b:=result.b-aBorder; result.r:=result.r+aBorder; result.t:=result.t+aBorder; if aMiterLimit>0.0 then begin BoundMiters(result,aBorder,aMiterLimit,aPolarity); end; end; end; { TpvSignedDistanceField2DMSDFGenerator } class function TpvSignedDistanceField2DMSDFGenerator.Median(a,b,c:TpvDouble):TpvDouble; begin result:=Max(Min(a,b),Min(Max(a,b),c)); end; class function TpvSignedDistanceField2DMSDFGenerator.Sign(n:TpvDouble):TpvInt32; begin if n<0.0 then begin result:=-1; end else if n>0.0 then begin result:=1; end else begin result:=0; end; end; class function TpvSignedDistanceField2DMSDFGenerator.NonZeroSign(n:TpvDouble):TpvInt32; begin if n<0.0 then begin result:=-1; end else begin result:=1; end; end; class function TpvSignedDistanceField2DMSDFGenerator.SolveQuadratic(out x0,x1:TpvDouble;const a,b,c:TpvDouble):TpvSizeInt; var d:TpvDouble; begin if IsZero(a) or (abs(b)>(abs(a)*1e+12)) then begin if IsZero(b) then begin if IsZero(c) then begin result:=-1; end else begin result:=0; end; end else begin x0:=(-c)/b; result:=1; end; end else begin d:=sqr(b)-(4.0*a*c); if IsZero(d) then begin x0:=(-b)/(2.0*a); result:=1; end else if d>0.0 then begin d:=sqrt(d); x0:=((-b)+d)/(2.0*a); x1:=((-b)-d)/(2.0*a); result:=2; end else begin result:=0; end; end; end; class function TpvSignedDistanceField2DMSDFGenerator.SolveCubicNormed(out x0,x1,x2:TpvDouble;a,b,c:TpvDouble):TpvSizeInt; const ONE_OVER_3=1.0/3.0; ONE_OVER_9=1.0/9.0; ONE_OVER_54=1.0/9.0; BoolSign:array[boolean] of TpvInt32=(-1,1); var a2,q,r,r2,q3,t,u,v:TpvDouble; begin a2:=sqr(a); q:=ONE_OVER_9*(a2-(3.0*b)); r:=ONE_OVER_54*((a*((2.0*a2)-(9.0*b)))+(27*c)); r2:=sqr(r); q3:=sqr(q)*q; a:=a*ONE_OVER_3; if r2<q3 then begin t:=r/sqrt(q3); if t<-1.0 then begin t:=-1.0; end else if t>1.0 then begin t:=1.0; end; t:=ArcCos(t); q:=(-2.0)*sqrt(q); x0:=(q*cos(ONE_OVER_3*t))-a; x1:=(q*cos(ONE_OVER_3*((t+2)*PI)))-a; x2:=(q*cos(ONE_OVER_3*((t-2)*PI)))-a; result:=3; end else begin u:=BoolSign[Boolean(r<0)]*Power(abs(r)+sqrt(r2-q3),1.0/3.0); if IsZero(u) then begin v:=0.0; end else begin v:=q/u; end; x0:=(u+v)-a; if SameValue(u,v) or (abs(u-v)<(1e-12*abs(u+v))) then begin x1:=((-0.5)*(u+v))-a; result:=2; end else begin result:=1; end; end; end; class function TpvSignedDistanceField2DMSDFGenerator.SolveCubic(out x0,x1,x2:TpvDouble;const a,b,c,d:TpvDouble):TpvSizeInt; var bn:TpvDouble; begin if IsZero(a) then begin result:=SolveQuadratic(x0,x1,b,c,d); end else begin bn:=b/a; if abs(bn)<1e+6 then begin result:=SolveCubicNormed(x0,x1,x2,bn,c/a,d/a); end else begin result:=SolveQuadratic(x0,x1,b,c,d); end; end; end; class function TpvSignedDistanceField2DMSDFGenerator.Shoelace(const a,b:TpvVectorPathVector):TpvDouble; begin result:=(b.x-a.x)*(a.y+b.y); end; class procedure TpvSignedDistanceField2DMSDFGenerator.AutoFrame({$ifdef fpc}constref{$else}const{$endif} aShape:TpvSignedDistanceField2DMSDFGenerator.TShape;const aWidth,aHeight:TpvSizeInt;const aPixelRange:TpvDouble;out aTranslate,aScale:TpvVectorPathVector); var Bounds:TpvSignedDistanceField2DMSDFGenerator.TBounds; l,b,r,t:TpvDouble; Frame,Dimensions:TpvVectorPathVector; begin Bounds:=aShape.GetBounds; l:=Bounds.l; b:=Bounds.b; r:=Bounds.r; t:=Bounds.t; if (l>=r) or (b>=t) then begin l:=0.0; b:=0.0; r:=1.0; t:=1.0; end; Frame:=TpvVectorPathVector.Create(aWidth-aPixelRange,aHeight-aPixelRange); if (Frame.x<=1e-6) or (Frame.y<=1e-6) then begin raise EpvSignedDistanceField2DMSDFGenerator.Create('Cannot fit the specified pixel range'); end; Dimensions:=TpvVectorPathVector.Create(r-l,t-b); if (Dimensions.x*Frame.y)<(Dimensions.y*Frame.x) then begin aTranslate:=TpvVectorPathVector.Create(((((Frame.x/Frame.y)*Dimensions.y)-Dimensions.x)*0.5)-l,-b); aScale:=TpvVectorPathVector.Create(Frame.y/Dimensions.y); end else begin aTranslate:=TpvVectorPathVector.Create(-l,((((Frame.y/Frame.x)*Dimensions.x)-Dimensions.y)*0.5)-b); aScale:=TpvVectorPathVector.Create(Frame.x/Dimensions.x); end; aTranslate:=aTranslate+(TpvVectorPathVector.Create(aPixelRange*0.5)/aScale); end; class function TpvSignedDistanceField2DMSDFGenerator.IsCorner(const aDirection,bDirection:TpvVectorPathVector;const aCrossThreshold:TpvDouble):boolean; begin result:=(aDirection.Dot(bDirection)<=0.0) or (abs(aDirection.Dot(bDirection))>aCrossThreshold); end; class procedure TpvSignedDistanceField2DMSDFGenerator.SwitchColor(var aColor:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor;var aSeed:TpvUInt64;const aBanned:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.BLACK); const Start:array[0..2] of TpvSignedDistanceField2DMSDFGenerator.TEdgeColor= ( TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.CYAN, TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.MAGENTA, TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.YELLOW ); var Combined:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor; Shifted:TpvUInt32; begin Combined:=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor(TpvUInt32(TpvUInt32(aColor) and TpvUInt32(aBanned))); case Combined of TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.RED, TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.GREEN, TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.BLUE:begin aColor:=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor(TpvUInt32(TpvUInt32(aColor) xor TpvUInt32(TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.WHITE))); end; TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.BLACK, TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.WHITE:begin aColor:=Start[aSeed mod 3]; aSeed:=aSeed div 3; end; else begin Shifted:=TpvUInt32(aColor) shl (1+(aSeed and 1)); aColor:=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor(TpvUInt32(TpvUInt32(Shifted or (Shifted shr 3)) and TpvUInt32(TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.WHITE))); aSeed:=aSeed shr 1; end; end; end; class procedure TpvSignedDistanceField2DMSDFGenerator.EdgeColoringSimple(var aShape:TpvSignedDistanceField2DMSDFGenerator.TShape;const aAngleThreshold:TpvDouble;aSeed:TpvUInt64); type TCorners=array of TpvSizeInt; var ContourIndex,EdgeIndex,CountCorners,Corner,Spline,Start,Index:TpvSizeInt; CrossThreshold:TpvDouble; Corners:TCorners; Contour:TpvSignedDistanceField2DMSDFGenerator.PContour; PreviousDirection:TpvVectorPathVector; Edge:TpvSignedDistanceField2DMSDFGenerator.PEdgeSegment; Color,InitialColor:TpvSignedDistanceField2DMSDFGenerator.TEdgeColor; Colors:array[0..5] of TpvSignedDistanceField2DMSDFGenerator.TEdgeColor; Parts:array[0..6] of TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment; begin CrossThreshold:=sin(aAngleThreshold); Corners:=nil; try for ContourIndex:=0 to aShape.Count-1 do begin Contour:=@aShape.Contours[ContourIndex]; try CountCorners:=0; if Contour^.Count>0 then begin PreviousDirection:=Contour^.Edges[Contour^.Count-1].Direction(1); for EdgeIndex:=0 to Contour^.Count-1 do begin Edge:=@Contour^.Edges[EdgeIndex]; if IsCorner(PreviousDirection.Normalize,Edge^.Direction(0).Normalize,CrossThreshold) then begin if CountCorners>=length(Corners) then begin SetLength(Corners,(CountCorners+1)+((CountCorners+1) shr 1)); end; Corners[CountCorners]:=EdgeIndex; inc(CountCorners); end; PreviousDirection:=Edge^.Direction(1); end; case CountCorners of 0:begin for EdgeIndex:=0 to Contour^.Count-1 do begin Edge:=@Contour^.Edges[EdgeIndex]; Edge^.Color:=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.WHITE; end; end; 1:begin Colors[0]:=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.WHITE; TpvSignedDistanceField2DMSDFGenerator.SwitchColor(Colors[0],aSeed); Colors[2]:=Colors[0]; TpvSignedDistanceField2DMSDFGenerator.SwitchColor(Colors[2],aSeed); Corner:=Corners[0]; if Contour.Count>=3 then begin for EdgeIndex:=0 to Contour.Count-1 do begin Edge:=@Contour^.Edges[(EdgeIndex+Corner) mod Contour.Count]; Edge^.Color:=Colors[3+trunc((((3+((2.875*EdgeIndex)/(Contour.Count-1)))-1.4375)+0.5)-3)]; end; end else if Contour.Count>=1 then begin Contour.Edges[0].SplitInThirds(Parts[(3*Corner)+0],Parts[(3*Corner)+1],Parts[(3*Corner)+2]); if Contour.Count>=2 then begin Contour.Edges[0].SplitInThirds(Parts[3-(3*Corner)],Parts[4-(3*Corner)],Parts[5-(3*Corner)]); Parts[0].Color:=Colors[0]; Parts[1].Color:=Colors[0]; Parts[2].Color:=Colors[1]; Parts[3].Color:=Colors[1]; Parts[4].Color:=Colors[2]; Parts[5].Color:=Colors[2]; Contour.Count:=6; SetLength(Contour.Edges,6); Contour.Edges[0]:=Parts[0]; Contour.Edges[1]:=Parts[1]; Contour.Edges[2]:=Parts[2]; Contour.Edges[3]:=Parts[3]; Contour.Edges[4]:=Parts[4]; Contour.Edges[5]:=Parts[5]; end else begin Parts[0].Color:=Colors[0]; Parts[1].Color:=Colors[1]; Parts[2].Color:=Colors[2]; Contour.Count:=3; SetLength(Contour.Edges,3); Contour.Edges[0]:=Parts[0]; Contour.Edges[1]:=Parts[1]; Contour.Edges[2]:=Parts[2]; end; end; end; else begin Spline:=0; Start:=Corners[0]; Color:=TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.WHITE; TpvSignedDistanceField2DMSDFGenerator.SwitchColor(Color,aSeed,TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.BLACK); InitialColor:=Color; for EdgeIndex:=0 to Contour^.Count-1 do begin Index:=(Start+EdgeIndex) mod Contour^.Count; if ((Spline+1)<CountCorners) and (Corners[Spline+1]=Index) then begin inc(Spline); TpvSignedDistanceField2DMSDFGenerator.SwitchColor(Color,aSeed,TpvSignedDistanceField2DMSDFGenerator.TEdgeColor(TpvUInt32(TpvUInt32(ord(Spline=(CountCorners-1)) and 1)*TpvUInt32(InitialColor)))); end; Contour^.Edges[Index].Color:=Color; end; end; end; end; finally Corners:=nil; end; end; finally Corners:=nil; end; end; class procedure TpvSignedDistanceField2DMSDFGenerator.GenerateDistanceFieldPixel(var aImage:TpvSignedDistanceField2DMSDFGenerator.TImage;{$ifdef fpc}constref{$else}const{$endif} aShape:TpvSignedDistanceField2DMSDFGenerator.TShape;const aRange:TpvDouble;const aScale,aTranslate:TpvVectorPathVector;const aX,aY:TpvSizeInt); type TEdgePoint=Record MinDistance:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance; NearEdge:TpvSignedDistanceField2DMSDFGenerator.PEdgeSegment; NearParam:TpvDouble; end; var x,y,ContourIndex,EdgeIndex,Winding:TpvSizeInt; Contour:TpvSignedDistanceField2DMSDFGenerator.PContour; Edge:TpvSignedDistanceField2DMSDFGenerator.PEdgeSegment; r,g,b,sr,sg,sb:TEdgePoint; p:TpvVectorPathVector; Param,MedianMinDistance,MinMedianDistance, PositiveDistance,NegativeDistance:TpvDouble; MinDistance,Distance:TpvSignedDistanceField2DMSDFGenerator.TSignedDistance; HasMinDistance:boolean; Pixel:TpvSignedDistanceField2DMSDFGenerator.PPixel; MultiSignedDistance:TMultiSignedDistance; begin x:=aX; if aShape.InverseYAxis then begin y:=aImage.Height-(aY+1); end else begin y:=aY; end; p:=(TpvVectorPathVector.Create(x+0.5,y+0.5)/aScale)-aTranslate; MinMedianDistance:=abs(TpvSignedDistanceField2DMSDFGenerator.PositiveInfinityDistance); PositiveDistance:=TpvSignedDistanceField2DMSDFGenerator.NegativeInfinityDistance; NegativeDistance:=TpvSignedDistanceField2DMSDFGenerator.PositiveInfinityDistance; MinDistance:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Empty; HasMinDistance:=false; sr.MinDistance:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Empty; sr.NearEdge:=nil; sr.NearParam:=0.0; sg.MinDistance:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Empty; sg.NearEdge:=nil; sg.NearParam:=0.0; sb.MinDistance:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Empty; sb.NearEdge:=nil; sb.NearParam:=0.0; Winding:=0; for ContourIndex:=0 to aShape.Count-1 do begin r.MinDistance:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Empty; r.NearEdge:=nil; r.NearParam:=0.0; g.MinDistance:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Empty; g.NearEdge:=nil; g.NearParam:=0.0; b.MinDistance:=TpvSignedDistanceField2DMSDFGenerator.TSignedDistance.Empty; b.NearEdge:=nil; b.NearParam:=0.0; Contour:=@aShape.Contours[ContourIndex]; if Contour^.Count>0 then begin for EdgeIndex:=0 to Contour^.Count-1 do begin Edge:=@Contour^.Edges[EdgeIndex]; Distance:=Edge^.MinSignedDistance(p,Param); if (not HasMinDistance) or (Distance<MinDistance) then begin MinDistance:=Distance; HasMinDistance:=true; end; if ((TpvUInt32(Edge^.Color) and TpvUInt32(TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.RED))<>0) and ((not assigned(r.NearEdge)) or (Distance<r.MinDistance)) then begin r.MinDistance:=Distance; r.NearEdge:=Edge; r.NearParam:=Param; end; if ((TpvUInt32(Edge^.Color) and TpvUInt32(TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.GREEN))<>0) and ((not assigned(g.NearEdge)) or (Distance<g.MinDistance)) then begin g.MinDistance:=Distance; g.NearEdge:=Edge; g.NearParam:=Param; end; if ((TpvUInt32(Edge^.Color) and TpvUInt32(TpvSignedDistanceField2DMSDFGenerator.TEdgeColor.BLUE))<>0) and ((not assigned(b.NearEdge)) or (Distance<b.MinDistance)) then begin b.MinDistance:=Distance; b.NearEdge:=Edge; b.NearParam:=Param; end; end; end; if (not assigned(sr.NearEdge)) or (r.MinDistance<sr.MinDistance) then begin sr:=r; end; if (not assigned(sg.NearEdge)) or (g.MinDistance<sg.MinDistance) then begin sg:=g; end; if (not assigned(sb.NearEdge)) or (b.MinDistance<sb.MinDistance) then begin sb:=b; end; MedianMinDistance:=abs(TpvSignedDistanceField2DMSDFGenerator.Median(r.MinDistance.Distance,g.MinDistance.Distance,b.MinDistance.Distance)); if MedianMinDistance<MinMedianDistance then begin MinMedianDistance:=MedianMinDistance; Winding:=Contour^.Winding; end; if assigned(r.NearEdge) then begin r.NearEdge^.DistanceToPseudoDistance(r.MinDistance,p,r.NearParam); end; if assigned(r.NearEdge) then begin g.NearEdge^.DistanceToPseudoDistance(g.MinDistance,p,g.NearParam); end; if assigned(r.NearEdge) then begin b.NearEdge^.DistanceToPseudoDistance(b.MinDistance,p,b.NearParam); end; MedianMinDistance:=abs(TpvSignedDistanceField2DMSDFGenerator.Median(r.MinDistance.Distance,g.MinDistance.Distance,b.MinDistance.Distance)); Contour^.MultiSignedDistance.r:=r.MinDistance.Distance; Contour^.MultiSignedDistance.g:=g.MinDistance.Distance; Contour^.MultiSignedDistance.b:=b.MinDistance.Distance; Contour^.MultiSignedDistance.Median:=MedianMinDistance; if abs(MedianMinDistance)<>1e240 then begin if (Contour^.Winding>0) and (MedianMinDistance>=0) and (abs(MedianMinDistance)<abs(PositiveDistance)) then begin PositiveDistance:=MedianMinDistance; end; if (Contour^.Winding<0) and (MedianMinDistance<=0) and (abs(MedianMinDistance)<abs(NegativeDistance)) then begin NegativeDistance:=MedianMinDistance; end; end; end; if assigned(sr.NearEdge) then begin sr.NearEdge^.DistanceToPseudoDistance(sr.MinDistance,p,sr.NearParam); end; if assigned(r.NearEdge) then begin sg.NearEdge^.DistanceToPseudoDistance(sg.MinDistance,p,sg.NearParam); end; if assigned(r.NearEdge) then begin sb.NearEdge^.DistanceToPseudoDistance(sb.MinDistance,p,sb.NearParam); end; MultiSignedDistance.r:=TpvSignedDistanceField2DMSDFGenerator.NegativeInfinityDistance; MultiSignedDistance.g:=TpvSignedDistanceField2DMSDFGenerator.NegativeInfinityDistance; MultiSignedDistance.b:=TpvSignedDistanceField2DMSDFGenerator.NegativeInfinityDistance; MultiSignedDistance.Median:=TpvSignedDistanceField2DMSDFGenerator.NegativeInfinityDistance; if (PositiveDistance>=0.0) and (abs(PositiveDistance)<=abs(NegativeDistance)) then begin Winding:=1; for ContourIndex:=0 to aShape.Count-1 do begin Contour:=@aShape.Contours[ContourIndex]; if (Contour^.Winding>0) and (Contour^.MultiSignedDistance.Median>MultiSignedDistance.Median) and (abs(Contour^.MultiSignedDistance.Median)<abs(NegativeDistance)) then begin MultiSignedDistance:=Contour^.MultiSignedDistance; end; end; end else if (NegativeDistance<=0.0) and (abs(NegativeDistance)<=abs(PositiveDistance)) then begin MultiSignedDistance.Median:=-MultiSignedDistance.Median; Winding:=-1; for ContourIndex:=0 to aShape.Count-1 do begin Contour:=@aShape.Contours[ContourIndex]; if (Contour^.Winding<0) and (Contour^.MultiSignedDistance.Median<MultiSignedDistance.Median) and (abs(Contour^.MultiSignedDistance.Median)<abs(PositiveDistance)) then begin MultiSignedDistance:=Contour^.MultiSignedDistance; end; end; end; for ContourIndex:=0 to aShape.Count-1 do begin Contour:=@aShape.Contours[ContourIndex]; if (Contour^.Winding<>Winding) and (abs(Contour^.MultiSignedDistance.Median)<abs(MultiSignedDistance.Median)) then begin MultiSignedDistance:=Contour^.MultiSignedDistance; end; end; if SameValue(TpvSignedDistanceField2DMSDFGenerator.Median(sr.MinDistance.Distance,sg.MinDistance.Distance,sb.MinDistance.Distance),MultiSignedDistance.Median) then begin MultiSignedDistance.r:=sr.MinDistance.Distance; MultiSignedDistance.g:=sg.MinDistance.Distance; MultiSignedDistance.b:=sb.MinDistance.Distance; end; Pixel:=@aImage.Pixels[(aY*aImage.Width)+aX]; Pixel^.r:=(MultiSignedDistance.r/aRange)+0.5; Pixel^.g:=(MultiSignedDistance.g/aRange)+0.5; Pixel^.b:=(MultiSignedDistance.b/aRange)+0.5; Pixel^.a:=(MinDistance.Distance/aRange)+0.5; if MultiSignedDistance.r<>0 then begin if Pixel^.r>0 then begin end; end; end; type TpvSignedDistanceField2DMSDFGeneratorGenerateDistanceFieldData=record Image:TpvSignedDistanceField2DMSDFGenerator.PImage; Shape:TpvSignedDistanceField2DMSDFGenerator.PShape; Range:TpvDouble; Scale:TpvVectorPathVector; Translate:TpvVectorPathVector; end; PpvSignedDistanceField2DMSDFGeneratorGenerateDistanceFieldData=^TpvSignedDistanceField2DMSDFGeneratorGenerateDistanceFieldData; procedure TpvSignedDistanceField2DMSDFGeneratorGenerateDistanceFieldParallelForJobFunction(const Job:PPasMPJob;const ThreadIndex:TPasMPInt32;const DataPointer:TpvPointer;const FromIndex,ToIndex:TPasMPNativeInt); var Data:PpvSignedDistanceField2DMSDFGeneratorGenerateDistanceFieldData; Index,x,y,w:TPasMPNativeInt; begin Data:=DataPointer; w:=Data^.Image^.Width; for Index:=FromIndex to ToIndex do begin y:=Index div w; x:=Index-(y*w); TpvSignedDistanceField2DMSDFGenerator.GenerateDistanceFieldPixel(Data^.Image^,Data^.Shape^,Data^.Range,Data^.Scale,Data^.Translate,x,y); end; end; class procedure TpvSignedDistanceField2DMSDFGenerator.GenerateDistanceField(var aImage:TpvSignedDistanceField2DMSDFGenerator.TImage;{$ifdef fpc}constref{$else}const{$endif} aShape:TpvSignedDistanceField2DMSDFGenerator.TShape;const aRange:TpvDouble;const aScale,aTranslate:TpvVectorPathVector;const aPasMPInstance:TPasMP=nil); var x,y:TpvSizeInt; Data:TpvSignedDistanceField2DMSDFGeneratorGenerateDistanceFieldData; begin if assigned(aPasMPInstance) then begin Data.Image:=@aImage; Data.Shape:=@aShape; Data.Range:=aRange; Data.Scale:=aScale; Data.Translate:=aTranslate; aPasMPInstance.Invoke(aPasMPInstance.ParallelFor(@Data,0,(aImage.Width*aImage.Height)-1,TpvSignedDistanceField2DMSDFGeneratorGenerateDistanceFieldParallelForJobFunction,1,10,nil,0)); end else begin for y:=0 to aImage.Height-1 do begin for x:=0 to aImage.Width-1 do begin TpvSignedDistanceField2DMSDFGenerator.GenerateDistanceFieldPixel(aImage,aShape,aRange,aScale,aTranslate,x,y); end; end; end; end; class function TpvSignedDistanceField2DMSDFGenerator.DetectClash({$ifdef fpc}constref{$else}const{$endif} a,b:TpvSignedDistanceField2DMSDFGenerator.TPixel;const aThreshold:TpvDouble):boolean; var a0,a1,a2,b0,b1,b2,t:TpvDouble; begin a0:=a.r; a1:=a.g; a2:=a.b; b0:=b.r; b1:=b.g; b2:=b.b; if abs(b0-a0)<abs(b1-a1) then begin t:=a0; a0:=a1; a1:=t; t:=b0; b0:=b1; b1:=t; end; if abs(b1-a1)<abs(b2-a2) then begin t:=a1; a1:=a2; a2:=t; t:=b1; b1:=b2; b2:=t; if abs(b0-a0)<abs(b1-a1) then begin t:=a0; a0:=a1; a1:=t; t:=b0; b0:=b1; b1:=t; end; end; result:=(abs(b1-a1)>=aThreshold) and (not (SameValue(b0,b1) and SameValue(b0,b2))) and (abs(a2-0.5)>=abs(b2-0.5)); end; class procedure TpvSignedDistanceField2DMSDFGenerator.ErrorCorrection(var aImage:TpvSignedDistanceField2DMSDFGenerator.TImage;const aThreshold:TpvVectorPathVector); type TClash=record x,y:TpvSizeInt; end; PClash=^TClash; TClashes=array of TClash; var x,y,Count,Index:TpvSizeInt; Clashes:TClashes; Clash:PClash; Pixel:TpvSignedDistanceField2DMSDFGenerator.PPixel; Median:TpvDouble; begin Clashes:=nil; Count:=0; try for y:=0 to aImage.Height-1 do begin for x:=0 to aImage.Width-1 do begin if ((x>0) and TpvSignedDistanceField2DMSDFGenerator.DetectClash(aImage.Pixels[(y*aImage.Width)+x],aImage.Pixels[(y*aImage.Width)+(x-1)],aThreshold.x)) or ((x<(aImage.Width-1)) and TpvSignedDistanceField2DMSDFGenerator.DetectClash(aImage.Pixels[(y*aImage.Width)+x],aImage.Pixels[(y*aImage.Width)+(x+1)],aThreshold.x)) or ((y>0) and TpvSignedDistanceField2DMSDFGenerator.DetectClash(aImage.Pixels[(y*aImage.Width)+x],aImage.Pixels[((y-1)*aImage.Width)+x],aThreshold.y)) or ((y<(aImage.Height-1)) and TpvSignedDistanceField2DMSDFGenerator.DetectClash(aImage.Pixels[(y*aImage.Width)+x],aImage.Pixels[((y+1)*aImage.Width)+x],aThreshold.y)) then begin if Count>=length(Clashes) then begin SetLength(Clashes,(Count+1)+((Count+1) shr 1)); end; Clash:=@Clashes[Count]; inc(Count); Clash^.x:=x; Clash^.y:=y; end; end; end; for Index:=0 to Count-1 do begin Clash:=@Clashes[Index]; Pixel:=@aImage.Pixels[(Clash^.y*aImage.Width)+Clash^.x]; Median:=TpvSignedDistanceField2DMSDFGenerator.Median(Pixel^.r,Pixel^.g,Pixel^.b); Pixel^.r:=Median; Pixel^.g:=Median; Pixel^.b:=Median; end; finally Clashes:=nil; end; Clashes:=nil; Count:=0; try for y:=0 to aImage.Height-1 do begin for x:=0 to aImage.Width-1 do begin if ((x>0) and (y>0) and TpvSignedDistanceField2DMSDFGenerator.DetectClash(aImage.Pixels[(y*aImage.Width)+x],aImage.Pixels[((y-1)*aImage.Width)+(x-1)],aThreshold.x)) or ((x<(aImage.Width-1)) and (y>0) and TpvSignedDistanceField2DMSDFGenerator.DetectClash(aImage.Pixels[(y*aImage.Width)+x],aImage.Pixels[((y-1)*aImage.Width)+(x+1)],aThreshold.x)) or ((x>0) and (y<(aImage.Height-1)) and TpvSignedDistanceField2DMSDFGenerator.DetectClash(aImage.Pixels[(y*aImage.Width)+x],aImage.Pixels[((y+1)*aImage.Width)+(x-1)],aThreshold.y)) or ((x<(aImage.Width-1)) and (y<(aImage.Height-1)) and TpvSignedDistanceField2DMSDFGenerator.DetectClash(aImage.Pixels[(y*aImage.Width)+x],aImage.Pixels[((y+1)*aImage.Width)+(x+1)],aThreshold.y)) then begin if Count>=length(Clashes) then begin SetLength(Clashes,(Count+1)+((Count+1) shr 1)); end; Clash:=@Clashes[Count]; inc(Count); Clash^.x:=x; Clash^.y:=y; end; end; end; for Index:=0 to Count-1 do begin Clash:=@Clashes[Index]; Pixel:=@aImage.Pixels[(Clash^.y*aImage.Width)+Clash^.x]; Median:=TpvSignedDistanceField2DMSDFGenerator.Median(Pixel^.r,Pixel^.g,Pixel^.b); Pixel^.r:=Median; Pixel^.g:=Median; Pixel^.b:=Median; end; finally Clashes:=nil; end; end; { TpvSignedDistanceField2DGenerator } constructor TpvSignedDistanceField2DGenerator.Create; begin inherited Create; fPointInPolygonPathSegments:=nil; fVectorPathShape:=nil; fDistanceField:=nil; fVariant:=TpvSignedDistanceField2DVariant.Default; end; destructor TpvSignedDistanceField2DGenerator.Destroy; begin fPointInPolygonPathSegments:=nil; fVectorPathShape:=nil; fDistanceField:=nil; inherited Destroy; end; function TpvSignedDistanceField2DGenerator.Clamp(const Value,MinValue,MaxValue:TpvInt64):TpvInt64; begin if Value<=MinValue then begin result:=MinValue; end else if Value>=MaxValue then begin result:=MaxValue; end else begin result:=Value; end; end; function TpvSignedDistanceField2DGenerator.Clamp(const Value,MinValue,MaxValue:TpvDouble):TpvDouble; begin if Value<=MinValue then begin result:=MinValue; end else if Value>=MaxValue then begin result:=MaxValue; end else begin result:=Value; end; end; function TpvSignedDistanceField2DGenerator.VectorMap(const p:TpvVectorPathVector;const m:TpvSignedDistanceField2DDoublePrecisionAffineMatrix):TpvVectorPathVector; begin result.x:=(p.x*m[0])+(p.y*m[1])+m[2]; result.y:=(p.x*m[3])+(p.y*m[4])+m[5]; end; procedure TpvSignedDistanceField2DGenerator.GetOffset(out oX,oY:TpvDouble); begin case fVariant of TpvSignedDistanceField2DVariant.GSDF:begin case fColorChannelIndex of 1:begin oX:=1.0; oY:=0.0; end; 2:begin oX:=0.0; oY:=1.0; end; else {0:}begin oX:=0.0; oY:=0.0; end; end; end; TpvSignedDistanceField2DVariant.SSAASDF:begin case fColorChannelIndex of 0:begin oX:=0.125; oY:=0.375; end; 1:begin oX:=-0.125; oY:=-0.375; end; 2:begin oX:=0.375; oY:=-0.125; end; else {3:}begin oX:=-0.375; oY:=0.125; end; end; end; else begin oX:=0.0; oY:=0.0; end; end; end; procedure TpvSignedDistanceField2DGenerator.ApplyOffset(var aX,aY:TpvDouble); var oX,oY:TpvDouble; begin GetOffset(oX,oY); aX:=aX+oX; aY:=aY+oY; end; function TpvSignedDistanceField2DGenerator.ApplyOffset(const aPoint:TpvVectorPathVector):TpvVectorPathVector; var oX,oY:TpvDouble; begin GetOffset(oX,oY); result.x:=aPoint.x+oX; result.y:=aPoint.y+oY; end; function TpvSignedDistanceField2DGenerator.BetweenClosedOpen(const a,b,c:TpvDouble;const Tolerance:TpvDouble=0.0;const XFormToleranceToX:boolean=false):boolean; var ToleranceB,ToleranceC:TpvDouble; begin Assert(Tolerance>=0.0); if XFormToleranceToX then begin ToleranceB:=Tolerance/sqrt((sqr(b)*4.0)+1.0); ToleranceC:=Tolerance/sqrt((sqr(c)*4.0)+1.0); end else begin ToleranceB:=Tolerance; ToleranceC:=Tolerance; end; if b<c then begin result:=(a>=(b-ToleranceB)) and (a<(c-ToleranceC)); end else begin result:=(a>=(c-ToleranceC)) and (a<(b-ToleranceB)); end; end; function TpvSignedDistanceField2DGenerator.BetweenClosed(const a,b,c:TpvDouble;const Tolerance:TpvDouble=0.0;const XFormToleranceToX:boolean=false):boolean; var ToleranceB,ToleranceC:TpvDouble; begin Assert(Tolerance>=0.0); if XFormToleranceToX then begin ToleranceB:=Tolerance/sqrt((sqr(b)*4.0)+1.0); ToleranceC:=Tolerance/sqrt((sqr(c)*4.0)+1.0); end else begin ToleranceB:=Tolerance; ToleranceC:=Tolerance; end; if b<c then begin result:=(a>=(b-ToleranceB)) and (a<=(c+ToleranceC)); end else begin result:=(a>=(c-ToleranceC)) and (a<=(b+ToleranceB)); end; end; function TpvSignedDistanceField2DGenerator.NearlyZero(const Value:TpvDouble;const Tolerance:TpvDouble=DistanceField2DNearlyZeroValue):boolean; begin Assert(Tolerance>=0.0); result:=abs(Value)<=Tolerance; end; function TpvSignedDistanceField2DGenerator.NearlyEqual(const x,y:TpvDouble;const Tolerance:TpvDouble=DistanceField2DNearlyZeroValue;const XFormToleranceToX:boolean=false):boolean; begin Assert(Tolerance>=0.0); if XFormToleranceToX then begin result:=abs(x-y)<=(Tolerance/sqrt((sqr(y)*4.0)+1.0)); end else begin result:=abs(x-y)<=Tolerance; end; end; function TpvSignedDistanceField2DGenerator.SignOf(const Value:TpvDouble):TpvInt32; begin if Value<0.0 then begin result:=-1; end else begin result:=1; end; end; function TpvSignedDistanceField2DGenerator.IsColinear(const Points:array of TpvVectorPathVector):boolean; begin Assert(length(Points)=3); result:=abs(((Points[1].y-Points[0].y)*(Points[1].x-Points[2].x))- ((Points[1].y-Points[2].y)*(Points[1].x-Points[0].x)))<=DistanceField2DCloseSquaredValue; end; function TpvSignedDistanceField2DGenerator.PathSegmentDirection(const PathSegment:TpvSignedDistanceField2DPathSegment;const Which:TpvInt32):TpvVectorPathVector; begin case PathSegment.Type_ of TpvSignedDistanceField2DPathSegmentType.Line:begin result.x:=PathSegment.Points[1].x-PathSegment.Points[0].x; result.y:=PathSegment.Points[1].y-PathSegment.Points[0].y; end; TpvSignedDistanceField2DPathSegmentType.QuadraticBezierCurve:begin case Which of 0:begin result.x:=PathSegment.Points[1].x-PathSegment.Points[0].x; result.y:=PathSegment.Points[1].y-PathSegment.Points[0].y; end; 1:begin result.x:=PathSegment.Points[2].x-PathSegment.Points[1].x; result.y:=PathSegment.Points[2].y-PathSegment.Points[1].y; end; else begin result.x:=0.0; result.y:=0.0; Assert(false); end; end; end; else begin result.x:=0.0; result.y:=0.0; Assert(false); end; end; end; function TpvSignedDistanceField2DGenerator.PathSegmentCountPoints(const PathSegment:TpvSignedDistanceField2DPathSegment):TpvInt32; begin case PathSegment.Type_ of TpvSignedDistanceField2DPathSegmentType.Line:begin result:=2; end; TpvSignedDistanceField2DPathSegmentType.QuadraticBezierCurve:begin result:=3; end; else begin result:=0; Assert(false); end; end; end; function TpvSignedDistanceField2DGenerator.PathSegmentEndPoint(const PathSegment:TpvSignedDistanceField2DPathSegment):PpvVectorPathVector; begin case PathSegment.Type_ of TpvSignedDistanceField2DPathSegmentType.Line:begin result:=@PathSegment.Points[1]; end; TpvSignedDistanceField2DPathSegmentType.QuadraticBezierCurve:begin result:=@PathSegment.Points[2]; end; else begin result:=nil; Assert(false); end; end; end; function TpvSignedDistanceField2DGenerator.PathSegmentCornerPoint(const PathSegment:TpvSignedDistanceField2DPathSegment;const WhichA,WhichB:TpvInt32):PpvVectorPathVector; begin case PathSegment.Type_ of TpvSignedDistanceField2DPathSegmentType.Line:begin result:=@PathSegment.Points[WhichB and 1]; end; TpvSignedDistanceField2DPathSegmentType.QuadraticBezierCurve:begin result:=@PathSegment.Points[(WhichA and 1)+(WhichB and 1)]; end; else begin result:=nil; Assert(false); end; end; end; procedure TpvSignedDistanceField2DGenerator.InitializePathSegment(var PathSegment:TpvSignedDistanceField2DPathSegment); var p0,p1,p2,p1mp0,d,t,sp0,sp1,sp2,p01p,p02p,p12p:TpvVectorPathVector; Hypotenuse,CosTheta,SinTheta,a,b,h,c,g,f,gd,fd,x,y,Lambda:TpvDouble; begin case PathSegment.Type_ of TpvSignedDistanceField2DPathSegmentType.Line:begin p0:=PathSegment.Points[0]; p2:=PathSegment.Points[1]; PathSegment.BoundingBox.Min.x:=Min(p0.x,p2.x); PathSegment.BoundingBox.Min.y:=Min(p0.y,p2.y); PathSegment.BoundingBox.Max.x:=Max(p0.x,p2.x); PathSegment.BoundingBox.Max.y:=Max(p0.y,p2.y); PathSegment.ScalingFactor:=1.0; PathSegment.SquaredScalingFactor:=1.0; Hypotenuse:=p0.Distance(p2); CosTheta:=(p2.x-p0.x)/Hypotenuse; SinTheta:=(p2.y-p0.y)/Hypotenuse; PathSegment.XFormMatrix[0]:=CosTheta; PathSegment.XFormMatrix[1]:=SinTheta; PathSegment.XFormMatrix[2]:=(-(CosTheta*p0.x))-(SinTheta*p0.y); PathSegment.XFormMatrix[3]:=-SinTheta; PathSegment.XFormMatrix[4]:=CosTheta; PathSegment.XFormMatrix[5]:=(SinTheta*p0.x)-(CosTheta*p0.y); end; else {pstQuad:}begin p0:=PathSegment.Points[0]; p1:=PathSegment.Points[1]; p2:=PathSegment.Points[2]; PathSegment.BoundingBox.Min.x:=Min(p0.x,p2.x); PathSegment.BoundingBox.Min.y:=Min(p0.y,p2.y); PathSegment.BoundingBox.Max.x:=Max(p0.x,p2.x); PathSegment.BoundingBox.Max.y:=Max(p0.y,p2.y); p1mp0.x:=p1.x-p0.x; p1mp0.y:=p1.y-p0.y; d.x:=(p1mp0.x-p2.x)+p1.x; d.y:=(p1mp0.y-p2.y)+p1.y; if IsZero(d.x) then begin t.x:=p0.x; end else begin t.x:=p0.x+(Clamp(p1mp0.x/d.x,0.0,1.0)*p1mp0.x); end; if IsZero(d.y) then begin t.y:=p0.y; end else begin t.y:=p0.y+(Clamp(p1mp0.y/d.y,0.0,1.0)*p1mp0.y); end; PathSegment.BoundingBox.Min.x:=Min(PathSegment.BoundingBox.Min.x,t.x); PathSegment.BoundingBox.Min.y:=Min(PathSegment.BoundingBox.Min.y,t.y); PathSegment.BoundingBox.Max.x:=Max(PathSegment.BoundingBox.Max.x,t.x); PathSegment.BoundingBox.Max.y:=Max(PathSegment.BoundingBox.Max.y,t.y); sp0.x:=sqr(p0.x); sp0.y:=sqr(p0.y); sp1.x:=sqr(p1.x); sp1.y:=sqr(p1.y); sp2.x:=sqr(p2.x); sp2.y:=sqr(p2.y); p01p.x:=p0.x*p1.x; p01p.y:=p0.y*p1.y; p02p.x:=p0.x*p2.x; p02p.y:=p0.y*p2.y; p12p.x:=p1.x*p2.x; p12p.y:=p1.y*p2.y; a:=sqr((p0.y-(2.0*p1.y))+p2.y); h:=-(((p0.y-(2.0*p1.y))+p2.y)*((p0.x-(2.0*p1.x))+p2.x)); b:=sqr((p0.x-(2.0*p1.x))+p2.x); c:=((((((sp0.x*sp2.y)-(4.0*p01p.x*p12p.y))-(2.0*p02p.x*p02p.y))+(4.0*p02p.x*sp1.y))+(4.0*sp1.x*p02p.y))-(4.0*p12p.x*p01p.y))+(sp2.x*sp0.y); g:=((((((((((p0.x*p02p.y)-(2.0*p0.x*sp1.y))+(2.0*p0.x*p12p.y))-(p0.x*sp2.y))+(2.0*p1.x*p01p.y))-(4.0*p1.x*p02p.y))+(2.0*p1.x*p12p.y))-(p2.x*sp0.y))+(2.0*p2.x*p01p.y))+(p2.x*p02p.y))-(2.0*p2.x*sp1.y); f:=-(((((((((((sp0.x*p2.y)-(2.0*p01p.x*p1.y))-(2.0*p01p.x*p2.y))-(p02p.x*p0.y))+(4.0*p02p.x*p1.y))-(p02p.x*p2.y))+(2.0*sp1.x*p0.y))+(2.0*sp1.x*p2.y))-(2.0*p12p.x*p0.y))-(2.0*p12p.x*p1.y))+(sp2.x*p0.y)); CosTheta:=sqrt(a/(a+b)); SinTheta:=(-SignOf((a+b)*h))*sqrt(b/(a+b)); gd:=(CosTheta*g)-(SinTheta*f); fd:=(SinTheta*g)+(CosTheta*f); x:=gd/(a+b); y:=(1.0/(2.0*fd))*(c-(sqr(gd)/(a+b))); Lambda:=-((a+b)/(2.0*fd)); PathSegment.ScalingFactor:=abs(1.0/Lambda); PathSegment.SquaredScalingFactor:=sqr(PathSegment.ScalingFactor); CosTheta:=CosTheta*Lambda; SinTheta:=SinTheta*Lambda; PathSegment.XFormMatrix[0]:=CosTheta; PathSegment.XFormMatrix[1]:=-SinTheta; PathSegment.XFormMatrix[2]:=x*Lambda; PathSegment.XFormMatrix[3]:=SinTheta; PathSegment.XFormMatrix[4]:=CosTheta; PathSegment.XFormMatrix[5]:=y*Lambda; end; end; PathSegment.NearlyZeroScaled:=DistanceField2DNearlyZeroValue/PathSegment.ScalingFactor; PathSegment.SquaredTangentToleranceScaled:=sqr(DistanceField2DTangentToleranceValue)/PathSegment.SquaredScalingFactor; PathSegment.P0T:=VectorMap(p0,PathSegment.XFormMatrix); PathSegment.P2T:=VectorMap(p2,PathSegment.XFormMatrix); end; procedure TpvSignedDistanceField2DGenerator.InitializeDistances; var Index:TpvInt32; begin for Index:=0 to length(fDistanceFieldData)-1 do begin fDistanceFieldData[Index].SquaredDistance:=sqr(DistanceField2DMagnitudeValue); fDistanceFieldData[Index].Distance:=DistanceField2DMagnitudeValue; fDistanceFieldData[Index].DeltaWindingScore:=0; end; end; function TpvSignedDistanceField2DGenerator.AddLineToPathSegmentArray(var Contour:TpvSignedDistanceField2DPathContour;const Points:array of TpvVectorPathVector):TpvInt32; var PathSegment:PpvSignedDistanceField2DPathSegment; begin Assert(length(Points)=2); result:=Contour.CountPathSegments; if not (SameValue(Points[0].x,Points[1].x) and SameValue(Points[0].y,Points[1].y)) then begin inc(Contour.CountPathSegments); if length(Contour.PathSegments)<=Contour.CountPathSegments then begin SetLength(Contour.PathSegments,Contour.CountPathSegments*2); end; PathSegment:=@Contour.PathSegments[result]; PathSegment^.Type_:=TpvSignedDistanceField2DPathSegmentType.Line; PathSegment^.Points[0]:=Points[0]; PathSegment^.Points[1]:=Points[1]; InitializePathSegment(PathSegment^); end; end; function TpvSignedDistanceField2DGenerator.AddQuadraticBezierCurveToPathSegmentArray(var Contour:TpvSignedDistanceField2DPathContour;const Points:array of TpvVectorPathVector):TpvInt32; var PathSegment:PpvSignedDistanceField2DPathSegment; begin Assert(length(Points)=3); result:=Contour.CountPathSegments; if (Points[0].DistanceSquared(Points[1])<DistanceField2DCloseSquaredValue) or (Points[1].DistanceSquared(Points[2])<DistanceField2DCloseSquaredValue) or IsColinear(Points) then begin if not (SameValue(Points[0].x,Points[2].x) and SameValue(Points[0].y,Points[2].y)) then begin inc(Contour.CountPathSegments); if length(Contour.PathSegments)<=Contour.CountPathSegments then begin SetLength(Contour.PathSegments,Contour.CountPathSegments*2); end; PathSegment:=@Contour.PathSegments[result]; PathSegment^.Type_:=TpvSignedDistanceField2DPathSegmentType.Line; PathSegment^.Points[0]:=Points[0]; PathSegment^.Points[1]:=Points[2]; InitializePathSegment(PathSegment^); end; end else begin inc(Contour.CountPathSegments); if length(Contour.PathSegments)<=Contour.CountPathSegments then begin SetLength(Contour.PathSegments,Contour.CountPathSegments*2); end; PathSegment:=@Contour.PathSegments[result]; PathSegment^.Type_:=TpvSignedDistanceField2DPathSegmentType.QuadraticBezierCurve; PathSegment^.Points[0]:=Points[0]; PathSegment^.Points[1]:=Points[1]; PathSegment^.Points[2]:=Points[2]; InitializePathSegment(PathSegment^); end; end; function TpvSignedDistanceField2DGenerator.CubeRoot(Value:TpvDouble):TpvDouble; begin if IsZero(Value) then begin result:=0.0; end else begin result:=exp(ln(abs(Value))/3.0); if Value<0.0 then begin result:=-result; end; end; end; function TpvSignedDistanceField2DGenerator.CalculateNearestPointForQuadraticBezierCurve(const PathSegment:TpvSignedDistanceField2DPathSegment;const XFormPoint:TpvVectorPathVector):TpvDouble; const OneDiv3=1.0/3.0; OneDiv27=1.0/27.0; var a,b,a3,b2,c,SqrtC,CosPhi,Phi:TpvDouble; begin a:=0.5-XFormPoint.y; b:=(-0.5)*XFormPoint.x; a3:=sqr(a)*a; b2:=sqr(b); c:=(b2*0.25)+(a3*OneDiv27); if c>=0.0 then begin SqrtC:=sqrt(c); b:=b*(-0.5); result:=CubeRoot(b+SqrtC)+CubeRoot(b-SqrtC); end else begin CosPhi:=sqrt((b2*0.25)*((-27.0)/a3)); if b>0.0 then begin CosPhi:=-CosPhi; end; Phi:=ArcCos(CosPhi); if XFormPoint.x>0.0 then begin result:=2.0*sqrt(a*(-OneDiv3))*cos(Phi*OneDiv3); if not BetweenClosed(result,PathSegment.P0T.x,PathSegment.P2T.x) then begin result:=2.0*sqrt(a*(-OneDiv3))*cos((Phi*OneDiv3)+(pi*2.0*OneDiv3)); end; end else begin result:=2.0*sqrt(a*(-OneDiv3))*cos((Phi*OneDiv3)+(pi*2.0*OneDiv3)); if not BetweenClosed(result,PathSegment.P0T.x,PathSegment.P2T.x) then begin result:=2.0*sqrt(a*(-OneDiv3))*cos(Phi*OneDiv3); end; end; end; end; procedure TpvSignedDistanceField2DGenerator.PrecomputationForRow(out RowData:TpvSignedDistanceField2DRowData;const PathSegment:TpvSignedDistanceField2DPathSegment;const PointLeft,PointRight:TpvVectorPathVector); var XFormPointLeft,XFormPointRight:TpvVectorPathVector; x0,y0,x1,y1,m,b,m2,c,Tolerance,d:TpvDouble; begin if PathSegment.Type_=TpvSignedDistanceField2DPathSegmentType.QuadraticBezierCurve then begin XFormPointLeft:=VectorMap(PointLeft,PathSegment.XFormMatrix); XFormPointRight:=VectorMap(PointRight,PathSegment.XFormMatrix); RowData.QuadraticXDirection:=SignOf(PathSegment.P2T.x-PathSegment.P0T.x); RowData.ScanlineXDirection:=SignOf(XFormPointRight.x-XFormPointLeft.x); x0:=XFormPointLeft.x; y0:=XFormPointLeft.y; x1:=XFormPointRight.x; y1:=XFormPointRight.y; if NearlyEqual(x0,x1,PathSegment.NearlyZeroScaled,true) then begin RowData.IntersectionType:=TpvSignedDistanceField2DRowDataIntersectionType.VerticalLine; RowData.YAtIntersection:=sqr(x0); RowData.ScanlineXDirection:=0; end else begin m:=(y1-y0)/(x1-x0); b:=y0-(m*x0); m2:=sqr(m); c:=m2+(4.0*b); Tolerance:=(4.0*PathSegment.SquaredTangentToleranceScaled)/(m2+1.0); if (RowData.ScanlineXDirection=1) and (SameValue(PathSegment.Points[0].y,PointLeft.y) or SameValue(PathSegment.Points[2].y,PointLeft.y)) and NearlyZero(c,Tolerance) then begin RowData.IntersectionType:=TpvSignedDistanceField2DRowDataIntersectionType.TangentLine; RowData.XAtIntersection[0]:=m*0.5; RowData.XAtIntersection[1]:=m*0.5; end else if c<=0.0 then begin RowData.IntersectionType:=TpvSignedDistanceField2DRowDataIntersectionType.NoIntersection; end else begin RowData.IntersectionType:=TpvSignedDistanceField2DRowDataIntersectionType.TwoPointsIntersect; d:=sqrt(c); RowData.XAtIntersection[0]:=(m+d)*0.5; RowData.XAtIntersection[1]:=(m-d)*0.5; end; end; end; end; function TpvSignedDistanceField2DGenerator.CalculateSideOfQuadraticBezierCurve(const PathSegment:TpvSignedDistanceField2DPathSegment;const Point,XFormPoint:TpvVectorPathVector;const RowData:TpvSignedDistanceField2DRowData):TpvSignedDistanceField2DPathSegmentSide; var p0,p1:TpvDouble; sp0,sp1:TpvInt32; ip0,ip1:boolean; begin case RowData.IntersectionType of TpvSignedDistanceField2DRowDataIntersectionType.VerticalLine:begin result:=TpvSignedDistanceField2DPathSegmentSide(TpvInt32(SignOf(XFormPoint.y-RowData.YAtIntersection)*RowData.QuadraticXDirection)); end; TpvSignedDistanceField2DRowDataIntersectionType.TwoPointsIntersect:begin result:=TpvSignedDistanceField2DPathSegmentSide.None; p0:=RowData.XAtIntersection[0]; p1:=RowData.XAtIntersection[1]; sp0:=SignOf(p0-XFormPoint.x); ip0:=true; ip1:=true; if RowData.ScanlineXDirection=1 then begin if ((RowData.QuadraticXDirection=-1) and (PathSegment.Points[0].y<=Point.y) and NearlyEqual(PathSegment.P0T.x,p0,PathSegment.NearlyZeroScaled,true)) or ((RowData.QuadraticXDirection=1) and (PathSegment.Points[2].y<=Point.y) and NearlyEqual(PathSegment.P2T.x,p0,PathSegment.NearlyZeroScaled,true)) then begin ip0:=false; end; if ((RowData.QuadraticXDirection=-1) and (PathSegment.Points[2].y<=Point.y) and NearlyEqual(PathSegment.P2T.x,p1,PathSegment.NearlyZeroScaled,true)) or ((RowData.QuadraticXDirection=1) and (PathSegment.Points[0].y<=Point.y) and NearlyEqual(PathSegment.P0T.x,p1,PathSegment.NearlyZeroScaled,true)) then begin ip1:=false; end; end; if ip0 and BetweenClosed(p0,PathSegment.P0T.x,PathSegment.P2T.x,PathSegment.NearlyZeroScaled,true) then begin result:=TpvSignedDistanceField2DPathSegmentSide(TpvInt32(sp0*RowData.QuadraticXDirection)); end; if ip1 and BetweenClosed(p1,PathSegment.P0T.x,PathSegment.P2T.x,PathSegment.NearlyZeroScaled,true) then begin sp1:=SignOf(p1-XFormPoint.x); if (result=TpvSignedDistanceField2DPathSegmentSide.None) or (sp1=1) then begin result:=TpvSignedDistanceField2DPathSegmentSide(TpvInt32(-sp1*RowData.QuadraticXDirection)); end; end; end; TpvSignedDistanceField2DRowDataIntersectionType.TangentLine:begin result:=TpvSignedDistanceField2DPathSegmentSide.None; if RowData.ScanlineXDirection=1 then begin if SameValue(PathSegment.Points[0].y,Point.y) then begin result:=TpvSignedDistanceField2DPathSegmentSide(TpvInt32(SignOf(RowData.XAtIntersection[0]-XFormPoint.x))); end else if SameValue(PathSegment.Points[2].y,Point.y) then begin result:=TpvSignedDistanceField2DPathSegmentSide(TpvInt32(SignOf(XFormPoint.x-RowData.XAtIntersection[0]))); end; end; end; else begin result:=TpvSignedDistanceField2DPathSegmentSide.None; end; end; end; function TpvSignedDistanceField2DGenerator.DistanceToPathSegment(const Point:TpvVectorPathVector;const PathSegment:TpvSignedDistanceField2DPathSegment;const RowData:TpvSignedDistanceField2DRowData;out PathSegmentSide:TpvSignedDistanceField2DPathSegmentSide):TpvDouble; var XFormPoint,x:TpvVectorPathVector; NearestPoint:TpvDouble; begin XFormPoint:=VectorMap(Point,PathSegment.XFormMatrix); case PathSegment.Type_ of TpvSignedDistanceField2DPathSegmentType.Line:begin if BetweenClosed(XFormPoint.x,PathSegment.P0T.x,PathSegment.P2T.x) then begin result:=sqr(XFormPoint.y); end else if XFormPoint.x<PathSegment.P0T.x then begin result:=sqr(XFormPoint.x)+sqr(XFormPoint.y); end else begin result:=sqr(XFormPoint.x-PathSegment.P2T.x)+sqr(XFormPoint.y); end; if BetweenClosedOpen(Point.y,PathSegment.BoundingBox.Min.y,PathSegment.BoundingBox.Max.y) then begin PathSegmentSide:=TpvSignedDistanceField2DPathSegmentSide(TpvInt32(SignOf(XFormPoint.y))); end else begin PathSegmentSide:=TpvSignedDistanceField2DPathSegmentSide.None; end; end; TpvSignedDistanceField2DPathSegmentType.QuadraticBezierCurve:begin NearestPoint:=CalculateNearestPointForQuadraticBezierCurve(PathSegment,XFormPoint); if BetweenClosed(NearestPoint,PathSegment.P0T.x,PathSegment.P2T.x) then begin x.x:=NearestPoint; x.y:=sqr(NearestPoint); result:=XFormPoint.DistanceSquared(x)*PathSegment.SquaredScalingFactor; end else begin result:=Min(XFormPoint.DistanceSquared(PathSegment.P0T),XFormPoint.DistanceSquared(PathSegment.P2T))*PathSegment.SquaredScalingFactor; end; if BetweenClosedOpen(Point.y,PathSegment.BoundingBox.Min.y,PathSegment.BoundingBox.Max.y) then begin PathSegmentSide:=CalculateSideOfQuadraticBezierCurve(PathSegment,Point,XFormPoint,RowData); end else begin PathSegmentSide:=TpvSignedDistanceField2DPathSegmentSide.None; end; end; else begin PathSegmentSide:=TpvSignedDistanceField2DPathSegmentSide.None; result:=0.0; end; end; end; procedure TpvSignedDistanceField2DGenerator.ConvertShape(const DoSubdivideCurvesIntoLines:boolean); var LocalVectorPathShape:TpvVectorPathShape; LocalVectorPathContour:TpvVectorPathContour; LocalVectorPathSegment:TpvVectorPathSegment; Contour:PpvSignedDistanceField2DPathContour; Scale,Translate:TpvVectorPathVector; begin Scale:=TpvVectorPathVector.Create(fScale*DistanceField2DRasterizerToScreenScale); Translate:=TpvVectorPathVector.Create(fOffsetX,fOffsetY); LocalVectorPathShape:=TpvVectorPathShape.Create(fVectorPathShape); try if DoSubdivideCurvesIntoLines then begin LocalVectorPathShape.ConvertCurvesToLines; end else begin LocalVectorPathShape.ConvertCubicCurvesToQuadraticCurves; end; fShape.Contours:=nil; fShape.CountContours:=0; try for LocalVectorPathContour in LocalVectorPathShape.Contours do begin if length(fShape.Contours)<(fShape.CountContours+1) then begin SetLength(fShape.Contours,(fShape.CountContours+1)*2); end; Contour:=@fShape.Contours[fShape.CountContours]; inc(fShape.CountContours); try for LocalVectorPathSegment in LocalVectorPathContour.Segments do begin case LocalVectorPathSegment.Type_ of TpvVectorPathSegmentType.Line:begin AddLineToPathSegmentArray(Contour^,[(TpvVectorPathSegmentLine(LocalVectorPathSegment).Points[0]*Scale)+Translate, (TpvVectorPathSegmentLine(LocalVectorPathSegment).Points[1]*Scale)+Translate]); end; TpvVectorPathSegmentType.QuadraticCurve:begin AddQuadraticBezierCurveToPathSegmentArray(Contour^,[(TpvVectorPathSegmentQuadraticCurve(LocalVectorPathSegment).Points[0]*Scale)+Translate, (TpvVectorPathSegmentQuadraticCurve(LocalVectorPathSegment).Points[1]*Scale)+Translate, (TpvVectorPathSegmentQuadraticCurve(LocalVectorPathSegment).Points[2]*Scale)+Translate]); end; TpvVectorPathSegmentType.CubicCurve:begin raise Exception.Create('Ups?!'); end; end; end; finally SetLength(Contour^.PathSegments,Contour^.CountPathSegments); end; end; finally SetLength(fShape.Contours,fShape.CountContours); end; finally FreeAndNil(LocalVectorPathShape); end; end; function TpvSignedDistanceField2DGenerator.ConvertShapeToMSDFShape:TpvSignedDistanceField2DMSDFGenerator.TShape; var ContourIndex,EdgeIndex:TpvSizeInt; SrcContour:PpvSignedDistanceField2DPathContour; DstContour:TpvSignedDistanceField2DMSDFGenerator.PContour; SrcPathSegment:PpvSignedDistanceField2DPathSegment; DstEdge:TpvSignedDistanceField2DMSDFGenerator.PEdgeSegment; begin result:=TpvSignedDistanceField2DMSDFGenerator.TShape.Create; result.Contours:=nil; SetLength(result.Contours,fShape.CountContours); result.Count:=fShape.CountContours; for ContourIndex:=0 to fShape.CountContours-1 do begin SrcContour:=@fShape.Contours[ContourIndex]; DstContour:=@result.Contours[ContourIndex]; DstContour^.Edges:=nil; SetLength(DstContour^.Edges,SrcContour^.CountPathSegments); DstContour^.Count:=SrcContour^.CountPathSegments; DstContour^.CachedWinding:=Low(TpvSizeInt); for EdgeIndex:=0 to SrcContour^.CountPathSegments-1 do begin SrcPathSegment:=@SrcContour^.PathSegments[EdgeIndex]; DstEdge:=@DstContour.Edges[EdgeIndex]; case SrcPathSegment^.Type_ of TpvSignedDistanceField2DPathSegmentType.Line:begin DstEdge^:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(TpvVectorPathVector.Create(SrcPathSegment^.Points[0].x,SrcPathSegment^.Points[0].y),TpvVectorPathVector.Create(SrcPathSegment^.Points[1].x,SrcPathSegment^.Points[1].y)); end; else {TpvSignedDistanceField2DPathSegmentType.QuadraticBezierCurve:}begin DstEdge^:=TpvSignedDistanceField2DMSDFGenerator.TEdgeSegment.Create(TpvVectorPathVector.Create(SrcPathSegment^.Points[0].x,SrcPathSegment^.Points[0].y),TpvVectorPathVector.Create(SrcPathSegment^.Points[1].x,SrcPathSegment^.Points[1].y),TpvVectorPathVector.Create(SrcPathSegment^.Points[2].x,SrcPathSegment^.Points[2].y)); end; end; end; DstContour^.Winding; end; result.Normalize; end; procedure TpvSignedDistanceField2DGenerator.CalculateDistanceFieldDataLineRange(const FromY,ToY:TpvInt32); var ContourIndex,PathSegmentIndex,x0,y0,x1,y1,x,y,PixelIndex,Dilation,DeltaWindingScore:TpvInt32; Contour:PpvSignedDistanceField2DPathContour; PathSegment:PpvSignedDistanceField2DPathSegment; PathSegmentBoundingBox:TpvSignedDistanceField2DBoundingBox; PreviousPathSegmentSide,PathSegmentSide:TpvSignedDistanceField2DPathSegmentSide; RowData:TpvSignedDistanceField2DRowData; DistanceFieldDataItem:PpvSignedDistanceField2DDataItem; PointLeft,PointRight,Point,p0,p1,Direction,OriginPointDifference:TpvVectorPathVector; pX,pY,CurrentSquaredDistance,CurrentSquaredPseudoDistance,Time,Value,oX,oY:TpvDouble; begin GetOffset(oX,oY); RowData.QuadraticXDirection:=0; for ContourIndex:=0 to fShape.CountContours-1 do begin Contour:=@fShape.Contours[ContourIndex]; for PathSegmentIndex:=0 to Contour^.CountPathSegments-1 do begin PathSegment:=@Contour^.PathSegments[PathSegmentIndex]; PathSegmentBoundingBox.Min.x:=PathSegment.BoundingBox.Min.x-DistanceField2DPadValue; PathSegmentBoundingBox.Min.y:=PathSegment.BoundingBox.Min.y-DistanceField2DPadValue; PathSegmentBoundingBox.Max.x:=PathSegment.BoundingBox.Max.x+DistanceField2DPadValue; PathSegmentBoundingBox.Max.y:=PathSegment.BoundingBox.Max.y+DistanceField2DPadValue; x0:=Clamp(Trunc(Floor(PathSegmentBoundingBox.Min.x)),0,fDistanceField.Width-1); y0:=Clamp(Trunc(Floor(PathSegmentBoundingBox.Min.y)),0,fDistanceField.Height-1); x1:=Clamp(Trunc(Ceil(PathSegmentBoundingBox.Max.x)),0,fDistanceField.Width-1); y1:=Clamp(Trunc(Ceil(PathSegmentBoundingBox.Max.y)),0,fDistanceField.Height-1); { x0:=0; y0:=0; x1:=DistanceField.Width-1; y1:=DistanceField.Height-1;} for y:=Max(FromY,y0) to Min(ToY,y1) do begin PreviousPathSegmentSide:=TpvSignedDistanceField2DPathSegmentSide.None; pY:=y+oY+0.5; PointLeft.x:=x0; PointLeft.y:=pY; PointRight.x:=x1; PointRight.y:=pY; if BetweenClosedOpen(pY,PathSegment.BoundingBox.Min.y,PathSegment.BoundingBox.Max.y) then begin PrecomputationForRow(RowData,PathSegment^,PointLeft,PointRight); end; for x:=x0 to x1 do begin PixelIndex:=(y*fDistanceField.Width)+x; pX:=x+oX+0.5; Point.x:=pX; Point.y:=pY; DistanceFieldDataItem:=@fDistanceFieldData[PixelIndex]; Dilation:=Clamp(Floor(sqrt(Max(1,DistanceFieldDataItem^.SquaredDistance))+0.5),1,DistanceField2DPadValue); PathSegmentBoundingBox.Min.x:=Floor(PathSegment.BoundingBox.Min.x)-DistanceField2DPadValue; PathSegmentBoundingBox.Min.y:=Floor(PathSegment.BoundingBox.Min.y)-DistanceField2DPadValue; PathSegmentBoundingBox.Max.x:=Ceil(PathSegment.BoundingBox.Max.x)+DistanceField2DPadValue; PathSegmentBoundingBox.Max.y:=Ceil(PathSegment.BoundingBox.Max.y)+DistanceField2DPadValue; if (Dilation<>DistanceField2DPadValue) and not (((x>=PathSegmentBoundingBox.Min.x) and (x<=PathSegmentBoundingBox.Max.x)) and ((y>=PathSegmentBoundingBox.Min.y) and (y<=PathSegmentBoundingBox.Max.y))) then begin continue; end else begin PathSegmentSide:=TpvSignedDistanceField2DPathSegmentSide.None; CurrentSquaredDistance:=DistanceToPathSegment(Point,PathSegment^,RowData,PathSegmentSide); CurrentSquaredPseudoDistance:=CurrentSquaredDistance; if (PreviousPathSegmentSide=TpvSignedDistanceField2DPathSegmentSide.Left) and (PathSegmentSide=TpvSignedDistanceField2DPathSegmentSide.Right) then begin DeltaWindingScore:=-1; end else if (PreviousPathSegmentSide=TpvSignedDistanceField2DPathSegmentSide.Right) and (PathSegmentSide=TpvSignedDistanceField2DPathSegmentSide.Left) then begin DeltaWindingScore:=1; end else begin DeltaWindingScore:=0; end; PreviousPathSegmentSide:=PathSegmentSide; if CurrentSquaredDistance<DistanceFieldDataItem^.SquaredDistance then begin DistanceFieldDataItem^.SquaredDistance:=CurrentSquaredDistance; end; inc(DistanceFieldDataItem^.DeltaWindingScore,DeltaWindingScore); end; end; end; end; end; end; procedure TpvSignedDistanceField2DGenerator.CalculateDistanceFieldDataLineRangeParallelForJobFunction(const Job:PPasMPJob;const ThreadIndex:TPasMPInt32;const Data:TpvPointer;const FromIndex,ToIndex:TPasMPNativeInt); begin CalculateDistanceFieldDataLineRange(FromIndex,ToIndex); end; function TpvSignedDistanceField2DGenerator.PackDistanceFieldValue(Distance:TpvDouble):TpvUInt8; begin result:=Clamp(Round((Distance*(128.0/DistanceField2DMagnitudeValue))+128.0),0,255); end; function TpvSignedDistanceField2DGenerator.PackPseudoDistanceFieldValue(Distance:TpvDouble):TpvUInt8; begin result:=Clamp(Round((Distance*(128.0/DistanceField2DMagnitudeValue))+128.0),0,255); end; procedure TpvSignedDistanceField2DGenerator.ConvertToPointInPolygonPathSegments; var ContourIndex,PathSegmentIndex,CountPathSegments:TpvInt32; Contour:PpvSignedDistanceField2DPathContour; PathSegment:PpvSignedDistanceField2DPathSegment; StartPoint,LastPoint:TpvVectorPathVector; procedure AddPathSegment(const p0,p1:TpvVectorPathVector); var Index:TpvInt32; PointInPolygonPathSegment:PpvSignedDistanceField2DPointInPolygonPathSegment; begin if not (SameValue(p0.x,p1.x) and SameValue(p0.y,p1.y)) then begin Index:=CountPathSegments; inc(CountPathSegments); if length(fPointInPolygonPathSegments)<CountPathSegments then begin SetLength(fPointInPolygonPathSegments,CountPathSegments*2); end; PointInPolygonPathSegment:=@fPointInPolygonPathSegments[Index]; PointInPolygonPathSegment^.Points[0]:=p0; PointInPolygonPathSegment^.Points[1]:=p1; end; end; procedure AddQuadraticBezierCurveAsSubdividedLinesToPathSegmentArray(const p0,p1,p2:TpvVectorPathVector); var LastPoint:TpvVectorPathVector; procedure LineToPointAt(const Point:TpvVectorPathVector); begin AddPathSegment(LastPoint,Point); LastPoint:=Point; end; procedure Recursive(const x1,y1,x2,y2,x3,y3:TpvDouble;const Level:TpvInt32); var x12,y12,x23,y23,x123,y123,dx,dy:TpvDouble; Point:TpvVectorPathVector; begin x12:=(x1+x2)*0.5; y12:=(y1+y2)*0.5; x23:=(x2+x3)*0.5; y23:=(y2+y3)*0.5; x123:=(x12+x23)*0.5; y123:=(y12+y23)*0.5; dx:=x3-x1; dy:=y3-y1; if (Level>CurveRecursionLimit) or ((Level>0) and (sqr(((x2-x3)*dy)-((y2-y3)*dx))<((sqr(dx)+sqr(dy))*CurveTessellationToleranceSquared))) then begin Point.x:=x3; Point.y:=y3; LineToPointAt(Point); end else begin Recursive(x1,y1,x12,y12,x123,y123,Level+1); Recursive(x123,y123,x23,y23,x3,y3,Level+1); end; end; begin LastPoint:=p0; Recursive(p0.x,p0.y,p1.x,p1.y,p2.x,p2.y,0); LineToPointAt(p2); end; begin fPointInPolygonPathSegments:=nil; CountPathSegments:=0; try for ContourIndex:=0 to fShape.CountContours-1 do begin Contour:=@fShape.Contours[ContourIndex]; if Contour^.CountPathSegments>0 then begin StartPoint.x:=0.0; StartPoint.y:=0.0; LastPoint.x:=0.0; LastPoint.y:=0.0; for PathSegmentIndex:=0 to Contour^.CountPathSegments-1 do begin PathSegment:=@Contour^.PathSegments[PathSegmentIndex]; case PathSegment^.Type_ of TpvSignedDistanceField2DPathSegmentType.Line:begin if PathSegmentIndex=0 then begin StartPoint:=PathSegment^.Points[0]; end; LastPoint:=PathSegment^.Points[1]; AddPathSegment(PathSegment^.Points[0],PathSegment^.Points[1]); end; TpvSignedDistanceField2DPathSegmentType.QuadraticBezierCurve:begin if PathSegmentIndex=0 then begin StartPoint:=PathSegment^.Points[0]; end; LastPoint:=PathSegment^.Points[2]; AddQuadraticBezierCurveAsSubdividedLinesToPathSegmentArray(PathSegment^.Points[0],PathSegment^.Points[1],PathSegment^.Points[2]); end; end; end; if not (SameValue(LastPoint.x,StartPoint.x) and SameValue(LastPoint.y,StartPoint.y)) then begin AddPathSegment(LastPoint,StartPoint); end; end; end; finally SetLength(fPointInPolygonPathSegments,CountPathSegments); end; end; function TpvSignedDistanceField2DGenerator.GetWindingNumberAtPointInPolygon(const Point:TpvVectorPathVector):TpvInt32; var Index,CaseIndex:TpvInt32; PointInPolygonPathSegment:PpvSignedDistanceField2DPointInPolygonPathSegment; x0,y0,x1,y1:TpvDouble; begin result:=0; for Index:=0 to length(fPointInPolygonPathSegments)-1 do begin PointInPolygonPathSegment:=@fPointInPolygonPathSegments[Index]; if not (SameValue(PointInPolygonPathSegment^.Points[0].x,PointInPolygonPathSegment^.Points[1].x) and SameValue(PointInPolygonPathSegment^.Points[0].y,PointInPolygonPathSegment^.Points[1].y)) then begin y0:=PointInPolygonPathSegment^.Points[0].y-Point.y; y1:=PointInPolygonPathSegment^.Points[1].y-Point.y; if y0<0.0 then begin CaseIndex:=0; end else if y0>0.0 then begin CaseIndex:=2; end else begin CaseIndex:=1; end; if y1<0.0 then begin inc(CaseIndex,0); end else if y1>0.0 then begin inc(CaseIndex,6); end else begin inc(CaseIndex,3); end; if CaseIndex in [1,2,3,6] then begin x0:=PointInPolygonPathSegment^.Points[0].x-Point.x; x1:=PointInPolygonPathSegment^.Points[1].x-Point.x; if not (((x0>0.0) and (x1>0.0)) or ((not ((x0<=0.0) and (x1<=0.0))) and ((x0-(y0*((x1-x0)/(y1-y0))))>0.0))) then begin if CaseIndex in [1,2] then begin inc(result); end else begin dec(result); end; end; end; end; end; end; function TpvSignedDistanceField2DGenerator.GenerateDistanceFieldPicture(const DistanceFieldData:TpvSignedDistanceField2DData;const Width,Height,TryIteration:TpvInt32):boolean; var x,y,PixelIndex,DistanceFieldSign,WindingNumber,Value:TpvInt32; DistanceFieldDataItem:PpvSignedDistanceField2DDataItem; DistanceFieldPixel:PpvSignedDistanceField2DPixel; p:TpvVectorPathVector; oX,oY,SignedDistance:TpvDouble; begin result:=true; GetOffset(oX,oY); PixelIndex:=0; for y:=0 to Height-1 do begin WindingNumber:=0; for x:=0 to Width-1 do begin DistanceFieldDataItem:=@DistanceFieldData[PixelIndex]; if TryIteration=2 then begin p.x:=x+oX+0.5; p.y:=y+oY+0.5; WindingNumber:=GetWindingNumberAtPointInPolygon(p); end else begin inc(WindingNumber,DistanceFieldDataItem^.DeltaWindingScore); if (x=(Width-1)) and (WindingNumber<>0) then begin result:=false; break; end; end; case fVectorPathShape.FillRule of TpvVectorPathFillRule.NonZero:begin if WindingNumber<>0 then begin DistanceFieldSign:=1; end else begin DistanceFieldSign:=-1; end; end; else {TpvVectorPathFillRule.EvenOdd:}begin if (WindingNumber and 1)<>0 then begin DistanceFieldSign:=1; end else begin DistanceFieldSign:=-1; end; end; end; DistanceFieldPixel:=@fDistanceField^.Pixels[PixelIndex]; case fVariant of TpvSignedDistanceField2DVariant.MSDF:begin if assigned(fMSDFImage) then begin SignedDistance:=TpvSignedDistanceField2DMSDFGenerator.Median(fMSDFImage^.Pixels[PixelIndex].r,fMSDFImage^.Pixels[PixelIndex].g,fMSDFImage^.Pixels[PixelIndex].b); if SameValue(SignedDistance,0.5) then begin fMSDFAmbiguous:=true; fMSDFMatches[PixelIndex]:=0; end else if TpvSignedDistanceField2DMSDFGenerator.Sign(SignedDistance-0.5)<>DistanceFieldSign then begin fMSDFImage.Pixels[PixelIndex].r:=0.5-(fMSDFImage.Pixels[PixelIndex].r-0.5); fMSDFImage.Pixels[PixelIndex].g:=0.5-(fMSDFImage.Pixels[PixelIndex].g-0.5); fMSDFImage.Pixels[PixelIndex].b:=0.5-(fMSDFImage.Pixels[PixelIndex].b-0.5); fMSDFMatches[PixelIndex]:=-1; end else begin fMSDFMatches[PixelIndex]:=1; end; if TpvSignedDistanceField2DMSDFGenerator.Sign(fMSDFImage^.Pixels[PixelIndex].a-0.5)<>DistanceFieldSign then begin fMSDFImage^.Pixels[PixelIndex].a:=0.5-(fMSDFImage.Pixels[PixelIndex].a-0.5); end; end; end; TpvSignedDistanceField2DVariant.GSDF:begin case fColorChannelIndex of 1:begin DistanceFieldPixel^.g:=PackDistanceFieldValue((sqrt(DistanceFieldDataItem^.SquaredDistance)*DistanceFieldSign)-DistanceFieldDataItem^.Distance); end; 2:begin DistanceFieldPixel^.b:=PackDistanceFieldValue((sqrt(DistanceFieldDataItem^.SquaredDistance)*DistanceFieldSign)-DistanceFieldDataItem^.Distance); end; else {0:}begin DistanceFieldDataItem^.Distance:=sqrt(DistanceFieldDataItem^.SquaredDistance)*DistanceFieldSign; Value:=PackDistanceFieldValue(DistanceFieldDataItem^.Distance); DistanceFieldPixel^.r:=Value; DistanceFieldPixel^.g:=Value; DistanceFieldPixel^.b:=Value; DistanceFieldPixel^.a:=Value; end; end; end; TpvSignedDistanceField2DVariant.SSAASDF:begin Value:=PackDistanceFieldValue(sqrt(DistanceFieldDataItem^.SquaredDistance)*DistanceFieldSign); case fColorChannelIndex of 0:begin DistanceFieldPixel^.r:=Value; end; 1:begin DistanceFieldPixel^.g:=Value; end; 2:begin DistanceFieldPixel^.b:=Value; end; else {3:}begin DistanceFieldPixel^.a:=Value; end; end; end; else begin Value:=PackDistanceFieldValue(sqrt(DistanceFieldDataItem^.SquaredDistance)*DistanceFieldSign); DistanceFieldPixel^.r:=Value; DistanceFieldPixel^.g:=Value; DistanceFieldPixel^.b:=Value; DistanceFieldPixel^.a:=Value; end; end; inc(PixelIndex); end; if not result then begin break; end; end; end; procedure TpvSignedDistanceField2DGenerator.Execute(var aDistanceField:TpvSignedDistanceField2D;const aVectorPathShape:TpvVectorPathShape;const aScale:TpvDouble;const aOffsetX:TpvDouble;const aOffsetY:TpvDouble;const aVariant:TpvSignedDistanceField2DVariant;const aProtectBorder:boolean); var PasMPInstance:TPasMP; procedure Generate; var TryIteration,ColorChannelIndex,CountColorChannels:TpvInt32; OK:boolean; begin case aVariant of TpvSignedDistanceField2DVariant.GSDF:begin CountColorChannels:=3; end; TpvSignedDistanceField2DVariant.SSAASDF:begin CountColorChannels:=4; end; else begin CountColorChannels:=1; end; end; fDistanceFieldData:=nil; try SetLength(fDistanceFieldData,fDistanceField.Width*fDistanceField.Height); try Initialize(fShape); try fPointInPolygonPathSegments:=nil; try for TryIteration:=0 to 2 do begin case TryIteration of 0,1:begin InitializeDistances; ConvertShape(TryIteration in [1,2]); end; else {2:}begin InitializeDistances; ConvertShape(true); ConvertToPointInPolygonPathSegments; end; end; OK:=true; for ColorChannelIndex:=0 to CountColorChannels-1 do begin fColorChannelIndex:=ColorChannelIndex; PasMPInstance.Invoke(PasMPInstance.ParallelFor(nil,0,fDistanceField.Height-1,CalculateDistanceFieldDataLineRangeParallelForJobFunction,1,10,nil,0)); if not GenerateDistanceFieldPicture(fDistanceFieldData,fDistanceField.Width,fDistanceField.Height,TryIteration) then begin OK:=false; break; end; end; if OK then begin break; end else begin // Try it again, after all quadratic bezier curves were subdivided into lines at the next try iteration end; end; finally fPointInPolygonPathSegments:=nil; end; finally Finalize(fShape); end; finally fDistanceField:=nil; end; finally fDistanceFieldData:=nil; end; end; procedure GenerateMSDF; var x,y,NeighbourMatch:TpvSizeInt; MSDFShape:TpvSignedDistanceField2DMSDFGenerator.TShape; MSDFImage:TpvSignedDistanceField2DMSDFGenerator.TImage; sp:TpvSignedDistanceField2DMSDFGenerator.PPixel; dp:PpvSignedDistanceField2DPixel; begin MSDFImage.Pixels:=nil; try MSDFImage.Width:=aDistanceField.Width; MSDFImage.Height:=aDistanceField.Height; SetLength(MSDFImage.Pixels,MSDFImage.Width*MSDFImage.Height); FillChar(MSDFImage.Pixels[0],MSDFImage.Width*MSDFImage.Height*SizeOf(TpvSignedDistanceField2DMSDFGenerator.TPixel),#0); Initialize(fShape); try ConvertShape(false); MSDFShape:=ConvertShapeToMSDFShape; try TpvSignedDistanceField2DMSDFGenerator.EdgeColoringSimple(MSDFShape,3,0); TpvSignedDistanceField2DMSDFGenerator.GenerateDistanceField(MSDFImage,MSDFShape,VulkanDistanceField2DSpreadValue,TpvVectorPathVector.Create(1.0,1.0),TpvVectorPathVector.Create(0.0,0.0)); finally MSDFShape.Contours:=nil; end; finally Finalize(fShape); end; TpvSignedDistanceField2DMSDFGenerator.ErrorCorrection(MSDFImage,TpvVectorPathVector.Create(1.001/VulkanDistanceField2DSpreadValue)); fMSDFShape:=@MSDFShape; fMSDFImage:=@MSDFImage; fMSDFAmbiguous:=false; fMSDFMatches:=nil; try SetLength(fMSDFMatches,MSDFImage.Width*MSDFImage.Height); Generate; if fMSDFAmbiguous then begin for y:=0 to MSDFImage.Height-1 do begin for x:=0 to MSDFImage.Width-1 do begin if fMSDFMatches[(y*MSDFImage.Width)+x]=0 then begin NeighbourMatch:=0; if x>0 then begin inc(NeighbourMatch,fMSDFMatches[(y*MSDFImage.Width)+(x-1)]); end; if x<(MSDFImage.Width-1) then begin inc(NeighbourMatch,fMSDFMatches[(y*MSDFImage.Width)+(x+1)]); end; if y>0 then begin inc(NeighbourMatch,fMSDFMatches[((y-1)*MSDFImage.Width)+x]); end; if y<(MSDFImage.Height-1) then begin inc(NeighbourMatch,fMSDFMatches[((y+1)*MSDFImage.Width)+x]); end; if NeighbourMatch<0 then begin sp:=@MSDFImage.Pixels[(y*MSDFImage.Width)+x]; sp^.r:=0.5-(sp^.r-0.5); sp^.g:=0.5-(sp^.g-0.5); sp^.b:=0.5-(sp^.b-0.5); end; end; end; end; end; finally fMSDFMatches:=nil; end; fMSDFImage:=nil; fMSDFShape:=nil; sp:=@MSDFImage.Pixels[0]; dp:=@aDistanceField.Pixels[0]; for y:=0 to MSDFImage.Height-1 do begin for x:=0 to MSDFImage.Width-1 do begin dp^.r:=Min(Max(Round(sp^.r*256),0),255); dp^.g:=Min(Max(Round(sp^.g*256),0),255); dp^.b:=Min(Max(Round(sp^.b*256),0),255); dp^.a:=Min(Max(Round(sp^.a*256),0),255); inc(sp); inc(dp); end; end; finally MSDFImage.Pixels:=nil; end; end; var x,y:TpvSizeInt; begin PasMPInstance:=TPasMP.GetGlobalInstance; fDistanceField:=@aDistanceField; fVectorPathShape:=aVectorPathShape; fScale:=aScale; fOffsetX:=aOffsetX; fOffsetY:=aOffsetY; fVariant:=aVariant; try case aVariant of TpvSignedDistanceField2DVariant.MSDF:begin GenerateMSDF; end; else begin fMSDFShape:=nil; fMSDFImage:=nil; Generate; end; end; finally fVectorPathShape:=nil; end; if aProtectBorder and (aDistanceField.Width>=4) and (aDistanceField.Height>=4) then begin for y:=0 to aDistanceField.Height-1 do begin aDistanceField.Pixels[(y*aDistanceField.Width)+0]:=aDistanceField.Pixels[(y*aDistanceField.Width)+1]; aDistanceField.Pixels[(y*aDistanceField.Width)+(aDistanceField.Width-1)]:=aDistanceField.Pixels[(y*aDistanceField.Width)+(aDistanceField.Width-2)]; end; for x:=0 to aDistanceField.Width-1 do begin aDistanceField.Pixels[(aDistanceField.Width*0)+x]:=aDistanceField.Pixels[(aDistanceField.Width*1)+x]; aDistanceField.Pixels[(aDistanceField.Width*(aDistanceField.Height-1))+x]:=aDistanceField.Pixels[(aDistanceField.Width*(aDistanceField.Height-2))+x]; end; end; end; class procedure TpvSignedDistanceField2DGenerator.Generate(var aDistanceField:TpvSignedDistanceField2D;const aVectorPathShape:TpvVectorPathShape;const aScale:TpvDouble;const aOffsetX:TpvDouble;const aOffsetY:TpvDouble;const aVariant:TpvSignedDistanceField2DVariant;const aProtectBorder:boolean); var Generator:TpvSignedDistanceField2DGenerator; begin Generator:=TpvSignedDistanceField2DGenerator.Create; try Generator.Execute(aDistanceField,aVectorPathShape,aScale,aOffsetX,aOffsetY,aVariant,aProtectBorder); finally Generator.Free; end; end; end.
// Sorting demo program Sort; const DataLength = 60; type TNumber = Integer; TData = array [1..DataLength] of TNumber; PData = ^TData; procedure Swap(var x, y: TNumber); var buf: TNumber; begin buf := x; x := y; y := buf; end; function Partition(var data: TData; len: Integer): Integer; var pivot: TNumber; pivotIndex, i: Integer; begin pivot := data[len]; pivotIndex := 1; for i := 1 to len do if data[i] < pivot then begin Swap(data[pivotIndex], data[i]); Inc(pivotIndex); end; {if} Swap(data[len], data[pivotIndex]); Result := pivotIndex; end; procedure QuickSort(var data: TData; len: Integer); var pivotIndex: Integer; dataShiftedPtr: PData; begin if len > 1 then begin pivotIndex := Partition(data, len); dataShiftedPtr := PData(@data[pivotIndex + 1]); QuickSort(data, pivotIndex - 1 ); QuickSort(dataShiftedPtr^, len - pivotIndex); end; // if end; procedure BubbleSort(var data: TData; len: Integer); var changed: Boolean; i: Integer; begin repeat changed := FALSE; for i := 1 to len - 1 do if data[i + 1] < data[i] then begin Swap(data[i + 1], data[i]); changed := TRUE; end; until not changed; end; procedure SelectionSort(var data: TData; len: Integer); var i, j, extrIndex: Integer; extr: TNumber; begin for i := 1 to len do begin extr := data[i]; extrIndex := i; for j := i + 1 to len do if data[j] < extr then begin extr := data[j]; extrIndex := j; end; Swap(data[i], data[extrIndex]); end; // for end; var RandomData: TData; i: Integer; Method: Char; begin WriteLn; WriteLn('Sorting demo'); WriteLn; WriteLn('Initial array: '); WriteLn; Randomize; for i := 1 to DataLength do begin RandomData[i] := Round((Random - 0.5) * 1000000); Write(RandomData[i]); if i mod 4 <> 0 then Write(#9) else WriteLn; end; WriteLn; WriteLn; Write('Select method (Q - quick, B - bubble, S - selection): '); Read(Method); WriteLn; WriteLn; case Method of 'Q', 'q': begin WriteLn('Quick sorting'); QuickSort(RandomData, DataLength); end; 'B', 'b': begin WriteLn('Bubble sorting'); BubbleSort(RandomData, DataLength); end; 'S', 's': begin WriteLn('Selection sorting'); SelectionSort(RandomData, DataLength); end else WriteLn('Sorting method is not selected.'); ReadLn; Halt; end; WriteLn; WriteLn('Sorted array: '); WriteLn; for i := 1 to DataLength do begin Write(RandomData[i]); if i mod 4 <> 0 then Write(#9) else WriteLn; end; WriteLn; WriteLn; WriteLn('Done.'); ReadLn; end.
unit PhysRod; {$WARN SYMBOL_PLATFORM OFF} interface uses Windows, ActiveX, Classes, ComObj, Phys_TLB, StdVcl, Math; type TPhysRod = class(TTypedComObject, IPhysRod) private fLength: Single; fRadius: Single; fPoisson: Single; fRigidity: Single; procedure UpdateRigidity(); protected function Get_Length: Single; stdcall; function Set_Length(Value: Single): HResult; stdcall; function Get_Radius: Single; stdcall; function Set_Radius(Value: Single): HResult; stdcall; function Get_Poisson: Single; stdcall; function Set_Poisson(Value: Single): HResult; stdcall; function Get_Rigidity: Single; stdcall; public constructor Create(); end; implementation uses ComServ; constructor TPhysRod.Create(); begin inherited Create(); fLength := 1.0; fRadius := 0.01; fPoisson := 0.28; UpdateRigidity(); end; function TPhysRod.Get_Length: Single; begin Result := fLength; end; function TPhysRod.Set_Length(Value: Single): HResult; begin fLength := Value; UpdateRigidity(); Result := S_OK; end; function TPhysRod.Get_Radius: Single; begin Result := fRadius; end; function TPhysRod.Set_Radius(Value: Single): HResult; begin fRadius := Value; UpdateRigidity(); Result := S_OK; end; function TPhysRod.Get_Poisson: Single; begin Result := fPoisson; end; function TPhysRod.Set_Poisson(Value: Single): HResult; begin fPoisson := Value; UpdateRigidity(); Result := S_OK; end; function TPhysRod.Get_Rigidity: Single; begin Result := fRigidity; end; procedure TPhysRod.UpdateRigidity(); var G, J: Single; begin G := 2E11 / (2 * (1 + fPoisson)); J := Pi * Power((2 * fRadius), 4.0) / 32.0; fRigidity := G * J / fLength; end; initialization TTypedComObjectFactory.Create(ComServer, TPhysRod, Class_PhysRod, ciMultiInstance, tmApartment); end.
uses Actor; type TNpcActor = class (TActor) private m_nEffX :Integer; //0x240 m_nEffY :Integer; //0x244 m_bo248 :Boolean; //0x248 m_dwUseEffectTick :LongWord; //0x24C m_EffSurface :TDirectDrawSurface; //0x250 public constructor Create; override; procedure Run; override; procedure CalcActorFrame; override; function GetDefaultFrame (wmode: Boolean): integer; override; procedure LoadSurface; override; procedure DrawChr (dsurface: TDirectDrawSurface; dx, dy: integer; blend: Boolean;boFlag:Boolean); override; procedure DrawEff (dsurface: TDirectDrawSurface; dx, dy: integer); override; end; implementation {============================== NPCActor =============================} procedure TNpcActor.CalcActorFrame; var Pm:pTMonsterAction; HairCount:Integer; begin m_boUseMagic :=False; m_nCurrentFrame :=-1; m_nBodyOffset :=GetNpcOffset(m_wAppearance); { if m_btRace = 50 then //NPC m_nBodyOffset := MERCHANTFRAME * m_wAppearance; } Pm:=GetRaceByPM(m_btRace,m_wAppearance); if pm = nil then exit; m_btDir := m_btDir mod 3; //规氢篮 0, 1, 2 观俊 绝澜.. case m_nCurrentAction of SM_TURN: begin m_nStartFrame := pm.ActStand.start + m_btDir * (pm.ActStand.frame + pm.ActStand.skip); m_nEndFrame := m_nStartFrame + pm.ActStand.frame - 1; m_dwFrameTime := pm.ActStand.ftime; m_dwStartTime := GetTickCount; m_nDefFrameCount := pm.ActStand.frame; Shift (m_btDir, 0, 0, 1); if ((m_wAppearance = 33) or (m_wAppearance = 34))and not m_boUseEffect then begin m_boUseEffect:=True; m_nEffectFrame:=m_nEffectStart; m_nEffectEnd:=m_nEffectStart + 9; m_dwEffectStartTime:=GetTickCount(); m_dwEffectFrameTime:=300; end else begin if m_wAppearance in [42..47] then begin m_nStartFrame:=20; m_nEndFrame:=10; m_boUseEffect:=True; m_nEffectStart:=0; m_nEffectFrame:=0; m_nEffectEnd:=19; m_dwEffectStartTime:=GetTickCount(); m_dwEffectFrameTime:=100; end else begin if m_wAppearance = 51 then begin m_boUseEffect:=True; m_nEffectStart:=60; m_nEffectFrame:=m_nEffectStart; m_nEffectEnd:=m_nEffectStart + 7; m_dwEffectStartTime:=GetTickCount(); m_dwEffectFrameTime:=500; end; end; end; end; SM_HIT: begin case m_wAppearance of 33,34,52: begin m_nStartFrame := pm.ActStand.start + m_btDir * (pm.ActStand.frame + pm.ActStand.skip); m_nEndFrame := m_nStartFrame + pm.ActStand.frame - 1; m_dwStartTime := GetTickCount; m_nDefFrameCount := pm.ActStand.frame; end; else begin m_nStartFrame := pm.ActAttack.start + m_btDir * (pm.ActAttack.frame + pm.ActAttack.skip); m_nEndFrame := m_nStartFrame + pm.ActAttack.frame - 1; m_dwFrameTime := pm.ActAttack.ftime; m_dwStartTime := GetTickCount; if m_wAppearance = 51 then begin m_boUseEffect:=True; m_nEffectStart:=60; m_nEffectFrame:=m_nEffectStart; m_nEffectEnd:=m_nEffectStart + 7; m_dwEffectStartTime:=GetTickCount(); m_dwEffectFrameTime:=500; end; end; end; end; SM_DIGUP: begin if m_wAppearance = 52 then begin m_bo248:=True; m_dwUseEffectTick:=GetTickCount + 23000; Randomize; PlaySound(Random(7) + 146); m_boUseEffect:=True; m_nEffectStart:=60; m_nEffectFrame:=m_nEffectStart; m_nEffectEnd:=m_nEffectStart + 11; m_dwEffectStartTime:=GetTickCount(); m_dwEffectFrameTime:=100; end; end; end; end; constructor TNpcActor.Create; //0x0047C42C begin inherited; m_EffSurface:=nil; m_boHitEffect:=False; m_bo248:=False; end; procedure TNpcActor.DrawChr(dsurface: TDirectDrawSurface; dx, dy: integer; blend, boFlag: Boolean); var ceff: TColorEffect; begin m_btDir := m_btDir mod 3; if GetTickCount - m_dwLoadSurfaceTime > 60 * 1000 then begin m_dwLoadSurfaceTime := GetTickCount; LoadSurface; end; ceff := GetDrawEffectValue; if m_BodySurface <> nil then begin if m_wAppearance = 51 then begin DrawEffSurface (dsurface, m_BodySurface, dx + m_nPx + m_nShiftX, dy + m_nPy + m_nShiftY, True, ceff); end else begin DrawEffSurface (dsurface, m_BodySurface, dx + m_nPx + m_nShiftX, dy + m_nPy + m_nShiftY, blend, ceff); end; end; end; procedure TNpcActor.DrawEff(dsurface: TDirectDrawSurface; dx, dy: integer); begin // inherited; if m_boUseEffect and (m_EffSurface <> nil) then begin DrawBlend (dsurface, dx + m_nEffX + m_nShiftX, dy + m_nEffY + m_nShiftY, m_EffSurface, 1); end; end; function TNpcActor.GetDefaultFrame (wmode: Boolean): integer; var cf, dr: integer; pm: PTMonsterAction; begin Result:=0;//Jacky pm := GetRaceByPM (m_btRace,m_wAppearance); if pm = nil then exit; m_btDir := m_btDir mod 3; //规氢篮 0, 1, 2 观俊 绝澜.. if m_nCurrentDefFrame < 0 then cf := 0 else if m_nCurrentDefFrame >= pm.ActStand.frame then cf := 0 else cf := m_nCurrentDefFrame; Result := pm.ActStand.start + m_btDir * (pm.ActStand.frame + pm.ActStand.skip) + cf; end; procedure TNpcActor.LoadSurface; var WMImage:TWMImages; begin { case m_btRace of 50: begin //Npc m_BodySurface:=FrmMain.WNpcImg.GetCachedImage (m_nBodyOffset + m_nCurrentFrame, m_nPx, m_nPy); if m_nBodyOffset >= 1000 then begin if FrmMain.GetNpcImg(m_wAppearance,WMImage) then begin m_BodySurface:=WMImage.GetCachedImage (m_nCurrentFrame, m_nPx, m_nPy); end; end; end; end; } if m_btRace = 50 then begin m_BodySurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nCurrentFrame, m_nPx, m_nPy); end; if m_wAppearance in [42..47] then m_BodySurface:=nil; if m_boUseEffect then begin if m_wAppearance in [33..34] then begin m_EffSurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nEffectFrame, m_nEffX, m_nEffY); end else if m_wAppearance = 42 then begin m_EffSurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nEffectFrame, m_nEffX, m_nEffY); m_nEffX:=m_nEffX + 71; m_nEffY:=m_nEffY + 5; end else if m_wAppearance = 43 then begin m_EffSurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nEffectFrame, m_nEffX, m_nEffY); m_nEffX:=m_nEffX + 71; m_nEffY:=m_nEffY + 37; end else if m_wAppearance = 44 then begin m_EffSurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nEffectFrame, m_nEffX, m_nEffY); m_nEffX:=m_nEffX + 7; m_nEffY:=m_nEffY + 12; end else if m_wAppearance = 45 then begin m_EffSurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nEffectFrame, m_nEffX, m_nEffY); m_nEffX:=m_nEffX + 6; m_nEffY:=m_nEffY + 12; end else if m_wAppearance = 46 then begin m_EffSurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nEffectFrame, m_nEffX, m_nEffY); m_nEffX:=m_nEffX + 7; m_nEffY:=m_nEffY + 12; end else if m_wAppearance = 47 then begin m_EffSurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nEffectFrame, m_nEffX, m_nEffY); m_nEffX:=m_nEffX + 8; m_nEffY:=m_nEffY + 12; end else if m_wAppearance = 51 then begin m_EffSurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nEffectFrame, m_nEffX, m_nEffY); end else if m_wAppearance = 52 then begin m_EffSurface:=g_WNpcImgImages.GetCachedImage(m_nBodyOffset + m_nEffectFrame, m_nEffX, m_nEffY); end; end; end; procedure TNpcActor.Run; var nEffectFrame:Integer; dwEffectFrameTime:LongWord; begin inherited Run; nEffectFrame:=m_nEffectFrame; if m_boUseEffect then begin if m_boUseMagic then begin dwEffectFrameTime:=Round(m_dwEffectFrameTime / 3); end else dwEffectFrameTime:=m_dwEffectFrameTime; if GetTickCount - m_dwEffectStartTime > dwEffectFrameTime then begin m_dwEffectStartTime:=GetTickCount(); if m_nEffectFrame < m_nEffectEnd then begin Inc(m_nEffectFrame); end else begin if m_bo248 then begin if GetTickCount > m_dwUseEffectTick then begin m_boUseEffect:=False; m_bo248:=False; m_dwUseEffectTick:=GetTickCount(); end; m_nEffectFrame:=m_nEffectStart; end else m_nEffectFrame:=m_nEffectStart; m_dwEffectStartTime:=GetTickCount(); end; end; end; if nEffectFrame <> m_nEffectFrame then begin m_dwLoadSurfaceTime:=GetTickCount(); LoadSurface(); end; end; end.
//************************************************************************************************** // // Unit uSettings // unit for the VCL Styles for Notepad++ // https://github.com/RRUZ/vcl-styles-plugins // // 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 uSettings.pas. // // The Initial Developer of the Original Code is Rodrigo Ruz V. // // Portions created by Rodrigo Ruz V. are Copyright (C) 2014-2021 Rodrigo Ruz V. // All Rights Reserved. // //************************************************************************************************** unit uSettings; interface uses Winapi.Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, NppForms, StdCtrls, Vcl.ExtCtrls, Vcl.Imaging.pngimage, Vcl.Styles.Ext; type TSettingsForm = class(TNppForm) BtnOK: TButton; Label9: TLabel; ComboBoxVCLStyle: TComboBox; PanelPreview: TPanel; BtnCancel: TButton; procedure LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ComboBoxVCLStyleChange(Sender: TObject); procedure BtnCancelClick(Sender: TObject); procedure BtnOKClick(Sender: TObject); private FPreview:TVclStylesPreview; procedure LoadStyles; procedure DrawSeletedVCLStyle; procedure RefreshStyle; public { Public declarations } end; implementation {$R *.dfm} uses Vcl.Themes, ShellAPi, Vcl.Styles.Npp, uMisc; type TVclStylesPreviewClass = class(TVclStylesPreview); procedure TSettingsForm.BtnCancelClick(Sender: TObject); begin inherited; Close(); end; procedure TSettingsForm.BtnOKClick(Sender: TObject); begin inherited; if not SameText(ComboBoxVCLStyle.Text, TVCLStylesNppPlugin(Npp).Settings.VclStyle) then if MessageBox(Handle, 'Do you want apply the changes?'+sLineBreak+'Note: You must restart Notepad++ to get better results', 'Question', MB_YESNO + MB_ICONQUESTION) = IDYES then begin TVCLStylesNppPlugin(Npp).Settings.VclStyle:=ComboBoxVCLStyle.Text; WriteSettings(TVCLStylesNppPlugin(Npp).Settings, TVCLStylesNppPlugin(Npp).SettingsFileName); ReadSettings(TVCLStylesNppPlugin(Npp).Settings, TVCLStylesNppPlugin(Npp).SettingsFileName); TStyleManager.SetStyle(TVCLStylesNppPlugin(Npp).Settings.VclStyle); RefreshStyle; end; end; //function EnumChildProc(const hWindow: hWnd; const LParam: Winapi.Windows.LParam): boolean; stdcall; //begin // InvalidateRect(hWindow, nil, False); // SendMessage(hWindow, WM_NCPAINT, 0, 0); // Result:= True; //end; procedure TSettingsForm.RefreshStyle; begin //EnumChildWindows(Npp.NppData.NppHandle, @EnumChildProc, 0); ShowWindow(Npp.NppData.NppHandle, SW_MINIMIZE); ShowWindow(Npp.NppData.NppHandle, SW_RESTORE); end; procedure TSettingsForm.ComboBoxVCLStyleChange(Sender: TObject); begin inherited; DrawSeletedVCLStyle; end; procedure TSettingsForm.DrawSeletedVCLStyle; var StyleName: string; LStyle: TCustomStyleServices; begin StyleName:=ComboBoxVCLStyle.Text; if (StyleName<>'') and (not SameText(StyleName, 'Windows')) then begin TStyleManager.StyleNames;//call DiscoverStyleResources LStyle:=TStyleManager.Style[StyleName]; FPreview.Caption:=StyleName; FPreview.Style:=LStyle; TVclStylesPreviewClass(FPreview).Paint; end; end; procedure TSettingsForm.FormCreate(Sender: TObject); begin inherited; FPreview:=TVclStylesPreview.Create(Self); FPreview.Parent:=PanelPreview; FPreview.BoundsRect := PanelPreview.ClientRect; LoadStyles; ComboBoxVCLStyle.ItemIndex:=ComboBoxVCLStyle.Items.IndexOf(TVCLStylesNppPlugin(Npp).Settings.VCLStyle); DrawSeletedVCLStyle; end; procedure TSettingsForm.FormDestroy(Sender: TObject); begin inherited; FPreview.Free; end; procedure TSettingsForm.LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); begin ShellAPI.ShellExecute(0, 'Open', PChar(Link), nil, nil, SW_SHOWNORMAL); end; procedure TSettingsForm.LoadStyles; var Style: string; begin try ComboBoxVCLStyle.Items.BeginUpdate; ComboBoxVCLStyle.Items.Clear; for Style in TStyleManager.StyleNames do ComboBoxVCLStyle.Items.Add(Style); finally ComboBoxVCLStyle.Items.EndUpdate; end; end; end.
unit UniButtonsFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ToolWin, ComCtrls, BaseGUI, ActnList, Menus, StdCtrls; type TfrmButtons = class(TFrame) tlbr: TToolBar; imgList: TImageList; actnLst: TActionList; actnSave: TAction; actnClear: TAction; actnReload: TAction; actnAutoSave: TAction; btnSave: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; actnAdd: TAction; actnDelete: TAction; btnAdd: TToolButton; ToolButton6: TToolButton; actnFind: TAction; ToolButton7: TToolButton; actnSort: TAction; ToolButton8: TToolButton; pmnSort: TPopupMenu; ToolButton9: TToolButton; actnSelectAll: TAction; actnAddGroup: TAction; ToolButton10: TToolButton; ToolButton11: TToolButton; actnEdit: TAction; actnCancel: TAction; btnCancel: TToolButton; procedure actnAutoSaveExecute(Sender: TObject); procedure actnAutoSaveUpdate(Sender: TObject); procedure actnSaveExecute(Sender: TObject); procedure actnSaveUpdate(Sender: TObject); procedure actnClearExecute(Sender: TObject); procedure actnClearUpdate(Sender: TObject); procedure actnReloadExecute(Sender: TObject); procedure actnReloadUpdate(Sender: TObject); procedure actnAddExecute(Sender: TObject); procedure actnDeleteExecute(Sender: TObject); procedure actnAddUpdate(Sender: TObject); procedure actnDeleteUpdate(Sender: TObject); procedure actnFindExecute(Sender: TObject); procedure actnFindUpdate(Sender: TObject); procedure pmiNameClick(Sender: TObject); procedure actnSortExecute(Sender: TObject); procedure actnSelectAllExecute(Sender: TObject); procedure actnSelectAllUpdate(Sender: TObject); procedure actnAddGroupExecute(Sender: TObject); procedure actnAddGroupUpdate(Sender: TObject); procedure actnEditExecute(Sender: TObject); procedure actnEditUpdate(Sender: TObject); procedure actnSortUpdate(Sender: TObject); procedure actnCancelExecute(Sender: TObject); procedure actnCancelUpdate(Sender: TObject); private { Private declarations } FGUIAdapter: TGUIAdapter; procedure SetGUIAdapter(const Value: TGUIAdapter); public { Public declarations } property GUIAdapter: TGUIAdapter read FGUIAdapter write SetGUIAdapter; end; implementation {$R *.dfm} { TfrmButtons } procedure TfrmButtons.SetGUIAdapter(const Value: TGUIAdapter); var i: integer; pmi: TMenuItem; begin if FGUIAdapter <> Value then begin FGUIAdapter := Value; actnSave.Visible := abSave in GUIAdapter.Buttons; actnAutoSave.Visible := abAutoSave in GUIAdapter.Buttons; actnClear.Visible := abClear in GUIAdapter.Buttons; actnReload.Visible := abReload in GUIAdapter.Buttons; actnAdd.Visible := abAdd in GUIAdapter.Buttons; actnDelete.Visible := abDelete in GUIAdapter.Buttons; actnFind.Visible := abFind in GUIAdapter.Buttons; actnSort.Visible := abSort in GUIAdapter.Buttons; actnSelectAll.Visible := abSelectAll in GUIAdapter.Buttons; actnAddGroup.Visible := abAddGroup in GUIAdapter.Buttons; actnEdit.Visible := abEdit in GUIAdapter.Buttons; actnCancel.Visible := abCancel in GUIAdapter.Buttons; if FGUIAdapter is TCollectionGUIAdapter then with FGUIAdapter as TCollectionGUIAdapter do begin for i := 0 to SortOrders.Count - 1 do begin pmi := TMenuItem.Create(pmnSort); pmnSort.Items.Add(pmi); pmi.Caption := SortOrders.Items[i].Name; pmi.Tag := i; pmi.OnClick := pmiNameClick; pmi.ImageIndex := 8; pmi.RadioItem := true; pmi.GroupIndex := 1; end; end; end; end; procedure TfrmButtons.actnAutoSaveExecute(Sender: TObject); begin actnAutoSave.Checked := not actnAutoSave.Checked; GUIAdapter.AutoSave := actnAutoSave.Checked; end; procedure TfrmButtons.actnAutoSaveUpdate(Sender: TObject); begin actnAutoSave.Enabled := Assigned(GUIAdapter); end; procedure TfrmButtons.actnSaveExecute(Sender: TObject); begin GUIAdapter.Save; end; procedure TfrmButtons.actnSaveUpdate(Sender: TObject); begin actnSave.Enabled := Assigned(GUIAdapter) and GUIAdapter.CanSave; end; procedure TfrmButtons.actnClearExecute(Sender: TObject); begin GUIAdapter.Clear; end; procedure TfrmButtons.actnClearUpdate(Sender: TObject); begin actnClear.Enabled := Assigned(GUIAdapter) and GUIAdapter.CanClear; end; procedure TfrmButtons.actnReloadExecute(Sender: TObject); begin GUIAdapter.Reload; end; procedure TfrmButtons.actnReloadUpdate(Sender: TObject); begin actnReload.Enabled := Assigned(GUIAdapter) and GUIAdapter.CanReload; end; procedure TfrmButtons.actnAddExecute(Sender: TObject); begin GUIAdapter.Add; end; procedure TfrmButtons.actnDeleteExecute(Sender: TObject); begin GUIAdapter.Delete; end; procedure TfrmButtons.actnAddUpdate(Sender: TObject); begin actnAdd.Enabled := Assigned(GUIAdapter) and GUIAdapter.CanAdd; end; procedure TfrmButtons.actnDeleteUpdate(Sender: TObject); begin actnDelete.Enabled := Assigned(GUIAdapter) and GUIAdapter.CanDelete; end; procedure TfrmButtons.actnFindExecute(Sender: TObject); begin GUIAdapter.StartFind; end; procedure TfrmButtons.actnFindUpdate(Sender: TObject); begin actnFind.Enabled := Assigned(GUIAdapter) and GuiAdapter.CanFind; end; procedure TfrmButtons.pmiNameClick(Sender: TObject); var bOrder: boolean; pmi: TMenuItem; begin if GUIAdapter is TCollectionGUIAdapter then begin pmi := Sender as TMenuItem; bOrder := pmi.ImageIndex = 9; if GUIAdapter is TCollectionGUIAdapter then with GUIAdapter as TCollectionGUIAdapter do begin OrderBy := pmi.Tag; StraightOrder := bOrder; end; GUIAdapter.Reload; if bOrder then pmi.ImageIndex := 8 else pmi.ImageIndex := 9; pmi.Checked := true; end; end; procedure TfrmButtons.actnSortExecute(Sender: TObject); begin actnSort.Enabled := Assigned (GUIAdapter); end; procedure TfrmButtons.actnSelectAllExecute(Sender: TObject); begin GUIAdapter.SelectAll; end; procedure TfrmButtons.actnSelectAllUpdate(Sender: TObject); begin actnSelectAll.Enabled := Assigned (GUIAdapter); end; procedure TfrmButtons.actnAddGroupExecute(Sender: TObject); begin GUIAdapter.AddGroup; end; procedure TfrmButtons.actnAddGroupUpdate(Sender: TObject); begin actnAddGroup.Enabled := Assigned(GUIAdapter) and GUIAdapter.CanAddGroup; end; procedure TfrmButtons.actnEditExecute(Sender: TObject); begin GUIAdapter.Edit; end; procedure TfrmButtons.actnEditUpdate(Sender: TObject); begin actnEdit.Enabled := Assigned(GUIAdapter) and GUIAdapter.CanEdit; end; procedure TfrmButtons.actnSortUpdate(Sender: TObject); begin actnSort.Enabled := Assigned(GUIAdapter) and (GUIAdapter is TCollectionGUIAdapter) and (GUIAdapter as TCollectionGUIAdapter).CanSort; end; procedure TfrmButtons.actnCancelExecute(Sender: TObject); begin GUIAdapter.Cancel; end; procedure TfrmButtons.actnCancelUpdate(Sender: TObject); begin actnCancel.Enabled := GUIAdapter.CanCancel; end; end.
{ Subroutine STRING_COPY (S1,S2) * * Copy the contents of string S1 into string S2. This is different * from doing a pascal assignment statement in several ways. First, * only the string itself and not the unused characters past the end * of the string are copied. Second, the two strings need not have * the same max length. In this case pascal would not allow one to * be assigned to the other. * * If the length of S1 is longer than the max length of S2, then the * string in S2 is truncated. } module string_copy; define string_copy; %include 'string2.ins.pas'; procedure string_copy ( {copy one string into another} in s1: univ string_var_arg_t; {input string} in out s2: univ string_var_arg_t); {output string} var n: sys_int_machine_t; {number of chars to copy} i: sys_int_machine_t; {string index} begin n := s1.len; {init number of chars to copy} if n > s2.max then n := s2.max; {truncate to S2 max length} for i := 1 to n do {once for each character} s2.str[i] := s1.str[i]; {copy a character} s2.len := n; {set length of string in S2} end;
unit EditStyle; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, System.UITypes; type TEditStyle = class(TEdit) private { Private declarations } protected { Protected declarations } public constructor Create(AOwner: TComponent); override; { Public declarations } published { Published declarations } end; procedure Register; implementation uses Forms, Graphics; procedure Register; begin RegisterComponents('Jovio', [TEditStyle]); end; { TEditStyle } constructor TEditStyle.Create(AOwner: TComponent); begin inherited; BevelInner := bvLowered; BevelKind := bkFlat; BevelOuter := bvRaised; BorderStyle := bsNone; Font.Color := clBlue; Font.Style := Font.Style + [fsBold]; CharCase := ecUpperCase; end; end.
unit uLuaFuns; interface uses Winapi.Windows, System.SysUtils, VerySimple.Lua, VerySimple.Lua.Lib; type TLuaFuns = class private public function LoadPackage(L: lua_State): Integer; procedure PackageReg(L: lua_State); published {$REGION 'Windows API'} /// <summary> /// 暂停函数 /// </summary> /// <param name="L">暂停的毫秒数</param> /// <returns></returns> function MsSleep(L: lua_State): Integer; function MsFindWindow(L: lua_State): Integer; function MsFindWindowEx(L: lua_State): Integer; function MsIsWindow(L: lua_State): Integer; function MsGetTickCount(L: lua_State): Integer; function MsGetClientRect(L: lua_State): Integer; function MsSendMessage(L: lua_State): Integer; {$ENDREGION} {$REGION '封装功能'} //--前置窗口 function MsFrontWindow(L: lua_State): Integer; /// <summary> /// 输出调试信息 /// </summary> /// <param name="L">调试信息文本</param> /// <returns></returns> function MsDebugInfo(L: lua_State): Integer; function MsStartGame(L: lua_State): Integer; function MsPressPassWord(L: lua_State): Integer; function MsCheck(L: lua_State): Integer; function MsCloseGame(L: lua_State): Integer; function MsGetTopLeft(L: lua_State): Integer; function MsDaMa(L: lua_State): Integer; function MsQuitSafe(L: lua_State): Integer; function MsGetCarryAmount(L: lua_State): Integer; function MsCreateBmp(L: lua_State): Integer; function MsSetGameCfg(L: lua_State): Integer; function MsGetPwd(L: lua_State): Integer; {$ENDREGION} {$REGION '大漠'} function MsClick(L: lua_State): Integer; function MsDbClick(L: lua_State): Integer; function MsRightClick(L: lua_State): Integer; function MsDragMouse(L: lua_State): Integer; function MsFindImg(L: lua_State): Integer; function MsFindImgEx(L: lua_State): Integer; function MsAreaFindImg(L: lua_State): Integer; function MsAreaFindImgEx(L: lua_State): Integer; function MsAreaFindString(L: lua_State): Integer; function MsFindString(L: lua_State): Integer; function MsFindStringEx(L: lua_State): Integer; /// <summary> /// 获取数量 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsGetNumber(L: lua_State): Integer; /// <summary> /// 连续按下删除按键 /// </summary> /// <param name="L">按下多少次</param> /// <returns></returns> function MsPressDel(L: lua_State): Integer; /// <summary> /// 按下回车键 /// </summary> /// <returns></returns> function MsPressEnter(L: lua_State): Integer; /// <summary> /// 按下返回键 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsPressEsc(L: lua_State): Integer; /// <summary> /// 截取游戏窗口 /// </summary> function MsCaptureGame(L: lua_State): Integer; /// <summary> /// 区域截图 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsCaptureArea(L: lua_State): Integer; /// <summary> /// 移动窗口 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsMoveWindow(L: lua_State): Integer; /// <summary> /// 按键 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsPressKey(L: lua_State): Integer; /// <remarks> /// 按下方向键走路 /// </remarks> function MsTheKeysWalk(L: lua_State): Integer; /// <summary> /// /// </summary> /// <param name="L"></param> /// <returns></returns> function MsPressChar(L: lua_State): Integer; /// <summary> /// 向下滑动鼠标 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsWheelDown(L: lua_State): Integer; /// <summary> /// 鼠標移動到 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsMoveTo(L: lua_State): Integer; /// <summary> /// 输入字符串 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsPressString(L: lua_State): Integer; /// <summary> /// 屏幕取字 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsOcr(L: lua_State): Integer; /// <summary> /// 屏幕取字 /// </summary> /// <param name="L"></param> /// <returns></returns> function MsOcrEx(L: lua_State): Integer; {$ENDREGION} {$REGION '公共变量'} function MsGetGameHandle(L: lua_State): Integer; function MsSetGameHandle(L: lua_State): Integer; {$ENDREGION} {$REGION '公共参数'} function MsGetDelay(L: lua_State): Integer; function MsGetPianSe(L: lua_State): Integer; {$ENDREGION} {$REGION '通讯'} function MsPostStatus(L: lua_State): Integer; /// <remarks> /// 告诉控制台自己执行到哪一步了 /// </remarks> function MsSetRoleStep(L: lua_State): Integer; function MsResetRoleStep(L: lua_State): Integer; function MsGetRoleStep(L: lua_State): Integer; // function MsSetTargetRoleStep(L: lua_State): Integer; function MsGetTargetRoleStep(L: lua_State): Integer; function MsSetMasterRecRoleName(L: lua_State): Integer; function MsClearRecvRoleName(L: lua_State): Integer; function MsGetMasterRecRoleName(L: lua_State): Integer; {$ENDREGION} end; implementation uses uCommFuns, uTradeClient, uGlobal, ManSoy.Global; { TTradeFunctions } function TLuaFuns.LoadPackage(L: lua_State): Integer; begin lua_newtable(L); {$REGION 'Windows API'} TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsSleep'), 'MsSleep'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsFindWindow'), 'MsFindWindow'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsFindWindowEx'), 'MsFindWindowEx'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsIsWindow'), 'MsIsWindow'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetTickCount'), 'MsGetTickCount'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetClientRect'), 'MsGetClientRect'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsSendMessage'), 'MsSendMessage'); lua_rawset(L, -3); {$ENDREGION} {$REGION '封装'} TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsFrontWindow'), 'MsFrontWindow'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsDebugInfo'), 'MsDebugInfo'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsStartGame'), 'MsStartGame'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsPressPassWord'), 'MsPressPassWord'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsCheck'), 'MsCheck'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsCloseGame'), 'MsCloseGame'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetTopLeft'), 'MsGetTopLeft'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsDaMa'), 'MsDaMa'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsQuitSafe'), 'MsQuitSafe'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetCarryAmount'), 'MsGetCarryAmount'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsCreateBmp'), 'MsCreateBmp'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsSetGameCfg'), 'MsSetGameCfg'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetPwd'), 'MsGetPassWord'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsOcr'), 'MsOcr'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsOcrEx'), 'MsOcrEx'); lua_rawset(L, -3); {$ENDREGION} {$REGION '大漠'} TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsClick'), 'MsClick'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsDbClick'), 'MsDbClick'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsRightClick'), 'MsRightClick'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsDragMouse'), 'MsDragMouse'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsFindImg'), 'MsFindImg'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsFindImgEx'), 'MsFindImgEx'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsAreaFindImg'), 'MsAreaFindImg'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsAreaFindImgEx'), 'MsAreaFindImgEx'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsAreaFindString'), 'MsAreaFindString'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsFindString'), 'MsFindString'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsFindStringEx'), 'MsFindStringEx'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetNumber'), 'MsGetNumber'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsPressDel'), 'MsPressDel'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsPressEnter'), 'MsPressEnter'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsPressEsc'), 'MsPressEsc'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsCaptureGame'), 'MsCaptureGame'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsCaptureArea'), 'MsCaptureArea'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsMoveWindow'), 'MsMoveWindow'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsPressKey'), 'MsPressKey'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsTheKeysWalk'), 'MsTheKeysWalk'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsPressChar'), 'MsPressChar'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsWheelDown'), 'MsWheelDown'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsMoveTo'), 'MsMoveTo'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsPressString'), 'MsPressString'); lua_rawset(L, -3); {$ENDREGION} {$REGION '公共变量'} TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetGameHandle'), 'MsGetGameHandle'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsSetGameHandle'), 'MsSetGameHandle'); lua_rawset(L, -3); {$ENDREGION} {$REGION '公共参数'} TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetDelay'), 'MsGetDelay'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetPianSe'), 'MsGetPianSe'); lua_rawset(L, -3); {$ENDREGION} {$REGION '通讯'} TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsPostStatus'), 'MsPostStatus'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsSetRoleStep'), 'MsSetRoleStep'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsResetRoleStep'), 'MsResetRoleStep'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetRoleStep'), 'MsGetRoleStep'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetTargetRoleStep'), 'MsGetTargetRoleStep'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsSetMasterRecRoleName'), 'MsSetMasterRecRoleName'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsClearRecvRoleName'), 'MsClearRecvRoleName'); lua_rawset(L, -3); TVerySimpleLua.PushFunction(L, Self, MethodAddress('MsGetMasterRecRoleName'), 'MsGetMasterRecRoleName'); lua_rawset(L, -3); {$ENDREGION} Result := 1; end; procedure TLuaFuns.PackageReg(L: lua_State); begin TVerySimpleLua.RegisterPackage(L, 'TLuaFuns', Self, 'LoadPackage'); end; {$REGION 'Windows API'} function TLuaFuns.MsFindWindow(L: lua_State): Integer; var ArgCount: Integer; sClassName, sWindowText: string; szClassName, szWindowText: PChar; hWindow: HWND; begin Result := 1; try ArgCount := Lua_GetTop(L); sClassName := string(AnsiString(Lua_ToString(L, 2))); sWindowText := string(AnsiString(Lua_ToString(L, 3))); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 3 then begin Lua_PushInteger(L, RetErr); Exit; end; if sClassName = '' then szClassName := nil else szClassName := PChar(sClassName); if sWindowText = '' then szWindowText := nil else szWindowText := PChar(sWindowText); hWindow := WinApi.Windows.FindWindow(szClassName, szWindowText); if not WinApi.Windows.IsWindow(hWindow) then begin Lua_PushInteger(L, 0); Exit; end; Lua_PushInteger(L, hWindow); except end; end; function TLuaFuns.MsFindWindowEx(L: lua_State): Integer; var ArgCount: Integer; sClassName, sWindowText: string; szClassName, szWindowText: PChar; hParent, hAfter, hWindow: HWND; begin Result := 1; try ArgCount := Lua_GetTop(L); hParent := Lua_ToInteger(L, 2); hAfter := Lua_ToInteger(L, 3); sClassName := string(AnsiString(Lua_ToString(L, 4))); sWindowText := string(AnsiString(Lua_ToString(L, 5))); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 5 then begin Lua_PushInteger(L, RetErr); Exit; end; if sClassName = '' then szClassName := nil else szClassName := PChar(sClassName); if sWindowText = '' then szWindowText := nil else szWindowText := PChar(sWindowText); hWindow := WinApi.Windows.FindWindowEx(hParent, hAfter, szClassName, szWindowText); if not WinApi.Windows.IsWindow(hWindow) then begin Lua_PushInteger(L, 0); Exit; end; Lua_PushInteger(L, hWindow); except end; end; function TLuaFuns.MsIsWindow(L: lua_State): Integer; var X, Y, X1, Y1: Integer; ArgCount: Integer; hWindow: HWND; begin Result := RetOK; try ArgCount := Lua_GetTop(L); hWindow := Lua_ToInteger(L, 2); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; if not Winapi.Windows.IsWindow(hWindow) then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except end; end; function TLuaFuns.MsGetTickCount(L: lua_State): Integer; var dwTickCount: DWORD; begin Result := 1; try dwTickCount := WinApi.Windows.GetTickCount(); Lua_PushInteger(L, dwTickCount); except end; end; function TLuaFuns.MsSleep(L: lua_State): Integer; var ArgCount: Integer; dwInterVal, dwAdd, dwTmp: DWORD; begin Result := RetOK; try dwTmp := 0; ArgCount := Lua_GetTop(L); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; dwInterVal := Lua_ToInteger(L, 2); if ArgCount > 2 then begin dwAdd := Lua_ToInteger(L, 3); dwTmp := Random(dwAdd); end; Lua_Pop(L, Lua_GetTop(L)); Winapi.Windows.Sleep(dwInterVal + dwTmp); Lua_PushInteger(L, RetOk); except end; end; function TLuaFuns.MsGetClientRect(L: lua_State): Integer; var X, Y, X1, Y1: Integer; ArgCount: Integer; hWindow: HWND; begin Result := 4; //Result 表示返回的参数个数 try ArgCount := Lua_GetTop(L); hWindow := Lua_ToInteger(L, 2); if ArgCount >= 2 then begin GCommFuns.fn获取客户区域(hWindow, X, Y, X1, Y1); Lua_Pop(L, Lua_GetTop(L)); Lua_PushInteger(L, X); Lua_PushInteger(L, Y); Lua_PushInteger(L, X1); Lua_PushInteger(L, Y1); end else begin Lua_PushInteger(L, -1); Lua_PushInteger(L, -1); Lua_PushInteger(L, -1); Lua_PushInteger(L, -1); end; except end; end; function TLuaFuns.MsSendMessage(L: lua_State): Integer; var ArgCount: Integer; hHandle: HWND; WmMsg: DWORD; lP: LPARAM; wP: WPARAM; lRet: LRESULT; begin Result := 1; try ArgCount := Lua_GetTop(L); if ArgCount < 3 then begin Lua_Pop(L, Lua_GetTop(L)); Lua_PushInteger(L, RetErr); Exit; end; hHandle := Lua_ToInteger(L, 2); WmMsg := Lua_ToInteger(L, 3); lP := 0; wP := 0; if ArgCount > 3 then begin lP := Lua_ToInteger(L, 4); end; if ArgCount > 4 then begin wP := Lua_ToInteger(L, 5); end; lRet := SendMessage(hHandle, WmMsg, wP, lP); Lua_PushInteger(L, lRet); except end; end; {$ENDREGION} {$REGION '封装功能'} //--前置窗口 function TLuaFuns.MsFrontWindow(L: lua_State): Integer; var ArgCount: Integer; hWindow: HWND; bRet: Boolean; begin Result := 1; try ArgCount := Lua_GetTop(L); hWindow := lua_toInteger(L, 2); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; bRet := GCommFuns.fn前置窗口(hWindow); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOk); except end; end; function TLuaFuns.MsDebugInfo(L: lua_State): Integer; var ArgCount: Integer; sText: string; bRet: Boolean; begin Result := 0; try ArgCount := Lua_GetTop(L); sText := lua_toString(L, 2); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then Exit; ManSoy.Global.DebugInf(sText, []); except end; end; function TLuaFuns.MsPressPassWord(L: lua_State): Integer; var ArgCount: Integer; vHPwd: HWND; vPassWord: string; bRet: Boolean; begin Result := 1; try ArgCount := Lua_GetTop(L); vHPwd := HWND(Lua_ToInteger(L, 2)); vPassWord := string(AnsiString(lua_tostring(L, 3))); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 3 then begin Lua_PushInteger(L, RetErr); Exit; end; bRet := GCommFuns.PressPassWord(vHPwd, vPassWord, 200); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOk); except end; end; function TLuaFuns.MsStartGame(L: lua_State): Integer; var sGamePath: string; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; bRet: Boolean; begin Result := 1; try FillChar(ProcessInfo, SizeOf(TProcessInformation), 0); FillChar(StartupInfo, SizeOf(TStartupInfo), 0); StartupInfo.cb := SizeOf(TStartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := SW_SHOW; sGamePath := Format('%s\start\DNFchina.exe', [GSharedInfo.ClientSet.GamePath]); if not FileExists(sGamePath) then begin TradeClient.PostStatus('游戏路径设置有误', [], tsFail); Lua_PushInteger(L, RetErr); Exit; end; //Sleep(1000); bRet := CreateProcess(PWideChar(sGamePath), nil, nil, nil, False, NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo); if not bRet then begin uGlobal.AddLogMsg('创建游戏进程失败:%d', [GetLastError]); Lua_PushInteger(L, RetErr); Exit; end; CloseHandle(ProcessInfo.hThread); CloseHandle(ProcessInfo.hProcess); Lua_PushInteger(L, RetOK); except on E: Exception do uGlobal.AddLogMsg('启动游戏异常[%s]',[E.Message]); end; end; function TLuaFuns.MsCheck(L: lua_State): Integer; var ArgCount: Integer; bCheckWindow, bRet: Boolean; begin Result := 1; try ArgCount := Lua_GetTop(L); if ArgCount > 1 then bCheckWindow := Lua_ToInteger(L, 2) <> 0; Lua_Pop(L, Lua_GetTop(L)); bRet := GCommFuns.fn校验(bCheckWindow); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except end; end; function TLuaFuns.MsCloseGame(L: lua_State): Integer; var bRet: Boolean; dwDelay: Integer; ArgCount: Integer; begin Result := 1; try ArgCount := Lua_GetTop(L); if ArgCount > 1 then dwDelay := Lua_ToInteger(L, 2); Lua_Pop(L, Lua_GetTop(L)); bRet := GCommFuns.CloseGame(dwDelay); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except end; end; function TLuaFuns.MsGetTopLeft(L: lua_State): Integer; var ArgCount: Integer; hGame: HWND; X, Y, X1, Y1: Integer; begin Result := 2; ArgCount := lua_gettop(L); if ArgCount < 2 then begin lua_pushinteger(L, -1); lua_pushinteger(L, -1); end; hGame := lua_tointeger(L, 2); if not IsWindow(hGame) then begin lua_pushinteger(L, -1); lua_pushinteger(L, -1); end; GCommFuns.fn获取客户区域(hGame, X, Y, X1, Y1); if IsWindow(hGame) then begin lua_pushinteger(L, X); lua_pushinteger(L, Y); end; end; function TLuaFuns.MsDaMa(L: lua_State): Integer; var ArgCount: Integer; sRet, sAcc, sPwd, sFileName: string; iDelay: Integer; begin Result := 1; ArgCount := lua_gettop(L); if ArgCount < 3 then begin Lua_pushString(L, ''); Exit; end; sAcc := GSharedInfo.ClientSet.Dama2User; sPwd := GSharedInfo.ClientSet.Dama2Pwd; sFileName := string(AnsiString(lua_tostring(L,2))); iDelay := lua_tointeger(L, 3); sRet := GCommFuns.fnDaMa(sAcc, sPwd, sFileName, iDelay); Lua_pushString(L, PAnsiChar(AnsiString(sRet))); end; function TLuaFuns.MsQuitSafe(L: lua_State): Integer; var sRet: string; begin Result := 1; sRet := GCommFuns.fnQuitSate; Lua_pushString(L, PAnsiChar(AnsiString(sRet))); end; function TLuaFuns.MsGetCarryAmount(L: lua_State): Integer; var ArgCount: Integer; iRoleLevel, iRet: Integer; begin Result := 1; ArgCount := lua_gettop(L); if ArgCount < 2 then begin lua_pushinteger(L, -1); Exit; end; iRoleLevel := lua_tointeger(L,2); iRet := GCommFuns.GetCarryAmount(iRoleLevel); lua_pushinteger(L, iRet); end; function TLuaFuns.MsCreateBmp(L: lua_State): Integer; var ArgCount: Integer; sCaption, sImg: string; R, G, B: Integer; begin Result := 1; ArgCount := lua_gettop(L); if ArgCount < 6 then begin lua_pushinteger(L, RetErr); Exit; end; sCaption := string(AnsiString(lua_tostring(L, 2))); sImg := string(AnsiString(lua_tostring(L, 3))); R := lua_tointeger(L,4); G := lua_tointeger(L,5); B := lua_tointeger(L,6); sImg := Format('%sBmp(W7)\%s.bmp', [GSharedInfo.AppPath, sImg]); if FileExists(sImg) then begin GCommFuns.FreePic(sImg); DeleteFile(sImg); Sleep(200); end; if GCommFuns.CreateBmp(sCaption, R, G, B, sImg) then begin lua_pushinteger(L, RetOK); end else begin lua_pushinteger(L, RetErr); end; end; function TLuaFuns.MsSetGameCfg(L: lua_State): Integer; var sGameSvr, sGameAccount: string; ArgCount: Integer; begin Result := 1; ArgCount := lua_gettop(L); if ArgCount < 3 then begin lua_pushinteger(L, RetErr); Exit; end; sGameSvr := string(AnsiString(lua_tostring(L, 2))); sGameAccount := string(AnsiString(lua_tostring(L, 3))); if GCommFuns.WriteGameRegionSvr(GSharedInfo.ClientSet.GamePath, sGameSvr, sGameAccount) then begin lua_pushinteger(L, RetErr); Exit; end; lua_pushinteger(L, RetOK); end; function TLuaFuns.MsGetPwd(L: lua_State): Integer; var sAccount, sPwd: string; ArgCount: Integer; begin Result := 1; ArgCount := lua_gettop(L); if ArgCount < 2 then begin Lua_pushString(L, PAnsiChar(AnsiString('-1'))); Exit; end; sAccount := string(AnsiString(lua_tostring(L, 2))); sPwd := GCommFuns.GetPassWord(sAccount); Lua_pushString(L, PAnsiChar(AnsiString(sPwd))); end; {$ENDREGION} {$REGION '大漠'} function TLuaFuns.MsClick(L: lua_State): Integer; var X, Y, X1, Y1, ArgCount: Integer; begin Result := 1; try ArgCount := Lua_GetTop(L); if ArgCount > 1 then X := Lua_ToInteger(L, 2); if ArgCount > 2 then Y := Lua_ToInteger(L, 3); if ArgCount > 3 then X1 := Lua_ToInteger(L, 4); if ArgCount > 4 then Y1 := Lua_ToInteger(L, 5); if ArgCount > 4 then begin Randomize; X := X + Random(X1); Y := Y + Random(Y1); end; Lua_Pop(L, Lua_GetTop(L)); GCommFuns.pro点击鼠标左键(X, Y); lua_pushinteger(L, RetOK); except end; end; function TLuaFuns.MsDbClick(L: lua_State): Integer; var X, Y, ArgCount: Integer; begin Result := 0; try ArgCount := Lua_GetTop(L); if ArgCount > 1 then X := Lua_ToInteger(L, 2); if ArgCount > 2 then Y := Lua_ToInteger(L, 3); GCommFuns.pro双击鼠标左键(X, Y); except end; end; function TLuaFuns.MsRightClick(L: lua_State): Integer; var X, Y, ArgCount: Integer; begin Result := 1; try ArgCount := Lua_GetTop(L); if ArgCount > 1 then X := Lua_ToInteger(L, 2); if ArgCount > 2 then Y := Lua_ToInteger(L, 3); Lua_Pop(L, Lua_GetTop(L)); GCommFuns.pro点击鼠标右键(X, Y); lua_pushinteger(L, RetOK); except end; end; function TLuaFuns.MsDragMouse(L: lua_State): Integer; var X, Y, X2, Y2, ArgCount: Integer; begin Result := 0; try ArgCount := Lua_GetTop(L); if ArgCount > 1 then X := Lua_ToInteger(L, 2); if ArgCount > 2 then Y := Lua_ToInteger(L, 3); if ArgCount > 3 then X2 := Lua_ToInteger(L, 4); if ArgCount > 4 then Y2 := Lua_ToInteger(L, 5); //DebugInfo('MS - %d-%d-%d-%d', []); GCommFuns.pro拖动鼠标(X, Y, X2, Y2); Sleep(1000); GCommFuns.MoveTo(0, 0); except end; end; function TLuaFuns.MsFindImg(L: lua_State): Integer; var ArgCount: Integer; sImgName: string; iRatio: Single; iDelay: DWORD; bRet: Boolean; begin Result := 1; try iRatio := 1.0; iDelay := 1; ArgCount := Lua_GetTop(L); if ArgCount > 1 then sImgName := string(AnsiString(Lua_ToString(L, 2))); if ArgCount > 2 then iRatio := Lua_ToNumber(L, 3); if ArgCount > 3 then iDelay := Lua_ToInteger(L, 4); DebugInf('MS - FindImgParam[%s][%.2f][%d]', [sImgName, iRatio, iDelay]); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; bRet := GCommFuns.fn查找图片(sImgName, iRatio, iDelay); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOk); except end; end; function TLuaFuns.MsFindImgEx(L: lua_State): Integer; var ArgCount: Integer; sImgName: string; iRatio: Single; iDelay: DWORD; vPos: TFindRet; begin Result := 3; try iRatio := 1.0; iDelay := 1; ArgCount := Lua_GetTop(L); if ArgCount > 1 then sImgName := string(AnsiString(Lua_ToString(L, 2))); if ArgCount > 2 then iRatio := Lua_ToNumber(L, 3); if ArgCount > 3 then iDelay := Lua_ToInteger(L, 4); if ArgCount < 2 then begin Lua_PushInteger(L, -1); Lua_PushInteger(L, -1); Lua_PushInteger(L, -1); Exit; end; vPos := GCommFuns.fn查找图片_返回坐标(sImgName, iRatio, iDelay); Lua_PushInteger(L, vPos.X); Lua_PushInteger(L, vPos.Y); Lua_PushInteger(L, vPos.Ret); except end; end; function TLuaFuns.MsAreaFindImg(L: lua_State): Integer; var ArgCount: Integer; sImgName: string; iRatio: Single; iDelay: DWORD; bRet: Boolean; X, Y, X1, Y1: Integer; begin Result := 1; try iRatio := 1.0; iDelay := 1; ArgCount := Lua_GetTop(L); X := Lua_ToInteger(L, 2); Y := Lua_ToInteger(L, 3); X1 := Lua_ToInteger(L, 4); Y1 := Lua_ToInteger(L, 5); if ArgCount > 5 then sImgName := string(AnsiString(Lua_ToString(L, 6))); if ArgCount > 6 then iRatio := Lua_ToNumber(L, 7); if ArgCount > 7 then iDelay := Lua_ToInteger(L, 8); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 5 then begin Lua_PushInteger(L, RetErr); Exit; end; bRet := GCommFuns.fn查找图片_区域(X, Y, X1, Y1, sImgName, iRatio, iDelay); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except end; end; function TLuaFuns.MsAreaFindImgEx(L: lua_State): Integer; var ArgCount: Integer; sImgName: string; iRatio: Single; iDelay: DWORD; vFindRet: TFindRet; X, Y, X1, Y1: Integer; begin Result := 3; try iRatio := 1.0; iDelay := 1; ArgCount := Lua_GetTop(L); X := Lua_ToInteger(L, 2); Y := Lua_ToInteger(L, 3); X1 := Lua_ToInteger(L, 4); Y1 := Lua_ToInteger(L, 5); if ArgCount > 5 then sImgName := string(AnsiString(Lua_ToString(L, 6))); if ArgCount > 6 then iRatio := Lua_ToNumber(L, 7); if ArgCount > 7 then iDelay := Lua_ToInteger(L, 8); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 5 then begin Lua_PushInteger(L, -1); Lua_PushInteger(L, -1); Lua_PushInteger(L, -1); Exit; end; vFindRet := GCommFuns.fn查找图片_返回坐标_区域(X, Y, X1, Y1, sImgName, iRatio, iDelay); Lua_PushInteger(L, vFindRet.X); Lua_PushInteger(L, vFindRet.Y); Lua_PushInteger(L, vFindRet.Ret); except end; end; function TLuaFuns.MsAreaFindString(L: lua_State): Integer; var x1, y1, x2, y2, ArgCount: Integer; sText, sPianSe: string; iRatio: Single; iDelay: DWORD; fRet: TFindRet; begin Result := 3; try iRatio := 1.0; iDelay := 1; ArgCount := Lua_GetTop(L); if ArgCount > 1 then x1 := Lua_ToInteger(L, 2); if ArgCount > 2 then y1 := Lua_ToInteger(L, 3); if ArgCount > 3 then x2 := Lua_ToInteger(L, 4); if ArgCount > 4 then y2 := Lua_ToInteger(L, 5); if ArgCount > 5 then sText := string(AnsiString(Lua_ToString(L, 6))); if ArgCount > 6 then sPianSe := string(AnsiString(Lua_ToString(L, 7))); if ArgCount > 7 then iRatio := Lua_ToNumber(L, 8); if ArgCount > 8 then iDelay := Lua_ToInteger(L, 9); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 7 then begin Lua_PushInteger(L, RetErr); Exit; end; fRet := GCommFuns.fn区域找字(x1, y1, x2, y2, sText, sPianSe, CON_SYS_DICT, iRatio, iDelay); // if fRet.Ret = -1 then // begin // Lua_PushInteger(L, -1); // Lua_PushInteger(L, -1); // Lua_PushInteger(L, -1); // Exit; // end; Lua_PushInteger(L, fRet.X); Lua_PushInteger(L, fRet.Y); Lua_PushInteger(L, fRet.Ret); except end; end; function TLuaFuns.MsFindString(L: lua_State): Integer; var ArgCount: Integer; sText, sPianSe: string; iRatio: Single; iDelay: DWORD; bRet: Boolean; X, Y, X1, Y1: Integer; begin Result := 1; try iRatio := 1.0; iDelay := 1; ArgCount := Lua_GetTop(L); if ArgCount > 1 then sText := string(AnsiString(Lua_ToString(L, 2))); if ArgCount > 2 then sPianSe := string(AnsiString(Lua_ToString(L, 3))); if ArgCount > 3 then iRatio := Lua_ToNumber(L, 4); if ArgCount > 4 then iDelay := Lua_ToInteger(L, 5); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 3 then begin Lua_PushInteger(L, RetErr); Exit; end; bRet := GCommFuns.fn全屏找字(sText, sPianSe, CON_SYS_DICT, iRatio, iDelay); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except end; end; function TLuaFuns.MsFindStringEx(L: lua_State): Integer; var ArgCount: Integer; sText, sPianSe: string; iRatio: Single; iDelay: DWORD; vPos: TFindRet; X, Y, X1, Y1: Integer; begin Result := 3; try iRatio := 1.0; iDelay := 1; ArgCount := Lua_GetTop(L); if ArgCount > 1 then sText := string(AnsiString(Lua_ToString(L, 2))); if ArgCount > 2 then sPianSe := string(AnsiString(Lua_ToString(L, 3))); if ArgCount > 3 then iRatio := Lua_ToNumber(L, 4); if ArgCount > 4 then iDelay := Lua_ToInteger(L, 5); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 3 then begin Lua_PushInteger(L, -1); Lua_PushInteger(L, -1); Lua_PushInteger(L, -1); Exit; end; vPos := GCommFuns.fn全屏找字_返回坐标(sText, sPianSe, CON_SYS_DICT, iRatio, iDelay); Lua_PushInteger(L, vPos.X); Lua_PushInteger(L, vPos.Y); Lua_PushInteger(L, vPos.Ret); except end; end; function TLuaFuns.MsGetNumber(L: lua_State): Integer; var ArgCount: Integer; sPianSe: string; iRatio: Single; iRet: Int64; X, Y, X1, Y1: Integer; begin Result := 1; try iRatio := 1.0; ArgCount := Lua_GetTop(L); X := Lua_ToInteger(L, 2); Y := Lua_ToInteger(L, 3); X1 := Lua_ToInteger(L, 4); Y1 := Lua_ToInteger(L, 5); if ArgCount > 5 then sPianSe := string(AnsiString(Lua_ToString(L, 6))); if ArgCount > 6 then iRatio := Lua_ToNumber(L, 7); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 5 then begin Lua_PushInteger(L, -1); Exit; end; iRet := GCommFuns.fn获取数量(X, Y, X1, Y1, sPianSe, iRatio); Lua_PushInteger(L, iRet); except end; end; function TLuaFuns.MsPressDel(L: lua_State): Integer; var ArgCount: Integer; iTimes: Integer; iRet: Integer; begin Result := 1; try iTimes := 1; ArgCount := Lua_GetTop(L); if ArgCount > 1 then iTimes := Lua_toInteger(L, 2); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; GCommFuns.pro按下删除键(iTimes); Lua_PushInteger(L, RetOk); except end; end; function TLuaFuns.MsPressEnter(L: lua_State): Integer; var iRet: Integer; cmd: string; begin Result := 1; try iRet := GCommFuns.KeyPress(VK_RETURN); //if uCommFuns.MsKeyPress(VK_RETURN) then iRet := 1 else iRet := 0; //cmd:= Format('%sIoPress.exe 2 %d', [GSharedInfo.AppPath, VK_RETURN]); //if GCommFuns.StartProcess(cmd, False) then iRet := 1 else iRet := 0; Lua_PushInteger(L, iRet); except end; end; function TLuaFuns.MsPressEsc(L: lua_State): Integer; var iRet: Integer; begin Result := 1; try iRet := GCommFuns.KeyPress(VK_ESCAPE); Lua_PushInteger(L, iRet); except end; end; function TLuaFuns.MsCaptureGame(L: lua_State): Integer; var ArgCount: Integer; sFileName: string; bRet: Boolean; begin Result := 1; try ArgCount := lua_gettop(L); sFileName := string(AnsiString(lua_tostring(L, 2))); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin lua_pushinteger(L, RetErr); Exit; end; bRet := GCommFuns.fn截取屏幕(sFileName); if not bRet then begin lua_pushinteger(L, RetErr); Exit; end; lua_pushinteger(L, RetOK); except end; end; function TLuaFuns.MsCaptureArea(L: lua_State): Integer; var ArgCount, X, Y, X1, Y1: Integer; sFileName: string; bRet: Boolean; begin Result := 1; try ArgCount := lua_gettop(L); X := Lua_ToInteger(L, 2); Y := Lua_ToInteger(L, 3); X1 := Lua_ToInteger(L, 4); Y1 := Lua_ToInteger(L, 5); sFileName := string(AnsiString(lua_tostring(L, 6))); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 6 then begin lua_pushinteger(L, RetErr); Exit; end; //GCommFuns.DebugInfo('MS '); bRet := GCommFuns.fn截取屏幕_区域(X, Y, X1, Y1, sFileName); if not bRet then begin lua_pushinteger(L, RetErr); Exit; end; lua_pushinteger(L, RetOK); except end; end; function TLuaFuns.MsMoveWindow(L: lua_State): Integer; var ArgCount, X, Y: Integer; hWindow: HWND; iRet: Integer; begin Result := 1; try ArgCount := lua_gettop(L); hWindow := Lua_ToInteger(L, 2); X := Lua_ToInteger(L, 3); Y := Lua_ToInteger(L, 4); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 4 then begin lua_pushinteger(L, RetErr); Exit; end; iRet := GCommFuns.fn移动窗口(hWindow, X, Y); lua_pushinteger(L, iRet); except end; end; function TLuaFuns.MsPressKey(L: lua_State): Integer; var ArgCount: Integer; iKey: Integer; iRet: Integer; begin Result := 1; try iKey := 0; ArgCount := Lua_GetTop(L); if ArgCount > 1 then iKey := Lua_toInteger(L, 2); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; iRet := GCommFuns.fn按键(iKey); Lua_PushInteger(L, iRet); except end; end; function TLuaFuns.MsTheKeysWalk(L: lua_State): Integer; var ArgCount: Integer; iKey: Integer; iTime: Integer; iRet: Integer; begin Result := 1; try iKey := 0; iTime := 500; ArgCount := Lua_GetTop(L); if ArgCount > 1 then iKey := Lua_toInteger(L, 2); if ArgCount > 2 then iTime := Lua_toInteger(L, 3); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; iRet := GCommFuns.fn方向键走路(iKey, iTime); Lua_PushInteger(L, iRet); except end; end; function TLuaFuns.MsPressChar(L: lua_State): Integer; var ArgCount: Integer; sKey: string; iRet: Integer; begin Result := 1; try ArgCount := Lua_GetTop(L); if ArgCount > 1 then sKey := string(AnsiString(lua_tostring(L, 2))); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; iRet := GCommFuns.KeyPressChar(sKey); Lua_PushInteger(L, iRet); except end; end; function TLuaFuns.MsWheelDown(L: lua_State): Integer; var ArgCount: Integer; iRet: Integer; begin Result := 1; try ArgCount := Lua_GetTop(L); Lua_Pop(L, Lua_GetTop(L)); iRet := GCommFuns.WheelDown(); Lua_PushInteger(L, iRet); except end; end; function TLuaFuns.MsMoveTo(L: lua_State): Integer; var X, Y, ArgCount: Integer; begin Result := 1; try ArgCount := Lua_GetTop(L); if ArgCount > 1 then X := Lua_ToInteger(L, 2); if ArgCount > 2 then Y := Lua_ToInteger(L, 3); Lua_Pop(L, Lua_GetTop(L)); GCommFuns.pro移动鼠标(X, Y); lua_pushinteger(L, RetOK); except end; end; function TLuaFuns.MsPressString(L: lua_State): Integer; var ArgCount: Integer; sText: string; hGame: HWND; iRet: Integer; begin Result := 1; ArgCount := lua_gettop(L); if ArgCount < 3 then begin lua_pushinteger(L, RetErr); Exit; end; hGame := lua_tointeger(L, 2); sText := string(AnsiString(lua_tostring(L, 3))); if not IsWindow(hGame) then begin lua_pushinteger(L, RetErr); Exit; end; iRet := GCommFuns.SendString(hGame, sText); lua_pushinteger(L, RetOk); end; function TLuaFuns.MsOcr(L: lua_State): Integer; var ArgCount: Integer; sText, sPianSe: string; iRatio: Single; bRet: Boolean; X, Y, X1, Y1: Integer; begin Result := 1; try iRatio := 1.0; ArgCount := Lua_GetTop(L); sText := 'Error'; if ArgCount < 5 then begin //Lua_PushInteger(L, RetErr); lua_pushstring(L, PAnsiChar(AnsiString(sText))); Exit; end; X := Lua_ToInteger(L, 2); Y := Lua_ToInteger(L, 3); X1 := Lua_ToInteger(L, 4); Y1 := Lua_ToInteger(L, 5); sPianSe := string(AnsiString(Lua_ToString(L, 6))); if ArgCount > 6 then iRatio := Lua_ToNumber(L, 7); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 3 then begin lua_pushstring(L, PAnsiChar(AnsiString(sText))); Exit; end; sText := GCommFuns.Ocr(X, Y, X1, Y1, sPianSe, iRatio); lua_pushstring(L, PAnsiChar(AnsiString(sText))); except end; end; function TLuaFuns.MsOcrEx(L: lua_State): Integer; var ArgCount: Integer; sText, sPianSe: string; iRatio: Single; bRet: Boolean; X, Y, X1, Y1: Integer; begin Result := 1; try iRatio := 1.0; ArgCount := Lua_GetTop(L); sText := 'Error'; if ArgCount < 5 then begin //Lua_PushInteger(L, RetErr); lua_pushstring(L, PAnsiChar(AnsiString(sText))); Exit; end; X := Lua_ToInteger(L, 2); Y := Lua_ToInteger(L, 3); X1 := Lua_ToInteger(L, 4); Y1 := Lua_ToInteger(L, 5); sPianSe := string(AnsiString(Lua_ToString(L, 6))); if ArgCount > 6 then iRatio := Lua_ToNumber(L, 7); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 3 then begin lua_pushstring(L, PAnsiChar(AnsiString(sText))); Exit; end; sText := GCommFuns.OcrEx(X, Y, X1, Y1, sPianSe, iRatio); lua_pushstring(L, PAnsiChar(AnsiString(sText))); except end; end; {$ENDREGION} {$REGION '公共变量'} function TLuaFuns.MsGetGameHandle(L: lua_State): Integer; begin Result := 1; try if IsWindow(GSharedInfo.GameWindow) then begin Lua_PushInteger(L, GSharedInfo.GameWindow); end else begin Lua_PushInteger(L, RetErr); end; except end; end; function TLuaFuns.MsSetGameHandle(L: lua_State): Integer; var ArgCount: Integer; hGameWindow: HWND; begin Result := 1; try ArgCount := Lua_GetTop(L); hGameWindow := lua_ToInteger(L, 2); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; GSharedInfo.GameWindow := hGameWindow; Lua_PushInteger(L, RetOk); except end; end; {$ENDREGION} {$REGION '公共参数'} function TLuaFuns.MsGetDelay(L: lua_State): Integer; var sKey: string; ArgCount: Integer; iRet: Integer; begin Result := 1; try ArgCount := lua_gettop(L); sKey := string(AnsiString(lua_tostring(L, 2))); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin lua_pushinteger(L, RetErr); Exit; end; iRet := GCommFuns.GetDealy(sKey); lua_pushinteger(L, iRet); except end; end; function TLuaFuns.MsGetPianSe(L: lua_State): Integer; var sKey, sRet: string; ArgCount: Integer; begin Result := 1; try ArgCount := lua_gettop(L); sKey := string(AnsiString(lua_tostring(L, 2))); Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin lua_pushinteger(L, RetErr); Exit; end; sRet := GCommFuns.GetPianSe(sKey); lua_pushstring(L, PAnsiChar(AnsiString(sRet))); except end; end; {$ENDREGION} {$REGION '通讯'} function TLuaFuns.MsPostStatus(L: lua_State): Integer; var ArgCount: Integer; sText: string; vStatus: TTaskState; bRestart, bRet: Boolean; begin Result := 1; try vStatus := tsNormal; bRestart := True; ArgCount := Lua_GetTop(L); if ArgCount > 1 then sText := string(AnsiString(lua_tostring(L, 2))); if ArgCount > 2 then vStatus := TTaskState(lua_toInteger(L, 3)); if ArgCount > 3 then bRestart := lua_toInteger(L, 4) <> 0; Lua_Pop(L, Lua_GetTop(L)); if ArgCount < 2 then begin Lua_PushInteger(L, RetErr); Exit; end; bRet := TradeClient.PostStatus(sText, [], vStatus, bRestart); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except end; end; function TLuaFuns.MsResetRoleStep(L: lua_State): Integer; var ArgCount: Integer; vRoleStep: Integer; bRet: Boolean; begin Result := 1; try ArgCount := lua_gettop(L); if ArgCount < 2 then Exit; vRoleStep := lua_tointeger(L, 2); Lua_Pop(L, ArgCount); bRet := TradeClient.ReSetRoleStep(GSharedInfo.ClientSet.GroupName, GSharedInfo.OrderItem.roles[GSharedInfo.RoleIndex].role, GSharedInfo.OrderItem.roles[GSharedInfo.RoleIndex].receiptRole, vRoleStep); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except end; end; function TLuaFuns.MsGetRoleStep(L: lua_State): Integer; var vRoleStep: TRoleStep; begin Result := 1; try Lua_Pop(L, lua_gettop(L)); vRoleStep := TradeClient.GetRoleStep(GSharedInfo.ClientSet.GroupName); Lua_PushInteger(L, Integer(vRoleStep)); except end; end; function TLuaFuns.MsGetTargetRoleStep(L: lua_State): Integer; var ArgCount: Integer; vRoleStep: TRoleStep; sRoleName, sTargetRoleName: string; begin Result := 1; try ArgCount := lua_gettop(L); Lua_Pop(L, ArgCount); vRoleStep := TradeClient.GetTargetRoleStep(GSharedInfo.ClientSet.GroupName , GSharedInfo.OrderItem.roles[GSharedInfo.RoleIndex].role , GSharedInfo.OrderItem.roles[GSharedInfo.RoleIndex].receiptRole ); Lua_PushInteger(L, Integer(vRoleStep)); except end; end; function TLuaFuns.MsSetMasterRecRoleName(L: lua_State): Integer; var ArgCount: Integer; sRecRoleName, sMasterRoleName: string; bRet: Boolean; begin Result := 1; try ArgCount := lua_gettop(L); //if ArgCount < 3 then Exit; //sMasterRoleName := string(AnsiString(lua_tostring(L, 2))); //sRecRoleName := string(AnsiString(lua_tostring(L, 3))); Lua_Pop(L, ArgCount); bRet := TradeClient.SetMasterRecRoleName( GSharedInfo.ClientSet.GroupName, GSharedInfo.OrderItem.orderNo, GSharedInfo.OrderItem.roles[GSharedInfo.RoleIndex].receiptRole, GSharedInfo.OrderItem.roles[GSharedInfo.RoleIndex].role); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except end; end; function TLuaFuns.MsClearRecvRoleName(L: lua_State): Integer; var ArgCount: Integer; sRecRoleName, sMasterRoleName: string; bRet: Boolean; begin Result := 1; try ArgCount := lua_gettop(L); Lua_Pop(L, ArgCount); bRet := TradeClient.ClearRecvRoleName( GSharedInfo.ClientSet.GroupName, GSharedInfo.OrderItem.orderNo, GSharedInfo.OrderItem.roles[GSharedInfo.RoleIndex].role); if not bRet then begin Lua_PushInteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except end; end; function TLuaFuns.MsGetMasterRecRoleName(L: lua_State): Integer; var ArgCount: Integer; sTargetRoleName, sMasterRoleName: string; begin Result := 1; try ArgCount := lua_gettop(L); if ArgCount < 2 then Exit; sMasterRoleName := string(AnsiString(lua_tostring(L, 2))); Lua_Pop(L, ArgCount); sTargetRoleName := TradeClient.GetMasterRecRoleName(GSharedInfo.ClientSet.GroupName, sMasterRoleName); lua_pushstring(L, PAnsiChar(AnsiString(sTargetRoleName))); AddLogMsg('获取到的子号角色为[%s]', [sTargetRoleName], True); except end; end; function TLuaFuns.MsSetRoleStep(L: lua_State): Integer; var ArgCount: Integer; vRoleStep: Integer; bRet: Boolean; begin Result := 1; try ArgCount := lua_gettop(L); if ArgCount < 2 then Exit; vRoleStep := lua_tointeger(L, 2); Lua_Pop(L, ArgCount); bRet := TradeClient.SetRoleStep( GSharedInfo.ClientSet.GroupName, GSharedInfo.OrderItem.roles[GSharedInfo.RoleIndex].role, vRoleStep ); if not bRet then begin lua_pushinteger(L, RetErr); Exit; end; Lua_PushInteger(L, RetOK); except on E: Exception do AddLogMsg('MsPostRoleInfo fail[%s]...', [E.Message]); end; end; {$ENDREGION} end.
unit UC.HTTPClient.Delphi; interface uses System.Classes, System.Net.HTTPClient, UC.Net.Interfaces; type TDelphiHTTP = class(TInterfacedObject, IucHTTPRequest) private FHTTP: THTTPClient; FResponse: IHTTPResponse; FStatusCode: Integer; FStatusText: string; FStatusType: THTTPStatusType; protected function GetResponseStr: string; function GetStatusCode: Integer; function GetStatusText: string; function GetStatusType: THTTPStatusType; procedure Clear; function Post(AURL: string; AData: string): boolean; public constructor Create; destructor Destroy; override; end; implementation uses System.SysUtils; { TDelphiHTTP } procedure TDelphiHTTP.Clear; begin FResponse := nil; FStatusCode := -1; FStatusText := ''; end; constructor TDelphiHTTP.Create; begin inherited Create; FHTTP := THTTPClient.Create; end; destructor TDelphiHTTP.Destroy; begin FHTTP.Free; inherited; end; function TDelphiHTTP.GetResponseStr: string; begin result := FResponse.ContentAsString; end; function TDelphiHTTP.GetStatusCode: Integer; begin result := FStatusCode; end; function TDelphiHTTP.GetStatusText: string; begin result := FStatusText; end; function TDelphiHTTP.GetStatusType: THTTPStatusType; begin result := FStatusType; end; function TDelphiHTTP.Post(AURL, AData: string): boolean; var lStream: TStringStream; begin FStatusText := ''; lStream := TStringStream.Create(AData); try lStream.Position := 0; try FResponse := FHTTP.Post(AURL, lStream); FStatusCode := FResponse.StatusCode; result := (FResponse.StatusCode >= 200) AND (FResponse.StatusCode <= 299); if result then FStatusType := THTTPStatusType.OK else begin FStatusType := THTTPStatusType.Fail; try FStatusText := FResponse.StatusText; except end; end; except on E: Exception do begin FStatusType := THTTPStatusType.Exception; FStatusText := E.ClassName + ':' + E.Message; result := False; end; end; finally lStream.Free; end; end; end.
{***********************************************} {* Connect 4 - Player Related Attributes *} {* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *} {* *} {* Author: Nathan Bartram *} {* Contact: nathan_bartram@hotmail.co.uk *} {* Licence: GPL *} {* *} {***********************************************} unit PlayersDialog; {$mode objfpc}{$H+} interface uses LResources, Forms, Controls, Graphics, ButtonPanel, StdCtrls, ExtCtrls, Classes; type { TPlayersDialogForm } TPlayersDialogForm = class(TForm) ButtonPanel: TButtonPanel; Player1TypeCPURadioButton: TRadioButton; Player1TypeHumRadioButton: TRadioButton; Player2LabeledEdit: TLabeledEdit; Player2Coin: TImage; Player1GroupBox: TGroupBox; Player1Coin: TImage; Player2GroupBox: TGroupBox; Player1LabeledEdit: TLabeledEdit; Player2TypeCPURadioButton: TRadioButton; Player2TypeHumRadioButton: TRadioButton; procedure FormCreate(Sender: TObject); procedure PlayerRadioButtonClick(Sender: TObject); public IsPlayer1Bot: boolean; IsPlayer2Bot: boolean; FirstShow: boolean; Skin: string; procedure UpdateForm; end; var PlayersDialogForm: TPlayersDialogForm; implementation { TPlayersDialogForm } //----------------------------------------------------------------------------// procedure TPlayersDialogForm.PlayerRadioButtonClick(Sender: TObject); begin if FirstShow then // laz bug, click event triggered on first show of form begin // so added varaible to check if Player1TypeHumRadioButton.Checked then IsPlayer1Bot:=false else IsPlayer1Bot:=true; if Player2TypeHumRadioButton.Checked then IsPlayer2Bot:=false else IsPlayer2Bot:=true; end else FirstShow:=true; end; //----------------------------------------------------------------------------// procedure TPlayersDialogForm.FormCreate(Sender: TObject); begin FirstShow:=false; end; //----------------------------------------------------------------------------// procedure TPlayersDialogForm.UpdateForm; begin if IsPlayer1Bot then Player1TypeCPURadioButton.Checked:=true else Player1TypeHumRadioButton.Checked:=true; if IsPlayer2Bot then Player2TypeCPURadioButton.Checked:=true else Player2TypeHumRadioButton.Checked:=true; Player1Coin.Picture.LoadFromLazarusResource(Skin+'RedCoin'); Player2Coin.Picture.LoadFromLazarusResource(Skin+'YellowCoin'); end; //----------------------------------------------------------------------------// initialization {$I playersdialog.lrs} end.
PROGRAM WorkWithQueryString(INPUT, OUTPUT); USES DOS; VAR QueryString: String; FUNCTION GetQueryStringParameter(Key: String): String; VAR Position, AmperPosition: LongInt; BEGIN {GetQueryStringParameter} QueryString := GetEnv('QUERY_STRING'); Position := Pos(Key, QueryString); IF Position <> 0 THEN BEGIN DELETE(QueryString, 1, Position + Length(Key)); AmperPosition := Pos('&', QueryString); IF AmperPosition <> 0 THEN GetQueryStringParameter := Copy(QueryString, 1, AmperPosition - 1) ELSE GetQueryStringParameter := QueryString END ELSE GetQueryStringParameter := ('Parameter not found'); END; {GetQueryStringParameter} BEGIN {WorkWithQueryString} WRITELN('Content-Type: text/plain'); WRITELN; WRITELN('First Name: ', GetQueryStringParameter('first_name')); WRITELN('Last Name: ', GetQueryStringParameter('last_name')); WRITELN('Age: ', GetQueryStringParameter('age')) END. {WorkWithQueryString}
{*******************************************************} { } { FMX UI Frame 管理单元 } { } { 版权所有 (C) 2016 YangYxd } { } {*******************************************************} unit UI.Frame; interface uses UI.Base, UI.Toast, UI.Dialog, System.NetEncoding, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Generics.Collections, System.Rtti, System.SyncObjs, {$IFDEF ANDROID}FMX.Platform.Android, {$ENDIF} {$IFDEF POSIX}Posix.Signal, {$ENDIF} FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Platform, IOUtils; type TFrameView = class; TFrameViewClass = class of TFrameView; /// <summary> /// Frame 参数 /// </summary> TFrameParams = TDictionary<string, TValue>; TFrameDataType = (fdt_Integer, fdt_Long, fdt_Int64, fdt_Float, fdt_String, fdt_DateTime, fdt_Number, fdt_Boolean); TFrameDataValue = record DataType: TFrameDataType; Value: TValue; end; /// <summary> /// Frame 状态数据 /// </summary> TFrameStateData = TDictionary<string, TFrameDataValue>; TFrameStateDataHelper = class helper for TFrameStateData function GetDataValue(DataType: TFrameDataType; const Value: TValue): TFrameDataValue; function GetString(const Key: string): string; function GetInt(const Key: string; const DefaultValue: Integer = 0): Integer; function GetLong(const Key: string; const DefaultValue: Cardinal = 0): Cardinal; function GetInt64(const Key: string; const DefaultValue: Int64 = 0): Int64; function GetFloat(const Key: string; const DefaultValue: Double = 0): Double; function GetDateTime(const Key: string; const DefaultValue: TDateTime = 0): TDateTime; function GetNumber(const Key: string; const DefaultValue: NativeUInt = 0): NativeUInt; function GetBoolean(const Key: string; const DefaultValue: Boolean = False): Boolean; procedure Put(const Key: string; const Value: string); overload; inline; procedure Put(const Key: string; const Value: Integer); overload; inline; procedure Put(const Key: string; const Value: Cardinal); overload; inline; procedure Put(const Key: string; const Value: Int64); overload; inline; procedure Put(const Key: string; const Value: Double); overload; inline; procedure Put(const Key: string; const Value: NativeUInt); overload; inline; procedure Put(const Key: string; const Value: Boolean); overload; inline; procedure PutDateTime(const Key: string; const Value: TDateTime); inline; end; /// <summary> /// Frame 状态 /// </summary> TFrameState = class(TObject) private [Weak] FOwner: TComponent; FData: TFrameStateData; FIsChange: Boolean; FIsPublic: Boolean; FIsLoad: Boolean; FLocker: TCriticalSection; function GetCount: Integer; function GetStoragePath: string; procedure SetStoragePath(const Value: string); protected procedure InitData; procedure DoValueNotify(Sender: TObject; const Item: TFrameDataValue; Action: TCollectionNotification); function GetUniqueName: string; procedure Load(); public constructor Create(AOwner: TComponent; IsPublic: Boolean); destructor Destroy; override; procedure Clear(); procedure Save(); function Exist(const Key: string): Boolean; function ContainsKey(const Key: string): Boolean; function GetString(const Key: string): string; function GetInt(const Key: string; const DefaultValue: Integer = 0): Integer; function GetLong(const Key: string; const DefaultValue: Cardinal = 0): Cardinal; function GetInt64(const Key: string; const DefaultValue: Int64 = 0): Int64; function GetFloat(const Key: string; const DefaultValue: Double = 0): Double; function GetDateTime(const Key: string; const DefaultValue: TDateTime = 0): TDateTime; function GetNumber(const Key: string; const DefaultValue: NativeUInt = 0): NativeUInt; function GetBoolean(const Key: string; const DefaultValue: Boolean = False): Boolean; procedure Put(const Key: string; const Value: string); overload; procedure Put(const Key: string; const Value: Integer); overload; procedure Put(const Key: string; const Value: Cardinal); overload; procedure Put(const Key: string; const Value: Int64); overload; procedure Put(const Key: string; const Value: Double); overload; procedure Put(const Key: string; const Value: NativeUInt); overload; procedure Put(const Key: string; const Value: Boolean); overload; procedure PutDateTime(const Key: string; const Value: TDateTime); property Data: TFrameStateData read FData; property Count: Integer read GetCount; property StoragePath: string read GetStoragePath write SetStoragePath; end; /// <summary> /// Frame 视图, Frame 切换处理 /// </summary> [ComponentPlatformsAttribute(AllCurrentPlatforms)] TFrameView = class(FMX.Forms.TFrame) private FParams: TFrameParams; FPrivateState: TFrameState; FOnShow: TNotifyEvent; FOnHide: TNotifyEvent; FWaitDialog: TProgressDialog; procedure SetParams(const Value: TFrameParams); function GetTitle: string; procedure SetTitle(const Value: string); function GetPreferences: TFrameState; function GetSharedPreferences: TFrameState; protected [Weak] FLastView: TFrameView; [Weak] FNextView: TFrameView; function MakeFrame(FrameClass: TFrameViewClass): TFrameView; overload; procedure DoShow(); virtual; procedure DoHide(); virtual; // 检查是否需要释放,如果需要,就释放掉 function CheckFree(): Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; /// <summary> /// 流转化为 string /// </summary> function StreamToString(SrcStream: TStream; const CharSet: string = ''): string; /// <summary> /// 显示等待对话框 /// </summary> procedure ShowWaitDialog(const AMsg: string; ACancelable: Boolean = True); /// <summary> /// 隐藏等待对话框 /// </summary> procedure HideWaitDialog(); /// <summary> /// 显示 Frame /// </summary> class function ShowFrame(Parent: TFmxObject; Params: TFrameParams): TFrameView; overload; /// <summary> /// 显示 Frame /// </summary> class function ShowFrame(Parent: TFmxObject; const Title: string = ''): TFrameView; overload; /// <summary> /// 显示 Frame /// </summary> class function CreateFrame(Parent: TFmxObject; Params: TFrameParams): TFrameView; overload; /// <summary> /// 显示 Frame /// </summary> class function CreateFrame(Parent: TFmxObject; const Title: string = ''): TFrameView; overload; /// <summary> /// 开始一个视图,并隐藏当前视图 /// </summary> function StartFrame(FrameClass: TFrameViewClass): TFrameView; overload; /// <summary> /// 开始一个视图,并隐藏当前视图 /// </summary> function StartFrame(FrameClass: TFrameViewClass; Params: TFrameParams): TFrameView; overload; /// <summary> /// 开始一个视图,并隐藏当前视图 /// </summary> function StartFrame(FrameClass: TFrameViewClass; const Title: string): TFrameView; overload; /// <summary> /// 显示一个提示消息 /// </summary> procedure Hint(const Msg: string); overload; procedure Hint(const Msg: Double); overload; procedure Hint(const Msg: Int64); overload; /// <summary> /// 显示 Frame /// </summary> procedure Show(); override; /// <summary> /// 关闭 Frame /// </summary> procedure Close(); virtual; /// <summary> /// 隐藏 Frame /// </summary> procedure Hide(); override; /// <summary> /// 完成当前 Frame (返回上一个 Frame 或 关闭) /// </summary> procedure Finish(); virtual; /// <summary> /// 启动时的参数 /// </summary> property Params: TFrameParams read FParams write SetParams; /// <summary> /// 启动此Frame的Frame /// </summary> property Last: TFrameView read FLastView; /// <summary> /// 私有预设参数 (私有,非线程安全) /// </summary> property Preferences: TFrameState read GetPreferences; /// <summary> /// 共有预设参数 (全局,非线程安全) /// </summary> property SharedPreferences: TFrameState read GetSharedPreferences; published property Title: string read GetTitle write SetTitle; property OnShow: TNotifyEvent read FOnShow write FOnShow; property OnHide: TNotifyEvent read FOnHide write FOnHide; end; type TFrame = class(TFrameView); var MainFormMinChildren: Integer = 1; implementation const CS_Title = 'title'; var /// <summary> /// 公共状态数据 /// </summary> FPublicState: TFrameState = nil; { TFrameView } function TFrameView.CheckFree: Boolean; begin Result := False; if Assigned(Parent) then begin if not Assigned(Parent.Parent) then begin if (Parent is TForm) and (Parent.ChildrenCount <= MainFormMinChildren + 1) then begin {$IFDEF POSIX} {$IFDEF DEBUG} (Parent as TForm).Close; {$ELSE} Kill(0, SIGKILL); {$ENDIF} {$ELSE} (Parent as TForm).Close; {$ENDIF} Result := True; Exit; end; end; Parent.RemoveObject(Self); end; end; procedure TFrameView.Close; begin if CheckFree then Exit; {$IFNDEF AUTOREFCOUNT} Free; {$ENDIF} end; class function TFrameView.CreateFrame(Parent: TFmxObject; Params: TFrameParams): TFrameView; begin Result := nil; if (Assigned(Parent)) then begin try Result := Create(Parent); Result.Parent := Parent; Result.Align := TAlignLayout.Client; Result.FLastView := nil; Result.TagObject := Params; except if Assigned(Params) then Params.Free; raise; end; end else if Assigned(Params) then Params.Free; end; constructor TFrameView.Create(AOwner: TComponent); begin try inherited Create(AOwner); except Width := 200; Height := 400; end; end; class function TFrameView.CreateFrame(Parent: TFmxObject; const Title: string): TFrameView; begin Result := CreateFrame(Parent, nil); if Result <> nil then Result.Title := Title; end; function TFrameView.MakeFrame(FrameClass: TFrameViewClass): TFrameView; begin Result := FrameClass.Create(Parent); Result.Parent := Parent; Result.Align := TAlignLayout.Client; Result.FLastView := Self; FNextView := Result; end; destructor TFrameView.Destroy; begin if Assigned(FNextView) then FNextView.FLastView := nil; FLastView := nil; FNextView := nil; FreeAndNil(FParams); FreeAndNil(FPrivateState); inherited; end; procedure TFrameView.DoHide; begin if Assigned(FOnHide) then FOnHide(Self); end; procedure TFrameView.DoShow; begin if Assigned(FOnShow) then FOnShow(Self); end; procedure TFrameView.Finish; begin if not Assigned(FLastView) then Close else begin if CheckFree then Exit; FLastView.Show; FLastView.FNextView := nil; FLastView := nil; {$IFNDEF AUTOREFCOUNT} Free; {$ENDIF} end; end; function TFrameView.GetPreferences: TFrameState; begin if not Assigned(FPrivateState) then begin FPrivateState := TFrameState.Create(Self, False); FPrivateState.Load; end; Result := FPrivateState; end; function TFrameView.GetSharedPreferences: TFrameState; begin Result := FPublicState; end; function TFrameView.GetTitle: string; begin if FParams = nil then Result := '' else Result := FParams.Items[CS_Title].ToString; end; procedure TFrameView.Hide; begin Visible := False; DoHide; end; procedure TFrameView.HideWaitDialog; begin if Assigned(FWaitDialog) then begin FWaitDialog.Dismiss; FWaitDialog := nil; end; end; procedure TFrameView.Hint(const Msg: Double); begin Toast(FloatToStr(Msg)); end; procedure TFrameView.Hint(const Msg: Int64); begin Toast(IntToStr(Msg)); end; procedure TFrameView.Hint(const Msg: string); begin Toast(Msg); end; procedure TFrameView.SetParams(const Value: TFrameParams); begin if Assigned(FParams) then FParams.Free; FParams := Value; end; procedure TFrameView.SetTitle(const Value: string); begin if FParams = nil then begin if Value = '' then Exit; FParams := TFrameParams.Create(9); end; if FParams.ContainsKey(CS_Title) then FParams.Items[CS_Title] := Value else if Value <> '' then FParams.Add(CS_Title, Value); end; procedure TFrameView.Show(); begin if Title <> '' then Application.Title := Title; DoShow(); Visible := True; end; class function TFrameView.ShowFrame(Parent: TFmxObject; const Title: string): TFrameView; begin Result := CreateFrame(Parent, Title); if Result <> nil then Result.Show(); end; procedure TFrameView.ShowWaitDialog(const AMsg: string; ACancelable: Boolean); begin if (not Assigned(FWaitDialog)) or (FWaitDialog.IsDismiss) then begin FWaitDialog := nil; FWaitDialog := TProgressDialog.Create(Self); end; FWaitDialog.Cancelable := ACancelable; if not Assigned(FWaitDialog.RootView) then FWaitDialog.InitView(AMsg) else FWaitDialog.Message := AMsg; TDialog(FWaitDialog).Show(); end; function TFrameView.StartFrame(FrameClass: TFrameViewClass; const Title: string): TFrameView; begin Result := MakeFrame(FrameClass); Result.Title := Title; Result.Show(); Hide; end; function TFrameView.StreamToString(SrcStream: TStream; const CharSet: string): string; var LReader: TStringStream; begin if (CharSet <> '') and (string.CompareText(CharSet, 'utf-8') <> 0) then // do not translate LReader := TStringStream.Create('', System.SysUtils.TEncoding.GetEncoding(CharSet), True) else LReader := TStringStream.Create('', System.SysUtils.TEncoding.UTF8, False); try LReader.CopyFrom(SrcStream, 0); Result := LReader.DataString; finally LReader.Free; end; end; function TFrameView.StartFrame(FrameClass: TFrameViewClass; Params: TFrameParams): TFrameView; begin Result := MakeFrame(FrameClass); Result.Params := Params; Result.Show(); Hide; end; function TFrameView.StartFrame(FrameClass: TFrameViewClass): TFrameView; begin Result := MakeFrame(FrameClass); Result.Show(); Hide; end; class function TFrameView.ShowFrame(Parent: TFmxObject; Params: TFrameParams): TFrameView; begin Result := CreateFrame(Parent, Params); if Result <> nil then Result.Show(); end; { TFrameState } procedure TFrameState.Clear; begin FLocker.Enter; if FData <> nil then FData.Clear; FLocker.Leave; end; function TFrameState.ContainsKey(const Key: string): Boolean; begin FLocker.Enter; Result := FData.ContainsKey(Key); FLocker.Leave; end; constructor TFrameState.Create(AOwner: TComponent; IsPublic: Boolean); begin FOwner := AOwner; FData := nil; FIsChange := False; FIsPublic := IsPublic; FLocker := TCriticalSection.Create; InitData; {$IFNDEF MSWINDOWS} StoragePath := TPath.GetDocumentsPath; {$ENDIF} end; destructor TFrameState.Destroy; begin Save(); FreeAndNil(FData); FreeAndNil(FLocker); inherited; end; procedure TFrameState.DoValueNotify(Sender: TObject; const Item: TFrameDataValue; Action: TCollectionNotification); begin if Action <> TCollectionNotification.cnExtracted then FIsChange := True; end; function TFrameState.Exist(const Key: string): Boolean; begin FLocker.Enter; Result := FData.ContainsKey(Key); FLocker.Leave; end; function TFrameState.GetBoolean(const Key: string; const DefaultValue: Boolean): Boolean; begin FLocker.Enter; Result := FData.GetBoolean(Key, DefaultValue); FLocker.Leave; end; function TFrameState.GetCount: Integer; begin if Assigned(FData) then Result := FData.Count else Result := 0; end; function TFrameState.GetDateTime(const Key: string; const DefaultValue: TDateTime): TDateTime; begin FLocker.Enter; Result := FData.GetDateTime(Key, DefaultValue); FLocker.Leave; end; function TFrameState.GetFloat(const Key: string; const DefaultValue: Double): Double; begin FLocker.Enter; Result := FData.GetFloat(Key, DefaultValue); FLocker.Leave; end; function TFrameState.GetInt(const Key: string; const DefaultValue: Integer): Integer; begin FLocker.Enter; Result := FData.GetInt(Key, DefaultValue); FLocker.Leave; end; function TFrameState.GetInt64(const Key: string; const DefaultValue: Int64): Int64; begin FLocker.Enter; Result := FData.GetInt64(Key, DefaultValue); FLocker.Leave; end; function TFrameState.GetLong(const Key: string; const DefaultValue: Cardinal): Cardinal; begin FLocker.Enter; Result := FData.GetLong(Key, DefaultValue); FLocker.Leave; end; function TFrameState.GetNumber(const Key: string; const DefaultValue: NativeUInt): NativeUInt; begin FLocker.Enter; Result := FData.GetNumber(Key, DefaultValue); FLocker.Leave; end; function TFrameState.GetStoragePath: string; var SaveStateService: IFMXSaveStateService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXSaveStateService, SaveStateService) then Result := SaveStateService.GetStoragePath else Result := ''; end; function TFrameState.GetString(const Key: string): string; begin FLocker.Enter; Result := FData.GetString(Key); FLocker.Leave; end; function TFrameState.GetUniqueName: string; const UniqueNameSeparator = '_'; UniqueNamePrefix = 'FM'; UniqueNameExtension = '.Data'; var B: TStringBuilder; begin if FIsPublic then Result := 'AppPublicState.Data' else begin B := TStringBuilder.Create(Length(UniqueNamePrefix) + FOwner.ClassName.Length + Length(UniqueNameSeparator) + Length(UniqueNameExtension)); try B.Append(UniqueNamePrefix); B.Append(UniqueNameSeparator); B.Append(FOwner.ClassName); B.Append(UniqueNameExtension); Result := B.ToString; finally B.Free; end; end; end; procedure TFrameState.InitData; begin if FData <> nil then FData.Clear else begin if FIsPublic then FData := TFrameStateData.Create(97) else FData := TFrameStateData.Create(29); FData.OnValueNotify := DoValueNotify; end; end; procedure TFrameState.Load; var AStream: TMemoryStream; SaveStateService: IFMXSaveStateService; Reader: TBinaryReader; ACount, I: Integer; ASize: Int64; AKey: string; AType: TFrameDataType; begin FLocker.Enter; if FIsLoad then begin FLocker.Leave; Exit; end; try FData.Clear; AStream := TMemoryStream.Create; if TPlatformServices.Current.SupportsPlatformService(IFMXSaveStateService, SaveStateService) then SaveStateService.GetBlock(GetUniqueName, AStream); ASize := AStream.Size; Reader := nil; if AStream.Size > 0 then begin AStream.Position := 0; Reader := TBinaryReader.Create(AStream); ACount := Reader.ReadInteger; for I := 0 to ACount - 1 do begin if AStream.Position >= ASize then Break; AType := TFrameDataType(Reader.ReadShortInt); AKey := Reader.ReadString; case AType of fdt_Integer: FData.Put(AKey, Reader.ReadInt32); fdt_Long: FData.Put(AKey, Reader.ReadCardinal); fdt_Int64: FData.Put(AKey, Reader.ReadInt64); fdt_Float: FData.Put(AKey, Reader.ReadDouble); fdt_String: FData.Put(AKey, Reader.ReadString); fdt_DateTime: FData.PutDateTime(AKey, Reader.ReadDouble); fdt_Number: FData.Put(AKey, NativeUInt(Reader.ReadUInt64)); fdt_Boolean: FData.Put(AKey, Reader.ReadBoolean); else Break; end; end; end; finally FreeAndNil(AStream); FreeAndNil(Reader); FIsChange := False; FIsLoad := True; FLocker.Leave; end; end; procedure TFrameState.Put(const Key: string; const Value: Cardinal); begin FLocker.Enter; FData.Put(Key, Value); FLocker.Leave; end; procedure TFrameState.Put(const Key: string; const Value: Integer); begin FLocker.Enter; FData.Put(Key, Value); FLocker.Leave; end; procedure TFrameState.Put(const Key, Value: string); begin FLocker.Enter; FData.Put(Key, Value); FLocker.Leave; end; procedure TFrameState.Put(const Key: string; const Value: NativeUInt); begin FLocker.Enter; FData.Put(Key, Value); FLocker.Leave; end; procedure TFrameState.Put(const Key: string; const Value: Boolean); begin FLocker.Enter; FData.Put(Key, Value); FLocker.Leave; end; procedure TFrameState.Put(const Key: string; const Value: Int64); begin FLocker.Enter; FData.Put(Key, Value); FLocker.Leave; end; procedure TFrameState.Put(const Key: string; const Value: Double); begin FLocker.Enter; FData.Put(Key, Value); FLocker.Leave; end; procedure TFrameState.PutDateTime(const Key: string; const Value: TDateTime); begin FLocker.Enter; FData.PutDateTime(Key, Value); FLocker.Leave; end; procedure TFrameState.Save; var SaveStateService: IFMXSaveStateService; AStream: TMemoryStream; Writer: TBinaryWriter; ACount: Integer; Item: TPair<string, TFrameDataValue>; ADoubleValue: Double; begin FLocker.Enter; if not FIsChange then begin FLocker.Leave; Exit; end; try AStream := TMemoryStream.Create; Writer := TBinaryWriter.Create(AStream); ACount := Count; Writer.Write(ACount); for Item in FData do begin Writer.Write(ShortInt(Ord(Item.Value.DataType))); Writer.Write(Item.Key); case Item.Value.DataType of fdt_Integer: Writer.Write(Item.Value.Value.AsInteger); fdt_Long: Writer.Write(Cardinal(Item.Value.Value.AsInteger)); fdt_Int64: Writer.Write(Item.Value.Value.AsInt64); fdt_Float, fdt_DateTime: begin ADoubleValue := Item.Value.Value.AsExtended; Writer.Write(ADoubleValue); end; fdt_String: Writer.Write(Item.Value.Value.AsString); fdt_Number: Writer.Write(Item.Value.Value.AsUInt64); fdt_Boolean: Writer.Write(Item.Value.Value.AsBoolean); end; end; if TPlatformServices.Current.SupportsPlatformService(IFMXSaveStateService, SaveStateService) then SaveStateService.SetBlock(GetUniqueName, AStream); finally FreeAndNil(AStream); FreeAndNil(Writer); FIsChange := False; FLocker.Leave; end; end; procedure TFrameState.SetStoragePath(const Value: string); var SaveStateService: IFMXSaveStateService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXSaveStateService, SaveStateService) then SaveStateService.SetStoragePath(Value); end; { TFrameStateDataHelper } function TFrameStateDataHelper.GetBoolean(const Key: string; const DefaultValue: Boolean): Boolean; begin if ContainsKey(Key) then Result := Items[Key].Value.AsBoolean else Result := DefaultValue; end; function TFrameStateDataHelper.GetDataValue(DataType: TFrameDataType; const Value: TValue): TFrameDataValue; begin Result.DataType := DataType; Result.Value := Value; end; function TFrameStateDataHelper.GetDateTime(const Key: string; const DefaultValue: TDateTime): TDateTime; begin if ContainsKey(Key) then Result := Items[Key].Value.AsExtended else Result := DefaultValue; end; function TFrameStateDataHelper.GetFloat(const Key: string; const DefaultValue: Double): Double; begin if ContainsKey(Key) then Result := Items[Key].Value.AsExtended else Result := DefaultValue; end; function TFrameStateDataHelper.GetInt(const Key: string; const DefaultValue: Integer): Integer; begin if ContainsKey(Key) then Result := Items[Key].Value.AsInteger else Result := DefaultValue; end; function TFrameStateDataHelper.GetInt64(const Key: string; const DefaultValue: Int64): Int64; begin if ContainsKey(Key) then Result := Items[Key].Value.AsInt64 else Result := DefaultValue; end; function TFrameStateDataHelper.GetLong(const Key: string; const DefaultValue: Cardinal): Cardinal; begin if ContainsKey(Key) then Result := Items[Key].Value.AsInteger else Result := DefaultValue; end; function TFrameStateDataHelper.GetNumber(const Key: string; const DefaultValue: NativeUInt): NativeUInt; begin if ContainsKey(Key) then Result := Items[Key].Value.AsOrdinal else Result := DefaultValue; end; function TFrameStateDataHelper.GetString(const Key: string): string; begin if ContainsKey(Key) then Result := Items[Key].Value.ToString else Result := ''; end; procedure TFrameStateDataHelper.Put(const Key: string; const Value: Cardinal); begin AddOrSetValue(Key, GetDataValue(fdt_Long, Value)); end; procedure TFrameStateDataHelper.Put(const Key: string; const Value: Integer); begin AddOrSetValue(Key, GetDataValue(fdt_Integer, Value)); end; procedure TFrameStateDataHelper.Put(const Key, Value: string); begin AddOrSetValue(Key, GetDataValue(fdt_String, Value)); end; procedure TFrameStateDataHelper.Put(const Key: string; const Value: NativeUInt); begin AddOrSetValue(Key, GetDataValue(fdt_Number, Value)); end; procedure TFrameStateDataHelper.Put(const Key: string; const Value: Boolean); begin AddOrSetValue(Key, GetDataValue(fdt_Boolean, Value)); end; procedure TFrameStateDataHelper.Put(const Key: string; const Value: Int64); begin AddOrSetValue(Key, GetDataValue(fdt_Int64, Value)); end; procedure TFrameStateDataHelper.Put(const Key: string; const Value: Double); begin AddOrSetValue(Key, GetDataValue(fdt_Float, Value)); end; procedure TFrameStateDataHelper.PutDateTime(const Key: string; const Value: TDateTime); begin AddOrSetValue(Key, GetDataValue(fdt_DateTime, Value)); end; initialization FPublicState := TFrameState.Create(nil, True); FPublicState.Load; finalization FreeAndNil(FPublicState); end.
unit VSELog; {$IFNDEF VSE_LOG}{$ERROR Please don't include VSELog unit without VSE_LOG defined}{$ENDIF} interface uses Windows, AvL, avlSyncObjs, avlUtils; type TLogLevel = (llDebug, llInfo, llWarning, llError, llAlways); //Level of log message: debug (omitted if VSE_DEBUG is not defined), informational, warning, error, mandatory const LogLevelNames: array[TLogLevel] of string = ('debug', 'info', 'warning', 'error', 'always'); procedure Log(Level: TLogLevel; const S: string); //Add message to log procedure LogF(Level: TLogLevel; const Fmt: string; const Args: array of const); //Add message to log, Format version procedure LogRaw(Level: TLogLevel; const S: string; const Prefix: string = ''); //Add message to log as is procedure LogAssert(Condition: Boolean; const Msg: string); //Add message if Condition=false procedure LogMultiline(Level: TLogLevel; S: string); //Add multiline message to log var LogLevel: TLogLevel = {$IFDEF VSE_DEBUG}llDebug{$ELSE}llInfo{$ENDIF}; //Minimal level of message, that will be passed to log LogOnUpdate: procedure(Level: TLogLevel; const S: string) = nil; //used by VSEConsole implementation type TLogger = class(TThread) private FLogFile: TFileStream; FLogBufferLock: TCriticalSection; FLogEvent: TEvent; FBuffer: string; FLogStart, FLastEvent: Cardinal; FErrors, FWarnings: Integer; protected procedure Execute; override; public constructor Create; destructor Destroy; override; procedure Add(const S: string); function GetPrefix(Level: TLogLevel): string; end; var Logger: TLogger; {$IFNDEF DEBUGMEM}StartHeapStatus, EndHeapStatus: THeapStatus;{$ENDIF} function GetTickCount: Cardinal; var T, F: Int64; begin if QueryPerformanceFrequency(F) and QueryPerformanceCounter(T) then Result := 1000 * (T div F) + (1000 * (T mod F)) div F else Result := Windows.GetTickCount; end; function LogFileName: string; begin Result := ChangeFileExt(FullExeName, '.log'); end; procedure LogAssert(Condition: Boolean; const Msg: string); begin if not Condition then Log(llError, 'Assertion failed: ' + Msg); end; procedure LogMultiline(Level: TLogLevel; S: string); begin while (S <> '') and (S[Length(S)] in [#10, #13]) do Delete(S, Length(S), 1); Log(Level, Tok(#10#13, S)); while S <> '' do LogRaw(Level, Tok(#10#13, S)); end; procedure Log(Level: TLogLevel; const S: string); begin if not Assigned(Logger) then Exit; LogRaw(Level, S, Logger.GetPrefix(Level)); end; procedure LogF(Level: TLogLevel; const Fmt: string; const Args: array of const); begin Log(Level, Format(Fmt, Args)); end; procedure LogRaw(Level: TLogLevel; const S: string; const Prefix: string = ''); begin if (Level < LogLevel) or not Assigned(Logger) then Exit; if Assigned(LogOnUpdate) then LogOnUpdate(Level, S); Logger.Add(Prefix + S); end; { TLogger } constructor TLogger.Create; begin if not FileExists(LogFileName) then CloseHandle(FileCreate(LogFileName)); FLogFile := TFileStream.Create(LogFileName, fmOpenWrite or fmShareDenyWrite); FLogFile.Position := 0; SetEndOfFile(FLogFile.Handle); FLogEvent := TEvent.Create(nil, false, false, ''); FLogBufferLock := TCriticalSection.Create; FLogStart := GetTickCount; FLastEvent := FLogStart; Add('Log started at ' + DateTimeToStr(Now) + #13#10); inherited Create(false); end; destructor TLogger.Destroy; begin Add(#13#10'Log closed at ' + DateTimeToStr(Now)); Add('Errors: ' + IntToStr(FErrors) + ', Warnings: ' + IntToStr(FWarnings)); Terminate; FLogEvent.SetEvent; WaitFor; FAN(FLogEvent); FAN(FLogBufferLock); FAN(FLogFile); inherited; end; procedure TLogger.Add(const S: string); begin FLogBufferLock.Acquire; try FBuffer := FBuffer + S + #13#10; finally FLogBufferLock.Release; end; FLogEvent.SetEvent; end; function TLogger.GetPrefix(Level: TLogLevel): string; var Time, Delta: Cardinal; begin FLogBufferLock.Acquire; try Time := GetTickCount; Delta := Time - FLastEvent; FLastEvent := Time; Time := Time - FLogStart; finally FLogBufferLock.Release; end; Result := Format('[%02d:%02d:%02d.%03d (+%d ms)] ', [Time div 3600000, Time mod 3600000 div 60000, Time mod 60000 div 1000, Time mod 1000, Delta]); if Level = llError then begin InterlockedIncrement(FErrors); Result := Result + 'Error: '; end else if Level = llWarning then begin InterlockedIncrement(FWarnings); Result := Result + 'Warning: '; end; end; procedure TLogger.Execute; var Buffer: string; procedure WriteBuffer; begin FLogBufferLock.Acquire; try Buffer := FBuffer; FBuffer := ''; finally FLogBufferLock.Release; end; FLogFile.Write(Buffer[1], Length(Buffer)); FlushFileBuffers(FLogFile.Handle); end; begin while not Terminated do if FLogEvent.WaitFor(INFINITE) = wrSignaled then WriteBuffer else begin Buffer := 'LogEvent error: ' + SysErrorMessage(FLogEvent.LastError); FLogFile.Write(Buffer[1], Length(Buffer)); FlushFileBuffers(FLogFile.Handle); Break; end; WriteBuffer; end; {$IFNDEF DEBUGMEM} procedure CheckLeaks; var F: TFileStream; procedure WriteLn(S: string); begin S := S + #13#10; F.Write(S[1], Length(S)); end; procedure LogHeapStatus(Status: THeapStatus); begin with Status do begin WriteLn(Format(' Totals: Allocated: %u; Free: %u; Committed: %u; Uncommitted: %u; AddrSpace: %u', [TotalAllocated, TotalFree, TotalCommitted, TotalUncommitted, TotalAddrSpace])); WriteLn(Format(' Free: Small: %u, Big: %u; Unused: %u; Overhead: %u; ErrorCode: %u', [FreeSmall, FreeBig, Unused, Overhead, HeapErrorCode])); end; end; begin if EndHeapStatus.TotalAllocated <> StartHeapStatus.TotalAllocated then begin F := TFileStream.Create(LogFileName, fmOpenWrite or fmShareDenyWrite); try F.Position := F.Size; WriteLn(#13#10'Memory leak detected: ' + SizeToStr(Int64(EndHeapStatus.TotalAllocated) - StartHeapStatus.TotalAllocated)); WriteLn('Start heap status:'); LogHeapStatus(StartHeapStatus); WriteLn('End heap status:'); LogHeapStatus(EndHeapStatus); finally F.Free; end; end; end; {$ENDIF} initialization IsMultiThread := true; {$IFNDEF DEBUGMEM}StartHeapStatus := GetHeapStatus;{$ENDIF} Logger := TLogger.Create; finalization FAN(Logger); {$IFNDEF DEBUGMEM} EndHeapStatus := GetHeapStatus; CheckLeaks; {$ENDIF} end.
unit RenamePlaylistUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons; type TRenamePlaylistForm = class(TForm) NameLabel: TLabel; NameEdit: TEdit; SaveButton: TBitBtn; CancelButton: TBitBtn; procedure SaveButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var RenamePlaylistForm: TRenamePlaylistForm; implementation {$R *.dfm} uses MainUnit, LocalizationUnit, ToolsUnit; const PLAYLISTS_NAME = 'Playlists'; procedure TRenamePlaylistForm.CancelButtonClick(Sender: TObject); begin RenamePlaylistForm.Close; end; procedure TRenamePlaylistForm.SaveButtonClick(Sender: TObject); var ErrorCap, ErrorMsg, TrackName, NewPlaylistName, CurrentPlaylist: string; IsClosed, IsPlayed: Boolean; CurrentPosition: Integer; begin if Length(NameEdit.Text) <> 0 then begin if not FileExists(ExeDirectory + PLAYLISTS_NAME) then CreateDir(ExeDirectory + PLAYLISTS_NAME); MainForm.MusicListBox.FileName := ExeDirectory; IsClosed := False; if IsActive then begin IsPlayed := IsPlaying; CurrentPlaylist := CurrentPlaylistDirectory; IsClosed := True; TrackName := Tools.CuteName(MainForm.MusicPlayer.FileName); CurrentPosition := MainForm.MusicPlayer.Position; MainForm.MusicPlayer.Close; end; NewPlaylistName := ExeDirectory + '\' + PLAYLISTS_NAME + '\' + NameEdit.Text; RenameFile(CurrentPlaylistDirectory, NewPlaylistName); MainForm.UpdatePlaylists; CurrentPlaylistDirectory := NewPlaylistName; MainForm.MusicListBox.Directory := CurrentPlaylistDirectory; MainForm.MusicListBox.Update; MainForm.MusicLabel.Caption := NameEdit.Text; if IsClosed then begin if NowPlayPlaylistDir = CurrentPlaylist then begin MainForm.OpenTrack(NewPlaylistName + '\' + TrackName); NowPlayPlaylistDir := NewPlaylistName; end else MainForm.OpenTrack(NowPlayPlaylistDir + '\' + TrackName); MainForm.MusicPlayer.Position := CurrentPosition; if isPlayed then MainForm.PlayMusic else MainForm.PauseMusic; end; RenamePlaylistForm.Close; end else begin Localization.SelectLanguageForMessage( ErrorCap, ErrorMsg, ERROR_CAP_RUS, ENT_PLST_NAME_RUS, ERROR_CAP_ENG, ENT_PLST_NAME_ENG); MessageBox(Handle, PChar(ErrorMsg), PChar(ErrorCap), MB_OK + MB_ICONERROR); end; end; end.
unit FreeOTFEExplorerfrmPropertiesDlg_Base; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, SDUForms, SDFilesystem_FAT; type TfrmPropertiesDialog_Base = class(TSDUForm) pbOK: TButton; pbApply: TButton; pbCancel: TButton; PageControl1: TPageControl; tsGeneral: TTabSheet; edFileType: TLabel; lblFileType: TLabel; edLocation: TLabel; lblSizeOnDisk: TLabel; edSizeOnDisk: TLabel; lblSize: TLabel; edSize: TLabel; lblLocation: TLabel; lblAttributes: TLabel; ckReadOnly: TCheckBox; ckHidden: TCheckBox; edFilename: TEdit; Panel2: TPanel; Panel3: TPanel; imgFileType: TImage; ckArchive: TCheckBox; procedure pbOKClick(Sender: TObject); procedure pbApplyClick(Sender: TObject); procedure FormShow(Sender: TObject); protected procedure SetupCtlCheckbox(chkBox: TCheckbox); procedure SetupCtlSeparatorPanel(pnl: TPanel); public Filesystem: TSDFilesystem_FAT; end; implementation {$R *.dfm} uses SDUGeneral, SDUGraphics, SDUi18n; procedure TfrmPropertiesDialog_Base.FormShow(Sender: TObject); begin PageControl1.ActivePage := tsGeneral; SetupCtlSeparatorPanel(Panel2); SetupCtlSeparatorPanel(Panel3); // Should be enabled for individual files and directories, but since we // don't support allowing the user to change the directory/filenames from // here (yet)... edFilename.Readonly := TRUE; edFilename.Color := clBtnFace; edFilename.Text := ''; SetupCtlCheckbox(ckReadOnly); SetupCtlCheckbox(ckHidden); edSizeOnDisk.Caption := _('<not calculated>'); // Updating not currently supported. SDUEnableControl(pbOK, FALSE); SDUEnableControl(pbApply, FALSE); end; procedure TfrmPropertiesDialog_Base.pbApplyClick(Sender: TObject); begin // Do nothing... end; procedure TfrmPropertiesDialog_Base.pbOKClick(Sender: TObject); begin ModalResult := mrOK; end; procedure TfrmPropertiesDialog_Base.SetupCtlCheckbox(chkBox: TCheckbox); begin // Nothing - should really set to readonly, since we don't support letting // the user change these end; procedure TfrmPropertiesDialog_Base.SetupCtlSeparatorPanel(pnl: TPanel); begin pnl.Caption := ''; pnl.Height := 3; pnl.BevelOuter := bvLowered; pnl.BevelInner := bvNone; end; END.
unit uOPCFilter; interface uses Classes, Contnrs, SysUtils, uExprEval, uDCObjects, aCustomOPCSource, aOPCCinema; type EaOPCFilterException = class(Exception) end; // вычислитель выполняет расчет фильтра на каждый момент времени TaOPCFilterCalc = class private FEval: TExpressionCompiler; FCinema: TaOPCCinema; FOnCalcValueExpr: TCompiledExpression; public constructor Create; destructor Destroy; override; function Calc: Double; procedure Recompile(aExpression: string); property Eval: TExpressionCompiler read FEval; property Cinema: TaOPCCinema read FCinema; end; // Фильтр хранит информацию о датчиках и выражение для вычисления фильтра TaOPCFilter = class(TPersistent) private FEvaluator: TaOPCFilterCalc; FExpression: string; FDataLink: TaOPCDataLink; FDataLinks: TObjectList; FActive: Boolean; FAutoActive: Boolean; procedure SetExpression(const Value: string); procedure SetActive(const Value: Boolean); function GetEvaluator: TaOPCFilterCalc; procedure SetAutoActive(const Value: Boolean); function FindDataLinkByID(aID: TFloat64): TaOPCDataLink; // функция доступа к значению датчика (ступеньки) //function S(aID: TFloat64): TFloat64; function S(aID: TFloat): TFloat; // функция доступа к значению датчика (линия) //function L(aID: TFloat64): TFloat64; function L(aID: TFloat): TFloat; function GetActive: Boolean; function GetAutoActive: Boolean; function GetExpression: string; procedure SetDataLink(const Value: TaOPCDataLink); protected procedure AssignTo(Dest: TPersistent); override; public constructor Create; destructor Destroy; override; function AddDataLink(aID: string; aStairs: TDCStairsOptionsSet; aSource: TaCustomOPCSource): TaOPCDataLink; // фильтр включен: доступно свойство Expression (выключение Active освободит объект Expression) property Active: Boolean read GetActive write SetActive; // датчик, для которого будет применен фильтр property DataLink: TaOPCDataLink read FDataLink write SetDataLink; // датчики, которые учаcтвуют в расчете фильтра property DataLinks: TObjectList read FDataLinks; property Evaluator: TaOPCFilterCalc read GetEvaluator; published // фильтр будет автоматически включаться при попытке доступа к Expression property AutoActive: Boolean read GetAutoActive write SetAutoActive default True; property Expression: string read GetExpression write SetExpression; end; implementation { function S(aID: Double): Double; var aHistoryGroup: TOPCDataLinkGroupHistory; begin Result := 0; if not Assigned(GlobalCinema) then Exit; // 1. найти DataLink по ID aHistoryGroup := GlobalCinema.FindGroupHistory(IntToStr(Round(aID))); if not Assigned(aHistoryGroup) then Exit; // 2. вернуть значение на текущий момент Result := aHistoryGroup.GetValueOnDate(GlobalCinema.CurrentMoment); end; } { TaOPCFilter } function TaOPCFilter.AddDataLink(aID: string; aStairs: TDCStairsOptionsSet; aSource: TaCustomOPCSource): TaOPCDataLink; begin Result := TaOPCDataLink.Create(nil); FDataLinks.Add(Result); Result.PhysID := aID; Result.StairsOptions := aStairs; Result.OPCSource := aSource; end; procedure TaOPCFilter.AssignTo(Dest: TPersistent); var aDestFilter: TaOPCFilter; aDataLink: TaOPCDataLink; i: Integer; begin inherited AssignTo(Dest); if Dest is TaOPCFilter then begin aDestFilter := TaOPCFilter(Dest); aDestFilter.DataLink := DataLink; aDestFilter.Expression := Expression; aDestFilter.DataLinks.Clear; for i := 0 to DataLinks.Count - 1 do begin aDataLink := TaOPCDataLink(DataLinks[i]); aDestFilter.AddDataLink(aDataLink.PhysID, aDataLink.StairsOptions, aDataLink.RealSource); end; aDestFilter.AutoActive := AutoActive; aDestFilter.Active := Active; end; end; constructor TaOPCFilter.Create; begin FDataLink := TaOPCDataLink.Create(nil); FDataLinks := TObjectList.Create; FAutoActive := True; end; destructor TaOPCFilter.Destroy; begin Active := False; FreeAndNil(FDataLinks); FreeAndNil(FDataLink); inherited; end; function TaOPCFilter.FindDataLinkByID(aID: TFloat64): TaOPCDataLink; var i: Integer; aDataLink: TaOPCDataLink; begin Result := nil; if DataLink.ID = Trunc(aID) then begin Result := DataLink end else begin for i := FDataLinks.Count - 1 downto 0 do begin aDataLink := TaOPCDataLink(FDataLinks[i]); if aDataLink.ID = Trunc(aID) then begin Result := aDataLink; Exit; end; end; end; end; function TaOPCFilter.GetActive: Boolean; begin Result := FActive; end; function TaOPCFilter.GetAutoActive: Boolean; begin Result := FAutoActive; end; function TaOPCFilter.GetEvaluator: TaOPCFilterCalc; begin //Result := nil; if Active then begin Result := FEvaluator end else if AutoActive then begin Active := True; Result := FEvaluator; end else raise EaOPCFilterException.Create('Фильтр неактивен (Active = False), вычислитель недоступен.'); end; function TaOPCFilter.GetExpression: string; begin Result := FExpression; end; //function TaOPCFilter.L(aID: TFloat64): TFloat64; function TaOPCFilter.L(aID: TFloat): TFloat; var aDataLink: TaOPCDataLink; begin Result := 0; aDataLink := FindDataLinkByID(aID); if Assigned(aDataLink) then Result := StrToFloatDef(aDataLink.Value, 0) else AddDataLink(IntToStr(Trunc(aID)), [soIncrease, soDecrease], DataLink.OPCSource); end; //function TaOPCFilter.S(aID: TFloat64): TFloat64; function TaOPCFilter.S(aID: TFloat): TFloat; var aDataLink: TaOPCDataLink; begin Result := 0; aDataLink := FindDataLinkByID(aID); if Assigned(aDataLink) then Result := StrToFloatDef(aDataLink.Value, 0) else AddDataLink(IntToStr(Trunc(aID)), [], DataLink.OPCSource); end; procedure TaOPCFilter.SetActive(const Value: Boolean); var i: Integer; aDataLink: TaOPCDataLink; begin if FActive <> Value then begin FActive := Value; FDataLinks.Clear; if FActive then begin FEvaluator := TaOPCFilterCalc.Create; FEvaluator.Eval.AddFuncOfObject('S', S); FEvaluator.Eval.AddFuncOfObject('L', L); FEvaluator.Recompile(FExpression); DataLink.OPCSource := FEvaluator.Cinema; for i := 0 to FDataLinks.Count - 1 do begin aDataLink := TaOPCDataLink(FDataLinks[i]); aDataLink.OPCSource := FEvaluator.Cinema; end; end else begin DataLinks.Clear; DataLink.OPCSource := DataLink.RealSource; FreeAndNil(FEvaluator); end; end; end; procedure TaOPCFilter.SetAutoActive(const Value: Boolean); begin FAutoActive := Value; end; procedure TaOPCFilter.SetDataLink(const Value: TaOPCDataLink); begin FDataLink.Assign(Value); end; procedure TaOPCFilter.SetExpression(const Value: string); begin if FExpression <> Value then begin FExpression := Value; if Active then begin Active := False; Active := True; //Evaluator.Recompile(FExpression); end; end; end; { TaOPCFilterCalc } function TaOPCFilterCalc.Calc: Double; begin Result := FOnCalcValueExpr; end; constructor TaOPCFilterCalc.Create; begin FEval := TExpressionCompiler.Create; FCinema := TaOPCCinema.Create(nil); end; destructor TaOPCFilterCalc.Destroy; begin FreeAndNil(FCinema); FreeAndNil(FEval); inherited; end; procedure TaOPCFilterCalc.Recompile(aExpression: string); begin FOnCalcValueExpr := FEval.Compile(aExpression); // выполнем тестовый расчет, чтобы заполнить DataLinks Calc; end; end.
unit Game; interface Type Tile = record Blocked : boolean; end; Type GameField = array[0..800, 0..600] of Tile; function InitField() : GameField; function GenerationBorder(x : Integer) : Real; implementation function GenerationBorder(x : Integer) : Real; BEGIN GenerationBorder := 300 * cos(x/350) + 200; END; function InitField() : GameField; var i,j : Integer; BEGIN for i:=0 to 800 do BEGIN for j:=0 to 600 do BEGIN InitField[i][j].Blocked := (j >= GenerationBorder(i)); END; END; END; end.
// ---------------------------------------------------------------------------// // // dgViewportZBuffer // // Copyright © 2005-2009 DunconGames. All rights reserved. BSD License. Authors: simsmen // ---------------------------------------------------------------------------// // // ---------------------------------------------------------------------------// // History: // // 2009.04.11 simsmen // ---------------------------------------------------------------------------// // Bugs: // // ---------------------------------------------------------------------------// // Future: // // ---------------------------------------------------------------------------// unit dgViewportZBuffer; {$DEFINE dgAssert} {$DEFINE dgTrace} interface procedure dgInitViewportZBuffer; implementation uses OpenGL, windows, dgHeader, dgTraceCore, dgCore; const cnstUnitName = 'dgViewportZBuffer'; type TdgViewport3D = class(TdgDrawNotifier) constructor Create; destructor Destroy; override; private fDeltaTime: TdgFloat; public function pDeltaTime: PdgFloat; override; procedure Render; override; procedure Attach(const aNode: TdgDrawable); overload; override; procedure Detach(const aNode: TdgDrawable); overload; override; procedure Attach(const aNode: TdgLightable); overload; override; procedure Detach(const aNode: TdgLightable); overload; override; procedure DetachAllDrawable; override; end; constructor TdgViewport3D.Create; begin inherited Create; fDeltaTime := 0.0; end; destructor TdgViewport3D.Destroy; begin inherited Destroy; end; procedure TdgViewport3D.DetachAllDrawable; begin dgTrace.Write.Warning('DetachAllDrawable not work',cnstUnitName); end; procedure TdgViewport3D.Attach(const aNode: TdgDrawable); begin end; procedure TdgViewport3D.Detach(const aNode: TdgDrawable); begin end; procedure TdgViewport3D.Attach(const aNode: TdgLightable); begin end; procedure TdgViewport3D.Detach(const aNode: TdgLightable); begin end; function TdgViewport3D.pDeltaTime: PdgFloat; begin result := @fDeltaTime; end; procedure TdgViewport3D.Render; var T: LARGE_INTEGER; F: LARGE_INTEGER; Time: TdgFloat; begin QueryPerformanceFrequency(Int64(F)); QueryPerformanceCounter(Int64(T)); Time := T.QuadPart / F.QuadPart; dg.Window.Clear(false,true,false); QueryPerformanceCounter(Int64(T)); fDeltaTime := T.QuadPart / F.QuadPart - Time; end; function dgCreate3DRenderSet: TObject; begin result := TdgViewport3D.Create; end; procedure dgInitViewportZBuffer; begin dg.DrawNotifier.ZBuffer:=dg.CreateOnly.ObjectFactory( nil, nil, @dgCreate3DRenderSet, nil); end; end.
program symetrical_array; var i, j: integer; is_symetrical: boolean; arr: array[1 .. 4, 1 .. 4] of integer; begin randomize; for i := 1 to 4 do for j := 1 to 4 do arr[i, j] := random(2) + 1; is_symetrical := true; for i := 1 to 4 do begin for j := 1 to 4 do begin write(arr[i, j], ' '); if (arr[i, j] <> arr[j, i]) then is_symetrical := false; end; writeln; end; if (is_symetrical) then writeln('The array is symetrical.') else writeln('The array is NOT symetrical.'); end.
(* * 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. * * Contributor(s): * Jody Dawkins <jdawkins@delphixtreme.com> *) unit dSpec; interface uses Specifiers, dSpecIntf, BaseObjects, TestFramework, AutoDocObjects; type TSpecify = class(TObject) private FContext: IContext; public constructor Create(AContext : IContext); destructor Destroy; override; function That(Value : Integer; const ValueName : string = '') : ISpecifier; overload; function That(Value : Boolean; const ValueName : string = '') : ISpecifier; overload; function That(Value : Extended; const ValueName : string = '') : ISpecifier; overload; function That(Value : string; const ValueName : string = '') : ISpecifier; overload; function That(Value : TObject; const ValueName : string = '') : ISpecifier; overload; function That(Value : Pointer; const ValueName : string = '') : ISpecifier; overload; function That(Value : TClass; const ValueName : string = '') : ISpecifier; overload; function That(Value : TDateTime; const ValueName : string = '') : ISpecifier; overload; function That(Value : IInterface; const ValueName : string = '') : ISpecifier; overload; end; TAutoDocClass = class of TBaseAutoDoc; TContext = class(TTestCase, IContext) private FSpecify : TSpecify; FFailures: TFailureList; FTestResult: TTestResult; FSpecDocumentation : string; FContextDescription: string; FAutoDoc : IAutoDoc; { IContext } procedure AddFailure(const AMessage : string; ACallerAddress : Pointer); procedure NewSpecDox(const ValueName : string); procedure DocumentSpec(Value : Variant; const SpecName : string); procedure ReportFailures; procedure RepealLastFailure; function GetAutoDoc : IAutoDoc; procedure SetAutoDoc(Value : IAutoDoc); function GetContextDescription : string; procedure SetContextDescription(const Value : string); protected property Specify : TSpecify read FSpecify; property ContextDescription : string read GetContextDescription write SetContextDescription; property AutoDoc : IAutoDoc read GetAutoDoc write SetAutoDoc; procedure RunWithFixture(testResult: TTestResult); override; procedure Invoke(AMethod: TTestMethod); override; procedure DoStatus(const Msg : string); function CreateAutoDoc : IAutoDoc; dynamic; public constructor Create(MethodName : string); override; destructor Destroy; override; end; procedure RegisterSpec(spec: ITest); implementation uses dSpecUtils, SysUtils, Variants; procedure RegisterSpec(spec: ITest); begin TestFramework.RegisterTest(spec); end; { Specify } constructor TSpecify.Create(AContext: IContext); begin inherited Create; FContext := AContext; end; destructor TSpecify.Destroy; begin FContext := nil; inherited Destroy; end; function TSpecify.That(Value: Integer; const ValueName : string = ''): ISpecifier; begin Result := TIntegerSpecifier.Create(Value, CallerAddr, FContext, ValueName); FContext.NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: Boolean; const ValueName : string = ''): ISpecifier; begin Result := TBooleanSpecifier.Create(Value, CallerAddr, FContext, ValueName); FContext.NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: Extended; const ValueName : string = ''): ISpecifier; begin Result := TFloatSpecifier.Create(Value, CallerAddr, FContext, ValueName); FContext.NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: string; const ValueName : string = ''): ISpecifier; begin Result := TStringSpecifier.Create(Value, CallerAddr, FContext, ValueName); FContext.NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: TObject; const ValueName : string = ''): ISpecifier; begin Result := TObjectSpecifier.Create(Value, CallerAddr, FContext, ValueName); if ValueName <> '' then FContext.NewSpecDox(ValueName) else if Assigned(Value) then FContext.NewSpecDox(Value.ClassName) else FContext.NewSpecDox('TObject'); end; function TSpecify.That(Value: Pointer; const ValueName : string = ''): ISpecifier; begin Result := TPointerSpecifier.Create(Value, CallerAddr, FContext, ValueName); if ValueName <> '' then FContext.NewSpecDox(ValueName) else FContext.NewSpecDox('Pointer'); end; function TSpecify.That(Value: TClass; const ValueName : string = ''): ISpecifier; begin Result := TClassSpecifier.Create(Value, CallerAddr, FContext, ValueName); if ValueName <> '' then FContext.NewSpecDox(ValueName) else FContext.NewSpecDox(Value.ClassName); end; function TSpecify.That(Value: TDateTime; const ValueName : string = ''): ISpecifier; begin Result := TDateTimeSpecifier.Create(Value, CallerAddr, FContext, ValueName); FContext.NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: IInterface; const ValueName : string = ''): ISpecifier; begin Result := TInterfaceSpecifier.Create(Value, CallerAddr, FContext, ValueName); FContext.NewSpecDox(GetValueName(Value, ValueName)); end; { TContext } procedure TContext.AddFailure(const AMessage: string; ACallerAddress: Pointer); begin FFailures.AddFailure(AMessage, ACallerAddress); end; constructor TContext.Create; begin inherited Create(MethodName); FSpecify := TSpecify.Create(Self); FFailures := TFailureList.Create; FContextDescription := ''; AutoDoc := CreateAutoDoc; AutoDoc.Enabled := False; end; destructor TContext.Destroy; begin FreeAndNil(FSpecify); FreeAndNil(FFailures); inherited Destroy; end; procedure TContext.DocumentSpec(Value: Variant; const SpecName: string); begin FSpecDocumentation := FSpecDocumentation + '.' + SpecName; if Value <> null then FSpecDocumentation := FSpecDocumentation + Format('(%s)', [VarToStr(Value)]); end; procedure TContext.DoStatus(const Msg: string); begin if Msg <> '' then Status(Msg); end; function TContext.GetAutoDoc: IAutoDoc; begin Result := FAutoDoc; end; function TContext.CreateAutoDoc: IAutoDoc; begin Result := TBaseAutoDoc.Create(Self); end; function TContext.GetContextDescription: string; begin Result := FContextDescription; end; procedure TContext.Invoke(AMethod: TTestMethod); begin DoStatus(FAutoDoc.BeginSpec(ClassName, FTestName)); inherited; DoStatus(FAutoDoc.DocSpec(FSpecDocumentation)); end; procedure TContext.RepealLastFailure; begin if FFailures.Count > 0 then FFailures.Delete(FFailures.Count - 1); end; procedure TContext.ReportFailures; var c: Integer; begin try for c := 0 to FFailures.Count - 1 do FTestResult.AddFailure(Self, ETestFailure.Create(FFailures[c].Message), FFailures[c].FailureAddress); finally FFailures.Clear; end; end; procedure TContext.NewSpecDox(const ValueName : string); begin if FSpecDocumentation <> '' then DoStatus(FAutoDoc.DocSpec(FSpecDocumentation)); FSpecDocumentation := Format('Specify.That(%s).Should', [ValueName]); end; procedure TContext.RunWithFixture(testResult: TTestResult); begin FTestResult := testResult; inherited; FTestResult := nil; end; procedure TContext.SetAutoDoc(Value: IAutoDoc); begin FAutoDoc := Value; if not Assigned(FAutoDoc) then FAutoDoc := TBaseAutoDoc.Create(Self); end; procedure TContext.SetContextDescription(const Value: string); begin FContextDescription := Value; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin, SMXM7X, ExtCtrls, ComCtrls; type TForm1 = class(TForm) btSnapshot: TButton; btCancelSnapshot: TButton; cbExtTrgEnabled: TCheckBox; spnTimeout: TSpinEdit; Label1: TLabel; Message: TLabel; GroupBox1: TGroupBox; rbPositive: TRadioButton; rbNegative: TRadioButton; ComboBox1: TComboBox; Label2: TLabel; Timer1: TTimer; ComboBox2: TComboBox; Label3: TLabel; tbExposure: TTrackBar; lbExp: TLabel; procedure btSnapshotClick(Sender: TObject); procedure DisplayMessage( Str : String); procedure FormCreate(Sender: TObject); procedure btCancelSnapshotClick(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Timer1Timer(Sender: TObject); procedure ComboBox2Change(Sender: TObject); procedure tbExposureChange(Sender: TObject); private { Private declarations } public FSnapshotLoop : Boolean; FSnapshotCounter : Integer; CameraNo : Integer; hLoopThread : THandle; SavedFrames, CurrFrames : Dword; { Public declarations } end; Type frameArray = array [0..1400*1024-1] of byte; var Form1: TForm1; SnapshotFrame : frameArray; implementation uses Unit2; {$R *.dfm} Procedure SaveAsBitmap(Fn:string; pBuf : pointer; ScW,ScH:integer; ClDeep:integer); var i : integer; f : file; DibPixels : pchar; P : PChar; ColorFactor : integer; DibSize : integer; Dib : packed record Hdr : TBitmapInfoHeader; Colors : array[0..255] of longint; end; FileHdr : packed record SgBM : array [0..1] of char; TotalSz : integer; _rez : integer; HdrSz : integer; end; Begin { make } FillChar(Dib.Hdr,sizeof(Dib.Hdr),0); if ClDeep=8 then begin DibPixels:=CxBayerToRgb(pBuf, ScW, ScH, 0, FrameBuf); // mono !!! end else begin DibPixels:=CxBayerToRgb(pBuf, ScW, ScH, 2, FrameBuf); end; DibSize:=ScW*ScH*3; ColorFactor:=3; Dib.Hdr.biSize:=sizeof(Dib.Hdr); Dib.Hdr.biWidth:=ScW; Dib.Hdr.biHeight:=ScH; Dib.Hdr.biPlanes:=1; Dib.Hdr.biBitCount:=24; Dib.Hdr.biCompression:=bi_RGB; Dib.Hdr.biSizeImage:=DibSize; Dib.Hdr.biXPelsPerMeter := Round(GetDeviceCaps(GetDC(0), LOGPIXELSX) * 39.3701); Dib.Hdr.biYPelsPerMeter := Round(GetDeviceCaps(GetDC(0), LOGPIXELSY) * 39.3701); { store } FileHdr.SgBM:='BM'; FileHdr._rez:=0; FileHdr.HdrSz:=$36; FileHdr.TotalSz:=DibSize+FileHdr.HdrSz; If Fn='' then Exit;//Fn:=GenerateNewFileName('',1,'.bmp'); AssignFile(f,Fn); Rewrite(f,1); BlockWrite(f,FileHdr,sizeof(FileHdr)); BlockWrite(f,Dib.Hdr,sizeof(Dib.Hdr)); for i := ScH-1 downto 0 do begin p := DibPixels + ScW * i * ColorFactor; BlockWrite(f, p^, ScW*ColorFactor); end; CloseFile(f); end; procedure TForm1.FormCreate(Sender: TObject); Var H : THandle; Params : TCxScreenParams; MinExposure, MaxExposure:Integer; ExpMs:Single; begin FSnapshotLoop := False; FSnapshotCounter := 0; CameraNo := 0; hLoopThread := 0; SavedFrames := 0; CurrFrames := 0; try // Open device H := CxOpenDevice(CameraNo); if H <> INVALID_HANDLE_VALUE then begin CxGetScreenParams(H,Params); Params.Width := 1280; Params.Height := 1024; Params.StartX := 0; Params.StartY := 0; Params.Decimation := 1; CxSetScreenParams(H,Params); CxSetFrequency(H, 2); // 24 Mhz CxGetExposureMinMax(H,MinExposure, MaxExposure); CxSetExposure(H,MinExposure); CxGetExposureMs(H,ExpMs); lbExp.Caption := 'Exposure:'+Format('%7.2f',[ExpMs])+'ms'; //lbExp.Caption := 'Exposure:'+Format('%f.2',[ExpMs])+'ms'; tbExposure.Min := MinExposure; tbExposure.Max := MaxExposure; tbExposure.Position := MinExposure; CxCloseDevice(H); end; except // leave default setting end; DisplayMessage(''); end; procedure TForm1.DisplayMessage( Str : String); begin Message.Caption := Str; end; procedure TForm1.btSnapshotClick(Sender: TObject); procedure LoopSnapshotThreadProc(Var Foo); Stdcall; Var H : THandle; Status, Ok : Boolean; Params : TCxScreenParams; RetLen:DWORD; begin Form1.FSnapshotLoop := True; Form1.btCancelSnapshot.Enabled := True; Form1.btSnapshot.Enabled := False; while Form1.FSnapshotLoop do begin Application.ProcessMessages; try H := CxOpenDevice(Form1.CameraNo); if H <> INVALID_HANDLE_VALUE then begin Ok := False; CxGetScreenParams(H,Params); Params.Width := 1280; Params.Height := 1024; Params.StartX := 0; Params.StartY := 0; Params.Decimation := 1; CxSetScreenParams(H,Params); Status := CxGetSnapshot( H, Form1.spnTimeout.Value, Form1.cbExtTrgEnabled.Checked, Form1.rbPositive.Checked, True, @SnapshotFrame, sizeof(SnapshotFrame), RetLen ); Inc(Form1.CurrFrames); if not Status then begin Form1.DisplayMessage( 'Snapshot Status: Error!') end else begin if RetLen = 0 then Form1.DisplayMessage( 'Snapshot Status: Empty Frame (Timeout ?)!') else Ok := True; end; // Show snapshot if Ok then begin CxGetScreenParams(H,Params); Params.Width := Params.Width div Params.Decimation; Params.Height := Params.Height div Params.Decimation; SSForm.ShowFrame( @SnapshotFrame, Params.Width, Params.Height, Params.ColorDeep ); end else begin SSForm.Hide; end; CxCloseDevice(H); end else begin Form1.DisplayMessage('Error open Camera #0!'); Sleep(300); end; except // leave default setting end; end; // while FSnapshotLoop do end; // LoopSnapshotThreadProc Var ThreadId : Dword; Begin if hLoopThread = 0 then begin hLoopThread := CreateThread(Nil,0,@LoopSnapshotThreadProc,@Self,CREATE_SUSPENDED,ThreadId); end; if hLoopThread <> 0 then begin SetThreadPriority(hLoopThread,THREAD_PRIORITY_IDLE); ResumeThread(hLoopThread); end; Form1.FSnapshotLoop := True; Form1.btCancelSnapshot.Enabled := True; Form1.btSnapshot.Enabled := False; End; procedure TForm1.btCancelSnapshotClick(Sender: TObject); begin FSnapshotLoop := False; if hLoopThread <> 0 then begin SuspendThread(hLoopThread); end; btCancelSnapshot.Enabled := False; btSnapshot.Enabled := True; SSForm.Hide; end; procedure TForm1.ComboBox1Change(Sender: TObject); begin CameraNo := ComboBox1.ItemIndex; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin if hLoopThread <> 0 then begin TerminateThread(hLoopThread,0); CloseHandle(hLoopThread); hLoopThread := 0; end; end; procedure TForm1.Timer1Timer(Sender: TObject); begin SSForm.Caption := IntToStr( CurrFrames - SavedFrames ) + ' fps'; SavedFrames := CurrFrames; end; procedure TForm1.ComboBox2Change(Sender: TObject); Var H:THandle; MinExposure, MaxExposure:Integer; begin try H := CxOpenDevice(CameraNo); if H <> INVALID_HANDLE_VALUE then begin CxSetFrequency(H, ComboBox2.ItemIndex); CxGetExposureMinMax(H,MinExposure, MaxExposure); tbExposure.Min := MinExposure; tbExposure.Max := MaxExposure; CxCloseDevice(H); end; finally end; end; procedure TForm1.tbExposureChange(Sender: TObject); Var H:THandle; ExpMs:Single; begin try H := CxOpenDevice( CameraNo ); if H <> INVALID_HANDLE_VALUE then begin CxSetExposure(H, tbExposure.Position); CxGetExposureMs(H,ExpMs); lbExp.Caption := 'Exposure:'+Format('%7.2f',[ExpMs])+'ms'; CxCloseDevice(H); end; finally end; end; End.
unit RuCaptcha; interface uses System.SysUtils, IdHTTP, IdMultipartFormData, BaseCaptcha; type ERuCaptchaError = class(Exception); {$M+} TRuCaptcha = class private FHTTPClient: TIdHTTP; FAPIKey: string; FRequestTimeout: Integer; FHost: string; protected function GetBalance: string; function SendFormData(AFormData: TIdMultiPartFormDataStream): string; function ParseResponse(const Response: string): string; function GetAnswer(const CaptchaId: string): string; public constructor Create; virtual; destructor Destroy; override; procedure SolveCaptcha(Captcha: TBaseCaptcha); procedure ReportBad(const CaptchaId: string); procedure ReportGood(const CaptchaId: string); property Balance: string read GetBalance; published property APIKey: string read FAPIKey write FAPIKey; property RequestTimeout: Integer read FRequestTimeout write FRequestTimeout; property Host: string read FHost write FHost; end; {$M-} implementation uses System.Classes, StrUtils; { TRuCaptcha } constructor TRuCaptcha.Create; begin FHTTPClient := TIdHTTP.Create(nil); FHTTPClient.ReadTimeout := 30000; FHTTPClient.ConnectTimeout := 30000; FRequestTimeout := 5000; FHost := 'rucaptcha.com'; end; destructor TRuCaptcha.Destroy; begin FHTTPClient.Free; inherited; end; function TRuCaptcha.GetAnswer(const CaptchaId: string): string; var URL: string; Content: TStringStream; begin URL := Format('http://%s/res.php?key=%s&action=get&id=%s', [FHost, FAPIKey, CaptchaId]); Content := TStringStream.Create('', TEncoding.UTF8); try FHTTPClient.Get(URL, Content); Result := ParseResponse(Content.DataString); finally Content.Free; end; end; function TRuCaptcha.GetBalance: string; var URL: string; Content: TStringStream; begin URL := Format('http://%s/res.php?key=%s&action=getbalance', [FHost, FAPIKey]); Content := TStringStream.Create; try FHTTPClient.Get(URL, Content); Result := Content.DataString; finally Content.Free; end; end; function TRuCaptcha.ParseResponse(const Response: string): string; begin if AnsiSameText('CAPCHA_NOT_READY', Response) then Exit(Response); if AnsiPos('OK|', Response) <= 0 then raise ERuCaptchaError.Create(Response); Result := ReplaceText(Response, 'OK|', ''); end; function TRuCaptcha.SendFormData(AFormData: TIdMultiPartFormDataStream): string; var URL: string; Content: TStringStream; begin URL := Format('http://%s/in.php', [FHost]); Content := TStringStream.Create; try FHTTPClient.Post(URL, AFormData, Content); Result := ParseResponse(Content.DataString); finally Content.Free; end; end; procedure TRuCaptcha.ReportBad(const CaptchaId: string); var URL: string; Content: TStringStream; begin URL := Format('http://%s/res.php?key=%s&action=reportbad&id=%s', [FHost, FAPIKey, CaptchaId]); Content := TStringStream.Create; try FHTTPClient.Get(URL, Content); finally Content.Free; end; end; procedure TRuCaptcha.ReportGood(const CaptchaId: string); var URL: string; Content: TStringStream; begin URL := Format('http://%s/res.php?key=%s&action=reportgood&id=%s', [FHost, FAPIKey, CaptchaId]); Content := TStringStream.Create; try FHTTPClient.Get(URL, Content); finally Content.Free; end; end; procedure TRuCaptcha.SolveCaptcha(Captcha: TBaseCaptcha); var FormData: TIdMultiPartFormDataStream; Answer: string; begin FormData := Captcha.BuildFormData; FormData.AddFormField('soft_id', '838'); FormData.AddFormField('key', FAPIKey); Captcha.Id := SendFormData(FormData); repeat Sleep(FRequestTimeout); Answer := GetAnswer(Captcha.Id); until Answer <> 'CAPCHA_NOT_READY'; Captcha.Answer := Answer; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.dml.generator.interbase; interface uses SysUtils, StrUtils, Rtti, ormbr.dml.generator.firebird, ormbr.driver.register, dbebr.factory.interfaces, ormbr.criteria; type // Classe de banco de dados Interbase TDMLGeneratorInterbase = class(TDMLGeneratorFirebird) protected public constructor Create; override; destructor Destroy; override; end; implementation { TDMLGeneratorInterbase } constructor TDMLGeneratorInterbase.Create; begin inherited; FDateFormat := 'MM/dd/yyyy'; FTimeFormat := 'HH:MM:SS'; end; destructor TDMLGeneratorInterbase.Destroy; begin inherited; end; initialization TDriverRegister.RegisterDriver(dnInterbase, TDMLGeneratorInterbase.Create); end.
unit Model.Usuario; interface uses System.SysUtils, FMX.Graphics; type TUsuarioModel = class private FID : TGUID; FCodigo : Integer; FNome : String; FEmail : String; FSenha : String; FFoto : TBitmap; FLogado : Boolean; FTemFoto: Boolean; procedure SetEmail(const Value: String); procedure SetFoto(const Value: TBitmap); procedure SetID(const Value: TGUID); procedure SetLogado(const Value: Boolean); procedure SetNome(const Value: String); procedure SetSenha(const Value: String); procedure SetCodigo(const Value: Integer); procedure SetTemFoto(const Value: Boolean); public constructor Create; destructor Destroy; override; property ID : TGUID read FID write SetID; property Codigo : Integer read FCodigo write SetCodigo; property Nome : String read FNome write SetNome; property Email : String read FEmail write SetEmail; property Senha : String read FSenha write SetSenha; property Foto : TBitmap read FFoto write SetFoto; property TemFoto : Boolean read FTemFoto write SetTemFoto; property Logado : Boolean read FLogado write SetLogado; class function New : TUsuarioModel; end; implementation { TUsuarioModel } constructor TUsuarioModel.Create; begin FID := TGUID.Empty; FNome := EmptyStr; FEmail := EmptyStr; FSenha := EmptyStr; FFoto := TBitmap.Create; FLogado := False; end; destructor TUsuarioModel.Destroy; begin FFoto.DisposeOf; inherited; end; class function TUsuarioModel.New: TUsuarioModel; begin Result := Self.Create; end; procedure TUsuarioModel.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TUsuarioModel.SetEmail(const Value: String); begin FEmail := Value.Trim.ToLower; end; procedure TUsuarioModel.SetFoto(const Value: TBitmap); begin FFoto := Value; end; procedure TUsuarioModel.SetID(const Value: TGUID); begin FID := Value; end; procedure TUsuarioModel.SetLogado(const Value: Boolean); begin FLogado := Value; end; procedure TUsuarioModel.SetNome(const Value: String); begin FNome := Value.Trim; end; procedure TUsuarioModel.SetSenha(const Value: String); begin FSenha := Value.Trim; end; procedure TUsuarioModel.SetTemFoto(const Value: Boolean); begin FTemFoto := Value; end; end.
unit MainFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ShlObj, Buttons, StdCtrls, ExtCtrls, ToolWin, ComCtrls, ExtDlgs, ImgList, Menus, StrUtils, SearchProgressFormUnit, CompareProgressFormUnit, DecisionFormUnit, ShellAPI, JPEG; type TMainForm = class(TForm) GroupBox1: TGroupBox; Edit1: TEdit; SpeedButton1: TSpeedButton; CheckBox1: TCheckBox; BitBtn1: TBitBtn; GroupBox2: TGroupBox; ListView1: TListView; ImageList1: TImageList; ImageList2: TImageList; ToolBar1: TToolBar; ToolButton1: TToolButton; PopupMenu1: TPopupMenu; Details1: TMenuItem; List1: TMenuItem; Details2: TMenuItem; Smallicons1: TMenuItem; ImageList3: TImageList; ToolButton2: TToolButton; PopupMenu2: TPopupMenu; Byname1: TMenuItem; Bydimensions1: TMenuItem; Byfilesize1: TMenuItem; Bydate1: TMenuItem; N1: TMenuItem; Ascendant1: TMenuItem; Descendant1: TMenuItem; BitBtn2: TBitBtn; Panel1: TPanel; TrackBar1: TTrackBar; ComboBox1: TComboBox; ToolButton3: TToolButton; Panel2: TPanel; ImageList4: TImageList; ToolButton4: TToolButton; Panel3: TPanel; ComboBox2: TComboBox; procedure FormCreate(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure Smallicons1Click(Sender: TObject); procedure ListView1Compare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure ListView1ColumnClick(Sender: TObject; Column: TListColumn); procedure BitBtn2Click(Sender: TObject); procedure TrackBar1Change(Sender: TObject); procedure ComboBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure Descendant1Click(Sender: TObject); procedure Bydate1Click(Sender: TObject); procedure ComboBox2Change(Sender: TObject); private FAscendantOrder:Boolean; // Ordre de classement croissant/décroissant FColumnSortID:Integer; // Critère de classement public CurrentFolder:string; // Variables utilisées par les fenêtres de progression FileCount,FolderCount:Integer; CompareProgress:Single; procedure ClearData; // Pour nettoyer le ListView (la propriété Data des TListItem contient un pointeur vers une matrice de coefficients) end; TTriVertex=packed record x:Longint; y:Longint; Red:Word; Green:Word; Blue:Word; Alpha:Word; end; TSingleArray=array[0..$FFFFFF] of Single; PSingleArray=^TSingleArray; TSearchThread=class(TThread) // Thread de recherche de fichiers images private FSearchData:TSearchRec; // Variables utilisées dans la méthode synchronisée FPicture:TPicture; FBitmap1,FBitmap2:TBitmap; FRect1,FRect2:TRect; FPath,FSubPath:string; FSize:Integer; FBuffer:PSingleArray; protected procedure Execute;override; procedure Finished; // Méthode appelée à la fin du thread pour enlever la fenêtre de progression procedure AddFile; // Méthode synchronisée avec le thread principal pour manipuler le ListView1 end; TCompareThread=class(TThread) // Thread de comparaison des fichiers images trouvés private FFile1,FFile2:string; // Variables utilisées dans la méthode synchronisée FAction:TImageAction; FSimilarity:Single; protected procedure Execute;override; procedure Finished; // Méthode appelée à la fin du thread pour enlever la fenêtre de progression procedure FileAction; // Méthode synchronisée avec le thread principal pour manipuler le ListView1 et lancer le dialogue de suppression end; var MainForm: TMainForm; implementation {$R *.dfm} function CallBack(Wnd:HWND;uMsg:UINT;wParam,lpData:LPARAM):Integer;stdcall; // Fonction de "callback" appelée à l'initialisation de la begin // boîte de sélection de répertoire pour définir le répertoire if uMsg=BFFM_INITIALIZED then // par défaut SendMessage(Wnd,BFFM_SETSELECTION,1,lpData); Result:=0; end; function SelectFolder(var Folder:string;const AllowCreateNew:Boolean=False;const Title:string=''):Boolean; // Fonction pour demander à l'utilisateur de const // choisir un répertoire BIF_NEWDIALOGSTYLE=$0040; // Folder: le répertoire par défaut var // qui contiendra le répertoire BI:TBrowseInfo; // choisi en cas de confirmation p:PItemIDList; // AllowCreateNew: autorise ou non la possibilité begin // de créer un nouveau dossier ZeroMemory(@BI,SizeOf(BI)); // Title: titre de la boîte de dialogue with BI do begin // Résultat: True si l'utilisation a cliqué hwndOwner:=Application.Handle; // sur OK, False sinon pszDisplayName:=PChar(Folder); lpszTitle:=PChar(Title); ulFlags:=BIF_RETURNONLYFSDIRS; if AllowCreateNew then ulFlags:=ulFlags or BIF_NEWDIALOGSTYLE; if Folder<>'' then begin lParam:=Integer(PChar(Folder)); lpfn:=CallBack; end; end; p:=SHBrowseForFolder(BI); if Assigned(p) then begin SetLength(Folder,MAX_PATH); Result:=SHGetPathFromIDList(p,PChar(Folder)); GlobalFreePtr(p); SetLength(Folder,Length(PChar(Folder))); end else Result:=False; end; { TSearchThread } procedure TSearchThread.AddFile; // Procédure synchronisée avec le thread principal pour ajoutter un item dans le TListView function BuildWavelet:PSingleArray; // Fonction qui construit la transformée en ondelettes de Haar de l'image var a,b,c,d,e:Integer; s:PByteArray; begin GetMem(Result,FBitmap2.Width*FBitmap2.Height*3*SizeOf(Single)); for b:=0 to FBitmap2.Height-1 do begin s:=FBitmap2.ScanLine[b]; for a:=0 to 3*FBitmap2.Width-1 do Result[FSize*b*3+a]:=s[a]; end; c:=FSize; while c>1 do begin // Transformée en paquets d'ondelettes... e:=c div 2; for d:=0 to 2 do begin // On fait successivement la transformée des 3 canaux RGB for a:=0 to FSize-1 do begin // Transformée horizontale for b:=0 to c-1 do FBuffer[b]:=Result[(FSize*a+b)*3+d]; for b:=0 to e-1 do begin Result[(FSize*a+b)*3+d]:=0.5*(FBuffer[2*b]+FBuffer[2*b+1]); Result[(FSize*a+b+e)*3+d]:=0.5*(FBuffer[2*b+1]-FBuffer[2*b]); end; end; for a:=0 to FSize-1 do begin // Transformée verticale for b:=0 to c-1 do FBuffer[b]:=Result[(FSize*b+a)*3+d]; for b:=0 to e-1 do begin Result[(FSize*b+a)*3+d]:=0.5*(FBuffer[2*b]+FBuffer[2*b+1]); Result[(FSize*(b+e)+a)*3+d]:=0.5*(FBuffer[2*b+1]-FBuffer[2*b]); end; end; end; c:=c div 2; // Passage à l'échelle suivante end; end; begin MainForm.CurrentFolder:=FSubPath; // Variables utilisées par la fenêtre de progression... FPicture.LoadFromFile(FPath+'\'+FSearchData.Name); FBitmap1.Canvas.StretchDraw(FRect1,FPicture.Graphic); FBitmap2.Canvas.StretchDraw(FRect2,FPicture.Graphic); with MainForm,ListView1.Items.Add do begin Data:=BuildWavelet; Caption:=FSubPath+FSearchData.Name; SubItems.Add(Format('%d x %d',[FPicture.Width,FPicture.Height])); {$WARNINGS OFF} SubItems.Add(IntToStr(Int64(FSearchData.FindData.nFileSizeHigh) shl 32+FSearchData.FindData.nFileSizeLow)); {$WARNINGS ON} SubItems.Add(DateTimeToStr(FileDateToDateTime(FileAge(FPath+'\'+FSearchData.Name)))); ImageIndex:=ImageList1.Add(FBitmap1,nil); ImageList2.Add(FBitmap2,nil); end; Inc(MainForm.FileCount); end; procedure TSearchThread.Execute; var l:TStringList; procedure ListFolder(Path:string;SubPath:string); // Parcours récursif (en fonction de CheckBox1.Checked) d'un répertoire var f:TSearchRec; begin Inc(MainForm.FolderCount); if FindFirst(Path+'\*',faAnyFile or faDirectory,f)=0 then try repeat if Terminated then Break; if f.Attr and faDirectory=faDirectory then begin if MainForm.CheckBox1.Checked and (f.Name<>'.') and (f.Name<>'..') then ListFolder(Path+'\'+f.Name,SubPath+f.Name+'\'); end else if l.IndexOf(ExtractFileExt(f.Name))>-1 then begin // Si l'extension est une extension graphique connue (en l'occurence *.JPEG, *.BMP, *.ICO, *.WMF) try FSearchData:=f; FSubPath:=SubPath; FPath:=Path; Synchronize(AddFile); // Synchronisation de la méthode d'ajout except ; end; end; until FindNext(f)<>0; finally FindClose(f); end; end; begin l:=TStringList.Create; l.Text:=AnsiReplaceText(AnsiReplaceStr(GraphicFileMask(TGraphic),';',#13),'*',''); // Extraction de la liste des extensions graphiques connues l.CaseSensitive:=False; FPicture:=TPicture.Create; FBitmap1:=TBitmap.Create; FBitmap1.Width:=MainForm.ImageList1.Width; FBitmap1.Height:=MainForm.ImageList1.Height; FRect1:=Rect(0,0,FBitmap1.Width,FBitmap1.Height); FBitmap2:=TBitmap.Create; FBitmap2.Width:=MainForm.ImageList2.Width; FBitmap2.Height:=MainForm.ImageList2.Height; FBitmap2.PixelFormat:=pf24bit; // Format RGB24 FRect2:=Rect(0,0,FBitmap2.Width,FBitmap2.Height); FSize:=FBitmap2.Width; GetMem(FBuffer,FSize*SizeOf(Single)); // Buffer de travail... MainForm.ListView1.Items.BeginUpdate; // Pour éviter des réaffichages multiples try ListFolder(MainForm.Edit1.Text,''); finally MainForm.ListView1.Items.EndUpdate; FreeMem(FBuffer); FBitmap2.Destroy; FBitmap1.Destroy; FPicture.Destroy; l.Destroy; if not Terminated then Synchronize(Finished); // On cache la fenêtre de progression si elle est encore visible end; end; procedure TSearchThread.Finished; // On cache la fenêtre de progression si elle est encore visible begin if SearchProgressForm.Visible then SearchProgressForm.ModalResult:=mrOk; end; { TCompareThread } procedure TCompareThread.Execute; var a,b,c,n:Integer; t:PSingleArray; r,m:Single; const u:array[0..1,0..1] of Single=((0.25,1),(1,1)); function Dist(p,q:PSingleArray):Single; // Distance de 2 transformées d'ondelettes var a,b,c:Integer; begin Result:=0; for a:=0 to n-1 do begin if Result>m then // Si les 2 images sont déjà assez différentes, pas besoin de faire le calcul jusqu'au bout. Exit; for b:=0 to n-1 do for c:=0 to 2 do Result:=Result+t[n*a+b]*Abs(p[(n*a+b)*3+c]-q[(n*a+b)*3+c]); // Ajout des différences pondérées des 2 transformées en ondelettes end; end; begin n:=MainForm.ImageList2.Width; GetMem(t,n*n*SizeOf(Single)); // Matrice de pondération multi-échelle c:=1; r:=1/16; t[0]:=1; while c<n do begin // remplissage de la matrice de pondérations for a:=0 to c-1 do for b:=0 to c-1 do begin t[n*(a+c)+b]:=r*u[1,0]; t[n*a+b+c]:=r*u[0,1]; t[n*(a+c)+b+c]:=r*u[1,1]; end; c:=2*c; r:=r*u[0,0]; end; m:=100-MainForm.TrackBar1.Position/10; DecisionForm.Canceled:=False; DecisionForm.CheckBox1.Checked:=False; try a:=0; with MainForm do while a<ListView1.Items.Count do begin MainForm.CompareProgress:=a/(ListView1.Items.Count+1); for b:=ListView1.Items.Count-1 downto a+1 do begin FSimilarity:=100-Dist(ListView1.Items[a].Data,ListView1.Items[b].Data); if (FSimilarity>=TrackBar1.Position/10) then begin FFile1:=Edit1.Text+'\'+ListView1.Items[a].Caption; FFile2:=Edit1.Text+'\'+ListView1.Items[b].Caption; Synchronize(FileAction); // Synchronisation de l'affichage du dialogue de suppression case FAction of // Mise à jour du ListView1 en fonction de l'action choisie par l'utilisateur iaDelete1:begin FreeMem(ListView1.Items[a].Data); ListView1.Items.Delete(a); Dec(a); Break; end; iaDelete2:begin FreeMem(ListView1.Items[b].Data); ListView1.Items.Delete(b); end; end; end; if DecisionForm.Canceled or Terminated then // Action annulée... Break; end; if DecisionForm.Canceled or Terminated then // Action annulée... Break; Inc(a); end; finally FreeMem(t); end; if not Terminated then Synchronize(Finished); // On ferme la fenêtre de progression si elle est encore visible... end; procedure TCompareThread.FileAction; procedure DoDeleteFile(FileName:string); // Suppression d'un fichier var FOS:TSHFileOpStruct; begin if MainForm.ComboBox1.ItemIndex=1 then begin if not DeleteFile(FileName) then // Suppression irréversible RaiseLastOSError; end else begin ZeroMemory(@FOS,SizeOf(FOS)); // Envoi à la corbeille with FOS do begin wFunc:=FO_DELETE; pFrom:=PChar(FileName+#0#0); fFlags:=FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_SILENT; end; if ShFileOperation(FOS)<>0 then RaiseLastOSError; end; end; begin FAction:=DecisionForm.Execute(FFile1,FFile2,FSimilarity); // On demande son avis à l'utilisateur... case FAction of // Et on fait ce qu'il a décidé... iaDelete1:DoDeleteFile(FFile1); iaDelete2:DoDeleteFile(FFile2); end; end; procedure TCompareThread.Finished; begin if CompareProgressForm.Visible then CompareProgressForm.ModalResult:=mrOk; // On ferme la fenêtre de progression si elle est encore visible... end; { TMainForm } procedure TMainForm.FormCreate(Sender: TObject); begin Edit1.Text:=GetCurrentDir; // On se met dans le répertoire de travail end; procedure TMainForm.BitBtn1Click(Sender: TObject); const T:array[0..3] of Integer=(16,32,64,128); // Qualités de la transformée en ondelettes: Low, Average, Good, Very good begin ClearData; // On efface les données précédantes ImageList2.Width:=T[ComboBox2.ItemIndex]; // La taille de ImageList2 va définir la taille de la transformée en ondelettes (en fonction de la qualité désirée) ImageList2.Height:=T[ComboBox2.ItemIndex]; CurrentFolder:=''; // Initialisations diverses... FileCount:=0; FolderCount:=0; with TSearchThread.Create(False) do begin // Lancement du thread de recherche if SearchProgressForm.ShowModal=mrCancel then begin // Affichage de la fenêtre de progression: si l'utilisateur appuie dur "cancel"... Terminate; // ...alors on arrête le thread WaitFor; end; Destroy; end; GroupBox2.Caption:=Format('%d graphic files',[ListView1.Items.Count]); // Nombre de fichiers trouvés BitBtn2.Enabled:=True; // On peut passer à l'étape suivante end; procedure TMainForm.SpeedButton1Click(Sender: TObject); var s:string; begin s:=Edit1.Text; if SelectFolder(s) then begin // Changement du répertoire de recherche Edit1.Text:=s; ClearData; end; end; procedure TMainForm.Smallicons1Click(Sender: TObject); var a:Integer; begin // En fonction du menu coché, on adapte l'affichage du ListView for a:=0 to PopupMenu1.Items.Count-1 do if PopupMenu1.Items[a].Checked then ListView1.ViewStyle:=TViewStyle(a); end; procedure TMainForm.ListView1Compare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); function BoolSgn(x:Boolean):Integer; begin if x then Result:=1 else Result:=-1; if FAscendantOrder then Result:=-Result; end; function StrToDim(s:string):Integer; var a:Integer; begin a:=Pos(' x ',s); Result:=StrToInt(Copy(s,1,a-1))*StrToInt(Copy(s,a+3,Length(s))); end; begin case FColumnSortID of // Différentes méthodes de comparaison en fonction de la colonne cliquée 0:Compare:=BoolSgn(Item1.Caption>Item2.Caption); 1:Compare:=BoolSgn(StrToDim(Item1.SubItems[0])>StrToDim(Item2.SubItems[0])); 2:Compare:=BoolSgn(StrToInt(Item1.SubItems[1])>StrToInt(Item2.SubItems[1])); 3:Compare:=BoolSgn(StrToDateTime(Item1.SubItems[2])>StrToDateTime(Item2.SubItems[2])); end; end; procedure TMainForm.ListView1ColumnClick(Sender: TObject; Column: TListColumn); begin if Column.Index=FColumnSortID then begin // Si on a cliqué 2 fois sur la même colonne FAscendantOrder:=not FAscendantOrder; // alors on inverse l'ordre de classement Ascendant1.Checked:=not FAscendantOrder; // Mise à jour du menu coché Descendant1.Checked:=FAscendantOrder; end; FColumnSortID:=Column.Index; PopupMenu2.Items[FColumnSortID].Checked:=True; // Mise à jour du menu coché ListView1.CustomSort(nil,0); // on classe les items end; procedure TMainForm.ClearData; // libération de la mémoire occupée par les transformées en ondelette et on vide le ListView1 var a:Integer; begin BitBtn2.Enabled:=False; ListView1.Items.BeginUpdate; try for a:=0 to ListView1.Items.Count-1 do FreeMem(ListView1.Items[a].Data); ListView1.Clear; finally ListView1.Items.EndUpdate; end; ImageList1.Clear; // on efface les listes d'images ImageList2.Clear; ListView1.Repaint; end; procedure TMainForm.BitBtn2Click(Sender: TObject); begin with TCompareThread.Create(False) do begin // Lancement du thread de comparaison if CompareProgressForm.ShowModal=mrCancel then begin // Si l'utilisateur annule l'opération Terminate; // on arrête le thread WaitFor; end; Destroy; end; GroupBox2.Caption:=Format('%d graphic files',[ListView1.Items.Count]); // Nombre de fichiers restants end; procedure TMainForm.TrackBar1Change(Sender: TObject); begin Panel1.Caption:=Format('Max similarity value: %f %%',[TrackBar1.Position/10]); // Mise à jour de l'interface end; procedure TMainForm.ComboBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin with ComboBox1,ComboBox1.Canvas do begin // Affichage des icônes de la ComboBox if odSelected in State then Brush.Color:=clHighlight; Dec(Rect.Right,1); FillRect(Rect); ImageList4.Draw(Canvas,Rect.Left+1,Rect.Top,Index); TextOut(Rect.Left+21,Rect.Top+2,Items[Index]); end; end; procedure TMainForm.Descendant1Click(Sender: TObject); begin FAscendantOrder:=Ascendant1=Sender; // Changement de l'ordre d'affichage ListView1ColumnClick(nil,ListView1.Columns[FColumnSortID]); end; procedure TMainForm.Bydate1Click(Sender: TObject); begin FColumnSortID:=PopupMenu2.Items.IndexOf(TMenuItem(Sender)); // Changement du critère d'affichage ListView1ColumnClick(nil,ListView1.Columns[FColumnSortID]); // On range de nouveau les items end; procedure TMainForm.ComboBox2Change(Sender: TObject); begin ClearData; // On doit recalculer les transformées en ondelettes donc on efface tout end; end.
unit uDecoratorInterface; interface uses uLogger , uOrder , uAuthentication ; type IOrderProcessor = interface ['{193966C6-BD40-487F-8A2F-E36BC707CA7D}'] procedure ProcessOrder(aOrder: TOrder); end; TOrderProcessor = class(TInterfacedObject, IOrderProcessor) procedure ProcessOrder(aOrder: TOrder); end; // Decorated Order Processor TOrderProcessorDecorator = class abstract(TInterfacedObject, IOrderProcessor) private FInnerOrderProcessor: IOrderProcessor; public constructor Create(aOrderProcessor: IOrderProcessor); procedure ProcessOrder(aOrder: TOrder); virtual; abstract; end; TLoggingOrderProcessor = class(TOrderProcessorDecorator) private FLogger: ILogger; public constructor Create(aOrderProcessor: IOrderProcessor; aLogger: ILogger); procedure ProcessOrder(aOrder: TOrder); override; end; TAuthenticationOrderProcessor = class(TOrderProcessorDecorator) private FAuthentication: IAuthentication; public constructor Create(aOrderProcessor: IOrderProcessor; aAuthentication: IAuthentication); procedure ProcessOrder(aOrder: TOrder); override; end; procedure DoIt; implementation uses System.SysUtils ; procedure DoIt; var OrderProcessor: IOrderProcessor; Order: TOrder; begin Order := TOrder.Create(42); try OrderProcessor := TOrderProcessor.Create; OrderProcessor := TLoggingOrderProcessor.Create(OrderProcessor, TLogger.Create); OrderProcessor.ProcessOrder(Order); WriteLn; OrderProcessor := TAuthenticationOrderProcessor.Create(OrderProcessor, TAuthentication.Create); OrderProcessor.ProcessOrder(Order); finally Order.Free; end; end; { TOrderProcessor } procedure TOrderProcessor.ProcessOrder(aOrder: TOrder); begin WriteLn('Processed order for Order #', aOrder.ID); end; { TLoggingOrderProcessor } constructor TLoggingOrderProcessor.Create(aOrderProcessor: IOrderProcessor; aLogger: ILogger); begin inherited Create(aOrderProcessor); FLogger := aLogger; end; procedure TLoggingOrderProcessor.ProcessOrder(aOrder: TOrder); begin FLogger.Log('Logging: About to process Order #' + aOrder.ID.ToString); FInnerOrderProcessor.ProcessOrder(aOrder); FLogger.Log('Logging: Finished processing Order #' + aOrder.ID.ToString); end; { TOrderProcessorAdapter } constructor TOrderProcessorDecorator.Create(aOrderProcessor: IOrderProcessor); begin inherited Create; FInnerOrderProcessor := aOrderProcessor; end; { TAuthenticationOrderProcessor } constructor TAuthenticationOrderProcessor.Create(aOrderProcessor: IOrderProcessor; aAuthentication: IAuthentication); begin inherited Create(aOrderProcessor); FAuthentication := aAuthentication; end; procedure TAuthenticationOrderProcessor.ProcessOrder(aOrder: TOrder); begin if FAuthentication.Authenticate('mcid') then begin FInnerOrderProcessor.ProcessOrder(aOrder); end else begin WriteLn('You failed authentication!'); end; end; end.
{15. Se pide compactar un arreglo, como en el ejercicio 4, sin usar estructura auxiliar. } program Ej15; Uses crt; const cantElem = 50; type TV = array[1..cantElem] of integer; Procedure lectura(var A: TV; var N: byte); var arch: text; begin N:= 1; assign(arch, 'datos.txt'); reset(arch); while not eof(arch) do begin read(arch, A[N]); N:= N + 1; end; close(arch); end; Procedure show(V: TV; N: byte); var i: byte; begin for i:= 1 to N do write(V[i],' '); writeln(); end; // encuentra los ceros del arreglo A Procedure findCeros(var ceros: byte; A: TV; N: byte); var i: byte; begin ceros:= 0; for i:= 1 to N do begin if A[i] = 0 then ceros:= ceros + 1; end; writeln('hay ',ceros,' ceros'); end; Procedure find(var pos: byte; A: TV; N: byte); var i: byte; begin i:= 1; //busca el cero while (i <= N) and (0 <> A[i]) do i:= i + 1; if i <= N then // encontro el cero pos:= i else pos:= 0; end; Procedure Delete(var A: TV; var N: byte; pos: byte); var i: byte; begin for i:= pos + 1 to N do A[i - 1]:= A[i]; N:= N - 1; end; Procedure compactaA(var A: TV; var N: byte; pos, ceros: byte); var i: byte; begin i:= 0; repeat find(pos, A, N); if pos <> 0 then begin Delete(A, N, pos); i:= i + 1; end; until i = ceros; end; // Programa principal var A: TV; N, ceros, pos: byte; begin lectura(A, N); show(A, N); findCeros(ceros, A, N); compactaA(A, N, pos, ceros); writeln('Saco los ceros...'); show(A, N); readln(); end.
unit CellPropertyFrm; interface uses Forms, MSHTML, cxLookAndFeelPainters, StdCtrls, cxButtons, cxSpinEdit, cxCheckBox, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, Controls, ExtCtrls, Classes; type TCellPropertyForm = class(TForm) Panel1: TPanel; Label2: TLabel; Label3: TLabel; align: TcxComboBox; valign: TcxComboBox; UseHeight: TcxCheckBox; Panel4: TPanel; Panel5: TPanel; UseWidth: TcxCheckBox; PercentHeight: TcxCheckBox; PercentWidth: TcxCheckBox; _height: TcxSpinEdit; _width: TcxSpinEdit; Panel6: TPanel; OK: TcxButton; Cancel: TcxButton; nowrap: TcxCheckBox; Panel2: TPanel; rowSpan: TcxSpinEdit; colSpan: TcxSpinEdit; Label1: TLabel; Label4: TLabel; private { Private declarations } public { Public declarations } end; function GetCellPropertyForm(const TableCell: IHTMLTableCell): Integer; implementation uses SysUtils, StrUtils, AlignUtils; {$R *.dfm} function GetCellPropertyForm; var Form: TCellPropertyForm; i: Integer; begin Form := TCellPropertyForm.Create(Application); try with Form do begin // заполнение данных rowSpan.Value := TableCell.rowSpan; colSpan.Value := TableCell.colSpan; align.Text := Align2RusAlign(TableCell.align); valign.Text := Align2RusAlign(TableCell.vAlign); nowrap.Checked := TableCell.noWrap; // Высота UseHeight.Checked := Length(TableCell.height) > 0; PercentHeight.Checked := Pos('%', TableCell.height) > 0; if TryStrToInt(AnsiReplaceText(TableCell.height, '%', ''), i) then _height.Value := i; // Ширина UseWidth.Checked := Length(TableCell.width) > 0; PercentWidth.Checked := Pos('%', TableCell.width) > 0; if TryStrToInt(AnsiReplaceText(TableCell.width, '%', ''), i) then _width.Value := i; // запуск диалога Result := ShowModal; if Result = mrOK then begin // сохранение данных TableCell.rowSpan := rowSpan.Value; TableCell.colSpan := colSpan.Value; TableCell.align := RusAlign2Align(align.Text); TableCell.vAlign := RusAlign2Align(valign.Text); TableCell.noWrap := nowrap.Checked; // Ширина if UseWidth.Checked then begin TableCell.width := IntToStr(_width.Value); if PercentWidth.Checked then TableCell.width := TableCell.width + '%'; end else TableCell.width := ''; // Высота if UseHeight.Checked then begin TableCell.height := IntToStr(_height.Value); if PercentHeight.Checked then TableCell.height := TableCell.height + '%'; end else TableCell.height := ''; end; end; finally Form.Free; end; end; end.
unit parser; interface uses Classes, SysUtils; type TPosInfo = packed record Line: Integer; Pos: Integer; St: Integer; end; PPosInfo = ^TPosInfo; TWAParser = class(TObject) private FCode: TStringList; FFile: String; FLine: Integer; FPos: Integer; FSt: Integer; FPosits: TList; function IsWS (C: Char): Boolean; function IsAlpha (C: Char): Boolean; function ParseKeyword: Integer; function ParseString: Integer; function ParseSymbol: Integer; function IsNumeric (C: Char): Boolean; function ParseNumber: Integer; procedure WS; public constructor Create; destructor Destroy; override; procedure SetLine (const S: String); procedure InitParser; procedure LoadFromFile (const Fn: String); function GetToken: Integer; function GetString: String; function Peek: Integer; procedure NextLine; procedure PushInfo; procedure PopInfo; procedure Reload; property Line: Integer read FLine; property Char: Integer read FPos; property Filename: String read FFile; end; PWAParser = ^TWAParser; const T_PREPROC = 0; T_GET = 1; T_POST = 2; T_FOREACH = 3; T_MAIL = 4; T_INCLUDE = 5; T_ECHO = 6; T_REFERRER = 7; T_REF = 8; T_SET = 9; T_COOKIES = 10; T_AGENT = 11; T_CSV = 12; T_TEXT = 13; T_LOOKUP = 14; T_VERBOSE = 15; T_COOKIE = 16; T_SCRAPE = 17; T_FILE = 18; T_DOWNLOAD = 19; T_STRING = 20; T_OFF = 21; T_ON = 22; T_LBRACE = 23; T_RBRACE = 24; T_COMMA = 25; T_STRUCTVAR = 26; T_DEFINED = 27; T_WHERE = 28; T_IS = 29; T_EOL = 30; T_EOF = 31; T_JUNK = 32; T_FSLOOKUP = 33; T_FIELD = 34; T_HTMLPARSE = 35; T_ENCODE = 36; T_BASENAME = 37; T_PAUSE = 38; T_SLEEP = 39; T_INTEGER = 40; T_DUMP = 41; T_PROMPT = 42; T_RUN = 43; T_QUIT = 44; T_FREADLN = 45; T_FSEEK = 46; T_FWRITELN = 47; T_REALCSV = 48; T_AUTH = 49; T_CONFIG = 50; T_FILTER_FILENAME = 51; T_STRPARSE = 52; T_MATCH = 53; T_REGEX = 54; T_IN = 55; T_STR_REGEX = 56; T_MSLEEP = 57; T_GUI_PREVIEW = 58; T_WORDWRAP = 59; T_RECORD = 60; T_MKDIR = 61; implementation constructor TWAParser.Create; begin inherited Create; FCode := TStringList.Create; FPosits := TList.Create; FFile := 'memory://'; end; destructor TWAParser.Destroy; begin FPosits.Free; FCode.Free; inherited Destroy; end; function TWAParser.IsWS (C: Char): Boolean; begin Result := (C = ' ') or (C = #9); end; function TWAParser.IsAlpha (C: Char): Boolean; begin Result := ((Ord(C) >= Ord('a')) and (Ord(C) <= Ord('z'))) or ((Ord(C) >= Ord('A')) and (Ord(C) <= Ord('Z'))); end; function TWAParser.IsNumeric (C: Char): Boolean; begin Result := (Ord(C) >= Ord('0')) and (Ord(C) <= Ord('9')); end; procedure TWAParser.WS; begin while (FPos <= Length(FCode.Strings[FLine])) and (IsWS(FCode.Strings[FLine][FPos])) do begin Inc(FPos); end; end; function TWAParser.GetString: String; begin Result := Copy(FCode.Strings[FLine], FSt, FPos-FSt); end; function TWAParser.ParseKeyword: Integer; var k: String; begin FSt := FPos; while (FPos <= Length(FCode.Strings[FLine])) and ((IsAlpha(FCode.Strings[FLine][FPos])) or (IsNumeric(FCode.Strings[FLine][FPos])) or (FCode.Strings[FLine][FPos] in ['_', '-'])) do begin Inc(FPos); end; if FPos > FSt then begin k := Lowercase(GetString); if k = 'include' then Result := T_INCLUDE else if k = 'echo' then Result := T_ECHO else if k = 'referrer' then Result := T_REFERRER else if k = 'ref' then Result := T_REF else if k = 'get' then Result := T_GET else if k = 'post' then Result := T_POST else if k = 'set' then Result := T_SET else if k = 'cookies' then Result := T_COOKIES else if k = 'agent' then Result := T_AGENT else if k = 'foreach' then Result := T_FOREACH else if k = 'csv' then Result := T_CSV else if k = 'text' then Result := T_TEXT else if k = 'lookup' then Result := T_LOOKUP else if k = 'mail' then Result := T_MAIL else if k = 'verbose' then Result := T_VERBOSE else if k = 'cookie' then Result := T_COOKIE else if k = 'scrape' then Result := T_SCRAPE else if k = 'file' then Result := T_FILE else if k = 'download' then Result := T_DOWNLOAD else if k = 'defined' then Result := T_DEFINED else if k = 'where' then Result := T_WHERE else if k = 'is' then Result := T_IS else if k = 'off' then Result := T_OFF else if k = 'on' then Result := T_ON else if k = 'fslookup' then Result := T_FSLOOKUP else if k = 'field' then Result := T_FIELD else if k = 'parse' then Result := T_HTMLPARSE else if k = 'encode' then Result := T_ENCODE else if k = 'basename' then Result := T_BASENAME else if k = 'pause' then Result := T_PAUSE else if k = 'sleep' then Result := T_SLEEP else if k = 'dump' then Result := T_DUMP else if k = 'prompt' then Result := T_PROMPT else if k = 'run' then Result := T_RUN else if k = 'quit' then Result := T_QUIT else if k = 'freadline' then Result := T_FREADLN else if k = 'fseek' then Result := T_FSEEK else if k = 'fwriteline' then Result := T_FWRITELN else if k = 'realcsv' then Result := T_REALCSV else if k = 'authorization' then Result := T_AUTH else if k = 'config' then Result := T_CONFIG else if k = 'filter-filename' then Result := T_FILTER_FILENAME else if k = 'parse-string' then Result := T_STRPARSE else if k = 'match' then Result := T_MATCH else if k = 'regex' then Result := T_REGEX else if k = 'in' then Result := T_IN else if k = 'string-regex' then Result := T_STR_REGEX else if k = 'msleep' then Result := T_MSLEEP else if k = 'preview' then Result := T_GUI_PREVIEW else if k = 'wordwrap' then Result := T_WORDWRAP else if k = 'record' then Result := T_RECORD else if k = 'mkdir' then Result := T_MKDIR else Result := T_STRUCTVAR; end else Result := T_JUNK; end; procedure TWAParser.NextLine; begin Inc(FLine); FPos := 1; FSt := 1; while (Peek <> T_EOF) and (Peek = T_EOL) do begin Inc(FLine); end; end; function TWAParser.ParseNumber: Integer; begin if FPos > Length(FCode.Strings[FLine]) then begin Result := T_EOL; end else begin FSt := FPos; while (FPos <= Length(FCode.Strings[FLine])) and (IsNumeric(FCode.Strings[FLine][FPos])) do begin Inc(FPos); end; Result := T_INTEGER; end; end; function TWAParser.ParseString: Integer; begin if FPos > Length(FCode.Strings[FLine]) then begin Result := T_EOL; end else if FCode.Strings[FLine][FPos] <> '"' then begin Result := T_JUNK; end else begin Inc(FPos); while (FPos <= Length(FCode.Strings[FLine])) and (FCode.Strings[FLine][FPos] <> '"') do begin if FCode.Strings[FLine][FPos] = '\' then Inc(FPos); Inc(FPos); end; if (FPos <= Length(FCode.Strings[FLine])) and (FCode.Strings[FLine][FPos] <> '"') then Result := T_JUNK else begin Result := T_STRING; Inc(FPos); end; end; end; function TWAParser.ParseSymbol: Integer; begin FSt := FPos; case FCode.Strings[FLine][FPos] of '"': // string parsing begin Result := ParseString; end; '@': begin Result := T_PREPROC; Inc(FPos); end; '{': begin Result := T_LBRACE; Inc(FPos); end; '}': begin Result := T_RBRACE; Inc(FPos); end; ',': begin Result := T_COMMA; Inc(FPos); end; '/': begin if (FPos+1 <= Length(FCode.Strings[FLine])) and (FCode.Strings[FLine][FPos+1] = '/') then Result := T_EOL else Result := T_JUNK; end; else begin Result := T_JUNK; Inc(FPos); end; end; end; function TWAParser.GetToken: Integer; begin if FLine >= FCode.Count then begin Result := T_EOF; Exit; end; WS; if FPos > Length(FCode.Strings[FLine]) then begin Result := T_EOL; end else begin if (IsAlpha(FCode.Strings[FLine][FPos])) or (FCode.Strings[FLine][FPos] = '_') then begin Result := ParseKeyword; end else if IsNumeric(FCode.Strings[FLine][FPos]) then begin Result := ParseNumber; end else begin Result := ParseSymbol; end; end; end; function TWAParser.Peek: Integer; var tmpPos,tmpSt:Integer; begin tmpPos := FPos; tmpSt := FSt; Result := GetToken; FPos := tmpPos; FSt := tmpSt; end; procedure TWAParser.InitParser; begin FPos := 1; FLine := 0; FSt := 1; end; procedure TWAParser.SetLine (const S: String); begin FCode.Clear; FCode.Add(S); end; procedure TWAParser.LoadFromFile (const Fn: String); begin Self.FFile := Fn; FCode.LoadFromFile(Fn); InitParser; end; procedure TWAParser.PushInfo; var p: PPosInfo; begin New(p); p^.Line := FLine; p^.Pos := FPos; p^.St := FSt; FPosits.Add(p); end; procedure TWAParser.PopInfo; begin //Reload; FPosits.Remove(FPosits.Last); end; procedure TWAParser.Reload; var p: PPosInfo; begin if FPosits.Count < 1 then raise Exception.Create('Parser info list is empty'); p := FPosits.Last; FLine := p^.Line; FPos := p^.Pos; FSt := p^.St; end; end.
{******************************************************************************* 作者: dmzn@163.com 2008-08-07 描述: 系统数据库常量定义 备注: *.自动创建SQL语句,支持变量:$Inc,自增;$Float,浮点;$Integer=sFlag_Integer; $Decimal=sFlag_Decimal;$Image,二进制流 *******************************************************************************} unit USysDB; {$I Link.inc} interface uses SysUtils, Classes; const cSysDatabaseName: array[0..4] of String = ( 'Access', 'SQL', 'MySQL', 'Oracle', 'DB2'); //db names type TSysDatabaseType = (dtAccess, dtSQLServer, dtMySQL, dtOracle, dtDB2); //db types PSysTableItem = ^TSysTableItem; TSysTableItem = record FTable: string; FNewSQL: string; end; //系统表项 var gSysTableList: TList = nil; //系统表数组 gSysDBType: TSysDatabaseType = dtSQLServer; //系统数据类型 //------------------------------------------------------------------------------ const //自增字段 sField_Access_AutoInc = 'Counter'; sField_SQLServer_AutoInc = 'Integer IDENTITY (1,1) PRIMARY KEY'; //小数字段 sField_Access_Decimal = 'Float'; sField_SQLServer_Decimal = 'Decimal(15, 5)'; //图片字段 sField_Access_Image = 'OLEObject'; sField_SQLServer_Image = 'Image'; //日期相关 sField_SQLServer_Now = 'getDate()'; ResourceString {*权限项*} sPopedom_Read = 'A'; //浏览 sPopedom_Add = 'B'; //添加 sPopedom_Edit = 'C'; //修改 sPopedom_Delete = 'D'; //删除 sPopedom_Preview = 'E'; //预览 sPopedom_Print = 'F'; //打印 sPopedom_Export = 'G'; //导出 {*相关标记*} sFlag_Yes = 'Y'; //是 sFlag_No = 'N'; //否 sFlag_Enabled = 'Y'; //启用 sFlag_Disabled = 'N'; //禁用 sFlag_Integer = 'I'; //整数 sFlag_Decimal = 'D'; //小数 sFlag_CarType = 'CarType'; //车厢类型 sFlag_CarMode = 'CarMode'; //车厢型号 sFlag_TrainID = 'TrainID'; //火车标识 sFlag_QInterval = 'QueryInterval'; //查询间隔 sFlag_CollectTime = 'CollectInterval'; //采集间隔 sFlag_ResetTime = 'FrameResetTime'; //时钟同步 sFlag_PrintSend = 'PrintSendData'; sFlag_PrintRecv = 'PrintRecvData'; //打印数据 sFlag_UIInterval = 'UIItemInterval'; //界面间隔 sFlag_UIMaxValue = 'UIItemMaxValue'; //最大进度 sFlag_ChartCount = 'ChartMaxCount'; //最大点数 sFlag_ChartTime = 'ChartTimeLong'; //数据时长 sFlag_ReportPage = 'ReportPageSize'; //报表页(小时) {*数据表*} sTable_Entity = 'Sys_Entity'; //字典实体 sTable_DictItem = 'Sys_DataDict'; //字典明细 sTable_SysDict = 'Sys_Dict'; //系统字典 sTable_ExtInfo = 'Sys_ExtInfo'; //附加信息 sTable_SysLog = 'Sys_EventLog'; //系统日志 sTable_BaseInfo = 'Sys_BaseInfo'; //基础信息 sTable_Carriage = 'T_Carriage'; //车厢 sTable_Device = 'T_Device'; //设备 sTable_Port = 'T_COMPort'; //串口 sTable_BreakPipe = 'T_BreakPipe'; sTable_BreakPot = 'T_BreakPot'; sTable_TotalPipe = 'T_TotalPipe'; //数据记录 {*新建表*} sSQL_NewSysDict = 'Create Table $Table(D_ID $Inc, D_Name varChar(15),' + 'D_Desc varChar(30), D_Value varChar(50), D_Memo varChar(20),' + 'D_ParamA $Float, D_ParamB varChar(50), D_Index Integer Default 0)'; {----------------------------------------------------------------------------- 系统字典: SysDict *.D_ID: 编号 *.D_Name: 名称 *.D_Desc: 描述 *.D_Value: 取值 *.D_Memo: 相关信息 *.D_ParamA: 浮点参数 *.D_ParamB: 字符参数 *.D_Index: 显示索引 -----------------------------------------------------------------------------} sSQL_NewExtInfo = 'Create Table $Table(I_ID $Inc, I_Group varChar(20),' + 'I_ItemID varChar(20), I_Item varChar(30), I_Info varChar(50),' + 'I_ParamA $Float, I_ParamB varChar(50), I_Index Integer Default 0)'; {----------------------------------------------------------------------------- 扩展信息表: ExtInfo *.I_ID: 编号 *.I_Group: 信息分组 *.I_ItemID: 信息标识 *.I_Item: 信息项 *.I_Info: 信息内容 *.I_ParamA: 浮点参数 *.I_ParamB: 字符参数 *.I_Memo: 备注信息 *.I_Index: 显示索引 -----------------------------------------------------------------------------} sSQL_NewSysLog = 'Create Table $Table(L_ID $Inc, L_Date DateTime,' + 'L_Man varChar(32),L_Group varChar(20), L_ItemID varChar(20),' + 'L_KeyID varChar(20), L_Event varChar(220))'; {----------------------------------------------------------------------------- 系统日志: SysLog *.L_ID: 编号 *.L_Date: 操作日期 *.L_Man: 操作人 *.L_Group: 信息分组 *.L_ItemID: 信息标识 *.L_KeyID: 辅助标识 *.L_Event: 事件 -----------------------------------------------------------------------------} sSQL_NewBaseInfo = 'Create Table $Table(B_ID $Inc, B_Group varChar(15),' + 'B_Text varChar(50), B_Py varChar(25), B_Memo varChar(25),' + 'B_PID Integer, B_Index Float)'; {----------------------------------------------------------------------------- 基本信息表: BaseInfo *.B_ID: 编号 *.B_Group: 分组 *.B_Text: 内容 *.B_Py: 拼音简写 *.B_Memo: 备注信息 *.B_PID: 上级节点 *.B_Index: 创建顺序 -----------------------------------------------------------------------------} sSQL_NewCarriage = 'Create Table $Table(R_ID $Inc, C_ID varChar(15),' + 'C_Name varChar(50), C_TypeID Integer, C_TypeName varChar(32), ' + 'C_ModeID Integer, C_ModeName varChar(32), C_Position Integer)'; {----------------------------------------------------------------------------- 车厢: Carriage *.R_ID: 记录号 *.C_ID: 标识 *.C_Name: 名称 *.C_TypeID,C_TypeName: 类型 *.C_ModeID,C_ModeName: 型号 *.C_Postion: 前后位置 -----------------------------------------------------------------------------} sSQL_NewDevice = 'Create Table $Table(R_ID $Inc, D_ID varChar(15),' + 'D_Port varChar(16), D_Serial varChar(50), D_Index Integer,' + 'D_Carriage varChar(15), D_clBreakPipe Integer, D_clBreakPot Integer,' + 'D_clTotalPot Integer)'; {----------------------------------------------------------------------------- 设备: Device *.R_ID: 记录号 *.D_ID: 标识 *.D_Port: 端口 *.D_Serial: 装置号 *.D_Index: 地址索引 *.D_Carriage: 车厢 *.D_clBreakPipe,D_clBreakPot,D_clTotalPot: 曲线颜色 -----------------------------------------------------------------------------} sSQL_NewCOMPort = 'Create Table $Table(R_ID $Inc, C_ID varChar(15),' + 'C_Name varChar(50), C_Port varChar(16), C_Baund varChar(16),' + 'C_DataBits varChar(16), C_StopBits varChar(16), C_Position Integer)'; {----------------------------------------------------------------------------- 串口: port *.R_ID: 记录号 *.C_ID: 编号 *.C_Name: 名称 *.C_Port: 端口 *.C_Baund: 波特率 *.C_DataBits: 数据位 *.C_StopBits: 起停位 *.C_Position: 前后位置 -----------------------------------------------------------------------------} sSQL_NewBreakPipe = 'Create Table $Table(R_ID $Inc, P_Train varChar(15),' + 'P_Device varChar(15), P_Carriage varChar(15),' + 'P_Value $Float, P_Number Integer, P_Date DateTime)'; {----------------------------------------------------------------------------- 制动管: BreakPipe *.R_ID: 记录号 *.P_Train: 车辆标识 *.P_Device: 设备 *.P_Carriage: 车厢 *.P_Value: 数据 *.P_Number: 个数 *.P_Date: 采集日期 -----------------------------------------------------------------------------} sSQL_NewBreakPot = 'Create Table $Table(R_ID $Inc, P_Train varChar(15),' + 'P_Device varChar(15), P_Carriage varChar(15),' + 'P_Value $Float, P_Number Integer, P_Date DateTime)'; {----------------------------------------------------------------------------- 制动缸: BreakPot *.R_ID: 记录号 *.P_Train: 车辆标识 *.P_Device: 设备 *.P_Carriage: 车厢 *.P_Value: 数据 *.P_Number: 个数 *.P_Date: 采集日期 -----------------------------------------------------------------------------} sSQL_NewTotalPipe = 'Create Table $Table(R_ID $Inc, P_Train varChar(15),' + 'P_Device varChar(15), P_Carriage varChar(15),' + 'P_Value $Float, P_Date DateTime)'; {----------------------------------------------------------------------------- 总风管: TotalPipe *.R_ID: 记录号 *.P_Train: 车辆标识 *.P_Device: 设备 *.P_Carriage: 车厢 *.P_Value: 数据 *.P_Date: 采集日期 -----------------------------------------------------------------------------} //------------------------------------------------------------------------------ // 数据查询 //------------------------------------------------------------------------------ sQuery_SysDict = 'Select D_ID, D_Value, D_Memo From $Table ' + 'Where D_Name=''$Name'' Order By D_Index Desc'; {----------------------------------------------------------------------------- 从数据字典读取数据 *.$Table: 数据字典表 *.$Name: 字典项名称 -----------------------------------------------------------------------------} sQuery_ExtInfo = 'Select I_ID, I_Item, I_Info From $Table Where ' + 'I_Group=''$Group'' and I_ItemID=''$ID'' Order By I_Index Desc'; {----------------------------------------------------------------------------- 从扩展信息表读取数据 *.$Table: 扩展信息表 *.$Group: 分组名称 *.$ID: 信息标识 -----------------------------------------------------------------------------} implementation //------------------------------------------------------------------------------ //Desc: 添加系统表项 procedure AddSysTableItem(const nTable,nNewSQL: string); var nP: PSysTableItem; begin New(nP); gSysTableList.Add(nP); nP.FTable := nTable; nP.FNewSQL := nNewSQL; end; //Desc: 系统表 procedure InitSysTableList; begin gSysTableList := TList.Create; AddSysTableItem(sTable_SysDict, sSQL_NewSysDict); AddSysTableItem(sTable_ExtInfo, sSQL_NewExtInfo); AddSysTableItem(sTable_SysLog, sSQL_NewSysLog); AddSysTableItem(sTable_BaseInfo, sSQL_NewBaseInfo); AddSysTableItem(sTable_Carriage, sSQL_NewCarriage); AddSysTableItem(sTable_Device, sSQL_NewDevice); AddSysTableItem(sTable_Port, sSQL_NewCOMPort); AddSysTableItem(sTable_BreakPipe, sSQL_NewBreakPipe); AddSysTableItem(sTable_BreakPot, sSQL_NewBreakPot); AddSysTableItem(sTable_TotalPipe, sSQL_NewTotalPipe); end; //Desc: 清理系统表 procedure ClearSysTableList; var nIdx: integer; begin for nIdx:= gSysTableList.Count - 1 downto 0 do begin Dispose(PSysTableItem(gSysTableList[nIdx])); gSysTableList.Delete(nIdx); end; FreeAndNil(gSysTableList); end; initialization InitSysTableList; finalization ClearSysTableList; end.
unit XLSWriteII; { ******************************************************************************** ******* XLSReadWriteII V1.14 ******* ******* ******* ******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* *******************************************************f************************* ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} interface uses Classes, SysUtils, Dialogs, BIFFRecsII, CellFormats, SheetData, Windows, XLSUtils, XLSStream, XLSFonts, ExcelMaskII, EncodeFormulaII, MSODrawing, XLSReadWriteII, Picture, Cell, Graphics, XLSChart, Names; type TXLSWriteII = class(TObject) protected FXLS: TXLSReadWriteII; PBuf: PByteArray; FCurrSheet: integer; FXLSStream: TXLSStream; procedure WriteRecId(RecId: word); procedure WriteWord(RecId,Value: word); procedure WriteBoolean(RecId: word; Value: boolean); procedure WriteBuf(RecId,Size: word); procedure WritePointer(RecId: word; P: Pointer; Size: word); // File prefix procedure WREC_BOF(SubStreamType: TSubStreamType); procedure WREC_INTERFACEHDR; procedure WREC_ADDMENU; procedure WREC_DELMENU; procedure WREC_INTERFACEEND; procedure WREC_WRITEACCESS; procedure WREC_CODEPAGE; procedure WREC_DSF; procedure WREC_EXCEL9FILE; procedure WREC_TABID; procedure WREC_OBPROJ; procedure WREC_FNGROUPCOUNT; procedure WREC_WINDOWPROTECT; procedure WREC_PROTECT; procedure WREC_PROTECT_Sheet(Value: boolean); procedure WREC_PASSWORD; procedure WREC_PROT4REV; procedure WREC_PROT4REVPASS; procedure WREC_WINDOW1; procedure WREC_BACKUP; procedure WREC_HIDEOBJ; procedure WREC_1904; procedure WREC_PRECISION; procedure WREC_REFRESHALL; procedure WREC_BOOKBOOL; procedure WREC_UNCALCED; procedure WREC_FONT; procedure WREC_FORMAT; procedure WREC_XF; procedure WREC_STYLE; procedure WREC_PALETTE; // procedure WREC_EXTERNNAME; procedure WREC_EXTERNCOUNT; procedure WREC_EXTERNSHEET; procedure WREC_SUPBOOK; procedure WREC_NAMES; procedure WREC_USESELFS; procedure WREC_BOUNDSHEET; procedure WREC_COUNTRY; procedure WREC_RECALCID; procedure WREC_MSODRAWINGGROUP; procedure WREC_SST; procedure WREC_EXTSST; procedure WREC_EOF; // Sheet prefix procedure WREC_CALCMODE; procedure WREC_CALCCOUNT; procedure WREC_REFMODE; procedure WREC_ITERATION; procedure WREC_DELTA; procedure WREC_SAVERECALC; procedure WREC_PRINTHEADERS; procedure WREC_PRINTGRIDLINES; procedure WREC_GRIDSET; procedure WREC_GUTS; procedure WREC_DEFAULTROWHEIGHT; procedure WREC_WSBOOL; procedure WREC_HORIZONTALPAGEBREAKS; procedure WREC_VERTICALPAGEBREAKS; procedure WREC_HEADER; procedure WREC_FOOTER; procedure WREC_HCENTER; procedure WREC_VCENTER; procedure WREC_PLS; procedure WREC_SETUP; procedure WREC_DEFCOLWIDTH; procedure WREC_COLINFO; procedure WREC_DIMENSIONS; procedure WREC_ROW; // Sheet suffix procedure WREC_MSODRAWING; procedure WREC_MSODRAWINGSELECTION; procedure WREC_WINDOW2; procedure WREC_SCL; procedure WREC_PANE; procedure WREC_SELECTION; procedure WREC_DVAL; procedure WREC_DV; procedure WREC_HLINK; procedure WREC_MERGECELLS; procedure WriteFilePrefix; procedure WriteFileSuffix; procedure WritePagePrefix; procedure WritePageSuffix; procedure WriteCharts; public constructor Create(XLS: TXLSReadWriteII); destructor Destroy; override; procedure WriteToStream(Stream: TStream); procedure WriteToStream40(Stream: TStream); end; implementation type TWordArray = array[0..65535] of word; PWordArray = ^TWordArray; const DefaultXF4: array[0..20,0..11] of byte = ( ($00,$00,$F5,$FF,$20,$00,$00,$CE,$00,$00,$00,$00), ($01,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($01,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($02,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($02,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$F5,$FF,$20,$F4,$00,$CE,$00,$00,$00,$00), ($00,$00,$01,$00,$20,$00,$00,$CE,$00,$00,$00,$00), ($00,$08,$F5,$FF,$20,$F8,$00,$CE,$00,$00,$00,$00), ($00,$06,$F5,$FF,$20,$F8,$00,$CE,$00,$00,$00,$00), ($00,$0C,$F5,$FF,$20,$F8,$00,$CE,$00,$00,$00,$00), ($00,$0A,$F5,$FF,$20,$F8,$00,$CE,$00,$00,$00,$00), ($00,$0D,$F5,$FF,$20,$F8,$00,$CE,$00,$00,$00,$00)); const DefaultXF7: array[0..15] of TRecXF7 = ( (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 1;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 1;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 2;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 2;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $F420;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000), (FontIndex: 0;FormatIndex: 0;Data1: $0001;Data2: $0020;Data3: $20C0;Data4: $0000;Data5: $0000;Data6: $0000)); // If the number of default formats are changed, DEFAULT_FORMATS_HIGH in BIFFRecsII must be changed. const DefaultXF8: array[0..20] of TRecXF8 = ( (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $0000;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 1;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 1;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 2;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 2;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $FFF5;Data2: $0020;Data3: $F400;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: 0;Data1: $0001;Data2: $0020;Data3: $0000;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), // The last 5 XF records are for the STYLE records. (FontIndex: 0;FormatIndex: $2A;Data1: $FFF5;Data2: $0020;Data3: $0000;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: $2B;Data1: $FFF5;Data2: $0020;Data3: $0000;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: $2C;Data1: $FFF5;Data2: $0020;Data3: $0000;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: $2D;Data1: $FFF5;Data2: $0020;Data3: $0000;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0), (FontIndex: 0;FormatIndex: $09;Data1: $FFF5;Data2: $0020;Data3: $0000;Data4: $0000;Data5: $0000;Data6: $00000000;Data7: $20C0)); { TXLSWriteII } constructor TXLSWriteII.Create(XLS: TXLSReadWriteII); begin FXLS := XLS; GetMem(PBuf,FXLS.MaxBuffsize); FXLSStream := TXLSStream.Create; FXLSStream.SaveVBA := FXLS.PreserveMacros; end; destructor TXLSWriteII.Destroy; begin FXLSStream.Free; FreeMem(PBuf); end; procedure TXLSWriteII.WriteRecId(RecId: word); var Header: TBIFFHeader; begin Header.RecId := RecID; Header.Length := 0; FXLSStream.Write(Header,SizeOf(TBIFFHeader)); end; procedure TXLSWriteII.WriteWord(RecId,Value: word); var Header: TBIFFHeader; begin Header.RecId := RecID; Header.Length := SizeOf(word); FXLSStream.Write(Header,SizeOf(TBIFFHeader)); FXLSStream.Write(Value,SizeOf(word)); end; procedure TXLSWriteII.WriteBoolean(RecId: word; Value: boolean); begin if Value then WriteWord(RecId,1) else WriteWord(RecId,0); end; procedure TXLSWriteII.WriteBuf(RecId,Size: word); begin FXLSStream.WriteHeader(RecId,Size); if Size > 0 then FXLSStream.Write(PBuf^,Size); end; procedure TXLSWriteII.WritePointer(RecId: word; P: Pointer; Size: word); var Header: TBIFFHeader; begin Header.RecId := RecID; Header.Length := Size; FXLSStream.Write(Header,SizeOf(TBIFFHeader)); if Size > 0 then FXLSStream.Write(P^,Header.Length); end; procedure TXLSWriteII.WriteCharts; var i: integer; Pos: longint; begin for i := 0 to FXLS.FileCharts.Count - 1 do begin Pos := FXLSStream.Pos; FXLSStream.Seek(FXLS.FileCharts[i].BOUNDSHEETFilePos,0); FXLSStream.Write(Pos,SizeOf(longint)); FXLSStream.Seek(0,2); WREC_BOF(stChart); FXLS.FileCharts[i].Records.Write(FXLSStream,PBuf); WREC_EOF; end; end; procedure TXLSWriteII.WriteToStream(Stream: TStream); var i: integer; begin try FXLSStream.TargetStream := Stream; if FXLS.ExtraObjects.Count > 0 then FXLSStream.ExtraObjects := FXLS.ExtraObjects; FXLSStream.OpenWrite(FXLS.Filename,FXLS.Version); WriteFilePrefix; WriteCharts; for i := 0 to FXLS.Sheets.Count - 1 do begin FXLS.Sheets[i].CalcDimensions; FCurrSheet := i; WritePagePrefix; FXLS.Sheets[i].StreamWriteCells(FXLS.Version,FXLSStream); WritePageSuffix; end; WriteFileSuffix; if FXLS.ExtraObjects.Count > 0 then FXLSStream.WriteVBA; finally FXLSStream.Close; end; end; procedure TXLSWriteII.WriteToStream40(Stream: TStream); begin try FXLSStream.TargetStream := Stream; FXLSStream.OpenWrite(FXLS.Filename,FXLS.Version); WREC_BOF(stWorksheet); WREC_WRITEACCESS; // WREC_CODENAME; WREC_CALCMODE; WREC_CALCCOUNT; WREC_REFMODE; WREC_ITERATION; WREC_DELTA; WREC_SAVERECALC; WREC_PRECISION; WREC_1904; WREC_PRINTHEADERS; WREC_PRINTGRIDLINES; WREC_GRIDSET; WREC_GUTS; WREC_DEFAULTROWHEIGHT; WREC_COUNTRY; WREC_HIDEOBJ; WREC_WSBOOL; WREC_FONT; WREC_HEADER; WREC_FOOTER; WREC_HCENTER; WREC_VCENTER; WREC_SETUP; WREC_BACKUP; WREC_FORMAT; WREC_WINDOWPROTECT; WREC_XF; WREC_STYLE; WREC_DEFCOLWIDTH; WREC_DIMENSIONS; // WREC_ROW; FXLS.Sheets[0].StreamWriteCells(FXLS.Version,FXLSStream); WREC_WINDOW1; WREC_WINDOW2; WREC_SELECTION; // WREC_GCW; WREC_EOF; finally FXLSStream.Close; end; end; procedure TXLSWriteII.WriteFilePrefix; begin WREC_BOF(stGlobals); WREC_INTERFACEHDR; WREC_ADDMENU; WREC_DELMENU; WREC_INTERFACEEND; WREC_WRITEACCESS; WREC_CODEPAGE; WREC_DSF; // WREC_EXCEL9FILE; // This record should only be written by Excel2000 WREC_TABID; WREC_OBPROJ; WREC_FNGROUPCOUNT; WREC_WINDOWPROTECT; WREC_PROTECT; WREC_PASSWORD; WREC_PROT4REV; WREC_PROT4REVPASS; WREC_WINDOW1; WREC_BACKUP; WREC_HIDEOBJ; WREC_1904; WREC_PRECISION; WREC_REFRESHALL; WREC_BOOKBOOL; WREC_UNCALCED; WREC_FONT; WREC_FORMAT; WREC_XF; WREC_STYLE; WREC_PALETTE; WREC_USESELFS; WREC_BOUNDSHEET; WREC_COUNTRY; WREC_RECALCID; WREC_SUPBOOK; WREC_EXTERNCOUNT; WREC_EXTERNSHEET; WREC_NAMES; WREC_MSODRAWINGGROUP; WREC_SST; WREC_EXTSST; WREC_EOF; end; procedure TXLSWriteII.WriteFileSuffix; begin end; procedure TXLSWriteII.WritePagePrefix; var Pos: longint; begin Pos := FXLSStream.Pos; FXLSStream.Seek(FXLS.Sheets[FCurrSheet].BOUNDSHEETFilePos,0); FXLSStream.Write(Pos,SizeOf(longint)); FXLSStream.Seek(0,2); WREC_BOF(stWorksheet); WREC_CALCMODE; WREC_CALCCOUNT; WREC_REFMODE; WREC_ITERATION; WREC_DELTA; WREC_SAVERECALC; WREC_PRINTHEADERS; WREC_PRINTGRIDLINES; WREC_GRIDSET; WREC_GUTS; WREC_DEFAULTROWHEIGHT; if FXLS.Version < xvExcel97 then WREC_COUNTRY; WREC_WSBOOL; WREC_HORIZONTALPAGEBREAKS; WREC_VERTICALPAGEBREAKS; WREC_HEADER; WREC_FOOTER; WREC_HCENTER; WREC_VCENTER; WREC_PLS; WREC_SETUP; WREC_PROTECT_Sheet(soProtected in FXLS.Sheets[FCurrSheet].Options); WREC_DEFCOLWIDTH; WREC_COLINFO; WREC_DIMENSIONS; WREC_ROW; end; procedure TXLSWriteII.WritePageSuffix; begin WREC_MSODRAWING; WREC_MSODRAWINGSELECTION; if FXLS.Version < xvExcel97 then WREC_WINDOW1; WREC_WINDOW2; WREC_SCL; WREC_PANE; WREC_SELECTION; WREC_DVAL; WREC_HLINK; WREC_MERGECELLS; WREC_EOF; end; procedure TXLSWriteII.WREC_1904; begin WriteWord(BIFFRECID_1904,Integer(FXLS.DateSystem1904)); end; procedure TXLSWriteII.WREC_ADDMENU; begin // Not used end; procedure TXLSWriteII.WREC_BACKUP; begin WriteWord(BIFFRECID_BACKUP,Word(FXLS.Backup)); end; procedure TXLSWriteII.WREC_BOF(SubStreamType: TSubStreamType); begin case FXLS.Version of xvExcel40: begin PRecBOF4(PBuf).A := $0000; PRecBOF4(PBuf).B := $0010; PRecBOF4(PBuf).C := $18AF; end; xvExcel50: begin PRecBOF8(PBuf).VersionNumber := $0500; // Can not be zero. PRecBOF8(PBuf).BuildIdentifier := $0DBB; // Can not be zero. PRecBOF8(PBuf).BuildYear := $07CE; end; xvExcel97: begin PRecBOF8(PBuf).VersionNumber := $0600; PRecBOF8(PBuf).BuildIdentifier := $18AF; PRecBOF8(PBuf).BuildYear := $07CD; PRecBOF8(PBuf).FileHistoryFlags := $000040C1; if FXLS.IsMac then PRecBOF8(PBuf).FileHistoryFlags := PRecBOF8(PBuf).FileHistoryFlags or $00000010; PRecBOF8(PBuf).LowBIFF := $00000106; end; end; if FXLS.Version > xvExcel40 then begin case SubStreamType of stGlobals: PRecBOF8(PBuf).SubStreamType := $0005; stVBModule: PRecBOF8(PBuf).SubStreamType := $0006; stWorksheet: PRecBOF8(PBuf).SubStreamType := $0010; stChart: PRecBOF8(PBuf).SubStreamType := $0020; stExcel4Macro: PRecBOF8(PBuf).SubStreamType := $0040; stWorkspace: PRecBOF8(PBuf).SubStreamType := $0100; end; end; case FXLS.Version of xvExcel40: WriteBuf($0409,SizeOf(TRecBOF4)); xvExcel50: WriteBuf($0809,SizeOf(TRecBOF7)); xvExcel97: WriteBuf($0809,SizeOf(TRecBOF8)); end; end; procedure TXLSWriteII.WREC_BOOKBOOL; begin WriteWord(BIFFRECID_BOOKBOOL,Word(FXLS.OptionsDialog.SaveExtLinkVal)); end; procedure TXLSWriteII.WREC_UNCALCED; begin // WriteWord(BIFFRECID_UNCALCED,0); end; procedure TXLSWriteII.WREC_BOUNDSHEET; var i: integer; begin if FXLS.Version >= xvExcel97 then begin for i := 0 to FXLS.FileCharts.Count - 1 do begin FXLS.FileCharts[i].BOUNDSHEETFilePos := FXLSStream.Pos + SizeOf(TBIFFHeader); PRecBOUNDSHEET8(PBuf).BOFPos := 0; PRecBOUNDSHEET8(PBuf).Options := $0200; PRecBOUNDSHEET8(PBuf).NameLen := Length(FXLS.FileCharts[i].SheetName) - 1; if IsMultybyteString(FXLS.FileCharts[i].SheetName) then PRecBOUNDSHEET8(PBuf).NameLen := PRecBOUNDSHEET8(PBuf).NameLen div 2; Move(Pointer(FXLS.FileCharts[i].SheetName)^,PRecBOUNDSHEET8(PBuf).Name,Length(FXLS.FileCharts[i].SheetName)); WriteBuf(BIFFRECID_BOUNDSHEET,7 + Length(FXLS.FileCharts[i].SheetName)); end; end; for i := 0 to FXLS.Sheets.Count - 1 do begin if FXLS.Version >= xvExcel97 then begin FXLS.Sheets[i].BOUNDSHEETFilePos := FXLSStream.Pos + SizeOf(TBIFFHeader); PRecBOUNDSHEET8(PBuf).BOFPos := 0; PRecBOUNDSHEET8(PBuf).Options := 0; PRecBOUNDSHEET8(PBuf).NameLen := Length(FXLS.Sheets[i].RawName) - 1; if IsMultybyteString(FXLS.Sheets[i].RawName) then PRecBOUNDSHEET8(PBuf).NameLen := PRecBOUNDSHEET8(PBuf).NameLen div 2; Move(Pointer(FXLS.Sheets[i].RawName)^,PRecBOUNDSHEET8(PBuf).Name,Length(FXLS.Sheets[i].RawName)); WriteBuf(BIFFRECID_BOUNDSHEET,7 + Length(FXLS.Sheets[i].RawName)); end else if FXLS.Version >= xvExcel50 then begin FXLS.Sheets[i].BOUNDSHEETFilePos := FXLSStream.Pos + SizeOf(TBIFFHeader); PRecBOUNDSHEET7(PBuf).BOFPos := 0; PRecBOUNDSHEET7(PBuf).Options := 0; PRecBOUNDSHEET7(PBuf).NameLen := Length(FXLS.Sheets[i].Name); Move(Pointer(FXLS.Sheets[i].Name)^,PRecBOUNDSHEET7(PBuf).Name,Length(FXLS.Sheets[i].Name)); WriteBuf(BIFFRECID_BOUNDSHEET,7 + Length(FXLS.Sheets[i].Name)); end; end; end; procedure TXLSWriteII.WREC_CODEPAGE; begin WriteWord(BIFFRECID_CODEPAGE,FXLS.Codepage); end; procedure TXLSWriteII.WREC_COUNTRY; var S: string; n: integer; begin if FXLS.Version < xvExcel97 then Exit; if FXLS.WriteDefaultData then begin SetLength(S,7); n := GetLocaleInfo(GetSystemDefaultLCID,LOCALE_ICOUNTRY,PChar(S),7); SetLength(S,n); PRecCOUNTRY(PBuf).DefaultCountryIndex := $01; if n > 0 then StrToIntDef(S,1) else PRecCOUNTRY(PBuf).WinIniCountry := $01; end else begin PRecCOUNTRY(PBuf).DefaultCountryIndex := FXLS.DefaultCountryIndex; PRecCOUNTRY(PBuf).WinIniCountry := FXLS.WinIniCountry; end; WriteBuf(BIFFRECID_COUNTRY,SizeOf(TRecCOUNTRY)); end; // According to MS doc's, this record shall only be written by excel, but if // it's missing, excel asks if "changes shall be saved" when the file containes // formulas. $00FFFFFF seems to be the highest possible value. procedure TXLSWriteII.WREC_RECALCID; begin PRecRECALCID(PBuf).RecordIdRepeated := BIFFRECID_RECALCID; PRecRECALCID(PBuf).Reserved := 0; // PRecRECALCID(PBuf).RecalcEngineId := $00016960; PRecRECALCID(PBuf).RecalcEngineId := $00FFFFFF; WriteBuf(BIFFRECID_RECALCID,SizeOf(TRecRECALCID)); end; procedure TXLSWriteII.WREC_DELMENU; begin // Not used. end; procedure TXLSWriteII.WREC_DSF; begin if FXLS.Version < xvExcel97 then Exit; WriteWord(BIFFRECID_DSF,$00); end; procedure TXLSWriteII.WREC_EXCEL9FILE; begin WriteRecId(BIFFRECID_EXCEL9FILE); end; procedure TXLSWriteII.WREC_EOF; begin WriteRecId(BIFFRECID_EOF); end; procedure TXLSWriteII.WREC_EXTSST; begin // WriteWord(BIFFRECID_EXTSST,$0008); end; procedure TXLSWriteII.WREC_SUPBOOK; var i,j,Len,Pos: integer; S: string; procedure WWord(Val: word); begin FXLSStream.Write(Val,SizeOf(word)); end; procedure WriteExternNames(Index: integer); var i,Len: integer; S: string; V: byte; begin with FXLS.NameDefs.SupBooks[Index] do begin for i := 0 to ExternNamesCount - 1 do begin V := Length(ExternNames[i].Name); S := ToMultibyte1bHeader(ExternNames[i].Name); Len := SizeOf(word) + 4 + 1 + Length(S) + ExternNames[i].NameDefLen; if (ExternNames[i].Options and $FFFE) = 0 then // not DDE or OLE Inc(Len,2); FXLSStream.WriteHeader(BIFFRECID_EXTERNNAME,Len); WWord(ExternNames[i].Options); WWord(0); WWord(0); FXLSStream.Write(V,1); FXLSStream.Write(Pointer(S)^,Length(S)); if ExternNames[i].NameDefLen > 0 then begin if (ExternNames[i].Options and $FFFE) = 0 then // not DDE or OLE WWord(ExternNames[i].NameDefLen); FXLSStream.Write(ExternNames[i].NameDef^,ExternNames[i].NameDefLen); end else if (ExternNames[i].Options and $FFFE) = 0 then // not DDE or OLE WWord(0); end; end; end; begin if FXLS.AreaNames.Count > 0 then FXLS.NameDefs.AddEXTERNSHEET(FXLS.NameDefs.AddSUPBOOK(SUPBOOK_CURRFILE,Nil),0,0,False); with FXLS.NameDefs do begin for i := 0 to SupBooksCount - 1 do begin S := SupBooks[i].Filename; if (Length(S) = 2) and (Byte(S[1]) in [$00,$01,$02]) then begin FXLSStream.WriteHeader(BIFFRECID_SUPBOOK,4); // WWord(SupBooks[i].SheetNames.Count); WWord(FXLS.Sheets.Count); FXLSStream.Write(Pointer(S)^,Length(S)); end else begin Len := 2; Pos := FXLSStream.Pos; FXLSStream.WriteHeader(BIFFRECID_SUPBOOK,0); WWord(SupBooks[i].SheetNames.Count); WWord(Length(S)); S := ToMultibyte1bHeader(S); FXLSStream.Write(Pointer(S)^,Length(S)); Inc(Len,Length(S) + 2); for j := 0 to SupBooks[i].SheetNames.Count - 1 do begin WWord(Length(SupBooks[i].SheetNames[j])); S := ToMultibyte1bHeader(SupBooks[i].SheetNames[j]); FXLSStream.Write(Pointer(S)^,Length(S)); Inc(Len,Length(S) + 2); end; FXLSStream.Seek(Pos,soFromBeginning); FXLSStream.WriteHeader(BIFFRECID_SUPBOOK,Len); FXLSStream.Seek(0,soFromEnd); end; WriteExternNames(i); end; end; end; procedure TXLSWriteII.WREC_EXTERNCOUNT; begin if FXLS.NameDefs.ExternCount > 0 then WriteWord(BIFFRECID_EXTERNCOUNT,FXLS.NameDefs.ExternCount); end; procedure TXLSWriteII.WREC_EXTERNSHEET; var i: integer; begin with FXLS.NameDefs do begin PRecEXTERNSHEET8(PBuf).XTICount := ExternSheetsCount; for i := 0 to ExternSheetsCount - 1 do begin PRecEXTERNSHEET8(PBuf).XTI[i].SupBook := ExternSheets[i].SupBook; PRecEXTERNSHEET8(PBuf).XTI[i].FirstTab := ExternSheets[i].FirstTab; PRecEXTERNSHEET8(PBuf).XTI[i].LastTab := ExternSheets[i].LastTab; end; if ExternSheetsCount > 0 then WriteBuf(BIFFRECID_EXTERNSHEET,2 + ExternSheetsCount * SizeOf(TXTI)); end; end; // If NAMES is written, SUPBOOK and EXTRENSHEET has to be written as well. procedure TXLSWriteII.WREC_NAMES; var i: integer; S: string; procedure WWord(Val: word); begin FXLSStream.Write(Val,SizeOf(word)); end; procedure WByte(Val: byte); begin FXLSStream.Write(Val,SizeOf(byte)); end; begin with FXLS.NameDefs do begin for i := 0 to WorkbookNamesCount - 1 do begin S := ToMultibyte1bHeader(WorkbookNames[i].Name); FXLSStream.WriteHeader(BIFFRECID_NAME,14 + Length(S) + WorkbookNames[i].NameDefLen); WWord(WorkbookNames[i].Options); WByte(0); WByte(Length(WorkbookNames[i].Name)); WWord(WorkbookNames[i].NameDefLen); WWord(WorkbookNames[i].SheetIndex); WWord(WorkbookNames[i].TabIndex); WByte(0); WByte(0); WByte(0); WByte(0); FXLSStream.Write(Pointer(S)^,Length(S)); if WorkbookNames[i].NameDefLen > 0 then FXLSStream.Write(WorkbookNames[i].NameDef^,WorkbookNames[i].NameDefLen); end; end; for i := 0 to FXLS.AreaNames.Count - 1 do begin if FXLS.AreaNames[i].WorkbookName = Nil then begin // if not FXLS.AreaNames[i].DoubleStored then begin S := ToMultibyte1bHeader(FXLS.AreaNames[i].AreaName); FXLSStream.WriteHeader(BIFFRECID_NAME,14 + Length(S) + FXLS.AreaNames[i].NameDefLen); WWord(FXLS.AreaNames[i].Options); // Options, Always zero for user defined names. WByte(0); WByte(Length(FXLS.AreaNames[i].AreaName)); WWord(FXLS.AreaNames[i].NameDefLen); WWord(0); WWord(FXLS.AreaNames[i].TabIndex); WByte(0); WByte(0); WByte(0); WByte(0); FXLSStream.Write(Pointer(S)^,Length(S)); if FXLS.AreaNames[i].NameDefLen > 0 then FXLSStream.Write(FXLS.AreaNames[i].RawNameDef^,FXLS.AreaNames[i].NameDefLen); end; end; end; procedure TXLSWriteII.WREC_FONT; procedure WriteFONT30; var i,Sz: integer; begin for i := 0 to FXLS.Fonts.Count - 1 do begin PRecFont30(PBuf).Height := FXLS.Fonts[i].Size * 20; PRecFont30(PBuf).Attributes := 0; if xfsItalic in FXLS.Fonts[i].Style then PRecFont30(PBuf).Attributes := PRecFont30(PBuf).Attributes or $02; if xfsStrikeOut in FXLS.Fonts[i].Style then PRecFont30(PBuf).Attributes := PRecFont30(PBuf).Attributes or $08; PRecFont30(PBuf).ColorIndex := Integer(FXLS.Fonts[i].Color); Sz := SizeOf(TRecFONT30) - 256; PRecFont30(PBuf).NameLen := Length(FXLS.Fonts[i].Name); Move(Pointer(FXLS.Fonts[i].Name)^,PRecFont30(PBuf).Name,PRecFont30(PBuf).NameLen); Inc(Sz,PRecFont30(PBuf).NameLen); if i <> 4 then WriteBuf(BIFFRECID_FONT,Sz); end; end; procedure WriteFONT50; var i,Sz: integer; S: string; begin for i := 0 to FXLS.Fonts.Count - 1 do begin PRecFont(PBuf).Height := FXLS.Fonts[i].Size * 20; PRecFont(PBuf).Attributes := 0; if xfsItalic in FXLS.Fonts[i].Style then PRecFont(PBuf).Attributes := PRecFont(PBuf).Attributes or $02; if xfsStrikeOut in FXLS.Fonts[i].Style then PRecFont(PBuf).Attributes := PRecFont(PBuf).Attributes or $08; PRecFont(PBuf).ColorIndex := Integer(FXLS.Fonts[i].Color); if xfsBold in FXLS.Fonts[i].Style then PRecFont(PBuf).Bold := $02BC else PRecFont(PBuf).Bold := $0190; case FXLS.Fonts[i].SubSuperScript of xssNone: PRecFont(PBuf).SubSuperScript := $00; xssSuperscript: PRecFont(PBuf).SubSuperScript := $01; xssSubscript: PRecFont(PBuf).SubSuperScript := $02; end; case FXLS.Fonts[i].Underline of xulNone: PRecFont(PBuf).Underline := $00; xulSingle: PRecFont(PBuf).Underline := $01; xulDouble: PRecFont(PBuf).Underline := $02; xulSingleAccount: PRecFont(PBuf).Underline := $21; xulDoubleAccount: PRecFont(PBuf).Underline := $22; end; PRecFont(PBuf).Family := 0; PRecFont(PBuf).Reserved := 0; PRecFont(PBuf).CharSet := Byte(FXLS.Fonts[i].CharSet); PRecFont(PBuf).NameLen := Length(FXLS.Fonts[i].Name); Sz := SizeOf(TRecFONT) - 256; if FXLS.Version >= xvExcel97 then begin S := ToMultibyte1bHeader(FXLS.Fonts[i].Name); Move(Pointer(S)^,PRecFont(PBuf).Name,Length(S)); Inc(Sz,Length(S)); end else begin Move(Pointer(FXLS.Fonts[i].Name)^,PRecFont(PBuf).Name,PRecFont(PBuf).NameLen); Inc(Sz,PRecFont(PBuf).NameLen); end; { if (i = 0) and (FXLS.WriteDefaultData) then begin for j := 0 to DEFAULT_FONT_COUNT - 2 do WriteBuf(BIFFRECID_FONT,Sz); end } if i <> 4 then WriteBuf(BIFFRECID_FONT,Sz); end; end; begin if FXLS.Version > xvExcel40 then WriteFONT50 else WriteFONT30; end; procedure TXLSWriteII.WREC_FORMAT; var i: integer; S: string; begin for i := 0 to FXLS.Formats.NumberFormats.Count - 1 do begin if Length(FXLS.Formats.NumberFormats[i]) < 2 then Continue; // Don't write standard formats. if (i <= High(TInternalNumberFormats)) and (FXLS.Formats.NumberFormats[i] = TInternalNumberFormats[i]) then Continue; S := FXLS.Formats.NumberFormats[i]; if FXLS.Version > xvExcel40 then PRecFORMAT(PBuf).Index := i else PRecFORMAT(PBuf).Index := 0; if FXLS.Version >= xvExcel97 then begin if S[1] = #0 then begin PRecFORMAT97(PBuf).Len := Length(S) - 1; Move(Pointer(S)^,PRecFORMAT97(PBuf).Data,Length(S)); end else begin PRecFORMAT97(PBuf).Len := (Length(S) - 1) div 2; Move(Pointer(S)^,PRecFORMAT97(PBuf).Data,Length(S)); end; WriteBuf(BIFFRECID_FORMAT,4 + Length(S)); end else begin S := Copy(S,2,MAXINT); PRecFORMAT(PBuf).Len := Length(S); Move(Pointer(S)^,PRecFORMAT(PBuf).Data,Length(S)); WriteBuf(BIFFRECID_FORMAT,3 + Length(S)); end; end; end; procedure TXLSWriteII.WREC_HIDEOBJ; begin WriteWord(BIFFRECID_HIDEOBJ,Word(FXLS.OptionsDialog.ShowObjects)); end; procedure TXLSWriteII.WREC_INTERFACEEND; begin // WriteRecID(BIFFRECID_INTERFACEEND); end; procedure TXLSWriteII.WREC_INTERFACEHDR; begin { if FVersion = xvExcel97 then WriteWord(BIFFRECID_INTERFACEHDR,FCodepage) else WriteRecID(BIFFRECID_INTERFACEHDR); } end; procedure TXLSWriteII.WREC_MSODRAWINGGROUP; var n: integer; begin if FXLS.Version < xvExcel97 then Exit; n := FXLS.PicturesInSheetsCount + FXLS.NotesInSheetsCount + FXLS.ChartsInSheetsCount; if (n > 0) then WriteMSOGroup(poInMemory in FXLS.PictureOptions,FXLS.Pictures,n,FXLSStream); end; procedure TXLSWriteII.WREC_PASSWORD; begin WriteWord(BIFFRECID_PASSWORD,0); end; procedure TXLSWriteII.WREC_PRECISION; begin WriteWord(BIFFRECID_PRECISION,Word(not FXLS.OptionsDialog.PrecisionAsDisplayed)); end; procedure TXLSWriteII.WREC_PROT4REV; begin if FXLS.Version < xvExcel97 then Exit; WriteBoolean(BIFFRECID_PROT4REV,FXLS.Prot4Rev); end; procedure TXLSWriteII.WREC_PROT4REVPASS; begin if FXLS.Version < xvExcel97 then Exit; WriteWord(BIFFRECID_PROT4REVPASS,$0000); end; procedure TXLSWriteII.WREC_PROTECT; var i: integer; begin for i := 0 to FXLS.Sheets.Count - 1 do begin if soProtected in FXLS.Sheets[i].Options then begin WriteWord(BIFFRECID_PROTECT,1); Break; end; end; end; procedure TXLSWriteII.WREC_PROTECT_Sheet(Value: boolean); begin WriteWord(BIFFRECID_PROTECT,Word(Value)); end; procedure TXLSWriteII.WREC_REFRESHALL; begin WriteWord(BIFFRECID_REFRESHALL,Word(FXLS.RefreshAll)); end; procedure TXLSWriteII.WREC_SST; begin if FXLS.Version < xvExcel97 then Exit; FXLS.Sheets.WriteSST(FXLSStream); end; procedure TXLSWriteII.WREC_STYLE; const DefaultSTYLE: array[0..5] of longword = ($FF038010,$FF068011,$FF048012,$FF078013,$FF008000,$FF058014); var i: integer; begin if FXLS.WriteDefaultData then begin for i := 0 to High(DefaultSTYLE) do WritePointer(BIFFRECID_STYLE,@DefaultSTYLE[i],SizeOf(DefaultSTYLE[i])); end else begin for i := 0 to FXLS.Styles.Count - 1 do begin Move(FXLS.Styles[i]^,PBuf^,SizeOf(TRecSTYLE)); WriteBuf(BIFFRECID_STYLE,SizeOf(TRecSTYLE)); end; end; end; procedure TXLSWriteII.WREC_TABID; var i: integer; begin if FXLS.Version < xvExcel97 then Exit; for i := 0 to FXLS.Sheets.Count - 1 do PWordArray(PBuf)[i] := i + 1; WriteBuf(BIFFRECID_TABID,FXLS.Sheets.Count * 2); end; procedure TXLSWriteII.WREC_OBPROJ; // ThisWorkbook const D1: array[0..14] of byte = ($0C,$00,$00,$54,$68,$69,$73,$57,$6F,$72,$6B,$62,$6F,$6F,$6B); begin if FXLS.ExtraObjects.Count > 0 then begin FXLSStream.WriteHeader(BIFFRECID_OBPROJ,0); FXLSStream.WriteHeader($01BA,SizeOf(D1)); FXLSStream.Write(D1,SizeOf(D1)); WriteWord(BIFFRECID_FNGROUPCOUNT,$000E); end; end; procedure TXLSWriteII.WREC_USESELFS; begin if FXLS.Version < xvExcel97 then Exit; WriteWord(BIFFRECID_USESELFS,$0000); end; procedure TXLSWriteII.WREC_WINDOW1; begin PRecWINDOW1(PBuf).Left := FXLS.Workbook.Left; PRecWINDOW1(PBuf).Top := FXLS.Workbook.Top; PRecWINDOW1(PBuf).Width := FXLS.Workbook.Width; PRecWINDOW1(PBuf).Height := FXLS.Workbook.Height; PRecWINDOW1(PBuf).Options := 0; if woHidden in FXLS.Workbook.Options then PRecWINDOW1(PBuf).Options := PRecWINDOW1(PBuf).Options or $01; if woIconized in FXLS.Workbook.Options then PRecWINDOW1(PBuf).Options := PRecWINDOW1(PBuf).Options or $02; if woHScroll in FXLS.Workbook.Options then PRecWINDOW1(PBuf).Options := PRecWINDOW1(PBuf).Options or $08; if woVScroll in FXLS.Workbook.Options then PRecWINDOW1(PBuf).Options := PRecWINDOW1(PBuf).Options or $10; if woTabs in FXLS.Workbook.Options then PRecWINDOW1(PBuf).Options := PRecWINDOW1(PBuf).Options or $20; PRecWINDOW1(PBuf).SelectedTabIndex := FXLS.Workbook.SelectedTab + FXLS.FileCharts.Count; PRecWINDOW1(PBuf).FirstDispTabIndex := 0; PRecWINDOW1(PBuf).SelectedTabs := 1; PRecWINDOW1(PBuf).TabRatio := $0258; WriteBuf(BIFFRECID_WINDOW1,SizeOf(TRecWINDOW1)); end; procedure TXLSWriteII.WREC_WINDOWPROTECT; begin WriteWord(BIFFRECID_WINDOWPROTECT,Word(FXLS.BookProtected)); end; procedure TXLSWriteII.WREC_FNGROUPCOUNT; begin // WriteWord(BIFFRECID_FNGROUPCOUNT,$000E); end; procedure TXLSWriteII.WREC_WRITEACCESS; var B: byte; sz: byte; S: string; begin if FXLS.Version <= xvExcel40 then begin S := Copy(FXLS.UserName,1,31); FillChar(PBuf^,31,$20); Move(Pointer(S)^,PBuf^,Length(S)); WriteBuf(BIFFRECID_WRITEACCESS,sz); end else if FXLS.Version <= xvExcel50 then begin S := Copy(FXLS.UserName,1,110); S := Char(Length(S)) + #0 + S; FillChar(PBuf^,110,$20); Move(Pointer(S)^,PBuf^,Length(S)); WriteBuf(BIFFRECID_WRITEACCESS,112); end else begin S := Copy(FXLS.UserName,1,109); S := Char(Length(S)) + #0 + #0 + S; FillChar(PBuf^,109,$20); Move(Pointer(S)^,PBuf^,Length(S)); WriteBuf(BIFFRECID_WRITEACCESS,112); end; if FXLS.ReadOnly then PRecFILESHARING(PBuf).ReadOnly := 1 else PRecFILESHARING(PBuf).ReadOnly := 0; PRecFILESHARING(PBuf).Encrypted := 0; PRecFILESHARING(PBuf).LenUsername := 0; PRecFILESHARING(PBuf).Dummy := 0; WriteBuf(BIFFRECID_FILESHARING,SizeOf(TRecFILESHARING)); end; procedure TXLSWriteII.WREC_XF; const PB: array[0..19] of byte = ($00,$00,$00,$00,$01,$00,$20,$00,$00,$40,$00,$00,$00,$00,$00,$00,$00,$04,$2B,$20); var i: integer; function XF8BorderToXF7(Border: TCellBorderStyle): word; begin case Border of cbsNone: Result := $00; cbsThin: Result := $01; cbsMedium: Result := $02; cbsDashed: Result := $03; cbsDotted: Result := $04; cbsThick: Result := $05; cbsDouble: Result := $06; cbsHair: Result := $07; cbsMediumDashed: Result := $03; cbsDashDot: Result := $04; cbsMediumDashDot: Result := $04; cbsDashDotDot: Result := $04; cbsMediumDashDotDot: Result := $04; cbsSlantedDashDot: Result := $04; else Result := $00; end; end; begin if FXLS.WriteDefaultData then begin case FXLS.Version of xvExcel97: for i := 0 to High(DefaultXF8) do WritePointer(BIFFRECID_XF,@DefaultXF8[i],SizeOf(TRecXF8)); xvExcel50: for i := 0 to High(DefaultXF7) do WritePointer(BIFFRECID_XF,@DefaultXF7[i],SizeOf(TRecXF7)); xvExcel40: for i := 0 to High(DefaultXF4) do WritePointer(BIFFRECID_XF_40,@DefaultXF4[i],12); end; end; if FXLS.Version >= xvExcel97 then begin for i := 0 to FXLS.Formats.Count - 1 do begin FXLS.Formats[i].ToXF8(PBuf); // PRecXF8(PBuf).Data4 := DefaultXF8[15].Data4; WriteBuf(BIFFRECID_XF,SizeOf(TRecXF8)); end; end else if FXLS.Version >= xvExcel50 then begin for i := 0 to FXLS.Formats.Count - 1 do begin FXLS.Formats[i].ToXF7(PBuf); WriteBuf(BIFFRECID_XF,SizeOf(TRecXF7)); end; end else if FXLS.Version >= xvExcel40 then begin for i := 0 to FXLS.Formats.Count - 1 do begin FXLS.Formats[i].ToXF4(PBuf); WriteBuf(BIFFRECID_XF_40,SizeOf(TRecXF4)); end; end; end; procedure TXLSWriteII.WREC_PALETTE; var V,i: integer; WritePalette: boolean; begin WritePalette := False; for i := 0 to High(TDefaultExcelColorPalette) do begin if TDefaultExcelColorPalette[i] <> TExcelColorPalette[i] then begin WritePalette := True; Break; end; end; if WritePalette or (FXLS.Version = xvExcel50) then begin FXLSStream.WriteHeader(BIFFRECID_PALETTE,2 + SizeOf(longword) * 56); FXLSStream.WWord(56); for i := 8 to 63 do begin V := TExcelColorPalette[i]; FXLSStream.Write(V,SizeOf(longword)); end; end; end; // Sheet prefix procedure TXLSWriteII.WREC_CALCCOUNT; begin WriteWord(BIFFRECID_CALCCOUNT,FXLS.Sheets[FCurrSheet].CalcCount); end; procedure TXLSWriteII.WREC_CALCMODE; begin case FXLS.OptionsDialog.CalcMode of cmManual: WriteWord(BIFFRECID_CALCMODE,$0000); cmAutomatic: WriteWord(BIFFRECID_CALCMODE,$0001); cmAutoExTables: WriteWord(BIFFRECID_CALCMODE,$FFFF); end; end; procedure TXLSWriteII.WREC_COLINFO; var i: integer; begin with FXLS.Sheets[FCurrSheet] do begin for i := 0 to ColumnFormats.Count - 1 do begin PRecCOLINFO(PBuf).Col1 := ColumnFormats[i].Col1; PRecCOLINFO(PBuf).Col2 := ColumnFormats[i].Col2; PRecCOLINFO(PBuf).Width := ColumnFormats[i].Width; PRecCOLINFO(PBuf).FormatIndex := ColumnFormats[i].FormatIndex; if FXLS.WriteDefaultData then begin case FXLS.Version of xvExcel50: PRecCOLINFO(PBuf).FormatIndex := PRecCOLINFO(PBuf).FormatIndex + Length(DefaultXF7); xvExcel97: PRecCOLINFO(PBuf).FormatIndex := PRecCOLINFO(PBuf).FormatIndex + Length(DefaultXF8); end; end; PRecCOLINFO(PBuf).Options := 0; if ColumnFormats[i].Hidden then PRecCOLINFO(PBuf).Options := PRecCOLINFO(PBuf).Options or $0001; if ColumnFormats[i].UnknownOptionsFlag then PRecCOLINFO(PBuf).Options := PRecCOLINFO(PBuf).Options or $0002; PRecCOLINFO(PBuf).Options := PRecCOLINFO(PBuf).Options or (ColumnFormats[i].OutlineLevel shl 8); if ColumnFormats[i].CollapsedOutline then PRecCOLINFO(PBuf).Options := PRecCOLINFO(PBuf).Options or $1000; WriteBuf(BIFFRECID_COLINFO,SizeOf(TRecCOLINFO)); end; end; end; procedure TXLSWriteII.WREC_DEFAULTROWHEIGHT; begin if FXLS.Sheets[FCurrSheet].DefaultRowHeight > 0 then begin PRecDEFAULTROWHEIGHT(PBuf).Options := 1; PRecDEFAULTROWHEIGHT(PBuf).Height := FXLS.Sheets[FCurrSheet].DefaultRowHeight; end else begin PRecDEFAULTROWHEIGHT(PBuf).Options := 0; PRecDEFAULTROWHEIGHT(PBuf).Height := 255; end; WriteBuf(BIFFRECID_DEFAULTROWHEIGHT,SizeOf(TRecDEFAULTROWHEIGHT)); end; procedure TXLSWriteII.WREC_DEFCOLWIDTH; begin if FXLS.Sheets[FCurrSheet].DefaultColWidth > 0 then WriteWord(BIFFRECID_DEFCOLWIDTH,FXLS.Sheets[FCurrSheet].DefaultColWidth) end; procedure TXLSWriteII.WREC_DELTA; begin WritePointer(BIFFRECID_DELTA,@FXLS.Sheets[FCurrSheet].Delta,SizeOf(double)); end; procedure TXLSWriteII.WREC_DIMENSIONS; begin if FXLS.Version >= xvExcel97 then begin PRecDIMENSIONS8(PBuf).FirstCol := FXLS.Sheets[FCurrSheet].FirstCol; PRecDIMENSIONS8(PBuf).LastCol := FXLS.Sheets[FCurrSheet].LastCol + 1; PRecDIMENSIONS8(PBuf).FirstRow := FXLS.Sheets[FCurrSheet].FirstRow; PRecDIMENSIONS8(PBuf).LastRow := FXLS.Sheets[FCurrSheet].LastRow + 1; PRecDIMENSIONS8(PBuf).Reserved := 0; WriteBuf(BIFFRECID_DIMENSIONS,SizeOf(TRecDIMENSIONS8)); end else begin PRecDIMENSIONS7(PBuf).FirstCol := FXLS.Sheets[FCurrSheet].FirstCol; PRecDIMENSIONS7(PBuf).LastCol := FXLS.Sheets[FCurrSheet].LastCol + 1; PRecDIMENSIONS7(PBuf).FirstRow := FXLS.Sheets[FCurrSheet].FirstRow; PRecDIMENSIONS7(PBuf).LastRow := FXLS.Sheets[FCurrSheet].LastRow + 1; PRecDIMENSIONS7(PBuf).Reserved := 0; WriteBuf(BIFFRECID_DIMENSIONS,SizeOf(TRecDIMENSIONS7)); end; end; procedure TXLSWriteII.WREC_ROW; var i: integer; begin for i := 0 to FXLS.Sheets[FCurrSheet].ROWCount - 1 do begin FXLS.Sheets[FCurrSheet].GetRow(i,PRecROW(PBuf)); WriteBuf(BIFFRECID_ROW,SizeOf(TRecROW)); end; end; procedure TXLSWriteII.WREC_FOOTER; var S: string; begin if FXLS.Sheets[FCurrSheet].PrintSettings.Footer = '' then WriteRecId(BIFFRECID_FOOTER) else if FXLS.Version >= xvExcel97 then begin S := ToMultibyte1bHeader(FXLS.Sheets[FCurrSheet].PrintSettings.Footer); PRecSTRING(PBuf).Len := Length(FXLS.Sheets[FCurrSheet].PrintSettings.Footer); Move(Pointer(S)^,PRecSTRING(PBuf).Data,Length(S)); WriteBuf(BIFFRECID_FOOTER,2 + Length(S)); end else begin S := FXLS.Sheets[FCurrSheet].PrintSettings.Footer; PRecSTRING1Byte(PBuf).Len := Length(S); Move(Pointer(S)^,PRecSTRING1Byte(PBuf).Data,Length(S)); WriteBuf(BIFFRECID_FOOTER,2 + Length(S)); end; end; procedure TXLSWriteII.WREC_GRIDSET; begin WriteWord(BIFFRECID_GRIDSET,FXLS.Sheets[FCurrSheet].Gridset); end; procedure TXLSWriteII.WREC_GUTS; begin PRecGUTS(PBuf).SizeRow := FXLS.Sheets[FCurrSheet].RowGutter; PRecGUTS(PBuf).SizeCol := FXLS.Sheets[FCurrSheet].ColGutter; PRecGUTS(PBuf).LevelRow := FXLS.Sheets[FCurrSheet].RowOutlineGutter; PRecGUTS(PBuf).LevelCol := FXLS.Sheets[FCurrSheet].ColOutlineGutter; WriteBuf(BIFFRECID_GUTS,SizeOf(TRecGUTS)); end; procedure TXLSWriteII.WREC_HCENTER; begin WriteBoolean(BIFFRECID_HCENTER,psoHorizCenter in FXLS.Sheets[FCurrSheet].PrintSettings.Options); end; procedure TXLSWriteII.WREC_HEADER; var S: string; begin if FXLS.Sheets[FCurrSheet].PrintSettings.Header = '' then WriteRecId(BIFFRECID_HEADER) else if FXLS.Version >= xvExcel97 then begin S := ToMultibyte1bHeader(FXLS.Sheets[FCurrSheet].PrintSettings.Header); PRecSTRING(PBuf).Len := Length(FXLS.Sheets[FCurrSheet].PrintSettings.Header); Move(Pointer(S)^,PRecSTRING(PBuf).Data,Length(S)); WriteBuf(BIFFRECID_HEADER,2 + Length(S)); end else begin S := FXLS.Sheets[FCurrSheet].PrintSettings.Header; PRecSTRING1Byte(PBuf).Len := Length(S); Move(Pointer(S)^,PRecSTRING1Byte(PBuf).Data,Length(S)); WriteBuf(BIFFRECID_HEADER,2 + Length(S)); end; end; procedure TXLSWriteII.WREC_ITERATION; begin WriteBoolean(BIFFRECID_ITERATION,soIteration in FXLS.Sheets[FCurrSheet].Options); end; procedure TXLSWriteII.WREC_PLS; var P: PDeviceModeW; begin if FXLS.HasDEVMODE and (FXLS.Version >= xvExcel97) then begin P := FXLS.GetDEVMODE; FXLSStream.WriteHeader(BIFFRECID_PLS,P.dmSize + P.dmDriverExtra + 2); FXLSStream.WWord(0); FXLSStream.Write(P^,P.dmSize + P.dmDriverExtra); end; end; procedure TXLSWriteII.WREC_PRINTGRIDLINES; begin WriteBoolean(BIFFRECID_PRINTGRIDLINES,psoGridlines in FXLS.Sheets[FCurrSheet].PrintSettings.Options); end; procedure TXLSWriteII.WREC_PRINTHEADERS; begin WriteBoolean(BIFFRECID_PRINTHEADERS,psoRowColHeading in FXLS.Sheets[FCurrSheet].PrintSettings.Options); end; procedure TXLSWriteII.WREC_REFMODE; begin WriteBoolean(BIFFRECID_REFMODE,not (soR1C1Mode in FXLS.Sheets[FCurrSheet].Options)); end; procedure TXLSWriteII.WREC_SAVERECALC; begin WriteBoolean(BIFFRECID_SAVERECALC,FXLS.SaveRecalc); end; procedure TXLSWriteII.WREC_SETUP; begin with FXLS.Sheets[FCurrSheet].PrintSettings do begin if MarginLeft >= 0 then begin PRecMARGIN(PBuf).Value := MarginLeft; WriteBuf(BIFFRECID_LEFTMARGIN,SizeOf(TRecMARGIN)); end; if MarginRight >= 0 then begin PRecMARGIN(PBuf).Value := MarginRight; WriteBuf(BIFFRECID_RIGHTMARGIN,SizeOf(TRecMARGIN)); end; if MarginTop >= 0 then begin PRecMARGIN(PBuf).Value := MarginTop; WriteBuf(BIFFRECID_TOPMARGIN,SizeOf(TRecMARGIN)); end; if MarginBottom >= 0 then begin PRecMARGIN(PBuf).Value := MarginBottom; WriteBuf(BIFFRECID_BOTTOMMARGIN,SizeOf(TRecMARGIN)); end; PRecSETUP(PBuf).PaperSize := Integer(FXLS.Sheets[FCurrSheet].PrintSettings.PaperSize); PRecSETUP(PBuf).Scale := ScalingFactor; PRecSETUP(PBuf).PageStart := StartingPage; PRecSETUP(PBuf).FitWidth := 1; PRecSETUP(PBuf).FitHeight := 1; PRecSETUP(PBuf).Options := $0000; if psoLeftToRight in Options then PRecSETUP(PBuf).Options := PRecSETUP(PBuf).Options or $0001; if psoPortrait in Options then PRecSETUP(PBuf).Options := PRecSETUP(PBuf).Options or $0002; if psoNoColor in Options then PRecSETUP(PBuf).Options := PRecSETUP(PBuf).Options or $0008; if psoDraftQuality in Options then PRecSETUP(PBuf).Options := PRecSETUP(PBuf).Options or $0010; if psoNotes in Options then PRecSETUP(PBuf).Options := PRecSETUP(PBuf).Options or $0020; PRecSETUP(PBuf).Resolution := Resolution; PRecSETUP(PBuf).VertResolution := Resolution; PRecSETUP(PBuf).HeaderMargin := HeaderMargin; PRecSETUP(PBuf).FooterMargin := FooterMargin; PRecSETUP(PBuf).Copies := Copies; WriteBuf(BIFFRECID_SETUP,SizeOf(TRecSETUP)); end; end; procedure TXLSWriteII.WREC_VCENTER; begin WriteBoolean(BIFFRECID_VCENTER,psoVertCenter in FXLS.Sheets[FCurrSheet].PrintSettings.Options); end; procedure TXLSWriteII.WREC_WSBOOL; var W: word; begin W := 0; with FXLS.Sheets[FCurrSheet] do begin if woShowAutoBreaks in WorkspaceOptions then W := W or $0001; if woApplyStyles in WorkspaceOptions then W := W or $0020; if woRowSumsBelow in WorkspaceOptions then W := W or $0040; if woFitToPage in WorkspaceOptions then W := W or $0100; if woOutlineSymbols in WorkspaceOptions then W := W or $0600; end; WriteWord(BIFFRECID_WSBOOL,W); end; procedure TXLSWriteII.WREC_HORIZONTALPAGEBREAKS; var i: integer; begin if FXLS.Sheets[FCurrSheet].PrintSettings.HorizPagebreaks.Count <= 0 then Exit; if FXLS.Version >= xvExcel97 then begin with FXLS.Sheets[FCurrSheet].PrintSettings do begin PRecHORIZONTALPAGEBREAKS(PBuf).Count := HorizPagebreaks.Count; for i := 0 to HorizPagebreaks.Count - 1 do begin PRecHORIZONTALPAGEBREAKS(PBuf).Breaks[i].Val1 := HorizPagebreaks[i].Row + 1; PRecHORIZONTALPAGEBREAKS(PBuf).Breaks[i].Val2 := HorizPagebreaks[i].Col1 + 1; PRecHORIZONTALPAGEBREAKS(PBuf).Breaks[i].Val3 := HorizPagebreaks[i].Col2 + 1; end; WriteBuf(BIFFRECID_HORIZONTALPAGEBREAKS,2 + SizeOf(TPageBreak) * HorizPagebreaks.Count); end; end else begin with FXLS.Sheets[FCurrSheet].PrintSettings do begin PWordArray(PBuf)[0] := HorizPagebreaks.Count; for i := 0 to HorizPagebreaks.Count - 1 do PWordArray(PBuf)[i + 1] := HorizPagebreaks[i].Row + 1; WriteBuf(BIFFRECID_HORIZONTALPAGEBREAKS,2 + 2 * HorizPagebreaks.Count); end; end; end; procedure TXLSWriteII.WREC_VERTICALPAGEBREAKS; var i: integer; begin if FXLS.Sheets[FCurrSheet].PrintSettings.VertPagebreaks.Count <= 0 then Exit; if FXLS.Version >= xvExcel97 then begin with FXLS.Sheets[FCurrSheet].PrintSettings do begin PRecVERTICALPAGEBREAKS(PBuf).Count := VertPagebreaks.Count; for i := 0 to VertPagebreaks.Count - 1 do begin PRecVERTICALPAGEBREAKS(PBuf).Breaks[i].Val1 := VertPagebreaks[i].Col + 1; PRecVERTICALPAGEBREAKS(PBuf).Breaks[i].Val2 := VertPagebreaks[i].Row1 + 1; PRecVERTICALPAGEBREAKS(PBuf).Breaks[i].Val3 := VertPagebreaks[i].Row2 + 1; end; WriteBuf(BIFFRECID_VERTICALPAGEBREAKS,2 + SizeOf(TPageBreak) * VertPagebreaks.Count); end; end else begin with FXLS.Sheets[FCurrSheet].PrintSettings do begin PWordArray(PBuf)[0] := VertPagebreaks.Count; for i := 0 to VertPagebreaks.Count - 1 do PWordArray(PBuf)[i + 1] := VertPagebreaks[i].Col + 1; WriteBuf(BIFFRECID_VERTICALPAGEBREAKS,2 + 2 * VertPagebreaks.Count); end; end; end; // Sheet suffix procedure TXLSWriteII.WREC_MSODRAWING; var i,p,L,ObjId,Count: integer; S: string; MSO: TMSOWriteDrawing; procedure SetPictSize(Pict: TSheetPicture); var W,H,T: integer; CellW,CellH: integer; CurrFI: integer; PixCellWidth: integer; PixCellHeight: integer; C2,R2: integer; C: TCell; Canvas: TCanvas; begin Canvas := TCanvas.Create; try Canvas.Handle := GetDC(0); FXLS.Font.CopyToTFont(Canvas.Font); CurrFI := 0; C2 := Pict.Col; R2 := Pict.Row; PixCellWidth := FXLS.Sheets[FCurrSheet].DefaultColWidth * Canvas.TextWidth('8') + 4; if FXLS.Sheets[FCurrSheet].DefaultRowHeight > 0 then PixCellHeight := Round((FXLS.Sheets[FCurrSheet].DefaultRowHeight / 20) * (Canvas.Font.Size / -Canvas.Font.Height)) + 4 else PixCellHeight := -Canvas.Font.Height + 4; if (Pict.XLSPicture.Width <= 0) or (Pict.XLSPicture.Height <= 0) then begin W := Round(Pict.XLSPicture.BMP.Width * (Pict.Zoom / 100)); H := Round(Pict.XLSPicture.BMP.Height * (Pict.Zoom / 100)); end else begin W := Round(Pict.XLSPicture.Width * (Pict.Zoom / 100)); H := Round(Pict.XLSPicture.Height * (Pict.Zoom / 100)); end; repeat C := FXLS.Sheets[FCurrSheet].Cell[C2,Pict.Row]; if (C <> Nil) and (C.FormatIndex >= 0) and (FXLS.Formats[C.FormatIndex].FontIndex <> CurrFI) then begin CurrFI := FXLS.Formats[C.FormatIndex].FontIndex; FXLS.Fonts[CurrFI].CopyToTFont(Canvas.Font); end; T := FXLS.Sheets[FCurrSheet].ColumnFormats.ColWidth(C2); if T >= 0 then CellW := Round(T * (Canvas.TextWidth('8') / 256)) else CellW := PixCellWidth; Inc(C2); Dec(W,CellW); until (W < 0); if W < 0 then begin Dec(C2); Pict.Col2Offset := Round(1024 * ((CellW - -W) / CellW)); end; Pict.Col2 := C2; repeat C := FXLS.Sheets[FCurrSheet].Cell[Pict.Col,R2]; if (C <> Nil) and (C.FormatIndex >= 0) and (FXLS.Formats[C.FormatIndex].FontIndex <> CurrFI) then begin CurrFI := FXLS.Formats[C.FormatIndex].FontIndex; FXLS.Fonts[CurrFI].CopyToTFont(Canvas.Font); end; // T := FXLS.Sheets[FCurrSheet].ColumnFormats.ColWidth(C2); T := -1; if T >= 0 then CellH := Round((T / 20) * (Canvas.Font.Size / -Canvas.Font.Height)) + 4 else CellH := PixCellHeight; Inc(R2); Dec(H,CellH); until (H < 0); if H < 0 then begin Dec(R2); Pict.Row2Offset := Round(256 * ((CellH - -H) / CellH)); end; Pict.Row2 := R2; finally Canvas.Free; end; end; procedure AddOBJChart; begin FXLSStream.WriteHeader(BIFFRECID_OBJ,SizeOf(TObjCMO) + SizeOf(TBIFFHeader) * 2); FXLSStream.WriteHeader(OBJREC_CMO,SizeOf(TObjCMO)); FillChar(PBuf^,SizeOf(TObjCMO),#0); PObjCMO(PBuf).ObjType := $05; PObjCMO(PBuf).ObjId := ObjId; Inc(ObjId); PObjCMO(PBuf).Options := $0011; FXLSStream.Write(PBuf^,SizeOf(TObjCMO)); FXLSStream.WriteHeader(OBJREC_END,0); end; begin if FXLS.Version < xvExcel97 then Exit; with FXLS.Sheets[FCurrSheet] do begin if (Notes.Count + SheetPictures.Count + Charts.Count + FileCharts.Count) > 0 then MSO := TMSOWriteDrawing.Create(Notes,SheetPictures,FileCharts,Charts) else MSO := Nil; end; try Count := 0; ObjId := 1; for i := 0 to FXLS.Sheets[FCurrSheet].Notes.Count - 1 do begin MSO.WriteObject(Count,FXLSStream); Inc(Count); FXLSStream.WriteHeader(BIFFRECID_OBJ,SizeOf(TObjCMO) + SizeOf(TBIFFHeader) * 3); FXLSStream.WriteHeader(OBJREC_CMO,SizeOf(TObjCMO)); FillChar(PBuf^,SizeOf(TObjCMO),#0); PObjCMO(PBuf).ObjType := $19; PObjCMO(PBuf).ObjId := ObjId; Inc(ObjId); PObjCMO(PBuf).Options := $0011; FXLSStream.Write(PBuf^,SizeOf(TObjCMO)); FXLSStream.WriteHeader(OBJREC_NTS,0); FXLSStream.WriteHeader(OBJREC_END,0); MSO.WriteObject(Count,FXLSStream); Inc(Count); FXLSStream.WriteHeader(BIFFRECID_TXO,SizeOf(TRecTXO)); FillChar(PBuf^,SizeOf(TRecTXO),#0); S := Trim(FXLS.Sheets[FCurrSheet].Notes[i].Text.Text); repeat p := CPos(#$0D,S); if p > 0 then Delete(S,p,1); until (p <= 0); L := Length(S); S := ToMultibyte1bHeader(S); PRecTXO(PBuf).Options := $0012; PRecTXO(PBuf).TextLen := L; PRecTXO(PBuf).FormatLen := SizeOf(TRecTXORUN) * 2; FXLSStream.Write(PBuf^,SizeOf(TRecTXO)); FXLSStream.WriteHeader(BIFFRECID_CONTINUE,Length(S)); FXLSStream.Write(Pointer(S)^,Length(S)); FXLSStream.WriteHeader(BIFFRECID_CONTINUE,SizeOf(TRecTXORUN) * 2); PRecTXORUN(PBuf).CharIndex := 0; PRecTXORUN(PBuf).FontIndex := 0; // Wrong font. Shall be a 8pt font. The default, #0, is usually 10pt. PRecTXORUN(PBuf).Reserved := 0; FXLSStream.Write(PBuf^,SizeOf(TRecTXORUN)); PRecTXORUN(PBuf).CharIndex := L; PRecTXORUN(PBuf).FontIndex := 0; PRecTXORUN(PBuf).Reserved := 0; FXLSStream.Write(PBuf^,SizeOf(TRecTXORUN)); end; for i := 0 to FXLS.Sheets[FCurrSheet].SheetPictures.Count - 1 do begin if not FXLS.Sheets[FCurrSheet].SheetPictures[i].HasValidPosition then SetPictSize(FXLS.Sheets[FCurrSheet].SheetPictures[i]); MSO.WriteObject(Count,FXLSStream); Inc(Count); FXLSStream.WriteHeader(BIFFRECID_OBJ,SizeOf(TObjCMO) + SizeOf(TBIFFHeader) * 4); FXLSStream.WriteHeader(OBJREC_CMO,SizeOf(TObjCMO)); FillChar(PBuf^,SizeOf(TObjCMO),#0); PObjCMO(PBuf).ObjType := $08; PObjCMO(PBuf).ObjId := ObjId; // FXLS.Sheets[FCurrSheet].SheetPictures[i].XLSPicture.ItemId; Inc(ObjId); PObjCMO(PBuf).Options := $0011; FXLSStream.Write(PBuf^,SizeOf(TObjCMO)); FXLSStream.WriteHeader(OBJREC_CF,0); FXLSStream.WriteHeader(OBJREC_PIOGRBIT,0); FXLSStream.WriteHeader(OBJREC_END,0); end; for i := 0 to FXLS.Sheets[FCurrSheet].FileCharts.Count - 1 do begin MSO.WriteObject(Count,FXLSStream); Inc(Count); AddOBJChart; WREC_BOF(stChart); FXLS.Sheets[FCurrSheet].FileCharts[i].Records.Write(FXLSStream,PBuf); WREC_EOF; end; for i := 0 to FXLS.Sheets[FCurrSheet].Charts.Count - 1 do begin MSO.WriteObject(Count,FXLSStream); Inc(Count); AddOBJChart; WREC_BOF(stChart); FXLS.Sheets[FCurrSheet].Charts[i].Write(FXLSStream,PBuf); WREC_EOF; end; finally MSO.Free; end; for i := 0 to FXLS.Sheets[FCurrSheet].Notes.Count - 1 do begin if FXLS.Sheets[FCurrSheet].Notes[i].HasNoteRecord then begin PRecNOTE(PBuf).Row := FXLS.Sheets[FCurrSheet].Notes[i].CellRow; PRecNOTE(PBuf).Col := FXLS.Sheets[FCurrSheet].Notes[i].CellCol; PRecNOTE(PBuf).Options := 0; if FXLS.Sheets[FCurrSheet].Notes[i].AlwaysVisible then PRecNOTE(PBuf).Options := PRecNOTE(PBuf).Options or $0002; PRecNOTE(PBuf).ObjId := i + 1; PRecNOTE(PBuf).AuthorNameLen := 0; WriteBuf(BIFFRECID_NOTE,8); end; end; end; procedure TXLSWriteII.WREC_MSODRAWINGSELECTION; begin // Don't need to write this. end; procedure TXLSWriteII.WREC_SELECTION; begin if FXLS.Sheets[FCurrSheet].Pane.PaneType = ptNone then begin PRecSELECTION(PBuf).Pane := 3; PRecSELECTION(PBuf).ActiveRow := 0; PRecSELECTION(PBuf).ActiveCol := 0; PRecSELECTION(PBuf).ActiveRef := 0; PRecSELECTION(PBuf).Refs := 1; PRecSELECTION(PBuf).Row1 := 0; PRecSELECTION(PBuf).Row2 := 0; PRecSELECTION(PBuf).Col1 := 0; PRecSELECTION(PBuf).Col2 := 0; WriteBuf(BIFFRECID_SELECTION,SizeOf(TRecSELECTION)); end; if FXLS.ExtraObjects.Count > 0 then begin FXLSStream.WriteHeader($01BA,Length(FXLS.Sheets[FCurrSheet].Name) + 3); FXLSStream.WriteUnicodeStr16(#0 + FXLS.Sheets[FCurrSheet].Name); end; end; procedure TXLSWriteII.WREC_DVAL; begin if FXLS.Sheets[FCurrSheet].Validations.Count > 0 then begin PRecDVAL(PBuf).Options := $0004; PRecDVAL(PBuf).X := 0; PRecDVAL(PBuf).Y := 0; PRecDVAL(PBuf).DropDownId := $FFFFFFFF; PRecDVAL(PBuf).DVCount := FXLS.Sheets[FCurrSheet].Validations.Count; WriteBuf(BIFFRECID_DVAL,SizeOf(TRecDVAL)); WREC_DV; end; end; procedure TXLSWriteII.WREC_DV; var i,j,L: integer; Options: longword; begin for i := 0 to FXLS.Sheets[FCurrSheet].Validations.Count - 1 do begin with FXLS.Sheets[FCurrSheet].Validations[i] do begin if Areas.Count <= 0 then Continue; L := Sizeof(Options) + BufLenMultibyte1bHeader(InputTitle) + 2 + BufLenMultibyte1bHeader(ErrorTitle) + 2 + BufLenMultibyte1bHeader(InputMsg) + 2 + BufLenMultibyte1bHeader(ErrorMsg) + 2 + LenRawExpression1 + 2 + 2 + LenRawExpression2 + 2 + 2 + Areas.Count * 8 + 2; Options := $000C0100; Options := Options + (longword(ValidationType) and $000F); Options := Options + ((longword(ValidationStyle) and $0007) shl 4); Options := Options + ((longword(ValidationOperator) and $000F) shl 20); FXLSStream.WriteHeader(BIFFRECID_DV,L); FXLSStream.Write(Options,SizeOf(Options)); FXLSStream.WStr2ByteLen(InputTitle); FXLSStream.WStr2ByteLen(ErrorTitle); FXLSStream.WStr2ByteLen(InputMsg); FXLSStream.WStr2ByteLen(ErrorMsg); { if InputTitle <> '' then FXLSStream.WStr2ByteLen(InputTitle) else begin FXLSStream.WWord($0001); FXLSStream.WWord($0000); end; if ErrorTitle <> '' then FXLSStream.WStr2ByteLen(ErrorTitle) else begin FXLSStream.WWord($0001); FXLSStream.WWord($0000); end; if InputMsg <> '' then FXLSStream.WStr2ByteLen(InputMsg) else begin FXLSStream.WWord($0001); FXLSStream.WWord($0000); end; if ErrorMsg <> '' then FXLSStream.WStr2ByteLen(ErrorMsg) else begin FXLSStream.WWord($0001); FXLSStream.WWord($0000); end; } FXLSStream.WWord(LenRawExpression1); FXLSStream.WWord($0000); if LenRawExpression1 > 0 then FXLSStream.Write(RawExpression1^,LenRawExpression1); FXLSStream.WWord(LenRawExpression2); FXLSStream.WWord($0000); if LenRawExpression2 > 0 then FXLSStream.Write(RawExpression2^,LenRawExpression2); FXLSStream.WWord(Areas.Count); for j := 0 to Areas.Count - 1 do begin FXLSStream.WWord(Areas[j].Row1); FXLSStream.WWord(Areas[j].Row2); FXLSStream.WWord(Areas[j].Col1); FXLSStream.WWord(Areas[j].Col2); end; end; end; end; procedure TXLSWriteII.WREC_WINDOW2; begin PRecWINDOW2_7(PBuf).Options := $0020 + $0080 + $0400; with FXLS.Sheets[FCurrSheet] do begin if (Pane.PaneType = ptNone) and ((FixedRows > 0) or (FixedCols > 0)) then begin Pane.SplitColX := FixedCols; Pane.SplitRowY := FixedRows; Pane.LeftCol := FixedCols; Pane.TopRow := FixedRows; Pane.PaneType := ptFrozen; end; if soShowFormulas in Options then PRecWINDOW2_7(PBuf).Options := PRecWINDOW2_7(PBuf).Options or $0001; if soGridlines in Options then PRecWINDOW2_7(PBuf).Options := PRecWINDOW2_7(PBuf).Options or $0002; if soRowColHeadings in Options then PRecWINDOW2_7(PBuf).Options := PRecWINDOW2_7(PBuf).Options or $0004; if FXLS.Sheets[FCurrSheet].Pane.PaneType = ptFrozen then begin PRecWINDOW2_7(PBuf).Options := PRecWINDOW2_7(PBuf).Options or $0008; PRecWINDOW2_7(PBuf).Options := PRecWINDOW2_7(PBuf).Options or $0100; end; if soShowZeros in Options then PRecWINDOW2_7(PBuf).Options := PRecWINDOW2_7(PBuf).Options or $0010; // if FCurrSheet = 0 then PRecWINDOW2_7(PBuf).Options := PRecWINDOW2_7(PBuf).Options or $0200; if FCurrSheet = FXLS.Workbook.SelectedTab then PRecWINDOW2_7(PBuf).Options := PRecWINDOW2_7(PBuf).Options or $0200; if FXLS.Version < xvExcel97 then begin PRecWINDOW2_7(PBuf).TopRow := 0; PRecWINDOW2_7(PBuf).LeftCol := 0; PRecWINDOW2_7(PBuf).HeaderColorIndex := 0; WriteBuf(BIFFRECID_WINDOW2,SizeOf(TRecWINDOW2_7)); end else begin PRecWINDOW2_8(PBuf).TopRow := 0; PRecWINDOW2_8(PBuf).LeftCol := 0; PRecWINDOW2_8(PBuf).HeaderColorIndex := $40; PRecWINDOW2_8(PBuf).ZoomPreview := ZoomPreview; PRecWINDOW2_8(PBuf).Zoom := 100; WriteBuf(BIFFRECID_WINDOW2,SizeOf(TRecWINDOW2_8)); end; end; end; procedure TXLSWriteII.WREC_SCL; begin if (FXLS.Sheets[FCurrSheet].Zoom > 0) and (FXLS.Sheets[FCurrSheet].Zoom <> 100) then begin PRecSCL(PBuf).Numerator := FXLS.Sheets[FCurrSheet].Zoom; PRecSCL(PBuf).Denominator := 100; WriteBuf(BIFFRECID_SCL,SizeOf(TRecSCL)); end; end; procedure TXLSWriteII.WREC_PANE; procedure WriteSelection(P,C,R: integer); begin PRecSELECTION(PBuf).Pane := P; PRecSELECTION(PBuf).ActiveRow := R; PRecSELECTION(PBuf).ActiveCol := C; PRecSELECTION(PBuf).ActiveRef := 0; PRecSELECTION(PBuf).Refs := 1; PRecSELECTION(PBuf).Row1 := R; PRecSELECTION(PBuf).Row2 := R; PRecSELECTION(PBuf).Col1 := C; PRecSELECTION(PBuf).Col2 := C; WriteBuf(BIFFRECID_SELECTION,SizeOf(TRecSELECTION)); end; begin if FXLS.Sheets[FCurrSheet].Pane.PaneType > ptNone then begin if (FXLS.Sheets[FCurrSheet].Pane.SplitColX <= 0) and (FXLS.Sheets[FCurrSheet].Pane.SplitRowY <= 0) then Exit; if (FXLS.Sheets[FCurrSheet].Pane.SplitColX > 0) and (FXLS.Sheets[FCurrSheet].Pane.SplitRowY > 0) then PRecPANE(PBuf).PaneNumber := 0 else if (FXLS.Sheets[FCurrSheet].Pane.SplitColX > 0) and (FXLS.Sheets[FCurrSheet].Pane.SplitRowY = 0) then PRecPANE(PBuf).PaneNumber := 1 else PRecPANE(PBuf).PaneNumber := 2; PRecPANE(PBuf).X := FXLS.Sheets[FCurrSheet].Pane.SplitColX; PRecPANE(PBuf).Y := FXLS.Sheets[FCurrSheet].Pane.SplitRowY; PRecPANE(PBuf).LeftCol := FXLS.Sheets[FCurrSheet].Pane.LeftCol; PRecPANE(PBuf).TopRow := FXLS.Sheets[FCurrSheet].Pane.TopRow; WriteBuf(BIFFRECID_PANE,SizeOf(TRecPANE)); if (FXLS.Sheets[FCurrSheet].Pane.SplitColX > 0) and (FXLS.Sheets[FCurrSheet].Pane.SplitRowY > 0) then begin WriteSelection(3,0,0); WriteSelection(2,0,FXLS.Sheets[FCurrSheet].Pane.TopRow); WriteSelection(1,FXLS.Sheets[FCurrSheet].Pane.LeftCol,0); WriteSelection(0,FXLS.Sheets[FCurrSheet].Pane.LeftCol,FXLS.Sheets[FCurrSheet].Pane.TopRow); end else if (FXLS.Sheets[FCurrSheet].Pane.SplitColX > 0) and (FXLS.Sheets[FCurrSheet].Pane.SplitRowY = 0) then begin WriteSelection(3,0,FXLS.Sheets[FCurrSheet].Pane.TopRow); WriteSelection(1,FXLS.Sheets[FCurrSheet].Pane.LeftCol,0); end else begin WriteSelection(3,0,0); WriteSelection(2,0,FXLS.Sheets[FCurrSheet].Pane.TopRow); end; end; { if (FXLS.Sheets[FCurrSheet].FixedRows > 0) or (FXLS.Sheets[FCurrSheet].FixedCols > 0) then begin PRecPANE(PBuf).X := FXLS.Sheets[FCurrSheet].FixedCols * 1024; PRecPANE(PBuf).Y := FXLS.Sheets[FCurrSheet].FixedRows * 255; PRecPANE(PBuf).TopRow := FXLS.Sheets[FCurrSheet].FixedRows; PRecPANE(PBuf).LeftCol := FXLS.Sheets[FCurrSheet].FixedCols; PRecPANE(PBuf).PaneNumber := 3; WriteBuf(BIFFRECID_PANE,SizeOf(TRecPANE)); end; } end; procedure TXLSWriteII.WREC_HLINK; begin if FXLS.Version < xvExcel97 then Exit; FXLS.Sheets[FCurrSheet].StreamWriteHyperlinks(FXLS.Version,FXLSStream); end; procedure TXLSWriteII.WREC_MERGECELLS; begin if FXLS.Version < xvExcel97 then Exit; FXLS.Sheets[FCurrSheet].StreamWriteMergedCells(FXLS.Version,FXLSStream); end; end.
program sapper; uses sounds,graphabc,events; const n=16; {9*9 - 10;} bq=40; {16*16 - 40} size=25; var i,j,d,c:integer; f:array[-1..n+1,-1..n+1]of record s:-1..8; o,c:boolean; end; procedure checkwin; var b:boolean; begin b:=true; for i:=1 to n do for j:=1 to n do begin if (f[i,j].s>-1)and not f[i,j].o then b:=false; if (f[i,j].s=-1)and not f[i,j].c then b:=false; end; if b then begin setfontcolor(clred); textout((size*n) div 4,(size*n) div 3,'You have won!'); d:=loadsound('Xylophone.wav'); playsound(d); sleep(1000); destroysound(d); halt; end; end; procedure ocec; {opening connected empty cells} var k:integer; begin for k:=1 to n*n div 2 do for i:=1 to n do for j:=1 to n do if (f[i,j].s>-1)AND ( ( (f[i+1,j].s=0)and f[i+1,j].o )or ( (f[i-1,j].s=0)and f[i-1,j].o )or ( (f[i,j+1].s=0)and f[i,j+1].o )or ( (f[i,j-1].s=0)and f[i,j-1].o )or ( (f[i+1,j+1].s=0)and f[i+1,j+1].o )or ( (f[i+1,j-1].s=0)and f[i+1,j-1].o )or ( (f[i-1,j+1].s=0)and f[i-1,j+1].o )or ( (f[i-1,j-1].s=0)and f[i-1,j-1].o ) ) then begin f[i,j].o:=true; floodfill(j*size-1,i*size-1,clwhite); if f[i,j].s>0 then textout(j*size-2*size div 3,(i-1)*size+1,inttostr(f[i,j].s)); if f[i,j].c then with f[i,j] do begin setpencolor(clwhite); c:=false; line((j-1)*size+2,(i-1)*size+2,j*size-2,i*size-2); line((j-1)*size+2,i*size-2,j*size-2,(i-1)*size+2); end; end; end; procedure press(x,y,z:integer); begin for i:=1 to n do for j:=1 to n do if ((j-1)*size<x)and(x<j*size) and ((i-1)*size<y)and(y<i*size) then with f[i,j] do begin if z=1 then begin o:=true; floodfill(j*size-1,i*size-1,clwhite); d:=loadsound('letter.wav'); playsound(d); if s=-1 then {bomb} begin sleep(100); destroysound(d); d:=loadsound('expl.wav'); playsound(d); floodfill(j*size-1,i*size-1,clred); for i:=1 to n do for j:=1 to n do if f[i,j].s=-1 then floodfill(j*size-1,i*size-1,cldkgray); sleep(1500); destroysound(d); halt; end else begin if s>0 then textout(j*size-2*size div 3,(i-1)*size+1,inttostr(s)); {number} if s=0 then ocec; {empty} sleep(100); destroysound(d); end; end; if (z=2)and o then begin d:=loadsound('Neg.wav'); playsound(d); sleep(500); destroysound(d); end; if (z=2)and not o then {cross} begin if c then begin setpencolor(clskyblue); {-} c:=false; end else begin setpencolor(clred); {+} c:=true; end; line((j-1)*size+2,(i-1)*size+2,j*size-2,i*size-2); line((j-1)*size+2,i*size-2,j*size-2,(i-1)*size+2); end; break; end; checkwin; end; begin while c<>bq do {putting bombs} for i:=1 to n do for j:=1 to n do if (random(100)=0)and(c<bq) then begin f[i,j].s:=-1; c:=c+1; end; for i:=1 to n do {putting numbers} for j:=1 to n do if f[i,j].s<>-1 then begin c:=0; if f[i+1,j].s=-1 then c:=c+1; if f[i-1,j].s=-1 then c:=c+1; if f[i,j+1].s=-1 then c:=c+1; if f[i,j-1].s=-1 then c:=c+1; if f[i+1,j+1].s=-1 then c:=c+1; if f[i+1,j-1].s=-1 then c:=c+1; if f[i-1,j+1].s=-1 then c:=c+1; if f[i-1,j-1].s=-1 then c:=c+1; f[i,j].s:=c; end; setwindowsize(size*n,size*n); {field} setwindowtitle('Saper'); setfontsize(size-10); clearwindow(clskyblue); for i:=1 to n do begin line(0,i*size,size*n,i*size); line(i*size,0,i*size,n*size); end; setpenwidth(2); onmousedown:=press; end.
unit MainForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ToolWin, ComCtrls, StdCtrls, Buttons, ExtCtrls, CDKolcsonadasa, CDVisszakapasa, ShellAPI, ActnList, Menus, IniFiles, Beallitasok, Kereses, About, Grids, ImgList, CDNyDataFile, Db; type TfrmMainForm = class(TForm) ToolBar1: TToolBar; cmdKolcsonkerok: TSpeedButton; cmdCDk: TSpeedButton; cmdKolcsonadas: TSpeedButton; cmdKilepes: TSpeedButton; Bevel1: TBevel; cmdVisszakapas: TSpeedButton; ActionList1: TActionList; Bevel3: TBevel; cmdKereses: TSpeedButton; cmdBeallitasok: TSpeedButton; KolcsonkerokreKattintas: TAction; CDkreKattintas: TAction; CDKolcsonadasaraKattintas: TAction; CDVisszakapaasraKattintas: TAction; KeresesreKattintas: TAction; BeallitasokraKattintas: TAction; KilepesreKattintas: TAction; SegitsegKell: TAction; cmdAbout: TSpeedButton; PopupMenu1: TPopupMenu; mnuNevjegy: TMenuItem; N1: TMenuItem; mnuTartalom: TMenuItem; mnuTargymutato: TMenuItem; SaveDialog1: TSaveDialog; DataSource1: TDataSource; StringGrid1: TStringGrid; NevjegyreKattintas: TAction; cmdAblakElrendezes: TSpeedButton; PopupMenu2: TPopupMenu; mnuCascade: TMenuItem; mnuHTile: TMenuItem; mnuArrangeicons: TMenuItem; mnuVTile: TMenuItem; ImageList1: TImageList; ADOTable1: TCDNyDataFile_CDk; procedure cmdKolcsonkerokClick(Sender: TObject); procedure cmdCDkClick(Sender: TObject); procedure cmdKilepesClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure cmdKolcsonadasClick(Sender: TObject); procedure cmdVisszakapasClick(Sender: TObject); procedure KolcsonkerokreKattintasExecute(Sender: TObject); procedure CDkreKattintasExecute(Sender: TObject); procedure CDKolcsonadasaraKattintasExecute(Sender: TObject); procedure CDVisszakapasaraKattintasExecute(Sender: TObject); procedure KilepesreKattintasExecute(Sender: TObject); procedure SegitsegKellExecute(Sender: TObject); procedure cmdAboutClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); function NalNel(Kinel: string): string; procedure cmdBeallitasokClick(Sender: TObject); procedure cmdKeresesClick(Sender: TObject); procedure KeresesreKattintasExecute(Sender: TObject); procedure BeallitasokraKattintasExecute(Sender: TObject); procedure mnuNevjegyClick(Sender: TObject); procedure mnuTartalomClick(Sender: TObject); procedure mnuTargymutatoClick(Sender: TObject); procedure NevjegyreKattintasExecute(Sender: TObject); procedure cmdAblakElrendezesClick(Sender: TObject); procedure mnuCascadeClick(Sender: TObject); procedure mnuArrangeiconsClick(Sender: TObject); procedure mnuVTileClick(Sender: TObject); procedure mnuHTileClick(Sender: TObject); procedure RemoveWindow(Handle: HWND; Obj: TForm); private OldWinProc, NewWinProc: Pointer; OutCanvas: TCanvas; Hatterkep: TBitmap; fHatterSzin: TColor; fMegvaltozott: boolean; fGombok: TColor; fFulek: TColor; fBetuk: TColor; procedure NewWinProcedure(var Msg: TMessage); procedure RemoveWindow_Shrink(Handle: HWND; Obj: TForm); procedure RemoveWindow_Clock(Handle: HWND; Obj: TForm; Lepes: integer); procedure RemoveWindow_UpLeft(Handle: HWND; Obj: TForm); public property proHatterkep: TBitmap read Hatterkep write Hatterkep; property HatterSzin: TColor read fHatterSzin write fHatterSzin default 14209224; property Megvaltozott: boolean read fMegvaltozott write fMegvaltozott default false; property Gombok: TColor read fGombok write fGombok default 14209224; property Fulek: TColor read fFulek write fFulek default 14209224; property Betuk: TColor read fBetuk write fBetuk default 0; end; var frmMainForm: TfrmMainForm; ConfigFile: TIniFile; implementation uses Kolcsonkerok, CDk; {$R *.DFM} {$R kepek.res} procedure TfrmMainForm.RemoveWindow_Shrink(Handle: HWND; Obj:tform); var lepeskoz : integer; varakozas : integer; oldalarany : real; y_up : integer; y_down : integer; x_left : integer; x_right : integer; rgn : HRGN; rgnpoints : array[1..22] of tpoint; rgnpcount : integer; begin rgnpcount:=4; y_up :=0; y_down :=obj.height; oldalarany :=obj.width/obj.height; lepeskoz :=10; varakozas :=10; randomize; //ELTUNTETES while (y_up<y_down) do begin inc(y_up, lepeskoz); dec(y_down, lepeskoz); x_left := round(y_up * oldalarany); x_right := round(y_down * oldalarany); while y_up>y_down+1 do begin dec(y_up); inc(y_down); end; rgnpoints[1].x:=x_right; rgnpoints[1].y:=y_down; rgnpoints[2].x:=x_left; rgnpoints[2].y:=y_down; rgnpoints[3].x:=x_left; rgnpoints[3].y:=y_up; rgnpoints[4].x:=x_right; rgnpoints[4].y:=y_up; Rgn := CreatePolygonRgn(RgnPoints, rgnpcount, ALTERNATE); SetWindowRgn(Handle, Rgn, True); sleep(varakozas); end; end; procedure TfrmMainForm.cmdKolcsonkerokClick(Sender: TObject); begin if not Assigned(frmKolcsonkerok) then frmKolcsonkerok := TfrmKolcsonkerok.Create(Application); frmKolcsonkerok.Show; end; procedure TfrmMainForm.cmdCDkClick(Sender: TObject); begin if not Assigned(frmCDk) then frmCDk := TfrmCDk.Create(Application); frmCDk.Show; end; procedure TfrmMainForm.cmdKilepesClick(Sender: TObject); begin frmMainForm.Close; end; procedure TfrmMainForm.FormCreate(Sender: TObject); var temp: string; tempdate: TDateTime; Status: integer; TurelmiNapokSzama, ForintPerNap: integer; Konyvtar: string; tKep: TBitmap; tCfg: TIniFile; i: integer; begin NewWinProc := MakeObjectInstance(NewWinProcedure); OldWinProc := Pointer(SetWindowLong(ClientHandle,gwl_WndProc,Cardinal(NewWinProc))); OutCanvas := TCanvas.Create; {------------------------------------------------------------------------------} ConfigFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'CDNyilvantarto.ini'); Konyvtar := ConfigFile.ReadString('Skin','Actual','[Hiba]'); if Konyvtar <> '[Hiba]' then begin Konyvtar := ExtractFilePath(ParamStr(0)) + 'skins\' + Konyvtar + '\'; tCfg := TIniFile.Create(Konyvtar + 'skin.ini'); if tCfg.ValueExists('Szinek','Hatter') then fHatterSzin := tCfg.ReadInteger('Szinek','Hatter',14209224) else fHatterSzin := 14209224; if tCfg.ValueExists('Szinek','Gombok') then fGombok := tCfg.ReadInteger('Szinek','Gombok',14209224) else fGombok := 14209224; if tCfg.ValueExists('Szinek','Fulek') then fFulek := tCfg.ReadInteger('Szinek','Fulek',14209224) else fFulek := 14209224; if tCfg.ValueExists('Szinek','Betuk') then fBetuk := tCfg.ReadInteger('Szinek','Betuk',0) else fBetuk := 0; frmMainForm.Color := fHatterSzin; tCfg.Free; tKep := TBitmap.Create; if FileExists(Konyvtar + '1.bmp') then begin tKep.LoadFromFile(Konyvtar + '1.bmp'); if (tKep.Width = 32)and(tKep.Height = 32) then cmdKolcsonkerok.Glyph.LoadFromFile(Konyvtar + '1.bmp'); end; if FileExists(Konyvtar + '2.bmp') then begin tKep.LoadFromFile(Konyvtar + '2.bmp'); if (tKep.Width = 32)and(tKep.Height = 32) then cmdCDk.Glyph.LoadFromFile(Konyvtar + '2.bmp'); end; if FileExists(Konyvtar + '3.bmp') then begin tKep.LoadFromFile(Konyvtar + '3.bmp'); if (tKep.Width = 32)and(tKep.Height = 32) then cmdKolcsonadas.Glyph.LoadFromFile(Konyvtar + '3.bmp'); end; if FileExists(Konyvtar + '4.bmp') then begin tKep.LoadFromFile(Konyvtar + '4.bmp'); if (tKep.Width = 32)and(tKep.Height = 32) then cmdVisszakapas.Glyph.LoadFromFile(Konyvtar + '4.bmp'); end; if FileExists(Konyvtar + '6.bmp') then begin tKep.LoadFromFile(Konyvtar + '6.bmp'); if (tKep.Width = 32)and(tKep.Height = 32) then cmdKereses.Glyph.LoadFromFile(Konyvtar + '6.bmp'); end; if FileExists(Konyvtar + '7.bmp') then begin tKep.LoadFromFile(Konyvtar + '7.bmp'); if (tKep.Width = 32)and(tKep.Height = 32) then cmdBeallitasok.Glyph.LoadFromFile(Konyvtar + '7.bmp'); end; if FileExists(Konyvtar + '8.bmp') then begin tKep.LoadFromFile(Konyvtar + '8.bmp'); if (tKep.Width = 32)and(tKep.Height = 32) then cmdAbout.Glyph.LoadFromFile(Konyvtar + '8.bmp'); end; if FileExists(Konyvtar + '9.bmp') then begin tKep.LoadFromFile(Konyvtar + '9.bmp'); if (tKep.Width = 32)and(tKep.Height = 32) then cmdKilepes.Glyph.LoadFromFile(Konyvtar + '9.bmp'); end; Hatterkep := TBitmap.Create; if FileExists(Konyvtar + 'bg.bmp') then Hatterkep.LoadFromFile(Konyvtar + 'bg.bmp') else Hatterkep.LoadFromResourceName(HInstance,'background'); tKep.Free; end else begin Hatterkep := TBitmap.Create; Hatterkep.LoadFromResourceName(HInstance,'background'); end; ConfigFile.Free; {------------------------------------------------------------------------------} ConfigFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'CDNyilvantarto.ini'); TurelmiNapokSzama := ConfigFile.ReadInteger('TurelmiIdo','Napok',30); ForintPerNap := ConfigFile.ReadInteger('TurelmiIdo','ForintPerNap',5); if ConfigFile.ReadBool('TurelmiIdo','IndulaskorEllenorzes',false) then begin ADOTable1.OpenFile(ExtractFilePath(ParamStr(0)) + 'CDk.cdny'); for i := 1 to ADOTable1.Mennyiseg do begin if ADOTable1.GetIndex(i).KolcsonVan then begin TempDate := ADOTable1.GetIndex(i).Datum; TempDate := TempDate + TurelmiNapokSzama; if TempDate <= Now then begin temp := 'A ' + ADOTable1.GetIndex(i).CDNeve + ' nevű CD ' + IntToStr(TurelmiNapokSzama) + ' napnál tovább volt '; temp := temp + NalNel(ADOTable1.GetIndex(i).Kolcsonker) + '('; temp := temp + IntToStr(trunc(Now - TempDate)) + ' nappal = ' + IntToStr((trunc(Now-TempDate))*ForintPerNap) + ' Ft).'; Application.MessageBox(PChar(temp),'CD-Nyilvántartó',mb_Ok + mb_IconInformation); end; end; end; end; Status := ConfigFile.ReadInteger('frmMainForm','Status',0); if Status <> 0 then begin Top := ConfigFile.ReadInteger('frmMainForm','Top',Top); Left := ConfigFile.ReadInteger('frmMainForm','Left',Left); Width := ConfigFile.ReadInteger('frmMainForm','Width',Width); Height := ConfigFile.ReadInteger('frmMainForm','Height',Height); case status of 1: WindowState := wsNormal; 2: WindowState := wsMinimized; 3: WindowState := wsMaximized; end; end; ConfigFile.Free; end; procedure TfrmMainForm.NewWinProcedure(var Msg: TMessage); var BmpWidth, BmpHeight: integer; I, J: integer; begin Msg.Result := CallWindowProc(OldWinProc,ClientHandle,Msg.Msg,Msg.wParam,Msg.lParam); if Msg.Msg = wm_EraseBkgnd then begin BmpWidth := Hatterkep.Width; BmpHeight := Hatterkep.Height; if (BmpWidth <> 0)and(BmpHeight <> 0) then begin OutCanvas.Handle := Msg.wParam; for I := 0 to frmMainForm.ClientWidth div BmpWidth do for J := 0 to frmMainForm.ClientHeight div BmpHeight do OutCanvas.Draw(I * BmpWidth,J * BmpHeight,Hatterkep); end; end; if fMegvaltozott then begin frmMainForm.Color := fHatterSzin; frmAbout.Color := fHatterSzin; ToolBar1.Font.Color := fBetuk; ToolBar1.Canvas.Font.Color := fBetuk; cmdKolcsonkerok.Font.Color := fBetuk; cmdCDk.Font.Color := fBetuk; cmdKolcsonadas.Font.Color := fBetuk; cmdKilepes.Font.Color := fBetuk; cmdVisszakapas.Font.Color := fBetuk; cmdKereses.Font.Color := fBetuk; cmdBeallitasok.Font.Color := fBetuk; cmdAbout.Font.Color := fBetuk; StringGrid1.Font.Color := fBetuk; StringGrid1.Canvas.Font.Color := fBetuk; end; end; procedure TfrmMainForm.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button = mbRight) and (ssShift in Shift) then begin frmAbout.Show; frmAbout.ShowAboutText; end; end; procedure TfrmMainForm.cmdKolcsonadasClick(Sender: TObject); begin if not Assigned(frmCDKolcsonadasa) then frmCDKolcsonadasa := TfrmCDKolcsonadasa.Create(Application); frmCDKolcsonadasa.Show; end; procedure TfrmMainForm.cmdVisszakapasClick(Sender: TObject); begin if not Assigned(frmCDVisszakapasa) then frmCDVisszakapasa := TfrmCDVisszakapasa.Create(Application); frmCDVisszakapasa.Show; end; procedure TfrmMainForm.KolcsonkerokreKattintasExecute(Sender: TObject); begin cmdKolcsonkerokClick(Sender); end; procedure TfrmMainForm.CDkreKattintasExecute(Sender: TObject); begin cmdCDkClick(Sender); end; procedure TfrmMainForm.CDKolcsonadasaraKattintasExecute(Sender: TObject); begin cmdKolcsonadasClick(Sender); end; procedure TfrmMainForm.CDVisszakapasaraKattintasExecute(Sender: TObject); begin cmdVisszakapasClick(Sender); end; procedure TfrmMainForm.KilepesreKattintasExecute(Sender: TObject); begin cmdKilepesClick(Sender); end; procedure TfrmMainForm.SegitsegKellExecute(Sender: TObject); begin if not FileExists(ExtractFilePath(ParamStr(0)) + 'CDNyilvantarto.hlp') then begin Application.MessageBox('Nem találom a súgófilet!','Hiba',mb_Ok + mb_IconHand); Exit; end; ShellExecute(Handle,'open',PChar(ExtractFilePath(ParamStr(0)) + 'CDNyilvantarto.hlp'),'',PChar(ExtractFilePath(ParamStr(0))),sw_ShowNormal); end; procedure TfrmMainForm.cmdAboutClick(Sender: TObject); var Pt: TPoint; begin GetCursorPos(Pt); PopupMenu1.Popup(Pt.x,Pt.y); end; procedure TfrmMainForm.FormClose(Sender: TObject; var Action: TCloseAction); var Status: integer; begin ConfigFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'CDNyilvantarto.ini'); Status := 0; case WindowState of wsNormal: begin ConfigFile.WriteInteger('frmMainForm','Top',Top); ConfigFile.WriteInteger('frmMainForm','Left',Left); ConfigFile.WriteInteger('frmMainForm','Width',Width); ConfigFile.WriteInteger('frmMainForm','Height',Height); Status := 1; end; wsMinimized: Status := 2; wsMaximized: Status := 3; end; // if not Active then Status := 2; if not Application.Active then Status := 2; ConfigFile.WriteInteger('frmMainForm','Status',Status); ConfigFile.Free; RemoveWindow((Self as TForm).Handle,Self as TForm); end; function TfrmMainForm.NalNel(Kinel: string): string; var temp: string; i: integer; begin temp := 'nél'; for i := 1 to Length(Kinel) do if Kinel[i] in ['a','A','á','Á','o','O','ó','Ó','u','U'] then temp := 'nál'; Result := Kinel + temp; end; procedure TfrmMainForm.cmdBeallitasokClick(Sender: TObject); begin if not Assigned(frmBeallitasok) then frmBeallitasok := TfrmBeallitasok.Create(Application); frmBeallitasok.Show; end; procedure TfrmMainForm.cmdKeresesClick(Sender: TObject); begin if not Assigned(frmKereses) then frmKereses := TfrmKereses.Create(Application); frmKereses.Show; end; procedure TfrmMainForm.KeresesreKattintasExecute(Sender: TObject); begin cmdKeresesClick(Sender); end; procedure TfrmMainForm.BeallitasokraKattintasExecute(Sender: TObject); begin cmdBeallitasokClick(Sender); end; procedure TfrmMainForm.mnuNevjegyClick(Sender: TObject); begin FormMouseDown(Sender,mbRight,[ssShift],0,0); end; procedure TfrmMainForm.mnuTartalomClick(Sender: TObject); begin Application.HelpCommand(Help_Finder,0); end; procedure TfrmMainForm.mnuTargymutatoClick(Sender: TObject); begin Application.HelpCommand(Help_PartialKey,Longint(StrNew(''))); end; procedure TfrmMainForm.NevjegyreKattintasExecute(Sender: TObject); begin FormMouseDown(Sender,mbRight,[ssShift],0,0); end; procedure TfrmMainForm.cmdAblakElrendezesClick(Sender: TObject); var P: TPoint; begin GetCursorPos(P); PopupMenu2.Popup(P.x,P.y); end; procedure TfrmMainForm.mnuCascadeClick(Sender: TObject); begin frmMainForm.Cascade; end; procedure TfrmMainForm.mnuArrangeiconsClick(Sender: TObject); begin frmMainForm.ArrangeIcons; end; procedure TfrmMainForm.mnuVTileClick(Sender: TObject); begin frmMainForm.TileMode := tbVertical; frmMainForm.Tile; end; procedure TfrmMainForm.mnuHTileClick(Sender: TObject); begin frmMainForm.TileMode := tbHorizontal; frmMainForm.Tile; end; procedure TfrmMainForm.RemoveWindow(Handle: HWND; Obj: TForm); var Cfg: TIniFile; i: integer; begin Cfg := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'CDNyilvantarto.ini'); if Cfg.ReadBool('Altalanos','KilepesiEffekt',true) then begin Randomize; i := trunc(Random(3) + 1); case i of 1 : RemoveWindow_Shrink(Handle,Obj); 2 : RemoveWindow_Clock(Handle,Obj,Cfg.ReadInteger('Altalanos','Lepes',100)); 3 : RemoveWindow_UpLeft(Handle,Obj); else Application.MessageBox('Belső hiba!','CD-Nyilvántartó',mb_Ok + mb_IconAsterisk); end; end; Cfg.Free; end; procedure TfrmMainForm.RemoveWindow_Clock(Handle: HWND; Obj: TForm; Lepes: integer); var xm, ym: integer; ps: array[0..6] of TPoint; fh: THandle; x, y: single; LepesX, LepesY: single; Fill: integer; begin xm := Obj.Width div 2; ym := Obj.Height div 2; LepesX := Obj.Width / Lepes; LepesY := Obj.Height / Lepes; Fill := alternate; x := xm; while x <= Obj.Width do begin //1 ps[0] := point(0,0); ps[1] := point(xm,0); ps[2] := point(xm,ym); ps[3] := point(trunc(x),0); ps[4] := point(Obj.width,0); ps[5] := point(Obj.width,Obj.height); ps[6] := point(0,Obj.height); fh := CreatePolygonRgn(ps,7,Fill); SetWindowRgn(Handle,fh,true); // Sleep(1); x := x + LepesX; end; y := 0; while y <= height do begin //2 ps[0] := point(0,0); ps[1] := point(xm,0); ps[2] := point(xm,ym); ps[3] := point(Obj.width,trunc(y)); ps[4] := point(Obj.width,Obj.height); ps[5] := point(0,Obj.height); fh := CreatePolygonRgn(ps,6,Fill); SetWindowRgn(Handle,fh,true); // Sleep(1); y := y + LepesY; end; x := width; while x >= 0 do begin //3 ps[0] := point(0,0); ps[1] := point(xm,0); ps[2] := point(xm,ym); ps[3] := point(trunc(x),Obj.height); ps[4] := point(0,Obj.height); fh := CreatePolygonRgn(ps,5,Fill); SetWindowRgn(Handle,fh,true); // Sleep(1); x := x - LepesX; end; y := height; while y >= 0 do begin //4 ps[0] := point(0,0); ps[1] := point(xm,0); ps[2] := point(xm,ym); ps[3] := point(0,trunc(y)); fh := CreatePolygonRgn(ps,4,Fill); SetWindowRgn(Handle,fh,true); // Sleep(1); y := y - LepesY; end; x := 0; while x <= xm do begin //5 ps[0] := point(trunc(x),0); ps[1] := point(xm,0); ps[2] := point(xm,ym); fh := CreatePolygonRgn(ps,3,Fill); SetWindowRgn(Handle,fh,true); // Sleep(1); x := x + LepesX; end; end; procedure TfrmMainForm.RemoveWindow_UpLeft(Handle: HWND; Obj: TForm); var i: integer; begin for i := Obj.ClientHeight downto 0 do Obj.ClientHeight := i; for i := Obj.ClientWidth downto 0 do Obj.ClientWidth := i; end; end.
unit Repositorio.Cliente; interface uses System.SysUtils, DB, Classes, Repositorio.GenericRepository, Domain.Entity.Cliente, Repositorio.Base, Repositorio.Interfaces.Cliente,System.Generics.Collections,EF.QueryAble.Linq, Repositorio.Interfaces.base, Context, EF.Core.Types, EF.Engine.DbSet; type TRepositoryCliente<T:TCliente> = class(TRepositoryBase<T> ,IRepositoryCliente<T>) private E: T; _RepositoryCliente:IRepository<T>; public Constructor Create(dbContext:TContext<T>);override; function LoadDataSetPorNome(value: string):TDataSet; function LoadDataSetPorID(value: string):TDataSet; end; TRepositoryCliente = class sealed (TRepositoryCliente<TCliente>) end; implementation { TRepositoryCliente } constructor TRepositoryCliente<T>.Create(dbContext:TContext<T>); begin _RepositoryCliente := TRepository<T>.create(dbContext); _RepositoryBase := _RepositoryCliente As IRepository<T>; inherited; E := _RepositoryCliente.Entity; end; function TRepositoryCliente<T>.LoadDataSetPorID(value: string): TDataSet; begin if value <> '' then result := dbContext.ToDataSet( From( E ).Where( E.ID = strtoint(value) ).Select ) else result := dbContext.ToDataSet( From( E ).Select ); end; function TRepositoryCliente<T>.LoadDataSetPorNome(value: string): TDataSet; begin if value <> '' then result := dbContext.ToDataSet( From( E ).Where( E.Nome.Like( value ) ).Select ) else result := dbContext.ToDataSet( From( E ).Select ); end; initialization RegisterClass(TRepositoryCliente); finalization UnRegisterClass(TRepositoryCliente); end.
{*******************************************************} { } { XML File IO Manager } { XML文件的IO操作 } { } { Author: 穆洪星 } { Data: 2007-03-23 } { Build: 2007-03-23 } { } {*******************************************************} unit ZhXmlParserImpl; interface uses SysUtils, Classes, Variants, Forms, XMLDoc, XMLIntf, ZhConstProtocol; type TXMLParser = class private FExeDir: string; //可执行文件路径 FUpdateDir: string; //接收到的待更新文件的保存路径 FCurrentDir: string; //当前操作的路径 FFileName: string; FErrorInfo: string; function InitXMLDocument(var AXMLDocument: TXMLDocument): Boolean; function CreateXMLDocument(var AXMLDocument: TXMLDocument): Boolean; function GetRoot(var AXMLDocument: TXMLDocument): IXMLNode; procedure NoError; public constructor Create; destructor Destroy; override; { 公共函数 } class function GetExeDir: string; class function ConvertVariantToInt(const AVariant: OleVariant): Integer; class function ConvertVariantToStr(const AVariant: OleVariant): string; class function ConvertVariantToBool(const AVariant: OleVariant): Boolean; class function SetDir(const ADir: string): string; { Update List } function GetBatchNo: string; function SetBatchNo(const ABatchNo: string): Boolean; overload; function SetBatchNo(const ABatchNo: TDateTime): Boolean; overload; function GetUpdateList(var AList: TList): Boolean; function SetUpdateList(const AList: TList): Boolean; { Client Config } function GetClientConfig: TClientConfig; function SetClientConfig(const AClientConfig: TClientConfig): Boolean; { Client Running Information } function GetClientRunningInfo: TClientRunningInfo; function SetClientRunningInfo(const AClientRunningInfo: TClientRunningInfo): Boolean; { Client Backup File Information } procedure GetClientBackupInfoArray(var AClientBackupInfoArray: TClientBackupInfoArray); function GetClientBackupInfo(const AFileName: string): TClientBackupInfo; function InsertClientBackupInfo(const AClientBackupInfo: TClientBackupInfo): Boolean; function DeleteClientBackupInfo(const AFileName: string): Boolean; { 公共属性 } property ExeDir: string read FExeDir; property UpdateDir: string read FUpdateDir; property CurrentDir: string read FCurrentDir write FCurrentDir; property FileName: string read FFileName write FFileName; property ErrorInfo: string read FErrorInfo; end; const UPDATELIST_ROOT = 'UpdateList'; UPDATELIST_BATCHNO = 'BatchNo'; UPDATELIST_FILEINFO = 'FileInfo'; UPDATELIST_FILEINFO_INDEX = 'Index'; UPDATELIST_FILEINFO_FILENAME = 'FileName'; UPDATELIST_FILEINFO_FILEPATH = 'FilePath'; UPDATELIST_FILEINFO_FILELENGTH = 'FileLength'; CLIENTCONFIG_ROOT = 'ClientConfig'; CLIENTCONFIG_SERVERIP = 'ServerIP'; CLIENTCONFIG_SERVERPORT = 'ServerPort'; CLIENTRUNNING_ROOT = 'ClientRunning'; CLIENTRUNNING_TRANSPORT = 'Transport'; CLIENTRUNNING_FILEINDEX = 'FileIndex'; CLIENTRUNNING_PACKAGEINDEX = 'PackageIndex'; CLIENTBACKUP_ROOT = 'ClientBackupInfo'; CLIENTBACKUP_BACKUPINFO = 'FileInfo'; CLIENTBACKUP_BATCH = 'Batch'; CLIENTBACKUP_FILENAME = 'FileName'; {$I 'Language.inc'} implementation { TXMLParser } { 转换Variant类型 } { 2007-03-23 by muhx } class function TXMLParser.ConvertVariantToBool(const AVariant: OleVariant): Boolean; begin try if VarIsNull(AVariant) then Result := False else Result := AVariant; except Result := False; end; end; { 转换Variant类型 } { 2007-03-23 by muhx } class function TXMLParser.ConvertVariantToInt(const AVariant: OleVariant): Integer; begin try if VarIsNull(AVariant) then Result := 0 else Result := AVariant; except Result := 0; end; end; { 转换Variant类型 } { 2007-03-23 by muhx } class function TXMLParser.ConvertVariantToStr(const AVariant: OleVariant): string; begin try if VarIsNull(AVariant) then Result := '' else Result := AVariant; except Result := ''; end; end; { 返回当前可执行文件所在的路径, 以'\'结束 } { 2007-03-23 by muhx } class function TXMLParser.GetExeDir: string; begin try Result := ExtractFileDir(Application.ExeName); Result := Trim(Result); Result := IncludeTrailingPathDelimiter(Result); except Result := ''; end; end; { 设置查询路径 } { 2007-03-22 by muhx } class function TXMLParser.SetDir(const ADir: string): string; begin Result := ''; if not DirectoryExists(ADir) then if not ForceDirectories(ADir) then raise Exception.Create('Create Error'); Result := ADir; end; { 创建 } { 2007-03-23 by muhx } constructor TXMLParser.Create; begin inherited; try FExeDir := GetExeDir; FUpdateDir := SetDir(GetExeDir + FILEPATH_UPDATE); FCurrentDir := FUpdateDir; FFileName := FILENAME_UPDATELIST; NoError; except on E: Exception do FErrorInfo := E.Message; end; end; { 释放对象 } { 2007-03-23 by muhx } destructor TXMLParser.Destroy; begin inherited Destroy; end; { 创建XMLDocument控件并清空XML语句 } { 2007-03-23 by muhx } function TXMLParser.CreateXMLDocument(var AXMLDocument: TXMLDocument): Boolean; begin Result := False; if Assigned(AXMLDocument) then begin FErrorInfo := LXMLDocumentExist; Exit; end; AXMLDocument := TXMLDocument.Create(Application); try with AXMLDocument do begin Options := Options + [doNodeAutoIndent]; Active := False; XML.Clear; Active := True; Result := Active; if Result then NoError; end; except on E: Exception do FErrorInfo := E.Message; end; end; { 初始化XMLDocument控件 } { 2007-03-23 by muhx } function TXMLParser.InitXMLDocument(var AXMLDocument: TXMLDocument): Boolean; begin Result := False; if not Assigned(AXMLDocument) then Result := CreateXMLDocument(AXMLDocument); try with AXMLDocument do begin Active := False; Options := Options + [doNodeAutoIndent]; XML.Clear; Active := True; Version := '1.0'; Encoding := 'GB2312'; StandAlone := 'no'; Result := Active; if Result then NoError; end; except on E: Exception do FErrorInfo := E.Message; end; end; { 正常状态,清空错误代码 } { 2007-03-22 by muhx } procedure TXMLParser.NoError; begin FErrorInfo := ''; end; { 得到XML文件中的根节点 } { 2007-03-23 by muhx } function TXMLParser.GetRoot(var AXMLDocument: TXMLDocument): IXMLNode; begin try AXMLDocument.Active := False; AXMLDocument.XML.Clear; AXMLDocument.LoadFromFile(IncludeTrailingPathDelimiter(FCurrentDir) + FFileName); Result := AXMLDocument.DocumentElement; NoError; except on E: Exception do begin FErrorInfo := E.Message; Result := nil; end; end; end; { UpdateList } { 从文件中得到批次号 } { 2007-03-22 by muhx } function TXMLParser.GetBatchNo: string; var TmpRoot: IXMLNode; TmpFileName: string; TmpXMLDocument: TXMLDocument; begin Result := ''; { 在调用这个函数之前使用者要预先确定 FCurrentDir 和 FFileName } TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; CreateXMLDocument(TmpXMLDocument); try try if not FileExists(TmpFileName) then SetBatchNo(''); TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; if not Assigned(TmpRoot.ChildNodes.FindNode(UPDATELIST_BATCHNO)) then begin SetBatchNo(''); TmpRoot := GetRoot(TmpXMLDocument); end; Result := ConvertVariantToStr(TmpRoot.ChildNodes.FindNode(UPDATELIST_BATCHNO).NodeValue); NoError; except on E: Exception do FErrorInfo := E.Message; end; finally TmpXMLDocument.Free; end; end; { 将批次号写入文件 } { 2007-03-22 by muhx } function TXMLParser.SetBatchNo(const ABatchNo: string): Boolean; var TmpFileName: string; TmpRoot, TmpBatchNo: IXMLNode; TmpXMLDocument: TXMLDocument; begin Result := False; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_UPDATE); FFileName := FILENAME_UPDATELIST; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; if not FileExists(TmpFileName) then begin if not InitXMLDocument(TmpXMLDocument) then Abort; TmpRoot := TmpXMLDocument.AddChild(UPDATELIST_ROOT); TmpBatchNo := TmpRoot.AddChild(UPDATELIST_BATCHNO); TmpBatchNo.NodeValue := ABatchNo; end else begin TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; if not Assigned(TmpRoot.ChildNodes.FindNode(UPDATELIST_BATCHNO)) then TmpRoot.AddChild(UPDATELIST_BATCHNO); TmpRoot.ChildNodes.FindNode(UPDATELIST_BATCHNO).NodeValue := ABatchNo; end; TmpXMLDocument.SaveToFile(TmpFileName); NoError; Result := True; except on E: Exception do begin FErrorInfo := E.Message; Exit; end; end; finally TmpXMLDocument.Free; end; end; { 将批次号写入文件 } { 2007-03-22 by muhx } function TXMLParser.SetBatchNo(const ABatchNo: TDateTime): Boolean; var TmpBatchNo: string; begin TmpBatchNo := FormatDateTime(BATCH_FORMAT, Now); Result := SetBatchNo(TmpBatchNo); end; { 从文件中得到文件列表 } { 2007-03-22 by muhx } function TXMLParser.GetUpdateList(var AList: TList): Boolean; var TmpFileName: string; TmpRoot, TmpFileInfo: IXMLNode; TmpPFileInfo: PFileInfo; I: Integer; TmpXMLDocument: TXMLDocument; begin Result := False; if not Assigned(AList) then begin FErrorInfo := LListNotCreate; Exit; end; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_UPDATE); FFileName := FILENAME_UPDATELIST; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; AList.Clear; if not FileExists(TmpFileName) then SetUpdateList(AList); TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; for I := 0 to TmpRoot.ChildNodes.Count - 1 do begin TmpFileInfo := TmpRoot.ChildNodes[I]; if TmpFileInfo.NodeName = UPDATELIST_FILEINFO then begin New(TmpPFileInfo); TmpPFileInfo^.fiIndex := ConvertVariantToInt(TmpFileInfo.ChildNodes.FindNode(UPDATELIST_FILEINFO_INDEX).NodeValue); TmpPFileInfo^.fiFileName := ConvertVariantToStr(TmpFileInfo.ChildNodes.FindNode(UPDATELIST_FILEINFO_FILENAME).NodeValue); TmpPFileInfo^.fiFilePath := ConvertVariantToStr(TmpFileInfo.ChildNodes.FindNode(UPDATELIST_FILEINFO_FILEPATH).NodeValue); TmpPFileInfo^.fiFileLength := ConvertVariantToStr(TmpFileInfo.ChildNodes.FindNode(UPDATELIST_FILEINFO_FILELENGTH).NodeValue); AList.Add(TmpPFileInfo); end; end; NoError; Result := True; except on E: Exception do FErrorInfo := E.Message; end; finally TmpXMLDocument.Free; end; end; { 将更新列表写入XML文件 } { 2007-03-22 by muhx } function TXMLParser.SetUpdateList(const AList: TList): Boolean; var TmpFileName: string; TmpRoot, TmpFileInfo, TmpNode: IXMLNode; TmpPFileInfo: PFileInfo; I: Integer; TmpXMLDocument: TXMLDocument; begin Result := False; if not Assigned(AList) then begin FErrorInfo := LListNotCreate; Exit; end; TmpXMLDocument := nil; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_UPDATE); FFileName := FILENAME_UPDATELIST; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; if not FileExists(TmpFileName) then begin if not InitXMLDocument(TmpXMLDocument) then Abort; TmpRoot := TmpXMLDocument.AddChild(UPDATELIST_ROOT); end else TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; for I := TmpRoot.ChildNodes.Count - 1 downto 0 do if TmpRoot.ChildNodes[I].NodeName = UPDATELIST_FILEINFO then TmpRoot.ChildNodes.Delete(I); for I := 0 to AList.Count - 1 do begin TmpPFileInfo := PFileInfo(AList.Items[I]); TmpFileInfo := TmpRoot.AddChild(UPDATELIST_FILEINFO); TmpNode := TmpFileInfo.AddChild(UPDATELIST_FILEINFO_INDEX); TmpNode.NodeValue := TmpPFileInfo^.fiIndex; TmpNode := TmpFileInfo.AddChild(UPDATELIST_FILEINFO_FILENAME); TmpNode.NodeValue := TmpPFileInfo^.fiFileName; TmpNode := TmpFileInfo.AddChild(UPDATELIST_FILEINFO_FILEPATH); TmpNode.NodeValue := TmpPFileInfo^.fiFilePath; TmpNode := TmpFileInfo.AddChild(UPDATELIST_FILEINFO_FILELENGTH); TmpNode.NodeValue := TmpPFileInfo^.fiFileLength; end; TmpXMLDocument.SaveToFile(TmpFileName); NoError; Result := True; except on E: Exception do begin FErrorInfo := E.Message; Exit; end; end; finally TmpXMLDocument.Free; end; end; { Client Config } { 获取客户端配置 } { 2007-03-29 by muhx } function TXMLParser.GetClientConfig: TClientConfig; var TmpFileName: string; TmpRoot: IXMLNode; TmpXMLDocument: TXMLDocument; begin FillChar(Result, SizeOf(Result), 0); Result.ccServerIP := '127.0.0.1'; Result.ccServerPort := 5150; TmpXMLDocument := nil; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_CONFIG); FFileName := FILENAME_CLIENTCONFIG; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; if not FileExists(TmpFileName) then SetClientConfig(Result); TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; with Result do begin ccServerIP := ConvertVariantToStr(TmpRoot.ChildNodes.FindNode(CLIENTCONFIG_SERVERIP).NodeValue); ccServerPort := ConvertVariantToInt(TmpRoot.ChildNodes.FindNode(CLIENTCONFIG_SERVERPORT).NodeValue); end; NoError; except on E: Exception do FErrorInfo := E.Message; end; finally TmpXMLDocument.Free; end; end; { 设置客户端配置 } { 2007-03-29 by muhx } function TXMLParser.SetClientConfig(const AClientConfig: TClientConfig): Boolean; var TmpFileName: string; TmpRoot, TmpNode: IXMLNode; TmpXMLDocument: TXMLDocument; begin Result := False; TmpXMLDocument := nil; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_CONFIG); FFileName := FILENAME_CLIENTCONFIG; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; if not FileExists(TmpFileName) then begin if not InitXMLDocument(TmpXMLDocument) then Abort; TmpRoot := TmpXMLDocument.AddChild(CLIENTCONFIG_ROOT); TmpNode := TmpRoot.AddChild(CLIENTCONFIG_SERVERIP); TmpNode.NodeValue := AClientConfig.ccServerIP; TmpNode := TmpRoot.AddChild(CLIENTCONFIG_SERVERPORT); TmpNode.NodeValue := AClientConfig.ccServerPort; end else begin TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; if not Assigned(TmpRoot.ChildNodes.FindNode(CLIENTCONFIG_SERVERIP)) then TmpRoot.AddChild(CLIENTCONFIG_SERVERIP); TmpRoot.ChildNodes.FindNode(CLIENTCONFIG_SERVERIP).NodeValue := AClientConfig.ccServerIP; if not Assigned(TmpRoot.ChildNodes.FindNode(CLIENTCONFIG_SERVERPORT)) then TmpRoot.AddChild(CLIENTCONFIG_SERVERPORT); TmpRoot.ChildNodes.FindNode(CLIENTCONFIG_SERVERPORT).NodeValue := AClientConfig.ccServerPort; end; TmpXMLDocument.SaveToFile(TmpFileName); NoError; Result := True; except on E: Exception do begin FErrorInfo := E.Message; Exit; end; end; finally TmpXMLDocument.Free; end; end; { Client Running Information } { 读取客户端实时信息 } { 2007-03-30 by muhx } function TXMLParser.GetClientRunningInfo: TClientRunningInfo; var TmpFileName: string; TmpRoot: IXMLNode; TmpXMLDocument: TXMLDocument; begin FillChar(Result, SizeOf(Result), 0); TmpXMLDocument := nil; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_CONFIG); FFileName := FILENAME_RUNNING; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; if not FileExists(TmpFileName) then SetClientRunningInfo(Result); TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; with Result do begin criTransport := ConvertVariantToBool(TmpRoot.ChildNodes.FindNode(CLIENTRUNNING_TRANSPORT).NodeValue); criFileIndex := ConvertVariantToInt(TmpRoot.ChildNodes.FindNode(CLIENTRUNNING_FILEINDEX).NodeValue); criPackageIndex := ConvertVariantToInt(TmpRoot.ChildNodes.FindNode(CLIENTRUNNING_PACKAGEINDEX).NodeValue); end; NoError; except on E: Exception do FErrorInfo := E.Message; end; finally TmpXMLDocument.Free; end; end; { 设置客户端实时信息 } { 2007-03-30 by muhx } function TXMLParser.SetClientRunningInfo(const AClientRunningInfo: TClientRunningInfo): Boolean; var TmpFileName: string; TmpRoot, TmpNode: IXMLNode; TmpXMLDocument: TXMLDocument; begin Result := False; TmpXMLDocument := nil; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_CONFIG); FFileName := FILENAME_RUNNING; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; if not FileExists(TmpFileName) then begin if not InitXMLDocument(TmpXMLDocument) then Abort; TmpRoot := TmpXMLDocument.AddChild(CLIENTRUNNING_ROOT); { Transport } TmpNode := TmpRoot.AddChild(CLIENTRUNNING_TRANSPORT); TmpNode.NodeValue := AClientRunningInfo.criTransport; { File index } TmpNode := TmpRoot.AddChild(CLIENTRUNNING_FILEINDEX); TmpNode.NodeValue := AClientRunningInfo.criFileIndex; { Package index } TmpNode := TmpRoot.AddChild(CLIENTRUNNING_PACKAGEINDEX); TmpNode.NodeValue := AClientRunningInfo.criPackageIndex; end else begin TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; { Transport } if not Assigned(TmpRoot.ChildNodes.FindNode(CLIENTRUNNING_TRANSPORT)) then TmpRoot.AddChild(CLIENTRUNNING_TRANSPORT); TmpRoot.ChildNodes.FindNode(CLIENTRUNNING_TRANSPORT).NodeValue := AClientRunningInfo.criTransport; { File index } if not Assigned(TmpRoot.ChildNodes.FindNode(CLIENTRUNNING_FILEINDEX)) then TmpRoot.AddChild(CLIENTRUNNING_FILEINDEX); TmpRoot.ChildNodes.FindNode(CLIENTRUNNING_FILEINDEX).NodeValue := AClientRunningInfo.criFileIndex; { Package index } if not Assigned(TmpRoot.ChildNodes.FindNode(CLIENTRUNNING_PACKAGEINDEX)) then TmpRoot.AddChild(CLIENTRUNNING_PACKAGEINDEX); TmpRoot.ChildNodes.FindNode(CLIENTRUNNING_PACKAGEINDEX).NodeValue := AClientRunningInfo.criPackageIndex; end; TmpXMLDocument.SaveToFile(TmpFileName); NoError; Result := True; except on E: Exception do begin FErrorInfo := E.Message; Exit; end; end; finally TmpXMLDocument.Free; end; end; { Client Backup Information } { 取得所有备份文件记录 } { 2007-03-30 by muhx } procedure TXMLParser.GetClientBackupInfoArray(var AClientBackupInfoArray: TClientBackupInfoArray); var TmpFileName: string; TmpRoot, TmpNode: IXMLNode; TmpXMLDocument: TXMLDocument; TmpClientBackupInfo: TClientBackupInfo; TmpArrayLength, I: Integer; begin SetLength(AClientBackupInfoArray, 0); FillChar(TmpClientBackupInfo, SizeOf(TmpClientBackupInfo), 0); TmpXMLDocument := nil; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_BACKUP); FFileName := FILENAME_BACKUP; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; if not FileExists(TmpFileName) then InsertClientBackupInfo(TmpClientBackupInfo); TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; TmpArrayLength := TmpRoot.ChildNodes.Count; if TmpArrayLength <= 0 then Exit; SetLength(AClientBackupInfoArray, TmpArrayLength); for I := 0 to TmpArrayLength - 1 do begin TmpNode := TmpRoot.ChildNodes[I]; AClientBackupInfoArray[I].cbiBatch := ConvertVariantToStr(TmpNode.ChildNodes.FindNode(CLIENTBACKUP_BATCH).NodeValue); AClientBackupInfoArray[I].cbiFileName := ConvertVariantToStr(TmpNode.ChildNodes.FindNode(CLIENTBACKUP_FILENAME).NodeValue); end; NoError; except on E: Exception do FErrorInfo := E.Message; end; finally TmpXMLDocument.Free; end; end; { 取得符合条件的备份文件记录 } { 2007-03-30 by muhx } function TXMLParser.GetClientBackupInfo(const AFileName: string): TClientBackupInfo; var TmpFileName: string; TmpRoot: IXMLNode; TmpXMLDocument: TXMLDocument; I: Integer; begin FillChar(Result, SizeOf(Result), 0); TmpXMLDocument := nil; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_BACKUP); FFileName := FILENAME_BACKUP; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; if not FileExists(TmpFileName) then InsertClientBackupInfo(Result); TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; for I := 0 to TmpRoot.ChildNodes.Count - 1 do begin if AFileName = ConvertVariantToStr(TmpRoot.ChildNodes[I].ChildNodes.FindNode(CLIENTBACKUP_FILENAME).NodeValue) then begin Result.cbiFileName := AFileName; Result.cbiBatch := ConvertVariantToStr(TmpRoot.ChildNodes[I].ChildNodes.FindNode(CLIENTBACKUP_BATCH).NodeValue); end; end; NoError; except on E: Exception do FErrorInfo := E.Message; end; finally TmpXMLDocument.Free; end; end; { 删除符合条件的备份文件记录 } { 2007-03-30 by muhx } function TXMLParser.DeleteClientBackupInfo(const AFileName: string): Boolean; var TmpFileName: string; TmpRoot: IXMLNode; TmpXMLDocument: TXMLDocument; I: Integer; begin Result := False; FillChar(Result, SizeOf(Result), 0); TmpXMLDocument := nil; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_BACKUP); FFileName := FILENAME_BACKUP; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; if not FileExists(TmpFileName) then Exit; TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; for I := 0 to TmpRoot.ChildNodes.Count - 1 do begin if AFileName = ConvertVariantToStr(TmpRoot.ChildNodes[I].ChildNodes.FindNode(CLIENTBACKUP_FILENAME).NodeValue) then begin TmpRoot.ChildNodes.Delete(I); Break; end; end; { 保存文件 } TmpXMLDocument.SaveToFile(TmpFileName); NoError; Result := True; except on E: Exception do FErrorInfo := E.Message; end; finally TmpXMLDocument.Free; end; end; { 插入备份文件记录 } { 2007-03-30 by muhx } function TXMLParser.InsertClientBackupInfo( const AClientBackupInfo: TClientBackupInfo): Boolean; var TmpFileName: string; TmpRoot, TmpNode, TmpChildNode: IXMLNode; TmpXMLDocument: TXMLDocument; begin Result := False; TmpXMLDocument := nil; CreateXMLDocument(TmpXMLDocument); try try FCurrentDir := SetDir(GetExeDir + FILEPATH_BACKUP); FFileName := FILENAME_BACKUP; TmpFileName := IncludeTrailingPathDelimiter(FCurrentDir) + FFileName; { 判断文件是否存在,如果不存在则创建文件并创建根节点 } if not FileExists(TmpFileName) then begin if not InitXMLDocument(TmpXMLDocument) then Abort; TmpRoot := TmpXMLDocument.AddChild(CLIENTBACKUP_ROOT); end else begin TmpRoot := GetRoot(TmpXMLDocument); if TmpRoot = nil then Abort; end; { 判断是否只是创建文件 } if AClientBackupInfo.cbiBatch = '' then Exit; { 将数据插入文件中 } TmpNode := TmpRoot.AddChild(CLIENTBACKUP_BACKUPINFO); TmpChildNode := TmpNode.AddChild(CLIENTBACKUP_BATCH); TmpChildNode.NodeValue := AClientBackupInfo.cbiBatch; TmpChildNode := TmpNode.AddChild(CLIENTBACKUP_FILENAME); TmpChildNode.NodeValue := AClientBackupInfo.cbiFileName; { 保存文件 } TmpXMLDocument.SaveToFile(TmpFileName); NoError; Result := True; except on E: Exception do begin FErrorInfo := E.Message; Exit; end; end; finally TmpXMLDocument.Free; end; end; end.
unit HMAC; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) 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 HL7 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. } interface uses System.SysUtils, {$IFNDEF VER260} System.NetEncoding, {$ENDIF} EncdDecd, IdGlobal, IdHMAC, IdSSLOpenSSL, IdHash, BytesSupport; type TIdHMACClass = class of TIdHMAC; THMACUtils = class public class function HMAC(alg : TIdHMACClass; aKey, aMessage: TBytes): TBytes; class function HMAC_HexStr(alg : TIdHMACClass; aKey, aMessage: TBytes): TBytes; class function HMAC_Base64(alg : TIdHMACClass; aKey, aMessage: TBytes): AnsiString; end; function idb(b : TBytes) : TIdBytes; overload; function idb(b : TIdBytes) : TBytes; overload; implementation function idb(b : TBytes) : TIdBytes; begin SetLength(result, length(b)); if (length(b) > 0) then move(b[0], result[0], length(b)); end; function idb(b : TIdBytes) : TBytes; begin SetLength(result, length(b)); if (length(b) > 0) then move(b[0], result[0], length(b)); end; class function THMACUtils.HMAC(alg : TIdHMACClass; aKey, aMessage: TBytes): TBytes; var _alg : TIdHMAC; begin if not IdSSLOpenSSL.LoadOpenSSLLibrary then Exit; _alg := alg.Create; try _alg.Key := idb(aKey); Result:= idb(_alg.HashValue(idb(aMessage))); finally _alg.Free; end; end; class function THMACUtils.HMAC_HexStr(alg : TIdHMACClass; aKey, aMessage: TBytes): TBytes; var I: Byte; begin Result:= AnsiStringAsBytes('0x'); for I in HMAC(alg, aKey, aMessage) do Result:= BytesAdd(Result, AnsiStringAsBytes(AnsiString(IntToHex(I, 2)))); end; class function THMACUtils.HMAC_Base64(alg : TIdHMACClass; aKey, aMessage: TBytes): AnsiString; var _HMAC: TBytes; begin _HMAC:= HMAC(alg, aKey, aMessage); Result:= EncodeBase64(_HMAC, Length(_HMAC)); end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.OleCtnrs, uHostThumbnail, Vcl.ExtCtrls, Vcl.ComCtrls; type TFrmMain = class(TForm) Panel3: TPanel; EditFileName: TEdit; Button1: TButton; OpenDialog1: TOpenDialog; RadioGroup: TRadioGroup; Panel1: TPanel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); procedure RadioGroupClick(Sender: TObject); private { Private declarations } FPreview: THostThumbnailProvider; procedure LoadPreview(const FileName: string); public { Public declarations } end; var FrmMain: TFrmMain; implementation uses Winapi.ActiveX; {$R *.dfm} type THostThumbnailProviderClass=class(THostThumbnailProvider); procedure TFrmMain.Button1Click(Sender: TObject); begin if OpenDialog1.Execute() then begin EditFileName.Text:= OpenDialog1.FileName; LoadPreview(EditFileName.Text); end; end; procedure TFrmMain.FormCreate(Sender: TObject); begin ReportMemoryLeaksOnShutdown := True; FPreview:=nil; end; procedure TFrmMain.FormDestroy(Sender: TObject); begin if FPreview<>nil then FreeAndNil(FPreview); end; procedure TFrmMain.LoadPreview(const FileName: string); begin if FPreview<>nil then FreeAndNil(FPreview); FPreview := THostThumbnailProvider.Create(Self); FPreview.Top := 0; FPreview.Left := 0; FPreview.Width := Panel1.ClientWidth; FPreview.Height := Panel1.ClientHeight; FPreview.Parent := Panel1; FPreview.Align := alClient; //FPreview.FileName:='C:\Users\Dexter\Desktop\RAD Studio Projects\XE2\delphi-preview-handler\main.pas'; //FPreview.FileName:='C:\Users\Dexter\Desktop\RAD Studio Projects\2010\SMBIOS Delphi\Docs\DSP0119.pdf'; //FPreview.FileName:='C:\Users\Dexter\Desktop\seleccion\RePLE.msg'; FPreview.FileName:=FileName; end; procedure TFrmMain.RadioGroupClick(Sender: TObject); begin (* case RadioGroup.ItemIndex of 0: Print(32); 1: Print(64); 2: Print(128); 3: Print(256); end; *) end; end.
unit _Inspector; ///////////////////////////////////////////////////////////////////// // // Hi-Files Version 2 // Copyright (c) 1997-2004 Dmitry Liman [2:461/79] // // http://hi-files.narod.ru // ///////////////////////////////////////////////////////////////////// interface uses Objects, Dialogs, Drivers, _Working; type PInspector = ^TInspector; TInspector = object (TDialog) constructor Init( const ScriptName: String ); procedure Update( ANo, FNo: Integer ); procedure UpdateExec( S: PString ); procedure HandleEvent( var Event: TEvent ); virtual; function QueryCancel: Boolean; private AreaName : PParamText; FileName : PParamText; ExecLine : PParamText; AreaRoller: PProgress; FileRoller: PProgress; AreaPtr : PString; FilePtr : PString; ExecPtr : PString; AreaStr : String; FileStr : String; ExecStr : String; AreaNo : Integer; AloneText : String; Cancelled : Boolean; end; { TInspector } { =================================================================== } implementation uses MyLib, App, Views, MsgBox, _Fareas, _Log, _RES; { --------------------------------------------------------- } { TInspector } { --------------------------------------------------------- } { Init ---------------------------------------------------- } constructor TInspector.Init( const ScriptName: String ); var R: TRect; B: PButton; begin R.Assign( 0, 0, 50, 12 ); inherited Init( R, ScriptName ); Options := Options or ofCentered; Flags := 0; R.Grow( -2, -2 ); R.B.Y := Succ( R.A.Y ); AreaName := New( PParamText, Init( R, '%s', 1 ) ); Insert( AreaName ); R.Move( 0, 1 ); AreaRoller := New( PProgress, Init( R, FileBase^.Count ) ); Insert( AreaRoller ); R.Move( 0, 2 ); FileName := New( PParamText, Init( R, '%s', 1 ) ); Insert( FileName ); R.Move( 0, 1 ); FileRoller := New( PProgress, Init( R, 1 ) ); Insert( FileRoller ); R.Move( 0, 1 ); ExecLine := New( PParamText, Init( R, '%s', 1 ) ); Insert( ExecLine ); R.Move( 0, 2 ); Inc(R.B.Y); R.B.X := R.A.X + 20; B := New( PButton, Init( R, LoadString(_SCancelBtn), cmCancel, bfNormal ) ); B^.Options := B^.Options or ofCenterX; Insert( B ); AreaNo := -1; AreaPtr := @AreaStr; FilePtr := @FileStr; ExecPtr := @ExecStr; AreaName^.SetData( AreaPtr ); FileName^.SetData( FilePtr ); ExecLine^.SetData( ExecPtr ); AloneText := LoadString( _SAloneText ); end; { Init } { Update -------------------------------------------------- } procedure TInspector.Update( ANo, FNo: Integer ); var Area: PFileArea; FD : PFileDef; begin if ANo <> AreaNo then begin AreaNo := ANo; Area := FileBase^.At( ANo ); AreaStr := ^C + Area^.Name^; AreaName^.DrawView; AreaRoller^.Update( ANo + 1 ); FileRoller^.Reset( Area^.Count, 0 ); end else Area := FileBase^.At( ANo ); if FNo >= 0 then begin FD := Area^.At( FNo ); if FD^.AloneCmt then FileStr := ^C + AloneText else FileStr := ^C + FD^.NativeName^; end else FileStr := ''; FileName^.DrawView; FileRoller^.Update( FNo + 1 ); end; { Update } { UpdateExec ---------------------------------------------- } procedure TInspector.UpdateExec( S: PString ); begin ExecStr := S^; ExecLine^.DrawView; end; { UpdateExec } { HandleEvent --------------------------------------------- } procedure TInspector.HandleEvent( var Event: TEvent ); begin inherited HandleEvent( Event ); case Event.What of evCommand: begin case Event.Command of cmCancel: if MessageBox( LoadString(_SConfirmCancel), nil, mfConfirmation + mfYesNoCancel ) = cmYes then Cancelled := True; else Exit; end; ClearEvent( Event ); end; end; end; { HandleEvent } { QueryCancel --------------------------------------------- } function TInspector.QueryCancel: Boolean; var E: TEvent; begin GetEvent( E ); HandleEvent( E ); Result := Cancelled; end; { QueryCancel } end.
(****************************************************************************** * * * Usermanager * * Export -- Export class for exporting users into a csv file * * * * Copyright Michael Puff http://www.michael-puff.de * * * * * ******************************************************************************) {$I ..\..\CompilerSwitches.inc} unit Export; interface uses Windows, MPuTools, Exceptions, NTUser; type TExport = class(TObject) private FFilename: WideString; FComputer: WideString; FUsers: TUserCollection; procedure SetFilename(Filename: WideString); function GetFilename: WideString; procedure SetComputer(Computer: WideString); function GetComputer: WideString; procedure SetUsers(Users: TUserCollection); public property Filename: WideString read GetFilename write SetFilename; property Computer: WideString read GetComputer write SetComputer; property Users: TUserCollection write SetUsers; procedure ExportToCSV; procedure ExportToXML; end; implementation uses List; function BoolToStr(b: Boolean): string; const BoolStr : array[Boolean] of string = ('0', '-1'); begin result := BoolStr[b]; end; { TExport } procedure TExport.ExportToCSV; const CSV_SEP = ';'; var f : TextFile; i : Integer; s : WideString; Groups : TGroupCollection; j : Integer; strGroups : string; begin AssignFile(f, FFilename); {$I-} Rewrite(f); {$I+} if IOResult = 0 then begin s := 'Name' + CSV_SEP + 'FullName' + CSV_SEP + 'Description' + CSV_SEP + 'HomeDir' + CSV_SEP + 'ScriptPath' + CSV_SEP + 'CantChangePW' + CSV_SEP + 'AccountDontExpires' + CSV_SEP + 'MustChangePW' + CSV_SEP + 'AccountIsDeactivated' + CSV_SEP + 'AutoLogin' + CSV_SEP + 'IsAccountHidde' + CSV_SEP + 'Groups' + CSV_SEP; Writeln(f, s); s := ''; for i := 0 to FUsers.Count - 1 do begin Groups := FUsers.Items[i].Groups; for j := 0 to Groups.GetUserGroups(FUsers.Items[i]).Count - 1 do begin strGroups := strGroups + Groups.Items[j].Name + ','; end; // letzte Komma abschneiden strGroups := copy(strGroups, 1, length(strGroups) - 1); with FUsers do begin s := s + FUsers.Items[i].Name + CSV_SEP + FUsers.Items[i].FullName + CSV_SEP + Items[i].Description + CSV_SEP + Items[i].HomeDir + CSV_SEP + Items[i].ScriptPath + CSV_SEP + BoolToStr(Items[i].CantChangePW) + CSV_SEP + BoolToStr(Items[i].DontExpire) + CSV_SEP + BoolToStr(Items[i].MustChangePW) + CSV_SEP + BoolToStr(Items[i].Deactivated) + CSV_SEP + BoolToStr(Items[i].AutoLogin) + CSV_SEP + BoolToStr(Items[i].HideAccount) + CSV_SEP + strGroups + CSV_SEP; end; Writeln(f, s); s := ''; strGroups := ''; end; CloseFile(f); end else raise Exception.Create(SysErrorMessage(GetLastError), GetLastError); end; procedure TExport.ExportToXML; const LB = #13#10; INDENT = #9; function WriteStartNode(s: WideString): WideString; overload; begin result := FormatW('<%s>', [s]); end; function WriteStartNode(s: WideString; Attribut: WideString; Value: WideString): WideString; overload; begin result := FormatW('<%s %s="%s">', [s, Attribut, Value]); end; function WriteEndNode(s: WideString): WideString; begin result := FormatW('</%s>', [s]); end; var f : TextFile; s : string; i : Integer; Groups : TGroupCollection; j : Integer; strGroups : string; begin AssignFile(f, FFilename); {$I-} Rewrite(f); {$I+} if IOResult = 0 then begin s := '<?xml version="1.0" encoding="ISO-8859-1"?>'; Writeln(f, s); s := WriteStartNode('xpusermanager'); Writeln(f, s); s := WriteStartNode('users'); Writeln(f, s); for i := 0 to FUsers.Count - 1 do begin Groups := FUsers.Items[i].Groups; for j := 0 to Groups.GetUserGroups(FUsers.Items[i]).Count - 1 do begin strGroups := strGroups + WriteStartNode('group') +Groups.Items[j].Name + WriteEndNode('group'); end; with FUsers do begin s := WriteStartNode('account', 'value', Items[i].Name) + LB + INDENT + WriteStartNode('properties') + LB + INDENT + INDENT + WriteStartNode('password') + '' + WriteEndNode('password') + LB + INDENT + INDENT + WriteStartNode('fullname') + Items[i].FullName + WriteEndNode('fullname') + LB + INDENT + INDENT + WriteStartNode('description') + Items[i].Description + WriteEndNode('description') + LB + INDENT + INDENT + WriteStartNode('homedir') + Items[i].HomeDir + WriteEndNode('homedir') + LB + INDENT + INDENT + WriteStartNode('scriptpath') + Items[i].ScriptPath + WriteEndNode('scriptpath') + LB + INDENT + INDENT + WriteStartNode('cantchangepw') + BoolToStr(Items[i].CantChangePW) + WriteEndNode('cantchangepw') + LB + INDENT + INDENT + WriteStartNode('accountdontexpires') + BoolToStr(Items[i].DontExpire) + WriteEndNode('accountdontexpires') + LB + INDENT + INDENT + WriteStartNode('mustchangepw') + BoolToStr(Items[i].MustChangePW) + WriteEndNode('mustchangepw') + LB + INDENT + INDENT + WriteStartNode('accountisdeactivated') + BoolToStr(Items[i].Deactivated) + WriteEndNode('accountisdeactivated') + LB + INDENT + INDENT + WriteStartNode('autologin') + BoolToStr(Items[i].AutoLogin) + WriteEndNode('autologin') + LB + INDENT + INDENT + WriteStartNode('isaccounthidden') + BoolToStr(Items[i].HideAccount) + WriteEndNode('isaccounthidden') + LB + INDENT + WriteEndNode('properties')+ LB + INDENT + WriteStartNode('groups') + LB + INDENT + INDENT + strGroups + LB + INDENT + WriteEndNode('groups'); end; Writeln(f, s); Writeln(f, WriteEndNode('account')); s := ''; strGroups := ''; end; s := WriteEndNode('users'); Writeln(f, s); s := WriteEndNode('xpusermanager'); Writeln(f, s); CloseFile(f); end else raise Exception.Create(SysErrorMessage(GetLastError), GetLastError); end; function TExport.GetComputer: WideString; begin result := FComputer end; function TExport.GetFilename: WideString; begin result := FFilename; end; procedure TExport.SetComputer(Computer: WideString); begin FComputer := copy(Computer, 3, length(Computer)); end; procedure TExport.SetFilename(Filename: WideString); begin FFilename := Filename end; procedure TExport.SetUsers(Users: TUserCollection); begin if Assigned(Users) then FUsers := Users; end; end.
unit WSSubPic; interface uses Windows, WSTextArt; type // 用户自定义的字幕样式 TSubPicStyle = record bUseDefaultStyle: BOOL; // 是否使用默认样式 szFontName: array[0..127] of WideChar; // 字体名 nFontSize: Longint; // 字体大小 uStyle: UINT; // 字体样式 PCSFontStyleRegular | PCSFontStyleBold | PCSFontStyleItalic | PCSFontStyleUnderline Color: COLORREF; // 字体颜色 bShadow: BOOL; // 是否使用阴影 paramShadow: TShadowParam; // 文字阴影(bShadow为真时有效) {$IFDEF WIN32} nHalation: Longint; // 光晕值 0为无光晕效果 crHalation: COLORREF; // 光晕颜色值 {$ENDIF} nAngle: Longint; // 旋转角度 顺时针(0-360) nLeftTopX: Longint; // 字幕图片左上角在视频图片上的X坐标 nLeftTopY: Longint; // 字幕图片左上角在视频图片上的Y坐标 end; PUserSubPicRec = ^TUserSubPicRec; TUserSubPicRec = record uSubPicID: UINT; // 字幕ID Style: TSubPicStyle; // 字幕样式 nOpacity: Longint; // 透明度 Add by LSG end; TUserSubPicEx = record pSubPicPath: PWideChar; // 字幕名 Style: TSubPicStyle; // 字幕样式 end; PUserSubPicEx = ^TUserSubPicEx; implementation end.
(* В) Напишите целочисленную функцию Division для деления первого числа на второе без применения операции DIV. *) function DivisionSign(n1, n2: integer): integer; var r: integer; pos: boolean; begin if n2 = 0 then r := 0 else begin if (n1>0) and (n2>0) then pos := true else if (n1<0) and (n2<0) then pos := true else pos := false; n1 := Abs(n1); n2 := Abs(n2); r := 0; while (n1 >= n2) do begin n1 := n1 - n2; Inc(r); end; end; if not pos then r := r * -1; DivisionSign := r; end; // function DivisionUnsign(n1, n2: word): word; // var r: word; // begin // if n2 = 0 // then r := 0 // else begin // r := 0; // while (n1 >= n2) do begin // n1 := n1 - n2; // Inc(r); // end; // end; // DivisionUnsign := r; // end; begin // Writeln(DivisionUnsign(20, 20)); // Writeln(DivisionUnsign(20, 4)); // Writeln(DivisionUnsign(21, 5)); // Writeln(DivisionUnsign(11, 5)); // Writeln(DivisionUnsign(14, 5)); Writeln(DivisionSign(-20, 20)); Writeln(DivisionSign(20, -4)); Writeln(DivisionSign(-21, -5)); Writeln(DivisionSign(11, 5)); Writeln(DivisionSign(-14, 5)); end.
(*******************************************************) (* *) (* Engine Paulovich DirectX *) (* Win32-DirectX API Unit *) (* *) (* Copyright (c) 2003-2004, Ivan Paulovich *) (* *) (* iskatrek@hotmail.com uin#89160524 *) (* *) (* Unit: glWindow *) (* *) (*******************************************************) unit glWindow; interface uses Windows, Messages, Classes, SysUtils; type (* Events *) TMouseButton = (mbLeft, mbRight, mbMiddle); TShiftState = set of (ssShift, ssAlt, ssCtrl, ssLeft, ssRight, ssMiddle, ssDouble); TNotifyEvent = procedure(Sender: TObject) of object; TCommandEvent = procedure(Sender: TObject; ID: Integer) of object; TMouseEvent = procedure(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer) of object; TMouseMoveEvent = procedure(Sender: TObject; Shift: TShiftState; X, Y: Integer) of object; TKeyEvent = procedure(Sender: TObject; var Key: Word; Shift: TShiftState) of object; TKeyPressEvent = procedure(Sender: TObject; var Key: Char) of object; (* TReferer *) PWindowReferer = ^TWindowReferer; TWindowReferer = class of TWindow; (* TWindowOption *) TWindowOption = (doFullScreen, doAutoSize, doMaximizeBox, doMinimizeBox, doSysMenu, doCenter, doResMenu); (* TWindowOptions *) TWindowOptions = set of TWindowOption; (* TWindow *) PWindow = ^TWindow; TWindow = class private FHandle: HWND; FActive: Boolean; FInitialized: Boolean; FClientRect: TRect; FStyle: Integer; FKeys: array[0..255] of Byte; FClicked: Boolean; FNowOptions: TWindowOptions; FOptions: TWindowOptions; FCaption: string; FMenuName: Integer; FOnCreate: TNotifyEvent; FOnInitialize: TNotifyEvent; FOnFinalize: TNotifyEvent; FOnResize: TNotifyEvent; FOnClick: TNotifyEvent; FOnDblClick: TNotifyEvent; FOnMouseDown: TMouseEvent; FOnMouseMove: TMouseMoveEvent; FOnMouseUp: TMouseEvent; FOnKeyDown: TKeyEvent; FOnKeyPress: TKeyPressEvent; FOnKeyUp: TKeyEvent; FOnCommand: TCommandEvent; function KeyDown(var Message: TWMKey): Boolean; function KeyUp(var Message: TWMKey): Boolean; function KeyPress(var Message: TWMKey): Boolean; procedure MouseDown(var Message: TWMMouse; Button: TMouseButton; Shift: TShiftState); procedure MouseUp(var Message: TWMMouse; Button: TMouseButton); procedure MouseMove(var Message: TWMMouse); function GetBoundsRect: TRect; function GetKey(Index: Integer): Boolean; function GetCaption: string; procedure SetWindowRect; procedure SetWidth(Value: Integer); procedure SetHeight(Value: Integer); procedure SetLeft(Value: Integer); procedure SetTop(Value: Integer); procedure SetOptions(Value: TWindowOptions); procedure SetCaption(Value: string); protected procedure DoKeyDown(var Key: Word; Shift: TShiftState); virtual; procedure DoKeyPress(var Key: Char); virtual; procedure DoKeyUp(var Key: Word; Shift: TShiftState); virtual; procedure DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); virtual; procedure DoMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); virtual; procedure DoCommand(ID: Integer); virtual; procedure DoMouseMove(Shift: TShiftState; X, Y: Integer); virtual; procedure DoCreate; virtual; procedure DoInitialize; virtual; procedure DoFinalize; virtual; procedure DoResize; virtual; public constructor Create; destructor Destroy; function WndProc(hWnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; virtual; function Run: Integer; function IsActive: Boolean; function HasMessages: Boolean; function Pump: Boolean; class function GetWindow: PWindow; property Initialized: Boolean read FInitialized; property Handle: HWND read FHandle; property Width: Integer read FClientRect.Right write SetWidth; property Height: Integer read FClientRect.Bottom write SetHeight; property Left: Integer read FClientRect.Left write SetLeft; property Top: Integer read FClientRect.Top write SetTop; property Caption: string read GetCaption write SetCaption; property MenuName: Integer read FmenuName write FMenuName; property NowOptions: TWindowOptions read FNowOptions; property Options: TWindowOptions read FOptions write SetOptions; property Key[Index: Integer]: Boolean read GetKey; property Client: TRect read FClientRect write FClientRect; property OnInitialize: TNotifyEvent read FOnInitialize write FOnInitialize; property OnFinalize: TNotifyEvent read FOnFinalize write FOnFinalize; property OnClick: TNotifyEvent read FOnClick write FOnClick; property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick; property OnMouseDown: TMouseEvent read FOnMouseDown write FOnMouseDown; property OnMouseMove: TMouseMoveEvent read FOnMouseMove write FOnMouseMove; property OnMouseUp: TMouseEvent read FOnMouseUp write FOnMouseUp; property OnKeyDown: TKeyEvent read FOnKeyDown write FOnKeyDown; property OnKeyPress: TKeyPressEvent read FOnKeyPress write FOnKeyPress; property OnKeyUp: TKeyEvent read FOnKeyUp write FOnKeyUp; end; var Window: TWindow = nil; implementation uses glError, glConst; const WINDOW_OPTIONS = [doMaximizeBox, doMinimizeBox, doSysMenu, doCenter]; var CountWindow: Integer = 0; Log: PLogError = nil; function GlobalWndProc(hWnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; begin Result := Window.WndProc(hWnd, uMsg, wParam, lParam); end; function KeysToShiftState(Keys: Word): TShiftState; begin Result := []; if Keys and MK_SHIFT <> 0 then Include(Result, ssShift); if Keys and MK_CONTROL <> 0 then Include(Result, ssCtrl); if Keys and MK_LBUTTON <> 0 then Include(Result, ssLeft); if Keys and MK_RBUTTON <> 0 then Include(Result, ssRight); if Keys and MK_MBUTTON <> 0 then Include(Result, ssMiddle); if GetKeyState(VK_MENU) < 0 then Include(Result, ssAlt); end; function KeyDataToShiftState(KeyData: Longint): TShiftState; const AltMask = $20000000; begin Result := []; if GetKeyState(VK_SHIFT) < 0 then Include(Result, ssShift); if GetKeyState(VK_CONTROL) < 0 then Include(Result, ssCtrl); if KeyData and AltMask <> 0 then Include(Result, ssAlt); end; (* TWindow *) constructor TWindow.Create; begin SaveLog(Format(EVENT_TALK, ['TWindow.Create'])); Window := Self; FHandle := 0; FActive := False; FInitialized := False; SetRect(FClientRect, 0, 0, 640, 480); FStyle := 0; ZeroMemory(@FKeys, 256); FNowOptions := WINDOW_OPTIONS; FOptions := WINDOW_OPTIONS; FCaption := Format('Window%d', [CountWindow]); SaveLog(Format(EVENT_RESOLUTION, [FClientRect.Right, FClientRect.Bottom])); Inc(CountWindow); DoCreate; end; destructor TWindow.Destroy; begin DoFinalize; DestroyWindow(FHandle); Window := nil; end; function TWindow.WndProc(hWnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; var MouseMessage: TWMMouse; KeyboardMessage: TWMKey; procedure UpdateMouse; begin MouseMessage.Msg := uMsg; MouseMessage.Keys := wParam; MouseMessage.XPos := LOWORD(lParam); MouseMessage.YPos := HIWORD(lParam); end; procedure UpdateKeyboard; begin KeyboardMessage.Msg := uMsg; KeyboardMessage.CharCode := wParam; KeyboardMessage.KeyData := Integer(@FKeys); end; begin if Assigned(Log) then begin Result := DefWindowProc(hWnd, uMsg, wParam, lParam); Exit; end; try case uMsg of WM_CREATE: begin Window.FActive := True; end; WM_PAINT: begin ValidateRect(hWnd, nil); end; WM_MOVE: begin FClientRect.Left := LOWORD(lParam); FClientRect.Top := HIWORD(lParam); end; WM_SIZE: begin FClientRect.Right := LOWORD(lParam); FClientRect.Bottom := HIWORD(lParam); DoResize; end; WM_KEYDOWN: begin FKeys[wParam] := 1; UpdateKeyboard; KeyDown(KeyboardMessage); end; WM_CHAR: begin FKeys[wParam] := 1; UpdateKeyboard; KeyPress(KeyboardMessage); end; WM_KEYUP: begin FKeys[wParam] := 0; UpdateKeyboard; KeyUp(KeyboardMessage); end; WM_LBUTTONDOWN: begin UpdateMouse; MouseDown(MouseMessage, mbLeft, []); end; WM_LBUTTONUP: begin UpdateMouse; MouseUp(MouseMessage, mbLeft); end; WM_RBUTTONDOWN: begin UpdateMouse; MouseDown(MouseMessage, mbRight, []); end; WM_RBUTTONUP: begin UpdateMouse; MouseUp(MouseMessage, mbRight); end; WM_MOUSEMOVE: begin UpdateMouse; MouseMove(MouseMessage); end; WM_COMMAND: begin DoCommand(LOWORD(wParam)); end; WM_DESTROY, WM_CLOSE: begin PostQuitMessage(0); end; else begin Result := DefWindowProc(hWnd, uMsg, wParam, lParam); Exit; end; end; except New(Log); Result := 0; Exit; end; Result := 0; end; function TWindow.Run: Integer; var Wc: TWndClass; begin Result := E_FAIL; SaveLog(Format(EVENT_TALK, ['TWindow.Run'])); if doFullScreen in FNowOptions then FStyle := FStyle or WS_POPUP; if doMinimizeBox in FNowOptions then FStyle := FStyle or WS_MINIMIZEBOX; if doMaximizeBox in FNowOptions then FStyle := FStyle or WS_MAXIMIZEBOX; if doSysMenu in FNowOptions then FStyle := FStyle or WS_SYSMENU; if doAutoSize in FNowOptions then begin FClientRect.Left := 0; FClientRect.Top := 0; FClientRect.Right := GetSystemMetrics(SM_CXSCREEN); FClientRect.Bottom := GetSystemMetrics(SM_CYSCREEN); end; if DoCenter in FNowOptions then SetRect(FClientRect, (GetSystemMetrics(SM_CXSCREEN) - FClientRect.Right) div 2, (GetSystemMetrics(SM_CYSCREEN) - FClientRect.Bottom) div 2, FClientRect.Right, FClientRect.Bottom); FillChar(Wc, SizeOf(TWndClass), 0); Wc.lpszClassName := PChar(FCaption); Wc.lpfnWndProc := @GlobalWndProc; Wc.style := CS_VREDRAW or CS_HREDRAW; Wc.hInstance := HInstance; Wc.hIcon := LoadIcon(0, IDI_WINLOGO); Wc.hCursor := LoadCursor(0, IDC_ARROW); Wc.hbrBackground := GetStockObject(BLACK_BRUSH); if DoResMenu in FnowOptions then Wc.lpszMenuName := MakeIntResource(FMenuName) else Wc.lpszMenuName := nil; Wc.cbClsExtra := 0; Wc.cbWndExtra := 0; if Windows.RegisterClass(Wc) = 0 then raise ELogError.Create(Format(ERROR_REGISTRY, ['TWindow'])) else SaveLog(Format(EVENT_REGISTRY, ['TWindow'])); AdjustWindowRect(FClientRect, FStyle, False); FHandle := CreateWindow(PChar(FCaption), PChar(FCaption), FStyle or WS_VISIBLE, FClientRect.Left, FClientRect.Top, FClientRect.Right, FClientRect.Bottom, 0, 0, HInstance, nil); if FHandle = 0 then raise ELogError.Create(Format(ERROR_INSTANCE, ['TWindow'])) else begin FInitialized := True; Result := S_OK; SaveLog(Format(EVENT_INSTANCE, ['TWindow'])); end; DoInitialize; if not (doFullScreen in FOptions) then ShowWindow(FHandle, SW_SHOW); UpdateWindow(FHandle); end; function TWindow.IsActive: Boolean; begin Result := FActive; end; function TWindow.HasMessages: Boolean; var Msg: TMsg; begin Result := PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE); end; function TWindow.Pump: Boolean; var Msg: TMsg; ErrorOut: ELogError; begin PeekMessage(Msg, 0, 0, 0, PM_REMOVE); if Msg.message = WM_QUIT then begin Result := False; Exit; end; TranslateMessage(Msg); DispatchMessage(Msg); if Assigned(Log) then begin ErrorOut := Log^; Dispose(Log); raise ELogError.Create(Format(ERROR_SITE, ['TWindow.Pump'])); end; Result := True; end; function TWindow.GetBoundsRect; begin GetClientRect(FHandle, FClientRect); Result := FClientRect; end; function TWindow.GetKey(Index: Integer): Boolean; begin Result := FKeys[Index] <> 0; end; function TWindow.GetCaption: string; begin GetWindowText(FHandle, PChar(FCaption), 255); Result := FCaption; end; procedure TWindow.SetWindowRect; begin MoveWindow(FHandle, FClientRect.Left, FClientRect.Top, FClientRect.Right, FClientRect.Bottom, True); end; procedure TWindow.SetWidth(Value: Integer); begin FClientRect.Right := Value; SetWindowRect; end; procedure TWindow.SetHeight(Value: Integer); begin FClientRect.Bottom := Value; SetWindowRect; end; procedure TWindow.SetLeft(Value: Integer); begin FClientRect.Left := Value; SetWindowRect; end; procedure TWindow.SetTop(Value: Integer); begin FClientRect.Top := Value; SetWindowRect; end; procedure TWindow.SetCaption(Value: string); begin FCaption := Value; SetWindowText(FHandle, PChar(FCaption)); end; procedure TWindow.SetOptions(Value: TWindowOptions); var OldOptions: TWindowOptions; begin FOptions := Value; FNowOptions := Value; { if FInitialized then begin OldOptions := FNowOptions; FNowOptions := FNowOptions * WINDOW_OPTIONS + (FOptions - WINDOW_OPTIONS); end else FNowOptions := FOptions; } end; class function TWindow.GetWindow: PWindow; begin Result := @Window; end; procedure TWindow.DoCreate; begin if Assigned(FOnCreate) then FOnCreate(Self); end; procedure TWindow.DoInitialize; begin if Assigned(FOnInitialize) then FOnInitialize(Self); end; procedure TWindow.DoFinalize; begin if Assigned(FOnFinalize) then FOnFinalize(Self); end; procedure TWindow.DoResize; begin if Assigned(FOnResize) then FOnResize(Self); end; function TWindow.KeyDown(var Message: TWMKey): Boolean; var ShiftState: TShiftState; begin with Message do begin ShiftState := KeyDataToShiftState(KeyData); DoKeyDown(CharCode, ShiftState); end; Result := Message.CharCode <> 0; end; function TWindow.KeyPress(var Message: TWMKey): Boolean; var Ch: Char; begin with Message do begin Ch := Char(CharCode); DoKeyPress(Ch); CharCode := Word(Ch); end; Result := Char(Message.CharCode) <> #0; end; function TWindow.KeyUp(var Message: TWMKey): Boolean; var ShiftState: TShiftState; begin with Message do begin ShiftState := KeyDataToShiftState(KeyData); DoKeyUp(CharCode, ShiftState); end; Result := Message.CharCode <> 0; end; procedure TWindow.DoKeyDown(var Key: Word; Shift: TShiftState); begin if Assigned(FOnKeyDown) then FOnKeyDown(Self, Key, Shift); end; procedure TWindow.DoKeyPress(var Key: Char); begin if Assigned(FOnKeyPress) then FOnKeyPress(Self, Key); end; procedure TWindow.DoKeyUp(var Key: Word; Shift: TShiftState); begin if Assigned(FOnKeyUp) then FOnKeyUp(Self, Key, Shift); end; procedure TWindow.MouseDown(var Message: TWMMouse; Button: TMouseButton; Shift: TShiftState); begin FClicked := True; DoMouseDown(Button, KeysToShiftState(Message.Keys) + Shift, Message.XPos, Message.YPos); end; procedure TWindow.MouseUp(var Message: TWMMouse; Button: TMouseButton); var Region: HRGN; Pos: TRect; begin FClicked := False; Pos := GetBoundsRect; Region := CreateRectRgn(Pos.Left, Pos.Top, Pos.Right, Pos.Bottom); if PtInRegion(Region, Message.XPos, Message.YPos) then with Message do DoMouseUp(Button, KeysToShiftState(Keys), XPos, YPos); end; procedure TWindow.MouseMove(var Message: TWMMouse); begin with Message do DoMouseMove(KeysToShiftState(Keys), XPos, YPos); end; procedure TWindow.DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(FOnMouseDown) then FOnMouseDown(Self, Button, Shift, Left, Top); end; procedure TWindow.DoMouseMove(Shift: TShiftState; X, Y: Integer); begin if Assigned(FOnMouseMove) then FOnMouseMove(Self, Shift, Left, Top); end; procedure TWindow.DoMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(FOnMouseUp) then FOnMouseUp(Self, Button, Shift, Left, Top); end; procedure TWindow.DoCommand(ID: Integer); begin if Assigned(FOnCommand) then FOnCommand(Self, ID); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ORCAMENTO_EMPRESARIAL] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit OrcamentoEmpresarialVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, OrcamentoDetalheVO, OrcamentoPeriodoVO; type [TEntity] [TTable('ORCAMENTO_EMPRESARIAL')] TOrcamentoEmpresarialVO = class(TVO) private FID: Integer; FID_ORCAMENTO_PERIODO: Integer; FNOME: String; FDESCRICAO: String; FDATA_INICIAL: TDateTime; FNUMERO_PERIODOS: Integer; FDATA_BASE: TDateTime; //Transientes FOrcamentoPeriodoNome: String; FOrcamentoPeriodoCodigo: String; FOrcamentoPeriodoVO: TOrcamentoPeriodoVO; FListaOrcamentoDetalheVO: TObjectList<TOrcamentoDetalheVO>; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_ORCAMENTO_PERIODO', 'Id Orcamento Periodo', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdOrcamentoPeriodo: Integer read FID_ORCAMENTO_PERIODO write FID_ORCAMENTO_PERIODO; [TColumnDisplay('ORCAMENTOPERIODO.PERIODO', 'Código Período', 80, [ldGrid, ldLookup], ftString, 'OrcamentoPeriodoVO.TOrcamentoPeriodoVO', True)] property OrcamentoPeriodoCodigo: String read FOrcamentoPeriodoCodigo write FOrcamentoPeriodoCodigo; [TColumnDisplay('ORCAMENTOPERIODO.NOME', 'Nome Período', 300, [ldGrid, ldLookup], ftString, 'OrcamentoPeriodoVO.TOrcamentoPeriodoVO', True)] property OrcamentoPeriodoNome: String read FOrcamentoPeriodoNome write FOrcamentoPeriodoNome; [TColumn('NOME', 'Nome', 240, [ldGrid, ldLookup, ldCombobox], False)] property Nome: String read FNOME write FNOME; [TColumn('DESCRICAO', 'Descricao', 450, [ldGrid, ldLookup, ldCombobox], False)] property Descricao: String read FDESCRICAO write FDESCRICAO; [TColumn('DATA_INICIAL', 'Data Inicial', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataInicial: TDateTime read FDATA_INICIAL write FDATA_INICIAL; [TColumn('NUMERO_PERIODOS', 'Numero Periodos', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property NumeroPeriodos: Integer read FNUMERO_PERIODOS write FNUMERO_PERIODOS; [TColumn('DATA_BASE', 'Data Base', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataBase: TDateTime read FDATA_BASE write FDATA_BASE; [TAssociation('ID', 'ID_ORCAMENTO_PERIODO')] property OrcamentoPeriodoVO: TOrcamentoPeriodoVO read FOrcamentoPeriodoVO write FOrcamentoPeriodoVO; [TManyValuedAssociation('ID_ORCAMENTO_EMPRESARIAL', 'ID')] property ListaOrcamentoDetalheVO: TObjectList<TOrcamentoDetalheVO> read FListaOrcamentoDetalheVO write FListaOrcamentoDetalheVO; end; implementation constructor TOrcamentoEmpresarialVO.Create; begin inherited; FOrcamentoPeriodoVO := TOrcamentoPeriodoVO.Create; FListaOrcamentoDetalheVO := TObjectList<TOrcamentoDetalheVO>.Create; end; destructor TOrcamentoEmpresarialVO.Destroy; begin FreeAndNil(FOrcamentoPeriodoVO); FreeAndNil(FListaOrcamentoDetalheVO); inherited; end; initialization Classes.RegisterClass(TOrcamentoEmpresarialVO); finalization Classes.UnRegisterClass(TOrcamentoEmpresarialVO); end.
unit UAddPictures; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtDlgs, Vcl.Mask, Vcl.DBCtrls, UMainDataModule; type TFormAddPictures = class(TForm) DBEditTitlePicture: TDBEdit; DBEditPathPicture: TDBEdit; Label1: TLabel; Label2: TLabel; opdPictures: TOpenPictureDialog; bibAddPic: TBitBtn; ButtonSearchPicture: TButton; bibCancel: TBitBtn; Panel1: TPanel; dbeTypePicture: TDBEdit; procedure bibAddPicClick(Sender: TObject); procedure ButtonSearchPictureClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure ChoiseType(i: integer); end; var FormAddPictures: TFormAddPictures; IsMonument: Boolean; implementation uses UArtWorkForm; {$R *.dfm} procedure TFormAddPictures.bibAddPicClick(Sender: TObject); begin if DBEditPathPicture.Field.Text = '' then MessageDlg('Поле '+Label2.Caption+' обовязкове для заповнення', mtError, [mbOk], 0); if DBEditTitlePicture.Field.Text = '' then DBEditTitlePicture.Field.Text:= ExtractFileName(opdPictures.FileName); if dbeTypePicture.Text = '2' then ArtWorkForm.dbePhoto.Field.Text:= ExtractFileName(opdPictures.FileName); MainDataModule.ADOTablePictures.Post; end; procedure TFormAddPictures.ButtonSearchPictureClick(Sender: TObject); begin if opdPictures.Execute then DBEditPathPicture.Field.Text:= opdPictures.FileName; end; procedure TFormAddPictures.ChoiseType(i: integer); begin case i of 0: dbeTypePicture.Field.Text:= '0'; 1: dbeTypePicture.Field.Text:= '1'; 2: dbeTypePicture.Field.Text:= '2'; end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [WMS_PARAMETRO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit WmsParametroController; interface uses Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, VO, Generics.Collections, WmsParametroVO; type TWmsParametroController = class(TController) private class var FDataSet: TClientDataSet; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); class function ConsultaLista(pFiltro: String): TObjectList<TWmsParametroVO>; class function ConsultaObjeto(pFiltro: String): TWmsParametroVO; class procedure Insere(pObjeto: TWmsParametroVO); class function Altera(pObjeto: TWmsParametroVO): Boolean; class function Exclui(pId: Integer): Boolean; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>); end; implementation uses UDataModule, T2TiORM; class procedure TWmsParametroController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TWmsParametroVO>; begin try Retorno := TT2TiORM.Consultar<TWmsParametroVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TWmsParametroVO>(Retorno); finally end; end; class function TWmsParametroController.ConsultaLista(pFiltro: String): TObjectList<TWmsParametroVO>; begin try Result := TT2TiORM.Consultar<TWmsParametroVO>(pFiltro, '-1', True); finally end; end; class function TWmsParametroController.ConsultaObjeto(pFiltro: String): TWmsParametroVO; begin try Result := TT2TiORM.ConsultarUmObjeto<TWmsParametroVO>(pFiltro, True); finally end; end; class procedure TWmsParametroController.Insere(pObjeto: TWmsParametroVO); var UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TWmsParametroController.Altera(pObjeto: TWmsParametroVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TWmsParametroController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TWmsParametroVO; begin try ObjetoLocal := TWmsParametroVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); TratarRetorno(Result); finally FreeAndNil(ObjetoLocal) end; end; class function TWmsParametroController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TWmsParametroController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; class procedure TWmsParametroController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>); begin try TratarRetorno<TWmsParametroVO>(TObjectList<TWmsParametroVO>(pListaObjetos)); finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TWmsParametroController); finalization Classes.UnRegisterClass(TWmsParametroController); end.
unit Pattern.Visitor; interface uses Pattern.ConcreteElementProgramador, Pattern.ConcreteElementGerente; type { Visitor } IVisitor = interface ['{9030B2DC-C821-4C91-861C-9322D2C04EA3}'] // O Visitor possui um método sobrecarregado para cada Concrete Element existente procedure Visit(Programador: TProgramador); overload; procedure Visit(Gerente: TGerente); overload; end; implementation end.
unit xxmReadHandler; interface uses Classes, Sockets; type THandlerReadStreamAdapter=class(TStream) private FSize:Int64; FSocket:TCustomIpClient; protected function GetSize: Int64; override; procedure SetSize(NewSize: Longint); overload; override; procedure SetSize(const NewSize: Int64); overload; override; public constructor Create(Socket:TCustomIpClient;Size:Int64); function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; overload; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; overload; override; end; implementation uses SysUtils; { THandlerReadStreamAdapter } constructor THandlerReadStreamAdapter.Create(Socket: TCustomIpClient; Size: Int64); begin inherited Create; FSize:=Size; FSocket:=Socket; end; function THandlerReadStreamAdapter.GetSize: Int64; begin Result:=FSize;//from HTTP request header end; function THandlerReadStreamAdapter.Seek(Offset: Integer; Origin: Word): Longint; begin //TXxmReqPars.Fill seeks to beginning only for convenience if (Offset=soFromBeginning) and (Origin=0) then Result:=0 else raise Exception.Create('THandlerReadStreamAdapter.Seek not supported'); end; function THandlerReadStreamAdapter.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin Result:=Seek(integer(Offset),word(Origin)); end; function THandlerReadStreamAdapter.Read(var Buffer; Count: Integer): Longint; begin Result:=FSocket.ReceiveBuf(Buffer,Count); end; procedure THandlerReadStreamAdapter.SetSize(NewSize: Integer); begin raise Exception.Create('THandlerReadStreamAdapter.SetSize not supported'); end; procedure THandlerReadStreamAdapter.SetSize(const NewSize: Int64); begin raise Exception.Create('THandlerReadStreamAdapter.SetSize not supported'); end; function THandlerReadStreamAdapter.Write(const Buffer; Count: Integer): Longint; begin raise Exception.Create('THandlerReadStreamAdapter.Write not supported'); end; end.
{*******************************************************} { } { Delphi Runtime Library } { Windows Simplified Printer Interface Unit } { } { Copyright (c) 1991,94 Borland International } { } {*******************************************************} unit WinPrn; {$S-} interface uses WinTypes; { AbortPrn will cause all unprinted portions of the writes to the } { file to be thrown away. Note: the file still must be closed. } procedure AbortPrn(var F: Text); { AssignPrn assigns a file to a printer. The Device, Driver, and } { Port can be retrieved from the WIN.INI file's [device] section } { or from the [windows] sections 'device' string. If Device is nil } { the default printer is used. } procedure AssignPrn(var F: Text; Device, Driver, Port: PChar); { AssignDefPrn calls AssignPrn with Device equal to nil. } procedure AssignDefPrn(var F: Text); { SetPrnFont will cause the file to begin printing using the given } { font. The old font is returned. } function SetPrnFont(var F: Text; Font: HFont): HFont; { TitlePrn will give a title to the file being printed which is } { displayed by Window's Print Manager. For this routine to have } { effect it needs to be called before ReWrite. } procedure TitlePrn(var F: Text; Title: PChar); { ProcessPrnMessage is called whenever a message is received by } { WinPrn's abort procedure. If the function returns false, the } { message is translated and dispatched, otherwise it is ignored. } { Use this variable if you wish modeless dialogs to continue to } { operate while printing. (Note: Since ObjectWindow automatically } { initializes this variable for KBHandler's, no special action is } { necessary when using ObjectWindows). } var ProcessPrnMessage: function (var Msg: TMsg): Boolean; implementation uses WinProcs, WinDos, SysUtils; { ---------------------------------------------------------------- } { Internal helper routines --------------------------------------- } { ---------------------------------------------------------------- } const wpInvalidDevice = 230; wpTooManyAborted = 231; wpPrintingError = 232; { Printer abort manager ------------------------------------------ } var AbortList: array[1..8] of HDC; { List of aborted printings } const AbortListLen: Byte = 0; { Abort ---------------------------------------------------------- } { Add the given DC to the abort list } procedure Abort(DC: HDC); begin if AbortListLen < SizeOf(AbortList) then begin Inc(AbortListLen); AbortList[AbortListLen] := DC; end else InOutRes := wpTooManyAborted; end; { UnAbort -------------------------------------------------------- } { Remove a DC value from the abort list. If not in the list } { ignore it. } procedure UnAbort(DC: HDC); var I: Byte; begin for I := 1 to AbortListLen do if DC = AbortList[I] then begin if AbortListLen <> I then Move(AbortList[I], AbortList[I + 1], AbortListLen - I - 1); Dec(AbortListLen); Exit; end; end; { IsAbort -------------------------------------------------------- } { Is the given DC in the abort list? } function IsAborted(DC: HDC): Bool; var I: Byte; begin for I := 1 to AbortListLen do if DC = AbortList[I] then begin IsAborted := True; Exit; end; IsAborted := False; end; { PrnRec --------------------------------------------------------- } { Printer data record } type PrnRec = record DC: HDC; { Printer device context } case Integer of 0: ( Title: PChar); { Title of the printout } 1: ( Cur: TPoint; { Next position to write text } Finish: TPoint; { End of the pritable area } Height: Word; { Height of the current line } Status: Word); { Error status of the printer } 2: ( Tmp: array[1..14] of Char); end; { NewPage -------------------------------------------------------- } { Start a new page. } procedure NewPage(var Prn: PrnRec); begin with Prn do begin LongInt(Cur) := 0; if not IsAborted(DC) and (Escape(DC, WinTypes.NewFrame, 0, nil, nil) <= 0) then Status := wpPrintingError; end; end; { NewLine -------------------------------------------------------- } { Start a new line on the current page, if no more lines left } { start a new page. } procedure NewLine(var Prn: PrnRec); function CharHeight: Word; var Metrics: TTextMetric; begin GetTextMetrics(Prn.DC, Metrics); CharHeight := Metrics.tmHeight; end; begin with Prn do begin Cur.X := 0; if Height = 0 then { two new lines in a row, use the current character height } Inc(Cur.Y, CharHeight) else { Advance the height of the tallest font } Inc(Cur.Y, Height); if Cur.Y > (Finish.Y - (Height * 2)) then NewPage(Prn); Height := 0; end; end; { PrnOutStr ------------------------------------------------------ } { Print a string to the printer without regard to special } { characters. These should handled by the caller. } procedure PrnOutStr(var Prn: PrnRec; Text: PChar; Len: Integer); var Extent: TPoint; { Size of the current text } L: Integer; { Temporary used for printing } begin with Prn do begin while Len > 0 do begin L := Len; LongInt(Extent) := GetTextExtent(DC, Text, L); { Wrap the text to the line } while (L > 0) and (Extent.X + Cur.X > Finish.X) do begin Dec(L); LongInt(Extent) := GetTextExtent(DC, Text, L); end; { Adjust the current line height } if Extent.Y > Height then Height := Extent.Y; if not IsAborted(DC) then TextOut(DC, Cur.X, Cur.Y, Text, L); Dec(Len, L); Inc(Text, L); if Len > 0 then NewLine(Prn) else Cur.X := Extent.X; end; end; end; { PrnString ------------------------------------------------------ } { Print a string to the printer handling special characters. } procedure PrnString(var Prn: PrnRec; Text: PChar; Len: Integer); var L: Integer; { Temporary used for printing } TabWidth: Word; { Width (in pixels) of a tab } { Flush to the printer the non-specal characters found so far } procedure Flush; begin if L <> 0 then PrnOutStr(Prn, Text, L); Inc(Text, L + 1); Dec(Len, L + 1); L := 0; end; { Calculate the average character width } function AvgCharWidth: Word; var Metrics: TTextMetric; begin GetTextMetrics(Prn.DC, Metrics); AvgCharWidth := Metrics.tmAveCharWidth; end; begin L := 0; with Prn do begin while L < Len do begin case Text[L] of #9: begin Flush; TabWidth := AvgCharWidth * 8; Inc(Cur.X, TabWidth - ((Cur.X + TabWidth + 1) mod TabWidth) + 1); if Cur.X > Finish.X then NewLine(Prn); end; #13: Flush; #10: begin Flush; NewLine(Prn); end; ^L: begin Flush; NewPage(Prn); end; else Inc(L); end; end; end; Flush; end; { PrnInput ------------------------------------------------------- } { Called when a Read or Readln is applied to a printer file. } { Since reading is illegal this routine tells the I/O system that } { no characters where read, which generates a runtime error. } function PrnInput(var F: TTextRec): Integer; far; begin with F do begin BufPos := 0; BufEnd := 0; end; PrnInput := 0; end; { PrnOutput ------------------------------------------------------ } { Called when a Write or Writeln is applied to a printer file. } { The calls PrnString to write the text in the buffer to the } { printer. } function PrnOutput(var F: TTextRec): Integer; far; begin with F do begin PrnString(PrnRec(UserData), PChar(BufPtr), BufPos); BufPos := 0; PrnOutput := PrnRec(UserData).Status; end; end; { PrnIgnore ------------------------------------------------------ } { Will ignore certain requests by the I/O system such as flush } { while doing an input. } function PrnIgnore(var F: TTextRec): Integer; far; begin PrnIgnore := 0; end; { AbortProc ------------------------------------------------------ } { Abort procedure used for printing. } var AbortProcInst: TFarProc; { Instance of the abort proc } function AbortProc(Prn: HDC; Code: Integer): Bool; export; var Msg: TMsg; UserAbort: Boolean; begin UserAbort := IsAborted(Prn); while not UserAbort and PeekMessage(Msg, 0, 0, 0, pm_Remove) do if not ProcessPrnMessage(Msg) then begin TranslateMessage(Msg); DispatchMessage(Msg); end; AbortProc := not UserAbort; end; { PrnClose ------------------------------------------------------- } { Deallocates the resources allocated to the printer file. } function PrnClose(var F: TTextRec): Integer; far; begin with PrnRec(F.UserData) do begin if DC <> 0 then begin if not IsAborted(DC) then begin NewPage(PrnRec(F.UserData)); if Escape(DC, WinTypes.EndDoc, 0, nil, nil) <= 0 then Status := wpPrintingError; end; DeleteDC(DC); UnAbort(DC); end; PrnClose := Status; end; end; { PrnOpen -------------------------------------------------------- } { Called to open I/O on a printer file. Sets up the TTextFile to } { point to printer I/O functions. } function PrnOpen(var F: TTextRec): Integer; far; const Blank: array[0..0] of Char = ''; begin with F, PrnRec(UserData) do begin if Mode = fmInput then begin InOutFunc := @PrnInput; FlushFunc := @PrnIgnore; CloseFunc := @PrnIgnore; end else begin Mode := fmOutput; InOutFunc := @PrnOutput; FlushFunc := @PrnOutput; CloseFunc := @PrnClose; { Setup the DC for printing } Status := Escape(DC, WinTypes.SetAbortProc, 0, PChar(AbortProcInst), nil); if Status > 0 then if Title <> nil then begin Status := Escape(DC, WinTypes.StartDoc, StrLen(Title), Title, nil); StrDispose(Title); end else Status := Escape(DC, WinTypes.StartDoc, 0, @Blank, nil); if Status <= 0 then Status := wpPrintingError else Status := 0; { Initialize the printer record } LongInt(Cur) := 0; Finish.X := GetDeviceCaps(DC, HorzRes); Finish.Y := GetDeviceCaps(DC, VertRes); Height := 0; end; PrnOpen := Status; end; end; { FetchStr ------------------------------------------------------- } { Returns a pointer to the first comma delimited field pointed } { to by Str. It replaces the comma with a #0 and moves the Str } { to the beginning of the next string (skipping white space). } { Str will point to a #0 character if no more strings are left. } { This routine is used to fetch strings out of text retrieved } { from WIN.INI. } function FetchStr(var Str: PChar): PChar; begin FetchStr := Str; if Str = nil then Exit; while (Str^ <> #0) and (Str^ <> ',') do Str := AnsiNext(Str); if Str^ = #0 then Exit; Str^ := #0; Inc(Str); while Str^ = ' ' do Str := AnsiNext(Str); end; { ---------------------------------------------------------------- } { External interface routines ------------------------------------ } { ---------------------------------------------------------------- } { AbortPrn ------------------------------------------------------- } procedure AbortPrn(var F: Text); begin Abort(PrnRec(TTextRec(F).UserData).DC); end; { AssignPrn ------------------------------------------------------ } procedure AssignPrn(var F: Text; Device, Driver, Port: PChar); var DeviceStr: array[0..80] of Char; P: PChar; begin if Device = nil then begin { Get the default printer device } GetProfileString('windows', 'device', '', DeviceStr, SizeOf(DeviceStr) - 1); P := DeviceStr; Device := FetchStr(P); Driver := FetchStr(P); Port := FetchStr(P); end; with TTextRec(F), PrnRec(UserData) do begin Mode := fmClosed; BufSize := SizeOf(Buffer); BufPtr := @Buffer; OpenFunc := @PrnOpen; Name[0] := #0; DC := CreateDC(Driver, Device, Port, nil); if DC = 0 then begin InOutRes := wpInvalidDevice; Exit; end; Title := nil; end; end; { AssignDefPrn --------------------------------------------------- } procedure AssignDefPrn(var F: Text); begin AssignPrn(F, nil, nil, nil); end; { SetPrnFont ----------------------------------------------------- } function SetPrnFont(var F: Text; Font: HFont): HFont; begin SetPrnFont := SelectObject(PrnRec(TTextRec(F).UserData).DC, Font); end; { TitlePrn ------------------------------------------------------- } procedure TitlePrn(var F: Text; Title: PChar); var S: array[0..31] of Char; begin { Limit title size to 31 characters plus 0 } StrLCopy(S, Title, SizeOf(S)); PrnRec(TTextRec(F).UserData).Title := StrNew(S); end; { ---------------------------------------------------------------- } function DummyMsg(var Msg: TMsg): Boolean; far; begin DummyMsg := False; end; var SaveExit: Pointer; { Saves the old ExitProc } procedure ExitWinPrn; far; begin FreeProcInstance(AbortProcInst); ExitProc := SaveExit; end; begin ProcessPrnMessage := DummyMsg; AbortProcInst := MakeProcInstance(@AbortProc, hInstance); SaveExit := ExitProc; ExitProc := @ExitWinPrn; end.
unit LuaSymbolListHandler; {$mode delphi} interface uses Classes, SysUtils, lua, lualib, LuaClass, SymbolListHandler; procedure initializeLuaSymbolListHandler; procedure pushSymbol(L: PLua_state; si: PCESymbolInfo); implementation uses LuaHandler, LuaObject, symbolhandler, ProcessHandlerUnit, NewKernelHandler; function getMainSymbolList(L: Plua_State): integer; cdecl; begin result:=1; luaclass_newClass(L, symhandler.GetMainSymbolList); end; function enumRegisteredSymbolLists(L: Plua_State): integer; cdecl; var list: tlist; i: integer; begin result:=1; list:=tlist.create; symhandler.GetSymbolLists(list); lua_createtable(L,list.count,0); for i:=0 to list.count-1 do begin lua_pushinteger(L,i+1); luaclass_newClass(L,list[i]); lua_settable(L,-3); end; exit(1); end; function createSymbolList(L: Plua_State): integer; cdecl; begin result:=1; luaclass_newClass(L, TSymbolListHandler.create); end; function SymbolList_clear(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; begin sl:=luaclass_getClassObject(L); sl.clear; result:=0; end; function SymbolList_register(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; begin sl:=luaclass_getClassObject(L); symhandler.AddSymbolList(sl); result:=0; end; function SymbolList_unregister(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; begin sl:=luaclass_getClassObject(L); symhandler.RemoveSymbolList(sl); result:=0; end; function SymbolList_getModuleList(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; list: TExtraModuleInfoList; i: integer; begin sl:=luaclass_getClassObject(L); sl.GetModuleList(list); lua_createtable(L, length(list),0); for i:=0 to length(list)-1 do begin lua_pushinteger(L,i+1); lua_createtable(L,0,5); lua_pushstring(L,'modulename'); lua_pushstring(L,pchar(list[i].modulename)); lua_settable(L,-3); lua_pushstring(L,'modulepath'); lua_pushstring(L,pchar(list[i].modulepath)); lua_settable(L,-3); lua_pushstring(L,'baseaddress'); lua_pushinteger(L,list[i].baseaddress); lua_settable(L,-3); lua_pushstring(L,'modulesize'); lua_pushinteger(L,list[i].modulesize); lua_settable(L,-3); lua_pushstring(L,'is64bitmodule'); lua_pushboolean(L,list[i].is64bitmodule); lua_settable(L,-3); lua_settable(L,-3); end; result:=1; end; function SymbolList_getSymbolList(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; list: tstringlist; i: integer; begin sl:=luaclass_getClassObject(L); list:=tstringlist.create; sl.GetSymbolList(list); lua_createtable(L, 0,list.count); for i:=0 to list.count-1 do begin lua_pushstring(L, pchar(list[i])); lua_pushinteger(L, ptruint(list.Objects[i])); lua_settable(L,-3); end; result:=1; list.free; end; procedure pushSymbol(L: PLua_state; si: PCESymbolInfo); var tableindex: integer; begin lua_newtable(L); tableindex:=lua_gettop(L); lua_pushstring(L,'modulename'); lua_pushstring(L,si.module); lua_settable(L, tableindex); lua_pushstring(L,'searchkey'); lua_pushstring(L,si.originalstring); lua_settable(L, tableindex); lua_pushstring(L,'address'); lua_pushinteger(L,si.address); lua_settable(L, tableindex); lua_pushstring(L,'symbolsize'); lua_pushinteger(L,si.size); lua_settable(L, tableindex); end; function SymbolList_GetSymbolFromAddress(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; si: PCESymbolInfo; begin result:=0; sl:=luaclass_getClassObject(L); si:=sl.FindAddress(lua_tointeger(L, 1)); if si<>nil then begin pushSymbol(L, si); result:=1; end; end; function SymbolList_getSymbolFromString(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; si: PCESymbolInfo; begin result:=0; sl:=luaclass_getClassObject(L); si:=sl.FindSymbol(lua_tostring(L, 1)); if si<>nil then begin pushSymbol(L, si); result:=1; end; end; function SymbolList_deleteModule(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; s: string; begin result:=0; sl:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin if lua_isnumber(L,1) then sl.DeleteModule(qword(lua_tointeger(L,1))) else begin s:=Lua_ToString(L,1); sl.DeleteModule(s); end; end; end; function SymbolList_addModule(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; modulename: string; modulepath: string; base: ptruint; size: integer; is64bit: boolean; begin result:=0; sl:=luaclass_getClassObject(L); if lua_gettop(L)>=4 then begin modulename:=Lua_ToString(L,1); modulepath:=Lua_ToString(L,2); base:=lua_tointeger(L,3); size:=lua_tointeger(L,4); if lua_gettop(L)>=5 then is64bit:=lua_toboolean(L,5) else is64bit:=processhandler.is64bit; sl.AddModule(modulename, modulepath, base, size, is64bit); end; end; function SymbolList_addSymbol(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; si: PCESymbolInfo; modulename: string; searchkey: string; address: qword; size: integer; skipAddressToSymbol: boolean; esd: TExtraSymbolData; returntype: string; parameters: string; begin result:=0; sl:=luaclass_getClassObject(L); esd:=nil; if lua_gettop(L)>=4 then //modulename, searchkey, address, symbolsize, skipAddressToSymbol begin modulename:=lua_tostring(L, 1); searchkey:=lua_tostring(L, 2); address:=lua_tointeger(L, 3); size:=lua_tointeger(L, 4); if lua_gettop(L)>=5 then skipAddressToSymbol:=lua_toboolean(L, 5) else skipAddressToSymbol:=false; if lua_gettop(L)>=6 then begin if lua_istable(L, 6) then begin lua_pushstring(L, 'returntype'); lua_gettable(L, 6); returntype:=Lua_ToString(L, -1); lua_pop(L,1); lua_pushstring(L, 'parameters'); lua_gettable(L, 6); parameters:=Lua_ToString(L, -1); lua_pop(L,1); if (returntype<>'') or (parameters<>'') then begin esd:=TExtraSymbolData.create; esd.return:=returntype; esd.simpleparameters:=parameters; esd.filledin:=true; sl.AddExtraSymbolData(esd); end; end; end else parameters:=''; si:=sl.AddSymbol(modulename, searchkey, address, size, skipAddressToSymbol, esd,true); if esd<>nil then esd.free; if si=nil then begin //outputdebugstring('sl.AddSymbol returned nil'); exit(0); end; pushSymbol(L, si); result:=1; end; end; function SymbolList_deleteSymbol(L: Plua_State): integer; cdecl; var sl: TSymbolListHandler; si: PCESymbolInfo; begin result:=0; sl:=luaclass_getClassObject(L); if lua_type(L,1)=LUA_TNUMBER then begin si:=sl.FindAddress(lua_tointeger(L, 1)); if si<>nil then begin if si.extra<>nil then begin sl.RemoveExtraSymbolData(si.extra); si.extra.free; end; sl.DeleteSymbol(lua_tointeger(L, 1)) end; end else begin si:=sl.FindSymbol(lua_tostring(L, 1)); if si<>nil then begin if si.extra<>nil then begin sl.RemoveExtraSymbolData(si.extra); si.extra.free; end; sl.DeleteSymbol(lua_tostring(L, 1)) end; end; end; procedure SymbolList_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'clear', SymbolList_clear); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getSymbolFromAddress', SymbolList_GetSymbolFromAddress); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getSymbolFromString', SymbolList_getSymbolFromString); luaclass_addClassFunctionToTable(L, metatable, userdata, 'addSymbol', SymbolList_addSymbol); luaclass_addClassFunctionToTable(L, metatable, userdata, 'deleteSymbol', SymbolList_deleteSymbol); luaclass_addClassFunctionToTable(L, metatable, userdata, 'addModule', SymbolList_addModule); luaclass_addClassFunctionToTable(L, metatable, userdata, 'deleteModule', SymbolList_deleteModule); luaclass_addClassFunctionToTable(L, metatable, userdata, 'register', SymbolList_register); luaclass_addClassFunctionToTable(L, metatable, userdata, 'unregister', SymbolList_unregister); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getModuleList', SymbolList_getModuleList); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getSymbolList', SymbolList_getSymbolList); end; procedure initializeLuaSymbolListHandler; begin lua_register(LuaVM, 'createSymbolList', createSymbolList); lua_register(LuaVM, 'getMainSymbolList', getMainSymbolList); lua_register(LuaVM, 'enumRegisteredSymbolLists', enumRegisteredSymbolLists); end; initialization luaclass_register(TSymbolListHandler, SymbolList_addMetaData); end.
unit CalcProcs; interface type { A simple array of 16 bytes } T16Bytes = array [0..15] of Byte; type { A 4-dimensional vector of single-precision floating-point values. Very common in 3D applications. } TVector4 = record public X, Y, Z, W: Single; public procedure Init(const AX, AY, AZ, AW: Single); end; procedure AddDelphi(const A, B: T16Bytes; out C: T16Bytes); procedure AddSIMD(const A, B: T16Bytes; out C: T16Bytes); {$IFDEF CPUARM}inline;{$ENDIF} procedure AddAndSaturateDelphi(const A, B: T16Bytes; out C: T16Bytes); procedure AddAndSaturateSIMD(const A, B: T16Bytes; out C: T16Bytes); {$IFDEF CPUARM}inline;{$ENDIF} function DistanceSquaredDelphi(const A, B: TVector4): Single; function DistanceSquaredSIMD(const A, B: TVector4): Single; {$IFDEF CPUARM}inline;{$ENDIF} {$IFDEF CPUARM} const {$IF Defined(ANDROID)} LIB_SIMD = 'libsimd-android.a'; {$ELSEIF Defined(IOS)} LIB_SIMD = 'libsimd-ios.a'; {$ELSE} {$MESSAGE Error 'Unsupported platform'} {$ENDIF} { Import ARM versions from static library. } procedure add_simd(A, B, C: Pointer); cdecl; external LIB_SIMD; procedure add_and_saturate_simd(A, B, C: Pointer); cdecl; external LIB_SIMD; function distance_squared_simd(A, B: Pointer): Single; cdecl; external LIB_SIMD; {$ENDIF} implementation procedure AddDelphi(const A, B: T16Bytes; out C: T16Bytes); var I: Integer; begin for I := 0 to 15 do C[I] := A[I] + B[I]; end; procedure AddAndSaturateDelphi(const A, B: T16Bytes; out C: T16Bytes); var I, Sum: Integer; begin for I := 0 to 15 do begin Sum := A[I] + B[I]; if (Sum > 255) then C[I] := 255 else C[I] := Sum; end; end; function DistanceSquaredDelphi(const A, B: TVector4): Single; var C: TVector4; begin { Subtract the two vectors } C.X := A.X - B.X; C.Y := A.Y - B.Y; C.Z := A.Z - B.Z; C.W := A.W - B.W; { Calculate the dot product of C x C } Result := (C.X * C.X) + (C.Y * C.Y) + (C.Z * C.Z) + (C.W * C.W); end; {$IF Defined(CPUX86)} // Windows 32 bit, macOS, iOS simulator procedure AddSIMD(const A, B: T16Bytes; out C: T16Bytes); // eax edx ecx asm movdqu xmm0, [eax] // Load A into xmm0 movdqu xmm1, [edx] // Load B into xmm1 paddb xmm0, xmm1 // xmm0 := xmm0 + xmm1 (16 times) movdqu [ecx], xmm0 // Store xmm0 into C end; procedure AddAndSaturateSIMD(const A, B: T16Bytes; out C: T16Bytes); // eax edx ecx asm movdqu xmm0, [eax] // Load A into xmm0 movdqu xmm1, [edx] // Load B into xmm1 paddusb xmm0, xmm1 // xmm0 := EnsureRange(xmm0 + xmm1, 0, 255) movdqu [ecx], xmm0 // Store xmm0 into C end; function DistanceSquaredSIMD(const A, B: TVector4): Single; // eax edx asm movups xmm0, [eax] // Load A into xmm0 (as 4 Singles) movups xmm1, [edx] // Load B into xmm1 // Subtract the two vectors subps xmm0, xmm1 // xmm0 := xmm0 - xmm1 (4 times) // Calculate dot product mulps xmm0, xmm0 // W*W Z*Z Y*Y X*X pshufd xmm1, xmm0, $0E // -- -- W*W Z*Z addps xmm0, xmm1 // -- -- (Y*Y + W*W) (X*X + Z*Z) pshufd xmm1, xmm0, $01 // -- -- -- (Y*Y + W*W) addss xmm0, xmm1 // (X*X + Z*Z) + (Y*Y + W*W) movss [Result], xmm0 // Store result in return value end; {$ELSEIF Defined(CPUX64)} // Windows 64 bit procedure AddSIMD(const A, B: T16Bytes; out C: T16Bytes); // rcx rdx r8 asm movdqu xmm0, [rcx] // Load A into xmm0 movdqu xmm1, [rdx] // Load B into xmm1 paddb xmm0, xmm1 // xmm0 := xmm0 + xmm1 (16 times) movdqu [r8], xmm0 // Store xmm0 into C end; procedure AddAndSaturateSIMD(const A, B: T16Bytes; out C: T16Bytes); // rcx rdx r8 asm movdqu xmm0, [rcx] // Load A into xmm0 movdqu xmm1, [rdx] // Load B into xmm1 paddusb xmm0, xmm1 // xmm0 := EnsureRange(xmm0 + xmm1, 0, 255) movdqu [r8], xmm0 // Store xmm0 into C end; function DistanceSquaredSIMD(const A, B: TVector4): Single; // rcx rdx asm movups xmm0, [rcx] // Load A into xmm0 (as 4 Singles) movups xmm1, [rdx] // Load B into xmm1 // Subtract the two vectors subps xmm0, xmm1 // xmm0 := xmm0 - xmm1 (4 times) // Calculate dot product mulps xmm0, xmm0 // W*W Z*Z Y*Y X*X pshufd xmm1, xmm0, $0E // -- -- W*W Z*Z addps xmm0, xmm1 // -- -- (Y*Y + W*W) (X*X + Z*Z) pshufd xmm1, xmm0, $01 // -- -- -- (Y*Y + W*W) addss xmm0, xmm1 // (X*X + Z*Z) + (Y*Y + W*W) movss [Result], xmm0 // Store result in return value end; {$ELSEIF Defined(CPUARM)} // iOS (32/64 bit), Android procedure AddSIMD(const A, B: T16Bytes; out C: T16Bytes); inline; begin add_simd(@A, @B, @C); end; procedure AddAndSaturateSIMD(const A, B: T16Bytes; out C: T16Bytes); inline; begin add_and_saturate_simd(@A, @B, @C); end; function DistanceSquaredSIMD(const A, B: TVector4): Single; inline; begin Result := distance_squared_simd(@A, @B); end; {$ELSE} {$MESSAGE Error 'Unsupported platform'} {$ENDIF} { TVector4 } procedure TVector4.Init(const AX, AY, AZ, AW: Single); begin X := AX; Y := AY; Z := AZ; W := AW; end; end.
unit Calcf; { Author: Michael Ax Copyright (c) 1996 HREF Tools Corp. Written for distribution with _Delphi 2.0 In-Depth_, Cary Jensen, Editor. } (* Permission is hereby granted, on 03-Oct-1996, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, UpdateOk, StdCtrls, TTwoNum, Buttons {component}; type TForm1 = class(TForm) TwoNumbers1: TTwoNumbers; Label1: TLabel; Label2: TLabel; BitBtn1: TBitBtn; procedure FormClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormClick(Sender: TObject); begin TwoNumbers1.Edit; end; procedure TForm1.BitBtn1Click(Sender: TObject); begin close; end; end.
unit EhExtraUnit; interface uses SysUtils, DB, DBGridEh; procedure DeleteGridSelection(Grid: TDBGridEh); procedure SortGridEh(Grid: TDBGridEh; Marker: TSortMarkerEh); procedure RefreshGrid(Grid: TDBGridEh); overload; procedure RefreshGrid(Grid: TDBGridEh; Field: TField); overload; procedure RefreshGrid(Grid: TDBGridEh; const Fields: array of TField); overload; function AssignFieldValue(Param: TParam; Field: TField): Boolean; function AssignParams(Params: TParams; FromChecked: Boolean; FromDate: TDateTime; ToChecked: Boolean; ToDate: TDateTime): Boolean; type TSelectionIteratorEh = procedure (DataSet: TDataSet) of object; TColumnIteratorEh = procedure (Column: TColumnEh) of object; procedure IterateSelectionRecords(Grid: TDBGridEh; Iterator: TSelectionIteratorEh); procedure IterateSelectionColumns(Grid: TDBGridEh; Iterator: TColumnIteratorEh); implementation uses Variants, IBCustomDataSet, IBDatabase; procedure IterateSelectionRecords(Grid: TDBGridEh; Iterator: TSelectionIteratorEh); var DataSet: TDataSet; Bookmark: TBookmarkStr; Rect: TDBGridEhSelectionRect; begin if Grid.DataSource = nil then Exit; DataSet := Grid.DataSource.DataSet; if (DataSet = nil) or (DataSet.Bof and DataSet.Eof) then Exit; if Grid.Selection.SelectionType <> gstRectangle then begin Iterator(DataSet); end else begin DataSet.DisableControls; try Bookmark := DataSet.Bookmark; try Rect := Grid.Selection.Rect; DataSet.Bookmark := Rect.TopRow; while True do begin Iterator(DataSet); if DataSet.CompareBookmarks(PChar(DataSet.Bookmark), PChar(Rect.BottomRow)) = 0 then Break; DataSet.Next; end; finally DataSet.Bookmark := Bookmark; end; finally DataSet.EnableControls; end; end; end; procedure IterateSelectionColumns(Grid: TDBGridEh; Iterator: TColumnIteratorEh); var Rect: TDBGridEhSelectionRect; I, LeftCol, RightCol: Integer; begin if Grid.Columns.Count > 0 then begin if Grid.Selection.SelectionType = gstRectangle then begin Rect := Grid.Selection.Rect; LeftCol := Rect.LeftCol; RightCol := Rect.RightCol; end else begin LeftCol := Grid.Col; RightCol := Grid.Col; end; for I := LeftCol to RightCol do Iterator(Grid.Columns[I]); end; end; function AssignFieldValue(Param: TParam; Field: TField): Boolean; var PV, FV: Variant; begin PV := Param.Value; FV := Field.Value; Result := VarIsNull(PV) or VarIsNull(FV) or (VarType(PV) <> VarType(FV)) or (PV <> FV); if Result then Param.AssignFieldValue(Field, FV); end; function AssignParams(Params: TParams; FromChecked: Boolean; FromDate: TDateTime; ToChecked: Boolean; ToDate: TDateTime): Boolean; var DateFrom, IgnoreFrom, DateTo, IgnoreTo: TParam; begin DateFrom := Params.FindParam('DATE_FROM'); IgnoreFrom := Params.FindParam('IGNORE_FROM'); DateTo := Params.FindParam('DATE_TO'); IgnoreTo := Params.FindParam('IGNORE_TO'); Result := (DateFrom <> nil) and (IgnoreFrom <> nil) and (DateTo <> nil) and (IgnoreTo <> nil); if Result then begin Result := ((IgnoreFrom.AsInteger <> Ord(not FromChecked)) or (FromChecked and (DateFrom.AsDate <> FromDate))) or ((IgnoreTo.AsInteger <> Ord(not ToChecked)) or (ToChecked and (DateTo.AsDate <> ToDate))); IgnoreFrom.AsInteger := Ord(not FromChecked); if FromChecked then DateFrom.AsDate := FromDate else DateFrom.Clear; IgnoreTo.AsInteger := Ord(not ToChecked); if ToChecked then DateTo.AsDate := ToDate else DateTo.Clear; end; end; procedure DeleteGridSelection(Grid: TDBGridEh); var Bookmarks: TBookmarkListEh; I: Integer; begin Bookmarks := Grid.Selection.Rows; if Bookmarks.Count = 0 then begin if not Grid.DataSource.DataSet.Bof or not Grid.DataSource.DataSet.Eof then Grid.DataSource.DataSet.Delete; end else begin for I := 0 to Bookmarks.Count - 1 do begin Grid.DataSource.DataSet.GotoBookmark(Pointer(Bookmarks.Items[I])); Grid.DataSource.DataSet.Delete; end; end; Grid.Selection.Clear; end; procedure SortGridEh(Grid: TDBGridEh; Marker: TSortMarkerEh); begin if dghAutoSortMarking in Grid.OptionsEh then begin Grid.Columns[Grid.Col].Title.SortMarker := Marker; Grid.DefaultApplySorting; end; end; procedure CommitRetainingTransaction(DataSet: TDataSet); var Transaction: TIBTransaction; begin if DataSet is TIBCustomDataSet then begin Transaction := TIBCustomDataSet(DataSet).Transaction; if (Transaction <> nil) and Transaction.Active then Transaction.CommitRetaining; end; end; procedure RefreshGrid(Grid: TDBGridEh); var DataSource: TDataSource; DataSet: TDataSet; Bookmark: Pointer; Col: Integer; begin DataSource := Grid.DataSource; if DataSource <> nil then begin DataSet := DataSource.DataSet; if DataSet <> nil then begin Col := Grid.Col; Bookmark := DataSet.GetBookmark; try DataSet.DisableControls; try DataSet.Close; CommitRetainingTransaction(DataSet); DataSet.Open; Grid.Col := Col; if DataSet.BookmarkValid(Bookmark) then DataSet.GotoBookmark(Bookmark); finally DataSet.EnableControls; end; finally DataSet.FreeBookmark(Bookmark); end; end; end; end; procedure RefreshGrid(Grid: TDBGridEh; Field: TField); var DataSource: TDataSource; DataSet: TDataSet; Value: Variant; Col: Integer; begin DataSource := Grid.DataSource; if DataSource <> nil then begin DataSet := DataSource.DataSet; if DataSet <> nil then begin Col := Grid.Col; Value := Field.Value; DataSet.DisableControls; try DataSet.Close; CommitRetainingTransaction(DataSet); DataSet.Open; Grid.Col := Col; DataSet.Locate(Field.FieldName, Value, []); finally DataSet.EnableControls; end; end; end; end; procedure RefreshGrid(Grid: TDBGridEh; const Fields: array of TField); var DataSource: TDataSource; DataSet: TDataSet; Values: Variant; I, N, Col: Integer; FieldNames: string; Field: TField; begin N := High(Fields); if N = 0 then RefreshGrid(Grid, Fields[0]) else begin DataSource := Grid.DataSource; if DataSource <> nil then begin DataSet := DataSource.DataSet; if DataSet <> nil then begin Col := Grid.Col; Values := VarArrayCreate([0, N], varVariant); FieldNames := ''; for I := 0 to N do begin Field := Fields[I]; if I > 0 then FieldNames := FieldNames + ';'; FieldNames := FieldNames + Field.FieldName; Values[I] := Field.Value; end; DataSet.DisableControls; try DataSet.Close; CommitRetainingTransaction(DataSet); DataSet.Open; Grid.Col := Col; DataSet.Locate(FieldNames, Values, []); finally DataSet.EnableControls; end; end; end; end; end; end.
{ Part of BGRA Controls. Made by third party. For detailed information see readme.txt Site: https://sourceforge.net/p/bgra-controls/ Wiki: http://wiki.lazarus.freepascal.org/BGRAControls Forum: http://forum.lazarus.freepascal.org/index.php/board,46.0.html This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit dtthemedclock; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ExtCtrls, LResources, Forms, Controls, Graphics, Dialogs, DTAnalogCommon, BGRABitmap, BGRABitmapTypes; type { TDTCustomThemedClock } TDTCustomThemedClock = class(TDTBaseAnalogDevice) private FClockFace: TBGRABitmap; FPointerBitmap: TBGRABitmap; FEnabled: boolean; FHoursPointerSettings: TDTPointerSettings; FMinutesPointerSettings: TDTPointerSettings; FPointerCapSettings: TDTPointerCapSettings; FPosition: integer; FSecondsPointerSettings: TDTPointerSettings; FTimer: TTimer; procedure SetHoursPointerSettings(AValue: TDTPointerSettings); procedure SetMinutesPointerSettings(AValue: TDTPointerSettings); procedure SetPointerCapSettings(AValue: TDTPointerCapSettings); procedure SetPosition(AValue: integer); procedure SetSecondsPointerSettings(AValue: TDTPointerSettings); { Private declarations } protected procedure SetEnabled(AValue: boolean); override; { Protected declarations } property SecondsPointerSettings: TDTPointerSettings read FSecondsPointerSettings write SetSecondsPointerSettings; property MinutesPointerSettings: TDTPointerSettings read FMinutesPointerSettings write SetMinutesPointerSettings; property HoursPointerSettings: TDTPointerSettings read FHoursPointerSettings write SetHoursPointerSettings; property PointerCapSettings: TDTPointerCapSettings read FPointerCapSettings write SetPointerCapSettings; property Position: integer read FPosition write SetPosition; property Enabled: boolean read FEnabled write SetEnabled; procedure TimerEvent({%H-}Sender: TObject); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint; override; procedure DrawClock; procedure DrawPointers; end; TDTThemedClock = class(TDTCustomThemedClock) private { Private declarations } protected { Protected declarations } public { Public declarations } published { Public declarations } property SecondsPointerSettings; property MinutesPointerSettings; property HoursPointerSettings; property PointerCapSettings; property ScaleSettings; property Position; property Enabled; end; procedure Register; implementation procedure Register; begin {$I icons\dtthemedclock_icon.lrs} RegisterComponents('BGRA Controls', [TDTThemedClock]); end; { TDTCustomThemedClock } procedure TDTCustomThemedClock.SetPointerCapSettings(AValue: TDTPointerCapSettings); begin if FPointerCapSettings = AValue then Exit; FPointerCapSettings := AValue; DoChange(self); end; procedure TDTCustomThemedClock.SetHoursPointerSettings(AValue: TDTPointerSettings); begin if FHoursPointerSettings = AValue then Exit; FHoursPointerSettings := AValue; DoChange(self); end; procedure TDTCustomThemedClock.SetEnabled(AValue: boolean); begin if FEnabled = AValue then Exit; FEnabled := AValue; FTimer.Enabled := FEnabled; DoChange(self); end; procedure TDTCustomThemedClock.SetMinutesPointerSettings(AValue: TDTPointerSettings); begin if FMinutesPointerSettings = AValue then Exit; FMinutesPointerSettings := AValue; DoChange(self); end; procedure TDTCustomThemedClock.SetPosition(AValue: integer); begin if FPosition = AValue then Exit; FPosition := AValue; DoChange(self); end; procedure TDTCustomThemedClock.SetSecondsPointerSettings(AValue: TDTPointerSettings); begin if FSecondsPointerSettings = AValue then Exit; FSecondsPointerSettings := AValue; DoChange(self); end; procedure TDTCustomThemedClock.TimerEvent(Sender: TObject); begin DrawPointers; DoChange(self); end; constructor TDTCustomThemedClock.Create(AOwner: TComponent); begin inherited Create(AOwner); FSecondsPointerSettings := TDTPointerSettings.Create; FSecondsPointerSettings.OnChange := @DoChange; FMinutesPointerSettings := TDTPointerSettings.Create; FMinutesPointerSettings.OnChange := @DoChange; FHoursPointerSettings := TDTPointerSettings.Create; FHoursPointerSettings.OnChange := @DoChange; FPointerCapSettings := TDTPointerCapSettings.Create; FPointerCapSettings.OnChange := @DoChange; FClockFace := TBGRABitmap.Create; FPointerBitmap := TBGRABitmap.Create; FSecondsPointerSettings.Color := BGRA(255, 81, 81); FSecondsPointerSettings.Length := 80; FSecondsPointerSettings.Thickness := 3; FMinutesPointerSettings.Color := BGRA(199, 199, 173); FMinutesPointerSettings.Length := 80; FMinutesPointerSettings.Thickness := 3; FHoursPointerSettings.Color := BGRA(199, 199, 173); FHoursPointerSettings.Length := 60; FHoursPointerSettings.Thickness := 5; FTimer := TTimer.Create(Self); FTimer.Interval := 1000; FTimer.Enabled := FEnabled; FTimer.OnTimer := @TimerEvent; end; destructor TDTCustomThemedClock.Destroy; begin FSecondsPointerSettings.OnChange:=nil; FSecondsPointerSettings.Free; FMinutesPointerSettings.OnChange:=nil; FMinutesPointerSettings.Free; FHoursPointerSettings.OnChange:=nil; FHoursPointerSettings.Free; FTimer.Enabled:=False; FTimer.OnTimer:=nil; FPointerCapSettings.OnChange:=nil; FPointerCapSettings.Free; FClockFace.Free; FPointerBitmap.Free; inherited Destroy; end; procedure TDTCustomThemedClock.Paint; begin inherited Paint; DrawClock; DrawPointers; FGaugeBitmap.BlendImage(0, 0, FClockFace, boLinearBlend); FGaugeBitmap.BlendImage(0, 0, FPointerBitmap, boLinearBlend); FGaugeBitmap.Draw(Canvas, 0, 0, False); end; procedure TDTCustomThemedClock.DrawClock; var Origin: TDTOrigin; r, i, x, y, xt, yt: integer; begin Origin := Initializebitmap(FClockFace, Width, Height); r := round(Origin.Radius * 0.85); // Draw minor tick marks if ScaleSettings.EnableSubTicks then begin for i := 1 to 60 do begin // Calculate draw from point X := Origin.CenterPoint.x + Round(r * sin(6 * i * Pi / 180)); Y := Origin.CenterPoint.y - Round(r * cos(6 * i * Pi / 180)); // Calculate draw to point xt := Origin.CenterPoint.x + Round((r - ScaleSettings.LengthSubTick) * sin(6 * i * Pi / 180)); yt := Origin.CenterPoint.y - Round((r - ScaleSettings.LengthSubTick) * cos(6 * i * Pi / 180)); FClockFace.DrawLineAntialias(x, y, xt, yt, ScaleSettings.TickColor, ScaleSettings.ThicknessSubTick); end; end; // Draw major tick marks if ScaleSettings.EnableMainTicks then begin for i := 1 to 12 do begin // Calculate draw from point X := Origin.CenterPoint.x + Round(r * sin(30 * i * Pi / 180)); Y := Origin.CenterPoint.y - Round(r * cos(30 * i * Pi / 180)); // Calculate draw to point xt := Origin.CenterPoint.x + Round((r - ScaleSettings.LengthMainTick) * sin(30 * i * Pi / 180)); yt := Origin.CenterPoint.y - Round((r - ScaleSettings.LengthMainTick) * cos(30 * i * Pi / 180)); FClockFace.DrawLineAntialias(x, y, xt, yt, ScaleSettings.TickColor, ScaleSettings.ThicknessMainTick); if ScaleSettings.EnableScaleText then begin FClockFace.FontName := ScaleSettings.TextFont; FClockFace.FontHeight := ScaleSettings.TextSize; FClockFace.FontQuality := fqFineAntialiasing; // Draw text for main ticks xt := Origin.CenterPoint.x + Round(ScaleSettings.TextRadius * sin(30 * i * Pi / 180)); yt := Origin.CenterPoint.y - Round(ScaleSettings.TextRadius * cos(30 * i * Pi / 180)); FClockFace.TextOut(Xt, Yt - (FClockFace.FontHeight / 1.7), IntToStr(i), ScaleSettings.TextColor, taCenter); end; end; end; end; procedure TDTCustomThemedClock.DrawPointers; var Origin: TDTOrigin; {%H-}r: integer; Xs, Ys, Xm, Ym, Xh, Yh: integer; th, tm, ts, tn: word; begin Origin := Initializebitmap(FPointerBitmap, Width, Height); r := round(Origin.Radius * 0.85); //// Convert current time to integer values decodetime(Time, th, tm, ts, tn); //{ Set coordinates (length of arm) for seconds } Xs := Origin.CenterPoint.x + Round(SecondsPointerSettings.Length * Sin(ts * 6 * Pi / 180)); Ys := Origin.CenterPoint.y - Round(SecondsPointerSettings.Length * Cos(ts * 6 * Pi / 180)); //{ Set coordinates (length of arm) for minutes } Xm := Origin.CenterPoint.x + Round(MinutesPointerSettings.Length * Sin(tm * 6 * Pi / 180)); Ym := Origin.CenterPoint.y - Round(MinutesPointerSettings.Length * Cos(tm * 6 * Pi / 180)); //{ Set coordinates (length of arm) for hours } Xh := Origin.CenterPoint.x + Round(HoursPointerSettings.Length * Sin((th * 30 + tm / 2) * Pi / 180)); Yh := Origin.CenterPoint.y - Round(HoursPointerSettings.Length * Cos((th * 30 + tm / 2) * Pi / 180)); FPointerBitmap.DrawLineAntialias(Origin.CenterPoint.x, Origin.CenterPoint.y, xs, ys, SecondsPointerSettings.Color, SecondsPointerSettings.Thickness); FPointerBitmap.DrawLineAntialias(Origin.CenterPoint.x, Origin.CenterPoint.y, xm, ym, MinutesPointerSettings.Color, MinutesPointerSettings.Thickness); FPointerBitmap.DrawLineAntialias(Origin.CenterPoint.x, Origin.CenterPoint.y, xh, yh, HoursPointerSettings.Color, HoursPointerSettings.Thickness); // Draw cap over needle FPointerBitmap.EllipseAntialias(origin.CenterPoint.x, origin.CenterPoint.y, PointerCapSettings.Radius, PointerCapSettings.Radius, PointerCapSettings.EdgeColor, 2, ColorToBGRA(PointerCapSettings.FillColor)); end; end.
unit UFrmMasterPwd; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Registry, CryptMod; Type TDlgPwdMode = (DLG_MASTERPWD, DLG_OLDPWD); type TFrmMasterPwd = class(TForm) BtnSave: TButton; edPwd1: TLabeledEdit; edPwd2: TLabeledEdit; ChBoxStrView: TCheckBox; ChBoxSaveНаrdLink: TCheckBox; procedure BtnSaveClick(Sender: TObject); procedure ChBoxStrViewClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure SaveMasterPassword; procedure ShowModeDlg(DlgMode: TDlgPwdMode); private { Private declarations } Procedure ReadPassword; public Apply: Boolean; DialogMode: TDlgPwdMode; { Public declarations } end; var FrmMasterPwd: TFrmMasterPwd; Reg: Tregistry; implementation USES UFrmMain; {$R *.dfm} procedure TFrmMasterPwd.BtnSaveClick(Sender: TObject); begin if edPwd1.Text = '' then begin ShowMessage('Введите пароль.'); exit; end; case DialogMode of DLG_MASTERPWD: begin if edPwd1.Text <> edPwd2.Text then begin ShowMessage('Веденные пароли не совпадают'); exit; end; MASTER_PASSWORD := edPwd1.Text; SaveMasterPassword; end; DLG_OLDPWD: begin // end; end; Apply := True; Close; end; procedure TFrmMasterPwd.ChBoxStrViewClick(Sender: TObject); begin if ChBoxStrView.Checked then begin edPwd1.PasswordChar := #0; edPwd2.PasswordChar := #0; end else begin edPwd1.PasswordChar := '*'; edPwd2.PasswordChar := '*'; end; end; procedure TFrmMasterPwd.FormClose(Sender: TObject; var Action: TCloseAction); begin edPwd1.Text := ''; edPwd2.Text := ''; end; procedure TFrmMasterPwd.FormCreate(Sender: TObject); begin ReadPassword; end; procedure TFrmMasterPwd.ShowModeDlg(DlgMode: TDlgPwdMode); begin Apply := False; DialogMode := DlgMode; Case DlgMode of DLG_MASTERPWD: begin Height := 230; Caption := 'Мастер пароль'; ChBoxSaveНаrdLink.Visible := True; ChBoxSaveНаrdLink.Checked := False; edPwd2.Show; end; DLG_OLDPWD: begin Height := 160; Caption := 'Пароль'; ChBoxSaveНаrdLink.Visible := False; edPwd1.Text := ''; edPwd2.Hide; end; End; ShowModal; end; procedure TFrmMasterPwd.ReadPassword; var Reg: Tregistry; begin try Reg := Tregistry.Create; Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\CryptoNote', True) then begin G_PWDHASH := Reg.ReadString('PasswordHash'); MASTER_PASSWORD := Reg.ReadString('MasterPassword'); if MASTER_PASSWORD = '' then begin G_PWDHASH := ''; exit; end; MASTER_PASSWORD := DecryptRC4_SHA1(GetKey, MASTER_PASSWORD); if G_PWDHASH = GetMD5Hash(MASTER_PASSWORD) then begin MASTER_PASSWORD := copy(MASTER_PASSWORD, 1, Length(MASTER_PASSWORD) - 16); edPwd1.Text := '********'; edPwd2.Text := '********'; ChBoxSaveНаrdLink.Checked := True; end else begin; G_PWDHASH := ''; MASTER_PASSWORD := ''; edPwd1.Text := ''; edPwd2.Text := ''; end; Reg.CloseKey; end; finally Reg.Free; end; end; procedure TFrmMasterPwd.SaveMasterPassword; var s_rand: AnsiString; PwdHash: AnsiString; i: Integer; begin if ChBoxSaveНаrdLink.Checked then begin try Reg := Tregistry.Create; Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\CryptoNote', True) then begin for i := 1 to 16 do s_rand := s_rand + AnsiChar(Random(255)); PwdHash := GetMD5Hash(MASTER_PASSWORD + s_rand); Reg.WriteString('MasterPassword', EncryptRC4_SHA1(GetKey, MASTER_PASSWORD + s_rand)); Reg.WriteString('PasswordHash', PwdHash); Reg.CloseKey; MessageBox(Handle, PChar('МАСТЕР ПАРОЛЬ сохранен и привязан к компьютеру, ' + ' МАСТЕР ПАРОЛЬ будет действовать пока его не замените.'), PChar(MB_CAPTION), MB_ICONINFORMATION); end; finally Reg.Free; end; end else begin try Reg := Tregistry.Create; Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\CryptoNote', True) then begin Reg.WriteString('MasterPassword', ''); Reg.WriteString('PasswordHash', ''); Reg.CloseKey; MessageBox(Handle, PChar('МАСТЕР ПАРОЛЬ введен и будет действовать пока не закроете программу'), PChar(MB_CAPTION), MB_ICONINFORMATION); end; finally Reg.Free; end end; end; end.
(*====< GLSoundFileOGG.pas >===================================================@br @created(2016-11-16) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(06/11/2017 : Creation ) ) --------------------------------------------------------------------------------@br @bold(Description :)@br L'unité @bold(GLSoundFileOGG) permet le chargement de fichier musicaux au format OGG Vorbis (https://www.xiph.org) par le biais de livrairie externe LibOgg et LibVorbis. Une fois chargé le fichier pourra être joué via le "SoundManager" de disponible de votre choix ------------------------------------------------------------------------------@br Notes : @br Vous trouverez les librairies nécessaire DLL pour Windows 32bits et 64bits dans le dossier "GLScene/Externals" ------------------------------------------------------------------------------@br Credits : @unorderedList( @item (Codé sur une base de GLScene http://www.sourceforge.net/glscene) ) @br ------------------------------------------------------------------------------@br LICENCE : MPL / GPL @br @br *==============================================================================*) unit BZSoundFileOGG; //============================================================================== {$mode objfpc}{$H+} {$i ..\..\bzscene_options.inc} //============================================================================== interface uses Classes, SysUtils, BZClasses, BZSoundSample, // OGG-Vorbis units BZLibOgg, BZLibVorbis, ctypes; Type EBZVorbisFileError = Class(EBZInvalidSoundFile); EBZVorbisLoadError = Class(EBZSoundException); TBZSoundOGGFormat = class (TBZSoundFileIO) private FDataByteLength : Int64; //FOpenALOGGExtension : Boolean; protected Function CheckFormat(): Boolean; override; Procedure LoadFromMemory; override; public Constructor Create(AOwner: TPersistent); Override; Destructor Destroy; Override; class function Capabilities : TBZDataFileCapabilities; override; end; implementation uses BZLogger, BZStreamClasses, BZLibOpenAL, Dialogs; Constructor TBZSoundOGGFormat.Create(AOwner: TPersistent); begin inherited create(AOwner); With DataFormatDesc do begin Name:='OGG'; Desc:='OGG Vorbis File'; FileMask:='*.ogg'; end; FDataByteLength := 0; { FOpenALOGGExtension := alIsExtensionPresent('AL_EXT_vorbis'); oggfile:=TMemoryStream.Create; oggfile.LoadFromFile(’boom.ogg’); AlBufferData(buffer, AL_FORMAT_VORBIS_EXT, oggfile.Memory, oggfile.Size, 44800); oggfile.Free; } end; Destructor TBZSoundOGGFormat.Destroy; begin inherited Destroy; end; class function TBZSoundOGGFormat.Capabilities : TBZDataFileCapabilities; begin Result:=[dfcRead]; end; function TBZSoundOGGFormat.CheckFormat(): Boolean; begin Result := True; End; { VorbisDecoder_ callbacks basé sur le code de Noeska (http://www.noeska.com/doal/tutorials.aspx). } function VorbisDecoder_read_func(ptr: pointer; size, nmemb: csize_t; datasource: pointer): csize_t; cdecl; var ReadCount: Int64; begin if (size = 0) or (nmemb = 0) or (ptr=nil) then begin Result := 0; Exit; end; ReadCount := TBZBufferedStream(DataSource).GetStream.Read(ptr^, Size * nmemb); Assert(ReadCount mod Size = 0); Result := ReadCount div Size; end; function VorbisDecoder_seek_func(datasource: pointer; offset: ogg_int64_t; whence: cint): cint; cdecl; const SEEK_SET = 0; SEEK_CUR = 1; SEEK_END = 2; begin try case whence of SEEK_CUR: TBZBufferedStream(DataSource).Seek(offset, soFromCurrent); SEEK_END: TBZBufferedStream(DataSource).Seek(offset, soFromEnd); SEEK_SET: TBZBufferedStream(DataSource).Seek(offset, soFromBeginning); else raise EBZSoundException.CreateFmt('Invalid VorbisDecoder_seek_func ' + 'whence param: %d', [whence]); end; Result := 0; except Result := -1; end; end; function VorbisDecoder_close_func(DataSource: Pointer): CInt; cdecl; begin Result := 0; end; function VorbisDecoder_tell_func(DataSource: Pointer): CLong;cdecl; begin Result := TBZBufferedStream(DataSource).Position; end; function VorbisErrorString(Code : Integer) : String; begin case Code of OV_EREAD : Result := 'Read from Media.'; OV_ENOTVORBIS : Result := 'Not Vorbis data.'; OV_EVERSION : Result := 'Vorbis version mismatch.'; OV_EBADHEADER : Result := 'Invalid Vorbis header.'; OV_EFAULT : Result := 'Internal logic fault (bug or heap/stack corruption.'; else Result := 'Unknown Ogg error.'; end; end; function VorbisDecode(aStream: TBZBufferedStream; out DataFormat: PtrUInt; out Frequency: LongWord): TMemoryStream; procedure CheckVorbisFileError(Err: CInt; const Event: string); var ErrDescription: string; begin { Liste d'erreurs (http://xiph.org/vorbis/doc/vorbisfile/return.html) } case Err of OV_FALSE: ErrDescription := 'No data available'; OV_HOLE: ErrDescription := 'Vorbisfile encountered missing or corrupt data in the bitstream'; {. Recovery is normally automatic and this return code is for informational purposes only. } OV_EREAD: ErrDescription := 'Read error while fetching compressed data for decode'; OV_EFAULT: ErrDescription := 'Internal inconsistency in decode state'; {. Continuing is likely not possible. } OV_EIMPL: ErrDescription := 'Feature not implemented'; OV_EINVAL: ErrDescription := 'Either an invalid argument, or incompletely initialized argument passed to libvorbisfile call'; OV_ENOTVORBIS: ErrDescription := 'The given file/data was not recognized as Ogg Vorbis data'; OV_EBADHEADER: ErrDescription := 'The file/data is apparently an Ogg Vorbis stream, but contains a corrupted or undecipherable header'; OV_EVERSION: ErrDescription := 'The bitstream format revision of the given stream is not supported'; OV_EBADLINK: ErrDescription := 'The given link exists in the Vorbis data stream, but is not decipherable due to garbacge or corruption'; OV_ENOSEEK: ErrDescription := 'The given stream is not seekable'; else ErrDescription := '(unknown vorbisfile error code)'; end; if Err <> 0 then raise EBZVorbisFileError.CreateFmt('VorbisFile error %d at "%s": %s', [Err, Event, ErrDescription]); end; const BufSize = 1024 * 1024; var OggFile: OggVorbis_File; OggInfo: Pvorbis_info; Callbacks: ov_callbacks; ReadCount: cLong; Res:Integer; Buffer: Pointer; BitStream: cInt; begin //if not VorbisFileInited then // raise EBZVorbisFileError.Create('vorbisfile library is not available, ' + // 'cannot decode OggVorbis file'); Result := TMemoryStream.Create; try Callbacks.read := @VorbisDecoder_read_func; Callbacks.seek := @VorbisDecoder_seek_func; Callbacks.close := @VorbisDecoder_close_func; Callbacks.tell := @VorbisDecoder_tell_func; Res:=0; Buffer := Nil; ReallocMem(Buffer,BufSize); Res:= ov_open_callbacks(aStream, OggFile,nil,0, Callbacks); CheckVorbisFileError(Res,'ov_open_callbacks'); //Result.WriteBuffer(Buffer^, BufSize); OggInfo := ov_info(OggFile, -1); if OggInfo^.channels = 1 then DataFormat := AL_FORMAT_MONO16 else DataFormat := AL_FORMAT_STEREO16; Frequency := OggInfo^.rate; try repeat // ov_read(var vf: OggVorbis_File; buffer: pointer; length: cint; bigendianp: cbool; word: cint; sgned: cbool; bitstream: pcint): clong; ReadCount := ov_read(OggFile, Buffer, BufSize, False,2, True, @BitStream); if ReadCount < 0 then CheckVorbisFileError(ReadCount, 'ov_read'); Result.WriteBuffer(Buffer^, ReadCount); until ReadCount <= 0; finally FreeMem(Buffer); Buffer:=nil; end; ov_clear(OggFile); except FreeAndNil(Result); raise; end; end; procedure TBZSoundOGGFormat.LoadFromMemory; var TmpStream : TMemoryStream; OggStream : TFileStream; Dt : PtrUint; Freq : LongWord; begin Try // OggStream := TFileStream.Create(Self.FullFileName, fmOpenRead); // Self.Memory. TmpStream := VorbisDecode(Self.Memory, dt,freq); //With Sampling do //begin Frequency := Freq; BitsPerSample := 16; Case dt of AL_FORMAT_MONO16 : NbChannels := 1; AL_FORMAT_STEREO16 : NbChannels := 2; else NbChannels := -1; End; // End; FDataByteLength := TmpStream.Size; SetSize(FDataByteLength); //Reallocmem(FSoundData, FDataByteLength); Move(PByte(TmpStream.Memory)^,SoundData^,FDataByteLength); Finally TmpStream.Free; End; End; initialization RegisterSoundFileFormat('ogg', 'OGG Vorbis files', TBZSoundOGGFormat); end.
unit wordpress_terms_model; {$mode objfpc}{$H+} interface uses Classes, SysUtils, database_lib; type { TWordpressTerms } TWordpressTerms = class(TSimpleModel) public constructor Create(const DefaultTableName: string = ''); function GetObjectTerms(const ObjectID: integer; const Taxonomy: array of string): boolean; end; implementation uses common, fastplaz_handler; { TWordpressTerms } constructor TWordpressTerms.Create(const DefaultTableName: string); begin inherited Create('terms'); end; { example: Terms.GetObjectTerms( News['ID'].AsInteger, ['post_tag']); } function TWordpressTerms.GetObjectTerms(const ObjectID: integer; const Taxonomy: array of string): boolean; var i: integer; where: string; begin Result := False; where := ''; for i := Low(Taxonomy) to High(Taxonomy) do begin if where = '' then where := '"' + Taxonomy[i] + '"' else where := where + ',"' + Taxonomy[i] + '"'; end; where := AppData.tablePrefix + 'term_taxonomy.taxonomy IN (' + where + ')'; AddInnerJoin('term_taxonomy', 'term_id', 'terms.term_id', ['count']); AddInnerJoin('term_relationships', 'term_taxonomy_id', 'term_taxonomy.term_taxonomy_id', []); Find([where, AppData.tablePrefix + 'term_relationships.object_id=' + i2s(ObjectID)], AppData.tablePrefix + 'terms.name ASC'); if RecordCount > 0 then Result := True; end; end.
unit Marvin.AulaMulticamada.Controlador.Intf; interface uses uMRVClasses; type IMRVControladorTipoCliente = interface(IMRVInterface) ['{9B75598E-A04F-4879-975A-C0682708B47A}'] procedure Inserir(const AItem: TMRVDadosBase); procedure Excluir(const AItem: TMRVDadosBase); procedure Alterar(const AItem: TMRVDadosBase); function ProcurarItem(const ACriterio, AResultado: TMRVDadosBase): Boolean; function ProcurarItens(const ACriterio: TMRVDadosBase; const AListaResultado: TMRVListaBase; const ASearchOption: TMRVSearchOption): Boolean; function RecuperarItens(const ACriterio: TMRVDadosBase; const AListaResultado: TMRVListaBase; const ASearchOption: TMRVSearchOption): Boolean; end; IMRVControladorCliente = interface(IMRVInterface) ['{9B75598E-A04F-4879-975A-C0682708B47A}'] procedure Inserir(const AItem: TMRVDadosBase); procedure Excluir(const AItem: TMRVDadosBase); procedure Alterar(const AItem: TMRVDadosBase); function ProcurarItem(const ACriterio, AResultado: TMRVDadosBase): Boolean; function ProcurarItens(const ACriterio: TMRVDadosBase; const AListaResultado: TMRVListaBase; const ASearchOption: TMRVSearchOption): Boolean; function RecuperarItens(const ACriterio: TMRVDadosBase; const AListaResultado: TMRVListaBase; const ASearchOption: TMRVSearchOption): Boolean; end; implementation end.
{SWAG=OOP.SWG,Simple Collection Demo;<www.prog.cz/swag/swag>} Program CollectingStuff; Uses Objects; Type Stuff = byte; StuffPtr = ^Stuff; StuffCollection = Object(TCollection) procedure FreeItem(Item:Pointer); virtual; procedure PutItem(var S:TStream;Item:Pointer); virtual; Function GetItem(var S:TStream):Pointer; virtual; end; StuffCollectionPtr = ^StuffCollection; Const RStuffCollection : TStreamRec = (ObjType : $424B; VMTLink : Ofs(TypeOf(StuffCollection)^); Load : @StuffCollection.Load; Store : @StuffCollection.Store); Var StuffArray : StuffCollectionPtr; procedure StuffCollection.FreeItem(Item:Pointer); begin dispose(StuffPtr(Item)); end; procedure StuffCollection.PutItem(var S:TStream;Item:Pointer); begin S.Write(StuffPtr(Item)^,SizeOf(Stuff)); end; Function StuffCollection.GetItem(var S:TStream):Pointer; var p:StuffPtr; Begin new(p); S.Read(p^,SizeOf(Stuff)); GetItem := p; End; Function SayWhat:Char; var s:String; Begin Writeln; if StuffArray <> Nil then Writeln('Current Array has ',StuffArray^.Count,' elements'); Writeln('[1] add stuff [2] remove stuff ', '[3] load stuff [4] store stuff '); Writeln('[5] view stuff [6] view all stuff ', '[7] match stuff (anything else exits))'); Readln(s); if s <> '' then SayWhat := s[1] else SayWhat := #0; End; Procedure AddToStuff; var sp:StuffPtr; b:byte; Begin if StuffArray = Nil then New(StuffArray,init(1,1)); repeat write('enter a byte : '); Readln(b); until ioresult = 0; new(sp); sp^ := b; StuffArray^.insert(sp); End; Procedure DelFromStuff; var w:word; Begin if (StuffArray = nil) or (StuffArray^.count = 0) then exit; repeat write('enter element number to delete : '); readln(w); until (ioresult = 0) and (w < StuffArray^.count); StuffArray^.AtFree(w); End; Procedure NewStuff; var s:string; f:PDosStream; Begin write('Enter the stuff''s file name : '); readln(s); new(f,init(s,StOpenRead)); if f^.status = StOk then begin if StuffArray <> nil then dispose(StuffArray,done); new(StuffArray,load(f^)); end; dispose(f,done); End; Procedure SaveStuff; var s:string; f:PDosStream; Begin write('Enter the stuff''s file name : '); readln(s); new(f,init(s,StCreate)); if f^.status = StOk then begin if StuffArray <> nil then StuffArray^.store(f^); end; dispose(f,done); End; Procedure ShowStuff; var w:word; Begin if (StuffArray = nil) or (StuffArray^.count = 0) then exit; repeat write('enter element number to view : '); readln(w); until (ioresult = 0) and (w < StuffArray^.count); writeln('Element # ',w,' = ',byte(StuffArray^.at(w)^)); End; Procedure AllStuff; Procedure ShowEm(p:StuffPtr); far; begin writeln('Stuff Element = [',byte(p^),']'); end; Begin if (StuffArray <> Nil) and (StuffArray^.count > 0) then StuffArray^.ForEach(@ShowEm); End; Procedure MatchStuff; var b:byte; p:StuffPtr; Function Matches(pb:StuffPtr):boolean; far; Begin Matches := pb^ = b; End; Begin if (StuffArray = Nil) or (StuffArray^.count = 0) then exit; repeat write('enter a byte to match : '); readln(b); until ioresult = 0; p := StuffArray^.FirstThat(@Matches); if p <> nil then writeln('Element ',StuffArray^.indexof(p), ' matches [',byte(p^),']') else writeln('no matches'); End; Procedure DoStuff; var stop:boolean; Begin stop := false; While not stop do Case SayWhat of '1' : AddToStuff; '2' : DelFromStuff; '3' : NewStuff; '4' : SaveStuff; '5' : ShowStuff; '6' : AllStuff; '7' : MatchStuff; else stop := true; end; End; var m:longint; begin m := memavail; registerType(RStuffCollection); StuffArray := Nil; DoStuff; if StuffArray <> Nil then Dispose(StuffArray,Done); if m <> memavail then writeln('heap ''a trouble'); end.
unit fmMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ActnList, Menus, ImgList, StdCtrls, ToolWin, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ADODB, cxMemo, cxCheckBox, hcDeployment, cxBlobEdit, Vcl.ExtCtrls, Vcl.Buttons, cxNavigator, System.ImageList, System.Actions, dxDateRanges, dxScrollbarAnnotations; type TfrmMain = class(TForm) mm1: TMainMenu; File1: TMenuItem; Exit1: TMenuItem; N3: TMenuItem; Help1: TMenuItem; Contents1: TMenuItem; SearchforHelpOn1: TMenuItem; HowtoUseHelp1: TMenuItem; About1: TMenuItem; CreateDeployment1: TMenuItem; mnuDeployments: TMenuItem; actlst1: TActionList; actExitApp: TAction; actCreateUpdate: TAction; actManageUpdate: TAction; Manage1: TMenuItem; tlbMain: TToolBar; cbUpdates: TComboBox; la1: TLabel; la2: TLabel; cbApps: TComboBox; tvGrid1DBTableView1: TcxGridDBTableView; lvGrid1Level1: TcxGridLevel; grd1: TcxGrid; statMain: TStatusBar; btnRefresh: TToolButton; btn2: TToolButton; il1: TImageList; qryLocationDeployment: TADOQuery; dsDeployments: TDataSource; colStudioNumber: TcxGridDBColumn; colIsAvailable: TcxGridDBColumn; colAvailableDate: TcxGridDBColumn; colLastAttempt: TcxGridDBColumn; colUpdateResult: TcxGridDBColumn; colUpdateLog: TcxGridDBColumn; actRefresh: TAction; colReceivedDate: TcxGridDBColumn; chkAutoRefresh: TCheckBox; tmrRefresh: TTimer; pmDeploymentItem: TPopupMenu; UnSelect1: TMenuItem; actlstDeploymentItem: TActionList; actUnSelect: TAction; qryWorker: TADOQuery; colStudioGUID: TcxGridDBColumn; btnRecall: TSpeedButton; btnNotes: TSpeedButton; mnuMarkAsSuccessful: TMenuItem; actMarkAsSuccessful: TAction; actMarkAsNotReceived: TAction; MarkAsNotReceived1: TMenuItem; actMarkAsAvailable: TAction; MarkAsAvailable1: TMenuItem; actMarkAsUnAvailable: TAction; MarkAsUnAvailable1: TMenuItem; procedure About1Click(Sender: TObject); procedure actExitAppExecute(Sender: TObject); procedure actCreateUpdateExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cbAppsChange(Sender: TObject); procedure FormResize(Sender: TObject); procedure actManageUpdateExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure cbUpdatesChange(Sender: TObject); procedure actManageUpdateUpdate(Sender: TObject); procedure tmrRefreshTimer(Sender: TObject); procedure chkAutoRefreshClick(Sender: TObject); procedure actUnSelectUpdate(Sender: TObject); procedure actUnSelectExecute(Sender: TObject); procedure btnRecallClick(Sender: TObject); procedure btnNotesClick(Sender: TObject); procedure actMarkAsSuccessfulUpdate(Sender: TObject); procedure actMarkAsSuccessfulExecute(Sender: TObject); procedure actMarkAsNotReceivedExecute(Sender: TObject); procedure actMarkAsNotReceivedUpdate(Sender: TObject); procedure tvGrid1DBTableView1TcxGridDBDataControllerTcxDataSummaryFooterSummaryItems0GetText( Sender: TcxDataSummaryItem; const AValue: Variant; AIsFooter: Boolean; var AText: string); procedure qryLocationDeploymentAfterOpen(DataSet: TDataSet); procedure actMarkAsAvailableExecute(Sender: TObject); procedure actMarkAsUnAvailableExecute(Sender: TObject); private FActiveDeployments :ThcActiveDeploymentList; procedure LoadUpdatesForApplication; procedure ShowCurrentStatusForUpdate; function SelectedUpdate :ThcDeployment; procedure LoadUpdateVersionCombo; public end; var frmMain: TfrmMain; implementation uses dmADO, hcQueryIntf, hcCodesiteHelper, fmAbout, fmDeployment, hcTypes, fmSelectStudios, hcUpdateConsts, hcObjectList, System.IOUtils, System.UITypes, fmEditNotes, Xml.XMLDoc, Xml.XMLIntf; {$R *.dfm} procedure TfrmMain.About1Click(Sender: TObject); begin TfrmAbout.Execute; end; procedure TfrmMain.actCreateUpdateExecute(Sender: TObject); var NewDeployment :ThcDeployment; VersionRec :TVersionRec; begin NewDeployment := ThcDeployment.Create(nil); NewDeployment.FactoryPool := dtmADO.hcFactoryPool; NewDeployment.Initialize; //default the new version to be 1 higher than the highest Version if FActiveDeployments.Count > 0 then begin VersionRec := ParseVersionInfo(ThcDeployment(FActiveDeployments.Items[0]).UpdateVersion.AsString); VersionRec.Build := VersionRec.Build + 1; with VersionRec do NewDeployment.UpdateVersion.AsString := Format('%d.%d.%d.%d',[Major,Minor,Release,Build]); end; if TfrmDeployment.Execute(NewDeployment) then begin //add the deployment to our list and make it the current one. FActiveDeployments.AddExternalObject(NewDeployment); FActiveDeployments.SortByVersion(stDescending); LoadUpdateVersionCombo; cbUpdates.ItemIndex := cbUpdates.Items.IndexOfObject(NewDeployment); ShowCurrentStatusForUpdate; end else NewDeployment.Release; end; procedure TfrmMain.actExitAppExecute(Sender: TObject); begin Close; end; procedure TfrmMain.actManageUpdateExecute(Sender: TObject); begin if (SelectedUpdate <> nil) and TfrmSelectStudios.Execute(SelectedUpdate) then actRefresh.Execute; end; procedure TfrmMain.actManageUpdateUpdate(Sender: TObject); begin actManageUpdate.Enabled := SelectedUpdate <> nil; end; procedure TfrmMain.actMarkAsUnAvailableExecute(Sender: TObject); begin with qryWorker do begin SQL.Text := Format('update LocationDeployment set AvailableUTCDate = NULL, IsAvailable = 0 where LocationGUID = ''%s'' and DeploymentGUID = ''%s'' ',[qryLocationDeployment.FieldByName('LocationGUID').AsString,qryLocationDeployment.FieldByName('DeploymentGUID').AsString]); ExecSQL; btnRefresh.Click; end; end; procedure TfrmMain.actMarkAsAvailableExecute(Sender: TObject); begin with qryWorker do begin SQL.Text := Format('update LocationDeployment set AvailableUTCDate = getdate(), IsAvailable = 1 where LocationGUID = ''%s'' and DeploymentGUID = ''%s'' ',[qryLocationDeployment.FieldByName('LocationGUID').AsString,qryLocationDeployment.FieldByName('DeploymentGUID').AsString]); ExecSQL; btnRefresh.Click; end; end; procedure TfrmMain.actMarkAsNotReceivedExecute(Sender: TObject); begin with qryWorker do begin SQL.Text := Format('update LocationDeployment set ReceivedUTCDate = null where LocationGUID = ''%s'' and DeploymentGUID = ''%s'' ',[qryLocationDeployment.FieldByName('LocationGUID').AsString,qryLocationDeployment.FieldByName('DeploymentGUID').AsString]); ExecSQL; btnRefresh.Click; end; end; procedure TfrmMain.actMarkAsNotReceivedUpdate(Sender: TObject); begin //only allow the user to reset the received date if there has been no attempt to apply the update which will only happen if the update was not actually received or if the Launcher was not run //this should only be used if the update was not actually received by the client actManageUpdate.Enabled := not(qryLocationDeployment.FieldByName('ReceivedUTCDate').IsNull) and (qryLocationDeployment.FieldByName('LastAttemptUTCDate').IsNull); end; procedure TfrmMain.actMarkAsSuccessfulExecute(Sender: TObject); begin with qryWorker do begin SQL.Text := Format('update StudioDeployment set LastAttemptUTCDate = getdate(), UpdateResult = ''Success'', UpdateLog = ''Manually Updated'' where StudioGUID = (Select StudioGUID from Studio where StudioNumber = %d) and DeploymentGUID = ''%s'' ',[qryLocationDeployment.FieldByName('StudioNumber').AsInteger,qryLocationDeployment.FieldByName('DeploymentGUID').AsString]); ExecSQL; btnRefresh.Click; end; end; procedure TfrmMain.actMarkAsSuccessfulUpdate(Sender: TObject); begin //if the studio received the update we can mark it as applied successfully (in case an error occurred and it was manually updated) if (qryLocationDeployment.FieldByName('IsAvailable').AsBoolean) and not(qryLocationDeployment.FieldByName('ReceivedUTCDate').IsNull) then begin {$ifdef FABUTAN} actMarkAsSuccessful.Caption := Format('Mark Update as Applied to Studio %d',[qryLocationDeployment.FieldByName('StudioNumber').AsInteger]); {$else} actMarkAsSuccessful.Caption := Format('Mark Update as Applied to Location: %s',[qryLocationDeployment.FieldByName('Location').AsString]); {$endif} actMarkAsSuccessful.Enabled := True; end else begin actMarkAsSuccessful.Caption := 'Mark Update as Applied'; actMarkAsSuccessful.Enabled := False; end; end; procedure TfrmMain.actRefreshExecute(Sender: TObject); begin ShowCurrentStatusForUpdate; end; procedure TfrmMain.actUnSelectExecute(Sender: TObject); begin with qryWorker do begin SQL.Text := Format('update StudioDeployment set IsAvailable = 0, AvailableUTCDate = null where StudioGUID = (Select StudioGUID from Studio where StudioNumber = %d) and DeploymentGUID = ''%s'' ',[qryLocationDeployment.FieldByName('StudioNumber').AsInteger,qryLocationDeployment.FieldByName('DeploymentGUID').AsString]); ExecSQL; btnRefresh.Click; end; end; procedure TfrmMain.actUnSelectUpdate(Sender: TObject); begin actUnSelect.Enabled := (tvGrid1DBTableView1.Controller.SelectedRecordCount = 1) and (tvGrid1DBTableView1.Controller.SelectedRecords[0].Values[colReceivedDate.Index] = Null) and (tvGrid1DBTableView1.Controller.SelectedRecords[0].Values[colIsAvailable.Index] = True) end; procedure TfrmMain.btnNotesClick(Sender: TObject); //display the change notes associated with this release var dlg :TfrmEditNotes; XMLDoc :IXMLDocument; iRootNode :IXMLNode; sFilePath :string; begin dlg := TfrmEditNotes.Create(Self); try dlg.Notes := SelectedUpdate.WhatsNew.AsString; dlg.Caption := Format('Notes for %s', [SelectedUpdate.UpdateVersion.AsString]); if dlg.ShowModal = mrOK then begin SelectedUpdate.WhatsNew.AsString := dlg.Notes; SelectedUpdate.WhatsNew.Write(osRDBMS,False); //see if we need to update the manifest if dlg.chkUpdateManifest.Checked then begin sFilePath := IncludeTrailingPathDelimiter(dtmADO.UpdateServerPath) + SelectedUpdate.UpdateVersion.AsString + '\'; //slProgress.Add('Loading and Processing Existing Manifest'); XMLDoc := TXMLDocument.Create(nil); try XMLDoc.LoadFromFile(sFilePath + ManifestFileName); XMLDoc.Active := True; iRootNode := XMLDoc.ChildNodes.First; iRootNode.Attributes['WhatsNew'] := SelectedUpdate.WhatsNew.AsString; XMLDoc.SaveToFile(sFilePath + ManifestFileName); finally XMLDoc := nil; end; end; end; finally dlg.Free; end; end; procedure TfrmMain.btnRecallClick(Sender: TObject); { Recall the update from all studios that have received it. Takes advantage of the shares available for each studio to delete the update folder (ie 3.2.1.4) from the Updates\Pending folder. } var sUpdateFolder :string; SaveCursor :TCursor; begin if MessageDlg('This will recall the update from all studios who have not yet applied it. The update will be removed from their hard drive and marked in the database as not available and not received. Are you sure you want to recall it?',mtConfirmation,mbYesNo,0) = mrYes then begin //make sure AutoRefresh is off if chkAutoRefresh.Checked then chkAutoRefreshClick(chkAutoRefresh); SaveCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try with qryLocationDeployment do begin First; while not EOF do begin sUpdateFolder := Format('\\studio%d\Studsoft\studio\Updates\Pending\%s',[FieldByName('StudioNumber').AsInteger,ThcDeployment(cbUpdates.Items.Objects[cbUpdates.ItemIndex]).UpdateVersion.AsString]); if TDirectory.Exists(sUpdateFolder) then begin TDirectory.Delete(sUpdateFolder,True); //mark the update as recalled (never received and not available) qryWorker.SQL.Text := Format('update LocationDeployment set ReceivedUTCDate = null, AvailableUTCDate = null, IsAvailable = 0 where StudioGUID = (Select StudioGUID from Studio where StudioNumber = %d) and DeploymentGUID = ''%s'' ',[FieldByName('StudioNumber').AsInteger,FieldByName('DeploymentGUID').AsString]); qryWorker.ExecSQL; end; Application.ProcessMessages; Next; end; end; finally Screen.Cursor := saveCursor; end; end; end; procedure TfrmMain.cbAppsChange(Sender: TObject); begin LoadUpdatesForApplication; end; procedure TfrmMain.cbUpdatesChange(Sender: TObject); begin ShowCurrentStatusForUpdate; end; procedure TfrmMain.chkAutoRefreshClick(Sender: TObject); begin tmrRefresh.Enabled := chkAutoRefresh.Checked; end; procedure TfrmMain.FormCreate(Sender: TObject); begin {$ifdef FABUTAN} actUnSelect.Visible := True; actMarkAsSuccessful.Visible := True; actMarkAsNotReceived.Visible := True; actManageUpdate.Visible := True; colStudioNumber.Caption := 'Studio'; TcxGridDBColumn(colStudioNumber).DataBinding.FieldName := 'StudioNumber'; Caption := 'Manage Studio Updates'; qryLocationDeployment.SQL.Text := 'SELECT '+ 's.StudioNumber '+ ',s.StudioGUID '+ ',DeploymentGUID '+ ',IsAvailable '+ ',dateadd(hour, datediff(hour, getutcdate(), getdate()),ReceivedUTCDate) as ReceivedUTCDate '+ ',dateadd(hour, datediff(hour, getutcdate(), getdate()),UpdatedUTCDate) as UpdatedUTCDate '+ ',dateadd(hour, datediff(hour, getutcdate(), getdate()),LastAttemptUTCDate) as LastAttemptUTCDate '+ ',UpdateResult '+ ',UpdateLog '+ ',dateadd(hour, datediff(hour, getutcdate(), getdate()),AvailableUTCDate) as AvailableUTCDate '+ 'FROM LocationDeployment sd '+ 'inner join studio s on s.StudioGUID = sd.StudioGUID '+ 'where DeploymentGUID = :DeploymentGUID '+ 'and s.IsActive = 1 '+ 'order by StudioNumber asc '; //the ability to recall a release requires a Fabutan specific share on a Virtual Private Network btnRecall.Visible := True; //the ability to update the notes for a release manifest requires access to the Update server's folder btnNotes.Visible := True; chkAutoRefresh.Visible := False; {$ELSE} actUnSelect.Visible := False; actMarkAsSuccessful.Visible := False; // actMarkAsNotReceived.Visible := False; actManageUpdate.Visible := False; chkAutoRefresh.Visible := False; //the ability to recall a release requires a Fabutan specific share on a Virtual Private Network btnRecall.Visible := False; //the ability to update the notes for a release manifest requires access to the Update server's folder btnNotes.Visible := False; colStudioNumber.Caption := 'Location'; TcxGridDBColumn(colStudioNumber).DataBinding.FieldName := 'Location'; Caption := 'Manage Location Updates'; qryLocationDeployment.SQL.Text := 'SELECT '+ 'l.Description as Location '+ ',l.LocationGUID '+ ',DeploymentGUID '+ ',IsAvailable '+ ',dateadd(hour, datediff(hour, getutcdate(), getdate()),ReceivedUTCDate) as ReceivedUTCDate '+ ',dateadd(hour, datediff(hour, getutcdate(), getdate()),UpdatedUTCDate) as UpdatedUTCDate '+ ',dateadd(hour, datediff(hour, getutcdate(), getdate()),LastAttemptUTCDate) as LastAttemptUTCDate '+ ',UpdateResult '+ ',UpdateLog '+ ',dateadd(hour, datediff(hour, getutcdate(), getdate()),AvailableUTCDate) as AvailableUTCDate '+ 'FROM LocationDeployment ld '+ 'inner join Location L on l.LocationGUID = ld.LocationGUID '+ 'where DeploymentGUID = :DeploymentGUID '+ // 'and l.IsActive = 1 '+ 'order by Location asc '; {$ENDIF} dtmADO.LoadRegisteredApplications(cbApps.Items); cbApps.ItemIndex := 0; //we're guaranteed to have at least 1 app LoadUpdatesForApplication; ShowCurrentStatusForUpdate; statMain.Panels[0].Text := dtmADO.DataSource; chkAutoRefresh.Checked := False; // chkAutoRefresh.Checked := True; // chkAutoRefreshClick(Self); //start autorefresh end; function TfrmMain.SelectedUpdate: ThcDeployment; begin if cbUpdates.ItemIndex <> -1 then Result := ThcDeployment(cbUpdates.Items.Objects[cbUpdates.ItemIndex]) else Result := nil; end; procedure TfrmMain.ShowCurrentStatusForUpdate; begin if (SelectedUpdate <> nil) then begin qryLocationDeployment.Close; qryLocationDeployment.Parameters.ParamByName('DeploymentGUID').Value := SelectedUpdate.DeploymentGUID.AsString; qryLocationDeployment.Open; end; end; procedure TfrmMain.tmrRefreshTimer(Sender: TObject); begin btnRefresh.Click; end; procedure TfrmMain.tvGrid1DBTableView1TcxGridDBDataControllerTcxDataSummaryFooterSummaryItems0GetText( Sender: TcxDataSummaryItem; const AValue: Variant; AIsFooter: Boolean; var AText: string); begin AText := Format('Total: %s',[AText]); end; procedure TfrmMain.FormResize(Sender: TObject); begin //simulate alClient alignment for grid (align to client doesn't work) grd1.Top := tlbMain.Height; grd1.Height := ClientHeight - statMain.Height - tlbMain.Height; grd1.Width := ClientWidth; end; procedure TfrmMain.LoadUpdateVersionCombo; var I: Integer; begin cbUpdates.Items.Clear; for I := 0 to FActiveDeployments.Count - 1 do cbUpdates.Items.AddObject(ThcDeployment(FActiveDeployments[I]).UpdateVersion.AsString,ThcDeployment(FActiveDeployments[I])); if cbUpdates.Items.Count > 0 then cbUpdates.ItemIndex := 0 else cbUpdates.Text := '<None>'; end; procedure TfrmMain.qryLocationDeploymentAfterOpen(DataSet: TDataSet); begin {$ifdef FABUTAN} statMain.Panels[1].Text := Format('Total # of Studios: %d ',[qryLocationDeployment.RecordCount]); {$ELSE} statMain.Panels[1].Text := Format('Total # of Locations: %d ',[qryLocationDeployment.RecordCount]); {$ENDIF} end; procedure TfrmMain.LoadUpdatesForApplication; { Loads updates for currently selected application, excluding any updates that are marked as complete in order of the most recent Update Version first, which is the default. } begin FActiveDeployments := ThcActiveDeploymentList.Create; FActiveDeployments.FactoryPool := dtmADO.hcFactoryPool; // if cbApps.ItemIndex = -1 then // begin // ShowMessage('No Applications are Registered'); // Halt(0); // end; FActiveDeployments.ApplicationGUID := TRegisteredApp(cbApps.Items.Objects[cbApps.ItemIndex]).GUID; FActiveDeployments.Load; FActiveDeployments.SortByVersion(stDescending); LoadUpdateVersionCombo; end; end.
unit rpc.ControlRemoteWindowProtocol; interface uses dco.framework.Executor; type TControlRemoteWindowProtocol = class public type Iface = interface procedure ResizeWindow(Width: Cardinal; Height: Cardinal); end; public type TClient = class(TInterfacedObject, Iface) private FExecutor: IExecutor; public constructor Create(const Executor: IExecutor); reintroduce; destructor Destroy; override; protected // Iface procedure ResizeWindow(Width: Cardinal; Height: Cardinal); end; end; implementation uses System.SysUtils, superobject, dco.framework.Command; constructor TControlRemoteWindowProtocol.TClient.Create(const Executor: IExecutor); begin assert(Executor <> nil); inherited Create; FExecutor := Executor; end; destructor TControlRemoteWindowProtocol.TClient.Destroy; begin FExecutor := nil; inherited; end; procedure TControlRemoteWindowProtocol.TClient.ResizeWindow(Width: Cardinal; Height: Cardinal); var Params: ISuperObject; ResponseContainer: ISuperObject; begin // Prepare parameters Params := SO; Params.I['Width'] := Width; Params.I['Height'] := Height; try ResponseContainer := FExecutor.ExecuteAwait('ResizeWindow', Params); // Do validation optionally except on E: Exception do raise EExternalException.Create(E.ToString); end; end; end.
unit RRManagerReportForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, FramesWizard, RRManagerReportFrame, RRManagerSelectReportingDataFrame, RRManagerReport, RRManagerWaitForReportFrame, RRManagerBaseGUI; type // TfrmReport = class(TForm) TfrmReport = class(TCommonForm) DialogFrame1: TDialogFrame; procedure FormActivate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); private { Private declarations } FAfterHide: TNotifyEvent; protected function GetDlg: TDialogFrame; override; function GetEditingObjectName: string; override; procedure OnFinishClick(Sender: TObject); procedure OnCancelClick(Sender: TObject); public { Public declarations } property AfterHide: TNotifyEvent read FAfterHide write FAfterHide; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmReport: TfrmReport; implementation {$R *.DFM} { TfrmReport } constructor TfrmReport.Create(AOwner: TComponent); var actn: TBaseAction; begin inherited; actn := TReportTablesBaseLoadAction.Create(Self); actn.Execute; dlg.CloseAfterFinish := false; dlg.AddFrame(TfrmSelectReport); dlg.AddFrame(TfrmSelectReportingData); dlg.AddFrame(TfrmWaitForReport); dlg.OnFinishClick := OnFinishClick; dlg.OnCancelClick := OnCancelClick; dlg.FinishEnableIndex := 2; end; destructor TfrmReport.Destroy; begin inherited; end; function TfrmReport.GetDlg: TDialogFrame; begin Result := DialogFrame1; end; procedure TfrmReport.FormActivate(Sender: TObject); begin (dlg.Frames[0] as TfrmSelectReport).Reload; end; function TfrmReport.GetEditingObjectName: string; begin Result := 'Отчёт о структуре'; end; procedure TfrmReport.FormShow(Sender: TObject); begin AllOpts.Push; end; procedure TfrmReport.FormHide(Sender: TObject); begin AllOpts.Pop; if Assigned(FAfterHide) then FAfterHide(Sender); end; procedure TfrmReport.OnFinishClick(Sender: TObject); begin // выдача отчета frmReport.Save; end; procedure TfrmReport.OnCancelClick(Sender: TObject); begin Close; end; end.
{Implementación de Colas con Arreglos (Circular).} {Maximiliano Sosa; Ricardo Quesada; Gonzalo J. García} unit Ucolas2; interface uses Udatos; const MaxCola = 20; type TipoCola = record frente, final: integer; elementos: array[1..MaxCola] of TipoDato; end; function PosSig(i: integer): integer; function ColaVacia(C: TipoCola): boolean; function ColaLlena(C: TipoCola): boolean; procedure CrearCola(var C: TipoCola); procedure SacarDeCola(var C: TipoCola; var x: TipoDato); procedure PonerEnCola(var C: TipoCola; x: TipoDato); implementation function PosSig(i: integer): integer; begin PosSig := (i Mod MaxCola) + 1 end; procedure CrearCola(var C: TipoCola); begin C.frente := 1; C.final := MaxCola; end; function ColaVacia(C: TipoCola): boolean; begin ColaVacia := PosSig(C.final) = C.frente; end; function ColaLlena(C: TipoCola): boolean; begin ColaLlena := PosSig(PosSig(C.final)) = C.frente; end; procedure SacarDeCola(var C: TipoCola; var x: TipoDato); begin x := C.elementos[C.frente]; C.frente := PosSig(C.frente); end; procedure PonerEnCola(var C: TipoCola; x: TipoDato); begin C.final := PosSig(C.final); C.elementos[C.final] := x; end; end.
{******************************************************************************} { } { CreateDirs - Create Directories } { Unit principal do programa. } { } { Copyright (c) 1999 Fernando J.A. Silva (aka ^Magico^) } { } { Todos os direitos reservados } { } {******************************************************************************} unit frmMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, BrowseDr; type TWndMain = class(TForm) BtnCreate: TButton; MemoDirectories: TMemo; LabelDirectories: TLabel; LabelParent: TLabel; EditDir: TEdit; BtnBrowse: TButton; LabelLast: TLabel; RichEditResults: TRichEdit; BrowseDirectoryDlg: TBrowseDirectoryDlg; procedure BtnCreateClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CreateParams(var Params: TCreateParams); override; procedure BtnBrowseClick(Sender: TObject); private { Private declarations } procedure Animate(var Msg: TWMSYSCOMMAND); message WM_SYSCOMMAND; public { Public declarations } end; var WndMain: TWndMain; implementation {$R *.DFM} procedure TWndMain.BtnCreateClick(Sender: TObject); procedure Imprime(Directory: string; Tipo: string); begin if Tipo = 'RED' then begin RichEditResults.SelAttributes.Color := clRed; RichEditResults.SelAttributes.Style := [fsBold]; RichEditResults.Lines.Add('NOT Created '); RichEditResults.SelAttributes.Style := []; RichEditResults.Lines.Append(Directory); end; if Tipo = 'GREEN' then begin RichEditResults.SelAttributes.Color := clLime; RichEditResults.SelAttributes.Style := [fsBold]; RichEditResults.Lines.Add('Created '); RichEditResults.SelAttributes.Style := []; RichEditResults.Lines.Append(Directory); end; if Tipo = 'YELLOW' then begin RichEditResults.SelAttributes.Color := clYellow; RichEditResults.SelAttributes.Style := [fsBold]; RichEditResults.Lines.Add('Directory already exists '); RichEditResults.SelAttributes.Style := []; RichEditResults.Lines.Append(Directory); end; end; var I: Integer; Criado: Boolean; TempDir: string; begin EditDir.Enabled := FALSE; BtnBrowse.Enabled := FALSE; MemoDirectories.Enabled := FALSE; BtnCreate.Enabled := FALSE; RichEditResults.Lines.Clear; if (EditDir.Text <> '') and DirExists(EditDir.Text) then begin TempDir := EditDir.Text; if TempDir[Length(TempDir)] <> '\' then TempDir := TempDir + '\'; for I := 0 to MemoDirectories.Lines.Count - 1 do begin Criado := CreateDir(TempDir + MemoDirectories.Lines.Strings[I]); if not Criado then if DirExists(TempDir + MemoDirectories.Lines.Strings[I]) then Imprime(TempDir + MemoDirectories.Lines.Strings[I], 'YELLOW') else Imprime(TempDir + MemoDirectories.Lines.Strings[I], 'RED') else Imprime(TempDir + MemoDirectories.Lines.Strings[I], 'GREEN') end end else MessageDlg('Invalid parent directory.', mtError, [mbOK], 0); EditDir.Enabled := TRUE; BtnBrowse.Enabled := TRUE; MemoDirectories.Enabled := TRUE; BtnCreate.Enabled := TRUE; end; procedure TWndMain.FormCreate(Sender: TObject); begin Windows.SetParent(WndMain.Handle, GetDesktopWindow); // Used to animate form end; procedure TWndMain.Animate(var Msg: TWMSYSCOMMAND); begin Msg.Result := DefWindowProc(Handle, WM_SYSCOMMAND, TMESSAGE(Msg).wParam, TMESSAGE(Msg).lParam); end; procedure TWndMain.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.WndParent := 0; end; procedure TWndMain.BtnBrowseClick(Sender: TObject); begin if BrowseDirectoryDlg.Execute then EditDir.Text := BrowseDirectoryDlg.Selection; end; end.
unit eMediaFile; interface uses API_Files, eAudioAlbum, eAudioArtist, eAudioFile, eAudioStream, eAudioTrack, eVideoFile, eVideoMovie, eVideoStream, System.Generics.Collections; type TMediaLibList = class private FAudioList: TAudioList; FVideoList: TVideoList; public constructor Create; destructor Destroy; override; property AudioList: TAudioList read FAudioList; property VideoList: TVideoList read FVideoList; end; TID3v1 = record public Album: string; Artist: string; Comment: string; Genre: string; Title: string; Track: string; Year: Integer; procedure Load(const aPath: string); procedure Save(const aPath: string); end; TID3v2 = record public Album: string; AlbumArtist: string; Artist: string; BPM: string; Comment: string; Composer: string; Copyright: string; Disc: string; Encoded: string; Genre: string; OrigArtist: string; Publisher: string; Title: string; Track: string; URL: string; Year: Integer; procedure Load(const aPath: string); procedure Save(const aPath: string); end; TMediaInfoGeneral = record public Duration: Integer; Format: string; Name: string; Path: string; Size: Int64; end; TMediaDataVariants = record public ArtistNameVariantArr: TArray<string>; MovieNameVariantArr: TArray<string>; end; TMediaFormat = (mfUNKNOWN, mfMP3); TMediaFile = class private FAlbum: TAlbum; FArtist: TArtist; FAudioFile: TAudioFile; FID3v1: TID3v1; FID3v2: TID3v2; FMovie: TMovie; FTrack: TTrack; FVideoFile: TVideoFile; function CheckConsilience(aVariantArr: TArray<string>; aValue: string): Boolean; function GetDestinationPath: WideString; function GetFilePath: string; function GetMediaDataVariants: TMediaDataVariants; function GetMediaFormat: TMediaFormat; function GetSource: TFileInfo; procedure AddVariant(var aVariantArr: TArray<string>; const aValue: string); procedure LoadTags; public //constructor Create(aArtist: TArtist; aAlbum: TAlbum; aTrack: TTrack); overload; constructor Create(aMovie: TMovie; aVideoFile: TVideoFile); overload; constructor Create(aMediaInfoGeneral: TMediaInfoGeneral; aVideoStreamArr: TArray<TVideoStream>; aAudioStreamArr: TArray<TAudioStream>); overload; property Album: TAlbum read FAlbum; property Artist: TArtist read FArtist write FArtist; property AudioFile: TAudioFile read FAudioFile; property DestinationPath: WideString read GetDestinationPath; property FilePath: string read GetFilePath; property ID3v1: TID3v1 read FID3v1; property ID3v2: TID3v2 read FID3v2; property MediaDataVariants: TMediaDataVariants read GetMediaDataVariants; property MediaFormat: TMediaFormat read GetMediaFormat; property Movie: TMovie read FMovie write FMovie; property Source: TFileInfo read GetSource; property Track: TTrack read FTrack; property VideoFile: TVideoFile read FVideoFile; end; TMediaFileList = class(TObjectList<TMediaFile>) public procedure PrepareMoveAction; end; implementation uses eAction, ID3v1Library, ID3v2Library, System.SysUtils; function TMediaFile.CheckConsilience(aVariantArr: TArray<string>; aValue: string): Boolean; var ArrValue: string; begin Result := False; for ArrValue in aVariantArr do if UpperCase(ArrValue) = UpperCase(aValue) then Exit(True); end; procedure TMediaFile.AddVariant(var aVariantArr: TArray<string>; const aValue: string); begin if not aValue.IsEmpty and not CheckConsilience(aVariantArr, aValue.Trim) then aVariantArr := aVariantArr + [aValue.Trim]; end; function TMediaFile.GetFilePath: string; begin Result := ''; if AudioFile <> nil then Result := AudioFile.Path else if VideoFile <> nil then Result := VideoFile.Path; end; procedure TMediaFile.LoadTags; begin if MediaFormat = mfMP3 then begin FID3v1.Load(FilePath); FID3v2.Load(FilePath); end; end; function TMediaFile.GetMediaFormat: TMediaFormat; begin Result := mfUNKNOWN; if FAudioFile <> nil then begin if FAudioFile.Format = 'MPEG Audio' then Exit(mfMP3); end; end; function TMediaFile.GetMediaDataVariants: TMediaDataVariants; begin Result.ArtistNameVariantArr := []; case MediaFormat of mfMP3: begin AddVariant(Result.ArtistNameVariantArr, ID3v1.Artist); AddVariant(Result.ArtistNameVariantArr, ID3v2.Artist); end; end; end; procedure TID3v2.Load(const aPath: string); var Description: string; ID3v2Tag: TID3v2Tag; LanguageID: TLanguageID; begin ID3v2Tag := TID3v2Tag.Create; try ID3v2Tag.LoadFromFile(aPath); Self.Track := ID3v2Tag.GetUnicodeText('TRCK'); Self.Disc := ID3v2Tag.GetUnicodeText('MCDI'); Self.Title := ID3v2Tag.GetUnicodeText('TIT2'); Self.Artist := ID3v2Tag.GetUnicodeText('TPE1'); Self.Album := ID3v2Tag.GetUnicodeText('TALB'); Self.Year := StrToIntDef(ID3v2Tag.GetUnicodeText('TYER'), 0); Self.Genre := ID3v2DecodeGenre(ID3v2Tag.GetUnicodeText('TCON')); Self.Comment := ID3v2Tag.GetUnicodeComment('COMM', LanguageID, Description); Self.Composer := ID3v2Tag.GetUnicodeText('TCOM'); Self.Publisher := ID3v2Tag.GetUnicodeText('TPUB'); Self.OrigArtist := ID3v2Tag.GetUnicodeText('TOPE'); Self.Copyright := ID3v2Tag.GetUnicodeText('WCOP'); Self.URL := ID3v2Tag.GetUnicodeText('WXXX'); Self.Encoded := ID3v2Tag.GetUnicodeText('TENC'); Self.BPM := ID3v2Tag.GetUnicodeText('TBPM'); finally ID3v2Tag.Free; end; end; procedure TID3v2.Save(const aPath: string); var Description: string; FrameIndex: Integer; ID3v2Tag: TID3v2Tag; LanguageID: TLanguageID; begin ID3v2Tag := TID3v2Tag.Create; try ID3v2Tag.LoadFromFile(aPath); ID3v2Tag.SetUnicodeText('TRCK', Self.Track); ID3v2Tag.SetUnicodeText('MCDI', Self.Disc); ID3v2Tag.SetUnicodeText('TIT2', Self.Title); ID3v2Tag.SetUnicodeText('TPE1', Self.Artist); ID3v2Tag.SetUnicodeText('TALB', Self.Album); ID3v2Tag.SetUnicodeText('TYER', Self.Year.ToString); ID3v2Tag.SetUnicodeText('TCON', Self.Genre); StringToLanguageID(Self.Comment, LanguageID); ID3v2Tag.SetUnicodeComment('COMM', Self.Comment, LanguageID, ''); ID3v2Tag.SetUnicodeText('TCOM', Self.Composer); ID3v2Tag.SetUnicodeText('TPUB', Self.Publisher); ID3v2Tag.SetUnicodeText('TOPE', Self.OrigArtist); ID3v2Tag.SetUnicodeText('WCOP', Self.Copyright); ID3v2Tag.SetUnicodeText('WXXX', Self.URL); ID3v2Tag.SetUnicodeText('TENC', Self.Encoded); ID3v2Tag.SetUnicodeText('TBPM', Self.BPM); ID3v2Tag.SaveToFile(aPath); finally ID3v2Tag.Free; end; end; procedure TID3v1.Save(const aPath: string); var ID3v1Tag: TID3v1Tag; begin ID3v1Tag := TID3v1Tag.Create; try ID3v1Tag.LoadFromFile(aPath); ID3v1Tag.Track := StrToIntDef(Self.Track, 1); ID3v1Tag.Album := Self.Album; ID3v1Tag.Artist := Self.Artist; ID3v1Tag.Title := Self.Title; ID3v1Tag.Year := Self.Year.ToString; ID3v1Tag.Genre := Self.Genre; ID3v1Tag.Comment := Self.Comment; ID3v1Tag.SaveToFile(aPath); finally ID3v1Tag.Free; end; end; procedure TID3v1.Load(const aPath: string); var ID3v1Tag: TID3v1Tag; begin ID3v1Tag := TID3v1Tag.Create; try ID3v1Tag.LoadFromFile(aPath); Self.Track := ID3v1Tag.TrackString; Self.Album := ID3v1Tag.Album; Self.Artist := ID3v1Tag.Artist; Self.Title := ID3v1Tag.Title; Self.Year := StrToIntDef(ID3v1Tag.Year, 0); Self.Genre := ID3v1Tag.Genre; Self.Comment := ID3v1Tag.Comment; finally ID3v1Tag.Free; end; end; function TMediaFile.GetSource: TFileInfo; begin if (VideoFile <> nil) and (not VideoFile.Path.IsEmpty) then Result.LoadFromPath(VideoFile.Path); end; constructor TMediaFile.Create(aMediaInfoGeneral: TMediaInfoGeneral; aVideoStreamArr: TArray<TVideoStream>; aAudioStreamArr: TArray<TAudioStream>); var AudioStream: TAudioStream; V2AStremRel: TV2AStremRel; VideoStream: TVideoStream; begin if Length(aVideoStreamArr) > 0 then begin FVideoFile := TVideoFile.Create; FVideoFile.Duration := aMediaInfoGeneral.Duration; FVideoFile.Format := aMediaInfoGeneral.Format; FVideoFile.MovieName := aMediaInfoGeneral.Name; FVideoFile.Path := aMediaInfoGeneral.Path; FVideoFile.Size := aMediaInfoGeneral.Size; for VideoStream in aVideoStreamArr do FVideoFile.VideoStreams.Add(VideoStream); for AudioStream in aAudioStreamArr do begin V2AStremRel := TV2AStremRel.Create; V2AStremRel.AudioStream := AudioStream; FVideoFile.AudioStreamRels.Add(V2AStremRel); end; end; if (Length(aVideoStreamArr) = 0) and (Length(aAudioStreamArr) > 0) then begin FAudioFile := TAudioFile.Create; FAudioFile.Format := aMediaInfoGeneral.Format; FAudioFile.Path := aMediaInfoGeneral.Path; LoadTags; end; end; {constructor TMediaFile.Create(aArtist: TArtist; aAlbum: TAlbum; aTrack: TTrack); begin FArtist := aArtist; FAlbum := aAlbum; FTrack := aTrack; // MediaDataVariants.MovieNameVariantArr end; } constructor TMediaFile.Create(aMovie: TMovie; aVideoFile: TVideoFile); begin FMovie := aMovie; FVideoFile := aVideoFile; end; procedure TMediaFileList.PrepareMoveAction; var Action: TAction; MediaFile: TMediaFile; MovieActionRel: TMovieActionRel; begin Action := TAction.Create; try Action.ActionTypeID := 1; for MediaFile in Self do begin if MediaFile.VideoFile.Path <> MediaFile.DestinationPath then begin MovieActionRel := TMovieActionRel.Create; MovieActionRel.MovieID := MediaFile.Movie.ID; Action.MovieActionRels.Add(MovieActionRel); end; end; if Action.MovieActionRels.Count > 0 then Action.StoreAll; finally Action.Free; end; end; function TMediaFile.GetDestinationPath: WideString; var Codec: string; Extension: string; FileName: string; begin if VideoFile.VideoStreams[0].Codec.Length < VideoFile.VideoStreams[0].CodecID.Length then Codec := VideoFile.VideoStreams[0].Codec.ToUpper else Codec := VideoFile.VideoStreams[0].CodecID.ToUpper; FileName := Format('%s (%d.%s.%s)', [ Movie.Title, Movie.Year, Codec, VideoFile.ReleaseType.Name ]); if not Source.Extension.IsEmpty then Extension := Source.Extension else Extension := VideoFile.Format.ToLower; Result := 'D:\Video\%s\%s.%s'; Result := Format(Result, [ Movie.GenreRels[0].Genre.Name, FileName, Extension ]); end; destructor TMediaLibList.Destroy; begin FVideoList.Free; FAudioList.Free; inherited; end; constructor TMediaLibList.Create; begin FVideoList := TVideoList.Create(True); FAudioList := TAudioList.Create(True); end; end.
unit UGroupPage; interface uses UPageSuper, USysPageHandler, UTypeDef; type TRoot = class (TPageContainer) public class function PageType (): TPageType; override; function ChildShowInTree (ptChild: TPageType): boolean; override; function CanOwnChild (ptChild: TPageType): boolean; override; class function SingleInstance (): boolean; override; end; TGroupSuper = class (TPageContainer) public function CanOwnChild (ptChild: TPageType): boolean; override; end; TGroupPage = class (TGroupSuper) protected public class function PageType (): TPageType; override; function ChildShowInTree (ptChild: TPageType): boolean; override; class function DefChildType (): TPageType; override; end; TGroupRoot = class (TGroupPage) public class function PageType (): TPageType; override; class function SingleInstance (): boolean; override; function CanDelete (): boolean; override; end; TGroupRootHandler = class (TSysPageHandlerSuper) protected function PageType (): TPageType; override; function NameResource (): integer; override; function MenuItem_Manage (): integer; override; end; implementation uses UxlFunctions, UPageFactory, Resource; class function TRoot.PageType (): TPageType; begin result := ptRoot; end; function TRoot.ChildShowInTree (ptChild: TPageType): boolean; begin result := true; end; function TRoot.CanOwnChild (ptChild: TPageType): boolean; begin result := ptChild in [ptRecentRoot, ptFAvorite, ptTagRoot, ptSearch, ptGroupRoot, ptRecycleBin, ptTemplate, ptFastLink, ptClip]; end; class function TRoot.SingleInstance (): boolean; begin result := true; end; //-------------------- function TGroupSuper.CanOwnChild (ptChild: TPageType): boolean; begin result := ptChild in [ptGroup, ptNote, ptCalc, ptMemo, ptDict, ptLink, ptContact, ptTemplate, ptSheet]; end; //------------------ class function TGroupPage.PageType (): TPageType; begin result := ptGroup; end; function TGroupPage.ChildShowInTree (ptChild: TPageType): boolean; begin result := true; end; class function TGroupPage.DefChildType (): TPageType; begin result := ptNote; end; //------------------ class function TGroupRoot.PageType (): TPageType; begin result := ptGroupRoot; end; class function TGroupRoot.SingleInstance (): boolean; begin result := true; end; function TGroupRoot.CanDelete (): boolean; begin result := false; end; //------------------ function TGroupRootHandler.PageType (): TPageType; begin result := ptGroupRoot; end; function TGroupRootHandler.NameResource (): integer; begin result := sr_GroupRoot; end; function TGroupRootHandler.MenuItem_Manage (): integer; begin result := -1; end; //------------------- initialization PageFactory.RegisterClass (TGroupPage); PageImageList.AddImageWithOverlay (ptGroup, m_newgroup); PageNameMan.RegisterDefName (ptGroup, sr_defgroupname); // PageDefSettingsMan.RegisterType (ptGroup, TListPageSuper.ListInitialsettings); PageFactory.RegisterClass (TGroupRoot); PageImageList.AddImageWithOverlay (ptGroupRoot, m_newgroup); PageFactory.RegisterClass (TRoot); finalization end.
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved. // // 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 Benchmarks.PriorityModel; interface uses Core.Benchmark.Base, Casbin.Types; type TBenchmarkPriorityModel = class(TBaseBenchmark) private fCasbin: ICasbin; public procedure runBenchmark; override; procedure setDown; override; procedure setUp; override; end; implementation uses Casbin; { TBenchmarkPriorityModel } procedure TBenchmarkPriorityModel.runBenchmark; var i: Integer; begin inherited; for i:=0 to Operations do begin fCasbin.enforce(['alice','data1','read']); Percentage:=i / Operations; end; end; procedure TBenchmarkPriorityModel.setDown; begin inherited; end; procedure TBenchmarkPriorityModel.setUp; begin inherited; fCasbin:=TCasbin.Create('..\..\..\Examples\Default\priority_model.conf', '..\..\..\Examples\Default\priority_policy.csv'); end; end.
{ Batch combine LIP and XWM files into FUZ, or split FUZ into XWM and LIP } unit FUZer; const // extensions to use sXWM = '.xwm'; sLIP = '.lip'; sFUZ = '.fuz'; bShowProgress = True; // show processed files, can slow down on large amount of files sDefaultSourcePath = ''; // Data folder will be used if empty sDefaultDestinationPath = ''; // Data folder will be used if empty //============================================================================ procedure BatchProcess(aSrcPath, aDstPath: string; bToFuz: Boolean); var TDirectory: TDirectory; // to access member functions i, Processed: integer; fuz: TwbFUZFile; elLIP, elXWM: TdfElement; files: TStringDynArray; f, f2, s: string; begin if (aSrcPath = '') or (aDstPath = '') then Exit; aSrcPath := IncludeTrailingBackslash(aSrcPath); aDstPath := IncludeTrailingBackslash(aDstPath); Processed := 0; fuz := TwbFUZFile.Create; fuz.SetToDefault; elLIP := fuz.Elements['LIP Data']; elXWM := fuz.Elements['XWM Data']; // LIP Data is limited by LIP Size field which is 0 by default, ignore that check when creating FUZ if bToFuz then elLIP.BeginUpdate; try if bToFuz then files := TDirectory.GetFiles(aSrcPath, '*' + sXWM, soAllDirectories) else files := TDirectory.GetFiles(aSrcPath, '*' + sFUZ, soAllDirectories); AddMessage('Processing files in "' + aSrcPath + '", press and hold ESC to abort...'); // processing files for i := 0 to Pred(Length(files)) do begin f := files[i]; f2 := aDstPath + Copy(f, Length(aSrcPath) + 1, Length(f)); s := ExtractFilePath(f2); if not DirectoryExists(s) then if not ForceDirectories(s) then raise Exception.Create('Can not create destination directory ' + s); // combine lip and xwm into fuz if bToFuz then begin s := ChangeFileExt(f, sLIP); if FileExists(s) then begin elLIP.LoadFromFile(s); elXWM.LoadFromFile(f); f2 := ChangeFileExt(f2, sFUZ); fuz.SaveToFile(f2); AddMessage('Saved: ' + f2); end else AddMessage('LIP not found: ' + s); end // split fuz to lip and xwm else begin fuz.LoadFromFile(f); elLIP.SaveToFile(ChangeFileExt(f2, sLIP)); elXWM.SaveToFile(ChangeFileExt(f2, sXWM)); AddMessage('Split: ' + f); end; Inc(Processed); // break the files processing loop if Escape is pressed if GetKeyState(VK_ESCAPE) and 128 = 128 then Break; end; AddMessage(Format(#13#10'Processed Files: %d', [Processed])); finally fuz.Free; end; end; //============================================================================ procedure btnSrcClick(Sender: TObject); var ed: TLabeledEdit; s: string; begin ed := TLabeledEdit(TForm(Sender.Parent).FindComponent('edSrc')); s := SelectDirectory('Select source', '', ed.Text, nil); if s <> '' then begin ed.Text := s; ed := TLabeledEdit(TForm(Sender.Parent).FindComponent('edDst')); if ed.Text = '' then ed.Text := s; end; end; //============================================================================ procedure btnDstClick(Sender: TObject); var ed: TLabeledEdit; s: string; begin ed := TLabeledEdit(TForm(Sender.Parent).FindComponent('edDst')); s := SelectDirectory('Select destination', '', ed.Text, nil); if s <> '' then ed.Text := s; end; //============================================================================ function Initialize: Integer; var frm: TForm; edSrc, edDst: TLabeledEdit; btnOk, btnCancel, btnSrc, btnDst: TButton; rbToFuz, rbFromFuz: TRadioButton; pnl: TPanel; begin frm := TForm.Create(nil); try frm.Caption := 'FUZer'; frm.Width := 500; frm.Height := 220; frm.Position := poMainFormCenter; frm.BorderStyle := bsDialog; edSrc := TLabeledEdit.Create(frm); edSrc.Parent := frm; edSrc.Name := 'edSrc'; edSrc.Left := 12; edSrc.Top := 24; edSrc.Width := frm.Width - 70; edSrc.LabelPosition := lpAbove; edSrc.EditLabel.Caption := 'Source folder'; if sDefaultSourcePath <> '' then edSrc.Text := sDefaultSourcePath else edSrc.Text := wbDataPath; btnSrc := TButton.Create(frm); btnSrc.Parent := frm; btnSrc.Top := edSrc.Top - 1; btnSrc.Left := edSrc.Left + edSrc.Width + 6; btnSrc.Width := 32; btnSrc.Height := 22; btnSrc.Caption := '...'; btnSrc.OnClick := btnSrcClick; edDst := TLabeledEdit.Create(frm); edDst.Parent := frm; edDst.Name := 'edDst'; edDst.Left := 12; edDst.Top := edSrc.Top + 46; edDst.Width := frm.Width - 70; edDst.LabelPosition := lpAbove; edDst.EditLabel.Caption := 'Destination folder'; if sDefaultDestinationPath <> '' then edDst.Text := sDefaultDestinationPath else edDst.Text := wbDataPath; btnDst := TButton.Create(frm); btnDst.Parent := frm; btnDst.Top := edDst.Top - 1; btnDst.Left := edDst.Left + edDst.Width + 6; btnDst.Width := 32; btnDst.Height := 22; btnDst.Caption := '...'; btnDst.OnClick := btnDstClick; rbToFuz := TRadioButton.Create(frm); rbToFuz.Parent := frm; rbToFuz.Left := edDst.Left + 12; rbToFuz.Top := edDst.Top + 40; rbToFuz.Width := 140; rbToFuz.Caption := StringReplace(Format('%s + %s to %s', [UpperCase(sLIP), UpperCase(sXWM), UpperCase(sFUZ)]), '.', '', [rfReplaceAll]); rbToFuz.Checked := True; rbFromFuz := TRadioButton.Create(frm); rbFromFuz.Parent := frm; rbFromFuz.Left := rbToFuz.Left + rbToFuz.Width + 20; rbFromFuz.Top := rbToFuz.Top; rbFromFuz.Width := 140; rbFromFuz.Caption := StringReplace(Format('%s to %s + %s', [UpperCase(sFUZ), UpperCase(sLIP), UpperCase(sXWM)]), '.', '', [rfReplaceAll]); btnOk := TButton.Create(frm); btnOk.Parent := frm; btnOk.Caption := 'OK'; btnOk.ModalResult := mrOk; btnOk.Left := frm.Width - 176; btnOk.Top := frm.Height - 62; btnCancel := TButton.Create(frm); btnCancel.Parent := frm; btnCancel.Caption := 'Cancel'; btnCancel.ModalResult := mrCancel; btnCancel.Left := btnOk.Left + btnOk.Width + 8; btnCancel.Top := btnOk.Top; pnl := TPanel.Create(frm); pnl.Parent := frm; pnl.Left := 8; pnl.Top := btnOk.Top - 12; pnl.Width := frm.Width - 20; pnl.Height := 2; if frm.ShowModal = mrOk then BatchProcess( edSrc.Text, edDst.Text, rbToFuz.Checked ); finally frm.Free; end; Result := 1; end; end.
unit uOPCCash; interface type TaOPCCash = class private FPath: string; FActive: boolean; procedure SetPath(const Value: string); public property Path: string read FPath write SetPath; property Active:boolean read FActive; end; var OPCCash : TaOPCCash; implementation uses //Windows, ActiveX, ShlObj, System.IOUtils, SysUtils; { TaOPCCash } procedure TaOPCCash.SetPath(const Value: string); begin FPath := Value; FActive := DirectoryExists(FPath); end; initialization OPCCash := TaOPCCash.Create; //OPCCash.Path := GetSpecialFolderLocation(CSIDL_PERSONAL)+'\OPCCash'; OPCCash.Path := TPath.GetTempPath + TPath.AltDirectorySeparatorChar + 'OPCCash'; if not DirectoryExists(OPCCash.Path) then CreateDir(OPCCash.Path); finalization FreeAndNil(OPCCash); end.
unit UTemplatePage; interface uses UPageSuper, UPageProperty, UxlClasses, UxlList, UxlMiscCtrls, UTypeDef, UEditBox, UxlComboBox; type TTemplatePage = class (TChildItemContainer) private public class function PageType (): TPageType; override; class function DefChildType (): TPageType; override; class procedure GetListShowCols (o_list: TxlIntList); override; class procedure InitialListProperty (lp: TListProperty); override; class function SingleInstance (): boolean; override; end; TTemplateProperty = class (TClonableProperty) private public Template: widestring; HotKey: THotKey; Abbrev: widestring; Remark: widestring; procedure Load (o_list: TxlStrList); override; procedure Save (o_list: TxlStrList); override; class procedure GetShowCols (o_list: TxlIntList); function GetColText (id_col: integer; var s_result: widestring): boolean; override; end; TTemplateItem = class (TChildItemSuper) private FTemplate: TTemplateProperty; protected function GetImageIndex (): integer; override; public constructor Create (i_id: integer); override; destructor Destroy (); override; class function PageType (): TPageType; override; // function GetColText (id_col: integer): widestring; override; procedure Delete (); override; class procedure GetSearchCols (o_list: TxlIntList); override; property Template: TTemplateProperty read FTemplate; end; TTemplateBox = class (TEditBoxSuper) private FHotKey: TxlHotKey; protected procedure OnInitialize (); override; procedure OnOpen (); override; procedure OnClose (); override; procedure LoadItem (value: TPageSuper); override; procedure ClearAndNew (); override; function SaveItem (value: TPageSuper): integer; override; public class function PageType (): TPageType; override; end; implementation uses Windows, UxlFunctions, UxlListView, UxlStrUtils, UPageFactory, UPageStore, ULangManager, UGlobalObj, Resource; class function TTemplatePage.PageType (): TPageType; begin result := ptTemplate; end; class function TTemplatePage.DefChildType (): TPageType; begin result := ptTemplateItem; end; class function TTemplatePage.SingleInstance (): boolean; begin result := true; end; class procedure TTemplatePage.InitialListProperty (lp: TListProperty); const c_cols: array[0..2] of integer = (sr_Title, sr_Text, sr_Hotkey); c_widths: array[0..2] of integer = (100, 200, 60); begin with lp do begin ColList.Populate (c_cols); WidthList.Populate (c_widths); CheckBoxes := false; View := lpvReport; FullrowSelect := true; GridLines := false; end; end; class procedure TTemplatePage.GetListShowCols (o_list: TxlIntList); begin TTemplateProperty.GetShowCols (o_list); end; //----------------------- constructor TTemplateItem.Create (i_id: integer); begin inherited Create (i_id); FTemplate := TTemplateProperty.Create (i_id); FItemProperty := FTemplate; AddProperty (FTemplate); end; destructor TTemplateItem.Destroy (); begin FTemplate.free; inherited; end; class function TTemplateItem.PageType (): TPageType; begin result := ptTemplateItem; end; function TTemplateItem.GetImageIndex (): integer; begin result := PageImageList.IndexOf (PageType); end; class procedure TTemplateItem.GetSearchCols (o_list: TxlIntList); begin TTemplateProperty.GetShowCols (o_list); end; procedure TTemplateItem.Delete (); begin EventMan.EventNotify (e_TemplateItemDeleted, id); inherited Delete; end; //---------------- procedure TTemplateProperty.Load (o_list: TxlStrList); begin Template := SingleLineToMultiLine(o_list[0]); HotKey := StrToIntDef(o_list[1]); Abbrev := o_list[2]; Remark := SingleLineToMultiLine(o_list[3]); o_list.Delete (0, 4); end; procedure TTemplateProperty.Save (o_list: TxlStrList); begin with o_list do begin Add (MultiLineToSingleLine(Template)); Add (IntToStr(HotKey)); Add (Abbrev); Add (MultiLineToSingleLine(Remark)); end; end; class procedure TTemplateProperty.GetShowCols (o_list: TxlIntList); const c_cols: array[0..4] of integer = (sr_Title, sr_Text, sr_Hotkey, sr_abbrev, sr_Remark); var i: integer; begin for i := Low(c_cols) to High(c_cols) do o_list.Add (c_cols[i]); end; function TTemplateProperty.GetColText (id_col: integer; var s_result: widestring): boolean; begin result := true; case id_col of sr_Title: s_result := PageStore[FPageId].Name; sr_Text: s_result := Template; sr_Hotkey: s_result := HotKeyToString(HotKey); sr_Abbrev: s_result := Abbrev; sr_Remark: s_result := Remark; else result := false; end; end; //-------------------- procedure TTemplateBox.OnInitialize (); begin SetTemplate (Template_Box, m_Template); end; const c_TemplateBox: array[0..6] of word = (st_title, st_text, st_hotkey, st_abbrev, cb_new, IDOK, IDCANCEL); procedure TTemplateBox.OnOpen (); begin FHotKey := TxlHotKey.Create (self, ItemHandle[hk_templatehotkey]); inherited; RefreshItemText (self, c_TemplateBox); end; procedure TTemplateBox.OnClose (); begin FHotKey.Free; inherited; end; class function TTemplateBox.PageType (): TPageType; begin result := ptTemplateItem; end; procedure TTemplateBox.LoadItem (value: TPageSuper); var p: TTemplateProperty; begin self.Text := LangMan.GetItem(sr_EditTemplate); ItemText[sle_title] := value.name; p := TTemplateItem(value).Template; ItemText[mle_text] := p.Template; FHotKey.HotKey := p.HotKey; ItemText[sle_abbrev] := p.Abbrev; ItemText[mle_remark] := p.remark; FocusControl (sle_title); end; procedure TTemplateBox.ClearAndNew (); begin self.Text := LangMan.GetItem(sr_NewTemplate); ItemText[sle_title] := ''; ItemText[mle_text] := ''; FHotkey.Hotkey := 0; ItemText[sle_abbrev] := ''; ItemText[mle_remark] := ''; FocusControl (sle_title); end; function TTemplateBox.SaveItem (value: TPageSuper): integer; begin value.name := ItemText[sle_title]; with TTemplateItem (value).Template do begin if ItemText[mle_text] <> '' then Template := itemText[mle_text] else Template := ItemText[sle_title]; if HotKey <> FHotkey.HotKey then begin Hotkey := FHotKey.HotKey; EventMan.EventNotify (e_TemplateHotkeyChanged, value.id, Hotkey); end; Abbrev := ItemText[sle_abbrev]; remark := ItemText[mle_remark]; end; end; //-------------------- initialization PageFactory.RegisterClass (TTemplatePage); PageImageList.AddImageWithOverlay (ptTemplate, m_Template); // PageNameMan.RegisterDefName (ptTemplate, sr_defTemplatename); PageFactory.RegisterClass (TTemplateItem); PageImageList.AddImages (ptTemplateItem, [m_inserttemplate]); // PageNameMan.RegisterDefName (ptTemplateItem, sr_defTemplateItemname); EditBoxFactory.RegisterClass (TTemplateBox); finalization end.
unit MainModule; interface uses uniGUIMainModule, SysUtils, Classes, uniGUIBaseClasses, uniGUIClasses; type TUniMainModule = class(TUniGUIMainModule) private { Private declarations } public { Public declarations } procedure SetGA4(PageWiew: string; GA: string = 'G-VSH6WJS3B3'); end; function UniMainModule: TUniMainModule; implementation {$R *.dfm} uses UniGUIVars, ServerModule, uniGUIApplication; function UniMainModule: TUniMainModule; begin Result := TUniMainModule(UniApplication.UniMainModule) end; { TUniMainModule } procedure TUniMainModule.SetGA4(PageWiew, GA: string); begin UniSession.AddJS('gtag(''event'',''page_view'',{''page_title'': '''+PageWiew+''', ''send_to'': '''+GA+'''});'); end; initialization RegisterMainModuleClass(TUniMainModule); end.
unit uPizzaShackPizza; interface type TPizza = class private FDescription: string; protected function GetDescription: string; virtual; procedure SetDescription(const Value: string); public function Cost: Currency; virtual; abstract; property Description: string read GetDescription write SetDescription; end; TPizzaDecorator = class(TPizza) private FPizza: TPizza; public constructor Create(aPizza: TPizza); destructor Destroy; override; end; TParmesanCheesePizza = class(TPizza) constructor Create; function Cost: Currency; override; end; TMozarellaCheesePizza = class(TPizza) constructor Create; function Cost: Currency; override; end; TPepperoni = class(TPizzaDecorator) protected function GetDescription: string; override; public function Cost: Currency; override; end; TSausage = class(TPizzaDecorator) protected function GetDescription: string; override; public function Cost: Currency; override; end; TBlackOlives = class(TPizzaDecorator) protected function GetDescription: string; override; public function Cost: Currency; override; end; TOnions = class(TPizzaDecorator) protected function GetDescription: string; override; public function Cost: Currency; override; end; implementation { TPizza } function TPizza.GetDescription: string; begin Result := FDescription; end; procedure TPizza.SetDescription(const Value: string); begin FDescription := Value; end; { TParmesanCheesePizza } function TParmesanCheesePizza.Cost: Currency; begin Result := 7.99 end; constructor TParmesanCheesePizza.Create; begin inherited Create; FDescription := 'Parmesan Cheese Pizza'; end; { TMozarellaCheesePizza } function TMozarellaCheesePizza.Cost: Currency; begin Result := 6.99; end; constructor TMozarellaCheesePizza.Create; begin inherited Create; FDescription := 'Mozarella Cheese Pizza'; end; { TPepperoni } function TPepperoni.Cost: Currency ; begin Result := 1.20 + FPizza.Cost; end; function TPepperoni.GetDescription: string; begin Result := FPizza.GetDescription + ', Pepperoni'; end; { TSausage } function TSausage.Cost: Currency; begin Result := 0.95 + FPizza.Cost; end; function TSausage.GetDescription: string; begin Result := FPizza.GetDescription + ', Sausage'; end; { TPizzaDecorator } constructor TPizzaDecorator.Create(aPizza: TPizza); begin inherited Create; FPizza := aPizza; end; destructor TPizzaDecorator.Destroy; begin FPizza.Free; inherited; end; { TBlackOlives } function TBlackOlives.Cost: Currency; begin Result := FPizza.Cost + 0.85; end; function TBlackOlives.GetDescription: string; begin Result := FPizza.GetDescription + ', Black Olives'; end; { TOnions } function TOnions.Cost: Currency; begin Result := FPizza.Cost + 0.50; end; function TOnions.GetDescription: string; begin Result := FPizza.GetDescription + ', Onions'; end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2012 Vincent Parrett } { } { vincent@finalbuilder.com } { http://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 DUnitX.Tests.TestFixture; interface uses DUnitX.TestFramework, DUnitX.TestFixture; type {$M+} [TestFixture] TTestClassWithNonPublicSetup = class private FSetupRun : Boolean; protected [Setup] procedure Setup; public constructor Create; property SetupRun : Boolean read FSetupRun; end; {$M-} MockTestSourceAttribute = class(CustomTestCaseSourceAttribute) protected function GetCaseInfoArray : TestCaseInfoArray; override; end; {$M+} [TestFixture] TTestClassWithTestSource = class public [Test] [MockTestSource] procedure DataTest(Value : Integer); end; {$M-} implementation uses Math, SysUtils; { TDUnitXTestFixtureTests } { TTestClassWithNonPublicSetup } constructor TTestClassWithNonPublicSetup.Create; begin inherited Create; FSetupRun := False; end; procedure TTestClassWithNonPublicSetup.Setup; begin //Optimised out as the method is not used internally; FSetupRun := True; end; { TTestSourceAttribute } function MockTestSourceAttribute.GetCaseInfoArray: TestCaseInfoArray; var I : Integer; begin SetLength(result,3); for I := 0 to 2 do begin result[I].Name := 'DataTest' + IntToStr(I); SetLength(result[I].Values,1); result[I].Values[0] := I; end; end; { TTestClassWithTestSource } procedure TTestClassWithTestSource.DataTest(Value: Integer); begin TDUnitX.CurrentRunner.Status(Format('DataTest(%d) Called',[Value])); Assert.IsTrue(InRange(Value,0,2)); end; initialization TDUnitX.RegisterTestFixture(TTestClassWithNonPublicSetup); TDUnitX.RegisterTestFixture(TTestClassWithTestSource); end.
unit uGerarXML; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.pngimage, Vcl.Imaging.jpeg, System.Actions, Vcl.ActnList, Vcl.Styles, Vcl.Themes, Vcl.Touch.GestureMgr, System.Rtti, System.Bindings.Outputs, Vcl.Bind.Editors, Data.Bind.EngExt, Vcl.Bind.DBEngExt, Data.Bind.Components, Vcl.Buttons, Vcl.Imaging.GIFImg, Vcl.Grids, Vcl.DBGrids, Data.DB, Vcl.DBCtrls, System.DateUtils, Xml.xmldom, Xml.XMLIntf, Xml.Win.msxmldom, Xml.XMLDoc; type TGerarXMLForm = class(TForm) Panel1: TPanel; TitleLabel: TLabel; Image1: TImage; ScrollBox1: TScrollBox; TextPanel: TPanel; ItemTitle: TLabel; ItemSubtitle: TLabel; Image2: TImage; AppBar: TPanel; GestureManager1: TGestureManager; ActionList1: TActionList; Action1: TAction; CloseButton: TImage; ListBox1: TListBox; Label1: TLabel; ListBox2: TListBox; Label2: TLabel; SpeedButtonConexao: TSpeedButton; procedure BackToMainForm(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); procedure SpeedButtonConexaoClick(Sender: TObject); private { Private declarations } procedure AppBarResize; procedure AppBarShow(mode: integer); public { Public declarations } end; var GerarXMLForm: TGerarXMLForm = nil; implementation {$R *.dfm} uses uInovarAuto, uDataModule; procedure TGerarXMLForm.Action1Execute(Sender: TObject); begin AppBarShow(-1); end; const AppBarHeight = 75; procedure TGerarXMLForm.AppBarResize; begin AppBar.SetBounds(0, AppBar.Parent.Height - AppBarHeight, AppBar.Parent.Width, AppBarHeight); end; procedure TGerarXMLForm.AppBarShow(mode: integer); begin if mode = -1 then // Toggle mode := integer(not AppBar.Visible ); if mode = 0 then AppBar.Visible := False else begin AppBar.Visible := True; AppBar.BringToFront; end; end; procedure TGerarXMLForm.FormCreate(Sender: TObject); var LStyle: TCustomStyleServices; MemoColor, MemoFontColor: TColor; begin //Set background color for memos to the color of the form, from the active style. LStyle := TStyleManager.ActiveStyle; MemoColor := LStyle.GetStyleColor(scGenericBackground); MemoFontColor := LStyle.GetStyleFontColor(sfButtonTextNormal); //Fill image GridForm.PickImageColor(Image2, clBtnShadow); end; procedure TGerarXMLForm.FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); begin AppBarShow(0); end; procedure TGerarXMLForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then AppBarShow(-1) else AppBarShow(0); end; procedure TGerarXMLForm.FormResize(Sender: TObject); begin AppBarResize; end; procedure TGerarXMLForm.FormShow(Sender: TObject); var iAno, iMes: Integer; begin AppBarShow(0); ListBox1.Items.Clear; for iAno := YearOf(Now)-5 to YearOf(Now) do for iMes := 1 to 12 do if EncodeDate(iAno, iMes, 1) <= Now then ListBox1.Items.Add(FormatDateTime('yyyy-mmm',EncodeDate(iAno, iMes, 1))); ListBox1.Selected[ListBox1.Count-1] := True; ListBox2.Items.Clear; dInovarAuto.FDMemTableClientes.First; while not dInovarAuto.FDMemTableClientes.Eof do begin ListBox2.Items.Add(dInovarAuto.FDMemTableClientesCNPJ.AsString + ' - ' + dInovarAuto.FDMemTableClientesRazaoSocial.AsString); dInovarAuto.FDMemTableClientes.Next; end; end; procedure TGerarXMLForm.SpeedButtonConexaoClick(Sender: TObject); var HeaderFile: TStringList; ItemFile: TStringList; XML, Items: TStringList; DataInicial, DataFinal: TDateTime; varCNPJ: String; Indice, Index: Integer; function getMes(str: string): Integer; begin str := copy( str, 6, 3 ); if str = 'jan' then result := 01 else if str = 'fev' then result := 02 else if str = 'mar' then result := 03 else if str = 'abr' then result := 04 else if str = 'mai' then result := 05 else if str = 'jun' then result := 06 else if str = 'jul' then result := 07 else if str = 'ago' then result := 08 else if str = 'set' then result := 09 else if str = 'out' then result := 10 else if str = 'nov' then result := 11 else if str = 'dez' then result := 12; end; begin for Indice := 0 to ListBox1.Count-1 do begin if ListBox1.Selected[Indice] then begin DataInicial := EncodeDate( StrToInt(Copy(ListBox1.Items[Indice], 1, 4)), getMes(ListBox1.Items[Indice]), 01 ); DataFinal := IncMonth(DataInicial)-1; HeaderFile := TStringList.Create; HeaderFile.LoadFromFile(ExtractFilePath(Application.ExeName) + 'InovarXML.part1.txt'); ItemFile := TStringList.Create; ItemFile.LoadFromFile(ExtractFilePath(Application.ExeName) + 'InovarXML.part2.txt'); Items := TStringList.Create; for Index := 0 to ListBox2.Count-1 do begin if ListBox2.Selected[Index] then begin varCNPJ := Copy(ListBox2.Items[Index], 1, 18); dInovarAuto.FDMemTableNotaFiscal.Filter := 'CNPJ = ' + QuotedStr( varCNPJ ) + ' AND mes = ' + IntToStr( MonthOf(DataInicial) ) + ' AND tot_nota > 0.00 AND ano = ' + IntToStr( YearOf(DataInicial) ); dInovarAuto.FDMemTableNotaFiscal.First; while not dInovarAuto.FDMemTableNotaFiscal.Eof do begin Items.AddStrings(ItemFile); Items.Text := StringReplace( Items.Text, '%razao_social%', dInovarAuto.FDMemTableNotaFiscalRazaoSocial.AsString, [rfReplaceAll] ); Items.Text := StringReplace( Items.Text, '%cnpj%', StringReplace(StringReplace(StringReplace(dInovarAuto.FDMemTableNotaFiscalCNPJ.AsString,'.','',[rfReplaceAll]),'/','',[rfReplaceAll]),'-','',[rfReplaceAll]), [rfReplaceAll] ); Items.Text := StringReplace( Items.Text, '%mes_ref%', FormatFloat('00', StrToInt(dInovarAuto.FDMemTableNotaFiscalmes.AsString)/1), [rfReplaceAll] ); Items.Text := StringReplace( Items.Text, '%ano_ref%', FormatFloat('0000', StrToInt(dInovarAuto.FDMemTableNotaFiscalano.AsString)/1), [rfReplaceAll] ); Items.Text := StringReplace( Items.Text, '%vl_total_notas%', StringReplace(StringReplace(FormatFloat('#,##0.00', StrToFloat(dInovarAuto.FDMemTableNotaFiscaltot_nota.AsString)),'.','',[rfReplaceAll]),',','.',[rfReplaceAll]), [rfReplaceAll] ); Items.Text := StringReplace( Items.Text, '%vl_parc_dedutivel%', StringReplace(StringReplace(FormatFloat('#,##0.00', StrToFloat(dInovarAuto.FDMemTableNotaFiscalparc_dedutivel.AsString)),'.','',[rfReplaceAll]),',','.',[rfReplaceAll]), [rfReplaceAll] ); dInovarAuto.FDMemTableNotaFiscal.Next; end; end; end; XML := TStringList.Create; XML.AddStrings(HeaderFile); XML.Text := StringReplace( XML.Text, '%%itens%%', Items.Text, [rfReplaceAll] ); XML.SaveToFile( ExtractFilePath(Application.ExeName) + '01111039000491_V_' + FormatDateTime( 'mm_yyyy' , DataInicial ) + '.xml' ); ShowMessage('Arquivo gerado com sucesso.'#13#10#13#10 + ExtractFilePath(Application.ExeName) + 'Inovar-' + FormatDateTime( 'yyyymm' , DataInicial ) + Copy(StringReplace(StringReplace(StringReplace(varCNPJ,'.','',[rfReplaceAll]),'/','',[rfReplaceAll]),'-','',[rfReplaceAll]),1,8) + '.XML' ); FreeAndNil(XML); FreeAndNil(Items); FreeAndNil(ItemFile); FreeAndNil(HeaderFile); end; end; end; procedure TGerarXMLForm.BackToMainForm(Sender: TObject); begin Hide; GridForm.BringToFront; end; end.
unit BaseObjectType; interface uses BaseObjects, Registrator, Contnrs, BaseConsts; type TObjectType = class (TRegisteredIDObject) public constructor Create (ACollection: TIDObjects); override; end; TObjectTypes = class (TRegisteredIDObjects) private function GetItems(Index: integer): TObjectType; public property Items[Index: integer]: TObjectType read GetItems; constructor Create; override; end; TObjectTypeMapperItem = class(TObject) private FObjectTypeID: integer; FFilterColumnName: string; public property FilterColumnName: string read FFilterColumnName; property ObjectTypeID: integer read FObjectTypeID; end; TObjectTypeMapper = class(TObjectList) private function GetItems(Index: integer): TObjectTypeMapperItem; public property Items[Index: integer]: TObjectTypeMapperItem read GetItems; function AddMapperItem(AId: integer; AColName: string): TObjectTypeMapperItem; function GetItemByID(AID: integer): TObjectTypeMapperItem; constructor Create; virtual; end; TDefaultObjectTypeMapper = class(TObjectTypeMapper) public constructor Create; override; end; implementation uses Facade, BaseFacades, ObjectTypePoster; { TObjectTypes } constructor TObjectTypes.Create; begin inherited; FObjectClass := TObjectType; Poster := TMainFacade.GetInstance.DataPosterByClassType[TObjectTypeDataPoster]; end; function TObjectTypes.GetItems(Index: integer): TObjectType; begin Result := inherited Items[Index] as TObjectType; end; { TObjectType } constructor TObjectType.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Тип объекта'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TObjectTypeDataPoster]; end; { TObjectTypeMapper } function TObjectTypeMapper.AddMapperItem(AId: integer; AColName: string): TObjectTypeMapperItem; begin Result := GetItemByID(AID); if not Assigned(Result) then begin Result := TObjectTypeMapperItem.Create; Result.FObjectTypeID := AId; Result.FFilterColumnName := AColName; inherited Add(Result); end; end; constructor TObjectTypeMapper.Create; begin inherited Create(true); end; function TObjectTypeMapper.GetItemByID( AID: integer): TObjectTypeMapperItem; var i: integer; begin Result := nil; for i := 0 to Count - 1 do if Items[i].ObjectTypeID = AID then begin Result := Items[i]; break; end; end; function TObjectTypeMapper.GetItems(Index: integer): TObjectTypeMapperItem; begin Result := TObjectTypeMapperItem(inherited Items[Index]); end; { TDefaultObjectTypeMapper } constructor TDefaultObjectTypeMapper.Create; begin inherited; AddMapperItem(PETROL_REGION_OBJECT_TYPE_ID, 'Petrol_Region_ID'); AddMapperItem(ORGANIZATION_OBJECT_TYPE_ID, 'Organization_ID'); AddMapperItem(DISTRICT_OBJECT_TYPE_ID, 'District_ID'); end; end.
(* Category: SWAG Title: TIMER/RESOLUTION ROUTINES Original name: 0014.PAS Description: Timing Unit Author: CHRIS BOYD Date: 01-27-94 12:23 *) { > Now what I want to do is calculate the total run-time of the overall > event, from start to finish, i.e., parse the log file taking the last and > first time entries and calculate the time. I'm sure there is an easier way > to do this but I'm new to Pascal, and, open to suggestions. Below is what > appears in the event.log : } { Unit Timer; } { SIMPLE TIMER 1.0 ================= This is a Timer unit, it calculates time by system clock. A few limitations are: 1) Must not modify clock. 2) Must not time more than a day 3) Must StopTimer before displaying Time Usage: StartTimer; Starts Timer StopTimer; Stops Timer CalcTimer; Calculates time DispTime: Displays time between StartTimer and StopTimer, you don't need to call CalcTimer if you call DispTime. This unit may be used in freeware and shareware programs as long as: 1) The program is a DECENT program, no "Adult" or "XXX" type programs shall lawfully contain any code found within this file (modified or in original form) or this file after it's been compiled. 2) This copyrighting is not added to, or removed from the program by any other person other than I, the author. This is copyrighted but may be used or modified in programs as long as the above conditions are followed. I may be reached at: 1:130/709 - Fidonet Chris.Boyd@f709.n130.z1.fidonet.org - Internet Alpha Zeta, Ft. Worth (817) 246-3058 - Bulletin Board If you have any comments or suggestions (not complaints). I assume no responsibility for anything resulting from the usage of this code. -Chris Boyd } { Interface } Uses Dos; Type TimeStruct = record Hour, Minute, Second, S100 : Word; End; Var StartT, StopT, TimeT : TimeStruct; Stopped : Boolean; { procedure StartTimer; procedure StopTimer; procedure DispTime; procedure CalcTimer; Implementation } procedure TimerError(Err : Byte); Begin Case Err of 1 : Begin Writeln(' Error: Must Use StartTimer before StopTimer'); Halt(1); End; 2 : Begin Writeln(' Error: Timer can not handle change of day'); Halt(2); End; 3 : Begin Writeln(' Error: Internal - Must StopTimer before DispTime'); Halt(3); End; End; End; procedure CalcTimer; Begin If (Stopped = True) Then Begin If (StopT.Hour < StartT.Hour) Then TimerError(2); TimeT.Hour := StopT.Hour - StartT.Hour; If (StopT.Minute < StartT.Minute) Then Begin TimeT.Hour := TimeT.Hour - 1; StopT.Minute := StopT.Minute + 60; End; TimeT.Minute := StopT.Minute - StartT.Minute; If (StopT.Second < StartT.Second) Then Begin TimeT.Minute := TimeT.Minute - 1; StopT.Second := StopT.Second + 60; End; TimeT.Second := StopT.Second - StartT.Second; If (StopT.S100 < StartT.S100) Then Begin TimeT.Second := TimeT.Second - 1; StopT.S100 := StopT.S100 + 100; End; TimeT.S100 := StopT.S100 - StartT.S100; End Else TimerError(3); End; procedure DispTime; Begin CalcTimer; Write(' Time : '); Write(TimeT.Hour); Write(':'); If (TimeT.Minute < 10) Then Write('0'); Write(TimeT.Minute); Write(':'); If (TimeT.Second < 10) Then Write('0'); Write(TimeT.Second); Write('.'); If (TimeT.S100 < 10) Then Write('0'); Writeln(TimeT.S100); End; procedure StartTimer; Begin GetTime(StartT.Hour, StartT.Minute, StartT.Second, StartT.S100); Stopped := False; End; procedure StopTimer; Begin If (Stopped = False) Then Begin GetTime(StopT.Hour, StopT.Minute, StopT.Second, StopT.S100); Stopped := TRUE; End Else TimerError(1); End; { This is a unit that I wrote. It will not change day without calling an error in itself. This can be modified though, I just haven't went about doing it. For example, if you started the timer at 11:29 pm and stopped it at 1:00 am, it wouldn't work, but if you started the timer at 12:00 am and stopped it at 11:59 pm in that same day it would work. The TimeStruct type doesn't store day, just time and the only thing you have to do to use it is: In your main program: } { Program MyProg; Uses Timer; } var i: longint; Begin { Program stuff.... } StartTimer; { More Program Stuff... } for i := 1 to 30000000 do ; StopTimer; { If you don't want to display the time to the screen, then you need to call CalcTimer, so that it modifies TimeT} DispTime; {Whenever you want to display the time.. The calculated time is stored in the record variable Timer.TimeT, if you wanted to access it. All the fields of the record a word in type. To access the hours for example, you'd go like: Timer.TimeT.Hour or TimeT.Hour You probably will have to try both.} End.
unit Iocp.ReadWriteLocker; { 用原子操作加临界区实现的读写锁,性能比Delphi自带的高很多 ZY 2011.1.4 测试代码: var L: TIocpReadWriteLocker; L2: TMultiReadExclusiveWriteSynchronizer; t: DWORD; i: Integer; begin L := TIocpReadWriteLocker.Create; t := GetTickCount; for i := 1 to 10000000 do begin L.ReadLock; L.WriteLock; L.WriteUnlock; L.ReadUnlock; end; t := CalcTickDiff(t, GetTickCount); Memo1.Lines.Add('TIocpReadWriteLocker: ' + TickToTimeStr(t)); L.Free; L2 := TMultiReadExclusiveWriteSynchronizer.Create; t := GetTickCount; for i := 1 to 10000000 do begin L2.BeginRead; L2.BeginWrite; L2.EndWrite; L2.EndRead; end; t := CalcTickDiff(t, GetTickCount); Memo1.Lines.Add('TMultiReadExclusiveWriteSynchronizer: ' + TickToTimeStr(t)); L2.Free; end; 测试结果: TIocpReadWriteLocker: 625毫秒 TMultiReadExclusiveWriteSynchronizer: 17秒235毫秒 } interface uses Windows; type TIocpReadWriteLocker = class private FReaderCount: Integer; // FCriRead: TRTLCriticalSection; FCriWrite: TRTLCriticalSection; public constructor Create; virtual; destructor Destroy; override; procedure ReadLock; procedure ReadUnlock; procedure WriteLock; procedure WriteUnlock; procedure BeginRead; procedure EndRead; procedure BeginWrite; procedure EndWrite; end; implementation { TIocpReadWriteLocker } constructor TIocpReadWriteLocker.Create; begin // InitializeCriticalSection(FCriRead); InitializeCriticalSection(FCriWrite); FReaderCount := 0; end; destructor TIocpReadWriteLocker.Destroy; begin // DeleteCriticalSection(FCriRead); DeleteCriticalSection(FCriWrite); inherited Destroy; end; procedure TIocpReadWriteLocker.ReadLock; begin { EnterCriticalSection(FCriRead); Inc(FReaderCount); if (FReaderCount = 1) then WriteLock; LeaveCriticalSection(FCriRead);} if (InterlockedIncrement(FReaderCount) = 1) then WriteLock; end; procedure TIocpReadWriteLocker.ReadUnlock; begin { EnterCriticalSection(FCriRead); Dec(FReaderCount); if (FReaderCount = 0) then WriteUnlock; LeaveCriticalSection(FCriRead);} if (InterlockedDecrement(FReaderCount) = 0) then WriteUnlock; end; procedure TIocpReadWriteLocker.WriteLock; begin EnterCriticalSection(FCriWrite); end; procedure TIocpReadWriteLocker.WriteUnlock; begin LeaveCriticalSection(FCriWrite); end; procedure TIocpReadWriteLocker.BeginRead; begin ReadLock; end; procedure TIocpReadWriteLocker.BeginWrite; begin WriteLock; end; procedure TIocpReadWriteLocker.EndRead; begin ReadUnlock; end; procedure TIocpReadWriteLocker.EndWrite; begin WriteUnlock; end; end.
unit my_sheets; {$mode objfpc}{$H+} interface uses Classes, SysUtils, my_tabsheet,dialogs,Actnlist; { type { TmysheetEmployee } //Журнал сотрудников TmysheetEmployee=class(Tmytabsheet) private protected public constructor Create(TheOwner: TComponent);override; destructor Destroy;override; function loadDBGrid:boolean;override; procedure SettingPAG;override; end; { TmysheetEmployeeUv } //Журнал уволенных сотрудников TmysheetEmployeeUv=class(Tmytabsheet) private protected public constructor Create(TheOwner: TComponent);override; destructor Destroy;override; function loadDBGrid:boolean;override; procedure SettingPAG;override; end; { TmysheetEmployeeTMPSTOP } //Журнал сотрудников с временным прекращением TmysheetEmployeeTMPSTOP=class(Tmytabsheet) private protected public constructor Create(TheOwner: TComponent);override; destructor Destroy;override; function loadDBGrid:boolean;override; procedure SettingPAG;override; end; { TmysheetMNI } //Журнал зарегистрированных МНИ TmysheetMNI=class(Tmytabsheet) private protected public constructor Create(TheOwner: TComponent);override; destructor Destroy;override; function loadDBGrid:boolean;override; procedure SettingPAG;override; end; { TmysheetDELETEMNI } //Журнал списанных МНИ TmysheetDELETEMNI=class(Tmytabsheet) private protected public constructor Create(TheOwner: TComponent);override; destructor Destroy;override; function loadDBGrid:boolean;override; procedure SettingPAG;override; end; { TmysheetMOVEMNI } //Журнал движения МНИ TmysheetMOVEMNI=class(Tmytabsheet) private protected public constructor Create(TheOwner: TComponent);override; destructor Destroy;override; function loadDBGrid:boolean;override; procedure SettingPAG;override; end; { TmysheetSERTIFIKAT } //Журнал Сертификатво TmysheetSERTIFIKAT=class(Tmytabsheet) private protected public constructor Create(TheOwner: TComponent);override; destructor Destroy;override; function loadDBGrid:boolean;override; procedure SettingPAG;override; end; //Журнал Криптосредства { TmysheetKRIPTO } TmysheetKRIPTO=class(Tmytabsheet) private protected public constructor Create(TheOwner: TComponent);override; destructor Destroy;override; function loadDBGrid:boolean;override; procedure SettingPAG;override; end; } implementation { { TmysheetKRIPTO } constructor TmysheetKRIPTO.Create(TheOwner: TComponent); begin inherited Create(TheOwner); end; destructor TmysheetKRIPTO.Destroy; begin inherited Destroy; end; function TmysheetKRIPTO.loadDBGrid: boolean; begin end; procedure TmysheetKRIPTO.SettingPAG; begin end; { TmysheetMOVEMNI } constructor TmysheetMOVEMNI.Create(TheOwner: TComponent); begin inherited Create(TheOwner); end; destructor TmysheetMOVEMNI.Destroy; begin inherited Destroy; end; function TmysheetMOVEMNI.loadDBGrid: boolean; var tSQL:string; begin tSQL:='select MOVE_MNI.ID as ID, MOVE_MNI.DTR AS M_M_DT, PEOPLES.FAM, KEY_.NAME AS KEYN,PR_RASPR_MNI.NAME AS PR_R_M from MOVE_MNI join MNI on (MOVE_MNI.ID_MNI=mni.ID) '+lineending+ 'join START_WORK on (MOVE_MNI.ID_START_WORK=START_WORK.ID) join PEOPLES ON (START_WORK.ID_PEOPLE=PEOPLES.ID)'+lineending+ 'join KEY_ on (KEY_.ID=MOVE_MNI.ID_KEY)'+lineending+ 'join PR_RASPR_MNI on (MOVE_MNI.ID_PR_RASPR=PR_RASPR_MNI.ID)'+lineending+ ''+lineending+ 'order by M_M_DT'; result:=false; //загружаем данные в сетку FTrans.DataBase:=connector; FQuery.DataBase:=connector; FQuery.Transaction:=FTrans; FQuery.SQL.Clear; Fquery.SQL.Add(tSQL); FQuery.ReadOnly:=true; FQuery.Open; FDS.DataSet:=FQuery; FDBGR.DataSource:=FDS; //первоначальная настройка //сначало то, что видимое Fquery.Fields.FieldByName('M_M_DT').DisplayWidth:=20; Fquery.Fields.FieldByName('M_M_DT').DisplayLabel:='дата'; Fquery.Fields.FieldByName('FAM').DisplayWidth:=20; Fquery.Fields.FieldByName('FAM').DisplayLabel:='ответственный'; Fquery.Fields.FieldByName('KEYN').DisplayWidth:=9; Fquery.Fields.FieldByName('KEYN').DisplayLabel:='ключевой'; Fquery.Fields.FieldByName('PR_R_M').DisplayWidth:=9; Fquery.Fields.FieldByName('PR_R_M').DisplayLabel:='распределен'; //теперь то, что не видимое Fquery.Fields.FieldByName('ID').Visible:=false; //настраиваем кнопки данной сетки SettingPAG; result:=true; end; procedure TmysheetMOVEMNI.SettingPAG; var cmp:tcomponent; begin //настраиваем кнопки и др. на форме по необходимости { cmp:=self.parent_frm.FindComponent('Aadding'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='добавить сертификат'; end; cmp:=self.parent_frm.FindComponent('AEditing'); if cmp<>nil then begin TAction(cmp).Enabled:=not FQuery.IsEmpty; TAction(cmp).Hint:='просмотреть'; end; } cmp:=self.parent_frm.FindComponent('AUpdating'); if cmp<>nil then begin TAction(cmp).Enabled:=true;//not FQuery.IsEmpty; TAction(cmp).Hint:='Обновить данные'; end; cmp:=self.parent_frm.FindComponent('AExit'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='закрыть журнал'; end; end; { TmysheetSERTIFIKAT } constructor TmysheetSERTIFIKAT.Create(TheOwner: TComponent); begin inherited Create(TheOwner); end; destructor TmysheetSERTIFIKAT.Destroy; begin inherited Destroy; end; function TmysheetSERTIFIKAT.loadDBGrid: boolean; var tSQL:string; begin tSQL:='select SERTIFIKATS.ID as ID, SERTIFIKATS.DT, SERTIFIKATS.NAME, SERTIFIKATS.DT_START,SERTIFIKATS.DT_END,'+lineending+ 'PEOPLES.FAM||'' ''||left(PEOPLES.NAM,1)||''. ''||left(PEOPLES.OTCH,1)||''.'' as FIO from SERTIFIKATS join START_WORK on (SERTIFIKATS.ID_START_WORK=START_WORK.ID) '+lineending+ 'join PEOPLES ON (START_WORK.ID_PEOPLE=PEOPLES.ID) where (SERTIFIKATS.DT_END>CURRENT_DATE)'+lineending+ 'order by DT, NAME'; result:=false; //загружаем данные в сетку FTrans.DataBase:=connector; FQuery.DataBase:=connector; FQuery.Transaction:=FTrans; FQuery.SQL.Clear; Fquery.SQL.Add(tSQL); FQuery.ReadOnly:=true; FQuery.Open; FDS.DataSet:=FQuery; FDBGR.DataSource:=FDS; //первоначальная настройка //сначало то, что видимое Fquery.Fields.FieldByName('NAME').DisplayWidth:=20; Fquery.Fields.FieldByName('NAME').DisplayLabel:='номер'; Fquery.Fields.FieldByName('DT').DisplayWidth:=9; Fquery.Fields.FieldByName('DT').DisplayLabel:='дата получения'; Fquery.Fields.FieldByName('DT_START').DisplayWidth:=9; Fquery.Fields.FieldByName('DT_START').DisplayLabel:='начало действия'; Fquery.Fields.FieldByName('DT_END').DisplayWidth:=9; Fquery.Fields.FieldByName('DT_END').DisplayLabel:='окончание действия'; Fquery.Fields.FieldByName('FIO').DisplayWidth:=18; Fquery.Fields.FieldByName('FIO').DisplayLabel:='пользователь'; //теперь то, что не видимое Fquery.Fields.FieldByName('ID').Visible:=false; //настраиваем кнопки данной сетки SettingPAG; result:=true; end; procedure TmysheetSERTIFIKAT.SettingPAG; var cmp:tcomponent; begin //настраиваем кнопки и др. на форме по необходимости cmp:=self.parent_frm.FindComponent('Aadding'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='добавить сертификат'; end; cmp:=self.parent_frm.FindComponent('AEditing'); if cmp<>nil then begin TAction(cmp).Enabled:=not FQuery.IsEmpty; TAction(cmp).Hint:='просмотреть'; end; cmp:=self.parent_frm.FindComponent('AUpdating'); if cmp<>nil then begin TAction(cmp).Enabled:=true;//not FQuery.IsEmpty; TAction(cmp).Hint:='Обновить данные'; end; cmp:=self.parent_frm.FindComponent('AExit'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='закрыть журнал'; end; end; { TmysheetDELETEMNI } constructor TmysheetDELETEMNI.Create(TheOwner: TComponent); begin inherited Create(TheOwner); end; destructor TmysheetDELETEMNI.Destroy; begin inherited Destroy; end; function TmysheetDELETEMNI.loadDBGrid: boolean; var tSQL:string; begin tSQL:='select DELETE_MNI.ID as ID, DELETE_MNI.DT, MNI.UCHETN, MOTIVE_DELETE_MNI.NAME from DELETE_MNI JOIN MNI ON'+lineending+ ' (DELETE_MNI.ID_MNI=MNI.ID) join MOTIVE_DELETE_MNI ON(MOTIVE_DELETE_MNI.ID=DELETE_MNI.ID_MOTIVE_DELETE_MNI)'+lineending+ 'where (MNI.ID_RAION='+inttostr(id_raion)+')'+lineending+ 'order by DELETE_MNI.DT, MNI.UCHETN'; result:=false; //загружаем данные в сетку FTrans.DataBase:=connector; FQuery.DataBase:=connector; FQuery.Transaction:=FTrans; FQuery.SQL.Clear; Fquery.SQL.Add(tSQL); FQuery.ReadOnly:=true; FQuery.Open; FDS.DataSet:=FQuery; FDBGR.DataSource:=FDS; //первоначальная настройка Fquery.Fields.FieldByName('DT').DisplayWidth:=8; Fquery.Fields.FieldByName('DT').DisplayLabel:='дата списания'; Fquery.Fields.FieldByName('UCHETN').DisplayWidth:=5; Fquery.Fields.FieldByName('UCHETN').DisplayLabel:='учетный номер'; Fquery.Fields.FieldByName('NAME').DisplayWidth:=30; Fquery.Fields.FieldByName('NAME').DisplayLabel:='основание списания'; //теперь то, что не видимое Fquery.Fields.FieldByName('ID').Visible:=false; //настраиваем кнопки данной сетки SettingPAG; result:=true; end; procedure TmysheetDELETEMNI.SettingPAG; var cmp:tcomponent; begin //настраиваем кнопки и др. на форме по необходимости //TAction(self.parent_frm.FindComponent('Aadding111')).Visible:=true; cmp:=self.parent_frm.FindComponent('AUpdating'); if cmp<>nil then begin TAction(cmp).Enabled:=true;//not FQuery.IsEmpty; TAction(cmp).Hint:='Обновить данные'; end; cmp:=self.parent_frm.FindComponent('AExit'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='закрыть журнал'; end; cmp:=self.parent_frm.FindComponent('Aakt'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Visible:=true; TAction(cmp).Hint:='выгрузить АКТ'; end; end; { TmysheetMNI } constructor TmysheetMNI.Create(TheOwner: TComponent); begin inherited Create(TheOwner); end; destructor TmysheetMNI.Destroy; begin inherited Destroy; end; function TmysheetMNI.loadDBGrid: boolean; var tSQL:string; begin tSQL:='select MNI.id as id, MNI_TIP.NAME as tip, PR_RASPR_MNI.NAME as raspr, MNI.UCHETN as uch, PEOPLES.FAM as fam, GROUPS.NAME as group_, MNI.SERIAL as serial,'+lineending+ 'MNI.SSIZE as ssize, MNI.DT as dt, MNI_MODEL.NAME as model_, MNI.OTKUDA as otkuda from MNI join MNI_TIP on (MNI.ID_TIP=MNI_TIP.ID)'+lineending+ 'join PR_RASPR_MNI on (MNI.ID_PR_RASPR=PR_RASPR_MNI.ID) join START_WORK on'+lineending+ '(START_WORK.ID=MNI.ID_START_WORK) join PEOPLES on (START_WORK.ID_PEOPLE=PEOPLES.ID) left join GROUPS'+lineending+ 'on (GROUPS.ID=START_WORK.ID_GROUP) left join MNI_MODEL on (MNI.ID_MODEL=MNI_MODEL.ID) where'+lineending+ '(MNI.ID_RAION='+inttostr(id_raion)+')and'+lineending+ '(not exists(select * from DELETE_MNI where DELETE_MNI.ID_MNI=MNI.ID))'+lineending+ 'order by MNI.DT'; result:=false; //загружаем данные в сетку FTrans.DataBase:=connector; FQuery.DataBase:=connector; FQuery.Transaction:=FTrans; FQuery.SQL.Clear; Fquery.SQL.Add(tSQL); FQuery.ReadOnly:=true; FQuery.Open; FDS.DataSet:=FQuery; FDBGR.DataSource:=FDS; //первоначальная настройка Fquery.Fields.FieldByName('tip').DisplayWidth:=5; Fquery.Fields.FieldByName('raspr').DisplayWidth:=10; Fquery.Fields.FieldByName('uch').DisplayWidth:=8; Fquery.Fields.FieldByName('fam').DisplayWidth:=20; Fquery.Fields.FieldByName('group_').DisplayWidth:=8; Fquery.Fields.FieldByName('serial').DisplayWidth:=10; Fquery.Fields.FieldByName('ssize').DisplayWidth:=8; Fquery.Fields.FieldByName('dt').DisplayWidth:=8; Fquery.Fields.FieldByName('model_').DisplayWidth:=10; Fquery.Fields.FieldByName('otkuda').DisplayWidth:=20; //настраиваем кнопки данной сетки SettingPAG; result:=true; end; procedure TmysheetMNI.SettingPAG; var cmp:tcomponent; begin //настраиваем кнопки и др. на форме по необходимости //TAction(self.parent_frm.FindComponent('Aadding111')).Visible:=true; cmp:=self.parent_frm.FindComponent('Aadding'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='добавить МНИ'; end; cmp:=self.parent_frm.FindComponent('AEditing'); if cmp<>nil then begin TAction(cmp).Enabled:=not FQuery.IsEmpty; TAction(cmp).Hint:='Внести изменения'; end; cmp:=self.parent_frm.FindComponent('ADeleting'); if cmp<>nil then begin TAction(cmp).Enabled:=not FQuery.IsEmpty; TAction(cmp).Hint:='снятие с учета МНИ'; end; cmp:=self.parent_frm.FindComponent('AUpdating'); if cmp<>nil then begin TAction(cmp).Enabled:=true;//not FQuery.IsEmpty; TAction(cmp).Hint:='Обновить данные'; end; cmp:=self.parent_frm.FindComponent('AExit'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='закрыть журнал'; end; end; { TmysheetEmployeeTMPSTOP } constructor TmysheetEmployeeTMPSTOP.Create(TheOwner: TComponent); begin inherited Create(TheOwner); end; destructor TmysheetEmployeeTMPSTOP.Destroy; begin inherited Destroy; end; function TmysheetEmployeeTMPSTOP.loadDBGrid: boolean; var tSQL:string; begin tSQL:='select MOTIVE_TMP_STOP_SW.NAME, TMP_STOP_SW.DT_START, TMP_STOP_SW.DT_END, START_WORK.ID_PEOPLE, TMP_STOP_SW.ID as ID, RAIONS.NAME as rr, PEOPLES.FAM, PEOPLES.NAM, PEOPLES.OTCH, PEOPLES.REGISTRATION, PEOPLES.DTB, PEOPLES.PLB, POSTS.NAME as post, GROUPS.NAME as ngroup from TMP_STOP_SW JOIN START_WORK ON (TMP_STOP_SW.ID_START_WORK=START_WORK.ID) join PEOPLES ON (START_WORK.ID_PEOPLE=PEOPLES.ID) left join groups '+lineending+ 'on (START_WORK.ID_GROUP=GROUPS.ID) join POSTS ON (START_WORK.ID_POST=POSTS.ID) join RAIONS on (START_WORK.ID_RAION=RAIONS.ID) join MOTIVE_TMP_STOP_SW ON (TMP_STOP_SW.ID_MOTIVE_TMP_STOP_SW=MOTIVE_TMP_STOP_SW.ID) where ((START_WORK.ID_RAION='+ inttostr(id_raion)+')/*and(TMP_STOP_SW.DT_END is null)*/)'+lineending+ 'order by TMP_STOP_SW.DT_START, MOTIVE_TMP_STOP_SW.NAME, ngroup, PEOPLES.FAM, PEOPLES.NAM, PEOPLES.OTCH '; result:=false; //загружаем данные в сетку FTrans.DataBase:=connector; FQuery.DataBase:=connector; FQuery.Transaction:=FTrans; FQuery.SQL.Clear; Fquery.SQL.Add(tSQL); FQuery.ReadOnly:=true; FQuery.Open; FDS.DataSet:=FQuery; FDBGR.DataSource:=FDS; //первоначальная настройка Fquery.Fields.FieldByName('NAME').DisplayWidth:=20; Fquery.Fields.FieldByName('rr').DisplayWidth:=5; Fquery.Fields.FieldByName('FAM').DisplayWidth:=20; Fquery.Fields.FieldByName('NAM').DisplayWidth:=20; Fquery.Fields.FieldByName('OTCH').DisplayWidth:=20; Fquery.Fields.FieldByName('post').DisplayWidth:=20; Fquery.Fields.FieldByName('ngroup').DisplayWidth:=20; Fquery.Fields.FieldByName('DTB').DisplayWidth:=20; Fquery.Fields.FieldByName('PLB').DisplayWidth:=20; Fquery.Fields.FieldByName('REGISTRATION').DisplayWidth:=20; //настраиваем кнопки данной сетки SettingPAG; result:=true; end; procedure TmysheetEmployeeTMPSTOP.SettingPAG; var cmp:tcomponent; begin //настраиваем кнопки и др. на форме по необходимости //TAction(self.parent_frm.FindComponent('Aadding111')).Visible:=true; cmp:=self.parent_frm.FindComponent('AEditing'); if cmp<>nil then begin TAction(cmp).Enabled:=not FQuery.IsEmpty; TAction(cmp).Hint:='Внести изменения'; end; cmp:=self.parent_frm.FindComponent('AUpdating'); if cmp<>nil then begin TAction(cmp).Enabled:=true;//not FQuery.IsEmpty; TAction(cmp).Hint:='Обновить данные'; end; cmp:=self.parent_frm.FindComponent('AExit'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='закрыть журнал'; end; end; { TmysheetEmployeeUv } constructor TmysheetEmployeeUv.Create(TheOwner: TComponent); begin inherited Create(TheOwner); end; destructor TmysheetEmployeeUv.Destroy; begin inherited Destroy; end; function TmysheetEmployeeUv.loadDBGrid: boolean; var tSQL:string; begin tSQL:='select MOTIVE_DISCHARGE.NAME,START_WORK.ID_PEOPLE, DISCHARGE.ID as ID, RAIONS.NAME as rr, PEOPLES.FAM, PEOPLES.NAM, PEOPLES.OTCH, PEOPLES.REGISTRATION, PEOPLES.DTB, PEOPLES.PLB, POSTS.NAME as post, GROUPS.NAME as ngroup from DISCHARGE JOIN START_WORK ON (DISCHARGE.ID_START_WORK=START_WORK.ID) join PEOPLES ON (START_WORK.ID_PEOPLE=PEOPLES.ID) left join groups '+lineending+ 'on (START_WORK.ID_GROUP=GROUPS.ID) join POSTS ON (START_WORK.ID_POST=POSTS.ID) join RAIONS on (START_WORK.ID_RAION=RAIONS.ID) join MOTIVE_DISCHARGE ON (DISCHARGE.ID_MOTIVE_DISCHARGE=MOTIVE_DISCHARGE.ID) where (START_WORK.ID_RAION='+ inttostr(id_raion)+')'+lineending+ 'order by DISCHARGE.DT, ngroup, PEOPLES.FAM, PEOPLES.NAM, PEOPLES.OTCH'; result:=false; //загружаем данные в сетку FTrans.DataBase:=connector; FQuery.DataBase:=connector; FQuery.Transaction:=FTrans; FQuery.SQL.Clear; Fquery.SQL.Add(tSQL); FQuery.ReadOnly:=true; FQuery.Open; FDS.DataSet:=FQuery; FDBGR.DataSource:=FDS; //первоначальная настройка Fquery.Fields.FieldByName('NAME').DisplayWidth:=20; Fquery.Fields.FieldByName('rr').DisplayWidth:=5; Fquery.Fields.FieldByName('FAM').DisplayWidth:=20; Fquery.Fields.FieldByName('NAM').DisplayWidth:=20; Fquery.Fields.FieldByName('OTCH').DisplayWidth:=20; Fquery.Fields.FieldByName('post').DisplayWidth:=20; Fquery.Fields.FieldByName('ngroup').DisplayWidth:=20; Fquery.Fields.FieldByName('DTB').DisplayWidth:=20; Fquery.Fields.FieldByName('PLB').DisplayWidth:=20; Fquery.Fields.FieldByName('REGISTRATION').DisplayWidth:=20; //настраиваем кнопки данной сетки SettingPAG; result:=true; end; procedure TmysheetEmployeeUv.SettingPAG; var cmp:tcomponent; begin //настраиваем кнопки и др. на форме по необходимости //TAction(self.parent_frm.FindComponent('Aadding111')).Visible:=true; cmp:=self.parent_frm.FindComponent('AUpdating'); if cmp<>nil then begin TAction(cmp).Enabled:=true;//not FQuery.IsEmpty; TAction(cmp).Hint:='Обновить данные'; end; cmp:=self.parent_frm.FindComponent('AExit'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='закрыть журнал'; end; cmp:=self.parent_frm.FindComponent('AEditing'); if cmp<>nil then begin TAction(cmp).Enabled:=not FQuery.IsEmpty; TAction(cmp).Hint:='Внести изменения'; end; end; { TmysheetEmployee } procedure TmysheetEmployee.SettingPAG; var cmp:tcomponent; begin //настраиваем кнопки и др. на форме по необходимости //TAction(self.parent_frm.FindComponent('Aadding111')).Visible:=true; cmp:=self.parent_frm.FindComponent('Aadding'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='добавить сотрудника'; end; cmp:=self.parent_frm.FindComponent('AEditing'); if cmp<>nil then begin TAction(cmp).Enabled:=not FQuery.IsEmpty; TAction(cmp).Hint:='Внести изменения'; end; cmp:=self.parent_frm.FindComponent('aMoving'); if cmp<>nil then begin TAction(cmp).Enabled:=not FQuery.IsEmpty; TAction(cmp).Hint:='Временное прекращение'; end; cmp:=self.parent_frm.FindComponent('ADeleting'); if cmp<>nil then begin TAction(cmp).Enabled:=not FQuery.IsEmpty; TAction(cmp).Hint:='увольнение сотрудника'; end; cmp:=self.parent_frm.FindComponent('AUpdating'); if cmp<>nil then begin TAction(cmp).Enabled:=true;//not FQuery.IsEmpty; TAction(cmp).Hint:='Обновить данные'; end; cmp:=self.parent_frm.FindComponent('AExit'); if cmp<>nil then begin TAction(cmp).Enabled:=true; TAction(cmp).Hint:='закрыть журнал'; end; end; constructor TmysheetEmployee.Create(TheOwner: TComponent); begin inherited Create(TheOwner); end; destructor TmysheetEmployee.Destroy; begin inherited Destroy; end; function TmysheetEmployee.loadDBGrid: boolean; var tSQL:string; begin tSQL:='select START_WORK.TABNOM, START_WORK.ID_PEOPLE, START_WORK.ID as ID, RAIONS.NAME as rr,'+lineending+ ' PEOPLES.FAM, PEOPLES.NAM, PEOPLES.OTCH, POSTS.NAME as post, GROUPS.NAME as ngroup, LOCATIONS.NAME as loc,'+lineending+ ' PEOPLES.DTB, PEOPLES.REGISTRATION, PEOPLES.PLB'+lineending+ ' from START_WORK join PEOPLES ON (START_WORK.ID_PEOPLE=PEOPLES.ID) left join groups '+lineending+ 'on (START_WORK.ID_GROUP=GROUPS.ID) join POSTS ON (START_WORK.ID_POST=POSTS.ID)'+lineending+ ' join RAIONS on (START_WORK.ID_RAION=RAIONS.ID) join LOCATIONS on (LOCATIONS.ID=START_WORK.ID_LOCATION) where (START_WORK.ID_RAION='+ inttostr(id_raion)+')and(not exists(select * from DISCHARGE where DISCHARGE.ID_START_WORK=START_WORK.ID))'+LINEENDING+ 'and(not exists(select * from TMP_STOP_SW where ((TMP_STOP_SW.ID_START_WORK=START_WORK.ID)and(TMP_STOP_SW.DT_END is NULL))))'+lineending+ 'order by ngroup, PEOPLES.FAM, PEOPLES.NAM, PEOPLES.OTCH'; result:=false; //загружаем данные в сетку FTrans.DataBase:=connector; FQuery.DataBase:=connector; FQuery.Transaction:=FTrans; FQuery.SQL.Clear; Fquery.SQL.Add(tSQL); FQuery.ReadOnly:=true; FQuery.Open; FDS.DataSet:=FQuery; FDBGR.DataSource:=FDS; //первоначальная настройка //сначало то, что видимое Fquery.Fields.FieldByName('TABNOM').DisplayWidth:=5; Fquery.Fields.FieldByName('TABNOM').DisplayLabel:='таб.№'; Fquery.Fields.FieldByName('FAM').DisplayWidth:=11; Fquery.Fields.FieldByName('FAM').DisplayLabel:='Фамилия'; Fquery.Fields.FieldByName('NAM').DisplayWidth:=9; Fquery.Fields.FieldByName('NAM').DisplayLabel:='Имя'; Fquery.Fields.FieldByName('OTCH').DisplayWidth:=14; Fquery.Fields.FieldByName('OTCH').DisplayLabel:='Отчество'; Fquery.Fields.FieldByName('post').DisplayWidth:=36; Fquery.Fields.FieldByName('post').DisplayLabel:='Должность'; Fquery.Fields.FieldByName('ngroup').DisplayWidth:=20; Fquery.Fields.FieldByName('ngroup').DisplayLabel:='Группа'; Fquery.Fields.FieldByName('DTB').DisplayWidth:=10; Fquery.Fields.FieldByName('DTB').DisplayLabel:='дата рождения'; Fquery.Fields.FieldByName('PLB').DisplayWidth:=10; Fquery.Fields.FieldByName('PLB').DisplayLabel:='место рождения'; Fquery.Fields.FieldByName('REGISTRATION').DisplayWidth:=10; Fquery.Fields.FieldByName('REGISTRATION').DisplayLabel:='место регистрации'; Fquery.Fields.FieldByName('loc').DisplayWidth:=10; Fquery.Fields.FieldByName('loc').DisplayLabel:='местоположение'; //теперь то, что не видимое Fquery.Fields.FieldByName('rr').Visible:=false; Fquery.Fields.FieldByName('rr').DisplayWidth:=5; Fquery.Fields.FieldByName('rr').DisplayLabel:='район'; Fquery.Fields.FieldByName('id').Visible:=false; Fquery.Fields.FieldByName('ID_PEOPLE').Visible:=false; //настраиваем кнопки данной сетки SettingPAG; result:=true; end; } end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TfMain = class(TForm) mmList: TMemo; procedure FormCreate(Sender: TObject); private procedure ReadXML; end; var fMain: TfMain; implementation uses System.Math, uXML; {$R *.dfm} procedure TfMain.FormCreate(Sender: TObject); begin Self.ReadXML; end; procedure TfMain.ReadXML; var oXMLResponseType: IXMLResponseType; oXMLItemType: IXMLItemType; nIndex: integer; begin oXMLResponseType := uXML.Loadresponse('../../mission19.xml'); mmList.Lines.Clear; for nIndex := ZeroValue to Pred(oXMLResponseType.Result.Count) do begin oXMLItemType := oXMLResponseType.Result.Item[nIndex]; mmList.Lines.Add('ID: ' + oXMLItemType.Id.ToString); mmList.Lines.Add('Name: ' + oXMLItemType.First_name); mmList.Lines.Add('Last name: ' + oXMLItemType.Last_name); mmList.Lines.Add('Gender: ' + oXMLItemType.Gender); mmList.Lines.Add('Date of birth: ' + oXMLItemType.Dob); mmList.Lines.Add('E-mail: ' + oXMLItemType.Email); mmList.Lines.Add('Phone: ' + oXMLItemType.Phone); mmList.Lines.Add('Website: ' + oXMLItemType.Website); mmList.Lines.Add('Address: ' + oXMLItemType.Address); mmList.Lines.Add('Status: ' + oXMLItemType.Status); mmList.Lines.Add('Link (HATEOAS):'); mmList.Lines.Add('|_ Resource: ' + oXMLItemType._links.Self.Href); mmList.Lines.Add('|_ Edit: ' + oXMLItemType._links.Edit.Href); mmList.Lines.Add('|_ Avatar: ' + oXMLItemType._links.Avatar.Href); end; end; end.