text
stringlengths
14
6.51M
{-------------------------------------------------- Progressive Path Tracing --------------------------------------------------- This unit contains types for a vector (TVector), a ray (TRay), and all the implemented geometric primitives, as descendants of the TPrimitive class. Those classes must expose three methods - an Intersect method which returns the distance along the ray passed as a parameter at which an intersection with said primitive occurs (the result is negative if no intersection exists), a NormalAt function which returns the surface normal at a given point (this point is guaranteed to be located on the primitive if and only if the primitive's Intersect function is accurate), and a constructor which takes as an input a pointer, which points to a memory range containing the primitive's description (for instance, a sphere would read its center and radius). Primitives must remember to call their inherited constructor at the end of their own constructor, passing an appropriately incremented pointer (that is, pointing to just after the memory range containing the primitive's information. This is to read the primitive's material. Primitive constructors can choose to read it themselves if they wish to, however (it's a Longword). -------------------------------------------------------------------------------------------------------------------------------} unit VectorTypes; interface uses SysUtils, Math; type { Defines a 3D vector. } TVector = record X, Y, Z: Double; end; PVector = ^TVector; { Defines a ray. } TRay = record Origin, Direction: TVector; end; PRay = ^TRay; { Helper function declarations. } function Vector(const X, Y, Z: Double): TVector; function RayBetween(const P1, P2: TVector): TRay; type { The base primitive class. } TPrimitive = class private FMaterial: Longword; public constructor Create(Data: Pointer); virtual; function Intersects(Ray: TRay): Double; virtual; abstract; function NormalAt(Point: TVector): TVector; virtual; abstract; property Material: Longword read FMaterial; end; { A sphere primitive. } TSphere = class(TPrimitive) private FCenter: TVector; FRadius: Double; FRadiusSquared: Double; public constructor Create(Data: Pointer); override; function Intersects(Ray: TRay): Double; override; function NormalAt(Point: TVector): TVector; override; property Center: TVector read FCenter; property Radius: Double read FRadius; end; { A plane primitive. } TPlane = class(TPrimitive) private FNormal, FPoint: TVector; public constructor Create(Data: Pointer); override; function Intersects(Ray: TRay): Double; override; function NormalAt(Point: TVector): TVector; override; property Normal: TVector read FNormal; property Point: TVector read FPoint; end; { A triangle primitive. } TTriangle = class(TPrimitive) private FPoints: array [0..2] of TVector; FNormal: TVector; FE1, FE2: TVector; function GetPoints(Index: Integer): TVector; public constructor Create(Data: Pointer); override; function Intersects(Ray: TRay): Double; override; function NormalAt(Point: TVector): TVector; override; property Points[Index: Integer]: TVector read GetPoints; end; implementation uses VectorMath; { Converts a triplet of (x, y, z) coordinates into a TVector record. } function Vector(const X, Y, Z: Double): TVector; begin Result.X := X; Result.Y := Y; Result.Z := Z; end; { Returns a normalized ray starting at P1 and going through P2. } function RayBetween(const P1, P2: TVector): TRay; begin Result.Origin := P1; Result.Direction := NormalizeVector(SubVector(P2, P1)); end; { -------------------------------------------------------- PRIMITIVE --------------------------------------------------------- } constructor TPrimitive.Create(Data: Pointer); begin { We just read the material indez. } FMaterial := PLongword(Data)^; end; { ---------------------------------------------------------- SPHERE ---------------------------------------------------------- } constructor TSphere.Create(Data: Pointer); Var P: PDouble; begin { A sphere is defined by a center and a radius, so we need to read 4 doubles from the scene data stream. } P := Data; FCenter.X := P^; Inc(P); FCenter.Y := P^; Inc(P); FCenter.Z := P^; Inc(P); FRadius := P^; Inc(P); inherited Create(P); FRadiusSquared := FRadius * FRadius; end; function TSphere.Intersects(Ray: TRay): Double; Var qA, qB, qC, Delta, P1, P2: Double; begin { Transform the ray origin to sphere center. } Ray.Origin := SubVector(Ray.Origin, FCenter); { Compute the quadratic terms. } qA := SelfDotVector(Ray.Direction); qB := 2 * DotVector(Ray.Direction, Ray.Origin); qC := SelfDotVector(Ray.Origin) - FRadiusSquared; { Compute the discriminant. } Delta := qB * qB - 4 * qA * qC; { If there is no solution, return a negative number. } if (Delta < 0) then Result := -1 else begin { Otherwise, compute the two solutions, and decide which one to return. } Delta := Sqrt(Delta); qA := qA * 2; qB := -qB; P1 := (qB + Delta) / qA; P2 := (qB - Delta) / qA; if (P1 < 0) then begin Result := P2; Exit; end; // regardless since negative result = no intersection if (P2 < 0) then begin Result := P1; Exit; end; // regardless since negative result = no intersection Result := Min(P1, P2); end; end; function TSphere.NormalAt(Point: TVector): TVector; begin { This one is easy, just take the vector from the sphere's center to the point and normalize. Note that since the sphere's intersection code is correct, we know that Point will always be located on the sphere. We can therefore take a shortcut and simply divide by the radius instead of going through the whole normalization process. } Result := DivVector(SubVector(Point, FCenter), FRadius); end; { ---------------------------------------------------------- PLANE ----------------------------------------------------------- } constructor TPlane.Create(Data: Pointer); Var P: PDouble; begin { A plane is defined by a point on the plane, and a normal vector. } P := Data; FNormal.X := P^; Inc(P); FNormal.Y := P^; Inc(P); FNormal.Z := P^; Inc(P); FPoint.X := P^; Inc(P); FPoint.Y := P^; Inc(P); FPoint.Z := P^; Inc(P); inherited Create(P); end; function TPlane.Intersects(Ray: TRay): Double; Var dn: Double; begin { Compute the denominator. } dn := DotVector(Ray.Direction, FNormal); { If the denominator is dangerously close to zero, there is no intersection (means the ray is almost parallel to the plane). } if Abs(dn) < 0.0000001 then Result := -1 else begin { Compute the numerator and divide. } Result := DotVector(SubVector(FPoint, Ray.Origin), FNormal) / dn; end; end; function TPlane.NormalAt(Point: TVector): TVector; begin { A plane is actually defined by its normal so there is no need to calculate it - it's given to us. } Result := FNormal; end; { --------------------------------------------------------- TRIANGLE --------------------------------------------------------- } constructor TTriangle.Create(Data: Pointer); Var I: Longword; P: PDouble; begin { A triangle is defined by three vectors representing the triangle's vertices. } P := Data; for I := 0 to 2 do begin FPoints[I].X := P^; Inc(P); FPoints[I].Y := P^; Inc(P); FPoints[I].Z := P^; Inc(P); end; { Call the inherited constructor). } inherited Create(P); { Precompute some values. } FE1 := SubVector(FPoints[1], FPoints[0]); FE2 := SubVector(FPoints[2], FPoints[0]); { The triangle's normal at any point is the cross product of (Point1 - Point0) and (Point2 - Point0). Note that this makes the order of the vertices important, as inverting two vertices will invert the normal too, this is known as winding. } FNormal := NormalizeVector(CrossVector(FE1, FE2)); end; function TTriangle.GetPoints(Index: Integer): TVector; begin Result := FPoints[Index]; end; function TTriangle.Intersects(Ray: TRay): Double; Var H, S, Q: TVector; A, U, V: Double; begin { I tried to simplify and optimise a code found online. } { This code is NOT optimal for triangle intersection, because it involves a normalization to obtain the "t" parameter of the ray. } H := CrossVector(Ray.Direction, FE2); A := DotVector(H, FE1); if (Abs(A) < 0.00001) then Result := -1 else begin A := 1 / A; S := SubVector(Ray.Origin, FPoints[0]); U := A * DotVector(S, H); if (U < 0.0) or (U > 1) then Result := -1 else begin Q := CrossVector(S, FE1); V := A * DotVector(Ray.Direction, Q); { If both barycentric coordinates U, V are between 0 and 1, we use the barycentric formula to retrieve the intersection distance. } if (V < 0.0) or (U + V > 1.0) then Result := -1 else if (Abs(A * DotVector(FE2, Q)) < 0.00001) then Result := -1 else Result := LengthVector(SubVector(AddVector(AddVector(MulVector(FPoints[0], 1 - u - v), MulVector(FPoints[1], u)), MulVector(FPoints[2], v)), Ray.Origin)); end; end; end; function TTriangle.NormalAt(Point: TVector): TVector; begin { The normal has been precomputed since it is independent of the point's location. } Result := FNormal; end; end.
unit SelLangForm; { Inno Setup Copyright (C) 1997-2006 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. "Select Language" form $jrsoftware: issrc/Projects/SelLangForm.pas,v 1.18 2010/01/13 17:48:52 mlaan Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, SetupForm, StdCtrls, ExtCtrls, NewStaticText, BitmapImage, BidiCtrls; type TSelectLanguageForm = class(TSetupForm) SelectLabel: TNewStaticText; LangCombo: TNewComboBox; OKButton: TNewButton; CancelButton: TNewButton; IconBitmapImage: TBitmapImage; private { Private declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; end; function AskForLanguage: Boolean; implementation uses Struct, Msgs, MsgIDs, Main; {$R *.DFM} var DefComboWndProcW, PrevComboWndProc: Pointer; function NewComboWndProc(Wnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; begin case Msg of { CB_ADDSTRING must pass to the default Unicode combo box window procedure since PrevWndProc is an ANSI window procedure and calling it would result in Unicode->ANSI conversion. Do the same for CB_GETLBTEXT(LEN) so that MSAA sees Unicode strings. } CB_ADDSTRING, CB_GETLBTEXT, CB_GETLBTEXTLEN: Result := CallWindowProcW(DefComboWndProcW, Wnd, Msg, wParam, lParam) else Result := CallWindowProcW(PrevComboWndProc, Wnd, Msg, wParam, lParam); end; end; function AskForLanguage: Boolean; { Creates and shows the "Select Language" dialog. Returns True and activates the selected language if the user clicks OK, or False otherwise. } var LangForm: TSelectLanguageForm; I, J: Integer; LangEntry: PSetupLanguageEntry; {$IFNDEF UNICODE} ClassInfo: TWndClassW; N: String; {$ENDIF} PrevLang: String; begin LangForm := TSelectLanguageForm.Create(Application); try {$IFNDEF UNICODE} { On NT, make it possible to add Unicode strings to our ANSI combo box by installing a window procedure with special CB_ADDSTRING handling. Yeah, this is a hack; it's too hard to create a native Unicode control in Delphi. } if Win32Platform = VER_PLATFORM_WIN32_NT then begin if GetClassInfoW(0, 'COMBOBOX', ClassInfo) then begin DefComboWndProcW := ClassInfo.lpfnWndProc; Longint(PrevComboWndProc) := SetWindowLongW(LangForm.LangCombo.Handle, GWL_WNDPROC, Longint(@NewComboWndProc)); end; end; {$ENDIF} for I := 0 to Entries[seLanguage].Count-1 do begin LangEntry := Entries[seLanguage][I]; {$IFDEF UNICODE} J := LangForm.LangCombo.Items.Add(LangEntry.LanguageName); LangForm.LangCombo.Items.Objects[J] := TObject(I); {$ELSE} if (I = ActiveLanguage) or (LangEntry.LanguageCodePage = 0) or (LangEntry.LanguageCodePage = GetACP) or (shShowUndisplayableLanguages in SetupHeader.Options) then begin { Note: LanguageName is Unicode } N := LangEntry.LanguageName + #0#0; { need wide null! } if Win32Platform = VER_PLATFORM_WIN32_NT then J := SendMessageW(LangForm.LangCombo.Handle, CB_ADDSTRING, 0, Longint(PWideChar(Pointer(N)))) else J := LangForm.LangCombo.Items.Add(WideCharToString(PWideChar(Pointer(N)))); if J >= 0 then LangForm.LangCombo.Items.Objects[J] := TObject(I); end; {$ENDIF} end; { If there's multiple languages, select the previous language, if available } if (shUsePreviousLanguage in SetupHeader.Options) and (LangForm.LangCombo.Items.Count > 1) then begin { do not localize or change the following string } PrevLang := GetPreviousData(ExpandConst(SetupHeader.AppId), 'Inno Setup: Language', ''); if PrevLang <> '' then begin for I := 0 to Entries[seLanguage].Count-1 do begin if CompareText(PrevLang, PSetupLanguageEntry(Entries[seLanguage][I]).Name) = 0 then begin LangForm.LangCombo.ItemIndex := LangForm.LangCombo.Items.IndexOfObject(TObject(I)); Break; end; end; end; end; { Select the active language if no previous language was selected } if LangForm.LangCombo.ItemIndex = -1 then LangForm.LangCombo.ItemIndex := LangForm.LangCombo.Items.IndexOfObject(TObject(ActiveLanguage)); if LangForm.LangCombo.Items.Count > 1 then begin Result := (LangForm.ShowModal = mrOK); if Result then begin I := LangForm.LangCombo.ItemIndex; if I >= 0 then SetActiveLanguage(Integer(LangForm.LangCombo.Items.Objects[I])); end; end else begin { Don't show language dialog if there aren't multiple languages to choose from, which can happen if only one language matches the user's code page. } Result := True; end; finally LangForm.Free; end; end; { TSelectLanguageForm } constructor TSelectLanguageForm.Create(AOwner: TComponent); begin inherited; InitializeFont; Center; Caption := SetupMessages[msgSelectLanguageTitle]; SelectLabel.Caption := SetupMessages[msgSelectLanguageLabel]; OKButton.Caption := SetupMessages[msgButtonOK]; CancelButton.Caption := SetupMessages[msgButtonCancel]; IconBitmapImage.Bitmap.Canvas.Brush.Color := Color; IconBitmapImage.Bitmap.Width := Application.Icon.Width; IconBitmapImage.Bitmap.Height := Application.Icon.Height; IconBitmapImage.Bitmap.Canvas.Draw(0, 0, Application.Icon); IconBitmapImage.Width := IconBitmapImage.Bitmap.Width; IconBitmapImage.Height := IconBitmapImage.Bitmap.Height; end; end.
unit UImportaExcel; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ComObj, Vcl.StdCtrls, Vcl.Buttons, FireDac.Comp.Client, Vcl.Grids, Vcl.ExtCtrls, Vcl.Samples.Gauges; type TFImportaExcel = class(TForm) OpenDialog1: TOpenDialog; StringGrid1: TStringGrid; ScrollBox1: TScrollBox; btnImportarExcel: TBitBtn; BitBtn1: TBitBtn; btnGerarScript: TBitBtn; GroupBox1: TGroupBox; rgTipos: TRadioGroup; btnExportarTabela: TBitBtn; PNomeTabela: TPanel; BitBtn2: TBitBtn; gbProgressBar: TGroupBox; Gauge1: TGauge; procedure btnImportarExcelClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure StringGrid1DblClick(Sender: TObject); procedure StringGrid1Exit(Sender: TObject); procedure btnGerarScriptClick(Sender: TObject); procedure btnExportarTabelaClick(Sender: TObject); procedure BitBtn2Click(Sender: TObject); private { Private declarations } function XlsToStringGrid(XStringGrid: TStringGrid; xFileXLS: string): Boolean; function NomeTabela(Campo: String): String; function fncConfiguraColunas(vloStringGrid : TStringGrid):Boolean; function fncRetornaTipoCampo(Campo: String): String; public { Public declarations } vlsPrimeiroCampo, vlsNomeTabela : String; procedure ExcluirDadosTabela(Tabela: String); end; var FImportaExcel: TFImportaExcel; implementation {$R *.dfm} uses ULeScript, UExportaTabela, UDMPrincipal; { TForm1 } procedure TFImportaExcel.BitBtn1Click(Sender: TObject); begin Close; end; procedure TFImportaExcel.BitBtn2Click(Sender: TObject); begin if fncConfiguraColunas(StringGrid1) then begin StringGrid1.Refresh; ShowMessage('Tabela Configurada com sucesso!'); end; end; procedure TFImportaExcel.btnExportarTabelaClick(Sender: TObject); begin Application.CreateForm(TFExportaTabela, FExportaTabela); FExportaTabela.ShowModal; FreeAndNil(FExportaTabela); end; procedure TFImportaExcel.btnGerarScriptClick(Sender: TObject); var vlsDadosComando, vlsStringComando : String; vlLinhas: Integer; vlColunas: Integer; vlsStringListComando : TStringList; begin if StringGrid1.RowCount > 1 then begin try vlsStringListComando := TStringList.Create; ExcluirDadosTabela(vlsNomeTabela); for vlLinhas := 0 to StringGrid1.RowCount -1 do begin vlsDadosComando := ''; for vlColunas := 0 to StringGrid1.Rows[vlLinhas].Count - 1 do begin if vlLinhas = 0 then begin if Trim(vlsDadosComando) = '' then vlsDadosComando := Trim(StringGrid1.Rows[vlLinhas].Strings[vlColunas]) else vlsDadosComando := vlsDadosComando + ', ' + Trim(StringGrid1.Rows[vlLinhas].Strings[vlColunas]); end else begin if Trim(vlsDadosComando) = '' then vlsDadosComando := QuotedStr(Trim(StringGrid1.Rows[vlLinhas].Strings[vlColunas])) else vlsDadosComando := vlsDadosComando + ',' + QuotedStr(Trim(StringGrid1.Rows[vlLinhas].Strings[vlColunas])); end; end; if vlLinhas = 0 then begin if rgTipos.ItemIndex = 0 then begin vlsStringComando := 'INSERT INTO '+FLeScript.vlsTabela+' ('+vlsDadosComando+') VALUES'; end else if rgTipos.ItemIndex = 1 then begin ShowMessage('Não implementado nessa versão!'); Abort; end else if rgTipos.ItemIndex = 2 then begin ShowMessage('Não implementado nessa versão!'); Abort; end else if rgTipos.ItemIndex = 3 then begin ShowMessage('Não implementado nessa versão!'); Abort; end; end else begin if rgTipos.ItemIndex = 0 then begin if Trim(vlsDadosComando) <> '' then begin vlsStringListComando.Add(vlsStringComando + ' ('+vlsDadosComando+');'); end; end else if rgTipos.ItemIndex = 1 then begin ShowMessage('Não implementado nessa versão!'); Abort; end else if rgTipos.ItemIndex = 2 then begin ShowMessage('Não implementado nessa versão!'); Abort; end else if rgTipos.ItemIndex = 3 then begin ShowMessage('Não implementado nessa versão!'); Abort; end; end; end; FLeScript.MScript.Lines.Clear; FLeScript.MScript.Lines.AddStrings(vlsStringListComando); FLeScript.MScript.Hint := 'Importado pelo Excel!'; FLeScript.MScript.ShowHint := True; FLeScript.MScript.ReadOnly := True; FLeScript.MScript.Enabled := True; FLeScript.MScript.SetFocus; FLeScript.btnSalva.Enabled := True; FLeScript.btnLocaliza.Enabled := True; FLeScript.btnImprime.Enabled := True; FLeScript.btnExecuta.Enabled := True; if FLeScript.MScript.Lines.Count > 0 then begin FLeScript.MScript.Height := 564; FLeScript.btnEditar.Visible := True; FLeScript.btnGravarAlt.Visible := True; FLeScript.btnEditar.Enabled := True; FLeScript.btnGravarAlt.Enabled := False; FLeScript.lblQtdeLinhas.Caption := ''; FLeScript.lblQtdeLinhas.Caption := IntToStr(FLeScript.MScript.Lines.Count); end; Close; Application.ProcessMessages; finally FreeAndNil(vlsStringListComando); end; end; end; procedure TFImportaExcel.btnImportarExcelClick(Sender: TObject); begin OpenDialog1.Title := 'Carregando arquivo de Excel'; OpenDialog1.Filter := 'Arquivos de Excel|*.xlsx|Arquivos de Excel 97-2003|*.xls'; try OpenDialog1.InitialDir := ExtractFilePath(Application.ExeName); except on e : exception do begin ShowMessage('Erro com a mensagem: ' + e.Message); end; end; if OpenDialog1.Execute then Begin try StringGrid1.RowCount := 0; XlsToStringGrid(StringGrid1,OpenDialog1.FileName) except StringGrid1.RowCount := 0; XlsToStringGrid(StringGrid1,OpenDialog1.FileName) end; FLeScript.vlsTabela := ''; FLeScript.vlsTabela := NomeTabela(vlsPrimeiroCampo); StringGrid1.Hint := OpenDialog1.FileName; StringGrid1.ShowHint := True; fncConfiguraColunas(StringGrid1); end; end; procedure TFImportaExcel.FormShow(Sender: TObject); begin StringGrid1.RowCount := 0; StringGrid1.ColCount := 0; PNomeTabela.Visible := False; end; procedure TFImportaExcel.StringGrid1DblClick(Sender: TObject); begin StringGrid1.Options := StringGrid1.Options + [goEditing]; end; procedure TFImportaExcel.StringGrid1Exit(Sender: TObject); begin StringGrid1.Options := StringGrid1.Options - [goEditing]; end; Function TFImportaExcel.XlsToStringGrid(xStringGrid: TStringGrid; xFileXLS: string): Boolean; const xlCellTypeLastCell = $0000000B; var XLSAplicacao, AbaXLS: OLEVariant; RangeMatrix: Variant; x, y, k, r, vliTamanhoColuna: Integer; begin Result := False; // Cria Excel- OLE Object XLSAplicacao := CreateOleObject('Excel.Application'); try // Esconde Excel XLSAplicacao.Visible := False; // Abre o Workbook XLSAplicacao.Workbooks.Open(xFileXLS); AbaXLS := XLSAplicacao.Workbooks[ExtractFileName(xFileXLS)].WorkSheets[1]; AbaXLS.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate; // Pegar o número da última linha x := XLSAplicacao.ActiveCell.Row; // Pegar o número da última coluna y := XLSAplicacao.ActiveCell.Column; // Seta xStringGrid linha e coluna XStringGrid.RowCount := x; XStringGrid.ColCount := y; // Associaca a variant WorkSheet com a variant do Delphi RangeMatrix := XLSAplicacao.Range['A1', XLSAplicacao.Cells.Item[x, y]].Value; // Cria o loop para listar os registros no TStringGrid k := 1; vlsPrimeiroCampo := ''; try vlsPrimeiroCampo := RangeMatrix[1, 2]; except vlsPrimeiroCampo := RangeMatrix[1, 1]; end; repeat for r := 1 to y do XStringGrid.Cells[(r - 1), (k - 1)] := RangeMatrix[k, r]; Inc(k, 1); until k > x; for r := 1 to y do begin vliTamanhoColuna := Length(RangeMatrix[1, r]) * 8; StringGrid1.ColWidths[r - 1] := vliTamanhoColuna; end; RangeMatrix := Unassigned; finally // Fecha o Microsoft Excel if not VarIsEmpty(XLSAplicacao) then begin XLSAplicacao.Quit; XLSAplicacao := Unassigned; AbaXLS := Unassigned; Result := True; end; end; end; function TFImportaExcel.NomeTabela(Campo : String) : String; var QTabela : TFDQuery; begin QTabela := TFDQuery.Create(nil); try QTabela.Close; QTabela.Connection := FLeScript.vgConexao; QTabela.SQL.Clear; QTabela.SQL.Add('SELECT RDB$RELATION_NAME AS TABELA FROM RDB$RELATION_FIELDS'); QTabela.SQL.Add('WHERE RDB$FIELD_NAME = :CAMPO'); QTabela.SQL.Add('ORDER BY RDB$FIELD_POSITION'); QTabela.ParamByName('CAMPO').AsString := Campo; QTabela.Open; if not QTabela.IsEmpty then begin Result := QTabela.FieldByName('TABELA').AsString; PNomeTabela.Caption := ' TABELA: ' + UpperCase(QTabela.FieldByName('TABELA').AsString); PNomeTabela.Visible := True; vlsNomeTabela := UpperCase(QTabela.FieldByName('TABELA').AsString); end else ShowMessage('Campo: ' + Campo + ' não contem em nenhuma tabela!'); finally FreeAndNil(QTabela); end; end; function TFImportaExcel.fncConfiguraColunas(vloStringGrid : TStringGrid):Boolean; var I, vlI: Integer; vlsTipoCampos, vlsString : String; begin Result := False; if vloStringGrid.RowCount > 1 then begin Result := True; try gbProgressBar.Visible := True; Gauge1.Progress := 0; gbProgressBar.Caption := 'Corrigindo linha 1 de ' + IntToStr(vloStringGrid.RowCount - 1); Gauge1.MaxValue := vloStringGrid.RowCount - 1; Application.ProcessMessages; for I := 1 to vloStringGrid.RowCount do //Qtde Linhas begin for vlI := 0 to vloStringGrid.ColCount do //Qtde Colunas begin if Trim(vloStringGrid.Cells[1, I]) <> '' then begin vlsTipoCampos := fncRetornaTipoCampo(vloStringGrid.Cells[vlI, 0]); if vloStringGrid.Cells[vlI, I] = '30/12/1899' then //Corrigi a data para 01/01/1900 begin vloStringGrid.Cells[vlI, I] := '01/01/1900'; end; if vlsTipoCampos = 'BOOLEAN' then //Corrigi campos booleanos begin vlsString := vloStringGrid.Cells[vlI, 0]; vlsString := vloStringGrid.Cells[vlI, I]; if Trim(vloStringGrid.Cells[vlI, I]) = '' then vloStringGrid.Cells[vlI, I] := 'False'; end; if vlsTipoCampos = 'DOUBLE' then //Corrigi campos booleanos begin vlsString := vloStringGrid.Cells[vlI, 0]; vlsString := vloStringGrid.Cells[vlI, I]; if vlsString = '' then ShowMessage('Fodeo'); vloStringGrid.Cells[vlI, I] := StringReplace(vloStringGrid.Cells[vlI, I], ',','.',[rfReplaceAll, rfIgnoreCase]) end; if (vlsTipoCampos = 'DATE') and (Trim(vloStringGrid.Cells[vlI, I]) = '') then //Corrigi campos booleanos begin vlsString := vloStringGrid.Cells[vlI, I]; vloStringGrid.Cells[vlI, I] := '01/01/1900'; end; end else begin Exit; end; end; Gauge1.Progress := Gauge1.Progress + 1; gbProgressBar.Caption := 'Corrigindo linha '+IntToStr(I)+' de ' + IntToStr(vloStringGrid.RowCount - 1); Application.ProcessMessages; end; finally gbProgressBar.Visible := False; end; end; end; function TFImportaExcel.fncRetornaTipoCampo(Campo : String) : String; var QTabela : TFDQuery; begin QTabela := TFDQuery.Create(nil); try QTabela.Close; QTabela.Connection := FLeScript.vgConexao; QTabela.SQL.Clear; QTabela.SQL.Add('SELECT'); QTabela.SQL.Add('R.RDB$FIELD_SOURCE AS "DOMÍNIO",'); QTabela.SQL.Add('F.RDB$FIELD_LENGTH AS TAMANHO,'); QTabela.SQL.Add('CASE F.RDB$FIELD_TYPE'); QTabela.SQL.Add(' WHEN 261 THEN ''BLOB'''); QTabela.SQL.Add(' WHEN 14 THEN ''CHAR'''); QTabela.SQL.Add(' WHEN 40 THEN ''CSTRING'''); QTabela.SQL.Add(' WHEN 11 THEN ''D_FLOAT'''); QTabela.SQL.Add(' WHEN 27 THEN ''DOUBLE'''); QTabela.SQL.Add(' WHEN 10 THEN ''FLOAT'''); QTabela.SQL.Add(' WHEN 16 THEN ''INT64'''); QTabela.SQL.Add(' WHEN 8 THEN ''INTEGER'''); QTabela.SQL.Add(' WHEN 9 THEN ''QUAD'''); QTabela.SQL.Add(' WHEN 7 THEN ''SMALLINT'''); QTabela.SQL.Add(' WHEN 12 THEN ''DATE'''); QTabela.SQL.Add(' WHEN 13 THEN ''TIME'''); QTabela.SQL.Add(' WHEN 35 THEN ''TIMESTAMP'''); QTabela.SQL.Add(' WHEN 37 THEN ''VARCHAR'''); QTabela.SQL.Add(' ELSE ''UNKNOWN'''); QTabela.SQL.Add('END AS TIPO'); QTabela.SQL.Add('FROM RDB$RELATION_FIELDS R'); QTabela.SQL.Add('LEFT JOIN RDB$FIELDS F ON R.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME'); QTabela.SQL.Add('WHERE R.RDB$RELATION_NAME= :TABELA AND R.RDB$FIELD_NAME =:CAMPO'); QTabela.SQL.Add('ORDER BY R.RDB$FIELD_POSITION;'); QTabela.ParamByName('TABELA').AsString := vlsNomeTabela; QTabela.ParamByName('CAMPO').AsString := Campo; QTabela.Open; if ((QTabela.FieldByName('TIPO').AsString = 'VARCHAR') AND (QTabela.FieldByName('TAMANHO').AsInteger = 5) AND (QTabela.FieldByName('DOMÍNIO').AsString = 'BOLEANO')) then Result := 'BOOLEAN' else Result := QTabela.FieldByName('TIPO').AsString; finally FreeAndNil(QTabela); end; end; procedure TFImportaExcel.ExcluirDadosTabela(Tabela : String); var QTabela : TFDQuery; begin QTabela := TFDQuery.Create(nil); try if MessageDlg('Deseja apagar os dados da tabela: ' +Tabela+ ' antes da importação?', MtConfirmation, [mbYes, mbNo], 0) = MrYes then begin QTabela.Close; QTabela.Connection := FLeScript.vgConexao; QTabela.SQL.Clear; QTabela.SQL.Add('DELETE FROM ' + Tabela); QTabela.ExecSQL; end; finally FreeAndNil(QTabela); end; end; end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.Filter; {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, CP.IntegralImage; type TComparator = function(a, b: double): double; { TFilter } TFilter = class(TObject) private FType: integer; FY: integer; FHeight: integer; FWidth: integer; public property _Type: integer read FType write FType; property Y: integer read FY write FY; property Height: integer read FHeight write FHeight; property Width: integer read FWidth write FWidth; public constructor Create(_Type: integer = 0; Y: integer = 0; Height: integer = 0; Width: integer = 0); function Apply(image: TIntegralImage; offset: integer): double; end; implementation uses {$IFDEF FPC} DaMath; {$ELSE} Math; {$ENDIF} { TFilter } function Subtract(a, b: double): double; inline; begin Result := a - b; end; function SubtractLog(a, b: double): double; inline; var r: double; begin r := ln(1.0 + a) - ln(1.0 + b); // assert(!IsNaN(r)); Result := r; end; // oooooooooooooooo // oooooooooooooooo // oooooooooooooooo // oooooooooooooooo function Filter0(image: TIntegralImage; x, Y, w, h: integer; cmp: TComparator): double; var a, b: double; begin a := image.Area(x, Y, x + w - 1, Y + h - 1); b := 0; Result := cmp(a, b); end; // ................ // ................ // oooooooooooooooo // oooooooooooooooo function Filter1(image: TIntegralImage; x, Y, w, h: integer; cmp: TComparator): double; var a, b: double; h_2: integer; begin h_2 := h div 2; a := image.Area(x, Y + h_2, x + w - 1, Y + h - 1); b := image.Area(x, Y, x + w - 1, Y + h_2 - 1); Result := cmp(a, b); end; // .......ooooooooo // .......ooooooooo // .......ooooooooo // .......ooooooooo function Filter2(image: TIntegralImage; x, Y, w, h: integer; cmp: TComparator): double; var a, b: double; w_2: integer; begin w_2 := w div 2; a := image.Area(x + w_2, Y, x + w - 1, Y + h - 1); b := image.Area(x, Y, x + w_2 - 1, Y + h - 1); Result := cmp(a, b); end; // .......ooooooooo // .......ooooooooo // ooooooo......... // ooooooo......... function Filter3(image: TIntegralImage; x, Y, w, h: integer; cmp: TComparator): double; var a, b: double; w_2, h_2: integer; begin w_2 := w div 2; h_2 := h div 2; a := image.Area(x, Y + h_2, x + w_2 - 1, Y + h - 1) + image.Area(x + w_2, Y, x + w - 1, Y + h_2 - 1); b := image.Area(x, Y, x + w_2 - 1, Y + h_2 - 1) + image.Area(x + w_2, Y + h_2, x + w - 1, Y + h - 1); Result := cmp(a, b); end; // ................ // oooooooooooooooo // ................ function Filter4(image: TIntegralImage; x, Y, w, h: integer; cmp: TComparator): double; var a, b: double; h_3: integer; begin h_3 := h div 3; a := image.Area(x, Y + h_3, x + w - 1, Y + 2 * h_3 - 1); b := image.Area(x, Y, x + w - 1, Y + h_3 - 1) + image.Area(x, Y + 2 * h_3, x + w - 1, Y + h - 1); Result := cmp(a, b); end; // .....oooooo..... // .....oooooo..... // .....oooooo..... // .....oooooo..... function Filter5(image: TIntegralImage; x, Y, w, h: integer; cmp: TComparator): double; var a, b: double; w_3: integer; begin w_3 := w div 3; a := image.Area(x + w_3, Y, x + 2 * w_3 - 1, Y + h - 1); b := image.Area(x, Y, x + w_3 - 1, Y + h - 1) + image.Area(x + 2 * w_3, Y, x + w - 1, Y + h - 1); Result := cmp(a, b); end; constructor TFilter.Create(_Type: integer; Y: integer; Height: integer; Width: integer); begin FType := _Type; FY := Y; FHeight := Height; FWidth := Width; end; function TFilter.Apply(image: TIntegralImage; offset: integer): double; begin case (FType) of 0: Result := Filter0(image, offset, FY, FWidth, FHeight, SubtractLog); 1: Result := Filter1(image, offset, FY, FWidth, FHeight, SubtractLog); 2: Result := Filter2(image, offset, FY, FWidth, FHeight, SubtractLog); 3: Result := Filter3(image, offset, FY, FWidth, FHeight, SubtractLog); 4: Result := Filter4(image, offset, FY, FWidth, FHeight, SubtractLog); 5: Result := Filter5(image, offset, FY, FWidth, FHeight, SubtractLog); else Result := 0.0; end; end; end.
namespace Sugar; interface type GuidFormat = public enum (&Default, Braces, Parentheses); {$IF ECHOES}[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Auto, Size := 1)]{$ENDIF} Guid = public {$IF COOPER}class mapped to java.util.UUID{$ELSEIF ECHOES}record mapped to System.Guid{$ELSEIF TOFFEE}class{$ENDIF} private {$IF ECHOES} class method Exchange(Value: array of Byte; Index1, Index2: Integer); {$ELSEIF TOFFEE} fData: array of Byte; method AppendRange(Data: NSMutableString; Range: NSRange); class method InternalParse(Data: String): array of Byte; {$ENDIF} public constructor; constructor(Value: array of Byte); method CompareTo(Value: Guid): Integer; method &Equals(Value: Guid): Boolean; class method NewGuid: Guid; class method Parse(Value: String): Guid; {$IF COOPER} {$ELSE} [Obsolete('Use Empty method instead.')] {$ENDIF} class method EmptyGuid: Guid; class method &Empty: Guid; method ToByteArray: array of Byte; method ToString(Format: GuidFormat): String; {$IF COOPER} method ToString: java.lang.String; override; {$ELSEIF ECHOES} method ToString: System.String; override; {$ELSEIF TOFFEE} method description: NSString; override; {$ENDIF} end; implementation constructor Guid; begin {$IF COOPER} exit new java.util.UUID(0, 0); {$ELSEIF ECHOES} exit mapped.Empty; {$ELSEIF TOFFEE} fData := new Byte[16]; memset(fData, 0, 16); {$ENDIF} end; constructor Guid(Value: array of Byte); begin {$IF COOPER} var bb := java.nio.ByteBuffer.wrap(Value); exit new java.util.UUID(bb.getLong, bb.getLong); {$ELSEIF ECHOES} Exchange(Value, 0, 3); Exchange(Value, 1, 2); Exchange(Value, 4, 5); Exchange(Value, 6, 7); exit new System.Guid(Value); {$ELSEIF TOFFEE} fData := new Byte[16]; memcpy(fData, Value, 16); {$ENDIF} end; method Guid.CompareTo(Value: Guid): Integer; begin {$IF COOPER OR ECHOES} exit mapped.CompareTo(Value); {$ELSEIF TOFFEE} exit memcmp(fData, Value.fData, 16); {$ENDIF} end; method Guid.Equals(Value: Guid): Boolean; begin {$IF COOPER OR ECHOES} exit mapped.Equals(Value); {$ELSEIF TOFFEE} exit CompareTo(Value) = 0; {$ENDIF} end; class method Guid.NewGuid: Guid; begin {$IF COOPER} exit mapped.randomUUID; {$ELSEIF ECHOES} exit mapped.NewGuid; {$ELSEIF TOFFEE} var UUID: CFUUIDRef := CFUUIDCreate(kCFAllocatorDefault); var RefBytes: CFUUIDBytes := CFUUIDGetUUIDBytes(UUID); CFRelease(UUID); var Data := new Byte[16]; memcpy(Data, @RefBytes, 16); exit new Guid(Data); {$ENDIF} end; class method Guid.Parse(Value: String): Guid; begin if (Value.Length <> 38) and (Value.Length <> 36) then raise new SugarFormatException(ErrorMessage.FORMAT_ERROR); {$IF COOPER} if Value.Chars[0] = '{' then begin if Value.Chars[37] <> '}' then raise new SugarFormatException(ErrorMessage.FORMAT_ERROR); end else if Value.Chars[0] = '(' then begin if Value.Chars[37] <> ')' then raise new SugarFormatException(ErrorMessage.FORMAT_ERROR); end; Value := java.lang.String(Value.ToUpper).replaceAll("[{}()]", ""); exit mapped.fromString(Value); {$ELSEIF ECHOES} exit new System.Guid(Value); {$ELSEIF TOFFEE} var Data := InternalParse(Value); exit new Guid(Data); {$ENDIF} end; class method Sugar.Guid.Empty: Guid; begin {$IF COOPER} exit new java.util.UUID(0, 0); {$ELSEIF ECHOES} exit mapped.Empty; {$ELSEIF TOFFEE} exit new Guid; {$ENDIF} end; class method Guid.EmptyGuid: Guid; begin exit &Empty; end; method Guid.ToByteArray: array of Byte; begin {$IF COOPER} var buffer := java.nio.ByteBuffer.wrap(new SByte[16]); buffer.putLong(mapped.MostSignificantBits); buffer.putLong(mapped.LeastSignificantBits); exit buffer.array; {$ELSEIF ECHOES} var Value := mapped.ToByteArray; //reverse byte order to normal (.NET reverse first 4 bytes and next two 2 bytes groups) Exchange(Value, 0, 3); Exchange(Value, 1, 2); Exchange(Value, 4, 5); Exchange(Value, 6, 7); exit Value; {$ELSEIF TOFFEE} result := new Byte[16]; memcpy(result, fData, 16); {$ENDIF} end; method Guid.ToString(Format: GuidFormat): String; begin {$IF COOPER} case Format of Format.Default: result := mapped.toString; Format.Braces: result := "{"+mapped.toString+"}"; Format.Parentheses: result := "("+mapped.toString+")"; else result := mapped.toString; end; exit result.ToUpper; {$ELSEIF ECHOES} case Format of Format.Default: result := mapped.ToString("D"); Format.Braces: result := mapped.ToString("B"); Format.Parentheses: result := mapped.ToString("P"); else result := mapped.ToString("D"); end; exit result.ToUpper; {$ELSEIF TOFFEE} var GuidString := new NSMutableString(); AppendRange(GuidString, NSMakeRange(0, 3)); GuidString.appendString("-"); AppendRange(GuidString, NSMakeRange(4, 5)); GuidString.appendString("-"); AppendRange(GuidString, NSMakeRange(6, 7)); GuidString.appendString("-"); AppendRange(GuidString, NSMakeRange(8, 9)); GuidString.appendString("-"); AppendRange(GuidString, NSMakeRange(10, 15)); case Format of Format.Default: exit GuidString; Format.Braces: exit "{"+GuidString+"}"; Format.Parentheses: exit "("+GuidString+")"; else exit GuidString; end; {$ENDIF} end; {$IF COOPER} method Guid.ToString: java.lang.String; begin exit self.ToString(GuidFormat.Default); end; {$ELSEIF ECHOES} method Guid.ToString: System.String; begin exit self.ToString(GuidFormat.Default); end; class method Guid.Exchange(Value: array of Byte; Index1: Integer; Index2: Integer); begin var Temp := Value[Index1]; Value[Index1] := Value[Index2]; Value[Index2] := Temp; end; {$ELSEIF TOFFEE} method Guid.AppendRange(Data: NSMutableString; Range: NSRange); begin for i: Integer := Range.location to Range.length do Data.appendFormat("%02hhX", fData[i]); end; method Guid.description: NSString; begin exit self.ToString(GuidFormat.Default); end; class method Guid.InternalParse(Data: String): array of Byte; begin var Offset: Int32; if (Data.Length <> 38) and (Data.Length <> 36) then raise new SugarFormatException(ErrorMessage.FORMAT_ERROR); if Data.Chars[0] = '{' then begin if Data.Chars[37] <> '}' then raise new SugarFormatException(ErrorMessage.FORMAT_ERROR); Offset := 1; end else if Data.Chars[0] = '(' then begin if Data.Chars[37] <> ')' then raise new SugarFormatException(ErrorMessage.FORMAT_ERROR); Offset := 1; end; if (Data.Chars[8+Offset] <> '-') or (Data.Chars[13+Offset] <> '-') or (Data.Chars[18+Offset] <> '-') or (Data.Chars[23+Offset] <> '-') then raise new SugarFormatException(ErrorMessage.FORMAT_ERROR); //Clear string from "{}()-" symbols var Regex := NSRegularExpression.regularExpressionWithPattern("[^A-F0-9]") options(NSRegularExpressionOptions.NSRegularExpressionCaseInsensitive) error(nil); var HexString := new NSMutableString withString(Regex.stringByReplacingMatchesInString(Data) options(NSMatchingOptions(0)) range(NSMakeRange(0, Data.length)) withTemplate("")); // We should get 32 chars if HexString.length <> 32 then raise new SugarFormatException(ErrorMessage.FORMAT_ERROR); Result := new Byte[16]; var Idx: UInt32 := 0; var Idx2: UInt32 := 0; //Convert hex to byte while Idx < HexString.length do begin var Range := NSMakeRange(Idx, 2); var Buffer := HexString.substringWithRange(Range); var ByteScanner := NSScanner.scannerWithString(Buffer); var IntValue: UInt32; ByteScanner.scanHexInt(var IntValue); Result[Idx2] := Byte(IntValue); inc(Idx, 2); inc(Idx2); end; end; {$ENDIF} end.
unit uLanDateTimeTools; interface uses Types, Classes, SysUtils, Windows, System.UITypes, IniFiles, Forms; function ServerDateTime(const AServerName: string): TDateTime; function WorkstationDateTime(const AWorkstationName: string): TDateTime; function ServerDate(const AServerName: string): TDateTime; function WorkstationDate(const AWorkstationName: string): TDateTime; function GetIPServer: string; implementation type PTimeOfDayInfo = ^TTimeOfDayInfo; TTimeOfDayInfo = packed record tod_elapsedt: DWORD; tod_msecs: DWORD; tod_hours: DWORD; tod_mins: DWORD; tod_secs: DWORD; tod_hunds: DWORD; tod_timezone: Longint; tod_tinterval: DWORD; tod_day: DWORD; tod_month: DWORD; tod_year: DWORD; tod_weekday: DWORD; end; NET_API_STATUS = DWORD; function NetRemoteTOD(UncServerName: LPCWSTR; BufferPtr: PBYTE): NET_API_STATUS; stdcall; external 'netapi32.dll' Name 'NetRemoteTOD'; function NetApiBufferFree(Buffer: Pointer): NET_API_STATUS; stdcall; external 'netapi32.dll' Name 'NetApiBufferFree'; function ServerDateTime(const AServerName: string): TDateTime; const NERR_SUCCESS = 0; var TimeOfDayInfo: PTimeOfDayInfo; ServerName: array[0..255] of WideChar; dwRetValue: NET_API_STATUS; GMTTime: TSystemTime; CurTime: TDateTime; begin StringToWideChar(AServerName, @ServerName, SizeOf(ServerName)); dwRetValue := NetRemoteTOD(@ServerName, PBYTE(@TimeOfDayInfo)); if dwRetValue <> NERR_SUCCESS then raise Exception.Create(SysErrorMessage(dwRetValue)); with TimeOfDayInfo^ do begin FillChar(GMTTime, SizeOf(GMTTime), 0); with GMTTime do begin wYear := tod_year; wMonth := tod_month; wDayOfWeek := tod_weekday; wDay := tod_day; wHour := tod_hours; wMinute := tod_mins; wSecond := tod_secs; wMilliseconds := tod_hunds; end; CurTime := SystemTimeToDateTime(GMTTime); if tod_timezone <> -1 then CurTime := CurTime + ((1 / 24 / 60) * -tod_timezone); Result := CurTime; end; NetApiBufferFree(TimeOfDayInfo); end; function WorkstationDateTime(const AWorkstationName: string): TDateTime; begin Result := ServerDateTime(AWorkstationName) end; function GetIPServer: string; var Ini: TIniFile; strApoio: string; begin Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'Infotec.ini'); strApoio := Ini.ReadString('CLIENT/SERVER', 'NOME SERVIDOR INTERBASE', strApoio); if Pos(':\', strApoio) > 0 then begin if Pos('/', strApoio) > 0 then Result := Copy(strApoio, 1, Pos(':\', strApoio) - 8) else if (Copy(strApoio, 1, 3) = 'C:\') then Result := '' else Result := Copy(strApoio, 1, Pos(':\', strApoio) - 3); end; Ini.Free; end; function ServerDate(const AServerName: string): TDateTime; begin Result := ServerDateTime(AServerName) + StrToTime('00:00:00'); end; function WorkstationDate(const AWorkstationName: string): TDateTime; begin Result := ServerDateTime(AWorkstationName) + StrToTime('00:00:00'); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } unit IdWebDAV; //implements http://www.faqs.org/rfcs/rfc2518.html { general cleanup possibilities: todo change embedded strings to consts todo change depth param from infinity to -1? also string>integer? } interface uses Classes, IdHTTP, IdSys, IdGlobal; const Id_HTTPMethodPropFind = 'PROPFIND'; Id_HTTPMethodPropPatch = 'PROPPATCH'; Id_HTTPMethodOrderPatch = 'ORDERPATCH'; Id_HTTPMethodSearch = 'SEARCH'; Id_HTTPMethodMove = 'MOVE'; Id_HTTPMethodCopy = 'COPY'; Id_HTTPMethodCheckIn = 'CHECKIN'; Id_HTTPMethodCheckOut = 'CHECKOUT'; Id_HTTPMethodUnCheckOut = 'UNCHECKOUT'; Id_HTTPMethodLock = 'LOCK'; Id_HTTPMethodUnLock = 'UNLOCK'; Id_HTTPMethodReport = 'REPORT'; Id_HTTPMethodVersion = 'VERSION-CONTROL'; Id_HTTPMethodLabel = 'LABEL'; const //casing is according to rfc cTimeoutInfinite='Infinite'; cDepthInfinity='infinity'; type TIdWebDAV = class(TIdHTTP) public procedure DAVCheckIn(const AURL,AComment:string); procedure DAVCheckOut(const AURL:string;const XMLQuery: TStream;const AComment:string); procedure DAVCopy(const AURL, DURL: string;const AResponseContent:TStream;const AOverWrite:boolean=true;const ADepth:string=cDepthInfinity); procedure DAVDelete(const AURL: string;const ALockToken:string); procedure DAVLabel(const AURL: string;const XMLQuery:TStream); procedure DAVLock(const AURL: string;const XMLQuery, AResponseContent: TStream;const LockToken, Tags:string;const TimeOut:string=cTimeoutInfinite;const MustExist:Boolean=False;const Depth:string='0'); procedure DAVMove(const AURL, DURL: string;const AResponseContent:TStream;const overwrite:boolean=true;const Depth:string=cDepthInfinity); procedure DAVOrderPatch(const AURL: string;const XMLQuery: TStream); procedure DAVPropFind(const AURL: string;const XMLQuery, AResponseContent: TStream;const Depth:string='0';const RangeFrom:integer=-1;const RangeTo:Integer=-1); //finds properties procedure DAVPropPatch(const AURL: string;const XMLQuery, AResponseContent: TStream;const Depth:string='0'); //patches properties procedure DAVPut(const AURL: string; const ASource: TStream;const LockToken:String); procedure DAVReport(const AURL: string;const XMLQuery, AResponseContent:TStream); procedure DAVSearch(const AURL: string;const rangeFrom, rangeTo:integer;const XMLQuery, AResponseContent: TStream;const Depth:string='0'); //performs a search procedure DAVUnCheckOut(const AURL:String); procedure DAVUnLock(const AURL: string;const LockToken:string); procedure DAVVersionControl(const AURL: string); end; implementation {todo place somewhere else? procedure Register; begin RegisterComponents('Indy Clients', [TIdWebDAV]); end; } procedure TIdWebDAV.DAVProppatch(const AURL:string;const XMLQuery,AResponseContent:TStream;const Depth:string); begin request.CustomHeaders.Add('Depth '+request.CustomHeaders.NameValueSeparator+' '+depth); DoRequest(Id_HTTPMethodPropPatch, AURL, XMLQuery, AResponseContent,[]); request.CustomHeaders.Delete(request.customHeaders.indexOfName('Depth')); end; procedure TIdWebDAV.DAVPropfind(const AURL: string;const XMLQuery, AResponseContent:TStream;const Depth:string; const RangeFrom:Integer;const RangeTo:Integer); begin if rangeTo>-1 then request.CustomHeaders.Add('Range'+request.CustomHeaders.NameValueSeparator+' Rows='+sys.intToStr(rangeFrom)+'-'+Sys.IntToStr(rangeTo)); request.CustomHeaders.Add('Depth'+request.CustomHeaders.NameValueSeparator+' '+depth); try DoRequest(Id_HTTPMethodPropfind, AURL, XMLQuery, AResponseContent,[]); finally request.CustomHeaders.Delete(request.customHeaders.indexOfName('Depth')); if rangeTo>-1 then request.CustomHeaders.Delete(request.customHeaders.indexOfName('Range')); end; end; procedure TIdWebDAV.DAVORDERPATCH(const AURL: string;const XMLQuery : TStream); begin DoRequest(Id_HTTPMethodOrderPatch, AURL, XMLQuery, Nil, []); end; procedure TIdWebDAV.DAVSearch(const AURL: string;const rangeFrom, rangeTo:integer;const XMLQuery, AResponseContent: TStream;const Depth:string); begin if rangeTo>-1 then request.CustomHeaders.Add('Range'+request.CustomHeaders.NameValueSeparator+' Rows='+Sys.IntToStr(rangeFrom)+'-'+Sys.IntToStr(rangeTo)); request.CustomHeaders.Add('Depth'+request.CustomHeaders.NameValueSeparator+' '+depth); try DoRequest(Id_HTTPMethodSearch, AURL, XMLQuery, AResponseContent, []); finally request.CustomHeaders.Delete(request.customHeaders.indexOfName('Depth')); if rangeTo>-1 then request.CustomHeaders.Delete(request.customHeaders.indexOfName('Range')); end; end; procedure TIdWebDAV.DAVMove(const AURL, DURL: string;const AResponseContent:TStream;const overwrite:boolean;const Depth:string); var foverwrite:string; begin if not overwrite then begin foverwrite:='F'; request.CustomHeaders.Add('Overwrite'+request.CustomHeaders.NameValueSeparator+' '+foverwrite); end; request.CustomHeaders.Add('Destination'+request.CustomHeaders.NameValueSeparator+' '+DURL); request.CustomHeaders.Add('Depth'+request.CustomHeaders.NameValueSeparator+' '+depth); try DoRequest(Id_HTTPMethodMove, AURL, Nil, AResponseContent, []); finally request.CustomHeaders.Delete(request.customHeaders.indexOfName('Destination')); if not overwrite then request.CustomHeaders.Delete(request.customHeaders.indexOfName('Overwrite')); request.CustomHeaders.Delete(request.customHeaders.indexOfName('Depth')); end; end; procedure TIdWebDAV.DAVCopy(const AURL, DURL: string;const AResponseContent:TStream;const AOverWrite:Boolean;const ADepth:string); var foverwrite:string; begin if AOverWrite then foverwrite:='T' else foverwrite:='f'; request.CustomHeaders.Add('Destination'+request.CustomHeaders.NameValueSeparator+' '+DURL); request.CustomHeaders.Add('Overwrite'+request.CustomHeaders.NameValueSeparator+' '+foverwrite); request.CustomHeaders.Add('Depth'+request.CustomHeaders.NameValueSeparator+' '+aDepth); try DoRequest(Id_HTTPMethodCopy, AURL, Nil, AResponseContent, []); finally request.CustomHeaders.Delete(request.customHeaders.indexOfName('Destination')); request.CustomHeaders.Delete(request.customHeaders.indexOfName('Overwrite')); request.CustomHeaders.Delete(request.customHeaders.indexOfName('Depth')); end; end; procedure TIdWebDAV.DAVCheckIn(const AURL,AComment:string); var xml:TMemoryStream; s:string; begin DoRequest(Id_HTTPMethodCheckIn, AURL, Nil, Nil, []); if AComment<>'' then begin xml:=TMemoryStream.create; try s:=('<?xml version="1.0" encoding="utf-8" ?><propertyupdate xmlns:D="DAV:"><set><prop>' +'<comment>'+AComment+'</comment></set></set></propertyupdate>'); xml.write(s[1], length(s)); DoRequest(Id_HTTPMethodPropPatch, AURL, xml, Nil, []); finally xml.free; end; end; end; procedure TIdWebDAV.DAVCheckOut(const AURL:String;const XMLQuery: TStream;const AComment:String); var xml:TMemoryStream; s:string; begin DoRequest(Id_HTTPMethodCheckOut, AURL, XMLQuery, nil, []); if AComment<>'' then begin xml:=TMemoryStream.create; try s:=('<?xml version="1.0" encoding="utf-8" ?><propertyupdate xmlns:D="DAV:"><set><prop>' +'<comment>'+AComment+'</comment></set></set></propertyupdate>'); xml.write(s[1], length(s)); DoRequest(Id_HTTPMethodPropPatch, AURL, xml, Nil, []); finally xml.free; end; end; end; procedure TIdWebDAV.DAVUnCheckOut(const AURL:string); begin DoRequest(Id_HTTPMethodUnCheckOut, AURL, Nil, Nil, []); end; procedure TIdWebDAV.DAVLock( const AURL: string; const XMLQuery, AResponseContent: TStream; const LockToken, Tags:string; const TimeOut:string; const MustExist:Boolean; const Depth:string); var index:integer; begin //NOTE - do not specify a LockToken and Tags value. If both exist then only LockToken will be used. If you wish to use LockToken //together with other tags then concatenate and send via Tags value //Also note that specifying the lock token in a lock request facilitates a lock refresh request.CustomHeaders.Add('Timeout'+request.CustomHeaders.NameValueSeparator+' '+TimeOut); if mustExist then request.CustomHeaders.Add('If-Match'+request.CustomHeaders.NameValueSeparator+' *') else request.CustomHeaders.Add('If-None-Match'+request.CustomHeaders.NameValueSeparator+' *'); request.CustomHeaders.Add('Depth'+request.CustomHeaders.NameValueSeparator+' '+depth); if LockToken<>'' then request.CustomHeaders.Add('If'+request.CustomHeaders.NameValueSeparator+' (<'+LockToken+'>)') else if Tags<>'' then request.CustomHeaders.Add('If'+request.CustomHeaders.NameValueSeparator+' ('+Tags+')'); try DoRequest(Id_HTTPMethodLock, AURL, XMLQuery, AResponseContent, []); finally request.CustomHeaders.Delete(request.customHeaders.indexOfName('Timeout')); index:=request.customHeaders.indexOfName('If-Match'); if index<>-1 then request.CustomHeaders.Delete(index); index:=request.customHeaders.indexOfName('If-None-Match'); if index<>-1 then request.CustomHeaders.Delete(index); request.CustomHeaders.Delete(request.customHeaders.indexOfName('Depth')); index:=request.customHeaders.indexOfName('If'); if index<>-1 then request.CustomHeaders.Delete(index); end; end; procedure TIdWebDAV.DAVUnLock(const AURL: string;const LockToken:string); begin request.CustomHeaders.Add('Lock-Token'+request.CustomHeaders.NameValueSeparator+' <'+LockToken+'>'); DoRequest(Id_HTTPMethodUnLock, AURL, Nil, Nil, []); request.CustomHeaders.Delete(request.customHeaders.indexOfName('Lock-Token')); end; procedure TIdWebDAV.DAVReport(const AURL: string;const XMLQuery, AResponseContent:TStream); begin DoRequest(Id_HTTPMethodReport, AURL, XMLQuery, AResponseContent, []); end; procedure TIdWebDAV.DAVVersionControl(const AURL: string); begin DoRequest(Id_HTTPMethodVersion, AURL, Nil, Nil, []); end; procedure TIdWebDAV.DAVLabel(const AURL: string;const XMLQuery:TStream); begin DoRequest(Id_HTTPMethodLabel, AURL, XMLQuery, Nil, []); end; procedure TIdWebDAV.DAVPut(const AURL: string; const ASource: TStream;const LockToken:String); begin if lockToken<>'' then Request.CustomHeaders.Add('If'+request.CustomHeaders.NameValueSeparator+' (<'+LockToken+'>)'); try //possible conflicts with baseclass PUT? DoRequest(Id_HTTPMethodPut, AURL, ASource, Nil, []); finally if lockToken<>'' then Request.CustomHeaders.Delete(request.customHeaders.indexOfName('If')); end; end; procedure TIdWebDAV.DAVDelete(const AURL:string;const ALockToken:string); begin if ALockToken<>'' then Request.CustomHeaders.Add('If'+request.CustomHeaders.NameValueSeparator+' (<'+ALockToken+'>)'); try DoRequest(Id_HTTPMethodDelete, AURL, Nil, nil, []); finally if ALockToken<>'' then Request.CustomHeaders.Delete(request.customHeaders.indexOfName('If')); end; end; end.
unit CarrylessRangeCoder; {$mode delphi} {$packrecords c} interface uses Classes, SysUtils, CTypes; type PInStream = ^TInStream; TInStream = record nextByte: function(self: PInStream): cuint8; cdecl; end; PCarrylessRangeCoder = ^TCarrylessRangeCoder; TCarrylessRangeCoder = record input: PInStream; low, code, range, bottom: cuint32; uselow: cbool; end; procedure InitializeRangeCoder(self: PCarrylessRangeCoder; input: PInStream; uselow: cbool; bottom: cint); function RangeCoderCurrentCount(self: PCarrylessRangeCoder; scale: cuint32): cuint32; procedure RemoveRangeCoderSubRange(self: PCarrylessRangeCoder; lowcount: cuint32; highcount: cuint32); function NextSymbolFromRangeCoder(self: PCarrylessRangeCoder; freqtable: pcuint32; numfreq: cint): cint; function NextBitFromRangeCoder(self: PCarrylessRangeCoder): cint; function NextWeightedBitFromRangeCoder(self: PCarrylessRangeCoder; weight: cint; size: cint): cint; function NextWeightedBitFromRangeCoder2(self: PCarrylessRangeCoder; weight: cint; shift: cint): cint; procedure NormalizeRangeCoder(self: PCarrylessRangeCoder); function InStreamNextByte(self: PInStream): cuint8; inline; implementation procedure InitializeRangeCoder(self: PCarrylessRangeCoder; input: PInStream; uselow: cbool; bottom: cint); begin self^.input:= input; self^.low:= 0; self^.code:= 0; self^.range:= $ffffffff; self^.uselow:= uselow; self^.bottom:= bottom; self^.code:= InStreamNextByte(input) shl 24 or InStreamNextByte(input) shl 16 or InStreamNextByte(input) shl 8 or InStreamNextByte(input); end; function RangeCoderCurrentCount(self: PCarrylessRangeCoder; scale: cuint32): cuint32; begin self^.range:= self^.range div scale; Result:= (self^.code - self^.low) div self^.range; end; procedure RemoveRangeCoderSubRange(self: PCarrylessRangeCoder; lowcount: cuint32; highcount: cuint32); begin if (self^.uselow) then self^.low += self^.range * lowcount else self^.code -= self^.range * lowcount; self^.range *= highcount - lowcount; NormalizeRangeCoder(self); end; function NextSymbolFromRangeCoder(self: PCarrylessRangeCoder; freqtable: pcuint32; numfreq: cint): cint; var totalfreq: cuint32 = 0; cumulativefreq: cuint32 = 0; n: cint = 0; tmp: cuint32; i: cint; begin for i:= 0 to numfreq - 1 do totalfreq += freqtable[i]; tmp:= RangeCoderCurrentCount(self, totalfreq); while(n < numfreq - 1) and (cumulativefreq + freqtable[n] <= tmp) do begin cumulativefreq += freqtable[n]; Inc(n); end; RemoveRangeCoderSubRange(self, cumulativefreq, cumulativefreq + freqtable[n]); Result:= n; end; function NextBitFromRangeCoder(self: PCarrylessRangeCoder): cint; var bit: cint; begin bit:= RangeCoderCurrentCount(self, 2); if (bit = 0) then RemoveRangeCoderSubRange(self, 0, 1) else RemoveRangeCoderSubRange(self, 1, 2); Result:= bit; end; function NextWeightedBitFromRangeCoder(self: PCarrylessRangeCoder; weight: cint; size: cint): cint; var val, bit: cint; begin val:= RangeCoderCurrentCount(self, size); if (val < weight) then // <= ? begin bit:= 0; RemoveRangeCoderSubRange(self, 0, weight); end else begin bit:= 1; RemoveRangeCoderSubRange(self, weight, size); end; Result:= bit; end; function NextWeightedBitFromRangeCoder2(self: PCarrylessRangeCoder; weight: cint; shift: cint): cint; var bit: cint; threshold: cuint32; begin threshold:= (self^.range shr shift) * weight; if (self^.code < threshold) then // <= ? begin bit:= 0; self^.range:= threshold; end else begin bit:= 1; self^.range -= threshold; self^.code -= threshold; end; NormalizeRangeCoder(self); Result:= bit; end; procedure NormalizeRangeCoder(self: PCarrylessRangeCoder); begin while True do begin if ( (self^.low xor (self^.low + self^.range)) >= $1000000 ) then begin if (self^.range >= self^.bottom) then Break else self^.range:= -cint32(self^.low and (self^.bottom - 1)); end; self^.code:= (self^.code shl 8) or InStreamNextByte(self^.input); self^.range:= self^.range shl 8; self^.low:= self^.low shl 8; end; end; function InStreamNextByte(self: PInStream): cuint8; begin Result := self^.nextByte(self); end; end.
{ Elabore um programa que entre com os dados de n (max. 20) pessoas (nome, rg, sexo, idade). Utilizar um vetor de registros para armazenar esses dados. Em seguida, o programa deve exibir um relatório contendo todos os dados das pessoas do sexo feminino com mais de 30 anos. } Program Exc5; uses Crt; Type reg_pessoa = record nome: string; rg: string; sexo: char; idade: integer; end; vet_pessoas = array[1..20] of reg_pessoa; Procedure ler(var vet: vet_pessoas; n: integer); var sexo: char; i: integer; begin for i := 1 to n do begin write('Nome da pessoa ', i, ': '); readln(vet[i].nome); write('RG da pessoa ', i, ': '); readln(vet[i].rg); write('Idade da pessoa ', i, ': '); readln(vet[i].idade); repeat write('Sexo da pessoa ', i, '(Digite M ou F): '); readln(sexo); sexo := LowerCase(sexo); ClrScr; until(sexo = 'm') or (sexo = 'f'); vet[i].sexo := sexo; end; end; Procedure imprimir(vet: vet_pessoas; n: integer); var i: integer; begin writeln('-----------------PESSOAS DO SEXO FEMININO COM MAIS DE 30 ANOS-------------------'); for i := 1 to n do begin if(vet[i].sexo = 'f') and (vet[i].idade > 30) then begin writeln('Nome da pessoa ', i, ': ', vet[i].nome); writeln('RG da pessoa ', i, ': ', vet[i].rg); writeln('idade da pessoa ', i, ': ', vet[i].idade); writeln('----------------'); end; end; writeln('-------------------------------------------------------------------------------'); end; Var n: integer; vet: vet_pessoas; Begin repeat write('Quantas pessoas você quer registrar? (Máximo 20): '); readln(n); ClrScr; until(n <= 20); ler(vet, n); imprimir(vet, n); End.
unit UOperationsResumeList; interface uses UThread, UOperationResume; type TOperationsResumeList = Class private FList : TPCThreadList; function GetOperationResume(index: Integer): TOperationResume; public Constructor Create; Destructor Destroy; override; Procedure Add(Const OperationResume : TOperationResume); Function Count : Integer; Procedure Delete(index : Integer); Procedure Clear; Property OperationResume[index : Integer] : TOperationResume read GetOperationResume; default; End; implementation uses Classes, SysUtils; { TOperationsResumeList } Type POperationResume = ^TOperationResume; procedure TOperationsResumeList.Add(const OperationResume: TOperationResume); Var P : POperationResume; begin New(P); P^ := OperationResume; FList.Add(P); end; procedure TOperationsResumeList.Clear; Var P : POperationResume; i : Integer; l : TList; begin l := FList.LockList; try for i := 0 to l.Count - 1 do begin P := l[i]; Dispose(P); end; l.Clear; finally FList.UnlockList; end; end; function TOperationsResumeList.Count: Integer; Var l : TList; begin l := FList.LockList; Try Result := l.Count; Finally FList.UnlockList; End; end; constructor TOperationsResumeList.Create; begin FList := TPCThreadList.Create('TOperationsResumeList_List'); end; procedure TOperationsResumeList.Delete(index: Integer); Var P : POperationResume; l : TList; begin l := FList.LockList; Try P := l[index]; l.Delete(index); Dispose(P); Finally FList.UnlockList; End; end; destructor TOperationsResumeList.Destroy; begin Clear; FreeAndNil(FList); inherited; end; function TOperationsResumeList.GetOperationResume(index: Integer): TOperationResume; Var l : TList; begin l := FList.LockList; try if index<l.Count then Result := POperationResume(l[index])^ else Result := CT_TOperationResume_NUL; finally FList.UnlockList; end; end; end.
// Author : Thierry Parent // Version : 12.4 // // HomePage : http://www.codeproject.com/csharp/TraceTool.asp // Download : http://sourceforge.net/projects/tracetool/ // See License.txt for license informationunit unt_XTraceOptions; unit unt_XTraceOptions ; {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, ActiveX, TraceToolCom_TLB, StdVcl, tracetool; type TXTraceOptions = class(TAutoObject, IXTraceOptions) // TInterfacedObject protected function Get_ColorKind: ColorKind; safecall; procedure Set_ColorKind(Value: ColorKind); safecall; function Get_SocketHost: WideString; safecall; procedure Set_SocketHost(const Value: WideString); safecall; function Get_SendMode: SendMode; safecall; procedure Set_SendMode(Value: SendMode); safecall; function Get_SendDate: WordBool; safecall; procedure Set_SendDate(Value: WordBool); safecall; function Get_SendFunctions: WordBool; safecall; procedure Set_SendFunctions(Value: WordBool); safecall; function Get_SendProcessName: WordBool; safecall; function Get_SendThreadId: WordBool; safecall; procedure Set_SendProcessName(Value: WordBool); safecall; procedure Set_SendThreadId(Value: WordBool); safecall; function Get_SocketPort: SYSINT; safecall; procedure Set_SocketPort(Value: SYSINT); safecall; function Get_SocketUdp: WordBool; safecall; procedure Set_SocketUdp(Value: WordBool); safecall; public // no link is necessary destructor Destroy; override; end; function ConvertColor(color : integer) : integer; var globalColorKind : integer ; // BGR = $00000000; RGB = $00000001; implementation uses ComServ; //------------------------------------------------------------------------------ // return the color converted to BGR function ConvertColor(color : integer) : integer; var b,g,r : integer ; begin if globalColorKind = BGR then // like for delphi result := Color else begin // RGB // vb, dot net B := Color and $FF; G := Color shr 8 and $FF; R := Color shr 16 and $FF; // convert to BGR result := (B shl 16) + (G shl 8) + R; end; end; //------------------------------------------------------------------------------ destructor TXTraceOptions.Destroy; begin //ttrace.error.send ('TXTraceOptions.Destroy', integer(pointer(self))) ; inherited; end; //------------------------------------------------------------------------------ function TXTraceOptions.Get_SocketHost: WideString; begin result := TTrace.Options.SocketHost ; end; //------------------------------------------------------------------------------ procedure TXTraceOptions.Set_SocketHost(const Value: WideString); begin TTrace.Options.SocketHost := Value ; end; //------------------------------------------------------------------------------ function TXTraceOptions.Get_SendMode: SendMode; begin if TTrace.Options.SendMode = tmWinMsg then result := WinMsg // TOleEnum else Result := Socket ; end; //------------------------------------------------------------------------------ procedure TXTraceOptions.Set_SendMode(Value: SendMode); begin if value = WinMsg then // TOleEnum TTrace.Options.SendMode := tmWinMsg else TTrace.Options.SendMode := tmAlternate ; end; //------------------------------------------------------------------------------ function TXTraceOptions.Get_SendDate: WordBool; begin result := ttrace.Options.SendDate ; end; //------------------------------------------------------------------------------ procedure TXTraceOptions.Set_SendDate(Value: WordBool); begin ttrace.Options.SendDate := Value ; end; //------------------------------------------------------------------------------ function TXTraceOptions.Get_SendFunctions: WordBool; begin result := ttrace.Options.SendFunctions ; end; //------------------------------------------------------------------------------ procedure TXTraceOptions.Set_SendFunctions(Value: WordBool); begin ttrace.Options.SendFunctions := value ; end; //------------------------------------------------------------------------------ function TXTraceOptions.Get_SendProcessName: WordBool; begin result := ttrace.Options.SendProcessName ; end; //------------------------------------------------------------------------------ procedure TXTraceOptions.Set_SendProcessName(Value: WordBool); begin ttrace.Options.SendProcessName := value ; end; //------------------------------------------------------------------------------ function TXTraceOptions.Get_SendThreadId: WordBool; begin result := ttrace.Options.SendThreadId ; end; //------------------------------------------------------------------------------ procedure TXTraceOptions.Set_SendThreadId(Value: WordBool); begin ttrace.Options.SendThreadId := value ; end; //------------------------------------------------------------------------------ function TXTraceOptions.Get_SocketUdp: WordBool; begin result := ttrace.Options.SocketUdp ; end; //------------------------------------------------------------------------------ procedure TXTraceOptions.Set_SocketUdp(Value: WordBool); begin ttrace.Options.SocketUdp := Value ; end; //------------------------------------------------------------------------------ function TXTraceOptions.Get_SocketPort: SYSINT; begin result := ttrace.Options.SocketPort ; end; //------------------------------------------------------------------------------ procedure TXTraceOptions.Set_SocketPort(Value: SYSINT); begin ttrace.Options.SocketPort := value ; end; //------------------------------------------------------------------------------ function TXTraceOptions.Get_ColorKind: ColorKind; begin result := globalColorKind ; end; //------------------------------------------------------------------------------ procedure TXTraceOptions.Set_ColorKind(Value: ColorKind); begin globalColorKind := Value ; end; initialization TAutoObjectFactory.Create(ComServer, TXTraceOptions, Class_XTraceOptions, ciMultiInstance, tmApartment); end.
unit MFichas.Model.Produto.Metodos.Buscar.Model; interface uses System.SysUtils, System.Generics.Collections, MFichas.Model.Produto.Interfaces, MFichas.Model.Entidade.PRODUTO; type TModelProdutoMetodosBuscarModel = class(TInterfacedObject, iModelProdutoMetodosBuscarModel) private [weak] FParent: iModelProduto; constructor Create(AParent: iModelProduto); public destructor Destroy; override; class function New(AParent: iModelProduto): iModelProdutoMetodosBuscarModel; function BuscarPorCodigo(AGUUID: String): TObjectList<TPRODUTO>; function &End : iModelProdutoMetodos; end; implementation { TModelProdutoMetodosBuscarModel } function TModelProdutoMetodosBuscarModel.&End: iModelProdutoMetodos; begin Result := FParent.Metodos; end; function TModelProdutoMetodosBuscarModel.BuscarPorCodigo( AGUUID: String): TObjectList<TPRODUTO>; begin Result := FParent.DAO.FindWhere('GUUID = ' + QuotedStr(AGUUID)); end; constructor TModelProdutoMetodosBuscarModel.Create(AParent: iModelProduto); begin FParent := AParent; end; destructor TModelProdutoMetodosBuscarModel.Destroy; begin inherited; end; class function TModelProdutoMetodosBuscarModel.New(AParent: iModelProduto): iModelProdutoMetodosBuscarModel; begin Result := Self.Create(AParent); end; end.
unit uCanvas; (* Generic off-screen drawing canvas *) (* 2016-18 pjde *) {$mode objfpc}{$H+} { Interpolation originally derived from FPCanvas whose copyright message reads :- This file is part of the Free Pascal run time library. Copyright (c) 2003 by the Free Pascal development team Basic canvas definitions. See the file COPYING.FPC, included in this distribution, for details about the copyright. 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. **********************************************************************} {Tweaked to run on Ultibo Canvas pjde 2018 } {$H+} interface uses Classes, SysUtils, FrameBuffer, uFontInfo, Ultibo, freetypeh, FPImage; type TFPCustomInterpolation = class; { TCanvas } TCanvas = class private IP : TFPCustomInterpolation; function GetFont (byFont : string; Load : boolean) : TFontInfo; public ColourFormat : LongWord; Width, Height : integer; Left, Top : integer; Buffer : PByteArray; BufferSize : integer; BitCount : integer; Fonts : TList; procedure FindFonts; procedure SetSize (w, h : integer; cf : LongWord); procedure Fill (Col : LongWord); overload; procedure Fill (Rect : Ultibo.TRect; Col : LongWord); overload; function TextExtents (Text, Font : string; Size : integer) : FT_Vector; procedure DrawText (x, y: integer; Text, Font : string; FontSize : integer; Col : LongWord); overload; procedure DrawText (x, y: integer; Text, Font : string; FontSize : integer; Col : LongWord; Alpha : byte); overload; procedure Flush (FrameBuff : PFrameBufferDevice; x, y : integer); overload; procedure Flush (FrameBuff : PFrameBufferDevice); overload; procedure Assign (anOther : TCanvas); procedure DrawImage (anImage : TFPCustomImage; x, y : integer); overload; procedure DrawImage (anImage : TFPCustomImage; x, y, h, w : integer); overload; constructor Create; destructor Destroy; override; end; { TFPCustomInterpolation } TFPCustomInterpolation = class private FCanvas: TCanvas; FImage: TFPCustomImage; protected public procedure Initialise (anImage : TFPCustomImage; aCanvas : TCanvas); virtual; procedure Execute (x, y, w, h : integer); virtual; abstract; property Canvas : TCanvas read fCanvas; property Image : TFPCustomImage read fimage; end; { TFPBaseInterpolation } TFPBaseInterpolation = class (TFPCustomInterpolation) private procedure CreatePixelWeights (OldSize, NewSize : integer; out Entries: Pointer; out EntrySize : integer; out Support : integer); protected public procedure Execute (x, y, w, h : integer); override; function Filter (x : double) : double; virtual; function MaxSupport : double; virtual; end; { TMitchelInterpolation } TMitchelInterpolation = class (TFPBaseInterpolation) protected function Filter (x : double) : double; override; function MaxSupport : double; override; end; function SetRect (Left, Top, Right, Bottom : long) : Ultibo.TRect; function GetRValue (c : LongWord) : byte; function GetGValue (c : LongWord) : byte; function GetBValue (c : LongWord) : byte; function rgb (r, g, b : byte) : LongWord; inline; implementation uses GlobalConst, uLog, Math; var FTLib : PFT_Library; // handle to FreeType library function FT_New_Memory_Face (alibrary: PFT_Library; file_base: pointer; file_size: longint; face_index: integer; var face: PFT_Face) : integer; cdecl; external freetypedll Name 'FT_New_Memory_Face'; const DPI = 72; { TCanvas } function SetRect (Left, Top, Right, Bottom : long) : Ultibo.TRect; begin Result.left := Left; Result.top := Top; Result.right := Right; Result.bottom := Bottom; end; function GetRValue (c : LongWord) : byte; inline; begin Result := (c and $ff0000) shr 16; end; function GetGValue (c : LongWord) : byte; inline; begin Result := (c and $ff00) shr 8; end; function GetBValue (c : LongWord) : byte; inline; begin Result := c and $ff; end; function rgb (r, g, b : byte) : LongWord; inline; begin Result := $ff000000 + (r shl 16) + (g shl 8) + b; end; function TCanvas.TextExtents (Text, Font : string; Size : integer) : FT_Vector; var err : integer; aFace : PFT_Face; fn : string; i: integer; kerning : boolean; glyph_index, prev : cardinal; delta : FT_Vector; anInfo : TFontInfo; begin Result.x := 0; Result.y := 0; delta.x := 0; delta.y := 0; if not Assigned (FTLib) then exit; aFace := nil; if ExtractFileExt (Font) = '' then fn := Font + '.ttf' else fn := Font; anInfo := GetFont (fn, true); if anInfo = nil then exit; err := FT_New_Memory_Face (FTLIB, anInfo.Stream.Memory, anInfo.Stream.Size, 0, aFace); if err = 0 then // if font face loaded ok begin err := FT_Set_Char_Size (aFace, // handle to face object 0, // char width in 1/64th of points - Same as height Size * 64, // char height in 1/64th of points DPI, // horizontal device resolution 0); // vertical device resolution if err = 0 then begin prev := 0; // no previous char kerning := FT_HAS_KERNING (aFace); for i := 1 to length (Text) do begin // convert character code to glyph index glyph_index := FT_Get_Char_Index (aFace, cardinal (Text[i])); if kerning and (prev <> 0) and (glyph_index <> 0) then begin FT_Get_Kerning (aFace, prev, glyph_index, FT_KERNING_DEFAULT, &delta); Result.x := Result.x + delta.x; //if aFace^.glyph^.bitmap^.height + aFace^.glyph^.bitmap_top > Result.y then //Result.y := aFace^.glyph^.bitmap^.height + aFace^.glyph^.bitmap_top; end; // load glyph image into the slot (erase previous one) err := FT_Load_Glyph (aFace, glyph_index, FT_LOAD_NO_BITMAP); if err > 0 then continue; // ignore errors Result.x := Result.x + aFace^.glyph^.advance.x; //if aFace^.glyph^.bitmap^.height + aFace^.glyph^.bitmap_top > Result.y then //Result.y := aFace^.glyph^.bitmap^.height + aFace^.glyph^.bitmap_top; prev := glyph_index; end; end; FT_Done_Face (aFace); end; Result.x := Result.x div 64; Result.y := Result.y div 64; end; procedure TCanvas.DrawText (x, y : integer; Text, Font : string; FontSize : integer; Col : LongWord; Alpha : byte); var err : integer; aFace : PFT_Face; fn : string; i, tx, ty : integer; kerning : boolean; glyph_index, prev : cardinal; delta : FT_Vector; anInfo : TFontInfo; procedure DrawChar (b : FT_Bitmap; dx, dy : integer); var i , j : integer; x_max, y_max : integer; p, q : integer; fm : PByte; rd, gn, bl : byte; cp : PCardinal; // canvas pointer begin x_max := dx + b.width; y_max := dy + b.rows; // Log ('dx ' + InttoStr (dx) + ' dy ' + IntToStr (dy) + ' x max ' + IntToStr (x_max) + ' y max ' + IntToStr (y_max)); case ColourFormat of COLOR_FORMAT_ARGB32 : {32 bits per pixel Red/Green/Blue/Alpha (RGBA8888)} begin q := 0; for j := dy to y_max - 1 do begin if (j >= 0) and (j < Height) then begin {$warnings off} cp := PCardinal (LongWord (Buffer) + ((j * Width) + dx) * 4); {$warnings on} p := 0; for i := dx to x_max - 1 do begin if (i >= 0) and (i < Width) then begin LongWord (fm) := LongWord (b.buffer) + q * b.width + p; // read alpha value of font char fm^ := (fm^ * alpha) div 255; rd := ((GetRValue (Col) * fm^) + (GetRValue (cp^) * (255 - fm^))) div 255; gn := ((GetGValue (Col) * fm^) + (GetGValue (cp^) * (255 - fm^))) div 255; bl := ((GetBValue (Col) * fm^) + (GetBValue (cp^) * (255 - fm^))) div 255; cp^ := rgb (rd, gn, bl); end; p := p + 1; Inc (cp, 1); end; q := q + 1; end; end; end; // colour format end; // case end; begin if not Assigned (FTLib) then exit; aFace := nil; tx := x; ty := y; delta.x := 0; delta.y := 0; if ExtractFileExt (Font) = '' then fn := Font + '.ttf' else fn := Font; anInfo := GetFont (fn, true); if anInfo = nil then exit; err := FT_New_Memory_Face (FTLIB, anInfo.Stream.Memory, anInfo.Stream.Size, 0, aFace); if err = 0 then // if font face loaded ok begin err := FT_Set_Char_Size (aFace, // handle to face object 0, // char_width in 1/64th of points - Same as height FontSize * 64, // char_height in 1/64th of points DPI, // horizontal device resolution - dots per inch 0); // vertical device resolution - dots per inch if err = 0 then begin prev := 0; // no previous char kerning := FT_HAS_KERNING (aFace); for i := 1 to length (Text) do begin // convert character code to glyph index glyph_index := FT_Get_Char_Index (aFace, cardinal (Text[i])); if kerning and (prev <> 0) and (glyph_index <> 0) then begin FT_Get_Kerning (aFace, prev, glyph_index, FT_KERNING_DEFAULT, &delta); tx := tx + delta.x div 64; end; // load glyph image into the slot (erase previous one) err := FT_Load_Glyph (aFace, glyph_index, FT_LOAD_RENDER); if err > 0 then continue; // ignore errors // now draw to our target surface DrawChar (aFace^.glyph^.bitmap, tx + aFace^.glyph^.bitmap_left, ty - aFace^.glyph^.bitmap_top); tx := tx + aFace^.glyph^.advance.x div 64; prev := glyph_index; end; end; FT_Done_Face (aFace); end; end; procedure TCanvas.DrawText (x, y : integer; Text, Font : string; FontSize: integer; Col: LongWord); begin DrawText (x, y, text, Font, FontSize, Col, 255); end; function TCanvas.GetFont (byFont : string; Load : boolean) : TFontInfo; var i : integer; f : TFilestream; begin Result := nil; for i := 0 to Fonts.Count - 1 do begin if TFontInfo (Fonts[i]).FileName = byFont then begin Result := TFontInfo (Fonts[i]); break; end; end; if (Result = nil) and FileExists (byFont) then begin Result := TFontInfo.Create; if FontInfo (byFont, Result) then Fonts.Add (Result) else begin Result.Free; Result := nil; end; end; if (Result = nil) or (not Load) then exit; if Result.Stream <> nil then exit; // already loaded Result.Stream := TMemoryStream.Create; try f := TFileStream.Create (byFont, fmOpenRead); Result.Stream.CopyFrom (f, f.Size); f.Free; except // Log ('Error loading font.'); Result.Stream.Free; Result.Stream := nil; end; end; procedure TCanvas.FindFonts; var i : integer; SearchRec : TSearchRec; anInfo : TFontInfo; begin for i := 0 to Fonts.Count - 1 do // first clear list TFontInfo (Fonts[i]).Free; Fonts.Clear; if FindFirst ('C:\*.ttf', faAnyFile, SearchRec) = 0 then repeat anInfo := TFontInfo.Create; if FontInfo (SearchRec.Name, anInfo) then Fonts.Add (anInfo) else anInfo.Free; until FindNext (SearchRec) <> 0; FindClose (SearchRec); end; procedure TCanvas.SetSize (w, h : integer; cf : LongWord); var bc : integer; begin if Buffer <> nil then FreeMem (Buffer); Buffer := nil; Width := w; Height := h; ColourFormat := cf; case ColourFormat of COLOR_FORMAT_ARGB32, {32 bits per pixel Alpha/Red/Green/Blue (ARGB8888)} COLOR_FORMAT_ABGR32, {32 bits per pixel Alpha/Blue/Green/Red (ABGR8888)} COLOR_FORMAT_RGBA32, {32 bits per pixel Red/Green/Blue/Alpha (RGBA8888)} COLOR_FORMAT_BGRA32 : bc := 4; {32 bits per pixel Blue/Green/Red/Alpha (BGRA8888)} COLOR_FORMAT_RGB24, {24 bits per pixel Red/Green/Blue (RGB888)} COLOR_FORMAT_BGR24 : bc := 3; {24 bits per pixel Blue/Green/Red (BGR888)} // COLOR_FORMAT_RGB18 = 6; {18 bits per pixel Red/Green/Blue (RGB666)} COLOR_FORMAT_RGB16, {16 bits per pixel Red/Green/Blue (RGB565)} COLOR_FORMAT_RGB15 : bc := 2; {15 bits per pixel Red/Green/Blue (RGB555)} COLOR_FORMAT_RGB8 : bc := 1; {8 bits per pixel Red/Green/Blue (RGB332)} else bc := 0; end; BufferSize := Width * Height * bc; if BufferSize > 0 then begin GetMem (Buffer, BufferSize); FillChar (Buffer^, BufferSize, 0); end; end; procedure TCanvas.Fill (Col: LongWord); var Rect : Ultibo.TRect; begin Rect := SetRect (0, 0, Width - 1, Height - 1); Fill (Rect, Col); end; procedure TCanvas.Fill (Rect: Ultibo.TRect; Col: LongWord); var i, j : integer; p : pointer; begin case ColourFormat of COLOR_FORMAT_ARGB32 : {32 bits per pixel Red/Green/Blue/Alpha (RGBA8888)} begin // Log ('Fill Width ' + IntToStr (Rect.right - rect.left) + ' Height ' // + IntToStr (Rect.bottom - rect.top)); if Rect.left < 0 then Rect.left:= 0; if Rect.top < 0 then rect.top := 0; if Rect.left >= Width then exit; if Rect.top >= Height then exit; if Rect.right >= Width then Rect.right := width - 1; if Rect.bottom >= Height then Rect.bottom := height - 1; if Rect.left >= Rect.right then exit; if Rect.top >= Rect.bottom then exit; for j := Rect.top to Rect.bottom do begin cardinal (p) := cardinal (Buffer) + ((j * Width) + Rect.left) * 4; for i := Rect.left to Rect.right do begin // 000000ff blue 0000ff00 green 00ff0000 red PCardinal (p)^ := Col; Inc (p, 4); end; end; end; end; end; procedure TCanvas.Flush (FrameBuff : PFrameBufferDevice; x, y : integer); begin FramebufferDevicePutRect (FrameBuff, x, y, Buffer, Width, Height, 0, FRAMEBUFFER_TRANSFER_DMA); end; procedure TCanvas.Flush (FrameBuff: PFrameBufferDevice); begin FramebufferDevicePutRect (FrameBuff, Left, Top, Buffer, Width, Height, 0, FRAMEBUFFER_TRANSFER_DMA); end; procedure TCanvas.Assign (anOther: TCanvas); begin if (anOther.Width <> Width) or (anOther.Height <> Height) or (anOther.ColourFormat <> ColourFormat) then SetSize (anOther.Width, anOther.Height, anOther.ColourFormat); Move (anOther.Buffer[0], Buffer[0], BufferSize); end; procedure TCanvas.DrawImage (anImage: TFPCustomImage; x, y: integer); // derived from FPCanvas var xx, xi, yi, xm, ym, r, t : integer; c : cardinal; aCol : TFPColor; a : byte; p : pointer; begin xm := x + anImage.width - 1; if xm >= width then xm := width - 1; ym := y + anImage.height - 1; if ym >= height then ym := height - 1; xi := x; yi := y; for r := xi to xm do begin xx := r - x; for t := yi to ym do begin // colors [r,t] := anImage.colors[xx,t-y]; aCol := anImage.Colors[xx, t - y]; LongWord (p) := LongWord (Buffer) + ((t * Width) + r) * 4; a := aCol.alpha div $100; c := ((GetRValue (PLongWord (p)^) * (255 - a)) + (aCol.red div $100) * a) div $100; c := c shl 8; c := c + ((GetGValue (PLongWord (p)^) * (255 - a)) + (aCol.green div $100) * a) div $100; c := c shl 8; c := c + ((GetBValue (PLongWord (p)^) * (255 - a)) + (aCol.blue div $100) * a) div $100; PLongWord (p)^ := c; end; end; end; procedure TCanvas.DrawImage (anImage: TFPCustomImage; x, y, h, w : integer); begin if IP = nil then IP := TMitchelInterpolation.Create; try with IP do begin Initialise (anImage, Self); Execute (x, y, h, w); end; finally end; end; constructor TCanvas.Create; var res : integer; begin Width := 0; Height := 0; Left := 0; Top := 0; Buffer := nil; IP := nil; ColourFormat := COLOR_FORMAT_UNKNOWN; Fonts := TList.Create; if FTLib = nil then begin res := FT_Init_FreeType (FTLib); if res <> 0 then log ('FTLib failed to Initialise.'); end; end; destructor TCanvas.Destroy; var i : integer; begin for i := 0 to Fonts.Count - 1 do TFontInfo (Fonts[i]).Free; Fonts.Free; if IP <> nil then IP.Free; if Buffer <> nil then FreeMem (Buffer); inherited; end; { TFPCustomInterpolation } procedure TFPCustomInterpolation.Initialise (anImage: TFPCustomImage; aCanvas: TCanvas); begin FImage := anImage; FCanvas := aCanvas; end; { TFPBaseInterpolation } procedure TFPBaseInterpolation.CreatePixelWeights(OldSize, NewSize : integer; out Entries : Pointer; out EntrySize : integer; out Support : integer); // create an array of #NewSize entries. Each entry starts with an integer // for the StartIndex, followed by #Support singles for the pixel weights. // The sum of weights for each entry is 1. var Entry: Pointer; procedure SetSupport (NewSupport : integer); begin Support := NewSupport; EntrySize := SizeOf (integer) + SizeOf (Single) * Support; GetMem (Entries, EntrySize * NewSize); Entry := Entries; end; var i : Integer; Factor : double; StartPos : Double; StartIndex : Integer; j : Integer; FirstValue : Double; begin if NewSize = OldSize then begin SetSupport (1); for i := 0 to NewSize - 1 do begin // 1:1 PInteger (Entry)^ := i; inc (Entry, SizeOf (Integer)); PSingle (Entry)^ := 1.0; inc (Entry, SizeOf (Single)); end; end else if NewSize < OldSize then begin // shrink SetSupport (Max (2, (OldSize + NewSize - 1) div NewSize)); Factor := double (OldSize) / double (NewSize); for i := 0 to NewSize - 1 do begin StartPos := Factor * i; StartIndex := Floor (StartPos); PInteger (Entry)^:=StartIndex; inc (Entry, SizeOf (Integer)); // first pixel FirstValue := (1.0 - (StartPos - double (StartIndex))); PSingle (Entry)^ := FirstValue / Factor; inc (Entry, SizeOf (Single)); // middle pixel for j := 1 to Support - 2 do begin PSingle (Entry)^ := 1.0 / Factor; inc (Entry, SizeOf (Single)); end; // last pixel PSingle(Entry)^ := (Factor - FirstValue - (Support - 2)) / Factor; inc (Entry, SizeOf (Single)); end; end else begin // enlarge if OldSize = 1 then begin SetSupport (1); for i := 0 to NewSize - 1 do begin // nothing to interpolate PInteger (Entry)^ :=0; inc (Entry, SizeOf (Integer)); PSingle (Entry)^ := 1.0; inc (Entry, SizeOf (Single)); end; end else begin SetSupport (2); Factor := double (OldSize - 1) / double (NewSize); for i := 0 to NewSize - 1 do begin StartPos := Factor * i + Factor / 2; StartIndex := Floor (StartPos); PInteger (Entry)^ := StartIndex; inc (Entry, SizeOf (Integer)); // first pixel FirstValue := (1.0 - (StartPos - double (StartIndex))); // convert linear distribution FirstValue := Min (1.0, Max (0.0, Filter (FirstValue / MaxSupport))); PSingle(Entry)^ := FirstValue; inc (Entry, SizeOf (Single)); // last pixel PSingle (Entry)^ := 1.0 - FirstValue; inc (Entry, SizeOf (Single)); end; end; end; if Entry <> Entries + EntrySize * NewSize then raise Exception.Create ('TFPBase2Interpolation.Execute inconsistency'); end; procedure TFPBaseInterpolation.Execute (x, y, w, h : integer); // paint Image on Canvas at x,y,w*h var dy : Integer; dx : Integer; HorzResized : PFPColor; xEntries : Pointer; xEntrySize : integer; xSupport : integer;// how many horizontal pixel are needed to create one pixel yEntries : Pointer; yEntrySize : integer; ySupport : integer;// how many vertizontal pixel are needed to create one pixel NewSupportLines : LongInt; yEntry : Pointer; SrcStartY : LongInt; LastSrcStartY : LongInt; LastyEntry : Pointer; sy : Integer; xEntry : Pointer; sx : LongInt; cx : Integer; f: Single; NewCol: TFPColor; Col: TFPColor; CurEntry : Pointer; p : pointer; c : cardinal; a : byte; begin if (w <= 0) or (h <= 0) or (image.Width = 0) or (image.Height = 0) then exit; xEntries := nil; yEntries := nil; HorzResized := nil; try CreatePixelWeights (image.Width, w, xEntries, xEntrySize, xSupport); CreatePixelWeights (image.Height, h, yEntries, yEntrySize, ySupport); // create temporary buffer for the horizontally resized pixel for the // current y line GetMem (HorzResized, w * ySupport * SizeOf (TFPColor)); LastyEntry := nil; SrcStartY := 0; for dy := 0 to h - 1 do begin if dy = 0 then begin yEntry := yEntries; SrcStartY := PInteger (yEntry)^; NewSupportLines := ySupport; end else begin LastyEntry := yEntry; LastSrcStartY := SrcStartY; inc (yEntry, yEntrySize); SrcStartY := PInteger (yEntry)^; NewSupportLines := SrcStartY - LastSrcStartY; // move lines up if (NewSupportLines > 0) and (ySupport > NewSupportLines) then System.Move (HorzResized[NewSupportLines * w], HorzResized[0], (ySupport - NewSupportLines) * w * SizeOf (TFPColor)); end; // compute new horizontally resized line(s) for sy := ySupport - NewSupportLines to ySupport - 1 do begin xEntry := xEntries; for dx := 0 to w - 1 do begin sx := PInteger (xEntry)^; inc (xEntry,SizeOf(integer)); NewCol := colTransparent; for cx := 0 to xSupport - 1 do begin f := PSingle (xEntry)^; inc (xEntry, SizeOf (Single)); Col := image.Colors[sx + cx, SrcStartY + sy]; NewCol.red := Min (NewCol.red + round (Col.red * f), $ffff); NewCol.green := Min (NewCol.green + round (Col.green * f), $ffff); NewCol.blue := Min (NewCol.blue + round (Col.blue * f), $ffff); NewCol.alpha := Min (NewCol.alpha + round (Col.alpha * f), $ffff); end; HorzResized [dx + sy * w] := NewCol; end; end; // compute new vertically resized line for dx := 0 to w - 1 do begin CurEntry := yEntry + SizeOf (integer); NewCol := colTransparent; for sy := 0 to ySupport - 1 do begin f := PSingle (CurEntry)^; inc (CurEntry, SizeOf (Single)); Col := HorzResized[dx + sy * w]; NewCol.red := Min (NewCol.red + round (Col.red * f),$ffff); NewCol.green := Min (NewCol.green + round (Col.green * f),$ffff); NewCol.blue := Min (NewCol.blue + round (Col.blue * f), $ffff); NewCol.alpha := Min (NewCol.alpha + round (Col.alpha * f), $ffff); end; LongWord (p) := LongWord (Canvas.Buffer) + (((y + dy) * Canvas.Width) + x + dx) * 4; a := NewCol.alpha div $100; c := ((GetRValue (PLongWord (p)^) * (255 - a)) + (NewCol.red div $100) * a) div $100; c := c shl 8; c := c + ((GetGValue (PLongWord (p)^) * (255 - a)) + (NewCol.green div $100) * a) div $100; c := c shl 8; c := c + ((GetBValue (PLongWord (p)^) * (255 - a)) + (NewCol.blue div $100) * a) div $100; PLongWord (p)^ := c; end; end; finally if xEntries <> nil then FreeMem (xEntries); if yEntries <> nil then FreeMem (yEntries); if HorzResized <> nil then FreeMem (HorzResized); end; end; function TFPBaseInterpolation.Filter (x : double) : double; begin Result := x; end; function TFPBaseInterpolation.MaxSupport : double; begin Result := 1.0; end; { TMitchelInterpolation } function TMitchelInterpolation.Filter (x : double) : double; const B = (1.0 / 3.0); C = (1.0 / 3.0); P0 = (( 6.0 - 2.0 * B ) / 6.0); P2 = ((-18.0 + 12.0 * B + 6.0 * C) / 6.0); P3 = (( 12.0 - 9.0 * B - 6.0 * C) / 6.0); Q0 = (( 8.0 * B + 24.0 * C) / 6.0); Q1 = (( -12.0 * B - 48.0 * C) / 6.0); Q2 = (( 6.0 * B + 30.0 * C) / 6.0); Q3 = (( - 1.0 * B - 6.0 * C) / 6.0); begin if (x < -2.0) then Result := 0.0 else if (x < -1.0) then Result := Q0 - x * (Q1 - x * (Q2 - x * Q3)) else if (x < 0.0) then Result := P0 + x * x * (P2 - x * P3) else if (x < 1.0) then Result := P0 + x * x * (P2 + x * P3) else if (x < 2.0) then Result := Q0 + x * (Q1 + x * (Q2 + x * Q3)) else Result := 0.0; end; function TMitchelInterpolation.MaxSupport : double; begin Result := 2.0; end; end.
{ MIT License Copyright (c) 2017-2019 Marcos Douglas B. Santos 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. } unit JamesBase64Tests; {$i James.inc} interface uses Classes, SysUtils, SynCommons, JamesDataBase, JamesDataCore, JamesBase64Adapters, JamesTestCore, JamesTestPlatform; type /// all tests for TBase64Adapter TBase64AdapterTests = class(TTestCase) published procedure TestRawByteString; procedure TestDataStream; end; implementation { TBase64AdapterTests } const ENCODED_TEXT = 'SmFtZXMgTGli'; DECODED_TEXT = 'James Lib'; procedure TBase64AdapterTests.TestRawByteString; var a: TBase64Adapter; begin a.Init(baDecode, ENCODED_TEXT); check(a.AsRawByteString = DECODED_TEXT, 'decoded'); a.Init(baEncode, DECODED_TEXT); check(a.AsRawByteString = ENCODED_TEXT, 'encoded'); end; procedure TBase64AdapterTests.TestDataStream; var a: TBase64Adapter; s: IDataStream; begin a.Init(baDecode, ENCODED_TEXT); s := TDataStream.Create(DECODED_TEXT); check(a.AsDataStream.AsRawByteString = s.AsRawByteString, 'decoded'); a.Init(baEncode, DECODED_TEXT); s := TDataStream.Create(ENCODED_TEXT); check(a.AsDataStream.AsRawByteString = s.AsRawByteString, 'encoded'); end; initialization TTestSuite.Create('Base64').Ref .Add(TTest.Create(TBase64AdapterTests)) end.
program USubsystemProgram; {$mode delphi} {$h+} uses Classes,FpSock,Process,SSockets,SysUtils; type TArrayOfString = array of String; TTargetPlatform = class Options:array of String; Config,Symbol:String; constructor Create(Options:array of String;Config,Symbol:String); procedure Build(ProgramFile,BuildDir:String); end; const UltiboInstallation='/root/ultibo/core/fpc'; var FrameNumber:Integer; Qemu:TTargetPlatform; Rpi2:TTargetPlatform; // QemuMonitor:TTcpChannel; QemuProcess:TProcess; QemuStopping:Boolean; // SerialChannels:array [0..3] of TTcpChannel; procedure Log(Message:String); begin WriteLn(Message); end; function Path(Parts:array of String):String; var I:Integer; begin Result:=Parts[Low(Parts)]; for I:=Low(Parts) + 1 to High(Parts) do Result:=Result + '/' + Parts[I]; end; function WhichExecutable(ProgramName:String):String; begin Result:=''; end; constructor TTargetPlatform.Create(Options:array of String;Config,Symbol:String); var I:Integer; begin SetLength(self.Options,Length(Options)); for I:=Low(Options) to High(Options) do self.Options[I]:=Options[I]; self.Config:=Config; self.Symbol:=Symbol; end; function Option(Name,Value:String):String; begin Result:=Name + Value; end; procedure Fail(Condition:Boolean); begin if not Condition then raise Exception.Create('Fail'); end; procedure RecreateDir(Dir:String); var FileRec:TSearchRec; P:String; begin if FileExists(Dir) then begin if FindFirst(Path([Dir,'*']),faAnyFile,FileRec) = 0 then begin repeat P:=Path([Dir,FileRec.Name]); if FileGetAttr(P) and faDirectory = 0 then Fail(DeleteFile(P)); until FindNext(FileRec) <> 0; FindClose(FileRec); Fail(RemoveDir(Dir)); end; end; Fail(CreateDir(Dir)); end; procedure TestProcess; var P:TProcess; L:TStringList; begin P:=TProcess.Create(nil); P.Executable:='/bin/ls'; P.Options:=P.Options + [poWaitOnExit,poUsePipes]; P.Execute; Log(Format('exit status %d',[P.ExitStatus])); L:=TStringList.Create; L.LoadFromStream(P.Output); L.SaveToFile('testoutput.txt'); L.Free; P.Free; end; procedure CopyFile(Source,Destination:String); var S:TMemoryStream; begin S:=TMemoryStream.Create; try S.LoadFromFile(Source); S.SaveToFile(Destination); finally S.Free; end; end; procedure StartQemu; var I:Integer; Parts:TStringList; Command:String; begin QemuProcess:=TProcess.Create(nil); { Qemu.(["qemu-system-arm", "-M", "versatilepb", "-cpu", "cortex-a8", "-kernel", "kernel.bin", "-m", "1024M", "-usb", "-display", "none", "-monitor", "tcp:127.0.0.1:38004,server", "-serial", "tcp:127.0.0.1:38000,server", "-serial", "tcp:127.0.0.1:38001,server", "-serial", "tcp:127.0.0.1:38002,server", "-serial", "tcp:127.0.0.1:38003,server"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) } end; procedure TTargetPlatform.Build(ProgramFile,BuildDir:String); var I:Integer; Fpc:TProcess; Parts:TStringList; Command:String; begin Log(Format('Build %s into %s',[ProgramFile,BuildDir])); RecreateDir(BuildDir); RecreateDir('artifacts'); Parts:=TStringList.Create; Parts.Add('fpc'); Parts.Add('-d' + Symbol); Parts.Add('-l-'); Parts.Add('-v0ewn'); Parts.Add('-B'); Parts.Add('-Tultibo'); Parts.Add('-O2'); Parts.Add('-Parm'); Parts.Add(Option('-FE',BuildDir)); for I:=Low(Options) to High(Options) do Parts.Add(Options[I]); Parts.Add(Option('@',Path([UltiboInstallation,'bin',Config]))); Parts.Add(ProgramFile); Command:=Parts[0]; for I:=1 to Parts.Count - 1 do Command:=Command + ' ' + Parts[I]; Parts.Free; Fpc:=TProcess.Create(nil); Fpc.Options:=Fpc.Options + [poWaitOnExit]; //,poUsePipes]; Fpc.Executable:='/bin/bash'; Fpc.Parameters.Add('-c'); Fpc.Parameters.Add(Command); // Log(Fpc.Executable); // for I:=0 to Fpc.Parameters.Count - 1 do // Log(Fpc.Parameters[I]); Fpc.Execute; if Fpc.ExitStatus = 0 then CopyFile('kernel.bin','artifacts/kernel.bin') else Log(Format('exit status %d',[Fpc.ExitStatus])); Fpc.Free; //Log('mv kernel* $LPR_FOLDER/$OUTPUT'); //Log('if [[ $? -ne 0 ]]; then log fail: $?; fi'); //Log('local THISOUT=$OUTPUT/kernels-and-tests/$FOLDER'); //Log('rm -rf $THISOUT && \'); //Log('// mkdir -p $THISOUT && \'); //Log('// cp -a $FOLDER/$OUTPUT/* $THISOUT && \'); //Log('// if [[ $? -ne 0 ]]; then log fail: $?; fi'); end; procedure Build; begin Qemu:=TTargetPlatform.Create (['-CpARMV7A','-WpQEMUVPB'],'qemuvpb.cfg','TARGET_QEMUARM7A'); // RPi:=TTargetPlatform.Create // (['-CpARMV6','-WpRPIB'],'rpi.cfg','TARGET_RPI_INCLUDING_RPI0'); RPi2:=TTargetPlatform.Create (['-CpARMV7A','-WpRPI2B'],'rpi2.cfg','TARGET_RPI2_INCLUDING_RPI3'); // RPi3:=TTargetPlatform.Create // (['-CpARMV7A','-WpRPI3B'],'rpi3.cfg','TARGET_RPI3'); Qemu.Build('projects/projectone/projectone.lpr','obj'); //Rpi2.Build('projects/projectone/projectone.lpr','obj'); //TestProcess; end; procedure Bootstrap; begin end; procedure Main; var s:String; begin if ParamCount = 1 then begin s:=ParamStr(1); if s = 'bootstrap' then Bootstrap else if s = 'build' then Build else Log(Format('unrecognized %s',[s])); end else begin Log('need one argument'); end; end; begin Main; end. OUTPUT=build-output ERRORS=$OUTPUT/build-errors.txt LOG=$OUTPUT/build.log rm -rf $OUTPUT mkdir -p $OUTPUT rm -f $LOG function create-build-summary { cat $LOG | egrep -i '(fail|error|warning|note):' | sort | uniq > $ERRORS log log Summary: log cat $ERRORS | tee -a $LOG log log $(wc $ERRORS) if [[ -s $ERRORS ]] exit 1 function unix_line_endings { tr -d \\r < $1 > tmp && \ mv tmp $1 function convert-frames { convert-frames-by-size 1024x768 convert-frames-by-size 1920x1080 convert-frames-by-size 1920x1200 function convert-frames-by-size { local SIZE=$1 local FRAMES=run-qemu-output/frame*-${SIZE}x3.fb ls $FRAMES > /dev/null 2>&1 if [[ $? -eq 0 ]] for frame in $FRAMES ultibo-bash convert -size $SIZE -depth 8 rgb:$frame ${frame%.fb}.png rm $frame function test-qemu-target { local FOLDER=$1 cd $FOLDER/$OUTPUT time python $RESTORE_PWD/run-qemu for textfile in run-qemu-output/*.txt unix_line_endings $textfile sed -i 's/.\x1b.*\x1b\[D//' run-qemu-output/qemumonitor.txt sed -i 's/\x1b\[K//' run-qemu-output/qemumonitor.txt ls run-qemu-output/screen*.ppm > /dev/null 2>&1 if [[ $? -eq 0 ]] for screen in run-qemu-output/screen*.ppm ultibo-bash convert $screen ${screen%.ppm}.png && \ rm $screen convert-frames file run-qemu-output/* outputfolder = 'run-qemu-output' class TcpChannel: def __init__ (self, name, port): # print name, port self.name = name self.port = port self.linebuffer = "" self.socket = socket.socket () opened = False while not opened: try: self.socket.connect (('127.0.0.1', self.port)) opened = True except: sleep (0.1) self.logfile = open ('{}/{}.txt'.format (outputfolder, self.name), 'a') def writeline (self, line, echo=False): # print '{}>>>>{}'.format (self.name, line) if echo: self.logfile.write ('{}>>>>{}\n'.format (self.name, line)) self.socket.sendall (line + '\n') def writekeyboardline (self, line, echo=False): # print '{}>>>>{}'.format (self.name, line) if echo: self.logfile.write ('{}>>>>{}\n'.format (self.name, line)) self.socket.sendall (line + '\r') def drain (self): # print 'drain {}'.format (self.name) while ([], [], []) != select.select ([self.socket], [], [], 0): try: data = self.socket.recv (4096) except: break if data == "": break self.logfile.write (data) for c in data: if c == '\r': pass elif c == '\n': # print '{}<<<<{}'.format(self.name, self.linebuffer) index = self.linebuffer.find ('program stop') if index != -1: # print self.linebuffer global stopping stopping = True monitor.writeline ('quit') index = self.linebuffer.find ('frame buffer') if index != -1: # print self.linebuffer fb = parse.parse ('{} frame buffer at {address} size {width:d}x{height:d}x{depth:d}', self.linebuffer) if fb: framecapture (fb.named ['address'], fb.named ['width'], fb.named ['height'], fb.named ['depth']) self.linebuffer = "" else: self.linebuffer = self.linebuffer + c sleep (0.001, self.name) def finishquit (self, process): while process.returncode == None: sleep (0.001, 'finishquit ' + self.name) process.poll () if ([], [], []) != select.select ([self.socket], [], [], 0): sys.stdout.write (self.socket.recv (4096)) def close (self): self.logfile.close () self.socket.close () procedure DrainAll; var I:Integer; begin for I:=Low(SerialChannels) to High(SerialChannels) do SerialChannels[I].Drain; QemuMonitor.Drain; end; procedure FrameCapture(Address,Width,Height,Depth:Integer); begin print 'framecapture', address, width, height, depth monitor.writeline ('memsave {} {} {}/frame-{:02d}-{}x{}x{}.fb'.format (address, width * height * depth, outputfolder, framenumber, width, height, depth)) Inc(FrameNumber); end; procedure QemuWork; begin QemuStopping:=False; while not QemuStopping do Drainall('not stopping'); Drainall ('stopping'); Sleep(1*1000); Drainall ('one more before quit'); QemuMonitor.FinishQuit(QemuProcess); end; RunQemuTest; begin RecreateDir(QemuOutputFolder); StartQemu; FrameNumber:=1; QemuMonitor:=TcpChannel.Create('qemumonitor', 38004); for I:=Low(SerialChannels) to High(SerialChannels) do SerialChannels[I]:=TcpChannel.Create(Format('serial%d',[38000 + I])); QemuWork; QemuMonitor.Close; for I:=Low(SerialChannels) to High(SerialChannels) do SerialChannels[I].Close; end; #screennumber = 1 #def screendump (): # global screennumber # monitor.writeline ('screendump {}/screen-{:02d}.ppm'.format (outputfolder, screennumber)) # screennumber = screennumber + 1
{*********************************************************} {* VPDBINTF.PAS 1.03 *} {*********************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* Version: MPL 1.1 *} {* *} {* The contents of this file are subject to the Mozilla Public License *} {* Version 1.1 (the "License"); you may not use this file except in *} {* compliance with the License. You may obtain a copy of the License at *} {* http://www.mozilla.org/MPL/ *} {* *} {* Software distributed under the License is distributed on an "AS IS" basis, *} {* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *} {* for the specific language governing rights and limitations under the *} {* License. *} {* *} {* The Original Code is TurboPower Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* Hannes Danzl *} {* *} {* ***** END LICENSE BLOCK ***** *} { This unit was provided by Hannes Danzl and is used here with permission } // base unit for all interfaced tdatasets<br> // defines interfaces for connecting to db independent datasets unit VPDbIntf; interface uses classes, db, sysutils; type // interface for sql capable datasets ISQLDataSet = interface ['{5855A2B8-8568-4AA5-86BC-6DDB06833F8E}'] // see iSQL procedure SetiSQL(const value: String); // see iSQL function GetiSQL:String; // see iConnectionParams procedure SetiConnectionParams(const value: String); // see iConnectionParams function GetiConnectionParams:String; // interface to the ExecSQL method procedure IExecSQL; // interface for setting the SQL statement property iSQL: String read GetiSQL write SetiSQL; // interface for optional connection parameters for the dataset property iConnectionParams: String read GetiConnectionParams write SetiConnectionParams; end; // interface for datasets capable of creating "tables" ICreateTableDataSet = interface ['{83FC58AD-C245-4F03-A2B8-D1B737BC1955}'] // should create the given table procedure iCreateTable(const aTableName: String; const aFieldDefs: TFieldDefs; const aIndexDefs: TIndexDefs); end; // internal storage type TCreateInstance = function (InterfaceClass: String): TObject; // factory for creating classes that implement ISQLDataset TDBFactory = class(TObject) protected // list of registered creation methods; a method must be of type TCreateInstance fStringlist: TStringlist; public // constructor constructor Create; virtual; // destructor destructor Destroy; override; // registers a class that implements ISQLDataSet. aproc is a function, // that creates an instance of a TDataset descendant with ISQLDataSet // implementation and returns it. procedure RegisterInterfaceType(InterfaceClass: String; aProc: TCreateinstance); // calls the appropriate creation method and returns the dataset; nil if the // classtype is not known. function CreateInstance(InterfaceClass: String): TObject; end; // the single instance of TSQLDatasetFactory for each application // use it to register and create datasets function sSQLDatasetFactory: TDBFactory; implementation { TSQLDatasetFactory } constructor TDBFactory.Create; begin inherited; fStringlist:=TStringlist.Create; end; function TDBFactory.CreateInstance(InterfaceClass: String): TObject; var anindex: integer; begin result:=nil; anindex:=fStringlist.IndexOf(InterfaceClass); if anindex>-1 then result:=TCreateinstance(fStringlist.Objects[anIndex])(InterfaceClass) else assert(false, 'DB type "'+InterfaceClass+'" not registered with factory.'); end; destructor TDBFactory.Destroy; begin fStringlist.Free; inherited; end; procedure TDBFactory.RegisterInterfaceType(InterfaceClass: String; aProc: TCreateinstance); begin fStringlist.AddObject(InterfaceClass, TObject(@aProc)) end; var fSQLDatasetFactory: TDBFactory; function sSQLDatasetFactory: TDBFactory; begin if fSQLDatasetFactory=nil then fSQLDatasetFactory:=TDBFactory.Create; result:=fSQLDatasetFactory; end; initialization fSQLDatasetFactory:=nil; end.
unit Eagle.ConsoleIO; interface uses Console; type IConsoleIO = interface ['{53469311-2F04-4568-9928-5E85CB2822EC}'] procedure WriteInfo(const Msg : string); procedure WriteError(const Msg : string); procedure WriteProcess(const Msg : string); end; TConsoleIO = class(TInterfacedObject, IConsoleIO) private procedure WriteColor(const Text: string; Color: Byte; const NewLine : Boolean = True); public procedure WriteInfo(const Msg : string); procedure WriteError(const Msg : string); procedure WriteProcess(const Msg : string); end; implementation { TConsoleIO } procedure TConsoleIO.WriteColor(const Text: string; Color: Byte; const NewLine : Boolean = True); var OldColor: Byte; begin OldColor := TextColor; TextColor(Color); if NewLine then Writeln(''); Write(Text); TextColor(OldColor); end; procedure TConsoleIO.WriteError(const Msg: string); begin WriteColor(Msg, Red); end; procedure TConsoleIO.WriteInfo(const Msg: string); begin WriteColor(Msg, LightGray); end; procedure TConsoleIO.WriteProcess(const Msg: string); begin GotoXY(WhereX - (WhereX -1), WhereY); WriteColor(Msg, LightGray, False); end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clRequestChooser; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Forms, Classes, Controls, StdCtrls, TypInfo, SysUtils, Dialogs, ComCtrls, {$ELSE} Vcl.Forms, System.Classes, Vcl.Controls, Vcl.StdCtrls, System.TypInfo, System.SysUtils, Vcl.Dialogs, Vcl.ComCtrls, {$ENDIF} clHttpRequest, clHtmlParser; type THttpRequestChooser = class(TForm) btnOK: TButton; btnCancel: TButton; lblCaption: TLabel; procedure FormShow(Sender: TObject); private FEditControl: TControl; procedure DoOnGetHtmlForm(Sender: TObject; AParser: TclHtmlParser; var AForm: TclHtmlForm); function GetRightMargin: Integer; procedure DoFileButtonClick(Sender: TObject); function GetLeftMargin: Integer; procedure SetControlsTabOrder(AStartFrom: Integer); procedure SetFocusControl; public class function AddSingleHttpItem(AHTTPRequest: TclHttpRequest): Boolean; class function BuildRequestItemsByUrl(AHTTPRequest: TclHttpRequest): Boolean; class function BuildRequestItemsByFile(AHTTPRequest: TclHttpRequest): Boolean; class function BuildRequestItemsByText(AHTTPRequest: TclHttpRequest): Boolean; end; implementation uses clFormChooser, clActionInfo; const hcOpenFileDialog = 0; type TControlAccess = class(TControl); {$R *.DFM} class function THttpRequestChooser.AddSingleHttpItem(AHttpRequest: TclHttpRequest): Boolean; var i: Integer; Dlg: THttpRequestChooser; ComboBox: TComboBox; begin Dlg := THttpRequestChooser.Create(nil); try Dlg.Caption := 'Specify Request Item'; Dlg.lblCaption.Caption := 'Type'; ComboBox := TComboBox.Create(Dlg); ComboBox.Parent := Dlg; ComboBox.Left := 46; ComboBox.Top := 8; ComboBox.Width := 204; ComboBox.Style := csDropDownList; for i := 0 to GetRegisteredHttpRequestItems().Count - 1 do begin ComboBox.Items.Add(TclHttpRequestItemClass(GetRegisteredHttpRequestItems()[i]).ClassName); end; ComboBox.ItemIndex := 0; ComboBox.TabOrder := 0; Dlg.SetControlsTabOrder(1); Result := (Dlg.ShowModal() = mrOK); if Result then begin AHttpRequest.Items.Add(TclHttpRequestItemClass(GetRegisteredHttpRequestItems()[ComboBox.ItemIndex])); end; finally Dlg.Free(); end; end; procedure THttpRequestChooser.DoFileButtonClick(Sender: TObject); var dlg: TOpenDialog; begin dlg := TOpenDialog.Create(nil); try dlg.Filename := TControlAccess(FEditControl).Text; dlg.InitialDir := ExtractFilePath(dlg.Filename); dlg.Filter := '*.*'; dlg.HelpContext := hcOpenFileDialog; dlg.Options := dlg.Options + [ofShowHelp, ofEnableSizing]; if dlg.Execute then TControlAccess(FEditControl).Text := dlg.Filename; finally dlg.Free(); end; end; class function THttpRequestChooser.BuildRequestItemsByFile(AHTTPRequest: TclHttpRequest): Boolean; var Dlg: THttpRequestChooser; Edit: TEdit; Button: TButton; List: TStrings; OldOnGetHtmlForm: TclGetHtmlFormEvent; begin Dlg := THttpRequestChooser.Create(nil); try Dlg.Caption := 'Build Request Items by local file'; Dlg.lblCaption.Caption := 'File Name'; Dlg.Width := 500; Edit := TEdit.Create(Dlg); Dlg.FEditControl := Edit; Edit.Parent := Dlg; Button := TButton.Create(Dlg); Button.Caption := '...'; Button.OnClick := Dlg.DoFileButtonClick; Button.Parent := Dlg; Button.Top := 8; Button.Width := 22; Button.Height := 22; Button.Left := Dlg.ClientWidth - Dlg.GetRightMargin() - Button.Width; Edit.Left := 66; Edit.Top := 8; Edit.Width := Dlg.ClientWidth - Edit.Left - Button.Width - Dlg.GetRightMargin() - 1; Edit.TabOrder := 0; Button.TabOrder := 1; Dlg.SetControlsTabOrder(2); Result := (Dlg.ShowModal() = mrOK); if Result and FileExists(Edit.Text) then begin List := TStringList.Create(); OldOnGetHtmlForm := AHttpRequest.OnGetHtmlForm; try AHttpRequest.OnGetHtmlForm := Dlg.DoOnGetHtmlForm; List.LoadFromFile(Edit.Text); THttpActionInfo.ShowAction(AHttpRequest.BuildFormPostRequest(List)); finally AHttpRequest.OnGetHtmlForm := OldOnGetHtmlForm; List.Free(); end; end; finally Dlg.Free(); end; end; class function THttpRequestChooser.BuildRequestItemsByUrl(AHTTPRequest: TclHttpRequest): Boolean; var Dlg: THttpRequestChooser; Edit: TEdit; OldOnGetHtmlForm: TclGetHtmlFormEvent; begin Dlg := THttpRequestChooser.Create(nil); try Dlg.Caption := 'Build Request Items by Url'; Dlg.lblCaption.Caption := 'URL'; Dlg.Width := 500; Edit := TEdit.Create(Dlg); Dlg.FEditControl := Edit; Edit.Parent := Dlg; Edit.Left := 46; Edit.Top := 8; Edit.Width := Dlg.ClientWidth - Edit.Left - Dlg.GetRightMargin(); Edit.TabOrder := 0; Dlg.SetControlsTabOrder(1); Result := (Dlg.ShowModal() = mrOK); if Result and (system.Pos('http://', LowerCase(Edit.Text)) = 1) then begin OldOnGetHtmlForm := AHttpRequest.OnGetHtmlForm; try AHttpRequest.OnGetHtmlForm := Dlg.DoOnGetHtmlForm; THttpActionInfo.ShowAction(AHttpRequest.BuildFormPostRequestByUrl(Edit.Text)); finally AHttpRequest.OnGetHtmlForm := OldOnGetHtmlForm; end; end; finally Dlg.Free(); end; end; procedure THttpRequestChooser.DoOnGetHtmlForm(Sender: TObject; AParser: TclHtmlParser; var AForm: TclHtmlForm); var num: Integer; begin num := THttpFormChooser.ChooseForm(AParser); if (num > -1) and (num < AParser.Forms.Count) then begin AForm := AParser.Forms[num]; end; end; function THttpRequestChooser.GetRightMargin: Integer; begin Result := ClientWidth - btnCancel.Left - btnCancel.Width; end; function THttpRequestChooser.GetLeftMargin: Integer; begin Result := lblCaption.Left; end; class function THttpRequestChooser.BuildRequestItemsByText(AHTTPRequest: TclHttpRequest): Boolean; var Dlg: THttpRequestChooser; Edit: TRichEdit; OldOnGetHtmlForm: TclGetHtmlFormEvent; begin Dlg := THttpRequestChooser.Create(nil); try Dlg.Caption := 'Build Request Items by Text'; Dlg.lblCaption.Caption := 'Enter the Html tags to parse'; Dlg.BorderStyle := bsSizeable; Edit := TRichEdit.Create(Dlg); Dlg.FEditControl := Edit; Edit.Parent := Dlg; Edit.Left := Dlg.GetLeftMargin(); Edit.Top := 29; Edit.Height := 4; Edit.Width := Dlg.ClientWidth - Edit.Left - Dlg.GetRightMargin(); Edit.Anchors := [akLeft, akTop, akRight, akBottom]; Edit.PlainText := True; Edit.WordWrap := False; Edit.ScrollBars := ssBoth; Dlg.Width := 500; Dlg.Height := 300; Dlg.Constraints.MinWidth := 300; Dlg.Constraints.MinHeight := 200; Edit.TabOrder := 0; Dlg.SetControlsTabOrder(1); Result := (Dlg.ShowModal() = mrOK); if Result and (Edit.Lines.Count > 0) then begin OldOnGetHtmlForm := AHttpRequest.OnGetHtmlForm; try AHttpRequest.OnGetHtmlForm := Dlg.DoOnGetHtmlForm; THttpActionInfo.ShowAction(AHttpRequest.BuildFormPostRequest(Edit.Lines)); finally AHttpRequest.OnGetHtmlForm := OldOnGetHtmlForm; end; end; finally Dlg.Free(); end; end; procedure THttpRequestChooser.SetControlsTabOrder(AStartFrom: Integer); begin btnOK.TabOrder := AStartFrom; btnCancel.TabOrder := AStartFrom + 1; end; procedure THttpRequestChooser.SetFocusControl; var i: Integer; begin for i := 0 to ControlCount - 1 do begin if (Controls[i] is TWinControl) and (TWinControl(Controls[i]).TabOrder = 0) and (TWinControl(Controls[i]).CanFocus()) then begin TWinControl(Controls[i]).SetFocus(); Break; end; end; end; procedure THttpRequestChooser.FormShow(Sender: TObject); begin SetFocusControl(); end; end.
// SAX for Pascal, Simple API for XML Interfaces in Pascal. // Ver 1.1 July 4, 2003 // http://xml.defined.net/SAX (this will change!) // Based on http://www.saxproject.org/ // No warranty; no copyright -- use this as you will. unit SAXAdapters; interface uses SAX, SAXExt, BSAX, BSAXExt; resourcestring SAdaptedNil = 'Adapted interface must not be nil'; // functions to adapt from buffered to un-buffered interfaces function adapt(const value: IBufferedContentHandler; useAttributes2: Boolean): IContentHandler; overload; function adapt(const value: IBufferedContentHandler; const XMLReader: IXMLReader): IContentHandler; overload; function adapt(const value: IBufferedDTDHandler): IDTDHandler; overload; function adapt(const value: IBufferedDeclHandler): IDeclHandler; overload; function adapt(const value: IBufferedLexicalHandler): ILexicalHandler; overload; // functions to adapt from un-buffered to buffered interfaces function adapt(const value: IContentHandler; useAttributes2: Boolean): IBufferedContentHandler; overload; function adapt(const value: IContentHandler; const XMLReader: IBufferedXMLReader): IBufferedContentHandler; overload; function adapt(const value: IDTDHandler): IBufferedDTDHandler; overload; function adapt(const value: IDeclHandler): IBufferedDeclHandler; overload; function adapt(const value: ILexicalHandler): IBufferedLexicalHandler; overload; type ISAXAdapter = interface ['{5794D4DF-E2B4-45CD-BD8B-52467E5A2F68}'] function getAdaptedIntf: IUnknown; property AdaptedIntf: IUnknown read getAdaptedIntf; end; TSAXAdapter = class(TInterfacedObject, ISAXAdapter) private FAdapted: IUnknown; protected property Adapted: IUnknown read FAdapted; // convenience property { ISAXAdapter } function getAdaptedIntf: IUnknown; public constructor Create(const adaptedIntf: IUnknown); end; TBufferedAttributesAdapter = class; TAttributesAdapter = class(TInterfacedObject, IBufferedAttributes) private FAttributes: IAttributes; protected FUriStr, FLocalNameStr, FQNameStr, FTypeStr, FValueStr: SAXString; { IBufferedAttributes } function getLength() : Integer; procedure getURI(index : Integer; out uri: PSAXChar; out uriLength: Integer); procedure getLocalName(index : Integer; out localName: PSAXChar; out localNameLength: Integer); procedure getQName(index : Integer; out qName: PSAXChar; out qNameLength: Integer); procedure getType(index : Integer; out attType: PSAXChar; out attTypeLength: Integer); overload; procedure getType(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; out attType: PSAXChar; out attTypeLength: Integer); overload; procedure getType(qName: PSAXChar; qNameLength: Integer; out attType: PSAXChar; out attTypeLength: Integer); overload; procedure getValue(index : Integer; out value: PSAXChar; out valueLength: Integer); overload; procedure getValue(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; out value: PSAXChar; out valueLength: Integer); overload; procedure getValue(qName : PSAXChar; qNameLength : Integer; out value: PSAXChar; out valueLength: Integer); overload; function getIndex(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer) : Integer; overload; function getIndex(qName : PSAXChar; qNameLength : Integer) : Integer; overload; public procedure init(const attributes: IAttributes); function getInterface() : IBufferedAttributes; virtual; end; TAttributes2Adapter = class(TAttributesAdapter, IBufferedAttributes2) protected { IBufferedAttributes2 } function isDeclared(index : Integer) : Boolean; overload; function isDeclared(qName : PSAXChar; qNameLength : Integer) : Boolean; overload; function isDeclared(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer) : Boolean; overload; function isSpecified(index : Integer) : Boolean; overload; function isSpecified(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer) : Boolean; overload; function isSpecified(qName : PSAXChar; qNameLength : Integer) : Boolean; overload; public function getInterface() : IBufferedAttributes; override; end; TContentHandlerAdapter = class(TSAXAdapter, IBufferedContentHandler) private FAttributes: TBufferedAttributesAdapter; protected function getUseAttributes2: Boolean; procedure setUseAttributes2(Value: Boolean); { IBufferedContentHandler } procedure setDocumentLocator(const locator: ILocator); procedure startDocument(); procedure endDocument(); procedure startPrefixMapping(prefix: PSAXChar; prefixLength: Integer; uri: PSAXChar; uriLength: Integer); procedure endPrefixMapping(prefix: PSAXChar; prefixLength: Integer); procedure startElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; const atts: IBufferedAttributes); procedure endElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer); procedure characters(ch : PSAXChar; chLength : Integer); procedure ignorableWhitespace(ch : PSAXChar; chLength : Integer); procedure processingInstruction(target : PSAXChar; targetLength : Integer; data : PSAXChar; dataLength : Integer); procedure skippedEntity(name : PSAXChar; nameLength : Integer); public constructor create(const contentHandler: IContentHandler; useAttributes2: Boolean); destructor Destroy; override; property UseAttributes2: Boolean read GetUseAttributes2 write SetUseAttributes2; end; TDTDHandlerAdapter = class(TSAXAdapter, IBufferedDTDHandler) protected { IBufferedDTDHandler } procedure notationDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer); procedure unparsedEntityDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer; notationName : PSAXChar; notationNameLength : Integer); public constructor create(const dtdHandler: IDTDHandler); end; TDeclHandlerAdapter = class(TSAXAdapter, IBufferedDeclHandler) protected { IBufferedDeclHandler } procedure elementDecl(name : PSAXChar; nameLength : Integer; model : PSAXChar; modelLength : Integer); procedure attributeDecl(eName : PSAXChar; eNameLength : Integer; aName : PSAXChar; aNameLength : Integer; attrType : PSAXChar; attrTypeLength : Integer; mode : PSAXChar; modeLength : Integer; value : PSAXChar; valueLength : Integer); procedure internalEntityDecl(name : PSAXChar; nameLength : Integer; value : PSAXChar; valueLength : Integer); procedure externalEntityDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer); public constructor create(const declHandler: IDeclHandler); end; TLexicalHandlerAdapter = class(TSAXAdapter, IBufferedLexicalHandler) protected { IBufferedLexicalHandler } procedure startDTD(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer); procedure endDTD(); procedure startEntity(name : PSAXChar; nameLength : Integer); procedure endEntity(name : PSAXChar; nameLength : Integer); procedure startCDATA(); procedure endCDATA(); procedure comment(ch : PSAXChar; chLength : Integer); public constructor create(const lexicalHandler: ILexicalHandler); end; TBufferedAttributesAdapter = class(TInterfacedObject, IAttributes) private FAttributes: IBufferedAttributes; protected { IAttributes } function getLength() : Integer; function getURI(index : Integer) : SAXString; function getLocalName(index : Integer) : SAXString; function getQName(index : Integer) : SAXString; function getType(index : Integer) : SAXString; overload; function getType(const uri, localName : SAXString) : SAXString; overload; function getType(const qName : SAXString) : SAXString; overload; function getValue(index : Integer) : SAXString; overload; function getValue(const uri, localName : SAXString) : SAXString; overload; function getValue(const qName : SAXString) : SAXString; overload; function getIndex(const uri, localName : SAXString) : Integer; overload; function getIndex(const qName : SAXString) : Integer; overload; public procedure init(const bufferedAttributes: IBufferedAttributes); function getInterface(): IAttributes; virtual; end; TBufferedAttributes2Adapter = class(TBufferedAttributesAdapter, IAttributes2) protected { IAttributes2 } function isDeclared(index : Integer) : Boolean; overload; function isDeclared(const qName : SAXString) : Boolean; overload; function isDeclared(const uri, localName : SAXString) : Boolean; overload; function isSpecified(index : Integer) : Boolean; overload; function isSpecified(const uri, localName : SAXString) : Boolean; overload; function isSpecified(const qName : SAXString) : Boolean; overload; public function getInterface(): IAttributes; override; end; TBufferedContentHandlerAdapter = class(TSAXAdapter, IContentHandler) private FAttributes: TAttributesAdapter; protected function getUseAttributes2: Boolean; procedure setUseAttributes2(Value: Boolean); { IContentHandler } procedure setDocumentLocator(const locator: ILocator); procedure startDocument(); procedure endDocument(); procedure startPrefixMapping(const prefix, uri : SAXString); procedure endPrefixMapping(const prefix : SAXString); procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); procedure endElement(const uri, localName, qName: SAXString); procedure characters(const ch : SAXString); procedure ignorableWhitespace(const ch : SAXString); procedure processingInstruction(const target, data : SAXString); procedure skippedEntity(const name : SAXString); public constructor create(const contentHandler: IBufferedContentHandler; useAttributes2: Boolean); destructor Destroy; override; property UseAttributes2: Boolean read GetUseAttributes2 write SetUseAttributes2; end; TBufferedDTDHandlerAdapter = class(TSAXAdapter, IDTDHandler) protected { IDTDHandler } procedure notationDecl(const name, publicId, systemId : SAXString); procedure unparsedEntityDecl(const name, publicId, systemId, notationName : SAXString); public constructor create(const dtdHandler: IBufferedDTDHandler); end; TBufferedDeclHandlerAdapter = class(TSAXAdapter, IDeclHandler) protected { IDeclHandler } procedure elementDecl(const name, model : SAXString); procedure attributeDecl(const eName, aName, attrType, mode, value: SAXString); procedure internalEntityDecl(const name, value : SAXString); procedure externalEntityDecl(const name, publicId, systemId : SAXString); public constructor create(const declHandler: IBufferedDeclHandler); end; TBufferedLexicalHandlerAdapter = class(TSAXAdapter, ILexicalHandler) protected { ILexicalHandler } procedure startDTD(const name, publicId, systemId : SAXString); procedure endDTD(); procedure startEntity(const name : SAXString); procedure endEntity(const name : SAXString); procedure startCDATA(); procedure endCDATA(); procedure comment(const ch : SAXString); public constructor create(const lexicalHandler: IBufferedLexicalHandler); end; implementation { Functions to adapt from buffered to un-buffered interfaces} function adapt(const value: IBufferedContentHandler; useAttributes2: Boolean): IContentHandler; begin Result:= TBufferedContentHandlerAdapter.create(value, useAttributes2); end; function adapt(const value: IBufferedContentHandler; const XMLReader: IXMLReader): IContentHandler; var useAttributes2: Boolean; begin try useAttributes2:= XMLReader.Features[useAttributes2Feature]; except on ESAXNotSupportedException do useAttributes2:= False; on ESAXNotRecognizedException do useAttributes2:= False; else raise; end; Result:= adapt(value, useAttributes2); end; function adapt(const value: IBufferedDTDHandler): IDTDHandler; begin Result:= TBufferedDTDHandlerAdapter.create(value); end; function adapt(const value: IBufferedDeclHandler): IDeclHandler; begin Result:= TBufferedDeclHandlerAdapter.create(value); end; function adapt(const value: IBufferedLexicalHandler): ILexicalHandler; begin Result:= TBufferedLexicalHandlerAdapter.create(value); end; { Functions to adapt from un-buffered to buffered interfaces} function adapt(const value: IContentHandler; useAttributes2: Boolean): IBufferedContentHandler; begin Result:= TContentHandlerAdapter.create(value, useAttributes2); end; function adapt(const value: IContentHandler; const XMLReader: IBufferedXMLReader): IBufferedContentHandler; var useAttributes2: Boolean; begin try useAttributes2:= XMLReader.Features[UseAttributes2Feature]; except on ESAXNotSupportedException do useAttributes2:= False; on ESAXNotRecognizedException do useAttributes2:= False; else raise; end; Result:= adapt(value, useAttributes2); end; function adapt(const value: IDTDHandler): IBufferedDTDHandler; begin Result:= TDTDHandlerAdapter.create(value); end; function adapt(const value: IDeclHandler): IBufferedDeclHandler; begin Result:= TDeclHandlerAdapter.create(value); end; function adapt(const value: ILexicalHandler): IBufferedLexicalHandler; begin Result:= TLexicalHandlerAdapter.create(value); end; { TSAXAdapter } constructor TSAXAdapter.Create(const adaptedIntf: IUnknown); begin if adaptedIntf = nil then raise ESAXException.Create(SAdaptedNil); inherited Create; FAdapted := adaptedIntf; end; function TSAXAdapter.getAdaptedIntf: IUnknown; begin Result := FAdapted; end; { TAttributesAdapter } function TAttributesAdapter.getIndex(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer): Integer; begin Result:= FAttributes.getIndex(PSAXCharToSAXString(uri, uriLength), PSAXCharToSAXString(localName, localNameLength)); end; function TAttributesAdapter.getIndex(qName: PSAXChar; qNameLength: Integer): Integer; begin Result:= FAttributes.getIndex(PSAXCharToSAXString(qName, qNameLength)); end; function TAttributesAdapter.getInterface: IBufferedAttributes; begin Result:= Self; end; function TAttributesAdapter.getLength: Integer; begin Result:= FAttributes.getLength(); end; procedure TAttributesAdapter.getLocalName(index: Integer; out localName: PSAXChar; out localNameLength: Integer); begin FLocalNameStr:= FAttributes.getLocalName(index); localName:= PSAXChar(FLocalNameStr); localNameLength:= Length(FLocalNameStr); end; procedure TAttributesAdapter.getQName(index: Integer; out qName: PSAXChar; out qNameLength: Integer); begin FQNameStr:= FAttributes.getQName(index); qName:= PSAXChar(FQNameStr); qNameLength:= Length(FQNameStr); end; procedure TAttributesAdapter.getType(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; out attType: PSAXChar; out attTypeLength: Integer); begin FTypeStr:= FAttributes.getType(PSAXCharToSAXString(uri, uriLength), PSAXCharToSAXString(localName, localNameLength)); attType:= PSAXChar(FTypeStr); attTypeLength:= Length(FTypeStr); end; procedure TAttributesAdapter.getType(qName: PSAXChar; qNameLength: Integer; out attType: PSAXChar; out attTypeLength: Integer); begin FTypeStr:= FAttributes.getType(PSAXCharToSAXString(qName, qNameLength)); attType:= PSAXChar(FTypeStr); attTypeLength:= Length(FTypeStr); end; procedure TAttributesAdapter.getType(index: Integer; out attType: PSAXChar; out attTypeLength: Integer); begin FTypeStr:= FAttributes.getType(index); attType:= PSAXChar(FTypeStr); attTypeLength:= Length(FTypeStr); end; procedure TAttributesAdapter.getURI(index: Integer; out uri: PSAXChar; out uriLength: Integer); begin FUriStr:= FAttributes.getUri(index); uri:= PSAXChar(FUriStr); uriLength:= Length(FUriStr); end; procedure TAttributesAdapter.getValue(qName: PSAXChar; qNameLength: Integer; out value: PSAXChar; out valueLength: Integer); begin FValueStr:= FAttributes.getValue(PSAXCharToSAXString(qName, qNameLength)); value:= PSAXChar(FValueStr); valueLength:= Length(FValueStr); end; procedure TAttributesAdapter.getValue(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; out value: PSAXChar; out valueLength: Integer); begin FValueStr:= FAttributes.getValue(PSAXCharToSAXString(uri, uriLength), PSAXCharToSAXString(localName, localNameLength)); value:= PSAXChar(FValueStr); valueLength:= Length(FValueStr); end; procedure TAttributesAdapter.getValue(index: Integer; out value: PSAXChar; out valueLength: Integer); begin FValueStr:= FAttributes.getValue(index); value:= PSAXChar(FValueStr); valueLength:= Length(FValueStr); end; procedure TAttributesAdapter.init(const attributes: IAttributes); begin FAttributes:= attributes; FUriStr := ''; FLocalNameStr := ''; FQNameStr := ''; FTypeStr := ''; FValueStr := ''; end; { TAttributes2Adapter } function TAttributes2Adapter.getInterface: IBufferedAttributes; begin Result:= IBufferedAttributes2(Self); end; function TAttributes2Adapter.isDeclared(index : Integer) : Boolean; begin Result:= IAttributes2(FAttributes).isDeclared(index); end; function TAttributes2Adapter.isDeclared(qName : PSAXChar; qNameLength : Integer) : Boolean; begin Result:= IAttributes2(FAttributes).isDeclared( PSAXCharToSAXString(qName, qNameLength)); end; function TAttributes2Adapter.isDeclared(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer) : Boolean; begin Result:= IAttributes2(FAttributes).isDeclared( PSAXCharToSAXString(uri, uriLength), PSAXCharToSAXString(localName, localNameLength)); end; function TAttributes2Adapter.isSpecified(index: Integer): Boolean; begin Result:= IAttributes2(FAttributes).isSpecified(index); end; function TAttributes2Adapter.isSpecified(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer): Boolean; begin Result:= IAttributes2(FAttributes).isSpecified( PSAXCharToSAXString(uri, uriLength), PSAXCharToSAXString(localName, localNameLength)); end; function TAttributes2Adapter.isSpecified(qName: PSAXChar; qNameLength: Integer): Boolean; begin Result:= IAttributes2(FAttributes).isSpecified( PSAXCharToSAXString(qName, qNameLength)); end; { TContentHandlerAdapter } procedure TContentHandlerAdapter.characters(ch: PSAXChar; chLength: Integer); begin IContentHandler(Adapted).characters(PSAXCharToSAXString(ch, chLength)); end; constructor TContentHandlerAdapter.create( const contentHandler: IContentHandler; useAttributes2: Boolean); begin inherited Create(contentHandler); if UseAttributes2 then FAttributes:= TBufferedAttributes2Adapter.create() else FAttributes:= TBufferedAttributesAdapter.create(); FAttributes._AddRef; end; destructor TContentHandlerAdapter.destroy; begin FAttributes._Release; inherited; end; procedure TContentHandlerAdapter.endDocument; begin IContentHandler(Adapted).endDocument(); end; procedure TContentHandlerAdapter.endElement(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; qName: PSAXChar; qNameLength: Integer); begin IContentHandler(Adapted).endElement(PSAXCharToSAXString(uri, uriLength), PSAXCharToSAXString(localName, localNameLength), PSAXCharToSAXString(qName, qNameLength)); end; procedure TContentHandlerAdapter.endPrefixMapping(prefix: PSAXChar; prefixLength: Integer); begin IContentHandler(Adapted).endPrefixMapping(PSAXCharToSAXString(prefix, prefixLength)); end; function TContentHandlerAdapter.getUseAttributes2: Boolean; begin Result := FAttributes is TBufferedAttributes2Adapter; end; procedure TContentHandlerAdapter.ignorableWhitespace(ch: PSAXChar; chLength: Integer); begin IContentHandler(Adapted).ignorableWhitespace(PSAXCharToSAXString(ch, chLength)); end; procedure TContentHandlerAdapter.processingInstruction(target: PSAXChar; targetLength: Integer; data: PSAXChar; dataLength: Integer); begin IContentHandler(Adapted).processingInstruction( PSAXCharToSAXString(target, targetLength), PSAXCharToSAXString(data, dataLength)); end; procedure TContentHandlerAdapter.setDocumentLocator( const locator: ILocator); begin IContentHandler(Adapted).setDocumentLocator(locator); end; procedure TContentHandlerAdapter.setUseAttributes2(Value: Boolean); begin if Value and (FAttributes is TBufferedAttributesAdapter) then begin FAttributes._Release; FAttributes := TBufferedAttributes2Adapter.Create; FAttributes._AddRef; end else if not Value and (FAttributes is TBufferedAttributes2Adapter) then begin FAttributes._Release; FAttributes := TBufferedAttributesAdapter.Create; FAttributes._AddRef; end; end; procedure TContentHandlerAdapter.skippedEntity(name: PSAXChar; nameLength: Integer); begin IContentHandler(Adapted).skippedEntity(PSAXCharToSAXString(name, nameLength)); end; procedure TContentHandlerAdapter.startDocument; begin IContentHandler(Adapted).startDocument(); end; procedure TContentHandlerAdapter.startElement(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; qName: PSAXChar; qNameLength: Integer; const atts: IBufferedAttributes); begin if (atts <> nil) then begin FAttributes.init(atts); IContentHandler(Adapted).startElement(PSAXCharToSAXString(uri, uriLength), PSAXCharToSAXString(localName, localNameLength), PSAXCharToSAXString(qName, qNameLength), FAttributes.getInterface()); end else begin IContentHandler(Adapted).startElement(PSAXCharToSAXString(uri, uriLength), PSAXCharToSAXString(localName, localNameLength), PSAXCharToSAXString(qName, qNameLength), nil); end; end; procedure TContentHandlerAdapter.startPrefixMapping(prefix: PSAXChar; prefixLength: Integer; uri: PSAXChar; uriLength: Integer); begin IContentHandler(Adapted).startPrefixMapping(PSAXCharToSAXString(prefix, prefixLength), PSAXCharToSAXString(uri, uriLength)); end; { TDTDHandlerAdapter } constructor TDTDHandlerAdapter.create(const dtdHandler: IDTDHandler); begin inherited create(dtdHandler); end; procedure TDTDHandlerAdapter.notationDecl(name: PSAXChar; nameLength: Integer; publicId: PSAXChar; publicIdLength: Integer; systemId: PSAXChar; systemIdLength: Integer); begin IDTDHandler(Adapted).notationDecl( PSAXCharToSAXString(name, nameLength), PSAXCharToSAXString(publicId, publicIdLength), PSAXCharToSAXString(systemId, systemIdLength)); end; procedure TDTDHandlerAdapter.unparsedEntityDecl(name: PSAXChar; nameLength: Integer; publicId: PSAXChar; publicIdLength: Integer; systemId: PSAXChar; systemIdLength: Integer; notationName: PSAXChar; notationNameLength: Integer); begin IDTDHandler(Adapted).unparsedEntityDecl( PSAXCharToSAXString(name, nameLength), PSAXCharToSAXString(publicId, publicIdLength), PSAXCharToSAXString(systemId, systemIdLength), PSAXCharToSAXString(notationName, notationNameLength)); end; { TDeclHandlerAdapter } procedure TDeclHandlerAdapter.attributeDecl(eName: PSAXChar; eNameLength: Integer; aName: PSAXChar; aNameLength: Integer; attrType: PSAXChar; attrTypeLength: Integer; mode: PSAXChar; modeLength: Integer; value: PSAXChar; valueLength: Integer); begin IDeclHandler(Adapted).attributeDecl( PSAXCharToSAXString(eName, eNameLength), PSAXCharToSAXString(aName, aNameLength), PSAXCharToSAXString(attrType, attrTypeLength), PSAXCharToSAXString(mode, modeLength), PSAXCharToSAXString(value, valueLength)); end; constructor TDeclHandlerAdapter.create(const declHandler: IDeclHandler); begin inherited create(declHandler); end; procedure TDeclHandlerAdapter.elementDecl(name: PSAXChar; nameLength: Integer; model: PSAXChar; modelLength: Integer); begin IDeclHandler(Adapted).elementDecl( PSAXCharToSAXString(name, nameLength), PSAXCharToSAXString(model, modelLength)); end; procedure TDeclHandlerAdapter.externalEntityDecl(name: PSAXChar; nameLength: Integer; publicId: PSAXChar; publicIdLength: Integer; systemId: PSAXChar; systemIdLength: Integer); begin IDeclHandler(Adapted).externalEntityDecl( PSAXCharToSAXString(name, nameLength), PSAXCharToSAXString(publicId, publicIdLength), PSAXCharToSAXString(systemId, systemIdLength)); end; procedure TDeclHandlerAdapter.internalEntityDecl(name: PSAXChar; nameLength: Integer; value: PSAXChar; valueLength: Integer); begin IDeclHandler(Adapted).internalEntityDecl( PSAXCharToSAXString(name, nameLength), PSAXCharToSAXString(value, valueLength)); end; { TLexicalHandlerAdapter } procedure TLexicalHandlerAdapter.comment(ch: PSAXChar; chLength: Integer); begin ILexicalHandler(Adapted).comment(PSAXCharToSAXString(ch, chLength)); end; constructor TLexicalHandlerAdapter.create( const lexicalHandler: ILexicalHandler); begin inherited Create(lexicalHandler); end; procedure TLexicalHandlerAdapter.endCDATA; begin ILexicalHandler(Adapted).endCDATA(); end; procedure TLexicalHandlerAdapter.endDTD; begin ILexicalHandler(Adapted).endDTD(); end; procedure TLexicalHandlerAdapter.endEntity(name: PSAXChar; nameLength: Integer); begin ILexicalHandler(Adapted).endEntity(PSAXCharToSAXString(name, nameLength)); end; procedure TLexicalHandlerAdapter.startCDATA; begin ILexicalHandler(Adapted).startCDATA(); end; procedure TLexicalHandlerAdapter.startDTD(name: PSAXChar; nameLength: Integer; publicId: PSAXChar; publicIdLength: Integer; systemId: PSAXChar; systemIdLength: Integer); begin ILexicalHandler(Adapted).startDTD( PSAXCharToSAXString(name, nameLength), PSAXCharToSAXString(publicId, publicIdLength), PSAXCharToSAXString(systemId, systemIdLength)); end; procedure TLexicalHandlerAdapter.startEntity(name: PSAXChar; nameLength: Integer); begin ILexicalHandler(Adapted).startEntity(PSAXCharToSAXString(name, nameLength)); end; { TBufferedContentHandlerAdapter } procedure TBufferedContentHandlerAdapter.characters(const ch: SAXString); begin IBufferedContentHandler(Adapted).characters(PSAXChar(ch), Length(ch)); end; constructor TBufferedContentHandlerAdapter.create( const contentHandler: IBufferedContentHandler; useAttributes2: Boolean); begin inherited Create(contentHandler); if useAttributes2 then FAttributes:= TAttributes2Adapter.Create() else FAttributes:= TAttributesAdapter.Create(); FAttributes._AddRef; end; destructor TBufferedContentHandlerAdapter.destroy; begin FAttributes._Release; inherited; end; procedure TBufferedContentHandlerAdapter.endDocument; begin IBufferedContentHandler(Adapted).endDocument(); end; procedure TBufferedContentHandlerAdapter.endElement(const uri, localName, qName: SAXString); begin IBufferedContentHandler(Adapted).endElement(PSAXChar(uri), Length(uri), PSAXChar(localName), Length(localName), PSAXCHar(qName), Length(qName)); end; procedure TBufferedContentHandlerAdapter.endPrefixMapping( const prefix: SAXString); begin IBufferedContentHandler(Adapted).endPrefixMapping( PSAXChar(prefix), Length(prefix)); end; function TBufferedContentHandlerAdapter.getUseAttributes2: Boolean; begin Result := FAttributes is TAttributes2Adapter; end; procedure TBufferedContentHandlerAdapter.ignorableWhitespace( const ch: SAXString); begin IBufferedContentHandler(Adapted).ignorableWhitespace( PSAXChar(ch), Length(ch)); end; procedure TBufferedContentHandlerAdapter.processingInstruction( const target, data: SAXString); begin IBufferedContentHandler(Adapted).processingInstruction(PSAXChar(target), Length(target), PSAXChar(data), Length(data)); end; procedure TBufferedContentHandlerAdapter.setDocumentLocator( const locator: ILocator); begin IBufferedContentHandler(Adapted).setDocumentLocator(locator); end; procedure TBufferedContentHandlerAdapter.setUseAttributes2(Value: Boolean); begin if Value and (FAttributes is TAttributesAdapter) then begin FAttributes._Release; FAttributes := TAttributes2Adapter.Create; FAttributes._AddRef; end else if not Value and (FAttributes is TAttributes2Adapter) then begin FAttributes._Release; FAttributes := TAttributesAdapter.Create; FAttributes._AddRef; end; end; procedure TBufferedContentHandlerAdapter.skippedEntity( const name: SAXString); begin IBufferedContentHandler(Adapted).skippedEntity(PSAXChar(name), Length(name)); end; procedure TBufferedContentHandlerAdapter.startDocument; begin IBufferedContentHandler(Adapted).startDocument(); end; procedure TBufferedContentHandlerAdapter.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); begin if (atts <> nil) then begin FAttributes.init(atts); IBufferedContentHandler(Adapted).startElement(PSAXChar(uri), Length(uri), PSAXChar(localName), Length(localName), PSAXChar(qName), Length(qName), FAttributes.getInterface()); end else begin IBufferedContentHandler(Adapted).startElement(PSAXChar(uri), Length(uri), PSAXChar(localName), Length(localName), PSAXChar(qName), Length(qName), nil); end; end; procedure TBufferedContentHandlerAdapter.startPrefixMapping(const prefix, uri: SAXString); begin IBufferedContentHandler(Adapted).startPrefixMapping(PSAXChar(prefix), Length(prefix), PSAXChar(uri), Length(uri)); end; { TBufferedDTDHandlerAdapter } constructor TBufferedDTDHandlerAdapter.create( const dtdHandler: IBufferedDTDHandler); begin inherited create(dtdHandler); end; procedure TBufferedDTDHandlerAdapter.notationDecl(const name, publicId, systemId: SAXString); begin IBufferedDTDHandler(Adapted).notationDecl( PSAXChar(name), Length(name), PSAXChar(publicId), Length(publicId), PSAXChar(systemId), Length(systemId)); end; procedure TBufferedDTDHandlerAdapter.unparsedEntityDecl(const name, publicId, systemId, notationName: SAXString); begin IBufferedDTDHandler(Adapted).unparsedEntityDecl( PSAXChar(name), Length(name), PSAXChar(publicId), Length(publicId), PSAXChar(systemId), Length(systemId), PSAXChar(notationName), Length(notationName)); end; { TBufferedDeclHandlerAdapter } procedure TBufferedDeclHandlerAdapter.attributeDecl(const eName, aName, attrType, mode, value: SAXString); begin IBufferedDeclHandler(Adapted).attributeDecl(PSAXChar(eName), Length(eName), PSAXChar(aName), Length(aName), PSAXChar(attrType), Length(attrType), PSAXChar(mode), Length(mode), PSAXChar(value), Length(value)); end; constructor TBufferedDeclHandlerAdapter.create( const declHandler: IBufferedDeclHandler); begin inherited Create(declHandler); end; procedure TBufferedDeclHandlerAdapter.elementDecl(const name, model: SAXString); begin IBufferedDeclHandler(Adapted).ElementDecl( PSAXChar(name), Length(name), PSAXChar(model), Length(model)); end; procedure TBufferedDeclHandlerAdapter.externalEntityDecl(const name, publicId, systemId: SAXString); begin IBufferedDeclHandler(Adapted).externalEntityDecl( PSAXChar(name), Length(name), PSAXChar(publicId), Length(publicId), PSAXChar(systemId), Length(systemId)); end; procedure TBufferedDeclHandlerAdapter.internalEntityDecl(const name, value: SAXString); begin IBufferedDeclHandler(Adapted).internalEntityDecl( PSAXChar(name), Length(name), PSAXChar(value), Length(value)); end; { TBufferedLexicalHandlerAdapter } procedure TBufferedLexicalHandlerAdapter.comment(const ch: SAXString); begin IBufferedLexicalHandler(Adapted).comment(PSAXChar(ch), Length(ch)); end; constructor TBufferedLexicalHandlerAdapter.create( const lexicalHandler: IBufferedLexicalHandler); begin inherited Create(lexicalHandler); end; procedure TBufferedLexicalHandlerAdapter.endCDATA; begin IBufferedLexicalHandler(Adapted).endCDATA(); end; procedure TBufferedLexicalHandlerAdapter.endDTD; begin IBufferedLexicalHandler(Adapted).endDTD(); end; procedure TBufferedLexicalHandlerAdapter.endEntity(const name: SAXString); begin IBufferedLexicalHandler(Adapted).endEntity(PSAXChar(name), Length(name)); end; procedure TBufferedLexicalHandlerAdapter.startCDATA; begin IBufferedLexicalHandler(Adapted).startCDATA(); end; procedure TBufferedLexicalHandlerAdapter.startDTD(const name, publicId, systemId: SAXString); begin IBufferedLexicalHandler(Adapted).startDTD(PSAXChar(name), Length(name), PSAXChar(publicId), Length(publicId), PSAXChar(systemId), Length(systemId)); end; procedure TBufferedLexicalHandlerAdapter.startEntity(const name: SAXString); begin IBufferedLexicalHandler(Adapted).startEntity(PSAXChar(name), Length(name)); end; { TBufferedAttributesAdapter } function TBufferedAttributesAdapter.getIndex(const uri, localName: SAXString): Integer; begin Result:= FAttributes.getIndex(PSAXChar(uri), Length(uri), PSAXChar(localName), Length(localName)); end; function TBufferedAttributesAdapter.getIndex( const qName: SAXString): Integer; begin Result:= FAttributes.getIndex(PSAXChar(qName), Length(qName)); end; function TBufferedAttributesAdapter.getInterface: IAttributes; begin Result:= Self; end; function TBufferedAttributesAdapter.getLength: Integer; begin Result:= FAttributes.getLength(); end; function TBufferedAttributesAdapter.getLocalName( index: Integer): SAXString; var locName: PSAXChar; locLen: Integer; begin FAttributes.getLocalName(index, locName, locLen); Result:= PSAXCharToSAXString(locName, locLen); end; function TBufferedAttributesAdapter.getQName(index: Integer): SAXString; var QName: PSAXChar; QLen: Integer; begin FAttributes.getQName(index, QName, QLen); Result:= PSAXCharToSAXString(QName, QLen); end; function TBufferedAttributesAdapter.getType(const uri, localName: SAXString): SAXString; var typeName: PSAXChar; typeLen: Integer; begin FAttributes.getType(PSAXChar(uri), Length(uri), PSAXChar(localName), Length(localName), typeName, typeLen); Result:= PSAXCharToSAXString(typeName, typeLen); end; function TBufferedAttributesAdapter.getType( const qName: SAXString): SAXString; var typeName: PSAXChar; typeLen: Integer; begin FAttributes.getType(PSAXChar(qName), Length(qName), typeName, typeLen); Result:= PSAXCharToSAXString(typeName, typeLen); end; function TBufferedAttributesAdapter.getType(index: Integer): SAXString; var typeName: PSAXChar; typeLen: Integer; begin FAttributes.getType(index, typeName, typeLen); Result:= PSAXCharToSAXString(typeName, typeLen); end; function TBufferedAttributesAdapter.getURI(index: Integer): SAXString; var uri: PSAXChar; uriLen: Integer; begin FAttributes.getURI(index, uri, uriLen); Result:= PSAXCharToSAXString(uri, uriLen); end; function TBufferedAttributesAdapter.getValue( const qName: SAXString): SAXString; var value: PSAXChar; valueLen: Integer; begin FAttributes.getValue(PSAXChar(qName), Length(qName), value, valueLen); Result:= PSAXCharToSAXString(value, valueLen); end; function TBufferedAttributesAdapter.getValue(const uri, localName: SAXString): SAXString; var value: PSAXChar; valueLen: Integer; begin FAttributes.getValue(PSAXChar(uri), Length(uri), PSAXChar(localName), Length(localName), value, valueLen); Result:= PSAXCharToSAXString(value, valueLen); end; function TBufferedAttributesAdapter.getValue(index: Integer): SAXString; var value: PSAXChar; valueLen: Integer; begin FAttributes.getValue(index, value, valueLen); Result:= PSAXCharToSAXString(value, valueLen); end; procedure TBufferedAttributesAdapter.init( const bufferedAttributes: IBufferedAttributes); begin FAttributes:= bufferedAttributes; end; { TBufferedAttributes2Adapter } function TBufferedAttributes2Adapter.getInterface: IAttributes; begin Result:= IAttributes2(Self); end; function TBufferedAttributes2Adapter.isDeclared(index: Integer): Boolean; begin Result:= IBufferedAttributes2(FAttributes).IsDeclared(index); end; function TBufferedAttributes2Adapter.isDeclared(const uri, localName: SAXString): Boolean; begin Result:= IBufferedAttributes2(FAttributes).IsDeclared(PSAXChar(uri), Length(uri), PSAXChar(localName), Length(localName)); end; function TBufferedAttributes2Adapter.isDeclared( const qName: SAXString): Boolean; begin Result:= IBufferedAttributes2(FAttributes).IsDeclared( PSAXChar(qName), Length(qName)); end; function TBufferedAttributes2Adapter.isSpecified(index: Integer): Boolean; begin Result:= IBufferedAttributes2(FAttributes).IsSpecified(index); end; function TBufferedAttributes2Adapter.isSpecified(const uri, localName: SAXString): Boolean; begin Result:= IBufferedAttributes2(FAttributes).IsSpecified(PSAXChar(uri), Length(uri), PSAXChar(localName), Length(localName)); end; function TBufferedAttributes2Adapter.isSpecified( const qName: SAXString): Boolean; begin Result:= IBufferedAttributes2(FAttributes).IsSpecified( PSAXChar(qName), Length(qName)); end; end.
unit LUX.GPU.Vulkan.Layere; interface //#################################################################### ■ uses vulkan_core, LUX.Data.List; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TVkLayeres<TVulkan_:class> = class; TVkLayere<TVulkan_:class> = class; TVkExtenss = TArray<VkExtensionProperties>; TVkDevLays<TVkDevice_:class> = class; TVkDevLay<TVkDevice_:class> = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkLayere TVkLayere<TVulkan_:class> = class( TListChildr<TVulkan_,TVkLayeres<TVulkan_>> ) private type TVkLayeres_ = TVkLayeres<TVulkan_>; protected _Inform :VkLayerProperties; _ExtenssN :Integer; _Extenss :TVkExtenss; ///// メソッド function FindExtenss :VkResult; public constructor Create( const Layeres_:TVkLayeres_; const Inform_:VkLayerProperties ); overload; virtual; destructor Destroy; override; ///// プロパティ property Vulkan :TVulkan_ read GetOwnere ; property Layeres :TVkLayeres_ read GetParent ; property Inform :VkLayerProperties read _Inform ; property ExtenssN :Integer read _ExtenssN; property Extenss :TVkExtenss read _Extenss ; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkLayeres TVkLayeres<TVulkan_:class> = class( TListParent<TVulkan_,TVkLayere<TVulkan_>> ) private type TVkLayere_ = TVkLayere<TVulkan_>; protected ///// メソッド function FindLayeres :VkResult; public constructor Create( const Vulkan_:TVulkan_ ); override; destructor Destroy; override; ///// プロパティ property Vulkan :TVulkan_ read GetOwnere; ///// メソッド function Add( const Inform_:VkLayerProperties ) :TVkLayere_; overload; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDevLay TVkDevLay<TVkDevice_:class> = class( TListChildr<TVkDevice_,TVkDevLays<TVkDevice_>> ) private type TVkDevLays_ = TVkDevLays<TVkDevice_>; protected _LayereI :Integer; _ExtenssN :Integer; _Extenss :TVkExtenss; ///// メソッド function FindExtenss :VkResult; public constructor Create( const DevLays_:TVkDevLays_; const LayereI_:Integer ); overload; virtual; destructor Destroy; override; ///// プロパティ property Device :TVkDevice_ read GetOwnere ; property DevLays :TVkDevLays_ read GetParent ; property ExtenssN :Integer read _ExtenssN; property Extenss :TVkExtenss read _Extenss ; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDevLays TVkDevLays<TVkDevice_:class> = class( TListParent<TVkDevice_,TVkDevLay<TVkDevice_>> ) private type TVkDevLay_ = TVkDevLay<TVkDevice_>; protected ///// メソッド procedure FindDevLays; public ///// プロパティ property Device :TVkDevice_ read GetOwnere; ///// メソッド function Add( const LayereI_:Integer ) :TVkDevLay_; overload; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses LUX.GPU.Vulkan; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkLayere //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド function TVkLayere<TVulkan_>.FindExtenss :VkResult; begin repeat Result := vkEnumerateInstanceExtensionProperties( _Inform.layerName, @_ExtenssN, nil ); if Result <> VK_SUCCESS then Exit; if _ExtenssN = 0 then Exit( VK_SUCCESS ); SetLength( _Extenss, _ExtenssN ); Result := vkEnumerateInstanceExtensionProperties( _Inform.layerName, @_ExtenssN, @_Extenss[0] ); until Result <> VK_INCOMPLETE; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkLayere<TVulkan_>.Create( const Layeres_:TVkLayeres_; const Inform_:VkLayerProperties ); begin inherited Create( Layeres_ ); _Inform := Inform_ ; FindExtenss; end; destructor TVkLayere<TVulkan_>.Destroy; begin inherited; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkLayeres //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド function TVkLayeres<TVulkan_>.FindLayeres :VkResult; var LsN, I :UInt32; Ls :TArray<VkLayerProperties>; begin (* * It's possible, though very rare, that the number of * instance layers could change. For example, installing something * could include new layers that the loader would pick up * between the initial query for the count and the * request for VkLayerProperties. The loader indicates that * by returning a VK_INCOMPLETE status and will update the * the count parameter. * The count parameter will be updated with the number of * entries loaded into the data pointer - in case the number * of layers went down or is smaller than the size given. *) repeat Result := vkEnumerateInstanceLayerProperties( @LsN, nil ); if Result <> VK_SUCCESS then Exit; if LsN = 0 then Exit( VK_SUCCESS ); SetLength( Ls, LsN ); Result := vkEnumerateInstanceLayerProperties( @LsN, @Ls[0] ); until Result <> VK_INCOMPLETE; (* * Now gather the extension list for each instance layer. *) for I := 0 to LsN-1 do Add( Ls[I] ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkLayeres<TVulkan_>.Create( const Vulkan_:TVulkan_ ); begin inherited Create; FindLayeres; end; destructor TVkLayeres<TVulkan_>.Destroy; begin inherited; end; /////////////////////////////////////////////////////////////////////// メソッド function TVkLayeres<TVulkan_>.Add( const Inform_:VkLayerProperties ) :TVkLayere_; begin Result := TVkLayere_.Create( Self, Inform_ ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDevLay //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド function TVkDevLay<TVkDevice_>.FindExtenss :VkResult; var D :TVkDevice; C :PAnsiChar; begin D := TVkDevice( Device ); C := D.Instan.Vulkan.Layeres[ _LayereI ].Inform.layerName; repeat Result := vkEnumerateDeviceExtensionProperties( D.Physic, C, @_ExtenssN, nil ); if Result <> VK_SUCCESS then Exit; if _ExtenssN = 0 then Exit( VK_SUCCESS ); SetLength( _Extenss, _ExtenssN ); Result := vkEnumerateDeviceExtensionProperties( D.Physic, C, @_ExtenssN, @_Extenss[0] ); until Result <> VK_INCOMPLETE; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkDevLay<TVkDevice_>.Create( const DevLays_:TVkDevLays_; const LayereI_:Integer ); begin inherited Create( DevLays_ ); _LayereI := LayereI_; FindExtenss; end; destructor TVkDevLay<TVkDevice_>.Destroy; begin inherited; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDevLays //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TVkDevLays<TVkDevice_>.FindDevLays; var Ls :TVkLayeres; I :Integer; begin Ls := TVkDevice( Device ).Instan.Vulkan.Layeres; (* query device extensions for enabled layers *) for I := 0 to Ls.ChildrsN-1 do Add( I ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド function TVkDevLays<TVkDevice_>.Add( const LayereI_:Integer ) :TVkDevLay_; begin Result := TVkDevLay_.Create( Self, LayereI_ ); end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
unit StockData_Import_tdx; interface uses Classes, Sysutils, BaseApp, define_datasrc, define_dealitem, define_price, define_stock_quotes, StockMinuteDataAccess; function ImportStockData_Minute_TDX_FromFile(AMinuteDataAccess: TStockMinuteDataAccess; AFileUrl: string): integer; implementation uses define_data_tdx, define_datetime, UtilsDateTime; function ImportStockData_Minute_TDX_FromFile(AMinuteDataAccess: TStockMinuteDataAccess; AFileUrl: string): integer; type TColumnsIndex = array[TImportDataHeadName_tdx] of Integer; var tmpFileContent: TStringList; tmpRowDatas: TStringList; tmpIsReadHead: Boolean; tmpColumnIndex: TColumnsIndex; iCol: TImportDataHeadName_tdx; i, j: integer; tmpPos: integer; tmpRowData: string; tmpTimeStr: string; tmpDateTimeParse: TDateTimeParseRecord; tmpDateTimeParse2: TDateTimeParseRecord; tmpMinuteParseData: TRT_Quote_Minute; tmpMinuteData: PRT_Quote_Minute; tmpMinuteData2: PRT_Quote_Minute; tmpStockDateTime: TDateTimeStock; begin Result := 0; if not FileExists(AFileUrl) then exit; if nil = AMinuteDataAccess then exit; tmpFileContent := TStringList.Create; tmpRowDatas := TStringList.Create; try tmpFileContent.LoadFromFile(AFileUrl); tmpIsReadHead := false; for iCol := Low(TImportDataHeadName_tdx) to High(TImportDataHeadName_tdx) do tmpColumnIndex[iCol] := -1; for i := 0 to tmpFileContent.Count - 1 do begin tmpRowData := Trim(tmpFileContent[i]); if '' <> tmpRowData then begin // 上证指数 (999999) // '时间'#9' 开盘'#9' 最高'#9' 最低'#9' 收盘'#9' 成交量'#9'BOLL-M.BOLL '#9'BOLL-M.UB '#9'BOLL-M.LB '#9' VOL.VOLUME'#9' VOL.MAVOL1'#9' VOL.MAVOL2'#9' CYHT.高抛 '#9' CYHT.SK '#9' CYHT.SD '#9' CYHT.低吸 '#9' CYHT.强弱分界'#9' CYHT.卖出 '#9' CYHT.买进 '#9' BDZX.AK '#9' BDZX.AD1 '#9' BDZX.AJ '#9' BDZX.aa '#9' BDZX.bb '#9' BDZX.cc '#9' BDZX.买进 '#9' BDZX.卖出' tmpRowDatas.Text := StringReplace(tmpRowData, #9, #13#10, [rfReplaceAll]); if not tmpIsReadHead then begin if 3 > tmpRowDatas.Count then begin if '' = AMinuteDataAccess.StockCode then begin tmpPos := Pos('(', tmpRowData); if 0 < tmpPos then begin tmpRowData := Trim(Copy(tmpRowData, tmpPos + 1, maxint)); tmpPos := Pos(')', tmpRowData); if 0 < tmpPos then begin tmpRowData := Trim(Copy(tmpRowData, 1, tmpPos - 1)); end; if '' <> tmpRowData then begin AMinuteDataAccess.StockCode := tmpRowData; end; end; end; end else begin for iCol := Low(TImportDataHeadName_tdx) to High(TImportDataHeadName_tdx) do begin if '' <> ImportDataHeadName_tdx[iCol] then begin for j := 0 to tmpRowDatas.Count - 1 do begin if SameText(ImportDataHeadName_tdx[iCol], Trim(tmpRowDatas[j])) then begin tmpIsReadHead := True; tmpColumnIndex[iCol] := j; end; end; end; end; end; end else begin FillChar(tmpDateTimeParse, SizeOf(tmpDateTimeParse), 0); tmpTimeStr := ''; if 0 <= tmpColumnIndex[headTime] then begin tmpTimeStr := tmpRowDatas[tmpColumnIndex[headTime]]; // 2014/06/12-10:30 end; if '' <> tmpTimeStr then begin ParseDateTime(@tmpDateTimeParse, tmpTimeStr); end; if (0 < tmpDateTimeParse.Date) then begin FillChar(tmpMinuteParseData, SizeOf(tmpMinuteParseData), 0); DateTime2DateTimeStock(tmpDateTimeParse.Date + tmpDateTimeParse.Time, @tmpStockDateTime); if 0 = tmpDateTimeParse.Time then begin // 60 * 4 AMinuteDataAccess.Minute := 240; end; trySetRTPricePack(@tmpMinuteParseData.PriceRange.PriceOpen, tmpRowDatas[tmpColumnIndex[headPrice_Open]]); trySetRTPricePack(@tmpMinuteParseData.PriceRange.PriceHigh, tmpRowDatas[tmpColumnIndex[headPrice_High]]); trySetRTPricePack(@tmpMinuteParseData.PriceRange.PriceLow, tmpRowDatas[tmpColumnIndex[headPrice_Low]]); trySetRTPricePack(@tmpMinuteParseData.PriceRange.PriceClose, tmpRowDatas[tmpColumnIndex[headPrice_Close]]); tmpMinuteParseData.DealVolume := StrToIntDef(tmpRowDatas[tmpColumnIndex[headDeal_Volume]], 0); tmpMinuteData := AMinuteDataAccess.FindRecord(tmpStockDateTime); if nil = tmpMinuteData then begin tmpMinuteData := AMinuteDataAccess.NewRecord(tmpStockDateTime); Result := Result + 1; if nil <> tmpMinuteData then begin tmpMinuteData.DealDateTime := tmpStockDateTime; tmpMinuteData.PriceRange := tmpMinuteParseData.PriceRange; tmpMinuteData.DealVolume := tmpMinuteParseData.DealVolume; tmpMinuteData.DealAmount := tmpMinuteParseData.DealAmount; end; end else begin if (tmpMinuteData.PriceRange.PriceOpen.Value <> tmpMinuteParseData.PriceRange.PriceOpen.Value) or (tmpMinuteData.PriceRange.PriceHigh.Value <> tmpMinuteParseData.PriceRange.PriceHigh.Value) or (tmpMinuteData.PriceRange.PriceLow.Value <> tmpMinuteParseData.PriceRange.PriceLow.Value) or (tmpMinuteData.PriceRange.PriceClose.Value <> tmpMinuteParseData.PriceRange.PriceClose.Value) or (tmpMinuteData.DealVolume <> tmpMinuteParseData.DealVolume) or (tmpMinuteData.DealAmount <> tmpMinuteParseData.DealAmount) then begin Result := Result + 1; tmpMinuteData.PriceRange := tmpMinuteParseData.PriceRange; tmpMinuteData.DealVolume := tmpMinuteParseData.DealVolume; tmpMinuteData.DealAmount := tmpMinuteParseData.DealAmount; end; end; end; end; end; end; finally tmpRowDatas.Clear; tmpRowDatas.Free; tmpFileContent.Free; end; if 0 = AMinuteDataAccess.Minute then begin if 1 < AMinuteDataAccess.RecordCount then begin i := 0; while i + 1 < AMinuteDataAccess.RecordCount do begin if 0 <> AMinuteDataAccess.Minute then Break; tmpMinuteData := AMinuteDataAccess.RecordItem[i]; tmpMinuteData2 := AMinuteDataAccess.RecordItem[i + 1]; DecodeDate(tmpMinuteData.DealDateTime.Date.Value, tmpDateTimeParse.Year, tmpDateTimeParse.Month, tmpDateTimeParse.Day); DecodeDate(tmpMinuteData2.DealDateTime.Date.Value, tmpDateTimeParse2.Year, tmpDateTimeParse2.Month, tmpDateTimeParse2.Day); if (tmpDateTimeParse.Year = tmpDateTimeParse2.Year) and (tmpDateTimeParse.Month = tmpDateTimeParse2.Month) and (tmpDateTimeParse.Day = tmpDateTimeParse2.Day) then begin DecodeTime(TimeStock2Time(@tmpMinuteData.DealDateTime.Time), tmpDateTimeParse.Hour, tmpDateTimeParse.Minute, tmpDateTimeParse.Second, tmpDateTimeParse.MSecond); DecodeTime(TimeStock2Time(@tmpMinuteData2.DealDateTime.Time), tmpDateTimeParse2.Hour, tmpDateTimeParse2.Minute, tmpDateTimeParse2.Second, tmpDateTimeParse2.MSecond); if tmpDateTimeParse.Hour = tmpDateTimeParse2.Hour then begin if tmpDateTimeParse.Minute <> tmpDateTimeParse2.Minute then begin AMinuteDataAccess.Minute := Abs(tmpDateTimeParse2.Minute - tmpDateTimeParse.Minute); end; end else begin if 1 = Abs(tmpDateTimeParse2.Hour - tmpDateTimeParse.Hour) then begin if tmpDateTimeParse.Minute = tmpDateTimeParse2.Minute then begin AMinuteDataAccess.Minute := 60; end; end else begin end; end; end; i := i + 1; end; end; end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.3 2004.02.03 5:45:06 PM czhower Name changes Rev 1.2 1/21/2004 3:27:50 PM JPMugaas InitComponent Rev 1.1 1/3/2004 12:59:52 PM JPMugaas These should now compile with Kudzu's change in IdCoreGlobal. Rev 1.0 11/14/2002 02:19:34 PM JPMugaas } unit IdEchoUDP; interface {$i IdCompilerDefines.inc} uses IdAssignedNumbers, IdUDPBase, IdUDPClient; type TIdEchoUDP = class(TIdUDPClient) protected FEchoTime: Cardinal; procedure InitComponent; override; public {This sends Text to the peer and returns the reply from the peer} Function Echo(AText: String): String; {Time taken to send and receive data} Property EchoTime: Cardinal read FEchoTime; published property Port default IdPORT_ECHO; end; implementation uses {$IFDEF USE_VCL_POSIX} {$IFDEF DARWIN} Macapi.CoreServices, {$ENDIF} {$ENDIF} IdGlobal; { TIdIdEchoUDP } procedure TIdEchoUDP.InitComponent; begin inherited InitComponent; Port := IdPORT_ECHO; end; function TIdEchoUDP.Echo(AText: String): String; var StartTime: Cardinal; begin StartTime := Ticks; Send(AText, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); Result := ReceiveString(IdTimeoutDefault, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); {This is just in case the TickCount rolled back to zero} FEchoTime := GetTickDiff(StartTime,Ticks); end; end.
unit uImportarExportarDados; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,cCadPessoa, Dialogs, Grids, StdCtrls, Buttons, ExtCtrls,uRESTDWPoolerDB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uDWConstsData, uDWAbout, uDWResponseTranslator, Vcl.DBGrids; type TfrmImportarExportarDados = class(TForm) strngrdDados: TStringGrid; Panel1: TPanel; btnCarregar: TBitBtn; btnInserir: TBitBtn; edtLocal: TEdit; btnSelecionar: TBitBtn; dlgOpen1: TOpenDialog; mmo1: TMemo; btnCarregarJson: TBitBtn; RESTDWClientSQL1: TRESTDWClientSQL; DWResponseTranslator1: TDWResponseTranslator; DataSource1: TDataSource; dbgrd1: TDBGrid; procedure btnCarregarClick(Sender: TObject); procedure btnInserirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSelecionarClick(Sender: TObject); procedure btnCarregarJsonClick(Sender: TObject); private { Private declarations } oPessoa: TPessoa; function FormataCampo(campo: string; delimitador: char; coluna, linhaLista: integer; lista: TStringList; var temAspasInicial, achouAspasFinal: boolean): string; procedure ImportaArquivoCSV(arquivo: string; delimitador: char; numColunas: integer); procedure RemoveLinhaStringGrid(linha: integer); procedure ClearStringGrid(const Grid: TStringGrid); public { Public declarations } end; var frmImportarExportarDados: TfrmImportarExportarDados; implementation uses uDTMConexao; {$R *.dfm} procedure TfrmImportarExportarDados.RemoveLinhaStringGrid(linha: integer); var x, y: integer; begin for x:=linha to strngrdDados.RowCount - 2 do for y:=0 to strngrdDados.ColCount - 1 do strngrdDados.Cells[y,x]:=strngrdDados.Cells[y,x + 1]; strngrdDados.RowCount:=strngrdDados.RowCount - 1; end; procedure TfrmImportarExportarDados.btnCarregarClick(Sender: TObject); begin if edtLocal.Text ='' then begin MessageDlg('Nenhum arquivo selecionado.',mtWarning,[mbOK],0); btnSelecionar.SetFocus; end else begin ClearStringGrid(strngrdDados); ImportaArquivoCSV(edtLocal.Text,',',27); end; end; procedure TfrmImportarExportarDados.ClearStringGrid(const Grid: TStringGrid); var c, r: Integer; begin for c := 0 to Pred(Grid.ColCount) do for r := 0 to Pred(Grid.RowCount) do Grid.Cells[c, r] := ''; end; procedure TfrmImportarExportarDados.btnCarregarJsonClick(Sender: TObject); begin RESTDWClientSQL1.OpenJson(mmo1.lines.text); dbgrd1.DataSource:= DataSource1; end; procedure TfrmImportarExportarDados.btnInserirClick(Sender: TObject); Var I : Integer; TableName : String; begin TableName := 'Table1'; for i := 1 to strngrdDados.RowCount-1 do begin try oPessoa.cod_pessoa := 0; oPessoa.nome := strngrdDados.Cells[0,i]; oPessoa.nome_pai := strngrdDados.Cells[1,i]; oPessoa.nome_mae := strngrdDados.Cells[2,i]; oPessoa.sexo := strngrdDados.Cells[3,i]; oPessoa.dta_nascimento := StrToDateTime(strngrdDados.Cells[4,i]); oPessoa.cod_congregacao := StrToInt( strngrdDados.Cells[5,i]); oPessoa.nro_rol := StrToInt( strngrdDados.Cells[6,i]); oPessoa.nrorg := strngrdDados.Cells[7,i]; oPessoa.nacionalidade := strngrdDados.Cells[8,i]; oPessoa.naturalidade := strngrdDados.Cells[9,i]; oPessoa.dta_casamento := StrToDateTime(strngrdDados.Cells[10,i]); oPessoa.dta_conversao :=StrToDateTime(strngrdDados.Cells[11,i]); oPessoa.dta_batismo_esprito :=StrToDateTime(strngrdDados.Cells[12,i]); oPessoa.dta_batismo_aguas :=StrToDateTime(strngrdDados.Cells[13,i]); oPessoa.dta_membro :=StrToDateTime(strngrdDados.Cells[14,i]); oPessoa.cep := strngrdDados.Cells[15,i]; oPessoa.logradouro := strngrdDados.Cells[16,i]; oPessoa.bairro := strngrdDados.Cells[17,i]; oPessoa.cidade := strngrdDados.Cells[18,i]; oPessoa.fone_celular := strngrdDados.Cells[19,i]; oPessoa.membro_congregado := strngrdDados.Cells[20,i];; oPessoa.cpf := strngrdDados.Cells[21,i]; oPessoa.funcao := strngrdDados.Cells[22,i]; oPessoa.uf_nascimento := strngrdDados.Cells[23,i]; oPessoa.uf_endereco := strngrdDados.Cells[24,i]; oPessoa.congregacao := strngrdDados.Cells[25,i]; oPessoa.setor :=strngrdDados.Cells[26,i]; oPessoa.Inserir ; except on E: Exception do begin MessageDlg(E.Message,mtError,[mbOK],0); MessageBeep(MB_ICONERROR); end; end; end; end; procedure TfrmImportarExportarDados.btnSelecionarClick(Sender: TObject); begin if dlgOpen1.Execute then begin if dlgOpen1.FileName <> '' then begin edtLocal.Text := dlgOpen1.FileName; btnInserir.Enabled:=true; //nome:= dlgOpen1.FileName; end; end; end; function TfrmImportarExportarDados.FormataCampo(campo: string; delimitador: char; coluna, linhaLista: integer; lista: TStringList; var temAspasInicial, achouAspasFinal: boolean): string; var x, aux: integer; str: string; delimitadorOK, encontrou: Boolean; begin if (not achouAspasFinal) then begin encontrou:=False; for x:=1 to Length(campo) do begin if (campo[x] = '"') then begin if (campo[x + 1] = ',') then begin encontrou:=True; Break; end; end; end; if (encontrou) then begin str:=copy(campo,1,x); achouAspasFinal:=True; lista[linhaLista]:=copy(lista[linhaLista],Length(str) + 2,Length(lista[linhaLista]) - Length(str)); end else str:=campo; end else begin x:=1; aux:=0; str:=''; delimitadorOK:=False; while (x < Length(campo) + 1) and (aux < coluna) do begin if (campo[x] = '"') then delimitadorOK:=not delimitadorOK; if (campo[x] = delimitador) and (not delimitadorOK) then Inc(aux); Inc(x); end; delimitadorOK:=False; while (x < Length(campo) + 1) and ((campo[x] <> delimitador) or delimitadorOK) do begin if (campo[x] = '"') then begin temAspasInicial:=not temAspasInicial; achouAspasFinal:=not achouAspasFinal; delimitadorOK:=not delimitadorOK; end; str:=str + campo[x]; Inc(x); end; end; FormataCampo:=Trim(str); end; procedure TfrmImportarExportarDados.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(oPessoa) then FreeAndNil(oPessoa); end; procedure TfrmImportarExportarDados.FormCreate(Sender: TObject); begin oPessoa := TPessoa.Create(dtmPrincipal.ConexaoDB); end; procedure TfrmImportarExportarDados.ImportaArquivoCSV(arquivo: string; delimitador: char; numColunas: integer); var listaCSV: TStringList; x, xAux, numLinha, numLinhaAux: integer; aspasIni, aspasFim: boolean; strTemp: string; begin listaCSV:=TStringList.Create; try strngrdDados.ColCount:=numColunas; listaCSV.LoadFromFile(arquivo); numLinha:=0; while (numLinha <= listaCSV.Count - 1) do begin strngrdDados.RowCount:=numLinha + 1; x:=0; xAux:=0; numLinhaAux:=numLinha; while (x <= strngrdDados.ColCount - 1) do begin strTemp:=FormataCampo(listaCSV[numLinha],delimitador,xAux,numLinha,listaCSV,aspasIni,aspasFim); if (strngrdDados.Cells[x,numLinhaAux] <> '') then strTemp:=strngrdDados.Cells[x,numLinhaAux] + #13#10 + strTemp; if (strTemp <> '') and (strTemp[1] = '"') and (strTemp[Length(strTemp)] = '"') then strTemp:=copy(strTemp,2,Length(strTemp) - 2); strngrdDados.Cells[x,numLinhaAux]:=strTemp; if ((aspasIni) and (not aspasFim)) then begin xAux:=-1; Inc(numLinha); end else begin Inc(x); Inc(xAux); aspasIni:=False; aspasFim:=True; end; end; Inc(numLinha); end; numLinha:=0; while (numLinha <= strngrdDados.RowCount - 1) do begin if (strngrdDados.Cells[0,numLinha] = '') then RemoveLinhaStringGrid(numLinha) else Inc(numLinha); end; finally listaCSV.Free; end; end; end.
unit NodeJS.Core; interface {forward type declarations} type //JFunction= class(JObject); JFunction = procedure(data: variant); Jchild_process= class(JObject); JError= class(JObject); JDate= class(JObject); type JNodeProcess = class; JNodeBuffer = class; function Process: JNodeProcess; function Global: variant; type Jconsole = class external "console" public procedure log(data: variant); overload; procedure log(data: array of variant); overload; procedure info(data: array of variant); procedure error(data: array of variant); procedure warn(data: array of variant); procedure dir(obj: variant); procedure timeEnd(label: string); procedure trace(label: string); procedure assert(expression: variant; message: array of string); end; function Console: Jconsole; function __Filename: string; function __Dirname: string; type TsetTimeout_callback_ = procedure (); function setTimeout(callback: TsetTimeout_callback_;ms: integer): variant;external; procedure clearTimeout(timeoutId: variant);external; type TsetInterval_callback_ = procedure (); function setInterval(callback: TsetInterval_callback_;ms: integer): variant;external; procedure clearInterval(intervalId: variant);external; type Jrequire = class external "require" public function resolve(): string; property cache: variant; property extensions: variant; end; function Require(id: string): variant; external 'require'; function Require_Obj: Jrequire; type Jmodule = class external "module" public function require(id: string): variant; property exports: variant; property id: string; property filename: string; property loaded: boolean; property parent: variant; property children: array of variant; end; function Module_Obj: Jmodule; function Exports: variant; type JSlowBuffer = class external "SlowBuffer" public function &new(str: string; encoding: string): JNodeBuffer;overload; function &new(size: integer): JNodeBuffer;overload; function &new(&array: array of variant): JNodeBuffer;overload; function isBuffer(obj: variant): boolean; function byteLength(string_: string; encoding: string): integer;overload; function concat(list: array of JNodeBuffer; totalLength: integer): JNodeBuffer;overload; property prototype: JNodeBuffer; end; function SlowBuffer_Obj: JSlowBuffer; type JBuffer = class external "Buffer" public function &new(str: string; encoding: string): JNodeBuffer;overload; function &new(size: integer): JNodeBuffer;overload; function &new(&array: array of variant): JNodeBuffer;overload; function isBuffer(obj: variant): boolean; function byteLength(string_: string; encoding: string): integer;overload; function concat(list: array of JNodeBuffer; totalLength: integer): JNodeBuffer;overload; property prototype: JNodeBuffer; end; function Buffer_Obj: JBuffer; type TEventEmitter_listeners_result_object = class; type JEventEmitter = class external "Object" public procedure addListener(event: string; listener: JFunction); procedure on(event: string; listener: JFunction); procedure once(event: string; listener: JFunction); procedure removeListener(event: string; listener: JFunction); procedure removeAllListener(event: string); procedure setMaxListeners(n: integer); function listeners(event: string): array of TEventEmitter_listeners_result_object; procedure emit(event: string; arg1: variant);overload; procedure emit(event: string; arg1: variant;arg2: variant);overload; end; TEventEmitter_listeners_result_object = class property &Function: variant; end; type JWritableStream = class external(JEventEmitter) public function write(str: string; encoding: string): boolean;overload; function write(str: string; encoding: string;fd: string): boolean;overload; function write(buffer: JNodeBuffer): boolean;overload; procedure &end();overload; procedure &end(str: string; enconding: string);overload; procedure &end(buffer: JNodeBuffer);overload; procedure destroy(); procedure destroySoon(); property writable: boolean; end; type TReadableStream_pipe_options_object = class; type JReadableStream = class external(JEventEmitter) public procedure setEncoding(encoding: string); procedure pause(); procedure resume(); procedure destroy(); procedure pipe(destination: JWritableStream; options: TReadableStream_pipe_options_object);overload; property readable: boolean; end; TReadableStream_pipe_options_object = class property &end: boolean; end; type TNodeProcess_versions_object = class; TNodeProcess_config_object = class; TNodeProcess_config_object_target_defaults_object = class; TNodeProcess_config_object_variables_object = class; TNodeProcess_memoryUsage_result_object = class; type JNodeProcess = class external(JEventEmitter) public procedure abort(); procedure chdir(directory: string); procedure cwd(); procedure &exit(code: integer);overload; function getgid(): integer; procedure setgid(id: integer);overload; procedure setgid(id: string);overload; function getuid(): integer; procedure setuid(id: integer);overload; procedure setuid(id: string);overload; procedure kill(pid: integer; signal: string);overload; function memoryUsage(): TNodeProcess_memoryUsage_result_object; procedure nextTick(callback: JFunction); function umask(mask: integer): integer;overload; function uptime(): integer; function hrtime(): array of integer; property stdout: JWritableStream; property stderr: JWritableStream; property stdin: JReadableStream; property argv: array of string; property execPath: string; property env: variant; property version: string; property versions: TNodeProcess_versions_object; property config: TNodeProcess_config_object; property pid: integer; property title: string; property arch: string; property platform: string; end; TNodeProcess_versions_object = class property http_parser: string; property node: string; property v8: string; property ares: string; property uv: string; property zlib: string; property openssl: string; end; TNodeProcess_config_object = class property target_defaults: TNodeProcess_config_object_target_defaults_object; property variables: TNodeProcess_config_object_variables_object; end; TNodeProcess_config_object_target_defaults_object = class property cflags: array of variant; property default_configuration: string; property defines: array of string; property include_dirs: array of string; property libraries: array of string; end; TNodeProcess_config_object_variables_object = class property clang: integer; property host_arch: string; property node_install_npm: boolean; property node_install_waf: boolean; property node_prefix: string; property node_shared_openssl: boolean; property node_shared_v8: boolean; property node_shared_zlib: boolean; property node_use_dtrace: boolean; property node_use_etw: boolean; property node_use_openssl: boolean; property target_arch: string; property v8_no_strict_aliasing: integer; property v8_use_snapshot: boolean; property visibility: string; end; TNodeProcess_memoryUsage_result_object = class property rss: integer; property heapTotal: variant; property number_: variant; property heapUsed: integer; end; type JNodeBuffer = class external "Object" public function GetItems(index: integer): integer; external array; procedure SetItems(index: integer; value: integer); external array; property Items[index: integer]: integer read GetItems write SetItems; default; function write(string_: string; offset: integer): integer;overload; function write(string_: string; offset: integer;length_: integer): integer;overload; function write(string_: string; offset: integer;length_: integer;encoding: string): integer;overload; function toString(encoding: string): string;overload; function toString(encoding: string;start: integer): string;overload; function toString(encoding: string;start: integer;&end: integer): string;overload; procedure copy(targetBuffer: JNodeBuffer; targetStart: integer);overload; procedure copy(targetBuffer: JNodeBuffer; targetStart: integer;sourceStart: integer);overload; procedure copy(targetBuffer: JNodeBuffer; targetStart: integer;sourceStart: integer;sourceEnd: integer);overload; function slice(start: integer): JNodeBuffer;overload; function slice(start: integer;&end: integer): JNodeBuffer;overload; function readUInt8(offset: integer; noAsset: boolean): integer;overload; function readUInt16LE(offset: integer; noAssert: boolean): integer;overload; function readUInt16BE(offset: integer; noAssert: boolean): integer;overload; function readUInt32LE(offset: integer; noAssert: boolean): integer;overload; function readUInt32BE(offset: integer; noAssert: boolean): integer;overload; function readInt8(offset: integer; noAssert: boolean): integer;overload; function readInt16LE(offset: integer; noAssert: boolean): integer;overload; function readInt16BE(offset: integer; noAssert: boolean): integer;overload; function readInt32LE(offset: integer; noAssert: boolean): integer;overload; function readInt32BE(offset: integer; noAssert: boolean): integer;overload; function readFloatLE(offset: integer; noAssert: boolean): integer;overload; function readFloatBE(offset: integer; noAssert: boolean): integer;overload; function readDoubleLE(offset: integer; noAssert: boolean): integer;overload; function readDoubleBE(offset: integer; noAssert: boolean): integer;overload; procedure writeUInt8(value: integer; offset: integer; noAssert: boolean);overload; procedure writeUInt16LE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeUInt16BE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeUInt32LE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeUInt32BE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeInt8(value: integer; offset: integer; noAssert: boolean);overload; procedure writeInt16LE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeInt16BE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeInt32LE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeInt32BE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeFloatLE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeFloatBE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeDoubleLE(value: integer; offset: integer; noAssert: boolean);overload; procedure writeDoubleBE(value: integer; offset: integer; noAssert: boolean);overload; procedure fill(value: variant; offset: integer);overload; procedure fill(value: variant; offset: integer;&end: integer);overload; property length: integer; property INSPECT_MAX_BYTES: integer; end; implementation function Process: JNodeProcess; begin asm @Result = process; end; end; function Global: variant; begin asm @Result = global; end; end; function Console: Jconsole; begin asm @Result = console; end; end; function __Filename: string; begin asm @Result = __filename; end; end; function __Dirname: string; begin asm @Result = __dirname; end; end; function Require_Obj: Jrequire; begin asm @Result = require; end; end; function Module_Obj: Jmodule; begin asm @Result = module; end; end; function Exports: variant; begin asm @Result = exports; end; end; function SlowBuffer_Obj: JSlowBuffer; begin asm @Result = SlowBuffer; end; end; function Buffer_Obj: JBuffer; begin asm @Result = Buffer; end; end; end.
unit k2Strings; { Библиотека "K-2" } { Автор: Люлин А.В. © } { Модуль: k2Strings - } { Начат: 11.04.2006 20:13 } { $Id: k2Strings.pas,v 1.3 2006/04/18 07:45:23 lulin Exp $ } // $Log: k2Strings.pas,v $ // Revision 1.3 2006/04/18 07:45:23 lulin // - cleanup. // // Revision 1.2 2006/04/11 17:55:28 lulin // - оптимизируем при помощи вынесения строк (по следам того как Вован наиграл в фильтрах 20% производительности). // // Revision 1.1 2006/04/11 16:35:37 lulin // - оптимизируем при помощи вынесения строк (по следам того как Вован наиграл в фильтрах 20% производительности). // {$Include k2Define.inc } interface resourcestring k2_errInterfaceNotImplemented = 'Interface %d for %s is not implemented'; k2_errReadOnly = 'Нельзя присвоить значение ReadOnly свойству %s для %s.'; k2_errNoChildren = 'Tag %s hasn''t children (%s)'; k2_errBadChild = 'For %s child type %s incompartible with %s'; k2_errConvertError = 'Cannot convert %s to %s'; k2_errAbstractMethod = 'Abstract method ''%s'' call'; k2_errPropExists = 'Atom #%d for %s is already defined and named %s'; k2_errCannotInheriteType = 'Cannot inherite type %s from %s'; k2_errTypeAlreadyDefined = 'Type %s already defined'; k2_strNil = 'nil'; k2_errDocumentHeaderMissing = 'Поток не открыт. Возможно отсутствует заголовок документа.'; k2_errInvalidType = 'Недопустимый тип.'; k2_errBadSkipLevel = 'Лишнее закрытие режима фильтрации тегов (несбалансированные вызовы IncSkipTags/DecSkipTags)'; k2_errBadFinishCall = 'Вызовов Finish больше чем вызовов Start'; k2_errParamNotDefined = 'Param %s for %s is not defined'; k2_errBracketsNotClosed = 'Не закрыто %d скобок в %s'; implementation end.
unit ListarVendas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Vcl.StdCtrls,ACBrUtil, ACBrNFeNotasFiscais, pcnConversao, pcnConversaoNFe, ACBrNFSe, pcnNFe, pnfsConversao, System.Math, Vendas; type TFrmListarVendas = class(TForm) Label3: TLabel; cbEntradaSaida: TComboBox; Label1: TLabel; dataInicial: TDateTimePicker; Label2: TLabel; dataFinal: TDateTimePicker; grid: TDBGrid; BtnCancelar: TSpeedButton; btnComprovante: TSpeedButton; btnNota: TSpeedButton; procedure FormShow(Sender: TObject); procedure cbEntradaSaidaChange(Sender: TObject); procedure dataInicialChange(Sender: TObject); procedure dataFinalChange(Sender: TObject); procedure BtnCancelarClick(Sender: TObject); procedure gridCellClick(Column: TColumn); procedure btnComprovanteClick(Sender: TObject); procedure btnNotaClick(Sender: TObject); private { Private declarations } procedure buscarData; public { Public declarations } end; var FrmListarVendas: TFrmListarVendas; idVenda : string; quantItem: integer; id_produto: integer; estoque : integer; estoqueP : integer; implementation {$R *.dfm} uses Modulo; { TFrmListaVendas } procedure TFrmListarVendas.BtnCancelarClick(Sender: TObject); begin if MessageDlg('Deseja Cancelar a venda?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin dm.query_vendas.Close; dm.query_vendas.SQL.Clear; dm.query_vendas.SQL.Add('UPDATE vendas set status = :status where id = :id') ; dm.query_vendas.ParamByName('status').Value := 'Cancelada'; dm.query_vendas.ParamByName('id').Value := idVenda; dm.query_vendas.ExecSql; //DELETAR TAMBÉM NA TABELA DE MOVIMENTAÇÕES dm.query_mov.Close; dm.query_mov.SQL.Clear; dm.query_mov.SQL.Add('DELETE FROM movimentacoes where id_movimento = :id'); dm.query_mov.ParamByName('id').Value := idVenda; dm.query_mov.ExecSQL; //DEVOLVER OS ITENS DA VENDA AO ESTOQUE dm.query_det_vendas.Close; dm.query_det_vendas.SQL.Clear; dm.query_det_vendas.SQL.Add('SELECT * from detalhes_vendas where id_venda = :id'); dm.query_det_vendas.ParamByName('id').Value := idVenda; dm.query_det_vendas.Open; if not dm.query_det_vendas.isEmpty then begin while not dm.query_det_vendas.Eof do begin id_produto := dm.query_det_vendas['id_produto']; quantItem := dm.query_det_vendas['quantidade']; //ATUALIZAR O ESTOQUE //RECUPERAR O ESTOQUE ATUAL dm.query_produtos.Close; dm.query_produtos.SQL.Clear; dm.query_produtos.SQL.Add('select * from produtos where id = :id'); dm.query_produtos.ParamByName('id').Value := id_produto; dm.query_produtos.Open; if not dm.query_produtos.isEmpty then begin estoqueP := dm.query_produtos['estoque']; end; estoque := estoqueP + quantItem; dm.query_produtos.Close; dm.query_produtos.SQL.Clear; dm.query_produtos.SQL.Add('UPDATE produtos set estoque = :estoque where id = :id'); dm.query_produtos.ParamByName('estoque').Value := estoque; dm.query_produtos.ParamByName('id').Value := id_produto; dm.query_produtos.ExecSQL; dm.query_det_vendas.Next; end; end; MessageDlg('Deletado com Sucesso!!', mtInformation, mbOKCancel, 0); end; BtnCancelar.Enabled := false; btnNota.Enabled := false; btnComprovante.Enabled := false; buscarData; end; procedure TFrmListarVendas.btnComprovanteClick(Sender: TObject); begin dm.query_vendas.Close; dm.query_vendas.SQL.Clear; dm.query_vendas.SQL.Add('SELECT * from vendas where id = :id'); dm.query_vendas.ParamByName('id').Value := idVenda; dm.query_vendas.Open; dm.query_det_vendas.Close; dm.query_det_vendas.SQL.Clear; dm.query_det_vendas.SQL.Add('SELECT * from detalhes_vendas where id_venda = :id'); dm.query_det_vendas.ParamByName('id').Value := idVenda; dm.query_det_vendas.Open; //Chamar o Relatório dm.rel_comprovante.LoadFromFile(GetCurrentDir + '\rel\comprovante.fr3'); dm.rel_comprovante.ShowReport(); //dm.rel_comprovante.Print; btnComprovante.Enabled := false; btnNota.Enabled := false; buscarData; end; procedure TFrmListarVendas.btnNotaClick(Sender: TObject); Var NotaF: NotaFiscal; item : integer; Produto: TDetCollectionItem; InfoPgto: TpagCollectionItem; begin btnComprovante.Enabled := false; btnNota.Enabled := false; FrmVendas.nfce.NotasFiscais.Clear; NotaF := FrmVendas.nfce.NotasFiscais.Add; //DADOS DA NOTA FISCAL NotaF.NFe.Ide.natOp := 'VENDA'; NotaF.NFe.Ide.indPag := ipVista; NotaF.NFe.Ide.modelo := 65; NotaF.NFe.Ide.serie := 1; NotaF.NFe.Ide.nNF := StrToInt(idVenda); NotaF.NFe.Ide.dEmi := Date; NotaF.NFe.Ide.dSaiEnt := Date; NotaF.NFe.Ide.hSaiEnt := Now; NotaF.NFe.Ide.tpNF := tnSaida; NotaF.NFe.Ide.tpEmis := teNormal; NotaF.NFe.Ide.tpAmb := taHomologacao; //Lembre-se de trocar esta variável quando for para ambiente de produção NotaF.NFe.Ide.verProc := '1.0.0.0'; //Versão do seu sistema NotaF.NFe.Ide.cUF := 31; //CODIGO DA CIDADE NotaF.NFe.Ide.cMunFG := 0624123; //VOCE PRECISA ALTERAR DE ACORDO COM O CODIGO DE EMISSAO DE NFCE PARA SEU MUNICIPIO NotaF.NFe.Ide.finNFe := fnNormal; //DADOS DO EMITENTE NotaF.NFe.Emit.CNPJCPF := '18311776000198'; NotaF.NFe.Emit.IE := ''; NotaF.NFe.Emit.xNome := 'Q-Cursos Networks'; NotaF.NFe.Emit.xFant := 'Q-Cursos'; NotaF.NFe.Emit.EnderEmit.fone := '(31)3333-3333'; NotaF.NFe.Emit.EnderEmit.CEP := 30512660; NotaF.NFe.Emit.EnderEmit.xLgr := 'Rua A'; NotaF.NFe.Emit.EnderEmit.nro := '325'; NotaF.NFe.Emit.EnderEmit.xCpl := ''; NotaF.NFe.Emit.EnderEmit.xBairro := 'Santa Monica'; NotaF.NFe.Emit.EnderEmit.cMun := 0624123; NotaF.NFe.Emit.EnderEmit.xMun := 'Belo Horizonte'; NotaF.NFe.Emit.EnderEmit.UF := 'MG'; NotaF.NFe.Emit.enderEmit.cPais := 1058; NotaF.NFe.Emit.enderEmit.xPais := 'BRASIL'; NotaF.NFe.Emit.IEST := ''; // NotaF.NFe.Emit.IM := '2648800'; // Preencher no caso de existir serviços na nota //NotaF.NFe.Emit.CNAE := '6201500'; // Verifique na cidade do emissor da NFe se é permitido // a inclusão de serviços na NFe NotaF.NFe.Emit.CRT := crtSimplesNacional;// (1-crtSimplesNacional, 2-crtSimplesExcessoReceita, 3-crtRegimeNormal) //DADOS DO DESTINATÁRIO // NotaF.NFe.Dest.CNPJCPF := '05481336000137'; // NotaF.NFe.Dest.IE := '687138770110'; // NotaF.NFe.Dest.ISUF := ''; // NotaF.NFe.Dest.xNome := 'D.J. COM. E LOCAÇÃO DE SOFTWARES LTDA - ME'; // // NotaF.NFe.Dest.EnderDest.Fone := '1532599600'; // NotaF.NFe.Dest.EnderDest.CEP := 18270170; // NotaF.NFe.Dest.EnderDest.xLgr := 'Rua Coronel Aureliano de Camargo'; // NotaF.NFe.Dest.EnderDest.nro := '973'; // NotaF.NFe.Dest.EnderDest.xCpl := ''; // NotaF.NFe.Dest.EnderDest.xBairro := 'Centro'; // NotaF.NFe.Dest.EnderDest.cMun := 3554003; // NotaF.NFe.Dest.EnderDest.xMun := 'Tatui'; // NotaF.NFe.Dest.EnderDest.UF := 'SP'; // NotaF.NFe.Dest.EnderDest.cPais := 1058; // NotaF.NFe.Dest.EnderDest.xPais := 'BRASIL'; //ITENS DA VENDA NA NOTA //RELACIONANDO OS ITENS COM A VENDA item := 1; dm.query_det_vendas.Close; dm.query_det_vendas.SQL.Clear; dm.query_det_vendas.SQL.Add('select * from detalhes_vendas WHERE id_venda = :num order by id asc') ; dm.query_det_vendas.ParamByName('num').Value := idVenda; dm.query_det_vendas.Open; dm.query_det_vendas.First; while not dm.query_det_vendas.eof do begin Produto := NotaF.NFe.Det.New; Produto.Prod.nItem := item; // Número sequencial, para cada item deve ser incrementado Produto.Prod.cProd := '123456'; Produto.Prod.cEAN := '7896523206646'; Produto.Prod.xProd := dm.query_det_vendas.FieldByName('produto').Value; Produto.Prod.NCM := '94051010'; // Tabela NCM disponível em http://www.receita.fazenda.gov.br/Aliquotas/DownloadArqTIPI.htm Produto.Prod.EXTIPI := ''; Produto.Prod.CFOP := '5101'; Produto.Prod.uCom := 'UN'; Produto.Prod.qCom := dm.query_det_vendas.FieldByName('quantidade').Value; Produto.Prod.vUnCom := dm.query_det_vendas.FieldByName('valor').Value; Produto.Prod.vProd := dm.query_det_vendas.FieldByName('total').Value; //INFORMAÇÕES DE IMPOSTOS SOBRE OS PRODUTOS Produto.Prod.cEANTrib := '7896523206646'; Produto.Prod.uTrib := 'UN'; Produto.Prod.qTrib := 1; Produto.Prod.vUnTrib := 100; Produto.Prod.vOutro := 0; Produto.Prod.vFrete := 0; Produto.Prod.vSeg := 0; Produto.Prod.vDesc := 0; Produto.Prod.CEST := '1111111'; Produto.infAdProd := 'Informacao Adicional do Produto'; // lei da transparencia nos impostos Produto.Imposto.vTotTrib := 0; Produto.Imposto.ICMS.CST := cst00; Produto.Imposto.ICMS.orig := oeNacional; Produto.Imposto.ICMS.modBC := dbiValorOperacao; Produto.Imposto.ICMS.vBC := 100; Produto.Imposto.ICMS.pICMS := 18; Produto.Imposto.ICMS.vICMS := 18; Produto.Imposto.ICMS.modBCST := dbisMargemValorAgregado; Produto.Imposto.ICMS.pMVAST := 0; Produto.Imposto.ICMS.pRedBCST:= 0; Produto.Imposto.ICMS.vBCST := 0; Produto.Imposto.ICMS.pICMSST := 0; Produto.Imposto.ICMS.vICMSST := 0; Produto.Imposto.ICMS.pRedBC := 0; // partilha do ICMS e fundo de probreza Produto.Imposto.ICMSUFDest.vBCUFDest := 0.00; Produto.Imposto.ICMSUFDest.pFCPUFDest := 0.00; Produto.Imposto.ICMSUFDest.pICMSUFDest := 0.00; Produto.Imposto.ICMSUFDest.pICMSInter := 0.00; Produto.Imposto.ICMSUFDest.pICMSInterPart := 0.00; Produto.Imposto.ICMSUFDest.vFCPUFDest := 0.00; Produto.Imposto.ICMSUFDest.vICMSUFDest := 0.00; Produto.Imposto.ICMSUFDest.vICMSUFRemet := 0.00; item := item + 1; dm.query_det_vendas.Next; end; //totalizando NotaF.NFe.Total.ICMSTot.vBC := 100; NotaF.NFe.Total.ICMSTot.vICMS := 18; NotaF.NFe.Total.ICMSTot.vBCST := 0; NotaF.NFe.Total.ICMSTot.vST := 0; NotaF.NFe.Total.ICMSTot.vProd := totalVenda; NotaF.NFe.Total.ICMSTot.vFrete := 0; NotaF.NFe.Total.ICMSTot.vSeg := 0; //NotaF.NFe.Total.ICMSTot.vDesc := strToFloat(edtDesconto.Text); NotaF.NFe.Total.ICMSTot.vII := 0; NotaF.NFe.Total.ICMSTot.vIPI := 0; NotaF.NFe.Total.ICMSTot.vPIS := 0; NotaF.NFe.Total.ICMSTot.vCOFINS := 0; NotaF.NFe.Total.ICMSTot.vOutro := 0; NotaF.NFe.Total.ICMSTot.vNF := totalcomDesconto; // lei da transparencia de impostos NotaF.NFe.Total.ICMSTot.vTotTrib := 0; // partilha do icms e fundo de probreza NotaF.NFe.Total.ICMSTot.vFCPUFDest := 0.00; NotaF.NFe.Total.ICMSTot.vICMSUFDest := 0.00; NotaF.NFe.Total.ICMSTot.vICMSUFRemet := 0.00; NotaF.NFe.Transp.modFrete := mfSemFrete; //SEM FRETE // YA. Informações de pagamento InfoPgto := NotaF.NFe.pag.New; InfoPgto.indPag := ipVista; InfoPgto.tPag := fpDinheiro; InfoPgto.vPag := totalcomDesconto; //RECUPERAR O NUMERO DE SERIE DO CERTIFICADO FrmVendas.nfce.Configuracoes.Certificados.NumeroSerie := certificadoDig; FrmVendas.nfce.NotasFiscais.Assinar; FrmVendas.nfce.Enviar(Integer(idVenda)); ShowMessage(FrmVendas.nfce.WebServices.StatusServico.Msg); end; procedure TFrmListarVendas.buscarData; begin dm.query_vendas.Close; dm.query_vendas.SQL.Clear; dm.query_vendas.SQL.Add('select * from vendas where data >= :dataInicial and data <= :dataFinal and status = :status order by id desc'); dm.query_vendas.ParamByName('dataInicial').Value := FormatDateTime('yyyy/mm/dd', dataInicial.Date); dm.query_vendas.ParamByName('dataFinal').Value := FormatDateTime('yyyy/mm/dd', dataFinal.Date); dm.query_vendas.ParamByName('status').Value := cbEntradaSaida.Text; dm.query_vendas.Open; end; procedure TFrmListarVendas.cbEntradaSaidaChange(Sender: TObject); begin buscarData; end; procedure TFrmListarVendas.dataFinalChange(Sender: TObject); begin buscarData; end; procedure TFrmListarVendas.dataInicialChange(Sender: TObject); begin buscarData; end; procedure TFrmListarVendas.FormShow(Sender: TObject); begin cbEntradaSaida.ItemIndex := 0; dm.tb_vendas.Active := True; dataInicial.Date := Date; dataFinal.Date := Date; buscarData; end; procedure TFrmListarVendas.gridCellClick(Column: TColumn); begin BtnCancelar.Enabled := true; btnNota.Enabled := true; btnComprovante.Enabled := true; idVenda := dm.query_vendas.FieldByName('id').Value; end; end.
inherited dmOperacoesFiscais: TdmOperacoesFiscais OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWARMTCFOP' ' (CODIGO, OPERACAO, ISS_ALIQUOTA, ISS_FATOR, ISS_REDUTOR, DT_AL' + 'TERACAO, OPERADOR)' 'VALUES' ' (:CODIGO, :OPERACAO, :ISS_ALIQUOTA, :ISS_FATOR, :ISS_REDUTOR, ' + ':DT_ALTERACAO, :OPERADOR)') SQLDelete.Strings = ( 'DELETE FROM STWARMTCFOP' 'WHERE' ' CODIGO = :Old_CODIGO') SQLUpdate.Strings = ( 'UPDATE STWARMTCFOP' 'SET' ' CODIGO = :CODIGO, OPERACAO = :OPERACAO, ISS_ALIQUOTA = :ISS_AL' + 'IQUOTA, ISS_FATOR = :ISS_FATOR, ISS_REDUTOR = :ISS_REDUTOR, DT_A' + 'LTERACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR' 'WHERE' ' CODIGO = :Old_CODIGO') SQLRefresh.Strings = ( 'SELECT CODIGO, OPERACAO, ISS_ALIQUOTA, ISS_FATOR, ISS_REDUTOR, D' + 'T_ALTERACAO, OPERADOR FROM STWARMTCFOP' 'WHERE' ' CODIGO = :Old_CODIGO') SQLLock.Strings = ( 'SELECT NULL FROM STWARMTCFOP' 'WHERE' 'CODIGO = :Old_CODIGO' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT * FROM STWARMTCFOP') object qryManutencaoCODIGO: TStringField FieldName = 'CODIGO' Required = True Size = 6 end object qryManutencaoOPERACAO: TStringField FieldName = 'OPERACAO' Size = 40 end object qryManutencaoISS_ALIQUOTA: TFloatField FieldName = 'ISS_ALIQUOTA' end object qryManutencaoISS_FATOR: TFloatField FieldName = 'ISS_FATOR' end object qryManutencaoISS_REDUTOR: TFloatField FieldName = 'ISS_REDUTOR' end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end end inherited qryLocalizacao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWARMTMOV' ' (CGC, SERIE, LOTE, NOTA, PRODUTO, SEQUENCIA, DCA, DT_MOV, QTD_' + 'MOV, VLR_MOV, RUA, NUMERO, ANDAR, SR_DEVOLUCAO, APARTAMENTO, AVA' + 'RIA, NOTA_DEVOLUCAO, OBSERVACAO, DT_ALTERACAO, OPERADOR)' 'VALUES' ' (:CGC, :SERIE, :LOTE, :NOTA, :PRODUTO, :SEQUENCIA, :DCA, :DT_M' + 'OV, :QTD_MOV, :VLR_MOV, :RUA, :NUMERO, :ANDAR, :SR_DEVOLUCAO, :A' + 'PARTAMENTO, :AVARIA, :NOTA_DEVOLUCAO, :OBSERVACAO, :DT_ALTERACAO' + ', :OPERADOR)') SQLDelete.Strings = ( 'DELETE FROM STWARMTMOV' 'WHERE' ' CGC = :Old_CGC AND LOTE = :Old_LOTE AND SERIE = :Old_SERIE AND' + ' NOTA = :Old_NOTA AND PRODUTO = :Old_PRODUTO AND SEQUENCIA = :Ol' + 'd_SEQUENCIA') SQLUpdate.Strings = ( 'UPDATE STWARMTMOV' 'SET' ' CGC = :CGC, SERIE = :SERIE, LOTE = :LOTE, NOTA = :NOTA, PRODUT' + 'O = :PRODUTO, SEQUENCIA = :SEQUENCIA, DCA = :DCA, DT_MOV = :DT_M' + 'OV, QTD_MOV = :QTD_MOV, VLR_MOV = :VLR_MOV, RUA = :RUA, NUMERO =' + ' :NUMERO, ANDAR = :ANDAR, SR_DEVOLUCAO = :SR_DEVOLUCAO, APARTAME' + 'NTO = :APARTAMENTO, AVARIA = :AVARIA, NOTA_DEVOLUCAO = :NOTA_DEV' + 'OLUCAO, OBSERVACAO = :OBSERVACAO, DT_ALTERACAO = :DT_ALTERACAO, ' + 'OPERADOR = :OPERADOR' 'WHERE' ' CGC = :Old_CGC AND LOTE = :Old_LOTE AND SERIE = :Old_SERIE AND' + ' NOTA = :Old_NOTA AND PRODUTO = :Old_PRODUTO AND SEQUENCIA = :Ol' + 'd_SEQUENCIA') SQLRefresh.Strings = ( 'SELECT CGC, SERIE, LOTE, NOTA, PRODUTO, SEQUENCIA, DCA, DT_MOV, ' + 'QTD_MOV, VLR_MOV, RUA, NUMERO, ANDAR, SR_DEVOLUCAO, APARTAMENTO,' + ' AVARIA, NOTA_DEVOLUCAO, OBSERVACAO, DT_ALTERACAO, OPERADOR FROM' + ' STWARMTMOV' 'WHERE' ' CGC = :CGC AND LOTE = :LOTE AND SERIE = :SERIE AND NOTA = :NOT' + 'A AND PRODUTO = :PRODUTO AND SEQUENCIA = :SEQUENCIA') SQLLock.Strings = ( 'SELECT NULL FROM STWARMTMOV' 'WHERE' 'CGC = :Old_CGC AND LOTE = :Old_LOTE AND SERIE = :Old_SERIE AND N' + 'OTA = :Old_NOTA AND PRODUTO = :Old_PRODUTO AND SEQUENCIA = :Old_' + 'SEQUENCIA' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT * FROM STWARMTCFOP') object qryLocalizacaoCODIGO: TStringField FieldName = 'CODIGO' Required = True Size = 6 end object qryLocalizacaoOPERACAO: TStringField FieldName = 'OPERACAO' Size = 40 end object qryLocalizacaoISS_ALIQUOTA: TFloatField FieldName = 'ISS_ALIQUOTA' end object qryLocalizacaoISS_FATOR: TFloatField FieldName = 'ISS_FATOR' end object qryLocalizacaoISS_REDUTOR: TFloatField FieldName = 'ISS_REDUTOR' end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end end inherited updManutencao: TIBCUpdateSQL InsertSQL.Strings = ( 'INSERT INTO STWARMTCFOP' ' (CODIGO, OPERACAO, ISS_ALIQUOTA, ISS_FATOR, ISS_REDUTOR, DT_AL' + 'TERACAO, OPERADOR)' 'VALUES' ' (:CODIGO, :OPERACAO, :ISS_ALIQUOTA, :ISS_FATOR, :ISS_REDUTOR, ' + ':DT_ALTERACAO, :OPERADOR)') DeleteSQL.Strings = ( 'DELETE FROM STWARMTCFOP' 'WHERE' ' CODIGO = :Old_CODIGO') ModifySQL.Strings = ( 'UPDATE STWARMTCFOP' 'SET' ' CODIGO = :CODIGO, OPERACAO = :OPERACAO, ISS_ALIQUOTA = :ISS_AL' + 'IQUOTA, ISS_FATOR = :ISS_FATOR, ISS_REDUTOR = :ISS_REDUTOR, DT_A' + 'LTERACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR' 'WHERE' ' CODIGO = :Old_CODIGO') RefreshSQL.Strings = ( 'SELECT CODIGO, OPERACAO, ISS_ALIQUOTA, ISS_FATOR, ISS_REDUTOR, D' + 'T_ALTERACAO, OPERADOR FROM STWARMTCFOP' 'WHERE' ' CODIGO = :Old_CODIGO') end end
unit ActionHandler; interface uses SysUtils, Classes, Generics.Collections, GlobalData; type TActionHandlerManager = class; TActionHandlerKind = (hkRemoteProgram, hkScript, hkDefault, hkPlugin); IActionHandler = interface ['{384E1135-64C2-43CE-853F-FC2D20F9B129}'] procedure ExecuteAction(UserData: Pointer = nil); end; TAbstractActionHandler = class abstract(TinterfacedObject, IActionHandler) private FOwner: TActionHandlerManager; FParams: TDictionary<String, String>; function GetParam(Name: string): string; procedure SetParam(Name: string; Value: string); protected procedure PrepareParams(ActionName: string; ActionKind: TActionHandlerKind); virtual; public constructor Create(AOwner: TActionHandlerManager); virtual; procedure ExecuteAction(UserData: Pointer = nil); virtual; abstract; destructor Destroy; override; property Param[Name: string]: string read GetParam write SetParam; end; TActionHandlerClass = class of TAbstractActionHandler; EActionHandlerException = class(Exception); TActionHandlerManager = class strict private type THandlerInfo = class HandlerClass: TActionHandlerClass; HandlerName: string; HandlerKind: TActionHandlerKind; UserData: Pointer; end; private FHandlers: TObjectList<THandlerInfo>; function GetCount: Integer; function GetActionHandler(Index: Integer): THandlerInfo; function CheckRegister(ActionName: string): Boolean; function Registered(ActionName: string): Boolean; public constructor Create; procedure Run(Index: Integer); function IndexOf(ActionName: string): Integer; procedure RegisterActionHandler(ActionName: string; ActionKind: TActionHandlerKind; ActionHandlerClass: TActionHandlerClass; UserData: Pointer = nil); procedure UnRegisterActionHanler(ActionHandlerClass: TActionHandlerClass); property Handlers[Index: Integer]: THandlerInfo read GetActionHandler; property RegisteredCount: Integer read GetCount; destructor Destroy; override; end; const HandlersListFileName: String = 'handlers.list'; HandlersKindNames: array [TActionHandlerKind] of String = ('Внешние программы', 'Макросы', 'Встроенные утилиты', 'Плагины'); function ActionHandlerManager(): TActionHandlerManager; implementation uses IniFiles; var _handlerManager: TActionHandlerManager; { TAbstractActionHandler } function ActionHandlerManager: TActionHandlerManager; begin if _handlerManager = nil then _handlerManager := TActionHandlerManager.Create; Result := _handlerManager; end; constructor TAbstractActionHandler.Create(AOwner: TActionHandlerManager); begin inherited Create; FOwner := AOwner; FParams := TDictionary<String, String>.Create(); end; destructor TAbstractActionHandler.Destroy; begin FOwner := nil; FParams.Free; inherited; end; function TAbstractActionHandler.GetParam(Name: string): string; begin if not FParams.TryGetValue(Name, Result) then Result := EmptyStr; end; procedure TAbstractActionHandler.PrepareParams(ActionName: string; ActionKind: TActionHandlerKind); begin end; procedure TAbstractActionHandler.SetParam(Name, Value: string); begin FParams.AddOrSetValue(Name, Value); end; { TActionHandlerManager } function TActionHandlerManager.CheckRegister(ActionName: string): Boolean; var Ini: TIniFile; begin Result := False; Ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'reg.ini'); try if not Ini.ValueExists('reg', ActionName) then Ini.WriteBool('reg', ActionName, True) else Result := Ini.ReadBool('reg', ActionName, False); finally Ini.Free; end; end; constructor TActionHandlerManager.Create; begin inherited Create; Self.FHandlers := TObjectList<THandlerInfo>.Create(); end; destructor TActionHandlerManager.Destroy; var I: Integer; begin for I := 0 to FHandlers.Count - 1 do if FHandlers[I].HandlerKind = hkPlugin then begin FHandlers[I].UserData := nil; end; FHandlers.Free; inherited; end; function TActionHandlerManager.GetActionHandler(Index: Integer): THandlerInfo; begin Result := FHandlers[Index]; end; function TActionHandlerManager.GetCount: Integer; begin Result := FHandlers.Count; end; function TActionHandlerManager.IndexOf(ActionName: string): Integer; var I: Integer; begin Result := -1; for I := 0 to FHandlers.Count - 1 do if AnsiSameText(ActionName, FHandlers[I].HandlerName) then exit(I); end; procedure TActionHandlerManager.RegisterActionHandler(ActionName: string; ActionKind: TActionHandlerKind; ActionHandlerClass: TActionHandlerClass; UserData: Pointer); var Info: THandlerInfo; begin if Registered(ActionName) then Exit; if (ActionKind = hkDefault) and not CheckRegister(ActionName) then exit; Info := THandlerInfo.Create; Info.HandlerName := ActionName; Info.HandlerKind := ActionKind; Info.HandlerClass := ActionHandlerClass; Info.UserData := UserData; FHandlers.Add(Info); end; function TActionHandlerManager.Registered(ActionName: string): Boolean; var I: Integer; begin Result := False; for I := 0 to FHandlers.Count - 1 do if AnsiSameText(FHandlers[I].HandlerName, ActionName) then Exit(True); end; procedure TActionHandlerManager.Run(Index: Integer); var ActionHandler: TAbstractActionHandler; begin ActionHandler := FHandlers[Index].HandlerClass.Create(Self); try ActionHandler.PrepareParams(FHandlers[Index].HandlerName, FHandlers[Index].HandlerKind); try ActionHandler.ExecuteAction(FHandlers[Index].UserData); except on E: Exception do ShowException(E, E.StackInfo); end; finally ActionHandler.Free; end; end; procedure TActionHandlerManager.UnRegisterActionHanler(ActionHandlerClass : TActionHandlerClass); var I, Index: Integer; begin Index := -1; for I := 0 to FHandlers.Count - 1 do if FHandlers[I].HandlerClass = ActionHandlerClass then begin Index := I; Break; end; if Index >= 0 then FHandlers.Delete(Index); end; initialization _handlerManager := nil; finalization FreeAndNil(_handlerManager); end.
unit modGlobals; interface uses windows, messages; //type // TmodOBDProtocolFamily = (modOBDProtocolFamily_CAN, modOBDProtocolFamily_SAE_J1850, modOBDProtocolFamily_J1939, // modOBDProtocolFamily_Custom); // //type // TmodOBDProtocol = (modOBDProtocol_Auto, modOBDProtocol_SAE_J1850_PWM, modOBDProtocol_SAE_J1850_VPW, modOBDProtocol_ISO_9141_2, // modOBDProtocol_ISO_14230_4_KWP_SI, modOBDProtocol_ISO_14230_4_KWP_FI, modOBDProtocol_ISO_15765_4_CAN_11_500, // modOBDProtocol_ISO_15765_4_CAN_29_500, modOBDProtocol_ISO_15765_4_CAN_11_250, modOBDProtocol_ISO_15765_4_CAN_29_250, // modOBDProtocol_SAE_J1939_CAN_29_250, modOBDProtocol_USER1_CAN_11_125, modOBDProtocol_USER1_CAN_11_50); const // data constants BMW_DATA_ECU_MAGIC = 6000014350977617741; BMW_DATA_ECU_FILE_VERSION = 1; // max com ports searched [1..n] MOD_COM_MAX = 16; MOD_COM_MAX_BYTES = 4096; MOD_COM_IO_TIMEOUT = 3000; MOD_COM_IO_MAX_REPEAT = 1; MOD_COM_IO_MAX_WAIT_TIME = 400; //in ms MOD_COM_IO_MAX_WAIT_TIME_SEND = 500; //in ms MOD_COM_IO_FLOOD_DANGER_THRESHOLD = 15; MOD_COM_ELM_HEARTBEAT_INTERVALL = 20; // seconds BMW_TASK_MAX_CYLCE_COUNT = 250; //MOD_ELM_MAX_PAYLOAD_LENGTH = 4095; // messaging system MOD_MSG_BASE = WM_APP + 1024; // messages to mainform // raw COM connection MOD_MSG_COM_SEARCH_START = MOD_MSG_BASE + 1; MOD_MSG_COM_SEARCH_STOP = MOD_MSG_BASE + 2; MOD_MSG_COM_SEARCH_FOUND = MOD_MSG_BASE + 3; // COM port connection messages MOD_MSG_COM_DISCONNECTED = MOD_MSG_BASE + 4; MOD_MSG_COM_CONNECTION_REFUSED = MOD_MSG_BASE + 5; MOD_MSG_COM_CONNECTION_OK = MOD_MSG_BASE + 6; // recieved message MOD_MSG_COM_MSG = MOD_MSG_BASE + 7; MOD_MSG_COM_MSG_SENT = MOD_MSG_BASE + 8; // too many packets are in queue, slow down! // wparam contains current amount of packets in out queue MOD_MSG_COM_MSG_FLOOD_DANGER = MOD_MSG_BASE + 9; // We are on normal packet levels again, you can kick it up a notch MOD_MSG_COM_MSG_FLOOD_DRIED = MOD_MSG_BASE + 10; // there was an error sending a packet! MOD_MSG_COM_MSG_SEND_ERROR = MOD_MSG_BASE + 11; // there was an error reading a packet. // wparam contains index of error entry in ELMInterface MOD_MSG_COM_MSG_RECV_ERROR = MOD_MSG_BASE + 12; MOD_OBD_MAX_PAYLOAD_LENGTH = 256; // // elm interpreter // // // found an ELM chip // MOD_MSG_COM_ELM_FOUND = MOD_MSG_BASE + 100; // // // recieved ELM version // MOD_MSG_COM_ELM_CORRECT_VERSION = MOD_MSG_BASE + 101; // // // ELM ready for car interaction // MOD_MSG_COM_ELM_READY = MOD_MSG_BASE + 102; // // // There was a fatal parsing error in one message. Tread with caution! // MOD_MSG_COM_ELM_PARSING_ERROR = MOD_MSG_BASE + 103; // // // ELM successfully found protocol version! // // contains protocol ID in wparam. // MOD_MSG_COM_ELM_FOUND_PROTOCOL = MOD_MSG_BASE + 104; // // // ELM cannot connect to CAN bus. Car is probably not in ignition. // MOD_MSG_COM_ELM_CANNOT_CONNECT_TO_CANBUS = MOD_MSG_BASE + 105; // // // ELM said there was a CAN error. Message is pretty much same as MOD_MSG_COM_ELM_CANNOT_CONNECT_TO_CANBUS, // // but for debugging I have chosen to seperate them. // MOD_MSG_COM_ELM_CAN_ERROR = MOD_MSG_BASE + 106; // // // ELM failed to find protocol version! // // this is fatal. // MOD_MSG_COM_ELM_FOUND_PROTOCOL_FAILED = MOD_MSG_BASE + 107; // // // You forgot to handle a message type (TmodELMMessageType), you dork. // MOD_MSG_COM_ELM_UNKNOWN_MESSAGE_TYPE = MOD_MSG_BASE + 108; // // // ELM interface message source isn't set! FATAL error. // MOD_MSG_COM_ELM_INTERFACE_NO_MESSAGE_SRC = MOD_MSG_BASE + 109; // // // ELM interface message dest isn't set! FATAL error. // MOD_MSG_COM_ELM_INTERFACE_NO_MESSAGE_DEST = MOD_MSG_BASE + 110; // // // this acts as a heartbeat message! // // recieved voltage from ELM // MOD_MSG_COM_ELM_VOLTAGE = MOD_MSG_BASE + 199; // obd related messages // ELM recieved a raw OBD message! MOD_MSG_OBD_RECIEVED = MOD_MSG_BASE + 200; // The message was parsed successfully by Car interface! MOD_MSG_OBD_PARSED = MOD_MSG_BASE + 201; // The message was NOT parsed by Car interface! MOD_MSG_OBD_PARSE_ERROR = MOD_MSG_BASE + 202; // task related messages // task started MOD_MSG_TASK_STARTED = MOD_MSG_BASE + 500; // task finished MOD_MSG_TASK_FINISHED = MOD_MSG_BASE + 501; // task error MOD_MSG_TASK_ERROR = MOD_MSG_BASE + 502; // all tasks processed MOD_MSG_TASK_ALL_FINISHED = MOD_MSG_BASE + 503; // car related messages // GOT full vin MOD_MSG_CAR_GOT_VIN = MOD_MSG_BASE + 1000; implementation { TmodELMData } end.
unit K609886857; {* [Requestlink:609886857] } // Модуль: "w:\common\components\rtl\Garant\Daily\K609886857.pas" // Стереотип: "TestCase" // Элемент модели: "K609886857" MUID: (5625E4EF030E) // Имя типа: "TK609886857" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK609886857 = class(TRTFtoEVDWriterTest) {* [Requestlink:609886857] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK609886857 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *5625E4EF030Eimpl_uses* //#UC END# *5625E4EF030Eimpl_uses* ; function TK609886857.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.12'; end;//TK609886857.GetFolder function TK609886857.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '5625E4EF030E'; end;//TK609886857.GetModelElementGUID initialization TestFramework.RegisterTest(TK609886857.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit findonline; {softpedia returns the following examples, need to test for each: file name 0.0.0 file name 0.0.0 / 0.0.0 Beta file name 0.0.0 Build 0 file name 0.0.0 r0 } {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TFindOnline } TFindOnline = class(TThread) private FStatus: string; FTitle: string; procedure Update; procedure OnTerminate; protected procedure Execute; override; public constructor Create(CreateSuspended: Boolean); property Status: string Read FStatus Write FStatus; property Title: string Read FTitle Write FTitle; end; implementation uses main, fphttpclient, strutils; { TFindOnline } procedure TFindOnline.OnTerminate; begin frmMain.UpdateGrid(colOnlineVer); frmMain.StatusBar.SimpleText:='Ready'; end; procedure TFindOnline.Update; begin frmMain.StatusBar.SimpleText:=Status; end; procedure TFindOnline.Execute; const SEARCH='http://www.softpedia.com/dyn-search.php?search_term='; TAG1='<h4 class="ln"><a href="'; TAG2='title="'; END2='">'; STATUS_MESSAGE='Get Online Version: '; var ipos: integer; buf, sname, snameurl, stemp, surl, sver: String; web: TFPHTTPClient; istart, iend, ilen: integer; begin if Terminated then exit; sname:=Title; snameurl:=StringsReplace(sname, [' '], ['%20'],[rfReplaceAll, rfIgnoreCase]); Status:=STATUS_MESSAGE+sname; Synchronize(@Update); surl:=SEARCH+snameurl; try try web:=TFPHTTPClient.Create(nil); web.AddHeader('User-Agent', 'Mozilla/5.0'); buf:=web.Get(surl); except {ignore error, user sees sver='?'} end; finally web.free; end; istart:=Pos(TAG1, buf); if istart=0 then begin sver:='?'; end else begin iend:=istart+((TAG1.Length+surl.Length)*2); ilen:=iend-istart; buf :=MidStr(buf,istart,ilen); istart:=Pos(TAG2, buf)+TAG2.Length; ilen :=buf.Length; buf :=MidStr(buf,istart,ilen); istart:=1; iend :=Pos(END2, buf); ilen :=iend-istart; stemp :=Trim(MidStr(buf,istart,ilen)); ipos:=Pos('Build',stemp); if ipos<>0 then stemp:=Trim(LeftStr(stemp,ipos)); ipos:=Pos('Beta',stemp); if ipos<>0 then begin sname:=Trim(LeftStr(stemp,sname.Length)); sver:=Trim(MidStr(stemp,sname.Length+2,stemp.Length)); end else begin ipos:=stemp.LastIndexOf(' '); sver:=MidStr(stemp,ipos+2,stemp.Length); if (LeftStr(sver,1)<Char('0')) or (LeftStr(sver,1)>Char('9')) then begin stemp:=Trim(LeftStr(stemp,ipos)); ipos:=stemp.LastIndexOf(' '); sver:=MidStr(stemp,ipos+2,stemp.Length); end; end; gOnlList.Add(sname+'|'+sver); end; gOnlList.Sort; Synchronize(@OnTerminate); end; constructor TFindOnline.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); FreeOnTerminate := True; end; end.
unit FoldersInfoKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы FoldersInfo } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Folders\Forms\FoldersInfoKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "FoldersInfoKeywordsPack" MUID: (4ABCD261014B_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , FoldersInfo_Form , tfwPropertyLike , vtPanel , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4ABCD261014B_Packimpl_uses* //#UC END# *4ABCD261014B_Packimpl_uses* ; type TkwCfFoldersInfoChildZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfFoldersInfo.ChildZone } private function ChildZone(const aCtx: TtfwContext; acfFoldersInfo: TcfFoldersInfo): TvtPanel; {* Реализация слова скрипта .TcfFoldersInfo.ChildZone } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwCfFoldersInfoChildZone Tkw_Form_FoldersInfo = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы FoldersInfo ---- *Пример использования*: [code]форма::FoldersInfo TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_FoldersInfo Tkw_FoldersInfo_Control_ChildZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ChildZone ---- *Пример использования*: [code]контрол::ChildZone TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersInfo_Control_ChildZone Tkw_FoldersInfo_Control_ChildZone_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола ChildZone ---- *Пример использования*: [code]контрол::ChildZone:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_FoldersInfo_Control_ChildZone_Push function TkwCfFoldersInfoChildZone.ChildZone(const aCtx: TtfwContext; acfFoldersInfo: TcfFoldersInfo): TvtPanel; {* Реализация слова скрипта .TcfFoldersInfo.ChildZone } begin Result := acfFoldersInfo.ChildZone; end;//TkwCfFoldersInfoChildZone.ChildZone class function TkwCfFoldersInfoChildZone.GetWordNameForRegister: AnsiString; begin Result := '.TcfFoldersInfo.ChildZone'; end;//TkwCfFoldersInfoChildZone.GetWordNameForRegister function TkwCfFoldersInfoChildZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwCfFoldersInfoChildZone.GetResultTypeInfo function TkwCfFoldersInfoChildZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfFoldersInfoChildZone.GetAllParamsCount function TkwCfFoldersInfoChildZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfFoldersInfo)]); end;//TkwCfFoldersInfoChildZone.ParamsTypes procedure TkwCfFoldersInfoChildZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ChildZone', aCtx); end;//TkwCfFoldersInfoChildZone.SetValuePrim procedure TkwCfFoldersInfoChildZone.DoDoIt(const aCtx: TtfwContext); var l_acfFoldersInfo: TcfFoldersInfo; begin try l_acfFoldersInfo := TcfFoldersInfo(aCtx.rEngine.PopObjAs(TcfFoldersInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfFoldersInfo: TcfFoldersInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ChildZone(aCtx, l_acfFoldersInfo)); end;//TkwCfFoldersInfoChildZone.DoDoIt function Tkw_Form_FoldersInfo.GetString: AnsiString; begin Result := 'cfFoldersInfo'; end;//Tkw_Form_FoldersInfo.GetString class procedure Tkw_Form_FoldersInfo.RegisterInEngine; begin inherited; TtfwClassRef.Register(TcfFoldersInfo); end;//Tkw_Form_FoldersInfo.RegisterInEngine class function Tkw_Form_FoldersInfo.GetWordNameForRegister: AnsiString; begin Result := 'форма::FoldersInfo'; end;//Tkw_Form_FoldersInfo.GetWordNameForRegister function Tkw_FoldersInfo_Control_ChildZone.GetString: AnsiString; begin Result := 'ChildZone'; end;//Tkw_FoldersInfo_Control_ChildZone.GetString class procedure Tkw_FoldersInfo_Control_ChildZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_FoldersInfo_Control_ChildZone.RegisterInEngine class function Tkw_FoldersInfo_Control_ChildZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ChildZone'; end;//Tkw_FoldersInfo_Control_ChildZone.GetWordNameForRegister procedure Tkw_FoldersInfo_Control_ChildZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ChildZone'); inherited; end;//Tkw_FoldersInfo_Control_ChildZone_Push.DoDoIt class function Tkw_FoldersInfo_Control_ChildZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ChildZone:push'; end;//Tkw_FoldersInfo_Control_ChildZone_Push.GetWordNameForRegister initialization TkwCfFoldersInfoChildZone.RegisterInEngine; {* Регистрация cfFoldersInfo_ChildZone } Tkw_Form_FoldersInfo.RegisterInEngine; {* Регистрация Tkw_Form_FoldersInfo } Tkw_FoldersInfo_Control_ChildZone.RegisterInEngine; {* Регистрация Tkw_FoldersInfo_Control_ChildZone } Tkw_FoldersInfo_Control_ChildZone_Push.RegisterInEngine; {* Регистрация Tkw_FoldersInfo_Control_ChildZone_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TcfFoldersInfo)); {* Регистрация типа TcfFoldersInfo } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
namespace Sugar.Test; interface uses Sugar, Sugar.IO, RemObjects.Elements.EUnit; type FolderTest = public class (Test) private Data: Folder; public method Setup; override; method TearDown; override; method CreateFile; method CreateFolder; method Delete; method GetFile; method GetFiles; method GetFolder; method GetFolders; method Rename; method FromPath; method UserLocal; method PathProperty; method Name; end; implementation method FolderTest.Setup; begin Data := Folder.UserLocal.CreateFolder("SugarTest", true); Assert.IsNotNil(Data); end; method FolderTest.TearDown; begin Data.Delete; end; method FolderTest.CreateFile; begin Assert.IsNil(Data.GetFile("Sample.txt")); var Value := Data.CreateFile("Sample.txt", true); Assert.IsNotNil(Value); Assert.IsNotNil(Data.GetFile("Sample.txt")); Value := Data.CreateFile("Sample.txt", false); Assert.IsNotNil(Value); Assert.AreEqual(length(Data.GetFiles), 1); Assert.Throws(->Data.CreateFile("Sample.txt", true)); Assert.Throws(->Data.CreateFile("/", true)); Assert.Throws(->Data.CreateFile(nil, true)); end; method FolderTest.CreateFolder; begin Assert.IsNil(Data.GetFolder("Sample")); var Value := Data.CreateFolder("Sample", true); Assert.IsNotNil(Value); Assert.IsNotNil(Data.GetFolder("Sample")); Value := Data.CreateFolder("Sample", false); Assert.IsNotNil(Value); Assert.AreEqual(length(Data.GetFolders), 1); Assert.Throws(->Data.CreateFolder("Sample", true)); Assert.Throws(->Data.CreateFolder("/", true)); Assert.Throws(->Data.CreateFolder(nil, true)); end; method FolderTest.Delete; begin Assert.IsNil(Data.GetFolder("Sample")); var Value := Data.CreateFolder("Sample", true); Assert.IsNotNil(Value); Assert.IsNotNil(Data.GetFolder("Sample")); Assert.AreEqual(length(Data.GetFolders), 1); Value.Delete; Assert.IsNil(Data.GetFolder("Sample")); Assert.AreEqual(length(Data.GetFolders), 0); Assert.Throws(->Value.Delete); end; method FolderTest.GetFile; begin Assert.IsNil(Data.GetFile("Sample.txt")); Assert.IsNotNil(Data.CreateFile("Sample.txt", true)); var Value := Data.GetFile("Sample.txt"); Assert.IsNotNil(Value); Assert.Throws(->Data.GetFile(nil)); end; method FolderTest.GetFiles; begin Assert.AreEqual(length(Data.GetFolders), 0); Assert.AreEqual(length(Data.GetFiles), 0); //setup Data.CreateFile("1", true); Data.CreateFile("2", true); Data.CreateFile("3", true); Data.CreateFolder("Temp1", true); Data.CreateFolder("Temp2", true); Assert.AreEqual(length(Data.GetFolders), 2); Assert.AreEqual(length(Data.GetFiles), 3); var Expected := new Sugar.Collections.List<String>; Expected.Add("1"); Expected.Add("2"); Expected.Add("3"); var Value := Data.GetFiles; Assert.AreEqual(length(Value), 3); for i: Integer := 0 to length(Value) - 1 do Assert.IsTrue(Expected.Contains(Value[i].Name)); end; method FolderTest.GetFolder; begin Assert.IsNil(Data.GetFolder("Sample")); Assert.IsNotNil(Data.CreateFolder("Sample", true)); var Value := Data.GetFolder("Sample"); Assert.IsNotNil(Value); Assert.Throws(->Data.GetFolder(nil)); end; method FolderTest.GetFolders; begin Assert.AreEqual(length(Data.GetFolders), 0); Assert.AreEqual(length(Data.GetFiles), 0); //setup Data.CreateFile("1", true); Data.CreateFile("2", true); Data.CreateFile("3", true); Data.CreateFolder("Temp1", true); Data.CreateFolder("Temp2", true); Assert.AreEqual(length(Data.GetFolders), 2); Assert.AreEqual(length(Data.GetFiles), 3); var Expected := new Sugar.Collections.List<String>; Expected.Add("Temp1"); Expected.Add("Temp2"); var Value := Data.GetFolders; Assert.AreEqual(length(Value), 2); for i: Integer := 0 to length(Value) - 1 do Assert.IsTrue(Expected.Contains(Value[i].Name)); end; method FolderTest.Rename; begin var Value := Data.CreateFolder("Sample", true); Assert.IsNotNil(Value); Assert.IsNotNil(Value.CreateFolder("Test", true)); Assert.IsNotNil(Value.CreateFile("1.txt", true)); var OldPath := Value.Path; Value.Rename("Temp"); Assert.IsTrue(OldPath <> Value.Path); Assert.IsNil(Data.GetFolder("Sample")); Assert.IsNotNil(Data.GetFolder("Temp")); Assert.Throws(->Value.Rename("Temp")); Data.CreateFolder("Temp1", true); Assert.Throws(->Value.Rename("Temp1")); Assert.Throws(->Value.Rename("/")); Assert.Throws(->Value.Rename(nil)); Assert.Throws(->Value.Rename("")); end; method FolderTest.FromPath; begin Assert.IsNotNil(Data.CreateFolder("Sample", true)); Assert.IsNotNil(new Folder(Path.Combine(Data.Path, "Sample"))); Assert.Throws(->new Folder(Path.Combine(Data.Path, "Unknown"))); Assert.Throws(->new Folder(nil)); end; method FolderTest.UserLocal; begin Assert.IsNotNil(Folder.UserLocal); end; method FolderTest.PathProperty; begin Assert.IsFalse(String.IsNullOrEmpty(Data.Path)); Assert.IsNotNil(Data.CreateFolder("Sample", true)); var Value := new Folder(Path.Combine(Data.Path, "Sample")); Assert.IsNotNil(Value); Assert.IsFalse(String.IsNullOrEmpty(Value.Path)); end; method FolderTest.Name; begin Assert.IsFalse(String.IsNullOrEmpty(Data.Name)); Assert.IsNotNil(Data.CreateFolder("Sample", true)); var Value := new Folder(Path.Combine(Data.Path, "Sample")); Assert.IsNotNil(Value); Assert.IsFalse(String.IsNullOrEmpty(Value.Name)); Assert.AreEqual(Value.Name, "Sample"); end; end.
{ Exercicio 37: Um cinema colheu de um espectador as respostas de um questionário, no qual constava: sua idade e sua opinião em relação ao filme, segundo as seguintes notas: Nota Significado A Ótimo B Bom C Regular D Ruim E Péssimo OBS: Faltou o resto do exercício. Vou exibir na tela a idade da pessoa e a nota que ela deu. } { Solução em Portugol Algoritmo Exercicio 37; Var idade: inteiro; nota: caracter; Inicio exiba("Pesquisa de satisfação com o filme."); exiba("Qual a sua idade: "); leia(idade); exiba("Dê uma nota de A até E para o filme, sendo A = ótimo e E = péssimo."); leia(nota); caso(nota)de "A": exiba("Você tem ",idade," anos e avaliou o filme como sendo ótimo."); "B": exiba("Você tem ",idade," anos e avaliou o filme como sendo bom."); "C": exiba("Você tem ",idade," anos e avaliou o filme como sendo regular."); "D": exiba("Você tem ",idade," anos e avaliou o filme como sendo ruim."); "E": exiba("Você tem ",idade," anos e avaliou o filme como sendo péssimo."); else exiba("Nota inválida."); fimcaso; Fim. } // Solução em Pascal Program Exercicio37; uses crt; var idade: integer; nota: char; begin clrscr; writeln('Pesquisa de satisfação com o filme.'); writeln('Qual a sua idade: '); readln(idade); writeln('Dê uma nota de A até E para o filme, sendo A = ótimo e E = péssimo.'); readln(nota); case(nota)of 'A': writeln('Você tem ',idade,' anos e avaliou o filme como sendo ótimo.'); 'B': writeln('Você tem ',idade,' anos e avaliou o filme como sendo bom.'); 'C': writeln('Você tem ',idade,' anos e avaliou o filme como sendo regular.'); 'D': writeln('Você tem ',idade,' anos e avaliou o filme como sendo ruim.'); 'E': writeln('Você tem ',idade,' anos e avaliou o filme como sendo péssimo.'); else writeln('Nota inválida.'); end; repeat until keypressed; end.
Unit Systematic.FMX.MacAddress; //************************************************// // Getting MAC Addresses // // Systematic.FMX.MacAddress; // // provided as is, no warranties // //************************************************// Interface Uses System.SysUtils, System.Classes, System.NetEncoding; Function GetMACAddress(ADevice: Integer): String; {$IF DEFINED(MSWINDOWS)} //as a short cut this uses the JCL, needs rewriting to be platform independant - i.e. get device list and use GetMacAddress Function GetAllMacAddresses(const UserPercentEncoding: boolean = False): string; {$ENDIF} Function GetLocalComputerName: String; Function GetOSUserName: String; Implementation {$IF DEFINED(MSWINDOWS)} Uses NB30, Winapi.Windows, jclSysInfo, REST.Utils; {$ELSE} Uses Posix.Base, Posix.SysSocket, Posix.NetIf, Posix.NetinetIn, Posix.ArpaInet, Posix.SysSysctl; Type u_char = UInt8; u_short = UInt16; sockaddr_dl = Record sdl_len: u_char; // * Total length of sockaddr */ sdl_family: u_char; // * AF_LINK */ sdl_index: u_short; // * if != 0, system given index for interface */ sdl_type: u_char; // * interface type */ sdl_nlen: u_char; // * interface name length, no trailing 0 reqd. */ sdl_alen: u_char; // * link level address length */ sdl_slen: u_char; // * link layer selector length */ sdl_data: Array [0 .. 11] Of AnsiChar; // * minimum work area, can be larger; // contains both if name and ll address */ End; psockaddr_dl = ^sockaddr_dl; Const IFT_ETHER = $6; // if_types.h {$ENDIF} {$IF DEFINED(MSWINDOWS)} Function GetMACAddress(ADevice: Integer): String; Var AdapterList: TLanaEnum; Adapter: TAdapterStatus; NCB1, NCB2: TNCB; Lana: AnsiChar; Begin FillChar(NCB1, SizeOf(NCB1), 0); NCB1.ncb_command := Char(NCBENUM); NCB1.ncb_buffer := @AdapterList; NCB1.ncb_length := SizeOf(AdapterList); Netbios(@NCB1); If Byte(AdapterList.length) > 0 Then Begin // AdapterList.lana[] contiene i vari lDevice hardware Lana := AdapterList.Lana[ADevice]; FillChar(NCB2, SizeOf(NCB2), 0); NCB2.ncb_command := Char(NCBRESET); NCB2.ncb_lana_num := Lana; If Netbios(@NCB2) <> Char(NRC_GOODRET) Then Begin Result := 'mac not found'; Exit; End; FillChar(NCB2, SizeOf(NCB2), 0); NCB2.ncb_command := Char(NCBASTAT); NCB2.ncb_lana_num := Lana; NCB2.ncb_callname := '*'; FillChar(Adapter, SizeOf(Adapter), 0); NCB2.ncb_buffer := @Adapter; NCB2.ncb_length := SizeOf(Adapter); If Netbios(@NCB2) <> Char(NRC_GOODRET) Then Begin Result := 'mac not found'; Exit; End; Result := IntToHex(Byte(Adapter.adapter_address[0]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[1]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[2]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[3]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[4]), 2) + '-' + IntToHex(Byte(Adapter.adapter_address[5]), 2); End Else Result := 'mac not found'; End; {$ELSE} Function getifaddrs(Var ifap: pifaddrs): Integer; Cdecl; External libc Name _PU + 'getifaddrs'; {$EXTERNALSYM getifaddrs} Procedure freeifaddrs(ifp: pifaddrs); Cdecl; External libc Name _PU + 'freeifaddrs'; {$EXTERNALSYM freeifaddrs} Function GetMACAddress(ADevice: Integer): String; Var ifap, Next: pifaddrs; sdp: psockaddr_dl; ip: AnsiString; MacAddr: Array [0 .. 5] Of Byte; lDevice: Integer; Begin lDevice := 0; Try If getifaddrs(ifap) <> 0 Then RaiseLastOSError; Try SetLength(ip, INET6_ADDRSTRLEN); Next := ifap; While Next <> Nil Do Begin Case Next.ifa_addr.sa_family Of AF_LINK: Begin sdp := psockaddr_dl(Next.ifa_addr); If sdp.sdl_type = IFT_ETHER Then Begin Move(Pointer(PAnsiChar(@sdp^.sdl_data[0]) + sdp.sdl_nlen)^, MacAddr, 6); If (ADevice = lDevice) Then Begin Result := IntToHex(MacAddr[0], 2) + '-' + IntToHex(MacAddr[1], 2) + '-' + IntToHex(MacAddr[2], 2) + '-' + IntToHex(MacAddr[3], 2) + '-' + IntToHex(MacAddr[4], 2) + '-' + IntToHex(MacAddr[5], 2); End; lDevice := lDevice + 1; End; End; End; Next := Next.ifa_next; End; Finally freeifaddrs(ifap); End; Except On E: Exception Do Result := ''; // E.ClassName + ': ' + E.Message; End; // se non ha trovato nulla End; {$ENDIF} {$IF DEFINED(MSWINDOWS)} Function GetAllMacAddresses(const UserPercentEncoding: boolean = False): string; var TS: TStringList; I: Integer; begin Result := ''; TS := TStringList.Create; try jclSysInfo.GetMacAddresses('', TS); for I := 0 to TS.Count - 1 do begin if UserPercentEncoding then Result := Result +URIEncode(TS[I].Replace('-', ':', [rfReplaceAll]).ToLower) + ',' else begin Result := Result + TS[I].Replace('-', ':', [rfReplaceAll]).ToLower + ','; end; end; finally TS.Free; end; Result := Result.TrimRight([',']); end; {$ENDIF} Function GetLocalComputerName: String; Var {$IFDEF MSWINDOWS} c1: DWORD; arrCh: Array [0 .. MAX_COMPUTERNAME_LENGTH] Of Char; {$ENDIF} {$IFDEF POSIX} len: size_t; p: PAnsiChar; res: Integer; {$ENDIF} Begin {$IFDEF MSWINDOWS} c1 := MAX_COMPUTERNAME_LENGTH + 1; If GetComputerName(arrCh, c1) Then SetString(Result, arrCh, c1) Else Result := ''; {$ENDIF} {$IFDEF POSIX} Result := ''; res := sysctlbyname('kern.hostname', Nil, @len, Nil, 0); If (res = 0) And (len > 0) Then Begin GetMem(p, len); Try res := sysctlbyname('kern.hostname', p, @len, Nil, 0); If res = 0 Then Result := String(AnsiString(p)); Finally FreeMem(p); End; End; {$ENDIF} End; Function GetOSUserName: String; {$IFDEF MSWINDOWS} Var lSize: DWORD; {$ENDIF} Begin {$IFDEF MACOS} Result := TNSString.Wrap(NSUserName).UTF8String; {$ENDIF} {$IFDEF MSWINDOWS} lSize := 1024; SetLength(Result, lSize); If GetUserName(PChar(Result), lSize) Then SetLength(Result, lSize - 1) Else RaiseLastOSError; {$ENDIF} End; End.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clImap4FileHandler; interface {$I clVer.inc} {$IFDEF DELPHI6} {$WARN SYMBOL_PLATFORM OFF} {$ENDIF} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$WARN UNSAFE_CAST OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, SyncObjs, Windows, {$ELSE} System.Classes, System.SysUtils, System.SyncObjs, Winapi.Windows, {$ENDIF} clImap4Server, clImapUtils, clUtils; type TclImap4MailBoxStore = class private FMailBox: TclImap4MailBoxItem; public constructor Create(AMailBox: TclImap4MailBoxItem); function Version: Integer; virtual; procedure Load(AStream: TStream); virtual; procedure Save(AStream: TStream); virtual; property MailBox: TclImap4MailBoxItem read FMailBox; end; TclImap4MessageStore = class private FMessages: TclImap4MessageList; public constructor Create(AMessages: TclImap4MessageList); function Version: Integer; virtual; procedure Load(AStream: TStream); virtual; procedure Save(AStream: TStream); virtual; property Messages: TclImap4MessageList read FMessages; end; TclImap4FileHandler = class(TComponent) private FServer: TclImap4Server; FMailBoxDir: string; FAccessor: TCriticalSection; FMailBoxInfoFile: string; FMessagesInfoFile: string; FSharedFolders: string; procedure SetMailBoxDir(const Value: string); procedure SetServer(const Value: TclImap4Server); procedure SetMailBoxInfoFile(const Value: string); procedure SetMessagesInfoFile(const Value: string); procedure SetSharedFolders(const Value: string); function GetMailBoxRoot(const AUserName: string): string; function MailBoxToPath(const AMailBox: string): string; function GetMailBoxPath(const AUserName, AMailBox: string): string; function HasSharedFolders: Boolean; function IsSharedFolder(const AMailboxPath: string): Boolean; procedure CollectMailBoxes(AMailBoxes: TclImap4MailBoxList; const APath, ARootMailBox: string); function GenUidValidity(const AMailboxPath: string): string; procedure SetCounter(AItem: TclImap4MailBoxItem; ACounter: Integer); function GetCounter(AItem: TclImap4MailBoxItem): Integer; procedure CollectMailBoxInfo(AItem: TclImap4MailBoxItem; const AMailboxPath: string; IsSubscribed: Boolean); procedure UpdateMailBoxInfo(const AMailBoxPath: string; AMailBox: TclImap4MailBoxItem); procedure UpdateMessageInfo(const AMsgInfoFile, AMessageFile: string; AFlags: TclMailMessageFlags; ADate: TDateTime); function GetMessageFilePaths(const AMailBoxPath, AFileMask: string): TStrings; procedure DoGetMailBoxes(Sender: TObject; AConnection: TclImap4CommandConnection; const ASelectedMailBox: string; AMailBoxes: TclImap4MailBoxList); procedure DoUpdateMailBox(Sender: TObject; AConnection: TclImap4CommandConnection; AMailBox: TclImap4MailBoxItem; var Success: Boolean); procedure DoCreateMailBox(Sender: TObject; AConnection: TclImap4CommandConnection; const AMailBox: string; var Success: Boolean); procedure DoDeleteMailBox(Sender: TObject; AConnection: TclImap4CommandConnection; const AMailBox: string; var Success: Boolean); procedure DoRenameMailBox(Sender: TObject; AConnection: TclImap4CommandConnection; const ACurrentName, ANewName: string; var Success: Boolean); procedure DoGetMessages(Sender: TObject; AConnection: TclImap4CommandConnection; AMessages: TclImap4MessageList; const AMailBox: string; var Success: Boolean); procedure DoUpdateMessages(Sender: TObject; AConnection: TclImap4CommandConnection; AMessages: TclImap4MessageList; const AMailBox: string; var Success: Boolean); procedure DoDeleteMessage(Sender: TObject; AConnection: TclImap4CommandConnection; AMessage: TclImap4MessageItem; const AMailBox: string; var Success: Boolean); procedure DoGetMessageSource(Sender: TObject; AConnection: TclImap4CommandConnection; AMessageSource: TStrings; const AMessageName, AMailBox: string; var Success: Boolean); procedure DoAppendMessage(Sender: TObject; AConnection: TclImap4CommandConnection; AFlags: TclMailMessageFlags; ADate: TDateTime; AMessageSource: TStrings; const AMailBox: string; var Success: Boolean); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure CleanEventHandlers; virtual; procedure InitEventHandlers; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Server: TclImap4Server read FServer write SetServer; property MailBoxDir: string read FMailBoxDir write SetMailBoxDir; property MailBoxInfoFile: string read FMailBoxInfoFile write SetMailBoxInfoFile; property MessagesInfoFile: string read FMessagesInfoFile write SetMessagesInfoFile; property SharedFolders: string read FSharedFolders write SetSharedFolders; end; resourcestring cMailBoxLoadError = 'Cannot load mailbox settings'; cMessageLoadError = 'Cannot load messages'; const cImapMailBoxInfoFile = 'imap.dat'; cImapMessagesInfoFile = 'messages.dat'; var cMaxTryCount: Integer = 1000; implementation { TclImap4MailBoxStore } constructor TclImap4MailBoxStore.Create(AMailBox: TclImap4MailBoxItem); begin inherited Create(); FMailBox := AMailBox; end; procedure TclImap4MailBoxStore.Load(AStream: TStream); var reader: TReader; counter: Integer; begin reader := TReader.Create(AStream, 1024); try if (reader.ReadInteger() <> Version) then begin raise EStreamError.Create(cMailBoxLoadError); end; MailBox.IsSubscribed := reader.ReadBoolean(); MailBox.UIDNext := reader.ReadInteger(); MailBox.UIDValidity := reader.ReadString(); counter := reader.ReadInteger(); if (counter > 0) then begin MailBox.Data := Pointer(counter); end else begin MailBox.Data := nil; end; finally reader.Free(); end; end; procedure TclImap4MailBoxStore.Save(AStream: TStream); var writer: TWriter; begin writer := TWriter.Create(AStream, 1024); try writer.WriteInteger(Version()); writer.WriteBoolean(MailBox.IsSubscribed); writer.WriteInteger(MailBox.UIDNext); writer.WriteString(MailBox.UIDValidity); if (MailBox.Data <> nil) then begin writer.WriteInteger(Integer(MailBox.Data)); end else begin writer.WriteInteger(0); end; finally writer.Free(); end; end; function TclImap4MailBoxStore.Version: Integer; begin Result := 1; end; { TclImap4MessageStore } constructor TclImap4MessageStore.Create(AMessages: TclImap4MessageList); begin inherited Create(); FMessages := AMessages; end; procedure TclImap4MessageStore.Load(AStream: TStream); var reader: TReader; i, cnt: Integer; item: TclImap4MessageItem; begin reader := TReader.Create(AStream, 1024); try if (reader.ReadInteger() <> Version()) then begin raise EStreamError(cMessageLoadError); end; Messages.Clear(); cnt := reader.ReadInteger(); for i := 0 to cnt - 1 do begin item := TclImap4MessageItem.Create(); Messages.Add(item); item.Name := reader.ReadString(); item.UID := reader.ReadInteger(); item.Flags := GetImapMessageFlagsByStr(UpperCase(reader.ReadString())); item.Date := reader.ReadFloat(); end; finally reader.Free(); end; end; procedure TclImap4MessageStore.Save(AStream: TStream); var writer: TWriter; i: Integer; item: TclImap4MessageItem; begin writer := TWriter.Create(AStream, 1024); try writer.WriteInteger(Version()); writer.WriteInteger(Messages.Count); for i := 0 to Messages.Count - 1 do begin item := Messages[i]; writer.WriteString(item.Name); writer.WriteInteger(item.UID); writer.WriteString(GetStrByImapMessageFlags(item.Flags)); writer.WriteFloat(item.Date); end; finally writer.Free(); end; end; function TclImap4MessageStore.Version: Integer; begin Result := 2; end; { TclImap4FileHandler } procedure TclImap4FileHandler.CleanEventHandlers; begin Server.OnGetMailBoxes := nil; Server.OnUpdateMailBox := nil; Server.OnCreateMailBox := nil; Server.OnDeleteMailBox := nil; Server.OnRenameMailBox := nil; Server.OnGetMessages := nil; Server.OnUpdateMessages := nil; Server.OnDeleteMessage := nil; Server.OnGetMessageSource := nil; Server.OnAppendMessage := nil; end; procedure TclImap4FileHandler.CollectMailBoxes(AMailBoxes: TclImap4MailBoxList; const APath, ARootMailBox: string); var sr: TSearchRec; item: TclImap4MailBoxItem; begin if {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindFirst(APath + '*.*', faDirectory, sr) = 0 then begin repeat if ((sr.Attr and faDirectory) <> 0) and (sr.Name <> '.') and (sr.Name <> '..') then begin item := AMailBoxes.Add(); item.Name := ARootMailBox + sr.Name; CollectMailBoxInfo(item, APath + sr.Name, False); CollectMailBoxes(AMailBoxes, APath + sr.Name + '\', sr.Name + Server.MailBoxSeparator); end; until ({$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindNext(sr) <> 0); {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(sr); end; end; procedure TclImap4FileHandler.CollectMailBoxInfo(AItem: TclImap4MailBoxItem; const AMailboxPath: string; IsSubscribed: Boolean); var store: TclImap4MailBoxStore; s: string; stream: TStream; begin store := nil; stream := nil; try store := TclImap4MailBoxStore.Create(AItem); s := AddTrailingBackSlash(AMailboxPath) + MailBoxInfoFile; if (not FileExists(s)) then begin AItem.IsSubscribed := IsSubscribed; AItem.UIDNext := 1; AItem.UIDValidity := GenUidValidity(AMailboxPath); SetCounter(AItem, 0); stream := TFileStream.Create(s, fmCreate); store.Save(stream); end else begin stream := TFileStream.Create(s, fmOpenRead or fmShareDenyWrite); store.Load(stream); end; finally stream.Free(); store.Free(); end; end; constructor TclImap4FileHandler.Create(AOwner: TComponent); begin inherited Create(AOwner); FAccessor := TCriticalSection.Create(); FMailBoxInfoFile := cImapMailBoxInfoFile; FMessagesInfoFile := cImapMessagesInfoFile; end; destructor TclImap4FileHandler.Destroy; begin FAccessor.Free(); inherited Destroy(); end; procedure TclImap4FileHandler.DoAppendMessage(Sender: TObject; AConnection: TclImap4CommandConnection; AFlags: TclMailMessageFlags; ADate: TDateTime; AMessageSource: TStrings; const AMailBox: string; var Success: Boolean); var mailBoxPath, msgFileName: string; mailBoxItem: TclImap4MailBoxItem; i, counter: Integer; begin FAccessor.Enter(); try Success := False; mailBoxPath := GetMailBoxPath(AConnection.UserName, AMailBox); mailBoxItem := TclImap4MailBoxItem.Create(nil); try mailBoxItem.Name := AMailBox; CollectMailBoxInfo(mailBoxItem, mailBoxPath, False); counter := GetCounter(mailBoxItem); msgFileName := ''; i := 0; while (True) do begin Inc(counter); msgFileName := mailBoxPath + Format('MAIL%.8d.MSG', [counter]); try if (not FileExists(msgFileName)) then begin TclStringsUtils.SaveStrings(AMessageSource, msgFileName, ''); Break; end; except on EStreamError do; end; Inc(i); if (i > cMaxTryCount) then begin raise Exception.Create('Cannot save new message'); end; end; SetCounter(mailBoxItem, counter); UpdateMailBoxInfo(mailBoxPath + MailBoxInfoFile, mailBoxItem); UpdateMessageInfo(mailBoxPath + MessagesInfoFile, msgFileName, AFlags, ADate); Success := True; finally mailBoxItem.Free(); end; finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.DoCreateMailBox(Sender: TObject; AConnection: TclImap4CommandConnection; const AMailBox: string; var Success: Boolean); var path: string; begin FAccessor.Enter(); try Success := False; if (SameText('INBOX', AMailBox)) then Exit; path := GetMailBoxPath(AConnection.UserName, AMailBox); if (DirectoryExists(path) or IsSharedFolder(path)) then Exit; Success := ForceFileDirectories(path); finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.DoDeleteMailBox(Sender: TObject; AConnection: TclImap4CommandConnection; const AMailBox: string; var Success: Boolean); function HasSubDirs(const ADir: string): Boolean; var sr: TSearchRec; begin Result := False; if {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindFirst(ADir + '*.*', faDirectory, sr) = 0 then begin repeat if ((sr.Attr and faDirectory) <> 0) and (sr.Name <> '.') and (sr.Name <> '..') then begin Result := True; Break; end; until ({$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindNext(sr) <> 0); {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(sr); end; end; var path: string; begin FAccessor.Enter(); try Success := False; if (SameText('INBOX', AMailBox)) then Exit; path := GetMailBoxPath(AConnection.UserName, AMailBox); if ((not DirectoryExists(path)) or IsSharedFolder(path)) then Exit; if HasSubDirs(AddTrailingBackSlash(path)) then Exit; Success := DeleteRecursiveDir(path); finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.DoDeleteMessage(Sender: TObject; AConnection: TclImap4CommandConnection; AMessage: TclImap4MessageItem; const AMailBox: string; var Success: Boolean); begin FAccessor.Enter(); try Success := False; if (FileExists(AMessage.Name)) then begin Success := DeleteFile(PChar(AMessage.Name)); end; finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.DoGetMailBoxes(Sender: TObject; AConnection: TclImap4CommandConnection; const ASelectedMailBox: string; AMailBoxes: TclImap4MailBoxList); var path: string; item: TclImap4MailBoxItem; begin FAccessor.Enter(); try path := GetMailBoxRoot(AConnection.UserName); if (ASelectedMailBox = '') then begin if (DirectoryExists(path)) then begin item := AMailBoxes.Add(); item.Name := 'INBOX'; CollectMailBoxInfo(item, path, True); CollectMailBoxes(AMailBoxes, path, ''); end; if (HasSharedFolders()) then begin CollectMailBoxes(AMailBoxes, AddTrailingBackSlash(SharedFolders), ''); end; end else begin path := GetMailBoxPath(AConnection.UserName, ASelectedMailBox); if (DirectoryExists(path)) then begin item := AMailBoxes.Add(); item.Name := ASelectedMailBox; CollectMailBoxInfo(item, path, False); end; end; finally FAccessor.Leave(); end; end; function TclImap4FileHandler.GetMessageFilePaths(const AMailBoxPath, AFileMask: string): TStrings; var sr: TSearchRec; begin Result := TStringList.Create(); try if {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindFirst(AMailBoxPath + AFileMask, faAnyFile, sr) = 0 then begin repeat if (sr.Name <> '.') and (sr.Name <> '..') then begin Result.Add(AMailBoxPath + sr.Name); end; until ({$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindNext(sr) <> 0); {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(sr); end; except Result.Free(); raise; end; end; procedure TclImap4FileHandler.DoGetMessages(Sender: TObject; AConnection: TclImap4CommandConnection; AMessages: TclImap4MessageList; const AMailBox: string; var Success: Boolean); var mailBoxPath, msgInfoFile: string; storedMessages: TclImap4MessageList; store: TclImap4MessageStore; stream: TStream; list: TStrings; i: Integer; s: string; storedItem, item: TclImap4MessageItem; begin FAccessor.Enter(); try Success := False; mailBoxPath := GetMailBoxPath(AConnection.UserName, AMailBox); if (not DirectoryExists(mailBoxPath)) then Exit; msgInfoFile := mailBoxPath + MessagesInfoFile; storedMessages := nil; store := nil; stream := nil; list := nil; try storedMessages := TclImap4MessageList.Create(); if (FileExists(msgInfoFile)) then begin store := TclImap4MessageStore.Create(storedMessages); stream := TFileStream.Create(msgInfoFile, fmOpenRead or fmShareDenyWrite); store.Load(stream); end; list := GetMessageFilePaths(mailBoxPath, '*.MSG'); for i := storedMessages.Count - 1 downto 0 do begin if (list.IndexOf(storedMessages[i].Name) < 0) then begin storedMessages.Delete(i); end; end; for i := 0 to list.Count - 1 do begin s := list[i]; storedItem := storedMessages.FindByName(s); item := TclImap4MessageItem.Create(s); if (storedItem <> nil) then begin item.UID := storedItem.UID; item.Flags := storedItem.Flags; end; item.Date := GetLocalFileTime(s); AMessages.Add(item); end; Success := True; finally list.Free(); stream.Free(); store.Free(); storedMessages.Free(); end; finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.DoGetMessageSource(Sender: TObject; AConnection: TclImap4CommandConnection; AMessageSource: TStrings; const AMessageName, AMailBox: string; var Success: Boolean); begin FAccessor.Enter(); try Success := False; try if (FileExists(AMessageName)) then begin TclStringsUtils.LoadStrings(AMessageName, AMessageSource, ''); Success := True; end; except on EStreamError do; end; finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.DoRenameMailBox(Sender: TObject; AConnection: TclImap4CommandConnection; const ACurrentName, ANewName: string; var Success: Boolean); var currentPath, newPath: string; begin FAccessor.Enter(); try Success := False; if ((SameText('INBOX', ACurrentName)) or (SameText('INBOX', ANewName))) then Exit; currentPath := GetMailBoxPath(AConnection.UserName, ACurrentName); newPath := GetMailBoxPath(AConnection.UserName, ANewName); if ((not DirectoryExists(currentPath)) or IsSharedFolder(currentPath) or (DirectoryExists(newPath)) or IsSharedFolder(newPath)) then Exit; Success := RenameFile(currentPath, newPath); finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.DoUpdateMailBox(Sender: TObject; AConnection: TclImap4CommandConnection; AMailBox: TclImap4MailBoxItem; var Success: Boolean); var s: string; begin FAccessor.Enter(); try s := GetMailBoxPath(AConnection.UserName, AMailBox.Name) + MailBoxInfoFile; if (FileExists(s)) then begin UpdateMailBoxInfo(s, AMailBox); end; finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.DoUpdateMessages(Sender: TObject; AConnection: TclImap4CommandConnection; AMessages: TclImap4MessageList; const AMailBox: string; var Success: Boolean); var mailBoxPath, msgInfoFile: string; storedMessages: TclImap4MessageList; stream: TStream; store: TclImap4MessageStore; msg, storedItem: TclImap4MessageItem; i: Integer; begin FAccessor.Enter(); try Success := False; mailBoxPath := GetMailBoxPath(AConnection.UserName, AMailBox); msgInfoFile := mailBoxPath + MessagesInfoFile; storedMessages := nil; stream := nil; store := nil; try storedMessages := TclImap4MessageList.Create(); if (FileExists(msgInfoFile)) then begin stream := TFileStream.Create(msgInfoFile, fmOpenRead or fmShareDenyWrite); store := TclImap4MessageStore.Create(storedMessages); store.Load(stream); end; for i := 0 to AMessages.Count - 1 do begin msg := AMessages[i]; if (not FileExists(msg.Name)) then Continue; storedItem := storedMessages.FindByName(msg.Name); if (storedItem = nil) then begin storedItem := TclImap4MessageItem.Create(msg.Name); storedMessages.Add(storedItem); storedItem.UID := msg.UID; end else if (storedItem.UID < 0) then begin storedItem.UID := msg.UID; end; storedItem.Flags := msg.Flags; SetLocalFileTime(msg.Name, msg.Date); end; stream.Free(); stream := nil; store.Free(); store := nil; stream := TFileStream.Create(msgInfoFile, fmCreate); store := TclImap4MessageStore.Create(storedMessages); store.Save(stream); Success := True; finally store.Free(); stream.Free(); storedMessages.Free(); end; finally FAccessor.Leave(); end; end; function TclImap4FileHandler.GenUidValidity(const AMailboxPath: string): string; var sr: TSearchRec; s: string; begin Result := '0'; s := AMailboxPath; if (s <> '') and (s[Length(s)] = '\') then begin system.Delete(s, Length(s), 1); end; if {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindFirst(s, faDirectory, sr) = 0 then begin Result := IntToStr(sr.FindData.ftLastWriteTime.dwLowDateTime) + IntToStr(sr.FindData.ftLastWriteTime.dwHighDateTime); {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(sr); end; end; function TclImap4FileHandler.GetCounter(AItem: TclImap4MailBoxItem): Integer; begin Result := Integer(AItem.Data); end; function TclImap4FileHandler.GetMailBoxPath(const AUserName, AMailBox: string): string; begin Result := GetMailBoxRoot(AUserName) + AddTrailingBackSlash(MailBoxToPath(AMailBox)); if (HasSharedFolders() and (not DirectoryExists(Result))) then begin Result := AddTrailingBackSlash(SharedFolders) + AddTrailingBackSlash(MailBoxToPath(AMailBox)); end; end; function TclImap4FileHandler.GetMailBoxRoot(const AUserName: string): string; begin Result := AddTrailingBackSlash(MailBoxDir) + AddTrailingBackSlash(AUserName); end; function TclImap4FileHandler.HasSharedFolders: Boolean; begin Result := (SharedFolders <> '') and DirectoryExists(SharedFolders); end; procedure TclImap4FileHandler.InitEventHandlers; begin Server.OnGetMailBoxes := DoGetMailBoxes; Server.OnUpdateMailBox := DoUpdateMailBox; Server.OnCreateMailBox := DoCreateMailBox; Server.OnDeleteMailBox := DoDeleteMailBox; Server.OnRenameMailBox := DoRenameMailBox; Server.OnGetMessages := DoGetMessages; Server.OnUpdateMessages := DoUpdateMessages; Server.OnDeleteMessage := DoDeleteMessage; Server.OnGetMessageSource := DoGetMessageSource; Server.OnAppendMessage := DoAppendMessage; end; function TclImap4FileHandler.IsSharedFolder(const AMailboxPath: string): Boolean; begin Result := False; if (AMailboxPath = '') or (not HasSharedFolders()) then Exit; Result := system.Pos(UpperCase(SharedFolders), UpperCase(AMailboxPath)) = 1; end; function TclImap4FileHandler.MailBoxToPath(const AMailBox: string): string; begin if (AMailBox = '') or (SameText('INBOX', AMailBox)) then begin Result := ''; end else begin Result := StringReplace(AMailBox, Server.MailBoxSeparator, '\', [rfReplaceAll]); end; end; procedure TclImap4FileHandler.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation <> opRemove) then Exit; if (AComponent = FServer) then begin CleanEventHandlers(); FServer := nil; end; end; procedure TclImap4FileHandler.SetCounter(AItem: TclImap4MailBoxItem; ACounter: Integer); begin AItem.Data := Pointer(ACounter); end; procedure TclImap4FileHandler.SetMailBoxDir(const Value: string); begin FAccessor.Enter(); try FMailBoxDir := Value; finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.SetMailBoxInfoFile(const Value: string); begin FAccessor.Enter(); try FMailBoxInfoFile := Value; finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.SetMessagesInfoFile(const Value: string); begin FAccessor.Enter(); try FMessagesInfoFile := Value; finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.SetServer(const Value: TclImap4Server); begin if (FServer <> Value) then begin if (FServer <> nil) then begin FServer.RemoveFreeNotification(Self); CleanEventHandlers(); end; FServer := Value; if (FServer <> nil) then begin FServer.FreeNotification(Self); InitEventHandlers(); end; end; end; procedure TclImap4FileHandler.SetSharedFolders(const Value: string); begin FAccessor.Enter(); try FSharedFolders := Value; finally FAccessor.Leave(); end; end; procedure TclImap4FileHandler.UpdateMailBoxInfo(const AMailBoxPath: string; AMailBox: TclImap4MailBoxItem); var store: TclImap4MailBoxStore; stream: TStream; begin store := nil; stream := nil; try store := TclImap4MailBoxStore.Create(AMailBox); stream := TFileStream.Create(AMailBoxPath, fmCreate); store.Save(stream); finally stream.Free(); store.Free(); end; end; procedure TclImap4FileHandler.UpdateMessageInfo(const AMsgInfoFile, AMessageFile: string; AFlags: TclMailMessageFlags; ADate: TDateTime); var storedMessages: TclImap4MessageList; store: TclImap4MessageStore; stream: TStream; storedItem: TclImap4MessageItem; begin storedMessages := nil; store := nil; stream := nil; try storedMessages := TclImap4MessageList.Create(); if (FileExists(AMsgInfoFile)) then begin store := TclImap4MessageStore.Create(storedMessages); stream := TFileStream.Create(AMsgInfoFile, fmOpenRead or fmShareDenyWrite); store.Load(stream); end; storedItem := storedMessages.FindByName(AMessageFile); if (storedItem = nil) then begin storedItem := TclImap4MessageItem.Create(AMessageFile); storedMessages.Add(storedItem); end; storedItem.Flags := AFlags; SetLocalFileTime(AMessageFile, ADate); stream.Free(); stream := nil; store.Free(); store := nil; stream := TFileStream.Create(AMsgInfoFile, fmCreate); store := TclImap4MessageStore.Create(storedMessages); store.Save(stream); finally stream.Free(); store.Free(); storedMessages.Free(); end; end; end.
///--// // Programa autoria de Miguel N.. Licensiado sobre a Apache License 2.0. Program CalculadoraCientifica; Uses Math; const pi = 3.1416; var tecla : integer; MAT_CALC, MAT_CALC_VOL_A, MAT_CALC_VOL_FINAL, MAT_VOL_FINAL, MAT_PYT_CALC, MAT_PYT_CALC_FINAL, MAT_SQR_FINAL, MAT_TRIG_sine, MAT_TRIG_cossine, MAT_TRIG_tangent, MAT_PHYSC_CALC_quicknessInKmPerHr : Real; MAT_SPH_raio, MAT_SPH_vol_FINAL, MAT_SUPER_raio, MAT_SUPER_FINAL, MAT_CIL_CALC_raio, MAT_CIL_CALC_FINAL, MAT_ARIT_CALC_FINAL, MAT_PYHS_CALC_FINAL, MAT_PHYS_CALC_quicknessInKmPerHr, MAT_PHYS_CALC_quicknessInMetersPerSec, MAT_PHYS_CALC_timeTakenInSeconds : real; MAT_lado1, MAT_lado2, MAT_VOL_baseLado1, MAT_VOL_baseLado2, MAT_VOL_Altura, MAT_PYT_cateto1, MAT_PYT_cateto2, MAT_PHYS_CALC_distInMetres, MAT_PHYS_timeTakenInSeconds : integer; MAT_TRIG_val1, MAT_SQR, MAT_SPH_diametro, MAT_SUPER_diametro, MAT_CIL_geratriz, MAT_CIL_diametro, MAT_ARIT_num1, MAT_ARIT_num2, MAT_PHYS_finalPos : integer; MAT_PHYS_initialPos, MAT_PHYS_dist, MAT_PHYS_timeTaken, ctrlVAR, usrchoice_LASTPROGRAM: integer; MAT_ARIT_OPER : char; repeater : string; Begin repeat Writeln('Bem-vindo á calculadora aritmética cientifica'); Writeln('===========MATEMÁTICA==================='); Writeln('As opções disponíveis são as seguintes: '); Writeln(' 1) Calcular a área do quadrado; '); Writeln(' 2) Calcular o volume do cubo; '); Writeln(' 3) Calcular a hipotenusa partir dos quadrados dos catetos (Teorema de Pitágoras) '); Writeln(' 4) Calcular o seno, tangente e cosseno de um número (Trigonometria) '); Writeln(' 5) Devolver o valor de PI '); Writeln(' 6) Devolver a raiz quadrada de um número '); Writeln(' 7) Caclular o volume de uma esfera '); Writeln(' 8) Calcular a área da superficie esférica '); Writeln(' 9) Calcular a área total de um cilindro '); Writeln(' 10) Cálculos aritméticos simples (Divisão, subtraccção, multiplicação e soma)' ); Writeln(' =============FÍSICA======================'); Writeln(' 11) Determinar o deslocamento escalar (pos. em segundos) '); Writeln(' 12) Determinar a rapidez média de um objeto '); Writeln(' 13) Calcular o valor da força resultante num corpo '); Writeln('Depois de apresentadas estas opções, escolha uma: '); Readln(tecla); // impossível usar readkey, tipos de dados seriam incompatíveis case tecla of 1: Begin clrscr; Writeln('1 - Calcular a área do quadrado.'); Delay(2000); Writeln('Introduza o primeiro lado: '); Read(MAT_lado1); Writeln('Introduza o segundo lado: '); Read(MAT_lado2); MAT_CALC := MAT_lado1 * MAT_lado2; Writeln('Área do quadrado: ', MAT_CALC:0:0, '.'); End; 2: Begin clrscr; Writeln('2 - Calcular o volume do cubo.'); Delay(2000); Writeln('Introduza o primeiro lado da base: '); Read(MAT_VOL_baseLado1); Writeln('Introduza o segundo lado da base: '); Read(MAT_VOL_baseLado2); Writeln('Introduza a altura do cubo: '); Read(MAT_VOL_Altura); MAT_CALC_VOL_A := MAT_VOL_baseLado1 * MAT_VOL_baseLado2; // calcular a área da base MAT_VOL_FINAL := MAT_CALC_VOL_A * MAT_VOL_Altura; // multiplicar a área da base pela altura Writeln('Volume do cubo: ', MAT_VOL_FINAL:0:0, 'cm3.'); Delay(2000); End; 3: Begin clrscr; Writeln('3 - Calcular a hipotenusa partir dos quadrados dos catetos (Teorema de Pitágoras).'); Delay(2000); Writeln('Introduza o primeiro cateto: '); Read(MAT_PYT_cateto1); Writeln('Introduza o segundo cateto: '); Read(MAT_PYT_cateto2); MAT_PYT_CALC := pow(MAT_PYT_cateto1, 2) + pow(MAT_PYT_cateto2, 2); MAT_PYT_CALC_FINAL := sqrt(MAT_PYT_CALC); Writeln('Hipotenusa do triângulo: ', MAT_PYT_CALC_FINAL:0:0, 'cm.'); Delay(2000); End; 4: Begin clrscr; Writeln('4 - Calcular o seno, tangente e cosseno de um número (Trigonometria).'); Delay(2000); Writeln('Introduza um número para o qual calcular os valores trigonométricos: '); Read(MAT_TRIG_val1); MAT_TRIG_sine := sin(MAT_TRIG_val1); MAT_TRIG_cossine := cos(MAT_TRIG_val1); MAT_TRIG_tangent := tan(MAT_TRIG_VAL1); Writeln('Seno de ', MAT_TRIG_val1, ': ', MAT_TRIG_sine, '.'); Writeln('Cosseno de ', MAT_TRIG_val1, ': ', MAT_TRIG_cossine, '.'); Writeln('Tangente de ', MAT_TRIG_val1, ': ', MAT_TRIG_tangent, '.'); Delay(2000); End; 5: Begin clrscr; Writeln('5 - Devolver o valor de PI.'); Delay(2000); Writeln('O valor de Pi é ', pi, '.'); Delay(2000); End; 6: Begin clrscr; Writeln('6 - Devolver a raiz quadrada de um número.'); Delay(2000); Writeln('Introduza um número: '); Read(MAT_SQR); MAT_SQR_FINAL := sqrt(MAT_SQR); Writeln('A raiz quadrada de ', MAT_SQR, ' é de ', MAT_SQR_FINAL:0:0, '.'); Delay(2000); End; 7: Begin clrscr; Writeln('7 - Calcular o volume de uma esfera.'); Delay(2000); Writeln('Introduza o diametro da esfera: '); Read(MAT_SPH_diametro); MAT_SPH_raio := MAT_SPH_diametro / 2; MAT_SPH_vol_FINAL := 4 / 3 * pi * pow(MAT_SPH_raio, 3); Writeln('O volume da esfera é de ', MAT_SPH_vol_FINAL:0:0, 'cm3.'); delay(2000); End; 8: Begin clrscr; Writeln('8 - Calcular a área da superficie esférica.'); Delay(2000); Writeln('Introduza o diametro da esfera: '); Read(MAT_SUPER_diametro); MAT_SUPER_raio := MAT_SUPER_diametro / 2; MAT_SUPER_FINAL := 4 * pi * sqr(MAT_SUPER_raio); Writeln('A área da superficie esférica é de ', MAT_SUPER_FINAL:0:0, 'cm2.'); Delay(2000); End; 9: Begin clrscr; Writeln('9 - Calcular a área total de um cilindro.'); Delay(2000); Writeln('Por favor introduza a geratriz do cilindro: '); Read(MAT_CIL_geratriz); Writeln('Por favor introduza o diâmetro da base do cilindro: '); Read(MAT_CIL_diametro); MAT_CIL_CALC_raio := MAT_CIL_diametro / 2; MAT_CIL_CALC_FINAL := 2 * pi * MAT_CIL_CALC_raio * MAT_CIL_geratriz + 2 * pi * sqr(MAT_CIL_CALC_raio); Writeln('A área total do cilindro é de ', MAT_CIL_CALC_FINAL:0:0, 'cm2.'); Delay(2000); End; 10: Begin Repeat clrscr; Writeln('10 - Cálculos aritméticos simples (Divisão, subtraccção, multiplicação e soma)'); Delay(2000); Writeln('Introduza um número: '); Read(MAT_ARIT_num1); Writeln('Introduza o operador desejado: '); Read(MAT_ARIT_OPER); Writeln('Introduza o segundo número: '); Read(MAT_ARIT_num2); case MAT_ARIT_OPER of '+': Begin MAT_ARIT_CALC_FINAL := MAT_ARIT_num1 + MAT_ARIT_num2; Writeln('Valor da soma desejada: ', MAT_ARIT_CALC_FINAL); Delay(2000); End; '-': Begin MAT_ARIT_CALC_FINAL := MAT_ARIT_num1 + MAT_ARIT_num2; Writeln('Valor da subtracção desejada: ', MAT_ARIT_CALC_FINAL); delay(2000); End; '*': Begin MAT_ARIT_CALC_FINAL := MAT_ARIT_num1 * MAT_ARIT_num2; Writeln('Valor da multiplicação desejada: ', MAT_ARIT_CALC_FINAL); delay(2000); End; '/': Begin MAT_ARIT_CALC_FINAL := MAT_ARIT_num1 / MAT_ARIT_num2; Writeln('Valor da divisão desejada: ', MAT_ARIT_CALC_FINAL); delay(2000); End else Begin ctrlVAR := 1; Writeln('Indroduziu um operador inválido! Por favor tente novamente.'); End; Delay(2000); End; until(ctrlVAR = 1); clrscr; End; 11: Begin clrscr; Writeln('11 - Determinar o deslocamento escalar (pos. em segundos).'); Delay(2000); Writeln('Introduza a posição final: '); Read(MAT_PHYS_finalPos); Writeln('Introduza a posição inicial: '); Read(MAT_PHYS_initialPos); MAT_PYHS_CALC_FINAL := MAT_PHYS_finalPos - MAT_PHYS_initialPos; Writeln('O deslocamento final é de ', MAT_PYHS_CALC_FINAL:0:0, 'm.'); End; 12: Begin clrscr; Writeln('12 - Determinar a rapidez média de um veículo.'); Delay(2000); Writeln('Introduza a distância percorrida pelo objeto, em quilometros (dispense do "km"): '); Read(MAT_PHYS_dist); Writeln('Introduza o tempo que esse objeto demorou a percorrer os ', MAT_PHYS_dist, 'km (em horas, dispense de "hr" ou "h"): '); Read(MAT_PHYS_timeTaken); MAT_PHYS_CALC_distInMetres := MAT_PHYS_dist * 1000; MAT_PHYS_CALC_timeTakenInSeconds := MAT_PHYS_timeTaken * 60 * 60; MAT_PHYS_CALC_quicknessInKmPerHr := MAT_PHYS_dist / MAT_PHYS_timeTaken; MAT_PHYS_CALC_quicknessInMetersPerSec := MAT_PHYS_CALC_distInMetres / MAT_PHYS_timeTakenInSeconds; Writeln('Rapidez média do objeto: ', MAT_PHYSC_CALC_quicknessInKmPerHr, 'km/h OU ', MAT_PHYS_CALC_quicknessInMetersPerSec, 'm/s. '); End; else Begin Writeln('Erro! Introduziu uma opção invalida! Tente novamente.'); Delay(2000); End; End; clrscr; Writeln('Repetir? 1 - SIM | 2 - NAO'); repeater := readkey; if(repeater = '2') then Begin Writeln('Interrompendo...'); halt(0); End; until(repeater <> '2'); Readkey; End.
{ Subroutine SST_R_SYN_DOIT (FNAM, GNAM, STAT) * * Process one top level SYN language input file. FNAM is the input file name. * GNAM is returned as the generic name of FNAM. Each call to this routine * adds to the single module that was created when this SST front end was * initialized (SST_R_SYN_INIT called). } module sst_r_syn_doit; define sst_r_syn_doit; %include 'sst_r_syn.ins.pas'; procedure sst_r_syn_doit ( {do SYN language front end phase} in fnam: univ string_var_arg_t; {raw input file name} in out gnam: univ string_var_arg_t; {returned as generic name of input file} out stat: sys_err_t); {completion status code} var fline_p: fline_p_t; {to FLINE library use state} coll_p: fline_coll_p_t; {the input file lines in FLINE collection} match: boolean; {syntax matched} data_p: symbol_data_p_t; {pointer to our data in hash table entry} undefined_syms: boolean; {TRUE if undefined symbols found} unused_syms: boolean; {TRUE after first unused symbol encountered} label loop_cmd, eod; { ******************************************************************************** * * Local subroutine FOLLOW_SYM (DATA) * * Propagate USED flag to all symbols ultimately referenced by the syntax * construction with the symbol table data DATA. } procedure follow_sym ( in data: symbol_data_t); {data about symbol to follow} val_param; var call_p: call_p_t; {points to data about called symbol} begin data.sym_p^.flags := {set FOLLOWED flag to prevent recursive calls} data.sym_p^.flags + [sst_symflag_followed_k]; call_p := data.call_p; {init to first entry in called chain} while call_p <> nil do begin {once for each entry in called chain} call_p^.data_p^.sym_p^.flags := {set USED flag} call_p^.data_p^.sym_p^.flags + [sst_symflag_used_k]; if not (sst_symflag_followed_k in call_p^.data_p^.sym_p^.flags) then begin follow_sym (call_p^.data_p^); {follow this nested symbol} end; call_p := call_p^.next_p; {advance to next called symbol in list} end; end; { ******************************************************************************** * * Start of main routine. } begin string_generic_fnam (fnam, '.syn', gnam); {make generic input file name} string_copy (gnam, prefix); {use generic name as subroutine prefix} { * Read the input file into a collection of text lines managed by the FLINE * library. COLL_P will be set pointing to the collection. } fline_lib_new ( {open the FLINE library} util_top_mem_context, {parent memory context} fline_p, {returned pointer to new library use state} stat); if sys_error(stat) then return; fline_file_get_suff ( {read the input file into a collection} fline_p^, {FLINE library use state} fnam, '.syn', {file name and mandatory suffix} coll_p, {returned pointer to the collection} stat); if sys_error(stat) then return; syn_parse_pos_coll (syn_p^, coll_p^); {init parse position to start of collection} { * Main loop. Come back here each new command in the SYN file. This loop * terminates either on an error or end of data. } loop_cmd: match := syn_parse_next ( {parse next command from input file} syn_p^, {our SYN library use state} addr(syn_chsyn_command)); {top level parsing routine to call} if not match then begin {syntax error encountered ?} syn_parse_err_reparse (syn_p^); {do error re-parse} end; syn_trav_init (syn_p^); {init for traversing syntax tree} sst_r_syn_command (stat); {process this SYN file command} if sys_stat_match (sst_subsys_k, sst_stat_eod_k, stat) {hit end of input data ?} then goto eod; if sys_error(stat) then return; {encountered hard error ?} if not match then begin {syntax error not caught as content error ?} syn_parse_err_show (syn_p^); {show the syntax error} sys_stat_set ( {indicate error, already handled} sst_subsys_k, sst_stat_err_handled_k, stat); return; {return with error condition} end; goto loop_cmd; {back for next command from SYN file} eod: {reached end of all input data} { * End of input data encountered. * * Propagate used flags to all appropriate SYN file symbols. } sst_r_syn_sym_loop_init; {init for looping over symbol table entries} while sst_r_syn_sym_loop_next (data_p) do begin if {this symbol used but not followed yet ?} (sst_symflag_used_k in data_p^.sym_p^.flags) and (not (sst_symflag_followed_k in data_p^.sym_p^.flags)) then begin follow_sym (data_p^); {propagate USED flag for this symbol} end; end; {back to process next symbol table entry} { * List any unused SYN symbols and clear FOLLOWED flags left from previous * pass over all the symbols. } unused_syms := false; {init to no unused symbols found} sst_r_syn_sym_loop_init; {init for looping over symbol table entries} while sst_r_syn_sym_loop_next (data_p) do begin data_p^.sym_p^.flags := {clear FOLLOWED flag} data_p^.sym_p^.flags - [sst_symflag_followed_k]; if {this symbol was never used ?} not (sst_symflag_used_k in data_p^.sym_p^.flags) then begin if not unused_syms then begin {this is first unused symbol ?} sys_message ('sst_syn_read', 'symbols_unused_show'); unused_syms := true; {flag that unused symbols were encountered} end; writeln (' ', data_p^.name_p^.str:data_p^.name_p^.len); {show unused symbol} end; end; {back to process next symbol table entry} { * Check for undefined SYN symbols. } undefined_syms := false; {init to no undefined symbols found} sst_r_syn_sym_loop_init; {init for looping over symbol table entries} while sst_r_syn_sym_loop_next (data_p) do begin if {used but undefined symbol ?} (sst_symflag_used_k in data_p^.sym_p^.flags) and {symbol used ?} (not (sst_symflag_def_k in data_p^.sym_p^.flags)) and {not defined here?} (not (sst_symflag_extern_k in data_p^.sym_p^.flags)) {not external ?} then begin if not undefined_syms then begin {this is first undefined symbol ?} sys_message ('sst_syn_read', 'symbols_undefined_show'); undefined_syms := true; {flag that undefined symbols were encountered} end; writeln (' ', data_p^.name_p^.str:data_p^.name_p^.len); {show undefined symbol} end; end; {back to process next symbol table entry} sst_r_syn_sym_delete; {delete symbol table, release its resources} if undefined_syms then begin {some undefined symbols were found ?} sys_message_bomb ('sst_syn_read', 'symbols_undefined_abort', nil, 0); end; end;
unit ImageButton; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs; type TButtonType = (btButton, btCheckBox, btSwitch); { TImageButton } TImageButton = class(TGraphicControl) private FButtonState: Integer; FBuffer: Array of TBitmap; FButtonType: TButtonType; FChecked: Boolean; FOnChange: TNotifyEvent; FOnClick: TNotifyEvent; FPicture: TPicture; FDown: Boolean; FSwitchCount: Integer; FSwitchIndex: Integer; procedure SetButtonType(AValue: TButtonType); procedure SetChecked(AValue: Boolean); procedure SetPicture(AValue: TPicture); procedure SetSwitchCount(AValue: Integer); procedure SetSwitchIndex(AValue: Integer); protected procedure PrepareBuffer; procedure Paint; override; procedure DoOnPictureChange(Sender: TObject); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Resize; override; procedure UpdateButtonState; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property ButtonType: TButtonType read FButtonType write SetButtonType default btButton; property Checked: Boolean read FChecked write SetChecked default False; property Picture: TPicture read FPicture write SetPicture; property SwitchCount: Integer read FSwitchCount write SetSwitchCount default 1; property SwitchIndex: Integer read FSwitchIndex write SetSwitchIndex default 0; property OnClick: TNotifyEvent read FOnClick write FOnClick; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; procedure Register; implementation procedure Register; begin RegisterComponents('Loader',[TImageButton]); end; { TImageButton } procedure TImageButton.SetButtonType(AValue: TButtonType); begin if FButtonType=AValue then Exit; FButtonType:=AValue; PrepareBuffer; UpdateButtonState; end; procedure TImageButton.SetChecked(AValue: Boolean); begin if FChecked=AValue then Exit; FChecked:=AValue; UpdateButtonState; end; procedure TImageButton.SetPicture(AValue: TPicture); begin FPicture.Assign(AValue); end; procedure TImageButton.SetSwitchCount(AValue: Integer); begin if AValue<1 then AValue:=1; if FSwitchCount=AValue then Exit; FSwitchCount:=AValue; PrepareBuffer; Invalidate; end; procedure TImageButton.SetSwitchIndex(AValue: Integer); begin if AValue<0 then AValue:=0; if AValue>FSwitchCount-1 then AValue:=FSwitchCount-1; if FSwitchIndex=AValue then Exit; FSwitchIndex:=AValue; if FButtonType=btSwitch then UpdateButtonState; end; procedure TImageButton.PrepareBuffer; var Count:Integer; I:Integer; begin //remove old for I:=0 to Length(FBuffer)-1 do FBuffer[I].Free; //image count case FButtonType of btButton: Count:=4; btCheckBox: Count:=4; btSwitch: Count:=FSwitchCount; end; //init images SetLength(FBuffer, Count); for I:=0 to Count-1 do begin FBuffer[I]:=TBitmap.Create; FBuffer[I].Width:=Width; FBuffer[I].Height:=Height; FBuffer[I].Canvas.Draw(0,-Height*I,FPicture.Graphic); end; end; procedure TImageButton.Paint; begin Canvas.Draw(0,0,FBuffer[FButtonState]); end; procedure TImageButton.DoOnPictureChange(Sender: TObject); begin PrepareBuffer; Invalidate; end; procedure TImageButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FDown:=True; UpdateButtonState; end; procedure TImageButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FDown:=False; if Enabled then begin if FButtonType=btCheckBox then begin FChecked:=not FChecked; if Assigned(FOnChange) then FOnChange(Self); end else if FButtonType=btSwitch then begin Inc(FSwitchIndex); if FSwitchIndex>FSwitchCount-1 then FSwitchIndex:=0; if Assigned(FOnChange) then FOnChange(Self); end; if Assigned(FOnClick) then FOnClick(Self); end; UpdateButtonState; end; procedure TImageButton.Resize; begin PrepareBuffer; end; procedure TImageButton.UpdateButtonState; var State: Integer; begin case FButtonType of btButton: begin if not Enabled then begin State:=2; end else if FDown then begin State:=1; end else begin State:=0; end; end; btCheckBox: begin if not Enabled then begin State:=3; end else if FDown then begin State:=2; end else if FChecked then begin State:=1; end else begin State:=0; end; end; btSwitch: begin State:=FSwitchIndex; end; end; if State=FButtonState then Exit; FButtonState:=State; Invalidate; end; constructor TImageButton.Create(AOwner: TComponent); begin inherited Create(AOwner); FPicture:=TPicture.Create; FDown:=False; FButtonType:=btButton; FChecked:=False; FSwitchCount:=1; FSwitchIndex:=0; FPicture.OnChange:=@DoOnPictureChange; UpdateButtonState; end; destructor TImageButton.Destroy; var I:Integer; begin FPicture.Free; for I:=0 to Length(FBuffer)-1 do FBuffer[I].Free; inherited Destroy; end; end.
unit SettingsForma; interface {$I defines.inc} uses Vcl.Menus, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, Vcl.ComCtrls, Vcl.Mask, System.Classes, Vcl.Forms, Winapi.Windows, System.SysUtils, System.Variants, Vcl.Graphics, Vcl.Dialogs, FIBQuery, pFIBQuery, OkCancel_frame, FIBDataSet, pFIBDataSet, DBCtrlsEh, PrjConst, FIBDatabase, pFIBDatabase, DBGridEh, DBLookupEh; type TSettingsForm = class(TForm) Query: TpFIBQuery; OkCancelFrame1: TOkCancelFrame; select: TpFIBDataSet; pgSettings: TPageControl; tsPayment: TTabSheet; cbPaymentSrv: TCheckBox; cbNegativePay: TCheckBox; cbCreatePayDoc: TCheckBox; lbl1: TLabel; edtBC: TEdit; btnBarSettings: TButton; cbFine: TCheckBox; grpFine: TGroupBox; Label6: TLabel; Label7: TLabel; Label5: TLabel; FinePercent: TDBNumberEditEh; FineMonth: TDBNumberEditEh; FineDay: TDBNumberEditEh; btnCashReg: TButton; tsLAN: TTabSheet; Label10: TLabel; cbBilling: TDBComboBoxEh; tsGlobal: TTabSheet; tsVisual: TTabSheet; chkBalansSaldo: TCheckBox; Label1: TLabel; FEE: TDBNumberEditEh; cbPersonalTarrif: TCheckBox; Label2: TLabel; DOLG: TDBNumberEditEh; pnl1: TPanel; Label15: TLabel; lstSettings: TListBox; clrbxDolg: TColorBox; clrbxOFF: TColorBox; Label19: TLabel; Label20: TLabel; pnlBilling: TPanel; Label12: TLabel; BillIP: TDBEditEh; Label11: TLabel; BillPort: TDBNumberEditEh; billSSL: TCheckBox; Label13: TLabel; BillLogin: TDBEditEh; Label14: TLabel; billPass: TDBEditEh; lblPP: TLabel; edtRP: TDBNumberEditEh; chkAddTarif: TCheckBox; grpDisc: TGroupBox; Label16: TLabel; Label17: TLabel; Label18: TLabel; ed3M: TDBNumberEditEh; ed6M: TDBNumberEditEh; ed12M: TDBNumberEditEh; chkPayDiscount: TCheckBox; chkIPTVPacket: TCheckBox; tsComm: TTabSheet; gbMail: TGroupBox; lbl2: TLabel; lbl5: TLabel; Label21: TLabel; Label22: TLabel; grp1: TGroupBox; chkEMAIL_REQ: TCheckBox; pnlSMSUtils: TPanel; pnlSMSPhone: TPanel; pnlSMS: TPanel; lbl3: TLabel; cbSMStype: TDBComboBoxEh; lbl4: TLabel; MainMenu1: TMainMenu; edtCOM: TDBNumberEditEh; lbl6: TLabel; PopupMenu1: TPopupMenu; edtSMcommand: TEdit; pnlSMSAdd: TPanel; chkSMSLAT: TCheckBox; lbl8: TLabel; edtSMSLen: TDBNumberEditEh; grpLS: TGroupBox; chkDOG: TCheckBox; Label3: TLabel; AccNumber: TDBNumberEditEh; lblORDER: TLabel; edtORDER: TDBEditEh; pmLS: TPopupMenu; btnCodeLS: TButton; btnInetSettings: TButton; lbl7: TLabel; edReqTime: TDateTimePicker; chkBARDELZERRO: TCheckBox; lbl9: TLabel; clrbxOFFMONEY: TColorBox; chkBARADDPAY: TCheckBox; chkIgnoreDate: TCheckBox; tsA4ON: TTabSheet; edtA4Login: TDBEditEh; edtA4APIkey: TDBEditEh; Label4: TLabel; lbl10: TLabel; cbFormat: TDBComboBoxEh; lbl11: TLabel; chkConfirmReceipt: TDBCheckBoxEh; cbSSLType: TDBComboBoxEh; chkCopyToMe: TDBCheckBoxEh; edtSmtpPort: TDBNumberEditEh; lbl12: TLabel; cbAuth: TDBComboBoxEh; lbl13: TLabel; lbl14: TLabel; edSMTP: TDBEditEh; edtEMAIL: TDBEditEh; edtSMTPLogin: TDBEditEh; edtSMTPpass: TDBEditEh; cbbRates: TDBComboBoxEh; lblRates: TLabel; tsMobile: TTabSheet; lbl16: TLabel; edtGMAPI: TDBEditEh; btnGoApi: TButton; chkShowAllInCustomer: TCheckBox; chkHidePayAdd: TCheckBox; chkHidePayPrint: TCheckBox; chkBidNotice: TCheckBox; tsEquipment: TTabSheet; dsServices: TpFIBDataSet; srcCardAdd: TDataSource; trRead: TpFIBTransaction; srcCardDel: TDataSource; grpSrv: TGroupBox; cbbCardDel: TDBLookupComboboxEh; cbbCardAdd: TDBLookupComboboxEh; chkPersChennals: TCheckBox; chkPersPackets: TCheckBox; chkVlanRequired: TCheckBox; lbl18: TLabel; dsRQtype: TpFIBDataSet; cbbRQ_TO_POSITIVE: TDBLookupComboboxEh; srcRQtype: TDataSource; lbl19: TLabel; edtSUM_POSITIVE: TDBNumberEditEh; chkAddressEdit: TCheckBox; tsOther: TTabSheet; Label8: TLabel; edtPswdExpire: TDBNumberEditEh; grp2: TGroupBox; lbl17: TLabel; lbl15: TLabel; edtPhFmt: TDBEditEh; edtMphFmt: TDBEditEh; grp3: TGroupBox; lbl20: TLabel; lbl21: TLabel; edtCheckPassportN: TDBEditEh; edtCheckPersN: TDBEditEh; chkWHOwner: TCheckBox; chkWHExecutor: TCheckBox; lbl22: TLabel; edtIdleHoure: TDBNumberEditEh; chkComplex: TCheckBox; chkStrictMode: TCheckBox; lbl23: TLabel; edtKeyMVD: TDBEditEh; lbl24: TLabel; edtMapUrl: TDBEditEh; chkRWD: TCheckBox; chkLANAddr: TCheckBox; chkDelLanEq: TCheckBox; procedure BillIPExit(Sender: TObject); procedure OkCancelFrame1bbOkClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnCashRegClick(Sender: TObject); procedure billPassChange(Sender: TObject); procedure cbBillingChange(Sender: TObject); procedure btnBarSettingsClick(Sender: TObject); procedure cbFineClick(Sender: TObject); procedure chkPayDiscountClick(Sender: TObject); procedure lstSettingsClick(Sender: TObject); procedure cbSMStypeChange(Sender: TObject); procedure btnCodeLSClick(Sender: TObject); procedure btnInetSettingsClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnGoApiClick(Sender: TObject); private { Private declarations } FLastAccount: integer; FPassChanged: boolean; FPageList: TStrings; // procedure SaveBilling; function CheckCashReg: boolean; function CheckInternetSetting: boolean; function CashRegSettings: boolean; procedure SaveSettingsStr(const name: string; const value: string = ''); procedure SaveSettingsInt(const name: string; const value: integer = 0); procedure SaveSettingsBoolean(const name: string; const chBox: TCheckBox); overload; procedure SaveSettingsBoolean(const name: string; const chBox: TDBCheckBoxEh); overload; procedure SaveSettingsBoolean(const name: string; const Checked: Boolean); overload; procedure miClick(Sender: TObject); function Internet: boolean; public { Public declarations } end; var SettingsForm: TSettingsForm; implementation uses DM, AtrStrUtils, BarSettingForma, ibase, synacode, atrCmdUtils; type TCashSettingsDialog = function(AppHandle: THandle; OPER: PWChar; OPER_PASS: PWChar): integer; stdcall; TDLLInternetSetting = function(DBName: PWChar; UserName: PWChar; Password: PWChar): integer; StdCall; {$R *.dfm} procedure TSettingsForm.SaveSettingsStr(const name: string; const value: string = ''); begin Query.SQL.Text := 'execute procedure set_settings(:name, :value)'; Query.Transaction.StartTransaction; Query.ParamByName('name').AsString := name; Query.ParamByName('value').AsString := value; Query.ExecQuery; Query.Transaction.Commit; end; procedure TSettingsForm.SaveSettingsBoolean(const name: string; const Checked: Boolean); begin if Checked then SaveSettingsStr(name, '1') else SaveSettingsStr(name, '0'); end; procedure TSettingsForm.SaveSettingsBoolean(const name: string; const chBox: TCheckBox); begin SaveSettingsBoolean(name, chBox.Checked); end; procedure TSettingsForm.SaveSettingsBoolean(const name: string; const chBox: TDBCheckBoxEh); begin SaveSettingsBoolean(name, chBox.Checked); end; procedure TSettingsForm.SaveSettingsInt(const name: string; const value: integer = 0); var s: string; begin try s := IntToStr(value); except s := '0'; end; SaveSettingsStr(name, s); end; { procedure TSettingsForm.SaveBilling; var s: string; begin SaveSettingsInt('USED_BILLING', cbBilling.value); SaveSettingsStr('BILLING_IP', BillIP.value); SaveSettingsInt('BILLING_PORT', BillPort.value); if not VarIsClear(edtRP.value) then SaveSettingsInt('UTM_RP_ID', edtRP.value) else begin Query.SQL.Text := 'execute procedure set_settings(''' + name + ''', '''')'; Query.Transaction.StartTransaction; Query.ExecQuery; Query.Transaction.Commit; end; SaveSettingsStr('BILLING_LOGIN', BillLogin.value); try s := billPass.value; except s := ''; end; if PassChanged then s := EncodeBase64(s); SaveSettingsStr('BILLING_SECRET', s); if billSSL.Checked then s := '1' else s := '0'; SaveSettingsStr('BILLING_SSL', s); if chkAddTarif.Checked then s := '1' else s := '0'; SaveSettingsStr('BILLING_TP', s); end; } procedure TSettingsForm.cbBillingChange(Sender: TObject); var i: integer; begin i := cbBilling.value; pnlBilling.Visible := not(i in [0, 3]); billSSL.Visible := (i = 2); chkAddTarif.Visible := (i = 2); edtRP.Visible := (i = 2); lblPP.Visible := (i = 2); end; procedure TSettingsForm.cbFineClick(Sender: TObject); begin FinePercent.Enabled := cbFine.Checked; FineMonth.Enabled := cbFine.Checked; FineDay.Enabled := cbFine.Checked; end; procedure TSettingsForm.cbSMStypeChange(Sender: TObject); begin pnlSMSPhone.Visible := (cbSMStype.value = 1); pnlSMSUtils.Visible := (cbSMStype.value = 2); pnlSMSAdd.Visible := (cbSMStype.value <> 0); end; procedure TSettingsForm.BillIPExit(Sender: TObject); begin if (Sender as TDBEditEh).Text = '' then Exit; if not CheckIP((Sender as TDBEditEh).Text) then begin ShowMessage(rsIPIncorrect); (Sender as TDBEditEh).SetFocus; end; end; procedure TSettingsForm.billPassChange(Sender: TObject); begin FPassChanged := True; end; procedure TSettingsForm.btnBarSettingsClick(Sender: TObject); begin With TBarSettingForm.Create(application) do begin CodeType := 0; BarCodeFormat := edtBC.Text; if showmodal = mrOk then edtBC.Text := BarCodeFormat; end; end; procedure TSettingsForm.btnCashRegClick(Sender: TObject); begin CashRegSettings; end; procedure TSettingsForm.btnCodeLSClick(Sender: TObject); begin With TBarSettingForm.Create(application) do begin CodeType := 1; BarCodeFormat := edtORDER.Text; if showmodal = mrOk then edtORDER.Text := BarCodeFormat; end; end; procedure TSettingsForm.btnGoApiClick(Sender: TObject); var s: string; begin s := 'https://developers.google.com/maps/documentation/javascript/get-api-key#key'; atrCmdUtils.ShellExecute(application.MainForm.Handle, '', s); end; procedure TSettingsForm.btnInetSettingsClick(Sender: TObject); begin Internet; end; procedure TSettingsForm.OkCancelFrame1bbOkClick(Sender: TObject); var i, j: integer; s: string; cr: TCursor; begin cr := Screen.Cursor; Screen.Cursor := crSQLWait; try if (dmMain.AllowedAction(rght_Programm_Settings)) then begin // saveBilling; SaveSettingsStr('A4LOGIN', edtA4Login.Text); SaveSettingsStr('A4APIKEY', edtA4APIkey.Text); SaveSettingsStr('FORMATN', cbFormat.Text); SaveSettingsStr('REG_PASSN', edtCheckPassportN.Text); SaveSettingsStr('REG_PERSN', edtCheckPersN.Text); SaveSettingsStr('KEY_MVD', edtKeyMVD.Text); SaveSettingsStr('MAP_URL', edtMapUrl.Text); SaveSettingsInt('FEE_ROUND', FEE.value); SaveSettingsInt('DOLG', DOLG.value); SaveSettingsInt('PSWD_EXPIRE', edtPswdExpire.value); SaveSettingsInt('IDLEHOURS', edtIdleHoure.value); SaveSettingsStr('BARCODE', edtBC.Text); SaveSettingsBoolean('BARNODELZERRO', chkBARDELZERRO); SaveSettingsBoolean('BARADDPAY', chkBARADDPAY); SaveSettingsBoolean('SHOWALLCUSTPAYS', chkShowAllInCustomer); SaveSettingsBoolean('HIDEPAYADD', chkHidePayAdd); SaveSettingsBoolean('HIDEPAYPRINT', chkHidePayPrint); SaveSettingsBoolean('BIDEDITNOTICE', chkBidNotice); SaveSettingsStr('SMTP', edSMTP.Text); SaveSettingsStr('SMTP_PORT', edtSmtpPort.Text); SaveSettingsStr('SMTP_LOGIN', edtSMTPLogin.Text); SaveSettingsStr('SMTP_PASS', edtSMTPpass.Text); SaveSettingsStr('EMAIL', edtEMAIL.Text); SaveSettingsStr('SMTP_AUTH', cbAuth.Text); SaveSettingsStr('SMTP_SSL', cbSSLType.Text); SaveSettingsStr('PHONE_FMT', edtPhFmt.Text); SaveSettingsStr('MOBILE_FMT', edtMphFmt.Text); if VarIsNull(cbbRates.value) then SaveSettingsStr('RATES_BANK', 'CBR') else SaveSettingsStr('RATES_BANK', cbbRates.value); SaveSettingsStr('GMAPI', edtGMAPI.Text); SaveSettingsBoolean('SMTP_2ME', chkCopyToMe); SaveSettingsBoolean('SMTP_CONF', chkConfirmReceipt); SaveSettingsStr('REQUEST_NEXT_DAY_TIME', FormatDateTime('hh:nn:ss', edReqTime.DateTime)); SaveSettingsBoolean('REQUEST_SKIP_WEEKEND', chkRWD); SaveSettingsStr('COLOR_DOLG', ColorToString(clrbxDolg.Selected)); SaveSettingsStr('COLOR_OFF', ColorToString(clrbxOFF.Selected)); SaveSettingsStr('COLOR_OFFMONEY', ColorToString(clrbxOFFMONEY.Selected)); SaveSettingsBoolean('EMAIL_REQ', chkEMAIL_REQ); SaveSettingsBoolean('PERSONEL_TARIF', cbPersonalTarrif); SaveSettingsBoolean('COMPLEX', chkComplex); SaveSettingsBoolean('IGNORE_CONTRACT', chkIgnoreDate); SaveSettingsBoolean('STRICT_MODE', chkStrictMode); SaveSettingsBoolean('IPTV_PACKET', chkIPTVPacket); SaveSettingsBoolean('VLAN_REQUIRED', chkVlanRequired); SaveSettingsBoolean('LAN_ADDRES', chkLANAddr); SaveSettingsBoolean('LAN_DELEQPMNT', chkDelLanEq); SaveSettingsBoolean('PAYMENT_SRV', cbPaymentSrv); SaveSettingsBoolean('NEGATIVE_PAY', cbNegativePay); SaveSettingsStr('ACCOUNT_FORMAT', edtORDER.Text); SaveSettingsBoolean('ACCOUNT_DOG', chkDOG); if FLastAccount <> AccNumber.value then begin try i := AccNumber.value; s := IntToStr(i); Query.SQL.Text := 'SET GENERATOR GEN_ACCOUNT_NO TO ' + s; Query.Transaction.StartTransaction; Query.ExecQuery; Query.Transaction.Commit; except s := '0'; end; end; // пеня SaveSettingsBoolean('SHOW_FINE', cbFine); try j := FinePercent.value * 100; i := j mod 100; j := j div 100; s := IntToStr(j) + '.' + IntToStr(i); except s := '0'; end; SaveSettingsStr('FINE_PERCENT', s); SaveSettingsInt('FINE_DAYS', FineDay.value); try s := IntToStr(FineMonth.value); except s := '1'; end; SaveSettingsStr('FINE_MONTH', s); SaveSettingsBoolean('CREATE_PD', cbCreatePayDoc); SaveSettingsBoolean('SHOW_AS_BALANCE', chkBalansSaldo); SaveSettingsBoolean('PAY_DISCOUNT', chkPayDiscount); try j := ed3M.value * 10000; i := j mod 10000; j := j div 10000; s := IntToStr(j) + '.' + IntToStr(i); except s := '1'; end; SaveSettingsStr('DISCOUNT_3', s); try j := ed6M.value * 10000; i := j mod 10000; j := j div 10000; s := IntToStr(j) + '.' + IntToStr(i); except s := '1'; end; SaveSettingsStr('DISCOUNT_6', s); try j := ed12M.value * 10000; i := j mod 10000; j := j div 10000; s := IntToStr(j) + '.' + IntToStr(i); except s := '1'; end; SaveSettingsStr('DISCOUNT_12', s); if VarIsNull(cbbCardAdd.KeyValue) then SaveSettingsStr('CARD_ADD_SRV', '') else SaveSettingsStr('CARD_ADD_SRV', cbbCardAdd.KeyValue); if VarIsNull(cbbCardDel.KeyValue) then SaveSettingsStr('CARD_DEL_SRV', '') else SaveSettingsStr('CARD_DEL_SRV', cbbCardDel.KeyValue); if VarIsNull(cbbRQ_TO_POSITIVE.KeyValue) then SaveSettingsStr('RQ_TO_POSITIVE', '') else SaveSettingsStr('RQ_TO_POSITIVE', cbbRQ_TO_POSITIVE.KeyValue); if (edtSUM_POSITIVE.Text = '') then SaveSettingsStr('RQ_SUM_POSITIVE', '0') else SaveSettingsStr('RQ_SUM_POSITIVE', edtSUM_POSITIVE.value); SaveSettingsBoolean('PERS_CHANNEL', chkPersChennals); SaveSettingsBoolean('PERS_PACKETS', chkPersPackets); SaveSettingsBoolean('EX_ADDRESS_EDIT', chkAddressEdit); SaveSettingsBoolean('WH_REQ_OWNER', chkWHOwner); SaveSettingsBoolean('WH_REQ_EXECUTOR', chkWHExecutor); dmMain.GetSettingsValue('ReloadSettingsFromDB'); end; except ModalResult := mrNone; end; Screen.Cursor := cr; end; function TSettingsForm.CheckInternetSetting: boolean; var CashSettingsDialog: TDLLInternetSetting; // TInternetSetting; HLib: THandle; begin result := False; if FileExists(ExtractFilePath(application.ExeName) + 'internet.dll') then begin HLib := 0; try HLib := LoadLibrary('internet.dll'); if HLib > HINSTANCE_ERROR then begin CashSettingsDialog := GetProcAddress(HLib, 'Settings'); if Assigned(CashSettingsDialog) then result := True; end finally if HLib > HINSTANCE_ERROR then FreeLibrary(HLib); end; end end; function TSettingsForm.CheckCashReg: boolean; var CashSettingsDialog: TCashSettingsDialog; HLib: THandle; begin result := False; if FileExists(ExtractFilePath(application.ExeName) + 'cashrgst.dll') then begin HLib := 0; try HLib := LoadLibrary('cashrgst.dll'); if HLib > HINSTANCE_ERROR then begin CashSettingsDialog := GetProcAddress(HLib, 'CashSettingsDialog'); if Assigned(CashSettingsDialog) then result := True; end finally if HLib > HINSTANCE_ERROR then FreeLibrary(HLib); end; end end; procedure TSettingsForm.chkPayDiscountClick(Sender: TObject); begin ed3M.Enabled := chkPayDiscount.Checked; ed6M.Enabled := chkPayDiscount.Checked; ed12M.Enabled := chkPayDiscount.Checked; end; function TSettingsForm.CashRegSettings: boolean; var CashSettingsDialog: TCashSettingsDialog; HLib: THandle; i: integer; OPER: string; begin // напечатаем чек result := False; if FileExists(ExtractFilePath(application.ExeName) + 'cashrgst.dll') then begin HLib := 0; try HLib := LoadLibrary('cashrgst.dll'); if HLib > HINSTANCE_ERROR then begin CashSettingsDialog := GetProcAddress(HLib, 'CashSettingsDialog'); if Assigned(CashSettingsDialog) then begin OPER := dmMain.GetOperatorFIO; i := CashSettingsDialog(application.Handle, PWChar(OPER), PWChar(dmMain.CashBoxPSWD)); result := (i > 0); // показали диалог end else ShowMessage(Format(rsErrorDll, ['cashrgst.dll'])); end else ShowMessage(Format(rsErrorLoadDll, ['cashrgst.dll'])); finally if HLib > HINSTANCE_ERROR then FreeLibrary(HLib); end; end end; procedure TSettingsForm.FormClose(Sender: TObject; var Action: TCloseAction); begin FPageList.Free; dsServices.Close; dsRQtype.Close; end; procedure TSettingsForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then OkCancelFrame1bbOkClick(Sender); end; procedure TSettingsForm.FormShow(Sender: TObject); var f: TFormatSettings; s: string; i: integer; Global: boolean; val: TStringArray; begin dsServices.Open; dsRQtype.Open; FPageList := TStringList.Create(); Global := True; lstSettings.Items.Clear; for i := 0 to pgSettings.PageCount - 1 do begin pgSettings.Pages[i].TabVisible := False; pgSettings.Pages[i].Visible := Global; if pgSettings.Pages[i].name = tsLAN.name then begin {$IFDEF LAN} tsLAN.Visible := Global; {$ELSE} tsLAN.Visible := False; {$ENDIF} end; if pgSettings.Pages[i].Visible then begin FPageList.Add(IntToStr(i)); lstSettings.Items.Add(pgSettings.Pages[i].Caption); end; end; lstSettings.ItemIndex := 0; pgSettings.ActivePageIndex := 0; btnCashReg.Visible := CheckCashReg; btnInetSettings.Visible := CheckInternetSetting; cbBilling.value := 0; if Global then begin select.Open; cbPersonalTarrif.Checked := False; chkPersPackets.Checked := True; for i := 0 to ComponentCount - 1 do if Components[i] is TDBNumberEditEh then (Components[i] as TDBNumberEditEh).value := 0; while not select.Eof do begin if AnsiUpperCase(select.FN('VAR_NAME').value) = 'STRICT_MODE' then chkStrictMode.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'A4LOGIN' then edtA4Login.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'A4APIKEY' then edtA4APIkey.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'FORMATN' then cbFormat.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'REG_PASSN' then edtCheckPassportN.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'REG_PERSN' then edtCheckPersN.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'KEY_MVD' then edtKeyMVD.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'MAP_URL' then edtMapUrl.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'FEE_ROUND' then FEE.value := select.FN('VAR_VALUE').AsInteger; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'DOLG' then DOLG.value := select.FN('VAR_VALUE').AsInteger; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'PERSONEL_TARIF' then cbPersonalTarrif.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'COMPLEX' then chkComplex.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'IGNORE_CONTRACT' then chkIgnoreDate.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'IPTV_PACKET' then chkIPTVPacket.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'VLAN_REQUIRED' then chkVlanRequired.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'LAN_ADDRES' then chkLANAddr.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'LAN_DELEQPMNT' then chkDelLanEq.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'PAYMENT_SRV' then cbPaymentSrv.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'ACCOUNT_FORMAT' then edtORDER.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'ACCOUNT_DOG' then chkDOG.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'PERS_CHANNEL' then chkPersChennals.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'PERS_PACKETS' then chkPersPackets.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'EX_ADDRESS_EDIT' then chkAddressEdit.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'WH_REQ_OWNER' then chkWHOwner.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'PSWD_EXPIRE' then edtPswdExpire.value := select.FN('VAR_VALUE').AsInteger; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'IDLEHOURS' then edtIdleHoure.value := select.FN('VAR_VALUE').AsInteger; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'WH_REQ_EXECUTOR' then chkWHExecutor.Checked := (select.FN('VAR_VALUE').AsInteger = 1); // пеня if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SHOW_FINE' then cbFine.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'FINE_PERCENT' then begin s := select.FN('VAR_VALUE').AsString; f.DecimalSeparator := '.'; FinePercent.value := StrToFloat(s, f); end; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'FINE_DAYS' then FineDay.value := select.FN('VAR_VALUE').AsInteger; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'BARCODE' then edtBC.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'BARNODELZERRO' then chkBARDELZERRO.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'BARADDPAY' then chkBARADDPAY.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SHOWALLCUSTPAYS' then chkShowAllInCustomer.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'HIDEPAYADD' then chkHidePayAdd.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'HIDEPAYPRINT' then chkHidePayPrint.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'BIDEDITNOTICE' then chkBidNotice.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'FINE_MONTH' then FineMonth.value := select.FN('VAR_VALUE').AsInteger; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'CREATE_PD' then cbCreatePayDoc.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'NEGATIVE_PAY' then cbNegativePay.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SHOW_AS_BALANCE' then chkBalansSaldo.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'PAY_DISCOUNT' then chkPayDiscount.Checked := (select.FN('VAR_VALUE').AsInteger = 1); chkPayDiscountClick(Sender); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'DISCOUNT_3' then begin s := select.FN('VAR_VALUE').AsString; f.DecimalSeparator := '.'; ed3M.value := StrToFloat(s, f); end; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'DISCOUNT_6' then begin s := select.FN('VAR_VALUE').AsString; f.DecimalSeparator := '.'; ed6M.value := StrToFloat(s, f); end; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'DISCOUNT_12' then begin s := select.FN('VAR_VALUE').AsString; f.DecimalSeparator := '.'; ed12M.value := StrToFloat(s, f); end; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'PHONE_FMT' then edtPhFmt.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'MOBILE_FMT' then edtMphFmt.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'RATES_BANK' then cbbRates.value := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'GMAPI' then edtGMAPI.Text := select.FN('VAR_VALUE').AsString; // email if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SMTP' then edSMTP.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SMTP_LOGIN' then edtSMTPLogin.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'EMAIL' then edtEMAIL.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SMTP_PASS' then edtSMTPpass.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SMTP_PORT' then edtSmtpPort.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SMTP_AUTH' then cbAuth.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SMTP_SSL' then cbSSLType.Text := select.FN('VAR_VALUE').AsString; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SMTP_2ME' then chkCopyToMe.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'SMTP_CONF' then chkConfirmReceipt.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'EMAIL_REQ' then chkEMAIL_REQ.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'COLOR_DOLG' then clrbxDolg.Selected := StringToColor(select.FN('VAR_VALUE').AsString); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'COLOR_OFF' then clrbxOFF.Selected := StringToColor(select.FN('VAR_VALUE').AsString); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'COLOR_OFFMONEY' then clrbxOFFMONEY.Selected := StringToColor(select.FN('VAR_VALUE').AsString); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'REQUEST_NEXT_DAY_TIME' then edReqTime.DateTime := StrToDateTime(select.FN('VAR_VALUE').AsString); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'REQUEST_SKIP_WEEKEND' then chkRWD.Checked := (select.FN('VAR_VALUE').AsInteger = 1); if AnsiUpperCase(select.FN('VAR_NAME').value) = 'CARD_ADD_SRV' then begin if (TryStrToInt(select.FN('VAR_VALUE').AsString, i)) then cbbCardAdd.KeyValue := i; end; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'CARD_DEL_SRV' then begin if (TryStrToInt(select.FN('VAR_VALUE').AsString, i)) then cbbCardDel.KeyValue := i; end; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'RQ_TO_POSITIVE' then begin if (TryStrToInt(select.FN('VAR_VALUE').AsString, i)) then cbbRQ_TO_POSITIVE.KeyValue := i; end; if AnsiUpperCase(select.FN('VAR_NAME').value) = 'RQ_SUM_POSITIVE' then begin if (TryStrToInt(select.FN('VAR_VALUE').AsString, i)) then edtSUM_POSITIVE.value := i; end; select.Next; end; FPassChanged := False; select.Close; select.SQLs.SelectSQL.Text := 'select gen_id(GEN_ACCOUNT_NO,0) as accN from rdb$database'; select.Open; FLastAccount := select.FN('accN').AsInteger; AccNumber.value := FLastAccount; select.Close; val := Explode(';', ls_fields); pmLS.Items.Clear; for i := 0 to Length(val) - 1 do begin pmLS.Items.Add(NewItem(val[i], 0, False, True, miClick, 0, 'mils' + IntToStr(i))); end; end; {$IFNDEF DEMOVERSION} edtA4Login.Enabled := True; edtA4APIkey.Enabled := True; {$ENDIF} end; procedure TSettingsForm.miClick(Sender: TObject); begin if (Sender is TMenuItem) then (ActiveControl as TDBEditEh).Text := (ActiveControl as TDBEditEh).Text + (Sender as TMenuItem).Caption; end; procedure TSettingsForm.lstSettingsClick(Sender: TObject); begin pgSettings.ActivePageIndex := StrToInt(FPageList.Strings[lstSettings.ItemIndex]); end; function TSettingsForm.Internet: boolean; var CashSettingsDialog: TDLLInternetSetting; HLib: THandle; i: integer; s: string; begin // настройки интернет биллинга result := False; if FileExists(ExtractFilePath(application.ExeName) + 'internet.dll') then begin HLib := 0; try HLib := LoadLibrary('internet.dll'); if HLib > HINSTANCE_ERROR then begin CashSettingsDialog := GetProcAddress(HLib, 'Settings'); if Assigned(CashSettingsDialog) then begin s := dmMain.Server; s := s + ':' + dmMain.Database; i := CashSettingsDialog(PWChar(s), PWChar(dmMain.USER), PWChar(dmMain.Password)); result := (i > 0); // показали диалог end else ShowMessage(Format(rsErrorDll, ['Internet.dll'])); end else ShowMessage(Format(rsErrorLoadDll, ['Internet.dll'])); finally if HLib > HINSTANCE_ERROR then FreeLibrary(HLib); end; end end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TForm1 } TForm1 = class(TForm) Button1: TButton; ListBox1: TListBox; procedure Button1Click(Sender: TObject); private public end; var Form1: TForm1; implementation uses FileUtil; {$R *.lfm} { TForm1 } procedure TForm1.Button1Click(Sender: TObject); const c: array[boolean] of string = ('MISSED', 'found'); var L: TStringList; dir, S: string; b: boolean; fnd: integer; begin dir:= ExtractFileDir(ExtractFileDir(Application.ExeName)); Listbox1.Items.Clear; Listbox1.Items.Add('Find all files/dirs in '+dir); L:= TStringList.Create; try FindAllFiles(L, dir, '', True); fnd:= 0; for S in L do begin b:= FileExists(S); if b then Inc(fnd) else Listbox1.Items.Add(S+': '+c[b]); end; Listbox1.Items.Add('FileExists ok: '+Inttostr(fnd)); L.Clear; FindAllDirectories(L, dir); fnd:= 0; for S in L do begin b:= DirectoryExists(S); if b then Inc(fnd) else Listbox1.Items.Add(S+': '+c[b]); end; Listbox1.Items.Add('DirExists ok: '+Inttostr(fnd)); finally L.Free; end; end; end.
{$I tdl_dire.inc} {$IFDEF USEOVERLAYS} {$O+,F+} {$ENDIF} unit tdl_cach; { Encapsulates title file/data cache functionality into an object. The title cache is the base directory where titles are uncompressed into before they can be launched. } interface uses tdl_glob, strings, objects, DOS; type PFileCache=^TFileCache; TFileCache=object(TObject) Constructor Init(cachepath:string); Destructor Done; virtual; {Refresh free space stats. DOS can take up to 15+ seconds on very slow systems to refresh this number, so by breaking it out, we might be able to hide it. Can use bytesFree and megsFree for cached referencing.} Function Remaining:longint; Function EstimateCacheUsage(filetype:ExtStr;filepath:PathStr):longint; {title cache directory functions} Function CDir(tf:PFileStruct):PathStr; Function CDirExists(tf:PFileStruct):boolean; public path:PathStr; bytesFree:longint; megsFree:word; private {Some functions need the number of the cache's drive letter: 0 = current drive, 1=A:, 2=B:, 3=C:, etc.} cacheDriveNum:byte; end; implementation uses tdl_conf, support; Constructor TFileCache.Init; begin Inherited Init; path:=cachePath; {Create the cache dir if it doesn't exist} if not DirExists(path) then begin MkDirCDir(path); if not DirExists(path) then fatalerror(2,'Creation of '+path+' failed'); end; {ensure cache path is fully qualified and sanitized (ends with "\")} path:=StdPath(FExpand(path)); cacheDriveNum:=byte(upcase(path[1]))-64; end; Destructor TFileCache.done; begin Inherited Done; end; Function TFileCache.Remaining; begin bytesFree:=diskfree(cacheDriveNum); megsFree:=bytesFree div (1024*1024); Remaining:=bytesFree; end; Function TFileCache.EstimateCacheUsage; { This attempts to estimate how much cache we'll need to store an extracted title. The minimum number returned is the size of available free RAM, in case all of RAM needs to be swapped to disk to execute the title. If the title is a compressed file we can deal with, then determine the total uncompressed size needed, rounding each file upward to the DOS cluster amount so that the number is accurate. } var dosclustersize:word; estimate:longint; f:file; {===========================================================================} Function RoundToNearestCluster(l:longint):longint; var rounded:longint; begin rounded:=(l + (DOSClusterSize-1)) AND NOT longint(DOSClusterSize-1); RoundToNearestCluster:=rounded; end; {=========================ZIP file support routines=========================} Function GetZipUncompSizeCluster:longint; const pkzip_local_header_sig=$04034B50; pkzip_central_header_sig=$02014B50; type pkzip_local_header=record ZIPLOCSIG:longint; {Local File Header Signature} ZIPVER :word; {Version needed to extract } ZIPGENFLG:word; {General purpose bit flag } ZIPMTHD :word; {Compression method } ZIPTIME :word; {Last mod file time (MS-DOS)} ZIPDATE :word; {Last mod file date (MS-DOS)} ZIPCRC :longint; {CRC-32 } ZIPSIZE :longint; {Compressed size } ZIPUNCMP :longint; {Uncompressed size } ZIPFNLN :word; {Filename length } ZIPXTRALN:word; {Extra field length } end; var plr:pkzip_local_header; s:string; l:longint; numread:word; begin assign(f,filepath); reset(f,1); l:=0; while not eof(f) do begin blockread(f,plr,sizeof(plr),numread); {if we hit the end of the file, bail out} if numread<sizeof(plr) then exit; {if we hit the central header, we're done reading filenames} if plr.ziplocsig=pkzip_central_header_sig then break; {if we didn't read a local signature, something's wrong, keep going} if plr.ziplocsig<>pkzip_local_header_sig then continue; l:=l+RoundToNearestCluster(plr.zipuncmp); {seek to next local header} seek(f,filepos(f)+plr.zipsize+plr.zipfnln+plr.zipxtraln); end; close(f); GetZipUncompSizeCluster:=l end; {===========================================================================} begin {detemine DOS cluster size} DOSClusterSize:=clustsize(cacheDriveNum); {start with maximum amount of diskspace needed to swap out all of RAM} estimate:=RoundToNearestCluster(config^.freeLowDOSRAM); {If there's an easy way to estimate uncompressed size, do it} if filetype='ZIP'then begin estimate:=estimate+GetZipUncompSizeCluster; end else begin {not something we recognize, so assume we'll need 1x the space for it} estimate:=estimate+RoundToNearestCluster(sizeoffile(filepath)); end; EstimateCacheUsage:=estimate; end; Function TFileCache.cDir(tf:PFileStruct):PathStr; begin {must NOT have trailing slash due to chdir() assumption/limitation} cDir:=path+basename(tf^.name) end; Function TFileCache.cDirExists(tf:PFileStruct):boolean; begin if dirExists(cdir(tf)) then cDirExists:=true else cDirExists:=false; end; end.
unit a3unit; { This unit contains a sample solution to assignment 2 which has been expanded to allow AVL tree insertion. The insert procedure has been modified to call a private procedure named "rebalance" that restores the AVL property. This procedure updates the balance fields from the new node upwards and performs rotations if necessary. The rotations are performed using the procedures "RotateClockwise" and "RotateCounterClockwise". Your job is to write the "Rebalance" procedure. See the code below for more details. UPDATED: June 6, 1999 to fix the rebalancing in the rotation procedures } interface uses btadt; { ******************* TYPE DEFINITIONS ******************* } type { Since we are using the BinaryTree ADT, all we have to do here is relate the main types for collections to the main types for binary trees. } collection_element = TreeElement; collection = BinaryTree; procedure Create(var C:collection); procedure Destroy(var C:collection); function Size(C: collection): integer; function Is_Empty(C:collection): boolean; procedure Insert(var C:collection; V:collection_element); procedure Delete (var C:collection; V: collection_element); procedure Join(var C1: collection; var C2: collection); procedure Print(C: collection); function MemCheck: boolean; implementation { ********************* Memory Management Stuff ******************** } {Note that since all the memory management is done by BinTrADT, we just have to call the MemCheck_BT function here} Function MemCheck; begin MemCheck := MemCheck_BT end; { ******************** COLLECTION IMPLEMENTATIONS ********************* } { Create(C) preconditions: C is undefined postconditions: C is the empty collection with storage allocated as needed. } procedure Create(var C:collection); { Constant Time O(1) } begin Create_Empty_BT(C); end; { Destroy(C) preconditions: C is a defined collection postconditions: C' is undefined. All dynamically allocated memory } procedure Destroy(var C:collection); { Linear Time O(n) } begin Destroy_BT(C); end; { Is_Empty(C) preconditions: C is a defined collection. postconditions: returns true if C is empty, false otherwise. } function Is_Empty(C:collection): boolean; { Constant Time O(1) } begin Is_Empty := Is_Empty_BT(C); end; { Size(C) preconditions: C is a defined collection. postconditions: returns the number of elements in C. } function Size(C: collection): integer; { Linear Time O(n) } begin If Is_Empty(C) then Size := 0 else Size := 1 + Size(LeftChild_BT(C))+ Size(RightChild_BT(C)); end; { PRIVATE Procedure RotateClockWise(Root) Pre: Root is the root of a subtree tree to be rotated Post: A single clockwise rotation has been performed using the Root as a pivot. If Root had a parent then the parent's child pointer is updated. If Root had no parent, then Root now points to the rotator. The Balance fields of the Pivot and Rotator are updated accordingly. } Procedure RotateClockWise(var Root:BinaryTree); var Pivot, PivotsParent, InsideSubtree, Rotator: BinaryTree; HasParent: Boolean; PivotSide: Direction; begin Pivot := Root; Rotator := LeftChild_BT(Pivot); If Is_Empty_BT(Rotator) then writeln('ERROR - tried to rotate clockwise with no rotator') else begin { IDENTIFY THE RELEVANT NODES AND SUBTREES } PivotsParent := Parent_BT(Pivot); HasParent := not Is_Empty_BT(PivotsParent); { Remember whether or not the pivot had a parent} If HasParent then PivotSide := Which_Side_BT(Pivot); { Remember which side the pivot was on} InsideSubtree := RightChild_BT(Rotator); { STEPS 1 to 3 - PRUNE PIVOT, ROTATOR, and INSIDE SUBTREE } If HasParent then Prune_BT(Pivot); Prune_BT(Rotator); if not Is_Empty_BT(InsideSubtree) then Prune_BT(InsideSubtree); { STEPS 4 to 6 - REATTACH } if HasParent then Attach_BT(Rotator,PivotsParent,PivotSide) else Root := Rotator; { If root had no parent, update the pointer instead } Attach_BT(InsideSubtree,Pivot,left); Attach_BT(Pivot,Rotator,right) end; { UPDATE BALANCE FIELDS OF PIVOT AND ROTATOR - this can be done based on the previous value of the rotator's balance field. The possible values are 1, 0, -1, and -2. If the Rotator did have a balance of -2, then this must be the second rotation of a double rotation. IMPORTANT - These rebalancing operations are not totally independent. I am assuming you are always doing the correct rotations.} If Get_Balance_Field_BT(Rotator) = -1 then begin If Get_Balance_Field_BT(Pivot) = -2 then begin { NEW STUFF HERE } Set_Balance_Field_BT(Rotator,0); Set_Balance_Field_BT(Pivot,0) end else begin Set_Balance_Field_BT(Rotator,1); Set_Balance_Field_BT(Pivot,1); { END NEW STUFF } end end else if Get_Balance_Field_BT(Rotator) = 1 then begin Set_Balance_Field_BT(Rotator,2); Set_Balance_Field_BT(Pivot,0) end else if Get_Balance_field_BT(Rotator) = 0 then begin if Get_Balance_Field_BT(Pivot) = 2 then begin { NEW STUFF HERE } Set_Balance_Field_BT(Rotator,1); Set_Balance_Field_BT(Pivot,-1) end else begin Set_Balance_Field_BT(Rotator,1); Set_Balance_Field_BT(Pivot,0); { END NEW STUFF } end end else begin { Must be the second of a double rotation } Set_Balance_Field_BT(Rotator,0); Set_Balance_Field_BT(Pivot,1); end end; { PRIVATE Procedure RotateCounterClockwise(Root) Pre: Root is the root of a subtree tree to be rotated Post: A single counter-clockwise rotation has been performed using the Root as a pivot. If Root had a parent then the parent's child pointer is updated. If Root had no parent, then Root now points to the rotator. The Balance fields of the Pivot and Rotator are updated accordingly. } Procedure RotateCounterClockWise(var Root:BinaryTree); var Pivot, PivotsParent, InsideSubtree, Rotator: BinaryTree; HasParent: Boolean; PivotSide: Direction; begin Pivot := Root; Rotator := RightChild_BT(Pivot); If Is_Empty_BT(Rotator) then writeln('ERROR - tried to rotate counter-clockwise with no rotator') else begin { IDENTIFY THE RELEVANT NODES AND SUBTREES } PivotsParent := Parent_BT(Pivot); HasParent := not Is_Empty_BT(PivotsParent); { Remember whether or not the pivot had a parent} If HasParent then PivotSide := Which_Side_BT(Pivot); { Remember which side the pivot was on} InsideSubtree := LeftChild_BT(Rotator); { STEPS 1 to 3 - PRUNE PIVOT, ROTATOR, and INSIDE SUBTREE } If HasParent then Prune_BT(Pivot); Prune_BT(Rotator); if not Is_Empty_BT(InsideSubtree) then Prune_BT(InsideSubtree); { STEPS 4 to 6 - REATTACH } if HasParent then Attach_BT(Rotator,PivotsParent,PivotSide) else Root := Rotator; { If root had no parent, update the pointer instead } Attach_BT(InsideSubtree,Pivot,right); Attach_BT(Pivot,Rotator,left) end; { UPDATE BALANCE FIELDS OF PIVOT AND ROTATOR - this can be done based on the previous value of the rotator's balance field. The possible values are 1, 0, -1, and 2. If the Rotator did have a balance of 2, then this must be the second rotation of a double rotation. IMPORTANT - These rebalancing operations are not totally independent. I am assuming you are always doing the correct rotations.} If Get_Balance_Field_BT(Rotator) = 1 then begin If Get_Balance_Field_BT(Pivot)=2 then begin { NEW STUFF HERE } Set_Balance_Field_BT(Rotator,0); Set_Balance_Field_BT(Pivot,0) end else begin Set_Balance_Field_BT(Rotator,-1); Set_Balance_Field_BT(Pivot,-1) { END NEW STUFF } end end else if Get_Balance_Field_BT(Rotator) = -1 then begin Set_Balance_Field_BT(Rotator,-2); Set_Balance_Field_BT(Pivot,0) end else if Get_Balance_Field_BT(Rotator) = 0 then begin if Get_Balance_Field_BT(Pivot) = 2 then begin { NEW STUFF HERE } Set_Balance_Field_BT(Rotator,-1); Set_Balance_Field_BT(Pivot,1) end else begin Set_Balance_Field_BT(Rotator,-1); Set_Balance_Field_BT(Pivot,0); { END NEW STUFF } end end else begin { Must be the second of a double rotation } Set_Balance_Field_BT(Rotator,0); Set_Balance_Field_BT(Pivot,-1); end end; { PRIVATE Procedure Rebalance(NewNode, Root) pre: NewNode is a new leaf node just added to the tree. Root is the root of the entire tree. post: The tree is rebalanced as an AVL tree, and all the balance fields of the nodes are updated appropriately. Root points to the new root of the tree. NOTE: To give you some ideas, I have included the comments and local variables from my implementation. But you are free to use your own variables and/or algorithm if you want. } Procedure Rebalance(NewNode:BinaryTree; var Root:BinaryTree); var Finished, { Indicates whether loop is finished } Rotate, { Indicates whether a rotation should be performed } HasNoParent: Boolean; { Indicates whether pivot has a parent } Pivot, { Pivot for main rotation } Rotator, { Rotator for main rotation } Parent: BinaryTree; { Parent of current node in while loop } begin { STEP 1: Update the balance fields Method: a. Set NewNode's Balance field to 0 b. Traverse the parent pointers, updating the balance fields as you go (e.g. if NewNode was the left child of its parent, you should subtract one from the parents balance field. c. If a node (other than NewNode) becomes perfectly balanced, then stop. No rotation is necessary. d. If you reach the top of the tree without any nodes becoming unbalanced, then stop. No rotation is necessary. e. If a node becomes unbalanced (balance field set to 2 or -2, then stop. Rotations must be performed in the next step. In this case, remember the node that became unbalanced - it will be the pivot for the main rotation.} { **** STEP 1 CODE GOES HERE **** } Set_Balance_Field_BT(NewNode, 0); Finished := false ; while not Finished do BEGIN Parent := Parent_BT(NewNode) ; if which_side_BT(NewNode) = left then Set_Balance_Field_BT(Parent, (Get_Balance_Field_BT(Parent) - 1)) else Set_Balance_Field_BT(Parent, (Get_Balance_Field_BT(Parent) + 1)); if is_empty(Parent_BT(parent)) then finished := true ; if abs(Get_Balance_Field_BT(Parent)) = 1 then Rotate := false else if abs(Get_Balance_Field_BT(Parent)) = 0 then BEGIN Rotate := false ; Finished := true END else { Balance = +-2 } BEGIN Rotate := true ; Finished := true END ; NewNode := Parent END; { while } { STEP 2: Perform rotation if necessary Method: a. Check to see if the pivot has a parent. IF not, you will have to change the root value after the rotations. b. If the pivot got the value -2, then the rotator will be the left child. If the rotator is right heavy, then a double rotation is necessary - first counter-clockwise, then clockwise. If not, then a single clockwise rotation will do. Call the given procedures to do the rotations. They will update the balance fields for you. Don't forget to update the root of the tree if necessary - the value it gets will depend on whether you do a single or double rotation. c. If the pivot got the value 2, do the mirror image of part b.} { **** STEP 2 CODE GOES HERE *** } if Rotate then BEGIN Pivot := NewNode ; if is_empty(Parent_BT(Pivot)) then HasNoParent := true else HasNoParent := false ; if Get_Balance_Field_BT(Pivot) = -2 then BEGIN Rotator := LeftChild_BT(Pivot) ; if Get_Balance_Field_BT(Rotator) = 1 then RotateCounterClockwise(Rotator) ; RotateClockwise(Pivot) ; if HasNoParent then Root := Pivot END { if } else BEGIN Rotator := RightChild_BT(Pivot) ; if Get_Balance_Field_BT(Rotator) = -1 then RotateClockwise(Rotator) ; RotateCounterClockwise(Pivot) ; if HasNoParent then Root := Pivot END { else } END { Step 2 } end; { proc Rebalance } { Insert(C,V) preconditions: C is a defined collection, V is a collection element. postconditions: C has value V added. Storage is allocated as needed. If V already occurs in C an additional copy is added. NOTE: This procedure contains the non-recursive insertion routine from the assignment 2 solution, but it has been modified to call the tree rebalancing routines when necessary. IN THIS IMPLEMENTATION, DUPLICATES GO INTO THE LEFT SUBTREE } procedure Insert(var C:collection; V:collection_element); var TempTree, NewTree, UnbalancedTree: BinaryTree; done: boolean; HeavySide: Direction; begin If Is_Empty(C) then begin { Check the empty case first } Create_Singleton_BT(C); Set_Root_Value_BT(C, V); Set_Balance_Field_BT(C,0); {NEW: SET BALANCE FIELD } end else begin TempTree := C; { Otherwise start the tree traversal } done := false; repeat if Get_Root_Value_BT(TempTree) < V then begin { If root < V, go right } if Is_Empty(RightChild_BT(TempTree)) then begin { If no right tree, insert here } Create_Singleton_BT(NewTree); Set_Root_Value_BT(NewTree,V); Attach_BT(NewTree,TempTree,Right); Rebalance(NewTree,C); { NEW: REBALANCE TREE } done := true end else begin { Otherwise, traverse the right tree } TempTree := RightChild_BT(TempTree) end end else begin if Is_Empty(LeftChild_BT(TempTree)) then begin { If root >= V, go left } Create_Singleton_BT(NewTree); { If no left tree, insert here } Set_Root_Value_BT(NewTree,V); Attach_BT(NewTree,TempTree,Left); Rebalance(NewTree,C); { NEW: REBALANCE TREE } done := true end else begin { Otherwise, traverse the left tree } TempTree := LeftChild_BT(TempTree) end end until done; end end; {insert} { Delete(C,V) preconditions: C is a defined collection, V is a collection element postconditions: C has the value V removed. If V occurs more than once, only one occurrence is removed. If V does not occur in C, no change is made. NOTE: This procedure has been disabled. If you want to try to write an AVL delete, then go for it! } procedure Delete (var C:collection; V: collection_element); begin Writeln('*** AVL Deletion Not Implemented') end; { Join(C1,C2) preconditions: C1 and C2 are two different defined collections. postconditions: C1 is the union of the two collections (i.e. it contains all the elements originally in C1 and C2). C2 is undefined. } procedure Join(var C1: collection; var C2: collection); { O(m log n) where m is size of C2, n is size of C1 } var LTree, RTree: BinaryTree; begin if not Is_Empty(C2) then begin {If C2 is empty, do nothing} If Is_Empty(C1) then begin {If C1 is empty, just point it to C2} C1 := C2; end else begin Insert(C1, Get_Root_Value_BT(C2)); {Insert the root value of C2 into C1} LTree := LeftChild_BT(C2); {Prune off the left and right subtrees of C2} RTree := RightChild_BT(C2); Prune_BT(LTree); Prune_BT(RTree); Destroy_Singleton_BT(C2); {Destroy the root node of C2} Join(C1, Ltree); {Recursively join C1 to the left and right} Join(C1, Rtree); { subtrees of C2 } end; end end; { Print(C1) preconditions: C1 is a defined collection. postconditions: The elements in C1 are printed to the screen in any order. If C1 is empty, the message "EMPTY COLLECTION" is printed to the screen. NOTE: The print could be done in any order, but to help you out, it prints in alphabetical order using an InOrder traversal. It also makes use of a nested subprocedure (Print_Rec). This subprocedure is hidden from all other parts of the program. } procedure Print(C: Collection); { Linear time O(n) } procedure Print_Rec(C: Collection); begin if not Is_Empty(C) then begin Print_Rec(LeftChild_BT(C)); Writeln(Get_Root_Value_BT(C)); PRint_Rec(RightChild_BT(C)) end end; begin if Is_Empty(C) then writeln('Empty Collection') else Print_Rec(C) end; { ************************** IDENTIFICATION ************************ } { Change this procedure to identify yourself } procedure IdentifyMyself; begin writeln; writeln('***** Student Name: Mark Sattolo'); writeln('***** Student Number: 428500'); writeln('***** Professor Name: Sam Scott'); writeln('***** Course Number: CSI-2114D'); writeln('***** T.A. Name: Adam Murray'); writeln('***** Tutorial Number: D-1'); writeln; end; { ****************** INITIALIZATION CODE ******************** } { this must be placed at the end of the TPU file. If you want to initialize other globals, you may do so by adding code to this section } Begin IdentifyMyself; end.
unit np.json; interface uses sysUtils, Generics.Collections; type TJSONType = (json_null, json_int, json_text, json_object, json_array, json_boolean); TJSONPair = class; TJSONArray = TObjectList<TJSONPair>; TJSONObject = TDictionary<String,TJSONPair>; PSearchControl = ^TSearchControl; TSearchControl = record level : Cardinal; state : (cNormal,cStopLevel,cStopAll); end; TJSONPairClass = class of TJSONPair; TJSONTypes = set of TJSONType; TJSONPair = class private FArray : TJSONArray; FObject : TJSONObject; function GetAsBoolean: Boolean; function GetAsObject(const Key: String): TJSONPair; procedure OnObjectNotify(Sender: TObject; const Item: TJSONPair; Action: TCollectionNotification); procedure OnArrayNotify(Sender: TObject; const Item: TJSONPair; Action: TCollectionNotification); procedure SetAsBoolean(const Value: Boolean); procedure SetAsObject(const Key: String; const Value: TJSONPair); function GetAsInteger: int64; procedure SetAsInteger(const Value: int64); function GetAsString: String; function InternalToString(sb : TStringBuilder ) : integer; procedure SetAsString(const Value: String); function GetAsArray(i: integer): TJSONPair; procedure SetAsArray(i: integer; const Value: TJSONPair); public name : string; typeIs : TJSONType; IsString : String; IsInteger : int64; owner : TJSONPair; // FJSONPairClass : TJSONPairClass; constructor Create(const Value: string); overload; destructor Destroy; override; procedure Clear; function count : integer; procedure Increment; function Parse(const JSON : string;var I : integer) : TJSONPair; overload; function Parse(const JSON : string): TJSONPair; overload; function find(const s : array of string; out AResult: TJSONPair) : Boolean; procedure forAll( proc : TProc<TJSONPair,PSearchControl>; control: PSearchControl ); function IsNull : Boolean; function Clone : TJSONPair; procedure assign( pair : TJSONPair; overrideName : Boolean = true; aDelete: Boolean = false); function IsEmpty : Boolean; class function EncodeJSONText(const s: string): string; static; class function DecodeJSONText(const JSON : string): string; overload; static; class function DecodeJSONText(const JSON : string; var Index: Integer): string; overload; static; function ToString : string; override; function CreateJSONPair: TJSONPair; virtual; function IsArray : TJSONArray; function IsObject : TJSONObject; // function save(out v : TJSONPair) : TJSONPair; property AsInteger: int64 read GetAsInteger write SetAsInteger; property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean; property AsObject[const Key: String]: TJSONPair read GetAsObject write SetAsObject; default; property AsArray[i : integer] : TJSONPair read GetAsArray write SetAsArray; property AsString: String read GetAsString write SetAsString; end; const ValueTypes : TJSONTypes = [json_null, json_boolean, json_int, json_text]; implementation constructor TJSONPair.Create(const Value: string); begin Parse(Value); end; function TJSONPair.CreateJSONPair: TJSONPair; type TJSONPairClass = class of TJSONPair; begin result := TJSONPairClass( self.ClassType ).Create; end; { TJSONPair } //constructor TJSONPair.Create( Parent : TJSONPair; theType : TJSONType); //begin // typeIs //end; function TJSONPair.Clone: TJSONPair; var I : Integer; enum : TJSONPair; begin result := CreateJSONPair; result.name := name; case typeIs of json_int: result.AsInteger := AsInteger; json_text: result.AsString := AsString; json_boolean: result.AsBoolean := AsBoolean; json_array: begin for i := 0 to Count-1 do result.AsArray[i] := AsArray[i].Clone; end; json_object: begin for enum in IsArray do result.AsObject[enum.name] := enum.Clone; end; end; end; function TJSONPair.IsEmpty : Boolean; var child : TJSONPair; begin case typeIs of json_object, json_array: begin for child in IsArray do if not child.IsEmpty then exit(false); exit(true); end; json_null: exit(true); else exit(false); end; end; function TJSONPair.count: integer; begin if assigned(FArray) then result := FArray.Count else result := 0; end; destructor TJSONPair.Destroy; begin if assigned(owner) and assigned(owner.FArray) then owner.FArray.Extract(self); Clear; if assigned(FArray) then FArray.OnNotify := nil; if assigned(FObject) then FObject.OnValueNotify := nil; FreeAndNil(FArray); FreeAndNil(FObject); inherited; end; procedure TJSONPair.assign(pair: TJSONPair; overrideName : Boolean; Adelete : Boolean); var s : String; begin if not assigned(pair) then begin Clear; exit; end; S := pair.ToString; if Adelete then freeAndNil(pair); Parse(s); end; procedure TJSONPair.Clear; begin IsString := ''; IsInteger := 0; typeIs := json_null; if assigned(FObject) then FObject.Clear; if assigned(FArray) then FArray.Clear; end; class function TJSONPair.DecodeJSONText(const JSON : string; var Index: Integer): string; var L : Integer; SkipMode : Boolean; begin result := ''; if Index < 1 then Index := 1; SkipMode := true; L := Length(JSON); While (Index<=L) DO BEGIN case JSON[Index] of '"': begin Inc(Index); //Skip rigth " if not SkipMode then break; skipMode := false; end; #0..#$1f: INC(Index);//ignore '\': begin if Index+1 <= L then begin case JSON[Index+1] of '"','\','/' : begin if not skipMode then Result := Result + JSON[Index+1]; INC(Index,2); end; 'u': begin if not skipMode then Result := Result + char(word( StrToIntDef('$'+copy(JSON,Index+2,4),ord('?')) )); INC(Index,6); end; 'b': begin if not skipMode then Result := Result + #8; INC(Index,2); end; 'f': begin if not skipMode then Result := Result + #12; INC(Index,2); end; 'n': begin if not skipMode then Result := Result + #10; INC(Index,2); end; 'r': begin if not skipMode then Result := Result + #13; INC(Index,2); end; 't': begin if not skipMode then Result := Result + #9; INC(Index,2); end; else INC(Index,2); //Ignore end; end; end; else begin if not skipMode then Result := Result + JSON[Index]; INC(Index); end; end; END; end; class function TJSONPair.DecodeJSONText(const JSON : string): string; var i : integer; begin i := 1; Result := TJSONPair.DecodeJSONText(JSON,i); end; function TJSONPair.GetAsArray(i: integer): TJSONPair; begin if (i < 0) or (i = maxInt) then i := count; case typeIs of json_boolean, json_int, json_text, json_null: begin result := Clone; asArray[i] := result; end; json_array,json_object: begin if i < IsArray.Count then exit(isArray[i]) else begin result := CreateJSONPair; asArray[i] := result end; end; else begin assert(false); result := nil; end; end; end; function TJSONPair.GetAsBoolean: Boolean; begin case typeIs of json_boolean, json_int: exit(IsInteger <> 0); json_text: exit( IsString = 'true'); json_null: exit(false); else result := (Count > 0); end; end; function TJSONPair.GetAsInteger: int64; begin case typeIs of json_null: exit(0); json_int: exit(IsInteger); json_text: begin if not TryStrToInt64(IsString, result) then exit(0); end; else begin if Count > 0 then exit(FArray[0].AsInteger) else exit(0); end; end; end; function TJSONPair.GetAsObject(const Key: String): TJSONPair; begin if (typeIs <> json_object) or not IsObject.TryGetValue(Key,result) then begin result := CreateJSONPair; asObject[Key] := result; end; end; function TJSONPair.GetAsString: String; begin case typeIs of // json_null: // exit(''); json_boolean: if AsBoolean then Exit('true') else exit('false'); json_int: exit(IntToStr(IsInteger)); json_text: exit(IsString); else // else // if (Count > 0) then // exit(IsArray[0].AsString) // else exit(''); end; end; procedure TJSONPair.Increment; begin AsInteger := AsInteger + 1; end; function TJSONPair.IsArray: TJSONArray; begin if not Assigned(FArray) then begin FArray := TJSONArray.Create; FArray.OnNotify := OnArrayNotify; end; result := FArray; end; function TJSONPair.IsObject: TJSONObject; begin if not Assigned(FObject) then begin FObject := TJSONObject.Create; FObject.OnValueNotify := OnObjectNotify; end; result := FObject; end; function TJSONPair.IsNull: Boolean; begin result := typeIs = json_null; end; //function TJSONPair.save(out v: TJSONPair): TJSONPair; //begin // result := self; // v := self; //end; procedure TJSONPair.OnObjectNotify(Sender: TObject; const Item: TJSONPair; Action: TCollectionNotification); begin if (Action = cnRemoved) and Assigned(FArray) then FArray.Remove(Item) end; function TJSONPair.Parse(const JSON: string; var I: integer) : TJSONPair; VAR L : INTEGER; J:INTEGER; K,V: String; begin result := self; if I < 1 then I := 1; Clear; L := Length(JSON); While I<=L DO BEGIN CASE JSON[I] OF '{': begin INC(I); repeat K := DecodeJSONText(JSON,I); While (I<=L) and (JSON[I] <> ':') DO INC(I); INC(I); AsObject[K] := CreateJSONPair.Parse(JSON,I); While (I<=L) and not (JSON[I] in [',','}']) DO INC(I); INC(I); until not((I<=L) and (I>1) and (JSON[I-1]=',')); end; '[': begin INC(I); repeat AsArray[count] := CreateJSONPair.Parse(JSON,I); //TODO: fix empty array : "array" : [] => "array.count = 0" While (I<=L) and not (JSON[I] in [',',']']) DO INC(I); INC(I); until not((I<=L) and (I>1) and (JSON[I-1]=',')); {if (count = 1) and AsArray[0].IsNull then AsArray[0].Free;} end; '"': begin //sb.Append('<').Append(path).Append('>').Append(V).Append('</').Append(path).Append('>'); AsString := DecodeJSONText(JSON,I); end; #0..#$20: begin INC(I); continue; end; else begin V := ''; //unknown reserver world like "true" "false" "null"... try sync While (I<=L) and not (JSON[I] in [',',']','}']) DO begin if (word(JSON[I]) > $20) and ( word(JSON[I]) < $80) then V := V + JSON[I]; INC(I); end; if V <> '' then begin if sameText(v,'null') then else if sameText(v,'true') then begin AsBoolean := true; end else if sameText(v,'false') then begin asBoolean := false; end else begin if TryStrToInt64(V, IsInteger) then result.typeIs := json_int else begin result.typeIs := json_text; result.IsString := V; end; end; end; end; END; break; END; end; procedure TJSONPair.OnArrayNotify(Sender: TObject; const Item: TJSONPair; Action: TCollectionNotification); begin if (Action in [cnRemoved,cnExtracted]) and assigned(FObject) then begin FObject.ExtractPair(Item.name); end; end; function TJSONPair.Parse(const JSON : string): TJSONPair; var i : integer; begin i := 1; Result := Parse(JSON,I); end; //procedure TJSONPair.SetAsArray(i: integer; const Value: TJSONPair); //begin // if value = nil then // begin // if Assigned(FArray) then // begin // if (i < 0) then // FArray.Delete(FArray.Count-1) // else // if (i < FArray.Count) then // FArray.Delete(i); // end; // exit; // end; // if i < 0 then // i := count; // if Assigned(Value.owner) and (Value.owner <> self) and assigned(Value.owner.FArray) then // begin // value.Owner.FArray.Extract(Value); // end; // if (typeIs <> json_array) and (typeIs <> json_object) then // begin // Clear; // typeIs := json_array; // end; // value.owner := self; // value.name := IntToStr(i); // while IsArray.Count < i do // IsArray.add(TJSONPair.Create); // if I = IsArray.Count then // IsArray.Add(Value) // else // IsArray[i] := Value; //end; procedure TJSONPair.SetAsArray(i: integer; const Value: TJSONPair); var index : Integer; begin if (i < 0) or (i = MaxInt) then begin if Value = nil then exit; //nop i := count; end else if value = nil then begin if Assigned(FArray) then FArray.Delete(i); exit; end; if Assigned(Value.owner) and (Value.owner <> self) and assigned(Value.owner.FArray) then begin value.Owner.FArray.Extract(Value); end; if (typeIs <> json_array) and (typeIs <> json_object) then begin Clear; end; typeIs := json_array; value.owner := self; value.name := IntToStr(i); while IsArray.Count < i do IsArray.add(CreateJSONPair); if I = IsArray.Count then IsArray.Add(Value) else IsArray[i] := Value; end; procedure TJSONPair.SetAsBoolean(const Value: Boolean); begin if typeIs <> json_boolean then begin Clear; typeIs := json_boolean end; IsInteger := ord(Value); end; procedure TJSONPair.SetAsInteger(const Value: int64); begin if typeIs <> json_int then begin Clear; typeIs := json_int end; IsInteger := Value; end; procedure TJSONPair.SetAsObject(const Key: String; const Value: TJSONPair); var copyItems : TJSONPair; begin if Value = nil then begin if assigned(FObject) then FObject.Remove(Key); exit; end; if typeIs = json_array then begin //convert to object for copyItems in IsArray do IsObject.AddOrSetValue(copyItems.name,copyItems); typeIs := json_object; end; if typeIs <> json_object then begin Clear; typeIs := json_object; end; if assigned(Value.owner) and (Value.owner <> self) and assigned( Value.owner.FArray) then Value.owner.FArray.Extract(Value); Value.name := Key; Value.owner := self; IsObject.AddOrSetValue(Key,Value); IsArray.Add(value); end; procedure TJSONPair.SetAsString(const Value: String); begin if typeIs <> json_text then begin Clear; typeIs := json_text; end; IsString := value; end; function TJSONPair.ToString: string; var sb : TStringBuilder; begin sb := TStringBuilder.Create; try InternalToString(sb); result := sb.ToString; finally sb.Free; end; end; function TJSONPair.InternalToString(sb : TStringBuilder ) : integer; var item : TJSONPair; sv1,sv2 : integer; begin result := 0; sv2 := sb.Length; case typeIs of json_boolean: begin if AsBoolean then sb.Append('true') else sb.Append('false'); inc(result); end; json_int: begin sb.Append(AsInteger); inc(result); end; json_text: begin sb.Append('"').Append(EncodeJSONText(AsString)).Append('"'); inc(result); end; json_array: begin sb.Append('['); for item in IsArray do begin if not item.IsNull then begin sv1 := sb.Length; if result > 0 then sb.Append(','); if item.InternalToString(sb) = 0 then sb.Length := sv1 else inc(result); end; end; sb.Append(']'); end; json_object: begin sb.Append('{'); for item in IsArray do begin if not item.IsNull then begin sv1 := sb.Length; if result > 0 then sb.Append(','); sb.Append('"').Append(EncodeJSONText(item.name)).Append('":'); if item.InternalToString(sb) = 0 then sb.Length := sv1 else inc(result); end; end; sb.Append('}'); end; end; if result = 0 then sb.Length := sv2; end; class function TJSONPair.EncodeJSONText(const s: string): string; var sb : TStringBuilder; ch : char; begin sb := TStringBuilder.Create; try for ch in s do begin case ch of //#0..#7:; #8: sb.Append('\b'); #9: sb.Append('\t'); #10: sb.Append('\n'); //#11:; #12: sb.Append('\f'); #13: sb.Append('\r'); //#14..#$1f:; '"': sb.Append('\"'); '\': sb.Append('\\'); '/': sb.Append('\/'); #$80..#$ffff: sb.AppendFormat('\u%.4x',[word(ch)]); else begin case ch of #$20..#$7f: sb.Append(ch); end; end; end; end; result := sb.ToString; finally sb.Free; end; end; function TJSONPair.find(const s: array of string; out AResult: TJSONPair): Boolean; var tmp: TJSONPair; i : integer; index: int64; begin Aresult := nil; tmp := self; for i := low(s) to High(s) do begin case tmp.typeIs of json_array : begin if TryStrToInt64(s[i],index) and (tmp.FArray.Count > index) and (index >= 0) then begin tmp := tmp.FArray[index]; continue; end; end; json_object: if tmp.FObject.TryGetValue(s[i],tmp) then continue; end; exit(False); end; Aresult := tmp; Exit(True); end; procedure TJSONPair.forAll(proc: TProc<TJSONPair, PSearchControl>; control : PSearchControl); var item : TJSONPair; newControl : TSearchControl; begin if not assigned(proc) then exit; if self = nil then exit; if IsNull then exit; if control = nil then begin newControl.level := 0; control := @newControl; control.state := cNormal; end else if control.state <> cNormal then exit; proc(self, control); if control.state <> cNormal then exit; case typeis of json_object, json_array: begin inc(control.level); for item in IsArray do begin item.forAll(proc,control); case control.state of cStopLevel: begin control.state := cNormal; break; end; cStopAll: exit; end; end; dec(control.level); end; end; end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.ProgressDialog.iOS; interface uses System.UITypes, System.UIConsts, System.Messaging, System.TypInfo, Macapi.ObjectiveC, iOSapi.UIKit, iOSapi.Foundation, FGX.ProgressDialog, FGX.ProgressDialog.Types, FGX.Asserts; const SHADOW_ALPHA = 180; MESSAGE_FONT_SIZE = 15; MESSAGE_MARGINS = 5; MESSAGE_HEIGHT = 20; INDICATOR_MARGIN = 5; PROGRESSBAR_WIDTH = 200; PROGRESSBAR_HEIGHT = 20; type { TIOSProgressDialogService } TIOSProgressDialogService = class(TInterfacedObject, IFGXProgressDialogService) public { IFGXProgressDialogService } function CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog; function CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog; end; IiOSShadow = interface(NSObject) ['{5E0B5363-01B8-4670-A90A-107EDD428029}'] procedure tap; cdecl; end; TiOSDelegate = class(TOCLocal) private [Weak] FNativeDialog: TfgNativeDialog; protected function GetObjectiveCClass: PTypeInfo; override; public constructor Create(const ADialog: TfgNativeDialog); { UIView } procedure tap; cdecl; end; TiOSNativeActivityDialog = class(TfgNativeActivityDialog) private FActivityIndicator: UIActivityIndicatorView; FShadow: TiOSDelegate; FShadowColor: TAlphaColor; FShadowView: UIView; FMessageLabel: UILabel; FDelegate: TiOSDelegate; FTapRecognizer: UITapGestureRecognizer; procedure DoOrientationChanged(const Sender: TObject; const M: TMessage); protected procedure MessageChanged; override; public constructor Create(const AOwner: TObject); override; destructor Destroy; override; procedure Show; override; procedure Hide; override; procedure Realign; end; TiOSNativeProgressDialog = class(TfgNativeProgressDialog) private FDelegate: TiOSDelegate; FTapRecognizer: UITapGestureRecognizer; FProgressView: UIProgressView; FShadowColor: TAlphaColor; FShadowView: UIView; FMessageLabel: UILabel; procedure DoOrientationChanged(const Sender: TObject; const M: TMessage); protected procedure MessageChanged; override; procedure ProgressChanged; override; public constructor Create(const AOwner: TObject); override; destructor Destroy; override; procedure ResetProgress; override; procedure Show; override; procedure Hide; override; procedure Realign; end; procedure RegisterService; procedure UnregisterService; implementation uses System.Types, System.Math, System.SysUtils, iOSapi.CoreGraphics, Macapi.ObjCRuntime, Macapi.Helpers, FMX.Platform, FMX.Platform.iOS, FMX.Forms, FMX.Helpers.iOS, FGX.Helpers.iOS; procedure RegisterService; begin TPlatformServices.Current.AddPlatformService(IFGXProgressDialogService, TIOSProgressDialogService.Create); end; procedure UnregisterService; begin TPlatformServices.Current.RemovePlatformService(IFGXProgressDialogService); end; { TIOSProgressDialogService } function TIOSProgressDialogService.CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog; begin Result := TiOSNativeActivityDialog.Create(AOwner); end; function TIOSProgressDialogService.CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog; begin Result := TiOSNativeProgressDialog.Create(AOwner); end; { TiOSNativeProgressDialog } constructor TiOSNativeActivityDialog.Create(const AOwner: TObject); begin AssertIsNotNil(MainScreen); AssertIsNotNil(SharedApplication.keyWindow); AssertIsNotNil(SharedApplication.keyWindow.rootViewController); AssertIsNotNil(SharedApplication.keyWindow.rootViewController.view); inherited Create(AOwner); FShadowColor := MakeColor(0, 0, 0, SHADOW_ALPHA); FDelegate := TiOSDelegate.Create(Self); FTapRecognizer := TUITapGestureRecognizer.Create; FTapRecognizer.setNumberOfTapsRequired(1); FTapRecognizer.addTarget(FDelegate.GetObjectID, sel_getUid('tap')); // Shadow FShadowView := TUIView.Create; FShadowView.setUserInteractionEnabled(True); FShadowView.setHidden(True); FShadowView.setAutoresizingMask(UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleHeight); FShadowView.setBackgroundColor(TUIColor.MakeColor(FShadowColor)); FShadowView.addGestureRecognizer(FTapRecognizer); // Creating Ani indicator FActivityIndicator := TUIActivityIndicatorView.Alloc; FActivityIndicator.initWithActivityIndicatorStyle(UIActivityIndicatorViewStyleWhite); FActivityIndicator.setUserInteractionEnabled(False); FActivityIndicator.startAnimating; FActivityIndicator.setAutoresizingMask(UIViewAutoresizingFlexibleLeftMargin or UIViewAutoresizingFlexibleRightMargin); // Creating message label FMessageLabel := TUILabel.Create; FMessageLabel.setUserInteractionEnabled(False); FMessageLabel.setTextColor(TUIColor.whiteColor); FMessageLabel.setBackgroundColor(TUIColor.clearColor); FMessageLabel.setFont(FMessageLabel.font.fontWithSize(MESSAGE_FONT_SIZE)); FMessageLabel.setTextAlignment(UITextAlignmentCenter); // Adding view FShadowView.addSubview(FActivityIndicator); FShadowView.addSubview(FMessageLabel); // Adding Shadow to application SharedApplication.keyWindow.rootViewController.view.AddSubview(FShadowView); Realign; { Message subscription } TMessageManager.DefaultManager.SubscribeToMessage(TOrientationChangedMessage, DoOrientationChanged); end; destructor TiOSNativeActivityDialog.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TOrientationChangedMessage, DoOrientationChanged); FreeAndNil(FShadow); FActivityIndicator.removeFromSuperview; FActivityIndicator.release; FActivityIndicator := nil; FMessageLabel.removeFromSuperview; FMessageLabel.release; FMessageLabel := nil; FShadowView.removeFromSuperview; FShadowView.release; FShadowView := nil; inherited Destroy; end; procedure TiOSNativeActivityDialog.DoOrientationChanged(const Sender: TObject; const M: TMessage); begin Realign; end; procedure TiOSNativeActivityDialog.Hide; begin AssertIsNotNil(FShadowView); inherited; FadeOut(FShadowView, DEFAULT_ANIMATION_DURATION); DoHide; end; procedure TiOSNativeActivityDialog.MessageChanged; begin AssertIsNotNil(FMessageLabel); FMessageLabel.setText(StrToNSStr(Message)); // We should call it once for starting animation if IsShown then Application.ProcessMessages; end; procedure TiOSNativeActivityDialog.Realign; var ScreenBounds: TSize; CenterPoint: NSPoint; begin ScreenBounds := Screen.Size; FShadowView.setFrame(CGRect.Create(ScreenBounds.Width, ScreenBounds.Height)); CenterPoint := FShadowView.center; FActivityIndicator.setCenter(CGPointMake(CenterPoint.X, CenterPoint.Y - FActivityIndicator.bounds.height - INDICATOR_MARGIN)); FMessageLabel.setBounds(CGRect.Create(FShadowView.bounds.width, 25)); FMessageLabel.setCenter(CGPointMake(CenterPoint.X, CenterPoint.Y + MESSAGE_MARGINS)); end; procedure TiOSNativeActivityDialog.Show; begin AssertIsNotNil(FShadowView); AssertIsNotNil(FMessageLabel); inherited; FadeIn(FShadowView, DEFAULT_ANIMATION_DURATION); DoShow; // We should call it once for starting animation Application.ProcessMessages; end; { TiOSNativeProgressDialog } constructor TiOSNativeProgressDialog.Create(const AOwner: TObject); begin AssertIsNotNil(MainScreen); AssertIsNotNil(SharedApplication.keyWindow); AssertIsNotNil(SharedApplication.keyWindow.rootViewController); AssertIsNotNil(SharedApplication.keyWindow.rootViewController.view); inherited Create(AOwner); FShadowColor := MakeColor(0, 0, 0, SHADOW_ALPHA); FDelegate := TiOSDelegate.Create(Self); FTapRecognizer := TUITapGestureRecognizer.Create; FTapRecognizer.setNumberOfTapsRequired(1); FTapRecognizer.addTarget(FDelegate.GetObjectID, sel_getUid('tap')); // Shadow FShadowView := TUIView.Create; FShadowView.setUserInteractionEnabled(True); FShadowView.setHidden(True); FShadowView.setAutoresizingMask(UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleHeight); FShadowView.setBackgroundColor(TUIColor.MakeColor(FShadowColor)); FShadowView.addGestureRecognizer(FTapRecognizer); // Creating message label FMessageLabel := TUILabel.Create; FMessageLabel.setBackgroundColor(TUIColor.clearColor); FMessageLabel.setTextColor(TUIColor.whiteColor); FMessageLabel.setTextAlignment(UITextAlignmentCenter); FMessageLabel.setFont(FMessageLabel.font.fontWithSize(MESSAGE_FONT_SIZE)); // Creating Ani indicator FProgressView := TUIProgressView.Alloc; FProgressView.initWithProgressViewStyle(UIProgressViewStyleDefault); // Adding view FShadowView.addSubview(FProgressView); FShadowView.addSubview(FMessageLabel); // Adding Shadow to application SharedApplication.keyWindow.rootViewController.view.AddSubview(FShadowView); Realign; { Message subscription } TMessageManager.DefaultManager.SubscribeToMessage(TOrientationChangedMessage, DoOrientationChanged); end; destructor TiOSNativeProgressDialog.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TOrientationChangedMessage, DoOrientationChanged); FreeAndNil(FDelegate); FProgressView.removeFromSuperview; FProgressView.release; FProgressView := nil; FMessageLabel.removeFromSuperview; FMessageLabel.release; FMessageLabel := nil; FShadowView.removeFromSuperview; FShadowView.release; FShadowView := nil; inherited Destroy; end; procedure TiOSNativeProgressDialog.DoOrientationChanged(const Sender: TObject; const M: TMessage); begin Realign; end; procedure TiOSNativeProgressDialog.Hide; begin AssertIsNotNil(FShadowView); inherited; FadeOut(FShadowView, DEFAULT_ANIMATION_DURATION); DoHide; end; procedure TiOSNativeProgressDialog.MessageChanged; begin AssertIsNotNil(FMessageLabel); FMessageLabel.setText(StrToNSStr(Message)); // We should call it once for starting animation if IsShown then Application.ProcessMessages; end; procedure TiOSNativeProgressDialog.ProgressChanged; begin AssertIsNotNil(FProgressView); AssertInRange(Progress, 0, Max); if Max > 0 then FProgressView.setProgress(Progress / Max, True) else FProgressView.setProgress(0); // We should call it once for starting animation if IsShown then Application.ProcessMessages; end; procedure TiOSNativeProgressDialog.Realign; var ScreenBounds: TSize; CenterPoint: NSPoint; begin ScreenBounds := Screen.size; FShadowView.setFrame(CGRect.Create(ScreenBounds.Width, ScreenBounds.Height)); CenterPoint := FShadowView.center; FMessageLabel.setBounds(CGRect.Create(FShadowView.bounds.width, MESSAGE_HEIGHT)); FMessageLabel.setCenter(CGPointMake(CenterPoint.X, CenterPoint.Y - FMessageLabel.bounds.height)); FProgressView.setBounds(CGRect.Create(PROGRESSBAR_WIDTH, PROGRESSBAR_HEIGHT)); FProgressView.setCenter(CenterPoint); end; procedure TiOSNativeProgressDialog.ResetProgress; begin AssertIsNotNil(FProgressView); inherited ResetProgress; FProgressView.setProgress(0); end; procedure TiOSNativeProgressDialog.Show; begin AssertIsNotNil(FShadowView); inherited; FadeIn(FShadowView, DEFAULT_ANIMATION_DURATION); DoShow; // We should call it once for starting animation Application.ProcessMessages; end; { TiOSShadow } constructor TiOSDelegate.Create(const ADialog: TfgNativeDialog); begin AssertIsNotNil(ADialog); inherited Create; FNativeDialog := ADialog; end; function TiOSDelegate.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(IiOSShadow); end; procedure TiOSDelegate.tap; begin AssertIsNotNil(FNativeDialog); if FNativeDialog.Cancellable then begin FNativeDialog.Hide; if Assigned(FNativeDialog.OnCancel) then FNativeDialog.OnCancel(FNativeDialog.Owner); end; end; end.
unit LUX.GPU.Vulkan.Pipeli; interface //#################################################################### ■ uses System.Generics.Collections, vulkan_core, vulkan_win32, vulkan.util, LUX.GPU.Vulkan.Shader; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TVkPipeli<TVkDevice_:class> = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkPipeli TVkPipeli<TVkDevice_:class> = class private type TVkPipeli_ = TVkPipeli<TVkDevice_>; TVkShader_ = TVkShader<TVkPipeli_>; TVkShaders_ = TObjectList<TVkShader_>; T_dynamicStateEnables = array [ 0..2-1 ] of VkDynamicState; protected _Device :TVkDevice_; _Handle :VkPipeline; _DepthTest :Boolean; _Shaders :TVkShaders_; ///// アクセス function GetHandle :VkPipeline; procedure SetHandle( const Handle_:VkPipeline ); ///// メソッド procedure CreateHandle; procedure DestroHandle; public constructor Create; overload; constructor Create( const Device_:TVkDevice_; const DepthTest_:Boolean ); overload; destructor Destroy; override; ///// プロパティ property Device :TVkDevice_ read _Device ; property Handle :VkPipeline read GetHandle write SetHandle; property Shaders :TVkShaders_ read _Shaders ; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses LUX.GPU.Vulkan; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkPipeli //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkPipeli<TVkDevice_>.GetHandle :VkPipeline; begin if _Handle = 0 then CreateHandle; Result := _Handle; end; procedure TVkPipeli<TVkDevice_>.SetHandle( const Handle_:VkPipeline ); begin if _Handle <> 0 then DestroHandle; _Handle := Handle_; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TVkPipeli<TVkDevice_>.CreateHandle; var res :VkResult; dynamicStateEnables :T_dynamicStateEnables; // Viewport + Scissor dynamicState :VkPipelineDynamicStateCreateInfo; vi :VkPipelineVertexInputStateCreateInfo; ia :VkPipelineInputAssemblyStateCreateInfo; rs :VkPipelineRasterizationStateCreateInfo; cb :VkPipelineColorBlendStateCreateInfo; att_state :array [ 0..1-1 ] of VkPipelineColorBlendAttachmentState; vp :VkPipelineViewportStateCreateInfo; ds :VkPipelineDepthStencilStateCreateInfo; ms :VkPipelineMultisampleStateCreateInfo; pipeline :VkGraphicsPipelineCreateInfo; shaderStages : TArray<VkPipelineShaderStageCreateInfo>; S :TVkShader_; begin dynamicStateEnables := Default( T_dynamicStateEnables ); dynamicState := Default( VkPipelineDynamicStateCreateInfo ); dynamicState.sType := VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamicState.pNext := nil; dynamicState.pDynamicStates := @dynamicStateEnables[0]; dynamicState.dynamicStateCount := 0; vi := Default( VkPipelineVertexInputStateCreateInfo ); vi.sType := VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vi.pNext := nil; vi.flags := 0; vi.vertexBindingDescriptionCount := 1; vi.pVertexBindingDescriptions := @TVkDevice( _Device ).Instan.Vulkan.Info.vi_binding; vi.vertexAttributeDescriptionCount := 2; vi.pVertexAttributeDescriptions := @TVkDevice( _Device ).Instan.Vulkan.Info.vi_attribs[0]; ia.sType := VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; ia.pNext := nil; ia.flags := 0; ia.primitiveRestartEnable := VK_FALSE; ia.topology := VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; rs.sType := VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rs.pNext := nil; rs.flags := 0; rs.polygonMode := VK_POLYGON_MODE_FILL; rs.cullMode := Ord( VK_CULL_MODE_BACK_BIT ); rs.frontFace := VK_FRONT_FACE_CLOCKWISE; rs.depthClampEnable := VK_FALSE; rs.rasterizerDiscardEnable := VK_FALSE; rs.depthBiasEnable := VK_FALSE; rs.depthBiasConstantFactor := 0; rs.depthBiasClamp := 0; rs.depthBiasSlopeFactor := 0; rs.lineWidth := 1.0; cb.sType := VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; cb.flags := 0; cb.pNext := nil; att_state[0].colorWriteMask := $f; att_state[0].blendEnable := VK_FALSE; att_state[0].alphaBlendOp := VK_BLEND_OP_ADD; att_state[0].colorBlendOp := VK_BLEND_OP_ADD; att_state[0].srcColorBlendFactor := VK_BLEND_FACTOR_ZERO; att_state[0].dstColorBlendFactor := VK_BLEND_FACTOR_ZERO; att_state[0].srcAlphaBlendFactor := VK_BLEND_FACTOR_ZERO; att_state[0].dstAlphaBlendFactor := VK_BLEND_FACTOR_ZERO; cb.attachmentCount := 1; cb.pAttachments := @att_state[0]; cb.logicOpEnable := VK_FALSE; cb.logicOp := VK_LOGIC_OP_NO_OP; cb.blendConstants[0] := 1.0; cb.blendConstants[1] := 1.0; cb.blendConstants[2] := 1.0; cb.blendConstants[3] := 1.0; vp := Default( VkPipelineViewportStateCreateInfo ); vp.sType := VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; vp.pNext := nil; vp.flags := 0; vp.viewportCount := NUM_VIEWPORTS; dynamicStateEnables[dynamicState.dynamicStateCount] := VK_DYNAMIC_STATE_VIEWPORT; Inc( dynamicState.dynamicStateCount ); vp.scissorCount := NUM_SCISSORS; dynamicStateEnables[dynamicState.dynamicStateCount] := VK_DYNAMIC_STATE_SCISSOR ; Inc( dynamicState.dynamicStateCount ); vp.pScissors := nil; vp.pViewports := nil; var include_depth :VkBool32; if _DepthTest then include_depth := 1 else include_depth := 0; ds.sType := VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; ds.pNext := nil; ds.flags := 0; ds.depthTestEnable := include_depth; ds.depthWriteEnable := include_depth; ds.depthCompareOp := VK_COMPARE_OP_LESS_OR_EQUAL; ds.depthBoundsTestEnable := VK_FALSE; ds.stencilTestEnable := VK_FALSE; ds.back.failOp := VK_STENCIL_OP_KEEP; ds.back.passOp := VK_STENCIL_OP_KEEP; ds.back.compareOp := VK_COMPARE_OP_ALWAYS; ds.back.compareMask := 0; ds.back.reference := 0; ds.back.depthFailOp := VK_STENCIL_OP_KEEP; ds.back.writeMask := 0; ds.minDepthBounds := 0; ds.maxDepthBounds := 0; ds.stencilTestEnable := VK_FALSE; ds.front := ds.back; ms.sType := VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; ms.pNext := nil; ms.flags := 0; ms.pSampleMask := nil; ms.rasterizationSamples := NUM_SAMPLES; ms.sampleShadingEnable := VK_FALSE; ms.alphaToCoverageEnable := VK_FALSE; ms.alphaToOneEnable := VK_FALSE; ms.minSampleShading := 0.0; pipeline.sType := VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipeline.pNext := nil; pipeline.layout := TVkDevice( _Device ).Instan.Vulkan.Info.pipeline_layout; pipeline.basePipelineHandle := VK_NULL_HANDLE; pipeline.basePipelineIndex := 0; pipeline.flags := 0; pipeline.pVertexInputState := @vi; pipeline.pInputAssemblyState := @ia; pipeline.pRasterizationState := @rs; pipeline.pColorBlendState := @cb; pipeline.pTessellationState := nil; pipeline.pMultisampleState := @ms; pipeline.pDynamicState := @dynamicState; pipeline.pViewportState := @vp; pipeline.pDepthStencilState := @ds; for S in _Shaders do shaderStages := shaderStages + [ S.Stage ]; pipeline.pStages := @shaderStages[0]; pipeline.stageCount := Length( shaderStages ); pipeline.renderPass := TVkDevice( _Device ).Instan.Vulkan.Info.render_pass; pipeline.subpass := 0; res := vkCreateGraphicsPipelines( TVkDevice( _Device ).Handle, TVkDevice( _Device ).Instan.Vulkan.Info.pipelineCache, 1, @pipeline, nil, @_Handle ); Assert( res = VK_SUCCESS ); end; procedure TVkPipeli<TVkDevice_>.DestroHandle; begin vkDestroyPipeline( TVkDevice( _Device ).Handle, _Handle, nil ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkPipeli<TVkDevice_>.Create; begin inherited; _Handle := 0; _Shaders := TVkShaders_.Create; end; constructor TVkPipeli<TVkDevice_>.Create( const Device_:TVkDevice_; const DepthTest_:Boolean ); begin Create; _Device := Device_; _DepthTest := DepthTest_; end; destructor TVkPipeli<TVkDevice_>.Destroy; begin _Shaders.Free; Handle := 0; inherited; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
unit UMainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, UFigure, UCircle, URectangle, UTriangle; const MaxN = 100; type TMainForm = class(TForm) image: TImage; rgFig: TRadioGroup; lbPoint: TLabel; edPoint: TEdit; lbSecondPoint: TLabel; edSecondPoint: TEdit; lbColor: TLabel; cbColor: TComboBox; lbThirdPoint: TLabel; edThirdPoint: TEdit; btAdd: TButton; btExit: TButton; btClear: TButton; btArea: TButton; btCircles: TButton; procedure FormCreate(Sender: TObject); procedure btExitClick(Sender: TObject); procedure CircleSelected; procedure RectangleSelected; procedure TriangleSelected; procedure ClearEdits; procedure rgFigClick(Sender: TObject); procedure btAddClick(Sender: TObject); procedure DrawFigures; procedure ClearImage; procedure edPointKeyPress(Sender: TObject; var Key: Char); procedure btClearClick(Sender: TObject); procedure btAreaClick(Sender: TObject); procedure btCirclesClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; FigureArray: array[0..MaxN - 1] of TFigure; count: integer; implementation {$R *.dfm} procedure TMainForm.ClearImage; var rect: TRect; begin Rect.Left:=0; Rect.Top:=0; Rect.Right:=Image.Width; Rect.Bottom:=Image.Height; Image.Canvas.Brush.Color:=clWhite; image.Canvas.FillRect(rect); end; procedure TMainForm.FormCreate(Sender: TObject); begin ClearImage; count:= 0; rgFig.ItemIndex:= 0; cbColor.ItemIndex:= 0; end; procedure TMainForm.ClearEdits; begin edThirdPoint.Clear; edPoint.Clear; edSecondPoint.Clear; end; procedure TMainForm.CircleSelected; begin ClearEdits; lbSecondPoint.Caption:= 'Радиус'; lbThirdPoint.Visible:= false; edThirdPoint.Visible:= false; end; procedure TMainForm.RectangleSelected; begin ClearEdits; lbSecondPoint.Caption:= 'Вторая точка'; lbThirdPoint.Visible:= false; edThirdPoint.Visible:= false; end; procedure TMainForm.TriangleSelected; begin ClearEdits; lbSecondPoint.Caption:= 'Вторая точка'; lbThirdPoint.Visible:= true; lbThirdPoint.Caption:= 'Третья точка'; edThirdPoint.Visible:= true; end; procedure TMainForm.btExitClick(Sender: TObject); begin Close; end; procedure TMainForm.rgFigClick(Sender: TObject); begin case rgFig.ItemIndex of 0: CircleSelected; 1: RectangleSelected; 2: TriangleSelected; end; end; function NextWord(Str:string; var i:integer):string; var len:integer; begin len:= Length(Str); Result:= ''; while (i<=len) and (Str[i] = ' ') do inc(i); while (i<=len) and (Str[i] <> ' ') do begin Result:= Result + Str[i]; inc(i); end; end; function TryGetPoint(Str:string; var Point:TPoint):boolean; var i, X, Y:integer; begin i:= 1; Result:= TryStrToInt(NextWord(Str, i), X) and (X >= 0) and TryStrToInt(NextWord(Str, i), Y) and (Y >= 0); if Result then begin Point.X:= X; Point.Y:= Y; end; end; procedure TMainForm.DrawFigures; var i:integer; begin ClearImage; for i:=0 to count - 1 do FigureArray[i].Draw(Image); end; procedure TMainForm.btAddClick(Sender: TObject); var Point, SecondPoint, ThirdPoint:TPoint; Color:TColor; radius: integer; begin Color:= clWhite; case cbColor.ItemIndex of 0: Color:= clRed; 1: Color:= clGreen; 2: Color:= clBlue; 3: Color:= clYellow; 4: Color:= clBlack; end; case rgFig.ItemIndex of 0: begin if TryGetPoint(edPoint.Text, Point) and TryStrToInt(edSecondPoint.Text, radius) and (radius > 0) then begin FigureArray[count]:= TCircle.Create(Point, Color, radius); inc(count); end else ShowMessage('Проверьте данные!'); end; 1: begin if TryGetPoint(edPoint.Text, Point) and TryGetPoint(edSecondPoint.Text, SecondPoint) then begin FigureArray[count]:= TRectangle.Create(Point, Color, SecondPoint); inc(count); end else ShowMessage('Проверьте данные!'); end; 2: begin if TryGetPoint(edPoint.Text, Point) and TryGetPoint(edSecondPoint.Text, SecondPoint) and TryGetPoint(edThirdPoint.Text, ThirdPoint) then begin FigureArray[count]:= TTriangle.Create(Point, Color, SecondPoint, ThirdPoint); inc(count); end else ShowMessage('Проверьте данные!'); end; end; DrawFigures; end; procedure TMainForm.edPointKeyPress(Sender: TObject; var Key: Char); begin if not(key in ['0'..'9', ' ', #127, #8]) then key:= #0; end; procedure TMainForm.btClearClick(Sender: TObject); begin count:= 0; ClearEdits; DrawFigures; end; procedure TMainForm.btAreaClick(Sender: TObject); var i:integer; sum:real; begin sum:= 0; for i:=0 to count - 1 do sum:= sum + FigureArray[i].Area; ShowMessage('Общая сумма всех площадей: ' + FloatToStr(sum)); end; procedure TMainForm.btCirclesClick(Sender: TObject); var i, j:integer; OK:boolean; begin i:= 0; OK:= false; while (i < count) and not OK do begin j:= 0; if FigureArray[i].WhatItIs = 'Круг' then while (j < count) and not OK do begin OK:= FigureArray[j].Contains(FigureArray[i].point); inc(j); end; inc(i); end; if OK then ShowMessage('Есть прямоугольники, которые содержат круг') else ShowMessage('Нет прямоугольников, которые содержат круг'); end; end.
{ lzRichEdit Copyright (C) 2010 Elson Junio elsonjunio@yahoo.com.br 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 library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit Win32WSRichBox; {$mode objfpc}{$H+} interface uses Windows, Classes, SysUtils, Controls, LCLType, StdCtrls, Graphics, Win32Proc, Win32Int, Win32WSControls, WSRichBox, RichEdit, RichBox; type { TWin32WSCustomRichBox } TWin32WSCustomRichBox = class(TWSCustomRichBox) class function CreateHandle(const AWinControl: TWinControl; const AParams: TCreateParams): HWND; override; //-- //Funções de Fonte class function Font_GetCharset(const AWinControl: TWinControl): TFontCharset; override; class function Font_GetColor(const AWinControl: TWinControl): TColor; override; class function Font_GetName(const AWinControl: TWinControl): TFontName; override; class function Font_GetPitch(const AWinControl: TWinControl): TFontPitch; override; class function Font_GetProtected(const AWinControl: TWinControl): boolean; override; class function Font_GetSize(const AWinControl: TWinControl): integer; override; class function Font_GetStyle(const AWinControl: TWinControl): TFontStyles; override; // //Funções de Paragrafos class function Para_GetAlignment(const AWinControl: TWinControl): TAlignment; override; class function Para_GetFirstIndent(const AWinControl: TWinControl): Longint; override; class function Para_GetLeftIndent(const AWinControl: TWinControl): Longint; override; class function Para_GetRightIndent(const AWinControl: TWinControl): Longint; override; class function Para_GetNumbering(const AWinControl: TWinControl): TNumberingStyle; override; class function Para_GetTab(const AWinControl: TWinControl; Index: Byte): Longint; override; class function Para_GetTabCount(const AWinControl: TWinControl): Integer; override; // //Procedimentos de Fonte class procedure Font_SetCharset(const AWinControl: TWinControl; Value: TFontCharset); override; class procedure Font_SetColor(const AWinControl: TWinControl; Value: TColor); override; class procedure Font_SetName(const AWinControl: TWinControl; Value: TFontName); override; class procedure Font_SetPitch(const AWinControl: TWinControl; Value: TFontPitch); override; class procedure Font_SetProtected(const AWinControl: TWinControl; Value: boolean); override; class procedure Font_SetSize(const AWinControl: TWinControl; Value: integer); override; class procedure Font_SetStyle(const AWinControl: TWinControl; Value: TFontStyles); override; // //Procedimentos de Paragrafos class procedure Para_SetAlignment(const AWinControl: TWinControl; Value: TAlignment); override; class procedure Para_SetFirstIndent(const AWinControl: TWinControl; Value: Longint); override; class procedure Para_SetLeftIndent(const AWinControl: TWinControl; Value: Longint); override; class procedure Para_SetRightIndent(const AWinControl: TWinControl; Value: Longint); override; class procedure Para_SetNumbering(const AWinControl: TWinControl; Value: TNumberingStyle); override; class procedure Para_SetTab(const AWinControl: TWinControl; Index: Byte; Value: Longint); override; class procedure Para_SetTabCount(const AWinControl: TWinControl; Value: Integer); override; //-- class procedure SaveToStream(const AWinControl: TWinControl; var Stream: TStream); override; class procedure LoadFromStream(const AWinControl: TWinControl; const Stream: TStream); override; end; {Exceptional} procedure InitFMT(var FMT: TCHARFORMAT2); procedure F_GetAttributes(const Window: HWND; var FMT: TCHARFORMAT2); procedure F_SetAttributes(const Window: HWND; var FMT: TCHARFORMAT2); // procedure InitPARAFMT(var PARAFMT: TPARAFORMAT2); procedure P_GetAttributes(const Window: HWND; var PARAFMT: TPARAFORMAT2); procedure P_SetAttributes(const Window: HWND; var PARAFMT: TPARAFORMAT2); // function StreamSave(dwCookie: PDWORD; pbBuff: LPBYTE; cb: LONG; var pcb: LONG): DWORD; stdcall; function StreamLoad(dwCookie: PDWORD; pbBuff: LPBYTE; cb: LONG; var pcb: LONG): DWORD; stdcall; {...} implementation var RichEditLibrary_HWND: THandle; const RichEditClass: ansistring = ''; function RichEditProc(Window: HWnd; Msg: UInt; WParam: Windows.WParam; LParam: Windows.LParam): LResult; stdcall; begin if Msg = WM_PAINT then begin Result := CallDefaultWindowProc(Window, Msg, WParam, LParam); end else Result := WindowProc(Window, Msg, WParam, LParam); end; {Exceptional} procedure InitFMT(var FMT: TCHARFORMAT2); begin FillChar(FMT, SizeOf(TCHARFORMAT2), 0); FMT.cbSize := SizeOf(TCHARFORMAT2); end; procedure F_GetAttributes(const Window: HWND; var FMT: TCHARFORMAT2); begin InitFMT(FMT); SendMessage(Window, EM_GETCHARFORMAT, SCF_SELECTION, LPARAM(@FMT)); end; procedure F_SetAttributes(const Window: HWND; var FMT: TCHARFORMAT2); begin SendMessage(Window, EM_SETCHARFORMAT, SCF_SELECTION, LPARAM(@FMT)); end; // procedure InitPARAFMT(var PARAFMT: TPARAFORMAT2); begin FillChar(PARAFMT, SizeOf(TPARAFORMAT2), 0); PARAFMT.cbSize := SizeOf(TPARAFORMAT2); end; procedure P_GetAttributes(const Window: HWND; var PARAFMT: TPARAFORMAT2); begin InitPARAFMT(PARAFMT); SendMessage(Window, EM_GETPARAFORMAT, 0, LPARAM(@PARAFMT)); end; procedure P_SetAttributes(const Window: HWND; var PARAFMT: TPARAFORMAT2); begin SendMessage(Window, EM_SETPARAFORMAT, 0, LPARAM(@PARAFMT)); end; function StreamSave(dwCookie: PDWORD; pbBuff: LPBYTE; cb: LONG; var pcb: LONG ): DWORD; stdcall; var Stream: TStream; begin try Stream := TStream(dwCookie^); pcb := Stream.Write(pbBuff^, cb); Result := 0; except Result := 1; end; end; function StreamLoad(dwCookie: PDWORD; pbBuff: LPBYTE; cb: LONG; var pcb: LONG ): DWORD; stdcall; var s: TStream; begin try s := TStream(dwCookie^); pcb := s.Read(pbBuff^, cb); Result := 0; except Result := 1; end; end; { TWin32WSCustomRichBox } class function TWin32WSCustomRichBox.CreateHandle(const AWinControl: TWinControl; const AParams: TCreateParams): HWND; const AlignmentToEditFlags: array[TAlignment] of DWord = ( { taLeftJustify } ES_LEFT, { taRightJustify } ES_RIGHT, { taCenter } ES_CENTER ); var Params: TCreateWindowExParams; begin //-- if (RichEditLibrary_HWND = 0) then begin RichEditLibrary_HWND := LoadLibrary('Msftedit.dll'); if (RichEditLibrary_HWND <> 0) and (RichEditLibrary_HWND <> HINSTANCE_ERROR) then RichEditClass := 'RichEdit50W' else RichEditLibrary_HWND := 0; end; //-- if (RichEditLibrary_HWND = 0) then begin RichEditLibrary_HWND := LoadLibrary('RICHED20.DLL'); if (RichEditLibrary_HWND <> 0) and (RichEditLibrary_HWND <> HINSTANCE_ERROR) then begin if UnicodeEnabledOS then RichEditClass := 'RichEdit20W' else RichEditClass := 'RichEdit20A'; end else RichEditLibrary_HWND := 0; end; //-- if (RichEditLibrary_HWND = 0) then begin RichEditLibrary_HWND := LoadLibrary('RICHED32.DLL'); if (RichEditLibrary_HWND <> 0) and (RichEditLibrary_HWND <> HINSTANCE_ERROR) then RichEditClass := 'RICHEDIT' else RichEditLibrary_HWND := 0; end; //-- if (RichEditLibrary_HWND = 0) then begin //'Aqui devo abortar a criação do componete!!!!' end; //-- //-- PrepareCreateWindow(AWinControl, AParams, Params); //-- with Params do begin SubClassWndProc := @RichEditProc; Flags := Flags or ES_AUTOVSCROLL or ES_MULTILINE or ES_WANTRETURN; if TCustomRichBox(AWinControl).ReadOnly then Flags := Flags or ES_READONLY; Flags := Flags or AlignmentToEditFlags[TCustomRichBox(AWinControl).Alignment]; case TCustomRichBox(AWinControl).ScrollBars of ssHorizontal, ssAutoHorizontal: Flags := Flags or WS_HSCROLL; ssVertical, ssAutoVertical: Flags := Flags or WS_VSCROLL; ssBoth, ssAutoBoth: Flags := Flags or WS_HSCROLL or WS_VSCROLL; end; if TCustomRichBox(AWinControl).WordWrap then Flags := Flags and not WS_HSCROLL else Flags := Flags or ES_AUTOHSCROLL; if TCustomRichBox(AWinControl).BorderStyle = bsSingle then FlagsEx := FlagsEx or WS_EX_CLIENTEDGE; pClassName := @RichEditClass[1]; WindowTitle := StrCaption; end; //-- FinishCreateWindow(AWinControl, Params, False); Params.WindowInfo^.needParentPaint := False; Result := Params.Window; end; class function TWin32WSCustomRichBox.Font_GetCharset( const AWinControl: TWinControl): TFontCharset; var FMT: TCHARFORMAT2; begin F_GetAttributes(AWinControl.Handle, FMT); Result := FMT.bCharset; end; class function TWin32WSCustomRichBox.Font_GetColor( const AWinControl: TWinControl): TColor; var FMT: TCHARFORMAT2; begin F_GetAttributes(AWinControl.Handle, FMT); with FMT do if (dwEffects and CFE_AUTOCOLOR) <> 0 then Result := clWindowText else Result := crTextColor; end; class function TWin32WSCustomRichBox.Font_GetName( const AWinControl: TWinControl): TFontName; var FMT: TCHARFORMAT2; begin F_GetAttributes(AWinControl.Handle, FMT); Result := FMT.szFaceName; end; class function TWin32WSCustomRichBox.Font_GetPitch( const AWinControl: TWinControl): TFontPitch; var FMT: TCHARFORMAT2; begin F_GetAttributes(AWinControl.Handle, FMT); case (FMT.bPitchAndFamily and $03) of DEFAULT_PITCH: Result := fpDefault; VARIABLE_PITCH: Result := fpVariable; FIXED_PITCH: Result := fpFixed; else Result := fpDefault; end; end; class function TWin32WSCustomRichBox.Font_GetProtected( const AWinControl: TWinControl): boolean; var FMT: TCHARFORMAT2; begin F_GetAttributes(AWinControl.Handle, FMT); with FMT do if (dwEffects and CFE_PROTECTED) <> 0 then Result := True else Result := False; end; class function TWin32WSCustomRichBox.Font_GetSize( const AWinControl: TWinControl): integer; var FMT: TCHARFORMAT2; begin F_GetAttributes(AWinControl.Handle, FMT); Result := FMT.yHeight div 20; end; class function TWin32WSCustomRichBox.Font_GetStyle( const AWinControl: TWinControl): TFontStyles; var FMT: TCHARFORMAT2; begin Result := []; F_GetAttributes(AWinControl.Handle, FMT); with FMT do begin if (dwEffects and CFE_BOLD) <> 0 then Include(Result, fsBold); if (dwEffects and CFE_ITALIC) <> 0 then Include(Result, fsItalic); if (dwEffects and CFE_UNDERLINE) <> 0 then Include(Result, fsUnderline); if (dwEffects and CFE_STRIKEOUT) <> 0 then Include(Result, fsStrikeOut); end; end; class function TWin32WSCustomRichBox.Para_GetAlignment( const AWinControl: TWinControl): TAlignment; var Paragraph: TPARAFORMAT2; begin P_GetAttributes(AWinControl.Handle, Paragraph); Result := TAlignment(Paragraph.wAlignment - 1); end; class function TWin32WSCustomRichBox.Para_GetFirstIndent( const AWinControl: TWinControl): Longint; var Paragraph: TPARAFORMAT2; begin P_GetAttributes(AWinControl.Handle, Paragraph); Result := Paragraph.dxOffset div 20; end; class function TWin32WSCustomRichBox.Para_GetLeftIndent( const AWinControl: TWinControl): Longint; var Paragraph: TPARAFORMAT2; begin P_GetAttributes(AWinControl.Handle, Paragraph); Result := Paragraph.dxStartIndent div 20 end; class function TWin32WSCustomRichBox.Para_GetRightIndent( const AWinControl: TWinControl): Longint; var Paragraph: TPARAFORMAT2; begin P_GetAttributes(AWinControl.Handle, Paragraph); Result := Paragraph.dxRightIndent div 20; end; class function TWin32WSCustomRichBox.Para_GetNumbering( const AWinControl: TWinControl): TNumberingStyle; var Paragraph: TPARAFORMAT2; begin P_GetAttributes(AWinControl.Handle, Paragraph); Result := TNumberingStyle(Paragraph.wNumbering); end; class function TWin32WSCustomRichBox.Para_GetTab( const AWinControl: TWinControl; Index: Byte): Longint; var Paragraph: TPARAFORMAT2; begin P_GetAttributes(AWinControl.Handle, Paragraph); Result := Paragraph.rgxTabs[Index] div 20; end; class function TWin32WSCustomRichBox.Para_GetTabCount( const AWinControl: TWinControl): Integer; var Paragraph: TPARAFORMAT2; begin P_GetAttributes(AWinControl.Handle, Paragraph); Result := Paragraph.cTabCount; end; class procedure TWin32WSCustomRichBox.Font_SetCharset(const AWinControl: TWinControl; Value: TFontCharset); var FMT: TCHARFORMAT2; begin InitFMT(FMT); with FMT do begin dwMask := CFM_CHARSET; bCharSet := Value; end; F_SetAttributes(AWinControl.Handle, FMT); end; class procedure TWin32WSCustomRichBox.Font_SetColor(const AWinControl: TWinControl; Value: TColor); var FMT: TCHARFORMAT2; begin InitFMT(FMT); with FMT do begin dwMask := CFM_COLOR; if Value = clWindowText then dwEffects := CFE_AUTOCOLOR else crTextColor := ColorToRGB(Value); end; F_SetAttributes(AWinControl.Handle, FMT); end; class procedure TWin32WSCustomRichBox.Font_SetName(const AWinControl: TWinControl; Value: TFontName); var FMT: TCHARFORMAT2; begin InitFMT(FMT); with FMT do begin dwMask := CFM_FACE; StrPLCopy(szFaceName, Value, SizeOf(szFaceName)); end; F_SetAttributes(AWinControl.Handle, FMT); end; class procedure TWin32WSCustomRichBox.Font_SetPitch(const AWinControl: TWinControl; Value: TFontPitch); var FMT: TCHARFORMAT2; begin InitFMT(FMT); with FMT do begin case Value of fpVariable: FMT.bPitchAndFamily := VARIABLE_PITCH; fpFixed: FMT.bPitchAndFamily := FIXED_PITCH; else FMT.bPitchAndFamily := DEFAULT_PITCH; end; end; F_SetAttributes(AWinControl.Handle, FMT); end; class procedure TWin32WSCustomRichBox.Font_SetProtected(const AWinControl: TWinControl; Value: boolean); var FMT: TCHARFORMAT2; begin InitFMT(FMT); with FMT do begin dwMask := CFM_PROTECTED; if Value then dwEffects := CFE_PROTECTED; end; F_SetAttributes(AWinControl.Handle, FMT); end; class procedure TWin32WSCustomRichBox.Font_SetSize(const AWinControl: TWinControl; Value: integer); var FMT: TCHARFORMAT2; begin InitFMT(FMT); with FMT do begin dwMask := integer(CFM_SIZE); yHeight := Value * 20; end; F_SetAttributes(AWinControl.Handle, FMT); end; class procedure TWin32WSCustomRichBox.Font_SetStyle(const AWinControl: TWinControl; Value: TFontStyles); var FMT: TCHARFORMAT2; begin InitFMT(FMT); with FMT do begin dwMask := CFM_BOLD or CFM_ITALIC or CFM_UNDERLINE or CFM_STRIKEOUT; if fsBold in Value then dwEffects := dwEffects or CFE_BOLD; if fsItalic in Value then dwEffects := dwEffects or CFE_ITALIC; if fsUnderline in Value then dwEffects := dwEffects or CFE_UNDERLINE; if fsStrikeOut in Value then dwEffects := dwEffects or CFE_STRIKEOUT; end; F_SetAttributes(AWinControl.Handle, FMT); end; class procedure TWin32WSCustomRichBox.Para_SetAlignment( const AWinControl: TWinControl; Value: TAlignment); var Paragraph: TPARAFORMAT2; begin InitPARAFMT(Paragraph); with Paragraph do begin dwMask := PFM_ALIGNMENT; wAlignment := Ord(Value) + 1; end; P_SetAttributes(AWinControl.Handle, Paragraph); end; class procedure TWin32WSCustomRichBox.Para_SetFirstIndent( const AWinControl: TWinControl; Value: Longint); var Paragraph: TPARAFORMAT2; begin InitPARAFMT(Paragraph); with Paragraph do begin dwMask := PFM_OFFSET; dxOffset := Value * 20; end; P_SetAttributes(AWinControl.Handle, Paragraph); end; class procedure TWin32WSCustomRichBox.Para_SetLeftIndent( const AWinControl: TWinControl; Value: Longint); var Paragraph: TPARAFORMAT2; begin InitPARAFMT(Paragraph); with Paragraph do begin dwMask := PFM_STARTINDENT; dxStartIndent := Value * 20; end; P_SetAttributes(AWinControl.Handle, Paragraph); end; class procedure TWin32WSCustomRichBox.Para_SetRightIndent( const AWinControl: TWinControl; Value: Longint); var Paragraph: TPARAFORMAT2; begin InitPARAFMT(Paragraph); with Paragraph do begin dwMask := PFM_RIGHTINDENT; dxRightIndent := Value * 20; end; P_SetAttributes(AWinControl.Handle, Paragraph); end; class procedure TWin32WSCustomRichBox.Para_SetNumbering( const AWinControl: TWinControl; Value: TNumberingStyle); var Paragraph: TPARAFORMAT2; begin case Value of nsBullets: if TWin32WSCustomRichBox.Para_GetLeftIndent(AWinControl) < 10 then TWin32WSCustomRichBox.Para_SetLeftIndent(AWinControl, 10); nsNone: TWin32WSCustomRichBox.Para_SetLeftIndent(AWinControl, 0); end; InitPARAFMT(Paragraph); with Paragraph do begin dwMask := PFM_NUMBERING; wNumbering := Ord(Value); end; P_SetAttributes(AWinControl.Handle, Paragraph); end; class procedure TWin32WSCustomRichBox.Para_SetTab( const AWinControl: TWinControl; Index: Byte; Value: Longint); var Paragraph: TPARAFORMAT2; begin InitPARAFMT(Paragraph); with Paragraph do begin rgxTabs[Index] := Value * 20; dwMask := PFM_TABSTOPS; if cTabCount < Index then cTabCount := Index; P_SetAttributes(AWinControl.Handle, Paragraph); end; end; class procedure TWin32WSCustomRichBox.Para_SetTabCount( const AWinControl: TWinControl; Value: Integer); var Paragraph: TPARAFORMAT2; begin P_GetAttributes(AWinControl.Handle, Paragraph); with Paragraph do begin dwMask := PFM_TABSTOPS; cTabCount := Value; P_SetAttributes(AWinControl.Handle, Paragraph); end; end; class procedure TWin32WSCustomRichBox.SaveToStream( const AWinControl: TWinControl; var Stream: TStream); var EditStream_: TEditStream; StrType: integer; begin EditStream_.dwCookie := longint(Pointer(@Stream)); EditStream_.pfnCallback := @StreamSave; EditStream_.dwError := 0; if TCustomRichBox(AWinControl).PlainText then StrType := SF_TEXT else StrType := SF_RTF; SendMessage(AWinControl.Handle, EM_STREAMOUT, StrType, longint(@EditStream_)); end; class procedure TWin32WSCustomRichBox.LoadFromStream( const AWinControl: TWinControl; const Stream: TStream); var EditStream_: TEditStream; StrType: integer; begin EditStream_.dwCookie := longint(Pointer(@Stream)); EditStream_.pfnCallback := @StreamLoad; EditStream_.dwError := 0; if TCustomRichBox(AWinControl).PlainText then StrType := SF_TEXT else StrType := SF_RTF; SendMessage(AWinControl.Handle, EM_STREAMIN, StrType, LPARAM(@EditStream_)); end; initialization finalization if (RichEditLibrary_HWND <> 0) then FreeLibrary(RichEditLibrary_HWND); end.
unit InfoBook; interface uses Classes, ExtCtrls, Controls, Messages{, Buffer, TileManager, TilePanel}; type TInfoBook = class; CInfoBookPage = class of TInfoBookPage; TInfoBookPage = class( TCustomPanel ) public constructor Create( anOwner : TComponent ); override; destructor Destroy; override; public procedure MoveTo( ord : integer ); protected procedure PageSelected; virtual; procedure PageUnselected; virtual; private fPageName : string; fIndex : integer; protected procedure SetPageName( aPageName : string ); virtual; function GetInfoBook : TInfoBook; virtual; published property InfoBook : TInfoBook read GetInfoBook; property PageName : string read fPageName write SetPageName; property Index : integer read fIndex write fIndex; property Align; property Alignment; property BevelInner; property BevelOuter; property BevelWidth; property BorderWidth; property BorderStyle; property DragCursor; property DragMode; property Enabled; property Caption; property Color; property Ctl3D; property Font; property Locked; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; public property Canvas; { private fTileInfo : TTileInfo; } private fExposing : boolean; private procedure WMEraseBkgnd(var Message : TMessage); message WM_ERASEBKGND; public property Exposing : boolean read fExposing; end; TPageOperation = (popInsertion, popSelection, popPropertyChange, popDeletion); TOnPageModified = procedure( Operation : TPageOperation; Page : TInfoBookPage ) of object; TInfoBook = class( TCustomPanel ) public constructor Create( anOwner : TComponent ); override; destructor Destroy; override; protected class function PageClass : CInfoBookPage; virtual; public function AddPage : TInfoBookPage; virtual; procedure DeletePage( PageIdx : integer ); virtual; procedure AddNewPage ( Page : TInfoBookPage ); procedure RemoveReferencesTo( Page : TInfoBookPage ); procedure DeleteAllPages; private fActivePage : TInfoBookPage; fOnPageModified : TOnPageModified; protected function GetPageIndex : integer; virtual; procedure SetPageIndex( PageIdx : integer ); virtual; procedure SetActivePage( Page : TInfoBookPage ); virtual; function GetPage( index : integer ) : TInfoBookPage; virtual; function GetPageCount : integer; public property PageCount : integer read GetPageCount; property Pages[index : integer] : TInfoBookPage read GetPage; published property ActivePage : TInfoBookPage read fActivePage write SetActivePage; property PageIndex : integer read GetPageIndex write SetPageIndex; property OnPageModified : TOnPageModified read fOnPageModified write fOnPageModified; published property Align; property Alignment; property BevelInner; property BevelOuter; property BevelWidth; property BorderWidth; property BorderStyle; property DragCursor; property DragMode; property Enabled; property Caption; property Color; property Ctl3D; property Font; property Locked; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; end; procedure Register; implementation uses Windows {$IFDEF VER140} , DesignIntf {$ELSE} , Dsgnintf {$ENDIF} //.rag {, Collection}; // TInfoBookPage constructor TInfoBookPage.Create( anOwner : TComponent ); begin inherited; BevelInner := bvNone; BevelOuter := bvNone; Align := alClient; end; destructor TInfoBookPage.Destroy; begin //fInfoBook.RemoveReferencesTo( self ); inherited; end; procedure TInfoBookPage.MoveTo( ord : integer ); { var Coll : TCollection; delta : integer; i : integer; } begin { Coll := TCollection.Create( 10, 5, rkUse ); for i := 0 to pred(InfoBook.ControlCount) do Coll.Insert( InfoBook.Pages[i] ); delta := abs(Index - ord) div (Index - ord); i := ord; while i <> Index do begin (Coll[i] as TInfoBookPage).Index := i + delta; inc( i, delta ); end; Index := ord; Coll.Free; } end; procedure TInfoBookPage.PageSelected; begin if (InfoBook <> nil) and assigned(InfoBook.OnPageModified) then InfoBook.OnPageModified( popSelection, self ); end; procedure TInfoBookPage.PageUnselected; begin end; procedure TInfoBookPage.SetPageName( aPageName : string ); begin fPageName := aPageName; if (InfoBook <> nil) and assigned(InfoBook.OnPageModified) then InfoBook.OnPageModified( popPropertyChange, self ); end; function TInfoBookPage.GetInfoBook : TInfoBook; begin if Parent <> nil then result := Parent as TInfoBook else result := nil; end; procedure TInfoBookPage.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; // TInfoBook constructor TInfoBook.Create( anOwner : TComponent ); begin inherited; BevelInner := bvNone; BevelOuter := bvNone; Align := alClient; Caption := ''; end; destructor TInfoBook.Destroy; begin inherited; end; class function TInfoBook.PageClass : CInfoBookPage; begin result := TInfoBookPage; end; function TInfoBook.AddPage : TInfoBookPage; begin result := PageClass.Create( self ); AddNewPage( result ); end; procedure TInfoBook.DeletePage( PageIdx : integer ); var Page : TInfoBookPage; begin Page := Pages[PageIdx]; if assigned(OnPageModified) then OnPageModified( popDeletion, Page ); RemoveReferencesTo( Page ); Page.Parent := nil; Page.Free; if ControlCount > 0 then PageIndex := 0; end; procedure TInfoBook.AddNewPage( Page : TInfoBookPage ); begin { if Page.TileName = '' then Page.TileName := TileName; } if (Page.Owner <> nil) and (Page.Owner <> self) then begin Page.Owner.RemoveComponent( Page ); InsertComponent( Page ); end; Page.Caption := ''; Page.Visible := false; Page.Parent := self; Page.fIndex := pred(ControlCount); //Page.PopupMenu := PopupMenu; ActivePage := Page; if assigned(OnPageModified) then OnPageModified( popInsertion, Page ); end; procedure TInfoBook.RemoveReferencesTo( Page : TInfoBookPage ); var i : integer; begin if not (csDestroying in ComponentState) then begin for i := 0 to pred(ControlCount) do if (Controls[i] as TInfoBookPage).Index > Page.Index then dec((Controls[i] as TInfoBookPage).fIndex); if Page = ActivePage then ActivePage := nil; end; end; procedure TInfoBook.DeleteAllPages; begin while PageCount > 0 do DeletePage(0); end; function TInfoBook.GetPageIndex : integer; begin if ActivePage <> nil then result := ActivePage.Index else result := -1; end; procedure TInfoBook.SetPageIndex( PageIdx : integer ); begin if PageIdx <> -1 then ActivePage := Pages[PageIdx] else ActivePage := nil; end; procedure TInfoBook.SetActivePage( Page : TInfoBookPage ); begin if Page <> ActivePage then begin if Page <> nil then begin Page.fExposing := true; Page.Visible := true; Page.SetZOrder( true ); Page.fExposing := false; end; if ActivePage <> nil then begin ActivePage.PageUnselected; ActivePage.Visible := false; end; fActivePage := Page; end; if ActivePage <> nil then ActivePage.PageSelected; end; function TInfoBook.GetPageCount : integer; begin result := ControlCount; end; function TInfoBook.GetPage( index : integer ) : TInfoBookPage; var i : integer; begin i := 0; while (i < ControlCount) and ((Controls[i] as TInfoBookPage).Index <> index) do inc( i ); if i < ControlCount then result := TInfoBookPage(Controls[i]) else result := nil; end; procedure TInfoBook.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; // Design time stuff: {$IFDEF VER140} // TBaseComponentEditor e implementar IComponentEditor y IDefaultEditor, {$ELSE} type TInfoBookEditor = class( TDefaultEditor ) procedure ExecuteVerb( Index : integer ); override; function GetVerb ( Index : integer ) : string; override; function GetVerbCount : integer; override; end; {$ENDIF} {$IFDEF VER140} {$ELSE} procedure TInfoBookEditor.ExecuteVerb( Index : integer ); var Book : TInfoBook; InfoBookPage : TInfoBookPage; Designer : IFormDesigner; //.rag i : integer; begin if Index = 0 then begin if Component is TInfoBookPage then Book := TInfoBook(TInfoBookPage(Component).Parent) else Book := TInfoBook(Component); if Book <> nil then begin Designer := Self.Designer; InfoBookPage := Book.PageClass.Create(Designer.Form); Book.AddNewPage( InfoBookPage ); try InfoBookPage.Name := Designer.UniqueName(TInfoBookPage.ClassName); InfoBookPage.Caption := ''; for i := 0 to pred(InfoBookPage.ComponentCount) do InfoBookPage.Components[i].Name := Designer.UniqueName(InfoBookPage.Components[i].ClassName); InfoBookPage.Parent := Book; except InfoBookPage.Free; raise; end; Designer.SelectComponent(InfoBookPage); Designer.Modified; end; end; end; function TInfoBookEditor.GetVerb( Index : integer ) : string; begin result := '&Add Page'; end; function TInfoBookEditor.GetVerbCount : integer; begin result := 1; end; {$ENDIF} procedure Register; begin RegisterComponents( 'Merchise', [TInfoBook] ); {$IFDEF VER140} {$ELSE} RegisterComponentEditor(TInfoBook, TInfoBookEditor); RegisterComponentEditor(TInfoBookPage, TInfoBookEditor); {$EndIf} end; end.
{!DOCTOPIC}{ Imaging functions } {!DOCREF} { @method: function se.GaussKernel(Radius: Integer; Sigma:Single): T2DFloatArray; @desc: Generates a gussin matrix/kernel. } function SimbaExt.GaussKernel(Radius: Integer; Sigma:Single): T2DFloatArray; begin Result := exp_GaussKernel(Radius, Sigma); end; {!DOCREF} { @method: function se.ImBlur(ImgArr: TIntMatrix; Radius:Integer): TIntMatrix; @desc: Applies a box-blur to the image. Running it multiple times with a small blur results similarly as to what a gaussian blur would, but larger. } function SimbaExt.ImBlur(ImgArr: TIntMatrix; Radius:Integer): TIntMatrix; begin Result := exp_ImBlur(ImgArr, Radius); end; {!DOCREF} { @method: function se.ImMedianBlur(ImgArr: TIntMatrix; Radius:Integer): TIntMatrix; @desc: Applies a median filter. Picks the median pixel value in a window with the given radius `Radius`. } function SimbaExt.ImMedianBlur(ImgArr: TIntMatrix; Radius:Integer): TIntMatrix; begin Result := exp_ImMedianBlur(ImgArr, Radius); end; {!DOCREF} { @method: function se.ImBrighten(ImgArr:TIntMatrix; Amount:Extended; Legacy:Boolean): TIntMatrix; @desc: Allows you to modify the brightness of the image } function SimbaExt.ImBrighten(ImgArr:TIntMatrix; Amount:Extended; Legacy:Boolean): TIntMatrix; begin Result := exp_ImBrighten(ImgArr, Amount, Legacy); end; {!DOCREF} { @method: function se.ImEnhance(ImgArr:TIntMatrix; Enhancement:Byte; C:Extended=0): TIntMatrix; @desc: Enhances R,G,B levels. } function SimbaExt.ImEnhance(ImgArr:TIntMatrix; Enhancement:Byte; C:Extended=0): TIntMatrix; begin Result := exp_ImEnhance(ImgArr, Enhancement, C); end; {!DOCREF} { @method: function se.ImThreshold(const ImgArr:TIntMatrix; Threshold, Alpha, Beta:Byte; Invert:Boolean=False): TIntMatrix; @desc: A simple threshold function. Anything above Threshold = Beta, and bellow = Alpha. Swaps Alpha and beta if Invert=True [params] ImgArr: A 2D matrix representation of an image. Alpha,Beta: Lower and upper result colors (0-255). Invert: Invert the result [/params] } function SimbaExt.ImThreshold(const ImgArr:TIntMatrix; Threshold, Alpha, Beta:Byte; Invert:Boolean=False): TIntMatrix; begin Result := exp_ImThreshold(ImgArr, Threshold, Alpha, Beta, Invert); end; {!DOCREF} { @method: function se.ImThresholdAdaptive(const ImgArr:T2DIntegerArray; Alpha, Beta: Byte; Invert:Boolean; Method:TThreshAlgo; C:Int32=0): TIntMatrix; @desc: Threshold function which first calculates the average color of the image, then turns anything above Mean = Beta, and bellow = Alpha. [params] ImgArr: A 2D matrix representation of an image. Alpha,Beta: Lower and upper result colors (0-255). Invert: Invert the result C: Modiefier to mean. Negative C substracts from mean, positive C adds to mean. Method: TA_MEAN | TA_MINMAX [/params] } function SimbaExt.ImThresholdAdaptive(const ImgArr:TIntMatrix; Alpha, Beta: Byte; Invert:Boolean; Method:TThreshAlgo; C:Int32=0): TIntMatrix; begin Result := exp_ImThresholdAdaptive(ImgArr, Alpha, Beta, Invert, Method, C); end; {!DOCREF} { @method: function se.ImFindContours(const ImgArr:TIntMatrix; Outlines:Boolean): T2DPointArray; @desc: Meh... } function SimbaExt.ImFindContours(const ImgArr:TIntMatrix; Outlines:Boolean): T2DPointArray; begin Result := exp_ImFindContours(ImgArr,Outlines); end; {!DOCREF} { @method: function se.ImCEdges(const ImgArr: TIntMatrix; MinDiff: Integer): TPointArray; @desc: Meh... } function SimbaExt.ImCEdges(const ImgArr: TIntMatrix; MinDiff: Integer): TPointArray; begin Result := exp_ImCEdges(ImgArr, MinDiff); end; {!DOCREF} { @method: function se.ImSobel(const ImgArr:TIntMatrix): TIntMatrix; @desc: Applies the sobel function on the image, both x, any y-wise } function SimbaExt.ImSobel(const ImgArr:TIntMatrix): TIntMatrix; begin Result := exp_ImSobel(ImgArr); end; {!DOCREF} { @method: function se.ImConvolve(const ImgArr:TIntMatrix; Mask:T2DFloatArray): TIntMatrix; @desc: 2D Convoution. [code=pascal] var Im:TRafBitmap; begin Im.Open('lena.png'); Im.FromMatrix( se.ImConvolve(Im.ToMatrix(), se.GaussKernel(5,3)) ); Im.Debug(); Im.Free(); end; [/code] } function SimbaExt.ImConvolve(const ImgArr:TIntMatrix; Mask:T2DFloatArray): TIntMatrix; begin Result := exp_ImConvolve(ImgArr, Mask); end; {!DOCREF} { @method: function se.ImGaussBlur(const ImgArr:TIntMatrix; Radius: Int32; Sigma:Single=1.5): TIntMatrix; @desc: Applies a gaussian blur to the image. } function SimbaExt.ImGaussBlur(const ImgArr:TIntMatrix; Radius: Int32; Sigma:Single=1.5): TIntMatrix; begin SetLength(Result, Length(ImgArr), Length(ImgArr[0])); exp_ImGaussBlur(ImgArr, Result, Radius, Sigma); end; {!DOCREF} { @method: function se.ImBlend(ImgArr1, ImgArr2:TIntMatrix; Alpha:Single): TIntMatrix; @desc: Applies a gaussian blur to the image. } function SimbaExt.ImBlend(ImgArr1, ImgArr2:TIntMatrix; Alpha:Single): TIntMatrix; begin Result := exp_ImBlend(ImgArr1, ImgArr2, Alpha); end; {!DOCREF} { @method: procedure se.ImResize(var ImgArr:TIntMatrix; NewW, NewH: Int32; Method:TResizeAlgo); @desc: Resize the image (matrix) by one of RA_NEAREST, RA_BICUBIC, and RA_BILINEAR interpolation } procedure SimbaExt.ImResize(var ImgArr:TIntMatrix; NewW, NewH: Integer; Method:TResizeAlgo); begin exp_ImResize(ImgArr, NewW, NewH, Method); end; {!DOCREF} { @method: function se.ImRotate(ImgArr:T2DIntArray; Angle:Single; Expand:Boolean; BiLinear:Boolean=True): T2DIntArray; @desc: Returns a rotated version of the image matrix, you can choose if you want to `expand` it, and if it should use `bilinear` interpolation (smoother rotation). Angle should be given in radians. } function SimbaExt.ImRotate(ImgArr:T2DIntArray; Angle:Single; Expand:Boolean; Bilinear:Boolean=True): T2DIntArray; begin Result := exp_ImRotate(ImgArr, Angle, Expand, Bilinear); end; {*=========================================================================================| | CornerDet.pas [placing it hear for now] | | Update: Replaced Exteded with Single :: Resulted in ~2x speedup | |=========================================================================================*} {!DOCREF} { @method: function se.CornerResponse(const ImgArr:TIntMatrix; GaussDev:Single; KSize:Integer): T2DFloatArray; @desc: Computes the harris response of the image, usually used to locate the corners. } function SimbaExt.CornerResponse(const ImgArr:TIntMatrix; GaussDev:Single; KSize:Integer): T2DFloatArray; begin Result := exp_CornerResponse(ImgArr, GaussDev, KSize); end; {!DOCREF} { @method: function se.FindCornerPoints(var ImgArr:TIntMatrix; GaussDev:Single; KSize:Integer; Thresh:Single; Footprint:Integer): TPointArray; @desc: Locates all the corner points in the image.[br] A few c'overloads' to simplify your life: [code=pascal] > function se.FindCornerPoints(var ImgArr:TIntMatrix; Thresh:Single; Footprint:Integer): TPointArray; overload; > function se.FindCornerPoints(var ImgArr:TIntMatrix; Thresh:Single): TPointArray; overload; [/code] [params] ImgArr: A 2D matrix representation of an image. GaussDev: Guassian deviation, used when we blur the image, a value between 1-3 is normal. KSize: Size of the gaussblur filter, 1 is usually good. Thresh: This is a tolerance, anything above the threshold = result point. Footprint: The square which we check for a peak, larger is better, but also slower. [/params] } function SimbaExt.FindCornerPoints(var ImgArr:TIntMatrix; GaussDev:Single; KSize:Integer; Thresh:Single; Footprint:Integer): TPointArray; begin Result := exp_FindCornerPoints(ImgArr, GaussDev, KSize, Thresh, Footprint); end; function SimbaExt.FindCornerPoints(var ImgArr:TIntMatrix; Thresh:Single; Footprint:Integer): TPointArray; overload; begin Result := exp_FindCornerPoints(ImgArr, 1.0, 1, Thresh, Footprint); end; function SimbaExt.FindCornerPoints(var ImgArr:TIntMatrix; Thresh:Single): TPointArray; overload; begin Result := exp_FindCornerPoints(ImgArr, 1.0, 1, Thresh, 5); end; {!DOCREF} { @method: function se.FindCornerMidPoints(var ImgArr:TIntMatrix; GaussDev:Single; KSize:Integer; Thresh:Single; MinDist:Integer): TPointArray; @desc: Locates all the corner points in the image. Similar to c'se.FindCornerPoints', only that this one uses ClusterTPA to find the mean of each point within the given tolerance. So if two points are within the given MinDist, they will be merged as one.[br] A few c'overloads' to simplify your life: [code=delphi] > function se.FindCornerMidPoints(var ImgArr:TIntMatrix; Thresh:Single; MinDist:Integer): TPointArray; overload; > function se.FindCornerMidPoints(var ImgArr:TIntMatrix; Thresh:Single): TPointArray; overload; [/code] Example: [code=pascal] var BMP:TRafBitmap; TPA: TPointArray; i:Int32; begin BMP.Open('calibrationimage.png'); TPA := se.FindCornerMidPoints(BMP.ToMatrix(), 2.0, 2, 0.07, 3); for i:=0 to High(TPA) do BMP.SetPixels(se.TPACross(TPA[i], 3), 255); BMP.Debug(); BMP.Free; end. [/code] Output: [img]http://slackworld.net/downloads/calibrationimage.png[/img] } function SimbaExt.FindCornerMidPoints(var ImgArr:TIntMatrix; GaussDev:Single; KSize:Integer; Thresh:Single; MinDist:Integer): TPointArray; begin Result := exp_FindCornerMidPoints(ImgArr, GaussDev, KSize, Thresh, MinDist); end; function SimbaExt.FindCornerMidPoints(var ImgArr:TIntMatrix; Thresh:Single; MinDist:Integer): TPointArray; overload; begin Result := exp_FindCornerPoints(ImgArr, 2.0, 1, Thresh, MinDist); end; function SimbaExt.FindCornerMidPoints(var ImgArr:TIntMatrix; Thresh:Single): TPointArray; overload; begin Result := exp_FindCornerPoints(ImgArr, 2.0, 1, Thresh, 3); end;
unit NOT_FINISHED_TestFrameWork; // Модуль: "w:\common\components\rtl\external\DUnit\src\NOT_FINISHED_TestFrameWork.pas" // Стереотип: "UtilityPack" // Элемент модели: "TestFrameWork" MUID: (4B2A0DCE03A9) interface {$If Defined(nsTest)} uses l3IntfUses , SysUtils ; type TTestResult = class(TObject) private FStop: Boolean; public function ShouldStop: Boolean; end;//TTestResult ITest = interface ['{3BA74AE0-1DCB-48A8-B8E4-410AAAD2FE44}'] function HasScriptChildren: Boolean; procedure RunTest(aTestResult: TTestResult); function GetSubFolder: AnsiString; procedure ClearEtalons; end;//ITest TAbstractTest = class(TInterfacedObject, ITest) protected function DoGetSubFolder: AnsiString; virtual; abstract; procedure DoClearEtalon; virtual; abstract; procedure Cleanup; virtual; procedure InitFields; virtual; function GetEnabled: Boolean; virtual; procedure SetEnabled(Value: Boolean); virtual; function GetFolder: AnsiString; virtual; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; virtual; {* Идентификатор элемента модели, который описывает тест } function DoHasScriptChildren: Boolean; virtual; procedure DoRunTest(aTestResult: TTestResult); virtual; abstract; function HasScriptChildren: Boolean; procedure RunTest(aTestResult: TTestResult); function GetSubFolder: AnsiString; procedure ClearEtalons; public function NotForTerminalSession: Boolean; virtual; {* Не запускать тест в терминальной сессии } end;//TAbstractTest ITestSuite = interface ['{1524FACE-9F51-4D1D-99F8-6CB79114530A}'] procedure AddTest(const aTest: ITest); procedure ReReadAbstractTests; end;//ITestSuite TTestFailure = class end;//TTestFailure TTestCase = class(TAbstractTest) private f_TestResult: TTestResult; f_DataSubFolder: AnsiString; {* Папка с данными тестов для режима работы с файлами из папки. } protected function ShouldStop: Boolean; function FolderMode: Boolean; {* Тест для файлов из папки. } class function IsScript: Boolean; virtual; {* Хак для конструктора - из-за хитрой иерархии и кучи конструкторов в TTestSuite. } procedure DoRunTest(aTestResult: TTestResult); override; function DoGetSubFolder: AnsiString; override; procedure DoClearEtalon; override; public class function Suite: ITestSuite; virtual; constructor Create(const aMethodName: AnsiString; const aFolder: AnsiString); reintroduce; virtual; public property DataSubFolder: AnsiString read f_DataSubFolder; {* Папка с данными тестов для режима работы с файлами из папки. } end;//TTestCase TTestCaseClass = TTestCase; TTestSuite = class(TAbstractTest, ITestSuite) private f_Suffix: AnsiString; protected procedure DoReReadAbstractTests; virtual; procedure DoAddTest(const aTest: ITest); virtual; procedure AddTest(const aTest: ITest); procedure DoRunTest(aTestResult: TTestResult); override; function DoGetSubFolder: AnsiString; override; procedure ReReadAbstractTests; procedure DoClearEtalon; override; public procedure AddTests(aTestClass: TTestCaseClass); virtual; end;//TTestSuite TTestMethod = procedure of object; ETestFailure = class(EAbort) end;//ETestFailure procedure RegisterTest; {$IfEnd} // Defined(nsTest) implementation {$If Defined(nsTest)} uses l3ImplUses {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} , ITestWordsPack {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) //#UC START# *4B2A0DCE03A9impl_uses* //#UC END# *4B2A0DCE03A9impl_uses* ; procedure RegisterTest; //#UC START# *4EA66E6C038E_4B2A0DCE03A9_var* //#UC END# *4EA66E6C038E_4B2A0DCE03A9_var* begin //#UC START# *4EA66E6C038E_4B2A0DCE03A9_impl* !!! Needs to be implemented !!! //#UC END# *4EA66E6C038E_4B2A0DCE03A9_impl* end;//RegisterTest function TTestResult.ShouldStop: Boolean; //#UC START# *4DDE1A9201A4_4B2F4252038D_var* //#UC END# *4DDE1A9201A4_4B2F4252038D_var* begin //#UC START# *4DDE1A9201A4_4B2F4252038D_impl* Result := FStop; //#UC END# *4DDE1A9201A4_4B2F4252038D_impl* end;//TTestResult.ShouldStop procedure TAbstractTest.Cleanup; //#UC START# *4B2F40FD0088_4B2F40E70101_var* //#UC END# *4B2F40FD0088_4B2F40E70101_var* begin //#UC START# *4B2F40FD0088_4B2F40E70101_impl* !!! Needs to be implemented !!! //#UC END# *4B2F40FD0088_4B2F40E70101_impl* end;//TAbstractTest.Cleanup procedure TAbstractTest.InitFields; //#UC START# *4B30EEA10210_4B2F40E70101_var* //#UC END# *4B30EEA10210_4B2F40E70101_var* begin //#UC START# *4B30EEA10210_4B2F40E70101_impl* !!! Needs to be implemented !!! //#UC END# *4B30EEA10210_4B2F40E70101_impl* end;//TAbstractTest.InitFields function TAbstractTest.GetEnabled: Boolean; //#UC START# *4C07996901BE_4B2F40E70101_var* //#UC END# *4C07996901BE_4B2F40E70101_var* begin //#UC START# *4C07996901BE_4B2F40E70101_impl* !!! Needs to be implemented !!! //#UC END# *4C07996901BE_4B2F40E70101_impl* end;//TAbstractTest.GetEnabled procedure TAbstractTest.SetEnabled(Value: Boolean); //#UC START# *4C446D7903B7_4B2F40E70101_var* //#UC END# *4C446D7903B7_4B2F40E70101_var* begin //#UC START# *4C446D7903B7_4B2F40E70101_impl* !!! Needs to be implemented !!! //#UC END# *4C446D7903B7_4B2F40E70101_impl* end;//TAbstractTest.SetEnabled function TAbstractTest.GetFolder: AnsiString; {* Папка в которую входит тест } //#UC START# *4C937013031D_4B2F40E70101_var* //#UC END# *4C937013031D_4B2F40E70101_var* begin //#UC START# *4C937013031D_4B2F40E70101_impl* Result := ''; //#UC END# *4C937013031D_4B2F40E70101_impl* end;//TAbstractTest.GetFolder function TAbstractTest.NotForTerminalSession: Boolean; {* Не запускать тест в терминальной сессии } //#UC START# *4C988C1B0246_4B2F40E70101_var* //#UC END# *4C988C1B0246_4B2F40E70101_var* begin //#UC START# *4C988C1B0246_4B2F40E70101_impl* Result := false; //#UC END# *4C988C1B0246_4B2F40E70101_impl* end;//TAbstractTest.NotForTerminalSession function TAbstractTest.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } //#UC START# *4DAED6F60146_4B2F40E70101_var* //#UC END# *4DAED6F60146_4B2F40E70101_var* begin //#UC START# *4DAED6F60146_4B2F40E70101_impl* Result := ''; //#UC END# *4DAED6F60146_4B2F40E70101_impl* end;//TAbstractTest.GetModelElementGUID function TAbstractTest.DoHasScriptChildren: Boolean; //#UC START# *4DCCD004030E_4B2F40E70101_var* //#UC END# *4DCCD004030E_4B2F40E70101_var* begin //#UC START# *4DCCD004030E_4B2F40E70101_impl* Result := False; //#UC END# *4DCCD004030E_4B2F40E70101_impl* end;//TAbstractTest.DoHasScriptChildren function TAbstractTest.HasScriptChildren: Boolean; //#UC START# *4DCCCFF001A4_4B2F40E70101_var* //#UC END# *4DCCCFF001A4_4B2F40E70101_var* begin //#UC START# *4DCCCFF001A4_4B2F40E70101_impl* Result := DoHasScriptChildren; //#UC END# *4DCCCFF001A4_4B2F40E70101_impl* end;//TAbstractTest.HasScriptChildren procedure TAbstractTest.RunTest(aTestResult: TTestResult); //#UC START# *4DDE1E8702D3_4B2F40E70101_var* //#UC END# *4DDE1E8702D3_4B2F40E70101_var* begin //#UC START# *4DDE1E8702D3_4B2F40E70101_impl* !!! Needs to be implemented !!! //#UC END# *4DDE1E8702D3_4B2F40E70101_impl* end;//TAbstractTest.RunTest function TAbstractTest.GetSubFolder: AnsiString; //#UC START# *4F9A4FBF00C0_4B2F40E70101_var* //#UC END# *4F9A4FBF00C0_4B2F40E70101_var* begin //#UC START# *4F9A4FBF00C0_4B2F40E70101_impl* !!! Needs to be implemented !!! //#UC END# *4F9A4FBF00C0_4B2F40E70101_impl* end;//TAbstractTest.GetSubFolder procedure TAbstractTest.ClearEtalons; //#UC START# *51B1DD5F0080_4B2F40E70101_var* //#UC END# *51B1DD5F0080_4B2F40E70101_var* begin //#UC START# *51B1DD5F0080_4B2F40E70101_impl* !!! Needs to be implemented !!! //#UC END# *51B1DD5F0080_4B2F40E70101_impl* end;//TAbstractTest.ClearEtalons function TTestCase.ShouldStop: Boolean; //#UC START# *4DDE2A3D0314_4B2A0DDE028B_var* //#UC END# *4DDE2A3D0314_4B2A0DDE028B_var* begin //#UC START# *4DDE2A3D0314_4B2A0DDE028B_impl* Result := f_TestResult.ShouldStop; //#UC END# *4DDE2A3D0314_4B2A0DDE028B_impl* end;//TTestCase.ShouldStop class function TTestCase.Suite: ITestSuite; //#UC START# *4EA553E901DB_4B2A0DDE028B_var* //#UC END# *4EA553E901DB_4B2A0DDE028B_var* begin //#UC START# *4EA553E901DB_4B2A0DDE028B_impl* !!! Needs to be implemented !!! //#UC END# *4EA553E901DB_4B2A0DDE028B_impl* end;//TTestCase.Suite function TTestCase.FolderMode: Boolean; {* Тест для файлов из папки. } //#UC START# *4EA6790E0142_4B2A0DDE028B_var* //#UC END# *4EA6790E0142_4B2A0DDE028B_var* begin //#UC START# *4EA6790E0142_4B2A0DDE028B_impl* !!! Needs to be implemented !!! //#UC END# *4EA6790E0142_4B2A0DDE028B_impl* end;//TTestCase.FolderMode class function TTestCase.IsScript: Boolean; {* Хак для конструктора - из-за хитрой иерархии и кучи конструкторов в TTestSuite. } //#UC START# *4DC395670274_4B2A0DDE028B_var* //#UC END# *4DC395670274_4B2A0DDE028B_var* begin //#UC START# *4DC395670274_4B2A0DDE028B_impl* Result := False; //#UC END# *4DC395670274_4B2A0DDE028B_impl* end;//TTestCase.IsScript constructor TTestCase.Create(const aMethodName: AnsiString; const aFolder: AnsiString); //#UC START# *4DC399CA00BC_4B2A0DDE028B_var* //#UC END# *4DC399CA00BC_4B2A0DDE028B_var* begin //#UC START# *4DC399CA00BC_4B2A0DDE028B_impl* !!! Needs to be implemented !!! //#UC END# *4DC399CA00BC_4B2A0DDE028B_impl* end;//TTestCase.Create procedure TTestCase.DoRunTest(aTestResult: TTestResult); //#UC START# *4DDE29F101B1_4B2A0DDE028B_var* //#UC END# *4DDE29F101B1_4B2A0DDE028B_var* begin //#UC START# *4DDE29F101B1_4B2A0DDE028B_impl* Assert(Assigned(FMethod), 'Method "' + FTestName + '" not found'); FExpectedException := nil; try try {$IFDEF CLR} aTestResult.FMethodPtr := nil; {$ELSE} CheckMethodIsNotEmpty(TMethod(FMethod).Code); aTestResult.FMethodPtr := TMethod(FMethod).Code; {$ENDIF} FCheckCalled := False; f_TestResult := aTestResult; try Invoke(FMethod); finally f_TestResult := nil; end; if FFailsOnNoChecksExecuted and (not FCheckCalled) then Fail('No checks executed in TestCase', aTestResult.FMethodPtr); StopExpectingException; except on E: ETestFailure do begin raise; end; on E: Exception do begin if not Assigned(FExpectedException) then raise else if not E.ClassType.InheritsFrom(fExpectedException) then FailNotEquals(fExpectedException.ClassName, E.ClassName, 'unexpected exception', ExceptAddr); end end; finally FExpectedException := nil; end; //#UC END# *4DDE29F101B1_4B2A0DDE028B_impl* end;//TTestCase.DoRunTest function TTestCase.DoGetSubFolder: AnsiString; //#UC START# *4F9A4FD70148_4B2A0DDE028B_var* //#UC END# *4F9A4FD70148_4B2A0DDE028B_var* begin //#UC START# *4F9A4FD70148_4B2A0DDE028B_impl* !!! Needs to be implemented !!! //#UC END# *4F9A4FD70148_4B2A0DDE028B_impl* end;//TTestCase.DoGetSubFolder procedure TTestCase.DoClearEtalon; //#UC START# *51B1DD8E0018_4B2A0DDE028B_var* //#UC END# *51B1DD8E0018_4B2A0DDE028B_var* begin //#UC START# *51B1DD8E0018_4B2A0DDE028B_impl* !!! Needs to be implemented !!! //#UC END# *51B1DD8E0018_4B2A0DDE028B_impl* end;//TTestCase.DoClearEtalon procedure TTestSuite.DoReReadAbstractTests; //#UC START# *5040A3CE0118_4DC24566022C_var* //#UC END# *5040A3CE0118_4DC24566022C_var* begin //#UC START# *5040A3CE0118_4DC24566022C_impl* !!! Needs to be implemented !!! //#UC END# *5040A3CE0118_4DC24566022C_impl* end;//TTestSuite.DoReReadAbstractTests procedure TTestSuite.DoAddTest(const aTest: ITest); //#UC START# *4DC28F1301D6_4DC24566022C_var* //#UC END# *4DC28F1301D6_4DC24566022C_var* begin //#UC START# *4DC28F1301D6_4DC24566022C_impl* Assert(Assigned(aTest)); if FSuffix = '' then FSuffix := aTest.GetSuffixName; FTests.Add(aTest); //#UC END# *4DC28F1301D6_4DC24566022C_impl* end;//TTestSuite.DoAddTest procedure TTestSuite.AddTests(aTestClass: TTestCaseClass); //#UC START# *4DC38C96018E_4DC24566022C_var* var l_MethodIter : Integer; l_NameOfMethod : string; l_MethodEnumerator : TMethodEnumerator; //#UC END# *4DC38C96018E_4DC24566022C_var* begin //#UC START# *4DC38C96018E_4DC24566022C_impl* { call on the method enumerator to get the names of the test cases in the testClass } l_MethodEnumerator := nil; try l_MethodEnumerator := TMethodEnumerator.Create(aTestClass); { make sure we add each test case to the list of tests } for l_MethodIter := 0 to l_MethodEnumerator.MethodCount - 1 do begin l_NameOfMethod := l_MethodEnumerator.NameOfMethod[l_MethodIter]; Self.AddTest(aTestClass.Create(l_NameOfMethod) as ITest); end; // for l_MethodIter := 0 to l_MethodEnumerator.Methodcount - 1 do finally l_MethodEnumerator.Free; end; //#UC END# *4DC38C96018E_4DC24566022C_impl* end;//TTestSuite.AddTests procedure TTestSuite.AddTest(const aTest: ITest); //#UC START# *4DC28F0500F3_4DC24566022C_var* //#UC END# *4DC28F0500F3_4DC24566022C_var* begin //#UC START# *4DC28F0500F3_4DC24566022C_impl* DoAddTest(aTest); //#UC END# *4DC28F0500F3_4DC24566022C_impl* end;//TTestSuite.AddTest procedure TTestSuite.DoRunTest(aTestResult: TTestResult); //#UC START# *4DDE29F101B1_4DC24566022C_var* var i : Integer; l_Test : ITest; //#UC END# *4DDE29F101B1_4DC24566022C_var* begin //#UC START# *4DDE29F101B1_4DC24566022C_impl* Assert(Assigned(aTestResult)); Assert(Assigned(FTests)); aTestResult.StartSuite(Self); for i := 0 to FTests.Count - 1 do begin if aTestResult.ShouldStop then Break; l_Test := FTests[i] as ITest; l_Test.RunWithFixture(aTestResult); end; // for i := 0 to FTests.Count - 1 do aTestResult.EndSuite(Self); //#UC END# *4DDE29F101B1_4DC24566022C_impl* end;//TTestSuite.DoRunTest function TTestSuite.DoGetSubFolder: AnsiString; //#UC START# *4F9A4FD70148_4DC24566022C_var* //#UC END# *4F9A4FD70148_4DC24566022C_var* begin //#UC START# *4F9A4FD70148_4DC24566022C_impl* !!! Needs to be implemented !!! //#UC END# *4F9A4FD70148_4DC24566022C_impl* end;//TTestSuite.DoGetSubFolder procedure TTestSuite.ReReadAbstractTests; //#UC START# *5040A3B80283_4DC24566022C_var* //#UC END# *5040A3B80283_4DC24566022C_var* begin //#UC START# *5040A3B80283_4DC24566022C_impl* !!! Needs to be implemented !!! //#UC END# *5040A3B80283_4DC24566022C_impl* end;//TTestSuite.ReReadAbstractTests procedure TTestSuite.DoClearEtalon; //#UC START# *51B1DD8E0018_4DC24566022C_var* //#UC END# *51B1DD8E0018_4DC24566022C_var* begin //#UC START# *51B1DD8E0018_4DC24566022C_impl* !!! Needs to be implemented !!! //#UC END# *51B1DD8E0018_4DC24566022C_impl* end;//TTestSuite.DoClearEtalon {$IfEnd} // Defined(nsTest) end.
unit Weather.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Net.HttpClient, Vcl.StdCtrls, IPPeerClient, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope, Weather.Classes, System.JSON, Vcl.ExtCtrls, Vcl.Imaging.pngimage, System.ImageList, Vcl.ImgList, Direct2D, D2D1, System.Generics.Collections, Vcl.Menus, HGM.Common.Settings, System.Types, Vcl.WinXCtrls, REST.Types; type TFormWeather = class(TForm) LabelTemp: TLabel; LabelLoc: TLabel; RESTClient: TRESTClient; RESTRequest: TRESTRequest; RESTResponse: TRESTResponse; LabelPressure: TLabel; LabelHumidity: TLabel; LabelWind: TLabel; LabelCloudiness: TLabel; ImageIcon: TImage; ImageList24: TImageList; TimerUpdate: TTimer; PopupMenu: TPopupMenu; MenuItemFix: TMenuItem; MenuItemSettings: TMenuItem; MenuItemUpdate: TMenuItem; N1: TMenuItem; N2: TMenuItem; TrayIcon: TTrayIcon; MenuItemQuit: TMenuItem; TimerTesting: TTimer; ActivityIndicator: TActivityIndicator; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormResize(Sender: TObject); procedure TimerUpdateTimer(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure RESTRequestAfterExecute(Sender: TCustomRESTRequest); procedure MenuItemFixClick(Sender: TObject); procedure CreateParams(var Params: TCreateParams); override; procedure MenuItemQuitClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure MenuItemSettingsClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure TimerTestingTimer(Sender: TObject); procedure MenuItemUpdateClick(Sender: TObject); private FWeather: TWeather; FSettings: TSettingsReg; FCity: string; FRotate: Integer; FTemp: Integer; FFixIt: Boolean; FColor: TColor; procedure SetFixIt(const Value: Boolean); procedure SetFontColor(AColor: TColor); property FixIt: Boolean read FFixIt write SetFixIt; public FLocateError: Boolean; FCheckIt: Boolean; procedure SetThemeColor(AColor: TColor); procedure UpdateWeather; end; var FormWeather: TFormWeather; implementation uses HGM.Common.Utils, Math, Weather.Settings; {$R *.dfm} function DegToStr(Value: Integer): string; begin if Between(0, Value, 20) then Exit('Ñ'); if Between(20, Value, 75) then Exit('ÑÂ'); if Between(75, Value, 105) then Exit('Â'); if Between(105, Value, 165) then Exit('ÞÂ'); if Between(165, Value, 195) then Exit('Þ'); if Between(195, Value, 255) then Exit('ÞÇ'); if Between(255, Value, 285) then Exit('Ç'); if Between(285, Value, 345) then Exit('ÑÇ'); if Between(345, Value, 360) then Exit('Ñ'); end; procedure TFormWeather.CreateParams(var Params: TCreateParams); begin inherited; Params.ExStyle := Params.ExStyle or WS_EX_TRANSPARENT; end; procedure TFormWeather.FormClose(Sender: TObject; var Action: TCloseAction); begin FSettings.SetBool('HGMWeather', 'Fixed', FixIt); FSettings.SetParamWindow('HGMWeather', Self, [wpsCoord]); FSettings.SetInt('HGMWeather', 'Color', FColor); end; procedure TFormWeather.SetFontColor(AColor: TColor); begin LabelTemp.Font.Color := AColor; LabelLoc.Font.Color := AColor; LabelPressure.Font.Color := AColor; LabelHumidity.Font.Color := AColor; LabelWind.Font.Color := AColor; LabelCloudiness.Font.Color := AColor; end; procedure TFormWeather.SetThemeColor(AColor: TColor); var i: Integer; begin for i := 0 to ImageList24.Count - 1 do ColorImages(ImageList24, i, AColor); SetFontColor(AColor); end; procedure TFormWeather.FormCreate(Sender: TObject); begin FSettings := TSettingsReg.Create(rrHKCU, 'Software\'); FWeather := TWeather.Create; FLocateError := False; FCheckIt := False; FRotate := 0; Left := Screen.Width - (ClientWidth + 100); Top := 100; FixIt := FSettings.GetBool('HGMWeather', 'Fixed', False); FCity := FSettings.GetStr('HGMWeather', 'Locate', 'Ìîñêâà'); FColor := FSettings.GetInt('HGMWeather', 'Color', clWhite); FSettings.GetParamWindow('HGMWeather', Self, [wpsCoord]); SetThemeColor(FColor); ActivityIndicator.Animate := True; ActivityIndicator.IndicatorSize := aisXLarge; ActivityIndicator.IndicatorColor := aicWhite; UpdateWeather; TimerUpdate.Enabled := not FLocateError; end; procedure TFormWeather.FormDestroy(Sender: TObject); begin FSettings.Free; FWeather.Free; end; procedure TFormWeather.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button = mbLeft) and (not FixIt) then begin ReleaseCapture; SendMessage(Handle, WM_SYSCOMMAND, 61458, 0); end; if Button = mbRight then begin PopupMenu.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; end; procedure TFormWeather.FormPaint(Sender: TObject); var ICO: TIcon; Pt: TPoint; R: TRect; begin with TDirect2DCanvas.Create(Canvas, ClientRect) do begin BeginDraw; Pt := Point(LabelWind.Left + LabelWind.Width, LabelWind.Top - 6); RenderTarget.SetTransform(TD2D1Matrix3x2F.Rotation(180 + FRotate, Pt.X + 12, Pt.Y + 12)); ICO := TIcon.Create; ImageList24.GetIcon(4, ICO); Draw(Pt.X, Pt.Y, ICO); ICO.Free; RenderTarget.SetTransform(TD2DMatrix3x2F.Identity); Brush.Color := Color; Pen.Color := clGray; Pen.Width := 3; // R := TRect.Create(TPoint.Create(10, 80), 30, 30); Ellipse(R); // R.Inflate(-5, 0); R.Top := 10; R.Bottom := 100; RoundRect(R, 20, 20); // Pen.Color := Color; R := TRect.Create(TPoint.Create(10, 80), 30, 30); R.Inflate(-3, -3); Ellipse(R); // Brush.Color := ColorRedOrBlue(Round(100 * ((Min(Max(-50, FTemp), 50) + 50) / 100))); //$008A8AFF; Pen.Color := Brush.Color; R := TRect.Create(TPoint.Create(10, 80), 30, 30); R.Inflate(-5, -5); Ellipse(R); // Pen.Width := 1; R := TRect.Create(TPoint.Create(10, 80), 30, 30); R.Inflate(-10, 0); //R.Top := 20; //R.Top := 90; 70 R.Left := R.Left - 1; R.Top := 90 - Round(70 * ((Min(Max(-50, FTemp), 50) + 50) / 100)); R.Bottom := 100; R.Width := R.Width + 1; Rectangle(R); EndDraw; Free; end; //6, 30 ImageList24.Draw(Canvas, LabelWind.Left - 30, LabelWind.Top - 6, 1, True); ImageList24.Draw(Canvas, LabelPressure.Left - 30, LabelPressure.Top - 6, 2, True); ImageList24.Draw(Canvas, LabelHumidity.Left - 30, LabelHumidity.Top - 6, 0, True); ImageList24.Draw(Canvas, LabelCloudiness.Left - 30, LabelCloudiness.Top - 6, 3, True); end; procedure TFormWeather.FormResize(Sender: TObject); begin Repaint; end; procedure TFormWeather.FormShow(Sender: TObject); begin ShowWindow(Application.Handle, SW_HIDE); end; procedure TFormWeather.MenuItemFixClick(Sender: TObject); begin FixIt := not FixIt; end; procedure TFormWeather.MenuItemQuitClick(Sender: TObject); begin Close; end; procedure TFormWeather.MenuItemSettingsClick(Sender: TObject); begin if TFormSettings.Execute(FCity, FColor) then begin FSettings.SetStr('HGMWeather', 'Locate', FCity); FSettings.SetInt('HGMWeather', 'Color', FColor); end; SetThemeColor(FColor); UpdateWeather; Repaint; end; procedure TFormWeather.MenuItemUpdateClick(Sender: TObject); begin ActivityIndicator.Animate := True; ActivityIndicator.Visible := True; LabelTemp.Hide; Repaint; UpdateWeather; end; procedure TFormWeather.RESTRequestAfterExecute(Sender: TCustomRESTRequest); var Mem: TMemoryStream; PNG: TPNGImage; begin if RESTResponse.StatusCode <> 200 then begin FLocateError := True; Exit; end; FLocateError := False; if FCheckIt then Exit; FWeather.ParseFromJson(TJSONObject(RESTRequest.Response.JSONValue)); Mem := DownloadURL('https://openweathermap.org/img/wn/' + FWeather.weather[0].icon + '@2x.png'); if Mem.Size > 0 then begin PNG := TPngImage.Create; try PNG.LoadFromStream(Mem); ImageIcon.Picture.Assign(PNG); finally PNG.Free; end; end else ImageIcon.Picture.Assign(nil); Mem.Free; LabelLoc.Caption := FCity; //FWeather.name; FTemp := Round(FWeather.main.temp - 273.15); LabelTemp.Caption := FTemp.ToString + '°'; if FTemp > 0 then LabelTemp.Caption := '+' + LabelTemp.Caption; LabelPressure.Caption := Round(FWeather.main.pressure * 0.750062).ToString + ' ìì ðò.ñò.'; LabelHumidity.Caption := FWeather.main.humidity.ToString + '%'; LabelCloudiness.Caption := FWeather.clouds.all.ToString + '%'; FRotate := Round(FWeather.wind.deg); LabelWind.Caption := FWeather.wind.speed.ToString + ' ì/ñ ' + DegToStr(FRotate); ActivityIndicator.Animate := False; ActivityIndicator.Visible := False; LabelTemp.Visible := True; Repaint; end; procedure TFormWeather.SetFixIt(const Value: Boolean); begin FFixIt := Value; AlphaBlend := Value; MenuItemFix.Checked := Value; end; procedure TFormWeather.TimerTestingTimer(Sender: TObject); begin FTemp := FTemp + 1; if FTemp >= 60 then FTemp := -60; LabelTemp.Caption := FTemp.ToString + '°'; if FTemp > 0 then LabelTemp.Caption := '+' + LabelTemp.Caption; FRotate := FRotate + 10; if FRotate >= 360 then FRotate := 0; LabelWind.Caption := FWeather.wind.speed.ToString + ' ì/ñ ' + DegToStr(FRotate); Repaint; end; procedure TFormWeather.TimerUpdateTimer(Sender: TObject); begin UpdateWeather; end; procedure TFormWeather.UpdateWeather; begin RESTRequest.Params.ParameterByName('q').Value := FCity; RESTRequest.ExecuteAsync; end; end.
unit SoundMixer; interface uses SoundTypes, SoundCache; const cMaxAllowedSounds = 30; // it does not make sense to create more than one instance of this class type TSoundMixer = class private fMaxAllowedSounds : integer; fSounds : array [0..cMaxAllowedSounds] of TSoundInfo; fSoundCount : integer; fSoundCache : TSoundCache; public constructor Create; destructor Destroy; override; public procedure AddSounds(const Sounds : array of TSoundInfo); procedure PlaySounds; procedure PauseSounds; procedure ResumeSounds; procedure StopSounds; procedure StopPlayingSound(const Name : string; Kind : integer); procedure ChangeSoundParams(const Name : string; Kind : integer; Pan, Volume : single); procedure ClearSoundCache; public property MaxAllowedSounds : integer read fMaxAllowedSounds write fMaxAllowedSounds; end; implementation uses SysUtils, SoundLib; var vMixerInstances : integer = 0; constructor TSoundMixer.Create; begin inherited; if vMixerInstances > 0 then raise Exception.Create('Too many mixer instances'); inc(vMixerInstances); fSoundCache := TSoundCache.Create; fMaxAllowedSounds := 30; end; destructor TSoundMixer.Destroy; begin fSoundCache.Free; dec(vMixerInstances); inherited; end; {$O-} procedure TSoundMixer.AddSounds(const Sounds : array of TSoundInfo); var i : integer; j : integer; k : integer; begin for i := low(Sounds) to high(Sounds) do begin j := 0; while (j < fSoundCount) and (Sounds[i].priority > fSounds[j].priority) do inc(j); if j < fMaxAllowedSounds then begin if fSoundCount >= fMaxAllowedSounds then dec(fSoundCount); for k:=j to fSoundCount do fSounds[k+1] := fSounds[k]; // Move(fSounds[j], fSounds[j+1], (fSoundCount - j)*sizeof(fSounds[0])); fSounds[j] := Sounds[i]; inc(fSoundCount); end; end; end; {$O+} procedure TSoundMixer.PlaySounds; var i : integer; startofs : integer; begin for i := 0 to pred(fSoundCount) do with fSounds[i] do if fSoundCache.GetSound(name, ssDiskFile) then begin if looped then startofs := random(SoundLength(name, kind)) else startofs := 0; PlaySound(name, kind, looped, pan, volume, startofs); end; fSoundCount := 0; end; procedure TSoundMixer.PauseSounds; begin PauseAllSounds; end; procedure TSoundMixer.ResumeSounds; begin ResumeAllSounds; end; procedure TSoundMixer.StopPlayingSound(const Name : string; Kind : integer); begin StopSound(Name, Kind); end; procedure TSoundMixer.ChangeSoundParams(const Name : string; Kind : integer; Pan, Volume : single); begin SetSoundPan(Name, Kind, Pan); SetSoundVolume(Name, Kind, Volume); end; procedure TSoundMixer.ClearSoundCache; begin fSoundCache.Clear; end; procedure TSoundMixer.StopSounds; begin StopAllSounds; end; end.
unit k2ProcessorTagTool; // Модуль: "w:\common\components\rtl\Garant\K2\k2ProcessorTagTool.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tk2ProcessorTagTool" MUID: (4BBF3D8B00CD) {$Include w:\common\components\rtl\Garant\K2\k2Define.inc} interface uses l3IntfUses , k2TagTool , k2PureMixIns , k2Interfaces , l3Variant , l3IID ; type Tk2ProcessorTagTool = class(Tk2TagTool) private f_Processor: Ik2Processor; protected function pm_GetProcessor: Ik2Processor; function GetProcessor: Ik2Processor; virtual; function StartOp(OpCode: Integer = 0; DoLock: Boolean = True): Ik2Op; function Get_Processor: Ik2Processor; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure DoFire(const anEvent: Tk2Event; const anOp: Ik2Op); override; function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } procedure ClearFields; override; public constructor Create(aTag: Tl3Variant; const aProcessor: Ik2Processor); reintroduce; class function Make(aTag: Tl3Variant; const aProcessor: Ik2Processor): Ik2TagTool; reintroduce; protected property Processor: Ik2Processor read pm_GetProcessor; end;//Tk2ProcessorTagTool implementation uses l3ImplUses //#UC START# *4BBF3D8B00CDimpl_uses* //#UC END# *4BBF3D8B00CDimpl_uses* ; function Tk2ProcessorTagTool.pm_GetProcessor: Ik2Processor; //#UC START# *54BD169902EF_4BBF3D8B00CDget_var* //#UC END# *54BD169902EF_4BBF3D8B00CDget_var* begin //#UC START# *54BD169902EF_4BBF3D8B00CDget_impl* Result := GetProcessor; //#UC END# *54BD169902EF_4BBF3D8B00CDget_impl* end;//Tk2ProcessorTagTool.pm_GetProcessor constructor Tk2ProcessorTagTool.Create(aTag: Tl3Variant; const aProcessor: Ik2Processor); //#UC START# *4BBF40C603BD_4BBF3D8B00CD_var* //#UC END# *4BBF40C603BD_4BBF3D8B00CD_var* begin //#UC START# *4BBF40C603BD_4BBF3D8B00CD_impl* inherited Create(aTag); f_Processor := aProcessor; //#UC END# *4BBF40C603BD_4BBF3D8B00CD_impl* end;//Tk2ProcessorTagTool.Create function Tk2ProcessorTagTool.GetProcessor: Ik2Processor; //#UC START# *54BD0F310322_4BBF3D8B00CD_var* //#UC END# *54BD0F310322_4BBF3D8B00CD_var* begin //#UC START# *54BD0F310322_4BBF3D8B00CD_impl* Result := f_Processor; //#UC END# *54BD0F310322_4BBF3D8B00CD_impl* end;//Tk2ProcessorTagTool.GetProcessor function Tk2ProcessorTagTool.StartOp(OpCode: Integer = 0; DoLock: Boolean = True): Ik2Op; //#UC START# *54BD16B6032F_4BBF3D8B00CD_var* //#UC END# *54BD16B6032F_4BBF3D8B00CD_var* begin //#UC START# *54BD16B6032F_4BBF3D8B00CD_impl* if (Processor = nil) then Result := nil else Result := Processor.StartOp(OpCode, DoLock); //#UC END# *54BD16B6032F_4BBF3D8B00CD_impl* end;//Tk2ProcessorTagTool.StartOp class function Tk2ProcessorTagTool.Make(aTag: Tl3Variant; const aProcessor: Ik2Processor): Ik2TagTool; var l_Inst : Tk2ProcessorTagTool; begin l_Inst := Create(aTag, aProcessor); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//Tk2ProcessorTagTool.Make function Tk2ProcessorTagTool.Get_Processor: Ik2Processor; //#UC START# *4BBF42BF004D_4BBF3D8B00CDget_var* //#UC END# *4BBF42BF004D_4BBF3D8B00CDget_var* begin //#UC START# *4BBF42BF004D_4BBF3D8B00CDget_impl* Result := GetProcessor; //#UC END# *4BBF42BF004D_4BBF3D8B00CDget_impl* end;//Tk2ProcessorTagTool.Get_Processor procedure Tk2ProcessorTagTool.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4BBF3D8B00CD_var* //#UC END# *479731C50290_4BBF3D8B00CD_var* begin //#UC START# *479731C50290_4BBF3D8B00CD_impl* f_Processor := nil; inherited; //#UC END# *479731C50290_4BBF3D8B00CD_impl* end;//Tk2ProcessorTagTool.Cleanup procedure Tk2ProcessorTagTool.DoFire(const anEvent: Tk2Event; const anOp: Ik2Op); //#UC START# *48CF73CE00B5_4BBF3D8B00CD_var* //#UC END# *48CF73CE00B5_4BBF3D8B00CD_var* begin //#UC START# *48CF73CE00B5_4BBF3D8B00CD_impl* inherited; if (anEvent.ID = k2_eidTypeTableWillBeDestroyed) then f_Processor := nil; //#UC END# *48CF73CE00B5_4BBF3D8B00CD_impl* end;//Tk2ProcessorTagTool.DoFire function Tk2ProcessorTagTool.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; {* Реализация запроса интерфейса } //#UC START# *4A60B23E00C3_4BBF3D8B00CD_var* //#UC END# *4A60B23E00C3_4BBF3D8B00CD_var* begin //#UC START# *4A60B23E00C3_4BBF3D8B00CD_impl* if IID.EQ(Ik2Processor) then begin Result.SetOk; Ik2Processor(Obj) := Processor; end//IID.EQ(Ik2Processor) else Result := inherited COMQueryInterface(IID, Obj) //#UC END# *4A60B23E00C3_4BBF3D8B00CD_impl* end;//Tk2ProcessorTagTool.COMQueryInterface procedure Tk2ProcessorTagTool.ClearFields; begin f_Processor := nil; inherited; end;//Tk2ProcessorTagTool.ClearFields end.
unit TextShortcuts; interface uses Classes, Menus, Collection; type TShortcutInfo = class public constructor Create( aDesc : string; aShortcut : TShortcut; aText : string ); private fDesc : string; fShortcut : TShortcut; fText : string; public property Desc : string read fDesc write fDesc; property Shortcut : TShortcut read fShortcut write fShortcut; property Text : string read fText write fText; end; TTextShortcutMger = class public constructor Create; destructor Destroy; override; public procedure LoadShortcuts( const FileName : string ); procedure SaveShortcuts( const FileName : string ); function AddShortcutText( Shortcut : TShortcut; Desc, Text : string ) : TShortcutInfo; procedure DeleteShortcutText( Shortcut : TShortcut ); function getShortcutText( ShiftState : TShiftState; Key : word; out Text : string ) : boolean; function getShortcutByDesc( aDesc : string ) : TShortcutInfo; function getShortcutByKey( aKey : TShortcut ) : TShortcutInfo; private fShortcuts : TCollection; function getCount : integer; function getShortcut( idx : integer) : TShortcutInfo; public property ShortcutCount : integer read getCount; property Shortcuts[idx : integer] : TShortcutInfo read getShortcut; end; implementation uses IniFiles, SysUtils; // TShorcutInfo constructor TShortcutInfo.Create( aDesc : string; aShortcut : TShortcut; aText : string ); begin inherited Create; fDesc := aDesc; fShortcut := aShortcut; fText := aText; end; // TTextShortcutMger constructor TTextShortcutMger.Create; begin inherited; fShortcuts := TCollection.Create( 20, rkBelonguer ); end; destructor TTextShortcutMger.Destroy; begin fShortcuts.Free; inherited; end; const DESC_ID = 'Desc'; SHORTCUT_ID = 'Shortcut'; TEXT_ID = 'Text'; procedure TTextShortcutMger.LoadShortcuts( const FileName : string ); var ini : TIniFile; sections : TStringList; Desc : string; Shortc : word; Text : string; i : integer; begin ini := TIniFile.Create( FileName ); sections := TStringList.Create; try ini.ReadSections( sections ); for i := 0 to pred(sections.Count) do begin Desc := ini.ReadString( sections[i], DESC_ID, '' ); Shortc := ini.ReadInteger( sections[i], SHORTCUT_ID, 0 ); Text := ini.ReadString( sections[i], TEXT_ID, '' ); AddShortcutText( Shortc, Desc, Text ); end; finally ini.Free; sections.Free; end; end; procedure TTextShortcutMger.SaveShortcuts( const FileName : string ); var ini : TIniFile; i : integer; StrLst : TStringList; begin ini := TIniFile.Create( FileName ); try StrLst := TStringList.Create; ini.ReadSections( StrLst ); for i := 0 to pred(StrLst.Count) do ini.EraseSection( StrLst[i] ); for i := 0 to pred(fShortcuts.Count) do begin ini.WriteString( 'Key.' + IntToStr(i), DESC_ID, TShortcutInfo(fShortcuts[i]).Desc ); ini.WriteInteger( 'Key.' + IntToStr(i), SHORTCUT_ID, TShortcutInfo(fShortcuts[i]).Shortcut ); ini.WriteString( 'Key.' + IntToStr(i), TEXT_ID, TShortcutInfo(fShortcuts[i]).Text ); end; finally ini.Free; end; end; function TTextShortcutMger.AddShortcutText( Shortcut : TShortcut; Desc, Text : string ) : TShortcutInfo; begin result := TShortcutInfo.Create( Desc, Shortcut, Text ); fShortcuts.Insert( result ); end; procedure TTextShortcutMger.DeleteShortcutText( Shortcut : TShortcut ); var info : TShortcutInfo; begin info := getShortcutByKey( Shortcut ); if info <> nil then fShortcuts.Delete( info ); end; function TTextShortcutMger.getShortcutByDesc( aDesc : string ) : TShortcutInfo; var found : boolean; i : integer; begin found := false; i := 0; while (i < fShortcuts.Count) and not found do begin found := TShortcutInfo(fShortcuts[i]).Desc = aDesc; inc( i ); end; if found then result := TShortcutInfo(fShortcuts[pred(i)]) else result := nil; end; function TTextShortcutMger.getShortcutByKey( aKey : TShortcut ) : TShortcutInfo; var found : boolean; i : integer; begin found := false; i := 0; while (i < fShortcuts.Count) and not found do begin found := TShortcutInfo(fShortcuts[i]).Shortcut = aKey; inc( i ); end; if found then result := TShortcutInfo(fShortcuts[pred(i)]) else result := nil; end; function TTextShortcutMger.getShortcutText( ShiftState : TShiftState; Key : word; out Text : string ) : boolean; var TheKey : TShortcut; info : TShortcutInfo; begin TheKey := Shortcut( Key, ShiftState ); info := getShortcutByKey( TheKey ); result := info <> nil; if result then Text := info.Text; end; function TTextShortcutMger.getCount : integer; begin result := fShortcuts.Count; end; function TTextShortcutMger.getShortcut( idx : integer) : TShortcutInfo; begin result := TShortcutInfo(fShortcuts[idx]); end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clSshDHGEX; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clUtils, clSshKeyExchanger, clCryptKex, clSshPacket, clConfig; type TclDhgEx = class(TclSshKeyExchanger) private FType: Integer; FState: Integer; FDh: TclKeyExchange; FV_S: TclByteArray; FV_C: TclByteArray; FI_S: TclByteArray; FI_C: TclByteArray; FPacket: TclPacket; FP: TclByteArray; FG: TclByteArray; FE: TclByteArray; protected function GetHashAlgorithm: string; virtual; abstract; function GetSignatureAlgorithm: string; virtual; abstract; public constructor Create; override; destructor Destroy; override; procedure Init(AConfig: TclConfig; const AV_S, AV_C, AI_S, AI_C: TclByteArray; var pp: TclPacket); override; function Next(APacket: TclPacket; var pp: TclPacket): Boolean; override; function GetKeyType: string; override; function GetState: Integer; override; end; TclDhgExSha1 = class(TclDhgEx) protected function GetHashAlgorithm: string; override; function GetSignatureAlgorithm: string; override; end; TclDhgExSha256 = class(TclDhgEx) protected function GetHashAlgorithm: string; override; function GetSignatureAlgorithm: string; override; end; implementation uses clCryptHash, clTranslator, clCryptSignature, clSshUtils; const cMin = 1024; cPreferred = 1024; cMax = 1024; { TclDhgEx } constructor TclDhgEx.Create; begin inherited Create(); FDh := nil; FPacket := nil; end; destructor TclDhgEx.Destroy; begin FDh.Free(); FPacket.Free(); inherited Destroy(); end; function TclDhgEx.GetKeyType: string; begin if (FType = SSH_DSS) then begin Result := 'DSA'; end else begin Result := 'RSA'; end; end; function TclDhgEx.GetState: Integer; begin Result := FState; end; procedure TclDhgEx.Init(AConfig: TclConfig; const AV_S, AV_C, AI_S, AI_C: TclByteArray; var pp: TclPacket); begin FConfig := AConfig; FV_S := AV_S; FV_C := AV_C; FI_S := AI_S; FI_C := AI_C; FreeAndNil(FSha); FSha := TclHash(FConfig.CreateInstance(GetHashAlgorithm())); FSha.Init(); FreeAndNil(FPacket); FPacket := TclPacket.Create(); FreeAndNil(FDh); FDh := TclKeyExchange(FConfig.CreateInstance('dh')); FDh.Init(); FPacket.Reset(); FPacket.PutByte($22); //TODO make it const FPacket.PutInt(CMin); FPacket.PutInt(CPreferred); FPacket.PutInt(cMax); FState := SSH_MSG_KEX_DH_GEX_GROUP; pp := FPacket; end; function TclDhgEx.Next(APacket: TclPacket; var pp: TclPacket): Boolean; var i, j: Integer; f, sig_of_H, foo, tmp, ee, n: TclByteArray; alg: string; sigRsa: TclSignatureRSA; keyRsa: TclRsaKey; begin {$IFNDEF DELPHI2005}f := nil; sig_of_H := nil; foo := nil; tmp := nil; ee := nil; n := nil;{$ENDIF} pp := nil; Result := False; case (FState) of SSH_MSG_KEX_DH_GEX_GROUP: begin APacket.GetInt(); APacket.GetByte(); j := APacket.GetByte(); if (j <> SSH_MSG_KEX_DH_GEX_GROUP) then begin Exit; end; FP := APacket.GetMPInt(); FG := APacket.GetMPInt(); FDh.SetP(FP); FDh.SetG(FG); FE := FDh.GetE(); FPacket.Reset(); FPacket.PutByte(SSH_MSG_KEX_DH_GEX_INIT); FPacket.PutMPInt(FE); pp := FPacket; FState := SSH_MSG_KEX_DH_GEX_REPLY; Result := True; end; SSH_MSG_KEX_DH_GEX_REPLY: begin APacket.GetInt(); APacket.GetByte(); j := APacket.GetByte(); if (j <> SSH_MSG_KEX_DH_GEX_REPLY) then begin Exit; end; FK_S := APacket.GetString(); f := APacket.GetMPInt(); sig_of_H := GetSignature(APacket.GetString()); FDh.SetF(f); FK := FDh.GetK(); FPacket.Init(); FPacket.PutString(FV_C); FPacket.PutString(FV_S); FPacket.PutString(FI_C); FPacket.PutString(FI_S); FPacket.PutString(FK_S); FPacket.PutInt(cMin); FPacket.PutInt(cPreferred); FPacket.PutInt(cMax); FPacket.PutMPInt(FP); FPacket.PutMPInt(FG); FPacket.PutMPInt(FE); FPacket.PutMPInt(f); FPacket.PutMPInt(FK); SetLength(foo, FPacket.GetLength()); FPacket.GetByte(foo); FSha.Update(foo, 0, Length(foo)); FH := FSha.Digest(); i := 0; j := ByteArrayReadDWord(FK_S, i); alg := TclTranslator.GetString(FK_S, i, j); Inc(i, j); if (alg = 'ssh-rsa') then begin FType := SSH_RSA; j := ByteArrayReadDWord(FK_S, i); SetLength(tmp, j); System.Move(FK_S[i], tmp[0], j); Inc(i, j); ee := tmp; j := ByteArrayReadDWord(FK_S, i); SetLength(tmp, j); System.Move(FK_S[i], tmp[0], j); Inc(i, j); n := tmp; keyRsa := nil; sigRsa := nil; try keyRsa := TclRsaKey(FConfig.CreateInstance('rsa-key')); keyRsa.Init(); keyRsa.SetPublicKeyParams(n, ee); sigRsa := TclSignatureRSA(FConfig.CreateInstance(GetSignatureAlgorithm())); sigRsa.Init(); sigRsa.SetPublicKey(keyRsa); sigRsa.Update(FH, 0, Length(FH)); sigRsa.Verify(sig_of_H); Result := True; finally sigRsa.Free(); keyRsa.Free(); end; end else begin raise EclSshError.Create(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode); end; FState := STATE_END; end; end; end; { TclDhgExSha1 } function TclDhgExSha1.GetHashAlgorithm: string; begin Result := 'sha1'; end; function TclDhgExSha1.GetSignatureAlgorithm: string; begin Result := 'ssh-rsa'; end; { TclDhgExSha256 } function TclDhgExSha256.GetHashAlgorithm: string; begin Result := 'sha2-256'; end; function TclDhgExSha256.GetSignatureAlgorithm: string; begin Result := 'rsa-sha2-256'; end; end.
unit ufrmTitulos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ToolWin, uTitulosControl, Vcl.WinXCtrls, Vcl.StdCtrls, Vcl.Mask, RxToolEdit, RxLookup, ufrmCadastroTitulos, System.ImageList, Vcl.ImgList, PngImageList, ufrmImprimir; type TfrmTitulos = class(TForm) ToolBar: TToolBar; btnNovo: TToolButton; btnEditar: TToolButton; btnDeletar: TToolButton; btnPesquisar: TToolButton; pnTop: TPanel; pnBottom: TPanel; dbgTitulos: TDBGrid; gbxFiltros: TGroupBox; Label1: TLabel; edtDescricao: TEdit; Label2: TLabel; dblStatus: TRxDBLookupCombo; icones: TPngImageList; Label3: TLabel; lbltotalRegistro: TLabel; btnImprimir: TToolButton; procedure FormCreate(Sender: TObject); procedure btnPesquisarClick(Sender: TObject); procedure btnNovoClick(Sender: TObject); procedure dbgTitulosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure btnDeletarClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnImprimirClick(Sender: TObject); private tituloControl: TTitulosControl; procedure editar; public dataSource: TDataSource; end; var frmTitulos: TfrmTitulos; implementation {$R *.dfm} procedure TfrmTitulos.btnDeletarClick(Sender: TObject); var id: integer; begin id := dbgTitulos.DataSource.DataSet.FieldByName('id').AsInteger; tituloControl.excluirTitulo(id); dbgTitulos.dataSource := tituloControl.getTitulos; end; procedure TfrmTitulos.btnEditarClick(Sender: TObject); begin editar; dbgTitulos.dataSource := tituloControl.getTitulos; end; procedure TfrmTitulos.btnImprimirClick(Sender: TObject); begin frmImprimir := TfrmImprimir.Create(frmImprimir); frmImprimir.RLReport.Preview(); end; procedure TfrmTitulos.btnNovoClick(Sender: TObject); begin frmCadastroTitulos := TfrmCadastroTitulos.Create(frmCadastroTitulos); frmCadastroTitulos.ShowModal; dbgTitulos.dataSource := tituloControl.getTitulos; lbltotalRegistro.Caption := IntToStr(dbgTitulos.DataSource.DataSet.RecordCount); end; procedure TfrmTitulos.btnPesquisarClick(Sender: TObject); begin dataSource := tituloControl.getTitulosByParam(edtDescricao.Text, dblStatus.value); dbgTitulos.DataSource := dataSource; end; procedure TfrmTitulos.dbgTitulosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var texto: string; valor: currency; begin with (Sender as TDBGrid).Canvas do begin texto := dbgTitulos.DataSource.DataSet.FieldByName(Column.Field.FieldName).AsString; if State = [] then begin if dbgTitulos.DataSource.DataSet.RecNo mod 2 = 1 then dbgTitulos.Canvas.Brush.Color := $00F3E2A9 else dbgTitulos.Canvas.Brush.Color := clWhite; end; dbgTitulos.DefaultDrawColumnCell(Rect, DataCol, Column, State); Font.Color := clBlack; Font.Size := 8; if (gdSelected in State) or (gdFocused in State) then TDBGrid(Sender).Canvas.Brush.Color := $0081F7F3; if dbgTitulos.DataSource.DataSet.FieldByName('status').AsString = 'Receita' then TDBGrid(Sender).Canvas.Font.Color := $00088A08; if dbgTitulos.DataSource.DataSet.FieldByName('status').AsString = 'Despesa' then TDBGrid(Sender).Canvas.Font.Color := $000101DF; dbgTitulos.DefaultDrawColumnCell(Rect, DataCol, Column, State); FillRect(Rect); if not (State=[]) then DrawFocusRect(Rect); if Column.FieldName = 'valor' then begin valor := dbgTitulos.DataSource.DataSet.FieldByName(Column.Field.FieldName).AsCurrency; texto := FormatFloat('###,##0.00', valor); TextOut(Rect.Right - (TextWidth(texto)+6), Rect.Top+1, texto); end else TextOut(Rect.Left+2, Rect.Top+1, texto); lbltotalRegistro.Caption := IntToStr(dbgTitulos.DataSource.DataSet.RecordCount); end; end; procedure TfrmTitulos.editar; begin frmCadastroTitulos := TfrmCadastroTitulos.Create(frmCadastroTitulos); with frmCadastroTitulos do begin editar := true; tituloID := dbgTitulos.DataSource.DataSet.FieldByName('id').AsInteger; edtDescricao.Text := dbgTitulos.DataSource.DataSet.FieldByName('descricao').AsString; cedValor.Text := dbgTitulos.DataSource.DataSet.FieldByName('valor').AsString; mmObservacoes.Lines.Add(dbgTitulos.DataSource.DataSet.FieldByName('observacoes').AsString); end; frmCadastroTitulos.ShowModal; end; procedure TfrmTitulos.FormClose(Sender: TObject; var Action: TCloseAction); begin try tituloControl.Free; finally Action := caFree; frmTitulos := nil; end; end; procedure TfrmTitulos.FormCreate(Sender: TObject); begin tituloControl := TTitulosControl.create; dataSource := TDataSource.Create(dataSource); dbgTitulos.dataSource := tituloControl.getTitulos; dataSource := tituloControl.getTitulos; dblStatus.LookupField := 'id'; dblStatus.LookupDisplay := 'descricao'; dblStatus.LookupSource := tituloControl.getStatus; dblStatus.DisplayEmpty := ' '; end; end.
unit xGradient; interface uses Classes, Graphics, Controls, xGraphUtils; type TxGraphicControl = class(TGraphicControl) public property Canvas; end; TxCustomControl = class(TCustomControl) public property Canvas; end; TxGradient = class(TPersistent) private FDirection: TGradientDirection; FColorEnd: TColor; FControl: TControl; FEnabled: boolean; FHalfEffect: boolean; FHalfColorPercent: integer; FOnChange: TNotifyEvent; procedure SetDirection(const Value: TGradientDirection); procedure SetColorBegin(const Value: TColor); procedure SetColorEnd(const Value: TColor); procedure SetEnabled(const Value: boolean); procedure SetHalfEffect(const Value: boolean); procedure SetHalfColorPercent(const Value: integer); public FColorBegin: TColor; constructor Create(AControl: TControl); reintroduce; overload; function GradientFill: boolean; procedure Assign(Source: TPersistent); override; published property ColorBegin: TColor read FColorBegin write SetColorBegin default clBtnFace; property ColorEnd: TColor read FColorEnd write SetColorEnd default clBtnFace; property Direction: TGradientDirection read FDirection write SetDirection default gdHorizontal; property Enabled: boolean read FEnabled write SetEnabled default False; property HalfEffect: boolean read FHalfEffect write SetHalfEffect default False; property HalfColorPercent: integer read FHalfColorPercent write SetHalfColorPercent default 0; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation uses Types; procedure TxGradient.Assign(Source: TPersistent); begin if (Source = nil) or not (Source is TxGradient) then Exit; with Source as TxGradient do begin Self.FDirection := Direction; Self.FColorBegin := ColorBegin; Self.FColorEnd := ColorEnd; Self.FEnabled := Enabled; Self.FHalfEffect := HalfEffect; Self.FHalfColorPercent := HalfColorPercent; end; if FControl <> nil then FControl.Invalidate; end; constructor TxGradient.Create(AControl: TControl); begin inherited Create; FControl := AControl; FColorBegin := clBtnFace; FColorEnd := clBtnFace; end; function TxGradient.GradientFill: boolean; var R1, R2, RF: TRect; Fixed: integer; FCanvas: TCanvas; begin Result := False; if FControl = nil then Exit; R1:=FControl.ClientRect; R2:=R1; if FDirection=gdHorizontal then Fixed:=Trunc(FHalfColorPercent/100*FControl.Width) else Fixed:=Trunc(FHalfColorPercent/100*FControl.Height); if FHalfEffect then if FDirection=gdHorizontal then R1.Right:=(R1.Right-Fixed) div 2 else R1.Bottom:=(R1.Bottom-Fixed) div 2; if FControl is TGraphicControl then FCanvas := TxGraphicControl(FControl).Canvas else FCanvas := TxCustomControl(FControl).Canvas; Result:=DrawGradient(FCanvas, R1, FColorBegin, FColorEnd, FDirection); if Fixed>0 then with FCanvas do begin Brush.Color:=FColorEnd; if FDirection=gdHorizontal then begin RF.Left:=R1.Right; RF.Top:=0; RF.Bottom:=R1.Bottom; RF.Right:=R1.Right+Fixed; end else begin RF.Left:=0; RF.Top:=R1.Bottom; RF.Bottom:=R1.Bottom+Fixed; RF.Right:=R1.Right; end; FillRect(RF); end; if FHalfEffect then begin if FDirection=gdHorizontal then R2.Left:=R1.Right+Fixed else R2.Top := R1.Bottom + Fixed; DrawGradient(FCanvas, R2, FColorEnd, FColorBegin, FDirection); end; end; procedure TxGradient.SetColorBegin(const Value: TColor); begin FColorBegin := Value; if FControl <> nil then FControl.Invalidate; if Assigned(FOnChange) then FOnChange(Self); end; procedure TxGradient.SetColorEnd(const Value: TColor); begin FColorEnd := Value; if FControl <> nil then FControl.Invalidate; if Assigned(FOnChange) then FOnChange(Self); end; procedure TxGradient.SetDirection(const Value: TGradientDirection); begin FDirection := Value; if FControl <> nil then FControl.Invalidate; if Assigned(FOnChange) then FOnChange(Self); end; procedure TxGradient.SetEnabled(const Value: boolean); begin FEnabled := Value; if FControl <> nil then FControl.Invalidate; if Assigned(FOnChange) then FOnChange(Self); end; procedure TxGradient.SetHalfColorPercent(const Value: integer); begin if Value<0 then FHalfColorPercent:=0 else if Value>100 then FHalfColorPercent:=100 else FHalfColorPercent := Value; if FControl <> nil then FControl.Invalidate; if Assigned(FOnChange) then FOnChange(Self); end; procedure TxGradient.SetHalfEffect(const Value: boolean); begin FHalfEffect := Value; if FControl <> nil then FControl.Invalidate; if Assigned(FOnChange) then FOnChange(Self); end; end.
unit USort; interface const N = 100; type TExperiment = record X:Integer; res:Real; end; TMas = Array[0 .. N-1] Of TExperiment; procedure sort(var ar: TMas; m, l:integer); procedure QuickSort(var ar: TMas; cnt:integer); implementation procedure sort(var ar: TMas; m, l: Integer); var i, j, k:Integer; x, tmp: TExperiment; s:string; begin i := m; j := l; x := ar[(m+l) div 2]; repeat while ar[i].res < x.res Do Inc(i); while ar[j].res > x.res Do Dec(j); if i <= j then begin tmp := ar[i]; ar[i] := ar[j]; ar[j] := tmp; Inc(i); Dec(j) end until i > j; if m < j then sort(ar, m, j); if i < l then sort(ar, i, l) end; procedure QuickSort(var ar: Tmas; cnt:integer); begin sort(ar, 0, cnt-1); end; function CountStep(j: integer): integer; //ф-я для вычисления шага 2^k-1 var i, st: integer; begin st:= 1; for i:= 1 to j do st:= 2*st; CountStep:= st - 1; end; var i, j, step, p, l, T: integer; el: TElem; begin T:= Trunc(Ln(n) / Ln(2)); // определяем кол-во шагов for j:= T downto 1 do begin step:= CountStep(j); //вычисляем очередной шаг for p := 1 to step do //применяем сортировку вставками для всех групп begin i:= step + p; while i <= N do begin el:= FMas[i]; l:= i - step; while (l >= 1) and (el < FMas[l]) do begin FMas[l + step]:= FMas[l]; l:= l - step; end; FMas[l + step]:= el; i:= i + step; end; //while end; //for end; //for end; end.
unit evCellInfo; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Модуль: "w:/common/components/gui/Garant/Everest/evCellInfo.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::CellUtils::TevCellInfo // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses evdTypes, evEditorInterfaces, l3ProtoObject ; type TevCellInfo = class(Tl3ProtoObject) private // private fields f_CellType : TedCellType; {* Поле для свойства CellType} f_BoundaryEqualUp : TedBoundaryCorrespondence; {* Поле для свойства BoundaryEqualUp} f_BoundaryEqualDown : TedBoundaryCorrespondence; {* Поле для свойства BoundaryEqualDown} f_OldWidth : Integer; {* Поле для свойства OldWidth} f_NewWidth : Integer; {* Поле для свойства NewWidth} f_Index : Integer; {* Поле для свойства Index} f_MergeStatus : TevMergeStatus; {* Поле для свойства MergeStatus} public // public methods constructor Create(anIndex: Integer; const aCell: IedCell); reintroduce; procedure UpdateBoundaryType(aType: TedBoundaryCorrespondence; anUp: Boolean); public // public properties property CellType: TedCellType read f_CellType; property BoundaryEqualUp: TedBoundaryCorrespondence read f_BoundaryEqualUp; property BoundaryEqualDown: TedBoundaryCorrespondence read f_BoundaryEqualDown; property OldWidth: Integer read f_OldWidth; property NewWidth: Integer read f_NewWidth; property Index: Integer read f_Index; property MergeStatus: TevMergeStatus read f_MergeStatus; end;//TevCellInfo implementation // start class TevCellInfo constructor TevCellInfo.Create(anIndex: Integer; const aCell: IedCell); //#UC START# *516D4FC00331_515ACFFB008D_var* //#UC END# *516D4FC00331_515ACFFB008D_var* begin //#UC START# *516D4FC00331_515ACFFB008D_impl* inherited Create; f_Index := anIndex; f_MergeStatus := aCell.MergeStatus; f_CellType := aCell.GetCellType; f_OldWidth := aCell.Width; f_BoundaryEqualUp := ed_bcNonEqual; f_BoundaryEqualDown := ed_bcNonEqual; //#UC END# *516D4FC00331_515ACFFB008D_impl* end;//TevCellInfo.Create procedure TevCellInfo.UpdateBoundaryType(aType: TedBoundaryCorrespondence; anUp: Boolean); //#UC START# *516D50000139_515ACFFB008D_var* //#UC END# *516D50000139_515ACFFB008D_var* begin //#UC START# *516D50000139_515ACFFB008D_impl* if anUp then f_BoundaryEqualUp := aType else f_BoundaryEqualDown := aType; //#UC END# *516D50000139_515ACFFB008D_impl* end;//TevCellInfo.UpdateBoundaryType end.
program ex; uses crt,Graph, unit1; Type pChar=^TChar; {описание абстрактно класса} TChar=object ch:char; x,y:integer; constructor Init(ach:char; ax,ay:integer); procedure Move(t:integer); procedure Rel(t:integer); virtual; destructor Done; virtual; {деструктор обязателен, так как объекты динамические полиморфные} end; constructor TChar.Init(ach:char; ax,ay:integer); begin ch:=ach; x:=ax; y:=ay; end; procedure TChar.Rel(t:integer); begin end; procedure TChar.Move(t:integer); begin SetColor(GetBkColor); OuttextXY(x,y,ch); Rel(t); {изменяем координаты} SetColor(ord(ch) mod 16); OutTextXY(x,y,ch); end; Destructor TChar.Done; begin end; {деструктор пустой, так как объект не содержит объектных полей} Type pLChar=^TLineChar; {описание класса символа, перемещающегося по горизонтали} TLineChar=object(TChar) xn:integer; constructor Init(ach:char; ax,ay:integer); procedure Rel(t:integer); virtual; end; constructor TLineChar.Init; begin inherited Init(ach,ax,ay); xn:=ax; end; procedure TLineChar.Rel; begin x:=(xn+t) mod GetMaxX; end; Type pVChar=^TVLineChar; {описание класса символа, перемещающего по вертикали} TVLineChar=object(TChar) yn:integer; constructor Init(ach:char; ax,ay:integer); procedure Rel(t:integer); virtual; end; constructor TVLineChar.Init; begin inherited Init(ach,ax,ay); yn:=ay; end; Procedure TVLineChar.Rel; begin y:=(yn+t) mod GetMaxY; end; Type pCChar=^TCirChar; {описание класса символа, перемещающегося по окружности} TCirChar=object(TChar) xc,yc,r:integer; t0:real; constructor Init(ach:char; ayc,ar:integer; at0:real); procedure Rel(t:integer); virtual; end; constructor TCirChar.Init; begin inherited Init(ach,axc+round(ar*sin(at0)),ayc+round(ar*cos(at0))); xc:=axc; yc:=ayc; r:=ar; t0:=at0; end; procedure TCirChar.Rel; begin x:=xc+Round(r*sin(t0+t*0.05)); y:=yc+Round(r*cos(t0+t*0.05)); end; Type TString=object mas:array[1..10] of pChar; {массив указателей на объекты} n:integer; {реальное количество объектов} procedure Init(as:string; tmove:byte); {создание объектов} procedure Move(t:integer); {перемещение строк} procedure Done; {уничтожение объектов} end; Procedure TString.Init; var i:integer; begin n:length(as); for i:=1 to n do begin case tmove of 1:mas[i]:=new(pLChar,Init(as[i],9*i,GetMaxY div 2)); 2:mas[i]:=new(pVChar,Init(as[i],GetMaxX div 2-n*5+10*i,0)); 3:mas[i]:=new(pCChar,Init(as[i],GetMaxX div 2,GetMaxY div2,100,2*pi*i-1)/n)); end; end; end; end; Procedure TString.Move; var i:integer; begin for i:=n downto 1 do mas[i]^.Move(t); end; procedure TString.Done; var i:integer; begin for i:=1 to n do dispose(mas[i],Done); end; var s:string; M:array[1..3] of string; i,t,dr,md:integer; begin write('Vvedite stroku do 10 simvolov:'); readln(s); InitGraph(dr,md'e:\bp\bgi'); for i:=1 to 3 do M[i].Init(s,i); t:=0; while not KeyPressed and (t<1000) do begin for i:=1 to 3 do M[i].Move(t); {перемещаем строки} t:=t+1; for i:=1 to 1000 do delay(1000); end; for i:=1 to 3 do M[i].Done; closeGraph; end.
unit unitMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Generics.Collections, System.Threading, System.IOUtils, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.Controls.Presentation, FMX.Edit, FMX.ListView, FMX.Layouts, FMX.Surfaces, FMX.Helpers.Android, Androidapi.Helpers, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes, Androidapi.Jni, Androidapi.JNIBridge, Androidapi.JNI.App, FMX.StdCtrls; type TformMain = class(TForm) layFind: TLayout; layAppList: TLayout; AppListView: TListView; txtFind: TEdit; ClearEditButton1: TClearEditButton; procedure FormCreate(Sender: TObject); procedure AppListViewItemClick(const Sender: TObject; const AItem: TListViewItem); procedure txtFindTyping(Sender: TObject); procedure txtFindChange(Sender: TObject); private { Private declarations } MainList : TList<JActivityInfo>; dictAppIcons : TDictionary<Integer, TBitmap>; procedure LoadActivityInfoList(var List : TList<JActivityInfo>); procedure LoadDictonaryAppIcons(index : Integer; appInfo : JApplicationInfo; var dictonaryAppIcons : TDictionary<Integer, TBitmap>); procedure LoadListView(listView : TListView; AppList: TList<JActivityInfo>; dictonaryAppIcons : TDictionary<Integer, TBitmap>); procedure OpenApp(PackageName, AppName : JString); procedure FilterListView(listView : TListView; filterName : string); procedure LoadListViewBitmap(listView: TListView; AppList: TList<JActivityInfo>; var dictonaryAppIcons : TDictionary<Integer, TBitmap>); function GetActivityAppList : JList; function GetOrSetCashAppIcon(appInfo : JApplicationInfo) : TBitmap; public { Public declarations } end; const DEFAUT_INDEX : Integer = -1; var formMain: TformMain; implementation {$R *.fmx} { TformMain } {------------------------------------------------------------------------------} procedure TformMain.OpenApp(PackageName, AppName : JString); var Intent : JIntent; NativeComponent : JComponentName; begin Intent := TJIntent.Create; Intent.setAction(TJIntent.JavaClass.ACTION_MAIN); Intent.addCategory(TJIntent.JavaClass.CATEGORY_LAUNCHER); NativeComponent := TJComponentName.JavaClass.init(PackageName, AppName); Intent.addFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK or TJIntent.JavaClass.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); Intent.setComponent(NativeComponent); SharedActivity.startActivity(Intent); end; {------------------------------------------------------------------------------} procedure TformMain.txtFindChange(Sender: TObject); begin if txtFind.Text='' then FilterListView(self.AppListView, txtFind.Text.Trim); end; procedure TformMain.txtFindTyping(Sender: TObject); begin FilterListView(self.AppListView, txtFind.Text.Trim); end; {------------------------------------------------------------------------------} procedure TformMain.AppListViewItemClick(const Sender: TObject; const AItem: TListViewItem); begin if not Assigned(MainList) then Exit; OpenApp(MainList.Items[AItem.Tag].applicationInfo.packageName, MainList.Items[AItem.Tag].name); end; {------------------------------------------------------------------------------} procedure TformMain.FilterListView(listView : TListView; filterName : string); var i : integer; item : TListViewItem; lower : string; begin if not Assigned(listView) then exit; lower := filterName.ToLower.Trim; if lower.IsEmpty then begin if Assigned(listView.Items.Filter) then listView.Items.Filter := nil; end else begin listView.ItemIndex := DEFAUT_INDEX; listView.Items.Filter := function(sFilter : string) : Boolean begin Result := (lower.IsEmpty) or sFilter.ToLower.Contains(lower); end; end; end; {------------------------------------------------------------------------------} procedure TformMain.FormCreate(Sender: TObject); begin LoadActivityInfoList(MainList); LoadListView(Self.AppListView, MainList, self.dictAppIcons); LoadListViewBitmap(Self.AppListView, MainList, self.dictAppIcons); Self.AppListView.So end; {------------------------------------------------------------------------------} function TformMain.GetActivityAppList: JList; var tempList : JList; Intent : JIntent; Manager : JPackageManager; begin Intent := TJIntent.Create; Intent.setAction(TJIntent.JavaClass.ACTION_MAIN); Intent.addCategory(TJIntent.JavaClass.CATEGORY_LAUNCHER); Manager := SharedActivity.getPackageManager; tempList := nil; tempList := Manager.queryIntentActivities(Intent, 0); Result := tempList; end; {------------------------------------------------------------------------------} function TformMain.GetOrSetCashAppIcon(appInfo: JApplicationInfo): TBitmap; var Drawable : JDrawable; Bitmap : JBitmap; itemBitmap : TBitmap; Surface : TBitmapSurface; saveDir : string; pngFileName : string; SaveParams: TBitmapCodecSaveParams; begin if not Assigned(appInfo) then begin Result := itemBitmap; exit; end; saveDir := TPath.GetCachePath; pngFileName := saveDir + '/' + JStringToString(appInfo.packageName) + '.png'; itemBitmap := TBitmap.Create; if not TDirectory.Exists(saveDir, False) then TDirectory.CreateDirectory(saveDir); if TFile.Exists(pngFileName) then itemBitmap.LoadFromFile(pngFileName) else begin Drawable := appInfo.loadIcon(SharedActivity.getPackageManager); Bitmap := TJBitmapDrawable.Wrap((Drawable as ILocalObject).GetObjectID).getBitmap; Surface := TBitmapSurface.Create; try if JBitmapToSurface(Bitmap, Surface) then begin itemBitmap.Assign(Surface); SaveParams.Quality := 100; itemBitmap.SaveToFile(pngFileName, @SaveParams); end; finally Surface.Free; end; end; Result := itemBitmap; end; {------------------------------------------------------------------------------} procedure TformMain.LoadActivityInfoList(var List: TList<JActivityInfo>); var tempList : JList; i : Integer; ResolveInfo : JResolveInfo; Info : JActivityInfo; AppInfo : JApplicationInfo; begin if not Assigned(List) then List := TList<JActivityInfo>.Create; List.Clear; tempList := Self.GetActivityAppList; for i := 0 to tempList.size - 1 do begin ResolveInfo := TJResolveInfo.Wrap((tempList.get(i) as ILocalObject).GetObjectID); Info := TJActivityInfo.Wrap((ResolveInfo.activityInfo as ILocalObject).GetObjectID); AppInfo := TJApplicationInfo.Wrap((Info.applicationInfo as ILocalObject).GetObjectID); List.Add(Info); end; end; {------------------------------------------------------------------------------} procedure TformMain.LoadDictonaryAppIcons( index : Integer; appInfo : JApplicationInfo; var dictonaryAppIcons : TDictionary<Integer, TBitmap>); var itemBitmap : TBitmap; begin if not Assigned(dictonaryAppIcons) then dictonaryAppIcons := TDictionary<Integer, TBitmap>.Create; if not dictonaryAppIcons.ContainsKey(index) then begin itemBitmap := GetOrSetCashAppIcon(appInfo); dictonaryAppIcons.AddOrSetValue(index, itemBitmap); end; end; {------------------------------------------------------------------------------} procedure TformMain.LoadListView(listView: TListView; AppList: TList<JActivityInfo>; dictonaryAppIcons : TDictionary<Integer, TBitmap>); var tempItem : TListViewItem; tempString, tempSubString, tempSubString2 : string; i : integer; begin if (not Assigned(listView)) or (not Assigned(AppList)) then exit; listView.ClearItems; listView.BeginUpdate; for I := 0 to AppList.Count - 1 do begin tempString := JStringToString(AppList.Items[i].applicationInfo.loadLabel(SharedActivity.getPackageManager).toString); tempItem := listView.Items.Add; tempItem.Text := tempString; tempItem.Tag := i; end; listView.EndUpdate; end; {------------------------------------------------------------------------------} procedure TformMain.LoadListViewBitmap(listView: TListView; AppList: TList<JActivityInfo>; var dictonaryAppIcons : TDictionary<Integer, TBitmap>); var i : integer; begin if (not Assigned(listView)) or (not Assigned(AppList)) then exit; listView.BeginUpdate; for I := 0 to listView.ItemCount - 1 do begin listView.Items[i].BeginUpdate; LoadDictonaryAppIcons(i, AppList.Items[listView.Items[i].Tag].applicationInfo, dictonaryAppIcons); if Assigned(dictonaryAppIcons) and (dictonaryAppIcons.ContainsKey(i)) then listView.Items[i].Bitmap := dictonaryAppIcons.Items[i]; listView.Items[i].EndUpdate; Application.ProcessMessages; end; listView.EndUpdate; end; {------------------------------------------------------------------------------} end.
unit osDBDualTree; interface uses Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, ComCtrls, DB, Variants, StdCtrls; type TNodeSelectEvent = procedure(LeafSelected: boolean) of object; TVariantRef = class(TObject) private FValue: Variant; public constructor Create(AValue: Variant); property Value: Variant read FValue; end; TosDBDualTree = class(TCustomPanel) private FLeftTree: TTreeView; FRightTree: TTreeView; FLeftLabel: TLabel; FRightLabel: TLabel; FToLeftButton: TButton; FToRightButton: TButton; FAssociationDataSet: TDataSet; FAssociationField: TField; FAssociationFieldName: string; FSourceDataSet: TDataSet; FSourceField: TField; FSourceFieldName: string; { DONE : Arranjar um nome mais sugestivo para FSourceFieldCount (e.g. LevelCount) } FLevelCount: integer; FSourceDescFields: array of TField; FSourceDescFieldNames: TStrings; FOnNodeSelect: TNodeSelectEvent; FOnLeftNodeSelect: TNodeSelectEvent; { TODO : Encontrar um modo mais elegante de impedir que o evento OnNodeSelect seja disparado durante o método Clear } FClearing: boolean; procedure SetAssociationFieldName(const Value: string); procedure SetSourceFieldName(const Value: string); procedure SetSourceDescFieldNames(const Value: TStrings); { DONE : Remover este método sobrecarregado quando se estiver certo da finalidade do método FindOrCreateNode } { DONE : Talvez seja melhor este método receber o TVariantRef já criado. Dessa forma não será necessário criar novos objetos (e excluir outros) ao fazer o movimento dos registros } { DONE : Verificar a necessidade de cada parâmetro do método FindOrCreateNode e mudar o seu nome, caso sua funcionalidade seja alterada (e.g. CreateNode) } procedure CreateNode(TreeView: TTreeView; const Captions: array of string; FieldIDRef: TVariantRef); procedure MoveSelectedNodes(FromTree, ToTree: TTreeView); { DONE : UpdateDataSet não é um nome bom para este método e ele poderia ser local ao método MoveSelectedNodes } procedure ToLeftButtonClick(Sender: TObject); procedure ToRightButtonClick(Sender: TObject); procedure RightTreeChange(Sender: TObject; Node: TTreeNode); procedure LeftTreeChange(Sender: TObject; Node: TTreeNode); procedure RightTreeEnter(Sender: TObject); procedure LeftTreeEnter(Sender: TObject); procedure ResizeComponents; function GetAssociationCaption: string; function GetSourceCaption: string; procedure SetAssociationCaption(const Value: string); procedure SetSourceCaption(const Value: string); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Resize; override; procedure Loaded; override; procedure DoNodeSelect(LeafSelected: boolean); procedure DoLeftNodeSelect(LeafSelected: boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Load; procedure Clear; // Just to test memory leaks procedure MoveRandomly(Direction: boolean); property AssociationTree: TTreeView read FRightTree; property SourceTree: TTreeView read FLeftTree; published property AssociationDataSet: TDataSet read FAssociationDataSet write FAssociationDataSet; property AssociationFieldName: string read FAssociationFieldName write SetAssociationFieldName; property SourceDataSet: TDataSet read FSourceDataSet write FSourceDataSet; property SourceFieldName: string read FSourceFieldName write SetSourceFieldName; property SourceDescFieldNames: TStrings read FSourceDescFieldNames write SetSourceDescFieldNames; property OnNodeSelect: TNodeSelectEvent read FOnNodeSelect write FOnNodeSelect; property OnLeftNodeSelect: TNodeSelectEvent read FOnLeftNodeSelect write FOnLeftNodeSelect; property AssociationCaption: string read GetAssociationCaption write SetAssociationCaption; property SourceCaption: string read GetSourceCaption write SetSourceCaption; property Align; property Alignment; property Anchors; property AutoSize; property BevelInner; property BevelOuter; property BevelWidth; property BiDiMode; property BorderWidth; property BorderStyle; property Caption; property Color; property Constraints; property Ctl3D; property UseDockManager default True; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property FullRepaint; property Font; property Locked; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; procedure Register; implementation procedure Register; begin RegisterComponents('OS Controls', [TosDBDualTree]); end; { TVariantRef } constructor TVariantRef.Create(AValue: Variant); begin FValue := AValue; end; { TosDBDualTree } { DONE : Fazer o componente reagir a mudanças do DataSet e posicionar-se nele quando o usuário clicar em uma folha da árvore } { TODO : Fazer o componente reagir a mudanças do DataSet } { TODO : Copiar o estado de expansão ao mover registros de uma árvore para outra } { DONE : Permitir a inserção de labels para os TreeView's } { TODO : Permitir que os nós da árvore sejam ordenados alfabeticamente } procedure TosDBDualTree.Clear; var Node: TTreeNode; begin FClearing := True; Node := FLeftTree.Items.GetFirstNode; while Node <> nil do begin if Node.Data <> nil then TVariantRef(Node.Data).Free; Node := Node.GetNext; end; FLeftTree.Items.Clear; Node := FRightTree.Items.GetFirstNode; while Node <> nil do begin if Node.Data <> nil then TVariantRef(Node.Data).Free; Node := Node.GetNext; end; FRightTree.Items.Clear; FClearing := False; end; constructor TosDBDualTree.Create(AOwner: TComponent); begin inherited; FClearing := False; BevelOuter := bvNone; // Previne o controle de tentar definir o próprio Caption ControlStyle := ControlStyle - [csSetCaption]; { TODO : Acertar o caption em design-time } Caption := ''; FLeftLabel := TLabel.Create(Self); FLeftLabel.Top := 0; FLeftLabel.Left := 0; FLeftLabel.AutoSize := False; FLeftLabel.Alignment := taCenter; FLeftLabel.Parent := Self; FRightLabel := TLabel.Create(Self); FRightLabel.Top := 0; FRightLabel.AutoSize := False; FRightLabel.Alignment := taCenter; FRightLabel.Parent := Self; FLeftTree := TTreeView.Create(Self); FLeftTree.Left := 0; FLeftTree.Top := 16; // FLeftTree.Align := alLeft; FLeftTree.Anchors := [akLeft, akTop, akBottom]; FLeftTree.MultiSelect := True; FLeftTree.MultiSelectStyle := [msControlSelect, msShiftSelect]; FLeftTree.ReadOnly := True; FLeftTree.Parent := Self; FLeftTree.HideSelection := False; FLeftTree.SortType := stText; FLeftTree.OnChange := LeftTreeChange; FLeftTree.OnEnter := LeftTreeEnter; FRightTree := TTreeView.Create(Self); FRightTree.Top := 16; // FRightTree.Align := alRight; FRightTree.Anchors := [akTop, akRight, akBottom]; FRightTree.MultiSelect := True; FRightTree.MultiSelectStyle := [msControlSelect, msShiftSelect]; FRightTree.ReadOnly := True; FRightTree.Parent := Self; FRightTree.OnChange := RightTreeChange; FRightTree.HideSelection := False; FRightTree.SortType := stText; FRightTree.OnEnter := RightTreeEnter; FToLeftButton := TButton.Create(Self); FToLeftButton.Caption := '<'; FToLeftButton.Height := 25; FToLeftButton.Width := 25; FToLeftButton.OnClick := ToLeftButtonClick; FToLeftButton.Parent := Self; FToRightButton := TButton.Create(Self); FToRightButton.Caption := '>'; FToRightButton.Height := 25; FToRightButton.Width := 25; FToRightButton.OnClick := ToRightButtonClick; FToRightButton.Parent := Self; FLevelCount := 0; FSourceDescFieldNames := TStringList.Create; end; destructor TosDBDualTree.Destroy; begin Finalize(FSourceDescFields); FSourceDescFieldNames.Free; inherited; end; procedure TosDBDualTree.DoNodeSelect(LeafSelected: boolean); begin if Assigned(FOnNodeSelect) then FOnNodeSelect(LeafSelected); end; procedure TosDBDualTree.CreateNode(TreeView: TTreeView; const Captions: array of string; FieldIDRef: TVariantRef); var i: integer; TreeNode, SearchNode: TTreeNode; begin Assert(Length(Captions) = FLevelCount, 'The length of Captions must be ' + 'be the count of fields in SourceDataSet'); { DONE : Este método não parece ter sido muito bem desenhado. O valor nil atribuído a TreeNode não parece ser muito coerente, uma vez que o método deve acabar com um TreeNode diferente de nil. Talvez exista um modo de remover o primeiro 'if' do loop 'for' } { DONE : Do modo como está construído as árvores nunca conterão nomes repetidos. Isso causa um efeito colateral ao mostrar os dados do ClientDataSet. Se existem dois registros com o mesmo nome na mesma árvore, aparecerá somente um registro nesta. Se ele for movido para a outra árvore e for feito um Load novamente, o registro com nome repetido aparecerá nas duas árvores. Seria mais conveniente se o componente aceitasse nomes repetidos na mesma árvore. } TreeNode := nil; for i := 0 to FLevelCount - 2 do begin if TreeNode = nil then SearchNode := TreeView.Items.GetFirstNode else SearchNode := TreeNode.getFirstChild; while (SearchNode <> nil) and (SearchNode.Text <> Captions[i]) do SearchNode := SearchNode.getNextSibling; if SearchNode = nil then TreeNode := TreeView.Items.AddChild(TreeNode, Captions[i]) else TreeNode := SearchNode; end; TreeNode := TreeView.Items.AddChild(TreeNode, Captions[FLevelCount - 1]); Assert(TreeNode <> nil, 'TreeNode must not be nil at the end of the ' + 'insertion. This can be caused by a null list of fields in ' + 'FSourceFieldNames'); { DONE : Provavelmente este teste (Result = fcCreated) deverá desaparecer. O bookmark será atribuído ao nó incodicionalmente } TreeNode.Data := FieldIDRef; end; function TosDBDualTree.GetAssociationCaption: string; begin Result := FRightLabel.Caption; end; function TosDBDualTree.GetSourceCaption: string; begin Result := FLeftLabel.Caption; end; procedure TosDBDualTree.Load; var i, j: integer; Bookmark: TBookmark; Values: array of string; DataSetActive: boolean; begin { TODO : Criar uma propriedade para o usuário escolher se deseja mostrar as linhas } DataSetActive := FSourceDataSet.Active; Bookmark := nil; if FLevelCount = 1 then begin FLeftTree.ShowRoot := False; FRightTree.ShowRoot := False; end; Clear; if DataSetActive then begin FSourceDataSet.DisableControls; Bookmark := FSourceDataSet.GetBookmark; end else FSourceDataSet.Active := True; SetLength(Values, FLevelCount); try FSourceDataSet.First; for i := 0 to FSourceDataSet.RecordCount - 1 do begin for j := 0 to FLevelCount - 1 do try Values[j] := FSourceDescFields[j].AsString; except Values[j] := ''; end; if FAssociationDataSet.Locate(FAssociationFieldName, VarArrayOf([FSourceField.Value]), []) then CreateNode(FRightTree, Values, TVariantRef.Create(FSourceField.Value)) else CreateNode(FLeftTree, Values, TVariantRef.Create(FSourceField.Value)); FSourceDataSet.Next; end; finally Finalize(Values); if DataSetActive then begin FSourceDataSet.GotoBookmark(Bookmark); FSourceDataSet.FreeBookmark(Bookmark); FSourceDataSet.EnableControls; end else FSourceDataSet.Active := False; end; { TODO : Encontrar um modo mais elegante de manter os itens ordenados } FLeftTree.SortType := stNone; FLeftTree.SortType := stText; FRightTree.SortType := stNone; FRightTree.SortType := stText; end; procedure TosDBDualTree.MoveRandomly(Direction: boolean); var j: integer; begin if Direction then begin if FLeftTree.Items.Count >= 2 then begin j := Random(FLeftTree.Items.Count); FLeftTree.Items.Item[j].Selected := True; j := Random(FLeftTree.Items.Count); FLeftTree.Items.Item[j].Selected := True; MoveSelectedNodes(FLeftTree, FRightTree); end; end else begin if FRightTree.Items.Count >= 2 then begin j := Random(FRightTree.Items.Count); FRightTree.Items.Item[j].Selected := True; j := Random(FRightTree.Items.Count); FRightTree.Items.Item[j].Selected := True; MoveSelectedNodes(FRightTree, FLeftTree); end; end; end; procedure TosDBDualTree.Loaded; var i: integer; begin inherited; ResizeComponents; { TODO : Arranjar um modo mais elegante de inicializar o array de fields e sua contagem } if Assigned(FSourceDataSet) then begin FLevelCount := FSourceDescFieldNames.Count; SetLength(FSourceDescFields, FLevelCount); for i := 0 to FLevelCount - 1 do FSourceDescFields[i] := FSourceDataSet.FindField(FSourceDescFieldNames[i]); end; if Assigned(FSourceDataSet) then FSourceField := FSourceDataSet.FindField(FSourceFieldName); if Assigned(FAssociationDataSet) then FAssociationField := FAssociationDataSet.FindField(FAssociationFieldName); end; procedure TosDBDualTree.MoveSelectedNodes(FromTree, ToTree: TTreeView); procedure UpdateDataSet(Node: TTreeNode); begin Assert(Node.Level = FLevelCount - 1, 'UpdateDataSet cannot handle tree ' + 'branches (only leaves)'); Assert((Node.Owner.Owner = FLeftTree) or (Node.Owner.Owner = FRightTree), 'The owner of the node must be one of the TreeViews in the control'); if Node.Owner.Owner = FRightTree then begin Assert(FAssociationDataSet.Locate(FAssociationFieldName, VarArrayOf([TVariantRef(Node.Data).Value]), []), 'Could not locate ' + 'the corresponding field in the dataset. Maybe the dataset has ' + 'changed while it was been edited by the control'); FAssociationDataSet.Locate(FAssociationFieldName, VarArrayOf([TVariantRef(Node.Data).Value]), []); FAssociationDataSet.Delete; end else begin Assert(not FAssociationDataSet.Locate(FAssociationFieldName, VarArrayOf([TVariantRef(Node.Data).Value]), []), 'A field with the ' + 'same ID was found in the dataset before inserting the new record. ' + 'Maybe the dataset has changed while it was been edited by the ' + 'control'); FAssociationDataSet.Append; FAssociationField.Value := TVariantRef(Node.Data).Value; FAssociationDataSet.Post; end; end; var Captions: array of string; Level, j, SelIndex: integer; Parent, Node: TTreeNode; begin { TODO : Impedir a movimentação de registros sem que pelo menos um nó esteja visivelmente selecionado } SetLength(Captions, FLevelCount); try SelIndex := Integer(FromTree.SelectionCount) - 1; while SelIndex >= 0 do begin Node := FromTree.Selections[SelIndex]; Level := Node.Level; Parent := Node; for j := Level downto 0 do begin Captions[j] := Parent.Text; Parent := Parent.Parent; end; j := Level; repeat if Node.HasChildren then begin Node := Node.getFirstChild; Inc(j); Captions[j] := Node.Text; continue; end; Parent := Node.Parent; if j = FLevelCount - 1 then begin CreateNode(ToTree, Captions, TVariantRef(Node.Data)); UpdateDataSet(Node); { DONE : Quando o método FindOrCreateNode receber o TVariantRef já construído não será mais necessário (e nem poderá) apagar o objeto após movê-lo } end; if Node.Selected then Dec(SelIndex); Node.Delete; Node := Parent; Dec(j); until (Node = nil) or (j < Level) and (Node.HasChildren); end; finally Finalize(Captions); end; { TODO : Encontrar um modo mais elegante de manter os itens ordenados } ToTree.SortType := stNone; ToTree.SortType := stText; end; procedure TosDBDualTree.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) then begin if AComponent = FAssociationDataSet then FAssociationDataSet := nil else if AComponent = FSourceDataSet then FSourceDataSet := nil; end; end; procedure TosDBDualTree.Resize; begin inherited; ResizeComponents; end; procedure TosDBDualTree.ResizeComponents; begin FLeftTree.Width := (Width - 39) div 2; FLeftTree.Height := Height - 16; FRightTree.Width := FLeftTree.Width + 1 - Width mod 2; FRightTree.Left := Width - FRightTree.Width; FRightTree.Height := FLeftTree.Height; FLeftLabel.Width := FLeftTree.Width; FRightLabel.Left := FRightTree.Left; FRightLabel.Width := FRightTree.Width; FToRightButton.Top := 16 + (Height - 73) div 2; FToRightButton.Left := FLeftTree.Width + 7; FToLeftButton.Top := FToRightButton.Top + 32; FToLeftButton.Left := FToRightButton.Left; end; procedure TosDBDualTree.RightTreeChange(Sender: TObject; Node: TTreeNode); begin if not FClearing then begin if Node.Level = FLevelCount - 1 then begin { TODO : Descobrir por que o Locate não funciona se não for feito um TDataSet.First primeiro. O caso de teste usava o form Cargo, com um detalhe (função) para o cargo e três detalhes (processos) para a função } FAssociationDataSet.First; Assert(FAssociationDataSet.Locate(FAssociationFieldName, VarArrayOf([TVariantRef(Node.Data).Value]), []), 'Could not locate the ' + 'corresponding field in the dataset. Maybe the dataset has changed ' + 'while it was been edited by the control'); FAssociationDataSet.Locate(FAssociationFieldName, VarArrayOf([TVariantRef(Node.Data).Value]), []); DoNodeSelect(True); end else DoNodeSelect(False); end; end; procedure TosDBDualTree.SetAssociationFieldName(const Value: string); begin FAssociationFieldName := Value; if Assigned(FAssociationDataSet) then FAssociationField := FAssociationDataSet.FindField(Value); end; procedure TosDBDualTree.SetAssociationCaption(const Value: string); begin FRightLabel.Caption := Value; end; procedure TosDBDualTree.SetSourceCaption(const Value: string); begin FLeftLabel.Caption := Value; end; procedure TosDBDualTree.SetSourceDescFieldNames(const Value: TStrings); var i: integer; begin FSourceDescFieldNames.Assign(Value); if Assigned(FSourceDataSet) then begin FLevelCount := FSourceDescFieldNames.Count; SetLength(FSourceDescFields, FLevelCount); for i := 0 to FLevelCount - 1 do FSourceDescFields[i] := FSourceDataSet.FindField(FSourceDescFieldNames[i]); end; end; procedure TosDBDualTree.SetSourceFieldName(const Value: string); begin FSourceFieldName := Value; if Assigned(FSourceDataSet) then FSourceField := FSourceDataSet.FindField(Value); end; procedure TosDBDualTree.ToLeftButtonClick(Sender: TObject); begin MoveSelectedNodes(FRightTree, FLeftTree); end; procedure TosDBDualTree.ToRightButtonClick(Sender: TObject); begin MoveSelectedNodes(FLeftTree, FRightTree); end; procedure TosDBDualTree.DoLeftNodeSelect(LeafSelected: boolean); begin if Assigned(FOnLeftNodeSelect) then FOnLeftNodeSelect(LeafSelected); end; procedure TosDBDualTree.LeftTreeChange(Sender: TObject; Node: TTreeNode); begin if not FClearing then begin if Node.Level = FLevelCount - 1 then begin if FSourceDataSet.Active then begin FSourceDataSet.First; Assert(FSourceDataSet.Locate(FSourceFieldName, VarArrayOf([TVariantRef(Node.Data).Value]), []), 'Could not locate the ' + 'corresponding field in the dataset. Maybe the dataset has changed ' + 'while it was been edited by the control'); FSourceDataSet.Locate(FSourceFieldName, VarArrayOf([TVariantRef(Node.Data).Value]), []); DoLeftNodeSelect(True); end; end else DoLeftNodeSelect(False); end; end; procedure TosDBDualTree.LeftTreeEnter(Sender: TObject); begin if Assigned(FLeftTree.Selected) then LeftTreeChange(FLeftTree, FLeftTree.Selected); end; procedure TosDBDualTree.RightTreeEnter(Sender: TObject); begin if Assigned(FRightTree.Selected) then RightTreeChange(FRightTree, FRightTree.Selected); end; end.
unit uUtils; {$mode objfpc}{$H+} interface function Iif(Cond:boolean; const TrueResult:String; const FalseResult:string):string;overload; function Iif(Cond:boolean; const TrueResult:integer; const FalseResult:integer):integer;overload; function IfEmpty(const S:String; const ThenReplace:string):string; implementation function IfEmpty(const S:String; const ThenReplace:string):string; begin if S = '' then Result:=ThenReplace else Result:=S; end; function Iif(Cond:boolean; const TrueResult:String; const FalseResult:string):string;overload; begin if Cond then Result:=TrueResult else Result:=FalseResult; end; function Iif(Cond:boolean; const TrueResult:integer; const FalseResult:integer):integer;overload; begin if Cond then Result:=TrueResult else Result:=FalseResult; end; end.
unit internet; interface uses WinInet, Winapi.Windows, System.SysUtils; function verificarConexaoComInternet(): Boolean; function checkUrl(url: string): boolean; implementation function verificarConexaoComInternet(): Boolean; var i: dword; begin Result := InternetGetConnectedState(@i, 0); end; function checkUrl(url: string): boolean; var hSession, hfile, hRequest: hInternet; dwindex, dwcodelen: dword; dwcode: array[1..20] of char; res: pchar; begin if pos('http://', LowerCase(url)) = 0 then url := 'http://' + url; Result := false; hSession := InternetOpen('InetURL:/1.0', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); if assigned(hsession) then begin hfile := InternetOpenUrl(hsession, pchar(url), nil, 0, INTERNET_FLAG_RELOAD, 0); dwIndex := 0; dwCodeLen := 10; HttpQueryInfo(hfile, HTTP_QUERY_STATUS_CODE, @dwcode, dwcodeLen, dwIndex); res := pchar(@dwcode); result := (res = '200') or (res = '302'); if assigned(hfile) then InternetCloseHandle(hfile); InternetCloseHandle(hsession); end; end; end.
//Font https://github.com/vintagedave/transparent-canvas unit TransparentCanvas; { 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 an alpha-aware canvas class and associated classes. The Initial Developer of the Original Code is David Millington. Portions created by David Millington are Copyright (C) 2008-2012. All Rights Reserved. Contributor(s): David Millington. Frank Staal } interface uses Windows, SysUtils, Classes, Controls, Graphics, Types {$if CompilerVersion >= 23.0} // XE2 , UITypes // Let inline function TFont.GetStyle be expanded {$ifend} ; type ETransparentCanvasException = class(Exception) end; TQuadColor = record constructor Create(Color : TColor); procedure Clear; function WrittenByGDI : Boolean; procedure SetAlpha(const Transparency : Byte; const PreMult : Single); function AsColorRef : COLORREF; procedure SetFromColorRef(const Color : COLORREF); procedure SetFromColorMultAlpha(const Color : TQuadColor); case Boolean of // These values are not in the same order as COLORREF RGB values - don't assign from a COLORREF directly True : (Blue, Green, Red, Alpha : Byte); False : (Quad : Cardinal); end; PQuadColor = ^TQuadColor; PPQuadColor = ^PQuadColor; TGDIObjects = record private FBrush : HBRUSH; FPen : HPEN; FFont : HFONT; public constructor CreateWithHandles(const hBrush : HBRUSH; const hPen : HPEN; const hFont : HFONT); property Brush : HBRUSH read FBrush; property Pen : HPEN read FPen; property Font : HFONT read FFont; end; TAlphaBitmapWrapper = class(TPersistent) private FDCHandle : HDC; FBMPHandle, FOriginalBMP : HBitmap; FQuads : PQuadColor; FWidth, FHeight : Integer; FOriginalObjects : TGDIObjects; procedure Construct(DC: HDC; Empty: Boolean; Width, Height: Integer; Inverted : boolean = false); procedure CheckHandles; procedure Clear; public constructor CreateBlank(DC: HDC; Width, Height: Integer); // The DummyX parameters are to avoid duplicate constructors with the same parameter list being // inaccessible from C++, although only necessary if you write C++ code that uses this (internal) // class constructor CreateForGDI(DC: HDC; Width, Height: Integer; DummyGDI : Byte = 0); constructor CreateForDrawThemeTextEx(DC: HDC; Width, Height: Integer; DummyDrawThemeTextEx : SmallInt = 0); constructor Create(var ToCopy : TAlphaBitmapWrapper); destructor Destroy; override; procedure SelectObjects(const GDI : TGDIObjects); procedure SelectOriginalObjects; procedure SetAllTransparency(const Alpha: Byte); procedure ProcessTransparency(const Alpha: Byte); overload; procedure ProcessTransparency(const Alpha: Byte; TranspRect : TRect); overload; procedure ProcessMaskTransparency(var MaskImage: TAlphaBitmapWrapper); procedure ProcessTransparentColor(const TransparentColor : COLORREF; const TransparentEdgeWidth : Integer = -1); procedure TintByAlphaToColor(const Color : TQuadColor); procedure BlendTo(X, Y: Integer; var Image: TAlphaBitmapWrapper; Transparency: Byte = $FF); procedure BlendToStretch(X, Y, StretchWidth, StretchHeight: Integer; var Image: TAlphaBitmapWrapper; Transparency: Byte); procedure BlendToDC(X, Y : Integer; DC : HDC; Transparency : Byte = $FF); function GetRawPixelPtr(const X, Y : Integer) : PQuadColor; procedure SafeSetRawPixel(const X, Y : Integer; Color : TQuadColor); published property Handle : HDC read FDCHandle; property BitmapHandle : HBitmap read FBMPHandle; function QuadPointer : PQuadColor; property Width : Integer read FWidth; property Height : Integer read FHeight; end; TCustomTransparentCanvas = class(TPersistent) class function TColorToQuadColor(Color : TColor) : TQuadColor; class function QuadColorToTColor(Color: TQuadColor) : TColor; private FFont : TFont; FBrush : TBrush; FPen : TPen; FAttachedDC : HDC; function GetHandle() : HDC; procedure SetFont(NewFont : TFont); procedure SetBrush(NewBrush : TBrush); procedure SetPen(NewPen : TPen); function GetPenPos : TPoint; procedure SetPenPos(NewPos : TPoint); function GetWidth : Integer; function GetHeight : Integer; // Converts to non-premultiplied alpha function GetPixel(X, Y : Integer) : COLORREF; procedure SetPixel(X, Y: Integer; Color: Cardinal); overload; procedure SetPixel(X, Y: Integer; Color: Cardinal; Alpha: Byte); overload; // Direct pre-multiplied alpha function GetRawPixel(X, Y : Integer) : TQuadColor; procedure SetRawPixel(X, Y : Integer; Color : TQuadColor); procedure TextOutPreVista(const Rect : TRect; const Text: string; const Alignment : TAlignment; const Alpha : Byte); procedure TextOutVistaPlus(const ARect : TRect; const Text: string; const Alignment : TAlignment; const Alpha : Byte); function CanUseDrawThemeTextEx : boolean; procedure InternalGlowTextOut(const X, Y, GlowSize: Integer; const Text: string; const Alignment : TAlignment; const Alpha: Byte; const ProcessBackColor : Boolean; const BackColor : TQuadColor); overload; procedure InternalGlowTextOut(const ARect : TRect; const GlowSize: Integer; const Text: string; const Alignment : TAlignment; const Alpha: Byte; const ProcessBackColor : Boolean; const BackColor : TQuadColor); overload; protected FWorkingCanvas : TAlphaBitmapWrapper; function OrphanAliasedFont : HFONT; public constructor Create(Width, Height : Integer); overload; constructor Create(Canvas: TCanvas); overload; constructor Create(DC : HDC; Width, Height : Integer); overload; constructor Create(ToCopy : TCustomTransparentCanvas); overload; destructor Destroy; override; procedure Assign(Source : TPersistent); override; procedure AssignTo(Dest: TPersistent); override; procedure SaveToFile(const Filename : string); procedure Draw(const X, Y: Integer; Canvas: TCanvas; const Width, Height : Integer; const UseTransparentColor : Boolean = false; const TransparentColor : COLORREF = $0; const TransparentEdgeWidth : Integer = -1); overload; procedure Draw(const X, Y: Integer; const Metafile: TMetafile; const Width, Height : Integer; const Transparency : Byte = $FF); overload; procedure Draw(const X, Y : Integer; Other : TCustomTransparentCanvas; const Transparency : Byte = 255); overload; procedure DrawTo(const X, Y : Integer; Canvas : TCanvas; const TargetWidth, TargetHeight: Integer; const Transparency : Byte = $FF); overload; procedure DrawTo(const X, Y: Integer; DC: HDC; const TargetWidth, TargetHeight: Integer; const Transparency : Byte = $FF); overload; procedure DrawToGlass(const X, Y : Integer; DC : HDC; const Transparency : Byte = $FF); procedure Ellipse(const X1, Y1, X2, Y2: Integer; const Alpha : Byte = $FF); overload; procedure Ellipse(const Rect : TRect; const Alpha : Byte = $FF); overload; procedure MoveTo(const X, Y: Integer); procedure RoundRect(const X1, Y1, X2, Y2, XRadius, YRadius: Integer; const Alpha : Byte = $FF); overload; procedure RoundRect(const Rect : TRect; const XRadius, YRadius : Integer; const Alpha : Byte = $FF); overload; procedure Rectangle(const X1, Y1, X2, Y2: Integer; const Alpha : Byte = $FF); overload; procedure Rectangle(const Rect : TRect; const Alpha : Byte = $FF); overload; function TextExtent(const Text: string): TSize; function TextHeight(const Text: string): Integer; procedure TextOut(const X, Y: Integer; const Text: string; const Alignment : TAlignment = taLeftJustify; const Alpha : Byte = $FF); procedure TextRect(const Rect: TRect; const Text: string; const Alignment : TAlignment = taLeftJustify; const Alpha : Byte = $FF); function TextWidth(const Text: string): Integer; function CanDrawGlowText : boolean; procedure GlowTextOut(const X, Y, GlowSize: Integer; const Text: string; const Alignment : TAlignment = taLeftJustify; const Alpha : Byte = $FF); procedure GlowTextOutBackColor(const X, Y, GlowSize: Integer; const Text: string; const BackColor : TColor; const Alignment : TAlignment = taLeftJustify; const GlowAlpha : Byte = $FF; const Alpha : Byte = $FF); procedure Clear; property Handle: HDC read GetHandle; property PenPos: TPoint read GetPenPos write SetPenPos; property Pixels[X, Y: Integer]: COLORREF read GetPixel write SetPixel; property RawPixels[X, Y: Integer]: TQuadColor read GetRawPixel write SetRawPixel; published property Brush: TBrush read FBrush write SetBrush; property Font: TFont read FFont write SetFont; property Pen: TPen read FPen write SetPen; property Width : Integer read GetWidth; property Height : Integer read GetHeight; end; TTransparentCanvas = class(TCustomTransparentCanvas) end; TTransparentControlCanvas = class(TCustomTransparentCanvas) private FControl : TWinControl; FControlDC : HDC; public constructor Create(Control : TWinControl); destructor Destroy; override; end; implementation uses Math, Themes, UxTheme, RTLConsts; {$if CompilerVersion >= 23.0} // XE2 function InternalStyleServices : TCustomStyleServices; begin {$if declared(StyleServices)} Result := StyleServices; {$else} Result := ThemeServices; // Deprecated in favour of StyleServices {$ifend} end; {$else} function InternalStyleServices : TThemeServices; begin Result := ThemeServices; end; {$ifend} function AlignmentToFlags(const Alignment : TAlignment) : DWORD; begin Result := 0; case Alignment of taLeftJustify: Result := DT_LEFT; taRightJustify: Result := DT_RIGHT; taCenter: Result := DT_CENTER; end; end; { TCustomTransparentCanvas } function TCustomTransparentCanvas.CanDrawGlowText: boolean; begin Result := CanUseDrawThemeTextEx; end; function TCustomTransparentCanvas.CanUseDrawThemeTextEx: boolean; begin Result := {$if declared(StyleServices)} // Can't test TCustomStyleServices.Enabled, assume deprecation follows StyleServices InternalStyleServices.Enabled {$else} InternalStyleServices.ThemesEnabled {$ifend} and (Win32MajorVersion >= 6); end; procedure TCustomTransparentCanvas.Clear; begin FWorkingCanvas.Clear; end; constructor TCustomTransparentCanvas.Create(Width, Height : Integer); begin inherited Create(); FWorkingCanvas := TAlphaBitmapWrapper.CreateBlank(0, Width, Height); FFont := TFont.Create; FBrush := TBrush.Create; FPen := TPen.Create; FAttachedDC := 0; end; constructor TCustomTransparentCanvas.Create(ToCopy: TCustomTransparentCanvas); begin inherited Create(); FWorkingCanvas := TAlphaBitmapWrapper.Create(ToCopy.FWorkingCanvas); FFont := TFont.Create; FFont.Assign(ToCopy.FFont); FBrush := TBrush.Create; FBrush.Assign(ToCopy.FBrush); FPen := TPen.Create; FPen.Assign(ToCopy.FPen); FAttachedDC := 0; end; constructor TCustomTransparentCanvas.Create(Canvas: TCanvas); begin inherited Create(); FAttachedDC := Canvas.Handle; FWorkingCanvas := TAlphaBitmapWrapper.CreateBlank(Canvas.Handle, Width, Height); FFont := TFont.Create; FBrush := TBrush.Create; FPen := TPen.Create; end; constructor TCustomTransparentCanvas.Create(DC: HDC; Width, Height : Integer); begin inherited Create(); FAttachedDC := DC; FWorkingCanvas := TAlphaBitmapWrapper.CreateBlank(DC, Width, Height); FFont := TFont.Create; FBrush := TBrush.Create; FPen := TPen.Create; end; destructor TCustomTransparentCanvas.Destroy; begin FreeAndNil(FWorkingCanvas); FreeAndNil(FFont); FreeAndNil(FBrush); FreeAndNil(FPen); inherited; end; procedure TCustomTransparentCanvas.Assign(Source : TPersistent); var ToCopy : TCustomTransparentCanvas; begin if Source is TCustomTransparentCanvas then begin ToCopy := Source as TCustomTransparentCanvas; FWorkingCanvas.Free; FWorkingCanvas := TAlphaBitmapWrapper.Create(ToCopy.FWorkingCanvas); assert(Assigned(FFont) and Assigned(FBrush) and Assigned(FPen)); FFont.Assign(ToCopy.FFont); FBrush.Assign(ToCopy.FBrush); FPen.Assign(ToCopy.FPen); FAttachedDC := 0; end else begin if Assigned(Source) then raise EConvertError.CreateResFmt(@RTLConsts.SAssignError, [Source.ClassName, ClassName]) else raise EConvertError.CreateResFmt(@RTLConsts.SAssignError, ['nil', ClassName]); end; end; procedure TCustomTransparentCanvas.AssignTo(Dest: TPersistent); begin Dest.Assign(Self); end; procedure TCustomTransparentCanvas.SaveToFile(const Filename : string); var BMP : TBitmap; begin // Draw to a transparent 32-bit bitmap, and save that BMP := TBitmap.Create; try BMP.PixelFormat := pf32bit; BMP.Width := Width; BMP.Height := Height; DrawTo(0, 0, BMP.Canvas, Width, Height); BMP.SaveToFile(Filename); finally BMP.Free; end; end; procedure TCustomTransparentCanvas.Draw(const X, Y: Integer; Canvas: TCanvas; const Width, Height : Integer; const UseTransparentColor : Boolean; const TransparentColor : COLORREF; const TransparentEdgeWidth : Integer); var TempImage : TAlphaBitmapWrapper; begin TempImage := TAlphaBitmapWrapper.CreateForGDI(FWorkingCanvas.FDCHandle, Width, Height); try BitBlt(TempImage.FDCHandle, 0, 0, Width, Height, Canvas.Handle, 0, 0, SRCCOPY); TempImage.SetAllTransparency($FF); // No need to test, all written by GDI if UseTransparentColor then TempImage.ProcessTransparentColor(TransparentColor, TransparentEdgeWidth); TempImage.BlendTo(X, Y, FWorkingCanvas); finally TempImage.Free; end; end; procedure TCustomTransparentCanvas.Draw(const X, Y: Integer; const Metafile: TMetafile; const Width, Height: Integer; const Transparency : Byte = $FF); var TempImage : TAlphaBitmapWrapper; begin TempImage := TAlphaBitmapWrapper.CreateForGDI(FWorkingCanvas.FDCHandle, Width, Height); try TempImage.SelectObjects(TGDIObjects.CreateWithHandles(Brush.Handle, Pen.Handle, Font.Handle)); try PlayEnhMetaFile(TempImage.FDCHandle, Metafile.Handle, Rect(0, 0, Width, Height)); TempImage.ProcessTransparency(Transparency); TempImage.BlendTo(X, Y, FWorkingCanvas); finally TempImage.SelectOriginalObjects; end; finally TempImage.Free; end; end; procedure TCustomTransparentCanvas.Draw(const X, Y : Integer; Other : TCustomTransparentCanvas; const Transparency : Byte = 255); begin Other.FWorkingCanvas.BlendTo(X, Y, FWorkingCanvas, Transparency); end; procedure TCustomTransparentCanvas.DrawTo(const X, Y: Integer; Canvas: TCanvas; const TargetWidth, TargetHeight: Integer; const Transparency : Byte = 255); begin DrawTo(X, Y, Canvas.Handle, TargetWidth, TargetHeight, Transparency); end; procedure TCustomTransparentCanvas.DrawTo(const X, Y: Integer; DC: HDC; const TargetWidth, TargetHeight: Integer; const Transparency : Byte = 255); var TempCanvas: TAlphaBitmapWrapper; begin // Create a 32-bit canvas with a copy of the dc drawn in it with opaque alpha TempCanvas := TAlphaBitmapWrapper.CreateBlank(DC, TargetWidth, TargetHeight); try BitBlt(TempCanvas.FDCHandle, 0, 0, TargetWidth, TargetHeight, DC, 0, 0, SRCCOPY); TempCanvas.SetAllTransparency($FF); // Now blend the working image onto it at (X, Y), possibly stretched if (TargetWidth = Width) and (TargetHeight = Height) then begin FWorkingCanvas.BlendTo(X, Y, TempCanvas, Transparency); end else begin FWorkingCanvas.BlendToStretch(X, Y, TargetWidth, TargetHeight, TempCanvas, Transparency); end; // Now blit the composited image back to the DC BitBlt(DC, 0, 0, TargetWidth, TargetHeight, TempCanvas.FDCHandle, 0, 0, SRCCOPY); finally TempCanvas.Free; end; end; procedure TCustomTransparentCanvas.DrawToGlass(const X, Y: Integer; DC: HDC; const Transparency : Byte); begin FWorkingCanvas.BlendToDC(X, Y, DC, Transparency); end; procedure TCustomTransparentCanvas.Ellipse(const X1, Y1, X2, Y2: Integer; const Alpha: Byte); var TempImage : TAlphaBitmapWrapper; begin TempImage := TAlphaBitmapWrapper.CreateForGDI(FWorkingCanvas.FDCHandle, X2-X1, Y2-Y1); try TempImage.SelectObjects(TGDIObjects.CreateWithHandles(Brush.Handle, Pen.Handle, Font.Handle)); SetWindowOrgEx(TempImage.FDCHandle, X1 - Pen.Width div 2, Y1 - Pen.Width div 2, nil); Windows.Ellipse(TempImage.FDCHandle, X1, Y1, X2, Y2); SetWindowOrgEx(TempImage.FDCHandle, 0, 0, nil); TempImage.ProcessTransparency(Alpha); TempImage.BlendTo(X1, Y1, FWorkingCanvas); TempImage.SelectOriginalObjects; finally TempImage.Free; end; end; procedure TCustomTransparentCanvas.Ellipse(const Rect: TRect; const Alpha: Byte); begin Ellipse(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, Alpha); end; function TCustomTransparentCanvas.GetHandle: HDC; begin Result := FWorkingCanvas.FDCHandle; end; function TCustomTransparentCanvas.GetHeight: Integer; begin Result := FWorkingCanvas.FHeight; end; function TCustomTransparentCanvas.GetPenPos: TPoint; begin GetCurrentPositionEx(FWorkingCanvas.FDCHandle, @Result); end; function TCustomTransparentCanvas.GetPixel(X, Y: Integer): COLORREF; begin Result := GetRawPixel(X, Y).AsColorRef; end; function TCustomTransparentCanvas.GetRawPixel(X, Y: Integer): TQuadColor; var PQuad : PQuadColor; InverseY : Integer; begin InverseY := FWorkingCanvas.FHeight - Y - 1; // 0 is top not bottom PQuad := FWorkingCanvas.FQuads; Inc(PQuad, (InverseY * Width) + X); Result := PQuad^; end; function TCustomTransparentCanvas.GetWidth: Integer; begin Result := FWorkingCanvas.FWidth; end; procedure TCustomTransparentCanvas.InternalGlowTextOut(const X, Y, GlowSize: Integer; const Text: string; const Alignment : TAlignment; const Alpha: Byte; const ProcessBackColor : Boolean; const BackColor : TQuadColor); var TextSize : TSize; begin TextSize := TextExtent(Text); InternalGlowTextOut(Rect(X, Y, X + TextSize.cx, Y + TextSize.cy), GlowSize, Text, Alignment, Alpha, ProcessBackColor, BackColor); end; procedure TCustomTransparentCanvas.InternalGlowTextOut(const ARect : TRect; const GlowSize: Integer; const Text: string; const Alignment : TAlignment; const Alpha: Byte; const ProcessBackColor : Boolean; const BackColor : TQuadColor); var TempImage : TAlphaBitmapWrapper; TextSize : TSize; Options : TDTTOpts; Details: TThemedElementDetails; TextRect : TRect; AlignFlags : DWORD; begin if Length(Text) = 0 then Exit; // Crash creating zero-sized bitmap if not CanDrawGlowText then raise ETransparentCanvasException.Create('Cannot use DrawThemeTextEx'); TextSize := TextExtent(Text); AlignFlags := AlignmentToFlags(Alignment); TempImage := TAlphaBitmapWrapper.CreateForDrawThemeTextEx(FWorkingCanvas.FDCHandle, TextSize.cx + GlowSize*2, TextSize.cy + GlowSize*2); try TempImage.SelectObjects(TGDIObjects.CreateWithHandles(0, 0, Font.Handle)); SetBkMode(TempImage.FDCHandle, TRANSPARENT); SetTextColor(TempImage.FDCHandle, ColorToRGB(Font.Color)); ZeroMemory(@Options, SizeOf(Options)); Options.dwSize := SizeOf(Options); Options.dwFlags := DTT_TEXTCOLOR or DTT_COMPOSITED or DTT_GLOWSIZE; Options.crText := ColorToRGB(Font.Color); Options.iGlowSize := GlowSize; Details := InternalStyleServices.GetElementDetails(teEditTextNormal); TextRect := Rect(GlowSize, GlowSize, TextSize.cx + GlowSize*2, TextSize.cy + GlowSize*2); DrawThemeTextEx(InternalStyleServices.Theme[teEdit], TempImage.FDCHandle, Details.Part, Details.State, PChar(Text), Length(Text), AlignFlags or DT_TOP or DT_NOCLIP, TextRect, Options); if ProcessBackColor then begin TempImage.TintByAlphaToColor(BackColor); // Now draw the text over again, but with no glow, so only the text is drawn TextRect := Rect(GlowSize, GlowSize, TextSize.cx + GlowSize, TextSize.cy + GlowSize); Options.dwFlags := DTT_TEXTCOLOR or DTT_COMPOSITED; Options.crText := ColorToRGB(Font.Color); Options.iGlowSize := 0; DrawThemeTextEx(InternalStyleServices.Theme[teEdit], TempImage.FDCHandle, Details.Part, Details.State, PChar(Text), Length(Text), AlignFlags or DT_TOP or DT_NOCLIP, TextRect, Options); end; case Alignment of taLeftJustify: TempImage.BlendTo(ARect.Left - GlowSize, ARect.Top - GlowSize, FWorkingCanvas, Alpha); taRightJustify: TempImage.BlendTo(ARect.Left - GlowSize * 2, ARect.Top - GlowSize, FWorkingCanvas, Alpha); taCenter: TempImage.BlendTo(ARect.Left - GlowSize * 2 + 1 + IfThen(GlowSize > 0, 1, -1), ARect.Top - GlowSize, FWorkingCanvas, Alpha); end; SetBkMode(TempImage.FDCHandle, OPAQUE); TempImage.SelectOriginalObjects; finally TempImage.Free; end; end; procedure TCustomTransparentCanvas.GlowTextOut(const X, Y, GlowSize: Integer; const Text: string; const Alignment : TAlignment; const Alpha: Byte); begin InternalGlowTextOut(X, Y, GlowSize, Text, Alignment, Alpha, False, TQuadColor.Create(0)); end; procedure TCustomTransparentCanvas.GlowTextOutBackColor(const X, Y, GlowSize: Integer; const Text: string; const BackColor: TColor; const Alignment : TAlignment; const GlowAlpha : Byte; const Alpha: Byte); var Background : TQuadColor; begin if (COLORREF(ColorToRGB(BackColor)) = RGB(255, 255, 255)) and (GlowAlpha = 255) then begin // White is the default on //Windows; do no special processing GlowTextOut(X, Y, GlowSize, Text, Alignment, Alpha); end else begin // Windows draws glowing text with a white background, always. To change the background colour, // draw with the normal white background and black text, then process the colours to change // white to the specified colour, and black to the font colour Background := TQuadColor.Create(BackColor); Background.SetAlpha(GlowAlpha, Alpha / 255.0); InternalGlowTextOut(X, Y, GlowSize, Text, Alignment, Alpha, True, Background); end; end; procedure TCustomTransparentCanvas.MoveTo(const X, Y: Integer); begin MoveToEx(FWorkingCanvas.FDCHandle, X, Y, nil); end; function TCustomTransparentCanvas.OrphanAliasedFont: HFONT; var FontWeight : Cardinal; begin // Font output and alpha is tricky with a ClearType or antialiased font. This method takes FFont // and creates a new font with the same attributes, but with ClearType and AA explicitly disabled if fsBold in Font.Style then FontWeight := FW_BOLD else FontWeight := FW_NORMAL; Result := CreateFont(FFont.Height, 0, 0, 0, FontWeight, Cardinal(fsItalic in Font.Style), Cardinal(fsUnderline in Font.Style), Cardinal(fsStrikeOut in Font.Style), DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH, PChar(Font.Name)); end; class function TCustomTransparentCanvas.QuadColorToTColor(Color: TQuadColor): TColor; begin Result := TColor(RGB(Color.Red, Color.Blue, Color.Green)); end; procedure TCustomTransparentCanvas.Rectangle(const X1, Y1, X2, Y2: Integer; const Alpha: Byte); var TempImage : TAlphaBitmapWrapper; begin TempImage := TAlphaBitmapWrapper.CreateForGDI(FWorkingCanvas.FDCHandle, X2-X1, Y2-Y1); try TempImage.SelectObjects(TGDIObjects.CreateWithHandles(Brush.Handle, Pen.Handle, Font.Handle)); SetWindowOrgEx(TempImage.FDCHandle, X1 - Pen.Width div 2, Y1 - Pen.Width div 2, nil); Windows.Rectangle(TempImage.FDCHandle, X1, Y1, X2, Y2); SetWindowOrgEx(TempImage.FDCHandle, 0, 0, nil); TempImage.ProcessTransparency(Alpha); TempImage.BlendTo(X1, Y1, FWorkingCanvas); TempImage.SelectOriginalObjects; finally TempImage.Free; end; end; procedure TCustomTransparentCanvas.Rectangle(const Rect: TRect; const Alpha: Byte); begin Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, Alpha); end; procedure TCustomTransparentCanvas.RoundRect(const Rect: TRect; const XRadius, YRadius : Integer; const Alpha : Byte = $FF); begin RoundRect(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, XRadius, YRadius, Alpha); end; procedure TCustomTransparentCanvas.RoundRect(const X1, Y1, X2, Y2, XRadius, YRadius: Integer; const Alpha : Byte = $FF); var TempImage : TAlphaBitmapWrapper; begin TempImage := TAlphaBitmapWrapper.CreateForGDI(FWorkingCanvas.FDCHandle, X2-X1 + Pen.Width, Y2-Y1 + Pen.Width); try TempImage.SelectObjects(TGDIObjects.CreateWithHandles(Brush.Handle, Pen.Handle, Font.Handle)); SetWindowOrgEx(TempImage.FDCHandle, X1 - Pen.Width div 2, Y1 - Pen.Width div 2, nil); Windows.RoundRect(TempImage.FDCHandle, X1, Y1, X2, Y2, XRadius, YRadius); SetWindowOrgEx(TempImage.FDCHandle, 0, 0, nil); TempImage.ProcessTransparency(Alpha); TempImage.BlendTo(X1, Y1, FWorkingCanvas); TempImage.SelectOriginalObjects; finally TempImage.Free; end; end; procedure TCustomTransparentCanvas.SetBrush(NewBrush: TBrush); begin FBrush.Assign(NewBrush); end; procedure TCustomTransparentCanvas.SetFont(NewFont: TFont); begin FFont.Assign(NewFont); end; procedure TCustomTransparentCanvas.SetPen(NewPen: TPen); begin FPen.Assign(NewPen); end; procedure TCustomTransparentCanvas.SetPenPos(NewPos: TPoint); begin MoveToEx(FWorkingCanvas.FDCHandle, NewPos.X, NewPos.Y, nil); end; procedure TCustomTransparentCanvas.SetPixel(X, Y: Integer; Color: Cardinal); begin SetPixel(X, Y, Color, $FF); end; procedure TCustomTransparentCanvas.SetPixel(X, Y: Integer; Color: Cardinal; Alpha: Byte); var PQuad : PQuadColor; InverseY : Integer; begin InverseY := FWorkingCanvas.FHeight - Y - 1; // 0 is top not bottom PQuad := FWorkingCanvas.FQuads; Inc(PQuad, (InverseY * Width) + X); PQuad.Quad := Color; PQuad.Alpha := Alpha; end; procedure TCustomTransparentCanvas.SetRawPixel(X, Y: Integer; Color: TQuadColor); var PQuad : PQuadColor; InverseY : Integer; begin InverseY := FWorkingCanvas.FHeight - Y - 1; // 0 is top not bottom PQuad := FWorkingCanvas.FQuads; Inc(PQuad, (InverseY * Width) + X); PQuad.Quad := Color.Quad; end; class function TCustomTransparentCanvas.TColorToQuadColor(Color: TColor): TQuadColor; begin Result := TQuadColor.Create(Color); end; function TCustomTransparentCanvas.TextExtent(const Text: string): TSize; var OldFontHandle, FontHandle : HFONT; begin if Length(Text) = 0 then begin Result.cx := 0; Result.cy := 0; Exit; end; if CanUseDrawThemeTextEx then begin // Can use DrawThemeTextEx; just get text extent normally FWorkingCanvas.SelectObjects(TGDIObjects.CreateWithHandles(0, 0, Font.Handle)); GetTextExtentPoint32(FWorkingCanvas.FDCHandle, PChar(Text), Length(Text), Result); FWorkingCanvas.SelectOriginalObjects; end else begin // Can't use DrawThemeTextEx; use aliased font (may affect output size, so need to explicitly // measure using the aliased font) FontHandle := OrphanAliasedFont; try OldFontHandle := SelectObject(FWorkingCanvas.FDCHandle, FontHandle); GetTextExtentPoint32(FWorkingCanvas.FDCHandle, PChar(Text), Length(Text), Result); SelectObject(FWorkingCanvas.FDCHandle, OldFontHandle); finally DeleteObject(FontHandle); end; end; end; function TCustomTransparentCanvas.TextHeight(const Text: string): Integer; begin Result := TextExtent(Text).cy; end; procedure TCustomTransparentCanvas.TextOut(const X, Y: Integer; const Text: string; const Alignment : TAlignment; const Alpha : Byte); var TextSize : TSize; begin if Length(Text) = 0 then Exit; // Crash creating zero-sized bitmap TextSize := TextExtent(Text); if CanUseDrawThemeTextEx then TextOutVistaPlus(Rect(X, Y, X + TextSize.cx, Y + TextSize.cy), Text, Alignment, Alpha) else TextOutPreVista(Rect(X, Y, X + TextSize.cx, Y + TextSize.cy), Text, Alignment, Alpha); end; procedure TCustomTransparentCanvas.TextOutPreVista(const Rect: TRect; const Text: string; const Alignment : TAlignment; const Alpha: Byte); var TempImage : TAlphaBitmapWrapper; FontHandle : HFONT; TextSize : TSize; OldAlign : UINT; begin if Length(Text) = 0 then Exit; // Crash creating zero-sized bitmap TextSize := TextExtent(Text); // Clip to the rest by restricting the size it thinks the text is - the bitmap will be this size, thus clipped TextSize.cx := min(TextSize.cx, Rect.Right-Rect.Left); TextSize.cy := min(TextSize.cy, Rect.Bottom-Rect.Top); FontHandle := OrphanAliasedFont; // Antialiased or cleartype text works terribly when trying to fix the alpha TempImage := TAlphaBitmapWrapper.CreateForGDI(FWorkingCanvas.FDCHandle, TextSize.cx, TextSize.cy); try TempImage.SelectObjects(TGDIObjects.CreateWithHandles(0, 0, FontHandle)); SetBkMode(TempImage.FDCHandle, TRANSPARENT); SetTextColor(TempImage.FDCHandle, ColorToRGB(Font.Color)); OldAlign := GetTextAlign(TempImage.FDCHandle); try case Alignment of taLeftJustify: SetTextAlign(TempImage.FDCHandle, TA_LEFT); taRightJustify: SetTextAlign(TempImage.FDCHandle, TA_RIGHT); taCenter: SetTextAlign(TempImage.FDCHandle, TA_CENTER); end; ExtTextOut(TempImage.FDCHandle, 0, 0, ETO_CLIPPED, nil, PChar(Text), Length(Text), nil); finally SetTextAlign(TempImage.FDCHandle, OldAlign); end; SetBkMode(TempImage.FDCHandle, OPAQUE); TempImage.ProcessTransparency(Alpha); TempImage.BlendTo(Rect.Left, Rect.Top, FWorkingCanvas); TempImage.SelectOriginalObjects; finally DeleteObject(FontHandle); TempImage.Free; end; end; procedure TCustomTransparentCanvas.TextOutVistaPlus(const ARect: TRect; const Text: string; const Alignment : TAlignment; const Alpha: Byte); var TempImage : TAlphaBitmapWrapper; TextSize : TSize; Options : TDTTOpts; Details: TThemedElementDetails; TextRect : TRect; AlignFlags : DWORD; begin if Length(Text) = 0 then Exit; // Crash creating zero-sized bitmap if not CanUseDrawThemeTextEx then raise ETransparentCanvasException.Create('Cannot use DrawThemeTextEx'); AlignFlags := AlignmentToFlags(Alignment); TextSize := TextExtent(Text); // Clip by clipping the size of the rectangle it assumes the text fits in TextSize.cx := min(TextSize.cx, ARect.Right-ARect.Left); TextSize.cy := min(TextSize.cy, ARect.Bottom-ARect.Top); TempImage := TAlphaBitmapWrapper.CreateForDrawThemeTextEx(FWorkingCanvas.FDCHandle, TextSize.cx, TextSize.cy); try TempImage.SelectObjects(TGDIObjects.CreateWithHandles(0, 0, Font.Handle)); SetBkMode(TempImage.FDCHandle, TRANSPARENT); SetTextColor(TempImage.FDCHandle, ColorToRGB(Font.Color)); ZeroMemory(@Options, SizeOf(Options)); Options.dwSize := SizeOf(Options); Options.dwFlags := DTT_TEXTCOLOR or DTT_COMPOSITED; Options.crText := ColorToRGB(Font.Color); Options.iGlowSize := 0; Details := InternalStyleServices.GetElementDetails(teEditTextNormal); TextRect := Rect(0, 0, TextSize.cx, TextSize.cy); DrawThemeTextEx(InternalStyleServices.Theme[teEdit], TempImage.FDCHandle, Details.Part, Details.State, PChar(Text), Length(Text), AlignFlags or DT_TOP, TextRect, Options); SetBkMode(TempImage.FDCHandle, OPAQUE); TempImage.BlendTo(ARect.Left, ARect.Top, FWorkingCanvas, Alpha); TempImage.SelectOriginalObjects; finally TempImage.Free; end; end; procedure TCustomTransparentCanvas.TextRect(const Rect: TRect; const Text: string; const Alignment : TAlignment; const Alpha: Byte); begin if Length(Text) = 0 then Exit; // Crash creating zero-sized bitmap if CanUseDrawThemeTextEx then TextOutVistaPlus(Rect, Text, Alignment, Alpha) else TextOutPreVista(Rect, Text, Alignment, Alpha); end; function TCustomTransparentCanvas.TextWidth(const Text: string): Integer; begin Result := TextExtent(Text).cx; end; { TAlphaBitmapWrapper } procedure TAlphaBitmapWrapper.BlendTo(X, Y: Integer; var Image: TAlphaBitmapWrapper; Transparency: Byte); var BlendFunc : TBlendFunction; begin with BlendFunc do begin BlendOp := AC_SRC_OVER; BlendFlags := 0; SourceConstantAlpha := Transparency; // Normally 255 AlphaFormat := AC_SRC_ALPHA; end; AlphaBlend(Image.FDCHandle, X, Y, FWidth, FHeight, FDcHandle, 0, 0, FWidth, FHeight, BlendFunc); end; procedure TAlphaBitmapWrapper.BlendToDC(X, Y: Integer; DC: HDC; Transparency: Byte); var BlendFunc : TBlendFunction; begin with BlendFunc do begin BlendOp := AC_SRC_OVER; BlendFlags := 0; SourceConstantAlpha := Transparency; AlphaFormat := AC_SRC_ALPHA; end; AlphaBlend(DC, X, Y, FWidth, FHeight, FDcHandle, 0, 0, FWidth, FHeight, BlendFunc); end; procedure TAlphaBitmapWrapper.BlendToStretch(X, Y, StretchWidth, StretchHeight: Integer; var Image: TAlphaBitmapWrapper; Transparency: Byte); var BlendFunc : TBlendFunction; begin with BlendFunc do begin BlendOp := AC_SRC_OVER; BlendFlags := 0; SourceConstantAlpha := Transparency; // Normally 255 AlphaFormat := AC_SRC_ALPHA; end; AlphaBlend(Image.FDCHandle, 0, 0,StretchWidth, StretchHeight, FDcHandle, X, Y, FWidth, FHeight, BlendFunc); end; procedure TAlphaBitmapWrapper.CheckHandles; begin if FDCHandle = 0 then raise ETransparentCanvasException.Create('Cannot create device context'); if FBMPHandle = 0 then raise ETransparentCanvasException.Create('Cannot create 32-bit bitmap'); if FQuads = nil then raise ETransparentCanvasException.Create('Cannot access bitmap bits'); end; procedure TAlphaBitmapWrapper.Clear; begin ZeroMemory(FQuads, FWidth * FHeight * SizeOf(TQuadColor)); end; procedure TAlphaBitmapWrapper.Construct(DC: HDC; Empty: Boolean; Width, Height: Integer; Inverted : boolean); var BMPInfo : TBitmapInfo; PQuads : Pointer; begin FWidth := Width; FHeight := Height; if (FWidth <= 0) or (FHeight <= 0) then raise ETransparentCanvasException.Create('Invalid size specified; Width and Height must both be greater than zero.'); FDCHandle := CreateCompatibleDC(DC); ZeroMemory(@BMPInfo, SizeOf(TBitmapInfo)); with BMPInfo.bmiHeader do begin biSize := SizeOf(TBitmapInfo); biWidth := FWidth; if Inverted then begin biHeight := -FHeight // For DrawThemeTextEx: requires inverted (bottom-up) bitmap end else begin biHeight := FHeight; end; biPlanes := 1; biBitCount := 32; biCompression := BI_RGB; biSizeImage := FWidth * FHeight * SizeOf(TQuadColor); end; PQuads := nil; FBMPHandle := 0; FBMPHandle := CreateDIBSection(FDCHandle, BMPInfo, DIB_RGB_COLORS, PQuads, 0, 0); FQuads := PQuadColor(PQuads); CheckHandles; FOriginalBMP := SelectObject(FDCHandle, FBMPHandle); GdiFlush; // Need to flush before any manipulation of bits if Empty then begin ZeroMemory(FQuads, Width * Height * SizeOf(TQuadColor)); end else begin FillMemory(FQuads, Width * Height * SizeOf(TQuadColor), $FF); end; end; constructor TAlphaBitmapWrapper.Create(var ToCopy: TAlphaBitmapWrapper); begin inherited Create(); Construct(ToCopy.FDCHandle, true, ToCopy.FWidth, ToCopy.FHeight); // true = init to all zeroes ToCopy.BlendTo(0, 0, Self); end; constructor TAlphaBitmapWrapper.CreateBlank(DC: HDC; Width, Height: Integer); begin inherited Create(); Construct(DC, true, Width, Height); // true = init to all zeroes end; constructor TAlphaBitmapWrapper.CreateForDrawThemeTextEx(DC: HDC; Width, Height: Integer; DummyDrawThemeTextEx : SmallInt = 0); begin inherited Create(); Construct(DC, true, Width, Height, true); // init to all zeroes; inverted (upside down) because DrawThemeTextEx needs it end; constructor TAlphaBitmapWrapper.CreateForGDI(DC: HDC; Width, Height: Integer; DummyGDI : Byte = 0); begin inherited Create(); Construct(DC, false, Width, Height); // false = init all bytes to $FF, so can test if written to end; destructor TAlphaBitmapWrapper.Destroy; begin SelectOriginalObjects; SelectObject(FDCHandle, FOriginalBMP); DeleteObject(FBMPHandle); FBMPHandle := 0; DeleteObject(FDCHandle); FDCHandle := 0; inherited; end; procedure TAlphaBitmapWrapper.TintByAlphaToColor(const Color: TQuadColor); var Loop : Integer; PQuad : PQuadColor; begin // Change the background colour of glowing text by changing white to BackColor, and black to // TextColor. Alpha remains the same GdiFlush; // Need to flush before any manipulation of bits PQuad := FQuads; for Loop := 0 to FWidth * FHeight - 1 do begin if PQuad.Alpha <> 0 then begin PQuad.SetFromColorMultAlpha(Color); // Sets the colour, and multiplies the alphas together end; Inc(PQuad); end; end; procedure TAlphaBitmapWrapper.ProcessMaskTransparency(var MaskImage: TAlphaBitmapWrapper); var Loop : Integer; PQuad, PMaskQuad : PQuadColor; begin if not ((FWidth = MaskImage.FWidth)) and (FHeight = MaskImage.FHeight) then raise ETransparentCanvasException.Create('Mask images must be identical in size'); GdiFlush; // Need to flush before any manipulation of bits PQuad := FQuads; PMaskQuad := MaskImage.FQuads; for Loop := 0 to FWidth * FHeight - 1 do begin if (PMaskQuad.Quad and $00FFFFFF) = 0 then begin PQuad.SetAlpha(255, 1.0); end else begin PQuad.Quad := 0; end; Inc(PQuad); Inc(PmaskQuad); end; end; procedure TAlphaBitmapWrapper.ProcessTransparentColor(const TransparentColor : COLORREF; const TransparentEdgeWidth : Integer); function IsEdge(const PixelIndex : Integer) : Boolean; var X, Y : Integer; begin if TransparentEdgeWidth < 0 then Exit(true); // Entire image should be processed // index = (Y * width) + X (note Y is inverse) Y := PixelIndex div FWidth; X := PixelIndex - (Y * FWidth); Result := (X < TransparentEdgeWidth) or (Y < TransparentEdgeWidth) or (X > (FWidth - TransparentEdgeWidth - 1)) or (Y > (FHeight - TransparentEdgeWidth - 1)); end; var Loop : Integer; PQuad : PQuadColor; R, G, B : Byte; begin if TransparentEdgeWidth = 0 then Exit; // Want to process an edge, but no edge width (pass -1 for whole image) GdiFlush; // Need to flush before any manipulation of bits R := GetRValue(TransparentColor); G := GetGValue(TransparentColor); B := GetBValue(TransparentColor); PQuad := FQuads; for Loop := 0 to FWidth * FHeight - 1 do begin if (PQuad.Red = R) and (PQuad.Green = G) and (PQuad.Blue = B) and IsEdge(Loop) then begin PQuad.SetAlpha(0, 0); // 32-bit OSes must have all channels 0 (premultiplied) for 0 alpha end; Inc(PQuad); end; end; procedure TAlphaBitmapWrapper.ProcessTransparency(const Alpha: Byte; TranspRect: TRect); var LoopX : Integer; PreMult : Single; PQuad : PQuadColor; LoopY: Integer; begin GdiFlush; // Need to flush before any manipulation of bits IntersectRect(TranspRect, TranspRect, Rect(0, 0, FWidth, FHeight)); // Clip to valid bounds PreMult := Alpha / 255.0; for LoopY := TranspRect.Top to TranspRect.Bottom - 1 do begin PQuad := FQuads; Inc(PQuad, LoopY); for LoopX := TranspRect.Left to TranspRect.Right - 1 do begin if PQuad.WrittenByGDI then begin PQuad.SetAlpha(Alpha, PreMult); end else begin PQuad.Quad := 0; end; Inc(PQuad); end; end; end; procedure TAlphaBitmapWrapper.ProcessTransparency(const Alpha: Byte); var Loop : Integer; PreMult : Single; PQuad : PQuadColor; begin GdiFlush; // Need to flush before any manipulation of bits PreMult := Alpha / 255.0; PQuad := FQuads; for Loop := 0 to FWidth * FHeight - 1 do begin if PQuad.WrittenByGDI then begin PQuad.SetAlpha(Alpha, PreMult); end else begin PQuad.Quad := 0; end; Inc(PQuad); end; end; function TAlphaBitmapWrapper.QuadPointer: PQuadColor; begin Result := FQuads; end; function TAlphaBitmapWrapper.GetRawPixelPtr(const X, Y: Integer): PQuadColor; var PQuad : PQuadColor; InverseY : Integer; begin if (X >= 0) and (X < FWidth) and (Y >= 0) and (Y < FHeight) then begin InverseY := FHeight - Y - 1; // 0 is top not bottom PQuad := FQuads; Inc(PQuad, (InverseY * FWidth) + X); Result := PQuad; end else begin Result := nil; end; end; procedure TAlphaBitmapWrapper.SafeSetRawPixel(const X, Y: Integer; Color: TQuadColor); var PQuad : PQuadColor; InverseY : Integer; begin if (X >= 0) and (X < FWidth) and (Y >= 0) and (Y < FHeight) then begin InverseY := FHeight - Y - 1; // 0 is top not bottom PQuad := FQuads; Inc(PQuad, (InverseY * FWidth) + X); PQuad.Quad := Color.Quad; end; end; procedure TAlphaBitmapWrapper.SelectObjects(const GDI: TGDIObjects); begin // This is only one layer deep - it stores the old objects in FOriginalObjects // If you call if more than once, it will overwrite the values in FOriginalObjects // If you find yourself doing this, this needs to be rewritten as a stack, and you'd // push and pop the handles. if (FOriginalObjects.FBrush <> 0) or (FOriginalObjects.FPen <> 0) or (FOriginalObjects.FFont <> 0) then raise ETransparentCanvasException.Create('SelectObjects has already been called'); FOriginalObjects.FBrush := SelectObject(FDCHandle, GDI.Brush); FOriginalObjects.FPen := SelectObject(FDCHandle, GDI.Pen); FOriginalObjects.FFont := SelectObject(FDCHandle, GDI.Font); end; procedure TAlphaBitmapWrapper.SelectOriginalObjects; begin SelectObject(FDCHandle, FOriginalObjects.FBrush); FOriginalObjects.FBrush := 0; SelectObject(FDCHandle, FOriginalObjects.FPen); FOriginalObjects.FPen := 0; SelectObject(FDCHandle, FOriginalObjects.FFont); FOriginalObjects.FFont := 0; end; procedure TAlphaBitmapWrapper.SetAllTransparency(const Alpha: Byte); var Loop : Integer; PreMult : Single; PQuad : PQuadColor; begin GdiFlush; // Need to flush before any manipulation of bits PreMult := Alpha / 255.0; PQuad := FQuads; for Loop := 0 to FWidth * FHeight - 1 do begin PQuad.SetAlpha(Alpha, PreMult); Inc(PQuad); end; end; { TQuadColor } function TQuadColor.AsColorRef: COLORREF; var PreDiv : Single; begin // contains premultiplied alpha, so un-premultiply it and return that if Alpha = 0 then begin Result := $00000000; end else begin PreDiv := 1 / (Alpha / 255.0); Result := RGB(Trunc(Red * PreDiv), Trunc(Green * PreDiv), Trunc(Blue * PreDiv)) or (Alpha shl 24); end; end; procedure TQuadColor.Clear; begin Quad := 0; end; constructor TQuadColor.Create(Color: TColor); var ColorRGB : COLORREF; begin Alpha := 255; ColorRGB := ColorToRGB(Color); Red := GetRValue(ColorRGB); Green := GetGValue(ColorRGB); Blue := GetBValue(ColorRGB); end; procedure TQuadColor.SetAlpha(const Transparency: Byte; const PreMult: Single); begin Alpha := Transparency; Blue := Trunc(Blue * PreMult); Green := Trunc(Green * PreMult); Red := Trunc(Red * PreMult); end; procedure TQuadColor.SetFromColorRef(const Color: COLORREF); begin // Sets the colour, but keeps the current alpha if Alpha = 0 then begin Quad := 0; end else begin Red := GetRValue(Color); Green := GetGValue(Color); Blue := GetBValue(Color); SetAlpha(Alpha, Alpha / 255.0); end; end; procedure TQuadColor.SetFromColorMultAlpha(const Color: TQuadColor); var MultAlpha : Byte; begin Red := Color.Red; Green := Color.Green; Blue := Color.Blue; MultAlpha := Round(Integer(Alpha) * Integer(Color.Alpha) / 255.0); SetAlpha(MultAlpha, MultAlpha / 255.0); end; function TQuadColor.WrittenByGDI: Boolean; begin Result := (Alpha = 0); end; { TTransparentControlCanvas } constructor TTransparentControlCanvas.Create(Control: TWinControl); begin if Control = nil then raise ETransparentCanvasException.Create('Control must not be nil'); if Control.Handle = 0 then raise ETransparentCanvasException.Create('Cannot access control handle'); FControl := Control; FControlDC := GetWindowDC(Control.Handle); if FControlDC = 0 then raise ETransparentCanvasException.Create('Cannot obtain control device context'); inherited Create(FControlDC, Control.Width, Control.Height); end; destructor TTransparentControlCanvas.Destroy; begin DrawTo(0, 0, FControlDC, FControl.Width, FControl.Height); ReleaseDC(FControl.Handle, FControlDC); FControlDC := 0; FWorkingCanvas.FDCHandle := 0; inherited; end; { TGDIObjects } constructor TGDIObjects.CreateWithHandles(const hBrush: HBRUSH; const hPen: HPEN; const hFont : HFONT); begin FBrush := hBrush; FPen := hPen; FFont := hFont; end; end.
unit MobileMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.Edit, FMX.ListBox, FMX.StdCtrls, FMX.TabControl, System.Actions, FMX.ActnList; type TfrmMobileMain = class(TForm) tabctrlMain: TTabControl; tabitmAccount: TTabItem; tabItmEmployee: TTabItem; ToolBar1: TToolBar; Label1: TLabel; btnLogout: TButton; ToolBar2: TToolBar; tabctrlLogin: TTabControl; tabitmAccountLogin: TTabItem; tabitmAccountRegister: TTabItem; ListBox1: TListBox; Label2: TLabel; btnLoginBack: TButton; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; ListBoxItem3: TListBoxItem; ListBoxItem4: TListBoxItem; edtLoginUsername: TEdit; edtLoginPassword: TEdit; ListBox2: TListBox; ListBoxItem5: TListBoxItem; edtRegisterUsername: TEdit; ListBoxItem6: TListBoxItem; edtRegisterPassword: TEdit; ListBoxItem7: TListBoxItem; ListBoxItem8: TListBoxItem; edtRegisterFullname: TEdit; edtRegisterEmail: TEdit; ListBoxItem9: TListBoxItem; btnRegisterExec: TButton; FlowLayout1: TFlowLayout; btnLoginGotoRegister: TButton; edtLoginExec: TButton; lblLoginForgotPassword: TLabel; ActionList1: TActionList; ChangeTabAction: TChangeTabAction; procedure FormCreate(Sender: TObject); procedure tabctrlLoginChange(Sender: TObject); procedure btnLoginGotoRegisterClick(Sender: TObject); procedure edtLoginExecClick(Sender: TObject); procedure btnLogoutClick(Sender: TObject); procedure btnLoginBackClick(Sender: TObject); procedure btnRegisterExecClick(Sender: TObject); procedure lblLoginForgotPasswordClick(Sender: TObject); private { Private declarations } procedure GotoAccountTab; procedure GotoEmployeeTab; procedure GotoLoginTab; procedure GotoRegisterTab; public { Public declarations } end; var frmMobileMain: TfrmMobileMain; implementation {$R *.fmx} //uses kinveyDataModule; procedure TfrmMobileMain.btnLoginBackClick(Sender: TObject); begin GotoLoginTab; end; procedure TfrmMobileMain.btnLoginGotoRegisterClick(Sender: TObject); begin GotoRegisterTab; end; procedure TfrmMobileMain.btnRegisterExecClick(Sender: TObject); begin // dmBaaSUser.SignUp( // edtRegisterUsername.Text, edtRegisterPassword.Text, // edtRegisterFullname.Text, edtRegisterEmail.Text); GotoEmployeeTab; edtRegisterUsername.Text := ''; edtRegisterPassword.Text := ''; edtRegisterFullname.Text := ''; edtRegisterEmail.Text := ''; end; procedure TfrmMobileMain.btnLogoutClick(Sender: TObject); begin // dmBaaSUser.Logout; GotoAccountTab; end; procedure TfrmMobileMain.edtLoginExecClick(Sender: TObject); begin // if not dmBaaSUser.Login(edtLoginUsername.Text, edtLoginPassword.Text) then // begin // ShowMessage('아이디 또는 비밀번호가 맞지 않습니다.'); // Exit; // End; GotoEmployeeTab; edtLoginUsername.Text := ''; edtLoginPassword.Text := ''; end; procedure TfrmMobileMain.FormCreate(Sender: TObject); begin // 메인 탭컨트롤 초기화 설정 tabctrlMain.ActiveTab := tabitmAccount; tabItmEmployee.Enabled := False; // 로그인탭의 탭컨트롤 초기화 설정 tabctrlLogin.TabPosition := TTabPosition.None; tabctrlLogin.ActiveTab := tabitmAccountLogin; btnLoginBack.Visible := False; end; procedure TfrmMobileMain.GotoAccountTab; begin ChangeTabAction.Tab := tabitmAccount; ChangeTabAction.ExecuteTarget(nil); tabitmAccount.Enabled := True; tabItmEmployee.Enabled := False; end; procedure TfrmMobileMain.GotoEmployeeTab; begin ChangeTabAction.Tab := tabItmEmployee; ChangeTabAction.ExecuteTarget(nil); tabitmAccount.Enabled := False; tabItmEmployee.Enabled := True; end; procedure TfrmMobileMain.GotoLoginTab; begin ChangeTabAction.Tab := tabitmAccountLogin; ChangeTabAction.ExecuteTarget(nil); end; procedure TfrmMobileMain.GotoRegisterTab; begin ChangeTabAction.Tab := tabitmAccountRegister; ChangeTabAction.ExecuteTarget(nil); end; procedure TfrmMobileMain.lblLoginForgotPasswordClick(Sender: TObject); begin if edtLoginUsername.Text = '' then begin ShowMessage('Username 항목을 입력해 주세요.'); Exit; end; // dmBaaSUser.ResetPassword(edtLoginUserName.Text); ShowMessage('비밀번호 초기화 요청했습니다. 회원가입 시 등록한 이메일을 확인해 주세요.'); end; procedure TfrmMobileMain.tabctrlLoginChange(Sender: TObject); begin btnLoginBack.Visible := (tabctrlLogin.ActiveTab = tabitmAccountRegister); end; end.
{*********************************************************} {* VPTASKLIST.PAS 1.03 *} {*********************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* Version: MPL 1.1 *} {* *} {* The contents of this file are subject to the Mozilla Public License *} {* Version 1.1 (the "License"); you may not use this file except in *} {* compliance with the License. You may obtain a copy of the License at *} {* http://www.mozilla.org/MPL/ *} {* *} {* Software distributed under the License is distributed on an "AS IS" basis, *} {* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *} {* for the specific language governing rights and limitations under the *} {* License. *} {* *} {* The Original Code is TurboPower Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* *} {* ***** END LICENSE BLOCK ***** *} {$I Vp.INC} unit VpTaskList; interface uses {$IFDEF LCL} LMessages,LCLProc,LCLType,LCLIntf, {$ELSE} Windows,Messages, {$ENDIF} Classes, Graphics, Controls, ComCtrls, ExtCtrls, StdCtrls, VpBase, VpBaseDS, VpMisc, VpData, VpSR, VpConst, VpCanvasUtils, Menus; type TVpTaskRec = packed record Task : Pointer; LineRect : TRect; CheckRect: TRect; end; type TVpTaskArray = array of TVpTaskRec; { forward declarations } TVpTaskList = class; TVpTaskDisplayOptions = class(TPersistent) protected{private} FTaskList : TVpTaskList; FShowAll : Boolean; FShowCompleted : Boolean; FShowDueDate : Boolean; FDueDateFormat : string; FCheckColor : TColor; FCheckBGColor : TColor; FCheckStyle : TVpCheckStyle; FOverdueColor : TColor; FNormalColor : TColor; FCompletedColor : TColor; procedure SetCheckColor(Value: TColor); procedure SetCheckBGColor(Value: TColor); procedure SetCheckStyle(Value: TVpCheckStyle); procedure SetDueDateFormat(Value: string); procedure SetShowCompleted(Value: Boolean); procedure SetShowDueDate(Value: Boolean); procedure SetShowAll(Value: Boolean); procedure SetOverdueColor(Value: TColor); procedure SetNormalColor(Value: TColor); procedure SetCompletedColor(Value: TColor); public constructor Create(Owner : TVpTaskList); destructor Destroy; override; published property CheckBGColor: TColor read FCheckBGColor write SetCheckBGColor; property CheckColor: TColor read FCheckColor write SetCheckColor; property CheckStyle: TVpCheckStyle read FCheckStyle write SetCheckStyle; property DueDateFormat: string read FDueDateFormat write SetDueDateFormat; property ShowCompletedTasks : Boolean read FShowCompleted write SetShowCompleted; property ShowAll : Boolean read FShowAll write SetShowAll; property ShowDueDate: Boolean read FShowDueDate write SetShowDueDate; property OverdueColor : TColor read FOverdueColor write SetOverdueColor; property NormalColor : TColor read FNormalColor write SetNormalColor; property CompletedColor : TColor read FCompletedColor write SetCompletedColor; end; { InPlace Editor } TVpTLInPlaceEdit = class(TCustomEdit) protected{private} procedure CreateParams(var Params: TCreateParams); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; public constructor Create(AOwner: TComponent); override; procedure Move(const Loc: TRect; Redraw: Boolean); end; TVpTaskHeadAttr = class(TVpPersistent) protected{private} FTaskList: TVpTaskList; FFont: TFont; FColor: TColor; procedure SetColor (Value: TColor); procedure SetFont (Value: TFont); public constructor Create(AOwner: TVpTaskList); destructor Destroy; override; procedure Invalidate; override; { The Invalidate method is used as a bridge between FFont & FTaskList. } property TaskList: TVpTaskList read FTaskList; published property Color: TColor read FColor write SetColor; property Font: TFont read FFont write SetFont; end; { Task List } TVpTaskList = class(TVpLinkableControl) protected{ private } FColor : TColor; FCaption : string; FDisplayOptions : TVpTaskDisplayOptions; FLineColor : TColor; FActiveTask : TVpTask; FShowResourceName : Boolean; FTaskIndex : Integer; FScrollBars : TScrollStyle; FTaskHeadAttr : TVpTaskHeadAttr; FMaxVisibleTasks : Word; FDrawingStyle : TVpDrawingStyle; FTaskID : Integer; FDefaultPopup : TPopupMenu; FShowIcon : Boolean; { task variables } FOwnerDrawTask : TVpOwnerDrawTask; FBeforeEdit : TVpBeforeEditTask; FAfterEdit : TVpAfterEditTask; FOwnerEditTask : TVpEditTask; { internal variables } tlVisibleTaskArray : TVpTaskArray; tlAllTaskList : TList; tlItemsBefore : Integer; tlItemsAfter : Integer; tlVisibleItems : Integer; tlHitPoint : TPoint; tlClickTimer : TTimer; tlLoaded : Boolean; tlRowHeight : Integer; tlInPlaceEditor : TVpTLInPlaceEdit; tlCreatingEditor : Boolean; tlPainting : Boolean; tlVScrollDelta : Integer; tlHotPoint : TPoint; { property methods } function GetTaskIndex: Integer; procedure SetLineColor(Value: TColor); procedure SetMaxVisibleTasks(Value: Word); procedure SetTaskIndex(Value: Integer); procedure SetDrawingStyle(const Value: TVpDrawingStyle); procedure SetColor(const Value: TColor); procedure SetShowIcon (const v : Boolean); procedure SetShowResourceName(Value: Boolean); { internal methods } procedure InitializeDefaultPopup; procedure PopupAddTask (Sender : TObject); procedure PopupDeleteTask (Sender : TObject); procedure PopupEditTask (Sender : TObject); procedure tlSetVScrollPos; procedure tlCalcRowHeight; procedure tlEditInPlace(Sender: TObject); procedure tlHookUp; procedure Paint; override; procedure Loaded; override; procedure tlSpawnTaskEditDialog(NewTask: Boolean); procedure tlSetActiveTaskByCoord(Pnt: TPoint); function tlVisibleTaskToTaskIndex (const VisTaskIndex : Integer) : Integer; function tlTaskIndexToVisibleTask (const ATaskIndex : Integer) : Integer; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; {$IFNDEF LCL} procedure WMLButtonDown(var Msg : TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMLButtonDblClk(var Msg : TWMLButtonDblClk); message WM_LBUTTONDBLCLK; procedure WMRButtonDown (var Msg : TWMRButtonDown); message WM_RBUTTONDOWN; {$ELSE} procedure WMLButtonDown(var Msg : TLMLButtonDown); message LM_LBUTTONDOWN; procedure WMLButtonDblClk(var Msg : TLMLButtonDblClk); message LM_LBUTTONDBLCLK; procedure WMRButtonDown (var Msg : TLMRButtonDown); message LM_RBUTTONDOWN; {$ENDIF} procedure EditTask; procedure EndEdit(Sender: TObject); procedure KeyDown(var Key: Word; Shift: TShiftState); override; { message handlers } {$IFNDEF LCL} procedure WMSize(var Msg: TWMSize); message WM_SIZE; procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL; procedure CMWantSpecialKey(var Msg: TCMWantSpecialKey); message CM_WANTSPECIALKEY; {$ELSE} procedure WMSize(var Msg: TLMSize); message LM_SIZE; procedure WMVScroll(var Msg: TLMVScroll); message LM_VSCROLL; {$ENDIF} public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DeleteActiveTask(Verify: Boolean); procedure LinkHandler(Sender: TComponent; NotificationType: TVpNotificationType; const Value: Variant); override; function GetControlType : TVpItemType; override; procedure PaintToCanvas (ACanvas : TCanvas; ARect : TRect; Angle : TVpRotationAngle); procedure RenderToCanvas (RenderCanvas : TCanvas; RenderIn : TRect; Angle : TVpRotationAngle; Scale : Extended; RenderDate : TDateTime; StartLine : Integer; StopLine : Integer; UseGran : TVpGranularity; DisplayOnly : Boolean); override; property ActiveTask: TVpTask read FActiveTask; property TaskIndex: Integer read GetTaskIndex write SetTaskIndex; published {inherited properties} property Align; property Anchors; property Font; property TabStop; property TabOrder; property ReadOnly; property DisplayOptions: TVpTaskDisplayOptions read FDisplayOptions write FDisplayOptions; property LineColor: TColor read FLineColor write SetLineColor; property MaxVisibleTasks: Word read FMaxVisibleTasks write SetMaxVisibleTasks; property TaskHeadAttributes: TVpTaskHeadAttr read FTaskHeadAttr write FTaskHeadAttr; property DrawingStyle: TVpDrawingStyle read FDrawingStyle write SetDrawingStyle; property Color: TColor read FColor write SetColor; property ShowIcon : Boolean read FShowIcon write SetShowIcon default True; property ShowResourceName: Boolean read FShowResourceName write SetShowResourceName; { events } property BeforeEdit: TVpBeforeEditTask read FBeforeEdit write FBeforeEdit; property AfterEdit : TVpAfterEditTask read FAfterEdit write FAfterEdit; property OnOwnerEditTask: TVpEditTask read FOwnerEditTask write FOwnerEditTask; end; implementation uses SysUtils, Math, Forms, Dialogs, VpTaskEditDlg, VpDlg; (*****************************************************************************) { TVpTaskDisplayOptions } constructor TVpTaskDisplayOptions.Create(Owner: TVpTaskList); begin inherited Create; FTaskList := Owner; FDueDateFormat := ShortDateFormat; FShowDueDate := true; FCheckColor := cl3DDkShadow; FCheckBGColor := clWindow; FCheckStyle := csCheck; FOverdueColor := clRed; FCompletedColor := clGray; FNormalColor := clBlack; end; {=====} destructor TVpTaskDisplayOptions.Destroy; begin inherited; end; {=====} procedure TVpTaskDisplayOptions.SetOverdueColor(Value : TColor); begin if FOverdueColor <> Value then begin FOverdueColor := Value; FTaskList.Invalidate; end; end; {=====} procedure TVpTaskDisplayOptions.SetNormalColor(Value: TColor); begin if FNormalColor <> Value then begin FNormalColor := Value; FTaskList.Invalidate; end; end; {=====} procedure TVpTaskDisplayOptions.SetCompletedColor(Value: TColor); begin if FCompletedColor <> Value then begin FCompletedColor := Value; FTaskList.Invalidate; end; end; {=====} procedure TVpTaskDisplayOptions.SetCheckColor(Value: TColor); begin if FCheckColor <> Value then begin FCheckColor := Value; FTaskList.Invalidate; end; end; {=====} procedure TVpTaskDisplayOptions.SetCheckBGColor(Value: TColor); begin if FCheckBGColor <> Value then begin FCheckBGColor := Value; FTaskList.Invalidate; end; end; {=====} procedure TVpTaskDisplayOptions.SetCheckStyle(Value: TVpCheckStyle); begin if Value <> FCheckStyle then begin FCheckStyle := Value; FTaskList.Invalidate; end; end; {=====} procedure TVpTaskDisplayOptions.SetDueDateFormat(Value: string); begin if FDueDateFormat <> Value then begin FDueDateFormat := Value; FTaskList.Invalidate; end; end; {=====} procedure TVpTaskDisplayOptions.SetShowCompleted(Value : Boolean); begin if FShowCompleted <> Value then begin FShowCompleted := Value; FTaskList.Invalidate; end; end; {=====} procedure TVpTaskDisplayOptions.SetShowDueDate(Value: Boolean); begin if FShowDueDate <> Value then begin FShowDueDate := Value; FTaskList.Invalidate; end; end; {=====} procedure TVpTaskDisplayOptions.SetShowAll(Value: Boolean); begin if FShowAll <> Value then begin FShowAll := Value; FTaskList.Invalidate; end; end; {=====} { TVpTaskHeadAttr } constructor TVpTaskHeadAttr.Create(AOwner: TVpTaskList); begin inherited Create; FTaskList := AOwner; FFont := TVpFont.Create(self); FFont.Assign(FTaskList.Font); FColor := clSilver; end; {=====} destructor TVpTaskHeadAttr.Destroy; begin FFont.Free; end; {=====} procedure TVpTaskHeadAttr.Invalidate; begin if Assigned(FTaskList) then FTaskList.Invalidate; end; {=====} procedure TVpTaskHeadAttr.SetColor(Value: TColor); begin if Value <> FColor then begin FColor := Value; TaskList.Invalidate; end; end; {=====} procedure TVpTaskHeadAttr.SetFont(Value: TFont); begin if Value <> FFont then begin FFont.Assign(Value); TaskList.Invalidate; end; end; {=====} { TVpCGInPlaceEdit } constructor TVpTLInPlaceEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); TabStop := False; BorderStyle := bsNone; {$IFDEF VERSION4} DoubleBuffered := False; {$ENDIF} end; {=====} procedure TVpTLInPlaceEdit.Move(const Loc: TRect; Redraw: Boolean); begin CreateHandle; Redraw := Redraw or not IsWindowVisible(Handle); Invalidate; with Loc do SetWindowPos(Handle, HWND_TOP, Left, Top, Right - Left, Bottom - Top, {SWP_SHOWWINDOW or} SWP_NOREDRAW); if Redraw then Invalidate; SetFocus; end; {=====} procedure TVpTLInPlaceEdit.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style{ or ES_MULTILINE}; end; {=====} procedure TVpTLInPlaceEdit.KeyDown(var Key: Word; Shift: TShiftState); var TaskList : TVpTaskList; begin TaskList := TVpTaskList(Owner); case Key of VK_RETURN: begin Key := 0; TaskList.EndEdit(Self); end; VK_UP: begin Key := 0; TaskList.TaskIndex := TaskList.TaskIndex - 1; end; VK_DOWN: begin Key := 0; TaskList.TaskIndex := TaskList.TaskIndex + 1; end; VK_ESCAPE: begin Key := 0; TaskList.EndEdit(Self); end; else inherited; end; end; {=====} (*****************************************************************************) { TVpTaskList } constructor TVpTaskList.Create(AOwner: TComponent); begin inherited; ControlStyle := [csCaptureMouse, csOpaque, csDoubleClicks]; { Create internal classes and stuff } tlClickTimer := TTimer.Create(self); FTaskHeadAttr := TVpTaskHeadAttr.Create(Self); FDisplayOptions := TVpTaskDisplayOptions.Create(self); tlAllTaskList := TList.Create; { Set styles and initialize internal variables } {$IFDEF VERSION4} DoubleBuffered := true; {$ENDIF} tlItemsBefore := 0; tlItemsAfter := 0; tlVisibleItems := 0; tlClickTimer.Enabled := false; FMaxVisibleTasks := 250; tlClickTimer.Interval := ClickDelay; tlClickTimer.OnTimer := tlEditInPlace; tlCreatingEditor := false; FDrawingStyle := ds3d; tlPainting := false; FShowResourceName := true; FColor := clWindow; FLineColor := clGray; FScrollBars := ssVertical; FTaskIndex := -1; FShowIcon := True; SetLength(tlVisibleTaskArray, MaxVisibleTasks); { size } Height := 225; Width := 169; FDefaultPopup := TPopupMenu.Create (Self); InitializeDefaultPopup; tlHookUp; end; {=====} destructor TVpTaskList.Destroy; begin tlClickTimer.Free; FDisplayOptions.Free; tlAllTaskList.Free; FTaskHeadAttr.Free; FDefaultPopup.Free; inherited; end; {=====} procedure TVpTaskList.DeleteActiveTask(Verify: Boolean); var Str: string; DoIt: Boolean; begin DoIt := not Verify; if FActiveTask <> nil then begin Str := FActiveTask.Description; if Verify then DoIt := (MessageDlg(RSDelete + ' ' + Str + ' ' + RSFromTaskList + #13#10#10 + RSPermanent, mtconfirmation, [mbYes, mbNo], 0) = mrYes); if DoIt then begin FActiveTask.Deleted := true; if Assigned (DataStore) then if Assigned (DataStore.Resource) then DataStore.Resource.TasksDirty := True; DataStore.PostTasks; DataStore.RefreshTasks; Invalidate; end; end; end; {=====} procedure TVpTaskList.LinkHandler(Sender: TComponent; NotificationType: TVpNotificationType; const Value: Variant); begin case NotificationType of neDataStoreChange: Invalidate; neInvalidate: Invalidate; end; end; {=====} procedure TVpTaskList.tlHookUp; var I: Integer; begin { If the component is being dropped on a form at designtime, then } { automatically hook up to the first datastore component found } if csDesigning in ComponentState then for I := 0 to pred(Owner.ComponentCount) do begin if (Owner.Components[I] is TVpCustomDataStore) then begin DataStore := TVpCustomDataStore(Owner.Components[I]); Exit; end; end; end; {=====} procedure TVpTaskList.Loaded; begin inherited; tlLoaded := true; end; {=====} function TVpTaskList.GetControlType : TVpItemType; begin Result := itTasks; end; {=====} procedure TVpTaskList.Paint; begin { paint simply calls RenderToCanvas and passes in the screen canvas. } RenderToCanvas (Canvas, {Screen Canvas} Rect (0, 0, Width, Height), { Clipping Rectangle } ra0, { Rotation Angle } 1, { Scale } Now, { Render Date } tlItemsBefore, { Starting Line } -1, { Stop Line } gr30Min, { Granularity - Not used int the task list } False); { Display Only - True for a printed version, } { False for an interactive version } end; {=====} procedure TVpTaskList.PaintToCanvas (ACanvas : TCanvas; ARect : TRect; Angle : TVpRotationAngle); begin RenderToCanvas (ACanvas, ARect, Angle, 1, Now, -1, -1, gr30Min, True); end; {=====} procedure TVpTaskList.RenderToCanvas (RenderCanvas : TCanvas; RenderIn : TRect; Angle : TVpRotationAngle; Scale : Extended; RenderDate : TDateTime; StartLine : Integer; StopLine : Integer; UseGran : TVpGranularity; DisplayOnly : Boolean); var HeadRect : TRect; Bmp : Graphics.TBitmap; SaveBrushColor : TColor; SavePenStyle : TPenStyle; SavePenColor : TColor; RowHeight : Integer; RealWidth : Integer; RealHeight : Integer; RealLeft : Integer; RealRight : Integer; RealTop : Integer; RealBottom : Integer; Rgn : HRGN; RealColor : TColor; BackgroundSelHighlight : TColor; ForegroundSelHighlight : TColor; BevelShadow : TColor; BevelHighlight : TColor; BevelDarkShadow : TColor; BevelFace : TColor; RealLineColor : TColor; RealCheckBgColor : TColor; RealCheckBoxColor : TColor; RealCheckColor : TColor; RealCompleteColor : TColor; RealOverdueColor : TColor; RealNormalColor : TColor; TaskHeadAttrColor : TColor; procedure DrawLines; var LinePos: Integer; begin RenderCanvas.Pen.Color := RealLineColor; RenderCanvas.Pen.Style := psSolid; LinePos := HeadRect.Bottom + RowHeight; while LinePos < RealBottom do begin TPSMoveTo (RenderCanvas, Angle, RenderIn, RealLeft, LinePos); TPSLineTo (RenderCanvas, Angle, RenderIn, RealRight - 2, LinePos); Inc (LinePos, RowHeight); end; end; {-} procedure Clear; var I: Integer; begin RenderCanvas.Brush.Color := RealColor; RenderCanvas.FillRect (RenderIn); { Clear the LineRect } for I := 0 to pred(Length(tlVisibleTaskArray)) do begin tlVisibleTaskArray[I].Task := nil; tlVisibleTaskArray[I].LineRect := Rect(0, 0, 0, 0); end; end; {-} procedure SetMeasurements; begin RealWidth := TPSViewportWidth (Angle, RenderIn); RealHeight := TPSViewportHeight (Angle, RenderIn); RealLeft := TPSViewportLeft (Angle, RenderIn); RealRight := TPSViewportRight (Angle, RenderIn); RealTop := TPSViewportTop (Angle, RenderIn); RealBottom := TPSViewportBottom (Angle, RenderIn); end; procedure MeasureRowHeight; begin RenderCanvas.Font.Assign(Font); RowHeight := RenderCanvas.TextHeight(VpProductName) + TextMargin * 2; end; {-} function DrawCheck (Rec : TRect; Checked : Boolean) : TRect; { draws the check box and returns it's rectangle } var CR: TRect; { checbox rectangle } W: Integer; { width of the checkbox } X, Y: Integer; { Coordinates } begin X := Rec.Left + TextMargin; Y := Rec.Top + TextMargin; W := RowHeight - TextMargin * 2; { draw check box } RenderCanvas.Pen.Color := RGB (192, 204, 216); RenderCanvas.Brush.Color := RealCheckBgColor; TPSRectangle (RenderCanvas, Angle, RenderIn, Rect (X, Y, X + W, Y + W)); RenderCanvas.Pen.Color := RGB (80, 100, 128); TPSPolyLine (RenderCanvas, Angle, RenderIn, [Point(X, Y + W - 2), Point(X, Y), Point(X + W - 1, Y)]); RenderCanvas.Pen.Color := RealCheckBoxColor; TPSPolyLine (RenderCanvas, Angle, RenderIn, [Point(X + 1, Y + W - 3), Point(X + 1, Y + 1), Point(X + W - 2, Y + 1)]); RenderCanvas.Pen.Color := RGB(128,152,176); TPSPolyLine (RenderCanvas, Angle, RenderIn, [Point(X + 1, Y + W - 2), Point(X + W - 2, Y + W - 2), Point(X+W-2, Y)]); { build check rect } CR := Rect(X + 3, Y + 3, X + W - 3, Y + W - 3); if Checked then begin RenderCanvas.Pen.Color := RealCheckColor; case FDisplayOptions.CheckStyle of csX : {X} begin with RenderCanvas do begin TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Top); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Bottom); TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Top+1); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right-1, CR.Bottom); TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left+1, CR.Top); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Bottom-1); TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Bottom-1); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Top-1); TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Bottom-2); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right-1, CR.Top-1); TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left+1, CR.Bottom-1); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Top); end; end; csCheck : {check} begin with RenderCanvas do begin TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Bottom - ((CR.Bottom - cr.Top) div 4)); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Left + ((CR.Right - CR.Left) div 4), CR.Bottom); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Top + 2); TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Bottom - ((CR.Bottom - cr.Top) div 4) - 1); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Left + ((CR.Right - CR.Left) div 4), CR.Bottom - 1); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Top + 1); TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Bottom - ((CR.Bottom - cr.Top) div 4) - 2); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Left + ((CR.Right - CR.Left) div 4), CR.Bottom - 2); TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Top); {TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Bottom-5); } {TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Left+3, CR.Bottom-2); } {TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Bottom-4); } {TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Left+3, CR.Bottom-1); } {TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left, CR.Bottom-3); } {TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Left+3, CR.Bottom); } {TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left+2, CR.Bottom-3); } {TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Top-1); } {TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left+2, CR.Bottom-2); } {TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Top); } {TPSMoveTo (RenderCanvas, Angle, RenderIn, CR.Left+2, CR.Bottom-1); } {TPSLineTo (RenderCanvas, Angle, RenderIn, CR.Right, CR.Top+1); } end; end; end; end; {if checked} result := cr; end; procedure DrawTasks; var I : Integer; Task : TVpTask; LineRect : TRect; CheckRect : TRect; DisplayStr : string; begin if (DataStore = nil) or (DataStore.Resource = nil) or (DataStore.Resource.Tasks.Count = 0) then begin if Focused then begin LineRect.TopLeft := Point (RealLeft + 2, HeadRect.Bottom); LineRect.BottomRight := Point (LineRect.Left + RealWidth - 4, LineRect.Top + RowHeight); RenderCanvas.Brush.Color := BackgroundSelHighlight; RenderCanvas.FillRect(LineRect); RenderCanvas.Brush.Color := RealColor; end; Exit; end; LineRect.TopLeft := Point (RealLeft + 2, HeadRect.Bottom); LineRect.BottomRight := Point (LineRect.Left + RealWidth - 4, LineRect.Top + RowHeight); tlVisibleItems := 0; RenderCanvas.Brush.Color := RealColor; tlAllTaskList.Clear; { Make sure the tasks are properly sorted } DataStore.Resource.Tasks.Sort; for I := 0 to pred(DataStore.Resource.Tasks.Count) do begin if DisplayOptions.ShowAll then { Get all tasks regardless of their status and due date } tlAllTaskList.Add(DataStore.Resource.Tasks.GetTask(I)) else begin { get all tasks which are incomplete, or were just completed today.} Task := DataStore.Resource.Tasks.GetTask(I); if not Task.Complete then tlAllTaskList.Add(Task) else if FDisplayOptions.ShowCompletedTasks and (trunc(Task.CompletedOn) = trunc(now)) then tlAllTaskList.Add(Task); end; end; for I := StartLine to pred(tlAllTaskList.Count) do begin Task := tlAllTaskList[I]; if (LineRect.Top + Trunc(RowHeight * 0.5) <= RealBottom) then begin { if this is the selected task and we are not in edit mode, } { then set background selection } if (Task = FActiveTask) and (tlInPlaceEditor = nil) and (not DisplayOnly) and Focused then begin RenderCanvas.Brush.Color := BackgroundSelHighlight; RenderCanvas.FillRect(LineRect); RenderCanvas.Brush.Color := RealColor; end; { draw the checkbox } CheckRect := DrawCheck (LineRect, Task.Complete); if Task.Complete then begin { complete task } RenderCanvas.Font.Style := RenderCanvas.Font.Style + [fsStrikeout]; RenderCanvas.Font.Color := RealCompleteColor; end else begin { incomplete task } RenderCanvas.Font.Style := RenderCanvas.Font.Style - [fsStrikeout]; if (Trunc (Task.DueDate) < Trunc (Now)) and (Trunc (Task.DueDate) <> 0) then { overdue task } RenderCanvas.Font.Color := RealOverdueColor else RenderCanvas.Font.Color := RealNormalColor; end; { if this is the selected task, set highlight text color } if (Task = FActiveTask) and (tlInPlaceEditor = nil) and (not DisplayOnly) and Focused then RenderCanvas.Font.Color := ForegroundSelHighlight; { build display string } DisplayStr := ''; if (FDisplayOptions.ShowDueDate) and (Trunc (Task.DueDate) <> 0) then DisplayStr := FormatDateTime(FDisplayOptions.DueDateFormat, Task.DueDate) + ' - '; DisplayStr := DisplayStr + Task.description; { Adjust display string - If the string is too long for the available } { space, Chop the end off and replace it with an ellipses. } DisplayStr := GetDisplayString(RenderCanvas, DisplayStr, 3, LineRect.Right - LineRect.Left - CheckRect.Right - TextMargin); { paint the text } TPSTextOut(RenderCanvas, Angle, RenderIn, CheckRect.Right + TextMargin * 2, LineRect.Top + TextMargin, DisplayStr); { store the tasks drawing details } tlVisibleTaskArray[tlVisibleItems].Task := Task; tlVisibleTaskArray[tlVisibleItems].LineRect := Rect(CheckRect.Right + TextMargin, LineRect.Top, LineRect.Right, LineRect.Bottom); tlVisibleTaskArray[tlVisibleItems].CheckRect := CheckRect; LineRect.Top := LineRect.Bottom; LineRect.Bottom := LineRect.Top + RowHeight; Inc(tlVisibleItems); end else if (LineRect.Bottom - TextMargin > RealBottom) then begin FLastPrintLine := I; Break; end; end; if tlVisibleItems + tlItemsBefore = tlAllTaskList.Count then begin FLastPrintLine := -2; tlItemsAfter := 0; end else begin tlItemsAfter := tlAllTaskList.Count - tlItemsBefore - tlVisibleItems; end; { these are for the syncing the scrollbar } if StartLine < 0 then tlItemsBefore := 0 else tlItemsBefore := StartLine; end; {-} procedure DrawHeader; var GlyphRect: TRect; HeadStr: string; begin RenderCanvas.Brush.Color := TaskHeadAttrColor; HeadRect.Left := RealLeft + 2; HeadRect.Top := RealTop + 2; HeadRect.Right := RealRight - 2; RenderCanvas.Font.Assign (FTaskHeadAttr.Font); HeadRect.Bottom := RealTop + RenderCanvas.TextHeight ('YyGg0') + TextMargin * 2; TPSFillRect (RenderCanvas, Angle, RenderIn, HeadRect); { draw the header cell borders } if FDrawingStyle = dsFlat then begin { draw an outer and inner bevel } HeadRect.Left := HeadRect.Left - 1; HeadRect.Top := HeadRect.Top - 1; DrawBevelRect (RenderCanvas, TPSRotateRectangle (Angle, RenderIn, HeadRect), BevelShadow, BevelShadow); end else if FDrawingStyle = ds3d then begin { draw a 3d bevel } HeadRect.Right := HeadRect.Right - 1; DrawBevelRect (RenderCanvas, TPSRotateRectangle (Angle, RenderIn, HeadRect), BevelHighlight, BevelDarkShadow); end; if ShowIcon then begin { Draw the glyph } Bmp := Graphics.TBitmap.Create; try Bmp.LoadFromResourceName(HINSTANCE,'VPCHECKPAD'); //soner changed: Bmp.Handle := LoadBaseBitmap('VPCHECKPAD'); { load and return the handle to bitmap resource} if Bmp.Height > 0 then begin GlyphRect.TopLeft := Point (HeadRect.Left + TextMargin, HeadRect.Top + TextMargin); GlyphRect.BottomRight := Point (GlyphRect.Left + Bmp.Width, GlyphRect.Top + Bmp.Height); //TODO: RenderCanvas.BrushCopy (TPSRotateRectangle (Angle, RenderIn, GlyphRect), // Bmp, Rect(0, 0, Bmp.Width, Bmp.Height), // Bmp.Canvas.Pixels[0, Bmp.Height - 1]); RenderCanvas.Draw(GlyphRect.TopLeft.x,GlyphRect.TopLeft.y,Bmp); //soner added HeadRect.Left := HeadRect.Left + Bmp.Width + TextMargin; end; finally Bmp.Free; end; end; { draw the text } if ShowResourceName and (DataStore <> nil) and (DataStore.Resource <> nil) then HeadStr := RSTaskTitleResource + DataStore.Resource.Description else HeadStr := RSTaskTitleNoResource; RenderCanvas.Font.Assign(FTaskHeadAttr.Font); TPSTextOut (RenderCanvas, Angle, RenderIn, HeadRect. Left + TextMargin, HeadRect.Top + TextMargin, HeadStr); end; {-} procedure DrawBorders; begin if FDrawingStyle = dsFlat then begin { draw an outer and inner bevel } DrawBevelRect (RenderCanvas, Rect (RenderIn.Left, RenderIn.Top, RenderIn.Right - 1, RenderIn.Bottom - 1), BevelShadow, BevelHighlight); DrawBevelRect (RenderCanvas, Rect (RenderIn.Left + 1, RenderIn.Top + 1, RenderIn.Right - 2, RenderIn.Bottom - 2), BevelHighlight, BevelShadow); end else if FDrawingStyle = ds3d then begin { draw a 3d bevel } DrawBevelRect (RenderCanvas, Rect (RenderIn.Left, RenderIn.Top, RenderIn.Right - 1, RenderIn.Bottom - 1), BevelShadow, BevelHighlight); DrawBevelRect (RenderCanvas, Rect (RenderIn.Left + 1, RenderIn.Top + 1, RenderIn.Right - 2, RenderIn.Bottom - 2), BevelDarkShadow, BevelFace); end; end; {-} begin if DisplayOnly then begin RealColor := clWhite; BackgroundSelHighlight := clBlack; ForegroundSelHighlight := clWhite; BevelShadow := clBlack; BevelHighlight := clBlack; BevelDarkShadow := clBlack; BevelFace := clBlack; RealLineColor := clBlack; RealCheckBgColor := clWhite; RealCheckBoxColor := clBlack; RealCheckColor := clBlack; RealCompleteColor := clBlack; RealOverdueColor := clBlack; RealNormalColor := clBlack; TaskHeadAttrColor := clSilver; end else begin RealColor := Color; BackgroundSelHighlight := clHighlight; ForegroundSelHighlight := clHighlightText; BevelShadow := clBtnShadow; BevelHighlight := clBtnHighlight; BevelDarkShadow := cl3DDkShadow; BevelFace := clBtnFace; RealLineColor := LineColor; RealCheckBgColor := FDisplayOptions.CheckBGColor; RealCheckBoxColor := FDisplayOptions.CheckColor; RealCheckColor := FDisplayOptions.CheckColor; RealCompleteColor := FDisplayOptions.FCompletedColor; RealOverdueColor := FDisplayOptions.FOverdueColor; RealNormalColor := FDisplayOptions.FNormalColor; TaskHeadAttrColor := FTaskHeadAttr.Color; end; tlPainting := true; SavePenStyle := RenderCanvas.Pen.Style; SaveBrushColor := RenderCanvas.Brush.Color; SavePenColor := RenderCanvas.Pen.Color; RenderCanvas.Pen.Style := psSolid; RenderCanvas.Pen.Width := 1; RenderCanvas.Pen.Mode := pmCopy; RenderCanvas.Brush.Style := bsSolid; Rgn := CreateRectRgn (RenderIn.Left, RenderIn.Top, RenderIn.Right, RenderIn.Bottom); try SelectClipRgn (RenderCanvas.Handle, Rgn); if StartLine < 0 then StartLine := 0; { clear client area } Clear; SetMeasurements; { measure the row height } MeasureRowHeight; { draw header } DrawHeader; { draw lines } DrawLines; { draw the tasks } DrawTasks; { draw the borders } DrawBorders; tlSetVScrollPos; finally SelectClipRgn (RenderCanvas.Handle, 0); DeleteObject (Rgn); end; { reinstate canvas settings} RenderCanvas.Pen.Style := SavePenStyle; RenderCanvas.Brush.Color := SaveBrushColor; RenderCanvas.Pen.Color := SavePenColor; tlPainting := false; end; {=====} procedure TVpTaskList.SetColor(const Value: TColor); begin if FColor <> Value then begin FColor := Value; Invalidate; end; end; {=====} procedure TVpTaskList.tlCalcRowHeight; var SaveFont: TFont; Temp: Integer; begin { Calculates row height based on the largest of the RowHead's Minute } { font, the standard client font, and a sample character string. } SaveFont := Canvas.Font; Canvas.Font := FTaskHeadAttr.Font; tlRowHeight := Canvas.TextHeight(RSTallShortChars); Canvas.Font.Assign(SaveFont); Temp := Canvas.TextHeight(RSTallShortChars); if Temp > tlRowHeight then tlRowHeight := Temp; tlRowHeight := tlRowHeight + TextMargin * 2; Canvas.Font := SaveFont; end; {=====} procedure TVpTaskList.SetDrawingStyle(const Value: TVpDrawingStyle); begin if FDrawingStyle <> Value then begin FDrawingStyle := Value; Repaint; end; end; {=====} procedure TVpTaskList.SetTaskIndex(Value: Integer); begin if (tlInPlaceEditor <> nil) then EndEdit(self); if (Value < DataStore.Resource.Tasks.Count) and (FTaskIndex <> Value) then begin FTaskIndex := Value; if FTaskIndex > -1 then FActiveTask := DataStore.Resource.Tasks.GetTask(Value) else FActiveTask := nil; Invalidate; end; end; {=====} function TVpTaskList.GetTaskIndex: Integer; begin if FActiveTask = nil then result := -1 else result := FActiveTask.ItemIndex; end; {=====} procedure TVpTaskList.SetLineColor(Value: TColor); begin if Value <> FLineColor then begin FLineColor := Value; Invalidate; end; end; {=====} procedure TVpTaskList.SetMaxVisibleTasks(Value: Word); begin if Value <> FMaxVisibleTasks then begin FMaxVisibleTasks := Value; SetLength(tlVisibleTaskArray, FMaxVisibleTasks); Invalidate; end; end; {=====} {$IFNDEF LCL} procedure TVpTaskList.WMSize(var Msg: TWMSize); {$ELSE} procedure TVpTaskList.WMSize(var Msg: TLMSize); {$ENDIF} begin inherited; { force a repaint on resize } Invalidate; end; {=====} procedure TVpTaskList.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := Style or WS_TABSTOP; Style := Style or WS_VSCROLL; {$IFNDEF LCL} WindowClass.style := CS_DBLCLKS; {$ENDIF} end; end; {=====} procedure TVpTaskList.CreateWnd; begin inherited; tlCalcRowHeight; tlSetVScrollPos; end; {=====} {$IFNDEF LCL} procedure TVpTaskList.WMLButtonDown(var Msg : TWMLButtonDown); {$ELSE} procedure TVpTaskList.WMLButtonDown(var Msg : TLMLButtonDown); {$ENDIF} begin inherited; if not Focused then SetFocus; if not (csDesigning in ComponentState) then begin {See if the user clicked on a checkbox} tlSetActiveTaskByCoord (Point(Msg.XPos, Msg.YPos)); end; end; {=====} {$IFNDEF LCL} procedure TVpTaskList.WMRButtonDown (var Msg : TWMRButtonDown); {$ELSE} procedure TVpTaskList.WMRButtonDown (var Msg : TLMRButtonDown); {$ENDIF} var ClientOrigin : TPoint; i : Integer; begin inherited; if not Assigned (PopupMenu) then begin if not Focused then SetFocus; tlSetActiveTaskByCoord(Point(Msg.XPos, Msg.YPos)); tlClickTimer.Enabled := False; ClientOrigin := GetClientOrigin; if not Assigned (FActiveTask) then for i := 0 to FDefaultPopup.Items.Count - 1 do begin if (FDefaultPopup.Items[i].Tag = 1) or (ReadOnly) then FDefaultPopup.Items[i].Enabled := False; end else for i := 0 to FDefaultPopup.Items.Count - 1 do FDefaultPopup.Items[i].Enabled := True; FDefaultPopup.Popup (Msg.XPos + ClientOrigin.x, Msg.YPos + ClientOrigin.y); end; end; {=====} {$IFNDEF LCL} procedure TVpTaskList.WMLButtonDblClk(var Msg : TWMLButtonDblClk); {$ELSE} procedure TVpTaskList.WMLButtonDblClk(var Msg : TLMLButtonDblClk); {$ENDIF} begin inherited; tlClickTimer.Enabled := false; { if the mouse was pressed down in the client area, then select the cell. } if not Focused then SetFocus; { The mouse click landed inside the client area } tlSetActiveTaskByCoord (Point (Msg.XPos, Msg.YPos)); { Spawn the TaskList editor } if not ReadOnly then tlSpawnTaskEditDialog (FActiveTask = nil); end; {=====} procedure TVpTaskList.InitializeDefaultPopup; var NewItem : TMenuItem; begin if RSTaskPopupAdd <> '' then begin NewItem := TMenuItem.Create (Self); NewItem.Caption := RSTaskPopupAdd; NewItem.OnClick := PopupAddTask; NewItem.Tag := 0; FDefaultPopup.Items.Add (NewItem); end; if RSTaskPopupEdit <> '' then begin NewItem := TMenuItem.Create (Self); NewItem.Caption := RSTaskPopupEdit; NewItem.OnClick := PopupEditTask; NewItem.Tag := 1; FDefaultPopup.Items.Add (NewItem); end; if RSTaskPopupDelete <> '' then begin NewItem := TMenuItem.Create (Self); NewItem.Caption := RSTaskPopupDelete; NewItem.OnClick := PopupDeleteTask; NewItem.Tag := 1; FDefaultPopup.Items.Add (NewItem); end; end; {=====} procedure TVpTaskList.PopupAddTask (Sender : TObject); begin if ReadOnly then Exit; if not CheckCreateResource then Exit; { Allow the user to fill in all the new information } Repaint; tlSpawnTaskEditDialog (True); end; {=====} procedure TVpTaskList.PopupDeleteTask (Sender : TObject); begin if ReadOnly then Exit; if FActiveTask <> nil then begin Repaint; DeleteActiveTask (True); end; end; {=====} procedure TVpTaskList.PopupEditTask (Sender : TObject); begin if ReadOnly then Exit; if FActiveTask <> nil then begin Repaint; { edit this Task } tlSpawnTaskEditDialog (False); end; end; {=====} procedure TVpTaskList.tlSpawnTaskEditDialog(NewTask: Boolean); var AllowIt : Boolean; Task : TVpTask; TaskDlg : TVpTaskEditDialog; begin tlClickTimer.Enabled := false; if not CheckCreateResource then Exit; if (DataStore = nil) or (DataStore.Resource = nil) then Exit; AllowIt := false; if NewTask then begin Task := DataStore.Resource.Tasks.AddTask(DataStore.GetNextID('Tasks')); Task.CreatedOn := now; Task.DueDate := Now + 7; end else Task := FActiveTask; if Assigned(FOwnerEditTask) then FOwnerEditTask(self, Task, DataStore.Resource, AllowIt) else begin TaskDlg := TVpTaskEditDialog.Create(nil); try TaskDlg.Options := TaskDlg.Options + [doSizeable]; TaskDlg.DataStore := DataStore; AllowIt := TaskDlg.Execute(Task); finally TaskDlg.Free; end; end; if AllowIt then begin DataStore.PostTasks(); Invalidate; end else begin if NewTask then begin DataStore.Resource.Tasks.DeleteTask(Task); end; DataStore.PostTasks; Invalidate; end; end; {=====} {$IFNDEF LCL} procedure TVpTaskList.CMWantSpecialKey(var Msg: TCMWantSpecialKey); begin inherited; Msg.Result := 1; end; {$ENDIF} {=====} procedure TVpTaskList.tlEditInPlace(Sender: TObject); begin { this is the timer Task which spawns an in-place editor } { if the task is doublecliked before this timer fires, then the } { task is edited in a dialog based editor. } tlClickTimer.Enabled := false; EditTask; end; {=====} procedure TVpTaskList.EditTask; var AllowIt : Boolean; R : TRect; VisTask : Integer; begin {don't allow a user to edit a completed task in place.} if FActiveTask.Complete then Exit; AllowIt := true; VisTask := tlTaskIndexToVisibleTask (TaskIndex); if VisTask < 0 then Exit; { call the user defined BeforeEdit task } if Assigned(FBeforeEdit) then FBeforeEdit(Self, FActiveTask, AllowIt); if AllowIt then begin { build the editor's rectangle } R := tlVisibleTaskArray[VisTask].LineRect; R.Top := R.Top + TextMargin; R.Left := R.Left + TextMargin - 1; { create and spawn the in-place editor } tlInPlaceEditor := TVpTLInPlaceEdit.Create(Self); tlInPlaceEditor.Parent := self; tlInPlaceEditor.OnExit := EndEdit; tlInPlaceEditor.Move(R , true); tlInPlaceEditor.Text := FActiveTask.Description; tlInPlaceEditor.Font.Assign(Font); tlInPlaceEditor.SelectAll; Invalidate; end; end; {=====} procedure TVpTaskList.EndEdit(Sender: TObject); begin if tlInPlaceEditor <> nil then begin if tlInPlaceEditor.Text <> FActiveTask.Description then begin FActiveTask.Description := tlInPlaceEditor.Text; FActiveTask.Changed := true; DataStore.Resource.TasksDirty := true; DataStore.PostTasks; if Assigned(FAfterEdit) then FAfterEdit(self, FActiveTask); end; tlInPlaceEditor.Free; tlInPlaceEditor := nil; SetFocus; Invalidate; end; end; {=====} procedure TVpTaskList.KeyDown(var Key: Word; Shift: TShiftState); var PopupPoint : TPoint; begin case Key of VK_UP : if TaskIndex > 0 then TaskIndex := TaskIndex - 1 else TaskIndex := Pred(DataStore.Resource.Tasks.Count); VK_DOWN : if TaskIndex < Pred(DataStore.Resource.Tasks.Count) then TaskIndex := TaskIndex + 1 else TaskIndex := 0; VK_NEXT : if TaskIndex < Pred (DataStore.Resource.Tasks.Count) - tlVisibleItems then TaskIndex := TaskIndex + tlVisibleItems else TaskIndex := Pred(DataStore.Resource.Tasks.Count); VK_PRIOR : if TaskIndex > tlVisibleItems then TaskIndex := TaskIndex - tlVisibleItems else TaskIndex := 0; VK_HOME : TaskIndex := 0; VK_END : TaskIndex := Pred(DataStore.Resource.Tasks.Count); VK_DELETE : DeleteActiveTask(true); VK_RETURN : tlSpawnTaskEditDialog (False); VK_INSERT : tlSpawnTaskEditDialog (True); VK_F2 : if Assigned (DataStore) then begin if Assigned (DataStore.Resource) then tlEditInPlace (Self); end; VK_SPACE : if Assigned (FActiveTask) then begin FActiveTask.Complete := not FActiveTask.Complete; Invalidate; end; {$IFNDEF LCL} VK_TAB : if ssShift in Shift then Windows.SetFocus (GetNextDlgTabItem(GetParent(Handle), Handle, False)) else Windows.SetFocus (GetNextDlgTabItem(GetParent(Handle), Handle, True)); {$ENDIF} VK_F10 : if (ssShift in Shift) and not (Assigned (PopupMenu)) then begin PopupPoint := GetClientOrigin; FDefaultPopup.Popup (PopupPoint.x + 10, PopupPoint.y + 10); end; VK_APPS : if not Assigned (PopupMenu) then begin PopupPoint := GetClientOrigin; FDefaultPopup.Popup (PopupPoint.x + 10, PopupPoint.y + 10); end; end; if TaskIndex < tlItemsBefore then tlItemsBefore := TaskIndex; if TaskIndex >= tlItemsBefore + tlVisibleItems then tlItemsBefore := TaskIndex - tlVisibleItems + 1; end; {=====} {$IFNDEF LCL} procedure TVpTaskList.WMVScroll(var Msg: TWMVScroll); {$ELSE} procedure TVpTaskList.WMVScroll(var Msg: TLMVScroll); {$ENDIF} begin { for simplicity, bail out of editing while scrolling. } EndEdit(Self); if tlInPlaceEditor <> nil then Exit; case Msg.ScrollCode of SB_LINEUP : if tlItemsBefore > 0 then tlItemsBefore := tlItemsBefore - 1; SB_LINEDOWN : if tlItemsAfter > 0 then tlItemsBefore := tlItemsBefore + 1; SB_PAGEUP : if tlItemsBefore >= tlVisibleItems then tlItemsBefore := tlItemsBefore - tlVisibleItems else tlItemsBefore := 0; SB_PAGEDOWN : if tlItemsAfter >= tlVisibleItems then tlItemsBefore := tlItemsBefore + tlVisibleItems else tlItemsBefore := tlAllTaskList.Count - tlVisibleItems; SB_THUMBPOSITION, SB_THUMBTRACK : tlItemsBefore := Msg.Pos; end; Invalidate; end; {=====} procedure TVpTaskList.tlSetVScrollPos; var SI : TScrollInfo; begin if (not HandleAllocated) or (DataStore = nil) or (DataStore.Resource = nil) or (csDesigning in ComponentState) then Exit; with SI do begin cbSize := SizeOf(SI); fMask := SIF_RANGE or SIF_PAGE or SIF_POS; nMin := 1; nMax := tlAllTaskList.Count; nPage := tlVisibleItems; if tlItemsAfter = 0 then nPos := tlAllTaskList.Count else nPos := tlItemsBefore; nTrackPos := nPos; end; SetScrollInfo(Handle, SB_VERT, SI, True); end; {=====} procedure TVpTaskList.SetShowIcon (const v : Boolean); begin if v <> FShowIcon then begin FShowIcon := v; Invalidate; end; end; {=====} procedure TVpTaskList.SetShowResourceName(Value: Boolean); begin if Value <> FShowResourceName then begin FShowResourceName := Value; Invalidate; end; end; {=====} procedure TVpTaskList.tlSetActiveTaskByCoord(Pnt: TPoint); var I: integer; begin if (DataStore = nil) or (DataStore.Resource = nil) then Exit; if not ReadOnly and tlClickTimer.Enabled then tlClickTimer.Enabled := false; TaskIndex := -1; for I := 0 to pred(Length(tlVisibleTaskArray)) do begin { we've hit the end of active tasks, so bail } if tlVisibleTaskArray[I].Task = nil then Exit; { if the point is in an active task's check box... } if PointInRect(Pnt, tlVisibleTaskArray[I].CheckRect) then begin { set the active task index } TaskIndex := tlVisibleTaskToTaskIndex (I); if not ReadOnly then begin { toggle the complete flag. } FActiveTask.Complete := not FActiveTask.Complete; FActiveTask.Changed := true; DataStore.Resource.TasksDirty := true; DataStore.PostTasks; Invalidate; end; Exit; end; { if the point is in an active task..} if PointInRect(Pnt, tlVisibleTaskArray[I].LineRect) then begin { Set ActiveTask to the selected one } TaskIndex := tlVisibleTaskToTaskIndex (I); if not ReadOnly then tlClickTimer.Enabled := true; Exit; end; end; end; {=====} function TVpTaskList.tlVisibleTaskToTaskIndex (const VisTaskIndex : Integer) : Integer; var RealTask : TVpTask; begin Result := -1; if (VisTaskIndex < 0) or (VisTaskIndex >= Length (tlVisibleTaskArray)) then Exit; RealTask := TVpTask (tlVisibleTaskArray[VisTaskIndex].Task); Result := RealTask.ItemIndex; end; function TVpTaskList.tlTaskIndexToVisibleTask (const ATaskIndex : Integer) : Integer; var i : Integer; begin Result := -1; for i := 0 to Length (tlVisibleTaskArray) - 1 do if ATaskIndex = TVpTask (tlVisibleTaskArray[i].Task).ItemIndex then begin Result := i; Break; end; end; {=====} end.
unit FiveLogonDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TFiveLogonDlg = class(TForm) Notebook1: TNotebook; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; ServerAddress: TEdit; ServerPort: TEdit; UserName: TEdit; Password: TEdit; Button1: TButton; Button2: TButton; ClientIP: TEdit; Label6: TLabel; Image1: TImage; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FiveLogonDlg: TFiveLogonDlg; implementation {$R *.DFM} procedure TFiveLogonDlg.FormCreate(Sender: TObject); begin Top := 0; Left := 0; Width := Screen.Width; Height := Screen.Height; end; end.
unit ssLabel; interface uses SysUtils, Classes, Controls, StdCtrls, Types, Graphics; type TssDisabledDraw = (ddStandard, ddUser); TssLabel = class(TLabel) private FDisabledDraw: TssDisabledDraw; FDisabledColor: TColor; procedure SetDisabledDraw(const Value: TssDisabledDraw); procedure SetDisabledColor(const Value: TColor); protected procedure DoDrawText(var Rect: TRect; Flags: Longint); override; published property DisabledDraw: TssDisabledDraw read FDisabledDraw write SetDisabledDraw; property DisabledColor: TColor read FDisabledColor write SetDisabledColor; end; procedure Register; //============================================================================================== //============================================================================================== //============================================================================================== implementation uses Windows; //============================================================================================== procedure Register; begin RegisterComponents('SS Pack', [TssLabel]); end; //============================================================================================== procedure TssLabel.DoDrawText(var Rect: TRect; Flags: Integer); var Text: string; begin Text := GetLabelText; if (Flags and DT_CALCRECT <> 0) and ((Text = '') or ShowAccelChar and (Text[1] = '&') and (Text[2] = #0)) then Text := Text + ' '; if not ShowAccelChar then Flags := Flags or DT_NOPREFIX; Flags := DrawTextBiDiModeFlags(Flags); Canvas.Font := Font; if not Enabled then begin if FDisabledDraw=ddStandard then begin Canvas.Font.Color := clBtnHighlight; OffsetRect(Rect, 1, 1); end else Canvas.Font.Color := FDisabledColor; DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); if FDisabledDraw=ddStandard then begin OffsetRect(Rect, -1, -1); Canvas.Font.Color := clBtnShadow; DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); end; end else DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); end; //============================================================================================== procedure TssLabel.SetDisabledColor(const Value: TColor); begin FDisabledColor := Value; Invalidate; end; //============================================================================================== procedure TssLabel.SetDisabledDraw(const Value: TssDisabledDraw); begin FDisabledDraw := Value; Invalidate; end; end.
unit Views.Samples; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Grids, Vcl.DBGrids, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.MSAcc, FireDAC.Phys.MSAccDef, FireDAC.VCLUI.Wait, Vcl.StdCtrls, FireDAC.Phys.IB, FireDAC.Phys.IBDef; type TFrmRagnaSamples = class(TForm) DBGrid1: TDBGrid; dsCountry: TDataSource; Country: TFDQuery; Button1: TButton; FDConnection: TFDConnection; CountryName: TWideStringField; CountryCapital: TWideStringField; CountryContinent: TWideStringField; CountryArea: TFloatField; CountryPopulation: TFloatField; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; mmJson: TMemo; Button7: TButton; Button8: TButton; Button9: TButton; Button10: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure Button9Click(Sender: TObject); procedure Button10Click(Sender: TObject); end; var FrmRagnaSamples: TFrmRagnaSamples; implementation {$R *.dfm} uses Ragna; procedure TFrmRagnaSamples.Button10Click(Sender: TObject); begin Country .OpenUp .EditFromJson('{"name":"A","capital":"B","continent":"C","area":1,"population":2}'); end; procedure TFrmRagnaSamples.Button1Click(Sender: TObject); begin Country.OpenUp; end; procedure TFrmRagnaSamples.Button2Click(Sender: TObject); begin Country.OpenEmpty; end; procedure TFrmRagnaSamples.Button3Click(Sender: TObject); begin Country .Where(CountryName).Equals('Brazil') .&Or(CountryName).Equals('Canada') .OpenUp; end; procedure TFrmRagnaSamples.Button4Click(Sender: TObject); begin Country .Where(CountryName).Equals('Brazil') .&And(CountryCapital).Equals('Brasilia') .OpenUp; end; procedure TFrmRagnaSamples.Button5Click(Sender: TObject); begin Country .Where(CountryName).Like('B') .OpenUp; end; procedure TFrmRagnaSamples.Button6Click(Sender: TObject); begin Country .Order(CountryName) .OpenUp; end; procedure TFrmRagnaSamples.Button7Click(Sender: TObject); begin mmJson.Lines.Text := Country.OpenUp.ToJSONObject.ToString; end; procedure TFrmRagnaSamples.Button8Click(Sender: TObject); begin mmJson.Lines.Text := Country.OpenUp.ToJSONArray.ToString; end; procedure TFrmRagnaSamples.Button9Click(Sender: TObject); begin Country.New('{"name":"A","capital":"B","continent":"C","area":1,"population":2}'); end; end.
unit IniOpts; interface uses Classes, SysUtils, ElHeader, ElTree, ElOpts; type TOptions = class(TElOptions) private FSort: Boolean; FOneInstance: Boolean; FLazyWrite: Boolean; FSimple: Boolean; FLoadLastUsed: Boolean; FShowDailyTip : Boolean; procedure SetLazyWrite(newValue: Boolean); procedure SetSimple(newValue: Boolean); procedure SetOneInstance(newValue: Boolean); procedure SetSort(newValue: Boolean); protected procedure SetAutoSave (value : boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property LoadLastUsed: Boolean read FLoadLastUsed write FLoadLastUsed; property LazyWrite: Boolean read FLazyWrite write SetLazyWrite default true; property Simple: Boolean read FSimple write SetSimple; property OneInstance: Boolean read FOneInstance write SetOneInstance; property Sort: Boolean read FSort write SetSort; property ShowDailyTip : Boolean read FShowDailyTip write FShowDailyTip; end; var Options : TOptions; implementation uses Main; procedure TOptions.SetAutoSave (value : boolean); begin if FAutoSave <> value then begin FAutoSave := value; MainForm.AutoSaveItem.Checked := value; end; end; procedure TOptions.SetLazyWrite(newValue: Boolean); begin if (FLazyWrite <> newValue) then begin FLazyWrite := newValue; MainForm.LazyItem.Checked := FLazyWrite; MainForm.IniFile.LazyWrite := FLazyWrite; if not FLazyWrite then MainForm.Modified := false; end; {if} end; procedure TOptions.SetSimple(newValue: Boolean); begin if (FSimple <> newValue) then begin FSimple := newValue; MainForm.IniFile.Simple := FSimple; if FSimple then MainForm.StandardItem.Checked := true else MainForm.EnhancedItem.Checked := true; MainForm.TreeItemFocused(Self); end; {if} end; procedure TOptions.SetOneInstance(newValue: Boolean); begin if (FOneInstance <> newValue) then begin FOneInstance := newValue; MainForm.OneInst.Enabled := newValue; MainForm.OneInstItem.Checked := newValue; end; {if} end; procedure TOptions.SetSort(newValue: Boolean); var SM : TElSSortMode; begin if (FSort <> newValue) then begin FSort := newValue; MainForm.SortItem.Checked := FSort; if FSort then begin MainForm.Tree.SortMode := smAddClick; if MainForm.Tree.SortDir = sdAscend then SM := hsmAscend else if MainForm.Tree.SortDir = sdDescend then SM := hsmDescend else sm:=hsmNone; MainForm.Tree.HeaderSections[MainForm.Tree.SortSection].SortMode := SM; MainForm.Tree.Sort(true); end else begin MainForm.Tree.SortMode := smNone; MainForm.Tree.HeaderSections[MainForm.Tree.SortSection].SortMode := hsmNone; end; end; {if} end; destructor TOptions.Destroy; begin inherited Destroy; end; constructor TOptions.Create(AOwner: TComponent); begin inherited Create(AOwner); StorageType := eosElIni; IniSection := 'Options'; FLazyWrite := true; FSort := true; FShowDailyTip := True; end; end.
unit ValidationRules.TestSuite; interface uses TestFramework, System.SysUtils, System.Variants, Framework.Interfaces, EnumClasses.TDataType, ValidationRules.TIsEmptyValidationRule, ValidationRules.TMaxLengthValidationRule, ValidationRules.TDataTypeValidationRule; type TTIsEmptyValidationRuleTest = class(TTestCase) strict private FIsEmptyValidationRule: IValidationRule; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_AcceptEmpty_EmptyValue; procedure TestParse_AcceptEmpty_NonEmptyValue; procedure TestParse_DoNotAcceptEmpty_EmptyValue; procedure TestParse_DoNotAcceptEmpty_NonEmptyValue; end; TTMaxLengthValidationRuleTest = class(TTestCase) strict private FIsEmptyValidationRule: IValidationRule; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_Invalid; procedure TestParse_Valid; end; TTDataTypeValidationRuleTest = class(TTestCase) strict private FDataTypeValidationRule: IValidationRule; public procedure SetUp; override; procedure TearDown; override; published //Boolean DataType procedure TestParse_BooleanDataType_True; procedure TestParse_BooleanDataType_False; procedure TestParse_BooleanDataType_StringBoolean_Invalid; procedure TestParse_BooleanDataType_StringBoolean_True_Valid; procedure TestParse_BooleanDataType_StringBoolean_False_Valid; //Currency DataType procedure TestParse_CurrencyDataType; procedure TestParse_CurrencyDataType_StringCurrency_Invalid; procedure TestParse_CurrencyDataType_StringCurrency_Valid; //DateTime DataType procedure TestParse_DateTimeDataType; procedure TestParse_DateTimeDataType_StringDateTime_Invalid; procedure TestParse_DateTimeDataType_StringDateTime_Valid; //Integer DataType procedure TestParse_IntegerDataType; procedure TestParse_IntegerDataType_StringInteger_Invalid; procedure TestParse_IntegerDataType_StringInteger_Valid; //Numeric DataType procedure TestParse_NumericDataType; procedure TestParse_NumericDataType_StringNumeric_Invalid; procedure TestParse_NumericDataType_StringNumeric_Valid; //String DataType procedure TestParse_StringDataType_Invalid; procedure TestParse_StringDataType_Valid; end; implementation { TTIsEmptyValidationRuleTest } procedure TTIsEmptyValidationRuleTest.SetUp; begin inherited; end; procedure TTIsEmptyValidationRuleTest.TearDown; begin inherited; end; procedure TTIsEmptyValidationRuleTest.TestParse_AcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := ''; AReasonForRejection := ''; FIsEmptyValidationRule := TIsEmptyValidationRule.Create(True); ReturnValue := FIsEmptyValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTIsEmptyValidationRuleTest.TestParse_AcceptEmpty_NonEmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 'field is not empty'; AReasonForRejection := ''; FIsEmptyValidationRule := TIsEmptyValidationRule.Create(True); ReturnValue := FIsEmptyValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTIsEmptyValidationRuleTest.TestParse_DoNotAcceptEmpty_EmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := ''; AReasonForRejection := ''; FIsEmptyValidationRule := TIsEmptyValidationRule.Create(False); ReturnValue := FIsEmptyValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection = TIsEmptyValidationRule.IS_EMPTY_MESSAGE); end; procedure TTIsEmptyValidationRuleTest.TestParse_DoNotAcceptEmpty_NonEmptyValue; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 'field is not empty'; AReasonForRejection := ''; FIsEmptyValidationRule := TIsEmptyValidationRule.Create(False); ReturnValue := FIsEmptyValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; { TTMaxLengthValidationRuleTest } procedure TTMaxLengthValidationRuleTest.SetUp; begin inherited; end; procedure TTMaxLengthValidationRuleTest.TearDown; begin inherited; end; procedure TTMaxLengthValidationRuleTest.TestParse_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 'this string is 31 chars length.'; AReasonForRejection := ''; FIsEmptyValidationRule := TMaxLengthValidationRule.Create(30); ReturnValue := FIsEmptyValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection = TMaxLengthValidationRule.INVALID_LENGTH_MESSAGE); end; procedure TTMaxLengthValidationRuleTest.TestParse_Valid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 'this string is 30 chars length'; AReasonForRejection := ''; FIsEmptyValidationRule := TMaxLengthValidationRule.Create(30); ReturnValue := FIsEmptyValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; { TTDataTypeValidationRuleTest } procedure TTDataTypeValidationRuleTest.SetUp; begin inherited; end; procedure TTDataTypeValidationRuleTest.TearDown; begin inherited; end; procedure TTDataTypeValidationRuleTest.TestParse_BooleanDataType_False; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := False; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(True, TDataType.dtBoolean, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_BooleanDataType_StringBoolean_False_Valid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 'False'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtBoolean, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_BooleanDataType_StringBoolean_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 'InvalidBoolean'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtBoolean, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection = TDataTypeValidationRule.INVALID_DATATYPE_MESSAGE + ' [' + TDataType.dtBoolean + ']'); end; procedure TTDataTypeValidationRuleTest.TestParse_BooleanDataType_StringBoolean_True_Valid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 'True'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtBoolean, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_BooleanDataType_True; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := True; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtBoolean, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_CurrencyDataType; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 12321.33; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtCurrency, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_CurrencyDataType_StringCurrency_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := '123,21.33'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtCurrency, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection = TDataTypeValidationRule.INVALID_DATATYPE_MESSAGE + ' [' + TDataType.dtCurrency + ']'); end; procedure TTDataTypeValidationRuleTest.TestParse_CurrencyDataType_StringCurrency_Valid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := '12360'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtCurrency, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_DateTimeDataType; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := Now; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtDateTime, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_DateTimeDataType_StringDateTime_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := '28/11/1973'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtDateTime, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection = TDataTypeValidationRule.INVALID_DATATYPE_MESSAGE + ' [' + TDataType.dtDateTime + ']'); end; procedure TTDataTypeValidationRuleTest.TestParse_DateTimeDataType_StringDateTime_Valid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := '1973/11/28'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtDateTime, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_IntegerDataType; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 1250; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtInteger, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_IntegerDataType_StringInteger_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := '1230.44'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtInteger, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection = TDataTypeValidationRule.INVALID_DATATYPE_MESSAGE + ' [' + TDataType.dtInteger + ']'); end; procedure TTDataTypeValidationRuleTest.TestParse_IntegerDataType_StringInteger_Valid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := '1250'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtInteger, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_NumericDataType; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 1250.443234; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtNumeric, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_NumericDataType_StringNumeric_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := '123,0.44'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtNumeric, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection = TDataTypeValidationRule.INVALID_DATATYPE_MESSAGE + ' [' + TDataType.dtNumeric + ']'); end; procedure TTDataTypeValidationRuleTest.TestParse_NumericDataType_StringNumeric_Valid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := '1250.234323'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtNumeric, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; procedure TTDataTypeValidationRuleTest.TestParse_StringDataType_Invalid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 1230.44; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtString, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = False); Check(AReasonForRejection = TDataTypeValidationRule.INVALID_DATATYPE_MESSAGE + ' [' + TDataType.dtString + ']'); end; procedure TTDataTypeValidationRuleTest.TestParse_StringDataType_Valid; var ReturnValue: Boolean; AReasonForRejection: String; AValue: Variant; begin AValue := 'ValidString'; AReasonForRejection := ''; FDataTypeValidationRule := TDataTypeValidationRule.Create(False, TDataType.dtString, 'yyyy/mm/dd', '/'); ReturnValue := FDataTypeValidationRule.Parse(AValue, AReasonForRejection); Check(ReturnValue = True); Check(AReasonForRejection = ''); end; initialization ReportMemoryLeaksOnShutdown := True; RegisterTest(TTIsEmptyValidationRuleTest.Suite); RegisterTest(TTMaxLengthValidationRuleTest.Suite); RegisterTest(TTDataTypeValidationRuleTest.Suite); end.
unit Utils; interface uses GDIPAPI, GDIPOBJ, System.Types, Winapi.Windows, System.SysUtils, Vcl.Graphics; procedure RotateFlipBitmap(Bitmap, Dest: TBitmap; RotateFlipType: TRotateFlipType); procedure SmoothScaleBitmap(Source, Dest: TBitmap; OutWidth, OutHeight: integer); function ForceForegroundWindow(hwnd: THandle): Boolean; implementation //https://www.nldelphi.com/showthread.php?42769-Bitmap-90-graden-roteren&p=358213&viewfull=1#post358213 //GolezTrol procedure RotateFlipBitmap(Bitmap, Dest: TBitmap; RotateFlipType: TRotateFlipType); var GdipBitmap: Pointer; NewBitmap: HBITMAP; begin GdipCreateBitmapFromHBITMAP(Bitmap.Handle, 0, GdipBitmap); GdipImageRotateFlip(GdipBitmap, RotateFlipType); GdipCreateHBITMAPFromBitmap(GdipBitmap, NewBitmap, 0); Dest.Handle := NewBitmap; end; //https://stackoverflow.com/questions/33608134/fast-way-to-resize-an-image-mixing-fmx-and-vcl-code //Dalija Prasnikar procedure SmoothScaleBitmap(Source, Dest: TBitmap; OutWidth, OutHeight: integer); var src, dst: TGPBitmap; g: TGPGraphics; h: HBITMAP; begin src := TGPBitmap.Create(Source.Handle, 0); try dst := TGPBitmap.Create(OutWidth, OutHeight); try g := TGPGraphics.Create(dst); try g.SetInterpolationMode(InterpolationModeHighQuality); g.SetPixelOffsetMode(PixelOffsetModeHighQuality); g.SetSmoothingMode(SmoothingModeHighQuality); g.DrawImage(src, 0, 0, dst.GetWidth, dst.GetHeight); finally g.Free; end; dst.GetHBITMAP(0, h); Dest.Handle := h; finally dst.Free; end; finally src.Free; end; end; //https://www.swissdelphicenter.ch/en/showcode.php?id=261 //unknown { Windows 98/2000 doesn't want to foreground a window when some other window has the keyboard focus. ForceForegroundWindow is an enhanced SetForeGroundWindow/bringtofront function to bring a window to the front. } { Manchmal funktioniert die SetForeGroundWindow Funktion nicht so, wie sie sollte; besonders unter Windows 98/2000, wenn ein anderes Fenster den Fokus hat. ForceForegroundWindow ist eine "verbesserte" Version von der SetForeGroundWindow API-Funktion, um ein Fenster in den Vordergrund zu bringen. } function ForceForegroundWindow(hwnd: THandle): Boolean; const SPI_GETFOREGROUNDLOCKTIMEOUT = $2000; SPI_SETFOREGROUNDLOCKTIMEOUT = $2001; var ForegroundThreadID: DWORD; ThisThreadID: DWORD; timeout: DWORD; begin if IsIconic(hwnd) then ShowWindow(hwnd, SW_RESTORE); if GetForegroundWindow = hwnd then Result := True else begin // Windows 98/2000 doesn't want to foreground a window when some other // window has keyboard focus if ((Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion > 4)) or ((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and ((Win32MajorVersion > 4) or ((Win32MajorVersion = 4) and (Win32MinorVersion > 0)))) then begin // Code from Karl E. Peterson, www.mvps.org/vb/sample.htm // Converted to Delphi by Ray Lischner // Published in The Delphi Magazine 55, page 16 Result := False; ForegroundThreadID := GetWindowThreadProcessID(GetForegroundWindow, nil); ThisThreadID := GetWindowThreadPRocessId(hwnd, nil); if AttachThreadInput(ThisThreadID, ForegroundThreadID, True) then begin BringWindowToTop(hwnd); // IE 5.5 related hack SetForegroundWindow(hwnd); AttachThreadInput(ThisThreadID, ForegroundThreadID, False); Result := (GetForegroundWindow = hwnd); end; if not Result then begin // Code by Daniel P. Stasinski SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, @timeout, 0); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(0), SPIF_SENDCHANGE); BringWindowToTop(hwnd); // IE 5.5 related hack SetForegroundWindow(hWnd); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(timeout), SPIF_SENDCHANGE); end; end else begin BringWindowToTop(hwnd); // IE 5.5 related hack SetForegroundWindow(hwnd); end; Result := (GetForegroundWindow = hwnd); end; end; { ForceForegroundWindow } end.
unit SpawnCommon; { Inno Setup Copyright (C) 1997-2007 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Constants and types shared by the SpawnServer and SpawnClient units $jrsoftware: issrc/Projects/SpawnCommon.pas,v 1.2 2007/09/04 00:51:58 jr Exp $ } interface uses Messages; const { Spawn client -> spawn server messages } WM_SpawnServer_Query = WM_USER + $1550; { Spawn client -> spawn server WM_COPYDATA messages } CD_SpawnServer_Exec = $4A73E9C0; CD_SpawnServer_ShellExec = $4A73E9C1; { Possible wParam values in a WM_SpawnServer_Query message } SPAWN_QUERY_STATUS = 1; SPAWN_QUERY_RESULTCODE_LO = 2; SPAWN_QUERY_RESULTCODE_HI = 3; { Bits set in high word of every response } SPAWN_MSGRESULT_SUCCESS_BITS = $6C830000; SPAWN_MSGRESULT_FAILURE_BITS = $6C840000; { Possible error codes returned by WM_COPYDATA handler } SPAWN_MSGRESULT_OUT_OF_MEMORY = SPAWN_MSGRESULT_FAILURE_BITS or 1; SPAWN_MSGRESULT_UNEXPECTED_EXCEPTION = SPAWN_MSGRESULT_FAILURE_BITS or 2; SPAWN_MSGRESULT_ALREADY_IN_CALL = SPAWN_MSGRESULT_FAILURE_BITS or 3; SPAWN_MSGRESULT_INVALID_DATA = SPAWN_MSGRESULT_FAILURE_BITS or 4; { Possible error codes returned by WM_SpawnServer_Query handler } SPAWN_MSGRESULT_INVALID_SEQUENCE_NUMBER = SPAWN_MSGRESULT_FAILURE_BITS or 5; SPAWN_MSGRESULT_INVALID_QUERY_OPERATION = SPAWN_MSGRESULT_FAILURE_BITS or 6; { Low word of response to SPAWN_QUERY_STATUS query } SPAWN_STATUS_EXCEPTION = 1; SPAWN_STATUS_RUNNING = 2; SPAWN_STATUS_RETURNED_TRUE = 3; SPAWN_STATUS_RETURNED_FALSE = 4; implementation end.
//Exercicio 53: Faça um algoritmo que leia 4 números inteiros e, informe, quantos e quais deles são pares. { Solução em Portugol Algoritmo Exercicio 53; Var N,contador,acumulador: inteiro; Inicio exiba("Programa que lê 4 números e diz quais/quantos são pares."); acumulador <- 0; para contador <- 1 até 4 faça exiba("Digite o ", contador,"º número:"); leia(N); se(resto(N,2) = 0) então Inicio acumulador <- acumulador + 1; exiba("O número ",N," é par."); Fim fimse; fimpara; exiba("São no total ",acumulador," números pares."); Fim. } // Solução em Pascal Program Exercicio53; uses crt; var N,contador,acumulador: integer; begin clrscr; writeln('Programa que lê 4 números e diz quais/quantos são pares.'); acumulador := 0; for contador := 1 to 4 do Begin writeln('Digite o ', contador,'º número:'); readln(N); if((N mod 2) = 0) then Begin acumulador := acumulador + 1; writeln('O número ',N,' é par.'); End End; writeln('São no total ',acumulador,' números pares.'); repeat until keypressed; end.
unit cyColorMatrix; { Component(s): tcyColorMatrix Description: It's a color matrix representation !!! This component allow best performance than TcyColorGrid despite of non published ColorList property ... Author: Mauricio mail: mauricio_box@yahoo.com $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $ €€€ Accept any PAYPAL DONATION $$$ € $ to: mauricio_box@yahoo.com € €€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€ Copyrights: You can use and distribute this component freely but you can' t remove this header } interface uses Classes, Types, Controls, Graphics, Messages; type TBoxStyle = (bsRectangle, bsRoundRect, bsCircle, bsHCrystal, Crystal); TProcOnPaintBox = procedure (Sender: TObject; aRect: TRect; aRow: integer; aCol: integer; aColor: TColor) of object; TProcOnBoxClick = procedure (Sender: TObject; aRow: integer; aCol: integer; aColor: TColor) of object; TcyColorMatrix = class(TGraphicControl) private FColorList: Array of Array of TColor; FptMouseDown: TPoint; FBackground: TColor; FBoxWidth: integer; FBoxHeight: integer; FBoxRows: integer; FBoxCols: integer; FBoxIntervalX: integer; FBoxIntervalY: integer; FBoxFrameWidth: integer; FBoxFrameColor: TColor; FOnCustomDrawBox: TProcOnPaintBox; FOnBeforePaintBoxes: TNotifyEvent; FOnAfterPaintBoxes: TNotifyEvent; FTransparent: Boolean; FOnBoxClick: TProcOnBoxClick; FDefaultColor: TColor; procedure SetBackground(const Value: TColor); procedure SetBoxWidth(const Value: integer); procedure SetBoxHeight(const Value: integer); procedure SetBoxRows(const Value: integer); procedure SetBoxCols(const Value: integer); procedure SetBoxIntervalX(const Value: integer); procedure SetBoxIntervalY(const Value: integer); procedure SetBoxFrameWidth(const Value: integer); procedure SetBoxFrameColor(const Value: TColor); procedure SetTransparent(const Value: Boolean); procedure PaintBoxes(AllColors: Boolean; paramColor: TColor); procedure PaintBox(var BoxRect: TRect; BoxColor: TColor; Row, Column: Integer; CustomDrawBox: Boolean); procedure InitializeColors(fromRow, fromCol: Integer); procedure SetDefaultColor(const Value: TColor); protected procedure Click; override; procedure Loaded; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; // Call OnMouseDown procedure ... procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure SetAutoSize(Value: Boolean); override; procedure Paint; override; function PartialPaint: Boolean; virtual; procedure DefaultDrawBox(var aRect: TRect; aRow, aCol: integer; aColor: TColor); virtual; procedure RedefineSize; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetBoxAtPos(aPoint: TPoint; var aRow: Integer; var aCol: Integer; ExactPos: Boolean): Boolean; function GetColorGrid(aRow: Integer; aCol: integer): TColor; virtual; procedure SetColorGrid(aRow: Integer; aCol: integer; aColor: TColor; FullRepaint: Boolean); procedure SubstColor(old, New: TColor; FullRepaint: Boolean); virtual; published property Align; property Autosize; property Anchors; property Canvas; property Constraints; property Enabled; property Visible; property OnClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property Background: TColor read FBackground write SetBackground; property BoxHeight: integer read FBoxHeight write SetBoxHeight; property BoxWidth: integer read FBoxWidth write SetBoxWidth; property BoxRows: integer read FBoxRows write SetBoxRows; property BoxCols: integer read FBoxCols write SetBoxCols; property BoxFrameColor: TColor read FBoxFrameColor write SetBoxFrameColor; property BoxFrameWidth: integer read FBoxFrameWidth write SetBoxFrameWidth default 0; property BoxIntervalX: integer read FBoxIntervalX write SetBoxIntervalX default 1; property BoxIntervalY: integer read FBoxIntervalY write SetBoxIntervalY default 1; property DefaultColor: TColor read FDefaultColor write SetDefaultColor; property Transparent: Boolean read FTransparent write SetTransparent default false; property OnCustomDrawBox: TProcOnPaintBox read FOnCustomDrawBox write FOnCustomDrawBox; property OnBeforePaintBoxes: TNotifyEvent read FOnBeforePaintBoxes write FOnBeforePaintBoxes; property OnAfterPaintBoxes: TNotifyEvent read FOnAfterPaintBoxes write FOnAfterPaintBoxes; property OnBoxClick: TProcOnBoxClick read FOnBoxClick write FOnBoxClick; end; procedure Register; implementation { TcyColorMatrix } constructor TcyColorMatrix.Create(AOwner: TComponent); begin inherited Create(AOwner); FBackground := clBlack; FDefaultColor := clGreen; FBoxHeight := 5; FBoxWidth := 5; FBoxRows := 30; FBoxCols := 30; FBoxIntervalX := 1; FBoxIntervalY := 1; FBoxFrameWidth := 0; FBoxFrameColor := clGray; FTransparent := false; SetLength(FColorList, FBoxCols, FBoxRows); InitializeColors(0, 0); Autosize:= true; end; destructor TcyColorMatrix.Destroy; begin inherited Destroy; end; procedure TcyColorMatrix.Loaded; begin Inherited; SetLength(FColorList, FBoxCols, FBoxRows); InitializeColors(0, 0); end; procedure TcyColorMatrix.InitializeColors(fromRow, fromCol: Integer); var r, c: Integer; begin for c := fromCol to FBoxCols - 1 do for r := fromRow to FBoxRows - 1 do FColorList[c, r] := FDefaultColor; end; procedure TcyColorMatrix.Paint; begin // Draw background: if not FTransparent then begin Canvas.Brush.Color := FBackground; Canvas.FillRect(ClientRect); end; if Assigned(FOnBeforePaintBoxes) then FOnBeforePaintBoxes(Self); PaintBoxes(true, 0); if Assigned(FOnAfterPaintBoxes) then FOnAfterPaintBoxes(Self); end; procedure TcyColorMatrix.PaintBoxes(AllColors: Boolean; paramColor: TColor); var r, c, xPos, yPos: integer; CurColor: TColor; BoxRect: TRect; CustomDrawBox: Boolean; function PaintThisOne: Boolean; begin if AllColors then RESULT := true else RESULT := CurColor = paramColor; end; begin CustomDrawBox := Assigned(FOnCustomDrawBox); yPos := FBoxIntervalY; for r := 0 to FBoxRows -1 do begin xPos := FBoxIntervalX; for c := 0 to FBoxCols -1 do begin CurColor := FColorList[c, r]; if PaintThisOne then begin BoxRect := classes.Rect(xPos, yPos, xPos + FBoxWidth, yPos + FBoxHeight); PaintBox(BoxRect, CurColor, r, c, CustomDrawBox); end; inc(xPos, FBoxWidth + FBoxIntervalX); end; inc(yPos, FBoxHeight + FBoxIntervalY); end; end; procedure TcyColorMatrix.PaintBox(var BoxRect: TRect; BoxColor: TColor; Row, Column: Integer; CustomDrawBox: Boolean); begin if CustomDrawBox then FOnCustomDrawBox(self, BoxRect, Row, Column, BoxColor) else DefaultDrawBox(BoxRect, Row, Column, BoxColor); end; function TcyColorMatrix.PartialPaint: Boolean; begin RESULT := false; if not Assigned(FOnBeforePaintBoxes) then if not Assigned(FOnAfterPaintBoxes) then RESULT := true; end; procedure TcyColorMatrix.SetAutoSize(Value: Boolean); begin if AutoSize <> Value then begin inherited SetAutoSize(Value); // Change Autosize value ... RedefineSize; end; end; procedure TcyColorMatrix.RedefineSize; begin if AutoSize then begin Width := FBoxIntervalX + FBoxCols * (FBoxWidth + FBoxIntervalX); Height := FBoxIntervalY + FBoxRows * (FBoxHeight + FBoxIntervalY); end; end; procedure TcyColorMatrix.SetBackground(const Value: TColor); begin FBackground := Value; Invalidate; end; procedure TcyColorMatrix.SetBoxCols(const Value: integer); var oldCols: Integer; begin oldCols := FBoxCols; FBoxCols := Value; SetLength(FColorList, FBoxCols, FBoxRows); InitializeColors(0, oldCols); RedefineSize; Invalidate; end; procedure TcyColorMatrix.SetBoxRows(const Value: integer); var oldRows: Integer; begin oldRows := FBoxRows; FBoxRows := Value; SetLength(FColorList, FBoxCols, FBoxRows); InitializeColors(oldRows, 0); RedefineSize; Invalidate; end; procedure TcyColorMatrix.SetBoxFrameColor(const Value: TColor); begin FBoxFrameColor := Value; Invalidate; end; procedure TcyColorMatrix.SetBoxFrameWidth(const Value: integer); begin FBoxFrameWidth := Value; Invalidate; end; procedure TcyColorMatrix.SetBoxHeight(const Value: integer); begin FBoxHeight := Value; RedefineSize; Invalidate; end; procedure TcyColorMatrix.SetBoxIntervalX(const Value: integer); begin FBoxIntervalX := Value; RedefineSize; Invalidate; end; procedure TcyColorMatrix.SetBoxIntervalY(const Value: integer); begin FBoxIntervalY := Value; RedefineSize; Invalidate; end; procedure TcyColorMatrix.SetBoxWidth(const Value: integer); begin FBoxWidth := Value; RedefineSize; Invalidate; end; procedure TcyColorMatrix.SetDefaultColor(const Value: TColor); begin SubstColor(FDefaultColor, Value, true); FDefaultColor := Value; Invalidate; end; procedure TcyColorMatrix.SetTransparent(const Value: Boolean); begin FTransparent := Value; Invalidate; end; function TcyColorMatrix.GetBoxAtPos(aPoint: TPoint; var aRow: Integer; var aCol: Integer; ExactPos: Boolean): Boolean; function VerifyIntervals: Boolean; begin RESULT := false; if (aCol >= 0) and (aCol < FBoxCols) then if (aRow >= 0) and (aRow < FBoxRows) then RESULT := true; end; begin RESULT := false; aCol := (aPoint.X - FBoxIntervalX div 2) div (FBoxWidth + FBoxIntervalX); aRow := (aPoint.Y - FBoxIntervalY div 2) div (FBoxHeight + FBoxIntervalY); if ExactPos then begin if aPoint.X >= (FBoxWidth + FBoxIntervalX) * aCol + FBoxIntervalX then if aPoint.X <= (FBoxWidth + FBoxIntervalX) * (aCol + 1) then if aPoint.Y >= (FBoxHeight + FBoxIntervalY) * aRow + FBoxIntervalY then if aPoint.Y <= (FBoxHeight + FBoxIntervalY) * (aRow + 1) then RESULT := VerifyIntervals; end else RESULT := VerifyIntervals; end; function TcyColorMatrix.GetColorGrid(aRow: Integer; aCol: integer): TColor; begin RESULT := FColorList[aCol, aRow]; end; procedure TcyColorMatrix.SetColorGrid(aRow: Integer; aCol: integer; aColor: TColor; FullRepaint: Boolean); var BoxRect: TRect; begin FColorList[aCol, aRow] := aColor; if FullRepaint then // More rapid but with blink effect if not doublebuffered ... Invalidate else begin // Avoid full repaint but with blinking effect ... BoxRect := classes.Rect(FBoxIntervalX + (FBoxWidth+FBoxIntervalX)*aCol, FBoxIntervalY + (FBoxHeight+FBoxIntervalY)*aRow, FBoxIntervalX + (FBoxWidth+FBoxIntervalX)*aCol + FBoxWidth, FBoxIntervalY + (FBoxHeight+FBoxIntervalY)*aRow + FBoxHeight); PaintBox(BoxRect, aColor, aRow, aCol, Assigned(FOnCustomDrawBox)); end; end; procedure TcyColorMatrix.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; end; procedure TcyColorMatrix.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FptMouseDown := Point(X, Y); inherited; end; procedure TcyColorMatrix.Click; var aRow, aCol: integer; begin if Assigned(FOnBoxClick) then if GetBoxAtPos(FptMouseDown, aRow, aCol, true) then FOnBoxClick(Self, aRow, aCol, FColorList[aCol, aRow]); Inherited; end; procedure TcyColorMatrix.SubstColor(old, New: TColor; FullRepaint: Boolean); var BoxRect: TRect; r, c: Integer; begin if FullRepaint // More rapid but with blink effect if not doublebuffered ... then begin for c := 0 to FBoxCols - 1 do for r := 0 to FBoxRows - 1 do if FColorList[c, r] = Old then FColorList[c, r] := New; Invalidate; end else begin // Avoid full repaint but with blinking effect ... for c := 0 to FBoxCols - 1 do for r := 0 to FBoxRows - 1 do if FColorList[c, r] = Old then begin FColorList[c, r] := New; BoxRect := classes.Rect(FBoxIntervalX + (FBoxWidth+FBoxIntervalX) * c, FBoxIntervalY + (FBoxHeight+FBoxIntervalY) * r, FBoxIntervalX + (FBoxWidth+FBoxIntervalX) * c + FBoxWidth, FBoxIntervalY + (FBoxHeight+FBoxIntervalY) * r + FBoxHeight); PaintBox(BoxRect, New, r, c, Assigned(FOnCustomDrawBox)); end; end; end; procedure TcyColorMatrix.DefaultDrawBox(var aRect: TRect; aRow, aCol: integer; aColor: TColor); begin if FBoxHeight = 1 then begin if FBoxWidth = 1 then begin // Draw a point : Canvas.Pixels[aRect.Left, aRect.Top] := aColor; end else begin // Draw horizontal line : Canvas.Brush.Color := aColor; Canvas.FillRect(aRect); end; end else begin if FBoxWidth = 1 then begin // Draw vertical line : Canvas.Brush.Color := aColor; Canvas.FillRect(aRect); end else case FBoxFrameWidth of 0 : begin Canvas.Brush.Color := aColor; Canvas.FillRect(aRect); // FillRect() is more rapid than rectangle() end; 1 : begin Canvas.Brush.Color := aColor; Canvas.Pen.Width := FBoxFrameWidth; Canvas.Pen.Color := FBoxFrameColor; Canvas.Rectangle(aRect); end; else begin Canvas.Brush.Color := FBoxFrameColor; Canvas.FillRect(aRect); // Draw rectangle inside aRect : aRect := classes.Rect(aRect.Left + FBoxFrameWidth, aRect.Top + FBoxFrameWidth, aRect.Right - FBoxFrameWidth, aRect.Bottom - FBoxFrameWidth); Canvas.Brush.Color := aColor; Canvas.FillRect(aRect); end; end; end; end; procedure Register; begin RegisterComponents('Cindy', [TcyColorMatrix]); end; end.
unit uBase; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.ImgList, Data.Win.ADODB, uDMConnection, uMainDataSet, System.Actions, Vcl.ActnList, Vcl.Menus, Vcl.ExtCtrls, uBaseCustom, RxMenus, Datasnap.Provider; type TBase = class(TBaseCustom) imgListBase: TImageList; MainDataSource: TDataSource; MainActionList: TActionList; acNew: TAction; acEdit: TAction; acDelete: TAction; MainMenuDef: TRxMainMenu; acRefresh: TAction; procedure acRefreshExecute(Sender: TObject); procedure acRefreshUpdate(Sender: TObject); private FMainDataSet: TMainDataSet; FMainTransferDataSet: TADODataSet; FMainProvider: TDataSetProvider; FADOConnection: TADOConnection; protected procedure DoBeforeCreate; procedure DoAfterCreate; virtual; procedure DoPrepare; virtual; procedure DoValidate; virtual; procedure DoShow; override; function DoSave: Boolean; virtual; function AddMenuItem(const aAction: TBasicAction; const aCaption: string; const aIcon: TImage = nil): TMenuItem; virtual; procedure CreateBaseMenuDef; virtual; procedure CreateBaseToolBarDef; public property MainDataSet: TMainDataSet read FMainDataSet write FMainDataSet; property MainConnection: TADOConnection read FADOConnection; constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; aMainDataSet: TMainDataSet); reintroduce; overload; virtual; destructor Destroy; override; end; implementation uses uImageConsts, Vcl.ComCtrls, Datasnap.DBClient, uBase_G, uBase_E; {$R *.dfm} procedure TBase.acRefreshExecute(Sender: TObject); begin inherited; if Assigned(FMainTransferDataSet) and FMainTransferDataSet.Active and Assigned(MainDataSet) and MainDataSet.Active then begin if (Sender is TBase_G) and ((Sender as TBase_G).EditFormInstance.FormState = esInsert) then begin FMainTransferDataSet.Close; FMainTransferDataSet.Open; MainDataSet.ReloadData; end else begin FMainTransferDataSet.Refresh; MainDataSet.Refresh; end; end; end; procedure TBase.acRefreshUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled := MainDataSet.Active; end; function TBase.AddMenuItem(const aAction: TBasicAction; const aCaption: string; const aIcon: TImage): TMenuItem; begin (*** Add item to toolbar menu ***) Result := nil; end; constructor TBase.Create(AOwner: TComponent; aMainDataSet: TMainDataSet); begin (*** It must pass DataSet ***) DoBeforeCreate; inherited Create(AOwner); if not Assigned(aMainDataSet) then raise Exception.Create('V konstruktoru nebyl předán DataSet') else begin FMainDataSet := TMainDataSet.Create(Self); FMainTransferDataSet := TADODataSet.Create(Self); FMainTransferDataSet.Connection := DMConnection.MSSQLConnection; FMainTransferDataSet.CommandType := cmdText; FMainTransferDataSet.CommandText := aMainDataSet.CommandText; FMainTransferDataSet.Open; FMainProvider := TDataSetProvider.Create(Self); FMainProvider.Name := 'MainProvider'; FMainProvider.DataSet := FMainTransferDataSet; FMainDataSet.ProviderName := FMainProvider.Name; MainDataSource.DataSet := FMainDataSet; end; DoAfterCreate; end; procedure TBase.CreateBaseMenuDef; begin end; procedure TBase.CreateBaseToolBarDef; begin (*** Create base toolbar ***) if MainMenuDef.Items.Count > 0 then begin with TToolBar.Create(Self) do begin Parent := Self; Align := alTop; Menu := MainMenuDef; end; end; end; destructor TBase.Destroy; begin FreeAndNil(FMainTransferDataSet); FreeAndNil(FMainProvider); inherited; end; procedure TBase.DoAfterCreate; begin (*** Action after create form ***) CreateBaseMenuDef; CreateBaseToolBarDef; if Assigned(MainDataSource) then begin FMainDataSet.Open; end; end; procedure TBase.DoBeforeCreate; begin (*** Action before create form ***) end; procedure TBase.DoPrepare; begin (*** Action after DoAfterCreate and before DoShow ***) end; function TBase.DoSave: Boolean; begin (*** Action for save actual data on the form ***) Result := False; end; procedure TBase.DoShow; begin DoPrepare; inherited; end; procedure TBase.DoValidate; begin end; constructor TBase.Create(AOwner: TComponent); begin inherited Create(AOwner); end; end.
inherited dmComissaoVendedores: TdmComissaoVendedores OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWOPETPCOM' ' (CGC, CODIGO, COMISSAO_BASE, VND_VALIDADE, VND_CONDICAO, VND_C' + 'OMISSAO, VND_GARANTIA, DT_ALTERACAO, OPERADOR)' 'VALUES' ' (:CGC, :CODIGO, :COMISSAO_BASE, :VND_VALIDADE, :VND_CONDICAO, ' + ':VND_COMISSAO, :VND_GARANTIA, :DT_ALTERACAO, :OPERADOR)') SQLDelete.Strings = ( 'DELETE FROM STWOPETPCOM' 'WHERE' ' CGC = :Old_CGC AND CODIGO = :Old_CODIGO') SQLUpdate.Strings = ( 'UPDATE STWOPETPCOM' 'SET' ' CGC = :CGC, CODIGO = :CODIGO, COMISSAO_BASE = :COMISSAO_BASE, ' + 'VND_VALIDADE = :VND_VALIDADE, VND_CONDICAO = :VND_CONDICAO, VND_' + 'COMISSAO = :VND_COMISSAO, VND_GARANTIA = :VND_GARANTIA, DT_ALTER' + 'ACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR' 'WHERE' ' CGC = :Old_CGC AND CODIGO = :Old_CODIGO') SQLRefresh.Strings = ( 'SELECT CGC, CODIGO, COMISSAO_BASE, VND_VALIDADE, VND_CONDICAO, V' + 'ND_COMISSAO, VND_GARANTIA, DT_ALTERACAO, OPERADOR FROM STWOPETPC' + 'OM' 'WHERE' ' CGC = :Old_CGC AND CODIGO = :Old_CODIGO') SQLLock.Strings = ( 'SELECT NULL FROM STWOPETPCOM' 'WHERE' 'CGC = :Old_CGC AND CODIGO = :Old_CODIGO' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT' ' COM.CGC,' ' COM.CODIGO,' ' COM.COMISSAO_BASE,' ' COM.VND_VALIDADE,' ' COM.VND_CONDICAO,' ' COM.VND_COMISSAO,' ' COM.VND_GARANTIA,' ' COM.DT_ALTERACAO,' ' COM.OPERADOR,' ' SERV.SERVICO NM_SERVICO' 'FROM STWOPETPCOM COM' 'LEFT JOIN STWOPETSERV SERV ON SERV.CODIGO = COM.CODIGO') object qryManutencaoCGC: TStringField FieldName = 'CGC' Required = True Size = 18 end object qryManutencaoCODIGO: TIntegerField FieldName = 'CODIGO' Required = True end object qryManutencaoCOMISSAO_BASE: TFloatField FieldName = 'COMISSAO_BASE' end object qryManutencaoVND_VALIDADE: TSmallintField FieldName = 'VND_VALIDADE' end object qryManutencaoVND_CONDICAO: TStringField FieldName = 'VND_CONDICAO' Size = 1 end object qryManutencaoVND_COMISSAO: TFloatField FieldName = 'VND_COMISSAO' end object qryManutencaoVND_GARANTIA: TFloatField FieldName = 'VND_GARANTIA' end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoNM_SERVICO: TStringField FieldName = 'NM_SERVICO' ProviderFlags = [] Size = 30 end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT' ' COM.CGC,' ' COM.CODIGO,' ' COM.COMISSAO_BASE,' ' COM.VND_VALIDADE,' ' COM.VND_CONDICAO,' ' COM.VND_COMISSAO,' ' COM.VND_GARANTIA,' ' COM.DT_ALTERACAO,' ' COM.OPERADOR,' ' SERV.SERVICO NM_SERVICO' 'FROM STWOPETPCOM COM' 'LEFT JOIN STWOPETSERV SERV ON SERV.CODIGO = COM.CODIGO') object qryLocalizacaoCGC: TStringField FieldName = 'CGC' Required = True Size = 18 end object qryLocalizacaoCODIGO: TIntegerField FieldName = 'CODIGO' Required = True end object qryLocalizacaoCOMISSAO_BASE: TFloatField FieldName = 'COMISSAO_BASE' end object qryLocalizacaoVND_VALIDADE: TSmallintField FieldName = 'VND_VALIDADE' end object qryLocalizacaoVND_CONDICAO: TStringField FieldName = 'VND_CONDICAO' Size = 1 end object qryLocalizacaoVND_COMISSAO: TFloatField FieldName = 'VND_COMISSAO' end object qryLocalizacaoVND_GARANTIA: TFloatField FieldName = 'VND_GARANTIA' end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoNM_SERVICO: TStringField FieldName = 'NM_SERVICO' ReadOnly = True Size = 30 end end inherited updManutencao: TIBCUpdateSQL InsertSQL.Strings = ( 'INSERT INTO STWOPETVEI (FROTA, CGC_PRO, MOTORISTA, TIPO, MARCA, ' + 'ANO, PLACA, CHASSIS, CERTIFIC, COR_CAV, COR_CAR, CAPAC, ALIENACA' + 'O, SEGURO, DT_SEG, MODELO, TIPO_CAR, CID_VEIC, UF_VEIC, COMBUSTI' + 'VEL, QTD_EIXOS, ALTURA, LARGURA, COMPRIMENTO, TARA, CAPAC_M3, NR' + 'O_MOTOR, RENAVAM, ODOMETRO, CARRO_PROPRIO, DT_ALTERACAO, OPERADO' + 'R, BLOQUEADO, MONITORAMENTO, PROVEDOR_TEC, ATIVO)' 'VALUES (:FROTA, :CGC_PRO, :MOTORISTA, :TIPO, :MARCA, :ANO, :PLAC' + 'A, :CHASSIS, :CERTIFIC, :COR_CAV, :COR_CAR, :CAPAC, :ALIENACAO, ' + ':SEGURO, :DT_SEG, :MODELO, :TIPO_CAR, :CID_VEIC, :UF_VEIC, :COMB' + 'USTIVEL, :QTD_EIXOS, :ALTURA, :LARGURA, :COMPRIMENTO, :TARA, :CA' + 'PAC_M3, :NRO_MOTOR, :RENAVAM, :ODOMETRO, :CARRO_PROPRIO, :DT_ALT' + 'ERACAO, :OPERADOR, :BLOQUEADO, :MONITORAMENTO, :PROVEDOR_TEC, :A' + 'TIVO)') DeleteSQL.Strings = ( 'DELETE FROM STWOPETVEI' 'WHERE (FROTA = :FROTA)') ModifySQL.Strings = ( 'UPDATE STWOPETVEI' 'SET CGC_PRO = :CGC_PRO,' ' MOTORISTA = :MOTORISTA,' ' TIPO = :TIPO,' ' MARCA = :MARCA,' ' ANO = :ANO,' ' PLACA = :PLACA,' ' CHASSIS = :CHASSIS,' ' CERTIFIC = :CERTIFIC,' ' COR_CAV = :COR_CAV,' ' COR_CAR = :COR_CAR,' ' CAPAC = :CAPAC,' ' ALIENACAO = :ALIENACAO,' ' SEGURO = :SEGURO,' ' DT_SEG = :DT_SEG,' ' MODELO = :MODELO,' ' TIPO_CAR = :TIPO_CAR,' ' CID_VEIC = :CID_VEIC,' ' UF_VEIC = :UF_VEIC,' ' COMBUSTIVEL = :COMBUSTIVEL,' ' QTD_EIXOS = :QTD_EIXOS,' ' ALTURA = :ALTURA,' ' LARGURA = :LARGURA,' ' COMPRIMENTO = :COMPRIMENTO,' ' TARA = :TARA,' ' CAPAC_M3 = :CAPAC_M3,' ' NRO_MOTOR = :NRO_MOTOR,' ' RENAVAM = :RENAVAM,' ' ODOMETRO = :ODOMETRO,' ' CARRO_PROPRIO = :CARRO_PROPRIO,' ' DT_ALTERACAO = :DT_ALTERACAO,' ' OPERADOR = :OPERADOR,' ' BLOQUEADO = :BLOQUEADO,' ' MONITORAMENTO = :MONITORAMENTO,' ' PROVEDOR_TEC = :PROVEDOR_TEC,' ' ATIVO = :ATIVO' 'WHERE (FROTA = :FROTA)') end end
program TESTSTA3 ( OUTPUT ) ; //************************************************************************************* //$A+,X+ //************************************************************************************* // assignment to const compenent inside with should throw error //------------------------------------------------------------------------------------- // in withstatement: insert information about constant in display entry // in selector: return information about component being constant to caller // then assignment (for example) can throw error, when assignment to constant is done // and same for passing to var parameters etc. //************************************************************************************* type TESTREC = record A : INTEGER ; B : STRING ( 10 ) ; C : INTEGER ; end ; const C = 17 ; C1 : INTEGER = 27 ; C2 : DECIMAL ( 7 , 2 ) = 12.5 ; C3 : BOOLEAN = TRUE ; C4 : CHAR ( 10 ) = 'HUGO' ; C5 : STRING ( 20 ) = 'TESTSTRING' ; F : array [ 1 .. 5 ] of CHAR = ( 'a' , 'b' , 'c' ) ; XC : record A : INTEGER ; B : INTEGER end = ( 12 , 15 ) ; CNEU = C ; FNEU = F ; CT : TESTREC = ( 2 , 'BERND' , 12 ) ; CM1 , CM2 : TESTREC = ( 2 , 'BERND' , 12 ) ; CM3 , CM4 = 47 ; CM5 = CM3 ; CM6 : TESTREC = CM1 ; CM7 : TESTREC = ( C , 'HUGO' , C ) ; CM8 = CM1 ; XX : array [ 1 .. 5 ] of TESTREC = ( CM1 , CM7 , CM2 , CM7 , CM1 ) ; YY : record PART1 : TESTREC ; PART2 : TESTREC end = ( CM1 , CM7 ) ; var X : array [ 1 .. 14 ] of INTEGER ; I : INTEGER ; CV : INTEGER := 5 ; V1 : INTEGER = 27 ; V2 : DECIMAL ( 7 , 2 ) = 12.5 ; V3 : BOOLEAN = TRUE ; V4 : CHAR ( 10 ) = 'HUGO' ; V5 : STRING ( 20 ) = 'TESTSTRING' ; VX : array [ 1 .. 14 ] of INTEGER = ( 2 , 3 , 5 , 7 , 11 , 13 ) ; VREC1 , VREC2 : TESTREC := ( 1 , 'BERND' , 7 ) ; VT : TESTREC = CT ; VVS , VVS2 : record A : INTEGER ; B : INTEGER end := ( 12 , 15 ) ; static S1 : INTEGER = 27 ; S2 : DECIMAL ( 7 , 2 ) = 12.5 ; S3 : BOOLEAN = TRUE ; S4 : CHAR ( 10 ) = 'HUGO' ; S5 : STRING ( 20 ) = 'TESTSTRING' ; SX : array [ 1 .. 14 ] of INTEGER = ( 2 , 3 , 5 , 7 , 11 , 13 ) ; SREC1 , SREC2 : TESTREC := ( 1 , 'BERND' , 7 ) ; ST : TESTREC = CM7 ; SVS , SVS2 : record A : INTEGER ; B : INTEGER end := ( 12 , 15 ) ; begin (* HAUPTPROGRAMM *) WRITELN ( 'cm1.a = ' , CM1 . A , ' (should be 2)' ) ; WRITELN ( 'cm2.a = ' , CM2 . A , ' (should be 2)' ) ; WRITELN ( 'cm3 = ' , CM3 , ' (should be 47)' ) ; WRITELN ( 'cm4 = ' , CM4 , ' (should be 47)' ) ; WRITELN ( 'cm5 = ' , CM5 , ' (should be 47)' ) ; WRITELN ( 'cm6.a = ' , CM6 . A , ' (should be 2)' ) ; WRITELN ( 'cm7.a = ' , CM7 . A , ' (should be 17)' ) ; WRITELN ( 'cm7.c = ' , CM7 . C , ' (should be 17)' ) ; WRITELN ( 'cm8.a = ' , CM8 . A , ' (should be 2)' ) ; for I := 1 to 5 do WRITE ( XX [ I ] . A ) ; WRITELN ; WRITELN ( 'yy.1 = ' , YY . PART1 . A , ' (should be 2)' ) ; WRITELN ( 'yy.2 = ' , YY . PART2 . A , ' (should be 17)' ) ; WRITELN ( C1 , C2 , ' ' , C3 , ' ' , C4 , C5 ) ; WRITELN ( S1 , S2 , ' ' , S3 , ' ' , S4 , S5 ) ; for I := 1 to 14 do WRITE ( SX [ I ] : 3 ) ; WRITELN ; for I := 1 to 14 do WRITE ( VX [ I ] : 3 ) ; WRITELN ; WRITE ( 'array f = ' ) ; for I := 1 to 5 do WRITE ( F [ I ] : 3 ) ; WRITELN ; WRITE ( 'array fneu = ' ) ; for I := 1 to 5 do WRITE ( FNEU [ I ] : 3 ) ; WRITELN ; WRITELN ( 'srec1 = ' , SREC1 . A , ' ' , SREC1 . B : - 10 , SREC1 . C ) ; WRITELN ( 'srec2 = ' , SREC2 . A , ' ' , SREC2 . B : - 10 , SREC2 . C ) ; WRITELN ( 'vrec1 = ' , VREC1 . A , ' ' , VREC1 . B : - 10 , VREC1 . C ) ; WRITELN ( 'vrec2 = ' , VREC2 . A , ' ' , VREC2 . B : - 10 , VREC2 . C ) ; WRITELN ( 'svs = ' , SVS . A , SVS . B ) ; WRITELN ( 'svs2 = ' , SVS2 . A , SVS2 . B ) ; for I := 1 to 14 do X [ I ] := 0 ; V5 := '' ; WRITELN ( V1 , V2 , ' ' , V3 , ' ' , V4 , V5 ) ; WRITELN ( 'vvs = ' , VVS . A , VVS . B ) ; WRITELN ( 'vvs2 = ' , VVS2 . A , VVS2 . B ) ; WRITELN ( 'cv = ' , CV , ' (should be 5)' ) ; with VVS do A := C ; WRITELN ( 'vvs = ' , VVS . A , VVS . B ) ; WRITELN ( 'vvs2 = ' , VVS2 . A , VVS2 . B ) ; WRITELN ( 'vt = ' , VT . A , ' ' , VT . B : - 10 , VT . C ) ; WRITELN ( 'st = ' , ST . A , ' ' , ST . B : - 10 , ST . C ) ; //******************************** // compiler should complain here // and not modify the constant //******************************** C := 15 ; WRITELN ( 'c = ' , C , ' (should be 17)' ) ; WRITELN ( 'cneu = ' , CNEU ) ; CV := 7 ; WRITELN ( 'cv = ' , CV ) ; SVS . A := 27 ; //******************************** // compiler should complain here // and not modify the constant //******************************** XC . A := SVS . A ; WRITELN ( 'xc.a = ' , XC . A , ' (should be 12)' ) ; //******************************** // compiler should complain here // and not modify the constant //******************************** with XC do A := SVS . A ; WRITELN ( 'xc.a = ' , XC . A , ' (should be 12)' ) ; WRITELN ( 'xc.b = ' , XC . B ) ; end (* HAUPTPROGRAMM *) .
{ *************************************************************************** } { } { Gnostice Shared Visual Component Library } { } { Copyright © 2002-2008 Gnostice Information Technologies Private Limited } { http://www.gnostice.com } { } { *************************************************************************** } {$I ..\gtSharedDefines.inc} unit gtClasses3; interface uses Classes, SysUtils {$IFDEF gtActiveX} , Controls, Graphics, Buttons {$ENDIF}; Type TgtException = class(Exception) public ErrorCode: Integer; end; CharSet = set of AnsiChar; EInvalidID = class(TgtException); EInvalidStream = class(TgtException); EReadError = class(TgtException); EWriteError = class(TgtException); TWString = record WString: WideString; end; TWideStrings = class private FWideStringList: TList; function Get(Index: Integer): WideString; procedure Put(Index: Integer; const S: WideString); public constructor Create; destructor Destroy; override; function Count: Integer; procedure Clear; function Add(const S: WideString): Integer; function Delete(Index: Integer): WideString; function IndexOf(const S: WideString): Integer; function IndexOfIgnoreCase(const S: WideString): Integer; procedure Insert(Index: Integer; const S: WideString); procedure SetTextStr(const Value: WideString); procedure LoadFromFile(const FileName: WideString); procedure LoadFromStream(Stream: TStream); property Strings[Index: Integer]: WideString read Get write Put; default; end; { TgtExtMemStream } TgtExtMemStream = Class(TMemoryStream) private FPadSize : Int64; public property PadSize: Int64 read FPadSize write FPadSize; constructor Create; procedure PadTo4Bytes; function SkipBytes(ANumBytes : Integer) : Integer; function ReadByte : Byte; function ReadLong : Integer; function ReadULong : Cardinal; function ReadShort : SmallInt; function ReadUShort : Word; function ReadString(ALength : Integer) : AnsiString; procedure ReadByteArray(AByteArray : array of Byte; AOffset, ALength : Integer); procedure WriteByte(AByte: Byte); procedure WriteLong(ALong : Integer); procedure WriteULong(AULong : Cardinal); procedure WriteShort(AShort : SmallInt); procedure WriteUShort(AUShort : Word); procedure WriteString(AString : AnsiString); procedure WriteByteArray(AByteArray : array of Byte); procedure WriteUShortArray(AUShortArray: array of Word); procedure WriteULongArray(AULongArray : array of Cardinal); end; { TgtBaseComponent } {$IFDEF gtActiveX} TgtBaseComponent = class(TCustomControl) {$ELSE} TgtBaseComponent = class(TComponent) {$ENDIF} private FAbout: String; FVersion: String; {$IFDEF gtActiveX} FIconBmp: TBitmap; function GetControlCanvas: TCanvas; {$ENDIF} procedure SetAbout(const Value: String); procedure SetVersion(const Value: String); protected {$IFDEF gtActiveX} property ControlCanvas: TCanvas read GetControlCanvas; property IconBmp: TBitmap read FIconBmp write FIconBmp; {$ENDIF} public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {$IFDEF gtActiveX} procedure Paint; override; {$ENDIF} published property About: String read FAbout write SetAbout; property Version: String read FVersion write SetVersion; end; { TgtReadOnlyFilter } TgtReadOnlyFilter = class(TStream) private FSize: Longint; FStream: TStream; public constructor Create(aStream: TStream); function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; property Stream: TStream read FStream; end; { TgtWriteOnlyFilter } TgtWriteOnlyFilter = class(TStream) private FStream: TStream; public constructor Create(aStream: TStream); function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function CopyFrom(Source: TStream; Count: Int64): Int64; property Stream: TStream read FStream; end; { TgtRandomAccessFilter } TgtRandomAccessFilter = class(TgtReadOnlyFilter) private FPeekLastChar: Boolean; public function PeekChar: Char; function PeekString(Count: Longint): String; function ReadChar: Char; function ReadString(Count: Longint): String; function ReadOffset(var Buffer; FromOffset, ToOffset: Longint): Longint; function Skip(Count: Longint): Longint; procedure PushBackChar; procedure IncPos(Count: Integer); property PeekLastChar: Boolean read FPeekLastChar; end; { TgtObjectList } TgtObjectList = class; PObjectItem = ^TgtObjectItem; TgtObjectItem = record FInteger: Integer; FObject: TObject; end; PObjectItemList = ^TgtObjectItemList; {$IFDEF WIN32} TgtObjectItemList = array[0..MaxListSize] of TgtObjectItem; {$ENDIF} {$IFDEF WIN64} TgtObjectItemList = array[0..134217726] of TgtObjectItem; {$ENDIF} TgtObjectList = class(TPersistent) private FList: PObjectItemList; FCount: Integer; FCapacity: Integer; procedure Grow; function GetCapacity: Integer; function GetCount: Integer; function GetObject(Index: Integer): TObject; procedure SetCapacity(NewCapacity: Integer); function GetItem(Index: Integer): TgtObjectItem; public destructor Destroy; override; function Add(ANo: Integer; AObject: TObject): Integer; overload; procedure Add(AObjectList: TgtObjectList); overload; procedure Clear; procedure Delete(Index: Integer); function IndexOf(const ObjectNo: Integer): Integer; procedure InsertItem(Index: Integer; ANo: Integer; AObject: TObject); property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount; property Objects[Index: Integer]: TObject read GetObject; default; property Items[Index: Integer]: TgtObjectItem read GetItem; end; //Exception type for improper image format and Unsupported Background Display type EImageExceptions=class(Exception); ExInvalidImageFormat = class(EImageExceptions); ExUnsupportedBackgroundDisplayType = class(EImageExceptions); resourcestring SInvalidID = 'Invalid unique ID (%d)'; SNullStreamError = 'Invalid Stream! Cannot create with null stream'; SWriteError = 'A read-only filter cannot write'; SReadError = 'A write-only filter cannot read'; SInvalidOffset = 'Invalid offset specified'; SSkipCount = 'Skip count exceeds Stream Size'; SListIndexOutOfBounds = 'List index out of bounds (%d)'; ErrInvalidImageFormat = 'Invalid Image Format'; ErrUnsupportedBackgroundDisplayType = 'Unsupported Background Display Type '; //const AX_SIZE = 28; //{$IFDEF gtDelphi5} // soBeginning = 0; // soCurrent = 1; // soEnd = 2; //{$ENDIF} implementation function InOpSet(W: WideChar; const Sets: CharSet): Boolean; begin if W <= #$FF then Result := AnsiChar(W) in Sets else Result := False; end; { TgtBaseComponent } constructor TgtBaseComponent.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF gtActiveX} FIconBmp := TBitmap.Create; FIconBmp.Transparent := True; FIconBmp.TransparentMode := tmAuto; SetBounds(Left, Top, AX_SIZE, AX_SIZE); Constraints.MinHeight := AX_SIZE; Constraints.MinWidth := AX_SIZE; Constraints.MaxHeight := AX_SIZE; Constraints.MaxWidth := AX_SIZE; {$ENDIF} end; destructor TgtBaseComponent.Destroy; begin {$IFDEF gtActiveX} FreeAndNil(FIconBmp); {$ENDIF} inherited; end; {$IFDEF gtActiveX} procedure TgtBaseComponent.Paint; begin inherited; DrawButtonFace(Canvas, Rect(0, 0, AX_SIZE, AX_SIZE), 1, bsNew, False, False, True); end; function TgtBaseComponent.GetControlCanvas: TCanvas; begin Result := Canvas; end; {$ENDIF} procedure TgtBaseComponent.SetAbout(const Value: String); begin end; procedure TgtBaseComponent.SetVersion(const Value: String); begin end; { TgtExtMemStream } constructor TgtExtMemStream.Create; begin inherited Create; Position := 0; PadSize := 0; end; procedure TgtExtMemStream.PadTo4Bytes; var I : Integer; Zero : Integer; begin Zero := 0; Position := Size; I := (4 - (Size mod 4)); if I <> 4 then Write(Zero, I); if I = 4 then PadSize := 0 else PadSize := I; end; function TgtExtMemStream.ReadByte: Byte; begin Read(Result, 1); end; procedure TgtExtMemStream.ReadByteArray(AByteArray: array of Byte; AOffset, ALength: Integer); var N, Cnt : Integer; begin N := 0; repeat Position := Position + (AOffset + N); Cnt := Read(AByteArray, ALength - N); if (Cnt < 0) then Exit; N := N + Cnt; until (N >= ALength); end; function TgtExtMemStream.ReadLong: Integer; var I : array[0..3] of Byte; begin Read(I, 4); Result := Integer(I[0] shl 24) + (I[1] shl 16) + (I[2] shl 8) + I[3]; end; function TgtExtMemStream.ReadShort: SmallInt; var I : array[0..1] of Byte; begin Read(I, 2); Result := SmallInt((I[0] shl 8) + I[1]); end; function TgtExtMemStream.ReadString(ALength: Integer): AnsiString; begin SetLength(Result, ALength); Read(Result[1], ALength); end; function TgtExtMemStream.ReadULong: Cardinal; var I : array[0..3] of Byte; begin Read(I, 4); Result := Cardinal((I[0] shl 24) + (I[1] shl 16) + (I[2] shl 8) + I[3]); end; function TgtExtMemStream.ReadUShort: Word; var I : array[0..1] of Byte; begin Read(I, 2); Result := Word((I[0] shl 8) + I[1]); end; function TgtExtMemStream.SkipBytes(ANumBytes: Integer): Integer; var NewPos : Integer; begin NewPos := Position + ANumBytes; if (NewPos > Size) then NewPos := Size else if (NewPos < 0) then NewPos := 0; Position := NewPos; Result := NewPos - Position; end; procedure TgtExtMemStream.WriteByte(AByte: Byte); begin Write(AByte, 1); end; procedure TgtExtMemStream.WriteByteArray(AByteArray: array of Byte); begin Write(AByteArray, SizeOf(AByteArray)); end; procedure TgtExtMemStream.WriteLong(ALong: Integer); var B : array[0..3] of Byte; begin B[0] := Byte(ALong shr 24); B[1] := Byte((ALong shl 8) shr 24); B[2] := Byte((ALong shl 16) shr 24); B[3] := Byte((ALong shl 24) shr 24); WriteByteArray(B); end; procedure TgtExtMemStream.WriteShort(AShort: SmallInt); var B : array[0..1] of Byte; begin B[0] := Byte(AShort shr 8); B[1] := Byte((AShort shl 8) shr 8); WriteByteArray(B); end; procedure TgtExtMemStream.WriteString(AString: AnsiString); var I : Integer; begin for I := 1 to Length(AString) do WriteByte(Ord(AString[I])); end; procedure TgtExtMemStream.WriteULong(AULong: Cardinal); var B : array[0..3] of Byte; begin B[0] := Byte(AULong shr 24); B[1] := Byte((AULong shl 8) shr 24); B[2] := Byte((AULong shl 16) shr 24); B[3] := Byte((AULong shl 24) shr 24); WriteByteArray(B); end; procedure TgtExtMemStream.WriteULongArray(AULongArray: array of Cardinal); var LI: Integer; begin for LI := Low(AULongArray) to High(AULongArray) do WriteULong(AULongArray[LI]); end; procedure TgtExtMemStream.WriteUShortArray(AUShortArray: array of Word); var LI: Integer; begin for LI := Low(AUShortArray) to High(AUShortArray) do WriteUShort(AUShortArray[LI]); end; procedure TgtExtMemStream.WriteUShort(AUShort: Word); var B : array[0..1] of Byte; begin B[0] := Byte(AUShort shr 8); B[1] := Byte((AUShort shl 8) shr 8); WriteByteArray(B); end; { TgtReadOnlyFilterStream } constructor TgtReadOnlyFilter.Create(aStream: TStream); begin inherited Create; if not Assigned(aStream) then raise EInvalidStream.Create(SNullStreamError) else begin FStream := aStream; FSize := FStream.Size; end; end; function TgtReadOnlyFilter.Read(var Buffer; Count: Integer): Longint; begin Result := FStream.Read(Buffer, Count); end; function TgtReadOnlyFilter.Seek(Offset: Integer; Origin: Word): Longint; begin if Offset = -1 then Result := Offset else Result := FStream.Seek(Offset, Origin); end; function TgtReadOnlyFilter.Write(const Buffer; Count: Integer): Longint; begin raise EReadError.Create(SReadError); Result := 0; end; { TgtRandomAccessFilter } procedure TgtRandomAccessFilter.IncPos(Count: Integer); begin FStream.Position := FStream.Position + Count; end; function TgtRandomAccessFilter.PeekChar: Char; begin FStream.Read(Result, 1); FPeekLastChar := (FStream.Position = FStream.Size); FStream.Position := FStream.Position - 1; end; function TgtRandomAccessFilter.PeekString(Count: Integer): String; begin SetLength(Result, Count); Count := FStream.Read(Result[1], Count); //FPeekLastChar := (FStream.Position = FStream.Size); FStream.Position := FStream.Position - Count; end; procedure TgtRandomAccessFilter.PushBackChar; begin FStream.Position := FStream.Position - 1; end; function TgtRandomAccessFilter.ReadChar: Char; begin FStream.Read(Result, 1); end; function TgtRandomAccessFilter.ReadOffset(var Buffer; FromOffset, ToOffset: Integer): Longint; function IsValidOffset(FromOffset, ToOffset: Longint): Boolean; begin Result := (FromOffset >= 0) and (ToOffset >= 0) and (ToOffset <= FSize); end; var CurrentPos: Longint; begin if not IsValidOffset(FromOffset, ToOffset) then begin raise Exception.Create(SInvalidOffset); Result := 0; Exit; end; Result := ToOffset - FromOffset; if Result > 0 then begin CurrentPos := FStream.Position; FStream.Position := FromOffset; Result := FStream.Read(Buffer, Result); FStream.Position := CurrentPos; end else Result := 0; end; function TgtRandomAccessFilter.ReadString(Count: Integer): String; begin SetLength(Result, Count); Read(Result[1], Count); end; function TgtRandomAccessFilter.Skip(Count: Integer): Longint; begin if (FStream.Position + Count)>FSize then raise Exception.Create(SSkipCount) else begin FStream.Position := (FStream.Position + Count); Result := Count; end; end; { TgtWriteOnlyFilter } function TgtWriteOnlyFilter.CopyFrom(Source: TStream; Count: Int64): Int64; begin Result := FStream.CopyFrom(Source, Count); end; constructor TgtWriteOnlyFilter.Create(aStream: TStream); begin inherited Create; if not Assigned(aStream) then raise EInvalidStream.Create(SNullStreamError) else FStream := aStream; end; function TgtWriteOnlyFilter.Read(var Buffer; Count: Integer): Longint; begin raise EReadError.Create(SReadError); Result := 0; end; function TgtWriteOnlyFilter.Seek(Offset: Integer; Origin: Word): Longint; begin Result := FStream.Seek(Offset, Origin); end; function TgtWriteOnlyFilter.Write(const Buffer; Count: Integer): Longint; begin Result := FStream.Write(Buffer, Count); end; { TgtObjectList } destructor TgtObjectList.Destroy; begin inherited Destroy; Clear; end; procedure TgtObjectList.Clear; begin if FCount <> 0 then begin FCount := 0; SetCapacity(0); end; end; function TgtObjectList.Add(ANo: Integer; AObject: TObject): Integer; begin Result := FCount; InsertItem(FCount, ANo, AObject); end; procedure TgtObjectList.Delete(Index: Integer); begin if (Index < 0) or (Index >= FCount) then Exception.CreateFmt(SListIndexOutOfBounds, [Index]); FList^[Index].FObject.Free; Dec(FCount); if Index < FCount then System.Move(FList^[Index + 1], FList^[Index], (FCount - Index) * SizeOf(TStringItem)); end; function TgtObjectList.GetObject(Index: Integer): TObject; begin if (Index < 0) or (Index >= FCount) then Exception.CreateFmt(SListIndexOutOfBounds, [Index]); Result := FList^[Index].FObject; end; function TgtObjectList.GetCapacity: Integer; begin Result := FCapacity; end; function TgtObjectList.GetCount: Integer; begin Result := FCount; end; procedure TgtObjectList.Grow; var Delta: Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; SetCapacity(FCapacity + Delta); end; function TgtObjectList.IndexOf( const ObjectNo: Integer): Integer; begin for Result := 0 to GetCount - 1 do if (FList^[Result].FInteger = ObjectNo) then Exit; Result := -1; end; procedure TgtObjectList.InsertItem(Index: Integer; ANo: Integer; AObject: TObject); begin if ANo < 0 then raise EInvalidID.CreateFmt(SInvalidID, [ANo]); if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(TgtObjectItem)); with FList^[Index] do begin FObject := AObject; FInteger := ANo; end; Inc(FCount); end; procedure TgtObjectList.SetCapacity(NewCapacity: Integer); begin ReallocMem(FList, NewCapacity * SizeOf(TgtObjectItem)); FCapacity := NewCapacity; end; procedure TgtObjectList.Add(AObjectList: TgtObjectList); var LI: Integer; LIndex: Integer; begin SetCapacity(FCount + AObjectList.Count); for LI := 0 to AObjectList.Count-1 do begin LIndex := IndexOf(AObjectList.Items[LI].FInteger); if LIndex = -1 then begin FList^[FCount] := AObjectList.Items[LI]; Inc(FCount); end else AObjectList.Items[LI].FObject.Free; end; end; function TgtObjectList.GetItem(Index: Integer): TgtObjectItem; begin Result := FList^[Index]; end; { TWideStrings implementation } constructor TWideStrings.Create; begin FWideStringList := TList.Create; end; destructor TWideStrings.Destroy; var Index: Integer; PWStr: ^TWString; begin { TODO - BB Investigate : Could call Clear here } for Index := 0 to FWideStringList.Count-1 do begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then Dispose(PWStr); end; FWideStringList.Free; inherited Destroy; end; function TWideStrings.Delete(Index: Integer): WideString; begin if ( (Index >= 0) and (Index < FWideStringList.Count) ) then begin FWideStringList.Delete(Index); end; end; function TWideStrings.Get(Index: Integer): WideString; var PWStr: ^TWString; begin Result := ''; if ( (Index >= 0) and (Index < FWideStringList.Count) ) then begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then Result := PWStr^.WString; end; end; procedure TWideStrings.Put(Index: Integer; const S: WideString); var PWStr: ^TWString; begin if((Index < 0) or (Index > FWideStringList.Count)) then Exit; //raise Exception.Create(SWideStringOutofBounds); if Index < FWideStringList.Count then begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then PWStr.WString := S; end else Add(S); end; function TWideStrings.Add(const S: WideString): Integer; var PWStr: ^TWString; begin New(PWStr); PWStr^.WString := S; Result := FWideStringList.Add(PWStr); end; function TWideStrings.IndexOfIgnoreCase(const S: WideString): Integer; var Index: Integer; PWStr: ^TWString; begin Result := -1; for Index := 0 to FWideStringList.Count -1 do begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then begin if SameText(S, PWStr^.WString) then begin Result := Index; break; end; end; end; end; function TWideStrings.IndexOf(const S: WideString): Integer; var Index: Integer; PWStr: ^TWString; begin Result := -1; for Index := 0 to FWideStringList.Count -1 do begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then begin if S = PWStr^.WString then begin Result := Index; break; end; end; end; end; function TWideStrings.Count: Integer; begin Result := FWideStringList.Count; end; procedure TWideStrings.Clear; var Index: Integer; PWStr: ^TWString; begin for Index := 0 to FWideStringList.Count-1 do begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then Dispose(PWStr); end; FWideStringList.Clear; end; procedure TWideStrings.Insert(Index: Integer; const S: WideString); var PWStr: ^TWString; LIdx: Integer; begin if((Index < 0) or (Index > FWideStringList.Count)) then Exit; //raise Exception.Create(SWideStringOutofBounds); if Index < FWideStringList.Count then begin Add(S); for LIdx := Count - 1 downto (Index + 1) do begin PWStr := FWideStringList.Items[LIdx]; if PWStr <> nil then PWStr.WString := Strings[LIdx - 1]; end; PWStr := FWideStringList.Items[Index]; if PWStr <> nil then PWStr.WString := S; end else Add(S); end; procedure TWideStrings.LoadFromFile(const FileName: WideString); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TWideStrings.LoadFromStream(Stream: TStream); var Size: Integer; S: WideString; begin Size := Stream.Size - Stream.Position; SetString(S, nil, Size div SizeOf(WideChar)); Stream.Read(Pointer(S)^, Size); SetTextStr(S); end; procedure TWideStrings.SetTextStr(const Value: WideString); var P, Start: PwideChar; S: WideString; begin Clear; P := Pointer(Value); if P <> nil then while P^ <> #0 do begin Start := P; while not InOpSet(P^, [AnsiChar(#0), AnsiChar(#10), AnsiChar(#13)]) do Inc(P); SetString(S, Start, P - Start); Add(S); if P^ = #13 then Inc(P); if P^ = #10 then Inc(P); end; end; end.
{ ***************************************************************************** * * * This file is part of the iPhone Laz Extension * * * * See the file COPYING.modifiedLGPL.txt, included in this distribution, * * for details about the copyright. * * * * 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. * * * ***************************************************************************** } unit PlistFile; {$mode delphi} interface uses Classes, SysUtils, DOM, XMLRead, XMLWrite, LazFilesUtils; type TPlistType = (ltString, ltArray, ltDict, ltData, ltDate, ltBoolean, ltNumber); { TPListValue } TPListValue = class(TObject) private fType : TPlistType; public str : WideString; binary : array of byte; date : TDateTime; bool : Boolean; number : Double; count : Integer; items : array of TPListValue; names : array of string; constructor Create(AType: TPlistType); function AddValue: Integer; property ValueType: TPListType read fType; end; { TPListFile } TPListFile = class(TObject) public root : TPListValue; constructor Create; destructor Destroy; override; function GetStrValue(const valname: string): string; end; function LoadFromXML(const fn: string; plist: TPListFile): Boolean; overload; function LoadFromXML(doc: TXMLDocument; plist: TPListFile): Boolean; overload; function WriteXML(const plist: TPlistFile): string; procedure DebugPlistFile(const fl: TPListFile); function LoadFromFile(const fn: string; plist: TPListFile): Boolean; implementation procedure DebugValue(kv: TPListValue; const prefix: string ); var i : integer; begin for i:=0 to kv.count-1 do begin if kv.fType=ltDict then writeln(prefix,kv.names[i],' (',kv.items[i].ValueType,')'); case kv.items[i].fType of ltString: writeln(prefix+' ', kv.items[i].str); ltBoolean: writeln(prefix+' ', kv.items[i].bool); ltDict: begin writeln; DebugValue(kv.items[i],prefix+' '); end; ltArray: begin //writeln; DebugValue(kv.items[i],prefix+' '); end; end; end; end; procedure DebugPlistFile(const fl: TPListFile); begin DebugValue(fl.root,''); end; function LoadFromFile(const fn: string; plist: TPListFile): Boolean; var st : TFileStream; buf : string[5]; xs : string; err : LongWord; m : TStringStream; doc : TXMLDocument; begin //todo: detect plist type and convert is necessary st:=TFileSTream.Create(fn, fmOpenRead or fmShareDenyNone); try st.Read(buf, 5); finally st.Free; end; if buf='<?xml' then Result:=LoadFromXML(fn, plist) else begin {$ifdef darwin} // the utility is not available anywhere else but OSX if not ExecCmdLineStdOut('plutil -convert xml1 -o - "'+fn+'"', xs, err) then begin Result:=false; Exit; end; m:=TStringStream.Create(xs); try ReadXMLFile(doc, m); Result:=LoadFromXML(doc, plist); doc.Free; finally m.Free; end; {$else} Result:=false; {$endif} end; end; const PlistXMLPrefix= '<?xml version="1.0" encoding="UTF-8"?>'+LineEnding+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'+LineEnding+ '<plist version="1.0">'; const EncText = ['<', '>', '&']; amp = '&amp;'; lt = '&lt;'; gt = '&gt;'; function XMLEncodeText(const v: WideString): string; var i : integer; j : Integer; k : integer; b : string; rp : string; begin Result:=''; b:=UTF8Encode(v); j:=1; for i:=1 to length(b) do begin if b[i] in EncText then begin if length(Result)=0 then begin SetLength(Result, length(b)*5); k:=1; end; Move(b[j], Result[k], i-j); inc(k, i-j); case b[i] of '<': rp:=lt; '>': rp:=gt; '&': rp:=amp; end; j:=i+1; Move(rp[1], Result[k], length(rp)); inc(k, length(rp)); end; end; if (Result='') and (b<>'') then Result:=b else begin if j<length(b) then begin i:=length(b)+1; Move(b[j], Result[k], i-j); inc(k, i-j); end; SetLength(Result, k-1); end; end; const XMLPFX = #9; procedure WriteXMLValue(v: TPListValue; dst: TStrings; const pfx: string); const boolTag : array [boolean] of string = ('<false/>','<true/>'); var i : integer; begin case v.ValueType of ltBoolean: dst.Add(pfx+boolTag[v.bool]); ltString: dst.Add(pfx+'<string>'+XMLEncodeText(v.str)+'</string>'); ltDict: begin dst.Add(pfx+'<dict>'); for i:=0 to v.count-1 do begin dst.Add(XMLPFX+'<key>'+XMLEncodeText(v.names[i])+'</key>'); WriteXMLValue(v.items[i], dst, pfx+XMLPFX); end; dst.Add(pfx+'</dict>'); end; ltArray: begin dst.Add(pfx+'<array>'); for i:=0 to v.count-1 do WriteXMLValue(v.items[i], dst, pfx+XMLPFX); dst.Add(pfx+'</array>'); end; end; end; function WriteXML(const plist: TPlistFile): string; var st: TSTringList; begin st:=TSTringList.Create; try st.Add(PlistXMLPrefix); WriteXMLValue(plist.root, st, ''); st.Add('</plist>'); Result:=st.Text; finally st.Free; end; end; function LoadFromXML(const fn: string; plist: TPListFile): Boolean; overload; var doc : TXMLDocument; begin ReadXMLFile(doc, fn); Result:=LoadFromXML(doc, plist); doc.Free; end; function ReadValByNode(valnode: TDomNode): TPListValue; forward; function NodeNameToPListType(const nd: string; var pl: TPlistType) : Boolean; begin Result:=true; if nd='string' then pl:=ltString else if nd ='array' then pl:=ltArray else if (nd ='fasle') or (nd = 'true') then pl:=ltBoolean else if (nd = 'dict') then pl:=ltDict //TPlistType = (ltData, ltDate, ltNumber); else Result:=false; end; procedure ReadArrVal(parent: TDomNode; kv: TPListValue); var idx : Integer; nd : TDomNode; begin if not Assigned(parent) then Exit; nd:=parent.FirstChild; while Assigned(nd) do begin idx:=kv.AddValue; kv.items[idx]:=ReadValByNode(nd); nd:=nd.NextSibling; end; end; procedure ReadKeyVal(parent: TDomNode; kv: TPListValue); var nd : TDOMNode; idx : integer; begin if not Assigned(parent) then Exit; nd:=parent.FirstChild; while Assigned(nd) do begin if nd.NodeName='key' then begin idx:=kv.AddValue; kv.names[idx]:=UTF8Encode(nd.TextContent); nd:=nd.NextSibling; if Assigned(nd) then begin kv.items[idx]:=ReadValByNode(nd); nd:=nd.NextSibling; end; end else nd:=nd.NextSibling; end; end; function ReadValByNode(valnode: TDomNode): TPListValue; var t : string; tp : TPlistType; begin Result:=nil; if not Assigned(valnode) then Exit; if not NodeNameToPListType(valnode.NodeName, tp) then Exit; Result:=TPListValue.Create(tp); case tp of ltBoolean: Result.bool:=(valnode.NodeName='true'); // false is false ltString: Result.str:=valnode.TextContent; ltArray: ReadArrVal(valnode, Result); ltDict: ReadKeyVal(valnode, Result); end; end; function LoadFromXML(doc: TXMLDocument; plist: TPListFile): Boolean; overload; var root : TDOMNode; nd : TDOMNode; r : TPListValue; begin Result:=false; root:=doc.FirstChild; //('plist'); if not Assigned(root) then Exit; while Assigned(root) do begin if (root.NodeType = ELEMENT_NODE) and (root.NodeName = 'plist') then Break; root:=root.NextSibling; end; if not Assigned(root) then Exit; nd:=root.FirstChild; r:=plist.root; plist.root:=ReadValByNode(nd); if Assigned(plist.root) then r.Free; Result:=true; end; constructor TPListFile.Create; begin inherited Create; root:=TPListValue.Create(ltDict) end; destructor TPListFile.Destroy; begin root.Free; inherited Destroy; end; function TPListFile.GetStrValue(const valname: string): string; var i : integer; begin if not Assigned(root) or (root.ValueType<>ltDict) then begin Result:=''; Exit; end; for i:=0 to root.count-1 do if root.names[i]=valname then begin Result:=UTF8Encode(root.items[i].str); Exit; end; Result:=''; end; { TPListValue } constructor TPListValue.Create(AType: TPlistType); begin inherited Create; fType:=AType; end; function TPListValue.AddValue: Integer; begin if not (fType in [ltArray, ltDict]) then begin Result:=0; Exit; end; Result:=count; if count=length(items) then begin if count=0 then SetLength(items, 4) else SetLength(items, length(items)*2); if fType=ltDict then SetLength(names, length(items)); end; inc(count); end; end.
unit fuMTSearch; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, AdvObj, BaseGrid, AdvGrid, DateUtils, Vcl.StdCtrls, Vcl.ExtCtrls, AdvGlowButton, AdvEdit, W7Classes, W7Bars, AdvUtil, ShellAPI, AdvOfficeButtons, VCLTee.TeeGDIPlus, VCLTee.TeEngine, VCLTee.Series, VCLTee.TeeProcs, VCLTee.Chart, Vcl.Menus, AdvMenus, AdvCustomComponent, AdvPDFIO, AdvGridPDFIO; type TfrmMTSearch = class(TForm) sgSearch: TAdvStringGrid; W7InformationBar1: TW7InformationBar; lblRecordCount: TLabel; Panel1: TPanel; cbCriteria: TComboBox; Label1: TLabel; chkOpenOnly: TAdvOfficeCheckBox; btnSearch: TAdvGlowButton; eSearch: TComboBox; TeeGDIPlus1: TTeeGDIPlus; chtResults: TChart; Series1: TPieSeries; Panel2: TPanel; pdfSave: TAdvGridPDFIO; AdvGlowButton1: TAdvGlowButton; popSave: TAdvPopupMenu; PDF1: TMenuItem; xlsx1: TMenuItem; sd1: TSaveDialog; procedure cbCriteriaChange(Sender: TObject); procedure SearchMT; procedure ClearGrid; procedure btnSearchClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure IncCtgyCount(CtgyID : integer); procedure FillAndShowCtgyChart; procedure eSearchKeyPress(Sender: TObject; var Key: Char); procedure PDF1Click(Sender: TObject); procedure xlsx1Click(Sender: TObject); procedure chtResultsClickSeries(Sender: TCustomChart; Series: TChartSeries; ValueIndex: Integer; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } public { Public declarations } stlMTS_MemberID : TStringList; iMTS_AssignedToID : integer; stlCtgyCount : TStringList; iMTS_ByCtgyID : integer; end; var frmMTSearch: TfrmMTSearch; implementation {$R *.dfm} uses duMT2, fuCustomerLog, uMT2GlobalVar, uCommon; procedure TfrmMTSearch.btnSearchClick(Sender: TObject); begin SearchMT; end; procedure TfrmMTSearch.cbCriteriaChange(Sender: TObject); begin eSearch.Items.Clear; eSearch.Text:= ''; case cbCriteria.ItemIndex of 0: begin eSearch.Items.Assign(stlGV_CLDept); eSearch.ItemIndex:= 0; end; else end; end; procedure TfrmMTSearch.chtResultsClickSeries(Sender: TCustomChart; Series: TChartSeries; ValueIndex: Integer; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var sCtgyName : String; begin sCtgyName:= Series.Labels[ValueIndex]; iMTS_ByCtgyID:= GetCategoryIDFromName(sCtgyName); SearchMT; end; procedure TfrmMTSearch.SearchMT; var iRow : integer; sOpenOnlyPhrase : String; sByCtgyPhrase : String; begin try sgSearch.BeginUpdate; ClearGrid; stlMTS_memberID.Clear; stlCtgyCount.Clear; iRow:= 1; if chkOpenOnly.Checked then sOpenOnlyPhrase:= ' AND a.status < 4 ' else sOpenOnlyPhrase:= ''; if iMTS_ByCtgyID > 0 then sByCtgyPhrase:= ' AND a.ctgyid = ' + IntToStr(iMTS_ByCtgyID) else sByCtgyPhrase:= ''; With dmMT2.fqMTSearch do try DisableControls; Active:= false; Params.Clear; SQL.Text:= UseDB; SQL.Add('SELECT a.logid,a.caller,a.logdate,a.summary,1,a.ctgyid,a.status,a.customerid'); SQL.Add(',b.custname'); SQL.Add('FROM tblCustomerLogInfo a'); SQL.Add('INNER JOIN [wddc].dbo.RM00101 b ON (a.customerid = b.custnmbr)'); case cbCriteria.ItemIndex of 0: begin //assigned to a department SQL.Add('WHERE a.DeptID=:prm1' + sOpenOnlyPhrase + sByCtgyPhrase); SQL.Add('ORDER BY a.logid DESC'); Params[0].AsInteger:= Integer(stlGV_CLDept.Objects[stlGV_CLDept.IndexOf(eSearch.Text)]); end; 1: begin //log id SQL.Add('WHERE a.logid =:prm0'); Params[0].AsInteger:= StrToIntDef(eSearch.Text,0); end; 2: begin //invoice number SQL.Add('JOIN tblInvoiceNumbers c ON (a.logid = c.logID)'); SQL.Add('WHERE c.invoicenumber LIKE :prm1' + sOpenOnlyPhrase + sByCtgyPhrase); Params[0].AsString:= eSearch.Text + '%'; end; 3: begin // an item SQL.Add('JOIN tblItems c ON (a.logID = c.logid)'); SQL.Add('WHERE c.itemcode LIKE :prb1' + sOpenOnlyPhrase + sByCtgyPhrase ); SQL.Add('ORDER BY a.logId DESC'); Params[0].AsString:= eSearch.Text + '%'; end; 4: begin // a word in the text field SQL.Add('JOIN tblCustomerLog c ON (a.LogId = c.logid)'); SQL.Add('WHERE c.problem LIKE :prb1' + sOpenOnlyPhrase + sByCtgyPhrase); SQL.Add('ORDER BY a.logId DESC'); Params[0].AsString:= '%' + eSearch.Text + '%'; end; 5: begin // longer than certain days SQL.Add('WHERE a.logdate < :prb1 AND a.status < 4' + sByCtgyPhrase); SQL.Add('ORDER BY a.logId DESC'); ParamByName('prb1').AsDateTime:= IncDay(Now, - (StrToIntDef(eSearch.Text,30))); end; 6: begin // certain words in summary SQL.Add('WHERE a.summary LIKE :prb1' + sOpenOnlyPhrase + sByCtgyPhrase); SQL.Add('ORDER BY a.logId DESC'); ParamByName('prb1').AsString:= '%' + eSearch.Text + '%'; end; 7: begin // logs created by the logged in user SQL.Add('WHERE a.creator = :prb1' + sOpenOnlyPhrase + sByCtgyPhrase); SQL.Add('ORDER BY a.logId DESC'); ParamByName('prb1').AsString:= rGV_MTUser.UserName; end; end; Active:= true; if RecordCount = 0 then begin MessageDlg('No records found. Change your search criteria and try again',mtInformation,[mbOK],0); lblRecordcount.Caption:= ''; end else begin while not EOF do begin WIth sgSearch do begin if iRow > 1 then AddRow; Cells[0,iRow]:= FOrmatDateTime('mm dd yyyy h:nn AM/PM',Fields[2].AsDateTime); Cells[1,iRow]:= FIelds[0].AsString; Cells[2,iRow]:= Fields[7].AsString + ' - ' + Fields[8].AsString; Cells[3,iRow]:= GetCategoryName(Fields[5].AsInteger); Cells[4,iRow]:= Fields[3].AsString; stlMTS_MemberID.Add(Fields[7].AsString); IncCtgyCount(Fields[5].AsInteger); end; Next; Inc(iRow); end; lblRecordcount.Caption:= IntToStr(Recordcount) + ' records found.'; end; finally begin Active:= false; EnableControls; end; end; finally sgSearch.EndUpdate; if cbCriteria.ItemIndex IN [3,4] then begin sgSearch.AutoSizeRows(false,3); sgSearch.HilightInCol(False,false,4,eSearch.Text); end; FillAndShowCtgyChart; iMTS_ByCtgyID:= 0; end; end; procedure TfrmMTSearch.xlsx1Click(Sender: TObject); begin sd1.FileName:= ''; sd1.DefaultExt:= 'xls'; sd1.Title:= 'Save as Excel'; sd1.Filter:= 'Excel|*.xls'; if sd1.Execute then begin sgSearch.SaveToXLS(sd1.FileName,true); ShellExecute(Self.Handle,'OPEN',PWideChar(sd1.FileName),nil,nil,SW_SHOWNORMAL); end; end; procedure TfrmMTSearch.ClearGrid; var x, y : integer; begin With sgSearch do for x:= 0 to Pred(ColCount) do for y:= 1 to Pred(RowCount) do Cells[x,y]:= ''; sgSearch.RowCount:= 2; end; procedure TfrmMTSearch.eSearchKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) and (cbCriteria.ItemIndex > -1) and (eSearch.Text <> '') then btnSearchClick(nil); end; procedure TfrmMTSearch.FormCreate(Sender: TObject); begin stlMTS_MemberID:= TStringList.Create; lblRecordCount.Caption:= ''; chtResults.Visible:= false; stlCtgyCount:= TStringList.Create; iMTS_ByCtgyID:= 0; end; procedure TfrmMTSearch.FormDestroy(Sender: TObject); begin stlMTS_MemberID.Free; stlCtgyCount.Free; end; procedure TfrmMTSearch.IncCtgyCount(CtgyID: Integer); var iDx : integer; iCount : integer; begin iDx:= stlCtgyCount.IndexOfName(IntToStr(CtgyID)); if iDx = -1 then stlCtgyCount.Add(IntToStr(CtgyID) + '=1') else begin iCount:= StrToInt(stlCtgyCount.ValueFromIndex[iDx]); Inc(iCount); stlCtgyCount[iDx]:= IntToStr(CtgyID) + '=' + IntTOStr(iCount); end; end; procedure TfrmMTSearch.PDF1Click(Sender: TObject); begin sd1.FileName:= ''; sd1.DefaultExt:= 'pdf'; sd1.Title:= 'Save as PDF'; sd1.Filter:= 'PDF|*.pdf'; if sd1.Execute then begin pdfSave.Options.Header:= cbCriteria.Text + ' ' + eSearch.Text; pdfSave.Options.Footer:= ''; pdfSave.Save(sd1.FileName); ShellExecute(Self.Handle,'OPEN',PWideChar(sd1.FileName),nil,nil,SW_SHOWNORMAL); end; end; procedure TfrmMTSearch.FillAndShowCtgyChart; var iInc : integer; sCtgyName : String; begin chtResults.Series[0].Clear; for iInc:= 0 to Pred(stlCtgyCount.Count) do begin sCtgyName:= GetCategoryName(StrToInt(stlCtgyCount.Names[iInc])); if sCtgyName = '' then sCtgyName:= 'Unknown, possibly deactivated'; chtResults.Series[0].Add(StrToInt(stlCtgyCount.ValueFromIndex[iInc]),sCtgyName); end; chtResults.Visible:= true; chtResults.Title.Text.Clear; end; end.
//Exercicio 27: Escreva um algoritmo que receba um número inteiro e exiba se esse número é par ou ímpar. { Solução em Portugol Algoritmo Exercicio 27; Var numero: inteiro; Inicio exiba("Programa que avalia se um número é par ou ímpar."); exiba("Digite um número inteiro:"); leia(numero); se(resto(numero,2) = 0) então exiba(numero," é par!") senão exiba(numero," é ímpar!"); fimse; Fim. } // Solução em Pascal Program Exercicio27; uses crt; var numero: integer; begin clrscr; writeln('Programa que avalia se um número é par ou ímpar.'); writeln('Digite um número inteiro:'); readln(numero); if(numero mod 2 = 0) then writeln(numero,' é par!') else writeln(numero,' é ímpar!'); repeat until keypressed; end.
unit MdiChilds.CalcRowsCount; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, MdiChilds.ProgressForm, MdiChilds.Reg, GsDocument, ActionHandler; type TFmRowsCount = class(TFmProcess) pcMain: TPageControl; tsDocs: TTabSheet; tsResult: TTabSheet; lvResult: TListView; lbDocs: TListBox; JvDragDrop: TJvDragDrop; btnSaveResult: TButton; sd: TSaveDialog; procedure JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure btnSaveResultClick(Sender: TObject); private { Private declarations } protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; procedure DoResize(Sender: TObject); override; public procedure AddToResult(D: TGsDocument; RowCount: Integer; ResourceCount: Integer); procedure SaveResult(AFileName: string); end; TRowsCountActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmRowsCount: TFmRowsCount; implementation {$R *.dfm} procedure TFmRowsCount.AddToResult(D: TGsDocument; RowCount: Integer; ResourceCount: Integer); var Item: TListItem; begin Item := lvResult.Items.Add; Item.Caption := D.TypeAndNumber; Item.SubItems.Add(IntToStr(RowCount)); Item.SubItems.Add(IntToStr(ResourceCount)); end; procedure TFmRowsCount.btnSaveResultClick(Sender: TObject); begin if sd.Execute then SaveResult(sd.FileName); end; procedure TFmRowsCount.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; D: TGsDocument; L: TList; RowCount, ResourceCount: Integer; begin ShowMessage := True; ProgressForm.InitPB(lbDocs.Count); ProgressForm.Show; for I := 0 to lbDocs.Count - 1 do begin if not ProgressForm.InProcess then Break; D := TGsDocument.Create; try D.LoadFromFile(lbDocs.Items[I]); L := TList.Create; try D.Chapters.EnumItems(L, TGsRow, True); RowCount := L.Count; L.Clear; D.Chapters.EnumItems(L, TGsResource, True); ResourceCount := L.Count; L.Clear; AddToResult(D, RowCount, ResourceCount); finally L.Free; end; finally D.Free; end; end; end; procedure TFmRowsCount.DoResize(Sender: TObject); begin inherited; btnSaveResult.Top := Self.Bevel.Height + 10; end; procedure TFmRowsCount.JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin lbDocs.Items.Assign(Value); end; procedure TFmRowsCount.SaveResult(AFileName: string); var I: Integer; S: TStringList; Line: string; begin S := TStringList.Create; try for I := 0 to lvResult.Items.Count - 1 do begin Line := lvResult.Items[I].Caption+#9 + lvResult.Items[I].SubItems[0]+#9+lvResult.Items[I].SubItems[1]; S.Add(Line); end; S.SaveToFile(AFileName); finally S.Free; end; end; { TRowsCountActionHandler } procedure TRowsCountActionHandler.ExecuteAction; begin TFmRowsCount.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Количество расценок в сборниках', hkDefault, TRowsCountActionHandler); end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clSshAuth; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, {$ELSE} System.Classes, {$ENDIF} clSshUserIdentity, clSshUserKey, clSshPacket, clConfig, clUtils; type TclSshAuthResult = (sarWork, sarSuccess, sarFail); TclSshShowBannerEvent = procedure(Sender: TObject; const AMessage, ALanguage: string) of object; TclSshUserAuth = class(TclConfigObject) private FMethods: string; FIdentity: TclSshUserIdentity; FSessionId: TclByteArray; FConfig: TclConfig; protected procedure SetMethods(const Value: string); function InitAuth: TclPacket; virtual; abstract; function ContinueAuth(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; virtual; abstract; function CanAuthenticate: Boolean; virtual; abstract; procedure ShowBanner(AInput: TclPacket); function AuthFailure(AInput: TclPacket): string; public constructor Create; override; function Init(AConfig: TclConfig; AIdentity: TclSshUserIdentity; const ASessionId: TclByteArray): Boolean; function Authenticate(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; property Config: TclConfig read FConfig; property Identity: TclSshUserIdentity read FIdentity; property SessionId: TclByteArray read FSessionId; property Methods: string read FMethods; end; TclUserAuthNone = class(TclSshUserAuth) protected function InitAuth: TclPacket; override; function ContinueAuth(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; override; function CanAuthenticate: Boolean; override; end; TclUserAuthPassword = class(TclSshUserAuth) protected function InitAuth: TclPacket; override; function ContinueAuth(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; override; function CanAuthenticate: Boolean; override; end; TclUserAuthPublicKeySha1 = class(TclSshUserAuth) private FKeyExchange: Boolean; function PublicKeyExchange(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; function PublicKeyAuth(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; function GetPublicKeyBlob: TclByteArray; function GetSignature(const AData: TclByteArray): TclByteArray; protected function InitAuth: TclPacket; override; function ContinueAuth(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; override; function CanAuthenticate: Boolean; override; end; implementation uses clCryptSignature, clTranslator, clSshUtils; { TclSshUserAuth } function TclSshUserAuth.Authenticate(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; begin if (AInput = nil) then begin AOutput := InitAuth(); Result := sarWork; end else begin Result := ContinueAuth(AInput, AOutput); end; end; constructor TclSshUserAuth.Create; begin inherited Create(); FMethods := ''; FIdentity := nil; FSessionId := nil; FConfig := nil; end; function TclSshUserAuth.Init(AConfig: TclConfig; AIdentity: TclSshUserIdentity; const ASessionId: TclByteArray): Boolean; begin FConfig := AConfig; FIdentity := AIdentity; FSessionId := ASessionId; Result := CanAuthenticate(); end; procedure TclSshUserAuth.SetMethods(const Value: string); begin FMethods := Value; end; procedure TclSshUserAuth.ShowBanner(AInput: TclPacket); var _message, _lang: TclByteArray; msg, lang: string; begin Assert(AInput.Buffer[5] = SSH_MSG_USERAUTH_BANNER); AInput.GetInt(); AInput.GetByte(); AInput.GetByte(); _message := AInput.GetString(); _lang := AInput.GetString(); msg := TclTranslator.GetString(_message, 'utf-8'); lang := TclTranslator.GetString(_lang, 'utf-8'); Identity.ShowBanner(msg, lang); end; function TclSshUserAuth.AuthFailure(AInput: TclPacket): string; begin AInput.GetInt(); AInput.GetByte(); AInput.GetByte(); Result := TclTranslator.GetString(AInput.GetString()); AInput.GetByte();//TODO returns partial_success; probably, throw exception if partial_success == false end; { TclUserAuthNone } function TclUserAuthNone.CanAuthenticate: Boolean; begin Result := True; end; function TclUserAuthNone.ContinueAuth(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; var _username: TclByteArray; begin {$IFNDEF DELPHI2005}_username := nil;{$ENDIF} Result := sarWork; AOutput := nil; if (AInput.Buffer[5] = SSH_MSG_SERVICE_ACCEPT) then begin _username := TclTranslator.GetBytes(Identity.GetUserName(), 'utf-8'); try AOutput := TclPacket.Create(); AOutput.Reset(); AOutput.PutByte(SSH_MSG_USERAUTH_REQUEST); AOutput.PutString(_username); AOutput.PutString(TclTranslator.GetBytes('ssh-connection')); AOutput.PutString(TclTranslator.GetBytes('none')); except AOutput.Free(); raise; end; end else if (AInput.Buffer[5] = SSH_MSG_USERAUTH_SUCCESS) then begin Result := sarSuccess; end else if (AInput.Buffer[5] = SSH_MSG_USERAUTH_BANNER) then begin ShowBanner(AInput); end else if (AInput.Buffer[5] = SSH_MSG_USERAUTH_FAILURE) then begin SetMethods(AuthFailure(AInput)); Result := sarFail; end else begin raise EclSshError.Create(UserAuthError, AInput.Buffer[5]); end; end; function TclUserAuthNone.InitAuth: TclPacket; begin Result := nil; try Result := TclPacket.Create(); Result.Reset(); Result.PutByte(SSH_MSG_SERVICE_REQUEST); Result.PutString(TclTranslator.GetBytes('ssh-userauth')); except Result.Free(); raise; end; end; { TclUserAuthPassword } function TclUserAuthPassword.CanAuthenticate: Boolean; begin Result := (Identity.GetUserName() <> '') and (Identity.GetPassword() <> ''); end; function TclUserAuthPassword.ContinueAuth(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; begin Result := sarWork; AOutput := nil; if (AInput.Buffer[5] = SSH_MSG_USERAUTH_SUCCESS) then begin Result := sarSuccess; end else if (AInput.Buffer[5] = SSH_MSG_USERAUTH_BANNER) then begin ShowBanner(AInput); end else if (AInput.Buffer[5] = SSH_MSG_USERAUTH_FAILURE) then begin SetMethods(AuthFailure(AInput)); Result := sarFail; end else begin try AOutput := TclPacket.Create(); AOutput.Reset(); AOutput.PutByte(SSH_MSG_USERAUTH_REQUEST); AOutput.PutString(TclTranslator.GetBytes(Identity.GetUserName(), 'utf-8')); AOutput.PutString(TclTranslator.GetBytes('ssh-connection')); AOutput.PutString(TclTranslator.GetBytes('password')); AOutput.PutByte(0); AOutput.PutString(TclTranslator.GetBytes(Identity.GetPassword(), 'utf-8')); except AOutput.Free(); raise; end; end; end; function TclUserAuthPassword.InitAuth: TclPacket; begin Result := nil; try Result := TclPacket.Create(); Result.Reset(); Result.PutByte(SSH_MSG_USERAUTH_REQUEST); Result.PutString(TclTranslator.GetBytes(Identity.GetUserName(), 'utf-8')); Result.PutString(TclTranslator.GetBytes('ssh-connection')); Result.PutString(TclTranslator.GetBytes('password')); Result.PutByte(0); Result.PutString(TclTranslator.GetBytes(Identity.GetPassword(), 'utf-8')); except Result.Free(); raise; end; end; { TclUserAuthPublicKeySha1 } function TclUserAuthPublicKeySha1.CanAuthenticate: Boolean; begin Result := (Identity.GetUserKey().GetPrivateKey() <> nil); end; function TclUserAuthPublicKeySha1.ContinueAuth(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; begin if (FKeyExchange) then begin Result := PublicKeyExchange(AInput, AOutput); end else begin Result := PublicKeyAuth(AInput, AOutput); end; end; function TclUserAuthPublicKeySha1.GetPublicKeyBlob: TclByteArray; var key: TclRsaKey; packet: TclPacket; m, e: TclByteArray; begin m := nil; e := nil; key := nil; packet := nil; try key := Config.CreateInstance('rsa-key') as TclRsaKey; key.Init(); key.SetRsaPrivateKey(Identity.GetUserKey().GetPrivateKey()); key.GetPublicKeyParams(m, e); m := FoldBytesWithZero(m); if (Length(e) > 0) and ((e[0] and $80) <> 0) then begin e := FoldBytesWithZero(e); end; packet := TclPacket.Create(Length('ssh-rsa') + 4 + Length(e) + 4 + Length(m) + 4); packet.PutString(TclTranslator.GetBytes('ssh-rsa')); packet.PutString(e); packet.PutString(m); Result := packet.Buffer; finally packet.Free(); key.Free(); end; end; function TclUserAuthPublicKeySha1.GetSignature(const AData: TclByteArray): TclByteArray; var key: TclRsaKey; signature: TclSignatureRsa; packet: TclPacket; begin signature := nil; key := nil; packet := nil; try signature := Config.CreateInstance('ssh-rsa') as TclSignatureRsa; signature.Init(); key := Config.CreateInstance('rsa-key') as TclRsaKey; key.Init(); key.SetRsaPrivateKey(Identity.GetUserKey().GetPrivateKey()); signature.SetPrivateKey(key); signature.Update(AData, 0, Length(AData)); Result := signature.Sign(); packet := TclPacket.Create(Length('ssh-rsa') + 4 + Length(Result) + 4); packet.PutString(TclTranslator.GetBytes('ssh-rsa')); packet.PutString(Result); Result := packet.Buffer; finally packet.Free(); key.Free(); signature.Free(); end; end; function TclUserAuthPublicKeySha1.InitAuth: TclPacket; var pubKeyBlob: TclByteArray; begin FKeyExchange := True; pubKeyBlob := GetPublicKeyBlob(); Result := nil; try Result := TclPacket.Create(); Result.Reset(); Result.PutByte(SSH_MSG_USERAUTH_REQUEST); Result.PutString(TclTranslator.GetBytes(Identity.GetUserName(), 'utf-8')); Result.PutString(TclTranslator.GetBytes('ssh-connection')); Result.PutString(TclTranslator.GetBytes('publickey')); Result.PutByte(0); Result.PutString(TclTranslator.GetBytes('ssh-rsa', 'utf-8')); Result.PutString(pubKeyBlob); except Result.Free(); raise; end; end; function TclUserAuthPublicKeySha1.PublicKeyAuth(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; begin Result := sarWork; AOutput := nil; if (AInput.Buffer[5] = SSH_MSG_USERAUTH_SUCCESS) then begin Result := sarSuccess; end else if (AInput.Buffer[5] = SSH_MSG_USERAUTH_BANNER) then begin ShowBanner(AInput); end else if (AInput.Buffer[5] = SSH_MSG_USERAUTH_FAILURE) then begin AuthFailure(AInput); Result := sarFail; end else begin raise EclSshError.Create(UserAuthError, AInput.Buffer[5]); end; end; function TclUserAuthPublicKeySha1.PublicKeyExchange(AInput: TclPacket; var AOutput: TclPacket): TclSshAuthResult; var sidLen, ind: Integer; pubKeyBlob, sid, tmp, signature: TclByteArray; begin {$IFNDEF DELPHI2005}pubKeyBlob := nil; sid := nil; tmp := nil; signature := nil;{$ENDIF} Result := sarWork; AOutput := nil; if (AInput.Buffer[5] = SSH_MSG_USERAUTH_PK_OK) then begin try AOutput := TclPacket.Create(); pubKeyBlob := GetPublicKeyBlob(); AOutput.Reset(); AOutput.PutByte(SSH_MSG_USERAUTH_REQUEST); AOutput.PutString(TclTranslator.GetBytes(Identity.GetUserName(), 'utf-8')); AOutput.PutString(TclTranslator.GetBytes('ssh-connection')); AOutput.PutString(TclTranslator.GetBytes('publickey')); AOutput.PutByte(1); AOutput.PutString(TclTranslator.GetBytes('ssh-rsa', 'utf-8')); AOutput.PutString(pubKeyBlob); sid := SessionId; sidlen := Length(sid); SetLength(tmp, 4 + sidlen + AOutput.GetIndex() - 5); ind := 0; ByteArrayWriteDWord(sidlen, tmp, ind); System.Move(sid[0], tmp[4], sidlen); System.Move(AOutput.Buffer[5], tmp[4 + sidlen], AOutput.GetIndex() - 5); signature := GetSignature(tmp); AOutput.PutString(signature); FKeyExchange := False; except AOutput.Free(); raise; end; end else if (AInput.Buffer[5] = SSH_MSG_USERAUTH_FAILURE) then begin AuthFailure(AInput); Result := sarFail; end else if (AInput.Buffer[5] = SSH_MSG_USERAUTH_BANNER) then begin ShowBanner(AInput); end else begin raise EclSshError.Create(UserAuthError, AInput.Buffer[5]); end; end; end.
unit clRestricaoEntrega; interface uses clConexao; type TRestricaoEntrega = Class(TObject) private function getNossoNumero: String; function getRestricao: Integer; procedure setNossoNumero(const Value: String); procedure setRestricao(const Value: Integer); constructor Create; destructor Destroy; protected _restricao: Integer; _nossonumero: String; _conexao: TConexao; public property Restricao: Integer read getRestricao write setRestricao; property NossoNumero: String read getNossoNumero write setNossoNumero; function Validar(): Boolean; function Delete(filtro: String): Boolean; function getObject(id, filtro: String): Boolean; function Insert(): Boolean; end; const TABLENAME = 'TBRESTRICAOENTREGA'; implementation { TRestricaoEntrega } uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB; constructor TRestricaoEntrega.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TRestricaoEntrega.Destroy; begin _conexao.Free; end; function TRestricaoEntrega.getNossoNumero: String; begin Result := _nossonumero; end; function TRestricaoEntrega.getRestricao: Integer; begin Result := _restricao; end; function TRestricaoEntrega.Validar(): Boolean; begin try Result := False; if Self.Restricao = 0 then begin MessageDlg('Código da Restrição incorreto!', mtWarning, [mbOK], 0); Exit; end; if TUtil.Empty(Self.NossoNumero) then begin MessageDlg('Informe o Nosso Número!', mtWarning, [mbOK], 0); Exit; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricaoEntrega.Delete(filtro: String): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_RESTRICAO = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Restricao; end else if filtro = 'NOSSONUMERO' then begin SQL.Add('WHERE NUM_NOSSONUMERO = :NOSSONUMERO AND COD_RESTRICAO = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Restricao; ParamByName('NOSSONUMERO').AsString := Self.NossoNumero; end; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricaoEntrega.getObject(id, filtro: String): Boolean; begin try Result := False; if TUtil.Empty(id) then Exit; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_RESTRICAO = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Restricao; end else if filtro = 'NOSSONUMERO' then begin SQL.Add('WHERE NUM_NOSSONUMERO = :NOSSONUMERO'); ParamByName('NOSSONUMERO').AsString := Self.NossoNumero; end; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount = 1 then begin Self.Restricao := dm.QryGetObject.FieldByName('COD_RESTRICAO').AsInteger; Self.NossoNumero := dm.QryGetObject.FieldByName ('NUM_NOSSONUMERO').AsString; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Result := True; end else if dm.QryGetObject.RecordCount > 1 then begin Result := True; Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricaoEntrega.Insert(): Boolean; begin Try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'COD_RESTRICAO, ' + 'NUM_NOSSONUMERO) ' + 'VALUES (' + ':CODIGO, ' + ':NOSSONUMERO)'; ParamByName('CODIGO').AsInteger := Self.Restricao; ParamByName('NOSSONUMERO').AsString := Self.NossoNumero; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; MessageDlg('Os dados foram salvos com sucesso!', mtInformation, [mbOK], 0); Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TRestricaoEntrega.setNossoNumero(const Value: String); begin _nossonumero := Value; end; procedure TRestricaoEntrega.setRestricao(const Value: Integer); begin _restricao := Value; end; end.
(*------------------------------------------------------------------ BinominalCoefficientNice || Neuhold Michael 24.10.2018 Calculate the binomial coefficient (k choose n). introducing a Factorial function bc = n! DIV (k! *(n-k)!) ------------------------------------------------------------------*) PROGRAM BinominalCoefficient; USES Crt; FUNCTION Factorial (n: INTEGER): LONGINT (* bei function nur call by value erlaubt *) VAR i : INTEGER; nf: LONGINT; BEGIN nf := 1; FOR i := 2 TO n DO BEGIN nf := nf * i; END; (* FOR *) Factorial := nf; (* Rückgabewert *) END; (* Factorial *) VAR k,n: INTEGER; kf, nf, nkf: LONGINT; (* kf .. k!, nf .. n!, nkf .. (n-k)! *) bc: LONGINT; (* binomial coefficient *) BEGIN WriteLn('Berechnung des Binominalkoeffizienten'); WriteLn('<#---------------------------------#>'); Write('n > '); ReadLn(n); Write('k > '); ReadLn(k); nf := Factorial(n); (* Function aufrufen Berechne: n! --> Rückgabewert in Variable speichern *) kf := Factorial(k); (* Function aufrufen Berechne: k! --> Rückgabewert in Variable speichern*) nkf := Factorial(n-k); (* Function aufrufen Berechne: (n-k)! --> Rückgabewert in Variable speichern*) bc := nf DIV (kf * nkf); (* DIV oder / *) (* Es geht auch: bc := Factorial(n) DIV (Factorial(k) * Factorial(nkf)); *) WriteLN('BinominalCoefficient ', n, ' über ', k, ' = ', bc); END. (* BinominalCoefficient *)
unit eAtasOrais.Model.ClasseAlunosConceitos; interface Type tAlunosConceitos = class Private FConceito: string; FAluno: string; procedure SetAluno(const Value: string); procedure SetConceito(const Value: string); Public Property Aluno : string read FAluno write SetAluno; Property Conceito : string read FConceito write SetConceito; end; implementation uses eAtasOrais.Model.Factory; { tAlunosConceitos } procedure tAlunosConceitos.SetAluno(const Value: string); begin FAluno := tmodelFactory.New.Funcoes.FormataNomeAluno(Value); end; procedure tAlunosConceitos.SetConceito(const Value: string); begin FConceito := Value; end; end.
{ Subroutine SST_W_C_POS_POP * * Pop old writing position from stack and restore it as the current writing * position. This subroutine is a matched pair with SST_W_POS_PUSH. } module sst_w_c_POS_POP; define sst_w_c_pos_pop; %include 'sst_w_c.ins.pas'; procedure sst_w_c_pos_pop; {pop old position from stack and restore} var frame_p: frame_posp_p_t; {pointer to this stack frame} begin util_stack_last_frame ( {make pointer to last stack frame} sst_stack, sizeof(frame_p^), frame_p); sst_out.dyn_p := frame_p^.dyn_p; {restore to old position handle} frame_scope_p^.sment_type := frame_p^.sment_type; {restore statement type} util_stack_pop (sst_stack, sizeof(frame_p^)); {remove frame from stack} %debug; write (sst_stack^.last_p^.curr_adr, ' '); %debug; writeln ('POS POP'); end;
{ Demo for fast html parser Try arrays } program project1; {$mode objfpc}{$H+} uses fasthtmlparser, // html parser arrhtmlparser, // same as fasthtmlparser but stores all tags/text in an array for later use sysutils; const HTMStringA = '<html><head></head><body><p>some text</p> <b>text in bold tag</b> more text <p><b>more bold</b></p> and the end of html</body></html>'; var InBold: boolean = false; procedure msg(s: string); begin writeln(s); end; procedure msg(s1,s2: string); begin writeln(s1,s2); end; procedure msg(s1: string; i: integer); begin writeln(s1,i); end; // TOnFoundTagP = procedure(NoCaseTag, ActualTag: string); // TOnFoundTextP = procedure(Text: string); procedure ExOnTag(NoCaseTag, ActualTag: string); begin if NoCaseTag = '<B>' then begin InBold := true; msg('bold start'); end; if NoCaseTag = '</B>' then begin InBold := false; msg('bold end'); end; end; procedure ExOnText(Text: string); begin if InBold then begin msg('Text tag: ', Text); end; end; procedure Example1; var hp: THTMLParser; begin hp := THTMLParser.create(HTMStringA); hp.OnFoundTagP := @ExOnTag; hp.OnFoundTextP := @ExOnText; hp.Exec; hp.free; hp := nil; end; procedure Example2; var ahp: TArrHTMLParser; i: integer; begin ahp := TArrHTMLParser.create(HTMStringA); ahp.OnFoundTagP := @ExOnTag; ahp.OnFoundTextP := @ExOnText; ahp.Exec; msg('Printing all tag items:'); msg('Length of Tags array: ',length(ahp.Tags)); // print out all tags in array for i := low(ahp.Tags) to high(ahp.Tags) do begin writeln(i,':',ahp.Tags[i]); end; msg('Printing all text items:'); msg('Length of Texts array: ', length(ahp.Texts)); // print out all texts in array for i := low(ahp.Texts) to high(ahp.Texts) do begin writeln(i,':',ahp.Texts[i]); end; ahp.free; ahp := nil; end; procedure Line; begin writeln('-----------------------------------------------'); end; begin Example1; Line; Example2; Line; ReadLn; // pause program on exit for <enter> to quit end.
unit ManuallyConnectTask; interface uses Tasks, Kernel, Accounts, CacheAgent, BackupInterfaces, Inventions, FacIds; type TMetaManuallyConnectTask = class(TMetaTask) private fToFacId : TFacId; fFromFacId : TFacId; public property ToFacId : integer read fToFacId write fToFacId; property FromFacId : integer read fFromFacId write fFromFacId; end; TManuallyConnectTask = class(TAtomicTask) public Connected : boolean; public function Execute : TTaskResult; override; private procedure MsgManuallyConnect(var Msg : TMsgFacsConnect); message msgKernel_SellToAll; public procedure StoreToCache(Prefix : string; Cache : TObjectCache); override; end; procedure RegisterBackup; implementation uses TaskUtils, ResidentialTasks, ClassStorage; // TManuallyConnectTask procedure TManuallyConnectTask.MsgManuallyConnect(var Msg : TMsgFacsConnect); begin if (Msg.Fac1 <> nil) and (Msg.Fac2 <> nil) and (Msg.Fac1.MetaFacility.FacId = TMetaManuallyConnectTask(MetaTask).ToFacId) and (Msg.Fac2.MetaFacility.FacId = TMetaManuallyConnectTask(MetaTask).FromFacId) then Connected := True; end; function TManuallyConnectTask.Execute : TTaskResult; begin if Connected then result := trFinished else result := trContinue; end; procedure TManuallyConnectTask.StoreToCache(Prefix : string; Cache : TObjectCache); begin inherited; Cache.WriteInteger(Prefix + 'IndustryId', TMetaManuallyConnectTask(MetaTask).FromFacId); end; procedure RegisterBackup; begin RegisterClass(TManuallyConnectTask); end; end.
unit Map; interface uses Engine, MapCustom, Tile; type TCell = record ID: Byte; // Tile : Tiles; end; TCells = array of array of TCell; TMap = class(TMapCustom) private Tile: TTiles; FCell: TCells; public property Cell: TCells read FCell write FCell; procedure Render(PCX, PCY: Integer); procedure Clear; override; function GetCell(X, Y: Integer): TCell; procedure SetCell(X, Y: Integer; Cell: TCell); procedure Save; procedure Load; procedure Gen; constructor Create; destructor Destroy; override; end; implementation { TMap } procedure TMap.Clear; var X, Y: Integer; begin for X := 0 to Width - 1 do for Y := 0 to Height - 1 do ; // SetCell(X, Y, 0); end; constructor TMap.Create; begin inherited; Tile := TTiles.Create; end; destructor TMap.Destroy; begin Tile.Free; inherited; end; function TMap.GetCell(X, Y: Integer): TCell; begin Result := FCell[Y][X]; end; procedure TMap.Render(PCX, PCY: Integer); var DX, DY, X, Y: Integer; begin MAP_TOP := PCY - GAME_SCR_HEIGHT div 2; MAP_LEFT := PCX - GAME_SCR_WIDTH div 2; for Y := -1 to GAME_SCR_HEIGHT do for X := -1 to GAME_SCR_WIDTH do Tile.Render(X, Y, 0); //{GetCell(X + Left, Y + Top).ID}); end; procedure TMap.Gen; begin end; procedure TMap.Load; begin end; procedure TMap.Save; begin end; procedure TMap.SetCell(X, Y: Integer; Cell: TCell); begin FCell[Y][X] := Cell; end; end.
unit qrFramelines; {==================================================================== Class TQRFrameline Placed on a band, these controls make vertical lines at the XPos location. (c) 2005 QBS Software DLM - march 2005 : Thanks to Mark Yang for the notion of a frame grid. ====================================================================} interface uses Classes, Controls, StdCtrls, SysUtils, Graphics, Buttons, ComCtrls, QuickRpt, QR6Const; type TQRFrameline = class(TQRPrintable) protected procedure Paint; override; procedure Print(OfsX, OfsY : integer); override; public constructor Create( aOwner : TComponent); override; published property Left; end; procedure Register; implementation procedure Register; begin RegisterComponents( 'QReport', [TQRFrameline] ); end; constructor TQRFrameline.Create( aOwner : TComponent); begin // we don't do anything but maybe in a later version inherited Create( aOwner); end; procedure TQRFrameline.Print(OfsX, OfsY : integer); begin // do nothing. Painted by TQRFrame.PaintIt end; procedure TQRFrameline.Paint; begin inherited paint; canvas.MoveTo(Width div 2,0); canvas.LineTo(Width div 2,Height); end; end.
unit ddServerBaseEngine; interface {$Include csDefine.inc} uses CsDataPipe, CsServer, csCommon, daDataProviderParams, ddBaseEngine, daTypes; type TServerBaseEngine = class(TBaseEngine) private f_CSServer: TCSServer; f_ServerHostName: String; f_ServerPort: Integer; f_AutolinkEnabled: Boolean; procedure ServerLoginExData(out aDataParams: TdaDataProviderParams; out TheFlags: TdaBaseFlags); procedure ServerGetIsBaseLocked(out theIsBaseLocked: Boolean); function _ReIndexTable(const aFileName: AnsiString): Boolean; function pm_GetBaseFlags: TdaBaseFlags; function CSCheckPassword(const aLoginName, aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TCsClientID): Boolean; protected procedure CreateCommunications; override; function DoStart: Boolean; override; procedure DoStop; override; function pm_GetWorkWithServer: Boolean; override; function pm_GetServerHostName: AnsiString; override; function pm_GetServerPort: Integer; override; public constructor Make(const aDataParams: TdaDataProviderParams; const aServerHostName: AnsiString; aServerPort: Integer = 32100; AutolinkEnabled: Boolean = False); procedure cs_GetBaseStatus(aPipe: TCSDataPipe); procedure ReindexTables(aFamily: Integer); procedure RepairTable(const aTable: AnsiString); // function TablePass(const aTable: AnsiString): PAnsiChar; property CSServer: TCSServer read f_CSServer; property BaseFlags: TdaBaseFlags read pm_GetBaseFlags; end; implementation Uses dt_Serv, l3IniFile, l3Base, ddFileIterator, ht_dll, StrUtils, SysUtils, daDataProvider, htDataProviderParams, daDataProviderSuperFactory, m3StgMgr ; const c_TablePass = 'corvax'; constructor TServerBaseEngine.Make(const aDataParams: TdaDataProviderParams; const aServerHostName: string; aServerPort: Integer = 32100; AutolinkEnabled: Boolean = False); begin Create(aDataParams); f_ServerHostName := aServerHostName; f_ServerPort := aServerPort; f_AutolinkEnabled := AutolinkEnabled; end; procedure TServerBaseEngine.CreateCommunications; begin if CSServer = nil then f_CSServer := TCSServer.Create('', CSCheckPassword); end; procedure TServerBaseEngine.cs_GetBaseStatus(aPipe: TCSDataPipe); var l_Msg: AnsiString; begin Guard.Acquire; try aPipe.WriteSmallInt(SmallInt(Ord(IsbaseLocked(l_Msg)))); aPIpe.WriteLn(l_Msg); finally Guard.Leave; end; end; function TServerBaseEngine.DoStart: Boolean; begin TdaDataProviderSuperFactory.Instance.LoadDBVersion(DataParams); // DocBaseVersion := l_DocBaseVersion; // AdminBaseVersion:= l_AdminBaseVersion; if not TdaDataProviderSuperFactory.Instance.IsParamsValid(DataParams) then begin Result := False; Exit; end; CreateDataProvider; // CreateHtEx(StationName, (DataParams as ThtDataProviderParams).MakePathRec, DataParams.DocBaseVersion, DataParams.AdminBaseVersion, (DataParams as ThtDataProviderParams).AliasesList); if CSServer = nil then f_CSServer := TCSServer.Create('', CSCheckPassword); f_CSServer.OnLoginExData := ServerLoginExData; f_CSServer.OnGetIsBaseLocked := ServerGetIsBaseLocked; DataProvider.LoginAsServer; Result:= True; end; function TServerBaseEngine.CSCheckPassword(const aLoginName: AnsiString; const aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TCsClientID): Boolean; begin Result := GlobalDataProvider.UserManager.CSCheckPassword(aLoginName, aPassword, RequireAdminRights, theUserID); end; procedure TServerBaseEngine.DoStop; begin DestroyDataProvider; l3Free(f_CSServer) end; procedure TServerBaseEngine.ReindexTables(aFamily: Integer); begin // *.htb with TddFileIterator.Create do try FileMask:= '*.htb'; Directory:= GetFamilyPath(aFamily); LoadFiles; Stop; IterateFiles(_ReIndexTable); Start; finally Free; end; end; procedure TServerBaseEngine.RepairTable(const aTable: AnsiString); var l_WrongRecords: Integer; l_Pass: PAnsiChar; begin l_Pass := TablePass(aTable); l_WrongRecords := htRepairTable(PAnsiChar(aTable), l_Pass, l_Pass); htUpdateTable(PAnsiChar(aTable), l_Pass, l_Pass, True, False); htRepairTableLog(PAnsiChar(aTable), l_Pass, l_Pass, 0); //if l_WrongRecords > 0 then // Log(Format('Из таблицы %s вычищено %d поврежденных записей.', [aTable, l_WrongRecords])); end; procedure TServerBaseEngine.ServerLoginExData(out aDataParams: TdaDataProviderParams; out TheFlags: TdaBaseFlags); begin aDataParams := DataParams; theFlags := BaseFlags; end; function TServerBaseEngine.TablePass(const aTable: AnsiString): PAnsiChar; var l_Mode: Integer; l_Success: Boolean; l_TableName: AnsiString; begin try l_Success := htTableHeadPswd(PAnsiChar(aTable), l_Mode) = 0; except l_Success := false; end; if l_Success then begin if l_Mode > 0 then Result := PAnsiChar(c_TablePass+#0) else Result := nil; end else begin l_TableName := AnsiUpperCase(ChangeFileExt(ExtractFileName(aTable), '')); if (l_TableName = 'ACCESS') or (l_TableName = 'PASS') or (l_TableName = 'BB_LOG') then Result := PAnsiChar(c_TablePass+#0) else Result := nil; end; end; function TServerBaseEngine._ReIndexTable(const aFileName: AnsiString): Boolean; var l_Pass: PAnsiChar; begin l_Pass := TablePass(aFileName); Result:= htUpdateTable(PAnsiChar(aFileName), l_Pass, l_Pass, True, True) = 0; end; function TServerBaseEngine.pm_GetBaseFlags: TdaBaseFlags; begin Result := []; {$IFDEF AAC} Include(Result, bfAAC); {$ENDIF AAC} if f_AutolinkEnabled then Include(Result, bfAutoLink); end; procedure TServerBaseEngine.ServerGetIsBaseLocked( out theIsBaseLocked: Boolean); begin theIsBaseLocked := IsBaseLocked; end; function TServerBaseEngine.pm_GetWorkWithServer: Boolean; begin Result := True; end; function TServerBaseEngine.pm_GetServerHostName: AnsiString; begin Result := f_ServerHostName; end; function TServerBaseEngine.pm_GetServerPort: Integer; begin Result := f_ServerPort; end; end.
{ Invokable interface IServico } unit ServicoIntf; interface uses InvokeRegistry, Types, XSBuiltIns, Classes, uLib; type { Invokable interfaces must derive from IInvokable } IServico = interface(IInvokable) ['{C10CE1E8-ED99-4A45-9DFD-ABDD9B0DEACB}'] function SendNotFis(ChaveAut: string; aNomeArquivo: string; aConteudoArquivo: WideString): string; stdcall; function GetOcorren(Filial, TpChave, Chave: string; dtInicial: string = ''; dtFinal: string = ''): string; stdcall; { Methods of Invokable interface must not use the default } { calling convention; stdcall is recommended } end; implementation initialization { Invokable interfaces must be registered } InvRegistry.RegisterInterface(TypeInfo(IServico)); end.
// ------------------------------------------------------------------------- // // // // Unit: Math // // Versão: 1.1v // //---------------------------------------------------------------------------// Unit Math ; Interface // contrato para a definição das funções descritas Const AUREA = 1.61803398875; {constante áurea} E = 2.71828182846; {número de Euler} HALF_PI = 1.57079632679; {metade de PI} TAL = 6.28318530718; {dobro de PI} LN_2 = 0.69314718056; {logaritmo natural de 2} LN_10 = 2.30258509299; {logaritmo natural de 10} // Funções trigonométricas function tan(a : real) : real; {tangente de [a]} function cot(a : real) : real; {cotangente de [a]} function csc(a : real) : real; {cossecante de [a]} function sec(a : real) : real; {secante de [a]} function sinh(a : real) : real; {seno hiperbólico de [a]} function cosh(a : real) : real; {coseno hiberbólico de [a]} function tanh(a : real) : real; {tangente hiperbólica de [a]} function coth(a : real) : real; {cotangente hiperbólica de [a]} function csch(a : real) : real; {cossecante hiperbólica de [a]} function sech(a : real) : real; {secante hiperbólica de [a]} function arcsin(a : real) : real; {arco seno de [a]} function arccos(a : real) : real; {arco cosseno de [a]} function arccot(a : real) : real; {arco cotangente de [a]} function arccsc(a : real) : real; {arco cosecante de [a]} function arcsec(a : real) : real; {arco secante de [a]} function arcsinh(a : real) : real; {arco seno hiberbólico de [a]} function arccosh(a : real) : real; {arco cosseno hiberbólico de [a]} function arctanh(a : real) : real; {arco tangente hiberbólico de [a]} function arccoth(a : real) : real; {arco cotangente hiberbólico de [a]} function arccsch(a : real) : real; {arco cossecante hiberbólico de [a]} function arcsech(a : real) : real; {arco secante hiberbólico de [a]} // Funções logarítmicas function log10(n : real) : real; {logaritmo de [n] na base 10} function log2(n : real) : real; {logaritmo de [n] na base 2} function log(n, m : real) : real; {logaritmo de [n] na base [m]} // Números aletórios function simpleRandom() : real; {número aleatório entre 0 e 1} function randomBetween(a, b : real) : real; {número aleatório entre [a] e [b]} function randomGaussian() : real; {número aleatório com distribuição normal} // Funções exponenciais function pow(x, n : real) : real; {[x] elevado a [n]} function exp2(x : real) : real; {2 elevado a [x]} function exp10(x : real) : real; {10 elevado a [x]} // Funções geométricas function hypot(a, b : real) : real; {hipotenusa dos catetos [a] e [b]} function radian(a : real) : real; {Converte graus para radianos} function degree(a : real) : real; {Converte radianos para graus} // Outras function min(a, b : real) : real; {retorna o menor valor entre [a] e [b]} function max(a, b : real) : real; {retorna o maior valor entre [a] e [b]} function constrain(a, b, c : real) : real; {limita o valor [a] dentro dos limites [b] e [c]} function gaussian(x, sigma : real) : real; {função gaussiana} function logistic(x, a : real) : real; {função logística, sendo [a] a constante de inclinação} function factorial(n : integer) : integer; {Calcula o fatorial de [n]} Implementation // implementação das funções descritas na interface escrita acima // ------------------------------------------------------------------------- // // Calcula a tangente do ângulo[a], sendo: // // tan(a) = sin(a)/cos(a) // // ------------------------------------------------------------------------- // function tan(a : real) : real; begin tan := sin(a)/cos(a); end; // ------------------------------------------------------------------------- // // Calcula a cotangente do ângulo[a], sendo: // // cot(a) = cos(a)/sin(a) // // ------------------------------------------------------------------------- // function cot(a : real) : real; begin cot := cos(a)/sin(a); end; // ------------------------------------------------------------------------- // // Calcula a cossecante do ângulo[a], sendo: // // csc(a) = 1/sin(a) // // ------------------------------------------------------------------------- // function csc(a : real) : real; begin csc := 1/sin(a); end; // ------------------------------------------------------------------------- // // Calcula a secante do ângulo[a], sendo: // // sec(a) = 1/cos(a) // // ------------------------------------------------------------------------- // function sec(a : real) : real; begin sec := 1/cos(a); end; // ------------------------------------------------------------------------- // // Calcula o seno hiperbólico do ângulo[a], sendo: // // sinh(a) = (exp(a) - exp(-a))/2 // // ------------------------------------------------------------------------- // function sinh(a : real) : real; begin sinh := (exp(a) - exp(-a))/2; end; // ------------------------------------------------------------------------- // // Calcula o coseno hiperbólico do ângulo[a], sendo: // // sinh(a) = (exp(a) - exp(-a))/2 // // ------------------------------------------------------------------------- // function cosh(a : real) : real; begin cosh := (exp(a) + exp(-a))/2; end; // ------------------------------------------------------------------------- // // Calcula a tangente hiperbólica do ângulo[a], sendo: // // tanh(a) = (exp(a) - exp(-a))/(exp(a) + exp(-a)) // // ------------------------------------------------------------------------- // function tanh(a : real) : real; begin tanh := (exp(a) - exp(-a))/(exp(a) + exp(-a)); end; // ------------------------------------------------------------------------- // // Calcula a cotangente hiperbólica do ângulo[a], sendo: // // coth(a) = (exp(a) + exp(-a))/(exp(a) - exp(-a)) // // ------------------------------------------------------------------------- // function coth(a : real) : real; begin coth := (exp(a) + exp(-a))/(exp(a) - exp(-a)); end; // ------------------------------------------------------------------------- // // Calcula a cossecante hiperbólica do ângulo[a], sendo: // // csch(a) = 2/(exp(a) - exp(-a)) // // ------------------------------------------------------------------------- // function csch(a : real) : real; begin csch := 2/(exp(a) - exp(-a)); end; // ------------------------------------------------------------------------- // // Calcula a secante hiperbólica do ângulo[a], sendo: // // sech(a) = 2/(exp(a) + exp(-a)) // // ------------------------------------------------------------------------- // function sech(a : real) : real; begin sech := 2/(exp(a) + exp(-a)); end; // ------------------------------------------------------------------------- // // Calcula o arco seno de [a], sendo: // // Fonte: http://mathworld.wolfram.com/InverseSine.html // // arcsin(a) = arctan(a / sqrt(1 - a * a )) // // ------------------------------------------------------------------------- // function arcsin(a : real) : real; var num : real; begin num := sqrt(1 - a * a); if num <> 0 then arcsin := arctan(a / num) else begin if a > 0 then arcsin := 1.5707963267948966 else if a < 0 then arcsin := -1.5707963267948966 else begin writeln('Erro: Função ''arcsin''.'); end; end; end; // ------------------------------------------------------------------------- // // Calcula o arco cosseno de [a], sendo: // // fonte: http://mathworld.wolfram.com/InverseCosine.html // // arcsin(a) = HALF_PI - arctan(a / sqrt(1 - a * a)) // // ------------------------------------------------------------------------- // function arccos(a : real) : real; var num : real; begin num := sqrt(1 - a * a); if num <> 0 then arccos := HALF_PI - arctan(a / num) else begin if a > 0 then arccos := HALF_PI - 1.5707963267948966 else if a < 0 then arccos := HALF_PI + 1.5707963267948966 else begin writeln('Erro: Função ''arccos''.'); end; end; end; // ------------------------------------------------------------------------- // // Calcula o arco cotangente de [a], sendo: // // fonte : http://mathworld.wolfram.com/InverseCotangent.html // // arccot(a) = a < 0 ? -HALF_PI - arctan(a) : HALF_PI - arctan(a) // // ------------------------------------------------------------------------- // function arccot(a : real) : real; begin if a < 0 then arccot := -HALF_PI - arctan(a) else arccot := HALF_PI - arctan(a); end; // ------------------------------------------------------------------------- // // Calcula o arco cosecante de [a], sendo: // // fonte : http://mathworld.wolfram.com/InverseCosecant.html // // arccsc(a) = a < -1 ? -arccot(sqrt(a * a - 1)) : arccot(sqrt(a * a - 1)) // // ------------------------------------------------------------------------- // function arccsc(a : real) : real; begin if a < -1 then arccsc := -arccot(sqrt(a * a - 1)) else arccsc := arccot(sqrt(a * a - 1)); end; // ------------------------------------------------------------------------- // // Calcula o arco secante de [a], sendo: // // fonte : http://mathworld.wolfram.com/InverseSecant.html // // arcsec(a) = a < -1 ? pi - arctan(sqrt(a * a - 1)) : // // arctan(sqrt(a * a - 1)) // // ------------------------------------------------------------------------- // function arcsec(a : real) : real; begin if a < -1 then arcsec := pi - arctan(sqrt(a * a - 1)) else arcsec := arctan(sqrt(a * a - 1)); end; // ------------------------------------------------------------------------- // // Calcula o arco seno hiperbólico de [a], sendo: // // fonte : http://mathworld.wolfram.com/InverseHyperbolicSine.html // // arcsinh(a) = ln(a + sqrt(a*a + 1)) // // ------------------------------------------------------------------------- // function arcsinh(a : real) : real; begin arcsinh := ln(a + sqrt(a * a + 1)); end; // ------------------------------------------------------------------------- // // Calcula o arco coseno hiperbólico de [a], sendo: // // fonte : http://mathworld.wolfram.com/InverseHyperbolicCosine.html // // arccosh(a) = ln(a + sqrt(a*a + 1) * sqrt(a*a - 1)) // // ------------------------------------------------------------------------- // function arccosh(a : real) : real; begin arccosh := ln(a + sqrt(a * a - 1)); end; // ------------------------------------------------------------------------- // // Calcula o arco tangente hiperbólico de [a], sendo: // // fonte : http://mathworld.wolfram.com/InverseHyperbolicTangent.html // // arctanh(a) = ln((1 + a)/(1 - a))/2 // // ------------------------------------------------------------------------- // function arctanh(a : real) : real; begin arctanh := ln((1 + a)/(1 - a))/2; end; // ------------------------------------------------------------------------- // // Calcula o arco cotangente hiperbólico de [a], sendo: // // fonte : http://www.mathworks.com/help/matlab/ref/acoth.html // // arccoth(a) = ln((1 + 1/a)/(1 - 1/a))/2 // // ------------------------------------------------------------------------- // function arccoth(a : real) : real; begin arccoth := ln((1 + 1/a)/(1 - 1/a))/2; end; // ------------------------------------------------------------------------- // // Calcula o arco cossecante hiperbólico de [a], sendo: // // fonte : http://mathworld.wolfram.com/InverseHyperbolicCosecant.html // // arccsch(a) = a < 0 ? ln((1 - sqrt(a * a + 1))/a) : // // ln((1 + sqrt(a * a + 1))/a) // // ------------------------------------------------------------------------- // function arccsch(a : real) : real; begin if a < 0 then arccsch := ln((1 - sqrt(a * a + 1))/a) else arccsch := ln((1 + sqrt(a * a + 1))/a); end; // ------------------------------------------------------------------------- // // Calcula o arco secante hiperbólico de [a], sendo: // // fonte : http://mathworld.wolfram.com/InverseHyperbolicSecant.html // // arcsech(a) = a < 0 ? ln((1 - sqrt(1 - a * a))/a) : // // ln((1 + sqrt(1 - a * a))/a) // // ------------------------------------------------------------------------- // function arcsech(a : real) : real; begin if a < 0 then arcsech := ln((1 - sqrt(1 - a * a))/a) else arcsech := ln((1 + sqrt(1 - a * a))/a); end; // ------------------------------------------------------------------------- // // Calcula o logaritmo de [n] na base 10, sendo: // // log10(n) = ln(n)/ln(10) // // = ln(n)/2.30258509299 // // ------------------------------------------------------------------------- // function log10(n : real) : real; begin log10 := ln(n)/LN_10; end; // ------------------------------------------------------------------------- // // Calcula o logaritmo de [n] na base 2, sendo: // // log2(n) = ln(n)/ln(10) // // = ln(n)/0.69314718056} // // ------------------------------------------------------------------------- // function log2(n : real) : real; begin log2 := ln(n)/LN_2; end; // ------------------------------------------------------------------------- // // Calcula o logaritmo de [n] na base [m], sendo: // // log(n, m) = ln(n)/ln(m) // // ------------------------------------------------------------------------- // function log(n, m : real) : real; begin log := ln(n)/ln(m); end; // ------------------------------------------------------------------------- // // Gera um número aleatório entre 0..1 // // ------------------------------------------------------------------------- // function simpleRandom() : real; begin simpleRandom := (random(maxint) + 1)/maxint; end; // ------------------------------------------------------------------------- // // Gera um número aleatório entre [a] e [b] // // ------------------------------------------------------------------------- // function randomBetween(a, b : real) : real; begin randomBetween := a + (b - a) * (random(maxint) + 1)/maxint; end; // ------------------------------------------------------------------------- // // Gera um número aleatório com distribuição normal // // ------------------------------------------------------------------------- // function randomGaussian() : real; begin if random(2) = 0 then randomGaussian := sqrt(-2 * ln((random(maxint) + 1)/maxint)) * sin((random(maxint) + 1)/maxint) else randomGaussian := -sqrt(-2 * ln((random(maxint) + 1)/maxint)) * sin((random(maxint) + 1)/maxint); end; // ------------------------------------------------------------------------- // // Calcula [x] elevado a [n], sendo: // // pow(x, n) = exp(ln(x) * n) // // ------------------------------------------------------------------------- // function pow(x, n : real) : real; begin pow := exp(ln(x) * n); end; // ------------------------------------------------------------------------- // // Calcula o valor de 2^x, sendo: // // exp2(x) = exp(ln(2) * x) // // ------------------------------------------------------------------------- // function exp2(x : real) : real; begin exp2 := exp(LN_2 * x); end; // ------------------------------------------------------------------------- // // Calcula o valor de 10^x, sendo: // // exp10(x) = exp(ln(10) * x) // // ------------------------------------------------------------------------- // function exp10(x : real) : real; begin exp10 := exp(LN_10 * x); end; // ------------------------------------------------------------------------- // // Retorna a hipotenusa do triângulo retângulo: // // hypot(a, b) = sqrt(a * a + b * b) // // ------------------------------------------------------------------------- // function hypot(a, b : real) : real; begin hypot := sqrt(a * a + b * b); end; // ------------------------------------------------------------------------- // // Converte graus em radianos: // // radian(a) = a * PI/180 // // ------------------------------------------------------------------------- // function radian(a : real) : real; begin radian := a * 0.01745329251; end; // ------------------------------------------------------------------------- // // Converte radianos em graus: // // radian(a) = a * 180/PI // // ------------------------------------------------------------------------- // function degree(a : real) : real; begin degree := a * 57.2957795131; end; // ------------------------------------------------------------------------- // // Retorna o maior valor: // // max(a, b) = a > b ? a : b; // // ------------------------------------------------------------------------- // function max(a, b : real) : real; begin if a > b then max := a else max := b; end; // ------------------------------------------------------------------------- // // Retorna o menor valor: // // min(a, b) = a < b ? a : b; // // ------------------------------------------------------------------------- // function min(a, b : real) : real; begin if a < b then min := a else min := b; end; // ------------------------------------------------------------------------- // // Limita o valor [a] dentro dos limites [b] e [c] // // ------------------------------------------------------------------------- // function constrain(a, b, c : real) : real; begin if a > c then constrain := c else if a < b then constrain := b else constrain := a; end; // ------------------------------------------------------------------------- // // Calcula o valor da função gaussiana, sendo: // // gaussian(x) = exp(-x * x) // // ------------------------------------------------------------------------- // function gaussian(x, sigma : real) : real; begin gaussian := exp(-x * x/(2 * sigma * sigma)); end; // ------------------------------------------------------------------------- // // Calcula o valor da função logística, sendo [a] a constante de inclinação: // // logistics(x) = 1/(1 + exp(-x * a) // // ------------------------------------------------------------------------- // function logistic(x, a : real) : real; begin logistic := 1/(1 + exp(-x * a)); end; // ------------------------------------------------------------------------- // // Calcula o fatorial do número [n] // // ------------------------------------------------------------------------- // function factorial(n : integer) : integer; var i, num : integer; begin num := 1; for i := n downto 2 do num := num * i; factorial := num; end; End.
unit HouseWorkForma; interface uses Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Mask, System.Classes, Data.DB, WinAPI.Windows, WinAPI.Messages, System.SysUtils, System.Variants, VCL.Graphics, VCL.Dialogs, Vcl.DBCtrls, DBLookupEh, OkCancel_frame, DBGridEh, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, DBCtrlsEh; type THouseWorkForm = class(TForm) edtDateWork: TDBDateTimeEditEh; dbcbWorker: TDBLookupComboboxEh; dbmmo1: TDBMemoEh; okcnl: TOkCancelFrame; lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; srcWork: TDataSource; dsWork: TpFIBDataSet; dsWorker: TpFIBDataSet; trRead: TpFIBTransaction; trWrite: TpFIBTransaction; srcWorker: TDataSource; procedure okcnlbbOkClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; function HouseWorkEdit(const aH_ID: Int64; aHW_ID: Int64): Boolean; implementation uses DM; {$R *.dfm} function HouseWorkEdit(const aH_ID: Int64; aHW_ID: Int64): Boolean; begin result := False; with THouseWorkForm.Create(Application) do try dsWorker.Open; if aHW_ID = -1 then begin dsWork.Open; dsWork.Insert; dsWork['HOUSE_ID'] := aH_ID; if (dmMain.GetIniValue('SET_AS_CURRENT_DATE') <> '0') then dsWork['DATE_PPR'] := Now(); // edtDateWork.Value := NOW; end else begin dsWork.ParamByName('HW_ID').AsInt64 := aHW_ID; dsWork.Open; end; if ShowModal = mrOk then begin if dsWork.State in [dsEdit, dsInsert] then dsWork.Post; result := True; end; finally dsWorker.Close; Free; end; end; procedure THouseWorkForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then okcnlbbOkClick(Sender); end; procedure THouseWorkForm.okcnlbbOkClick(Sender: TObject); begin if VarIsNull(edtDateWork.Value) then okcnl.bbOk.ModalResult := mrNone; if VarIsNull(dbcbWorker.Value) then okcnl.bbOk.ModalResult := mrNone; end; end.
unit jc.S3Amazon; interface uses Classes, SysUtils, Data.Cloud.CloudAPI, Data.Cloud.AmazonAPI, IPPeerClient; type TAws = class private class var FInstance: TAws; FConnection: TAmazonConnectionInfo; FS3: TAmazonStorageService; FS3Region: TAmazonRegion; FAccessKey: String; FSecretKey: String; FRegion: string; FEndPoint: string; public constructor create(const AccessKey, SecretKey: String); destructor destroy; override; class function New(): TAws; overload; class function New(const AccessKey, SecretKey: String): TAws; overload; function getEndPoint: String; function getRegion: String; function GetAmazonStorage: TAmazonStorageService; function getBuckets: TStrings; function getBucket(AName: String): TAmazonBucketResult; function DownloadObject(const ABucket, AFile, AOutPath: string): boolean; function UploadObject(const ABucket, AFile, AFileName: string): boolean; function DeleteObject(const ABucket, AFile: string): boolean; end; implementation Uses Jc.Utils; { TAws } constructor TAws.create(const AccessKey, SecretKey: String); begin FAccessKey := AccessKey; FSecretKey := SecretKey; FConnection := TAmazonConnectionInfo.Create(nil); FConnection.AccountName := FAccessKey; FConnection.AccountKey := FSecretKey; FS3 := TAmazonStorageService.Create(FConnection); FRegion := TAmazonStorageService.GetRegionString(FS3Region); FEndPoint := FConnection.StorageEndpoint; end; destructor TAws.destroy; begin if Assigned(FConnection) then FreeAndNil(FConnection); if Assigned(FS3) then FreeAndNil(FS3); inherited; end; class function TAws.New(): TAws; begin if not Assigned(FInstance) then raise Exception.Create('Primeiro, use o construtor new com parâmetros AccessKey e SecretKey'); result := FInstance; end; class function TAws.New(const AccessKey, SecretKey: String): TAws; begin if FInstance = nil then FInstance := TAws.Create(AccessKey, SecretKey); result := FInstance; end; function TAws.getEndPoint: String; begin result := FendPoint; end; function TAws.getRegion: String; begin Result := Fregion; end; function TAws.getBucket(AName: String): TAmazonBucketResult; begin result := GetAmazonStorage.GetBucket(AName, nil); end; function TAws.getBuckets: TStrings; var ResponseInfo : TCloudResponseInfo; begin ResponseInfo := TCloudResponseInfo.Create; try result := GetAmazonStorage.ListBuckets(ResponseInfo); finally ResponseInfo.Free; end; end; function TAws.GetAmazonStorage: TAmazonStorageService; begin result := FS3; end; function TAws.UploadObject(const ABucket, AFile, AFileName: string): boolean; var FileContent : TBytes; fReader : TBinaryReader; Meta, Headers : TStringList; begin //Cria o stream do arquivo para upload fReader := TBinaryReader.Create(AFile); try FileContent := fReader.ReadBytes(fReader.BaseStream.Size); finally fReader.Free; end; try //Prepara o upload try Meta := TStringList.Create; Headers := TStringList.Create; if ExtractFileExt(AFileName) = '.pdf' then Headers.Add('Content-type=application/pdf') else if ExtractFileExt(AFileName) = '.jpg' then Headers.Add('Content-Type=image/jpeg') else if ExtractFileExt(AFileName) = '.png' then Headers.Add('Content-Type=image/png') else if ExtractFileExt(AFileName) = '.zip' then Headers.Add('Content-type=application/zip') else Meta.Add('Content-type=text/xml'); //Faz o upload try GetAmazonStorage.UploadObject(ABucket, AFileName, FileContent, False, Meta, Headers, amzbaPublicRead); result := true; except on E:Exception do begin result := false; raise Exception.Create(e.Message); end; end; finally Meta.Free; Headers.Free; end; except on E:Exception do begin result := false; raise Exception.Create(e.Message); end; end; end; function TAws.DeleteObject(const ABucket, AFile: string): boolean; begin try GetAmazonStorage.DeleteObject(ABucket, AFile); result := true; except on E:Exception do begin result := false; raise Exception.Create(e.Message); end; end; end; function TAws.DownloadObject(const ABucket, AFile, AOutPath: string): boolean; var FStream : TStream; sFile : String; begin FStream := TMemoryStream.Create; try sFile := AFile; try //Download do arquivo para a vari�vei FStream GetAmazonStorage.GetObject(ABucket, sFile, FStream); FStream.Position := 0; //Permite selecionar a pasta TMemoryStream(FStream).SaveToFile(AOutPath + sFile); result := true; except result := false; end; finally FStream.Free; end; end; initialization finalization if TAws.FInstance <> nil then begin TAws.FInstance.Free; TAws.FInstance := nil end; end.
unit tmsUXlsSections; {$INCLUDE ..\FLXCOMPILER.INC} interface uses Classes, SysUtils, tmsUXlsBaseRecords, tmsUXlsBaseRecordLists, tmsUXlsOtherRecords, tmsUXlsSST, tmsXlsMessages, tmsUFlxMessages, tmsUOle2Impl; type TBaseSection = class private FBOF: TBOFRecord; FEOF: TEOFRecord; protected property sBOF: TBOFRecord read FBOF write FBOF; //renamed to sBOF to avoid conflicts with C++Builder property sEOF: TEOFRecord read FEOF write FEOF; public constructor Create; destructor Destroy; override; procedure Clear; virtual; function TotalSize:int64; virtual; function TotalRangeSize(const SheetIndex: integer; const CellRange: TXlsCellRange): int64; virtual; procedure LoadFromStream(const DataStream: TOle2File; var RecordHeader: TRecordHeader; const First: TBOFRecord; const SST: TSST);virtual;abstract; procedure SaveToStream(const DataStream: TOle2File);virtual;abstract; procedure SaveRangeToStream(const DataStream: TOle2File; const SheetIndex: integer; const CellRange: TXlsCellRange);virtual; abstract; end; implementation { TBaseSection } procedure TBaseSection.Clear; begin FreeAndNil(FBOF); FreeAndNil(FEOF); end; constructor TBaseSection.Create; begin inherited; FBOF:=nil; FEOF:=nil; end; destructor TBaseSection.Destroy; begin Clear; inherited; end; function TBaseSection.TotalRangeSize(const SheetIndex: integer; const CellRange: TXlsCellRange): int64; begin Result:=sEOF.TotalSize+ sBOF.TotalSize; end; function TBaseSection.TotalSize: int64; begin Result:=sEOF.TotalSize+ sBOF.TotalSize; end; end.