text
stringlengths
14
6.51M
unit _frMic; interface uses FrameBase, JsonData, AudioDevice, Strg, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.jpeg, Vcl.ExtCtrls, Vcl.StdCtrls; type TfrMic = class(TFrame) cbSystemAudio: TCheckBox; cbMic: TComboBox; Label1: TLabel; procedure cbMicKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbMicKeyPress(Sender: TObject; var Key: Char); procedure cbMicDropDown(Sender: TObject); procedure cbSystemAudioClick(Sender: TObject); procedure cbMicChange(Sender: TObject); private public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published procedure rp_ShowOptionControl(AParams:TJsonData); end; implementation uses Core, Options; {$R *.dfm} { TfrMic } function delete_whitespace(const text:string):string; var i: Integer; begin Result := ''; for i := 1 to Length(text) do if text[i] <> ' ' then Result := Result + text[i]; end; function is_device_in_the_list(list:TStrings; name:string):boolean; var i: Integer; begin Result := false; name := delete_whitespace(name); for i := 0 to list.Count-1 do if name = delete_whitespace(list[i]) then begin Result := true; Exit; end; end; procedure TfrMic.cbMicChange(Sender: TObject); begin TOptions.Obj.AudioOption.Mic := -1; if cbMic.ItemIndex > -1 then begin TOptions.Obj.AudioOption.Mic := Integer(cbMic.Items.Objects[cbMic.ItemIndex]); end; end; procedure TfrMic.cbMicDropDown(Sender: TObject); var i: Integer; device_name : string; begin cbMic.Items.Clear; cbMic.Items.AddObject('±âº» ÀåÄ¡', TObject(-1)); LoadAudioDeviceList; for i := 0 to GetAudioDeviceCount-1 do begin device_name := Trim(GetAudioDeviceName(i)); if GetAudioDeviceInputChannels(i) = 0 then Continue; if is_device_in_the_list(cbMic.Items, device_name) then Continue; if Pos('@', device_name) > 0 then Continue; cbMic.Items.AddObject(device_name, TObject(i)); end; end; procedure TfrMic.cbMicKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin Key := 0; end; procedure TfrMic.cbMicKeyPress(Sender: TObject; var Key: Char); begin Key := #0; end; procedure TfrMic.cbSystemAudioClick(Sender: TObject); begin TOptions.Obj.AudioOption.SystemAudio := cbSystemAudio.Checked; end; constructor TfrMic.Create(AOwner: TComponent); begin inherited; TCore.Obj.View.Add(Self); end; destructor TfrMic.Destroy; begin TCore.Obj.View.Remove(Self); inherited; end; procedure TfrMic.rp_ShowOptionControl(AParams: TJsonData); begin Visible := AParams.Values['Target'] = HelpKeyword; end; end.
{$Include MatrixCommon.inc} unit matrixProcessSignal; interface uses Windows, Messages, Classes, SysUtils, Math, Matrix32; type TDim2 = (dimRows, dimCols); { Fast3PointInterp() Быстрая 3-точечная (параболическая) интерполяция с помощью интерполяционных полиномов Ньютона. Values - перечень значений OldSteps - перечень координат Х, соответствующих значениям Values NewSteps - точки, в которых нужно вычислить приближенные значения AResult - новые (приближенные) значения в точках NewSteps Faster - позволяет значительно ускорить вычисления, если сетка NewSteps является регулярной. Используется для работы функции масштабирования StretchRows() Данный способ для вычисления очередного восстановленного значения использует следующий алгоритм: P(E) = Y0 + (Y1 - Y0) * E + (Y2 - 2 * Y1 + Y0) / 2 * E * (E - 1), где Е расчитывается по формуле E = (X - X0) / (X1 - X0) Функция поддерживает работу с массивами любых размерностей} procedure Fast3PointInterp(Values, OldSteps, NewSteps, AResult: TMatrix; Faster: Boolean = False); {Осуществляет изменение длины строк матрицы AMatrix в соответствии с NewLength. Эта операция выполняется посредством параболической интерполяции. Функция поддерживает работу с массивами любых размерностей} procedure StretchRows(AMatrix, AResult: TMatrix; NewLength: Integer); implementation const SigNames: array[1..12] of string = ( 'I', 'II', 'III', 'aVR', 'aVL', 'aVF', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6'); procedure Fast3PointInterp(Values, OldSteps, NewSteps, AResult: TMatrix; Faster: Boolean); var TempMatrix, ValuesRef: TMatrix; ColNum, I, J, K: Integer; OldDimValues: TDynIntArray; Tmp: Extended; const SFuncName = 'procedure Fast3PointInterp'; function CalcElem(X0, X1, Y0, Y1, Y2, X: Double): Double; var E: Real; begin E := (X - X0) / (X1 - X0); if (E < 0) or (E > 2) then raise MatrixCreateExceptObj(EMatrixError, 'CalcElem Error', 'function CalcElem'); Result := Y0 + (Y1 - Y0) * E + (Y2 - 2 * Y1 + Y0) / 2 * E * (E - 1); end; begin try if not IsSameMatrixTypes([Values, OldSteps, NewSteps, AResult], [mtNumeric]) then raise EMatrixWrongElemType.Create(matSNotNumericType); if (OldSteps.Rows > 1) or (Values.Cols <> OldSteps.Cols) or (OldSteps.Rows > 1) then raise EMatrixDimensionsError.Create(matSArraysNotAgree); if Values.ElemCount = 0 then raise EMatrixError.Create(matSArrayIsEmpty); // Создаем ссылку на исходный массив. Нам нужно будет преобразовать // исходный массив в матрицу. Однако не хочется этого делать над // массивом Values. Вдруг он используется в многопоточном приложении. ValuesRef := Values.CreateReference; // Создаем временный массив TempMatrix := AResult.CreateInstance; try // Запоминаем размеры массива SetLength(OldDimValues, 0); OldDimValues := Values.GetDimensions; // Исходный массив может быть многомерным. Превращаем его в матрицу ValuesRef.Reshape(ValuesRef.CalcMatrixDimensions); // Устанавливаем требуемые размеры массива TempMatrix.Resize([ValuesRef.Rows, NewSteps.Cols]); // Запоминаем число эл-в ColNum := OldSteps.Cols; for I := NewSteps.Cols - 1 downto 0 do begin // Запоминаем очередную точку Tmp := NewSteps.VecElem[I]; // Ищем точку в массиве исходных отсчетов for J := ColNum - 1 downto 0 do begin if Tmp >= OldSteps.VecElem[J] then begin for K := 0 to ValuesRef.Rows - 1 do begin if J = OldSteps.Cols - 1 then TempMatrix.Elem[K, I] := ValuesRef.Elem[K, J] else if J = OldSteps.Cols - 2 then TempMatrix.Elem[K, I] := CalcElem( OldSteps.VecElem[OldSteps.Cols - 3], OldSteps.VecElem[OldSteps.Cols - 2], ValuesRef.Elem[K, OldSteps.Cols - 3], ValuesRef.Elem[K, OldSteps.Cols - 2], ValuesRef.Elem[K, OldSteps.Cols - 1], NewSteps.VecElem[I]) else TempMatrix.Elem[K, I] := CalcElem( OldSteps.VecElem[J], OldSteps.VecElem[J + 1], ValuesRef.Elem[K, J], ValuesRef.Elem[K, J + 1], ValuesRef.Elem[K, J + 2], NewSteps.VecElem[I]); end; if Faster then ColNum := J + 1; Break; end; end; end; // for I // Устанавливаем для массива TempMatrix правильные размеры OldDimValues[Length(OldDimValues) - 1] := TempMatrix.Cols; TempMatrix.Reshape(OldDimValues); // Перемещаем элементы в AResult AResult.MoveFrom(TempMatrix); finally TempMatrix.Free; ValuesRef.Free; end; except on E: Exception do raise {$IFDEF RecreateEObj}MatrixReCreateExceptObj(E, SFuncName){$ENDIF} end; end; procedure DoIncRows(AMatrix, AResult: TMatrix; NewLength: Integer); var TempMatrix, OldSteps, NewSteps: TMatrix; begin TempMatrix := AResult.CreateInstance; // Создаем массивы отсчетов OldSteps := TIntegerMatrix.Create; NewSteps := TSingleMatrix.Create; try OldSteps.Resize([AMatrix.Cols]); OldSteps.FillByOrder; NewSteps.Resize([NewLength]); NewSteps.FillByStep2(0, AMatrix.Cols - 1); Fast3PointInterp(AMatrix, OldSteps, NewSteps, TempMatrix, True); AResult.MoveFrom(TempMatrix); finally TempMatrix.Free; OldSteps.Free; NewSteps.Free; end; end; procedure DoDecRows(AMatrix, AResult: TMatrix; NewLength: Integer); var TempMatrix, TempMatrix2, MatrixRef: TMatrix; Interval, Num, I, J, Column: Integer; OldDimValues: TDynIntArray; begin MatrixRef := AMatrix.CreateReference; TempMatrix := AResult.CreateInstance; TempMatrix2 := AResult.CreateInstance; try Interval := AMatrix.Cols div (NewLength - 1) + 1; Num := Interval * (NewLength - 1) + 1; // Запоминаем размеры AMatrix OldDimValues := AMatrix.GetDimensions; // Делаем MatrixRef 2-мерной матрицей MatrixRef.Reshape(MatrixRef.CalcMatrixDimensions); DoIncRows(MatrixRef, TempMatrix2, Num); TempMatrix.Resize([MatrixRef.Rows, NewLength]); Column := -1; for J := 1 to Num do begin if (J mod Interval) <> 1 then Continue; Inc(Column); for I := 0 to MatrixRef.Rows - 1 do TempMatrix.Elem[I, Column] := TempMatrix2.Elem[I, J - 1]; end; // Корректируем размеры TempMatrix OldDimValues[Length(OldDimValues) - 1] := NewLength; TempMatrix.Reshape(OldDimValues); AResult.MoveFrom(TempMatrix); finally TempMatrix.Free; TempMatrix2.Free; MatrixRef.Free; end; end; procedure StretchRows(AMatrix, AResult: TMatrix; NewLength: Integer); const SFuncName = 'procedure StretchRows'; resourcestring SMustBeLessOne = 'Значение длины массива должно быть больше единицы!'; begin try if NewLength < 2 then RaiseMatrixError(EMatrixBadParams, SMustBeLessOne); if NewLength > AMatrix.Cols then begin DoIncRows(AMatrix, AResult, NewLength); end else if NewLength < AMatrix.Cols then DoDecRows(AMatrix, AResult, NewLength) else AResult.CopyFrom(AMatrix); except on E: Exception do raise {$IFDEF RecreateEObj}MatrixReCreateExceptObj(E, SFuncName){$ENDIF} end; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Vcl.CaptionedDockTree; {$HPPEMIT LEGACYHPP} interface uses Winapi.Windows, Vcl.Controls, Vcl.Graphics, Winapi.Messages, Vcl.Themes; type /// <summary> /// TParentFormState: stores information about the parent dock form for /// use in drawing the dock site /// </summary> TParentFormState = record Caption: string; StartColor, EndColor, FontColor: TColor; Focused: Boolean; Icon: TIcon; end; TDockCaptionOrientation = (dcoHorizontal, dcoVertical); /// <summary> /// Hit tests for the caption. Note: The custom values allow you /// to return your own hit test results for your own drawer. /// </summary> TDockCaptionHitTest = Cardinal; /// <summary> /// The pin button style to draw, if any. /// </summary> TDockCaptionPinButton = (dcpbNone, dcpbUp, dcpbDown); TDockCaptionDrawer = class(TObject) private FDockCaptionOrientation: TDockCaptionOrientation; FDockCaptionPinButton: TDockCaptionPinButton; function GetCloseRect(const CaptionRect: TRect): TRect; function GetPinRect(const CaptionRect: TRect): TRect; function CalcButtonSize(const CaptionRect: TRect): Integer; protected property DockCaptionOrientation: TDockCaptionOrientation read FDockCaptionOrientation; public procedure DrawDockCaption(const Canvas: TCanvas; CaptionRect: TRect; State: TParentFormState); virtual; function DockCaptionHitTest(const CaptionRect: TRect; const MousePos: TPoint): TDockCaptionHitTest; virtual; /// <summary> /// Creates an instance of the TDockCaptionDrawer. It is virtual so the /// call to TCaptionedDockTree.GetDockCaptionDrawer.Create(..) will /// be called on the correct type. /// </summary> constructor Create(DockCaptionOrientation: TDockCaptionOrientation); virtual; property DockCaptionPinButton: TDockCaptionPinButton read FDockCaptionPinButton write FDockCaptionPinButton; end; TDockCaptionDrawerClass = class of TDockCaptionDrawer; TCaptionedDockTree = class(TDockTree) private FGrabberSize: Integer; FDockCaptionOrientation: TDockCaptionOrientation; FDockCaptionDrawer: TDockCaptionDrawer; procedure InvalidateDockSite(const Client: TControl); protected function AdjustCaptionRect(const ARect: TRect): TRect; virtual; procedure AdjustDockRect(Control: TControl; var ARect: TRect); override; function InternalCaptionHitTest(const Zone: TDockZone; const MousePos: TPoint): TDockCaptionHitTest; procedure PaintDockFrame(Canvas: TCanvas; Control: TControl; const ARect: TRect); override; function ZoneCaptionHitTest(const Zone: TDockZone; const MousePos: TPoint; var HTFlag: Integer): Boolean; override; property DockCaptionOrientation: TDockCaptionOrientation read FDockCaptionOrientation; property DockCaptionDrawer: TDockCaptionDrawer read FDockCaptionDrawer; procedure WndProc(var Message: TMessage); override; public constructor Create(DockSite: TWinControl); overload; override; constructor Create(DockSite: TWinControl; ADockCaptionOrientation: TDockCaptionOrientation); reintroduce; overload; destructor Destroy; override; class function GetParentFormState(const Control: TControl): TParentFormState; virtual; class function GetDockCaptionDrawer: TDockCaptionDrawerClass; virtual; end; TCaptionedDockTreeClass = class of TCaptionedDockTree; const /// <summary> /// TDockCaptionHitTest constant values used. You can use your own values, /// but start at the dchtCustom value. Items 4-9 are reserved for future /// VCL use, and the value of dchtCustom may change. /// </summary> dchtNone = 0; dchtCaption = 1; dchtClose = 2; dchtPin = 3; dchtCustom = 10; implementation uses {$IF DEFINED(CLR)} System.Runtime.InteropServices, {$ENDIF} System.Types, System.UITypes, Vcl.Forms, Vcl.GraphUtil; function GetThemeColor(Details: TThemedElementDetails; ElementColor: TElementColor; var Color: TColor): Boolean; inline; begin Result := StyleServices.Enabled and StyleServices.GetElementColor(Details, ElementColor, Color) and (Color <> clNone); end; { TCaptionedDockTree } procedure TCaptionedDockTree.AdjustDockRect(Control: TControl; var ARect: TRect); begin if FDockCaptionOrientation = dcoHorizontal then Inc(ARect.Top, FGrabberSize) else Inc(ARect.Left, FGrabberSize) end; constructor TCaptionedDockTree.Create(DockSite: TWinControl); begin inherited; FGrabberSize := 23; FDockCaptionDrawer := GetDockCaptionDrawer.Create(FDockCaptionOrientation); end; constructor TCaptionedDockTree.Create(DockSite: TWinControl; ADockCaptionOrientation: TDockCaptionOrientation); begin FDockCaptionOrientation := ADockCaptionOrientation; Create(DockSite); end; class function TCaptionedDockTree.GetParentFormState(const Control: TControl): TParentFormState; begin if Control is TCustomForm then begin Result.Caption := TCustomForm(Control).Caption; Result.Focused := (Screen.ActiveControl <> nil) and Screen.ActiveControl.Focused and (TWinControl(Control).ContainsControl(Screen.ActiveControl)); if Control is TForm then Result.Icon := TForm(Control).Icon else Result.Icon := nil; end else begin Result.Caption := ''; Result.Focused := False; Result.Icon := nil; end; if Result.Focused then begin Result.StartColor := clActiveBorder; Result.EndColor := GetHighlightColor(clActiveBorder, 22); Result.FontColor := clCaptionText; end else begin Result.StartColor := GetShadowColor(clBtnFace, -25); Result.EndColor := GetHighlightColor(clBtnFace, 15); Result.FontColor := clBtnText; end; end; procedure TCaptionedDockTree.InvalidateDockSite(const Client: TControl); var ParentForm: TCustomForm; Rect: TRect; begin ParentForm := GetParentForm(Client, False); { Just invalidate the parent form's rect in the HostDockSite so that we can "follow focus" on docked items. } if (ParentForm <> nil) and (ParentForm.HostDockSite <> nil) then begin with ParentForm.HostDockSite do if UseDockManager and (DockManager <> nil) then begin DockManager.GetControlBounds(ParentForm, Rect); InvalidateRect(Handle, Rect, False); end; end; end; function TCaptionedDockTree.AdjustCaptionRect(const ARect: TRect): TRect; begin Result := ARect; if FDockCaptionOrientation = dcoHorizontal then begin Result.Left := Result.Left + 1; Result.Bottom := Result.Top + FGrabberSize - 1; Result.Right := Result.Right - 2; { Shrink the rect a little } end else begin Result.Right := Result.Left + FGrabberSize - 1; Result.Left := Result.Left + 1; Result.Bottom := Result.Bottom - 3; end; end; procedure TCaptionedDockTree.PaintDockFrame(Canvas: TCanvas; Control: TControl; const ARect: TRect); begin FDockCaptionDrawer.DrawDockCaption(Canvas, AdjustCaptionRect(ARect), GetParentFormState(Control)); end; procedure TCaptionedDockTree.WndProc(var Message: TMessage); {$IF DEFINED(CLR)} var LGCHandle: GCHandle; {$ENDIF} begin if Message.Msg = CM_DOCKNOTIFICATION then begin {$IF DEFINED(CLR)} with TCMDockNotification.Create(Message) do begin if NotifyRec.ClientMsg = CM_INVALIDATEDOCKHOST then begin if NotifyRec.MsgWParam <> 0 then begin LGCHandle := GChandle(IntPtr(NotifyRec.MsgWParam)); if LGChandle.IsAllocated then InvalidateDockSite(TControl(LGCHandle.Target)) end; end else inherited; end; {$ELSE} with TCMDockNotification(Message) do begin if NotifyRec.ClientMsg = CM_INVALIDATEDOCKHOST then InvalidateDockSite(TControl(NotifyRec.MsgWParam)) else inherited; end; {$ENDIF} end else inherited; end; function TCaptionedDockTree.InternalCaptionHitTest(const Zone: TDockZone; const MousePos: TPoint): TDockCaptionHitTest; var FrameRect, CaptionRect: TRect; begin FrameRect := Zone.ChildControl.BoundsRect; AdjustDockRect(Zone.ChildControl, FrameRect); AdjustFrameRect(Zone.ChildControl, FrameRect); CaptionRect := AdjustCaptionRect(FrameRect); Result := FDockCaptionDrawer.DockCaptionHitTest(CaptionRect, MousePos); end; function TCaptionedDockTree.ZoneCaptionHitTest(const Zone: TDockZone; const MousePos: TPoint; var HTFlag: Integer): Boolean; var HitTest: TDockCaptionHitTest; begin HitTest := InternalCaptionHitTest(Zone, MousePos); if HitTest = dchtNone then Result := False else begin Result := True; if HitTest = dchtClose then HTFlag := HTCLOSE else if HitTest = dchtCaption then HTFlag := HTCAPTION; end; end; destructor TCaptionedDockTree.Destroy; begin FDockCaptionDrawer.Free; inherited; end; class function TCaptionedDockTree.GetDockCaptionDrawer: TDockCaptionDrawerClass; begin Result := TDockCaptionDrawer; end; { TDockCaptionDrawer } function TDockCaptionDrawer.CalcButtonSize( const CaptionRect: TRect): Integer; const cButtonBuffer = 8; begin if FDockCaptionOrientation = dcoHorizontal then Result := CaptionRect.Bottom - CaptionRect.Top - cButtonBuffer else Result := CaptionRect.Right - CaptionRect.Left - cButtonBuffer; end; constructor TDockCaptionDrawer.Create( DockCaptionOrientation: TDockCaptionOrientation); begin inherited Create; FDockCaptionOrientation := DockCaptionOrientation; //FDockCaptionPinButton := dcpbUp; // For testing end; function TDockCaptionDrawer.DockCaptionHitTest(const CaptionRect: TRect; const MousePos: TPoint): TDockCaptionHitTest; var CloseRect, PinRect: TRect; begin if CaptionRect.Contains(MousePos) then begin CloseRect := GetCloseRect(CaptionRect); { Make the rect vertically the same size as the captionrect } if FDockCaptionOrientation = dcoHorizontal then begin CloseRect.Top := CaptionRect.Top; CloseRect.Bottom := CaptionRect.Bottom; Inc(CloseRect.Right); end else begin CloseRect.Left := CaptionRect.Left; CloseRect.Right := CaptionRect.Right; Inc(CloseRect.Bottom); end; if CloseRect.Contains(MousePos) then Result := dchtClose else if FDockCaptionPinButton <> dcpbNone then begin { did it hit the pin? } if FDockCaptionOrientation = dcoHorizontal then begin PinRect := GetPinRect(CaptionRect); PinRect.Top := CaptionRect.Top; PinRect.Bottom := CaptionRect.Bottom; Inc(PinRect.Right); end else begin PinRect := GetPinRect(CaptionRect); PinRect.Left := CaptionRect.Left; PinRect.Right := CaptionRect.Right; Inc(PinRect.Bottom); end; if PinRect.Contains(MousePos) then Result := dchtPin else Result := dchtCaption; end else Result := dchtCaption end else Result := dchtNone; end; procedure TDockCaptionDrawer.DrawDockCaption(const Canvas: TCanvas; CaptionRect: TRect; State: TParentFormState); var LColor: TColor; LStyle: TCustomStyleServices; LDetails: TThemedElementDetails; procedure PaintCloseX(const LeftTip, TopTip: Integer); begin if not GetThemeColor(LDetails, ecEdgeFillColor, LColor) then LColor := GetShadowColor(clBtnFace, -120); Canvas.Pen.Color := LColor; Canvas.Pen.Style := psSolid; Canvas.Pen.Width := 1; // Left side Canvas.MoveTo(LeftTip + 0, TopTip + 0); Canvas.LineTo(LeftTip + 0, TopTip + 1); Canvas.LineTo(LeftTip + 1, TopTip + 2); Canvas.LineTo(LeftTip + 2, TopTip + 3); Canvas.LineTo(LeftTip + 1, TopTip + 4); Canvas.LineTo(LeftTip + 0, TopTip + 5); Canvas.LineTo(LeftTip + 0, TopTip + 7); // top Canvas.MoveTo(LeftTip + 1, TopTip - 1); Canvas.LineTo(LeftTip + 2, TopTip - 1); Canvas.LineTo(LeftTip + 3, TopTip + 0); Canvas.LineTo(LeftTip + 4, TopTip + 1); Canvas.LineTo(LeftTip + 5, TopTip + 0); Canvas.LineTo(LeftTip + 6, TopTip - 1); Canvas.LineTo(LeftTip + 8, TopTip - 1); // right side Canvas.MoveTo(LeftTip + 8, TopTip + 0); Canvas.LineTo(LeftTip + 8, TopTip + 1); Canvas.LineTo(LeftTip + 7, TopTip + 2); Canvas.LineTo(LeftTip + 6, TopTip + 3); Canvas.LineTo(LeftTip + 7, TopTip + 4); Canvas.LineTo(LeftTip + 8, TopTip + 5); Canvas.LineTo(LeftTip + 8, TopTip + 7); // bottom Canvas.MoveTo(LeftTip + 1, TopTip + 7); Canvas.LineTo(LeftTip + 2, TopTip + 7); Canvas.LineTo(LeftTip + 3, TopTip + 6); Canvas.LineTo(LeftTip + 4, TopTip + 5); Canvas.LineTo(LeftTip + 5, TopTip + 6); Canvas.LineTo(LeftTip + 6, TopTip + 7); Canvas.LineTo(LeftTip + 8, TopTip + 7); // Fill if not GetThemeColor(LDetails, ecEdgeHighLightColor, LColor) then LColor := clBtnHighlight; Canvas.Brush.Color := LColor; Canvas.FloodFill(LeftTip + 3, TopTip + 1, Canvas.Pixels[LeftTip + 3, TopTip + 1], fsSurface); end; procedure PaintPin(const LeftTip, TopTip: Integer); var Left, Top: Integer; begin Canvas.Pen.Color := Canvas.Font.Color; Canvas.Pen.Style := psSolid; Canvas.Pen.Width := 1; if not GetThemeColor(LDetails, ecEdgeFillColor, LColor) then LColor := GetShadowColor(clBtnFace, -120); Canvas.Pen.Color := LColor; if FDockCaptionPinButton = dcpbDown then begin Top := TopTip + 1; Left := LeftTip; { Draw the top box } Canvas.MoveTo(Left + 1, Top + 4); Canvas.LineTo(Left + 1, Top); Canvas.LineTo(Left + 5, Top); Canvas.LineTo(Left + 5, Top + 5); { Draw the middle line } Canvas.MoveTo(Left, Top + 5); Canvas.LineTo(Left + 7, Top + 5); { Draw a depth line } Canvas.MoveTo(Left + 4, Top + 1); Canvas.LineTo(Left + 4, Top + 5); Canvas.MoveTo(Left + 3, Top + 6); Canvas.LineTo(Left + 3, Top + 6 + 4); if not GetThemeColor(LDetails, ecEdgeHighLightColor, LColor) then LColor := clBtnHighlight; Canvas.Brush.Color := LColor; Canvas.FillRect(Rect(Left + 2, Top + 1, Left + 4, Top + 5)); end else begin Top := TopTip; Left := LeftTip; { Draw the right box } Canvas.MoveTo(Left + 4, Top + 1); Canvas.LineTo(Left + 9, Top + 1); Canvas.LineTo(Left + 9, Top + 5); Canvas.LineTo(Left + 3, Top + 5); { Draw the middle line } Canvas.MoveTo(Left + 3, Top); Canvas.LineTo(Left + 3, Top + 7); { Draw a depth line } Canvas.MoveTo(Left + 4, Top + 4); Canvas.LineTo(Left + 9, Top + 4); Canvas.MoveTo(Left, Top + 3); Canvas.LineTo(Left + 3, Top + 3); if not GetThemeColor(LDetails, ecEdgeHighLightColor, LColor) then LColor := clBtnHighlight; Canvas.Brush.Color := LColor; Canvas.FillRect(Rect(Left + 4, Top + 2, Left + 9, Top + 4)); end; end; procedure PaintOutline(const ARect: TRect); begin if not GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then LColor := GetShadowColor(clBtnFace, -75); Canvas.Pen.Color := LColor; if not GetThemeColor(LDetails, ecFillColor, LColor) then LColor := clBtnFace; Canvas.Brush.Color := LColor; Canvas.FillRect(Rect(ARect.Left + 1, ARect.Top + 1, ARect.Right - 1, ARect.Bottom - 1)); // Top left pixel Canvas.Pixels[ARect.Left + 1, ARect.Top + 1] := Canvas.Pen.Color; // top line Canvas.MoveTo(ARect.Left + 2, ARect.Top + 0); Canvas.LineTo(ARect.Right - 2, ARect.Top + 0); // top right pixel Canvas.Pixels[ARect.Right - 2, ARect.Top + 1] := Canvas.Pen.Color; // right line Canvas.MoveTo(ARect.Right - 1, ARect.Top + 2); Canvas.LineTo(ARect.Right - 1, ARect.Bottom - 2); // bottom right pixel Canvas.Pixels[ARect.Right - 2, ARect.Bottom - 2] := Canvas.Pen.Color; // bottom line Canvas.MoveTo(ARect.Left + 2, ARect.Bottom - 1); Canvas.LineTo(ARect.Right - 2, ARect.Bottom - 1); // bottom left pixel Canvas.Pixels[ARect.Left + 1, ARect.Bottom - 2] := Canvas.Pen.Color; // left line Canvas.MoveTo(ARect.Left + 0, ARect.Top + 2); Canvas.LineTo(ARect.Left + 0, ARect.Bottom - 2); // Lighter 3d'ish look // Right side if not GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then LColor := GetShadowColor(clBtnFace, -25); Canvas.Pen.Color := LColor; Canvas.MoveTo(ARect.Right - 4, ARect.Top + 1); Canvas.LineTo(ARect.Right - 3, ARect.Top + 1); Canvas.LineTo(ARect.Right - 3, ARect.Top + 2); Canvas.LineTo(ARect.Right - 2, ARect.Top + 2); // vert line Canvas.LineTo(ARect.Right - 2, ARect.Bottom - 3); Canvas.LineTo(ARect.Right - 3, ARect.Bottom - 3); Canvas.LineTo(ARect.Right - 3, ARect.Bottom - 2); // bottom line Canvas.LineTo(ARect.Left + 1, ARect.Bottom - 2); // last bottom left side pixel Canvas.Pixels[ARect.Left + 1, ARect.Bottom - 3] := Canvas.Pen.Color; end; procedure DrawCloseButton(const ARect: TRect); var OutlineRect: TRect; LeftTip, TopTip: Integer; begin OutlineRect.Left := ARect.Left - 1; OutlineRect.Top := ARect.Top - 1; OutlineRect.Right := ARect.Right + 2; OutlineRect.Bottom := ARect.Bottom + 2; LeftTip := ARect.Left + 2; TopTip := ARect.Top + 3; LDetails := LStyle.GetElementDetails(tpDockPanelCloseNormal); PaintOutline(OutlineRect); PaintCloseX(LeftTip, TopTip); end; procedure DrawPinButton(const ARect: TRect); var OutlineRect: TRect; LeftTip, TopTip: Integer; begin OutlineRect.Left := ARect.Left - 1; OutlineRect.Top := ARect.Top - 1; OutlineRect.Right := ARect.Right; OutlineRect.Bottom := ARect.Bottom + 2; if FDockCaptionPinButton = dcpbUp then begin LeftTip := ARect.Left + 2; TopTip := ARect.Top + 3; end else begin LeftTip := ARect.Left + 3; TopTip := ARect.Top + 1; end; LDetails := LStyle.GetElementDetails(tpDockPanelPinNormal); PaintOutline(OutlineRect); PaintPin(LeftTip, TopTip); end; function RectWidth(const Rect: TRect): Integer; begin Result := Rect.Right - Rect.Left; end; procedure DrawIcon; var FormBitmap: TBitmap; DestBitmap: TBitmap; ImageSize: Integer; X, Y: Integer; begin if (State.Icon <> nil) and (State.Icon.HandleAllocated) then begin if FDockCaptionOrientation = dcoHorizontal then begin ImageSize := CaptionRect.Bottom - CaptionRect.Top - 3; X := CaptionRect.Left; Y := CaptionRect.Top + 2; end else begin ImageSize := CaptionRect.Right - CaptionRect.Left - 3; X := CaptionRect.Left + 1; Y := CaptionRect.Top; end; FormBitmap := nil; DestBitmap := TBitmap.Create; try FormBitmap := TBitmap.Create; DestBitmap.Width := ImageSize; DestBitmap.Height := ImageSize; DestBitmap.Canvas.Brush.Color := clFuchsia; DestBitmap.Canvas.FillRect(Rect(0, 0, DestBitmap.Width, DestBitmap.Height)); FormBitmap.Width := State.Icon.Width; FormBitmap.Height := State.Icon.Height; FormBitmap.Canvas.Draw(0, 0, State.Icon); ScaleImage(FormBitmap, DestBitmap, DestBitmap.Width / FormBitmap.Width); DestBitmap.TransparentColor := DestBitmap.Canvas.Pixels[0, DestBitmap.Height - 1]; DestBitmap.Transparent := True; Canvas.Draw(X, Y, DestBitmap); finally FormBitmap.Free; DestBitmap.Free; end; if FDockCaptionOrientation = dcoHorizontal then CaptionRect.Left := CaptionRect.Left + 6 + ImageSize else CaptionRect.Top := CaptionRect.Top + 6 + ImageSize; end; end; const CHorzStates: array[Boolean] of TThemedPanel = (tpDockPanelHorzNormal, tpDockPanelHorzSelected); CVertStates: array[Boolean] of TThemedPanel = (tpDockPanelVertNormal, tpDockPanelVertSelected); var ShouldDrawClose: Boolean; CloseRect, PinRect: TRect; begin LStyle := StyleServices; LDetails := LStyle.GetElementDetails(CHorzStates[State.Focused]); if not GetThemeColor(LDetails, ecTextColor, LColor) then LColor := State.FontColor; Canvas.Font.Color := LColor; Canvas.Pen.Width := 1; if not GetThemeColor(LDetails, ecBorderColor, LColor) then LColor := State.StartColor; Canvas.Pen.Color := LColor; if FDockCaptionOrientation = dcoHorizontal then begin CaptionRect.Top := CaptionRect.Top + 1; { Fill the middle } if not GetThemeColor(LDetails, ecFillColor, LColor) then if State.Focused then LColor := clActiveCaption else LColor := clBtnFace; Canvas.Brush.Color := LColor; Canvas.FillRect(Rect(CaptionRect.Left + 1, CaptionRect.Top + 1, CaptionRect.Right, CaptionRect.Bottom)); { Draw a slight outline } Canvas.Pen.Color := GetShadowColor(Canvas.Pen.Color, -20); with CaptionRect do Canvas.Polyline([Point(Left + 2, Top), Point(Right - 2, Top), { Top line } Point(Right, Top + 2), { Top right curve } Point(Right, Bottom - 2), { Right side line } Point(Right - 2, Bottom), { Bottom right curve } Point(Left + 2, Bottom), { Bottom line } Point(Left, Bottom - 2), { Bottom left curve } Point(Left, Top + 2), { Left side line } Point(Left + 3, Top)]); { Top left curve } { Get the close rect size/position } CloseRect := GetCloseRect(CaptionRect); { Does it have the pin button? Make some room for it, and draw it. } if FDockCaptionPinButton <> dcpbNone then begin PinRect := GetPinRect(CaptionRect); if FDockCaptionPinButton = dcpbUp then Inc(PinRect.Top); { Down a little further - better looks } DrawPinButton(PinRect); CaptionRect.Right := PinRect.Right - 2; end else begin { Shrink the rect to consider the close button on the right, and not draw text in it. } CaptionRect.Right := CloseRect.Right - 2; end; { Move away from the left edge a little before drawing text } CaptionRect.Left := CaptionRect.Left + 6; { Draw the icon, if found. } DrawIcon; ShouldDrawClose := CloseRect.Left >= CaptionRect.Left; end else begin { Give a rounded effect } Canvas.MoveTo(CaptionRect.Left + 1, CaptionRect.Top + 1); Canvas.LineTo(CaptionRect.Right - 1, CaptionRect.Top + 1); { fill the middle } LDetails := LStyle.GetElementDetails(CVertStates[State.Focused]); if not GetThemeColor(LDetails, ecFillColor, LColor) then if State.Focused then LColor := clBtnHighlight else LColor := clBtnFace; Canvas.Brush.Color := LColor; Canvas.FillRect(Rect(CaptionRect.Left, CaptionRect.Top + 2, CaptionRect.Right, CaptionRect.Bottom)); Canvas.Pen.Color := State.EndColor; Canvas.MoveTo(CaptionRect.Left + 1, CaptionRect.Bottom); Canvas.LineTo(CaptionRect.Right - 1, CaptionRect.Bottom); Canvas.Font.Orientation := 900; { 90 degrees upwards } { Get the close rect size/position } CloseRect := GetCloseRect(CaptionRect); { Does it have the pin button? Make some room for it, and draw it. } if FDockCaptionPinButton <> dcpbNone then begin PinRect := GetPinRect(CaptionRect); DrawPinButton(PinRect); CaptionRect.Top := PinRect.Bottom + 2; end else { Add a little spacing between the close button and the text } CaptionRect.Top := CloseRect.Bottom + 2; ShouldDrawClose := CaptionRect.Top < CaptionRect.Bottom; { Make the captionrect horizontal for proper clipping } CaptionRect.Right := CaptionRect.Left + (CaptionRect.Bottom - CaptionRect.Top - 2); { Position the caption starting position at most at the bottom of the rectangle } CaptionRect.Top := CaptionRect.Top + Canvas.TextWidth(State.Caption) + 2; if CaptionRect.Top > CaptionRect.Bottom then CaptionRect.Top := CaptionRect.Bottom; end; Canvas.Brush.Style := bsClear; { For drawing the font } if State.Caption <> '' then begin if State.Focused then Canvas.Font.Style := Canvas.Font.Style + [fsBold] else Canvas.Font.Style := Canvas.Font.Style - [fsBold]; if ShouldDrawClose then CaptionRect.Right := CaptionRect.Right - (CloseRect.Right - CloseRect.Left) - 4; Canvas.TextRect(CaptionRect, State.Caption, [tfEndEllipsis, tfVerticalCenter, tfSingleLine]); end; if ShouldDrawClose then DrawCloseButton(CloseRect); end; const cSideBuffer = 4; function TDockCaptionDrawer.GetCloseRect(const CaptionRect: TRect): TRect; var CloseSize: Integer; begin CloseSize := CalcButtonSize(CaptionRect); if FDockCaptionOrientation = dcoHorizontal then begin Result.Left := CaptionRect.Right - CloseSize - cSideBuffer; Result.Top := CaptionRect.Top + ((CaptionRect.Bottom - CaptionRect.Top) - CloseSize) div 2; end else begin Result.Left := CaptionRect.Left + ((CaptionRect.Right - CaptionRect.Left) - CloseSize) div 2; Result.Top := CaptionRect.Top + 2 * cSideBuffer; end; Result.Right := Result.Left + CloseSize; Result.Bottom := Result.Top + CloseSize; end; function TDockCaptionDrawer.GetPinRect(const CaptionRect: TRect): TRect; var PinSize: Integer; begin PinSize := CalcButtonSize(CaptionRect); if FDockCaptionOrientation = dcoHorizontal then begin Result.Left := CaptionRect.Right - 2*PinSize - 2*cSideBuffer; Result.Top := CaptionRect.Top + ((CaptionRect.Bottom - CaptionRect.Top) - PinSize) div 2; end else begin Result.Left := CaptionRect.Left + ((CaptionRect.Right - CaptionRect.Left) - PinSize) div 2; Result.Top := CaptionRect.Top + 2*cSideBuffer + 2*PinSize; end; Result.Right := Result.Left + PinSize + 2; Result.Bottom := Result.Top + PinSize; end; initialization DefaultDockTreeClass := TCaptionedDockTree; end.
unit uObjectFont; interface uses SysUtils, Types, Classes, Contnrs, uObjectFontZnak; type TMyFont = class(TObjectList) private protected function GetItem(Index: Integer): TMyZnak; procedure SetItem(Index: Integer; Obj: TMyZnak); public property Znaky[Index: Integer]: TMyZnak read GetItem write SetItem; default; function PridajZnak(pozicia: integer): TMyZnak; function ZistiSirkuTextu(text: string; vyska_textu: double): double; end; implementation function TMyFont.GetItem(Index: Integer): TMyZnak; begin try result := (Items[Index] as TMyZnak); except raise Exception.Create('Unknown character ('+IntToStr(Index)+') in current font.'); end; end; function TMyFont.PridajZnak(pozicia: integer): TMyZnak; begin // ak vo fonte este nie je zaalokovany priestor na znak s danym 'indexom' (Ord(znak)) // tak to zaalokujeme a inicializujem na NIL while Capacity < (pozicia+1) do begin Capacity := Capacity + 1; Add(nil); end; Items[pozicia] := TMyZnak.Create; if OwnsObjects then ; result := TMyZnak(Items[pozicia]); end; procedure TMyFont.SetItem(Index: Integer; Obj: TMyZnak); begin Items[Index] := Obj; end; function TMyFont.ZistiSirkuTextu(text: string; vyska_textu: double): double; var i, indexZnaku: integer; sizeFaktor: Double; begin result := 0; sizeFaktor := vyska_textu / 10; for i := 1 to Length(text) do begin indexZnaku := Ord(Char(text[i])); if (indexZnaku > Capacity) OR (not Assigned(Self.Items[indexZnaku])) then indexZnaku := Ord(Char('?')); // ak taky znak nepozna, vykresli '?' result := result + ((Self.Znaky[indexZnaku].sirkaZnaku + Self.Znaky[indexZnaku].sirkaMedzery) * sizeFaktor); end; // este musime odpocitat sirku medzery za poslednym znakom (v premennej INDEXZNAKU nam ostal index posledneho znaku) if Assigned(Self.Items[indexZnaku]) then // ak taky znak pozna result := result - (Self.Znaky[indexZnaku].sirkaMedzery * sizeFaktor) end; end.
unit IdCoder; interface uses Classes, IdBaseComponent, IdGlobal; const CT_Creation = 0; CT_Realisation = $80; // Coder Priorities CP_FALLBACK = 0; CP_IMF = 1; CP_STANDARD = 8; // Notification messages - generic CN_CODED_DATA = 0; CN_DATA_START_FOUND = 1; CN_DATA_END_FOUND = 2; CN_CODING_STARTED = 3; CN_CODING_ENDED = 4; CN_NEW_FILENAME = 5; // Notifications messages - IMF coders CN_IMF_CODER_START = 20; // Not actually used?? CN_IMF_BODY_START = CN_IMF_CODER_START + 1; CN_IMF_BODY_PART_END = CN_IMF_CODER_START + 2; CN_IMF_HEAD_VALUE = CN_IMF_CODER_START + 3; CN_IMF_NEW_MULTIPART = CN_IMF_CODER_START + 4; // New boundary found CN_IMF_END_MULTIPART = CN_IMF_CODER_START + 5; // Boundary end CN_IMF_DATA_END = CN_IMF_CODER_START + 6; CN_IMF_NEW_FILENAME = CN_NEW_FILENAME; // Notification messages - UU coders CN_UU_CODER_START = 40; CN_UU_TABLE_FOUND = CN_UU_CODER_START + 1; CN_UU_BEGIN_FOUND = CN_UU_CODER_START + 2; CN_UU_TABLE_BEGIN_ABORT = CN_UU_CODER_START + 3; CN_UU_LAST_CHAR_FOUND = CN_UU_CODER_START + 4; CN_UU_END_FOUND = CN_UU_CODER_START + 5; CN_UU_TABLE_CHANGED = CN_UU_CODER_START + 6; CN_UU_PRIVILEGE_FOUND = CN_UU_CODER_START + 7; CN_UU_PRIVILEGE_ERROR = CN_UU_CODER_START + 8; CN_UU_NEW_FILENAME = CN_NEW_FILENAME; type TStringEvent = procedure(ASender: TComponent; const AOut: string) of object; TIntStringEvent = procedure(ASender: TComponent; AVal: Integer; const AOut: string) of object; TQWord = packed record L: LongWord; H: LongWord; end; PIdCoder = ^TIdCoder; TIdCoder = class(TIdBaseComponent) protected FAddCRLF: Boolean; FAutoCompleteInput: Boolean; FByteCount: TQWord; FBytesIn: TQWord; FBytesOut: TQWord; FCBufferSize: LongWord; FCBufferedData: LongWord; FCBuffer: string; FFileName: string; FIgnoreCodedData: Boolean; FIgnoreNotification: Boolean; FInCompletion: Boolean; FKey: string; FPriority: Byte; FOnCodedData: TStringEvent; FOnNotification: TIntStringEvent; FOutputStrings: TStringList; FTakesFileName: Boolean; FTakesKey: Boolean; FUseEvent: Boolean; procedure Coder; virtual; procedure CompleteCoding; virtual; procedure IncByteCount(bytes: LongWord); procedure InternSetBufferSize(BufferSize: Integer); procedure OutputNotification(AVal: Integer; AStr: string); procedure OutputString(s: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function CodeString(AStr: string): string; procedure CodeStringFromCoder(Sender: TComponent; const sOut: string); function CompletedInput: string; virtual; function GetCodedData: string; virtual; function GetNotification: string; virtual; procedure Reset; virtual; procedure SetKey(const key: string); virtual; procedure SetBufferSize(ASize: LongWord); virtual; property AddCRLF: Boolean read FAddCRLF write FAddCRLF; property AutoCompleteInput: Boolean read fAutoCompleteInput write fAutoCompleteInput; property BufferSize: LongWord read FCBufferSize write SetBufferSize; property ByteCount: TQWord read FByteCount; property BytesIn: TQWord read FBytesIn; property BytesOut: TQWord read FBytesOut; property FileName: string read FFileName write FFileName; property IgnoreCodedData: Boolean read FIgnoreCodedData write FIgnoreCodedData; property IgnoreNotification: Boolean read FIgnoreNotification write FIgnoreNotification; property Key: string read FKey write SetKey; property OnCodedData: TStringEvent read FOnCodedData write FOnCodedData; property OnNotification: TIntStringEvent read FOnNotification write FOnNotification; property Priority: Byte read FPriority; property TakesFileName: Boolean read FTakesFileName; property TakesKey: Boolean read FTakesKey; property UseEvent: Boolean read FUseEvent write FUseEvent; end; CIdCoder = class of TIdCoder; PIdCoderItem = ^TIdCoderItem; TIdCoderItem = class(TCollectionItem) protected FCoderType: Byte; FCoderPriority: Byte; FContentType: string; FContentTransferEncoding: string; FIdCoderClass: CIdCoder; public property CoderType: Byte read FCoderType; property CoderPriority: Byte read FCoderPriority; property ContentType: string read FContentType; property ContentTransferEncoding: string read FContentTransferEncoding; property IdCoderClass: CIdCoder read FIdCoderClass write FIdCoderClass; end; TIdCoderCollection = class(TCollection) protected FCount: LongWord; function GetCoder(Index: LongWord): TIdCoderItem; function Add: TIdCoderItem; public constructor Create(ItemClass: TCollectionItemClass); function AddCoder: TIdCoderItem; function GetCoderType(ContentType, ContentTransferEncoding: string; CoderType: Byte): TIdCoderItem; function GetExactCoderType(ContentType, ContentTransferEncoding: string; CoderType: Byte): TIdCoderItem; property Items[Index: LongWord]: TIdCoderItem read GetCoder; property ItemCount: LongWord read FCount; end; procedure RegisterCoderClass(ClassType: CIdCoder; CoderType, CoderPriority: Byte; ContentType, ContentTransferEncoding: string); procedure IncQWord(var QWord: TQWord; IncVal: LongWord); var CoderCollective: TIdCoderCollection; implementation uses SysUtils; procedure RegisterCoderClass; var item: TIdCoderItem; begin item := CoderCollective.AddCoder; item.IdCoderClass := ClassType; item.FCoderType := CoderType; item.FCoderPriority := CoderPriority; item.FContentType := ContentType; item.FContentTransferEncoding := ContentTransferEncoding; end; procedure IncQWord; var i: LongWord; begin if QWord.L > IncVal then begin i := IncVal; end else begin i := QWord.L; QWord.L := IncVal; end; if QWord.L and $80000000 = $80000000 then begin Inc(QWord.L, i); if QWord.L and $80000000 <> $00000000 then begin if QWord.H and $80000000 = $80000000 then begin Inc(QWord.H); if QWord.H and $80000000 <> $80000000 then begin QWord.L := 0; QWord.H := 0; end; end else begin Inc(QWord.H); end; end; end else begin Inc(QWord.L, i); end; end; /////////// // TIdCoder /////////// constructor TIdCoder.Create; begin inherited Create(AOwner); FCBufferSize := 4096; FAddCRLF := False; fAutoCompleteInput := False; FByteCount.L := 0; FByteCount.H := 0; FBytesIn.L := 0; FBytesIn.H := 0; FBytesOut.L := 0; FBytesOut.H := 0; FPriority := CP_FALLBACK; FInCompletion := False; FIgnoreCodedData := False; FIgnoreNotification := False; FFileName := ''; FTakesFileName := False; FKey := ''; FTakesKey := False; FUseEvent := False; FOutputStrings := TStringList.Create; SetLength(FCBuffer, FCBufferSize); end; procedure TIdCoder.Reset; begin InternSetBufferSize(FCBufferSize); FInCompletion := False; FOutputStrings.Clear; end; procedure TIdCoder.SetBufferSize; begin InternSetBufferSize(ASize); end; procedure TIdCoder.Coder; var s: string; begin SetLength(s, FCBufferSize); System.Move(FCBuffer[1], s[1], FCBufferSize); UniqueString(s); OutputString(s); FCBufferedData := 0; end; procedure TIdCoder.CompleteCoding; var s: string; begin SetLength(s, FCBufferedData); UniqueString(s); System.Move(FCBuffer[1], s[1], FCBufferedData); OutputString(s); IncByteCount(FCBufferedData); FCBufferedData := 0; end; procedure TIdCoder.CodeStringFromCoder; begin CodeString(sOut); end; function TIdCoder.CodeString; var i: Integer; str: string; begin str := AStr; IncQWord(FBytesIn, length(str)); while str <> '' do begin i := FCBufferSize - FCBufferedData; if Length(str) >= i then begin System.Move(str[1], FCBuffer[FCBufferedData + 1], i); str := Copy(str, i + 1, length(str)); FCBufferedData := FCBufferSize; Coder; end else begin System.Move(str[1], FCBuffer[FCBufferedData + 1], Length(str)); Inc(FCBufferedData, Length(str)); str := ''; end; end; if fAutoCompleteInput then begin result := CompletedInput; end else begin result := GetNotification; end; end; function TIdCoder.CompletedInput; begin FInCompletion := True; CompleteCoding; result := GetNotification; end; procedure TIdCoder.IncByteCount; begin IncQWord(FByteCount, bytes); end; procedure TIdCoder.SetKey; begin FKey := key; end; destructor TIdCoder.Destroy; begin FOutputStrings.Free; inherited; end; procedure TIdCoder.OutputNotification; begin if FUseEvent then begin if Assigned(FOnNotification) then begin FOnNotification(Self, AVal, AStr); end; end else begin FOutputStrings.Add(IntToStr(AVal) + ';' + AStr); end; end; procedure TIdCoder.OutputString; var s1: string; begin if FAddCRLF then begin s1 := s + CR + LF; end else begin s1 := s; end; IncQWord(FBytesOut, length(s1)); if FUseEvent then begin if Assigned(FOnCodedData) then begin OnCodedData(Self, s1); end; end else begin FOutputStrings.Add(IntToStr(CN_CODED_DATA) + ';' + s1); end; end; procedure TIdCoder.InternSetBufferSize; begin if BufferSize > length(FCBuffer) then begin SetLength(FCBuffer, BufferSize); UniqueString(FCBuffer); end; FCBufferSize := BufferSize; FCBufferedData := 0; end; function TIdCoder.GetNotification; var s, ent: string; exWhile: Boolean; begin if FIgnoreNotification and FIgnoreCodedData then begin FOutputStrings.Clear; result := ''; end else begin if FOutputStrings.Count > 0 then begin s := FOutputStrings[0]; if s[1] <> '0' then begin FOutputStrings.Delete(0); result := s; end else begin exWhile := False; FOutputStrings.Delete(0); Fetch(s, ';'); while not exWhile do begin if FOutputStrings.Count > 0 then begin ent := FOutputStrings[0]; if ent[1] = '0' then begin Fetch(ent, ';'); s := s + ent; FOutputStrings.Delete(0); end else begin exWhile := True; end; end else begin exWhile := True; end; if FOutputStrings.Count = 0 then begin exWhile := True; end; end; result := '0;' + s; end; end else begin result := ''; end; end; end; function TIdCoder.GetCodedData; var s: string; i: Integer; begin if FIgnoreNotification and FIgnoreCodedData then begin FOutputStrings.Clear; result := ''; end else begin if FOutputStrings.Count > 0 then begin s := FOutputStrings[0]; if s[1] = '0' then begin FOutputStrings.Delete(0); result := s; Fetch(result, ';'); end else if FIgnoreNotification then begin i := FOutputStrings.Count; while FOutputStrings[0][1] <> '0' do begin FOutputStrings.Delete(0); Dec(i); if i <= 0 then break; end; result := GetCodedData; end else begin result := ''; end; end else begin result := ''; end; end; end; ///////////////////// // TIdCoderCollection ///////////////////// constructor TIdCoderCollection.Create; begin inherited Create(ItemClass); FCount := 0; end; function TIdCoderCollection.Add; begin Inc(FCount); result := TIdCoderItem(inherited Add); end; function TIdCoderCollection.GetCoder; begin result := TIdCoderItem(inherited Items[Index]); end; function TIdCoderCollection.AddCoder; begin result := Self.Add; end; function TIdCoderCollection.GetExactCoderType; var i: Integer; TWCI: TIdCoderItem; begin result := nil; i := 0; while i < Count do begin TWCI := Items[i]; if CoderType = TWCI.CoderType then begin if LowerCase(TWCI.ContentTransferEncoding) = LowerCase(ContentTransferEncoding) then begin if LowerCase(TWCI.ContentType) = LowerCase(ContentType) then begin result := GetCoder(i); break; end; end; end; Inc(i); end; end; function TIdCoderCollection.GetCoderType; var i: Integer; TWCI: TIdCoderItem; found: Boolean; begin result := nil; TWCI := GetExactCoderType(ContentType, ContentTransferEncoding, CoderType); if TWCI = nil then begin i := 0; found := false; if ContentTransferEncoding <> '' then begin while i < Count do begin TWCI := Items[i]; if CoderType = TWCI.CoderType then begin if (LowerCase(TWCI.ContentTransferEncoding) = LowerCase(ContentTransferEncoding)) and (ContentTransferEncoding <> '') then begin result := TWCI; found := True; break; end; end; Inc(i); end; end; if (not found) and (ContentType <> '') then begin while i < Count do begin TWCI := Items[i]; if CoderType = TWCI.CoderType then begin if (LowerCase(TWCI.ContentType) = LowerCase(ContentType)) and (ContentType <> '') then begin result := TWCI; found := True; break; end; end; Inc(i); end; end; if not found then begin result := GetExactCoderType('application/octet-stream', '', CoderType); end; end else begin result := TWCI; end; end; initialization CoderCollective := TIdCoderCollection.Create(TIdCoderItem); RegisterCoderClass(TIdCoder, CT_CREATION, CP_FALLBACK, 'application/octet-stream', ''); RegisterCoderClass(TIdCoder, CT_REALISATION, CP_FALLBACK, 'application/octet-stream', ''); finalization CoderCollective.Free; end.
program PointingDevice; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, uSMBIOS { you can add units after this }; procedure GetPointingDeviceInfo; Var SMBios: TSMBios; LPointDevice: TBuiltInPointingDeviceInformation; begin SMBios:=TSMBios.Create; try WriteLn('Built-in Pointing Device Information'); WriteLn('------------------------------------'); if SMBios.HasBuiltInPointingDeviceInfo then for LPointDevice in SMBios.BuiltInPointingDeviceInformation do begin WriteLn(Format('Type %s',[LPointDevice.GetType])); WriteLn(Format('Interface %s',[LPointDevice.GetInterface])); WriteLn(Format('Number of Buttons %d',[LPointDevice.RAWBuiltInPointingDeviceInfo^.NumberofButtons])); WriteLn; end else Writeln('No Built-in Pointing Device Info was found'); finally SMBios.Free; end; end; begin try GetPointingDeviceInfo; except on E:Exception do Writeln(E.Classname, ':', E.Message); end; Writeln('Press Enter to exit'); Readln; end.
unit fGMV_Qualifiers; { ================================================================================ * * Application: Vitals * Revision: $Revision: 1 $ $Modtime: 2/26/09 12:50p $ * Developer: ddomain.user@domain.ext/doma.user@domain.ext * Site: Hines OIFO * * Description: Pop-up form for qualifiers when entering vitals. * * Notes: * ================================================================================ * $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSDATAENTRY/fGMV_Qualifiers.pas $ * * $History: fGMV_Qualifiers.pas $ * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 8/12/09 Time: 8:29a * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSDATAENTRY * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 3/09/09 Time: 3:38p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSDATAENTRY * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 1/13/09 Time: 1:26p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSDATAENTRY * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/14/07 Time: 10:29a * Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSDATAENTRY * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:43p * Created in $/Vitals/VITALS-5-0-18/VitalsDataEntry * GUI v. 5.0.18 updates the default vital type IENs with the local * values. * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:33p * Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsDataEntry * * ***************** Version 2 ***************** * User: Zzzzzzandria Date: 7/22/05 Time: 3:51p * Updated in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsDataEntry * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/24/05 Time: 3:35p * Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, No CCOW) - Delphi 6/VitalsDataEntry * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 4/16/04 Time: 4:20p * Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSDATAENTRY * * ***************** Version 2 ***************** * User: Zzzzzzandria Date: 1/30/04 Time: 4:32p * Updated in $/VitalsLite/VitalsLiteDLL * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 1/15/04 Time: 3:06p * Created in $/VitalsLite/VitalsLiteDLL * Vitals Lite DLL * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 10/29/03 Time: 4:15p * Created in $/Vitals503/Vitals User * Version 5.0.3 * * ***************** Version 3 ***************** * User: Zzzzzzandria Date: 7/16/03 Time: 5:40p * Updated in $/Vitals GUI Version 5.0/VitalsUserNoCCOW * * ***************** Version 2 ***************** * User: Zzzzzzandria Date: 6/05/03 Time: 2:01p * Updated in $/Vitals GUI Version 5.0/VitalsUserNoCCOW * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/21/03 Time: 1:18p * Created in $/Vitals GUI Version 5.0/VitalsUserNoCCOW * Pre CCOW Version of Vitals User * * ***************** Version 4 ***************** * User: Zzzzzzandria Date: 7/18/02 Time: 5:57p * Updated in $/Vitals GUI Version 5.0/Vitals User * * ***************** Version 3 ***************** * User: Zzzzzzandria Date: 7/12/02 Time: 5:00p * Updated in $/Vitals GUI Version 5.0/Vitals User * GUI Version T28 * * ***************** Version 2 ***************** * User: Zzzzzzandria Date: 7/01/02 Time: 5:14p * Updated in $/Vitals GUI Version 5.0/Vitals User * * ***************** Version 1 ***************** * User: Zzzzzzpetitd Date: 4/04/02 Time: 12:04p * Created in $/Vitals GUI Version 5.0/Vitals User * * ================================================================================ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CheckLst, ExtCtrls , uGMV_FileEntry , uGMV_Const , uGMV_GlobalVars , uGMV_VitalTypes ; type TfrmGMV_Qualifiers = class(TForm) pnlMain: TPanel; pnlBottom: TPanel; edtQuals: TEdit; sb: TScrollBox; Panel1: TPanel; btnOK: TButton; btnCancel: TButton; Panel2: TPanel; Panel4: TPanel; Bevel1: TBevel; pnlTitle: TPanel; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure pnlBottomResize(Sender: TObject); procedure FormActivate(Sender: TObject);// AAN 07/01/2002 private FPanelList: TList; protected public { Public declarations } FQIENS: string; function QualifierNames: string; function QualifierIENS: string; procedure QualifierClicked(Sender: TObject); procedure SetDefaultQualifier(aCategoryIEN,aQualifierIEN:String;aVType: TVitalType); end; function SelectQualifiers(VType: TVitalType; var Quals, QualsDisplay: string; Ctrl: TControl;aValue:String): Boolean; implementation uses uGMV_QualifyBox, uGMV_Common, uGMV_Engine, system.Types ; {$R *.DFM} //IDs //String function SelectQualifiers(VType: TVitalType; var Quals, QualsDisplay: string; Ctrl: TControl;aValue:String): Boolean; var s: String;//AAN 07/11/02 for Debugging only _QForm: TfrmGMV_Qualifiers; TQB, QPanel: TGMV_TemplateQualifierBox; iOrder, i, j: integer; ii: Integer; pt: TPoint; RetList: TStrings; begin Result := False; _QForm := TfrmGMV_Qualifiers.Create(Application); with _QForm do try pt := Ctrl.Parent.ClientToScreen(Point(Ctrl.Left, Ctrl.Top)); Left := pt.x; Top := pt.y + Ctrl.Height; RetList := getVitalQualifierList(GMVVitalTypeAbbv[VType]); _QForm.pnlTitle.Caption := piece(RetList.Text,'^',3) + ' Qualifiers'; for i := 0 to RetList.Count - 1 do begin // S := RetList[i]; if Piece(RetList[i], '^', 1) = 'C' then begin QPanel := TGMV_TemplateQualifierBox.CreateParented( // _QForm.pnlMain, _QForm,_QForm.sb, GMVVitalTypeIEN[VType], piece(RetList[i], '^', 2),''); FPanelList.Add(QPanel); // _QForm.Width := FPanelList.Count * 100; end; end; RetList.Free; // if FPanelList.Count < 2 then // _QForm.Width := 150; for i := 0 to _QForm.sb.ControlCount - 1 do begin if _QForm.sb.Controls[i] is TGMV_TemplateQualifierBox then begin iOrder := _QForm.sb.ControlCount - 1 - i; TGMV_TemplateQualifierBox(_QForm.sb.Controls[i]).TabOrder := iOrder; end; end; for i := 0 to FPanelList.Count - 1 do with TGMV_TemplateQualifierBox(FPanelList[i]) do begin { Left := i * (_QForm.Width div FPanelList.Count); Width := _QForm.Width div FPanelList.Count; if i < (FPanelList.Count - 1) then Align := alLeft else Align := alClient; } Align := alTop; Visible := True; OnClick := QualifierClicked; setPopupLayout; end; i := 1; for j := 0 to FPanelList.Count - 1 do begin TQB := TGMV_TemplateQualifierBox(FPanelList[j]); s := TQB.DefaultQualifierIEN; ii := StrToIntDef(s,0); if ii < 1 then begin s := piece(Quals, ':', i);// assigning qualifiers as DEFAULT (!?) try if s <> '' then // changed on 050708 by zzzzzzandria begin TGMV_TemplateQualifierBox(FPanelList[j]).DefaultQualifierIEN := s; // piece(Quals, ':', i); // TGMV_TemplateQualifierBox(FPanelList[j]).OnQualClick(TGMV_TemplateQualifierBox(FPanelList[j]).CLB); TGMV_TemplateQualifierBox(FPanelList[j]).OnQualClick(nil); end else // TGMV_TemplateQualifierBox(FPanelList[j]).OnQualClick(TGMV_TemplateQualifierBox(FPanelList[j]).CLB); TGMV_TemplateQualifierBox(FPanelList[j]).OnQualClick(nil); except on E: Exception do ShowMessage('Error assigning <'+s+'> as the default qualifier'+#13#10+ E.Message); end; end; inc(i); end; // --------------------------------Set Default Method for BP if value is like nnn/ // if (VType = vtBP) and (pos('/',aValue) = Length(aValue)) then // QForm.SetDefaultQualifier('2','45',vtBP); edtQuals.Text := QualifierNames; PositionForm(_QForm); ShowModal; if ModalResult = mrOk then begin Quals := _QForm.FQIENS; QualsDisplay := _QForm.edtQuals.Text; Result := True; end; finally free; end; end; function TfrmGMV_Qualifiers.QualifierNames: string; var i: integer; begin Result := ''; for i := 0 to FPanelList.Count - 1 do with TGMV_TemplateQualifierBox(FPanelList[i]) do if StrToIntDef(DefaultQualifierIEN, 0) > 0 then begin if Result <> '' then Result := Result + ', '; Result := Result + DefaultQualifierName; end; end; function TfrmGMV_Qualifiers.QualifierIENS: string; var i: integer; begin Result := ''; for i := 0 to FPanelList.Count - 1 do if TGMV_TemplateQualifierBox(FPanelList[i]).DefaultQualifierIEN <> '' then Result := Result + TGMV_TemplateQualifierBox(FPanelList[i]).DefaultQualifierIEN + ':' ; i:= Length(Result); if i > 0 then Result := copy(Result,1,i-1); { with TGMV_TemplateQualifierBox(FPanelList[i]) do begin if Result = '' then begin if DefaultQualifierIEN <> '' then Result := DefaultQualifierIEN; end else if DefaultQualifierIEN <> '' then Result := Result + ':' +DefaultQualifierIEN; end; } end; procedure TfrmGMV_Qualifiers.QualifierClicked(Sender: TObject); begin edtQuals.Text := QualifierNames; FQIENS := QualifierIENS; end; procedure TfrmGMV_Qualifiers.FormCreate(Sender: TObject); begin FPanelList := TList.Create; end; procedure TfrmGMV_Qualifiers.FormClose(Sender: TObject; var Action: TCloseAction); begin FreeAndNil(FPanelList); end; procedure TfrmGMV_Qualifiers.pnlBottomResize(Sender: TObject); begin // edtQuals.Width := pnlBottom.Width - (edtQuals.left * 2); // btnCancel.Left := pnlBottom.Width - btnCancel.Width - edtQuals.Left; // btnOK.Left := btnCancel.Left - btnOk.Width - edtQuals.Left; end; // AAN 07/01/2002 -------------------------------------------------------- Begin procedure TfrmGMV_Qualifiers.FormActivate(Sender: TObject); begin if (Left + Width) > Forms.Screen.Width then Left := Forms.Screen.Width - Width; if (Top + Height) > Forms.Screen.Height then Top := Forms.Screen.Height - Height - pnlBottom.Height div 2; end; // AAN 07/01/2002 ---------------------------------------------------------- End procedure TfrmGMV_Qualifiers.SetDefaultQualifier(aCategoryIEN,aQualifierIEN:String;aVType: TVitalType); var TQB: TGMV_TemplateQualifierBox; i: Integer; begin for i := 0 to FPanelList.Count - 1 do begin TQB := TGMV_TemplateQualifierBox(FPanelList[i]); if TQB.CategoryIEN = aCategoryIEN then TQB.DefaultQualifierIEN := aQualifierIEN; end; end; end.
unit Financials_MutualFund_c; {This file was generated on 11 Aug 2000 20:14:44 GMT by version 03.03.03.C1.06} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file account.idl. } {Delphi Pascal unit : Financials_MutualFund_c } {derived from IDL module : MutualFund } interface uses CORBA, Financials_MutualFund_i; type TAssetHelper = class; TAssetStub = class; TAssetHelper = class class procedure Insert (var _A: CORBA.Any; const _Value : Financials_MutualFund_i.Asset); class function Extract(var _A: CORBA.Any) : Financials_MutualFund_i.Asset; class function TypeCode : CORBA.TypeCode; class function RepositoryId : string; class function Read (const _Input : CORBA.InputStream) : Financials_MutualFund_i.Asset; class procedure Write(const _Output : CORBA.OutputStream; const _Value : Financials_MutualFund_i.Asset); class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : Financials_MutualFund_i.Asset; class function Bind(const _InstanceName : string = ''; _HostName : string = '') : Financials_MutualFund_i.Asset; overload; class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : Financials_MutualFund_i.Asset; overload; end; TAssetStub = class(CORBA.TCORBAObject, Financials_MutualFund_i.Asset) public function nav : Single; virtual; end; implementation class procedure TAssetHelper.Insert(var _A : CORBA.Any; const _Value : Financials_MutualFund_i.Asset); begin _A := Orb.MakeObjectRef( TAssetHelper.TypeCode, _Value as CORBA.CORBAObject); end; class function TAssetHelper.Extract(var _A : CORBA.Any): Financials_MutualFund_i.Asset; var _obj : Corba.CorbaObject; begin _obj := Orb.GetObjectRef(_A); Result := TAssetHelper.Narrow(_obj, True); end; class function TAssetHelper.TypeCode : CORBA.TypeCode; begin Result := ORB.CreateInterfaceTC(RepositoryId, 'Asset'); end; class function TAssetHelper.RepositoryId : string; begin Result := 'IDL:Financials/MutualFund/Asset:1.0'; end; class function TAssetHelper.Read(const _Input : CORBA.InputStream) : Financials_MutualFund_i.Asset; var _Obj : CORBA.CORBAObject; begin _Input.ReadObject(_Obj); Result := Narrow(_Obj, True) end; class procedure TAssetHelper.Write(const _Output : CORBA.OutputStream; const _Value : Financials_MutualFund_i.Asset); begin _Output.WriteObject(_Value as CORBA.CORBAObject); end; class function TAssetHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : Financials_MutualFund_i.Asset; begin Result := nil; if (_Obj = nil) or (_Obj.QueryInterface(Financials_MutualFund_i.Asset, Result) = 0) then exit; if _IsA and _Obj._IsA(RepositoryId) then Result := TAssetStub.Create(_Obj); end; class function TAssetHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : Financials_MutualFund_i.Asset; begin Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True); end; class function TAssetHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : Financials_MutualFund_i.Asset; begin Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True); end; function TAssetStub.nav : Single; var _Output: CORBA.OutputStream; _Input : CORBA.InputStream; begin inherited _CreateRequest('nav',True, _Output); inherited _Invoke(_Output, _Input); _Input.ReadFloat(Result); end; initialization end.
{ "MacOSX Screen Utils (FMX)" - Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com) @exclude } unit rtcFScreenUtilsOSX; interface {$include rtcDefs.inc} uses {$IFDEF IDE_XE6up} // FMX.Graphics, {$ENDIF} FMX.Types, FMX.Platform, rtcXBmpUtils, rtcXScreenUtils, Macapi.CoreFoundation, Macapi.CocoaTypes, Macapi.CoreGraphics, Macapi.ImageIO; function GetScreenBitmapInfo:TRtcBitmapInfo; function ScreenCapture(var Image: TRtcBitmapInfo; Forced:boolean):boolean; implementation type TMySize=record Width, Height:integer; end; function GetScreenSize: TMySize; var ScreenService: IFMXScreenService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(ScreenService)) then begin with ScreenService.GetScreenSize.Round do begin Result.Width := X; Result.Height := Y; end; end else begin Result.Width := 0; Result.Height := 0; end; end; function GetScreenBitmapInfo:TRtcBitmapInfo; begin FillChar(Result,SizeOf(Result),0); Result.Reverse:=False; Result.BuffType:=btRGBA32; Result.BytesPerPixel:=4; CompleteBitmapInfo(Result); end; function ScreenCapture(var Image: TRtcBitmapInfo; Forced:boolean):boolean; var Screenshot: CGImageRef; Img:CFDataRef; myPtr:pointer; myLen:integer; // srect:CGRect; scrsize:TMySize; begin Result:=False; ScreenShot := CGDisplayCreateImage(CGMainDisplayID); scrsize:=GetScreenSize; {srect.origin.x:=0; srect.origin.y:=0; srect.size.width:=scrsize.Width; srect.size.height:=scrsize.Height; ScreenShot := CGWindowListCreateImage(srect, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);} if ScreenShot = nil then Exit; try Img:=CGDataProviderCopyData(CGImageGetDataProvider(ScreenShot)); if Img=nil then Exit; try myPtr := CFDataGetBytePtr(Img); if myPtr=nil then Exit; myLen := CFDataGetLength(Img); if not assigned(Image.Data) or (Image.Width<>scrsize.Width) or (Image.Height<>scrsize.Height) then ResizeBitmapInfo(Image,scrsize.Width,scrsize.Height,False); if myLen<=Image.Width*Image.Height*Image.BytesPerPixel then Move(myPtr^, Image.Data^, myLen) else Move(myPtr^, Image.Data^, Image.Width * Image.Height * Image.BytesPerPixel); Result:=True; finally CFRelease(Img); end; finally CGImageRelease(ScreenShot); end; end; end.
unit TestInterfaces; { AFS 16 Jan 2000 This unit compiles but is not semantically meaningfull it is test cases for the code formatting utility This unit tests interface declarations. This was orignally extacted from TestTypeDefs but this version is a bit more mixed up } interface uses classes; type { some fairly simple real-world code (modified slightly and deformated a bit) } IMyIterator = interface (IUnknown) procedure First; safecall; procedure Next; safecall; end; IEntryJournalLookupDisp = dispinterface ['{D34D4103-FBC4-11D2-94F3-00A0CC39B56F}'] property StartDate: TDateTime dispid 1; property EndDate: TDateTime dispid 2; property MaxRows: Integer dispid 2000; property Iterator: IMyIterator readonly dispid 2001; function Execute: IMyIterator; dispid 2002; function GetNewOjectKey: IUnknown; dispid 2003; property Soy: integer writeonly; end; IEntryJournalIterator = interface(IMyIterator) ['{D34D4105-FBC4-11D2-94F3-00A0CC39B56F}'] function Get_Note: WideString; safecall; function Get_Status: WideString; safecall; function Get_CreatedDate: TDateTime; safecall; function Get_LoginName: WideString; safecall; function Get_Id: Integer; safecall; procedure Set_Id(Id: Integer); safecall; property Note: WideString read Get_Note; property Status: WideString read Get_Status; property CreatedDate: TDateTime read Get_CreatedDate; property LoginName: WideString read Get_LoginName; property Id: Integer read Get_Id write Set_Id; end; IMyOtherIterator = interface (IUnknown) procedure First; safecall; procedure Next; safecall; end; const FOO_DISP_ID = 12; BAR_DISP_ID = 1002; type IFooDisp = dispinterface ['{3050F1FF-98B5-11CF-BB82-00AA00CACE0B}'] procedure setAttribute(const strAttributeName: WideString; AttributeValue: OleVariant; lFlags: Integer); dispid -2147417611; function getAttribute(const strAttributeName: WideString; lFlags: Integer): OleVariant; dispid FOO_DISP_ID; function removeAttribute(const strAttributeName: WideString; lFlags: Integer): WordBool; dispid -2147417609; property className: WideString dispid BAR_DISP_ID + FOO_DISP_ID; property id: WideString dispid (-1 * FOO_DISP_ID); property onfilterchange: OleVariant dispid -2147412069; property children: IDispatch readonly dispid -2147417075; property all: IDispatch readonly dispid -2147417074; property foo[const bar: integer]: IDispatch readonly dispid -2147417073; property foo2[var bar: integer]: IDispatch readonly dispid -2147417072; property foo3[out bar: integer]: IDispatch readonly dispid -2147417071; end; implementation end.
{********************************************} { TeeChart Pro Charting Library } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeeRMSFuncEdit; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} TeeEdiPeri, TeCanvas; { Warning: This form is used for both TRMSFunction and TStdDeviationFunction. The reason is to share the same form for both functions to save resources, as both functions have only a "Complete" boolean property. } type TRMSFuncEditor = class(TTeeFunctionEditor) CBComplete: TCheckBox; procedure CBCompleteClick(Sender: TObject); private { Private declarations } protected procedure ApplyFormChanges; override; procedure SetFunction; override; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} uses StatChar; procedure TRMSFuncEditor.ApplyFormChanges; begin inherited; if IFunction is TRMSFunction then TRMSFunction(IFunction).Complete:=CBComplete.Checked else if IFunction is TStdDeviationFunction then TStdDeviationFunction(IFunction).Complete:=CBComplete.Checked; end; procedure TRMSFuncEditor.CBCompleteClick(Sender: TObject); begin EnableApply; end; procedure TRMSFuncEditor.SetFunction; begin inherited; if IFunction is TRMSFunction then CBComplete.Checked:=TRMSFunction(IFunction).Complete else CBComplete.Checked:=TStdDeviationFunction(IFunction).Complete; end; initialization RegisterClass(TRMSFuncEditor); end.
Unit nvram; (***********************************************************) (**) interface (**) (***********************************************************) const SaveFileName='.\sav\nvram.sav'; type c2500nvram=class (***********************************************************) (**) private (**) (***********************************************************) locations : array[0..$7fff] of byte; WP : boolean; (***********************************************************) (**) public (**) (***********************************************************) function InterfaceRead8 (address:word): byte; function InterfaceRead16 (address:word): word; procedure Load_NVRAMImage (var NVRAMFile:file); procedure InterfaceWrite8 (address:word;data:byte); procedure InterfaceWrite16(address:word;data:word); procedure unlockNVRAM; procedure StatusSave; procedure StatusRestore; procedure reset; constructor create; end; (******************************************************************************) (**) (**) (**) implementation (**) (**) (**) (******************************************************************************) function c2500nvram.InterfaceRead8 (address:word):byte; begin if address<$8000 then result:=locations[address]; end; (******************************************************************************) procedure c2500nvram.InterfaceWrite8(address:word;data:byte); begin if not wp then if address<$8000 then locations[address]:=data; end; (******************************************************************************) function c2500nvram.InterfaceRead16 (address:word):word; begin if address<$8000 then result:=locations[address] shl 8 + locations[address+1]; end; (******************************************************************************) procedure c2500nvram.InterfaceWrite16(address:word;data:word); begin if not wp then if address<$8000 then begin locations[address ]:=(data and $ff00) shr 8; locations[address+1]:= data and $ff; end; end; (******************************************************************************) constructor c2500nvram.create; begin wp:=true; end; (******************************************************************************) procedure c2500nvram.Load_NVRAMImage (var NVRAMFile:file); begin blockread(NVRAMFile,locations[0],filesize(NVRAMFile)); end; (******************************************************************************) procedure c2500nvram.reset; begin wp:=true; end; (******************************************************************************) procedure c2500nvram.unlockNVRAM; begin wp:=false; end; (******************************************************************************) procedure c2500nvram.StatusSave; var f:file; begin assignfile(f,SaveFileName); rewrite(f,1); blockwrite(f,locations,$8001); closefile(f); end; (******************************************************************************) procedure c2500nvram.StatusRestore; var f:file; begin assignfile(f,SaveFileName); system.reset(f,1); blockread(f,locations,$8001); closefile(f); end; end.
unit fVA508DispatcherHiddenWindow; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TfrmVA508JawsDispatcherHiddenWindow = class(TForm) tmrMain: TTimer; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tmrMainTimer(Sender: TObject); private FThreads: TStringList; protected procedure WndProc(var Msg: TMessage); override; procedure UpdateThreadList; public { Public declarations } end; var frmVA508JawsDispatcherHiddenWindow: TfrmVA508JawsDispatcherHiddenWindow; implementation uses VAUtils, JAWSCommon; {$R *.dfm} procedure TfrmVA508JawsDispatcherHiddenWindow.FormCreate(Sender: TObject); begin ErrorCheckClassName(Self, DISPATCHER_WINDOW_CLASS); FThreads := TStringList.Create; Caption := DISPATCHER_WINDOW_TITLE; UpdateThreadList; end; procedure TfrmVA508JawsDispatcherHiddenWindow.FormDestroy(Sender: TObject); begin FThreads.Free; end; procedure TfrmVA508JawsDispatcherHiddenWindow.tmrMainTimer(Sender: TObject); begin tmrMain.Enabled := FALSE; UpdateThreadList; if FThreads.Count < 1 then Application.Terminate else tmrMain.Enabled := TRUE; end; function WindowSearchProc(Handle: HWND; var FThreads: TStringList): BOOL; stdcall; var cls: string; test: string; Thread: DWORD; ThreadID: string; begin cls := GetWindowClassName(Handle); test := GetWindowTitle(handle); if (cls = DLL_MAIN_WINDOW_CLASS) then begin if (copy(GetWindowTitle(Handle),1,DLL_WINDOW_TITLE_LEN) = DLL_WINDOW_TITLE) then begin Thread := GetWindowThreadProcessId(Handle, nil); ThreadID := FastIntToHex(Thread); FThreads.AddObject(ThreadID, TObject(Handle)) end; end; Result := TRUE; end; procedure TfrmVA508JawsDispatcherHiddenWindow.UpdateThreadList; begin FThreads.Clear; EnumWindows(@WindowSearchProc, Integer(@FThreads)); end; procedure TfrmVA508JawsDispatcherHiddenWindow.WndProc(var Msg: TMessage); var CurrentWindow: HWND; Thread: DWORD; ThreadID: string; idx: integer; procedure FindActiveWindow; begin CurrentWindow := GetForegroundWindow(); if IsWindow(CurrentWindow) then begin Thread := GetWindowThreadProcessId(CurrentWindow, nil); ThreadID := FastIntToHex(Thread); idx := FThreads.IndexOf(ThreadID); if idx < 0 then begin UpdateThreadList; idx := FThreads.IndexOf(ThreadID); end; if idx >= 0 then begin SendReturnValue(Handle, Integer(FThreads.Objects[idx])); end; end; end; begin if Msg.Msg = MessageID then begin Msg.Result := 1; if assigned(Self) then // JAWS can detect the window before Delphi has finished creating it begin try if Msg.WParam = JAWS_MESSAGE_GET_DLL_WITH_FOCUS then FindActiveWindow; except end; end; end; inherited WndProc(Msg); end; end.
{ This file is part of the Pas2JS run time library. Copyright (c) 2017 by Mattias Gaertner 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. **********************************************************************} unit ClassesMore; {$mode objfpc} interface uses RTLConsts, Types, SysUtils, JS, TypInfo; type TNotifyEvent = procedure(Sender: TObject) of object; TNotifyEventRef = reference to procedure(Sender: TObject); TStringNotifyEventRef = Reference to Procedure(Sender: TObject; Const aString : String); // Notification operations : // Observer has changed, is freed, item added to/deleted from list, custom event. TFPObservedOperation = (ooChange,ooFree,ooAddItem,ooDeleteItem,ooCustom); EStreamError = class(Exception); EFCreateError = class(EStreamError); EFOpenError = class(EStreamError); EFilerError = class(EStreamError); EReadError = class(EFilerError); EWriteError = class(EFilerError); EClassNotFound = class(EFilerError); EMethodNotFound = class(EFilerError); EInvalidImage = class(EFilerError); EResNotFound = class(Exception); EListError = class(Exception); EBitsError = class(Exception); EStringListError = class(EListError); EComponentError = class(Exception); EParserError = class(Exception); EOutOfResources = class(EOutOfMemory); EInvalidOperation = class(Exception); TListAssignOp = (laCopy, laAnd, laOr, laXor, laSrcUnique, laDestUnique); TListSortCompare = function(Item1, Item2: JSValue): Integer; TListSortCompareFunc = reference to function (Item1, Item2: JSValue): Integer; TListCallback = Types.TListCallback; TListStaticCallback = Types.TListStaticCallback; TAlignment = (taLeftJustify, taRightJustify, taCenter); // Forward class definitions TFPList = Class; TReader = Class; TWriter = Class; TFiler = Class; { TFPListEnumerator } TFPListEnumerator = class private FList: TFPList; FPosition: Integer; public constructor Create(AList: TFPList); reintroduce; function GetCurrent: JSValue; function MoveNext: Boolean; property Current: JSValue read GetCurrent; end; { TFPList } TFPList = class(TObject) private FList: TJSValueDynArray; FCount: Integer; FCapacity: Integer; procedure CopyMove(aList: TFPList); procedure MergeMove(aList: TFPList); procedure DoCopy(ListA, ListB: TFPList); procedure DoSrcUnique(ListA, ListB: TFPList); procedure DoAnd(ListA, ListB: TFPList); procedure DoDestUnique(ListA, ListB: TFPList); procedure DoOr(ListA, ListB: TFPList); procedure DoXOr(ListA, ListB: TFPList); protected function Get(Index: Integer): JSValue; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} procedure Put(Index: Integer; Item: JSValue); {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} procedure SetCapacity(NewCapacity: Integer); procedure SetCount(NewCount: Integer); Procedure RaiseIndexError(Index: Integer); public //Type // TDirection = (FromBeginning, FromEnd); destructor Destroy; override; procedure AddList(AList: TFPList); function Add(Item: JSValue): Integer; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} procedure Clear; procedure Delete(Index: Integer); {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} class procedure Error(const Msg: string; const Data: String); procedure Exchange(Index1, Index2: Integer); function Expand: TFPList; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} function Extract(Item: JSValue): JSValue; function First: JSValue; function GetEnumerator: TFPListEnumerator; function IndexOf(Item: JSValue): Integer; function IndexOfItem(Item: JSValue; Direction: TDirection): Integer; procedure Insert(Index: Integer; Item: JSValue); {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} function Last: JSValue; procedure Move(CurIndex, NewIndex: Integer); procedure Assign (ListA: TFPList; AOperator: TListAssignOp=laCopy; ListB: TFPList=nil); function Remove(Item: JSValue): Integer; procedure Pack; procedure Sort(const Compare: TListSortCompare); procedure SortList(const Compare: TListSortCompareFunc); procedure ForEachCall(const proc2call: TListCallback; const arg: JSValue); procedure ForEachCall(const proc2call: TListStaticCallback; const arg: JSValue); property Capacity: Integer read FCapacity write SetCapacity; property Count: Integer read FCount write SetCount; property Items[Index: Integer]: JSValue read Get write Put; default; property List: TJSValueDynArray read FList; end; TListNotification = (lnAdded, lnExtracted, lnDeleted); TList = class; { TListEnumerator } TListEnumerator = class private FList: TList; FPosition: Integer; public constructor Create(AList: TList); reintroduce; function GetCurrent: JSValue; function MoveNext: Boolean; property Current: JSValue read GetCurrent; end; { TList } TList = class(TObject) private FList: TFPList; procedure CopyMove (aList : TList); procedure MergeMove (aList : TList); procedure DoCopy(ListA, ListB : TList); procedure DoSrcUnique(ListA, ListB : TList); procedure DoAnd(ListA, ListB : TList); procedure DoDestUnique(ListA, ListB : TList); procedure DoOr(ListA, ListB : TList); procedure DoXOr(ListA, ListB : TList); protected function Get(Index: Integer): JSValue; procedure Put(Index: Integer; Item: JSValue); procedure Notify(aValue: JSValue; Action: TListNotification); virtual; procedure SetCapacity(NewCapacity: Integer); function GetCapacity: integer; procedure SetCount(NewCount: Integer); function GetCount: integer; function GetList: TJSValueDynArray; property FPList : TFPList Read FList; public constructor Create; reintroduce; destructor Destroy; override; Procedure AddList(AList : TList); function Add(Item: JSValue): Integer; procedure Clear; virtual; procedure Delete(Index: Integer); class procedure Error(const Msg: string; Data: String); virtual; procedure Exchange(Index1, Index2: Integer); function Expand: TList; function Extract(Item: JSValue): JSValue; function First: JSValue; function GetEnumerator: TListEnumerator; function IndexOf(Item: JSValue): Integer; procedure Insert(Index: Integer; Item: JSValue); function Last: JSValue; procedure Move(CurIndex, NewIndex: Integer); procedure Assign (ListA: TList; AOperator: TListAssignOp=laCopy; ListB: TList=nil); function Remove(Item: JSValue): Integer; procedure Pack; procedure Sort(const Compare: TListSortCompare); procedure SortList(const Compare: TListSortCompareFunc); property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount write SetCount; property Items[Index: Integer]: JSValue read Get write Put; default; property List: TJSValueDynArray read GetList; end; { TPersistent } {$M+} TPersistent = class(TObject) private //FObservers : TFPList; procedure AssignError(Source: TPersistent); protected procedure DefineProperties(Filer: TFiler); virtual; procedure AssignTo(Dest: TPersistent); virtual; function GetOwner: TPersistent; virtual; public procedure Assign(Source: TPersistent); virtual; //procedure FPOAttachObserver(AObserver : TObject); //procedure FPODetachObserver(AObserver : TObject); //procedure FPONotifyObservers(ASender : TObject; AOperation: TFPObservedOperation; Data: TObject); function GetNamePath: string; virtual; end; TPersistentClass = Class of TPersistent; TStrings = Class; { TStringsEnumerator class } TStringsEnumerator = class private FStrings: TStrings; FPosition: Integer; public constructor Create(AStrings: TStrings); reintroduce; function GetCurrent: String; function MoveNext: Boolean; property Current: String read GetCurrent; end; TProc = Reference to Procedure; TProcString = Reference to Procedure(Const aString : String); { TStrings class } TStrings = class(TPersistent) private FSpecialCharsInited : boolean; FAlwaysQuote: Boolean; FQuoteChar : Char; FDelimiter : Char; FNameValueSeparator : Char; FUpdateCount: Integer; FLBS : TTextLineBreakStyle; FSkipLastLineBreak : Boolean; FStrictDelimiter : Boolean; FLineBreak : String; function GetCommaText: string; function GetName(Index: Integer): string; function GetValue(const Name: string): string; Function GetLBS : TTextLineBreakStyle; Procedure SetLBS (AValue : TTextLineBreakStyle); procedure SetCommaText(const Value: string); procedure SetValue(const Name : String; Const Value: string); procedure SetDelimiter(c:Char); procedure SetQuoteChar(c:Char); procedure SetNameValueSeparator(c:Char); procedure DoSetTextStr(const Value: string; DoClear : Boolean); Function GetDelimiter : Char; Function GetNameValueSeparator : Char; Function GetQuoteChar: Char; Function GetLineBreak : String; procedure SetLineBreak(const S : String); Function GetSkipLastLineBreak : Boolean; procedure SetSkipLastLineBreak(const AValue : Boolean); protected procedure Error(const Msg: string; Data: Integer); function Get(Index: Integer): string; virtual; abstract; function GetCapacity: Integer; virtual; function GetCount: Integer; virtual; abstract; function GetObject(Index: Integer): TObject; virtual; function GetTextStr: string; virtual; procedure Put(Index: Integer; const S: string); virtual; procedure PutObject(Index: Integer; AObject: TObject); virtual; procedure SetCapacity(NewCapacity: Integer); virtual; procedure SetTextStr(const Value: string); virtual; procedure SetUpdateState(Updating: Boolean); virtual; property UpdateCount: Integer read FUpdateCount; Function DoCompareText(const s1,s2 : string) : PtrInt; virtual; Function GetDelimitedText: string; Procedure SetDelimitedText(Const AValue: string); Function GetValueFromIndex(Index: Integer): string; Procedure SetValueFromIndex(Index: Integer; const Value: string); Procedure CheckSpecialChars; // Class Function GetNextLine (Const Value : String; Var S : String; Var P : Integer) : Boolean; Function GetNextLinebreak (Const Value : String; Out S : String; Var P : Integer) : Boolean; public constructor Create; reintroduce; destructor Destroy; override; function Add(const S: string): Integer; virtual; overload; function Add(const Fmt : string; const Args : Array of JSValue): Integer; overload; function AddFmt(const Fmt : string; const Args : Array of JSValue): Integer; function AddObject(const S: string; AObject: TObject): Integer; virtual; overload; function AddObject(const Fmt: string; Args : Array of JSValue; AObject: TObject): Integer; overload; procedure Append(const S: string); procedure AddStrings(TheStrings: TStrings); overload; virtual; procedure AddStrings(TheStrings: TStrings; ClearFirst : Boolean); overload; procedure AddStrings(const TheStrings: array of string); overload; virtual; procedure AddStrings(const TheStrings: array of string; ClearFirst : Boolean); overload; function AddPair(const AName, AValue: string): TStrings; overload; function AddPair(const AName, AValue: string; AObject: TObject): TStrings; overload; Procedure AddText(Const S : String); virtual; procedure Assign(Source: TPersistent); override; procedure BeginUpdate; procedure Clear; virtual; abstract; procedure Delete(Index: Integer); virtual; abstract; procedure EndUpdate; function Equals(Obj: TObject): Boolean; override; overload; function Equals(TheStrings: TStrings): Boolean; overload; procedure Exchange(Index1, Index2: Integer); virtual; function GetEnumerator: TStringsEnumerator; function IndexOf(const S: string): Integer; virtual; function IndexOfName(const Name: string): Integer; virtual; function IndexOfObject(AObject: TObject): Integer; virtual; procedure Insert(Index: Integer; const S: string); virtual; abstract; procedure InsertObject(Index: Integer; const S: string; AObject: TObject); procedure Move(CurIndex, NewIndex: Integer); virtual; procedure GetNameValue(Index : Integer; Out AName,AValue : String); Procedure LoadFromURL(Const aURL : String; Async : Boolean = True; OnLoaded : TNotifyEventRef = Nil; OnError: TStringNotifyEventRef = Nil); virtual; // Delphi compatibility. Must be an URL Procedure LoadFromFile(Const aFileName : String; const OnLoaded : TProc = Nil; const AError: TProcString = Nil); function ExtractName(Const S:String):String; Property TextLineBreakStyle : TTextLineBreakStyle Read GetLBS Write SetLBS; property Delimiter: Char read GetDelimiter write SetDelimiter; property DelimitedText: string read GetDelimitedText write SetDelimitedText; property LineBreak : string Read GetLineBreak write SetLineBreak; Property StrictDelimiter : Boolean Read FStrictDelimiter Write FStrictDelimiter; property AlwaysQuote: Boolean read FAlwaysQuote write FAlwaysQuote; property QuoteChar: Char read GetQuoteChar write SetQuoteChar; Property NameValueSeparator : Char Read GetNameValueSeparator Write SetNameValueSeparator; property ValueFromIndex[Index: Integer]: string read GetValueFromIndex write SetValueFromIndex; property Capacity: Integer read GetCapacity write SetCapacity; property CommaText: string read GetCommaText write SetCommaText; property Count: Integer read GetCount; property Names[Index: Integer]: string read GetName; property Objects[Index: Integer]: TObject read GetObject write PutObject; property Values[const Name: string]: string read GetValue write SetValue; property Strings[Index: Integer]: string read Get write Put; default; property Text: string read GetTextStr write SetTextStr; Property SkipLastLineBreak : Boolean Read GetSkipLastLineBreak Write SetSkipLastLineBreak; end; { TStringList} TStringItem = record FString: string; FObject: TObject; end; TStringItemArray = Array of TStringItem; TStringList = class; TStringListSortCompare = function(List: TStringList; Index1, Index2: Integer): Integer; TStringsSortStyle = (sslNone,sslUser,sslAuto); TStringsSortStyles = Set of TStringsSortStyle; TStringList = class(TStrings) private FList: TStringItemArray; FCount: Integer; FOnChange: TNotifyEvent; FOnChanging: TNotifyEvent; FDuplicates: TDuplicates; FCaseSensitive : Boolean; FForceSort : Boolean; FOwnsObjects : Boolean; FSortStyle: TStringsSortStyle; procedure ExchangeItemsInt(Index1, Index2: Integer); function GetSorted: Boolean; procedure Grow; procedure InternalClear(FromIndex : Integer = 0; ClearOnly : Boolean = False); procedure QuickSort(L, R: Integer; CompareFn: TStringListSortCompare); procedure SetSorted(Value: Boolean); procedure SetCaseSensitive(b : boolean); procedure SetSortStyle(AValue: TStringsSortStyle); protected Procedure CheckIndex(AIndex : Integer); procedure ExchangeItems(Index1, Index2: Integer); virtual; procedure Changed; virtual; procedure Changing; virtual; function Get(Index: Integer): string; override; function GetCapacity: Integer; override; function GetCount: Integer; override; function GetObject(Index: Integer): TObject; override; procedure Put(Index: Integer; const S: string); override; procedure PutObject(Index: Integer; AObject: TObject); override; procedure SetCapacity(NewCapacity: Integer); override; procedure SetUpdateState(Updating: Boolean); override; procedure InsertItem(Index: Integer; const S: string); virtual; procedure InsertItem(Index: Integer; const S: string; O: TObject); virtual; Function DoCompareText(const s1,s2 : string) : PtrInt; override; function CompareStrings(const s1,s2 : string) : Integer; virtual; public destructor Destroy; override; function Add(const S: string): Integer; override; procedure Clear; override; procedure Delete(Index: Integer); override; procedure Exchange(Index1, Index2: Integer); override; function Find(const S: string; Out Index: Integer): Boolean; virtual; function IndexOf(const S: string): Integer; override; procedure Insert(Index: Integer; const S: string); override; procedure Sort; virtual; procedure CustomSort(CompareFn: TStringListSortCompare); virtual; property Duplicates: TDuplicates read FDuplicates write FDuplicates; property Sorted: Boolean read GetSorted write SetSorted; property CaseSensitive: Boolean read FCaseSensitive write SetCaseSensitive; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChanging: TNotifyEvent read FOnChanging write FOnChanging; property OwnsObjects : boolean read FOwnsObjects write FOwnsObjects; Property SortStyle : TStringsSortStyle Read FSortStyle Write SetSortStyle; end; TCollection = class; { TCollectionItem } TCollectionItem = class(TPersistent) private FCollection: TCollection; FID: Integer; FUpdateCount: Integer; function GetIndex: Integer; protected procedure SetCollection(Value: TCollection);virtual; procedure Changed(AllItems: Boolean); function GetOwner: TPersistent; override; function GetDisplayName: string; virtual; procedure SetIndex(Value: Integer); virtual; procedure SetDisplayName(const Value: string); virtual; property UpdateCount: Integer read FUpdateCount; public constructor Create(ACollection: TCollection); virtual; reintroduce; destructor Destroy; override; function GetNamePath: string; override; property Collection: TCollection read FCollection write SetCollection; property ID: Integer read FID; property Index: Integer read GetIndex write SetIndex; property DisplayName: string read GetDisplayName write SetDisplayName; end; TCollectionEnumerator = class private FCollection: TCollection; FPosition: Integer; public constructor Create(ACollection: TCollection); reintroduce; function GetCurrent: TCollectionItem; function MoveNext: Boolean; property Current: TCollectionItem read GetCurrent; end; TCollectionItemClass = class of TCollectionItem; TCollectionNotification = (cnAdded, cnExtracting, cnDeleting); TCollectionSortCompare = function (Item1, Item2: TCollectionItem): Integer; TCollectionSortCompareFunc = reference to function (Item1, Item2: TCollectionItem): Integer; TCollection = class(TPersistent) private FItemClass: TCollectionItemClass; FItems: TFpList; FUpdateCount: Integer; FNextID: Integer; FPropName: string; function GetCount: Integer; function GetPropName: string; procedure InsertItem(Item: TCollectionItem); procedure RemoveItem(Item: TCollectionItem); procedure DoClear; protected { Design-time editor support } function GetAttrCount: Integer; virtual; function GetAttr(Index: Integer): string; virtual; function GetItemAttr(Index, ItemIndex: Integer): string; virtual; procedure Changed; function GetItem(Index: Integer): TCollectionItem; procedure SetItem(Index: Integer; Value: TCollectionItem); procedure SetItemName(Item: TCollectionItem); virtual; procedure SetPropName; virtual; procedure Update(Item: TCollectionItem); virtual; procedure Notify(Item: TCollectionItem;Action: TCollectionNotification); virtual; property PropName: string read GetPropName write FPropName; property UpdateCount: Integer read FUpdateCount; public constructor Create(AItemClass: TCollectionItemClass); reintroduce; destructor Destroy; override; function Owner: TPersistent; function Add: TCollectionItem; procedure Assign(Source: TPersistent); override; procedure BeginUpdate; virtual; procedure Clear; procedure EndUpdate; virtual; procedure Delete(Index: Integer); function GetEnumerator: TCollectionEnumerator; function GetNamePath: string; override; function Insert(Index: Integer): TCollectionItem; function FindItemID(ID: Integer): TCollectionItem; procedure Exchange(Const Index1, index2: integer); procedure Sort(Const Compare : TCollectionSortCompare); procedure SortList(Const Compare : TCollectionSortCompareFunc); property Count: Integer read GetCount; property ItemClass: TCollectionItemClass read FItemClass; property Items[Index: Integer]: TCollectionItem read GetItem write SetItem; end; TOwnedCollection = class(TCollection) private FOwner: TPersistent; protected Function GetOwner: TPersistent; override; public Constructor Create(AOwner: TPersistent; AItemClass: TCollectionItemClass); reintroduce; end; TComponent = Class; TOperation = (opInsert, opRemove); TComponentStateItem = ( csLoading, csReading, csWriting, csDestroying, csDesigning, csAncestor, csUpdating, csFixups, csFreeNotification, csInline, csDesignInstance); TComponentState = set of TComponentStateItem; TComponentStyleItem = (csInheritable, csCheckPropAvail, csSubComponent, csTransient); TComponentStyle = set of TComponentStyleItem; TGetChildProc = procedure (Child: TComponent) of object; TComponentName = string; { TComponentEnumerator } TComponentEnumerator = class private FComponent: TComponent; FPosition: Integer; public constructor Create(AComponent: TComponent); reintroduce; function GetCurrent: TComponent; function MoveNext: Boolean; property Current: TComponent read GetCurrent; end; HRESULT=integer; TSeekOrigin = (soBeginning, soCurrent, soEnd); { TStream } TStream = class(TObject) private FEndian: TEndian; function MakeInt(B: TBytes; aSize: Integer; Signed: Boolean): NativeInt; function MakeBytes(B: NativeInt; aSize: Integer; Signed: Boolean): TBytes; protected procedure InvalidSeek; virtual; procedure Discard(const Count: NativeInt); procedure DiscardLarge(Count: NativeInt; const MaxBufferSize: Longint); procedure FakeSeekForward(Offset: NativeInt; const Origin: TSeekOrigin; const Pos: NativeInt); function GetPosition: NativeInt; virtual; procedure SetPosition(const Pos: NativeInt); virtual; function GetSize: NativeInt; virtual; procedure SetSize(const NewSize: NativeInt); virtual; procedure SetSize64(const NewSize: NativeInt); virtual; procedure ReadNotImplemented; procedure WriteNotImplemented; function ReadMaxSizeData(Buffer : TBytes; aSize,aCount : NativeInt) : NativeInt; Procedure ReadExactSizeData(Buffer : TBytes; aSize,aCount : NativeInt); function WriteMaxSizeData(Const Buffer : TBytes; aSize,aCount : NativeInt) : NativeInt; Procedure WriteExactSizeData(Const Buffer : TBytes; aSize,aCount : NativeInt); public function Read(var Buffer: TBytes; Count: Longint): Longint; overload; function Read(Buffer : TBytes; aOffset, Count: Longint): Longint; virtual; abstract; overload; function Write(const Buffer: TBytes; Count: Longint): Longint; virtual; overload; function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; virtual; abstract; overload; function Seek(const Offset: NativeInt; Origin: TSeekOrigin): NativeInt; virtual; abstract; overload; function ReadData(Buffer: TBytes; Count: NativeInt): NativeInt; overload; function ReadData(var Buffer: Boolean): NativeInt; overload; function ReadData(var Buffer: Boolean; Count: NativeInt): NativeInt; overload; function ReadData(var Buffer: WideChar): NativeInt; overload; function ReadData(var Buffer: WideChar; Count: NativeInt): NativeInt; overload; // NativeLargeint. Stored as a float64, Read as float64. function ReadData(var Buffer: NativeLargeInt): NativeInt; overload; function ReadData(var Buffer: NativeLargeInt; Count: NativeInt): NativeInt; overload; function ReadData(var Buffer: NativeLargeUInt): NativeInt; overload; function ReadData(var Buffer: NativeLargeUInt; Count: NativeInt): NativeInt; overload; function ReadData(var Buffer: Double): NativeInt; overload; function ReadData(var Buffer: Double; Count: NativeInt): NativeInt; overload; procedure ReadBuffer(var Buffer: TBytes; Count: NativeInt); overload; procedure ReadBuffer(var Buffer: TBytes; Offset, Count: NativeInt); overload; procedure ReadBufferData(var Buffer: Boolean); overload; procedure ReadBufferData(var Buffer: Boolean; Count: NativeInt); overload; procedure ReadBufferData(var Buffer: WideChar); overload; procedure ReadBufferData(var Buffer: WideChar; Count: NativeInt); overload; // NativeLargeint. Stored as a float64, Read as float64. procedure ReadBufferData(var Buffer: NativeLargeInt); overload; procedure ReadBufferData(var Buffer: NativeLargeInt; Count: NativeInt); overload; procedure ReadBufferData(var Buffer: NativeLargeUInt); overload; procedure ReadBufferData(var Buffer: NativeLargeUInt; Count: NativeInt); overload; procedure ReadBufferData(var Buffer: Double); overload; procedure ReadBufferData(var Buffer: Double; Count: NativeInt); overload; procedure WriteBuffer(const Buffer: TBytes; Count: NativeInt); overload; procedure WriteBuffer(const Buffer: TBytes; Offset, Count: NativeInt); overload; function WriteData(const Buffer: TBytes; Count: NativeInt): NativeInt; overload; function WriteData(const Buffer: Boolean): NativeInt; overload; function WriteData(const Buffer: Boolean; Count: NativeInt): NativeInt; overload; function WriteData(const Buffer: WideChar): NativeInt; overload; function WriteData(const Buffer: WideChar; Count: NativeInt): NativeInt; overload; // NativeLargeint. Stored as a float64, Read as float64. function WriteData(const Buffer: NativeLargeInt): NativeInt; overload; function WriteData(const Buffer: NativeLargeInt; Count: NativeInt): NativeInt; overload; function WriteData(const Buffer: NativeLargeUInt): NativeInt; overload; function WriteData(const Buffer: NativeLargeUInt; Count: NativeInt): NativeInt; overload; function WriteData(const Buffer: Double): NativeInt; overload; function WriteData(const Buffer: Double; Count: NativeInt): NativeInt; overload; {$IFDEF FPC_HAS_TYPE_EXTENDED} function WriteData(const Buffer: Extended): NativeInt; overload; function WriteData(const Buffer: Extended; Count: NativeInt): NativeInt; overload; function WriteData(const Buffer: TExtended80Rec): NativeInt; overload; function WriteData(const Buffer: TExtended80Rec; Count: NativeInt): NativeInt; overload; {$ENDIF} procedure WriteBufferData(Buffer: Boolean); overload; procedure WriteBufferData(Buffer: Boolean; Count: NativeInt); overload; procedure WriteBufferData(Buffer: WideChar); overload; procedure WriteBufferData(Buffer: WideChar; Count: NativeInt); overload; // NativeLargeint. Stored as a float64, Read as float64. procedure WriteBufferData(Buffer: NativeLargeInt); overload; procedure WriteBufferData(Buffer: NativeLargeInt; Count: NativeInt); overload; procedure WriteBufferData(Buffer: NativeLargeUInt); overload; procedure WriteBufferData(Buffer: NativeLargeUInt; Count: NativeInt); overload; procedure WriteBufferData(Buffer: Double); overload; procedure WriteBufferData(Buffer: Double; Count: NativeInt); overload; function CopyFrom(Source: TStream; Count: NativeInt): NativeInt; function ReadComponent(Instance: TComponent): TComponent; function ReadComponentRes(Instance: TComponent): TComponent; procedure WriteComponent(Instance: TComponent); procedure WriteComponentRes(const ResName: string; Instance: TComponent); procedure WriteDescendent(Instance, Ancestor: TComponent); procedure WriteDescendentRes(const ResName: string; Instance, Ancestor: TComponent); procedure WriteResourceHeader(const ResName: string; {!!!:out} var FixupInfo: Longint); procedure FixupResourceHeader(FixupInfo: Longint); procedure ReadResHeader; function ReadByte : Byte; function ReadWord : Word; function ReadDWord : Cardinal; function ReadQWord : NativeLargeUInt; procedure WriteByte(b : Byte); procedure WriteWord(w : Word); procedure WriteDWord(d : Cardinal); procedure WriteQWord(q : NativeLargeUInt); property Position: NativeInt read GetPosition write SetPosition; property Size: NativeInt read GetSize write SetSize64; Property Endian: TEndian Read FEndian Write FEndian; end; { TCustomMemoryStream abstract class } TCustomMemoryStream = class(TStream) private FMemory: TJSArrayBuffer; FDataView : TJSDataView; FDataArray : TJSUint8Array; FSize, FPosition: PtrInt; FSizeBoundsSeek : Boolean; function GetDataArray: TJSUint8Array; function GetDataView: TJSDataview; protected Function GetSize : NativeInt; Override; function GetPosition: NativeInt; Override; procedure SetPointer(Ptr: TJSArrayBuffer; ASize: PtrInt); Property DataView : TJSDataview Read GetDataView; Property DataArray : TJSUint8Array Read GetDataArray; public Class Function MemoryToBytes(Mem : TJSArrayBuffer) : TBytes; overload; Class Function MemoryToBytes(Mem : TJSUint8Array) : TBytes; overload; Class Function BytesToMemory(aBytes : TBytes) : TJSArrayBuffer; function Read(Buffer : TBytes; Offset, Count: LongInt): LongInt; override; function Seek(const Offset: NativeInt; Origin: TSeekOrigin): NativeInt; override; procedure SaveToStream(Stream: TStream); Procedure LoadFromURL(Const aURL : String; Async : Boolean = True; OnLoaded : TNotifyEventRef = Nil; OnError: TStringNotifyEventRef = Nil); virtual; // Delphi compatibility. Must be an URL Procedure LoadFromFile(Const aFileName : String; const OnLoaded : TProc = Nil; const AError: TProcString = Nil); property Memory: TJSArrayBuffer read FMemory; Property SizeBoundsSeek : Boolean Read FSizeBoundsSeek Write FSizeBoundsSeek; end; { TMemoryStream } TMemoryStream = class(TCustomMemoryStream) private FCapacity: PtrInt; procedure SetCapacity(NewCapacity: PtrInt); protected function Realloc(var NewCapacity: PtrInt): TJSArrayBuffer; virtual; property Capacity: PtrInt read FCapacity write SetCapacity; public destructor Destroy; override; procedure Clear; procedure LoadFromStream(Stream: TStream); procedure SetSize(const NewSize: NativeInt); override; function Write(const Buffer: TBytes; Offset, Count: LongInt): LongInt; override; end; { TBytesStream } TBytesStream = class(TMemoryStream) private function GetBytes: TBytes; public constructor Create(const ABytes: TBytes); virtual; overload; property Bytes: TBytes read GetBytes; end; { TStringStream } TStringStream = class(TMemoryStream) private function GetDataString : String; public constructor Create(const aString: String); virtual; overload; property DataString: String read GetDataString; end; TFilerFlag = (ffInherited, ffChildPos, ffInline); TFilerFlags = set of TFilerFlag; TReaderProc = procedure(Reader: TReader) of object; TWriterProc = procedure(Writer: TWriter) of object; TStreamProc = procedure(Stream: TStream) of object; TFiler = class(TObject) private FRoot: TComponent; FLookupRoot: TComponent; FAncestor: TPersistent; FIgnoreChildren: Boolean; protected procedure SetRoot(ARoot: TComponent); virtual; public procedure DefineProperty(const Name: string; ReadData: TReaderProc; WriteData: TWriterProc; HasData: Boolean); virtual; abstract; procedure DefineBinaryProperty(const Name: string; ReadData, WriteData: TStreamProc; HasData: Boolean); virtual; abstract; Procedure FlushBuffer; virtual; abstract; property Root: TComponent read FRoot write SetRoot; property LookupRoot: TComponent read FLookupRoot; property Ancestor: TPersistent read FAncestor write FAncestor; property IgnoreChildren: Boolean read FIgnoreChildren write FIgnoreChildren; end; TValueType = ( vaNull, vaList, vaInt8, vaInt16, vaInt32, vaDouble, vaString, vaIdent, vaFalse, vaTrue, vaBinary, vaSet, vaNil, vaCollection, vaCurrency, vaDate, vaNativeInt ); { TAbstractObjectReader } TAbstractObjectReader = class public Procedure FlushBuffer; virtual; function NextValue: TValueType; virtual; abstract; function ReadValue: TValueType; virtual; abstract; procedure BeginRootComponent; virtual; abstract; procedure BeginComponent(var Flags: TFilerFlags; var AChildPos: Integer; var CompClassName, CompName: String); virtual; abstract; function BeginProperty: String; virtual; abstract; //Please don't use read, better use ReadBinary whenever possible procedure Read(var Buffer : TBytes; Count: Longint); virtual;abstract; { All ReadXXX methods are called _after_ the value type has been read! } procedure ReadBinary(const DestData: TMemoryStream); virtual; abstract; function ReadFloat: Extended; virtual; abstract; function ReadCurrency: Currency; virtual; abstract; function ReadIdent(ValueType: TValueType): String; virtual; abstract; function ReadInt8: ShortInt; virtual; abstract; function ReadInt16: SmallInt; virtual; abstract; function ReadInt32: LongInt; virtual; abstract; function ReadNativeInt: NativeInt; virtual; abstract; function ReadSet(EnumType: TTypeInfoEnum): Integer; virtual; abstract; procedure ReadSignature; virtual; abstract; function ReadStr: String; virtual; abstract; function ReadString(StringType: TValueType): String; virtual; abstract; function ReadWideString: WideString;virtual;abstract; function ReadUnicodeString: UnicodeString;virtual;abstract; procedure SkipComponent(SkipComponentInfos: Boolean); virtual; abstract; procedure SkipValue; virtual; abstract; end; { TBinaryObjectReader } TBinaryObjectReader = class(TAbstractObjectReader) protected FStream: TStream; function ReadWord : word; function ReadDWord : longword; procedure SkipProperty; procedure SkipSetBody; public constructor Create(Stream: TStream); function NextValue: TValueType; override; function ReadValue: TValueType; override; procedure BeginRootComponent; override; procedure BeginComponent(var Flags: TFilerFlags; var AChildPos: Integer; var CompClassName, CompName: String); override; function BeginProperty: String; override; //Please don't use read, better use ReadBinary whenever possible procedure Read(var Buffer : TBytes; Count: Longint); override; procedure ReadBinary(const DestData: TMemoryStream); override; function ReadFloat: Extended; override; function ReadCurrency: Currency; override; function ReadIdent(ValueType: TValueType): String; override; function ReadInt8: ShortInt; override; function ReadInt16: SmallInt; override; function ReadInt32: LongInt; override; function ReadNativeInt: NativeInt; override; function ReadSet(EnumType: TTypeInfoEnum): Integer; override; procedure ReadSignature; override; function ReadStr: String; override; function ReadString(StringType: TValueType): String; override; function ReadWideString: WideString;override; function ReadUnicodeString: UnicodeString;override; procedure SkipComponent(SkipComponentInfos: Boolean); override; procedure SkipValue; override; end; CodePointer = Pointer; TFindMethodEvent = procedure(Reader: TReader; const MethodName: string; var Address: CodePointer; var Error: Boolean) of object; TSetNameEvent = procedure(Reader: TReader; Component: TComponent; var Name: string) of object; TReferenceNameEvent = procedure(Reader: TReader; var Name: string) of object; TAncestorNotFoundEvent = procedure(Reader: TReader; const ComponentName: string; ComponentClass: TPersistentClass; var Component: TComponent) of object; TReadComponentsProc = procedure(Component: TComponent) of object; TReaderError = procedure(Reader: TReader; const Message: string; var Handled: Boolean) of object; TPropertyNotFoundEvent = procedure(Reader: TReader; Instance: TPersistent; var PropName: string; IsPath: boolean; var Handled, Skip: Boolean) of object; TFindComponentClassEvent = procedure(Reader: TReader; const ClassName: string; var ComponentClass: TComponentClass) of object; TCreateComponentEvent = procedure(Reader: TReader; ComponentClass: TComponentClass; var Component: TComponent) of object; TSetMethodPropertyEvent = procedure(Reader: TReader; Instance: TPersistent; PropInfo: TTypeMemberProperty; const TheMethodName: string; var Handled: boolean) of object; TReadWriteStringPropertyEvent = procedure(Sender:TObject; const Instance: TPersistent; PropInfo: TTypeMemberProperty; var Content:string) of object; { TReader } TReader = class(TFiler) private FDriver: TAbstractObjectReader; FOwner: TComponent; FParent: TComponent; FFixups: TObject; FLoaded: TFpList; FOnFindMethod: TFindMethodEvent; FOnSetMethodProperty: TSetMethodPropertyEvent; FOnSetName: TSetNameEvent; FOnReferenceName: TReferenceNameEvent; FOnAncestorNotFound: TAncestorNotFoundEvent; FOnError: TReaderError; FOnPropertyNotFound: TPropertyNotFoundEvent; FOnFindComponentClass: TFindComponentClassEvent; FOnCreateComponent: TCreateComponentEvent; FPropName: string; FCanHandleExcepts: Boolean; FOnReadStringProperty:TReadWriteStringPropertyEvent; procedure DoFixupReferences; function FindComponentClass(const AClassName: string): TComponentClass; protected function Error(const Message: string): Boolean; virtual; function FindMethod(ARoot: TComponent; const AMethodName: string): CodePointer; virtual; procedure ReadProperty(AInstance: TPersistent); procedure ReadPropValue(Instance: TPersistent; PropInfo: TTypeMemberProperty); procedure PropertyError; procedure ReadData(Instance: TComponent); property PropName: string read FPropName; property CanHandleExceptions: Boolean read FCanHandleExcepts; function CreateDriver(Stream: TStream): TAbstractObjectReader; virtual; public constructor Create(Stream: TStream); destructor Destroy; override; Procedure FlushBuffer; override; procedure BeginReferences; procedure CheckValue(Value: TValueType); procedure DefineProperty(const Name: string; AReadData: TReaderProc; WriteData: TWriterProc; HasData: Boolean); override; procedure DefineBinaryProperty(const Name: string; AReadData, WriteData: TStreamProc; HasData: Boolean); override; function EndOfList: Boolean; procedure EndReferences; procedure FixupReferences; function NextValue: TValueType; //Please don't use read, better use ReadBinary whenever possible //uuups, ReadBinary is protected .. procedure Read(var Buffer : TBytes; Count: LongInt); virtual; function ReadBoolean: Boolean; function ReadChar: Char; function ReadWideChar: WideChar; function ReadUnicodeChar: UnicodeChar; procedure ReadCollection(Collection: TCollection); function ReadComponent(Component: TComponent): TComponent; procedure ReadComponents(AOwner, AParent: TComponent; Proc: TReadComponentsProc); function ReadFloat: Extended; function ReadCurrency: Currency; function ReadIdent: string; function ReadInteger: Longint; function ReadNativeInt: NativeInt; function ReadSet(EnumType: Pointer): Integer; procedure ReadListBegin; procedure ReadListEnd; function ReadRootComponent(ARoot: TComponent): TComponent; function ReadVariant: JSValue; procedure ReadSignature; function ReadString: string; function ReadWideString: WideString; function ReadUnicodeString: UnicodeString; function ReadValue: TValueType; procedure CopyValue(Writer: TWriter); property Driver: TAbstractObjectReader read FDriver; property Owner: TComponent read FOwner write FOwner; property Parent: TComponent read FParent write FParent; property OnError: TReaderError read FOnError write FOnError; property OnPropertyNotFound: TPropertyNotFoundEvent read FOnPropertyNotFound write FOnPropertyNotFound; property OnFindMethod: TFindMethodEvent read FOnFindMethod write FOnFindMethod; property OnSetMethodProperty: TSetMethodPropertyEvent read FOnSetMethodProperty write FOnSetMethodProperty; property OnSetName: TSetNameEvent read FOnSetName write FOnSetName; property OnReferenceName: TReferenceNameEvent read FOnReferenceName write FOnReferenceName; property OnAncestorNotFound: TAncestorNotFoundEvent read FOnAncestorNotFound write FOnAncestorNotFound; property OnCreateComponent: TCreateComponentEvent read FOnCreateComponent write FOnCreateComponent; property OnFindComponentClass: TFindComponentClassEvent read FOnFindComponentClass write FOnFindComponentClass; property OnReadStringProperty: TReadWriteStringPropertyEvent read FOnReadStringProperty write FOnReadStringProperty; end; { TAbstractObjectWriter } TAbstractObjectWriter = class public { Begin/End markers. Those ones who don't have an end indicator, use "EndList", after the occurrence named in the comment. Note that this only counts for "EndList" calls on the same level; each BeginXXX call increases the current level. } procedure BeginCollection; virtual; abstract; { Ends with the next "EndList" } procedure BeginComponent(Component: TComponent; Flags: TFilerFlags; ChildPos: Integer); virtual; abstract; { Ends after the second "EndList" } procedure WriteSignature; virtual; abstract; procedure BeginList; virtual; abstract; procedure EndList; virtual; abstract; procedure BeginProperty(const PropName: String); virtual; abstract; procedure EndProperty; virtual; abstract; //Please don't use write, better use WriteBinary whenever possible procedure Write(const Buffer : TBytes; Count: Longint); virtual;abstract; Procedure FlushBuffer; virtual; abstract; procedure WriteBinary(const Buffer : TBytes; Count: Longint); virtual; abstract; procedure WriteBoolean(Value: Boolean); virtual; abstract; // procedure WriteChar(Value: Char); procedure WriteFloat(const Value: Extended); virtual; abstract; procedure WriteCurrency(const Value: Currency); virtual; abstract; procedure WriteIdent(const Ident: string); virtual; abstract; procedure WriteInteger(Value: NativeInt); virtual; abstract; procedure WriteNativeInt(Value: NativeInt); virtual; abstract; procedure WriteVariant(const Value: JSValue); virtual; abstract; procedure WriteMethodName(const Name: String); virtual; abstract; procedure WriteSet(Value: LongInt; SetType: Pointer); virtual; abstract; procedure WriteString(const Value: String); virtual; abstract; procedure WriteWideString(const Value: WideString);virtual;abstract; procedure WriteUnicodeString(const Value: UnicodeString);virtual;abstract; end; { TBinaryObjectWriter } TBinaryObjectWriter = class(TAbstractObjectWriter) protected FStream: TStream; FBuffer: Pointer; FBufSize: Integer; FBufPos: Integer; FBufEnd: Integer; procedure WriteWord(w : word); procedure WriteDWord(lw : longword); procedure WriteValue(Value: TValueType); public constructor Create(Stream: TStream); procedure WriteSignature; override; procedure BeginCollection; override; procedure BeginComponent(Component: TComponent; Flags: TFilerFlags; ChildPos: Integer); override; procedure BeginList; override; procedure EndList; override; procedure BeginProperty(const PropName: String); override; procedure EndProperty; override; Procedure FlushBuffer; override; //Please don't use write, better use WriteBinary whenever possible procedure Write(const Buffer : TBytes; Count: Longint); override; procedure WriteBinary(const Buffer : TBytes; Count: LongInt); override; procedure WriteBoolean(Value: Boolean); override; procedure WriteFloat(const Value: Extended); override; procedure WriteCurrency(const Value: Currency); override; procedure WriteIdent(const Ident: string); override; procedure WriteInteger(Value: NativeInt); override; procedure WriteNativeInt(Value: NativeInt); override; procedure WriteMethodName(const Name: String); override; procedure WriteSet(Value: LongInt; SetType: Pointer); override; procedure WriteStr(const Value: String); procedure WriteString(const Value: String); override; procedure WriteWideString(const Value: WideString); override; procedure WriteUnicodeString(const Value: UnicodeString); override; procedure WriteVariant(const VarValue: JSValue);override; end; TFindAncestorEvent = procedure (Writer: TWriter; Component: TComponent; const Name: string; var Ancestor, RootAncestor: TComponent) of object; TWriteMethodPropertyEvent = procedure (Writer: TWriter; Instance: TPersistent; PropInfo: TTypeMemberProperty; const MethodValue, DefMethodValue: TMethod; var Handled: boolean) of object; { TWriter } TWriter = class(TFiler) private FDriver: TAbstractObjectWriter; FDestroyDriver: Boolean; FRootAncestor: TComponent; FPropPath: String; FAncestors: TStringList; FAncestorPos: Integer; FCurrentPos: Integer; FOnFindAncestor: TFindAncestorEvent; FOnWriteMethodProperty: TWriteMethodPropertyEvent; FOnWriteStringProperty:TReadWriteStringPropertyEvent; procedure AddToAncestorList(Component: TComponent); procedure WriteComponentData(Instance: TComponent); Procedure DetermineAncestor(Component: TComponent); procedure DoFindAncestor(Component : TComponent); protected procedure SetRoot(ARoot: TComponent); override; procedure WriteBinary(AWriteData: TStreamProc); procedure WriteProperty(Instance: TPersistent; PropInfo: TTypeMemberProperty); procedure WriteProperties(Instance: TPersistent); procedure WriteChildren(Component: TComponent); function CreateDriver(Stream: TStream): TAbstractObjectWriter; virtual; public constructor Create(ADriver: TAbstractObjectWriter); constructor Create(Stream: TStream); destructor Destroy; override; procedure DefineProperty(const Name: string; ReadData: TReaderProc; AWriteData: TWriterProc; HasData: Boolean); override; procedure DefineBinaryProperty(const Name: string; ReadData, AWriteData: TStreamProc; HasData: Boolean); override; Procedure FlushBuffer; override; procedure Write(const Buffer : TBytes; Count: Longint); virtual; procedure WriteBoolean(Value: Boolean); procedure WriteCollection(Value: TCollection); procedure WriteComponent(Component: TComponent); procedure WriteChar(Value: Char); procedure WriteWideChar(Value: WideChar); procedure WriteDescendent(ARoot: TComponent; AAncestor: TComponent); procedure WriteFloat(const Value: Extended); procedure WriteCurrency(const Value: Currency); procedure WriteIdent(const Ident: string); procedure WriteInteger(Value: Longint); overload; procedure WriteInteger(Value: NativeInt); overload; procedure WriteSet(Value: LongInt; SetType: Pointer); procedure WriteListBegin; procedure WriteListEnd; Procedure WriteSignature; procedure WriteRootComponent(ARoot: TComponent); procedure WriteString(const Value: string); procedure WriteWideString(const Value: WideString); procedure WriteUnicodeString(const Value: UnicodeString); procedure WriteVariant(const VarValue: JSValue); property RootAncestor: TComponent read FRootAncestor write FRootAncestor; property OnFindAncestor: TFindAncestorEvent read FOnFindAncestor write FOnFindAncestor; property OnWriteMethodProperty: TWriteMethodPropertyEvent read FOnWriteMethodProperty write FOnWriteMethodProperty; property OnWriteStringProperty: TReadWriteStringPropertyEvent read FOnWriteStringProperty write FOnWriteStringProperty; property Driver: TAbstractObjectWriter read FDriver; property PropertyPath: string read FPropPath; end; TParserToken = (toUnknown, // everything else toEOF, // EOF toSymbol, // Symbol (identifier) toString, // ''string'' toInteger, // 123 toFloat, // 12.3 toMinus, // - toSetStart, // [ toListStart, // ( toCollectionStart, // < toBinaryStart, // { toSetEnd, // ] toListEnd, // ) toCollectionEnd, // > toBinaryEnd, // } toComma, // , toDot, // . toEqual, // = toColon // : ); TParser = class(TObject) private fStream : TStream; fBuf : Array of Char; FBufLen : integer; fPos : integer; fDeltaPos : integer; fFloatType : char; fSourceLine : integer; fToken : TParserToken; fEofReached : boolean; fLastTokenStr : string; function GetTokenName(aTok : TParserToken) : string; procedure LoadBuffer; procedure CheckLoadBuffer; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} procedure ProcessChar; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} function IsNumber : boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} function IsHexNum : boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} function IsAlpha : boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} function IsAlphaNum : boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} function GetHexValue(c : char) : byte; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} function GetAlphaNum : string; procedure HandleNewLine; procedure SkipBOM; procedure SkipSpaces; procedure SkipWhitespace; procedure HandleEof; procedure HandleAlphaNum; procedure HandleNumber; procedure HandleHexNumber; function HandleQuotedString : string; Function HandleDecimalCharacter: char; procedure HandleString; procedure HandleMinus; procedure HandleUnknown; public // Input stream is expected to be UTF16 ! constructor Create(Stream: TStream); destructor Destroy; override; procedure CheckToken(T: TParserToken); procedure CheckTokenSymbol(const S: string); procedure Error(const Ident: string); procedure ErrorFmt(const Ident: string; const Args: array of JSValue); procedure ErrorStr(const Message: string); procedure HexToBinary(Stream: TStream); function NextToken: TParserToken; function SourcePos: Longint; function TokenComponentIdent: string; function TokenFloat: Double; function TokenInt: NativeInt; function TokenString: string; function TokenSymbolIs(const S: string): Boolean; property FloatType: Char read fFloatType; property SourceLine: Integer read fSourceLine; property Token: TParserToken read fToken; end; { TObjectStreamConverter } TObjectTextEncoding = (oteDFM,oteLFM); TObjectStreamConverter = Class private FIndent: String; FInput : TStream; FOutput : TStream; FEncoding : TObjectTextEncoding; Private // Low level writing procedure OutLn(s: String); virtual; procedure OutStr(s: String); virtual; procedure OutString(s: String); virtual; // Low level reading function ReadWord: word; function ReadDWord: longword; function ReadDouble: Double; function ReadInt(ValueType: TValueType): NativeInt; function ReadInt: NativeInt; function ReadNativeInt: NativeInt; function ReadStr: String; function ReadString(StringType: TValueType): String; virtual; // High-level procedure ProcessBinary; virtual; procedure ProcessValue(ValueType: TValueType; Indent: String); virtual; procedure ReadObject(indent: String); virtual; procedure ReadPropList(indent: String); virtual; Public procedure ObjectBinaryToText(aInput, aOutput: TStream); procedure ObjectBinaryToText(aInput, aOutput: TStream; aEncoding: TObjectTextEncoding); Procedure Execute; Property Input : TStream Read FInput Write FInput; Property Output : TStream Read Foutput Write FOutput; Property Encoding : TObjectTextEncoding Read FEncoding Write FEncoding; Property Indent : String Read FIndent Write Findent; end; { TObjectTextConverter } TObjectTextConverter = Class private FParser: TParser; private FInput: TStream; Foutput: TStream; procedure WriteDouble(e: double); procedure WriteDWord(lw: longword); procedure WriteInteger(value: nativeInt); //procedure WriteLString(const s: String); procedure WriteQWord(q: nativeint); procedure WriteString(s: String); procedure WriteWord(w: word); procedure WriteWString(const s: WideString); procedure ProcessObject; virtual; procedure ProcessProperty; virtual; procedure ProcessValue; virtual; procedure ProcessWideString(const left: string); Property Parser : TParser Read FParser; Public // Input stream must be UTF16 ! procedure ObjectTextToBinary(aInput, aOutput: TStream); Procedure Execute; virtual; Property Input : TStream Read FInput Write FInput; Property Output: TStream Read Foutput Write Foutput; end; TLoadHelper = Class (TObject) Public Type TTextLoadedCallBack = reference to procedure (const aText : String); TBytesLoadedCallBack = reference to procedure (const aBuffer : TJSArrayBuffer); TErrorCallBack = reference to procedure (const aError : String); Class Procedure LoadText(aURL : String; aSync : Boolean; OnLoaded : TTextLoadedCallBack; OnError : TErrorCallBack); virtual; abstract; Class Procedure LoadBytes(aURL : String; aSync : Boolean; OnLoaded : TBytesLoadedCallBack; OnError : TErrorCallBack); virtual; abstract; end; TLoadHelperClass = Class of TLoadHelper; type TIdentMapEntry = record Value: Integer; Name: String; end; TIdentToInt = function(const Ident: string; var Int: Longint): Boolean; TIntToIdent = function(Int: Longint; var Ident: string): Boolean; TFindGlobalComponent = function(const Name: string): TComponent; TInitComponentHandler = function(Instance: TComponent; RootAncestor : TClass): boolean; procedure RegisterInitComponentHandler(ComponentClass: TComponentClass; Handler: TInitComponentHandler); Procedure RegisterClass(AClass : TPersistentClass); Procedure RegisterClasses(AClasses : specialize TArray<TPersistentClass>); Function GetClass(AClassName : string) : TPersistentClass; procedure RegisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent); procedure UnregisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent); function FindGlobalComponent(const Name: string): TComponent; Function FindNestedComponent(Root : TComponent; APath : String; CStyle : Boolean = True) : TComponent; procedure RedirectFixupReferences(Root: TComponent; const OldRootName, NewRootName: string); procedure RemoveFixupReferences(Root: TComponent; const RootName: string); procedure RegisterIntegerConsts(IntegerType: Pointer; IdentToIntFn: TIdentToInt; IntToIdentFn: TIntToIdent); function IdentToInt(const Ident: string; out Int: Longint; const Map: array of TIdentMapEntry): Boolean; function IntToIdent(Int: Longint; var Ident: string; const Map: array of TIdentMapEntry): Boolean; function FindIntToIdent(AIntegerType: Pointer): TIntToIdent; function FindIdentToInt(AIntegerType: Pointer): TIdentToInt; function FindClass(const AClassName: string): TPersistentClass; function CollectionsEqual(C1, C2: TCollection): Boolean; function CollectionsEqual(C1, C2: TCollection; Owner1, Owner2: TComponent): Boolean; procedure GetFixupReferenceNames(Root: TComponent; Names: TStrings); procedure GetFixupInstanceNames(Root: TComponent; const ReferenceRootName: string; Names: TStrings); procedure ObjectBinaryToText(aInput, aOutput: TStream); procedure ObjectBinaryToText(aInput, aOutput: TStream; aEncoding: TObjectTextEncoding); procedure ObjectTextToBinary(aInput, aOutput: TStream); Function SetLoadHelperClass(aClass : TLoadHelperClass) : TLoadHelperClass; Const // Some aliases vaSingle = vaDouble; vaExtended = vaDouble; vaLString = vaString; vaUTF8String = vaString; vaUString = vaString; vaWString = vaString; vaQWord = vaNativeInt; vaInt64 = vaNativeInt; toWString = toString; implementation uses simplelinkedlist; var GlobalLoaded, IntConstList: TFPList; GlobalLoadHelper : TLoadHelperClass; Function SetLoadHelperClass(aClass : TLoadHelperClass) : TLoadHelperClass; begin Result:=GlobalLoadHelper; GlobalLoadHelper:=aClass; end; Procedure CheckLoadHelper; begin If (GlobalLoadHelper=Nil) then Raise EInOutError.Create('No support for loading URLS. Include Rtl.BrowserLoadHelper in your project uses clause'); end; type TIntConst = class Private IntegerType: PTypeInfo; // The integer type RTTI pointer IdentToIntFn: TIdentToInt; // Identifier to Integer conversion IntToIdentFn: TIntToIdent; // Integer to Identifier conversion Public constructor Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt; AIntToIdent: TIntToIdent); end; { TStringStream } function TStringStream.GetDataString: String; var a : TJSUint16Array; begin Result:=''; // Silence warning a:=TJSUint16Array.New(Memory.slice(0,Size)); if a<>nil then asm // Result=String.fromCharCode.apply(null, new Uint16Array(a)); Result=String.fromCharCode.apply(null, a); end; end; constructor TStringStream.Create(const aString: String); Function StrToBuf(aLen : Integer) : TJSArrayBuffer; var I : Integer; begin Result:=TJSArrayBuffer.new(aLen*2);// 2 bytes for each char With TJSUint16Array.new(Result) do for i:=0 to aLen-1 do values[i] := TJSString(aString).charCodeAt(i); end; var Len : Integer; begin inherited Create; Len:=Length(aString); SetPointer(StrToBuf(len),Len*2); FCapacity:=Len*2; end; constructor TIntConst.Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt; AIntToIdent: TIntToIdent); begin IntegerType := AIntegerType; IdentToIntFn := AIdentToInt; IntToIdentFn := AIntToIdent; end; procedure RegisterIntegerConsts(IntegerType: Pointer; IdentToIntFn: TIdentToInt; IntToIdentFn: TIntToIdent); begin if Not Assigned(IntConstList) then IntConstList:=TFPList.Create; IntConstList.Add(TIntConst.Create(IntegerType, IdentToIntFn, IntToIdentFn)); end; function FindIntToIdent(AIntegerType: Pointer): TIntToIdent; var i: Integer; begin Result := nil; if Not Assigned(IntConstList) then exit; with IntConstList do for i := 0 to Count - 1 do if TIntConst(Items[i]).IntegerType = AIntegerType then exit(TIntConst(Items[i]).IntToIdentFn); end; function FindIdentToInt(AIntegerType: Pointer): TIdentToInt; var i: Integer; begin Result := nil; if Not Assigned(IntConstList) then exit; with IntConstList do for i := 0 to Count - 1 do with TIntConst(Items[I]) do if TIntConst(Items[I]).IntegerType = AIntegerType then exit(IdentToIntFn); end; function IdentToInt(const Ident: String; out Int: LongInt; const Map: array of TIdentMapEntry): Boolean; var i: Integer; begin for i := Low(Map) to High(Map) do if CompareText(Map[i].Name, Ident) = 0 then begin Int := Map[i].Value; exit(True); end; Result := False; end; function IntToIdent(Int: LongInt; var Ident: String; const Map: array of TIdentMapEntry): Boolean; var i: Integer; begin for i := Low(Map) to High(Map) do if Map[i].Value = Int then begin Ident := Map[i].Name; exit(True); end; Result := False; end; function GlobalIdentToInt(const Ident: String; var Int: LongInt):boolean; var i : Integer; begin Result := false; if Not Assigned(IntConstList) then exit; with IntConstList do for i := 0 to Count - 1 do if TIntConst(Items[I]).IdentToIntFn(Ident, Int) then Exit(True); end; function FindClass(const AClassName: string): TPersistentClass; begin Result := GetClass(AClassName); if not Assigned(Result) then raise EClassNotFound.CreateFmt(SClassNotFound, [AClassName]); end; function CollectionsEqual(C1, C2: TCollection): Boolean; Var Comp1,Comp2 : TComponent; begin Comp2:=Nil; Comp1:=TComponent.Create; try Result:=CollectionsEqual(C1,C2,Comp1,Comp2); finally Comp1.Free; Comp2.Free; end; end; function CollectionsEqual(C1, C2: TCollection; Owner1, Owner2: TComponent): Boolean; procedure stream_collection(s : tstream;c : tcollection;o : tcomponent); var w : twriter; begin w:=twriter.create(s); try w.root:=o; w.flookuproot:=o; w.writecollection(c); finally w.free; end; end; var s1,s2 : tbytesstream; b1,b2 : TBytes; I,Len : Integer; begin result:=false; if (c1.classtype<>c2.classtype) or (c1.count<>c2.count) then exit; if c1.count = 0 then begin result:= true; exit; end; s2:=Nil; s1:=tbytesstream.create; try s2:=tbytesstream.create; stream_collection(s1,c1,owner1); stream_collection(s2,c2,owner2); result:=(s1.size=s2.size); if Result then begin b1:=S1.Bytes; b2:=S2.Bytes; I:=0; Len:=S1.Size; // Not length of B While Result and (I<Len) do begin Result:=b1[I]=b2[i]; Inc(i); end; end; finally s2.free; s1.free; end; end; { TInterfacedPersistent } function TInterfacedPersistent._AddRef: Integer; begin Result:=-1; if Assigned(FOwnerInterface) then Result:=FOwnerInterface._AddRef; end; function TInterfacedPersistent._Release: Integer; begin Result:=-1; if Assigned(FOwnerInterface) then Result:=FOwnerInterface._Release; end; function TInterfacedPersistent.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin Result:=E_NOINTERFACE; if GetInterface(IID, Obj) then Result:=0; end; procedure TInterfacedPersistent.AfterConstruction; begin inherited AfterConstruction; if (GetOwner<>nil) then GetOwner.GetInterface(IInterface, FOwnerInterface); end; { TComponentEnumerator } constructor TComponentEnumerator.Create(AComponent: TComponent); begin inherited Create; FComponent := AComponent; FPosition := -1; end; function TComponentEnumerator.GetCurrent: TComponent; begin Result := FComponent.Components[FPosition]; end; function TComponentEnumerator.MoveNext: Boolean; begin Inc(FPosition); Result := FPosition < FComponent.ComponentCount; end; { TListEnumerator } constructor TListEnumerator.Create(AList: TList); begin inherited Create; FList := AList; FPosition := -1; end; function TListEnumerator.GetCurrent: JSValue; begin Result := FList[FPosition]; end; function TListEnumerator.MoveNext: Boolean; begin Inc(FPosition); Result := FPosition < FList.Count; end; { TFPListEnumerator } constructor TFPListEnumerator.Create(AList: TFPList); begin inherited Create; FList := AList; FPosition := -1; end; function TFPListEnumerator.GetCurrent: JSValue; begin Result := FList[FPosition]; end; function TFPListEnumerator.MoveNext: Boolean; begin Inc(FPosition); Result := FPosition < FList.Count; end; { TFPList } procedure TFPList.CopyMove(aList: TFPList); var r : integer; begin Clear; for r := 0 to aList.count-1 do Add(aList[r]); end; procedure TFPList.MergeMove(aList: TFPList); var r : integer; begin For r := 0 to aList.count-1 do if IndexOf(aList[r]) < 0 then Add(aList[r]); end; procedure TFPList.DoCopy(ListA, ListB: TFPList); begin if Assigned(ListB) then CopyMove(ListB) else CopyMove(ListA); end; procedure TFPList.DoSrcUnique(ListA, ListB: TFPList); var r : integer; begin if Assigned(ListB) then begin Clear; for r := 0 to ListA.Count-1 do if ListB.IndexOf(ListA[r]) < 0 then Add(ListA[r]); end else begin for r := Count-1 downto 0 do if ListA.IndexOf(Self[r]) >= 0 then Delete(r); end; end; procedure TFPList.DoAnd(ListA, ListB: TFPList); var r : integer; begin if Assigned(ListB) then begin Clear; for r := 0 to ListA.count-1 do if ListB.IndexOf(ListA[r]) >= 0 then Add(ListA[r]); end else begin for r := Count-1 downto 0 do if ListA.IndexOf(Self[r]) < 0 then Delete(r); end; end; procedure TFPList.DoDestUnique(ListA, ListB: TFPList); procedure MoveElements(Src, Dest: TFPList); var r : integer; begin Clear; for r := 0 to Src.count-1 do if Dest.IndexOf(Src[r]) < 0 then self.Add(Src[r]); end; var Dest : TFPList; begin if Assigned(ListB) then MoveElements(ListB, ListA) else Dest := TFPList.Create; try Dest.CopyMove(Self); MoveElements(ListA, Dest) finally Dest.Destroy; end; end; procedure TFPList.DoOr(ListA, ListB: TFPList); begin if Assigned(ListB) then begin CopyMove(ListA); MergeMove(ListB); end else MergeMove(ListA); end; procedure TFPList.DoXOr(ListA, ListB: TFPList); var r : integer; l : TFPList; begin if Assigned(ListB) then begin Clear; for r := 0 to ListA.Count-1 do if ListB.IndexOf(ListA[r]) < 0 then Add(ListA[r]); for r := 0 to ListB.Count-1 do if ListA.IndexOf(ListB[r]) < 0 then Add(ListB[r]); end else begin l := TFPList.Create; try l.CopyMove(Self); for r := Count-1 downto 0 do if listA.IndexOf(Self[r]) >= 0 then Delete(r); for r := 0 to ListA.Count-1 do if l.IndexOf(ListA[r]) < 0 then Add(ListA[r]); finally l.Destroy; end; end; end; function TFPList.Get(Index: Integer): JSValue; begin If (Index < 0) or (Index >= FCount) then RaiseIndexError(Index); Result:=FList[Index]; end; procedure TFPList.Put(Index: Integer; Item: JSValue); begin if (Index < 0) or (Index >= FCount) then RaiseIndexError(Index); FList[Index] := Item; end; procedure TFPList.SetCapacity(NewCapacity: Integer); begin If (NewCapacity < FCount) then Error (SListCapacityError, str(NewCapacity)); if NewCapacity = FCapacity then exit; SetLength(FList,NewCapacity); FCapacity := NewCapacity; end; procedure TFPList.SetCount(NewCount: Integer); begin if (NewCount < 0) then Error(SListCountError, str(NewCount)); If NewCount > FCount then begin If NewCount > FCapacity then SetCapacity(NewCount); end; FCount := NewCount; end; procedure TFPList.RaiseIndexError(Index: Integer); begin Error(SListIndexError, str(Index)); end; destructor TFPList.Destroy; begin Clear; inherited Destroy; end; procedure TFPList.AddList(AList: TFPList); Var I : Integer; begin If (Capacity<Count+AList.Count) then Capacity:=Count+AList.Count; For I:=0 to AList.Count-1 do Add(AList[i]); end; function TFPList.Add(Item: JSValue): Integer; begin if FCount = FCapacity then Expand; FList[FCount] := Item; Result := FCount; Inc(FCount); end; procedure TFPList.Clear; begin if Assigned(FList) then begin SetCount(0); SetCapacity(0); end; end; procedure TFPList.Delete(Index: Integer); begin If (Index<0) or (Index>=FCount) then Error (SListIndexError, str(Index)); FCount := FCount-1; System.Delete(FList,Index,1); Dec(FCapacity); end; class procedure TFPList.Error(const Msg: string; const Data: String); begin Raise EListError.CreateFmt(Msg,[Data]); end; procedure TFPList.Exchange(Index1, Index2: Integer); var Temp : JSValue; begin If (Index1 >= FCount) or (Index1 < 0) then Error(SListIndexError, str(Index1)); If (Index2 >= FCount) or (Index2 < 0) then Error(SListIndexError, str(Index2)); Temp := FList[Index1]; FList[Index1] := FList[Index2]; FList[Index2] := Temp; end; function TFPList.Expand: TFPList; var IncSize : Integer; begin if FCount < FCapacity then exit(self); IncSize := 4; if FCapacity > 3 then IncSize := IncSize + 4; if FCapacity > 8 then IncSize := IncSize+8; if FCapacity > 127 then Inc(IncSize, FCapacity shr 2); SetCapacity(FCapacity + IncSize); Result := Self; end; function TFPList.Extract(Item: JSValue): JSValue; var i : Integer; begin i := IndexOf(Item); if i >= 0 then begin Result := Item; Delete(i); end else Result := nil; end; function TFPList.First: JSValue; begin If FCount = 0 then Result := Nil else Result := Items[0]; end; function TFPList.GetEnumerator: TFPListEnumerator; begin Result:=TFPListEnumerator.Create(Self); end; function TFPList.IndexOf(Item: JSValue): Integer; Var C : Integer; begin Result:=0; C:=Count; while (Result<C) and (FList[Result]<>Item) do Inc(Result); If Result>=C then Result:=-1; end; function TFPList.IndexOfItem(Item: JSValue; Direction: TDirection): Integer; begin if Direction=fromBeginning then Result:=IndexOf(Item) else begin Result:=Count-1; while (Result >=0) and (Flist[Result]<>Item) do Result:=Result - 1; end; end; procedure TFPList.Insert(Index: Integer; Item: JSValue); begin if (Index < 0) or (Index > FCount )then Error(SlistIndexError, str(Index)); TJSArray(FList).splice(Index, 0, Item); inc(FCapacity); inc(FCount); end; function TFPList.Last: JSValue; begin If FCount = 0 then Result := nil else Result := Items[FCount - 1]; end; procedure TFPList.Move(CurIndex, NewIndex: Integer); var Temp: JSValue; begin if (CurIndex < 0) or (CurIndex > Count - 1) then Error(SListIndexError, str(CurIndex)); if (NewIndex < 0) or (NewIndex > Count -1) then Error(SlistIndexError, str(NewIndex)); if CurIndex=NewIndex then exit; Temp:=FList[CurIndex]; // ToDo: use TJSArray.copyWithin if available TJSArray(FList).splice(CurIndex,1); TJSArray(FList).splice(NewIndex,0,Temp); end; procedure TFPList.Assign(ListA: TFPList; AOperator: TListAssignOp; ListB: TFPList); begin case AOperator of laCopy : DoCopy (ListA, ListB); // replace dest with src laSrcUnique : DoSrcUnique (ListA, ListB); // replace dest with src that are not in dest laAnd : DoAnd (ListA, ListB); // remove from dest that are not in src laDestUnique: DoDestUnique (ListA, ListB);// remove from dest that are in src laOr : DoOr (ListA, ListB); // add to dest from src and not in dest laXOr : DoXOr (ListA, ListB); // add to dest from src and not in dest, remove from dest that are in src end; end; function TFPList.Remove(Item: JSValue): Integer; begin Result := IndexOf(Item); If Result <> -1 then Delete(Result); end; procedure TFPList.Pack; var Dst, i: Integer; V: JSValue; begin Dst:=0; for i:=0 to Count-1 do begin V:=FList[i]; if not Assigned(V) then continue; FList[Dst]:=V; inc(Dst); end; end; // Needed by Sort method. Procedure QuickSort(aList: TJSValueDynArray; L, R : Longint; const Compare: TListSortCompareFunc); var I, J : Longint; P, Q : JSValue; begin repeat I := L; J := R; P := aList[ (L + R) div 2 ]; repeat while Compare(P, aList[i]) > 0 do I := I + 1; while Compare(P, aList[J]) < 0 do J := J - 1; If I <= J then begin Q := aList[I]; aList[I] := aList[J]; aList[J] := Q; I := I + 1; J := J - 1; end; until I > J; // sort the smaller range recursively // sort the bigger range via the loop // Reasons: memory usage is O(log(n)) instead of O(n) and loop is faster than recursion if J - L < R - I then begin if L < J then QuickSort(aList, L, J, Compare); L := I; end else begin if I < R then QuickSort(aList, I, R, Compare); R := J; end; until L >= R; end; procedure TFPList.Sort(const Compare: TListSortCompare); begin if Not Assigned(FList) or (FCount < 2) then exit; QuickSort(Flist, 0, FCount-1, function(Item1, Item2: JSValue): Integer begin Result := Compare(Item1, Item2); end); end; procedure TFPList.SortList(const Compare: TListSortCompareFunc); begin if Not Assigned(FList) or (FCount < 2) then exit; QuickSort(Flist, 0, FCount-1, Compare); end; procedure TFPList.ForEachCall(const proc2call: TListCallback; const arg: JSValue ); var i : integer; v : JSValue; begin For I:=0 To Count-1 Do begin v:=FList[i]; if Assigned(v) then proc2call(v,arg); end; end; procedure TFPList.ForEachCall(const proc2call: TListStaticCallback; const arg: JSValue); var i : integer; v : JSValue; begin For I:=0 To Count-1 Do begin v:=FList[i]; if Assigned(v) then proc2call(v,arg); end; end; { TList } procedure TList.CopyMove(aList: TList); var r : integer; begin Clear; for r := 0 to aList.count-1 do Add(aList[r]); end; procedure TList.MergeMove(aList: TList); var r : integer; begin For r := 0 to aList.count-1 do if IndexOf(aList[r]) < 0 then Add(aList[r]); end; procedure TList.DoCopy(ListA, ListB: TList); begin if Assigned(ListB) then CopyMove(ListB) else CopyMove(ListA); end; procedure TList.DoSrcUnique(ListA, ListB: TList); var r : integer; begin if Assigned(ListB) then begin Clear; for r := 0 to ListA.Count-1 do if ListB.IndexOf(ListA[r]) < 0 then Add(ListA[r]); end else begin for r := Count-1 downto 0 do if ListA.IndexOf(Self[r]) >= 0 then Delete(r); end; end; procedure TList.DoAnd(ListA, ListB: TList); var r : integer; begin if Assigned(ListB) then begin Clear; for r := 0 to ListA.Count-1 do if ListB.IndexOf(ListA[r]) >= 0 then Add(ListA[r]); end else begin for r := Count-1 downto 0 do if ListA.IndexOf(Self[r]) < 0 then Delete(r); end; end; procedure TList.DoDestUnique(ListA, ListB: TList); procedure MoveElements(Src, Dest : TList); var r : integer; begin Clear; for r := 0 to Src.Count-1 do if Dest.IndexOf(Src[r]) < 0 then Add(Src[r]); end; var Dest : TList; begin if Assigned(ListB) then MoveElements(ListB, ListA) else try Dest := TList.Create; Dest.CopyMove(Self); MoveElements(ListA, Dest) finally Dest.Destroy; end; end; procedure TList.DoOr(ListA, ListB: TList); begin if Assigned(ListB) then begin CopyMove(ListA); MergeMove(ListB); end else MergeMove(ListA); end; procedure TList.DoXOr(ListA, ListB: TList); var r : integer; l : TList; begin if Assigned(ListB) then begin Clear; for r := 0 to ListA.Count-1 do if ListB.IndexOf(ListA[r]) < 0 then Add(ListA[r]); for r := 0 to ListB.Count-1 do if ListA.IndexOf(ListB[r]) < 0 then Add(ListB[r]); end else try l := TList.Create; l.CopyMove (Self); for r := Count-1 downto 0 do if listA.IndexOf(Self[r]) >= 0 then Delete(r); for r := 0 to ListA.Count-1 do if l.IndexOf(ListA[r]) < 0 then Add(ListA[r]); finally l.Destroy; end; end; function TList.Get(Index: Integer): JSValue; begin Result := FList.Get(Index); end; procedure TList.Put(Index: Integer; Item: JSValue); var V : JSValue; begin V := Get(Index); FList.Put(Index, Item); if Assigned(V) then Notify(V, lnDeleted); if Assigned(Item) then Notify(Item, lnAdded); end; procedure TList.Notify(aValue: JSValue; Action: TListNotification); begin if Assigned(aValue) then ; if Action=lnExtracted then ; end; procedure TList.SetCapacity(NewCapacity: Integer); begin FList.SetCapacity(NewCapacity); end; function TList.GetCapacity: integer; begin Result := FList.Capacity; end; procedure TList.SetCount(NewCount: Integer); begin if NewCount < FList.Count then while FList.Count > NewCount do Delete(FList.Count - 1) else FList.SetCount(NewCount); end; function TList.GetCount: integer; begin Result := FList.Count; end; function TList.GetList: TJSValueDynArray; begin Result := FList.List; end; constructor TList.Create; begin inherited Create; FList := TFPList.Create; end; destructor TList.Destroy; begin if Assigned(FList) then Clear; FreeAndNil(FList); end; procedure TList.AddList(AList: TList); var I: Integer; begin { this only does FList.AddList(AList.FList), avoiding notifications } FList.AddList(AList.FList); { make lnAdded notifications } for I := 0 to AList.Count - 1 do if Assigned(AList[I]) then Notify(AList[I], lnAdded); end; function TList.Add(Item: JSValue): Integer; begin Result := FList.Add(Item); if Assigned(Item) then Notify(Item, lnAdded); end; procedure TList.Clear; begin While (FList.Count>0) do Delete(Count-1); end; procedure TList.Delete(Index: Integer); var V : JSValue; begin V:=FList.Get(Index); FList.Delete(Index); if assigned(V) then Notify(V, lnDeleted); end; class procedure TList.Error(const Msg: string; Data: String); begin Raise EListError.CreateFmt(Msg,[Data]); end; procedure TList.Exchange(Index1, Index2: Integer); begin FList.Exchange(Index1, Index2); end; function TList.Expand: TList; begin FList.Expand; Result:=Self; end; function TList.Extract(Item: JSValue): JSValue; var c : integer; begin c := FList.Count; Result := FList.Extract(Item); if c <> FList.Count then Notify (Result, lnExtracted); end; function TList.First: JSValue; begin Result := FList.First; end; function TList.GetEnumerator: TListEnumerator; begin Result:=TListEnumerator.Create(Self); end; function TList.IndexOf(Item: JSValue): Integer; begin Result := FList.IndexOf(Item); end; procedure TList.Insert(Index: Integer; Item: JSValue); begin FList.Insert(Index, Item); if Assigned(Item) then Notify(Item,lnAdded); end; function TList.Last: JSValue; begin Result := FList.Last; end; procedure TList.Move(CurIndex, NewIndex: Integer); begin FList.Move(CurIndex, NewIndex); end; procedure TList.Assign(ListA: TList; AOperator: TListAssignOp; ListB: TList); begin case AOperator of laCopy : DoCopy (ListA, ListB); // replace dest with src laSrcUnique : DoSrcUnique (ListA, ListB); // replace dest with src that are not in dest laAnd : DoAnd (ListA, ListB); // remove from dest that are not in src laDestUnique: DoDestUnique (ListA, ListB);// remove from dest that are in src laOr : DoOr (ListA, ListB); // add to dest from src and not in dest laXOr : DoXOr (ListA, ListB); // add to dest from src and not in dest, remove from dest that are in src end; end; function TList.Remove(Item: JSValue): Integer; begin Result := IndexOf(Item); if Result <> -1 then Self.Delete(Result); end; procedure TList.Pack; begin FList.Pack; end; procedure TList.Sort(const Compare: TListSortCompare); begin FList.Sort(Compare); end; procedure TList.SortList(const Compare: TListSortCompareFunc); begin FList.SortList(Compare); end; { TPersistent } procedure TPersistent.AssignError(Source: TPersistent); var SourceName: String; begin if Source<>Nil then SourceName:=Source.ClassName else SourceName:='Nil'; raise EConvertError.Create('Cannot assign a '+SourceName+' to a '+ClassName+'.'); end; procedure TPersistent.DefineProperties(Filer: TFiler); begin if Filer=Nil then exit; // Do nothing end; procedure TPersistent.AssignTo(Dest: TPersistent); begin Dest.AssignError(Self); end; function TPersistent.GetOwner: TPersistent; begin Result:=nil; end; procedure TPersistent.Assign(Source: TPersistent); begin If Source<>Nil then Source.AssignTo(Self) else AssignError(Nil); end; function TPersistent.GetNamePath: string; var OwnerName: String; TheOwner: TPersistent; begin Result:=ClassName; TheOwner:=GetOwner; if TheOwner<>Nil then begin OwnerName:=TheOwner.GetNamePath; if OwnerName<>'' then Result:=OwnerName+'.'+Result; end; end; { This file is part of the Free Component Library (FCL) Copyright (c) 1999-2000 by the Free Pascal development team 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. **********************************************************************} {****************************************************************************} {* TStringsEnumerator *} {****************************************************************************} constructor TStringsEnumerator.Create(AStrings: TStrings); begin inherited Create; FStrings := AStrings; FPosition := -1; end; function TStringsEnumerator.GetCurrent: String; begin Result := FStrings[FPosition]; end; function TStringsEnumerator.MoveNext: Boolean; begin Inc(FPosition); Result := FPosition < FStrings.Count; end; {****************************************************************************} {* TStrings *} {****************************************************************************} // Function to quote text. Should move maybe to sysutils !! // Also, it is not clear at this point what exactly should be done. { //!! is used to mark unsupported things. } { For compatibility we can't add a Constructor to TSTrings to initialize the special characters. Therefore we add a routine which is called whenever the special chars are needed. } procedure TStrings.CheckSpecialChars; begin If Not FSpecialCharsInited then begin FQuoteChar:='"'; FDelimiter:=','; FNameValueSeparator:='='; FLBS:=DefaultTextLineBreakStyle; FSpecialCharsInited:=true; FLineBreak:=sLineBreak; end; end; function TStrings.GetSkipLastLineBreak: Boolean; begin CheckSpecialChars; Result:=FSkipLastLineBreak; end; procedure TStrings.SetSkipLastLineBreak(const AValue : Boolean); begin CheckSpecialChars; FSkipLastLineBreak:=AValue; end; function TStrings.GetLBS: TTextLineBreakStyle; begin CheckSpecialChars; Result:=FLBS; end; procedure TStrings.SetLBS(AValue: TTextLineBreakStyle); begin CheckSpecialChars; FLBS:=AValue; end; procedure TStrings.SetDelimiter(c:Char); begin CheckSpecialChars; FDelimiter:=c; end; function TStrings.GetDelimiter: Char; begin CheckSpecialChars; Result:=FDelimiter; end; procedure TStrings.SetLineBreak(const S: String); begin CheckSpecialChars; FLineBreak:=S; end; function TStrings.GetLineBreak: String; begin CheckSpecialChars; Result:=FLineBreak; end; procedure TStrings.SetQuoteChar(c:Char); begin CheckSpecialChars; FQuoteChar:=c; end; function TStrings.GetQuoteChar: Char; begin CheckSpecialChars; Result:=FQuoteChar; end; procedure TStrings.SetNameValueSeparator(c:Char); begin CheckSpecialChars; FNameValueSeparator:=c; end; function TStrings.GetNameValueSeparator: Char; begin CheckSpecialChars; Result:=FNameValueSeparator; end; function TStrings.GetCommaText: string; Var C1,C2 : Char; FSD : Boolean; begin CheckSpecialChars; FSD:=StrictDelimiter; C1:=Delimiter; C2:=QuoteChar; Delimiter:=','; QuoteChar:='"'; StrictDelimiter:=False; Try Result:=GetDelimitedText; Finally Delimiter:=C1; QuoteChar:=C2; StrictDelimiter:=FSD; end; end; function TStrings.GetDelimitedText: string; Var I: integer; RE : string; S : String; doQuote : Boolean; begin CheckSpecialChars; result:=''; RE:=QuoteChar+'|'+Delimiter; if not StrictDelimiter then RE:=' |'+RE; RE:='/'+RE+'/'; // Check for break characters and quote if required. For i:=0 to count-1 do begin S:=Strings[i]; doQuote:=FAlwaysQuote or (TJSString(s).search(RE)<>-1); if DoQuote then Result:=Result+QuoteString(S,QuoteChar) else Result:=Result+S; if I<Count-1 then Result:=Result+Delimiter; end; // Quote empty string: If (Length(Result)=0) and (Count=1) then Result:=QuoteChar+QuoteChar; end; procedure TStrings.GetNameValue(Index: Integer; out AName, AValue: String); Var L : longint; begin CheckSpecialChars; AValue:=Strings[Index]; L:=Pos(FNameValueSeparator,AValue); If L<>0 then begin AName:=Copy(AValue,1,L-1); // System.Delete(AValue,1,L); AValue:=Copy(AValue,L+1,length(AValue)-L); end else AName:=''; end; procedure TStrings.LoadFromURL(const aURL: String; Async: Boolean; OnLoaded: TNotifyEventRef; OnError: TStringNotifyEventRef); procedure DoLoaded(const aString : String); begin Text:=aString; if Assigned(OnLoaded) then OnLoaded(Self); end; procedure DoError(const AError : String); begin if Assigned(OnError) then OnError(Self,aError) else Raise EInOutError.Create('Failed to load from URL:'+aError); end; begin CheckLoadHelper; GlobalLoadHelper.LoadText(aURL,aSync,@DoLoaded,@DoError); end; procedure TStrings.LoadFromFile(const aFileName: String; const OnLoaded: TProc; const AError: TProcString); begin LoadFromURL(aFileName,False, Procedure (Sender : TObject) begin If Assigned(OnLoaded) then OnLoaded end, Procedure (Sender : TObject; Const ErrorMsg : String) begin if Assigned(aError) then aError(ErrorMsg) end); end; function TStrings.ExtractName(const S: String): String; var L: Longint; begin CheckSpecialChars; L:=Pos(FNameValueSeparator,S); If L<>0 then Result:=Copy(S,1,L-1) else Result:=''; end; function TStrings.GetName(Index: Integer): string; Var V : String; begin GetNameValue(Index,Result,V); end; function TStrings.GetValue(const Name: string): string; Var L : longint; N : String; begin Result:=''; L:=IndexOfName(Name); If L<>-1 then GetNameValue(L,N,Result); end; function TStrings.GetValueFromIndex(Index: Integer): string; Var N : String; begin GetNameValue(Index,N,Result); end; procedure TStrings.SetValueFromIndex(Index: Integer; const Value: string); begin If (Value='') then Delete(Index) else begin If (Index<0) then Index:=Add(''); CheckSpecialChars; Strings[Index]:=GetName(Index)+FNameValueSeparator+Value; end; end; procedure TStrings.SetDelimitedText(const AValue: string); var i,j:integer; aNotFirst:boolean; begin CheckSpecialChars; BeginUpdate; i:=1; j:=1; aNotFirst:=false; { Paraphrased from Delphi XE2 help: Strings must be separated by Delimiter characters or spaces. They may be enclosed in QuoteChars. QuoteChars in the string must be repeated to distinguish them from the QuoteChars enclosing the string. } try Clear; If StrictDelimiter then begin while i<=length(AValue) do begin // skip delimiter if aNotFirst and (i<=length(AValue)) and (AValue[i]=FDelimiter) then inc(i); // read next string if i<=length(AValue) then begin if AValue[i]=FQuoteChar then begin // next string is quoted j:=i+1; while (j<=length(AValue)) and ( (AValue[j]<>FQuoteChar) or ( (j+1<=length(AValue)) and (AValue[j+1]=FQuoteChar) ) ) do begin if (j<=length(AValue)) and (AValue[j]=FQuoteChar) then inc(j,2) else inc(j); end; // j is position of closing quote Add( StringReplace (Copy(AValue,i+1,j-i-1), FQuoteChar+FQuoteChar,FQuoteChar, [rfReplaceAll])); i:=j+1; end else begin // next string is not quoted; read until delimiter j:=i; while (j<=length(AValue)) and (AValue[j]<>FDelimiter) do inc(j); Add( Copy(AValue,i,j-i)); i:=j; end; end else begin if aNotFirst then Add(''); end; aNotFirst:=true; end; end else begin while i<=length(AValue) do begin // skip delimiter if aNotFirst and (i<=length(AValue)) and (AValue[i]=FDelimiter) then inc(i); // skip spaces while (i<=length(AValue)) and (Ord(AValue[i])<=Ord(' ')) do inc(i); // read next string if i<=length(AValue) then begin if AValue[i]=FQuoteChar then begin // next string is quoted j:=i+1; while (j<=length(AValue)) and ( (AValue[j]<>FQuoteChar) or ( (j+1<=length(AValue)) and (AValue[j+1]=FQuoteChar) ) ) do begin if (j<=length(AValue)) and (AValue[j]=FQuoteChar) then inc(j,2) else inc(j); end; // j is position of closing quote Add( StringReplace (Copy(AValue,i+1,j-i-1), FQuoteChar+FQuoteChar,FQuoteChar, [rfReplaceAll])); i:=j+1; end else begin // next string is not quoted; read until control character/space/delimiter j:=i; while (j<=length(AValue)) and (Ord(AValue[j])>Ord(' ')) and (AValue[j]<>FDelimiter) do inc(j); Add( Copy(AValue,i,j-i)); i:=j; end; end else begin if aNotFirst then Add(''); end; // skip spaces while (i<=length(AValue)) and (Ord(AValue[i])<=Ord(' ')) do inc(i); aNotFirst:=true; end; end; finally EndUpdate; end; end; procedure TStrings.SetCommaText(const Value: string); Var C1,C2 : Char; begin CheckSpecialChars; C1:=Delimiter; C2:=QuoteChar; Delimiter:=','; QuoteChar:='"'; Try SetDelimitedText(Value); Finally Delimiter:=C1; QuoteChar:=C2; end; end; procedure TStrings.SetValue(const Name: String; const Value: string); Var L : longint; begin CheckSpecialChars; L:=IndexOfName(Name); if L=-1 then Add (Name+FNameValueSeparator+Value) else Strings[L]:=Name+FNameValueSeparator+value; end; procedure TStrings.Error(const Msg: string; Data: Integer); begin Raise EStringListError.CreateFmt(Msg,[IntToStr(Data)]); end; function TStrings.GetCapacity: Integer; begin Result:=Count; end; function TStrings.GetObject(Index: Integer): TObject; begin if Index=0 then ; Result:=Nil; end; function TStrings.GetTextStr: string; Var I : Longint; S,NL : String; begin CheckSpecialChars; // Determine needed place if FLineBreak<>sLineBreak then NL:=FLineBreak else Case FLBS of tlbsLF : NL:=#10; tlbsCRLF : NL:=#13#10; tlbsCR : NL:=#13; end; Result:=''; For i:=0 To count-1 do begin S:=Strings[I]; Result:=Result+S; if (I<Count-1) or Not SkipLastLineBreak then Result:=Result+NL; end; end; procedure TStrings.Put(Index: Integer; const S: string); Var Obj : TObject; begin Obj:=Objects[Index]; Delete(Index); InsertObject(Index,S,Obj); end; procedure TStrings.PutObject(Index: Integer; AObject: TObject); begin // Empty. if Index=0 then exit; if AObject=nil then exit; end; procedure TStrings.SetCapacity(NewCapacity: Integer); begin // Empty. if NewCapacity=0 then ; end; function TStrings.GetNextLinebreak(const Value: String; out S: String; var P: Integer): Boolean; Var PP : Integer; begin S:=''; Result:=False; If ((Length(Value)-P)<0) then exit; PP:=TJSString(Value).IndexOf(LineBreak,P-1)+1; if (PP<1) then PP:=Length(Value)+1; S:=Copy(Value,P,PP-P); P:=PP+length(LineBreak); Result:=True; end; procedure TStrings.DoSetTextStr(const Value: string; DoClear: Boolean); Var S : String; P : Integer; begin Try BeginUpdate; if DoClear then Clear; P:=1; While GetNextLineBreak (Value,S,P) do Add(S); finally EndUpdate; end; end; procedure TStrings.SetTextStr(const Value: string); begin CheckSpecialChars; DoSetTextStr(Value,True); end; procedure TStrings.AddText(const S: String); begin CheckSpecialChars; DoSetTextStr(S,False); end; procedure TStrings.SetUpdateState(Updating: Boolean); begin // FPONotifyObservers(Self,ooChange,Nil); if Updating then ; end; destructor TStrings.Destroy; begin inherited destroy; end; constructor TStrings.Create; begin inherited Create; FAlwaysQuote:=False; end; function TStrings.Add(const S: string): Integer; begin Result:=Count; Insert (Count,S); end; function TStrings.Add(const Fmt: string; const Args: array of JSValue): Integer; begin Result:=Add(Format(Fmt,Args)); end; function TStrings.AddFmt(const Fmt: string; const Args: array of JSValue): Integer; begin Result:=Add(Format(Fmt,Args)); end; function TStrings.AddObject(const S: string; AObject: TObject): Integer; begin Result:=Add(S); Objects[result]:=AObject; end; function TStrings.AddObject(const Fmt: string; Args: array of JSValue; AObject: TObject): Integer; begin Result:=AddObject(Format(Fmt,Args),AObject); end; procedure TStrings.Append(const S: string); begin Add (S); end; procedure TStrings.AddStrings(TheStrings: TStrings; ClearFirst: Boolean); begin beginupdate; try if ClearFirst then Clear; AddStrings(TheStrings); finally EndUpdate; end; end; procedure TStrings.AddStrings(TheStrings: TStrings); Var Runner : longint; begin For Runner:=0 to TheStrings.Count-1 do self.AddObject (Thestrings[Runner],TheStrings.Objects[Runner]); end; procedure TStrings.AddStrings(const TheStrings: array of string); Var Runner : longint; begin if Count + High(TheStrings)+1 > Capacity then Capacity := Count + High(TheStrings)+1; For Runner:=Low(TheStrings) to High(TheStrings) do self.Add(Thestrings[Runner]); end; procedure TStrings.AddStrings(const TheStrings: array of string; ClearFirst: Boolean); begin beginupdate; try if ClearFirst then Clear; AddStrings(TheStrings); finally EndUpdate; end; end; function TStrings.AddPair(const AName, AValue: string): TStrings; begin Result:=AddPair(AName,AValue,Nil); end; function TStrings.AddPair(const AName, AValue: string; AObject: TObject): TStrings; begin Result := Self; AddObject(AName+NameValueSeparator+AValue, AObject); end; procedure TStrings.Assign(Source: TPersistent); Var S : TStrings; begin If Source is TStrings then begin S:=TStrings(Source); BeginUpdate; Try clear; FSpecialCharsInited:=S.FSpecialCharsInited; FQuoteChar:=S.FQuoteChar; FDelimiter:=S.FDelimiter; FNameValueSeparator:=S.FNameValueSeparator; FLBS:=S.FLBS; FLineBreak:=S.FLineBreak; AddStrings(S); finally EndUpdate; end; end else Inherited Assign(Source); end; procedure TStrings.BeginUpdate; begin if FUpdateCount = 0 then SetUpdateState(true); inc(FUpdateCount); end; procedure TStrings.EndUpdate; begin If FUpdateCount>0 then Dec(FUpdateCount); if FUpdateCount=0 then SetUpdateState(False); end; function TStrings.Equals(Obj: TObject): Boolean; begin if Obj is TStrings then Result := Equals(TStrings(Obj)) else Result := inherited Equals(Obj); end; function TStrings.Equals(TheStrings: TStrings): Boolean; Var Runner,Nr : Longint; begin Result:=False; Nr:=Self.Count; if Nr<>TheStrings.Count then exit; For Runner:=0 to Nr-1 do If Strings[Runner]<>TheStrings[Runner] then exit; Result:=True; end; procedure TStrings.Exchange(Index1, Index2: Integer); Var Obj : TObject; Str : String; begin beginUpdate; Try Obj:=Objects[Index1]; Str:=Strings[Index1]; Objects[Index1]:=Objects[Index2]; Strings[Index1]:=Strings[Index2]; Objects[Index2]:=Obj; Strings[Index2]:=Str; finally EndUpdate; end; end; function TStrings.GetEnumerator: TStringsEnumerator; begin Result:=TStringsEnumerator.Create(Self); end; function TStrings.DoCompareText(const s1, s2: string): PtrInt; begin result:=CompareText(s1,s2); end; function TStrings.IndexOf(const S: string): Integer; begin Result:=0; While (Result<Count) and (DoCompareText(Strings[Result],S)<>0) do Result:=Result+1; if Result=Count then Result:=-1; end; function TStrings.IndexOfName(const Name: string): Integer; Var len : longint; S : String; begin CheckSpecialChars; Result:=0; while (Result<Count) do begin S:=Strings[Result]; len:=pos(FNameValueSeparator,S)-1; if (len>=0) and (DoCompareText(Name,Copy(S,1,Len))=0) then exit; inc(result); end; result:=-1; end; function TStrings.IndexOfObject(AObject: TObject): Integer; begin Result:=0; While (Result<count) and (Objects[Result]<>AObject) do Result:=Result+1; If Result=Count then Result:=-1; end; procedure TStrings.InsertObject(Index: Integer; const S: string; AObject: TObject); begin Insert (Index,S); Objects[Index]:=AObject; end; procedure TStrings.Move(CurIndex, NewIndex: Integer); Var Obj : TObject; Str : String; begin BeginUpdate; Try Obj:=Objects[CurIndex]; Str:=Strings[CurIndex]; Objects[CurIndex]:=Nil; // Prevent Delete from freeing. Delete(Curindex); InsertObject(NewIndex,Str,Obj); finally EndUpdate; end; end; {****************************************************************************} {* TStringList *} {****************************************************************************} procedure TStringList.ExchangeItemsInt(Index1, Index2: Integer); Var S : String; O : TObject; begin S:=Flist[Index1].FString; O:=Flist[Index1].FObject; Flist[Index1].Fstring:=Flist[Index2].Fstring; Flist[Index1].FObject:=Flist[Index2].FObject; Flist[Index2].Fstring:=S; Flist[Index2].FObject:=O; end; function TStringList.GetSorted: Boolean; begin Result:=FSortStyle in [sslUser,sslAuto]; end; procedure TStringList.ExchangeItems(Index1, Index2: Integer); begin ExchangeItemsInt(Index1, Index2); end; procedure TStringList.Grow; Var NC : Integer; begin NC:=Capacity; If NC>=256 then NC:=NC+(NC Div 4) else if NC=0 then NC:=4 else NC:=NC*4; SetCapacity(NC); end; procedure TStringList.InternalClear(FromIndex: Integer; ClearOnly: Boolean); Var I: Integer; begin if FromIndex < FCount then begin if FOwnsObjects then begin For I:=FromIndex to FCount-1 do begin Flist[I].FString:=''; freeandnil(Flist[i].FObject); end; end else begin For I:=FromIndex to FCount-1 do Flist[I].FString:=''; end; FCount:=FromIndex; end; if Not ClearOnly then SetCapacity(0); end; procedure TStringList.QuickSort(L, R: Integer; CompareFn: TStringListSortCompare ); var Pivot, vL, vR: Integer; begin //if ExchangeItems is override call that, else call (faster) ExchangeItemsInt if R - L <= 1 then begin // a little bit of time saver if L < R then if CompareFn(Self, L, R) > 0 then ExchangeItems(L, R); Exit; end; vL := L; vR := R; Pivot := L + Random(R - L); // they say random is best while vL < vR do begin while (vL < Pivot) and (CompareFn(Self, vL, Pivot) <= 0) do Inc(vL); while (vR > Pivot) and (CompareFn(Self, vR, Pivot) > 0) do Dec(vR); ExchangeItems(vL, vR); if Pivot = vL then // swap pivot if we just hit it from one side Pivot := vR else if Pivot = vR then Pivot := vL; end; if Pivot - 1 >= L then QuickSort(L, Pivot - 1, CompareFn); if Pivot + 1 <= R then QuickSort(Pivot + 1, R, CompareFn); end; procedure TStringList.InsertItem(Index: Integer; const S: string); begin InsertItem(Index, S, nil); end; procedure TStringList.InsertItem(Index: Integer; const S: string; O: TObject); Var It : TStringItem; begin Changing; If FCount=Capacity then Grow; it.FString:=S; it.FObject:=O; TJSArray(FList).Splice(Index,0,It); Inc(FCount); Changed; end; procedure TStringList.SetSorted(Value: Boolean); begin If Value then SortStyle:=sslAuto else SortStyle:=sslNone end; procedure TStringList.Changed; begin If (FUpdateCount=0) Then begin If Assigned(FOnChange) then FOnchange(Self); end; end; procedure TStringList.Changing; begin If FUpdateCount=0 then if Assigned(FOnChanging) then FOnchanging(Self); end; function TStringList.Get(Index: Integer): string; begin CheckIndex(Index); Result:=Flist[Index].FString; end; function TStringList.GetCapacity: Integer; begin Result:=Length(FList); end; function TStringList.GetCount: Integer; begin Result:=FCount; end; function TStringList.GetObject(Index: Integer): TObject; begin CheckIndex(Index); Result:=Flist[Index].FObject; end; procedure TStringList.Put(Index: Integer; const S: string); begin If Sorted then Error(SSortedListError,0); CheckIndex(Index); Changing; Flist[Index].FString:=S; Changed; end; procedure TStringList.PutObject(Index: Integer; AObject: TObject); begin CheckIndex(Index); Changing; Flist[Index].FObject:=AObject; Changed; end; procedure TStringList.SetCapacity(NewCapacity: Integer); begin If (NewCapacity<0) then Error (SListCapacityError,NewCapacity); If NewCapacity<>Capacity then SetLength(FList,NewCapacity) end; procedure TStringList.SetUpdateState(Updating: Boolean); begin If Updating then Changing else Changed end; destructor TStringList.Destroy; begin InternalClear; Inherited destroy; end; function TStringList.Add(const S: string): Integer; begin If Not (SortStyle=sslAuto) then Result:=FCount else If Find (S,Result) then Case DUplicates of DupIgnore : Exit; DupError : Error(SDuplicateString,0) end; InsertItem (Result,S); end; procedure TStringList.Clear; begin if FCount = 0 then Exit; Changing; InternalClear; Changed; end; procedure TStringList.Delete(Index: Integer); begin CheckIndex(Index); Changing; if FOwnsObjects then FreeAndNil(Flist[Index].FObject); TJSArray(FList).splice(Index,1); FList[Count-1].FString:=''; Flist[Count-1].FObject:=Nil; Dec(FCount); Changed; end; procedure TStringList.Exchange(Index1, Index2: Integer); begin CheckIndex(Index1); CheckIndex(Index2); Changing; ExchangeItemsInt(Index1,Index2); changed; end; procedure TStringList.SetCaseSensitive(b : boolean); begin if b=FCaseSensitive then Exit; FCaseSensitive:=b; if FSortStyle=sslAuto then begin FForceSort:=True; try Sort; finally FForceSort:=False; end; end; end; procedure TStringList.SetSortStyle(AValue: TStringsSortStyle); begin if FSortStyle=AValue then Exit; if (AValue=sslAuto) then Sort; FSortStyle:=AValue; end; procedure TStringList.CheckIndex(AIndex: Integer); begin If (AIndex<0) or (AIndex>=FCount) then Error(SListIndexError,AIndex); end; function TStringList.DoCompareText(const s1, s2: string): PtrInt; begin if FCaseSensitive then result:=CompareStr(s1,s2) else result:=CompareText(s1,s2); end; function TStringList.CompareStrings(const s1,s2 : string) : Integer; begin Result := DoCompareText(s1, s2); end; function TStringList.Find(const S: string; out Index: Integer): Boolean; var L, R, I: Integer; CompareRes: PtrInt; begin Result := false; Index:=-1; if Not Sorted then Raise EListError.Create(SErrFindNeedsSortedList); // Use binary search. L := 0; R := Count - 1; while (L<=R) do begin I := L + (R - L) div 2; CompareRes := DoCompareText(S, Flist[I].FString); if (CompareRes>0) then L := I+1 else begin R := I-1; if (CompareRes=0) then begin Result := true; if (Duplicates<>dupAccept) then L := I; // forces end of while loop end; end; end; Index := L; end; function TStringList.IndexOf(const S: string): Integer; begin If Not Sorted then Result:=Inherited indexOf(S) else // faster using binary search... If Not Find (S,Result) then Result:=-1; end; procedure TStringList.Insert(Index: Integer; const S: string); begin If SortStyle=sslAuto then Error (SSortedListError,0) else begin If (Index<0) or (Index>FCount) then Error(SListIndexError,Index); // Cannot use CheckIndex, because there >= FCount... InsertItem (Index,S); end; end; procedure TStringList.CustomSort(CompareFn: TStringListSortCompare); begin If (FForceSort or (Not (FSortStyle=sslAuto))) and (FCount>1) then begin Changing; QuickSort(0,FCount-1, CompareFn); Changed; end; end; function StringListAnsiCompare(List: TStringList; Index1, Index: Integer): Integer; begin Result := List.DoCompareText(List.FList[Index1].FString, List.FList[Index].FString); end; procedure TStringList.Sort; begin CustomSort(@StringListAnsiCompare); end; {****************************************************************************} {* TCollectionItem *} {****************************************************************************} function TCollectionItem.GetIndex: Integer; begin if FCollection<>nil then Result:=FCollection.FItems.IndexOf(Self) else Result:=-1; end; procedure TCollectionItem.SetCollection(Value: TCollection); begin IF Value<>FCollection then begin If FCollection<>Nil then FCollection.RemoveItem(Self); if Value<>Nil then Value.InsertItem(Self); end; end; procedure TCollectionItem.Changed(AllItems: Boolean); begin If (FCollection<>Nil) and (FCollection.UpdateCount=0) then begin If AllItems then FCollection.Update(Nil) else FCollection.Update(Self); end; end; function TCollectionItem.GetNamePath: string; begin If FCollection<>Nil then Result:=FCollection.GetNamePath+'['+IntToStr(Index)+']' else Result:=ClassName; end; function TCollectionItem.GetOwner: TPersistent; begin Result:=FCollection; end; function TCollectionItem.GetDisplayName: string; begin Result:=ClassName; end; procedure TCollectionItem.SetIndex(Value: Integer); Var Temp : Longint; begin Temp:=GetIndex; If (Temp>-1) and (Temp<>Value) then begin FCollection.FItems.Move(Temp,Value); Changed(True); end; end; procedure TCollectionItem.SetDisplayName(const Value: string); begin Changed(False); if Value='' then ; end; constructor TCollectionItem.Create(ACollection: TCollection); begin Inherited Create; SetCollection(ACollection); end; destructor TCollectionItem.Destroy; begin SetCollection(Nil); Inherited Destroy; end; {****************************************************************************} {* TCollectionEnumerator *} {****************************************************************************} constructor TCollectionEnumerator.Create(ACollection: TCollection); begin inherited Create; FCollection := ACollection; FPosition := -1; end; function TCollectionEnumerator.GetCurrent: TCollectionItem; begin Result := FCollection.Items[FPosition]; end; function TCollectionEnumerator.MoveNext: Boolean; begin Inc(FPosition); Result := FPosition < FCollection.Count; end; {****************************************************************************} {* TCollection *} {****************************************************************************} function TCollection.Owner: TPersistent; begin result:=getowner; end; function TCollection.GetCount: Integer; begin Result:=FItems.Count; end; Procedure TCollection.SetPropName; { Var TheOwner : TPersistent; PropList : PPropList; I, PropCount : Integer; } begin FPropName:=''; { TheOwner:=GetOwner; // TODO: This needs to wait till Mattias finishes typeinfo. // It's normally only used in the designer so should not be a problem currently. if (TheOwner=Nil) Or (TheOwner.Classinfo=Nil) Then Exit; // get information from the owner RTTI PropCount:=GetPropList(TheOwner, PropList); Try For I:=0 To PropCount-1 Do If (PropList^[i]^.PropType^.Kind=tkClass) And (GetObjectProp(TheOwner, PropList^[i], ClassType)=Self) Then Begin FPropName:=PropList^[i]^.Name; Exit; End; Finally FreeMem(PropList); End; } end; function TCollection.GetPropName: string; {Var TheOwner : TPersistent;} begin Result:=FPropNAme; // TheOwner:=GetOwner; // If (Result<>'') or (TheOwner=Nil) Or (TheOwner.Classinfo=Nil) then exit; SetPropName; Result:=FPropName; end; procedure TCollection.InsertItem(Item: TCollectionItem); begin If Not(Item Is FitemClass) then exit; FItems.add(Item); Item.FCollection:=Self; Item.FID:=FNextID; inc(FNextID); SetItemName(Item); Notify(Item,cnAdded); Changed; end; procedure TCollection.RemoveItem(Item: TCollectionItem); Var I : Integer; begin Notify(Item,cnExtracting); I:=FItems.IndexOfItem(Item,fromEnd); If (I<>-1) then FItems.Delete(I); Item.FCollection:=Nil; Changed; end; function TCollection.GetAttrCount: Integer; begin Result:=0; end; function TCollection.GetAttr(Index: Integer): string; begin Result:=''; if Index=0 then ; end; function TCollection.GetItemAttr(Index, ItemIndex: Integer): string; begin Result:=TCollectionItem(FItems.Items[ItemIndex]).DisplayName; if Index=0 then ; end; function TCollection.GetEnumerator: TCollectionEnumerator; begin Result := TCollectionEnumerator.Create(Self); end; function TCollection.GetNamePath: string; var o : TPersistent; begin o:=getowner; if assigned(o) and (propname<>'') then result:=o.getnamepath+'.'+propname else result:=classname; end; procedure TCollection.Changed; begin if FUpdateCount=0 then Update(Nil); end; function TCollection.GetItem(Index: Integer): TCollectionItem; begin Result:=TCollectionItem(FItems.Items[Index]); end; procedure TCollection.SetItem(Index: Integer; Value: TCollectionItem); begin TCollectionItem(FItems.items[Index]).Assign(Value); end; procedure TCollection.SetItemName(Item: TCollectionItem); begin if Item=nil then ; end; procedure TCollection.Update(Item: TCollectionItem); begin if Item=nil then ; end; constructor TCollection.Create(AItemClass: TCollectionItemClass); begin inherited create; FItemClass:=AItemClass; FItems:=TFpList.Create; end; destructor TCollection.Destroy; begin FUpdateCount:=1; // Prevent OnChange try DoClear; Finally FUpdateCount:=0; end; if assigned(FItems) then FItems.Destroy; Inherited Destroy; end; function TCollection.Add: TCollectionItem; begin Result:=FItemClass.Create(Self); end; procedure TCollection.Assign(Source: TPersistent); Var I : Longint; begin If Source is TCollection then begin Clear; For I:=0 To TCollection(Source).Count-1 do Add.Assign(TCollection(Source).Items[I]); exit; end else Inherited Assign(Source); end; procedure TCollection.BeginUpdate; begin inc(FUpdateCount); end; procedure TCollection.Clear; begin if FItems.Count=0 then exit; // Prevent Changed BeginUpdate; try DoClear; finally EndUpdate; end; end; procedure TCollection.DoClear; var Item: TCollectionItem; begin While FItems.Count>0 do begin Item:=TCollectionItem(FItems.Last); if Assigned(Item) then Item.Destroy; end; end; procedure TCollection.EndUpdate; begin if FUpdateCount>0 then dec(FUpdateCount); if FUpdateCount=0 then Changed; end; function TCollection.FindItemID(ID: Integer): TCollectionItem; Var I : Longint; begin For I:=0 to Fitems.Count-1 do begin Result:=TCollectionItem(FItems.items[I]); If Result.Id=Id then exit; end; Result:=Nil; end; procedure TCollection.Delete(Index: Integer); Var Item : TCollectionItem; begin Item:=TCollectionItem(FItems[Index]); Notify(Item,cnDeleting); If assigned(Item) then Item.Destroy; end; function TCollection.Insert(Index: Integer): TCollectionItem; begin Result:=Add; Result.Index:=Index; end; procedure TCollection.Notify(Item: TCollectionItem;Action: TCollectionNotification); begin if Item=nil then ; if Action=cnAdded then ; end; procedure TCollection.Sort(Const Compare : TCollectionSortCompare); begin BeginUpdate; try FItems.Sort(TListSortCompare(Compare)); Finally EndUpdate; end; end; procedure TCollection.SortList(const Compare: TCollectionSortCompareFunc); begin BeginUpdate; try FItems.SortList(TListSortCompareFunc(Compare)); Finally EndUpdate; end; end; procedure TCollection.Exchange(Const Index1, index2: integer); begin FItems.Exchange(Index1,Index2); end; {****************************************************************************} {* TOwnedCollection *} {****************************************************************************} Constructor TOwnedCollection.Create(AOwner: TPersistent; AItemClass: TCollectionItemClass); Begin FOwner := AOwner; inherited Create(AItemClass); end; Function TOwnedCollection.GetOwner: TPersistent; begin Result:=FOwner; end; {****************************************************************************} {* TComponent *} {****************************************************************************} function TComponent.GetComponent(AIndex: Integer): TComponent; begin If not assigned(FComponents) then Result:=Nil else Result:=TComponent(FComponents.Items[Aindex]); end; function TComponent.GetComponentCount: Integer; begin If not assigned(FComponents) then result:=0 else Result:=FComponents.Count; end; function TComponent.GetComponentIndex: Integer; begin If Assigned(FOwner) and Assigned(FOwner.FComponents) then Result:=FOWner.FComponents.IndexOf(Self) else Result:=-1; end; procedure TComponent.Insert(AComponent: TComponent); begin If not assigned(FComponents) then FComponents:=TFpList.Create; FComponents.Add(AComponent); AComponent.FOwner:=Self; end; procedure TComponent.ReadLeft(AReader: TReader); begin FDesignInfo := (FDesignInfo and $ffff0000) or (AReader.ReadInteger and $ffff); end; procedure TComponent.ReadTop(AReader: TReader); begin FDesignInfo := ((AReader.ReadInteger and $ffff) shl 16) or (FDesignInfo and $ffff); end; procedure TComponent.Remove(AComponent: TComponent); begin AComponent.FOwner:=Nil; If assigned(FCOmponents) then begin FComponents.Remove(AComponent); IF FComponents.Count=0 then begin FComponents.Destroy; FComponents:=Nil; end; end; end; procedure TComponent.RemoveNotification(AComponent: TComponent); begin if FFreeNotifies<>nil then begin FFreeNotifies.Remove(AComponent); if FFreeNotifies.Count=0 then begin FFreeNotifies.Destroy; FFreeNotifies:=nil; Exclude(FComponentState,csFreeNotification); end; end; end; procedure TComponent.SetComponentIndex(Value: Integer); Var Temp,Count : longint; begin If Not assigned(Fowner) then exit; Temp:=getcomponentindex; If temp<0 then exit; If value<0 then value:=0; Count:=Fowner.FComponents.Count; If Value>=Count then value:=count-1; If Value<>Temp then begin FOWner.FComponents.Delete(Temp); FOwner.FComponents.Insert(Value,Self); end; end; procedure TComponent.ChangeName(const NewName: TComponentName); begin FName:=NewName; end; procedure TComponent.DefineProperties(Filer: TFiler); var Temp: LongInt; Ancestor: TComponent; begin Ancestor := TComponent(Filer.Ancestor); if Assigned(Ancestor) then Temp := Ancestor.FDesignInfo else Temp := 0; Filer.DefineProperty('Left', @ReadLeft, @WriteLeft, (FDesignInfo and $ffff) <> (Temp and $ffff)); Filer.DefineProperty('Top', @ReadTop, @WriteTop, (FDesignInfo and $ffff0000) <> (Temp and $ffff0000)); end; procedure TComponent.GetChildren(Proc: TGetChildProc; Root: TComponent); begin // Does nothing. if Proc=nil then ; if Root=nil then ; end; function TComponent.GetChildOwner: TComponent; begin Result:=Nil; end; function TComponent.GetChildParent: TComponent; begin Result:=Self; end; function TComponent.GetNamePath: string; begin Result:=FName; end; function TComponent.GetOwner: TPersistent; begin Result:=FOwner; end; procedure TComponent.Loaded; begin Exclude(FComponentState,csLoading); end; procedure TComponent.Loading; begin Include(FComponentState,csLoading); end; procedure TComponent.SetWriting(Value: Boolean); begin If Value then Include(FComponentState,csWriting) else Exclude(FComponentState,csWriting); end; procedure TComponent.SetReading(Value: Boolean); begin If Value then Include(FComponentState,csReading) else Exclude(FComponentState,csReading); end; procedure TComponent.Notification(AComponent: TComponent; Operation: TOperation); Var C : Longint; begin If (Operation=opRemove) then RemoveFreeNotification(AComponent); If Not assigned(FComponents) then exit; C:=FComponents.Count-1; While (C>=0) do begin TComponent(FComponents.Items[C]).Notification(AComponent,Operation); Dec(C); if C>=FComponents.Count then C:=FComponents.Count-1; end; end; procedure TComponent.PaletteCreated; begin end; procedure TComponent.ReadState(Reader: TReader); begin Reader.ReadData(Self); end; procedure TComponent.SetAncestor(Value: Boolean); Var Runner : Longint; begin If Value then Include(FComponentState,csAncestor) else Exclude(FCOmponentState,csAncestor); if Assigned(FComponents) then For Runner:=0 To FComponents.Count-1 do TComponent(FComponents.Items[Runner]).SetAncestor(Value); end; procedure TComponent.SetDesigning(Value: Boolean; SetChildren: Boolean); Var Runner : Longint; begin If Value then Include(FComponentState,csDesigning) else Exclude(FComponentState,csDesigning); if Assigned(FComponents) and SetChildren then For Runner:=0 To FComponents.Count - 1 do TComponent(FComponents.items[Runner]).SetDesigning(Value); end; procedure TComponent.SetDesignInstance(Value: Boolean); begin If Value then Include(FComponentState,csDesignInstance) else Exclude(FComponentState,csDesignInstance); end; procedure TComponent.SetInline(Value: Boolean); begin If Value then Include(FComponentState,csInline) else Exclude(FComponentState,csInline); end; procedure TComponent.SetName(const NewName: TComponentName); begin If FName=NewName then exit; If (NewName<>'') and not IsValidIdent(NewName) then Raise EComponentError.CreateFmt(SInvalidName,[NewName]); If Assigned(FOwner) Then FOwner.ValidateRename(Self,FName,NewName) else ValidateRename(Nil,FName,NewName); SetReference(False); ChangeName(NewName); SetReference(True); end; procedure TComponent.SetChildOrder(Child: TComponent; Order: Integer); begin // does nothing if Child=nil then ; if Order=0 then ; end; procedure TComponent.SetParentComponent(Value: TComponent); begin // Does nothing if Value=nil then ; end; procedure TComponent.Updating; begin Include (FComponentState,csUpdating); end; procedure TComponent.Updated; begin Exclude(FComponentState,csUpdating); end; procedure TComponent.ValidateRename(AComponent: TComponent; const CurName, NewName: string); begin //!! This contradicts the Delphi manual. If (AComponent<>Nil) and (CompareText(CurName,NewName)<>0) and (AComponent.Owner = Self) and (FindComponent(NewName)<>Nil) then raise EComponentError.Createfmt(SDuplicateName,[newname]); If (csDesigning in FComponentState) and (FOwner<>Nil) then FOwner.ValidateRename(AComponent,Curname,Newname); end; Procedure TComponent.SetReference(Enable: Boolean); var aField, aValue, aOwner : Pointer; begin if Name='' then exit; if Assigned(Owner) then begin aOwner:=Owner; // so as not to depend on low-level names aField := Owner.FieldAddress(Name); if Assigned(aField) then begin if Enable then aValue:= Self else aValue := nil; TJSObject(aOwner)[String(TJSObject(aField)['name'])]:=aValue; end; end; end; procedure TComponent.WriteLeft(AWriter: TWriter); begin AWriter.WriteInteger(FDesignInfo and $ffff); end; procedure TComponent.WriteTop(AWriter: TWriter); begin AWriter.WriteInteger((FDesignInfo shr 16) and $ffff); end; procedure TComponent.ValidateContainer(AComponent: TComponent); begin AComponent.ValidateInsert(Self); end; procedure TComponent.ValidateInsert(AComponent: TComponent); begin // Does nothing. if AComponent=nil then ; end; function TComponent._AddRef: Integer; begin Result:=-1; end; function TComponent._Release: Integer; begin Result:=-1; end; constructor TComponent.Create(AOwner: TComponent); begin FComponentStyle:=[csInheritable]; If Assigned(AOwner) then AOwner.InsertComponent(Self); end; destructor TComponent.Destroy; Var I : Integer; C : TComponent; begin Destroying; If Assigned(FFreeNotifies) then begin I:=FFreeNotifies.Count-1; While (I>=0) do begin C:=TComponent(FFreeNotifies.Items[I]); // Delete, so one component is not notified twice, if it is owned. FFreeNotifies.Delete(I); C.Notification (self,opRemove); If (FFreeNotifies=Nil) then I:=0 else if (I>FFreeNotifies.Count) then I:=FFreeNotifies.Count; dec(i); end; FreeAndNil(FFreeNotifies); end; DestroyComponents; If FOwner<>Nil Then FOwner.RemoveComponent(Self); inherited destroy; end; procedure TComponent.BeforeDestruction; begin if not(csDestroying in FComponentstate) then Destroying; end; procedure TComponent.DestroyComponents; Var acomponent: TComponent; begin While assigned(FComponents) do begin aComponent:=TComponent(FComponents.Last); Remove(aComponent); Acomponent.Destroy; end; end; procedure TComponent.Destroying; Var Runner : longint; begin If csDestroying in FComponentstate Then Exit; include (FComponentState,csDestroying); If Assigned(FComponents) then for Runner:=0 to FComponents.Count-1 do TComponent(FComponents.Items[Runner]).Destroying; end; function TComponent.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; procedure TComponent.WriteState(Writer: TWriter); begin Writer.WriteComponentData(Self); end; function TComponent.FindComponent(const AName: string): TComponent; Var I : longint; begin Result:=Nil; If (AName='') or Not assigned(FComponents) then exit; For i:=0 to FComponents.Count-1 do if (CompareText(TComponent(FComponents[I]).Name,AName)=0) then begin Result:=TComponent(FComponents.Items[I]); exit; end; end; procedure TComponent.FreeNotification(AComponent: TComponent); begin If (Owner<>Nil) and (AComponent=Owner) then exit; If not (Assigned(FFreeNotifies)) then FFreeNotifies:=TFpList.Create; If FFreeNotifies.IndexOf(AComponent)=-1 then begin FFreeNotifies.Add(AComponent); AComponent.FreeNotification (self); end; end; procedure TComponent.RemoveFreeNotification(AComponent: TComponent); begin RemoveNotification(AComponent); AComponent.RemoveNotification (self); end; function TComponent.GetParentComponent: TComponent; begin Result:=Nil; end; function TComponent.HasParent: Boolean; begin Result:=False; end; procedure TComponent.InsertComponent(AComponent: TComponent); begin AComponent.ValidateContainer(Self); ValidateRename(AComponent,'',AComponent.FName); Insert(AComponent); If csDesigning in FComponentState then AComponent.SetDesigning(true); Notification(AComponent,opInsert); end; procedure TComponent.RemoveComponent(AComponent: TComponent); begin Notification(AComponent,opRemove); Remove(AComponent); Acomponent.Setdesigning(False); ValidateRename(AComponent,AComponent.FName,''); end; procedure TComponent.SetSubComponent(ASubComponent: Boolean); begin if ASubComponent then Include(FComponentStyle, csSubComponent) else Exclude(FComponentStyle, csSubComponent); end; function TComponent.GetEnumerator: TComponentEnumerator; begin Result:=TComponentEnumerator.Create(Self); end; { --------------------------------------------------------------------- TStream ---------------------------------------------------------------------} Resourcestring SStreamInvalidSeek = 'Seek is not implemented for class %s'; SStreamNoReading = 'Stream reading is not implemented for class %s'; SStreamNoWriting = 'Stream writing is not implemented for class %s'; SReadError = 'Could not read data from stream'; SWriteError = 'Could not write data to stream'; SMemoryStreamError = 'Could not allocate memory'; SerrInvalidStreamSize = 'Invalid Stream size'; procedure TStream.ReadNotImplemented; begin raise EStreamError.CreateFmt(SStreamNoReading, [ClassName]); end; procedure TStream.WriteNotImplemented; begin raise EStreamError.CreateFmt(SStreamNoWriting, [ClassName]); end; function TStream.Read(var Buffer: TBytes; Count: Longint): Longint; begin Result:=Read(Buffer,0,Count); end; function TStream.Write(const Buffer: TBytes; Count: Longint): Longint; begin Result:=Self.Write(Buffer,0,Count); end; function TStream.GetPosition: NativeInt; begin Result:=Seek(0,soCurrent); end; procedure TStream.SetPosition(const Pos: NativeInt); begin Seek(pos,soBeginning); end; procedure TStream.SetSize64(const NewSize: NativeInt); begin // Required because can't use overloaded functions in properties SetSize(NewSize); end; function TStream.GetSize: NativeInt; var p : NativeInt; begin p:=Seek(0,soCurrent); GetSize:=Seek(0,soEnd); Seek(p,soBeginning); end; procedure TStream.SetSize(const NewSize: NativeInt); begin if NewSize<0 then Raise EStreamError.Create(SerrInvalidStreamSize); end; procedure TStream.Discard(const Count: NativeInt); const CSmallSize =255; CLargeMaxBuffer =32*1024; // 32 KiB var Buffer: TBytes; begin if Count=0 then Exit; if (Count<=CSmallSize) then begin SetLength(Buffer,CSmallSize); ReadBuffer(Buffer,Count) end else DiscardLarge(Count,CLargeMaxBuffer); end; procedure TStream.DiscardLarge(Count: NativeInt; const MaxBufferSize: Longint); var Buffer: TBytes; begin if Count=0 then Exit; if Count>MaxBufferSize then SetLength(Buffer,MaxBufferSize) else SetLength(Buffer,Count); while (Count>=Length(Buffer)) do begin ReadBuffer(Buffer,Length(Buffer)); Dec(Count,Length(Buffer)); end; if Count>0 then ReadBuffer(Buffer,Count); end; procedure TStream.InvalidSeek; begin raise EStreamError.CreateFmt(SStreamInvalidSeek, [ClassName]); end; procedure TStream.FakeSeekForward(Offset: NativeInt; const Origin: TSeekOrigin; const Pos: NativeInt); begin if Origin=soBeginning then Dec(Offset,Pos); if (Offset<0) or (Origin=soEnd) then InvalidSeek; if Offset>0 then Discard(Offset); end; function TStream.ReadData({var} Buffer: TBytes; Count: NativeInt): NativeInt; begin Result:=Read(Buffer,0,Count); end; function TStream.ReadMaxSizeData(Buffer : TBytes; aSize,aCount : NativeInt) : NativeInt; Var CP : NativeInt; begin if aCount<=aSize then Result:=read(Buffer,aCount) else begin Result:=Read(Buffer,aSize); CP:=Position; Result:=Result+Seek(aCount-aSize,soCurrent)-CP; end end; function TStream.WriteMaxSizeData(const Buffer : TBytes; aSize,aCount : NativeInt) : NativeInt; Var CP : NativeInt; begin if aCount<=aSize then Result:=Self.Write(Buffer,aCount) else begin Result:=Self.Write(Buffer,aSize); CP:=Position; Result:=Result+Seek(aCount-aSize,soCurrent)-CP; end end; procedure TStream.WriteExactSizeData(const Buffer : TBytes; aSize, aCount: NativeInt); begin // Embarcadero docs mentions no exception. Does not seem very logical WriteMaxSizeData(Buffer,aSize,ACount); end; procedure TStream.ReadExactSizeData(Buffer : TBytes; aSize, aCount: NativeInt); begin if ReadMaxSizeData(Buffer,aSize,ACount)<>aCount then Raise EReadError.Create(SReadError); end; function TStream.ReadData(var Buffer: Boolean): NativeInt; Var B : Byte; begin Result:=ReadData(B,1); if Result=1 then Buffer:=B<>0; end; function TStream.ReadData(var Buffer: Boolean; Count: NativeInt): NativeInt; Var B : TBytes; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,1,Count); if Result>0 then Buffer:=B[0]<>0 end; function TStream.ReadData(var Buffer: WideChar): NativeInt; begin Result:=ReadData(Buffer,2); end; function TStream.ReadData(var Buffer: WideChar; Count: NativeInt): NativeInt; Var W : Word; begin Result:=ReadData(W,Count); if Result=2 then Buffer:=WideChar(W); end; function TStream.ReadData(var Buffer: Int8): NativeInt; begin Result:=ReadData(Buffer,1); end; Function TStream.MakeInt(B : TBytes; aSize : Integer; Signed : Boolean) : NativeInt; Var Mem : TJSArrayBuffer; A : TJSUInt8Array; D : TJSDataView; isLittle : Boolean; begin IsLittle:=(Endian=TEndian.Little); Mem:=TJSArrayBuffer.New(Length(B)); A:=TJSUInt8Array.new(Mem); A._set(B); D:=TJSDataView.New(Mem); if Signed then case aSize of 1 : Result:=D.getInt8(0); 2 : Result:=D.getInt16(0,IsLittle); 4 : Result:=D.getInt32(0,IsLittle); // Todo : fix sign 8 : Result:=Round(D.getFloat64(0,IsLittle)); end else case aSize of 1 : Result:=D.getUInt8(0); 2 : Result:=D.getUInt16(0,IsLittle); 4 : Result:=D.getUInt32(0,IsLittle); 8 : Result:=Round(D.getFloat64(0,IsLittle)); end end; function TStream.MakeBytes(B: NativeInt; aSize: Integer; Signed: Boolean): TBytes; Var Mem : TJSArrayBuffer; A : TJSUInt8Array; D : TJSDataView; isLittle : Boolean; begin IsLittle:=(Endian=TEndian.Little); Mem:=TJSArrayBuffer.New(aSize); D:=TJSDataView.New(Mem); if Signed then case aSize of 1 : D.setInt8(0,B); 2 : D.setInt16(0,B,IsLittle); 4 : D.setInt32(0,B,IsLittle); 8 : D.setFloat64(0,B,IsLittle); end else case aSize of 1 : D.SetUInt8(0,B); 2 : D.SetUInt16(0,B,IsLittle); 4 : D.SetUInt32(0,B,IsLittle); 8 : D.setFloat64(0,B,IsLittle); end; SetLength(Result,aSize); A:=TJSUInt8Array.new(Mem); Result:=TMemoryStream.MemoryToBytes(A); end; function TStream.ReadData(var Buffer: Int8; Count: NativeInt): NativeInt; Var B : TBytes; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,1,Count); if Result>=1 then Buffer:=MakeInt(B,1,True); end; function TStream.ReadData(var Buffer: UInt8): NativeInt; begin Result:=ReadData(Buffer,1); end; function TStream.ReadData(var Buffer: UInt8; Count: NativeInt): NativeInt; Var B : TBytes; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,1,Count); if Result>=1 then Buffer:=MakeInt(B,1,False); end; function TStream.ReadData(var Buffer: Int16): NativeInt; begin Result:=ReadData(Buffer,2); end; function TStream.ReadData(var Buffer: Int16; Count: NativeInt): NativeInt; Var B : TBytes; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,2,Count); if Result>=2 then Buffer:=MakeInt(B,2,True); end; function TStream.ReadData(var Buffer: UInt16): NativeInt; begin Result:=ReadData(Buffer,2); end; function TStream.ReadData(var Buffer: UInt16; Count: NativeInt): NativeInt; Var B : TBytes; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,2,Count); if Result>=2 then Buffer:=MakeInt(B,2,False); end; function TStream.ReadData(var Buffer: Int32): NativeInt; begin Result:=ReadData(Buffer,4); end; function TStream.ReadData(var Buffer: Int32; Count: NativeInt): NativeInt; Var B : TBytes; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,4,Count); if Result>=4 then Buffer:=MakeInt(B,4,True); end; function TStream.ReadData(var Buffer: UInt32): NativeInt; begin Result:=ReadData(Buffer,4); end; function TStream.ReadData(var Buffer: UInt32; Count: NativeInt): NativeInt; Var B : TBytes; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,4,Count); if Result>=4 then Buffer:=MakeInt(B,4,False); end; function TStream.ReadData(var Buffer: NativeInt): NativeInt; begin Result:=ReadData(Buffer,8); end; function TStream.ReadData(var Buffer: NativeInt; Count: NativeInt): NativeInt; Var B : TBytes; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,8,8); if Result>=8 then Buffer:=MakeInt(B,8,True); end; function TStream.ReadData(var Buffer: NativeLargeUInt): NativeInt; begin Result:=ReadData(Buffer,8); end; function TStream.ReadData(var Buffer: NativeLargeUInt; Count: NativeInt): NativeInt; Var B : TBytes; B1 : Integer; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,4,4); if Result>=4 then begin B1:=MakeInt(B,4,False); Result:=Result+ReadMaxSizeData(B,4,4); Buffer:=MakeInt(B,4,False); Buffer:=(Buffer shl 32) or B1; end; end; function TStream.ReadData(var Buffer: Double): NativeInt; begin Result:=ReadData(Buffer,8); end; function TStream.ReadData(var Buffer: Double; Count: NativeInt): NativeInt; Var B : TBytes; Mem : TJSArrayBuffer; A : TJSUInt8Array; D : TJSDataView; begin SetLength(B,Count); Result:=ReadMaxSizeData(B,8,Count); if Result>=8 then begin Mem:=TJSArrayBuffer.New(8); A:=TJSUInt8Array.new(Mem); A._set(B); D:=TJSDataView.New(Mem); Buffer:=D.getFloat64(0); end; end; procedure TStream.ReadBuffer(var Buffer: TBytes; Count: NativeInt); begin ReadBuffer(Buffer,0,Count); end; procedure TStream.ReadBuffer(var Buffer: TBytes; Offset, Count: NativeInt); begin if Read(Buffer,OffSet,Count)<>Count then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: Boolean); begin ReadBufferData(Buffer,1); end; procedure TStream.ReadBufferData(var Buffer: Boolean; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: WideChar); begin ReadBufferData(Buffer,2); end; procedure TStream.ReadBufferData(var Buffer: WideChar; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: Int8); begin ReadBufferData(Buffer,1); end; procedure TStream.ReadBufferData(var Buffer: Int8; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: UInt8); begin ReadBufferData(Buffer,1); end; procedure TStream.ReadBufferData(var Buffer: UInt8; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: Int16); begin ReadBufferData(Buffer,2); end; procedure TStream.ReadBufferData(var Buffer: Int16; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: UInt16); begin ReadBufferData(Buffer,2); end; procedure TStream.ReadBufferData(var Buffer: UInt16; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: Int32); begin ReadBufferData(Buffer,4); end; procedure TStream.ReadBufferData(var Buffer: Int32; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: UInt32); begin ReadBufferData(Buffer,4); end; procedure TStream.ReadBufferData(var Buffer: UInt32; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: NativeLargeInt); begin ReadBufferData(Buffer,8) end; procedure TStream.ReadBufferData(var Buffer: NativeLargeInt; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: NativeLargeUInt); begin ReadBufferData(Buffer,8); end; procedure TStream.ReadBufferData(var Buffer: NativeLargeUInt; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.ReadBufferData(var Buffer: Double); begin ReadBufferData(Buffer,8); end; procedure TStream.ReadBufferData(var Buffer: Double; Count: NativeInt); begin if (ReadData(Buffer,Count)<>Count) then Raise EStreamError.Create(SReadError); end; procedure TStream.WriteBuffer(const Buffer: TBytes; Count: NativeInt); begin WriteBuffer(Buffer,0,Count); end; procedure TStream.WriteBuffer(const Buffer: TBytes; Offset, Count: NativeInt); begin if Self.Write(Buffer,Offset,Count)<>Count then Raise EStreamError.Create(SWriteError); end; function TStream.WriteData(const Buffer: TBytes; Count: NativeInt): NativeInt; begin Result:=Self.Write(Buffer, 0, Count); end; function TStream.WriteData(const Buffer: Boolean): NativeInt; begin Result:=WriteData(Buffer,1); end; function TStream.WriteData(const Buffer: Boolean; Count: NativeInt): NativeInt; Var B : Int8; begin B:=Ord(Buffer); Result:=WriteData(B,Count); end; function TStream.WriteData(const Buffer: WideChar): NativeInt; begin Result:=WriteData(Buffer,2); end; function TStream.WriteData(const Buffer: WideChar; Count: NativeInt): NativeInt; Var U : UInt16; begin U:=Ord(Buffer); Result:=WriteData(U,Count); end; function TStream.WriteData(const Buffer: Int8): NativeInt; begin Result:=WriteData(Buffer,1); end; function TStream.WriteData(const Buffer: Int8; Count: NativeInt): NativeInt; begin Result:=WriteMaxSizeData(MakeBytes(Buffer,1,True),1,Count); end; function TStream.WriteData(const Buffer: UInt8): NativeInt; begin Result:=WriteData(Buffer,1); end; function TStream.WriteData(const Buffer: UInt8; Count: NativeInt): NativeInt; begin Result:=WriteMaxSizeData(MakeBytes(Buffer,1,False),1,Count); end; function TStream.WriteData(const Buffer: Int16): NativeInt; begin Result:=WriteData(Buffer,2); end; function TStream.WriteData(const Buffer: Int16; Count: NativeInt): NativeInt; begin Result:=WriteMaxSizeData(MakeBytes(Buffer,2,True),2,Count); end; function TStream.WriteData(const Buffer: UInt16): NativeInt; begin Result:=WriteData(Buffer,2); end; function TStream.WriteData(const Buffer: UInt16; Count: NativeInt): NativeInt; begin Result:=WriteMaxSizeData(MakeBytes(Buffer,2,True),2,Count); end; function TStream.WriteData(const Buffer: Int32): NativeInt; begin Result:=WriteData(Buffer,4); end; function TStream.WriteData(const Buffer: Int32; Count: NativeInt): NativeInt; begin Result:=WriteMaxSizeData(MakeBytes(Buffer,4,True),4,Count); end; function TStream.WriteData(const Buffer: UInt32): NativeInt; begin Result:=WriteData(Buffer,4); end; function TStream.WriteData(const Buffer: UInt32; Count: NativeInt): NativeInt; begin Result:=WriteMaxSizeData(MakeBytes(Buffer,4,False),4,Count); end; function TStream.WriteData(const Buffer: NativeLargeInt): NativeInt; begin Result:=WriteData(Buffer,8); end; function TStream.WriteData(const Buffer: NativeLargeInt; Count: NativeInt): NativeInt; begin Result:=WriteMaxSizeData(MakeBytes(Buffer,8,True),8,Count); end; function TStream.WriteData(const Buffer: NativeLargeUInt): NativeInt; begin Result:=WriteData(Buffer,8); end; function TStream.WriteData(const Buffer: NativeLargeUInt; Count: NativeInt): NativeInt; begin Result:=WriteMaxSizeData(MakeBytes(Buffer,8,False),8,Count); end; function TStream.WriteData(const Buffer: Double): NativeInt; begin Result:=WriteData(Buffer,8); end; function TStream.WriteData(const Buffer: Double; Count: NativeInt): NativeInt; Var Mem : TJSArrayBuffer; A : TJSUint8array; D : TJSDataview; B : TBytes; I : Integer; begin Mem:=TJSArrayBuffer.New(8); D:=TJSDataView.new(Mem); D.setFloat64(0,Buffer); SetLength(B,8); A:=TJSUint8array.New(Mem); For I:=0 to 7 do B[i]:=A[i]; Result:=WriteMaxSizeData(B,8,Count); end; procedure TStream.WriteBufferData(Buffer: Int32); begin WriteBufferData(Buffer,4); end; procedure TStream.WriteBufferData(Buffer: Int32; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: Boolean); begin WriteBufferData(Buffer,1); end; procedure TStream.WriteBufferData(Buffer: Boolean; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: WideChar); begin WriteBufferData(Buffer,2); end; procedure TStream.WriteBufferData(Buffer: WideChar; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: Int8); begin WriteBufferData(Buffer,1); end; procedure TStream.WriteBufferData(Buffer: Int8; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: UInt8); begin WriteBufferData(Buffer,1); end; procedure TStream.WriteBufferData(Buffer: UInt8; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: Int16); begin WriteBufferData(Buffer,2); end; procedure TStream.WriteBufferData(Buffer: Int16; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: UInt16); begin WriteBufferData(Buffer,2); end; procedure TStream.WriteBufferData(Buffer: UInt16; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: UInt32); begin WriteBufferData(Buffer,4); end; procedure TStream.WriteBufferData(Buffer: UInt32; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: NativeInt); begin WriteBufferData(Buffer,8); end; procedure TStream.WriteBufferData(Buffer: NativeInt; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: NativeLargeUInt); begin WriteBufferData(Buffer,8); end; procedure TStream.WriteBufferData(Buffer: NativeLargeUInt; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; procedure TStream.WriteBufferData(Buffer: Double); begin WriteBufferData(Buffer,8); end; procedure TStream.WriteBufferData(Buffer: Double; Count: NativeInt); begin if (WriteData(Buffer,Count)<>Count) then Raise EStreamError.Create(SWriteError); end; function TStream.CopyFrom(Source: TStream; Count: NativeInt): NativeInt; var Buffer: TBytes; BufferSize, i: LongInt; const MaxSize = $20000; begin Result:=0; if Count=0 then Source.Position:=0; // This WILL fail for non-seekable streams... BufferSize:=MaxSize; if (Count>0) and (Count<BufferSize) then BufferSize:=Count; // do not allocate more than needed SetLength(Buffer,BufferSize); if Count=0 then repeat i:=Source.Read(Buffer,BufferSize); if i>0 then WriteBuffer(Buffer,i); Inc(Result,i); until i<BufferSize else while Count>0 do begin if Count>BufferSize then i:=BufferSize else i:=Count; Source.ReadBuffer(Buffer,i); WriteBuffer(Buffer,i); Dec(count,i); Inc(Result,i); end; end; function TStream.ReadComponent(Instance: TComponent): TComponent; var Reader: TReader; begin Reader := TReader.Create(Self); try Result := Reader.ReadRootComponent(Instance); finally Reader.Free; end; end; function TStream.ReadComponentRes(Instance: TComponent): TComponent; begin ReadResHeader; Result := ReadComponent(Instance); end; procedure TStream.WriteComponent(Instance: TComponent); begin WriteDescendent(Instance, nil); end; procedure TStream.WriteComponentRes(const ResName: string; Instance: TComponent); begin WriteDescendentRes(ResName, Instance, nil); end; procedure TStream.WriteDescendent(Instance, Ancestor: TComponent); var Driver : TAbstractObjectWriter; Writer : TWriter; begin Driver := TBinaryObjectWriter.Create(Self); Try Writer := TWriter.Create(Driver); Try Writer.WriteDescendent(Instance, Ancestor); Finally Writer.Destroy; end; Finally Driver.Free; end; end; procedure TStream.WriteDescendentRes(const ResName: string; Instance, Ancestor: TComponent); var FixupInfo: Longint; begin { Write a resource header } WriteResourceHeader(ResName, FixupInfo); { Write the instance itself } WriteDescendent(Instance, Ancestor); { Insert the correct resource size into the resource header } FixupResourceHeader(FixupInfo); end; procedure TStream.WriteResourceHeader(const ResName: string; {!!!: out} var FixupInfo: Longint); var ResType, Flags : word; B : Byte; I : Integer; begin ResType:=Word($000A); Flags:=Word($1030); { Note: This is a Windows 16 bit resource } { Numeric resource type } WriteByte($ff); { Application defined data } WriteWord(ResType); { write the name as asciiz } For I:=1 to Length(ResName) do begin B:=Ord(ResName[i]); WriteByte(B); end; WriteByte(0); { Movable, Pure and Discardable } WriteWord(Flags); { Placeholder for the resource size } WriteDWord(0); { Return current stream position so that the resource size can be inserted later } FixupInfo := Position; end; procedure TStream.FixupResourceHeader(FixupInfo: Longint); var ResSize,TmpResSize : Longint; begin ResSize := Position - FixupInfo; TmpResSize := longword(ResSize); { Insert the correct resource size into the placeholder written by WriteResourceHeader } Position := FixupInfo - 4; WriteDWord(TmpResSize); { Seek back to the end of the resource } Position := FixupInfo + ResSize; end; procedure TStream.ReadResHeader; var ResType, Flags : word; begin try { Note: This is a Windows 16 bit resource } { application specific resource ? } if ReadByte<>$ff then raise EInvalidImage.Create(SInvalidImage); ResType:=ReadWord; if ResType<>$000a then raise EInvalidImage.Create(SInvalidImage); { read name } while ReadByte<>0 do ; { check the access specifier } Flags:=ReadWord; if Flags<>$1030 then raise EInvalidImage.Create(SInvalidImage); { ignore the size } ReadDWord; except on EInvalidImage do raise; else raise EInvalidImage.create(SInvalidImage); end; end; function TStream.ReadByte : Byte; begin ReadBufferData(Result,1); end; function TStream.ReadWord : Word; begin ReadBufferData(Result,2); end; function TStream.ReadDWord : Cardinal; begin ReadBufferData(Result,4); end; function TStream.ReadQWord: NativeLargeUInt; begin ReadBufferData(Result,8); end; procedure TStream.WriteByte(b : Byte); begin WriteBufferData(b,1); end; procedure TStream.WriteWord(w : Word); begin WriteBufferData(W,2); end; procedure TStream.WriteDWord(d : Cardinal); begin WriteBufferData(d,4); end; procedure TStream.WriteQWord(q: NativeLargeUInt); begin WriteBufferData(q,8); end; {****************************************************************************} {* TCustomMemoryStream *} {****************************************************************************} procedure TCustomMemoryStream.SetPointer(Ptr: TJSArrayBuffer; ASize: PtrInt); begin FMemory:=Ptr; FSize:=ASize; FDataView:=Nil; FDataArray:=Nil; end; class function TCustomMemoryStream.MemoryToBytes(Mem: TJSArrayBuffer): TBytes; begin Result:=MemoryToBytes(TJSUint8Array.New(Mem)); end; class function TCustomMemoryStream.MemoryToBytes(Mem: TJSUint8Array): TBytes; Var I : Integer; begin // This must be improved, but needs some asm or TJSFunction.call() to implement answers in // https://stackoverflow.com/questions/29676635/convert-uint8array-to-array-in-javascript for i:=0 to mem.length-1 do Result[i]:=Mem[i]; end; class function TCustomMemoryStream.BytesToMemory(aBytes: TBytes): TJSArrayBuffer; Var a : TJSUint8Array; begin Result:=TJSArrayBuffer.new(Length(aBytes)); A:=TJSUint8Array.New(Result); A._set(aBytes); end; function TCustomMemoryStream.GetDataArray: TJSUint8Array; begin if FDataArray=Nil then FDataArray:=TJSUint8Array.new(Memory); Result:=FDataArray; end; function TCustomMemoryStream.GetDataView: TJSDataview; begin if FDataView=Nil then FDataView:=TJSDataView.New(Memory); Result:=FDataView; end; function TCustomMemoryStream.GetSize: NativeInt; begin Result:=FSize; end; function TCustomMemoryStream.GetPosition: NativeInt; begin Result:=FPosition; end; function TCustomMemoryStream.Read(Buffer: TBytes; Offset, Count: LongInt): LongInt; Var I,Src,Dest : Integer; begin Result:=0; If (FSize>0) and (FPosition<Fsize) and (FPosition>=0) then begin Result:=Count; If (Result>(FSize-FPosition)) then Result:=(FSize-FPosition); Src:=FPosition; Dest:=Offset; I:=0; While I<Result do begin Buffer[Dest]:=DataView.getUint8(Src); inc(Src); inc(Dest); inc(I); end; FPosition:=Fposition+Result; end; end; function TCustomMemoryStream.Seek(const Offset: NativeInt; Origin: TSeekOrigin): NativeInt; begin Case Origin of soBeginning : FPosition:=Offset; soEnd : FPosition:=FSize+Offset; soCurrent : FPosition:=FPosition+Offset; end; if SizeBoundsSeek and (FPosition>FSize) then FPosition:=FSize; Result:=FPosition; {$IFDEF DEBUG} if Result < 0 then raise Exception.Create('TCustomMemoryStream'); {$ENDIF} end; procedure TCustomMemoryStream.SaveToStream(Stream: TStream); begin if FSize>0 then Stream.WriteBuffer(TMemoryStream.MemoryToBytes(Memory),FSize); end; procedure TCustomMemoryStream.LoadFromURL(const aURL: String; Async: Boolean; OnLoaded: TNotifyEventRef; OnError: TStringNotifyEventRef = Nil); procedure DoLoaded(const abytes : TJSArrayBuffer); begin SetPointer(aBytes,aBytes.byteLength); if Assigned(OnLoaded) then OnLoaded(Self); end; procedure DoError(const AError : String); begin if Assigned(OnError) then OnError(Self,aError) else Raise EInOutError.Create('Failed to load from URL:'+aError); end; begin CheckLoadHelper; GlobalLoadHelper.LoadBytes(aURL,aSync,@DoLoaded,@DoError); end; procedure TCustomMemoryStream.LoadFromFile(const aFileName: String; const OnLoaded: TProc; const AError: TProcString); begin LoadFromURL(aFileName,False, Procedure (Sender : TObject) begin If Assigned(OnLoaded) then OnLoaded end, Procedure (Sender : TObject; Const ErrorMsg : String) begin if Assigned(aError) then aError(ErrorMsg) end); end; {****************************************************************************} {* TMemoryStream *} {****************************************************************************} Const TMSGrow = 4096; { Use 4k blocks. } procedure TMemoryStream.SetCapacity(NewCapacity: PtrInt); begin SetPointer (Realloc(NewCapacity),Fsize); FCapacity:=NewCapacity; end; function TMemoryStream.Realloc(var NewCapacity: PtrInt): TJSArrayBuffer; Var GC : PtrInt; DestView : TJSUInt8array; begin If NewCapacity<0 Then NewCapacity:=0 else begin GC:=FCapacity + (FCapacity div 4); // if growing, grow at least a quarter if (NewCapacity>FCapacity) and (NewCapacity < GC) then NewCapacity := GC; // round off to block size. NewCapacity := (NewCapacity + (TMSGrow-1)) and not (TMSGROW-1); end; // Only now check ! If NewCapacity=FCapacity then Result:=FMemory else if NewCapacity=0 then Result:=Nil else begin // New buffer Result:=TJSArrayBuffer.New(NewCapacity); If (Result=Nil) then Raise EStreamError.Create(SMemoryStreamError); // Transfer DestView:=TJSUInt8array.New(Result); Destview._Set(Self.DataArray); end; end; destructor TMemoryStream.Destroy; begin Clear; Inherited Destroy; end; procedure TMemoryStream.Clear; begin FSize:=0; FPosition:=0; SetCapacity (0); end; procedure TMemoryStream.LoadFromStream(Stream: TStream); begin Stream.Position:=0; SetSize(Stream.Size); If FSize>0 then Stream.ReadBuffer(MemoryToBytes(FMemory),FSize); end; procedure TMemoryStream.SetSize(const NewSize: NativeInt); begin SetCapacity (NewSize); FSize:=NewSize; IF FPosition>FSize then FPosition:=FSize; end; function TMemoryStream.Write(Const Buffer : TBytes; OffSet, Count: LongInt): LongInt; Var NewPos : PtrInt; begin If (Count=0) or (FPosition<0) then exit(0); NewPos:=FPosition+Count; If NewPos>Fsize then begin IF NewPos>FCapacity then SetCapacity (NewPos); FSize:=Newpos; end; DataArray._set(Copy(Buffer,Offset,Count),FPosition); FPosition:=NewPos; Result:=Count; end; {****************************************************************************} {* TBytesStream *} {****************************************************************************} constructor TBytesStream.Create(const ABytes: TBytes); begin inherited Create; SetPointer(TMemoryStream.BytesToMemory(aBytes),Length(ABytes)); FCapacity:=Length(ABytes); end; function TBytesStream.GetBytes: TBytes; begin Result:=TMemoryStream.MemoryToBytes(Memory); end; { ********************************************************************* * TFiler * *********************************************************************} procedure TFiler.SetRoot(ARoot: TComponent); begin FRoot := ARoot; end; { This file is part of the Free Component Library (FCL) Copyright (c) 1999-2000 by the Free Pascal development team 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. **********************************************************************} {****************************************************************************} {* TBinaryObjectReader *} {****************************************************************************} function TBinaryObjectReader.ReadWord : word; begin FStream.ReadBufferData(Result); end; function TBinaryObjectReader.ReadDWord : longword; begin FStream.ReadBufferData(Result); end; constructor TBinaryObjectReader.Create(Stream: TStream); begin inherited Create; If (Stream=Nil) then Raise EReadError.Create(SEmptyStreamIllegalReader); FStream := Stream; end; function TBinaryObjectReader.ReadValue: TValueType; var b: byte; begin FStream.ReadBufferData(b); Result := TValueType(b); end; function TBinaryObjectReader.NextValue: TValueType; begin Result := ReadValue; { We only 'peek' at the next value, so seek back to unget the read value: } FStream.Seek(-1,soCurrent); end; procedure TBinaryObjectReader.BeginRootComponent; begin { Read filer signature } ReadSignature; end; procedure TBinaryObjectReader.BeginComponent(var Flags: TFilerFlags; var AChildPos: Integer; var CompClassName, CompName: String); var Prefix: Byte; ValueType: TValueType; begin { Every component can start with a special prefix: } Flags := []; if (Byte(NextValue) and $f0) = $f0 then begin Prefix := Byte(ReadValue); Flags:=[]; if (Prefix and $01)<>0 then Include(Flags,ffInherited); if (Prefix and $02)<>0 then Include(Flags,ffChildPos); if (Prefix and $04)<>0 then Include(Flags,ffInline); if ffChildPos in Flags then begin ValueType := ReadValue; case ValueType of vaInt8: AChildPos := ReadInt8; vaInt16: AChildPos := ReadInt16; vaInt32: AChildPos := ReadInt32; vaNativeInt: AChildPos := ReadNativeInt; else raise EReadError.Create(SInvalidPropertyValue); end; end; end; CompClassName := ReadStr; CompName := ReadStr; end; function TBinaryObjectReader.BeginProperty: String; begin Result := ReadStr; end; procedure TBinaryObjectReader.Read(var Buffer: TBytes; Count: Longint); begin FStream.Read(Buffer,Count); end; procedure TBinaryObjectReader.ReadBinary(const DestData: TMemoryStream); var BinSize: LongInt; begin BinSize:=LongInt(ReadDWord); DestData.Size := BinSize; DestData.CopyFrom(FStream,BinSize); end; function TBinaryObjectReader.ReadFloat: Extended; begin FStream.ReadBufferData(Result); end; function TBinaryObjectReader.ReadCurrency: Currency; begin Result:=ReadFloat; end; function TBinaryObjectReader.ReadIdent(ValueType: TValueType): String; var i: Byte; c : Char; begin case ValueType of vaIdent: begin FStream.ReadBufferData(i); SetLength(Result,i); For I:=1 to Length(Result) do begin FStream.ReadBufferData(C); Result[I]:=C; end; end; vaNil: Result := 'nil'; vaFalse: Result := 'False'; vaTrue: Result := 'True'; vaNull: Result := 'Null'; end; end; function TBinaryObjectReader.ReadInt8: ShortInt; begin FStream.ReadBufferData(Result); end; function TBinaryObjectReader.ReadInt16: SmallInt; begin FStream.ReadBufferData(Result); end; function TBinaryObjectReader.ReadInt32: LongInt; begin FStream.ReadBufferData(Result); end; function TBinaryObjectReader.ReadNativeInt : NativeInt; begin FStream.ReadBufferData(Result); end; function TBinaryObjectReader.ReadSet(EnumType: TTypeInfoEnum): Integer; var Name: String; Value: Integer; begin try Result := 0; while True do begin Name := ReadStr; if Length(Name) = 0 then break; Value:=EnumType.EnumType.NameToInt[Name]; if Value=-1 then raise EReadError.Create(SInvalidPropertyValue); Result:=Result or (1 shl Value); end; except SkipSetBody; raise; end; end; Const // Integer version of 4 chars 'TPF0' FilerSignatureInt = 809914452; procedure TBinaryObjectReader.ReadSignature; var Signature: LongInt; begin FStream.ReadBufferData(Signature); if Signature <> FilerSignatureInt then raise EReadError.Create(SInvalidImage); end; function TBinaryObjectReader.ReadStr: String; var l,i: Byte; c : Char; begin FStream.ReadBufferData(L); SetLength(Result,L); For I:=1 to L do begin FStream.ReadBufferData(C); Result[i]:=C; end; end; function TBinaryObjectReader.ReadString(StringType: TValueType): String; var i: Integer; C : Char; begin Result:=''; if StringType<>vaString then Raise EFilerError.Create('Invalid string type passed to ReadString'); i:=ReadDWord; SetLength(Result, i); for I:=1 to Length(Result) do begin FStream.ReadbufferData(C); Result[i]:=C; end; end; function TBinaryObjectReader.ReadWideString: WideString; begin Result:=ReadString(vaWString); end; function TBinaryObjectReader.ReadUnicodeString: UnicodeString; begin Result:=ReadString(vaWString); end; procedure TBinaryObjectReader.SkipComponent(SkipComponentInfos: Boolean); var Flags: TFilerFlags; Dummy: Integer; CompClassName, CompName: String; begin if SkipComponentInfos then { Skip prefix, component class name and component object name } BeginComponent(Flags, Dummy, CompClassName, CompName); { Skip properties } while NextValue <> vaNull do SkipProperty; ReadValue; { Skip children } while NextValue <> vaNull do SkipComponent(True); ReadValue; end; procedure TBinaryObjectReader.SkipValue; procedure SkipBytes(Count: LongInt); var Dummy: TBytes; SkipNow: Integer; begin while Count > 0 do begin if Count > 1024 then SkipNow := 1024 else SkipNow := Count; SetLength(Dummy,SkipNow); Read(Dummy, SkipNow); Dec(Count, SkipNow); end; end; var Count: LongInt; begin case ReadValue of vaNull, vaFalse, vaTrue, vaNil: ; vaList: begin while NextValue <> vaNull do SkipValue; ReadValue; end; vaInt8: SkipBytes(1); vaInt16: SkipBytes(2); vaInt32: SkipBytes(4); vaInt64, vaDouble: SkipBytes(8); vaString, vaIdent: ReadStr; vaBinary: begin Count:=LongInt(ReadDWord); SkipBytes(Count); end; vaSet: SkipSetBody; vaCollection: begin while NextValue <> vaNull do begin { Skip the order value if present } if NextValue in [vaInt8, vaInt16, vaInt32] then SkipValue; SkipBytes(1); while NextValue <> vaNull do SkipProperty; ReadValue; end; ReadValue; end; end; end; { private methods } procedure TBinaryObjectReader.SkipProperty; begin { Skip property name, then the property value } ReadStr; SkipValue; end; procedure TBinaryObjectReader.SkipSetBody; begin while Length(ReadStr) > 0 do; end; // Quadruple representing an unresolved component property. Type { TUnresolvedReference } TUnresolvedReference = class(TlinkedListItem) Private FRoot: TComponent; // Root component when streaming FPropInfo: TTypeMemberProperty; // Property to set. FGlobal, // Global component. FRelative : string; // Path relative to global component. Function Resolve(Instance : TPersistent) : Boolean; // Resolve this reference Function RootMatches(ARoot : TComponent) : Boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} // True if Froot matches or ARoot is nil. Function NextRef : TUnresolvedReference; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} end; TLocalUnResolvedReference = class(TUnresolvedReference) Finstance : TPersistent; end; // Linked list of TPersistent items that have unresolved properties. { TUnResolvedInstance } TUnResolvedInstance = Class(TLinkedListItem) Public Instance : TPersistent; // Instance we're handling unresolveds for FUnresolved : TLinkedList; // The list Destructor Destroy; override; Function AddReference(ARoot : TComponent; APropInfo : TTypeMemberProperty; AGlobal,ARelative : String) : TUnresolvedReference; Function RootUnresolved : TUnresolvedReference; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} // Return root element in list. Function ResolveReferences : Boolean; // Return true if all unresolveds were resolved. end; // Builds a list of TUnResolvedInstances, removes them from global list on free. TBuildListVisitor = Class(TLinkedListVisitor) Private List : TFPList; Public Procedure Add(Item : TlinkedListItem); // Add TUnResolvedInstance item to list. Create list if needed Destructor Destroy; override; // All elements in list (if any) are removed from the global list. end; // Visitor used to try and resolve instances in the global list TResolveReferenceVisitor = Class(TBuildListVisitor) Function Visit(Item : TLinkedListItem) : Boolean; override; end; // Visitor used to remove all references to a certain component. TRemoveReferenceVisitor = Class(TBuildListVisitor) Private FRef : String; FRoot : TComponent; Public Constructor Create(ARoot : TComponent;Const ARef : String); Function Visit(Item : TLinkedListItem) : Boolean; override; end; // Visitor used to collect reference names. TReferenceNamesVisitor = Class(TLinkedListVisitor) Private FList : TStrings; FRoot : TComponent; Public Function Visit(Item : TLinkedListItem) : Boolean; override; Constructor Create(ARoot : TComponent;AList : TStrings); end; // Visitor used to collect instance names. TReferenceInstancesVisitor = Class(TLinkedListVisitor) Private FList : TStrings; FRef : String; FRoot : TComponent; Public Function Visit(Item : TLinkedListItem) : Boolean; override; Constructor Create(ARoot : TComponent;Const ARef : String; AList : TStrings); end; // Visitor used to redirect links to another root component. TRedirectReferenceVisitor = Class(TLinkedListVisitor) Private FOld, FNew : String; FRoot : TComponent; Public Function Visit(Item : TLinkedListItem) : Boolean; override; Constructor Create(ARoot : TComponent;Const AOld,ANew : String); end; var NeedResolving : TLinkedList; // Add an instance to the global list of instances which need resolving. Function FindUnresolvedInstance(AInstance: TPersistent) : TUnResolvedInstance; begin Result:=Nil; {$ifdef FPC_HAS_FEATURE_THREADING} EnterCriticalSection(ResolveSection); Try {$endif} If Assigned(NeedResolving) then begin Result:=TUnResolvedInstance(NeedResolving.Root); While (Result<>Nil) and (Result.Instance<>AInstance) do Result:=TUnResolvedInstance(Result.Next); end; {$ifdef FPC_HAS_FEATURE_THREADING} finally LeaveCriticalSection(ResolveSection); end; {$endif} end; Function AddtoResolveList(AInstance: TPersistent) : TUnResolvedInstance; begin Result:=FindUnresolvedInstance(AInstance); If (Result=Nil) then begin {$ifdef FPC_HAS_FEATURE_THREADING} EnterCriticalSection(ResolveSection); Try {$endif} If not Assigned(NeedResolving) then NeedResolving:=TLinkedList.Create(TUnResolvedInstance); Result:=NeedResolving.Add as TUnResolvedInstance; Result.Instance:=AInstance; {$ifdef FPC_HAS_FEATURE_THREADING} finally LeaveCriticalSection(ResolveSection); end; {$endif} end; end; // Walk through the global list of instances to be resolved. Procedure VisitResolveList(V : TLinkedListVisitor); begin {$ifdef FPC_HAS_FEATURE_THREADING} EnterCriticalSection(ResolveSection); Try {$endif} try NeedResolving.Foreach(V); Finally FreeAndNil(V); end; {$ifdef FPC_HAS_FEATURE_THREADING} Finally LeaveCriticalSection(ResolveSection); end; {$endif} end; procedure GlobalFixupReferences; begin If (NeedResolving=Nil) then Exit; {$ifdef FPC_HAS_FEATURE_THREADING} GlobalNameSpace.BeginWrite; try {$endif} VisitResolveList(TResolveReferenceVisitor.Create); {$ifdef FPC_HAS_FEATURE_THREADING} finally GlobalNameSpace.EndWrite; end; {$endif} end; procedure GetFixupReferenceNames(Root: TComponent; Names: TStrings); begin If (NeedResolving=Nil) then Exit; VisitResolveList(TReferenceNamesVisitor.Create(Root,Names)); end; procedure GetFixupInstanceNames(Root: TComponent; const ReferenceRootName: string; Names: TStrings); begin If (NeedResolving=Nil) then Exit; VisitResolveList(TReferenceInstancesVisitor.Create(Root,ReferenceRootName,Names)); end; procedure ObjectBinaryToText(aInput, aOutput: TStream); begin ObjectBinaryToText(aInput,aOutput,oteLFM); end; procedure ObjectBinaryToText(aInput, aOutput: TStream; aEncoding: TObjectTextEncoding); var Conv : TObjectStreamConverter; begin Conv:=TObjectStreamConverter.Create; try Conv.ObjectBinaryToText(aInput,aOutput,aEncoding); finally Conv.Free; end; end; procedure RedirectFixupReferences(Root: TComponent; const OldRootName, NewRootName: string); begin If (NeedResolving=Nil) then Exit; VisitResolveList(TRedirectReferenceVisitor.Create(Root,OldRootName,NewRootName)); end; procedure RemoveFixupReferences(Root: TComponent; const RootName: string); begin If (NeedResolving=Nil) then Exit; VisitResolveList(TRemoveReferenceVisitor.Create(Root,RootName)); end; { TUnresolvedReference } Function TUnresolvedReference.Resolve(Instance : TPersistent) : Boolean; Var C : TComponent; begin C:=FindGlobalComponent(FGlobal); Result:=(C<>Nil); If Result then begin C:=FindNestedComponent(C,FRelative); Result:=C<>Nil; If Result then SetObjectProp(Instance, FPropInfo,C); end; end; Function TUnresolvedReference.RootMatches(ARoot : TComponent) : Boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} begin Result:=(ARoot=Nil) or (ARoot=FRoot); end; Function TUnResolvedReference.NextRef : TUnresolvedReference; begin Result:=TUnresolvedReference(Next); end; { TUnResolvedInstance } destructor TUnResolvedInstance.Destroy; begin FUnresolved.Free; inherited Destroy; end; function TUnResolvedInstance.AddReference(ARoot: TComponent; APropInfo : TTypeMemberProperty; AGlobal, ARelative: String): TUnresolvedReference; begin If (FUnResolved=Nil) then FUnResolved:=TLinkedList.Create(TUnresolvedReference); Result:=FUnResolved.Add as TUnresolvedReference; Result.FGlobal:=AGLobal; Result.FRelative:=ARelative; Result.FPropInfo:=APropInfo; Result.FRoot:=ARoot; end; Function TUnResolvedInstance.RootUnresolved : TUnresolvedReference; begin Result:=Nil; If Assigned(FUnResolved) then Result:=TUnresolvedReference(FUnResolved.Root); end; Function TUnResolvedInstance.ResolveReferences:Boolean; Var R,RN : TUnresolvedReference; begin R:=RootUnResolved; While (R<>Nil) do begin RN:=R.NextRef; If R.Resolve(Self.Instance) then FUnresolved.RemoveItem(R,True); R:=RN; end; Result:=RootUnResolved=Nil; end; { TReferenceNamesVisitor } Constructor TReferenceNamesVisitor.Create(ARoot : TComponent;AList : TStrings); begin FRoot:=ARoot; FList:=AList; end; Function TReferenceNamesVisitor.Visit(Item : TLinkedListItem) : Boolean; Var R : TUnresolvedReference; begin R:=TUnResolvedInstance(Item).RootUnresolved; While (R<>Nil) do begin If R.RootMatches(FRoot) then If (FList.IndexOf(R.FGlobal)=-1) then FList.Add(R.FGlobal); R:=R.NextRef; end; Result:=True; end; { TReferenceInstancesVisitor } Constructor TReferenceInstancesVisitor.Create(ARoot : TComponent; Const ARef : String;AList : TStrings); begin FRoot:=ARoot; FRef:=UpperCase(ARef); FList:=AList; end; Function TReferenceInstancesVisitor.Visit(Item : TLinkedListItem) : Boolean; Var R : TUnresolvedReference; begin R:=TUnResolvedInstance(Item).RootUnresolved; While (R<>Nil) do begin If (FRoot=R.FRoot) and (FRef=UpperCase(R.FGLobal)) Then If Flist.IndexOf(R.FRelative)=-1 then Flist.Add(R.FRelative); R:=R.NextRef; end; Result:=True; end; { TRedirectReferenceVisitor } Constructor TRedirectReferenceVisitor.Create(ARoot : TComponent; Const AOld,ANew : String); begin FRoot:=ARoot; FOld:=UpperCase(AOld); FNew:=ANew; end; Function TRedirectReferenceVisitor.Visit(Item : TLinkedListItem) : Boolean; Var R : TUnresolvedReference; begin R:=TUnResolvedInstance(Item).RootUnresolved; While (R<>Nil) do begin If R.RootMatches(FRoot) and (FOld=UpperCase(R.FGLobal)) Then R.FGlobal:=FNew; R:=R.NextRef; end; Result:=True; end; { TRemoveReferenceVisitor } Constructor TRemoveReferenceVisitor.Create(ARoot : TComponent; Const ARef : String); begin FRoot:=ARoot; FRef:=UpperCase(ARef); end; Function TRemoveReferenceVisitor.Visit(Item : TLinkedListItem) : Boolean; Var I : Integer; UI : TUnResolvedInstance; R : TUnresolvedReference; L : TFPList; begin UI:=TUnResolvedInstance(Item); R:=UI.RootUnresolved; L:=Nil; Try // Collect all matches. While (R<>Nil) do begin If R.RootMatches(FRoot) and ((FRef = '') or (FRef=UpperCase(R.FGLobal))) Then begin If Not Assigned(L) then L:=TFPList.Create; L.Add(R); end; R:=R.NextRef; end; // Remove all matches. IF Assigned(L) then begin For I:=0 to L.Count-1 do UI.FUnresolved.RemoveItem(TLinkedListitem(L[i]),True); end; // If any references are left, leave them. If UI.FUnResolved.Root=Nil then begin If List=Nil then List:=TFPList.Create; List.Add(UI); end; Finally L.Free; end; Result:=True; end; { TBuildListVisitor } Procedure TBuildListVisitor.Add(Item : TlinkedListItem); begin If (List=Nil) then List:=TFPList.Create; List.Add(Item); end; Destructor TBuildListVisitor.Destroy; Var I : Integer; begin If Assigned(List) then For I:=0 to List.Count-1 do NeedResolving.RemoveItem(TLinkedListItem(List[I]),True); FreeAndNil(List); Inherited; end; { TResolveReferenceVisitor } Function TResolveReferenceVisitor.Visit(Item : TLinkedListItem) : Boolean; begin If TUnResolvedInstance(Item).ResolveReferences then Add(Item); Result:=True; end; {****************************************************************************} {* TREADER *} {****************************************************************************} constructor TReader.Create(Stream: TStream); begin inherited Create; If (Stream=Nil) then Raise EReadError.Create(SEmptyStreamIllegalReader); FDriver := CreateDriver(Stream); end; destructor TReader.Destroy; begin FDriver.Free; inherited Destroy; end; procedure TReader.FlushBuffer; begin Driver.FlushBuffer; end; function TReader.CreateDriver(Stream: TStream): TAbstractObjectReader; begin Result := TBinaryObjectReader.Create(Stream); end; procedure TReader.BeginReferences; begin FLoaded := TFpList.Create; end; procedure TReader.CheckValue(Value: TValueType); begin if FDriver.NextValue <> Value then raise EReadError.Create(SInvalidPropertyValue) else FDriver.ReadValue; end; procedure TReader.DefineProperty(const Name: String; AReadData: TReaderProc; WriteData: TWriterProc; HasData: Boolean); begin if Assigned(AReadData) and SameText(Name,FPropName) then begin AReadData(Self); SetLength(FPropName, 0); end else if assigned(WriteData) and HasData then ; end; procedure TReader.DefineBinaryProperty(const Name: String; AReadData, WriteData: TStreamProc; HasData: Boolean); var MemBuffer: TMemoryStream; begin if Assigned(AReadData) and SameText(Name,FPropName) then begin { Check if the next property really is a binary property} if FDriver.NextValue <> vaBinary then begin FDriver.SkipValue; FCanHandleExcepts := True; raise EReadError.Create(SInvalidPropertyValue); end else FDriver.ReadValue; MemBuffer := TMemoryStream.Create; try FDriver.ReadBinary(MemBuffer); FCanHandleExcepts := True; AReadData(MemBuffer); finally MemBuffer.Free; end; SetLength(FPropName, 0); end else if assigned(WriteData) and HasData then ; end; function TReader.EndOfList: Boolean; begin Result := FDriver.NextValue = vaNull; end; procedure TReader.EndReferences; begin FLoaded.Free; FLoaded := nil; end; function TReader.Error(const Message: String): Boolean; begin Result := False; if Assigned(FOnError) then FOnError(Self, Message, Result); end; function TReader.FindMethod(ARoot: TComponent; const AMethodName: String): CodePointer; var ErrorResult: Boolean; begin Result:=nil; if (ARoot=Nil) or (aMethodName='') then exit; Result := ARoot.MethodAddress(AMethodName); ErrorResult := Result = nil; { always give the OnFindMethod callback a chance to locate the method } if Assigned(FOnFindMethod) then FOnFindMethod(Self, AMethodName, Result, ErrorResult); if ErrorResult then raise EReadError.Create(SInvalidPropertyValue); end; procedure TReader.DoFixupReferences; Var R,RN : TLocalUnresolvedReference; G : TUnresolvedInstance; Ref : String; C : TComponent; P : integer; L : TLinkedList; begin If Assigned(FFixups) then begin L:=TLinkedList(FFixups); R:=TLocalUnresolvedReference(L.Root); While (R<>Nil) do begin RN:=TLocalUnresolvedReference(R.Next); Ref:=R.FRelative; If Assigned(FOnReferenceName) then FOnReferenceName(Self,Ref); C:=FindNestedComponent(R.FRoot,Ref); If Assigned(C) then if R.FPropInfo.TypeInfo.Kind = tkInterface then SetInterfaceProp(R.FInstance,R.FPropInfo,C) else SetObjectProp(R.FInstance,R.FPropInfo,C) else begin P:=Pos('.',R.FRelative); If (P<>0) then begin G:=AddToResolveList(R.FInstance); G.Addreference(R.FRoot,R.FPropInfo,Copy(R.FRelative,1,P-1),Copy(R.FRelative,P+1,Length(R.FRelative)-P)); end; end; L.RemoveItem(R,True); R:=RN; end; FreeAndNil(FFixups); end; end; procedure TReader.FixupReferences; var i: Integer; begin DoFixupReferences; GlobalFixupReferences; for i := 0 to FLoaded.Count - 1 do TComponent(FLoaded[I]).Loaded; end; function TReader.NextValue: TValueType; begin Result := FDriver.NextValue; end; procedure TReader.Read(var Buffer : TBytes; Count: LongInt); begin //This should give an exception if read is not implemented (i.e. TTextObjectReader) //but should work with TBinaryObjectReader. Driver.Read(Buffer, Count); end; procedure TReader.PropertyError; begin FDriver.SkipValue; raise EReadError.CreateFmt(SUnknownProperty,[FPropName]); end; function TReader.ReadBoolean: Boolean; var ValueType: TValueType; begin ValueType := FDriver.ReadValue; if ValueType = vaTrue then Result := True else if ValueType = vaFalse then Result := False else raise EReadError.Create(SInvalidPropertyValue); end; function TReader.ReadChar: Char; var s: String; begin s := ReadString; if Length(s) = 1 then Result := s[1] else raise EReadError.Create(SInvalidPropertyValue); end; function TReader.ReadWideChar: WideChar; var W: WideString; begin W := ReadWideString; if Length(W) = 1 then Result := W[1] else raise EReadError.Create(SInvalidPropertyValue); end; function TReader.ReadUnicodeChar: UnicodeChar; var U: UnicodeString; begin U := ReadUnicodeString; if Length(U) = 1 then Result := U[1] else raise EReadError.Create(SInvalidPropertyValue); end; procedure TReader.ReadCollection(Collection: TCollection); var Item: TCollectionItem; begin Collection.BeginUpdate; if not EndOfList then Collection.Clear; while not EndOfList do begin ReadListBegin; Item := Collection.Add; while NextValue<>vaNull do ReadProperty(Item); ReadListEnd; end; Collection.EndUpdate; ReadListEnd; end; function TReader.ReadComponent(Component: TComponent): TComponent; var Flags: TFilerFlags; function Recover(E : Exception; var aComponent: TComponent): Boolean; begin Result := False; if not ((ffInherited in Flags) or Assigned(Component)) then aComponent.Free; aComponent := nil; FDriver.SkipComponent(False); Result := Error(E.Message); end; var CompClassName, Name: String; n, ChildPos: Integer; SavedParent, SavedLookupRoot: TComponent; ComponentClass: TComponentClass; C, NewComponent: TComponent; SubComponents: TList; begin FDriver.BeginComponent(Flags, ChildPos, CompClassName, Name); SavedParent := Parent; SavedLookupRoot := FLookupRoot; SubComponents := nil; try Result := Component; if not Assigned(Result) then try if ffInherited in Flags then begin { Try to locate the existing ancestor component } if Assigned(FLookupRoot) then Result := FLookupRoot.FindComponent(Name) else Result := nil; if not Assigned(Result) then begin if Assigned(FOnAncestorNotFound) then FOnAncestorNotFound(Self, Name, FindComponentClass(CompClassName), Result); if not Assigned(Result) then raise EReadError.CreateFmt(SAncestorNotFound, [Name]); end; Parent := Result.GetParentComponent; if not Assigned(Parent) then Parent := Root; end else begin Result := nil; ComponentClass := FindComponentClass(CompClassName); if Assigned(FOnCreateComponent) then FOnCreateComponent(Self, ComponentClass, Result); if not Assigned(Result) then begin asm NewComponent = Object.create(ComponentClass); NewComponent.$init(); end; if ffInline in Flags then NewComponent.FComponentState := NewComponent.FComponentState + [csLoading, csInline]; NewComponent.Create(Owner); NewComponent.AfterConstruction; { Don't set Result earlier because else we would come in trouble with the exception recover mechanism! (Result should be NIL if an error occurred) } Result := NewComponent; end; Include(Result.FComponentState, csLoading); end; except On E: Exception do if not Recover(E,Result) then raise; end; if Assigned(Result) then try Include(Result.FComponentState, csLoading); { create list of subcomponents and set loading} SubComponents := TList.Create; for n := 0 to Result.ComponentCount - 1 do begin C := Result.Components[n]; if csSubcomponent in C.ComponentStyle then begin SubComponents.Add(C); Include(C.FComponentState, csLoading); end; end; if not (ffInherited in Flags) then try Result.SetParentComponent(Parent); if Assigned(FOnSetName) then FOnSetName(Self, Result, Name); Result.Name := Name; if FindGlobalComponent(Name) = Result then Include(Result.FComponentState, csInline); except On E : Exception do if not Recover(E,Result) then raise; end; if not Assigned(Result) then exit; if csInline in Result.ComponentState then FLookupRoot := Result; { Read the component state } Include(Result.FComponentState, csReading); for n := 0 to Subcomponents.Count - 1 do Include(TComponent(Subcomponents[n]).FComponentState, csReading); Result.ReadState(Self); Exclude(Result.FComponentState, csReading); for n := 0 to Subcomponents.Count - 1 do Exclude(TComponent(Subcomponents[n]).FComponentState, csReading); if ffChildPos in Flags then Parent.SetChildOrder(Result, ChildPos); { Add component to list of loaded components, if necessary } if (not ((ffInherited in Flags) or (csInline in Result.ComponentState))) or (FLoaded.IndexOf(Result) < 0) then begin for n := 0 to Subcomponents.Count - 1 do FLoaded.Add(Subcomponents[n]); FLoaded.Add(Result); end; except if ((ffInherited in Flags) or Assigned(Component)) then Result.Free; raise; end; finally Parent := SavedParent; FLookupRoot := SavedLookupRoot; Subcomponents.Free; end; end; procedure TReader.ReadData(Instance: TComponent); var SavedOwner, SavedParent: TComponent; begin { Read properties } while not EndOfList do ReadProperty(Instance); ReadListEnd; { Read children } SavedOwner := Owner; SavedParent := Parent; try Owner := Instance.GetChildOwner; if not Assigned(Owner) then Owner := Root; Parent := Instance.GetChildParent; while not EndOfList do ReadComponent(nil); ReadListEnd; finally Owner := SavedOwner; Parent := SavedParent; end; { Fixup references if necessary (normally only if this is the root) } If (Instance=FRoot) then DoFixupReferences; end; function TReader.ReadFloat: Extended; begin if FDriver.NextValue = vaExtended then begin ReadValue; Result := FDriver.ReadFloat end else Result := ReadNativeInt; end; procedure TReader.ReadSignature; begin FDriver.ReadSignature; end; function TReader.ReadCurrency: Currency; begin if FDriver.NextValue = vaCurrency then begin FDriver.ReadValue; Result := FDriver.ReadCurrency; end else Result := ReadInteger; end; function TReader.ReadIdent: String; var ValueType: TValueType; begin ValueType := FDriver.ReadValue; if ValueType in [vaIdent, vaNil, vaFalse, vaTrue, vaNull] then Result := FDriver.ReadIdent(ValueType) else raise EReadError.Create(SInvalidPropertyValue); end; function TReader.ReadInteger: LongInt; begin case FDriver.ReadValue of vaInt8: Result := FDriver.ReadInt8; vaInt16: Result := FDriver.ReadInt16; vaInt32: Result := FDriver.ReadInt32; else raise EReadError.Create(SInvalidPropertyValue); end; end; function TReader.ReadNativeInt: NativeInt; begin if FDriver.NextValue = vaInt64 then begin FDriver.ReadValue; Result := FDriver.ReadNativeInt; end else Result := ReadInteger; end; function TReader.ReadSet(EnumType: Pointer): Integer; begin if FDriver.NextValue = vaSet then begin FDriver.ReadValue; Result := FDriver.ReadSet(enumtype); end else Result := ReadInteger; end; procedure TReader.ReadListBegin; begin CheckValue(vaList); end; procedure TReader.ReadListEnd; begin CheckValue(vaNull); end; function TReader.ReadVariant: JSValue; var nv: TValueType; begin nv:=NextValue; case nv of vaNil: begin Result:=Undefined; readvalue; end; vaNull: begin Result:=Nil; readvalue; end; { all integer sizes must be split for big endian systems } vaInt8,vaInt16,vaInt32: begin Result:=ReadInteger; end; vaInt64: begin Result:=ReadNativeInt; end; { vaQWord: begin Result:=QWord(ReadInt64); end; } vaFalse,vaTrue: begin Result:=(nv<>vaFalse); readValue; end; vaCurrency: begin Result:=ReadCurrency; end; vaDouble: begin Result:=ReadFloat; end; vaString: begin Result:=ReadString; end; else raise EReadError.CreateFmt(SUnsupportedPropertyVariantType, [Ord(nv)]); end; end; procedure TReader.ReadProperty(AInstance: TPersistent); var Path: String; Instance: TPersistent; PropInfo: TTypeMemberProperty; Obj: TObject; Name: String; Skip: Boolean; Handled: Boolean; OldPropName: String; DotPos : String; NextPos: Integer; function HandleMissingProperty(IsPath: Boolean): boolean; begin Result:=true; if Assigned(OnPropertyNotFound) then begin // user defined property error handling OldPropName:=FPropName; Handled:=false; Skip:=false; OnPropertyNotFound(Self,Instance,FPropName,IsPath,Handled,Skip); if Handled and (not Skip) and (OldPropName<>FPropName) then // try alias property PropInfo := GetPropInfo(Instance.ClassType, FPropName); if Skip then begin FDriver.SkipValue; Result:=false; exit; end; end; end; begin try Path := FDriver.BeginProperty; try Instance := AInstance; FCanHandleExcepts := True; DotPos := Path; while True do begin NextPos := Pos('.',DotPos); if NextPos>0 then FPropName := Copy(DotPos, 1, NextPos-1) else begin FPropName := DotPos; break; end; Delete(DotPos,1,NextPos); PropInfo := GetPropInfo(Instance.ClassType, FPropName); if not Assigned(PropInfo) then begin if not HandleMissingProperty(true) then exit; if not Assigned(PropInfo) then PropertyError; end; if PropInfo.TypeInfo.Kind = tkClass then Obj := TObject(GetObjectProp(Instance, PropInfo)) //else if PropInfo^.PropType^.Kind = tkInterface then // Obj := TObject(GetInterfaceProp(Instance, PropInfo)) else Obj := nil; if not (Obj is TPersistent) then begin { All path elements must be persistent objects! } FDriver.SkipValue; raise EReadError.Create(SInvalidPropertyPath); end; Instance := TPersistent(Obj); end; PropInfo := GetPropInfo(Instance.ClassType, FPropName); if Assigned(PropInfo) then ReadPropValue(Instance, PropInfo) else begin FCanHandleExcepts := False; Instance.DefineProperties(Self); FCanHandleExcepts := True; if Length(FPropName) > 0 then begin if not HandleMissingProperty(false) then exit; if not Assigned(PropInfo) then PropertyError; end; end; except on e: Exception do begin SetLength(Name, 0); if AInstance.InheritsFrom(TComponent) then Name := TComponent(AInstance).Name; if Length(Name) = 0 then Name := AInstance.ClassName; raise EReadError.CreateFmt(SPropertyException, [Name, '.', Path, e.Message]); end; end; except on e: Exception do if not FCanHandleExcepts or not Error(E.Message) then raise; end; end; procedure TReader.ReadPropValue(Instance: TPersistent; PropInfo: TTypeMemberProperty); const NullMethod: TMethod = (Code: nil; Data: nil); var PropType: TTypeInfo; Value: LongInt; { IdentToIntFn: TIdentToInt; } Ident: String; Method: TMethod; Handled: Boolean; TmpStr: String; begin if (PropInfo.Setter='') then raise EReadError.Create(SReadOnlyProperty); PropType := PropInfo.TypeInfo; case PropType.Kind of tkInteger: case FDriver.NextValue of vaIdent : begin Ident := ReadIdent; if GlobalIdentToInt(Ident,Value) then SetOrdProp(Instance, PropInfo, Value) else raise EReadError.Create(SInvalidPropertyValue); end; vaNativeInt : SetOrdProp(Instance, PropInfo, ReadNativeInt); vaCurrency: SetFloatProp(Instance, PropInfo, ReadCurrency); else SetOrdProp(Instance, PropInfo, ReadInteger); end; tkBool: SetOrdProp(Instance, PropInfo, Ord(ReadBoolean)); tkChar: SetOrdProp(Instance, PropInfo, Ord(ReadChar)); tkEnumeration: begin Value := GetEnumValue(TTypeInfoEnum(PropType), ReadIdent); if Value = -1 then raise EReadError.Create(SInvalidPropertyValue); SetOrdProp(Instance, PropInfo, Value); end; {$ifndef FPUNONE} tkFloat: SetFloatProp(Instance, PropInfo, ReadFloat); {$endif} tkSet: begin CheckValue(vaSet); if TTypeInfoSet(PropType).CompType.Kind=tkEnumeration then SetOrdProp(Instance, PropInfo, FDriver.ReadSet(TTypeInfoEnum(TTypeInfoSet(PropType).CompType))); end; tkMethod, tkRefToProcVar: if FDriver.NextValue = vaNil then begin FDriver.ReadValue; SetMethodProp(Instance, PropInfo, NullMethod); end else begin Handled:=false; Ident:=ReadIdent; if Assigned(OnSetMethodProperty) then OnSetMethodProperty(Self,Instance,PropInfo,Ident,Handled); if not Handled then begin Method.Code := FindMethod(Root, Ident); Method.Data := Root; if Assigned(Method.Code) then SetMethodProp(Instance, PropInfo, Method); end; end; tkString: begin TmpStr:=ReadString; if Assigned(FOnReadStringProperty) then FOnReadStringProperty(Self,Instance,PropInfo,TmpStr); SetStrProp(Instance, PropInfo, TmpStr); end; tkJSValue: begin SetJSValueProp(Instance,PropInfo,ReadVariant); end; tkClass, tkInterface: case FDriver.NextValue of vaNil: begin FDriver.ReadValue; SetOrdProp(Instance, PropInfo, 0) end; vaCollection: begin FDriver.ReadValue; ReadCollection(TCollection(GetObjectProp(Instance, PropInfo))); end else begin If Not Assigned(FFixups) then FFixups:=TLinkedList.Create(TLocalUnresolvedReference); With TLocalUnresolvedReference(TLinkedList(FFixups).Add) do begin FInstance:=Instance; FRoot:=Root; FPropInfo:=PropInfo; FRelative:=ReadIdent; end; end; end; {tkint64: SetInt64Prop(Instance, PropInfo, ReadInt64);} else raise EReadError.CreateFmt(SUnknownPropertyType, [Str(PropType.Kind)]); end; end; function TReader.ReadRootComponent(ARoot: TComponent): TComponent; var Dummy, i: Integer; Flags: TFilerFlags; CompClassName, CompName, ResultName: String; begin FDriver.BeginRootComponent; Result := nil; {!!!: GlobalNameSpace.BeginWrite; // Loading from stream adds to name space try} try FDriver.BeginComponent(Flags, Dummy, CompClassName, CompName); if not Assigned(ARoot) then begin { Read the class name and the object name and create a new object: } Result := TComponentClass(FindClass(CompClassName)).Create(nil); Result.Name := CompName; end else begin Result := ARoot; if not (csDesigning in Result.ComponentState) then begin Result.FComponentState := Result.FComponentState + [csLoading, csReading]; { We need an unique name } i := 0; { Don't use Result.Name directly, as this would influence FindGlobalComponent in successive loop runs } ResultName := CompName; while Assigned(FindGlobalComponent(ResultName)) do begin Inc(i); ResultName := CompName + '_' + IntToStr(i); end; Result.Name := ResultName; end; end; FRoot := Result; FLookupRoot := Result; if Assigned(GlobalLoaded) then FLoaded := GlobalLoaded else FLoaded := TFpList.Create; try if FLoaded.IndexOf(FRoot) < 0 then FLoaded.Add(FRoot); FOwner := FRoot; FRoot.FComponentState := FRoot.FComponentState + [csLoading, csReading]; FRoot.ReadState(Self); Exclude(FRoot.FComponentState, csReading); if not Assigned(GlobalLoaded) then for i := 0 to FLoaded.Count - 1 do TComponent(FLoaded[i]).Loaded; finally if not Assigned(GlobalLoaded) then FLoaded.Free; FLoaded := nil; end; GlobalFixupReferences; except RemoveFixupReferences(ARoot, ''); if not Assigned(ARoot) then Result.Free; raise; end; {finally GlobalNameSpace.EndWrite; end;} end; procedure TReader.ReadComponents(AOwner, AParent: TComponent; Proc: TReadComponentsProc); var Component: TComponent; begin Root := AOwner; Owner := AOwner; Parent := AParent; BeginReferences; try while not EndOfList do begin FDriver.BeginRootComponent; Component := ReadComponent(nil); if Assigned(Proc) then Proc(Component); end; ReadListEnd; FixupReferences; finally EndReferences; end; end; function TReader.ReadString: String; var StringType: TValueType; begin StringType := FDriver.ReadValue; if StringType=vaString then Result := FDriver.ReadString(StringType) else raise EReadError.Create(SInvalidPropertyValue); end; function TReader.ReadWideString: WideString; begin Result:=ReadString; end; function TReader.ReadUnicodeString: UnicodeString; begin Result:=ReadString; end; function TReader.ReadValue: TValueType; begin Result := FDriver.ReadValue; end; procedure TReader.CopyValue(Writer: TWriter); (* procedure CopyBytes(Count: Integer); { var Buffer: array[0..1023] of Byte; } begin {!!!: while Count > 1024 do begin FDriver.Read(Buffer, 1024); Writer.Driver.Write(Buffer, 1024); Dec(Count, 1024); end; if Count > 0 then begin FDriver.Read(Buffer, Count); Writer.Driver.Write(Buffer, Count); end;} end; *) {var s: String; Count: LongInt; } begin case FDriver.NextValue of vaNull: Writer.WriteIdent('NULL'); vaFalse: Writer.WriteIdent('FALSE'); vaTrue: Writer.WriteIdent('TRUE'); vaNil: Writer.WriteIdent('NIL'); {!!!: vaList, vaCollection: begin Writer.WriteValue(FDriver.ReadValue); while not EndOfList do CopyValue(Writer); ReadListEnd; Writer.WriteListEnd; end;} vaInt8, vaInt16, vaInt32: Writer.WriteInteger(ReadInteger); {$ifndef FPUNONE} vaExtended: Writer.WriteFloat(ReadFloat); {$endif} vaString: Writer.WriteString(ReadString); vaIdent: Writer.WriteIdent(ReadIdent); {!!!: vaBinary, vaLString, vaWString: begin Writer.WriteValue(FDriver.ReadValue); FDriver.Read(Count, SizeOf(Count)); Writer.Driver.Write(Count, SizeOf(Count)); CopyBytes(Count); end;} {!!!: vaSet: Writer.WriteSet(ReadSet);} {!!!: vaCurrency: Writer.WriteCurrency(ReadCurrency);} vaInt64: Writer.WriteInteger(ReadNativeInt); end; end; function TReader.FindComponentClass(const AClassName: String): TComponentClass; var PersistentClass: TPersistentClass; function FindClassInFieldTable(Instance: TComponent): TComponentClass; var aClass: TClass; i: longint; ClassTI, MemberClassTI: TTypeInfoClass; MemberTI: TTypeInfo; begin aClass:=Instance.ClassType; while aClass<>nil do begin ClassTI:=typeinfo(aClass); for i:=0 to ClassTI.FieldCount-1 do begin MemberTI:=ClassTI.GetField(i).TypeInfo; if MemberTI.Kind=tkClass then begin MemberClassTI:=TTypeInfoClass(MemberTI); if SameText(MemberClassTI.Name,aClassName) and (MemberClassTI.ClassType is TComponent) then exit(TComponentClass(MemberClassTI.ClassType)); end; end; aClass:=aClass.ClassParent; end; end; begin Result := nil; Result:=FindClassInFieldTable(Root); if (Result=nil) and assigned(LookupRoot) and (LookupRoot<>Root) then Result:=FindClassInFieldTable(LookupRoot); if (Result=nil) then begin PersistentClass := GetClass(AClassName); if PersistentClass.InheritsFrom(TComponent) then Result := TComponentClass(PersistentClass); end; if (Result=nil) and assigned(OnFindComponentClass) then OnFindComponentClass(Self, AClassName, Result); if (Result=nil) or (not Result.InheritsFrom(TComponent)) then raise EClassNotFound.CreateFmt(SClassNotFound, [AClassName]); end; { TAbstractObjectReader } procedure TAbstractObjectReader.FlushBuffer; begin // Do nothing end; { This file is part of the Free Component Library (FCL) Copyright (c) 1999-2000 by the Free Pascal development team 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. **********************************************************************} {****************************************************************************} {* TBinaryObjectWriter *} {****************************************************************************} procedure TBinaryObjectWriter.WriteWord(w : word); begin FStream.WriteBufferData(w); end; procedure TBinaryObjectWriter.WriteDWord(lw : longword); begin FStream.WriteBufferData(lw); end; constructor TBinaryObjectWriter.Create(Stream: TStream); begin inherited Create; If (Stream=Nil) then Raise EWriteError.Create(SEmptyStreamIllegalWriter); FStream := Stream; end; procedure TBinaryObjectWriter.BeginCollection; begin WriteValue(vaCollection); end; procedure TBinaryObjectWriter.WriteSignature; begin FStream.WriteBufferData(FilerSignatureInt); end; procedure TBinaryObjectWriter.BeginComponent(Component: TComponent; Flags: TFilerFlags; ChildPos: Integer); var Prefix: Byte; begin { Only write the flags if they are needed! } if Flags <> [] then begin Prefix:=0; if ffInherited in Flags then Prefix:=Prefix or $01; if ffChildPos in Flags then Prefix:=Prefix or $02; if ffInline in Flags then Prefix:=Prefix or $04; Prefix := Prefix or $f0; FStream.WriteBufferData(Prefix); if ffChildPos in Flags then WriteInteger(ChildPos); end; WriteStr(Component.ClassName); WriteStr(Component.Name); end; procedure TBinaryObjectWriter.BeginList; begin WriteValue(vaList); end; procedure TBinaryObjectWriter.EndList; begin WriteValue(vaNull); end; procedure TBinaryObjectWriter.BeginProperty(const PropName: String); begin WriteStr(PropName); end; procedure TBinaryObjectWriter.EndProperty; begin end; procedure TBinaryObjectWriter.FlushBuffer; begin // Do nothing; end; procedure TBinaryObjectWriter.WriteBinary(const Buffer : TBytes; Count: LongInt); begin WriteValue(vaBinary); WriteDWord(longword(Count)); FStream.Write(Buffer, Count); end; procedure TBinaryObjectWriter.WriteBoolean(Value: Boolean); begin if Value then WriteValue(vaTrue) else WriteValue(vaFalse); end; procedure TBinaryObjectWriter.WriteFloat(const Value: Extended); begin WriteValue(vaDouble); FStream.WriteBufferData(Value); end; procedure TBinaryObjectWriter.WriteCurrency(const Value: Currency); Var F : Double; begin WriteValue(vaCurrency); F:=Value; FStream.WriteBufferData(F); end; procedure TBinaryObjectWriter.WriteIdent(const Ident: string); begin { Check if Ident is a special identifier before trying to just write Ident directly } if UpperCase(Ident) = 'NIL' then WriteValue(vaNil) else if UpperCase(Ident) = 'FALSE' then WriteValue(vaFalse) else if UpperCase(Ident) = 'TRUE' then WriteValue(vaTrue) else if UpperCase(Ident) = 'NULL' then WriteValue(vaNull) else begin WriteValue(vaIdent); WriteStr(Ident); end; end; procedure TBinaryObjectWriter.WriteInteger(Value: NativeInt); var s: ShortInt; i: SmallInt; l: Longint; begin { Use the smallest possible integer type for the given value: } if (Value >= -128) and (Value <= 127) then begin WriteValue(vaInt8); s := Value; FStream.WriteBufferData(s); end else if (Value >= -32768) and (Value <= 32767) then begin WriteValue(vaInt16); i := Value; WriteWord(word(i)); end else if (Value >= -$80000000) and (Value <= $7fffffff) then begin WriteValue(vaInt32); l := Value; WriteDWord(longword(l)); end else begin WriteValue(vaInt64); FStream.WriteBufferData(Value); end; end; procedure TBinaryObjectWriter.WriteNativeInt(Value: NativeInt); var s: Int8; i: Int16; l: Int32; begin { Use the smallest possible integer type for the given value: } if (Value <= 127) then begin WriteValue(vaInt8); s := Value; FStream.WriteBufferData(s); end else if (Value <= 32767) then begin WriteValue(vaInt16); i := Value; WriteWord(word(i)); end else if (Value <= $7fffffff) then begin WriteValue(vaInt32); l := Value; WriteDWord(longword(l)); end else begin WriteValue(vaQWord); FStream.WriteBufferData(Value); end; end; procedure TBinaryObjectWriter.WriteMethodName(const Name: String); begin if Length(Name) > 0 then begin WriteValue(vaIdent); WriteStr(Name); end else WriteValue(vaNil); end; procedure TBinaryObjectWriter.WriteSet(Value: LongInt; SetType: Pointer); var i: Integer; b : Integer; begin WriteValue(vaSet); B:=1; for i:=0 to 31 do begin if (Value and b) <>0 then begin WriteStr(GetEnumName(PTypeInfo(SetType), i)); end; b:=b shl 1; end; WriteStr(''); end; procedure TBinaryObjectWriter.WriteString(const Value: String); var i, len: Integer; begin len := Length(Value); WriteValue(vaString); WriteDWord(len); For I:=1 to len do FStream.WriteBufferData(Value[i]); end; procedure TBinaryObjectWriter.WriteWideString(const Value: WideString); begin WriteString(Value); end; procedure TBinaryObjectWriter.WriteUnicodeString(const Value: UnicodeString); begin WriteString(Value); end; procedure TBinaryObjectWriter.WriteVariant(const VarValue: JSValue); begin if isUndefined(varValue) then WriteValue(vaNil) else if IsNull(VarValue) then WriteValue(vaNull) else if IsNumber(VarValue) then begin if Frac(Double(varValue))=0 then WriteInteger(NativeInt(VarValue)) else WriteFloat(Double(varValue)) end else if isBoolean(varValue) then WriteBoolean(Boolean(VarValue)) else if isString(varValue) then WriteString(String(VarValue)) else raise EWriteError.Create(SUnsupportedPropertyVariantType); end; procedure TBinaryObjectWriter.Write(const Buffer : TBytes; Count: LongInt); begin FStream.Write(Buffer,Count); end; procedure TBinaryObjectWriter.WriteValue(Value: TValueType); var b: uint8; begin b := uint8(Value); FStream.WriteBufferData(b); end; procedure TBinaryObjectWriter.WriteStr(const Value: String); var len,i: integer; b: uint8; begin len:= Length(Value); if len > 255 then len := 255; b := len; FStream.WriteBufferData(b); For I:=1 to len do FStream.WriteBufferData(Value[i]); end; {****************************************************************************} {* TWriter *} {****************************************************************************} constructor TWriter.Create(ADriver: TAbstractObjectWriter); begin inherited Create; FDriver := ADriver; end; constructor TWriter.Create(Stream: TStream); begin inherited Create; If (Stream=Nil) then Raise EWriteError.Create(SEmptyStreamIllegalWriter); FDriver := CreateDriver(Stream); FDestroyDriver := True; end; destructor TWriter.Destroy; begin if FDestroyDriver then FDriver.Free; inherited Destroy; end; function TWriter.CreateDriver(Stream: TStream): TAbstractObjectWriter; begin Result := TBinaryObjectWriter.Create(Stream); end; Type TPosComponent = Class(TObject) Private FPos : Integer; FComponent : TComponent; Public Constructor Create(APos : Integer; AComponent : TComponent); end; Constructor TPosComponent.Create(APos : Integer; AComponent : TComponent); begin FPos:=APos; FComponent:=AComponent; end; // Used as argument for calls to TComponent.GetChildren: procedure TWriter.AddToAncestorList(Component: TComponent); begin FAncestors.AddObject(Component.Name,TPosComponent.Create(FAncestors.Count,Component)); end; procedure TWriter.DefineProperty(const Name: String; ReadData: TReaderProc; AWriteData: TWriterProc; HasData: Boolean); begin if HasData and Assigned(AWriteData) then begin // Write the property name and then the data itself Driver.BeginProperty(FPropPath + Name); AWriteData(Self); Driver.EndProperty; end else if assigned(ReadData) then ; end; procedure TWriter.DefineBinaryProperty(const Name: String; ReadData, AWriteData: TStreamProc; HasData: Boolean); begin if HasData and Assigned(AWriteData) then begin // Write the property name and then the data itself Driver.BeginProperty(FPropPath + Name); WriteBinary(AWriteData); Driver.EndProperty; end else if assigned(ReadData) then ; end; procedure TWriter.FlushBuffer; begin Driver.FlushBuffer; end; procedure TWriter.Write(const Buffer : TBytes; Count: Longint); begin //This should give an exception if write is not implemented (i.e. TTextObjectWriter) //but should work with TBinaryObjectWriter. Driver.Write(Buffer, Count); end; procedure TWriter.SetRoot(ARoot: TComponent); begin inherited SetRoot(ARoot); // Use the new root as lookup root too FLookupRoot := ARoot; end; procedure TWriter.WriteSignature; begin FDriver.WriteSignature; end; procedure TWriter.WriteBinary(AWriteData: TStreamProc); var MemBuffer: TBytesStream; begin { First write the binary data into a memory stream, then copy this buffered stream into the writing destination. This is necessary as we have to know the size of the binary data in advance (we're assuming that seeking within the writer stream is not possible) } MemBuffer := TBytesStream.Create; try AWriteData(MemBuffer); Driver.WriteBinary(MemBuffer.Bytes, MemBuffer.Size); finally MemBuffer.Free; end; end; procedure TWriter.WriteBoolean(Value: Boolean); begin Driver.WriteBoolean(Value); end; procedure TWriter.WriteChar(Value: Char); begin WriteString(Value); end; procedure TWriter.WriteWideChar(Value: WideChar); begin WriteWideString(Value); end; procedure TWriter.WriteCollection(Value: TCollection); var i: Integer; begin Driver.BeginCollection; if Assigned(Value) then for i := 0 to Value.Count - 1 do begin { Each collection item needs its own ListBegin/ListEnd tag, or else the reader wouldn't be able to know where an item ends and where the next one starts } WriteListBegin; WriteProperties(Value.Items[i]); WriteListEnd; end; WriteListEnd; end; procedure TWriter.DetermineAncestor(Component : TComponent); Var I : Integer; begin // Should be set only when we write an inherited with children. if Not Assigned(FAncestors) then exit; I:=FAncestors.IndexOf(Component.Name); If (I=-1) then begin FAncestor:=Nil; FAncestorPos:=-1; end else With TPosComponent(FAncestors.Objects[i]) do begin FAncestor:=FComponent; FAncestorPos:=FPos; end; end; procedure TWriter.DoFindAncestor(Component : TComponent); Var C : TComponent; begin if Assigned(FOnFindAncestor) then if (Ancestor=Nil) or (Ancestor is TComponent) then begin C:=TComponent(Ancestor); FOnFindAncestor(Self,Component,Component.Name,C,FRootAncestor); Ancestor:=C; end; end; procedure TWriter.WriteComponent(Component: TComponent); var SA : TPersistent; SR, SRA : TComponent; begin SR:=FRoot; SA:=FAncestor; SRA:=FRootAncestor; Try Component.FComponentState:=Component.FComponentState+[csWriting]; Try // Possibly set ancestor. DetermineAncestor(Component); DoFindAncestor(Component); // Mainly for IDE when a parent form had an ancestor renamed... // Will call WriteComponentData. Component.WriteState(Self); FDriver.EndList; Finally Component.FComponentState:=Component.FComponentState-[csWriting]; end; Finally FAncestor:=SA; FRoot:=SR; FRootAncestor:=SRA; end; end; procedure TWriter.WriteChildren(Component : TComponent); Var SRoot, SRootA : TComponent; SList : TStringList; SPos, I , SAncestorPos: Integer; O : TObject; begin // Write children list. // While writing children, the ancestor environment must be saved // This is recursive... SRoot:=FRoot; SRootA:=FRootAncestor; SList:=FAncestors; SPos:=FCurrentPos; SAncestorPos:=FAncestorPos; try FAncestors:=Nil; FCurrentPos:=0; FAncestorPos:=-1; if csInline in Component.ComponentState then FRoot:=Component; if (FAncestor is TComponent) then begin FAncestors:=TStringList.Create; if csInline in TComponent(FAncestor).ComponentState then FRootAncestor := TComponent(FAncestor); TComponent(FAncestor).GetChildren(@AddToAncestorList,FRootAncestor); FAncestors.Sorted:=True; end; try Component.GetChildren(@WriteComponent, FRoot); Finally If Assigned(Fancestors) then For I:=0 to FAncestors.Count-1 do begin O:=FAncestors.Objects[i]; FAncestors.Objects[i]:=Nil; O.Free; end; FreeAndNil(FAncestors); end; finally FAncestors:=Slist; FRoot:=SRoot; FRootAncestor:=SRootA; FCurrentPos:=SPos; FAncestorPos:=SAncestorPos; end; end; procedure TWriter.WriteComponentData(Instance: TComponent); var Flags: TFilerFlags; begin Flags := []; If (Assigned(FAncestor)) and //has ancestor (not (csInline in Instance.ComponentState) or // no inline component // .. or the inline component is inherited (csAncestor in Instance.Componentstate) and (FAncestors <> nil)) then Flags:=[ffInherited] else If csInline in Instance.ComponentState then Flags:=[ffInline]; If (FAncestors<>Nil) and ((FCurrentPos<>FAncestorPos) or (FAncestor=Nil)) then Include(Flags,ffChildPos); FDriver.BeginComponent(Instance,Flags,FCurrentPos); If (FAncestors<>Nil) then Inc(FCurrentPos); WriteProperties(Instance); WriteListEnd; // Needs special handling of ancestor. If not IgnoreChildren then WriteChildren(Instance); end; procedure TWriter.WriteDescendent(ARoot: TComponent; AAncestor: TComponent); begin FRoot := ARoot; FAncestor := AAncestor; FRootAncestor := AAncestor; FLookupRoot := ARoot; WriteSignature; WriteComponent(ARoot); end; procedure TWriter.WriteFloat(const Value: Extended); begin Driver.WriteFloat(Value); end; procedure TWriter.WriteCurrency(const Value: Currency); begin Driver.WriteCurrency(Value); end; procedure TWriter.WriteIdent(const Ident: string); begin Driver.WriteIdent(Ident); end; procedure TWriter.WriteInteger(Value: LongInt); begin Driver.WriteInteger(Value); end; procedure TWriter.WriteInteger(Value: NativeInt); begin Driver.WriteInteger(Value); end; procedure TWriter.WriteSet(Value: LongInt; SetType: Pointer); begin Driver.WriteSet(Value,SetType); end; procedure TWriter.WriteVariant(const VarValue: JSValue); begin Driver.WriteVariant(VarValue); end; procedure TWriter.WriteListBegin; begin Driver.BeginList; end; procedure TWriter.WriteListEnd; begin Driver.EndList; end; procedure TWriter.WriteProperties(Instance: TPersistent); var PropCount,i : integer; PropList : TTypeMemberPropertyDynArray; begin PropList:=GetPropList(Instance); PropCount:=Length(PropList); if PropCount>0 then for i := 0 to PropCount-1 do if IsStoredProp(Instance,PropList[i]) then WriteProperty(Instance,PropList[i]); Instance.DefineProperties(Self); end; procedure TWriter.WriteProperty(Instance: TPersistent; PropInfo: TTypeMemberProperty); var HasAncestor: Boolean; PropType: TTypeInfo; N,Value, DefValue: LongInt; Ident: String; IntToIdentFn: TIntToIdent; {$ifndef FPUNONE} FloatValue, DefFloatValue: Extended; {$endif} MethodValue: TMethod; DefMethodValue: TMethod; StrValue, DefStrValue: String; AncestorObj: TObject; C,Component: TComponent; ObjValue: TObject; SavedAncestor: TPersistent; Key, SavedPropPath, Name, lMethodName: String; VarValue, DefVarValue : JSValue; BoolValue, DefBoolValue: boolean; Handled: Boolean; O : TJSObject; begin // do not stream properties without getter if PropInfo.Getter='' then exit; // properties without setter are only allowed, if they are subcomponents PropType := PropInfo.TypeInfo; if (PropInfo.Setter='') then begin if PropType.Kind<>tkClass then exit; ObjValue := TObject(GetObjectProp(Instance, PropInfo)); if not ObjValue.InheritsFrom(TComponent) or not (csSubComponent in TComponent(ObjValue).ComponentStyle) then exit; end; { Check if the ancestor can be used } HasAncestor := Assigned(Ancestor) and ((Instance = Root) or (Instance.ClassType = Ancestor.ClassType)); //writeln('TWriter.WriteProperty Name=',PropType^.Name,' Kind=',GetEnumName(TypeInfo(TTypeKind),ord(PropType^.Kind)),' HasAncestor=',HasAncestor); case PropType.Kind of tkInteger, tkChar, tkEnumeration, tkSet: begin Value := GetOrdProp(Instance, PropInfo); if HasAncestor then DefValue := GetOrdProp(Ancestor, PropInfo) else begin if PropType.Kind<>tkSet then DefValue := Longint(PropInfo.Default) else begin o:=TJSObject(PropInfo.Default); DefValue:=0; for Key in o do begin n:=parseInt(Key,10); if n<32 then DefValue:=DefValue+(1 shl n); end; end; end; // writeln(PPropInfo(PropInfo)^.Name, ', HasAncestor=', ord(HasAncestor), ', Value=', Value, ', Default=', DefValue); if (Value <> DefValue) or (DefValue=longint($80000000)) then begin Driver.BeginProperty(FPropPath + PropInfo.Name); case PropType.Kind of tkInteger: begin // Check if this integer has a string identifier IntToIdentFn := FindIntToIdent(PropInfo.TypeInfo); if Assigned(IntToIdentFn) and IntToIdentFn(Value, Ident) then // Integer can be written a human-readable identifier WriteIdent(Ident) else // Integer has to be written just as number WriteInteger(Value); end; tkChar: WriteChar(Chr(Value)); tkSet: begin Driver.WriteSet(Value, TTypeInfoSet(PropType).CompType); end; tkEnumeration: WriteIdent(GetEnumName(TTypeInfoEnum(PropType), Value)); end; Driver.EndProperty; end; end; {$ifndef FPUNONE} tkFloat: begin FloatValue := GetFloatProp(Instance, PropInfo); if HasAncestor then DefFloatValue := GetFloatProp(Ancestor, PropInfo) else begin // This is really ugly.. DefFloatValue:=Double(PropInfo.Default); end; if (FloatValue<>DefFloatValue) or (not HasAncestor and (int(DefFloatValue)=longint($80000000))) then begin Driver.BeginProperty(FPropPath + PropInfo.Name); WriteFloat(FloatValue); Driver.EndProperty; end; end; {$endif} tkMethod: begin MethodValue := GetMethodProp(Instance, PropInfo); if HasAncestor then DefMethodValue := GetMethodProp(Ancestor, PropInfo) else begin DefMethodValue.Data := nil; DefMethodValue.Code := nil; end; Handled:=false; if Assigned(OnWriteMethodProperty) then OnWriteMethodProperty(Self,Instance,PropInfo,MethodValue, DefMethodValue,Handled); if isString(MethodValue.Code) then lMethodName:=String(MethodValue.Code) else lMethodName:=FLookupRoot.MethodName(MethodValue.Code); //Writeln('Writeln A: ',lMethodName); if (not Handled) and (MethodValue.Code <> DefMethodValue.Code) and ((not Assigned(MethodValue.Code)) or ((Length(lMethodName) > 0))) then begin //Writeln('Writeln B',FPropPath + PropInfo.Name); Driver.BeginProperty(FPropPath + PropInfo.Name); if Assigned(MethodValue.Code) then Driver.WriteMethodName(lMethodName) else Driver.WriteMethodName(''); Driver.EndProperty; end; end; tkString: // tkSString, tkLString, tkAString are not supported begin StrValue := GetStrProp(Instance, PropInfo); if HasAncestor then DefStrValue := GetStrProp(Ancestor, PropInfo) else begin DefValue :=Longint(PropInfo.Default); SetLength(DefStrValue, 0); end; if (StrValue<>DefStrValue) or (not HasAncestor and (DefValue=longint($80000000))) then begin Driver.BeginProperty(FPropPath + PropInfo.Name); if Assigned(FOnWriteStringProperty) then FOnWriteStringProperty(Self,Instance,PropInfo,StrValue); WriteString(StrValue); Driver.EndProperty; end; end; tkJSValue: begin { Ensure that a Variant manager is installed } VarValue := GetJSValueProp(Instance, PropInfo); if HasAncestor then DefVarValue := GetJSValueProp(Ancestor, PropInfo) else DefVarValue:=null; if (VarValue<>DefVarValue) then begin Driver.BeginProperty(FPropPath + PropInfo.Name); { can't use variant() typecast, pulls in variants unit } WriteVariant(VarValue); Driver.EndProperty; end; end; tkClass: begin ObjValue := TObject(GetObjectProp(Instance, PropInfo)); if HasAncestor then begin AncestorObj := TObject(GetObjectProp(Ancestor, PropInfo)); if (AncestorObj is TComponent) and (ObjValue is TComponent) then begin //writeln('TWriter.WriteProperty AncestorObj=',TComponent(AncestorObj).Name,' OwnerFit=',TComponent(AncestorObj).Owner = FRootAncestor,' ',TComponent(ObjValue).Name,' OwnerFit=',TComponent(ObjValue).Owner = Root); if (AncestorObj<> ObjValue) and (TComponent(AncestorObj).Owner = FRootAncestor) and (TComponent(ObjValue).Owner = Root) and (UpperCase(TComponent(AncestorObj).Name) = UpperCase(TComponent(ObjValue).Name)) then begin // different components, but with the same name // treat it like an override AncestorObj := ObjValue; end; end; end else AncestorObj := nil; if not Assigned(ObjValue) then begin if ObjValue <> AncestorObj then begin Driver.BeginProperty(FPropPath + PropInfo.Name); Driver.WriteIdent('NIL'); Driver.EndProperty; end end else if ObjValue.InheritsFrom(TPersistent) then begin { Subcomponents are streamed the same way as persistents } if ObjValue.InheritsFrom(TComponent) and ((not (csSubComponent in TComponent(ObjValue).ComponentStyle)) or ((TComponent(ObjValue).Owner<>Instance) and (TComponent(ObjValue).Owner<>Nil))) then begin Component := TComponent(ObjValue); if (ObjValue <> AncestorObj) and not (csTransient in Component.ComponentStyle) then begin Name:= ''; C:= Component; While (C<>Nil) and (C.Name<>'') do begin If (Name<>'') Then Name:='.'+Name; if C.Owner = LookupRoot then begin Name := C.Name+Name; break; end else if C = LookupRoot then begin Name := 'Owner' + Name; break; end; Name:=C.Name + Name; C:= C.Owner; end; if (C=nil) and (Component.Owner=nil) then if (Name<>'') then //foreign root Name:=Name+'.Owner'; if Length(Name) > 0 then begin Driver.BeginProperty(FPropPath + PropInfo.Name); WriteIdent(Name); Driver.EndProperty; end; // length Name>0 end; //(ObjValue <> AncestorObj) end // ObjValue.InheritsFrom(TComponent) else begin SavedAncestor := Ancestor; SavedPropPath := FPropPath; try FPropPath := FPropPath + PropInfo.Name + '.'; if HasAncestor then Ancestor := TPersistent(GetObjectProp(Ancestor, PropInfo)); WriteProperties(TPersistent(ObjValue)); finally Ancestor := SavedAncestor; FPropPath := SavedPropPath; end; if ObjValue.InheritsFrom(TCollection) then begin if (not HasAncestor) or (not CollectionsEqual(TCollection(ObjValue), TCollection(GetObjectProp(Ancestor, PropInfo)),root,rootancestor)) then begin Driver.BeginProperty(FPropPath + PropInfo.Name); SavedPropPath := FPropPath; try SetLength(FPropPath, 0); WriteCollection(TCollection(ObjValue)); finally FPropPath := SavedPropPath; Driver.EndProperty; end; end; end // Tcollection end; end; // Inheritsfrom(TPersistent) end; { tkInt64, tkQWord: begin Int64Value := GetInt64Prop(Instance, PropInfo); if HasAncestor then DefInt64Value := GetInt64Prop(Ancestor, PropInfo) else DefInt64Value := 0; if Int64Value <> DefInt64Value then begin Driver.BeginProperty(FPropPath + PPropInfo(PropInfo)^.Name); WriteInteger(Int64Value); Driver.EndProperty; end; end;} tkBool: begin BoolValue := GetOrdProp(Instance, PropInfo)<>0; if HasAncestor then DefBoolValue := GetOrdProp(Ancestor, PropInfo)<>0 else begin DefBoolValue := PropInfo.Default<>0; DefValue:=Longint(PropInfo.Default); end; // writeln(PropInfo.Name, ', HasAncestor=', ord(HasAncestor), ', Value=', Value, ', Default=', DefBoolValue); if (BoolValue<>DefBoolValue) or (DefValue=longint($80000000)) then begin Driver.BeginProperty(FPropPath + PropInfo.Name); WriteBoolean(BoolValue); Driver.EndProperty; end; end; tkInterface: begin { IntfValue := GetInterfaceProp(Instance, PropInfo); if Assigned(IntfValue) and Supports(IntfValue, IInterfaceComponentReference, CompRef) then begin Component := CompRef.GetComponent; if HasAncestor then begin AncestorObj := TObject(GetObjectProp(Ancestor, PropInfo)); if (AncestorObj is TComponent) then begin //writeln('TWriter.WriteProperty AncestorObj=',TComponent(AncestorObj).Name,' OwnerFit=',TComponent(AncestorObj).Owner = FRootAncestor,' ',TComponent(ObjValue).Name,' OwnerFit=',TComponent(ObjValue).Owner = Root); if (AncestorObj<> Component) and (TComponent(AncestorObj).Owner = FRootAncestor) and (Component.Owner = Root) and (UpperCase(TComponent(AncestorObj).Name) = UpperCase(Component.Name)) then begin // different components, but with the same name // treat it like an override AncestorObj := Component; end; end; end else AncestorObj := nil; if not Assigned(Component) then begin if Component <> AncestorObj then begin Driver.BeginProperty(FPropPath + PropInfo.Name); Driver.WriteIdent('NIL'); Driver.EndProperty; end end else if ((not (csSubComponent in Component.ComponentStyle)) or ((Component.Owner<>Instance) and (Component.Owner<>Nil))) then begin if (Component <> AncestorObj) and not (csTransient in Component.ComponentStyle) then begin Name:= ''; C:= Component; While (C<>Nil) and (C.Name<>'') do begin If (Name<>'') Then Name:='.'+Name; if C.Owner = LookupRoot then begin Name := C.Name+Name; break; end else if C = LookupRoot then begin Name := 'Owner' + Name; break; end; Name:=C.Name + Name; C:= C.Owner; end; if (C=nil) and (Component.Owner=nil) then if (Name<>'') then //foreign root Name:=Name+'.Owner'; if Length(Name) > 0 then begin Driver.BeginProperty(FPropPath + PropInfo.Name); WriteIdent(Name); Driver.EndProperty; end; // length Name>0 end; //(Component <> AncestorObj) end; end; //Assigned(IntfValue) and Supports(IntfValue,.. //else write NIL ? } end; end; end; procedure TWriter.WriteRootComponent(ARoot: TComponent); begin WriteDescendent(ARoot, nil); end; procedure TWriter.WriteString(const Value: String); begin Driver.WriteString(Value); end; procedure TWriter.WriteWideString(const Value: WideString); begin Driver.WriteWideString(Value); end; procedure TWriter.WriteUnicodeString(const Value: UnicodeString); begin Driver.WriteUnicodeString(Value); end; { TAbstractObjectWriter } { --------------------------------------------------------------------- Global routines ---------------------------------------------------------------------} var ClassList : TJSObject; InitHandlerList : TList; FindGlobalComponentList : TFPList; Procedure RegisterClass(AClass : TPersistentClass); begin ClassList[AClass.ClassName]:=AClass; end; Procedure RegisterClasses(AClasses : specialize TArray<TPersistentClass>); var AClass : TPersistentClass; begin for AClass in AClasses do RegisterClass(AClass); end; Function GetClass(AClassName : string) : TPersistentClass; begin Result:=nil; if AClassName='' then exit; if not ClassList.hasOwnProperty(AClassName) then exit; Result:=TPersistentClass(ClassList[AClassName]); end; procedure RegisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent); begin if not(assigned(FindGlobalComponentList)) then FindGlobalComponentList:=TFPList.Create; if FindGlobalComponentList.IndexOf(CodePointer(AFindGlobalComponent))<0 then FindGlobalComponentList.Add(CodePointer(AFindGlobalComponent)); end; procedure UnregisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent); begin if assigned(FindGlobalComponentList) then FindGlobalComponentList.Remove(CodePointer(AFindGlobalComponent)); end; function FindGlobalComponent(const Name: string): TComponent; var i : sizeint; begin Result:=nil; if assigned(FindGlobalComponentList) then begin for i:=FindGlobalComponentList.Count-1 downto 0 do begin FindGlobalComponent:=TFindGlobalComponent(FindGlobalComponentList[i])(name); if assigned(Result) then break; end; end; end; Function FindNestedComponent(Root : TComponent; APath : String; CStyle : Boolean = True) : TComponent; Function GetNextName : String; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} Var P : Integer; CM : Boolean; begin P:=Pos('.',APath); CM:=False; If (P=0) then begin If CStyle then begin P:=Pos('->',APath); CM:=P<>0; end; If (P=0) Then P:=Length(APath)+1; end; Result:=Copy(APath,1,P-1); Delete(APath,1,P+Ord(CM)); end; Var C : TComponent; S : String; begin If (APath='') then Result:=Nil else begin Result:=Root; While (APath<>'') And (Result<>Nil) do begin C:=Result; S:=Uppercase(GetNextName); Result:=C.FindComponent(S); If (Result=Nil) And (S='OWNER') then Result:=C; end; end; end; Type TInitHandler = Class(TObject) AHandler : TInitComponentHandler; AClass : TComponentClass; end; procedure RegisterInitComponentHandler(ComponentClass: TComponentClass; Handler: TInitComponentHandler); Var I : Integer; H: TInitHandler; begin If (InitHandlerList=Nil) then InitHandlerList:=TList.Create; H:=TInitHandler.Create; H.Aclass:=ComponentClass; H.AHandler:=Handler; try With InitHandlerList do begin I:=0; While (I<Count) and not H.AClass.InheritsFrom(TInitHandler(Items[I]).AClass) do Inc(I); { override? } if (I<Count) and (TInitHandler(Items[I]).AClass=H.AClass) then begin TInitHandler(Items[I]).AHandler:=Handler; H.Free; end else InitHandlerList.Insert(I,H); end; except H.Free; raise; end; end; procedure TObjectStreamConverter.OutStr(s: String); Var I : integer; begin For I:=1 to Length(S) do Output.WriteBufferData(s[i]); end; procedure TObjectStreamConverter.OutLn(s: String); begin OutStr(s + LineEnding); end; (* procedure TObjectStreamConverter.Outchars(P, LastP : Pointer; CharToOrdFunc: CharToOrdFuncty; UseBytes: boolean = false); var res, NewStr: String; w: Cardinal; InString, NewInString: Boolean; begin if p = nil then begin res:= ''''''; end else begin res := ''; InString := False; while P < LastP do begin NewInString := InString; w := CharToOrdfunc(P); if w = ord('''') then begin //quote char if not InString then NewInString := True; NewStr := ''''''; end else if (Ord(w) >= 32) and ((Ord(w) < 127) or (UseBytes and (Ord(w)<256))) then begin //printable ascii or bytes if not InString then NewInString := True; NewStr := char(w); end else begin //ascii control chars, non ascii if InString then NewInString := False; NewStr := '#' + IntToStr(w); end; if NewInString <> InString then begin NewStr := '''' + NewStr; InString := NewInString; end; res := res + NewStr; end; if InString then res := res + ''''; end; OutStr(res); end; *) procedure TObjectStreamConverter.OutString(s: String); begin OutStr(S); end; (* procedure TObjectStreamConverter.OutUtf8Str(s: String); begin if Encoding=oteLFM then OutChars(Pointer(S),PChar(S)+Length(S),@CharToOrd) else OutChars(Pointer(S),PChar(S)+Length(S),@Utf8ToOrd); end; *) function TObjectStreamConverter.ReadWord : word; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE} begin Input.ReadBufferData(Result); end; function TObjectStreamConverter.ReadDWord : longword; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE} begin Input.ReadBufferData(Result); end; function TObjectStreamConverter.ReadNativeInt : NativeInt; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE} begin Input.ReadBufferData(Result); end; function TObjectStreamConverter.ReadInt(ValueType: TValueType): NativeInt; begin case ValueType of vaInt8: Result := ShortInt(Input.ReadByte); vaInt16: Result := SmallInt(ReadWord); vaInt32: Result := LongInt(ReadDWord); vaNativeInt: Result := ReadNativeInt; end; end; function TObjectStreamConverter.ReadInt: NativeInt; begin Result := ReadInt(TValueType(Input.ReadByte)); end; function TObjectStreamConverter.ReadDouble : Double; begin Input.ReadBufferData(Result); end; function TObjectStreamConverter.ReadStr: String; var l,i: Byte; c : Char; begin Input.ReadBufferData(L); SetLength(Result,L); For I:=1 to L do begin Input.ReadBufferData(C); Result[i]:=C; end; end; function TObjectStreamConverter.ReadString(StringType: TValueType): String; var i: Integer; C : Char; begin Result:=''; if StringType<>vaString then Raise EFilerError.Create('Invalid string type passed to ReadString'); i:=ReadDWord; SetLength(Result, i); for I:=1 to Length(Result) do begin Input.ReadbufferData(C); Result[i]:=C; end; end; procedure TObjectStreamConverter.ProcessBinary; var ToDo, DoNow, i: LongInt; lbuf: TBytes; s: String; begin ToDo := ReadDWord; SetLength(lBuf,32); OutLn('{'); while ToDo > 0 do begin DoNow := ToDo; if DoNow > 32 then DoNow := 32; Dec(ToDo, DoNow); s := Indent + ' '; Input.ReadBuffer(lbuf, DoNow); for i := 0 to DoNow - 1 do s := s + IntToHex(lbuf[i], 2); OutLn(s); end; OutLn(indent + '}'); end; procedure TObjectStreamConverter.ProcessValue(ValueType: TValueType; Indent: String); var s: String; { len: LongInt; } IsFirst: Boolean; {$ifndef FPUNONE} ext: Extended; {$endif} begin case ValueType of vaList: begin OutStr('('); IsFirst := True; while True do begin ValueType := TValueType(Input.ReadByte); if ValueType = vaNull then break; if IsFirst then begin OutLn(''); IsFirst := False; end; OutStr(Indent + ' '); ProcessValue(ValueType, Indent + ' '); end; OutLn(Indent + ')'); end; vaInt8: OutLn(IntToStr(ShortInt(Input.ReadByte))); vaInt16: OutLn( IntToStr(SmallInt(ReadWord))); vaInt32: OutLn(IntToStr(LongInt(ReadDWord))); vaNativeInt: OutLn(IntToStr(ReadNativeInt)); vaDouble: begin ext:=ReadDouble; Str(ext,S);// Do not use localized strings. OutLn(S); end; vaString: begin OutString(''''+StringReplace(ReadString(vaString),'''','''''',[rfReplaceAll])+''''); OutLn(''); end; vaIdent: OutLn(ReadStr); vaFalse: OutLn('False'); vaTrue: OutLn('True'); vaBinary: ProcessBinary; vaSet: begin OutStr('['); IsFirst := True; while True do begin s := ReadStr; if Length(s) = 0 then break; if not IsFirst then OutStr(', '); IsFirst := False; OutStr(s); end; OutLn(']'); end; vaNil: OutLn('nil'); vaCollection: begin OutStr('<'); while Input.ReadByte <> 0 do begin OutLn(Indent); Input.Seek(-1, soCurrent); OutStr(indent + ' item'); ValueType := TValueType(Input.ReadByte); if ValueType <> vaList then OutStr('[' + IntToStr(ReadInt(ValueType)) + ']'); OutLn(''); ReadPropList(indent + ' '); OutStr(indent + ' end'); end; OutLn('>'); end; {vaSingle: begin OutLn('!!Single!!'); exit end; vaCurrency: begin OutLn('!!Currency!!'); exit end; vaDate: begin OutLn('!!Date!!'); exit end;} else Raise EReadError.CreateFmt(SErrInvalidPropertyType,[Ord(ValueType)]); end; end; procedure TObjectStreamConverter.ReadPropList(indent: String); begin while Input.ReadByte <> 0 do begin Input.Seek(-1, soCurrent); OutStr(indent + ReadStr + ' = '); ProcessValue(TValueType(Input.ReadByte), Indent); end; end; procedure TObjectStreamConverter.ReadObject(indent: String); var b: Byte; ObjClassName, ObjName: String; ChildPos: LongInt; begin // Check for FilerFlags b := Input.ReadByte; if (b and $f0) = $f0 then begin if (b and 2) <> 0 then ChildPos := ReadInt; end else begin b := 0; Input.Seek(-1, soCurrent); end; ObjClassName := ReadStr; ObjName := ReadStr; OutStr(Indent); if (b and 1) <> 0 then OutStr('inherited') else if (b and 4) <> 0 then OutStr('inline') else OutStr('object'); OutStr(' '); if ObjName <> '' then OutStr(ObjName + ': '); OutStr(ObjClassName); if (b and 2) <> 0 then OutStr('[' + IntToStr(ChildPos) + ']'); OutLn(''); ReadPropList(indent + ' '); while Input.ReadByte <> 0 do begin Input.Seek(-1, soCurrent); ReadObject(indent + ' '); end; OutLn(indent + 'end'); end; procedure TObjectStreamConverter.ObjectBinaryToText(aInput, aOutput: TStream; aEncoding: TObjectTextEncoding); begin FInput:=aInput; FOutput:=aOutput; FEncoding:=aEncoding; Execute; end; procedure TObjectStreamConverter.Execute; begin if FIndent = '' then FInDent:=' '; If Not Assigned(Input) then raise EReadError.Create('Missing input stream'); If Not Assigned(Output) then raise EReadError.Create('Missing output stream'); if Input.ReadDWord <> FilerSignatureInt then raise EReadError.Create('Illegal stream image'); ReadObject(''); end; procedure TObjectStreamConverter.ObjectBinaryToText(aInput, aOutput: TStream); begin ObjectBinaryToText(aInput,aOutput,oteDFM); end; { This file is part of the Free Component Library (FCL) Copyright (c) 1999-2007 by the Free Pascal development team 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. **********************************************************************} {****************************************************************************} {* TParser *} {****************************************************************************} const {$ifdef CPU16} { Avoid too big local stack use for MSDOS tiny memory model that uses less than 4096 bytes for total stack by default. } ParseBufSize = 512; {$else not CPU16} ParseBufSize = 4096; {$endif not CPU16} TokNames : array[TParserToken] of string = ( '?', 'EOF', 'Symbol', 'String', 'Integer', 'Float', '-', '[', '(', '<', '{', ']', ')', '>', '}', ',', '.', '=', ':' ); function TParser.GetTokenName(aTok: TParserToken): string; begin Result:=TokNames[aTok] end; procedure TParser.LoadBuffer; var CharsRead,i: integer; begin CharsRead:=0; for I:=0 to ParseBufSize-1 do begin if FStream.ReadData(FBuf[i])<>2 then Break; Inc(CharsRead); end; Inc(FDeltaPos, CharsRead); FPos := 0; FBufLen := CharsRead; FEofReached:=CharsRead = 0; FBuf[CharsRead] := #0; end; procedure TParser.CheckLoadBuffer; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} begin if fPos>=FBufLen then LoadBuffer; end; procedure TParser.ProcessChar; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} begin fLastTokenStr:=fLastTokenStr+fBuf[fPos]; inc(fPos); CheckLoadBuffer; end; function TParser.IsNumber: boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} begin Result:=fBuf[fPos] in ['0'..'9']; end; function TParser.IsHexNum: boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} begin Result:=fBuf[fPos] in ['0'..'9','A'..'F','a'..'f']; end; function TParser.IsAlpha: boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} begin Result:=fBuf[fPos] in ['_','A'..'Z','a'..'z']; end; function TParser.IsAlphaNum: boolean; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} begin Result:=IsAlpha or IsNumber; end; function TParser.GetHexValue(c: char): byte; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE} begin case c of '0'..'9' : Result:=ord(c)-$30; 'A'..'F' : Result:=ord(c)-$37; //-$41+$0A 'a'..'f' : Result:=ord(c)-$57; //-$61+$0A end; end; function TParser.GetAlphaNum: string; begin if not IsAlpha then ErrorFmt(SParserExpected,[GetTokenName(toSymbol)]); Result:=''; while IsAlphaNum do begin Result:=Result+fBuf[fPos]; inc(fPos); CheckLoadBuffer; end; end; procedure TParser.HandleNewLine; begin if fBuf[fPos]=#13 then //CR begin inc(fPos); CheckLoadBuffer; end; if fBuf[fPos]=#10 then begin inc(fPos); //CR LF or LF CheckLoadBuffer; end; inc(fSourceLine); fDeltaPos:=-(fPos-1); end; procedure TParser.SkipBOM; begin // No BOM support end; procedure TParser.SkipSpaces; begin while fBuf[fPos] in [' ',#9] do begin inc(fPos); CheckLoadBuffer; end; end; procedure TParser.SkipWhitespace; begin while true do begin case fBuf[fPos] of ' ',#9 : SkipSpaces; #10,#13 : HandleNewLine else break; end; end; end; procedure TParser.HandleEof; begin fToken:=toEOF; fLastTokenStr:=''; end; procedure TParser.HandleAlphaNum; begin fLastTokenStr:=GetAlphaNum; fToken:=toSymbol; end; procedure TParser.HandleNumber; type floatPunct = (fpDot,fpE); floatPuncts = set of floatPunct; var allowed : floatPuncts; begin fLastTokenStr:=''; while IsNumber do ProcessChar; fToken:=toInteger; if (fBuf[fPos] in ['.','e','E']) then begin fToken:=toFloat; allowed:=[fpDot,fpE]; while (fBuf[fPos] in ['.','e','E','0'..'9']) do begin case fBuf[fPos] of '.' : if fpDot in allowed then Exclude(allowed,fpDot) else break; 'E','e' : if fpE in allowed then begin allowed:=[]; ProcessChar; if (fBuf[fPos] in ['+','-']) then ProcessChar; if not (fBuf[fPos] in ['0'..'9']) then ErrorFmt(SParserInvalidFloat,[fLastTokenStr+fBuf[fPos]]); end else break; end; ProcessChar; end; end; if (fBuf[fPos] in ['s','S','d','D','c','C']) then //single, date, currency begin fFloatType:=fBuf[fPos]; inc(fPos); CheckLoadBuffer; fToken:=toFloat; end else fFloatType:=#0; end; procedure TParser.HandleHexNumber; var valid : boolean; begin fLastTokenStr:='$'; inc(fPos); CheckLoadBuffer; valid:=false; while IsHexNum do begin valid:=true; ProcessChar; end; if not valid then ErrorFmt(SParserInvalidInteger,[fLastTokenStr]); fToken:=toInteger; end; function TParser.HandleQuotedString: string; begin Result:=''; inc(fPos); CheckLoadBuffer; while true do begin case fBuf[fPos] of #0 : ErrorStr(SParserUnterminatedString); #13,#10 : ErrorStr(SParserUnterminatedString); '''' : begin inc(fPos); CheckLoadBuffer; if fBuf[fPos]<>'''' then exit; end; end; Result:=Result+fBuf[fPos]; inc(fPos); CheckLoadBuffer; end; end; Function TParser.HandleDecimalCharacter : Char; var i : integer; begin inc(fPos); CheckLoadBuffer; // read a word number i:=0; while IsNumber and (i<high(word)) do begin i:=i*10+Ord(fBuf[fPos])-ord('0'); inc(fPos); CheckLoadBuffer; end; if i>high(word) then i:=0; Result:=Char(i); end; procedure TParser.HandleString; var s: string; begin fLastTokenStr:=''; while true do begin case fBuf[fPos] of '''' : begin s:=HandleQuotedString; fLastTokenStr:=fLastTokenStr+s; end; '#' : begin fLastTokenStr:=fLastTokenStr+HandleDecimalCharacter; end; else break; end; end; fToken:=Classes.toString end; procedure TParser.HandleMinus; begin inc(fPos); CheckLoadBuffer; if IsNumber then begin HandleNumber; fLastTokenStr:='-'+fLastTokenStr; end else begin fToken:=toMinus; fLastTokenStr:='-'; end; end; procedure TParser.HandleUnknown; begin fToken:=toUnknown; fLastTokenStr:=fBuf[fPos]; inc(fPos); CheckLoadBuffer; end; constructor TParser.Create(Stream: TStream); begin fStream:=Stream; SetLength(fBuf,Succ(ParseBufSize)); fBufLen:=0; fPos:=0; fDeltaPos:=1; fSourceLine:=1; fEofReached:=false; fLastTokenStr:=''; fFloatType:=#0; fToken:=toEOF; LoadBuffer; SkipBom; NextToken; end; destructor TParser.Destroy; Var aCount : Integer; begin aCount:=Length(fLastTokenStr)*2; fStream.Position:=SourcePos-aCount; end; procedure TParser.CheckToken(T: tParserToken); begin if fToken<>T then ErrorFmt(SParserWrongTokenType,[GetTokenName(T),GetTokenName(fToken)]); end; procedure TParser.CheckTokenSymbol(const S: string); begin CheckToken(toSymbol); if CompareText(fLastTokenStr,S)<>0 then ErrorFmt(SParserWrongTokenSymbol,[s,fLastTokenStr]); end; procedure TParser.Error(const Ident: string); begin ErrorStr(Ident); end; procedure TParser.ErrorFmt(const Ident: string; const Args: array of JSValue); begin ErrorStr(Format(Ident,Args)); end; procedure TParser.ErrorStr(const Message: string); begin raise EParserError.CreateFmt(Message+SParserLocInfo,[SourceLine,fPos+fDeltaPos,SourcePos]); end; procedure TParser.HexToBinary(Stream: TStream); var outbuf : TBytes; b : byte; i : integer; begin SetLength(OutBuf,ParseBufSize); i:=0; SkipWhitespace; while IsHexNum do begin b:=(GetHexValue(fBuf[fPos]) shl 4); inc(fPos); CheckLoadBuffer; if not IsHexNum then Error(SParserUnterminatedBinValue); b:=b or GetHexValue(fBuf[fPos]); inc(fPos); CheckLoadBuffer; outbuf[i]:=b; inc(i); if i>=ParseBufSize then begin Stream.WriteBuffer(outbuf,i); i:=0; end; SkipWhitespace; end; if i>0 then Stream.WriteBuffer(outbuf,i); NextToken; end; function TParser.NextToken: TParserToken; Procedure SetToken(aToken : TParserToken); begin FToken:=aToken; Inc(fPos); end; begin SkipWhiteSpace; if fEofReached then HandleEof else case fBuf[fPos] of '_','A'..'Z','a'..'z' : HandleAlphaNum; '$' : HandleHexNumber; '-' : HandleMinus; '0'..'9' : HandleNumber; '''','#' : HandleString; '[' : SetToken(toSetStart); '(' : SetToken(toListStart); '<' : SetToken(toCollectionStart); '{' : SetToken(toBinaryStart); ']' : SetToken(toSetEnd); ')' : SetToken(toListEnd); '>' : SetToken(toCollectionEnd); '}' : SetToken(toBinaryEnd); ',' : SetToken(toComma); '.' : SetToken(toDot); '=' : SetToken(toEqual); ':' : SetToken(toColon); else HandleUnknown; end; Result:=fToken; end; function TParser.SourcePos: Longint; begin Result:=fStream.Position-fBufLen+fPos; end; function TParser.TokenComponentIdent: string; begin if fToken<>toSymbol then ErrorFmt(SParserExpected,[GetTokenName(toSymbol)]); CheckLoadBuffer; while fBuf[fPos]='.' do begin ProcessChar; fLastTokenStr:=fLastTokenStr+GetAlphaNum; end; Result:=fLastTokenStr; end; Function TParser.TokenFloat: double; var errcode : integer; begin Val(fLastTokenStr,Result,errcode); if errcode<>0 then ErrorFmt(SParserInvalidFloat,[fLastTokenStr]); end; Function TParser.TokenInt: NativeInt; begin if not TryStrToInt64(fLastTokenStr,Result) then Result:=StrToQWord(fLastTokenStr); //second chance for malformed files end; function TParser.TokenString: string; begin case fToken of toFloat : if fFloatType<>#0 then Result:=fLastTokenStr+fFloatType else Result:=fLastTokenStr; else Result:=fLastTokenStr; end; end; function TParser.TokenSymbolIs(const S: string): Boolean; begin Result:=(fToken=toSymbol) and (CompareText(fLastTokenStr,S)=0); end; procedure TObjectTextConverter.WriteWord(w : word); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE} begin Output.WriteBufferData(w); end; procedure TObjectTextConverter.WriteDWord(lw : longword); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE} begin Output.WriteBufferData(lw); end; procedure TObjectTextConverter.WriteQWord(q : NativeInt); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE} begin Output.WriteBufferData(q); end; procedure TObjectTextConverter.WriteDouble(e : double); begin Output.WriteBufferData(e); end; procedure TObjectTextConverter.WriteString(s: String); var i,size : byte; begin if length(s)>255 then size:=255 else size:=length(s); Output.WriteByte(size); For I:=1 to Length(S) do Output.WriteBufferData(s[i]); end; procedure TObjectTextConverter.WriteWString(Const s: WideString); var i : Integer; begin WriteDWord(Length(s)); For I:=1 to Length(S) do Output.WriteBufferData(s[i]); end; procedure TObjectTextConverter.WriteInteger(value: NativeInt); begin if (value >= -128) and (value <= 127) then begin Output.WriteByte(Ord(vaInt8)); Output.WriteByte(byte(value)); end else if (value >= -32768) and (value <= 32767) then begin Output.WriteByte(Ord(vaInt16)); WriteWord(word(value)); end else if (value >= -2147483648) and (value <= 2147483647) then begin Output.WriteByte(Ord(vaInt32)); WriteDWord(longword(value)); end else begin Output.WriteByte(ord(vaInt64)); WriteQWord(NativeUInt(value)); end; end; procedure TObjectTextConverter.ProcessWideString(const left : string); var ws : string; begin ws:=left+parser.TokenString; while (parser.NextToken = classes.toString) and (Parser.TokenString='+') do begin parser.NextToken; // Get next string fragment if not (parser.Token=Classes.toString) then parser.CheckToken(Classes.toString); ws:=ws+parser.TokenString; end; Output.WriteByte(Ord(vaWstring)); WriteWString(ws); end; procedure TObjectTextConverter.ProcessValue; var flt: double; stream: TBytesStream; begin case parser.Token of toInteger: begin WriteInteger(parser.TokenInt); parser.NextToken; end; toFloat: begin Output.WriteByte(Ord(vaExtended)); flt := Parser.TokenFloat; WriteDouble(flt); parser.NextToken; end; classes.toString: ProcessWideString(''); toSymbol: begin if CompareText(parser.TokenString, 'True') = 0 then Output.WriteByte(Ord(vaTrue)) else if CompareText(parser.TokenString, 'False') = 0 then Output.WriteByte(Ord(vaFalse)) else if CompareText(parser.TokenString, 'nil') = 0 then Output.WriteByte(Ord(vaNil)) else begin Output.WriteByte(Ord(vaIdent)); WriteString(parser.TokenComponentIdent); end; Parser.NextToken; end; // Set toSetStart: begin parser.NextToken; Output.WriteByte(Ord(vaSet)); if parser.Token <> toSetEnd then while True do begin parser.CheckToken(toSymbol); WriteString(parser.TokenString); parser.NextToken; if parser.Token = toSetEnd then break; parser.CheckToken(toComma); parser.NextToken; end; Output.WriteByte(0); parser.NextToken; end; // List toListStart: begin parser.NextToken; Output.WriteByte(Ord(vaList)); while parser.Token <> toListEnd do ProcessValue; Output.WriteByte(0); parser.NextToken; end; // Collection toCollectionStart: begin parser.NextToken; Output.WriteByte(Ord(vaCollection)); while parser.Token <> toCollectionEnd do begin parser.CheckTokenSymbol('item'); parser.NextToken; // ConvertOrder Output.WriteByte(Ord(vaList)); while not parser.TokenSymbolIs('end') do ProcessProperty; parser.NextToken; // Skip 'end' Output.WriteByte(0); end; Output.WriteByte(0); parser.NextToken; end; // Binary data toBinaryStart: begin Output.WriteByte(Ord(vaBinary)); stream := TBytesStream.Create; try parser.HexToBinary(stream); WriteDWord(stream.Size); Output.WriteBuffer(Stream.Bytes,Stream.Size); finally stream.Free; end; parser.NextToken; end; else parser.Error(SParserInvalidProperty); end; end; procedure TObjectTextConverter.ProcessProperty; var name: String; begin // Get name of property parser.CheckToken(toSymbol); name := parser.TokenString; while True do begin parser.NextToken; if parser.Token <> toDot then break; parser.NextToken; parser.CheckToken(toSymbol); name := name + '.' + parser.TokenString; end; WriteString(name); parser.CheckToken(toEqual); parser.NextToken; ProcessValue; end; procedure TObjectTextConverter.ProcessObject; var Flags: Byte; ObjectName, ObjectType: String; ChildPos: Integer; begin if parser.TokenSymbolIs('OBJECT') then Flags :=0 { IsInherited := False } else begin if parser.TokenSymbolIs('INHERITED') then Flags := 1 { IsInherited := True; } else begin parser.CheckTokenSymbol('INLINE'); Flags := 4; end; end; parser.NextToken; parser.CheckToken(toSymbol); ObjectName := ''; ObjectType := parser.TokenString; parser.NextToken; if parser.Token = toColon then begin parser.NextToken; parser.CheckToken(toSymbol); ObjectName := ObjectType; ObjectType := parser.TokenString; parser.NextToken; if parser.Token = toSetStart then begin parser.NextToken; ChildPos := parser.TokenInt; parser.NextToken; parser.CheckToken(toSetEnd); parser.NextToken; Flags := Flags or 2; end; end; if Flags <> 0 then begin Output.WriteByte($f0 or Flags); if (Flags and 2) <> 0 then WriteInteger(ChildPos); end; WriteString(ObjectType); WriteString(ObjectName); // Convert property list while not (parser.TokenSymbolIs('END') or parser.TokenSymbolIs('OBJECT') or parser.TokenSymbolIs('INHERITED') or parser.TokenSymbolIs('INLINE')) do ProcessProperty; Output.WriteByte(0); // Terminate property list // Convert child objects while not parser.TokenSymbolIs('END') do ProcessObject; parser.NextToken; // Skip end token Output.WriteByte(0); // Terminate property list end; procedure TObjectTextConverter.ObjectTextToBinary(aInput, aOutput: TStream); begin FinPut:=aInput; FOutput:=aOutput; Execute; end; procedure TObjectTextConverter.Execute; begin If Not Assigned(Input) then raise EReadError.Create('Missing input stream'); If Not Assigned(Output) then raise EReadError.Create('Missing output stream'); FParser := TParser.Create(Input); try Output.WriteBufferData(FilerSignatureInt); ProcessObject; finally FParser.Free; end; end; procedure ObjectTextToBinary(aInput, aOutput: TStream); var Conv : TObjectTextConverter; begin Conv:=TObjectTextConverter.Create; try Conv.ObjectTextToBinary(aInput, aOutput); finally Conv.free; end; end; initialization ClassList:=TJSObject.New; end.
unit FPMathExpressionBridge; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpexprpars_wp, mpMath_wp, Math; type TIdentifierParse = procedure(Index: integer; AName: string; out AValue: real) of object; TExprFunc = procedure(var Result: TFPExpressionResult; const Args: TExprParameterArray); TEvalueteResult = record Value: real; IsValid: boolean; end; type TFPMathExpressionBridge = class(TComponent) private {Private declarations} //FAbout : boolean; FParser: TFPExpressionParser; FIdentifierDefList: TList; //list of TFPExprIdentifierDef FExpression: string; FVariableOfFunc: string; FVarIndex: integer; FExpressionList: TStrings; FVariableList: TStrings; //variables... FConstantList: TStrings; //variables... FOnVariableParse: TIdentifierParse; //variables... FOnConstantParse: TIdentifierParse; //variables... //procedure SetAbout(Value : boolean); procedure SetExpressionList(AValue: TStrings); procedure SetVariableList(AValue: TStrings); procedure SetConstantList(AValue: TStrings); procedure DoVariableParse(Index: integer; AName: string; out AValue: real); procedure DoConstantParse(Index: integer; AName: string; out AValue: real); procedure SetExpressionByIndex(Index: integer); function GetExpressionByIndex(Index: integer): string; function GetExpressionIndexByName(AName: string): integer; function GetVariableIndexByName(AName: string): integer; procedure SetExpression(Expr: string); procedure SetVariableOfFunc(AName: string); protected { Protected declarations } public {Public declarations} function EvalFunc(AValue: real): TEvalueteResult; overload; //one variable.... function EvalFunc(AValues: array of real): TEvalueteResult; overload; //many variables... function EvalExpr(Expr: string; ANamesVar: array of string): TEvalueteResult; overload; function EvalExpr: TEvalueteResult; overload; function AddVariable(AName: string): integer; function AddConstant(AName: string): integer; function AddExpression(Expr: string): integer; procedure AddFunction(AName: string; paramCount: integer; callFunc: TExprFunc); constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Expression: string read FExpression write SetExpression; property VariableOfFunc: string read FVariableOfFunc write SetVariableOfFunc; property VarIndex: integer read FVarIndex; published {Published declarations } //property About : boolean read FAbout write SetAbout; property ListExpressions: TStrings read FExpressionList write SetExpressionList; property ListConstants: TStrings read FConstantList write SetConstantList; property ListVariables: TStrings read FVariableList write SetVariableList; property OnVariableParse: TIdentifierParse read FOnVariableParse write FOnVariableParse; property OnConstantParse: TIdentifierParse read FOnConstantParse write FOnConstantParse; end; function TrimChar(sText: string; delchar: char): string; function SplitStr(var theString: string; delimiter: string): string; implementation (* procedure TFPMathExpressionBridge.SetAbout(Value : boolean); const CrLf = #13#10; var msg : string; begin if Value then begin msg := 'TFPMathExpressionBridge - Version 0.1 - 02/2013' + CrLf + 'Author: Jose Marques Pessoa : jmpessoa__hotmail_com'+ CrLf + 'TFPMathExpressionBridge is a warapper for [math]* subset'+ CrLf + 'of TFPExpressionParse** attempting to establish a easy semantics'+ CrLf + 'for construction of function graph and expression evaluete.'+ CrLf + '::Warning: at the moment this code is just a "proof-of-concept".'; MessageDlg(msg, mtInformation, [mbOK], 0); end; FAbout := false; end; *) //sintax AddFunction('Delta', 3, @ExprDelta) procedure TFPMathExpressionBridge.AddFunction(AName: string; paramCount: integer; callFunc: TExprFunc); var strF: string; i: integer; begin StrF:=''; for i:=0 to paramCount-1 do strF:= StrF+ 'F'; FParser.Identifiers.AddFunction(AName,'F',strF,callFunc); end; function TFPMathExpressionBridge.GetVariableIndexByName(AName: string): integer; begin Result:= FVariableList.IndexOf(Uppercase(AName)); end; procedure TFPMathExpressionBridge.SetExpressionList(AValue: TStrings); begin FExpressionList.Assign(AValue); end; procedure TFPMathExpressionBridge.SetVariableList(AValue: TStrings); begin FVariableList.Assign(AValue); end; procedure TFPMathExpressionBridge.SetConstantList(AValue: TStrings); begin FConstantList.Assign(AValue); end; procedure TFPMathExpressionBridge.DoVariableParse(Index: integer; AName: string; out AValue: real); begin if Assigned(FOnVariableParse) then FOnVariableParse(Index, AName, AValue); end; procedure TFPMathExpressionBridge.DoConstantParse(Index: integer; AName: string; out AValue: real); begin if Assigned(FOnConstantParse) then FOnConstantParse(Index, AName, AValue); end; procedure TFPMathExpressionBridge.SetExpressionByIndex(Index: integer); begin SetExpression(ListExpressions.Strings[Index]); end; function TFPMathExpressionBridge.GetExpressionByIndex(Index: integer): string; begin Result:= ListExpressions.Strings[Index]; end; function TFPMathExpressionBridge.GetExpressionIndexByName(AName: string): integer; begin Result:= ListExpressions.IndexOf(AName); end; function TFPMathExpressionBridge.AddVariable(AName: string): integer; var upperName: string; begin Result:= -1; upperName:= Uppercase(Trim(AName)); FVariableOfFunc:= upperName; if FVariableList.Count > 0 then Result:= FVariableList.IndexOf(upperName); if Result < 0 then //not found begin FVariableList.Add(upperName); FVarIndex:= FVariableList.Count-1; //index Result:= FVarIndex; end; end; function TFPMathExpressionBridge.AddConstant(AName: string): integer; var upperStr: string; cName: string; begin upperStr:= Uppercase(Trim(AName)); if Pos('=', upperStr) > 0 then begin cName:= SplitStr(upperStr, '='); Result:= FConstantList.IndexOf(cName); if Result < 0 then begin FConstantList.Add(cName); Result:= FConstantList.Count-1; //index end; end else begin Result:= FConstantList.IndexOf(upperStr); if Result < 0 then begin FConstantList.Add(upperStr); Result:= FConstantList.Count-1; //index end; end; end; function TFPMathExpressionBridge.AddExpression(Expr: string): integer; var upperName: string; begin Result:= -1; upperName:= Trim(Uppercase(Expr)); if FExpressionList.Count > 0 then Result:= FExpressionList.IndexOf(upperName); //fixed! thanks to @mars if Result < 0 then //not found ... begin FExpressionList.Add(upperName); Result:= FExpressionList.Count-1; //index end; end; procedure TFPMathExpressionBridge.SetVariableOfFunc(AName: string); begin FVariableOfFunc:= Uppercase(Trim(AName)); FVarIndex:= GetVariableIndexByName(FVariableOfFunc); if FVarIndex < 0 then FVarIndex:= AddVariable(FVariableOfFunc); end; procedure TFPMathExpressionBridge.SetExpression(Expr: string); var i, indexExpr: integer; upperExpr: string; cName: string; outValue: real; begin for i:= 0 to FConstantList.Count-1 do begin if FParser.Identifiers.IndexOfIdentifier(FConstantList.Strings[i]) < 0 then //if not exist --> Add begin cName:= FConstantList.Strings[i]; DoConstantParse(i, cName, outValue); //event driver! FIdentifierDefList.Add(TFPExprIdentifierDef( FParser.Identifiers.AddFloatVariable(cName, outValue))); end; end; if FVariableList.Count > 0 then begin for i:= 0 to FVariableList.Count-1 do begin if FParser.Identifiers.IndexOfIdentifier(FVariableList.Strings[i]) < 0 then //if not exist --> Add begin FIdentifierDefList.Add(TFPExprIdentifierDef( FParser.Identifiers.AddFloatVariable(FVariableList.Strings[i],0.0))); end; end; end; upperExpr:= Uppercase(Trim(Expr)); indexExpr:= -1; if FExpressionList.Count > 0 then indexExpr:= FExpressionList.IndexOf(upperExpr); //fixed! thanks to @mars if indexExpr < 0 then FExpressionList.Add(upperExpr); FExpression:= upperExpr; FParser.Expression:= FExpression; end; //assign values for the firsts "count" variables.... function TFPMathExpressionBridge.EvalFunc(AValues: array of real): TEvalueteResult; Var E : TFPExpressionResult; i, j, count: integer; begin Result.Value:= 0.0; Result.IsValid:= False; j:= FConstantList.Count; //constants... count:= Length(AValues); if FVariableList.Count > 0 then begin //j is the first index disponible for variables! for i:= 0 to count-1 do begin if (i+j) < FIdentifierDefList.Count then TFPExprIdentifierDef(FIdentifierDefList.Items[j+i]).AsFloat:= AValues[i]; end; E:= FParser.Evaluate; if not IsNaN(E.ResFloat) then begin Result.Value:= E.ResFloat; Result.IsValid:= True; end; end; end; //only one variable... what? just FVariableOfFunc/FVarIndex function TFPMathExpressionBridge.EvalFunc(AValue: real): TEvalueteResult; Var E: TFPExpressionResult; j: integer; indexVar: integer; begin indexVar:= FVarIndex; Result.Value:= 0.0; Result.IsValid:= False; j:= FConstantList.Count; //constants... if FVariableList.Count > 0 then begin //j is the first index disponible for variables! TFPExprIdentifierDef(FIdentifierDefList.Items[j+indexVar]).AsFloat:= AValue; E:=FParser.Evaluate; if not IsNaN(E.ResFloat) then begin Result.Value:= E.ResFloat; Result.IsValid:= True; end; end end; function TFPMathExpressionBridge.EvalExpr: TEvalueteResult; // entirely event driver! Var E: TFPExpressionResult; outValue: real; j, i: integer; begin Result.Value:= 0.0; Result.IsValid:= False; //j is the first index disponible for variables! j:= FConstantList.Count; //NOTE: varibles index comes after last constant by code design! for i:= 0 to FVariableList.Count-1 do //variables begin DoVariableParse(i, FVariableList.Strings[i], outValue); //event driver! TFPExprIdentifierDef(FIdentifierDefList.Items[j+i]).AsFloat:= outValue; //NOTE: varibles index comes after last constant! end; E:=FParser.Evaluate; if not IsNaN(E.ResFloat) then begin Result.Value:= E.ResFloat; Result.IsValid:= True; end; end; function TFPMathExpressionBridge.EvalExpr(Expr: string; ANamesVar: array of string): TEvalueteResult; var i, count: integer; begin count:= Length(ANamesVar); for i:= 0 to count-1 do AddVariable(Uppercase(Trim(ANamesVar[i]))); SetExpression(Expr); Result:= Self.EvalExpr; //here "Self" must have! end; constructor TFPMathExpressionBridge.Create(AOwner: TComponent); begin inherited Create(AOwner); FExpressionList:= TStringList.Create; FVariableList:= TStringList.Create; FConstantList:= TStringList.Create; FIdentifierDefList:= TList.Create; FParser:= TFPExpressionParser.Create(nil); //nil? FParser.BuiltIns:= [bcMath]; //only Math functions! //Added by wp .......... Thank you wp!!! FParser.Identifiers.AddFunction('Degtorad', 'F', 'F', @ExprDegtorad); FParser.Identifiers.AddFunction('Radtodeg', 'F', 'F', @ExprRadtodeg); FParser.Identifiers.AddFunction('Tan', 'F', 'F', @ExprTan); FParser.Identifiers.AddFunction('Cot', 'F', 'F', @ExprCot); FParser.Identifiers.AddFunction('Arcsin', 'F', 'F', @ExprArcsin); FParser.Identifiers.AddFunction('Arccos', 'F', 'F', @ExprArccos); FParser.Identifiers.AddFunction('Arccot', 'F', 'F', @ExprArccot); FParser.Identifiers.AddFunction('Cosh', 'F', 'F', @ExprCosh); FParser.Identifiers.AddFunction('Coth', 'F', 'F', @ExprCoth); FParser.Identifiers.AddFunction('Sinh', 'F', 'F', @ExprSinh); FParser.Identifiers.AddFunction('Tanh', 'F', 'F', @ExprTanh); FParser.Identifiers.AddFunction('Arcosh', 'F', 'F', @ExprArcosh); FParser.Identifiers.AddFunction('Arsinh', 'F', 'F', @ExprArsinh); FParser.Identifiers.AddFunction('Artanh', 'F', 'F', @ExprArtanh); FParser.Identifiers.AddFunction('Arcoth', 'F', 'F', @ExprArcoth); FParser.Identifiers.AddFunction('Sinc', 'F', 'F', @ExprSinc); FParser.Identifiers.AddFunction('Power', 'F', 'FF', @ExprPower); FParser.Identifiers.AddFunction('Hypot', 'F', 'FF', @ExprHypot); FParser.Identifiers.AddFunction('Log10', 'F', 'F', @ExprLog10); FParser.Identifiers.AddFunction('Log2', 'F', 'F', @ExprLog2); FParser.Identifiers.AddFunction('Erf', 'F', 'F', @ExprErf); FParser.Identifiers.AddFunction('Erfc', 'F', 'F', @ExprErfc); FParser.Identifiers.AddFunction('I0', 'F', 'F', @ExprI0); FParser.Identifiers.AddFunction('I1', 'F', 'F', @ExprI1); FParser.Identifiers.AddFunction('J0', 'F', 'F', @ExprJ0); FParser.Identifiers.AddFunction('J1', 'F', 'F', @ExprJ1); FParser.Identifiers.AddFunction('K0', 'F', 'F', @ExprK0); FParser.Identifiers.AddFunction('K1', 'F', 'F', @ExprK1); FParser.Identifiers.AddFunction('Y0', 'F', 'F', @ExprY0); FParser.Identifiers.AddFunction('Y1', 'F', 'F', @ExprY1); FParser.Identifiers.AddFunction('Max', 'F', 'FF', @ExprMax); FParser.Identifiers.AddFunction('Min', 'F', 'FF', @ExprMin); end; destructor TFPMathExpressionBridge.Destroy; var i: integer; begin FExpressionList.Free; FVariableList.Free; FConstantList.Free; for i:= 0 to FIdentifierDefList.Count-1 do begin TFPExprIdentifierDef(FIdentifierDefList.Items[i]).Free; end; FIdentifierDefList.Free; FreeAndNil(FParser); inherited Destroy; end; {Generics function} function TrimChar(sText: string; delchar: char): string; var S: string; begin S := sText; while Pos(delchar,S) > 0 do Delete(S,Pos(delchar,S),1); Result := S; end; function SplitStr(var theString: string; delimiter: string): string; var i: integer; begin Result:= ''; if theString <> '' then begin i:= Pos(delimiter, theString); if i > 0 then begin Result:= Copy(theString, 1, i-1); theString:= Copy(theString, i+Length(delimiter), maxLongInt); end else begin Result := theString; theString := ''; end; end; end; end.
unit Emacsbasebindings; interface uses SysUtils, Classes, ToolsAPI; const kfImplicits = kfImplicitShift or kfImplicitModifier or kfImplicitKeypad; type TEmacsBindings = class(TNotifierObject, IUnknown, IOTANotifier) protected { Utility functions } function MarkWord(const Context: IOTAKeyContext): IOTAEditBlock; procedure SlideBlock(const Context: IOTAKeyContext; Backward: Boolean); { Default binding implementations } procedure AddWatchAtCursor(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure RunToCursor(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure EvaluateModify(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure AutoCodeInsight(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure BrowseSymbolAtCursor(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure BlockSave(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure ClassNavigate(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure ClassComplete(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure ClipClear(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure ClipCopy(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure ClipCut(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure ClipPaste(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure CodeTemplate(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure CodeCompletion(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure DebugInspect(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure GotoLine(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure HelpKeyword(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure IncrementalSearch(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure InsertCompilerOptions(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure InsertNewGUID(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure NullCmd(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure OpenFileAtCursor(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure OpenLine(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure Print(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure SetBlockStyle(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure SearchAgain(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure SearchFind(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure SearchReplace(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure SwapCPPHeader(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); procedure ViewExplorer(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); end; resourcestring sNoBlockMarked = 'No block marked'; implementation { TEmacsBindings } procedure TEmacsBindings.AddWatchAtCursor(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).AddWatchAtCursor; BindingResult := krHandled; end; procedure TEmacsBindings.RunToCursor(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).RunToCursor; BindingResult := krHandled; end; procedure TEmacsBindings.EvaluateModify(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).EvaluateModify; BindingResult := krHandled; end; procedure TEmacsBindings.AutoCodeInsight(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); var EP: IOTAEditPosition; EA: IOTAEditActions; AChar: Char; begin EP := Context.EditBuffer.EditPosition; EA := Context.EditBuffer.TopView as IOTAEditActions; AChar := Char(Byte(Context.Context)); EP.InsertCharacter(AChar); case AChar of '.', '>': EA.CodeCompletion(csCodeList); '(': EA.CodeCompletion(csParamList); end; BindingResult := krHandled; end; procedure TEmacsBindings.BlockSave(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.EditBlock.SaveToFile(''); BindingResult := krHandled; end; procedure TEmacsBindings.BrowseSymbolAtCursor(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).BrowseSymbolAtCursor; BindingResult := krHandled; end; procedure TEmacsBindings.ClassComplete(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).ClassComplete; BindingResult := krHandled; end; procedure TEmacsBindings.ClassNavigate(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).ClassNavigate(0); BindingResult := krHandled; end; procedure TEmacsBindings.ClipClear(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.EditBlock.Delete; BindingResult := krHandled; end; procedure TEmacsBindings.ClipCopy(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.EditBlock.Copy(False); BindingResult := krHandled; end; procedure TEmacsBindings.ClipCut(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.EditBlock.Cut(False); BindingResult := krHandled; end; procedure TEmacsBindings.ClipPaste(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.EditPosition.Paste; BindingResult := krHandled; end; procedure TEmacsBindings.CodeCompletion(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).CodeCompletion(Byte(Context.Context)); BindingResult := krHandled; end; procedure TEmacsBindings.CodeTemplate(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).CodeTemplate; BindingResult := krHandled; end; procedure TEmacsBindings.DebugInspect(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).InspectAtCursor; BindingResult := krHandled; end; procedure TEmacsBindings.GotoLine(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.EditPosition.GotoLine(0); BindingResult := krHandled; end; procedure TEmacsBindings.HelpKeyword(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).HelpKeyword; BindingResult := krHandled; end; procedure TEmacsBindings.IncrementalSearch(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin if Assigned(Context.Context) then Context.EditBuffer.EditPosition.SearchOptions.SetDirection(sdBackward) else Context.EditBuffer.EditPosition.SearchOptions.SetDirection(sdForward); (Context.EditBuffer.TopView as IOTAEditActions).IncrementalSearch; BindingResult := krHandled; end; procedure TEmacsBindings.InsertCompilerOptions(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).InsertCompilerOptions; BindingResult := krHandled; end; procedure TEmacsBindings.InsertNewGUID(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).InsertNewGUID; BindingResult := krHandled; end; function TEmacsBindings.MarkWord(const Context: IOTAKeyContext): IOTAEditBlock; var EP: IOTAEditPosition; EB: IOTAEditBlock; begin EP := Context.EditBuffer.EditPosition; EB := Context.EditBuffer.EditBlock; if EP.IsWordCharacter then EP.MoveCursor(mmSkipLeft or mmSkipWord); if EP.IsWhiteSpace then EP.MoveCursor(mmSkipRight or mmSkipWhite); if not EP.IsWhiteSpace then begin if not EP.IsWordCharacter then EP.MoveCursor(mmSkipRight or mmSkipNonWord); if EP.IsWordCharacter then begin EB.Reset; EB.Style := btNonInclusive; EB.BeginBlock; EP.MoveCursor(mmSkipRight or mmSkipWord); EB.EndBlock; end; end; Result := EB; end; procedure TEmacsBindings.NullCmd(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin BindingResult := krHandled; end; procedure TEmacsBindings.OpenFileAtCursor(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).OpenFileAtCursor; BindingResult := krHandled; end; procedure TEmacsBindings.OpenLine(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); var EP: IOTAEditPosition; begin EP := Context.EditBuffer.EditPosition; EP.Save; try EP.InsertCharacter(#10); finally EP.Restore; end; BindingResult := krHandled; end; procedure TEmacsBindings.Print(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.Print; BindingResult := krHandled; end; procedure TEmacsBindings.SearchAgain(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.EditPosition.RepeatLastSearchOrReplace; BindingResult := krHandled; end; procedure TEmacsBindings.SearchFind(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.EditPosition.Search; BindingResult := krHandled; end; procedure TEmacsBindings.SearchReplace(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin Context.EditBuffer.EditPosition.Replace; BindingResult := krHandled; end; procedure TEmacsBindings.SetBlockStyle(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); var Style: TOTABlockType; begin Style := TOTABlockType(Context.Context); Assert((Style >= btInclusive) and (Style < btUnknown), 'Invalid block style'); // do not localize Context.EditBuffer.EditBlock.Style := Style; BindingResult := krHandled; end; procedure TEmacsBindings.SlideBlock(const Context: IOTAKeyContext; Backward: Boolean); var EB: IOTAEditBlock; IndentAmount: Integer; begin EB := Context.EditBuffer.EditBlock; if EB.Size <> 0 then begin IndentAmount := Context.KeyboardServices.EditorServices.EditOptions.BlockIndent; if Backward then IndentAmount := IndentAmount * -1; EB.Indent(IndentAmount); end else Context.EditBuffer.TopView.SetTempMsg(sNoBlockMarked); end; procedure TEmacsBindings.SwapCPPHeader(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).SwapCPPHeader; BindingResult := krHandled; end; procedure TEmacsBindings.ViewExplorer(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); begin (Context.EditBuffer.TopView as IOTAEditActions).ViewExplorer; BindingResult := krHandled; 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.Android; interface uses AndroidApi.ProgressDialog, AndroidApi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, FGX.ProgressDialog, FGX.ProgressDialog.Types; type { TAndroidProgressDialogService } TAndroidProgressDialogService = class(TInterfacedObject, IFGXProgressDialogService) public { IFGXProgressDialogService } function CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog; function CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog; end; TDialogDismissListener = class; TAndroidNativeActivityDialog = class(TfgNativeActivityDialog) private FID: Integer; FNativeDialog: JProgressDialog; FDialogListener: TDialogDismissListener; protected procedure InitNativeDialog; virtual; { inherited } procedure TitleChanged; override; procedure MessageChanged; override; procedure CancellableChanged; override; function GetIsShown: Boolean; override; public constructor Create(const AOwner: TObject); override; destructor Destroy; override; procedure Show; override; procedure Hide; override; property ID: Integer read FID; end; TAndroidNativeProgressDialog = class(TfgNativeProgressDialog) private FID: Integer; FNativeDialog: JProgressDialog; FDialogListener: TDialogDismissListener; protected function IsDialogKindDeterminated(const DialogKind: TfgProgressDialogKind): Boolean; procedure InitNativeDialog; virtual; { inherited } procedure TitleChanged; override; procedure KindChanged; override; procedure MessageChanged; override; procedure ProgressChanged; override; procedure CancellableChanged; override; procedure RangeChanged; override; function GetIsShown: Boolean; override; public constructor Create(const AOwner: TObject); override; destructor Destroy; override; procedure ResetProgress; override; procedure Show; override; procedure Hide; override; property ID: Integer read FID; end; TDialogDismissListener = class(TJavaLocal, JDialogInterface_OnCancelListener) private [Weak] FDialog: TfgNativeDialog; public constructor Create(const ADialog: TfgNativeDialog); { JDialogInterface_OnCancelListener } procedure onCancel(dialog: JDialogInterface); cdecl; end; procedure RegisterService; procedure UnregisterService; implementation uses System.SysUtils, System.Classes, Androidapi.Helpers, AndroidApi.JNI.JavaTypes, Androidapi.JNI.App, FMX.Platform, FMX.Platform.Android, FMX.Helpers.Android, FMX.Types, FGX.Helpers, FGX.Helpers.Android, FGX.Asserts; procedure RegisterService; begin if TOSVersion.Check(2, 0) then TPlatformServices.Current.AddPlatformService(IFGXProgressDialogService, TAndroidProgressDialogService.Create); end; procedure UnregisterService; begin TPlatformServices.Current.RemovePlatformService(IFGXProgressDialogService); end; { TAndroidProgressDialogService } function TAndroidProgressDialogService.CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog; begin Result := TAndroidNativeActivityDialog.Create(AOwner); end; function TAndroidProgressDialogService.CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog; begin Result := TAndroidNativeProgressDialog.Create(AOwner); end; { TAndroidNativeProgressDialog } procedure TAndroidNativeActivityDialog.CancellableChanged; begin AssertIsNotNil(FNativeDialog); CallInUIThread(procedure begin FNativeDialog.setCancelable(Cancellable); FNativeDialog.setCanceledOnTouchOutside(Cancellable); end); end; constructor TAndroidNativeActivityDialog.Create(const AOwner: TObject); var ThemeID: Integer; begin inherited Create(AOwner); FID := TfgGeneratorUniqueID.GenerateID; FDialogListener := TDialogDismissListener.Create(Self); ThemeID := GetNativeTheme(AOwner); CallInUIThreadAndWaitFinishing(procedure begin FNativeDialog := TJProgressDialog.JavaClass.init(TAndroidHelper.Context, ThemeID); end); end; destructor TAndroidNativeActivityDialog.Destroy; begin FNativeDialog := nil; FreeAndNil(FDialogListener); inherited Destroy; end; function TAndroidNativeActivityDialog.GetIsShown: Boolean; begin Result := FNativeDialog.isShowing; end; procedure TAndroidNativeActivityDialog.Hide; begin AssertIsNotNil(FNativeDialog); inherited; DoHide; CallInUIThread(procedure begin HideDialog(FNativeDialog, FID); end); end; procedure TAndroidNativeActivityDialog.InitNativeDialog; begin AssertIsNotNil(FNativeDialog); FNativeDialog.setTitle(StrToJCharSequence(Title)); FNativeDialog.setMessage(StrToJCharSequence(Message)); FNativeDialog.setProgressStyle(TJProgressDialog.JavaClass.STYLE_SPINNER); FNativeDialog.setCanceledOnTouchOutside(Cancellable); FNativeDialog.setCancelable(Cancellable); FNativeDialog.setOnCancelListener(FDialogListener); end; procedure TAndroidNativeActivityDialog.MessageChanged; begin AssertIsNotNil(FNativeDialog); CallInUIThread(procedure begin FNativeDialog.setMessage(StrToJCharSequence(Message)); end); end; procedure TAndroidNativeActivityDialog.Show; begin AssertIsNotNil(FNativeDialog); inherited; CallInUIThread(procedure begin InitNativeDialog; ShowDialog(FNativeDialog, FID); end); DoShow; end; procedure TAndroidNativeActivityDialog.TitleChanged; begin AssertIsNotNil(FNativeDialog); CallInUIThread(procedure begin FNativeDialog.setTitle(StrToJCharSequence(Title)); end); end; { TAndroidNativeActivityDialog } procedure TAndroidNativeProgressDialog.CancellableChanged; begin AssertIsNotNil(FNativeDialog); CallInUIThread(procedure begin FNativeDialog.setCancelable(Cancellable); FNativeDialog.setCanceledOnTouchOutside(Cancellable); end); end; constructor TAndroidNativeProgressDialog.Create(const AOwner: TObject); var ThemeID: Integer; begin inherited Create(AOwner); FID := TfgGeneratorUniqueID.GenerateID; FDialogListener := TDialogDismissListener.Create(Self); ThemeID := GetNativeTheme(AOwner); CallInUIThreadAndWaitFinishing(procedure begin FNativeDialog := TJProgressDialog.JavaClass.init(TAndroidHelper.Context, ThemeID); end); end; destructor TAndroidNativeProgressDialog.Destroy; begin FNativeDialog := nil; FreeAndNil(FDialogListener); inherited Destroy; end; function TAndroidNativeProgressDialog.GetIsShown: Boolean; begin Result := FNativeDialog.isShowing; end; procedure TAndroidNativeProgressDialog.Hide; begin AssertIsNotNil(FNativeDialog); inherited; DoHide; CallInUIThread(procedure begin HideDialog(FNativeDialog, FID); end); end; procedure TAndroidNativeProgressDialog.InitNativeDialog; begin AssertIsNotNil(FNativeDialog); FNativeDialog.setTitle(StrToJCharSequence(Title)); FNativeDialog.setMessage(StrToJCharSequence(Message)); FNativeDialog.setMax(Round(Max)); FNativeDialog.setProgress(Round(Progress)); FNativeDialog.setProgressStyle(TJProgressDialog.JavaClass.STYLE_HORIZONTAL); FNativeDialog.setIndeterminate(IsDialogKindDeterminated(Kind)); FNativeDialog.setCanceledOnTouchOutside(Cancellable); FNativeDialog.setCancelable(Cancellable); FNativeDialog.setOnCancelListener(FDialogListener); end; function TAndroidNativeProgressDialog.IsDialogKindDeterminated(const DialogKind: TfgProgressDialogKind): Boolean; begin Result := DialogKind = TfgProgressDialogKind.Undeterminated; end; procedure TAndroidNativeProgressDialog.KindChanged; begin AssertIsNotNil(FNativeDialog); CallInUIThread(procedure begin FNativeDialog.setIndeterminate(IsDialogKindDeterminated(Kind)); end); end; procedure TAndroidNativeProgressDialog.MessageChanged; begin AssertIsNotNil(FNativeDialog); CallInUIThread(procedure begin FNativeDialog.setMessage(StrToJCharSequence(Message)); end); end; procedure TAndroidNativeProgressDialog.ProgressChanged; begin AssertIsNotNil(FNativeDialog); CallInUIThread(procedure begin FNativeDialog.setProgress(Round(Progress)); end); end; procedure TAndroidNativeProgressDialog.RangeChanged; begin AssertIsNotNil(FNativeDialog); inherited RangeChanged; CallInUIThread(procedure begin FNativeDialog.setMax(Round(Max)); end); end; procedure TAndroidNativeProgressDialog.ResetProgress; begin AssertIsNotNil(FNativeDialog); inherited ResetProgress; CallInUIThread(procedure begin FNativeDialog.setProgress(0); end); end; procedure TAndroidNativeProgressDialog.Show; begin AssertIsNotNil(FNativeDialog); inherited; CallInUIThread(procedure begin InitNativeDialog; ShowDialog(FNativeDialog, FID); end); DoShow; end; procedure TAndroidNativeProgressDialog.TitleChanged; begin AssertIsNotNil(FNativeDialog); CallInUIThread(procedure begin FNativeDialog.setTitle(StrToJCharSequence(Title)); end); end; { TDialogDismissListener } constructor TDialogDismissListener.Create(const ADialog: TfgNativeDialog); begin AssertIsNotNil(ADialog); inherited Create; FDialog := ADialog; end; procedure TDialogDismissListener.onCancel(dialog: JDialogInterface); begin AssertIsNotNil(FDialog); TThread.Synchronize(nil, procedure begin if Assigned(FDialog.OnCancel) then FDialog.OnCancel(FDialog.Owner); end); end; end.
unit UnCodigoBarra; interface uses sysUtils, classes ; type TCodigoBarra = class private public function retornaItem( Mascara : String ) : TstringList; function retornaTamanhos( Mascara : String ) : TstringList; Function GeraCodigoBarra( Mascara, Empresa, CodEmpFil, Classificacao, Produto, Referencia, Sequencial, BarraFor : string ) : string; end; implementation uses constantes, funstring; {***************** Gera os codigos dos Items do codigo *********************** 'A' = Empresa 'B' = filial 'C' = Classificacao do Produto 'D' = Codigo do Produto 'E' = Referencia do Fornecedor 'F' = Sequencial 'G' = Codigo de Barra do Fornecedor ******************************************************************************} function TCodigoBarra.retornaItem( Mascara : String ) : TstringList; var laco : integer; begin result := TStringList.create; laco := 2; while laco < length(mascara) do begin result.Add(mascara[laco]); laco := laco + 3; end; end; { ********** gera uma lista com os tamanhos dos items ************************ } function TCodigoBarra.retornaTamanhos( Mascara : String ) : TstringList; var laco : integer; begin result := TStringList.create; laco := 3; while laco < length(mascara) do begin result.Add(mascara[laco] + mascara[laco + 1] ); laco := laco + 3; end; end; {***************** gera o codigo de barras *********************************** } Function TCodigoBarra.GeraCodigoBarra( Mascara, Empresa, CodEmpFil, Classificacao, Produto, Referencia, Sequencial, BarraFor : string ) : string; var Tipo, Tamanho : TStringList; codigo : string; laco : integer; begin tipo := retornaItem(mascara); tamanho := retornaTamanhos(mascara); codigo := ''; for laco := 0 to Tipo.count - 1 do case tipo.Strings[laco][1] of 'A' : begin codigo := codigo + AdicionaCharE('0', Empresa, StrToInt(Tamanho.Strings[laco])); end; 'B' : begin codigo := codigo + AdicionaCharE('0', CodEmpFil, StrToInt(Tamanho.Strings[laco])); end; 'C' : begin codigo := codigo + AdicionaCharE('0', Classificacao, StrToInt(Tamanho.Strings[laco])); end; 'D' : begin codigo := codigo + AdicionaCharE('0', Produto, StrToInt(Tamanho.Strings[laco])); end; 'E' : begin codigo := codigo + AdicionaCharE('0', Referencia, StrToInt(Tamanho.Strings[laco])); end; 'F' : begin codigo := codigo + AdicionaCharE('0', Sequencial, StrToInt(Tamanho.Strings[laco])); end; 'G' : begin codigo := codigo + AdicionaCharE('0', BarraFor, StrToInt(Tamanho.Strings[laco])); end; end; result := codigo; end; end.
unit UnitEngineMasterData; interface uses System.Classes, UnitEnumHelper; type THimsenWearingSpareRec = record fHullNo, fEngineType, fTCModel, fRunningHour, fCylCount, fRatedRPM, fMainBearingMaker : string; fTierStep, fUsage: integer; fIsRetrofit: Boolean; end; TEngineMasterQueryDateType = (emdtNull, emdtProductDeliveryDate, emdtShipDeliveryDate, emdtWarrantyDueDate, emdtFinal); TEngineProductType = (vepteNull, vepte2StrokeEngine, vepte4StrokeEngine, vepteSternPost, veptePowerPlant, vepteEcoMachine, vepteGearBox, vepteVesselPump, vepteTurbine, veptePump, vepteFinal); TEngine2SProductType = (en2ptNull, en2ptStartingBox, en2ptEngineController, en2ptFinal);//2 Stroke Engine TEngine2SProductTypes = set of TEngine2SProductType; TEngine4SProductType = (en4ptNull, en4ptStartingBox, en4ptEngineController, en4ptLCP, en4ptFinal);//4 Stroke Engine TEngine4SProductTypes = set of TEngine4SProductType; TEngineModel_TierI = (et1Null, et1H1728, et1H1728U, et1H1728E, et1H2132, et1H2533, et1H3240, et1Final); TEngineModel_TierII = (et2Null, et2H1728, et2H1728U, et2H1728E, et2H2132, et2H2533V, et2H3240V, et2Final); TEngineModel_TierIII = (et3Null, et3H22DF, et3H27DF, et3H35DF, et3H54DF, et3H35G, et3H54G, et3Final); TTCModel_TierI = (tt1Null, tt1HPR3000, tt1HPR4000, tt1HPR5000, tt1HPR6000, tt1TPS44, tt1TPS48, tt1TPS52, tt1TPS57, tt1TPS61, tt1TPL67, tt1Final); TTCModel_TierII = (tt2Null, tt2ST3, tt2ST4, tt2ST5, tt2ST6, tt2ST7, tt2A130, tt2A135, tt2A140, tt2A145, tt2A150, tt2A155, tt2TPL65, tt2TPL67, tt2Final); TTCModel_TierIII = (tt3Null, tt3ST7, tt3A150, tt3A155, tt3Final); TEngineUsage = (euNull, euMarine, euStatinoary, euPropulsion, euFinal); TMainBearingMaker = (mmbNull, mbmMiba, mbmDaido, mbmFinal); const R_EngineMasterQueryDateType : array[Low(TEngineMasterQueryDateType)..High(TEngineMasterQueryDateType)] of string = ('', 'Product Delivery Date', 'Ship Delivery Date', 'Warranty Due Date', ''); R_EngineProductType : array[Low(TEngineProductType)..High(TEngineProductType)] of string = ('', '대형엔진', '중형엔진', '선미재', '엔진발전', '환경기계', '기어박스', '박용펌프', '터빈', 'PUMP', ''); R_Engine2SProductType : array[Low(TEngine2SProductType)..High(TEngine2SProductType)] of string = ( '', '(2행정)전계장-Starting Box', '(2행정)전자제어 제어기', '' ); R_Engine4SProductType : array[Low(TEngine4SProductType)..High(TEngine4SProductType)] of string = ( '', '(4행정)전계장-Starting Box', '(4행정)전자제어 제어기', '(4행정)LCP', '' ); R_EngineModel_TierI : array[Low(TEngineModel_TierI)..High(TEngineModel_TierI)] of string = ( '', 'H17/28', 'H17/28U', 'H17/28E', 'H21/32', 'H25/33', 'H32/40', '' ); R_EngineModel_TierII : array[Low(TEngineModel_TierII)..High(TEngineModel_TierII)] of string = ( '', 'H17/28', 'H17/28U', 'H17/28E', 'H21/32', 'H25/33(V)', 'H32/40(V)', '' ); R_EngineModel_TierIII : array[Low(TEngineModel_TierIII)..High(TEngineModel_TierIII)] of string = ( '', 'H22DF', 'H27DF(V)', 'H35DF(V)', 'H54DF(V)', 'H35G', 'H54G', '' ); R_TCModel_TierI : array[Low(TTCModel_TierI)..High(TTCModel_TierI)] of string = ( '', 'HPR3000', 'HPR4000', 'HPR5000', 'HPR6000', 'TPS44', 'TPS48', 'TPS52', 'TPS57', 'TPS61', 'TPL67', '' ); R_TCModel_TierII : array[Low(TTCModel_TierII)..High(TTCModel_TierII)] of string = ( '', 'ST3', 'ST4', 'ST5', 'ST6', 'ST7', 'A130', 'A135', 'A140', 'A145', 'A150', 'A155', 'TPL65', 'TPL67', '' ); R_TCModel_TierIII : array[Low(TTCModel_TierIII)..High(TTCModel_TierIII)] of string = ( '', 'ST7', 'A150', 'A155', '' ); R_EngineUsage : array[Low(TEngineUsage)..High(TEngineUsage)] of string = ( '', 'Marine', 'Stationary', 'Propulsion', '' ); R_MainBearingMaker : array[Low(TMainBearingMaker)..High(TMainBearingMaker)] of string = ( '', 'Miba', 'Daido', '' ); function GetEngineUsageChar(AIndex: integer): string; procedure EngineProductType2List(AList:TStrings); var g_EngineMasterQueryDateType: TLabelledEnum<TEngineMasterQueryDateType>; g_EngineProductType: TLabelledEnum<TEngineProductType>; g_Engine2SProductType: TLabelledEnum<TEngine2SProductType>; g_Engine4SProductType: TLabelledEnum<TEngine4SProductType>; g_EngineTier1: TLabelledEnum<TEngineModel_TierI>; g_EngineTier2: TLabelledEnum<TEngineModel_TierII>; g_EngineTier3: TLabelledEnum<TEngineModel_TierIII>; g_TCModelTier1: TLabelledEnum<TTCModel_TierI>; g_TCModelTier2: TLabelledEnum<TTCModel_TierII>; g_TCModelTier3: TLabelledEnum<TTCModel_TierIII>; g_EngineUsage: TLabelledEnum<TEngineUsage>; g_MainBearingMaker: TLabelledEnum<TMainBearingMaker>; implementation function GetEngineUsageChar(AIndex: integer): string; begin case AIndex of 1: Result := 'M'; 2: Result := 'S'; 3: Result := 'P'; end; end; procedure EngineProductType2List(AList:TStrings); var Li: TEngineProductType; begin AList.Clear; for Li := Succ(Low(TEngineProductType)) to Pred(High(TEngineProductType)) do begin AList.Add(R_EngineProductType[Li]); end; end; initialization g_EngineMasterQueryDateType.InitArrayRecord(R_EngineMasterQueryDateType); g_EngineProductType.InitArrayRecord(R_EngineProductType); g_Engine2SProductType.InitArrayRecord(R_Engine2SProductType); g_Engine4SProductType.InitArrayRecord(R_Engine4SProductType); g_EngineTier1.InitArrayRecord(R_EngineModel_TierI); g_EngineTier2.InitArrayRecord(R_EngineModel_TierII); g_EngineTier3.InitArrayRecord(R_EngineModel_TierIII); g_TCModelTier1.InitArrayRecord(R_TCModel_TierI); g_TCModelTier2.InitArrayRecord(R_TCModel_TierII); g_TCModelTier3.InitArrayRecord(R_TCModel_TierIII); g_EngineUsage.InitArrayRecord(R_EngineUsage); g_MainBearingMaker.InitArrayRecord(R_MainBearingMaker); finalization end.
procedure TForm1.btnGoClick(Sender: TObject); var level, size, step, stepSize, total, previousStep, increment: Integer; temp: String; begin temp := InputBox('Matrix size', 'Enter a matrix size', '1001'); size := StrToInt(temp); total := 1; stepSize := 0; previousStep := 1; size := floor((size - 1) / 2) + 1; for level := 2 to size do begin stepSize := (level - 1) * 2; for step := 1 to 4 do begin increment := previousStep + stepSize; total := total + increment; previousStep := increment; end; end; MessageDlg(Format('The totals is: %d', [total]), mtInformation, [mbOK], -1); end;
unit WebCombo; interface uses Classes, HTTPApp, Db, DbClient, Midas, XMLBrokr, WebComp, MidComp, PagItems, MidItems; type TSearchSelectOptionsInput = class(TWebTextInput, IScriptComponent) private FValuesField: string; FItemsField: string; FDataSet: TDataSet; FValues: TStrings; FItems: TStrings; FDisplayRows: Integer; protected { IHTMLField } function ImplGetHTMLControlName: string; override; { IScriptComponent implementation } procedure AddElements(AddIntf: IAddScriptElements); function GetSubComponents: TObject; // Object implementing IWebComponentContainer function ControlContent(Options: TWebContentOptions): string; override; function EventContent(Options: TWebContentOptions): string; override; function GetSelectIndex(ItemsStrings, ValuesStrings: TStrings): Integer; virtual; function FormatInputs(ItemsStrings, ValuesStrings: TStrings; Options: TWebContentOptions; var MaxWidth: Integer): string; function InputName: string; function ListName: string; procedure SetItems(const Value: TStrings); procedure SetValues(const Value: TStrings); procedure AddListAttributes(var Attrs: string); procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetDataSet(const Value: TDataSet); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Values: TStrings read FValues write SetValues; property Items: TStrings read FItems write SetItems; property DataSet: TDataSet read FDataSet write SetDataSet; property ValuesField: string Read FValuesField write FValuesField; property ItemsField: string read FItemsField write FItemsField; property DisplayRows: Integer read FDisplayRows write FDisplayRows; end; TQuerySearchSelectOptions = class(TSearchSelectOptionsInput, IQueryField) private FText: string; protected function GetText: string; procedure SetText(const Value: string); function GetSelectIndex(ItemsStrings, ValuesStrings: TStrings): Integer; override; procedure AddAttributes(var Attrs: string); override; public class function IsQueryField: Boolean; override; published property ParamName; property Values; property Items; property DataSet; property ValuesField; property ItemsField; property DisplayRows; property Style; property Custom; property StyleRule; property CaptionAttributes; property CaptionPosition; property Text: string read GetText write SetText; property FieldName; property TabIndex; property Caption; end; implementation uses sysutils, WbmConst; { TSearchSelectOptionsInput } const sComboSelChange = 'ComboSelChange'; sComboSelChangeFunction = 'function %0:s(list, input)' + #13#10 + '{' + #13#10 + ' input.value = list.options[list.selectedIndex].text;' + #13#10 + '}' + #13#10; sComboLookup = 'ComboLookup'; sComboLookupFunction = 'function %0:s(input, list)' + #13#10 + '{' + #13#10 + ' var s = input.value.toUpperCase();' + #13#10 + ' var count = list.options.length;' + #13#10 + ' var i = 0;' + #13#10 + ' while (i < count)' + #13#10 + ' {' + #13#10 + ' if (list.options[i].text.toUpperCase().indexOf(s)==0)' + #13#10 + ' {' + #13#10 + ' list.selectedIndex = i;' + #13#10 + ' break;' + #13#10 + ' }' + #13#10 + ' i++;' + #13#10 + ' }' + #13#10 + '}' + #13#10; constructor TSearchSelectOptionsInput.Create(AOwner: TComponent); begin inherited; FValues := TStringList.Create; FItems := TStringList.Create; FDisplayRows := -1; end; destructor TSearchSelectOptionsInput.Destroy; begin inherited; FValues.Free; FItems.Free; end; function TSearchSelectOptionsInput.EventContent(Options: TWebContentOptions): string; var HTMLForm: IHTMLForm; HTMLFormName: string; begin HTMLForm := GetHTMLForm; if Assigned(HTMLForm) then HTMLFormName := HTMLForm.HTMLFormName; Result := inherited EventContent(Options); Result := Format('%0:s onkeyup="%1:s(this, %2:s.%3:s);"', [Result, sComboLookup, HTMLFormName, ListName]); end; function TSearchSelectOptionsInput.ControlContent(Options: TWebContentOptions): string; var ItemsStrings, ValuesStrings: TStrings; ListContent: string; MaxWidth: Integer; begin if GetItemValuesFromDataSet(FDataSet, ItemsField, ValuesField, ItemsStrings, ValuesStrings) then begin try ListContent := FormatInputs(ItemsStrings, ValuesStrings, Options, MaxWidth); finally ItemsStrings.Free; ValuesStrings.Free; end; end else ListContent := FormatInputs(Items, Values, Options, MaxWidth); // Define edit control DisplayWidth := MaxWidth; Result := inherited ControlContent(Options); Result := Format(#13#10'<TABLE>' + ' <TR>' + ' <TD>' + ' %0:s' + ' </TD>' + ' </TR>'#13#10 + ' <TR>' + ' <TD>' + ' %1:s' + ' </TD>' + ' </TR>' + '</TABLE>', [Result, ListContent]); end; function TSearchSelectOptionsInput.InputName: string; begin Result := Format('_%s', [ListName]); end; function TSearchSelectOptionsInput.ListName: string; begin Result := inherited ImplGetHTMLControlName; end; procedure TSearchSelectOptionsInput.AddListAttributes(var Attrs: string); begin AddQuotedAttrib(Attrs, 'NAME', ListName); AddIntAttrib(Attrs, 'SIZE', DisplayRows); AddIntAttrib(Attrs, 'TABINDEX', TabIndex); AddQuotedAttrib(Attrs, 'STYLE', Style); AddQuotedAttrib(Attrs, 'CLASS', StyleRule); AddCustomAttrib(Attrs, Custom); end; function TSearchSelectOptionsInput.GetSelectIndex(ItemsStrings, ValuesStrings: TStrings): Integer; begin Result := -1; end; function TSearchSelectOptionsInput.FormatInputs(ItemsStrings, ValuesStrings: TStrings; Options: TWebContentOptions; var MaxWidth: Integer): string; var Index: Integer; Attrs, Events, Value: string; Item: string; HTMLForm: IHTMLForm; HTMLFormName: string; SelectIndex: Integer; OptionAttr: string; begin Result := ''; MaxWidth := -1; AddListAttributes(Attrs); HTMLForm := GetHTMLForm; if Assigned(HTMLForm) then HTMLFormName := HTMLForm.HTMLFormName; if (not (coNoScript in Options.Flags)) then Events := Format(' onchange="%0:s(this, %1:s.%2:s);"', [sComboSelChange, HTMLFormName, GetHTMLControlName]); SelectIndex := GetSelectIndex(ItemsStrings, ValuesStrings); Result := Format('<SELECT%0:s%1:s>'#13#10, [Attrs, Events]); for Index := 0 to ItemsStrings.Count - 1 do begin Item := ItemsStrings[Index]; if ItemsStrings.IndexOf(Item) <> Index then continue; // not unique if Length(Item) > MaxWidth then MaxWidth := Length(Item); if ValuesStrings.Count > Index then Value := ValuesStrings[Index] else Value := Item; OptionAttr := ''; AddQuotedAttrib(OptionAttr, 'VALUE', Value); AddBoolAttrib(OptionAttr, 'SELECTED', Index = SelectIndex); Result := Format('%0:s <OPTION %1:s>%2:s'#13#10, [Result, OptionAttr, Item]); end; Result := Format('%0:s</SELECT>', [Result]); end; procedure TSearchSelectOptionsInput.AddElements(AddIntf: IAddScriptElements); begin inherited; if Assigned(FDataSet) and (FDataSet.Active = False) then AddIntf.AddError(Format(sDataSetNotActive, [FDataSet.Name])); AddIntf.AddFunction(sComboSelChange, Format(sComboSelChangeFunction, [sComboSelChange])); AddIntf.AddFunction(sComboLookup, Format(sComboLookupFunction, [sComboLookup])); end; procedure TSearchSelectOptionsInput.SetItems(const Value: TStrings); begin FItems.Assign(Value); end; procedure TSearchSelectOptionsInput.SetValues(const Value: TStrings); begin FValues.Assign(Value); end; function TSearchSelectOptionsInput.ImplGetHTMLControlName: string; begin Result := InputName; end; procedure TSearchSelectOptionsInput.SetDataSet(const Value: TDataSet); begin if FDataSet <> Value then begin FDataSet := Value; if Value <> nil then begin Value.FreeNotification(Self); if not (csLoading in ComponentState) then Value.Active := True; end; end; end; procedure TSearchSelectOptionsInput.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = FDataSet) then DataSet := nil; end; function TSearchSelectOptionsInput.GetSubComponents: TObject; begin Result := nil; end; { TQuerySearchSelectOptiosn } procedure TQuerySearchSelectOptions.AddAttributes(var Attrs: string); begin Inherited; AddQuotedAttrib(Attrs, 'VALUE', Text); end; function TQuerySearchSelectOptions.GetSelectIndex(ItemsStrings, ValuesStrings: TStrings): Integer; begin Result := ItemsStrings.IndexOf(Text); end; function TQuerySearchSelectOptions.GetText: string; begin Result := FText; end; class function TQuerySearchSelectOptions.IsQueryField: Boolean; begin Result := True; end; procedure TQuerySearchSelectOptions.SetText(const Value: string); begin if Value <> FText then begin FText := Value; end; end; end.
unit AMostraRecibo; { Autor: Douglas Thomas Jacobsen Data Criação: 28/02/2000; Função: TELA BÁSICA Data Alteração: Alterado por: Motivo alteração: } interface uses Windows, SysUtils, Classes,Controls, Forms, Componentes1, ExtCtrls, PainelGradiente, Formularios, StdCtrls, Buttons, Tabela, Grids, DBCtrls, Localizacao, Mask, DBGrids, LabelCorMove, numericos, UnImpressao, Db, DBTables, UnClassesImprimir, DBClient, UnDados, unSistema, UnClientes, unDadosLocaliza; type TFMostraRecibo = class(TFormularioPermissao) PanelFechar: TPanelColor; BFechar: TBitBtn; BImprimir: TBitBtn; PainelTitulo: TPainelGradiente; PanelModelo: TPanelColor; Label1: TLabel; CModelo: TDBLookupComboBoxColor; CAD_DOC: TSQL; CAD_DOCI_NRO_DOC: TFMTBCDField; CAD_DOCI_SEQ_IMP: TFMTBCDField; CAD_DOCC_NOM_DOC: TWideStringField; CAD_DOCC_TIP_DOC: TWideStringField; DATACAD_DOC: TDataSource; PanelPai: TPanelColor; Shape1: TShape; Shape2: TShape; Shape3: TShape; Shape5: TShape; Shape6: TShape; Shape7: TShape; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Shape8: TShape; Shape11: TShape; Shape12: TShape; Shape13: TShape; Shape14: TShape; Label12: TLabel; Shape15: TShape; ENumero: TEditColor; EPessoa: TEditColor; EDescValor1: TEditColor; EDescValor2: TEditColor; EDescReferente1: TEditColor; EDescReferente2: TEditColor; ECidade: TEditColor; EDia: TEditColor; EMes: TEditColor; EAno: TEditColor; Shape16: TShape; Shape17: TShape; EEmitente: TEditColor; Label13: TLabel; Shape18: TShape; ECGCCPFGREmitente: TEditColor; Label14: TLabel; Shape19: TShape; EEnderecoEmitente: TEditColor; Label15: TLabel; Shape4: TShape; Shape9: TShape; Shape10: TShape; Shape20: TShape; EValor: Tnumerico; DBText2: TDBText; CAD_DOCC_NOM_IMP: TWideStringField; ECliente: TRBEditLocaliza; SpeedButton1: TSpeedButton; Label2: TLabel; EBairro: TEditColor; Label16: TLabel; Shape21: TShape; ECidadePagador: TEditColor; Label17: TLabel; EUF: TEditColor; ELocalizaEmitente: TRBEditLocaliza; SpeedButton2: TSpeedButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure BImprimirClick(Sender: TObject); procedure CModeloCloseUp(Sender: TObject); procedure FormShow(Sender: TObject); procedure EValorChange(Sender: TObject); procedure EClienteRetorno(VpaColunas: TRBColunasLocaliza); procedure ELocalizaEmitenteRetorno(VpaColunas: TRBColunasLocaliza); private IMP : TFuncoesImpressao; VprDCliente : TRBDCliente; procedure DesativaEdits; procedure ImprimeReciboFolhaemBranco; procedure CarDCliente; public { Public declarations } procedure ImprimeDocumento; procedure MostraDocumento(Dados: TDadosRecibo); procedure CarregaDados(Dados: TDadosRecibo); procedure CarregaEdits(Dados: TDadosRecibo); end; var FMostraRecibo: TFMostraRecibo; implementation uses APrincipal, FunSql, FunString, ConstMsg, Constantes, FunNumeros, FunObjeto, FunData, dmRave; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFMostraRecibo.FormCreate(Sender: TObject); begin IMP := TFuncoesImpressao.Criar(self, FPrincipal.BaseDados); VprDCliente := TRBDCliente.cria; AbreTabela(CAD_DOC); ECidade.Text := Varia.CidadeFilial; EDia.AInteiro := dia(date); EMes.Text := TextoMes(date,false); EAno.AInteiro := Ano(date); EEmitente.Text := varia.NomeFilial; end; { ******************* Quando o formulario e fechado ************************** } procedure TFMostraRecibo.FormClose(Sender: TObject; var Action: TCloseAction); begin FechaTabela(CAD_DOC); IMP.Destroy; VprDCliente.free; Action := CaFree; end; procedure TFMostraRecibo.BFecharClick(Sender: TObject); begin Close; end; procedure TFMostraRecibo.BImprimirClick(Sender: TObject); begin ImprimeDocumento; end; {******************************************************************************} procedure TFMostraRecibo.ImprimeDocumento; var VpfDados: TDadosRecibo; begin if ((not CAD_DOC.EOF) and (CModelo.Text <> '')) then begin if IMP.ImprimirDocumentonaLaser(CAD_DOCI_NRO_DOC.AsInteger) then ImprimeReciboFolhaemBranco else begin VpfDados := TDadosRecibo.Create; CarregaDados(VpfDados); IMP.InicializaImpressao(CAD_DOCI_NRO_DOC.AsInteger, CAD_DOCI_SEQ_IMP.AsInteger); IMP.ImprimirRecibo(VpfDados); // Imprime 1 documento. IMP.FechaImpressao(Config.ImpPorta, 'C:\IMP.TXT'); end; end else Aviso('Não existe modelo de documento para imprimir.'); end; procedure TFMostraRecibo.MostraDocumento(Dados: TDadosRecibo); begin CarregaEdits(Dados); BImprimir.Visible := False; PanelModelo.Visible := False; PanelFechar.Visible := False; PainelTitulo.Visible := False; Height := Height - PanelModelo.Height - PanelFechar.Height - PainelTitulo.Height; DesativaEdits; FormStyle := fsStayOnTop; BorderStyle := bsDialog; Show; end; procedure TFMostraRecibo.DesativaEdits; var I: Integer; begin for I := 0 to (ComponentCount -1) do begin if (Components[I] is TEditColor) then (Components[I] as TEditColor).ReadOnly := True; if (Components[I] is TNumerico) then (Components[I] as TNumerico).ReadOnly := True; end; end; {******************************************************************************} procedure TFMostraRecibo.ImprimeReciboFolhaemBranco; var VpfDFilial : TRBDFilial; begin VpfDFilial := TRBDFilial.Cria; Sistema.CarDFilial(VpfDFilial,Varia.CodigoEmpFil); CarDCliente; dtRave := TdtRave.create(self); dtRave.ImprimeRecibo(Varia.CodigoEmpFil,VprDCliente,EDescReferente1.Text+EDescReferente2.text,FormatFloat('#,###,##0.00',EValor.AValor),EDescValor1.Text+EDescValor2.Text,ECidade.text+', '+EDia.Text+' de '+EMes.Text+' de '+EAno.Text,EEmitente.Text); dtRave.free; VpfDFilial.Free; end; procedure TFMostraRecibo.CarDCliente; begin VprDCliente.NomCliente := EPessoa.Text; VprDCliente.DesEndereco := EEnderecoEmitente.Text; VprDCliente.DesBairro := EBairro.Text; VprDCliente.DesCidade := ECidadePagador.Text; VprDCliente.DesUF := EUF.Text; end; procedure TFMostraRecibo.CarregaEdits(Dados: TDadosRecibo); begin ENumero.Text := Dados.Numero; EValor.AValor := Dados.Valor; EPessoa.Text := Dados.Pessoa; EDescValor1.Text := Dados.DescValor1; EDescValor2.Text := Dados.DescValor2; EDescReferente1.Text := Dados.DescReferente1; EDescReferente2.Text := Dados.DescReferente2; ECidade.Text := Dados.Cidade; EDia.Text := Dados.Dia; EMes.Text := Dados.Mes; EAno.Text := Dados.Ano; EEmitente.Text := Dados.Emitente; ECGCCPFGREmitente.Text := Dados.CGCCPFGREmitente; EEnderecoEmitente.Text := Dados.EnderecoEmitente; end; procedure TFMostraRecibo.CarregaDados(Dados: TDadosRecibo); begin Dados.Numero := ENumero.Text; Dados.Valor := EValor.AValor; Dados.Pessoa := EPessoa.Text; Dados.DescValor1 := EDescValor1.Text; Dados.DescValor2 := EDescValor2.Text; Dados.DescReferente1 := EDescReferente1.Text; Dados.DescReferente2 := EDescReferente2.Text; Dados.Cidade := ECidade.Text; Dados.Dia := EDia.Text; Dados.Mes := EMes.Text; Dados.Ano := EAno.Text; Dados.Emitente := EEmitente.Text; Dados.CGCCPFGREmitente := ECGCCPFGREmitente.Text; Dados.EnderecoEmitente := EEnderecoEmitente.Text; end; procedure TFMostraRecibo.CModeloCloseUp(Sender: TObject); begin // Limpa os Edits. LimpaEdits(FMostraRecibo); LimpaEditsNumericos(FMostraRecibo); // Configura e limita os edits. if (not CAD_DOC.EOF) then IMP.LimitaTamanhoCampos(FMostraRecibo, CAD_DOCI_NRO_DOC.AsInteger); end; procedure TFMostraRecibo.FormShow(Sender: TObject); begin CModelo.KeyValue:=CAD_DOCI_NRO_DOC.AsInteger; // Posiciona no Primeiro; // Configura e limita os edits. if (not CAD_DOC.EOF) then IMP.LimitaTamanhoCampos(FMostraRecibo, CAD_DOCI_NRO_DOC.AsInteger); end; procedure TFMostraRecibo.EClienteRetorno(VpaColunas: TRBColunasLocaliza); begin if ECliente.AInteiro <> 0 then begin VprDCliente.CodCliente := ECliente.AInteiro; FunClientes.CarDCliente(VprDCliente); EPessoa.Text := VprDCliente.NomCliente; EEnderecoEmitente.Text := VprDCliente.DesEndereco; EBairro.Text := VprDCliente.DesBairro; ECidadePagador.Text := VprDCliente.DesCidade; EUF.Text := VprDCliente.DesUF; end; end; procedure TFMostraRecibo.ELocalizaEmitenteRetorno( VpaColunas: TRBColunasLocaliza); begin if ELocalizaEmitente.AInteiro <> 0 then begin VprDCliente.CodCliente := ELocalizaEmitente.AInteiro; FunClientes.CarDCliente(VprDCliente); EEmitente.Text := VprDCliente.NomCliente; ECGCCPFGREmitente.Text := VprDCliente.CGC_CPF; end; end; procedure TFMostraRecibo.EValorChange(Sender: TObject); var AUX: string; begin if (EValor.AValor > 0) then begin AUX := Maiusculas(RetiraAcentuacao(Extenso(EValor.AValor, 'reais', 'real'))); DivideTextoDoisComponentes(EDescValor1, EDescValor2, AUX); end else begin // Limpa descrição de valores. EDescValor1.Clear; EDescValor2.Clear; end; end; Initialization RegisterClasses([TFMostraRecibo]); end.
unit Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ListBox, FMX.Layouts, FMX.Edit, FMX.ComboEdit, System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent, FMX.Memo, Json, FMX.ScrollBox; type TForm1 = class(TForm) ToolBar1: TToolBar; Label1: TLabel; labelCountry: TLabel; Label2: TLabel; humidityLabel: TLabel; pressureLabel: TLabel; cloudlabel: TLabel; lonLabel: TLabel; labelCity: TLabel; btnGetWeather: TButton; ScrollBox1: TScrollBox; CityBox: TComboEdit; tempLabel: TLabel; latlabel: TLabel; ResponseField: TMemo; Label5: TLabel; procedure FormCreate(Sender: TObject); procedure btnGetWeatherClick(Sender: TObject); private { Private declarations } public { Public declarations } responsejson:string; owmadress:string; end; var Form1: TForm1; implementation {$R *.fmx} // Функция для получения данных от сервера (ответ в формате Json) function idHttpGet(const aURL: string): string; // uses System.Net.HttpClient, System.Net.HttpClientComponent, System.Net.URLClient; var Resp: TStringStream; Return: IHTTPResponse; begin Result := ''; with TNetHTTPClient.Create(nil) do begin Resp := TStringStream.Create('', TEncoding.ANSI); Return := Get( { TURI.URLEncode } (aURL), Resp); Result := Resp.DataString; Resp.Free; Free; end; end; procedure TForm1.btnGetWeatherClick(Sender: TObject); var JSON,JSONMain,JSONCountry, JSONCoords: TJSONObject; JSONDetail: TJSONArray; city:string; degrees,kelvins:double; begin // Выбираем город city:=CityBox.Text; owmadress:='http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid='+'ffe6d300f48841172ae985a4d1f3c576'; // Делаем запрос к серверу OWM и получаем данные о погоде в JSON responsejson:=idHttpGet(owmadress); // Помещаем ответ от сервера в поле memo ResponseField.Lines.Clear; ResponseField.Text:=responsejson; // Парсим полученный ответ и достаем из него информацию JSON := TJSONObject.ParseJSONValue(responsejson) as TJSONObject; JSONMain:=TJSONObject(JSON.Get('main').JsonValue); JSONDetail:=TJSONArray(JSON.Get('weather').JsonValue); JSONCountry:=TJSONObject(JSON.Get('sys').JsonValue); JSONCoords:=TJSONObject(JSON.Get('coord').JsonValue); // Переводим температуру из Кельвинов в Градусы kelvins:=Double.Parse(JSONMain.GetValue('temp').Value); degrees:=kelvins-273.15; // выводим пользователю tempLabel.Text:='Температура воздуха: '+FloatToStrF(degrees,ffGeneral,3,3)+' °С'; labelCountry.Text:='Страна: '+JSONCountry.GetValue('country').Value; labelCity.Text:='Город: '+JSON.GetValue('name').Value; cloudlabel.Text:='Облачность: '+(TJSONPair(TJSONObject(JSONDetail.Get(0)).Get('description')).JsonValue.Value); humidityLabel.Text:='Влажность: '+JSONMain.GetValue('humidity').Value+' %'; pressureLabel.Text:='Атмосферное давление: '+JSONMain.GetValue('pressure').Value+' hPa'; lonLabel.Text:='Долгота: '+JSONCoords.GetValue('lon').Value; latlabel.Text:='Широта: '+JSONCoords.GetValue('lat').Value; end; procedure TForm1.FormCreate(Sender: TObject); begin Toolbar1.TintColor:=TAlphaColors.Green; owmadress:='http://api.openweathermap.org/data/2.5/weather?q='+'Краматорск'+'&appid='+'ffe6d300f48841172ae985a4d1f3c576'; end; end.
unit Abc2; interface uses Winapi.Windows, System.SysUtils, mainForm; procedure alAbc2(matrix: TMatrix; awal, sumNode, max: Integer; var bestEver: TPath); implementation var n: Integer; procedure alAbc2(matrix: TMatrix; awal, sumNode, max: Integer; var bestEver: TPath); function picOne(fit: array of Real): Integer; var rand:Real; begin // Fungsi ini berguna untuk memilih salah satu bee yang secara acak // dengan kemungkinan bee yang memiliki fitness yg bagus akan mendapat kemungkinan // dipilih lebih besar. funcsi ini di copy daro ranbow train tentang Genetic Algorithm Result := 0; rand := Random; if rand > 1 then Exit; while (rand > 0) and (Result < Length(fit)) do begin rand := rand - fit[Result]; Result := Result + 1; if Result > Length(fit) then Result := Result - Length(fit); end; end; function sumDistance(path: TPath): Integer; var i: Integer; d : int64; begin //Fungsi untuk menghitung total jarak dari suatu path berdasarkan matrixAdj d := 0; if (matrix <> nil) and (path <> nil) then for i := 0 to n-1 do begin if path[i] < Length(path) then d := d + matrix[path[i]][path[i+1]] else begin Result := d; exit ; end; end else d := 9999; Result := d; // Memo1.Lines.Append(IntToStr(Memo1.Lines.Count + 1)+' '+IntToStr(Result)); end; //function sumFitness(bee:TPath; var d: Integer): Real; //begin // Result := 0; // d := sumDistance(bee); // Result := 1/(d+1); //end; procedure swapValue(var arr: Array of Integer; a, b: Integer); var temp: Integer; begin temp := arr[a]; arr[a] := arr[b]; arr[b] := temp; end; procedure copyOrder(var a, b:TPath); var i:Integer; begin //procedure ini berguhan untuk mengcopy nilai pada array a ke array b //fungsi ini dapat digantikan dengan perintah move pada delphi tapi //jika mengunakan fungsi move akan membuat bug yang mengakibatkan algoritma //tidak berjalan dengan efektif if a <> nil then begin SetLength(b, length(a)); for i := 0 to Length(a)-1 do b[i] := a[i]; end; end; procedure shuffle(var arr: TPath; sum: Integer); var indexA, indexB: Integer; i, j: Integer; begin for i := 0 to sum do begin indexA := Random((Length(arr)-1)); indexB := Random((Length(arr)-1)); //mengecek nilai random yang dibangkitkan jika nilai lebih besar dari //panjang array maka pertukaran tidak akan dilakukan if (indexA < Length(arr))and (indexB < Length(arr)) then swapValue(arr, indexA, indexB); end; end; procedure RandomPath(var bee: TPath); var tempBee: TPath;// Digunakan untuk menyimpan variable bee equal: BOOL; i, count: Integer; begin if bee <> nil then begin SetLength(tempBee, length(bee)); copyOrder(bee, tempBee); equal := True; //perulangan untuk mengecek kesamaan dari bee awal dan bee baru jika sama //maka perulangan akan dilakukan terus while equal do begin shuffle(bee, 10);//Acak Bee for i := 0 to Length(bee)-2 do if bee[i] <> tempBee[i] then //mengecek jika ada ketidak samaan begin equal := False; break; end else count := count + 1; if count >= 5*Length(bee) then equal :=False; end; end; end; procedure insertSequnece(var bee: TPath); var indexA, indexB, a, b: Int16; temp: TPath; begin for b := 0 to 10 do begin if bee <> nil then begin indexA := Random(Length(bee)-1); indexB := (indexA+1)+Random((Length(bee)-1)-(indexA+1)); while (indexA = indexB) or (indexA > indexB) or (indexB >= Length(bee)-1) do begin indexA := Random(Length(bee)-1); indexB := (indexA+1)+Random((Length(bee)-1)-(indexA+1)); end; SetLength(temp, indexB-indexA); for a := indexA to indexB-1 do temp[a-indexA] := bee[a]; bee[indexA] := bee[indexB]; for a := indexA+1 to indexB do bee[a] := temp[(a-indexA)-1]; end; end; end; procedure normalizeFitness(var fit: array of Real); var sum: real; i: Integer; begin sum := 0; for i := 0 to Length(fit) do sum := sum + fit[i]; for i := 0 to Length(fit) do fit[i] := fit[i]/sum; end; var i, j, recordDist, ind, a, tempDis: Integer; temp: TPath; tempFit: Integer; nectar: array of Integer; bee: array of TPath; fit, prob:array of real; lim: array of Integer; ToStr: string; begin n := sumNode; SetLength(bee, n); SetLength(fit, n); SetLength(prob, n); SetLength(lim, n); SetLength(nectar, n); recordDist := 9999; SetLength(bee[0], n+1); for i := 0 to n-1 do begin // if i = awal then // j := j + 1; bee[0][i] := i; end; bee[0][Length(bee[0])-1] := bee[0][0]; // bee[0][0] := awal; // bee[0][Length(bee[0])-1] := awal; // Tahap 1 mencari solusi secara acak Tugas Scout Bee. for i := 1 to n-1 do begin SetLength(bee[i], n+1); copyOrder(bee[i-1], bee[i]); RandomPath(bee[i]); bee[i][Length(bee[i])-1] := bee[i][0]; end; for j := 0 to max do begin //Tugas Employed Bee menghitung fitness dari solsi yang di temukan Scout for i := 0 to n-1 do begin nectar[i] := sumDistance(bee[i]); for a := 0 to 50 do begin copyOrder(bee[i], temp); shuffle(temp, 10); temp[Length(temp)-1] := temp[0]; tempDis := sumDistance(temp); if nectar[i] > tempDis then begin copyOrder(temp, bee[i]); nectar[i] := tempDis; end else lim[i] := lim[i] + 1; end; prob[i] := nectar[i]; end; normalizeFitness(prob); // Tugas Onlooker memilih solusi berdasaran probabilitasnya for i := 0 to n-1 do begin //memilih solusi dari employed bee secara acak dengan kemungkinan //solusih yang baik lebi besar kemungkinannya untuk dipilih. ind := picOne(prob); for a := 0 to 50 do begin copyOrder(bee[ind], temp); insertSequnece(temp); temp[Length(temp)-1] := temp[0]; tempDis := sumDistance(temp); if fit[i] > tempFit then begin copyOrder(temp, bee[i]); nectar[i] := tempDis; end else lim[i] := lim[i] + 1; end; end; // Tahap Scout Bee // Mencari Solusi Yang Tidak mengalami peningkatan untuk di ganti dengan // solusi baru secara acak. for i := 0 to n-1 do begin if lim[i] > 100 then begin RandomPath(bee[i]); bee[i][Length(bee[i])-1] := bee[i][0]; lim[i] := 0; end; end; //Mencari Solusi Terbaik. for i := 0 to n-1 do begin if nectar[i] < recordDist then begin copyOrder(bee[i], bestEver); recordDist := nectar[i]; ToStr := ''; for a := 0 to Length(bestEver)-1 do ToStr := ToStr + IntToStr(bestEver[a]); Form1.Memo1.Lines.Append(''); Form1.Memo1.Lines.Append('Jalur : '+ToStr); Form1.Memo1.Lines.Append('Jarak : '+IntToStr(recordDist)); end; end; end; ToStr := ''; for a := 0 to Length(bestEver)-1 do ToStr := ToStr + Chr(65+bestEver[a]); Form1.Memo1.Lines.Append(''); Form1.Memo1.Lines.Append('Solusi Yang didapatkan : '+ToStr); Form1.Memo1.Lines.Append('Jarak : '+IntToStr(recordDist)); end; end.
PROGRAM Notenliste; TYPE Uebung = RECORD punkte: real; abgegeben: boolean; END; (* Uebung *) UebungenArray = ARRAY [1..10] OF Uebung; Student = RECORD Name: string; Uebungen: UebungenArray; END; StudentArray = ARRAY [1..25] OF Student; VAR s: StudentArray; PROCEDURE AddResult(name: string; punkte: real; ue: integer); FORWARD; PROCEDURE InitStudentArray; VAR i, j: integer; BEGIN (* InitStudentArray *) FOR i:= Low(s) TO High(s) DO BEGIN s[i].Name := ''; FOR j := Low(s[i].Uebungen) TO High(s[i].Uebungen) DO BEGIN s[i].Uebungen[j].punkte := 0.0; s[i].Uebungen[j].abgegeben := false; END; (* FOR *) END; END; (* InitStudentArray *) FUNCTION FindStudentIndexWithName(name: string): integer; VAR i: integer; BEGIN (* FindStudentIndexWithName *) i:= 1; WHILE ((i <= High(s)) AND (s[i].name <> name) AND (s[i].name <> '')) DO Inc(i); IF i > High(s) THEN BEGIN WriteLn('Too many students!'); HALT; END; (* IF *) s[i].name := name; FindStudentIndexWithName:= i; END; (* FindStudentIndexWithName *) PROCEDURE AddEntry(name: string; ue: integer); var idx: integer; BEGIN (* AddEntry *) AddResult(name, -1, ue); END; (* AddEntry *) PROCEDURE AddResult(name: string; punkte: REAL; ue: integer); var idx: integer; BEGIN (* AddResult *) idx := FindStudentIndexWithName(name); s[idx].Uebungen[ue].abgegeben := TRUE; s[idx].Uebungen[ue].punkte := punkte; END; (* AddResult *) PROCEDURE FindBestTwo(ue: UebungenArray; var p1, p2: real); var i: integer; p: real; BEGIN (* FindBestTwo *) p1 := -1; p2 := -1; FOR i := Low(ue) TO High(ue) DO BEGIN p:= ue[i].punkte; IF ue[i].abgegeben THEN BEGIN IF p > p1 THEN BEGIN p2 := p1; p1 := p; END ELSE IF p > p2 THEN BEGIN p2 := p; END; (* IF *) END; (* IF *) END; (* FOR *) END; (* FindBestTwo *) FUNCTION AvgPunkte(st: student): real; var p1, p2: real; BEGIN (* AvgPunkte *) FindBestTwo(st.uebungen, p1, p2); IF p1 < 0 THEN BEGIN WriteLn('No result for ', st.name); HALT; END; (* IF *) IF p2 >= 0 THEN BEGIN AvgPunkte := (p1 + p2) / 2; END ELSE BEGIN AvgPunkte := p1; END; END; (* AvgPunkte *) PROCEDURE WriteStudent(st: student); var i: integer; anzAbgaben: integer; BEGIN (* WriteStudent *) anzAbgaben := 0; Write(st.name:20); FOR i := Low(st.uebungen) TO High(st.uebungen) DO BEGIN IF st.uebungen[i].abgegeben THEN BEGIN Write(i:3, ': ', st.uebungen[i].Punkte:5:1); Inc(anzAbgaben); END; (* IF *) END; (* FOR *) WriteLn(' Abgaben: ', anzAbgaben, ' Punkteschnitt: ', AvgPunkte(st):5:1); END; (* WriteStudent *) PROCEDURE WritePunkteListe; var i: integer; BEGIN (* WritePunkteListe *) i := 1; WHILE (i <= High(s)) AND (s[i].name <> '') DO BEGIN WriteStudent(s[i]); Inc(i); END; (* WHILE *) WriteLn('Number of Students: ', i - 1); END; (* WritePunkteListe *) BEGIN (* Notenliste *) AddEntry('Haas', 2); AddResult('Haas', 24, 1); AddEntry('Haas', 3); AddResult('Mitter', 24, 2); AddEntry('Mitter', 1); AddResult('Mitter', 22, 3); AddResult('GK', 5, 1); AddResult('GK', 6, 2); AddResult('GK', 7, 3); AddEntry('Student T', 1); AddEntry('Student T', 2); AddEntry('Student T', 3); WritePunkteListe; END. (* Notenliste *)
unit LanctoPagto; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Padrao1, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxGroupBox, StdCtrls, Buttons, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxCheckBox, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, cxDBEdit, FMTBcd, SqlExpr, Provider, DBClient, Menus, cxRadioGroup, cxCalendar, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter, ExtCtrls, fmeLogradouro, cxCurrencyEdit, cxLabel, cxDropDownEdit, fmeLocalPagto, StrUtils, dxCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, cxNavigator, Vcl.ComCtrls, cxDateUtils; type TfrmLanctoPagto = class(TfrmPadrao1) gbUnidConsum: TcxGroupBox; cds1: TClientDataSet; prov1: TDataSetProvider; dbg1: TcxGrid; GridDBTableView1: TcxGridDBTableView; cxGridDBColumn1: TcxGridDBColumn; cxGridDBColumn2: TcxGridDBColumn; cxGridDBColumn4: TcxGridDBColumn; cxGridDBColumn5: TcxGridDBColumn; cxGridDBColumn8: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; PopupMenu1: TPopupMenu; Novo1: TMenuItem; Alterar1: TMenuItem; Exluir1: TMenuItem; N1: TMenuItem; Sair1: TMenuItem; GridDBTableView1Column2: TcxGridDBColumn; Panel: TPanel; lblTitColPesquisa: TLabel; edPesquisa: TcxTextEdit; btnAdd: TBitBtn; btnEdit: TBitBtn; btnDel: TBitBtn; btnFechar: TBitBtn; qry1: TSQLQuery; ds1: TDataSource; GridDBTableView1Column4: TcxGridDBColumn; GridDBTableView1Column5: TcxGridDBColumn; edEnderDescrDisitro: TcxDBTextEdit; edEnderDescrBairro: TcxDBTextEdit; edEnderComplemento: TcxDBTextEdit; edEnderNum: TcxDBTextEdit; edDescrLograd: TcxDBTextEdit; Label2: TLabel; GridDBTableView1Column3: TcxGridDBColumn; GridDBTableView1Column6: TcxGridDBColumn; GroupBox1: TcxGroupBox; btnOk: TBitBtn; cxLabel1: TcxLabel; lblQtdLancto: TcxLabel; cxLabel2: TcxLabel; edDtPagto: TcxDateEdit; cxLabel3: TcxLabel; lblTotPagto: TcxLabel; frmeLocalPagto1: TfrmeLocalPagto; cxLabel4: TcxLabel; btnLimpar: TButton; cds1R_ID_UNID_CONSUM: TIntegerField; cds1R_NOME_PESSOA: TStringField; cds1R_DESCR_TIPO_PESSOA: TStringField; cds1R_CPF_CNPJ_FTDO: TStringField; cds1R_TIPO_FATURA: TStringField; cds1R_DESCR_TIPO_FATURA: TStringField; cds1R_REFERENCIA: TStringField; cds1R_REF_FTDO: TStringField; cds1R_DT_PAGTO: TDateField; cds1R_ID_LOCAL_PAGTO: TIntegerField; cds1R_DESCR_LOCAL_PAGTO: TStringField; cds1R_DT_VENCIMENTO: TDateField; cds1R_VAL_FATURA: TFMTBCDField; cds1R_VAL_DESCONTO: TFMTBCDField; cds1R_VAL_PAGTO: TFMTBCDField; cds1R_DESCR_CATEG: TStringField; cds1R_ENDER_LOGRAD_DESCR: TStringField; cds1R_ENDER_NUM_LETRA: TStringField; cds1R_ENDER_COMPLEM: TStringField; cds1R_ENDER_BAIRRO_DESCR: TStringField; cds1R_ENDER_DISTRITO_DESCR: TStringField; btnDetFatAvulsa: TBitBtn; qryUsuarioPermissaoTabela: TSQLQuery; qryUsuarioPermissaoTabelaINCLUIR: TStringField; qryUsuarioPermissaoTabelaALTERAR: TStringField; qryUsuarioPermissaoTabelaEXCLUIR: TStringField; qryFatAvulsaItem: TSQLQuery; qryFatAvulsaItemANO_MES: TStringField; qryFatAvulsaItemVAL_TOTAL: TFMTBCDField; procedure FormShow(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Novo1Click(Sender: TObject); procedure btnDelClick(Sender: TObject); procedure edPesquisaPropertiesChange(Sender: TObject); procedure GridDBTableView1ColumnHeaderClick(Sender: TcxGridTableView; AColumn: TcxGridDbColumn); procedure cdsEventoFixoAfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); procedure btnOkClick(Sender: TObject); procedure btnLimparClick(Sender: TObject); procedure cds1AfterOpen(DataSet: TDataSet); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnDetFatAvulsaClick(Sender: TObject); private { Private declarations } pv_sColIndex: string; procedure SetColGrid(iCol: Integer); procedure AtualizaTotal; procedure HabilitaBotoes(lOpcao: Boolean); procedure OpenTabPagtos; procedure PermissoesUsuario(iIdUsuario: integer; sNomeTab: String); public { Public declarations } end; var frmLanctoPagto: TfrmLanctoPagto; implementation uses udmPrincipal, gsLib, UtilsDb, VarGlobais, AddEditLanPagto, DetalhaFatura, CalcFaturaAvulsa; {$R *.dfm} procedure TfrmLanctoPagto.btnAddClick(Sender: TObject); Var iAddEdit: Integer; bkmReg: TBookmark; iRef : Integer; begin if TButton(Sender).Tag = 1 then begin frmAddEditLanPagto.pb_sDtPagto := edDtPagto.Text; frmAddEditLanPagto.pb_iIdLocal := StrToInt(Trim(frmeLocalPagto1.edId.Text)); iAddEdit := frmAddEditLanPagto.Executa(Self.Name,0,0,1,True); if iAddEdit > 0 then OpenTabPagtos; cds1.Last; end else begin if cds1.RecordCount = 0 then exit; bkmReg := cds1.GetBookmark; frmAddEditLanPagto.pb_sTipoFatura := cds1R_TIPO_FATURA.Value; if cds1R_TIPO_FATURA.Value = '1' then iRef := cds1R_REFERENCIA.AsInteger else iRef := StrToInt(RightStr(Trim(cds1R_REFERENCIA.Value),8)); iAddEdit := frmAddEditLanPagto.Executa(Self.Name, cds1R_ID_UNID_CONSUM.Value,iRef,1,False); if iAddEdit > 0 then begin OpenTabPagtos; cds1.GotoBookmark(bkmReg); cds1.FreeBookmark(bkmReg); end; end; end; procedure TfrmLanctoPagto.btnDelClick(Sender: TObject); Var sTextSqlDel: string; iErro: Integer; begin if not Confirma('Deseja realmente EXCLUIR essa Movimento ?') then exit; iErro := 0; if cds1R_TIPO_FATURA.Value = '2' then begin qryFatAvulsaItem.Close; qryFatAvulsaItem.Params[0].Value := StrToInt(RightStr(cds1R_REFERENCIA.Value,8)); qryFatAvulsaItem.Open; while not qryFatAvulsaItem.eof do begin sTextSqlDel := 'DELETE FROM LANCTO_PAGTO WHERE '+ '(TIPO_FATURA = '+QuotedStr('1')+') AND '+ '(REFERENCIA = '+QuotedStr(RightStr(qryFatAvulsaItemANO_MES.Value,4)+ LeftStr(qryFatAvulsaItemANO_MES.Value,2))+') AND '+ '(ID_UNID_CONSUM = '+cds1R_ID_UNID_CONSUM.AsString+')'; try dmPrincipal.SConPrincipal.ExecuteDirect(sTextSqlDel); except iErro := 1; end; if iErro = 1 then break; qryFatAvulsaItem.Next; end; qryFatAvulsaItem.Close; end; if iErro = 0 then begin sTextSqlDel := 'DELETE FROM LANCTO_PAGTO WHERE '+ '(TIPO_FATURA = '+QuotedStr(cds1R_TIPO_FATURA.Value)+') AND '+ '(REFERENCIA = '+QuotedStr(cds1R_REFERENCIA.AsString)+') AND '+ '(ID_UNID_CONSUM = '+cds1R_ID_UNID_CONSUM.AsString+')'; try dmPrincipal.SConPrincipal.ExecuteDirect(sTextSqlDel); cds1.Delete; AtualizaTotal; Mensagem('LANÇAMENTO EXCLUÍDO COM SUCESSO ...','AVISO !!!', MB_OK+MB_ICONINFORMATION); except Mensagem('NÃO FOI POSSÍVEL EXCLUIR ESTE LANÇAMENTO ...','ERRO !!!', MB_OK+MB_ICONERROR); end; end else begin Mensagem('NÃO FOI POSSÍVEL EXCLUIR ÍTEM DA FATURA AVULSA: '+cds1R_REFERENCIA.AsString+' ...', 'ERRO !!!',MB_OK+MB_ICONERROR); end; end; procedure TfrmLanctoPagto.btnDetFatAvulsaClick(Sender: TObject); begin if cds1R_TIPO_FATURA.Value = '1' then begin frmDetalhaFatura := TfrmDetalhaFatura.Create(Self); frmDetalhaFatura.pb_iIdUnidConsum := cds1R_ID_UNID_CONSUM.Value; frmDetalhaFatura.pb_sAnoMes := Trim(cds1R_REFERENCIA.Value); frmDetalhaFatura.ShowModal; FreeAndNil(frmDetalhaFatura); end else begin frmCalcFaturaAvulsa := TfrmCalcFaturaAvulsa.Create(Self); frmCalcFaturaAvulsa.pb_iIdFatura := StrToInt(RightStr(Trim(cds1R_REFERENCIA.Value),8)); frmCalcFaturaAvulsa.ShowModal; FreeAndNil(frmCalcFaturaAvulsa); end; end; procedure TfrmLanctoPagto.btnLimparClick(Sender: TObject); begin cds1.Close; HabilitaBotoes(True); lblQtdLancto.Caption := '0'; lblTotPagto.Caption := '0,00'; edDtPagto.SetFocus; end; procedure TfrmLanctoPagto.btnOkClick(Sender: TObject); begin OpenTabPagtos; HabilitaBotoes(False); SetColGrid(1); dbg1.SetFocus; end; procedure TfrmLanctoPagto.cds1AfterOpen(DataSet: TDataSet); begin AtualizaTotal; end; procedure TfrmLanctoPagto.cdsEventoFixoAfterApplyUpdates( Sender: TObject; var OwnerData: OleVariant); begin dmPrincipal.GeraLog(cds1,'3','LANCTO_PAGTO',Self.Name,''); end; procedure TfrmLanctoPagto.GridDBTableView1ColumnHeaderClick( Sender: TcxGridTableView; AColumn: TcxGridDbColumn); begin SetColGrid(AColumn.Index); pv_sColIndex := AColumn.DataBinding.FieldName; end; procedure TfrmLanctoPagto.edPesquisaPropertiesChange(Sender: TObject); begin if cds1.RecordCount = 0 then exit; PesquisaIncremental(TcxTextEdit(Sender).Text,ds1,pv_sColIndex); end; procedure TfrmLanctoPagto.FormCreate(Sender: TObject); begin inherited; frmAddEditLanPagto := TfrmAddEditLanPagto.Create(Self); end; procedure TfrmLanctoPagto.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(frmAddEditLanPagto); end; procedure TfrmLanctoPagto.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); Var iConta, iConta2, iQtdCols: Integer; begin inherited; if Key = VK_F3 then begin if edPesquisa.Enabled then edPesquisa.SetFocus; end else if (Key = VK_F4) AND (edPesquisa.Enabled) then begin iConta := 0; iQtdCols:= GridDBTableView1.ColumnCount - 1; while True do begin if iConta > iQtdCols then iConta := 0; if GridDBTableView1.Columns[iConta].SortOrder <> soNone then begin GridDBTableView1.Columns[iConta].SortOrder := soNone; iConta2 := iConta+1; while true do begin if iConta2 > iQtdCols then iConta2 := 0; if GridDBTableView1.Columns[iConta2].Tag = 1 then begin GridDBTableView1.Columns[iConta2].SortOrder := soAscending; SetColGrid(iConta2); exit; end; Inc(iConta2); end; end; Inc(iConta); end; end; end; procedure TfrmLanctoPagto.FormShow(Sender: TObject); begin inherited; Caption := 'LANÇAMENTOS DE PAGTOS (BAIXAS) DE FATURAS ...'; PermissoesUsuario(glb_iIdOperLogado,'LANCTO_PAGTO'); HabilitaBotoes(True); edDtPagto.SetFocus; end; procedure TfrmLanctoPagto.Novo1Click(Sender: TObject); begin if TMenuItem(Sender).Tag = 1 then btnAdd.Click else btnEdit.Click; end; Procedure TfrmLanctoPagto.SetColGrid(iCol: Integer); Var iConta: Integer; begin //pb_iUltCol := iCol; edPesquisa.Enabled := GridDBTableView1.Columns[iCol].Tag = 1; cds1.IndexFieldNames := GridDBTableView1. Columns[iCol].DataBinding.FieldName; for iConta := 0 to GridDBTableView1.ColumnCount - 1 do GridDBTableView1.Columns[iConta].Styles.Header := nil; GridDBTableView1.Columns[iCol].Styles.Header := dmPrincipal.cxStyle20; end; Procedure TfrmLanctoPagto.AtualizaTotal; Var crTotTemp: Currency; bkmReg: TBookmark; begin crTotTemp := 0; bkmReg := cds1.GetBookmark; cds1.DisableControls; cds1.First; while not cds1.eof do begin crTotTemp := crTotTemp + cds1R_VAL_PAGTO.AsCurrency; cds1.Next; end; cds1.EnableControls; cds1.First; lblTotPagto.Caption := FormatCurr(',0.00',crTotTemp); lblQtdLancto.Caption := FormatCurr(',0',cds1.RecordCount); Application.ProcessMessages; cds1.GotoBookmark(bkmReg); cds1.FreeBookmark(bkmReg); end; Procedure TfrmLanctoPagto.HabilitaBotoes(lOpcao: Boolean); begin edDtPagto.Enabled := lOpcao; frmeLocalPagto1.Enabled := lOpcao; btnOk.Enabled := lOpcao; btnAdd.Enabled := not lOpcao; btnEdit.Enabled := not lOpcao; btnDel.Enabled := not lOpcao; btnLimpar.Enabled := not lOpcao; edPesquisa.Enabled := not lOpcao; btnDetFatAvulsa.Enabled := not lOpcao; if lOpcao = True then UsuarioPermissaoTabela(glb_iIdOperLogado,'LANCTO_PAGTO'); end; Procedure TfrmLanctoPagto.OpenTabPagtos; begin screen.cursor := crHourGlass; cds1.close; qry1.ParamByName('pDtIni').Value := StrToDate(edDtPagto.Text); qry1.ParamByName('pDtFim').Value := StrToDate(edDtPagto.Text); qry1.ParamByName('pLocal').AsString := ';'+Trim(frmeLocalPagto1.edId.Text)+';'; cds1.Open; screen.cursor := crDefault; end; procedure TfrmLanctoPagto.PermissoesUsuario(iIdUsuario: integer; sNomeTab: String); begin qryUsuarioPermissaoTabela.Close; qryUsuarioPermissaoTabela.ParamByName('pIdUsuario').Value:= iIdUsuario; qryUsuarioPermissaoTabela.ParamByName('pNomeTab').Value := sNomeTab; qryUsuarioPermissaoTabela.Open; btnAdd.Enabled := (qryUsuarioPermissaoTabelaINCLUIR.Value='S'); btnEdit.Enabled:= (qryUsuarioPermissaoTabelaALTERAR.Value='S'); btnDel.Enabled:= (qryUsuarioPermissaoTabelaEXCLUIR.Value='S'); qryUsuarioPermissaoTabela.Close; end; end.
TYPE ModTimeString = STRING[12]; FUNCTION MakeZsModTime(yr,mn,dy,hh,mm,ss : BYTE) : ModTimeString; { leap year calculator expects year argument as years offset from 1900 } FUNCTION LeapYear(year : INTEGER) : BOOLEAN; BEGIN LeapYear := ((year MOD 4) = 0) AND ( ((year MOD 100) <> 0) OR ((year MOD 400) = 0) ); END; CONST SecondsInDay = 86400.0; monthDays : ARRAY[1..12] OF BYTE = (31,28,31,30,31,30,31,31,30,31,30,31); FUNCTION bcd2bin(bcd : BYTE) : BYTE; BEGIN bcd2bin := (bcd SHR 4) * 10 + (bcd AND $0F); END; VAR i,year,month : INTEGER; seconds : REAL; octal : ModTimeString; digit : BYTE; BEGIN year := bcd2bin(yr) + 1900; IF year < 1978 THEN year := year + 100; seconds := (year - 1970) * SecondsInDay * 365; FOR i := 1970 TO year - 1 DO IF LeapYear(i) THEN seconds := seconds + SecondsInDay; { add days for this year } month := bcd2bin(mn); FOR i := 1 TO month - 1 DO IF (i = 2) AND LeapYear(year) THEN seconds := seconds + SecondsInDay * 29 ELSE seconds := seconds + SecondsInDay * monthDays[i]; seconds := seconds + (bcd2bin(dy) - 1) * SecondsInDay; seconds := seconds + bcd2bin(hh) * 3600.0; seconds := seconds + bcd2bin(mm) * 60.0; seconds := seconds + bcd2bin(ss); seconds := seconds + 6 * 3600.0; octal := ''; REPEAT; seconds := seconds / 8; digit := Trunc(Frac(seconds)*8+0.001); seconds := seconds - Frac(seconds); octal := Chr(digit+$30) + octal; UNTIL seconds = 0.0; MakeZsModTime := octal; END; FUNCTION MakeZrModTime(date : INTEGER) : ModTimeString; FUNCTION bcd2bin(bcd : BYTE) : BYTE; BEGIN bcd2bin := (bcd SHR 4) * 10 + (bcd AND $0F); END; CONST SecondsInDay = 86400.0; VAR i,year,month : INTEGER; seconds : REAL; octal : ModTimeString; digit : BYTE; BEGIN seconds := 252374400.0; { seconds from 1/1/1970 to 12/31/1977 } seconds := seconds + SecondsInDay * (256.0 * Mem[date+1] + Mem[date]); seconds := seconds + bcd2bin(Mem[date+2]) * 3600.0; seconds := seconds + bcd2bin(Mem[date+3]) * 60.0; seconds := seconds + 6 * 3600.0; octal := ''; REPEAT seconds := seconds / 8; digit := Trunc(Frac(seconds)*8+0.001); seconds := seconds - Frac(seconds); octal := Chr(digit+$30) + octal; UNTIL seconds = 0.0; MakeZrModTime := octal; END; 
{ *********************************************************************** } { } { Delphi Runtime Library } { } { Copyright (c) 1999-2001 Borland Software Corporation } { } { *********************************************************************** } unit CorbaVCL; {$T-,H+,X+} interface uses Classes, CorbaObj; type TCorbaVclComponentFactory = class(TCorbaFactory) private FComponentClass: TComponentClass; protected function CreateInterface(const InstanceName: string): IObject; override; public constructor Create(const InterfaceName, InstanceName, RepositoryId: string; const ImplGUID: TGUID; AComponentClass: TComponentClass; Instancing: TCorbaInstancing = iMultiInstance; ThreadModel: TCorbaThreadModel = tmSingleThread); property ComponentClass: TComponentClass read FComponentClass; end; implementation type TCorbaVclComponentAdapter = class(TCorbaImplementation, IVCLComObject) private FComponent: TComponent; protected function ObjQueryInterface(const IID: TGUID; out Obj): HResult; override; procedure FreeOnRelease; public //constructor Create(AComponentClass: TComponentClass); reintroduce; constructor CreateFromFactory(AFactory: TCorbaVclComponentFactory); destructor Destroy; override; end; { TCorbaVclComponentAdapter } constructor TCorbaVclComponentAdapter.CreateFromFactory(AFactory: TCorbaVclComponentFactory); begin inherited Create(nil, AFactory); FComponent := AFactory.ComponentClass.Create(nil); FComponent.VCLComObject := Pointer(IVCLComObject(Self)); end; destructor TCorbaVclComponentAdapter.Destroy; begin if FComponent <> nil then begin FComponent.VCLComObject := nil; FComponent.Free; end; inherited Destroy; end; procedure TCorbaVclComponentAdapter.FreeOnRelease; begin // Always frees on release end; function TCorbaVclComponentAdapter.ObjQueryInterface(const IID: TGUID; out Obj): HResult; begin Result := inherited ObjQueryInterface(IID, Obj); if Result <> 0 then if FComponent.GetInterface(IID, Obj) then Result := 0; end; { TCorbaVclComponentFactory } constructor TCorbaVclComponentFactory.Create(const InterfaceName, InstanceName, RepositoryId: string; const ImplGUID: TGUID; AComponentClass: TComponentClass; Instancing: TCorbaInstancing; ThreadModel: TCorbaThreadModel); begin inherited Create(InterfaceName, InstanceName, RepositoryID, ImplGUID, Instancing, ThreadModel); FComponentClass := AComponentClass; end; function TCorbaVclComponentFactory.CreateInterface(const InstanceName: string): IObject; begin Result := TCorbaVclComponentAdapter.CreateFromFactory(Self); end; end.
Unit BaseObject_f_ObjectListWithOffset; Interface Uses BaseObject_c_FunctionResult, BaseObject_c_ID, BaseObject_c_ObjectPayloadCoordinate; // Function BaseObjectObjectListWithOffsetEntryAdd(Const xxObjectID: TBaseObjectID; Const xxObjectChildListID: TBaseObjectID; Const xxObjectFatherListID: TBaseObjectID; xxXVectorAngle: TBaseObjectObjectPayloadCoordinateVectorAngle; xxXVectorLength: TBaseObjectObjectPayloadCoordinateVectorLength; xxYVectorAngle: TBaseObjectObjectPayloadCoordinateVectorAngle; xxYVectorLength: TBaseObjectObjectPayloadCoordinateVectorLength; xxZVectorAngle: TBaseObjectObjectPayloadCoordinateVectorAngle; xxZVectorLength: TBaseObjectObjectPayloadCoordinateVectorLength): TBaseObjectFunctionResult; // Implementation Uses BaseObject_c_File, BaseObject_c_ObjectListWithOffset, BaseObject_c_ObjectPayloadPoint, BaseObject_c_ObjectType, BaseObject_f_File, SysUtils; // Function BaseObjectObjectListWithOffsetEntryAdd(Const xxObjectID: TBaseObjectID; Const xxObjectChildListID: TBaseObjectID; Const xxObjectFatherListID: TBaseObjectID; xxXVectorAngle: TBaseObjectObjectPayloadCoordinateVectorAngle; xxXVectorLength: TBaseObjectObjectPayloadCoordinateVectorLength; xxYVectorAngle: TBaseObjectObjectPayloadCoordinateVectorAngle; xxYVectorLength: TBaseObjectObjectPayloadCoordinateVectorLength; xxZVectorAngle: TBaseObjectObjectPayloadCoordinateVectorAngle; xxZVectorLength: TBaseObjectObjectPayloadCoordinateVectorLength): TBaseObjectFunctionResult; Var caBaseObjectObjectListFileLengthInByteFact: cardinal; caBaseObjectObjectListFileLengthInByteMust: cardinal; caBaseObjectObjectListMemoryLengthInByte: cardinal; xxBaseObjectObjectListWithOffsetMemoryPointer: TBaseObjectObjectListWithOffsetMemoryPointer; xxFile: TBaseObjectFile; boFlag: boolean; caIndex: cardinal; Begin xxFile.boFileIsAssigned := False; BaseObjectFileFileAssign(xxObjectChildListID, xxFile); xxFile.boFileIsOpened := False; xxFile.inFileMode := fmOpenReadWrite; result := BaseObjectFileFileOpen(xxFile); If (result = coBaseObjectFunctionResult_Ok) Then Begin caBaseObjectObjectListFileLengthInByteFact := FileSize(xxFile.fiFileHandle); caBaseObjectObjectListMemoryLengthInByte := caBaseObjectObjectListFileLengthInByteFact + SizeOf(xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectID) + SizeOf(xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece) + SizeOf(xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset); GetMem(xxBaseObjectObjectListWithOffsetMemoryPointer, caBaseObjectObjectListMemoryLengthInByte); If (xxBaseObjectObjectListWithOffsetMemoryPointer <> Nil) Then Begin xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectID := xxObjectChildListID; xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece := 0; If (caBaseObjectObjectListFileLengthInByteFact = 0) Then Begin xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectMain.ObjectType := coBaseObjectObjectTypeEnum_ObjectListWithOffsetPayload; xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectMain.ObjectFatherListID := xxObjectID; caBaseObjectObjectListFileLengthInByteFact := SizeOf(xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectMain); End Else Begin result := BaseObjectFileObjectListWithOffsetLoad(@xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset); End; If (result = coBaseObjectFunctionResult_Ok) Then Begin caBaseObjectObjectListFileLengthInByteMust := SizeOf(xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectMain) + (xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece * SizeOf(xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectListWithOffset)); If (caBaseObjectObjectListFileLengthInByteMust = caBaseObjectObjectListFileLengthInByteFact) Then Begin boFlag := False; For caIndex := 0 To xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece Do Begin If (xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectListWithOffset[caIndex].ObjectID = xxObjectID) Then Begin boFlag := True; break; End; End; If boFlag Then Begin End Else Begin xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectListWithOffset[xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece].ObjectID := xxObjectChildListID; xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectListWithOffset[xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece].ObjectOffset.Y.VectorLength := xxXVectorLength; xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectListWithOffset[xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece].ObjectOffset.Y.VectorAngle := xxYVectorAngle; xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectListWithOffset[xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece].ObjectOffset.Y.VectorLength := xxYVectorLength; xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectListWithOffset[xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece].ObjectOffset.Z.VectorAngle := xxZVectorAngle; xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectListWithOffset[xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece].ObjectOffset.Z.VectorLength := xxZVectorLength; xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece := xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece + 1; caBaseObjectObjectListFileLengthInByteFact := SizeOf(xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectMain) + 1200; result := BaseObjectFileUndefinedUpdate(xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectID, @xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset, caBaseObjectObjectListFileLengthInByteFact); End; End; End Else Begin result := coBaseObjectFunctionResult_BaseObjectFileLengthError; End; End; End Else Begin result := coBaseObjectFunctionResult_MemoryBufferNotCtreated; End; // ? ? ? // xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListLengthInPiece := 1; // xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectMain.ObjectType := coBaseObjectObjectTypeEnum_ObjectListWithOffsetPayload; // xxBaseObjectObjectListWithOffsetMemoryPointer.ObjectListWithOffset.ObjectMain.ObjectFatherListID := xxObjectID; End; // End.
unit TestNested; { AFS 11 Jan 2000 This unit compiles but is not semantically meaningfull it is test cases for the code formatting utility This unit uses nested procs } interface implementation uses SysUtils; function Fred: string; begin Result := IntToStr (Random (20)); end; function Fred2: string; function GetARandomNumber: integer; begin Result := Random (20); end; begin Result := IntToStr (GetARandomNumber); end; function Fred3: string; function GetARandomNumber: integer; function GetLimit: integer; begin Result := 20; end; begin Result := Random (GetLimit); end; begin Result := IntToStr (GetARandomNumber); end; { the same agian, with more complexity - parameters, local vars and constants } procedure Jim1 (var ps1: string; const ps2: string); const FRED = 'Jim1'; var ls3: string; begin ls3 := FRED; ps1 := ls3 + ps2; end; procedure Jim2 (var ps1: string; const ps2: string); const FRED = 'Jim2'; function GetARandomNumber: integer; var liLimit: integer; begin liLimit := 10 * 2; Result := Random (liLimit); end; var ls3: string; begin ls3 := FRED; ps1 := ls3 + IntToStr (GetARandomNumber) + ps2; end; procedure Jim3 (var ps1: string; const ps2: string); const FRED = 'Jim3'; var ls3: string; function GetARandomNumber: integer; function GetLimit: integer; const HALF_LIMIT = 10; begin Result := HALF_LIMIT * 2; end; var liLimit: integer; begin liLimit := GetLimit; Result := Random (liLimit); end; begin ls3 := FRED; ps1 := ls3 + IntToStr (GetARandomNumber) + ps2; end; function MultiPass: integer; function One: integer; begin Result := 1; end; function Two: integer; begin Result := 2; end; function Three: integer; begin Result := 3; end; begin Result := One + Two + Three; end; end.
unit TestAlignment; {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is TestAlignment, released May 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. 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/NPL/ 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. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface { AFS 31 March 2003 Test alignment processes } uses TestFrameWork, BaseTestProcess; type TTestAlignment = class(TBaseTestProcess) private public procedure SetUp; override; published procedure TestAlignConst; procedure TestAlignConst2; procedure TestAlignConst3; procedure TestAlignConst4; procedure TestAlignVars; procedure TestAlignVars2; procedure TestAlignVars3; procedure TestAlignAssign; procedure TestAlignAssign2; procedure TestAlignComments; procedure TestAlignComments2; procedure TestAlignTypedef; procedure TestAlignTypedef2; procedure TestAlignFields; procedure TestAlignFields2; end; implementation uses { delphi } SysUtils, { local } JcfStringUtils, JcfSettings, AlignConst, AlignVars, AlignAssign, AlignComment, AlignTypedef, AlignField; procedure TTestAlignment.Setup; begin inherited; JcfFormatSettings.Align.MaxVariance := 5; end; procedure TTestAlignment.TestAlignConst; const IN_UNIT_TEXT = UNIT_HEADER + 'const' + NativeLineBreak + ' a = 3;' + NativeLineBreak + ' bee = 3;' + NativeLineBreak + ' deedee = 4.567;' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + 'const' + NativeLineBreak + ' a = 3;' + NativeLineBreak + ' bee = 3;' + NativeLineBreak + ' deedee = 4.567;' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignConst, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignConst2; const IN_UNIT_TEXT = UNIT_HEADER + 'procedure foo;' + NativeLineBreak + 'const' + NativeLineBreak + ' a = 3;' + NativeLineBreak + ' bee = 3;' + NativeLineBreak + ' deedee = 4.567;' + NativeLineBreak + ' begin end; ' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + 'procedure foo;' + NativeLineBreak + 'const' + NativeLineBreak + ' a = 3;' + NativeLineBreak + ' bee = 3;' + NativeLineBreak + ' deedee = 4.567;' + NativeLineBreak + ' begin end; ' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignConst, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignConst3; const IN_UNIT_TEXT = UNIT_HEADER + 'const' + NativeLineBreak + ' a = 3; ' + NativeLineBreak + ' bee = 3; ' + NativeLineBreak + ' deedee = 4.567; ' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + 'const' + NativeLineBreak + ' a = 3; ' + NativeLineBreak + ' bee = 3; ' + NativeLineBreak + ' deedee = 4.567; ' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignConst, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignConst4; const IN_UNIT_TEXT = UNIT_HEADER + 'const' + NativeLineBreak + ' a = 3;' + NativeLineBreak + ' bee = 3;' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + 'const' + NativeLineBreak + ' a = 3;' + NativeLineBreak + ' bee = 3;' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignConst, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignVars; const IN_UNIT_TEXT = UNIT_HEADER + 'var' + NativeLineBreak + ' a: integer;' + NativeLineBreak + ' bee: string;' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + 'var' + NativeLineBreak + ' a: integer;' + NativeLineBreak + ' bee: string;' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignVars, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignVars2; const IN_UNIT_TEXT = UNIT_HEADER + 'var' + NativeLineBreak + ' a: integer;' + NativeLineBreak + ' bee: string;' + NativeLineBreak + ' deedee: float;' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + 'var' + NativeLineBreak + ' a: integer;' + NativeLineBreak + ' bee: string;' + NativeLineBreak + ' deedee: float;' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignVars, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; // input for align vars and allign assign tests const MULTI_ALIGN_IN_UNIT_TEXT = UNIT_HEADER + 'procedure foo;' + NativeLineBreak + 'var' + NativeLineBreak + ' a: integer;' + NativeLineBreak + ' bee: string;' + NativeLineBreak + ' deedee: float;' + NativeLineBreak + 'begin' + NativeLineBreak + ' a := 3;' + NativeLineBreak + ' bee := ''foo'';' + NativeLineBreak + ' deedee := 34.56;' + NativeLineBreak + 'end;' + UNIT_FOOTER; procedure TTestAlignment.TestAlignVars3; const OUT_UNIT_TEXT = UNIT_HEADER + 'procedure foo;' + NativeLineBreak + 'var' + NativeLineBreak + ' a: integer;' + NativeLineBreak + ' bee: string;' + NativeLineBreak + ' deedee: float;' + NativeLineBreak + 'begin' + NativeLineBreak + ' a := 3;' + NativeLineBreak + ' bee := ''foo'';' + NativeLineBreak + ' deedee := 34.56;' + NativeLineBreak + 'end;' + UNIT_FOOTER; begin JcfFormatSettings.Align.AlignAssign := True; TestProcessResult(TAlignVars, MULTI_ALIGN_IN_UNIT_TEXT, OUT_UNIT_TEXT); TestProcessResult(TAlignVars, OUT_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignAssign; const OUT_UNIT_TEXT = UNIT_HEADER + 'procedure foo;' + NativeLineBreak + 'var' + NativeLineBreak + ' a: integer;' + NativeLineBreak + ' bee: string;' + NativeLineBreak + ' deedee: float;' + NativeLineBreak + 'begin' + NativeLineBreak + ' a := 3;' + NativeLineBreak + ' bee := ''foo'';' + NativeLineBreak + ' deedee := 34.56;' + NativeLineBreak + 'end;' + UNIT_FOOTER; begin JcfFormatSettings.Align.AlignAssign := True; TestProcessResult(TAlignAssign, MULTI_ALIGN_IN_UNIT_TEXT, OUT_UNIT_TEXT); TestProcessResult(TAlignAssign, OUT_UNIT_TEXT, OUT_UNIT_TEXT); end; { this one tests that - multiple blocks work - they align independantly - don't necessarily align on last line } procedure TTestAlignment.TestAlignAssign2; const IN_UNIT_TEXT = UNIT_HEADER + 'procedure foo;' + NativeLineBreak + 'var' + NativeLineBreak + ' a, aa: integer;' + NativeLineBreak + ' bee, bee2: string;' + NativeLineBreak + ' deedee, deedee2: float;' + NativeLineBreak + 'begin' + NativeLineBreak + ' a := 3;' + NativeLineBreak + ' bee := ''foo'';' + NativeLineBreak + ' deedee := 34.56;' + NativeLineBreak + ' Foo;' + NativeLineBreak + ' Bar;' + NativeLineBreak + ' aa := 3;' + NativeLineBreak + ' deedee2 := 34.56;' + NativeLineBreak + ' bee2 := ''foo'';' + NativeLineBreak + 'end;' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + 'procedure foo;' + NativeLineBreak + 'var' + NativeLineBreak + ' a, aa: integer;' + NativeLineBreak + ' bee, bee2: string;' + NativeLineBreak + ' deedee, deedee2: float;' + NativeLineBreak + 'begin' + NativeLineBreak + ' a := 3;' + NativeLineBreak + ' bee := ''foo'';' + NativeLineBreak + ' deedee := 34.56;' + NativeLineBreak + ' Foo;' + NativeLineBreak + ' Bar;' + NativeLineBreak + ' aa := 3;' + NativeLineBreak + ' deedee2 := 34.56;' + NativeLineBreak + ' bee2 := ''foo'';' + NativeLineBreak + 'end;' + UNIT_FOOTER; begin TestProcessResult(TAlignAssign, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignComments; const IN_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' // foo' + NativeLineBreak + ' { bar bie } ' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' // foo' + NativeLineBreak + ' { bar bie } ' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignComment, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignComments2; const IN_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' // foo' + NativeLineBreak + ' { bar bie } ' + NativeLineBreak + ' // baz' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' // foo' + NativeLineBreak + ' { bar bie } ' + NativeLineBreak + ' // baz' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignComment, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignTypedef; const IN_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' type ' + NativeLineBreak + ' foo = integer; ' + NativeLineBreak + ' barnee = string; ' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' type ' + NativeLineBreak + ' foo = integer; ' + NativeLineBreak + ' barnee = string; ' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignTypedef, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignTypedef2; const IN_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' type ' + NativeLineBreak + ' foo = integer; ' + NativeLineBreak + ' barnee = string; ' + NativeLineBreak + ' Baaaaaaz = float; ' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' type ' + NativeLineBreak + ' foo = integer; ' + NativeLineBreak + ' barnee = string; ' + NativeLineBreak + ' Baaaaaaz = float; ' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignTypedef, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignFields; const IN_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' type ' + NativeLineBreak + ' foo = class ' + NativeLineBreak + ' private' + NativeLineBreak + ' aaaa: integer;' + NativeLineBreak + ' aaaaaa: integer;' + NativeLineBreak + ' aa: integer;' + NativeLineBreak + ' public' + NativeLineBreak + ' fi: integer;' + NativeLineBreak + ' fi1: integer;' + NativeLineBreak + ' fi111: integer;' + NativeLineBreak + ' end; ' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' type ' + NativeLineBreak + ' foo = class ' + NativeLineBreak + ' private' + NativeLineBreak + ' aaaa: integer;' + NativeLineBreak + ' aaaaaa: integer;' + NativeLineBreak + ' aa: integer;' + NativeLineBreak + ' public' + NativeLineBreak + ' fi: integer;' + NativeLineBreak + ' fi1: integer;' + NativeLineBreak + ' fi111: integer;' + NativeLineBreak + ' end; ' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignField, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestAlignment.TestAlignFields2; const IN_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' type ' + NativeLineBreak + ' TRfoo = record ' + NativeLineBreak + ' fi: integer;' + NativeLineBreak + ' fi1: integer;' + NativeLineBreak + ' fi111: integer;' + NativeLineBreak + ' end; ' + NativeLineBreak + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + NativeLineBreak + ' type ' + NativeLineBreak + ' TRfoo = record ' + NativeLineBreak + ' fi: integer;' + NativeLineBreak + ' fi1: integer;' + NativeLineBreak + ' fi111: integer;' + NativeLineBreak + ' end; ' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TAlignField, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; initialization TestFramework.RegisterTest('Processes', TTestAlignment.Suite); end.
unit ncBrowserUtils; interface uses Classes; procedure ChangeHomePage(aURL: String; aTabs: Boolean); function GetSysFolder(csidl: integer): String; // CHROME procedure Chrome_Install_Ext(aID, aPath, aVersion: String); procedure Chrome_Remove_Ext(aID: String); function Chrome_BaseExt_Folder: String; function Chrome_Ext_Folder(aID, aVersion: String): String; function Chrome_Pref_Folder: String; procedure Chrome_ChangeHomePage(aURL: String); procedure Chrome_ChangeTabHomePage(aURL: String); function GetLocalAppData: String; procedure Chrome_Install_NexCafe_Ext; procedure Chrome_Remove_NexCafe_Ext; // FIREFOX function FF_Profile_Folders: TStrings; procedure FF_ChangeHomePage(aURL: String; aTabs: Boolean); // IE procedure IE_ChangeHomePage(aURL: String; aTabs: Boolean); procedure IE_RemoveHomePage; implementation uses ncCheckWin64, Registry, Windows, SHFolder, SysUtils, ncChromeExt; const nexchromeext_id = 'jacgaboiemcjbhbkladmdaklboajmcgg'; nexchromeext_ver = '1.4'; procedure ChangeHomePage(aUrl: String; aTabs: Boolean); begin Chrome_ChangeHomePage(aUrl); Chrome_ChangeTabHomePage(aUrl); FF_ChangeHomePage(aUrl, aTabs); IE_ChangeHomePage(aUrl, aTabs); if aTabs then Chrome_Install_NexCafe_Ext else Chrome_Remove_NexCafe_Ext; end; procedure Chrome_Install_NexCafe_Ext; begin ncChromeExt.ExtractChromeExt; Chrome_Install_Ext(nexchromeext_id, ExtractFilePath(ParamStr(0))+'chrome_ext.crx', nexchromeext_ver); end; procedure Chrome_Remove_NexCafe_Ext; var s: string; begin Chrome_Remove_Ext(nexchromeext_id); s := ExtractFilePath(ParamStr(0))+'chrome_ext.crx'; if FileExists(s) then DeleteFile(s); end; function GetLocalAppData: String; begin Result := GetSysFolder(CSIDL_LOCAL_APPDATA); end; function GetSysFolder(csidl: integer): String; const TOKEN_DEFAULTUSER = $FFFF; // -1 var szBuffer: AnsiString; // <-- here ResultCode: Integer; begin Result := ''; // avoid function might return undefined warning SetLength(szBuffer, 255); ResultCode := SHGetFolderPathA(0, CSIDL, TOKEN_DEFAULTUSER, 0, PAnsiChar(szBuffer)); if ResultCode = 0 then Result := String(PAnsiChar(szBuffer)); end; function BasePath: String; begin if IsWow64 then Result := '\Software\Wow6432Node\Google\Chrome\Extensions' else Result := '\Software\Google\Chrome\Extensions'; end; function Chrome_BaseExt_Folder: String; begin Result := Chrome_Pref_Folder + '\Extensions'; end; function Chrome_Pref_Folder: String; begin Result := GetLocalAppData + '\Google\Chrome\User Data\Default'; end; function Chrome_Ext_Folder(aID, aVersion: String): String; begin Result := Chrome_BaseExt_Folder+'\'+aID+'\'+aVersion+'_0'; end; procedure Chrome_ChangeTabHomePage(aURL: String); var sl : TStrings; s : String; begin s := Chrome_Ext_Folder(nexchromeext_id, nexchromeext_ver)+'\redirect.html'; if not FileExists(s) then Exit; sl := TStringList.Create; try if not SameText(copy(aURL, 1, 7), 'http://') then aURL := 'http://'+aURL; sl.Text := '<html><head><meta http-equiv="Refresh" content="0; url='+aURL+'">'+ '<title>Nova página</title></head><body></body></html>'; sl.SaveToFile(s); finally sl.Free; end; end; procedure Chrome_Install_Ext(aID, aPath, aVersion: String); var R: TRegistry; begin R := TRegistry.Create; try R.Access := KEY_ALL_ACCESS; R.RootKey := HKEY_LOCAL_MACHINE; R.OpenKey(BasePath+'\'+aID, True); R.WriteString('path', aPath); R.WriteString('version', aVersion); R.CloseKey; finally R.Free; end; end; procedure Chrome_Remove_Ext(aID: String); var R: TRegistry; begin R := TRegistry.Create; try R.Access := KEY_ALL_ACCESS; R.RootKey := HKEY_LOCAL_MACHINE; R.DeleteKey(BasePath+'\'+aID); R.CloseKey; finally R.Free; end; end; procedure Chrome_ChangeHomePage(aURL: String); const find_str = '"urls_to_restore_on_startup":'; var sl : TStrings; i, p : Integer; s : String; aChanged: Boolean; begin S := Chrome_Pref_Folder+'\preferences'; if not FileExists(S) then Exit; aChanged := False; sl := TStringList.Create; try sl.LoadFromFile(s); for i := 0 to sl.Count -1 do begin P := Pos(find_str, sl[i]); if P>0 then begin sl[i] := Copy(sl[i], 1, p+length(find_str)-1) + ' [ "'+aURL+'" ]'; aChanged := True; end; end; if aChanged then sl.SaveToFile(s); finally sl.Free; end; end; function GetAppData: String; const TOKEN_DEFAULTUSER = $FFFF; // -1 var szBuffer: AnsiString; // <-- here ResultCode: Integer; begin Result := ''; // avoid function might return undefined warning SetLength(szBuffer, 255); ResultCode := SHGetFolderPathA(0, CSIDL_APPDATA, TOKEN_DEFAULTUSER, 0, PAnsiChar(szBuffer)); if ResultCode = 0 then Result := String(PAnsiChar(szBuffer)); end; function FF_Profile_Folders: TStrings; var s: String; sr: TSearchRec; begin Result := nil; S := GetAppData + '\Mozilla\Firefox\Profiles'; if not DirectoryExists(S) then Exit; if FindFirst(S+'\*.*', faDirectory, sr)=0 then try repeat if (sr.Name<>'.') and (sr.Name<>'..') then begin if Result=nil then Result := TStringList.Create; Result.Add(S+'\'+Sr.Name); end; until (FindNext(sr)<>0); finally FindClose(sr); end; end; procedure FF_ChangeHomePage(aURL: String; aTabs: Boolean); var sl : TStrings; sl2 : TStrings; i,p : Integer; s : String; procedure UpdateFile(aParam: String; aDel: Boolean); var j: integer; begin p := 0; for j := 0 to sl2.Count-1 do begin p := pos(aParam, sl2[j]); if p>0 then Break; end; aParam := 'user_pref('+aParam+', "'+aURL+'");'; if p>0 then begin if aDel then sl2.Delete(j) else sl2[j] := aParam ; end else if not aDel then sl2.Add(aParam); end; begin sl := FF_Profile_Folders; if sl=nil then Exit; sl2 := TStringList.Create; try for i := 0 to sl.count-1 do begin s := sl[i]+'\user.js'; sl2.Clear; if FileExists(s) then sl2.LoadFromFile(s); UpdateFile('"browser.startup.homepage"', False); UpdateFile('"browser.newtab.url"', not aTabs); sl2.SaveToFile(s); end; finally sl2.Free; sl.Free; end; end; procedure IE_RemoveHomePage; var R: TRegistry; begin R := TRegistry.Create; try R.Access := KEY_ALL_ACCESS; R.RootKey := HKEY_CURRENT_USER; R.OpenKey('\Software\Microsoft\Internet Explorer\Main', True); R.WriteString('Start Page', 'about:blank'); R.CloseKey; R.OpenKey('\Software\Microsoft\Internet Explorer\TabbedBrowsing', True); R.WriteInteger('NewTabPageShow', 0); R.CloseKey; R.OpenKey('\Software\Policies\Microsoft\Internet Explorer\Main', True); R.DeleteValue('Start Page'); R.CloseKey; R.OpenKey('\Software\Policies\Microsoft\Internet Explorer\TabbedBrowsing', True); R.DeleteValue('NewTabPageShow'); R.CloseKey; finally R.Free; end; end; procedure IE_ChangeHomePage(aURL: String; aTabs: Boolean); var R: TRegistry; begin R := TRegistry.Create; try R.Access := KEY_ALL_ACCESS; R.RootKey := HKEY_CURRENT_USER; R.OpenKey('\Software\Microsoft\Internet Explorer\Main', True); R.WriteString('Start Page', aURL); R.CloseKey; R.OpenKey('\Software\Microsoft\Internet Explorer\TabbedBrowsing', True); if aTabs then R.WriteInteger('NewTabPageShow', 1) else R.WriteInteger('NewTabPageShow', 0); R.CloseKey; R.OpenKey('\Software\Policies\Microsoft\Internet Explorer\Main', True); R.WriteString('Start Page', aURL); R.CloseKey; R.OpenKey('\Software\Policies\Microsoft\Internet Explorer\TabbedBrowsing', True); if aTabs then R.WriteInteger('NewTabPageShow', 1) else R.WriteInteger('NewTabPageShow', 0); R.CloseKey; finally R.Free; end; end; end.
unit int_32_0; interface implementation var i, j, r: Int32; procedure Test; begin i := 9; j := 9; r := j - i - 1; end; initialization Test(); finalization Assert(r = -1); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2015-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit EMSHosting.Helpers; {$SCOPEDENUMS ON} interface uses System.SysUtils, System.JSON, EMS.ResourceAPI, EMS.Services, EMS.ResourceTypes; type TEndpointHelpers = class private type TCreatorIDs = record const Master = '00000000-0000-0000-0000-000000000001'; Null = '00000000-0000-0000-0000-000000000000'; end; public class function IdentityFromContext(const AContext: TEndpointContext): string; class function CreatorRequired(const AContext: TEndpointContext): Boolean; class procedure SetCreatorRequired(const AContext: TEndpointContext); class procedure CheckCreator(const AContext: TEndpointContext; const AGetCreator: TFunc<string>); overload; class procedure CheckCreator(const AContext: TEndpointContext; const ACreator: string); overload; end; TLogHelpers = class protected type TLogCallback = reference to procedure(const AJSON: TJSONObject); private class function GetLoggingEnabled: Boolean; static; class function GetService: IEMSLoggingService; static; protected class procedure DoLog(const ACategory: string; const ACallback: TLogCallback); public class procedure LogSetupCustomOutput(const AEnabled: TEMSLoggingEnabledFunc; const AOutput: TEMSLoggingOutputProc; const ASynchronize: Boolean); class procedure LogSetupFileOutput(const AFileName: string; const AAppend: Boolean); class procedure LogRequest(const AResourceName, AEndpointName, AMethod, AUserID: string); static; class procedure LogRedirect(const AResourceName, AEndpointName, ADestinationResourceName, ADestinationEndpointName: string); static; class procedure LogHTTPError(ACode: Integer; const AReason: string; const AError, ADescription: string); class procedure LogException(const AException: Exception); class procedure LogPackageException(const AFileName: string; const AException: Exception); class procedure LogPackageLoading(const AFileName: string); static; class procedure LogPackageLoaded(const AFileName: string); static; class procedure LogRegisterResource(const AResource: TEMSResource); class procedure LogRegisterACL(const AName, AValue: string); static; class procedure LogRegisterRedirect(const AName, AValue: string); static; class procedure LogConfigurationLoaded(const AFileName: string; AFileExists: Boolean); static; class procedure LogMessage(const AMessage: string); static; class function Format(const AJSON: TJSONObject): string; static; class property LoggingEnabled: Boolean read GetLoggingEnabled; end; TErrorHelpers = class public class function CreateJSONError(const AReasonString, AError, ADescription: string): TJSONObject; static; end; TLogCategoryNames = record public const Request = 'Request'; Redirect = 'Redirect'; Error = 'Error'; Loading = 'Loading'; Loaded = 'Loaded'; Push = 'Push'; RegisterUnit = 'RegUnit'; RegisterResource = 'RegResource'; RegisterACL = 'RegACL'; RegisterRedirect = 'RegRedirect'; ConfigLoaded = 'ConfigLoaded'; DBConnection = 'DBConnection'; Licensing = 'Licensing'; TraceMessage = 'Trace'; PublicPath = 'PublicPath'; end; TLogErrorTypes = record public const HTTP = 'HTTP'; Other = 'Other'; Package = 'Package'; end; TLogObjectNames = record public const Application = 'Application'; Started = 'Started'; Log = 'Log'; Thread = 'Thread'; Resource = 'Resource'; Endpoint = 'Endpoint'; DestinationResource = 'DestinationResource'; DestinationEndpoint = 'DestinationEndpoint'; Endpoints = 'Endpoints'; Method = 'Method'; UserID = 'User'; Time = 'Time'; Redirect = 'Redirect'; Push = 'Push'; Code = 'Code'; Reason = 'Reason'; Error = 'Error'; Description = 'Description'; FileName = 'Filename'; FileExists = 'Exists'; UnitName = 'Unitname'; ExceptionClass = 'Exception'; ExceptionMessage = 'Message'; TraceMessage = 'Message'; ErrorType = 'Type'; DBInstanceName = 'InstanceName'; DBFileName = 'Filename'; Licensed = 'Licensed'; LicensedMaxUsers = 'LicensedMaxUsers'; DefaultMaxUsers = 'DefaultMaxUsers'; PublicDirectory = 'PublicDirectory'; LogicalPath = 'LogicalPath'; DefaultFile = 'DefaultFile'; Mimes = 'Mimes'; Extensions = 'Extensions'; Charset = 'Charset'; end; implementation uses EMSHosting.Endpoints, EMSHosting.Consts; const sBlank = '(blank)'; { TEndpointHelpers } class procedure TEndpointHelpers.CheckCreator( const AContext: TEndpointContext; const ACreator: string); begin CheckCreator(AContext, function: string begin Result := ACreator end); end; class function TEndpointHelpers.CreatorRequired( const AContext: TEndpointContext): Boolean; begin if AContext is TEndpointContextImpl then Result := TEndpointContextImpl(AContext).CreatorRequired else Result := False; end; class procedure TEndpointHelpers.SetCreatorRequired( const AContext: TEndpointContext); begin if AContext is TEndpointContextImpl then TEndpointContextImpl(AContext).SetCreatorRequired; end; class procedure TEndpointHelpers.CheckCreator( const AContext: TEndpointContext; const AGetCreator: TFunc<string>); var LContextIdentity: string; LCreator: string; begin if CreatorRequired(AContext) then begin LCreator := AGetCreator; if LCreator = TCreatorIDs.Null then // No creator EEMSHTTPError.RaiseUnauthorized else begin LContextIdentity := IdentityFromContext(AContext); Assert(LContextIdentity <> TCreatorIDs.Master); // Shouldn't be here if master auth if LContextIdentity <> AGetCreator then EEMSHTTPError.RaiseUnauthorized; end end; end; class function TEndpointHelpers.IdentityFromContext( const AContext: TEndpointContext): string; begin if AContext.User <> nil then Result := AContext.User.UserID else if TEndpointContext.TAuthenticate.MasterSecret in AContext.Authenticated then Result := TCreatorIDs.Master else Result := TCreatorIDs.Null end; { TLogHelpers } class procedure TLogHelpers.DoLog(const ACategory: string; const ACallback: TLogCallback); var LService: IEMSLoggingService; LJSON: TJSONObject; begin if LoggingEnabled then begin LService := GetService; LJSON := TJSONObject.Create; try ACallback(LJSON); Assert(ACategory <> ''); Assert(LJSON.Count > 0); LService.Log(ACategory, LJSON); finally LJSON.Free; end; end; end; class function TLogHelpers.Format(const AJSON: TJSONObject): string; var LBld: TStringBuilder; S: string; P, PEnd: PChar; begin LBld := TStringBuilder.Create; try S := AJSON.ToString; P := Pointer(S); PEnd := P + Length(S); while P < PEnd do begin case P^ of '\': begin Inc(P); case P^ of '"': LBld.Append('"'); '\': LBld.Append('\'); '/': LBld.Append('/'); 'b': LBld.Append(#$8); 'f': LBld.Append(#$c); 'n': LBld.Append(#$a); 'r': LBld.Append(#$d); 't': LBld.Append(#$9); end; end; '[': if (P + 1)^ = '{' then begin LBld.Append('[' + sLineBreak + ' {'); Inc(P); end else LBld.Append(P^); '}': if (P + 1)^ = ']' then begin LBld.Append('}' + sLineBreak + ']'); Inc(P); end else if ((P + 1)^ = ',') and ((P + 2)^ = '{') then begin LBld.Append('},' + sLineBreak + ' {'); Inc(P, 2); end else LBld.Append(P^); else LBld.Append(P^); end; Inc(P); end; Result := LBld.ToString(True); finally LBld.Free; end; end; class function TLogHelpers.GetLoggingEnabled: Boolean; var LService: IEMSLoggingService; begin LService := GetService; if LService <> nil then Result := LService.LoggingEnabled else Result := False; end; class function TLogHelpers.GetService: IEMSLoggingService; begin if (EMS.Services.EMSServices = nil) or not EMS.Services.EMSServices.TryGetService(IEMSLoggingService, Result) then Result := nil; end; class procedure TLogHelpers.LogSetupCustomOutput(const AEnabled: TEMSLoggingEnabledFunc; const AOutput: TEMSLoggingOutputProc; const ASynchronize: Boolean); var LService: IEMSLoggingServiceSetup; begin LService := GetService as IEMSLoggingServiceSetup; if LService <> nil then LService.SetupCustomOutput(AEnabled, AOutput, ASynchronize); end; class procedure TLogHelpers.LogSetupFileOutput(const AFileName: string; const AAppend: Boolean); var LService: IEMSLoggingServiceSetup; begin LService := GetService as IEMSLoggingServiceSetup; if LService <> nil then LService.SetupFileOutput(AFileName, AAppend); end; class procedure TLogHelpers.LogHTTPError(ACode: Integer; const AReason, AError, ADescription: string); begin DoLog(TLogCategoryNames.Error, procedure(const LJSON: TJSONObject) begin LJSON.AddPair(TLogObjectNames.ErrorType, TLogErrorTypes.HTTP); LJSON.AddPair(TLogObjectNames.Code, IntToStr(ACode)); LJSON.AddPair(TLogObjectNames.Reason, AReason); LJSON.AddPair(TLogObjectNames.Error, AError); LJSON.AddPair(TLogObjectNames.Description, ADescription); end); end; class procedure TLogHelpers.LogPackageException(const AFileName: string; const AException: Exception); begin DoLog(TLogCategoryNames.Error, procedure(const LJSON: TJSONObject) begin LJSON.AddPair(TLogObjectNames.ErrorType, TLogErrorTypes.Package); LJSON.AddPair(TLogObjectNames.FileName, AFileName); LJSON.AddPair(TLogObjectNames.ExceptionClass, AException.ClassName); LJSON.AddPair(TLogObjectNames.ExceptionMessage, AException.Message); end); end; class procedure TLogHelpers.LogPackageLoading(const AFileName: string); begin DoLog(TLogCategoryNames.Loading, procedure(const LJSON: TJSONObject) begin LJSON.AddPair(TLogObjectNames.FileName, AFileName); end); end; class procedure TLogHelpers.LogPackageLoaded(const AFileName: string); begin DoLog(TLogCategoryNames.Loaded, procedure(const LJSON: TJSONObject) begin LJSON.AddPair(TLogObjectNames.FileName, AFileName); end); end; class procedure TLogHelpers.LogRegisterACL(const AName, AValue: string); begin DoLog(TLogCategoryNames.RegisterACL, procedure(const LJSON: TJSONObject) var LJSONACL: TJSONValue; begin LJSON.AddPair(TLogObjectNames.Resource, AName); LJSONACL := TJSONObject.ParseJSONValue(AValue); if (LJSONACL = nil) or not (LJSONACL is TJSONObject) then begin LJSONACL.Free; LJSONACL := TJSONObject.Create; TJSONObject(LJSONACL).AddPair('InvalidJSON', AValue); end; LJSON.AddPair('ACL', LJSONACL); end); end; class procedure TLogHelpers.LogRegisterRedirect(const AName, AValue: string); begin DoLog(TLogCategoryNames.RegisterRedirect, procedure(const LJSON: TJSONObject) var LJSONRedirect: TJSONValue; begin LJSON.AddPair(TLogObjectNames.Resource, AName); LJSONRedirect := TJSONObject.ParseJSONValue(AValue); if (LJSONRedirect = nil) or not (LJSONRedirect is TJSONObject) then begin LJSONRedirect.Free; LJSONRedirect := TJSONObject.Create; TJSONObject(LJSONRedirect).AddPair('InvalidJSON', AValue); end; LJSON.AddPair('Redirect', LJSONRedirect); end); end; class procedure TLogHelpers.LogRegisterResource(const AResource: TEMSResource); begin DoLog(TLogCategoryNames.RegisterResource, procedure(const LJSON: TJSONObject) var LEndpoints: TJSONArray; S: string; begin if not Assigned(EMSLoggingResourceFunc) or not EMSLoggingResourceFunc(AResource, LJSON) then begin LJSON.AddPair(TLogObjectNames.Resource, AResource.Name); LEndpoints := TJSONArray.Create; for S in AResource.EndpointNames do LEndpoints.Add(S); LJSON.AddPair(TLogObjectNames.Endpoints, LEndpoints); end; end); end; class procedure TLogHelpers.LogConfigurationLoaded(const AFileName: string; AFileExists: Boolean); begin DoLog(TLogCategoryNames.ConfigLoaded, procedure(const LJSON: TJSONObject) begin LJSON.AddPair(TLogObjectNames.FileName, AFileName); LJSON.AddPair(TLogObjectNames.FileExists, TJSONBool.Create(AFileExists)); end); end; class procedure TLogHelpers.LogException( const AException: Exception); begin DoLog(TLogCategoryNames.Error, procedure(const LJSON: TJSONObject) begin LJSON.AddPair(TLogObjectNames.ErrorType, TLogErrorTypes.Other); LJSON.AddPair(TLogObjectNames.ExceptionClass, AException.ClassName); LJSON.AddPair(TLogObjectNames.ExceptionMessage, AException.Message); end); end; class procedure TLogHelpers.LogRequest(const AResourceName, AEndpointName, AMethod, AUserID: string); begin DoLog(TLogCategoryNames.Request, procedure(const LJSON: TJSONObject) begin LJSON.AddPair(TLogObjectNames.Resource, AResourceName); LJSON.AddPair(TLogObjectNames.Endpoint, AEndpointName); LJSON.AddPair(TLogObjectNames.Method, AMethod); if AUserID <> '' then LJSON.AddPair(TLogObjectNames.UserID, AUserID) else LJSON.AddPair(TLogObjectNames.UserID, TJSONString.Create(sBlank)); LJSON.AddPair(TLogObjectNames.Time, DateTimeToStr(Now)); end); end; class procedure TLogHelpers.LogRedirect(const AResourceName, AEndpointName, ADestinationResourceName, ADestinationEndpointName: string); begin DoLog(TLogCategoryNames.Redirect, procedure(const LJSON: TJSONObject) begin LJSON.AddPair(TLogObjectNames.Resource, AResourceName); LJSON.AddPair(TLogObjectNames.Endpoint, AEndpointName); LJSON.AddPair(TLogObjectNames.DestinationResource, ADestinationResourceName); LJSON.AddPair(TLogObjectNames.DestinationEndpoint, ADestinationEndpointName); LJSON.AddPair(TLogObjectNames.Time, DateTimeToStr(Now)); end); end; class procedure TLogHelpers.LogMessage(const AMessage: string); begin DoLog(TLogCategoryNames.TraceMessage, procedure(const LJSON: TJSONObject) begin LJSON.AddPair(TLogObjectNames.TraceMessage, AMessage); end); end; { TErrorHelpers } class function TErrorHelpers.CreateJSONError(const AReasonString, AError, ADescription: string): TJSONObject; const sError = 'error'; sDescription = 'description'; begin Result := TJSONObject.Create; if AError <> '' then Result.AddPair(sError, AError) // Do not localize else Result.AddPair(sError, AReasonString); if ADescription <> '' then Result.AddPair(sDescription, ADescription); end; end.
unit MediaProcessing.Convertor.RGB.VFW; interface uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global,VFW; type TCodecMode = (cmRealTime,cmStandard); TMediaProcessor_Convertor_Rgb_Vfw=class (TMediaProcessor,IMediaProcessor_Convertor_Rgb_Vfw) protected FCodecFCC: cardinal; FCodecState: TBytes; FCodecMode : TCodecMode; protected procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override; procedure LoadCustomProperties(const aReader: IPropertiesReader); override; class function MetaInfo:TMediaProcessorInfo; override; public constructor Create; override; destructor Destroy; override; function HasCustomProperties: boolean; override; procedure ShowCustomProperiesDialog;override; end; implementation uses Controls,uBaseClasses,MediaProcessing.Convertor.RGB.Vfw.SettingsDialog; { TMediaProcessor_Convertor_Rgb_Vfw } constructor TMediaProcessor_Convertor_Rgb_Vfw.Create; begin inherited; FCodecMode:=cmRealTime; end; destructor TMediaProcessor_Convertor_Rgb_Vfw.Destroy; begin inherited; end; function TMediaProcessor_Convertor_Rgb_Vfw.HasCustomProperties: boolean; begin result:=true; end; class function TMediaProcessor_Convertor_Rgb_Vfw.MetaInfo: TMediaProcessorInfo; begin result.Clear; result.TypeID:=IMediaProcessor_Convertor_Rgb_Vfw; result.Name:='Конвертор RGB->VFW'; result.Description:='Преобразует видеокадры формата RGB в любой формат, имеющийся в операционной системе (технология Video For Windows)'; result.SetInputStreamType(stRGB); result.OutputStreamType:=stUNIV; result.ConsumingLevel:=9; end; procedure TMediaProcessor_Convertor_Rgb_Vfw.LoadCustomProperties(const aReader: IPropertiesReader); begin inherited; FCodecFCC:=aReader.ReadInteger('Codec FCC',FCodecFCC); FCodecMode:=TCodecMode(aReader.ReadInteger('Codec Mode',integer(FCodecMode))); FCodecState:=aReader.ReadBytes('Codec State'); end; procedure TMediaProcessor_Convertor_Rgb_Vfw.SaveCustomProperties(const aWriter: IPropertiesWriter); begin inherited; aWriter.WriteInteger('Codec FCC',FCodecFCC); aWriter.WriteInteger('Codec Mode',integer(FCodecMode)); aWriter.WriteBytes('Codec State',FCodecState); end; procedure TMediaProcessor_Convertor_Rgb_Vfw.ShowCustomProperiesDialog; var aDialog: TfmMediaProcessingSettingsRgb_Vfw; begin aDialog:=TfmMediaProcessingSettingsRgb_Vfw.Create(nil); try aDialog.SetCodec(FCodecFCC,FCodecState); aDialog.edCodec.Text:=LowerCase(string(FOURCCTOSTR(FCodecFCC))); aDialog.buPerformanceSpeed.Checked:=FCodecMode=cmRealTime; aDialog.buPerformanceQuality.Checked:=FCodecMode=cmStandard; if aDialog.ShowModal=mrOK then begin aDialog.GetCodec(FCodecFCC,FCodecState); if aDialog.buPerformanceSpeed.Checked then FCodecMode:=cmRealTime else FCodecMode:=cmStandard; end; finally aDialog.Free; end; end; initialization MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Convertor_Rgb_Vfw); end.
unit CAM_GCM; (************************************************************************* DESCRIPTION : CAM GCM mode functions REQUIREMENTS : TP5-7, D1-D7/D9-D12/D17-D18/D25S, FPC, VP, WDOSX EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- WARNING : GCM mode (as all CTR modes) demands that the same key / IV pair is never reused for encryption. REFERENCES : [1] D. McGrew, J. Viega, The Galois/Counter Mode of Operation (GCM) http://www.csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf [2] B. Gladman, source code archives aes-modes-src-23-07-09.zip and aes-modes-vs2008-07-10-08.zip http://gladman.plushost.co.uk/oldsite/AES/index.php, source code archives [3] M. Dworkin, Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf REMARKS : This implementation uses a GCM version with 4KB table. [A table-less version can be generated if gf_t4k is removed and gf_mul_h simply uses gf_mul(a, ctx.ghash_h). Using a 256 byte table is slower than a table-less version, a 64KB table version is incompatible with 16-bit code.] See [3] for recommendations on IV and tag length Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 08.11.17 W.Ehrhardt Initial version: from AES_GCM 0.33 **************************************************************************) (*------------------------------------------------------------------------- Pascal Implementation (C) Copyright 2010-2017 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i STD.INC} interface uses BTypes, CAM_Base; type TCAMGCM_Tab4K = array[0..255] of TCAMBlock; {64 KB gf_mul_h table } type TBit64 = packed array[0..1] of longint; {64 bit counter } type TCAM_GCMContext = packed record actx : TCAMContext; {Basic CAM context } aad_ghv : TCAMBlock; {ghash value AAD } txt_ghv : TCAMBlock; {ghash value ciphertext} ghash_h : TCAMBlock; {ghash H value } gf_t4k : TCAMGCM_Tab4K; {gf_mul_h table } aad_cnt : TBit64; {processed AAD bytes } atx_cnt : TBit64; {authent. text bytes } y0_val : longint; {initial 32-bit ctr val} end; {$ifdef CONST} function CAM_GCM_Init(const Key; KeyBits: word; var ctx: TCAM_GCMContext): integer; {-Init context, calculate key-dependent GF(2^128) element H=E(K,0) and mul tables} {$ifdef DLL} stdcall; {$endif} {$else} function CAM_GCM_Init(var Key; KeyBits: word; var ctx: TCAM_GCMContext): integer; {-Init context, calculate key-dependent GF(2^128) element H=E(K,0) and gf_mul tables} {$endif} function CAM_GCM_Reset_IV(pIV: pointer; IV_len: word; var ctx: TCAM_GCMContext): integer; {-Reset: keep key but start new encryption with given IV} {$ifdef DLL} stdcall; {$endif} function CAM_GCM_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TCAM_GCMContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update auth data} {$ifdef DLL} stdcall; {$endif} function CAM_GCM_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TCAM_GCMContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode, update auth data} {$ifdef DLL} stdcall; {$endif} function CAM_GCM_Add_AAD(pAAD: pointer; aLen: longint; var ctx: TCAM_GCMContext): integer; {-Add additional authenticated data (will not be encrypted)} {$ifdef DLL} stdcall; {$endif} function CAM_GCM_Final(var tag: TCAMBlock; var ctx: TCAM_GCMContext): integer; {-Compute GCM tag from context} {$ifdef DLL} stdcall; {$endif} function CAM_GCM_Enc_Auth(var tag: TCAMBlock; {Tag record} {$ifdef CONST}const{$else}var{$endif} Key; KBits: word; {key and bitlength of key} pIV: pointer; IV_len: word; {IV: address / length} pAAD: pointer; aLen: word; {AAD: address / length} ptp: pointer; pLen: longint; {plaintext: address / length} ctp: pointer; {ciphertext: address} var ctx: TCAM_GCMContext {context, will be cleared} ): integer; {-All-in-one call to encrypt/authenticate} {$ifdef DLL} stdcall; {$endif} function CAM_GCM_Dec_Veri( ptag: pointer; tLen: word; {Tag: address / length (0..16)} {$ifdef CONST}const{$else}var{$endif} Key; KBits: word; {key and bitlength of key} pIV: pointer; IV_len: word; {IV: address / length} pAAD: pointer; aLen: word; {AAD: address / length} ctp: pointer; cLen: longint; {ciphertext: address / length} ptp: pointer; {plaintext: address} var ctx: TCAM_GCMContext {context, will be cleared} ): integer; {-All-in-one call to decrypt/verify. Decryption is done only if ptag^ is verified} {$ifdef DLL} stdcall; {$endif} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} {internal/testing} procedure gf_mul_h(var a: TCAMBlock; {$ifdef CONST}const{$else}var{$endif} ctx: TCAM_GCMContext); {-Multiply a by ctx.ghash_h in GF(2^128} procedure gf_mul(var a: TCAMBlock; {$ifdef CONST}const{$else}var{$endif} b: TCAMBlock); {-multiply two GF(2**128) field elements, a := a*b} implementation (* This implementation is based on Brian Gladman's source codes [2] which are --------------------------------------------------------------------------- Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. All rights reserved. LICENSE TERMS The redistribution and use of this software (with or without changes) is allowed without the payment of fees or royalties provided that: 1. source code distributions include the above copyright notice, this list of conditions and the following disclaimer; 2. binary distributions include the above copyright notice, this list of conditions and the following disclaimer in their documentation; 3. the name of the copyright holder is not used to endorse products built using this software without specific written permission. DISCLAIMER This software is provided 'as is' with no explicit or implied warranties in respect of its properties, including, but not limited to, correctness and/or fitness for purpose. --------------------------------------------------------------------------- *) {helper types} type TWA4 = packed array[0..3] of longint; {CAM block as array of longint} const CTR_POS = 12; BLK_MASK = CAMBLKSIZE-1; const gft_le: array[0..255] of word = ( {Table of 'carries' in mulx8 operation} $0000,$c201,$8403,$4602,$0807,$ca06,$8c04,$4e05,$100e,$d20f,$940d,$560c,$1809,$da08,$9c0a,$5e0b, $201c,$e21d,$a41f,$661e,$281b,$ea1a,$ac18,$6e19,$3012,$f213,$b411,$7610,$3815,$fa14,$bc16,$7e17, $4038,$8239,$c43b,$063a,$483f,$8a3e,$cc3c,$0e3d,$5036,$9237,$d435,$1634,$5831,$9a30,$dc32,$1e33, $6024,$a225,$e427,$2626,$6823,$aa22,$ec20,$2e21,$702a,$b22b,$f429,$3628,$782d,$ba2c,$fc2e,$3e2f, $8070,$4271,$0473,$c672,$8877,$4a76,$0c74,$ce75,$907e,$527f,$147d,$d67c,$9879,$5a78,$1c7a,$de7b, $a06c,$626d,$246f,$e66e,$a86b,$6a6a,$2c68,$ee69,$b062,$7263,$3461,$f660,$b865,$7a64,$3c66,$fe67, $c048,$0249,$444b,$864a,$c84f,$0a4e,$4c4c,$8e4d,$d046,$1247,$5445,$9644,$d841,$1a40,$5c42,$9e43, $e054,$2255,$6457,$a656,$e853,$2a52,$6c50,$ae51,$f05a,$325b,$7459,$b658,$f85d,$3a5c,$7c5e,$be5f, $00e1,$c2e0,$84e2,$46e3,$08e6,$cae7,$8ce5,$4ee4,$10ef,$d2ee,$94ec,$56ed,$18e8,$dae9,$9ceb,$5eea, $20fd,$e2fc,$a4fe,$66ff,$28fa,$eafb,$acf9,$6ef8,$30f3,$f2f2,$b4f0,$76f1,$38f4,$faf5,$bcf7,$7ef6, $40d9,$82d8,$c4da,$06db,$48de,$8adf,$ccdd,$0edc,$50d7,$92d6,$d4d4,$16d5,$58d0,$9ad1,$dcd3,$1ed2, $60c5,$a2c4,$e4c6,$26c7,$68c2,$aac3,$ecc1,$2ec0,$70cb,$b2ca,$f4c8,$36c9,$78cc,$bacd,$fccf,$3ece, $8091,$4290,$0492,$c693,$8896,$4a97,$0c95,$ce94,$909f,$529e,$149c,$d69d,$9898,$5a99,$1c9b,$de9a, $a08d,$628c,$248e,$e68f,$a88a,$6a8b,$2c89,$ee88,$b083,$7282,$3480,$f681,$b884,$7a85,$3c87,$fe86, $c0a9,$02a8,$44aa,$86ab,$c8ae,$0aaf,$4cad,$8eac,$d0a7,$12a6,$54a4,$96a5,$d8a0,$1aa1,$5ca3,$9ea2, $e0b5,$22b4,$64b6,$a6b7,$e8b2,$2ab3,$6cb1,$aeb0,$f0bb,$32ba,$74b8,$b6b9,$f8bc,$3abd,$7cbf,$bebe); {$ifndef BIT16} {32/64-bit code} {$ifdef BIT64} {---------------------------------------------------------------------------} function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif} {-reverse byte order in longint} begin RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24); end; {$else} {$ifdef CPUARM} {---------------------------------------------------------------------------} function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif} {-reverse byte order in longint} begin RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24); end; {$else} {---------------------------------------------------------------------------} function RB(A: longint): longint; assembler; {&frame-} {-reverse byte order in longint} asm {$ifdef LoadArgs} mov eax,[A] {$endif} xchg al,ah rol eax,16 xchg al,ah end; {$endif} {$endif} {$ifndef HAS_INT64} {---------------------------------------------------------------------------} procedure Inc64(var whi, wlo: longint; BLen: longint); {-Add BLen to 64 bit value (wlo, whi)} begin asm mov edx, wlo mov ecx, whi mov eax, Blen add [edx], eax adc dword ptr [ecx], 0 end; end; {$endif} {---------------------------------------------------------------------------} procedure mul_x(var a: TCAMBlock; const b: TCAMBlock); {-Multiply a = b*x in GF(2^128)} var t: longint; y: TWA4 absolute b; const MASK_80 = longint($80808080); MASK_7F = longint($7f7f7f7f); begin t := gft_le[(y[3] shr 17) and MASK_80]; TWA4(a)[3] := ((y[3] shr 1) and MASK_7F) or (((y[3] shl 15) or (y[2] shr 17)) and MASK_80); TWA4(a)[2] := ((y[2] shr 1) and MASK_7F) or (((y[2] shl 15) or (y[1] shr 17)) and MASK_80); TWA4(a)[1] := ((y[1] shr 1) and MASK_7F) or (((y[1] shl 15) or (y[0] shr 17)) and MASK_80); TWA4(a)[0] := (((y[0] shr 1) and MASK_7F) or ( (y[0] shl 15) and MASK_80)) xor t; end; {$else} {---------------------------------------------------------------------------} function RB(A: longint): longint; {-reverse byte order in longint} inline( $58/ { pop ax } $5A/ { pop dx } $86/$C6/ { xchg dh,al} $86/$E2); { xchg dl,ah} {---------------------------------------------------------------------------} procedure Inc64(var whi, wlo: longint; BLen: longint); {-Add BLen to 64 bit value (wlo, whi)} inline( $58/ {pop ax } $5A/ {pop dx } $5B/ {pop bx } $07/ {pop es } $26/$01/$07/ {add es:[bx],ax } $26/$11/$57/$02/ {adc es:[bx+02],dx} $5B/ {pop bx } $07/ {pop es } $26/$83/$17/$00/ {adc es:[bx],0 } $26/$83/$57/$02/$00);{adc es:[bx+02],0 } {---------------------------------------------------------------------------} procedure mul_x(var a: TCAMBlock; {$ifdef CONST}const{$else}var{$endif} b: TCAMBlock); {-Multiply a = b*x in GF(2^128)} var x: TWA4; t: longint; const hibit : array[0..1] of longint = (0, longint($80000000)); gf_poly: array[0..1] of longint = (0, longint($e1000000)); begin x[0] := RB(TWA4(b)[0]); x[1] := RB(TWA4(b)[1]); x[2] := RB(TWA4(b)[2]); x[3] := RB(TWA4(b)[3]); t := gf_poly[x[3] and 1]; x[3] := (x[3] shr 1) or hibit[x[2] and 1]; x[2] := (x[2] shr 1) or hibit[x[1] and 1]; x[1] := (x[1] shr 1) or hibit[x[0] and 1]; TWA4(a)[0] := RB((x[0] shr 1) xor t); TWA4(a)[1] := RB(x[1]); TWA4(a)[2] := RB(x[2]); TWA4(a)[3] := RB(x[3]); end; {$endif} {Note: At least on my machine inlining CAM_Xorblock in gf_mul is slower for} {32-bit Delphi! The conditional define can be adjusted on other machines,} {$ifdef DELPHI} {$undef inline_xorblock} {$else} {$define inline_xorblock} {$endif} {---------------------------------------------------------------------------} procedure gf_mul(var a: TCAMBlock; {$ifdef CONST}const{$else}var{$endif} b: TCAMBlock); {-multiply two GF(2**128) field elements, a := a*b} var p: array[0..7] of TCAMBlock; r: TCAMBlock; x: TWA4 absolute r; {$ifndef BIT16} t: longint; {$else} w: word; {$endif} {$ifdef inline_xorblock} j: integer; {$endif} i: integer; c: byte; begin p[0] := b; for i:=1 to 7 do mul_x(p[i], p[i-1]); fillchar(r,sizeof(r),0); for i:=0 to 15 do begin c := a[15-i]; if i>0 then begin {this is the inline code of the mul_x8 procedure} {$ifndef BIT16} t := gft_le[x[3] shr 24]; x[3] := ((x[3] shl 8) or (x[2] shr 24)); x[2] := ((x[2] shl 8) or (x[1] shr 24)); x[1] := ((x[1] shl 8) or (x[0] shr 24)); x[0] := ((x[0] shl 8) xor t); {$else} w := gft_le[r[15]]; r[15] := r[14]; r[14] := r[13]; r[13] := r[12]; r[12] := r[11]; r[11] := r[10]; r[10] := r[09]; r[09] := r[08]; r[08] := r[07]; r[07] := r[06]; r[06] := r[05]; r[05] := r[04]; r[04] := r[03]; r[03] := r[02]; r[02] := r[01]; r[01] := r[00] xor hi(w); r[00] := byte(w); {$endif} end; {$ifdef inline_xorblock} for j:=0 to 7 do begin if c and ($80 shr j) <> 0 then begin x[3] := x[3] xor TWA4(p[j])[3]; x[2] := x[2] xor TWA4(p[j])[2]; x[1] := x[1] xor TWA4(p[j])[1]; x[0] := x[0] xor TWA4(p[j])[0]; end; end; {$else} if c and $80 <> 0 then CAM_Xorblock(r,p[0],r); if c and $40 <> 0 then CAM_Xorblock(r,p[1],r); if c and $20 <> 0 then CAM_Xorblock(r,p[2],r); if c and $10 <> 0 then CAM_Xorblock(r,p[3],r); if c and $08 <> 0 then CAM_Xorblock(r,p[4],r); if c and $04 <> 0 then CAM_Xorblock(r,p[5],r); if c and $02 <> 0 then CAM_Xorblock(r,p[6],r); if c and $01 <> 0 then CAM_Xorblock(r,p[7],r); {$endif} end; a := r; end; {---------------------------------------------------------------------------} procedure Make4K_Table(var ctx: TCAM_GCMContext); {-Build 4K gf_mul table from ctx.ghash_h. Assumes gf_t4k is zero-filled} var j,k: integer; begin with ctx do begin gf_t4k[128] := ghash_h; j := 64; while j>0 do begin mul_x(gf_t4k[j], gf_t4k[j+j]); j := j shr 1; end; j := 2; while j<256 do begin for k:=1 to j-1 do CAM_Xorblock(gf_t4k[k], gf_t4k[j], gf_t4k[j+k]); j := j+j; end; end; end; {---------------------------------------------------------------------------} procedure gf_mul_h(var a: TCAMBlock; {$ifdef CONST}const{$else}var{$endif} ctx: TCAM_GCMContext); {-Multiply a by ctx.ghash_h in GF(2^128} var r: TCAMBlock; x: TWA4 absolute r; i: integer; t: longint; p: pointer; begin with ctx do begin r := gf_t4k[a[15]]; for i:=14 downto 0 do begin p := @gf_t4k[a[i]]; t := gft_le[x[3] shr 24]; {preform mul_x8 and xor in pre-computed table entries} {$ifndef BIT16} x[3] := ((x[3] shl 8) or (x[2] shr 24)) xor TWA4(p^)[3]; x[2] := ((x[2] shl 8) or (x[1] shr 24)) xor TWA4(p^)[2]; x[1] := ((x[1] shl 8) or (x[0] shr 24)) xor TWA4(p^)[1]; x[0] := ((x[0] shl 8) xor t) xor TWA4(p^)[0]; {$else} {$ifdef BASM16} asm les di, [p] db $66; mov bx, word ptr x[3*4] db $66; mov cx, word ptr x[2*4] db $66; mov dx, word ptr x[1*4] db $66; mov si, word ptr x[0] db $66; mov ax, cx db $66; shr ax, 24 db $66; shl bx, 8 db $66; or ax, bx db $66; xor ax, es:[di+12] db $66; mov word ptr x[3*4],ax db $66; mov ax, dx db $66; shr ax, 24 db $66; shl cx, 8 db $66; or ax, cx db $66; xor ax, es:[di+8] db $66; mov word ptr x[2*4],ax db $66; mov ax, si db $66; shr ax, 24 db $66; shl dx, 8 db $66; or ax, dx db $66; xor ax, es:[di+4] db $66; mov word ptr x[1*4],ax db $66; shl si, 8 db $66; xor si, word ptr t db $66; xor si, es:[di] db $66; mov word ptr x[0],si end; {$else} t := gft_le[r[15]]; r[15] := r[14]; r[14] := r[13]; r[13] := r[12]; r[12] := r[11]; r[11] := r[10]; r[10] := r[09]; r[09] := r[08]; r[08] := r[07]; r[07] := r[06]; r[06] := r[05]; r[05] := r[04]; r[04] := r[03]; r[03] := r[02]; r[02] := r[01]; r[01] := r[00] xor TBA4(t)[1]; r[00] := byte(t); x[3] := x[3] xor TWA4(p^)[3]; x[2] := x[2] xor TWA4(p^)[2]; x[1] := x[1] xor TWA4(p^)[1]; x[0] := x[0] xor TWA4(p^)[0]; {$endif} {$endif} end; a := r; end; end; (* {Use this for table-less versions} {---------------------------------------------------------------------------} procedure gf_mul_h(var a: TCAMBlock; {$ifdef CONST}const{$else}var{$endif} ctx: TCAM_GCMContext); {-Multiply a by ctx.ghash_h in GF(2^128} begin {Simply compute a*ghash_h, pre-computing the p-array for ghash_h} {does not hurt, but does not give significant speed improvments.} gf_mul(a, ctx.ghash_h); end; *) {---------------------------------------------------------------------------} function CAM_GCM_Init({$ifdef CONST}const{$else}var{$endif} Key; KeyBits: word; var ctx: TCAM_GCMContext): integer; {-Init context, calculate key-dependent GF(2^128) element H=E(K,0) and gf_mul tables} var err: integer; begin fillchar(ctx, sizeof(ctx), 0); with ctx do begin err := CAM_Init(Key, KeyBits, actx); if err=0 then begin CAM_Encrypt(actx, ghash_h, ghash_h); Make4K_Table(ctx); end; end; CAM_GCM_Init := err; end; {---------------------------------------------------------------------------} procedure GCM_IncCtr(var x: TCAMBlock); {-GCM IncProc, only 32 LSB bits are changed (big-endian notation)} var j: integer; begin for j:=15 downto CTR_POS do begin if x[j]=$FF then x[j] := 0 else begin inc(x[j]); exit; end; end; end; {---------------------------------------------------------------------------} function CAM_GCM_Reset_IV(pIV: pointer; IV_len: word; var ctx: TCAM_GCMContext): integer; {-Reset: keep key but start new encryption with given IV} var n_pos: longint; i: integer; begin CAM_GCM_Reset_IV := 0; if (pIV=nil) and (IV_Len<>0) then begin CAM_GCM_Reset_IV := CAM_Err_NIL_Pointer; exit; end; with ctx do begin {compute initial IV counter value Y0} if IV_len=CTR_POS then begin {if bitlen(IV)=96 then Y0=IV||1} move(pIV^, actx.IV, CTR_POS); TWA4(actx.IV)[3] := $01000000; {big-endian 32-bit 1} end else begin {Y0 = GHASH(IV, H)} n_pos := IV_len; fillchar(actx.IV, sizeof(actx.IV),0); while n_pos >= CAMBLKSIZE do begin CAM_Xorblock(actx.IV, PCAMBlock(pIV)^, actx.IV); inc(Ptr2Inc(pIV), CAMBLKSIZE); dec(n_pos, CAMBLKSIZE); gf_mul_h(actx.IV, ctx); end; if n_pos>0 then begin for i:=0 to n_pos-1 do begin actx.IV[i] := actx.IV[i] xor pByte(pIV)^; inc(Ptr2Inc(pIV)); end; gf_mul_h(actx.IV, ctx); end; n_pos := longint(IV_len) shl 3; i := 15; while n_pos>0 do begin actx.IV[i] := actx.IV[i] xor byte(n_pos); n_pos := n_pos shr 8; dec(i); end; gf_mul_h(actx.IV, ctx); end; {save initial 32-bit ctr val for final operation} y0_val := TWA4(actx.IV)[3]; {Reset other data} fillchar(aad_ghv, sizeof(aad_ghv),0); fillchar(txt_ghv, sizeof(txt_ghv),0); actx.Flag := 0; actx.bLen := 0; aad_cnt[0] := 0; aad_cnt[1] := 0; atx_cnt[0] := 0; atx_cnt[1] := 0; end; end; {---------------------------------------------------------------------------} function CAM_GCM_Final(var tag: TCAMBlock; var ctx: TCAM_GCMContext): integer; {-Compute GCM tag from context} var tbuf: TCAMBlock; x: TWA4 absolute tbuf; {$ifdef HAS_INT64} ln: int64; {$else} ln: TBit64; {$endif} begin with ctx do begin if actx.Flag and $02 <> 0 then begin CAM_GCM_Final := CAM_Err_GCM_Auth_After_Final; exit; end; actx.Flag := actx.Flag or $02; {compute GHASH(H, AAD, ctp)} gf_mul_h(aad_ghv, ctx); gf_mul_h(txt_ghv, ctx); {Compute len(AAD) || len(ctp) with each len as 64-bit big-endian } {Note: Tag calculation with Brian Gladman's original code will be} {incorrect if either of the following shifts produces carries: } {(ctx->txt_acnt << 3) or (ctx->hdr_cnt << 3)} {$ifdef HAS_INT64} {Gladman's code with 64-bit counters} ln := (int64(atx_cnt) + CAMBLKSIZE - 1) div CAMBLKSIZE; if (int64(aad_cnt)>0) and (ln<>0) then begin tbuf := ghash_h; while ln<>0 do begin if odd(ln) then gf_mul(aad_ghv, tbuf); ln := ln shr 1; if ln<>0 then gf_mul(tbuf, tbuf); end; end; {$else} {equivalent code for compilers without int64} ln[0] := atx_cnt[0]; ln[1] := atx_cnt[1]; Inc64(ln[1], ln[0], CAMBLKSIZE - 1); ln[0] := (ln[0] shr 4) or ((ln[1] and $F) shl 28); ln[1] := ln[1] shr 4; if (aad_cnt[0] or aad_cnt[1] <> 0) and (ln[0] or ln[1] <> 0) then begin tbuf := ghash_h; while (ln[0] or ln[1])<>0 do begin if odd(ln[0]) then gf_mul(aad_ghv, tbuf); ln[0] := ln[0] shr 1; if odd(ln[1]) then ln[0] := ln[0] or longint($80000000); ln[1] := ln[1] shr 1; if ln[0] or ln[1] <> 0 then gf_mul(tbuf, tbuf); end; end; {$endif} x[0] := RB((aad_cnt[0] shr 29) or (aad_cnt[1] shl 3)); x[1] := RB((aad_cnt[0] shl 3)); x[2] := RB((atx_cnt[0] shr 29) or (atx_cnt[1] shl 3)); x[3] := RB((atx_cnt[0] shl 3)); CAM_Xorblock(tbuf, txt_ghv, tbuf); CAM_Xorblock(aad_ghv, tbuf, aad_ghv); gf_mul_h(aad_ghv, ctx); {compute E(K,Y0)} tbuf := actx.IV; x[3] := y0_val; CAM_Encrypt(actx, tbuf, tbuf); {tag = GHASH(H, AAD, ctp) xor E(K,Y0)} CAM_Xorblock(aad_ghv, tbuf, tag); end; CAM_GCM_Final := 0; end; {---------------------------------------------------------------------------} function crypt_data(ptp, ctp: Pointer; ILen: longint; var ctx: TCAM_GCMContext): integer; {-Internal: en/decrypt ILen byte from ptp to ctp} var cnt: longint; b_pos: integer; begin crypt_data := 0; if ILen<=0 then exit; cnt := 0; with ctx do begin b_pos := actx.bLen; if b_pos=0 then b_pos := CAMBLKSIZE else begin while (cnt < ILen) and (b_pos < CAMBLKSIZE) do begin pByte(ctp)^ := pByte(ptp)^ xor actx.buf[b_pos]; inc(b_pos); inc(Ptr2Inc(ptp)); inc(Ptr2Inc(ctp)); inc(cnt); end; end; while cnt + CAMBLKSIZE <= ILen do begin GCM_IncCtr(actx.IV); CAM_Encrypt(actx, actx.IV, actx.buf); CAM_XorBlock(PCAMBlock(ptp)^, actx.buf, PCAMBlock(ctp)^); inc(Ptr2Inc(ptp), CAMBLKSIZE); inc(Ptr2Inc(ctp), CAMBLKSIZE); inc(cnt, CAMBLKSIZE); end; while cnt < ILen do begin if b_pos=CAMBLKSIZE then begin GCM_IncCtr(actx.IV); CAM_Encrypt(actx, actx.IV, actx.buf); b_pos := 0; end; pByte(ctp)^ := actx.buf[b_pos] xor pByte(ptp)^; inc(b_pos); inc(Ptr2Inc(ptp)); inc(Ptr2Inc(ctp)); inc(cnt); end; actx.bLen := (actx.bLen + cnt) and BLK_MASK;; end; end; {---------------------------------------------------------------------------} function auth_data(ctp: pointer; ILen: longint; var ctx: TCAM_GCMContext): integer; {-Internal: add ILen bytes from cipher text to auth ghash} var cnt: longint; b_pos: integer; begin auth_data := 0; if ILen<=0 then exit; cnt := 0; with ctx do begin if actx.Flag and $02 <> 0 then begin auth_data := CAM_Err_GCM_Auth_After_Final; exit; end; b_pos := atx_cnt[0] and BLK_MASK; if (b_pos=0) and (atx_cnt[0] or atx_cnt[1] <> 0) then gf_mul_h(txt_ghv, ctx); while (cnt < ILen) and (b_pos < CAMBLKSIZE) do begin txt_ghv[b_pos] := txt_ghv[b_pos] xor pByte(ctp)^; inc(b_pos); inc(Ptr2Inc(ctp)); inc(cnt); end; while cnt + CAMBLKSIZE <= ILen do begin gf_mul_h(txt_ghv, ctx); CAM_Xorblock(txt_ghv, PCAMBlock(ctp)^, txt_ghv); inc(Ptr2Inc(ctp), CAMBLKSIZE); inc(cnt, CAMBLKSIZE); end; while cnt < ILen do begin if b_pos=CAMBLKSIZE then begin gf_mul_h(txt_ghv, ctx); b_pos := 0; end; txt_ghv[b_pos] := txt_ghv[b_pos] xor pByte(ctp)^; inc(b_pos); inc(Ptr2Inc(ctp)); inc(cnt); end; {$ifdef HAS_INT64} Inc(int64(atx_cnt), cnt); {$else} Inc64(atx_cnt[1], atx_cnt[0],cnt); {$endif} end; end; {---------------------------------------------------------------------------} function CAM_GCM_Add_AAD(pAAD: pointer; aLen: longint; var ctx: TCAM_GCMContext): integer; {-Add additional authenticated data (will not be encrypted)} var cnt: longint; b_pos: integer; begin CAM_GCM_Add_AAD := 0; if aLen <= 0 then exit; if pAAD=nil then begin CAM_GCM_Add_AAD := CAM_Err_NIL_Pointer; exit; end; {$ifdef BIT16} if (aLen>$FFFF) or (ofs(pAAD^)+aLen>$FFFF) then begin CAM_GCM_Add_AAD := CAM_Err_Invalid_16Bit_Length; exit; end; {$endif} cnt := 0; with ctx do begin if actx.Flag and $02 <> 0 then begin CAM_GCM_Add_AAD := CAM_Err_GCM_Auth_After_Final; exit; end; b_pos := aad_cnt[0] and BLK_MASK; if (b_pos=0) and (aad_cnt[0] or aad_cnt[1] <> 0) then gf_mul_h(aad_ghv, ctx); while (cnt < aLen) and (b_pos < CAMBLKSIZE) do begin aad_ghv[b_pos] := aad_ghv[b_pos] xor pByte(pAAD)^; inc(b_pos); inc(Ptr2Inc(pAAD)); inc(cnt); end; while cnt + CAMBLKSIZE <= aLen do begin gf_mul_h(aad_ghv, ctx); CAM_Xorblock(aad_ghv, PCAMBlock(pAAD)^, aad_ghv); inc(Ptr2Inc(pAAD), CAMBLKSIZE); inc(cnt, CAMBLKSIZE); end; while cnt < aLen do begin if b_pos=CAMBLKSIZE then begin gf_mul_h(aad_ghv, ctx); b_pos := 0; end; aad_ghv[b_pos] := aad_ghv[b_pos] xor pByte(pAAD)^; inc(b_pos); inc(Ptr2Inc(pAAD)); inc(cnt); end; {$ifdef HAS_INT64} Inc(int64(aad_cnt),cnt); {$else} Inc64(aad_cnt[1],aad_cnt[0],cnt); {$endif} end; end; {---------------------------------------------------------------------------} function CAM_GCM_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TCAM_GCMContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update auth data} var err: integer; begin if ILen <= 0 then begin CAM_GCM_Encrypt := 0; exit; end; if (ptp=nil) or (ctp=nil) then begin CAM_GCM_Encrypt := CAM_Err_NIL_Pointer; exit; end; {$ifdef BIT16} if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin CAM_GCM_Encrypt := CAM_Err_Invalid_16Bit_Length; exit; end; {$endif} err := crypt_data(ptp, ctp, ILen, ctx); if err=0 then err := auth_data(ctp, ILen, ctx); CAM_GCM_Encrypt := err; end; {---------------------------------------------------------------------------} function CAM_GCM_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TCAM_GCMContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode, update auth data} var err: integer; begin if ILen <= 0 then begin CAM_GCM_Decrypt := 0; exit; end; if (ptp=nil) or (ctp=nil) then begin CAM_GCM_Decrypt := CAM_Err_NIL_Pointer; exit; end; {$ifdef BIT16} if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin CAM_GCM_Decrypt := CAM_Err_Invalid_16Bit_Length; exit; end; {$endif} err := auth_data(ctp, ILen, ctx); if err=0 then err := crypt_data(ctp, ptp, ILen, ctx); CAM_GCM_Decrypt := err; end; {---------------------------------------------------------------------------} function Internal_Dec_Veri(var ctx: TCAM_GCMContext; ptag: pointer; tLen: word; ctp: pointer; cLen: longint; ptp: pointer): integer; {-calculate and verify tLen bytes of ptag^, decrypt if OK} var err,i: integer; diff: byte; tag: TCAMBlock; begin if cLen <= 0 then cLen := 0; if cLen>0 then begin if (ptp=nil) or (ctp=nil) then begin Internal_Dec_Veri := CAM_Err_NIL_Pointer; exit; end; {$ifdef BIT16} if (ofs(ptp^)+cLen>$FFFF) or (ofs(ctp^)+cLen>$FFFF) then begin Internal_Dec_Veri := CAM_Err_Invalid_16Bit_Length; exit; end; {$endif} end; err := auth_data(ctp, cLen, ctx); if err=0 then begin {Compute/verify tag before doing decryption} err := CAM_GCM_Final(tag, ctx); if err=0 then begin diff :=0; for i:=0 to pred(tLen) do begin diff := diff or (pByte(ptag)^ xor tag[i]); inc(Ptr2Inc(ptag)); end; err := (((integer(diff)-1) shr 8) and 1)-1; {0 compare, -1 otherwise} err := err and CAM_Err_GCM_Verify_Tag; end; if err=0 then err := crypt_data(ctp, ptp, cLen, ctx); end; Internal_Dec_Veri := err; end; {---------------------------------------------------------------------------} function CAM_GCM_Enc_Auth(var tag: TCAMBlock; {Tag record} {$ifdef CONST}const{$else}var{$endif} Key; KBits: word; {key and bitlength of key} pIV: pointer; IV_len: word; {IV: address / length} pAAD: pointer; aLen: word; {AAD: address / length} ptp: pointer; pLen: longint; {plaintext: address / length} ctp: pointer; {ciphertext: address} var ctx: TCAM_GCMContext {context, will be cleared} ): integer; {-All-in-one call to encrypt/authenticate} var err: integer; begin err := CAM_GCM_Init(Key, KBits, ctx); if err=0 then err := CAM_GCM_Reset_IV(pIV, IV_len, ctx); if err=0 then err := CAM_GCM_Add_AAD(pAAD, aLen, ctx); if err=0 then err := CAM_GCM_Encrypt(ptp, ctp, pLen, ctx); if err=0 then err := CAM_GCM_Final(tag, ctx); fillchar(ctx, sizeof(ctx), 0); CAM_GCM_Enc_Auth := err; end; {---------------------------------------------------------------------------} function CAM_GCM_Dec_Veri( ptag: pointer; tLen: word; {Tag: address / length (0..16)} {$ifdef CONST}const{$else}var{$endif} Key; KBits: word; {key and bitlength of key} pIV: pointer; IV_len: word; {IV: address / length} pAAD: pointer; aLen: word; {AAD: address / length} ctp: pointer; cLen: longint; {ciphertext: address / length} ptp: pointer; {plaintext: address} var ctx: TCAM_GCMContext {context, will be cleared} ): integer; {-All-in-one call to decrypt/verify. Decryption is done only if ptag^ is verified} var err: integer; begin err := CAM_GCM_Init(Key, KBits, ctx); if err=0 then err := CAM_GCM_Reset_IV(pIV, IV_len, ctx); if err=0 then err := CAM_GCM_Add_AAD(pAAD, aLen, ctx); if err=0 then err := Internal_Dec_Veri(ctx,ptag,tLen,ctp,cLen,ptp); fillchar(ctx, sizeof(ctx), 0); CAM_GCM_Dec_Veri := err; end; end.
unit UPlayerEx; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ImgList, ToolWin, ExtCtrls, StrUtils, CommCtrl, Tracker2, Menus; const WM_PLAYNOTIFY = WM_USER + 1; type TPlayerState = (psClosed, psPlaying, psEndOfPlay, psStopped, psPaused); TFPlay = class(TForm) tlbBar: TToolBar; btnPlay: TToolButton; btnFastPlay: TToolButton; btnPause: TToolButton; btnRewind: TToolButton; btnBkFrame: TToolButton; btnGoFrame: TToolButton; pnlPlayWnd: TPanel; btnSep1: TToolButton; btnStop: TToolButton; btnSep5: TToolButton; btnSep2: TToolButton; btnSearch: TToolButton; btnSep: TToolButton; btnOpen: TToolButton; btn1: TToolButton; btnCapture: TToolButton; btnAbout: TToolButton; btnHelp: TToolButton; btnAudio: TToolButton; btnLoop: TToolButton; btn2: TToolButton; dlgOpen: TOpenDialog; ilImList: TImageList; btnLang: TToolButton; pnlStat: TPanel; lblLength: TLabel; lbl1: TLabel; lblPos: TLabel; ilDisabled: TImageList; btnSpeed: TToolButton; pmSpeed: TPopupMenu; N1001: TMenuItem; N2001: TMenuItem; N4001: TMenuItem; N8001: TMenuItem; procedure btnStopClick(Sender: TObject); procedure btnPauseClick(Sender: TObject); procedure btnOpenClick(Sender: TObject); procedure btnPlayClick(Sender: TObject); procedure btnFastPlayClick(Sender: TObject); procedure btnBkFrameClick(Sender: TObject); procedure btnRewindClick(Sender: TObject); procedure btnSearchClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnGoFrameClick(Sender: TObject); procedure btnCaptureClick(Sender: TObject); procedure btnLoopClick(Sender: TObject); procedure btnAudioClick(Sender: TObject); procedure btnSettClick(Sender: TObject); procedure btnAboutClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure btnLangClick(Sender: TObject); procedure TrackBarPositionChanged(Sender: TObject); procedure FormCreate(Sender: TObject); procedure N1001Click(Sender: TObject); private FPlayerState: TPlayerState; Port: Word; Speed: DWORD; TimeLength: DWORD; // TimePlayed : DWORD; PlayedFile: string; FilesPath: string; TrackBar: TTrackBar2; LastPos: Integer; InNotify: boolean; // OldPosition : Integer; procedure SetPlayerState(const Value: TPlayerState); procedure DoGrayScale; protected property PlayerState: TPlayerState read FPlayerState write SetPlayerState; procedure WMPLAYNOTIFY(var Message: TMessage); message WM_PLAYNOTIFY; public procedure LangChanged; procedure OpenFile(FileName: string); procedure Check(Res: integer; Msg: string); end; var FPlay: TFPlay; implementation uses HH5Player, HHReadWriter, RegIni, USearch; {$R *.dfm} procedure TFPlay.btnStopClick(Sender: TObject); begin if PlayerState in [psClosed, psStopped, psPaused] then Exit; Check(HH5PLAYER_Stop(Port), 'Can"t stop file'); PlayerState := psStopped; end; procedure TFPlay.btnPauseClick(Sender: TObject); begin if PlayerState in [psClosed, psStopped, psPaused] then Exit; Check(HH5PLAYER_Pause(Port), 'Can"t pause file'); PlayerState := psPaused; end; procedure TFPlay.btnOpenClick(Sender: TObject); begin with dlgOpen do begin InitialDir := FilesPath; if Execute then OpenFile(FileName); end; end; procedure TFPlay.btnPlayClick(Sender: TObject); begin if (PlayedFile <> '') and (PlayerState = psClosed) then begin OpenFile(PlayedFile); Exit; end; if PlayerState in [psClosed, psPlaying] then Exit; if PlayerState = psStopped then Check(HH5PLAYER_Play(Port), 'Can"t play file') else Check(HH5PLAYER_Resume(Port), 'Can"t resume file'); PlayerState := psPlaying; end; procedure TFPlay.btnFastPlayClick(Sender: TObject); begin if PlayerState in [psClosed] then Exit; Check(HH5PLAYER_FastPlay(Port, Speed), 'Can"t fastplay file'); end; procedure TFPlay.btnBkFrameClick(Sender: TObject); begin if PlayerState in [psClosed, psPlaying] then Exit; Check(HH5PLAYER_FrameBack(Port), 'Can"t FrameBack file'); end; procedure TFPlay.btnRewindClick(Sender: TObject); begin if PlayerState in [psClosed] then Exit; Check(HH5PLAYER_FastPlayBack(Port, Speed), 'Can"t fastplay file'); end; procedure TFPlay.Check(Res: integer; Msg: string); begin if Res <> 0 then begin MessageDlg(Msg + ',error : ' + IntToStr(Res), mtError, [mbOK], 0); Abort; end; end; procedure TFPlay.btnSearchClick(Sender: TObject); var FileName: string; P: TPoint; begin P := tlbBar.ClientToScreen(Point(btnSearch.Left - FSearch.Width div 2, btnSearch.Top - FSearch.Height)); FileName := Search(FilesPath, P); if FileName <> '' then OpenFile(FileName); end; procedure TFPlay.OpenFile(FileName: string); var P: PChar; I: Integer; begin if CompareText(FilesPath, Copy(FileName, 1, Length(FilesPath))) <> 0 then begin I := Pos('\General\', FileName); if I <> 0 then FilesPath := ExtractFilePath(Copy(FileName, 1, I - 1)); end; PlayedFile := FileName; P := StrAlloc(Length(FileName) + 1); try StrPCopy(P, FileName); Check(HH5PLAYER_OpenStreamFileM(Port, @P, 1, TimeLength), 'Can"t open file'); HH5PLAYER_RegPlayStatusMsg(Port, Handle, WM_PLAYNOTIFY); finally StrDispose(P); end; Check(HH5PLAYER_Play(Port), 'Can"t play file'); PlayerState := psPlaying; Check(HH5PLAYER_SetAudio(Port, btnAudio.Down), 'Can"t set audo'); Check(HH5PLAYER_SetPlayLoop(Port, btnLoop.Down), 'Can"t set loop'); lblLength.Caption := FormatDateTime('HH:nn:ss', TimeLength / SecsPerDay); end; procedure TFPlay.LangChanged; begin btnPlay.Hint := ifthen(LangEn, 'Play', 'Воспроизведение'); btnFastPlay.Hint := ifthen(LangEn, 'Fast play', 'Быстрое Воспроизведение'); btnPause.Hint := ifthen(LangEn, 'Pause', 'Пауза'); btnRewind.Hint := ifthen(LangEn, 'Rewind', 'Перемотка'); btnBkFrame.Hint := ifthen(LangEn, 'Back frame', 'Назад кадр'); btnGoFrame.Hint := ifthen(LangEn, 'Forw frame', 'Вперед кадр'); btnStop.Hint := ifthen(LangEn, 'Stop', 'Остановить'); btnSearch.Hint := ifthen(LangEn, 'Search', 'Поиск'); btnOpen.Hint := ifthen(LangEn, 'Open file', 'Открыть файл'); btnCapture.Hint := ifthen(LangEn, 'Capture frame', 'Сохранить кадр'); btnAbout.Hint := ifthen(LangEn, 'About', 'О программе'); btnHelp.Hint := ifthen(LangEn, 'Help', 'Помощь'); btnAudio.Hint := ifthen(LangEn, 'Audio', 'Звук'); btnLoop.Hint := ifthen(LangEn, 'Loop', 'АвтоПовтор'); btnSpeed.Hint := ifthen(LangEn, 'Rewind speed', 'Скорость перемотки'); btnLang.Hint := 'English/Русский'; end; procedure TFPlay.FormShow(Sender: TObject); begin PlayerState := psClosed; FilesPath := ReadString('Common', 'FilesPath', 'C:\XDVfiles'); LangEn := ReadBool('Common', 'LangEn', True); Speed := ReadInteger('Common', 'RewindSpeed', 100); btnAudio.Down := ReadBool('Common', 'Audio', True); btnLoop.Down := ReadBool('Common', 'Loop', False); LangChanged; Port := 0; Check(HH5PLAYER_InitSDK(pnlPlayWnd.Handle), 'HH5PLAYER_InitSDK'); Check(HH5PLAYER_InitPlayer(Port, pnlPlayWnd.Handle), 'HH5PLAYER_InitPlayer'); end; procedure TFPlay.FormDestroy(Sender: TObject); begin HH5PLAYER_ReleasePlayer(Port); HH5PLAYER_ReleaseSDK; TrackBar.Free; end; procedure TFPlay.WMPLAYNOTIFY(var Message: TMessage); begin if Message.WParam = Port then begin if DWORD(Message.LParam) = $FFFFFFFF then // lParam PlayTime, $FFFFFFFF : end of play begin Message.LParam := 0; if not btnLoop.Down then PlayerState := psEndOfPlay; end; { if (DWORD(LParam) > EndTime then LParam := 0; } LastPos := (Message.LParam * 100) div Integer(TimeLength); InNotify := True; TrackBar.PositionL := LastPos; InNotify := False; end else if Message.WParam = 301 then begin end; Message.Result := 1; end; procedure TFPlay.btnGoFrameClick(Sender: TObject); begin if PlayerState in [psClosed, psPlaying] then Exit; Check(HH5PLAYER_FrameGO(Port), 'Can"t GoFrame file'); end; procedure TFPlay.btnCaptureClick(Sender: TObject); var bmp: Pointer; Size: Integer; T: TSystemTime; FBmp: string; H: THandle; begin if PlayerState in [psClosed] then Exit; Check(HH5PLAYER_CaptureOnePicture(Port, @bmp, size), 'CaptureOnePicture'); GetSystemTime(T); FBmp := FilesPath + 'picture'; ForceDirectories(FBmp); FBmp := FBmp + '\' + Format('%04d_%02d_%02d_%02d_%02d_%02d.bmp', [t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond]); H := FileCreate(FBmp); if H = INVALID_HANDLE_VALUE then Check(GetLastError, 'Can"t create picture file') else begin FileWrite(H, bmp^, size); FileClose(H); end; end; procedure TFPlay.btnLoopClick(Sender: TObject); begin Check(HH5PLAYER_SetPlayLoop(Port, btnLoop.Down), 'Can"t set audo'); WriteBool('Common', 'Loop', btnLoop.Down); end; procedure TFPlay.btnAudioClick(Sender: TObject); begin Check(HH5PLAYER_SetAudio(Port, btnAudio.Down), 'Can"t set audo'); WriteBool('Common', 'Audio', btnAudio.Down); end; procedure TFPlay.btnSettClick(Sender: TObject); begin ; end; function ConvertBitmapToGrayscale(const Bitmap: TBitmap): TBitmap; var I, J: Integer; Grayshade, Red, Green, Blue: Byte; PixelColor: Longint; begin with Bitmap do for I := 0 to Width - 1 do for J := 0 to Height - 1 do begin PixelColor := ColorToRGB(Canvas.Pixels[I, J]); Red := PixelColor; Green := PixelColor shr 8; Blue := PixelColor shr 16; Grayshade := Round(0.3 * Red + 0.6 * Green + 0.1 * Blue); Canvas.Pixels[I, J] := RGB(Grayshade, Grayshade, Grayshade); end; Result := Bitmap; end; procedure TFPlay.DoGrayScale; var BMP: TBitmap; I: Integer; begin BMP := TBitmap.Create; try for I := 0 to ilImList.Count - 3 do begin ilImList.GetBitmap(I, BMP); BMP := ConvertBitmapToGrayscale(BMP); BMP.Transparent := True; ilDisabled.AddMasked(BMP, clWhite); end; finally BMP.Free; end; end; procedure TFPlay.btnAboutClick(Sender: TObject); begin ; end; procedure TFPlay.btnHelpClick(Sender: TObject); begin ; end; procedure TFPlay.SetPlayerState(const Value: TPlayerState); begin FPlayerState := Value; btnPlay.Enabled := (FPlayerState in [psStopped, psPaused, psEndOfPlay]); btnFastPlay.Enabled := FPlayerState in [psStopped, psPaused]; btnPause.Enabled := FPlayerState in [psPlaying]; btnRewind.Enabled := FPlayerState in [psStopped, psPaused, psPlaying]; btnBkFrame.Enabled := FPlayerState in [psStopped, psPaused]; btnGoFrame.Enabled := FPlayerState in [psStopped, psPaused]; btnStop.Enabled := FPlayerState in [psPlaying]; // btnOpen.Enabled := FPlayerState in []; btnCapture.Enabled := FPlayerState in [psStopped, psPaused, psPlaying]; end; procedure TFPlay.btnLangClick(Sender: TObject); begin LangEn := not LangEn; if LangEn then btnLang.ImageIndex := 14 else btnLang.ImageIndex := 15; WriteBool('Common', 'LangEn', LangEn); LangChanged; end; procedure TFPlay.TrackBarPositionChanged(Sender: TObject); var Secs: Integer; begin Secs := MulDiv(TTrackBar2(Sender).PositionL, TimeLength, 100); lblPos.Caption := FormatDateTime('HH:nn:ss', Secs / SecsPerDay); if not InNotify then begin Check(HH5PLAYER_Pause(Port), 'Can"t pause file'); PlayerState := psPaused; Check(HH5PLAYER_SeekToSecond(Port, Secs), 'HH5PLAYER_SeekToSecond'); Check(HH5PLAYER_Resume(Port), 'Can"t resume file'); PlayerState := psPlaying; end; end; procedure TFPlay.FormCreate(Sender: TObject); begin TrackBar := TTrackBar2.Create(Self); with TrackBar do begin Parent := Self; SecondThumb := False; Orientation := toHorizontal; OnChange := TrackBarPositionChanged; ThumbStyle := tsMediumPointer; TickStyle := tiUserDrawn; TickSize := 0; Height := 22; Color := $00F4D8BD; Align := alBottom; Max := 100; end; DoGrayScale; end; procedure TFPlay.N1001Click(Sender: TObject); begin Speed := StrToInt(TMenuItem(Sender).Caption); WriteInteger('Common', 'RewindSpeed', Speed); end; end.
unit UDaoCompra; interface uses uDao, DB, SysUtils, Messages, UCompra, UDaoFornecedor, UDaoProduto, UDaoCondicaoPagamento, UDaoFuncionario, UDaoTransportadora, UDaoContasPagar, UContasPagar, UDaoUsuario, UDaoCfop, Dialogs; type DaoCompra = class(Dao) private protected umCompra : Compra; umaDaoFornecedor : DaoFornecedor; umaDaoProduto : DaoProduto; umaDaoCondicaoPagamento : DaoCondicaoPagamento; umaDaoFuncionario : DaoFuncionario; umaDaoUsuario : DaoUsuario; umaDaoTransportadora : DaoTransportadora; umaDaoContasPagar : DaoContasPagar; umaContaPagar : ContasPagar; umaDaoCfop : DaoCfop; public Constructor CrieObjeto; Destructor Destrua_se; function Salvar(obj:TObject): string; override; function GetDS : TDataSource; override; function Carrega(obj:TObject): TObject; override; function Buscar(obj : TObject) : Boolean; override; function Excluir(obj : TObject) : string ; override; function VerificarNota (obj : TObject) : Boolean; function VerificarProduto (obj : TObject) : Boolean; procedure AtualizaGrid; procedure Ordena(campo: string); end; implementation { DaoCompra } function DaoCompra.Buscar(obj: TObject): Boolean; var prim: Boolean; sql, e, onde: string; umaCompra: Compra; begin e := ' and '; onde := ' where'; prim := true; umaCompra := Compra(obj); sql := 'select * from compra c'; if umaCompra.getUmFornecedor.getNome_RazaoSoCial <> '' then begin //Buscar a descricao do fornecedor na tabela fornecedor sql := sql+' INNER JOIN fornecedor f ON c.idfornecedor = f.idfornecedor and f.nome_razaosocial like '+quotedstr('%'+umaCompra.getUmFornecedor.getNome_RazaoSoCial+'%'); if (prim) and (umaCompra.getStatus <> '')then begin prim := false; sql := sql+onde; end end; if umaCompra.getStatus <> '' then begin if prim then begin prim := false; sql := sql+onde; end; sql := sql+' c.status like '+quotedstr('%'+umaCompra.getStatus+'%'); //COLOCA CONDIÇAO NO SQL end; if (DateToStr(umaCompra.getDataEmissao) <> '30/12/1899') and (datetostr(umaCompra.getDataCompra) <> '30/12/1899') then begin if prim then begin prim := false; sql := sql+onde; end else sql := sql+e; sql := sql+' c.dataemissao between '+QuotedStr(DateToStr(umaCompra.getDataEmissao))+' and '+QuotedStr(DateToStr(umaCompra.getDataCompra)); end; with umDM do begin QCompra.Close; QCompra.sql.Text := sql+' order by numnota'; QCompra.Open; if QCompra.RecordCount > 0 then result := True else result := false; end; end; function DaoCompra.VerificarNota(obj: TObject): Boolean; var sql: string; umaCompra: Compra; begin umaCompra := Compra(obj); sql := 'select * from compra where numnota = '+IntToStr(umaCompra.getNumNota)+' and serienota = '''+umaCompra.getSerieNota+ ''' and idfornecedor = '+IntToStr(umaCompra.getUmFornecedor.getId)+' and status = '''+umaCompra.getStatus+'''' ; with umDM do begin QCompra.Close; QCompra.sql.Text := sql+' order by idcompra'; QCompra.Open; if QCompra.RecordCount > 0 then result := True else result := false; QCompra.Refresh; end; end; function DaoCompra.VerificarProduto (obj : TObject) : Boolean; var sql: string; umaCompra: Compra; begin umaCompra := Compra(obj); sql := 'select * from compra_produto where idproduto = '+IntToStr(umaCompra.getumProdutoCompra.getId); with umDM do begin QProdutoCompra.Close; QProdutoCompra.sql.Text := sql+' order by idcompra'; QProdutoCompra.Open; if QProdutoCompra.RecordCount > 0 then result := True else result := false; end; end; procedure DaoCompra.AtualizaGrid; begin with umDM do begin QCompra.Close; QCompra.sql.Text := 'select * from compra order by idcompra, numnota'; QCompra.Open; end; end; function DaoCompra.Carrega(obj: TObject): TObject; var umaCompra: Compra; begin umaCompra := Compra(obj); with umDM do begin if not QCompra.Active then QCompra.Open; umaCompra.setIdCompra(QCompraidcompra.AsInteger); umaCompra.setNumNota(QCompranumnota.AsInteger); umaCompra.setSerieNota(QCompraserienota.AsString); umaCompra.setBaseICMS(QComprabase_icms.AsFloat); umaCompra.setTotalICMS(QCompratotal_icms.AsFloat); umaCompra.setValorFrete(QCompravalor_frete.AsFloat); umaCompra.setValorDesconto(QCompravalor_desconto.AsFloat); umaCompra.setTotalIPI(QCompratotal_ipi.AsFloat); umaCompra.setTotalProduto(QCompratotal_produto.AsFloat); umaCompra.setTotalNota(QCompratotal_nota.AsFloat); umaCompra.setObservacao(QCompraobservacao.AsString); umaCompra.setStatus(QComprastatus.AsString); umaCompra.setTipoFrete(QCompratipofrete.AsInteger); umaCompra.setDataEmissao(QCompradataemissao.AsDateTime); umaCompra.setDataCompra(QCompradatacompra.AsDateTime); umaCompra.setDataCadastro(QCompradatacadastro.AsDateTime); umaCompra.setDataAlteracao(QCompradataalteracao.AsDateTime); // Busca o Fornecedor referente a Compra umaCompra.getUmFornecedor.setId(QCompraidfornecedor.AsInteger); umaDaoFornecedor.Carrega(umaCompra.getumFornecedor); //Busca Funcioanrio referente a Compra umaCompra.getUmUsuario.setIdUsuario(QCompraidusuario.AsInteger); umaDaoUsuario.Carrega(umaCompra.getUmUsuario); //Busca Transportadora referente a Compra if (QCompraidtransportadora.AsInteger <> 0) then begin umaCompra.getUmaTransportadora.setId(QCompraidtransportadora.AsInteger); umaDaoFornecedor.Carrega(umaCompra.getUmaTransportadora); end; //Busca Condicao de Pagamento referente a Compra umaCompra.getUmaCondicaoPagamento.setId(QCompraidcondicaopagamento.AsInteger); umaDaoCondicaoPagamento.Carrega(umaCompra.getUmaCondicaoPagamento); //Carregar os Produtos QProdutoCompra.Close; QProdutoCompra.SQL.Text := 'select * from produto_compra where idcompra = '+ IntToStr(umaCompra.getIdCompra)+' and numnota = '+IntToStr(umaCompra.getNumNota)+' and serienota = '''+umaCompra.getSerieNota+ ''' and idfornecedor = '+IntToStr(umaCompra.getUmFornecedor.getId); QProdutoCompra.Open; QProdutoCompra.First; if umaCompra.CountProdutos <> 0 then umaCompra.LimparListaProduto; //Limpar a lista caso a lista vim com itens carregados if umaCompra.CountParcelas <> 0 then umaCompra.LimparListaParcelas; //Limpar a lista caso a lista vim com itens carregados while not QProdutoCompra.Eof do begin UmaCompra.CrieObejtoProduto; umaCompra.addProdutoCompra(umaCompra.getUmProdutoCompra); UmaCompra.getUmProdutoCompra.setId(QProdutoCompraidproduto.AsInteger); umaDaoProduto.Carrega(UmaCompra.getUmProdutoCompra); //Buscar Descricao do Produto UmaCompra.getUmProdutoCompra.setNCMSH(QProdutoComprancm_sh.AsString); UmaCompra.getUmProdutoCompra.setCSTCompra(QProdutoCompracst.AsString); //Busca CFOP referente a Compra umaCompra.getumProdutoCompra.getUmCfop.setId(QProdutoCompraidcfop.AsInteger); umaDaoCfop.Carrega(umaCompra.getumProdutoCompra.getUmCfop); UmaCompra.getUmProdutoCompra.setUnidadeCompra(QProdutoCompraunidade.AsString); UmaCompra.getUmProdutoCompra.setQuantidadeCompra(StrToFloat(FormatFloat('#0.000', QProdutoCompraquantidade.AsFloat))); UmaCompra.getUmProdutoCompra.setValorUnitarioCompra(StrToFloat(FormatFloat('#0.0000', QProdutoCompraprecocusto.AsFloat))); UmaCompra.getUmProdutoCompra.setDescontoCompra(StrToFloat(FormatFloat('#0.0000', QProdutoCompradesconto.AsFloat))); UmaCompra.getUmProdutoCompra.setValorTotalCompra(StrToFloat(FormatFloat('#0.0000', QProdutoCompravalortotal.AsFloat))); UmaCompra.getUmProdutoCompra.setBaseIcmsCompra(StrToFloat(FormatFloat('#0.0000', QProdutoComprabaseicms.AsFloat))); UmaCompra.getUmProdutoCompra.setValorIcmsCompra(StrToFloat(FormatFloat('#0.0000', QProdutoCompravaloricms.AsFloat))); UmaCompra.getUmProdutoCompra.setValorIpiCompra(StrToFloat(FormatFloat('#0.0000', QProdutoCompravaloripi.AsFloat))); UmaCompra.getUmProdutoCompra.setICMSCompra(StrToFloat(FormatFloat('#0.0000', QProdutoCompraicms.AsFloat))); UmaCompra.getUmProdutoCompra.setIPICompra(StrToFloat(FormatFloat('#0.0000', QProdutoCompraipi.AsFloat))); QProdutoCompra.Next; end; end; Self.AtualizaGrid; result := umaCompra; end; constructor DaoCompra.CrieObjeto; begin inherited; umaDaoFornecedor := DaoFornecedor.CrieObjeto; umaDaoProduto := DaoProduto.CrieObjeto; umaDaoCondicaoPagamento := DaoCondicaoPagamento.CrieObjeto; umaDaoFuncionario := DaoFuncionario.CrieObjeto; umaDaoUsuario := DaoUsuario.CrieObjeto; umaDaoTransportadora := DaoTransportadora.CrieObjeto; umaDaoContasPagar := DaoContasPagar.CrieObjeto; umaContaPagar := ContasPagar.CrieObjeto; umaDaoCfop := DaoCfop.CrieObjeto; end; destructor DaoCompra.Destrua_se; begin inherited; end; function DaoCompra.Excluir(obj: TObject): string; begin end; function DaoCompra.GetDS: TDataSource; begin umDM.QCompra.FieldByName('numnota').DisplayLabel := 'NN'; umDM.QCompra.FieldByName('serienota').DisplayLabel := 'SN'; umDM.QCompra.FieldByName('numnota').DisplayWidth := 5; umDM.QCompra.FieldByName('serienota').DisplayWidth := 5; umDM.QCompra.FieldByName('idcompra').Visible := False; (umDM.QCompra.FieldByName('base_icms') as TFloatField).DisplayFormat := '0.00'; (umDM.QCompra.FieldByName('valor_frete') as TFloatField).DisplayFormat := '0.00'; (umDM.QCompra.FieldByName('total_icms') as TFloatField).DisplayFormat := '0.00'; (umDM.QCompra.FieldByName('total_ipi') as TFloatField).DisplayFormat := '0.00'; (umDM.QCompra.FieldByName('valor_desconto') as TFloatField).DisplayFormat := '0.00'; (umDM.QCompra.FieldByName('total_produto') as TFloatField).DisplayFormat := '0.00'; (umDM.QCompra.FieldByName('total_nota') as TFloatField).DisplayFormat := '0.00'; result := umDM.DSCompra; end; procedure DaoCompra.Ordena(campo: string); begin umDM.QCompra.IndexFieldNames := campo; end; function DaoCompra.Salvar(obj: TObject): string; var umaCompra : Compra; i : Integer; cancelar : Boolean; CP_Status : string; valor, numNotaAux, quantidade : Real; begin umaCompra := Compra(obj); with umDM do begin try beginTrans; QCompra.Close; //Buscar a Conta a Pagar umaContaPagar.setNumNota(umaCompra.getNumNota); umaContaPagar.setSerieNota(umaCompra.getSerieNota); umaContaPagar.getUmFornecedor.setId(umaCompra.getUmFornecedor.getId); umaContaPagar.setStatus('PAGA'); if umaCompra.getStatus = 'FINALIZADA' then begin umaContaPagar.setStatus(''); if (umaDaoContasPagar.VerificarContas(umaContaPagar)) then begin umaContaPagar.setStatus('CANCELADA'); if (not umaDaoContasPagar.VerificarContas(umaContaPagar)) then begin result := 'Esse Número, Série e Fornecedor da Nota já foram cadastrados no Contas a Pagar!'; Self.AtualizaGrid; Exit; end; end; QCompra.SQL := UpdateCompra.InsertSQL end else begin if (umaDaoContasPagar.VerificarContas(umaContaPagar)) then begin result := 'Essa Compra não pode ser Cancelada pois 1 ou mais das parcelas ja foram pagas!'; Self.AtualizaGrid; Exit; end; QCompra.SQL := UpdateCompra.ModifySQL; QCompra.Params.ParamByName('OLD_numnota').Value := umaCompra.getNumNota; QCompra.Params.ParamByName('OLD_serienota').Value := umaCompra.getSerieNota; QCompra.Params.ParamByName('OLD_idfornecedor').Value := umaCompra.getUmFornecedor.getId; end; QCompra.Params.ParamByName('numnota').Value := umaCompra.getNumNota; QCompra.Params.ParamByName('serienota').Value := umaCompra.getSerieNota; QCompra.Params.ParamByName('idfornecedor').Value := umaCompra.getUmFornecedor.getId; QCompra.Params.ParamByName('idusuario').Value := umaCompra.getUmUsuario.getIdUsuario; QCompra.Params.ParamByName('idcondicaopagamento').Value := umaCompra.getUmaCondicaoPagamento.getId; if (umaCompra.getUmaTransportadora.getId <> 0) then QCompra.Params.ParamByName('idtransportadora').Value := umaCompra.getUmaTransportadora.getId; QCompra.Params.ParamByName('tipofrete').Value := umaCompra.getTipoFrete; QCompra.Params.ParamByName('base_icms').Value := umaCompra.getBaseICMS; QCompra.Params.ParamByName('valor_frete').Value := umaCompra.getValorFrete; QCompra.Params.ParamByName('total_icms').Value := umaCompra.getTotalICMS; QCompra.Params.ParamByName('total_ipi').Value := umaCompra.getTotalIPI; QCompra.Params.ParamByName('valor_desconto').Value := umaCompra.getValorDesconto; QCompra.Params.ParamByName('total_produto').Value := umaCompra.getTotalProduto; QCompra.Params.ParamByName('total_nota').Value := umaCompra.getTotalNota; QCompra.Params.ParamByName('status').Value := umaCompra.getStatus; QCompra.Params.ParamByName('observacao').Value := umaCompra.getObservacao; QCompra.Params.ParamByName('dataemissao').Value := umaCompra.getDataEmissao; QCompra.Params.ParamByName('datacompra').Value := umaCompra.getDataCompra; QCompra.Params.ParamByName('datacadastro').Value := umaCompra.getDataCadastro; QCompra.Params.ParamByName('dataalteracao').Value := umaCompra.getDataAlteracao; QCompra.ExecSQL; if umaCompra.getIdCompra = 0 then begin QGenerica.Close; QGenerica.SQL.Text := 'Select last_value as idcompra from compra_idcompra_seq'; QGenerica.Open; umaCompra.setIdCompra(QGenerica.Fields.FieldByName('idcompra').Value); end; numNotaAux := QProdutoCompranumnota.AsInteger; //Recupera o numNota da tabela relacional //Faz Relacao com os Itens da Compra for i := 1 to umaCompra.CountProdutos do begin if umaCompra.getStatus = 'FINALIZADA' then begin QProdutoCompra.SQL := UpdateProdutoCompra.InsertSQL; cancelar := False; end else begin QProdutoCompra.SQL := UpdateProdutoCompra.ModifySQL; cancelar := True; end; QProdutoCompra.Params.ParamByName('idcompra').Value := umaCompra.getIdCompra; QProdutoCompra.Params.ParamByName('numnota').Value := umaCompra.getNumNota; QProdutoCompra.Params.ParamByName('serienota').Value := umaCompra.getSerieNota; QProdutoCompra.Params.ParamByName('idfornecedor').Value := umaCompra.getUmFornecedor.getId; QProdutoCompra.Params.ParamByName('idproduto').Value := umaCompra.getProdutoCompra(i-1).getId; QProdutoCompra.Params.ParamByName('ncm_sh').Value := umaCompra.getProdutoCompra(i-1).getNCMSH; QProdutoCompra.Params.ParamByName('cst').Value := umaCompra.getProdutoCompra(i-1).getCSTCompra; QProdutoCompra.Params.ParamByName('idcfop').Value := umaCompra.getProdutoCompra(i-1).getUmCfop.getId; QProdutoCompra.Params.ParamByName('unidade').Value := umaCompra.getProdutoCompra(i-1).getUnidadeCompra; QProdutoCompra.Params.ParamByName('quantidade').Value := umaCompra.getProdutoCompra(i-1).getQuantidadeCompra; QProdutoCompra.Params.ParamByName('precocusto').Value := umaCompra.getProdutoCompra(i-1).getValorUnitarioCompra; QProdutoCompra.Params.ParamByName('desconto').Value := umaCompra.getProdutoCompra(i-1).getDescontoCompra; QProdutoCompra.Params.ParamByName('valortotal').Value := umaCompra.getProdutoCompra(i-1).getValorTotalCompra; QProdutoCompra.Params.ParamByName('baseicms').Value := umaCompra.getProdutoCompra(i-1).getBaseIcmsCompra; QProdutoCompra.Params.ParamByName('valoricms').Value := umaCompra.getProdutoCompra(i-1).getValorIcmsCompra; QProdutoCompra.Params.ParamByName('valoripi').Value := umaCompra.getProdutoCompra(i-1).getValorIpiCompra; QProdutoCompra.Params.ParamByName('icms').Value := umaCompra.getProdutoCompra(i-1).getICMSCompra; QProdutoCompra.Params.ParamByName('ipi').Value := umaCompra.getProdutoCompra(i-1).getIPICompra; quantidade := umaCompra.getProdutoCompra(i-1).getQuantidade; if (cancelar) then begin //Diminui o estoque do produto correspondente umaCompra.getProdutoCompra(i-1).setQuantidade( quantidade - umaCompra.getProdutoCompra(i-1).getQuantidadeCompra); if(umaCompra.getProdutoCompra(i-1).getQuantidade = 0) then begin umaCompra.getProdutoCompra(i-1).setICMS(0); umaCompra.getProdutoCompra(i-1).setIPI(0); umaCompra.getProdutoCompra(i-1).setPrecoCompra(0); umaCompra.getProdutoCompra(i-1).setICMSAnterior(0); umaCompra.getProdutoCompra(i-1).setIPIAnterior(0); umaCompra.getProdutoCompra(i-1).setPrecoCompraAnt(0); end else begin umaCompra.getProdutoCompra(i-1).setICMS(umaCompra.getProdutoCompra(i-1).getICMSAnterior); umaCompra.getProdutoCompra(i-1).setIPI(umaCompra.getProdutoCompra(i-1).getIPIAnterior); umaCompra.getProdutoCompra(i-1).getPrecoCompra; end; end else begin //Aumenta o estoque do produto correspondente umaCompra.getProdutoCompra(i-1).setQuantidade( quantidade + umaCompra.getProdutoCompra(i-1).getQuantidadeCompra); umaCompra.getProdutoCompra(i-1).setICMS(umaCompra.getProdutoCompra(i-1).getICMSCompra); umaCompra.getProdutoCompra(i-1).setIPI(umaCompra.getProdutoCompra(i-1).getIPICompra); umaCompra.getProdutoCompra(i-1).getPrecoCompra; end; umaDaoProduto.Salvar(umaCompra.getProdutoCompra(i-1)); QProdutoCompra.ExecSQL; end; //Gerar as Contas a Pagar if (umaCompra.getTipo = True) then for i := 1 to umaCompra.CountParcelas do begin if (umaCompra.getStatus <> 'FINALIZADA') and (not umaDaoContasPagar.VerificarContas(umaContaPagar)) then begin QContasPagar.SQL := UpdateContasPagar.ModifySQL; QContasPagar.Params.ParamByName('OLD_numnota').Value := umaCompra.getNumNota; QContasPagar.Params.ParamByName('OLD_serienota').Value := umaCompra.getSerieNota; QContasPagar.Params.ParamByName('OLD_idfornecedor').Value := umaCompra.getUmFornecedor.getId; QContasPagar.Params.ParamByName('OLD_numparcela').Value := umaCompra.getParcelas(i-1).getNumParcela; CP_Status := 'CANCELADA'; end else begin QContasPagar.SQL := UpdateContasPagar.InsertSQL; CP_Status := 'PENDENTE'; end; QContasPagar.Params.ParamByName('idcompra').Value := umaCompra.getIdCompra; QContasPagar.Params.ParamByName('numnota').Value := umaCompra.getNumNota; QContasPagar.Params.ParamByName('serienota').Value := umaCompra.getSerieNota; QContasPagar.Params.ParamByName('numparcela').Value := umaCompra.getParcelas(i-1).getNumParcela; QContasPagar.Params.ParamByName('datavencimento').Value := DateToStr(Date + (umaCompra.getParcelas(i-1).getDias)); valor := StrToFloat(FormatFloat('#0.00',(umaCompra.getParcelas(i-1).getPorcentagem/100) * umaCompra.getTotalNota)); QContasPagar.Params.ParamByName('valor').Value := valor; QContasPagar.Params.ParamByName('dataemissao').Value := DateToStr(Date); QContasPagar.Params.ParamByName('status').Value := CP_Status; QContasPagar.Params.ParamByName('idfornecedor').Value := umaCompra.getUmFornecedor.getId; QContasPagar.Params.ParamByName('idusuario').Value := umaCompra.getUmUsuario.getIdUsuario; QContasPagar.Params.ParamByName('idformapagamento').Value := umaCompra.getUmaCondicaoPagamento.getUmaFormaPagamento.getId; QContasPagar.ExecSQL; end; Commit; if umaCompra.getStatus = 'CANCELADA' then result := 'Compra Cancelada com sucesso!' else result := 'Compra salva com sucesso!'; except on e: Exception do begin rollback; if umaCompra.getStatus = 'CANCELADA' then Result := 'Ocorreu um erro! Compra não foi cancelada. Erro: '+e.Message else Result := 'Ocorreu um erro! Compra não foi salva. Erro: '+e.Message; end; end; end; Self.AtualizaGrid; end; end.
{Заpяд в электpической цепи описывается уpавнением: / | y``+cos(y``)-(x*x+y)-ky`+sin(y`)=0 < y(0)=1 | y(1)=0.5 \ где k - наименьший положительный коpень уpавнения 2x-sin(x)-1.2=0 Пpоинтеpполиpовать по Hьютону y(x), взяв значения y(x) в точках x=0, 0.2, 0.4,0.6,0.8,1. Сpавнить значения полученного многочлена и y(x) во всех точках, где было вычислено y(x). Pезультат гpафически вывести на экpан. Составить пpогpамму, вычисляющую силу тока для любого момента вpемени x из интеpвала [0, 1]. Пpовести вычисления пpи x=0.05, 0.1, 0.15, 0.2,...,1 Указание: Сила тока I=dq/dt. Диффеpенциальное уpавнение pешить методом Pунге-Кутта четвертого поpядка с точностью 0.0001. Для вычисления пpоизводной взять шаг 0.05} uses crt,graph; Type typeY=array[1..2] of real; const eps=0.0001; y_0=1; y_1=0.5; rastx=300; rasty=300; Var kkk,endH,kf:real; k,i,gm,gd:integer; uzels:array[1..6,1..6] of real;{Для сост. таблицы кон. разностей} function difura(x,y,y1,y11:real):real; begin difura:=y11+cos(y11)-(x*x+y)-k*y1+sin(y1); end; Function poiskK:real; {------------------------} function k1(x:real): real; begin k1:=2*x-sin(x)-1.2; end; {------------------------} {**************************} function MPD(a,b:real):real; var c:real; begin c:=(a+b)/2; while abs((b-a)/2)>eps/1000 do begin if (k1(a)*k1(c)<0) then b:=c else a:=c; c:=(a+b)/2; end; MPD:=c; end; {**************************} Var a,b,step,ax,bx:real; begin a:=0; b:=1; step:=1; while (b<4) do begin b:=b*2; step:=step/2; ax:=a; bx:=a+step; while bx<b do begin if ((k1(ax)*k1(bx))<0) then kf:=MPD(ax,bx); ax:=ax+step; bx:=bx+step; end; end; end; procedure poiskInt(var a:real;var b:real;x,y,y1:real); var c,d,h,fa,fb:real; i:integer; begin c:=-10; d:=10; h:=1; a:=c; b:=a+h; fa:=1; fb:=1; while fa*fb>0 do begin a:=c; b:=a+h; fa:=difura(x,y,y1,a); fb:=difura(x,y,y1,b); while b<d do begin a:=b; b:=b+h; fa:=fb; fb:=difura(x,y,y1,b); if fa*fb<0 then break; end; c:=c-1; d:=d+1; h:=h/2; end; end; procedure MHord(x,y,y1:real; var kr:real); var fa,fb,fc,c,cp,a,b:real; begin poiskInt(a,b,x,y,y1); fa:=difura(x,y,y1,a); fb:=difura(x,y,y1,b); c:=0; cp:=(fb*a-fa*b)/(fb-fa); while (abs(cp-c)>eps) do begin c:=cp; fc:=difura(x,y,y1,c); if fa*fc<0 then begin b:=c; fb:=fc; end else begin a:=c; fa:=fc; end; cp:=(fb*a-fa*b)/(fb-fa); end; kr:=cp; end; {Возвращает значение y`` c подставленными параметрами} function dif(x:double; y:real; y1:real):real; var a,b,kk:real; begin MHord(x,y,y1,kk); dif:=kk; end; function Runge_Kutt(xi:real; var Y:TypeY; h:real):real; var K:array[1..4,1..2] of real; rrr:typeY; begin k[1,1]:=y[2]; k[1,2]:=dif(xi,y[1],y[2]); k[2,1]:=y[2]+(h/2)*k[1,2]; k[2,2]:=dif(xi+h/2,y[1]+(h/2)*k[1,1],y[2]+(h/2)*k[1,2]); k[3,1]:=y[2]+(h/2)*k[2,2]; k[3,2]:=dif(xi+h/2,y[1]+(h/2)*k[2,1],y[2]+(h/2)*k[2,2]); k[4,1]:=y[2]+h*k[3,2]; k[4,2]:=dif(xi+h,y[1]+h*k[3,1],y[2]+h*k[3,2]); y[1]:=y[1]+(h/6)*(k[1,1]+2*k[2,1]+2*k[3,1]+k[4,1]); y[2]:=y[2]+(h/6)*(k[1,2]+2*k[2,2]+2*k[3,2]+k[4,2]); end; procedure DoublePer(var Yb:typeY; kr:real); var hh, xi:double; Yh,Yh_2:TypeY; i: integer; begin hh:=0.05; xi:=0; yh[1]:=y_0; yh[2]:=kr; yh_2:=yh; While (xi<1) do begin Runge_Kutt(xi,Yh,hh); Runge_Kutt(xi,Yh_2,hh/2); Runge_Kutt(xi+hh/2,Yh_2,hh/2); if (abs(Yh[1]-Yh_2[1])>15*eps) then begin hh:=hh/2; xi:=0; yh[1]:=y_0; yh[2]:=kr; yh_2:=yh; end else xi:=xi+hh; end; endH:=hh/2; yb:=yh_2; writeln(' y(1)=', yh_2[1]:10:10,' y`(1)= ',yh_2[2]:10:10); end; procedure strelba; var a,b,c,t:real; ya,yb,yc:TypeY; Begin a:=-3; b:=3; DoublePer(ya,a); DoublePer(yb,b); repeat c:=((yb[1]-y_1)*a-(ya[1]-y_1)*b)/(yb[1]-ya[1]); DoublePer(yc,c); if ((ya[1]-y_1)*(yc[1]-y_1))<0 then begin b:=c; yb:=yc; end else begin a:=c; ya:=yc; end; until (abs(y_1-yc[1])<eps); kkk:=c; writeln('y`(0) = ',kkk:1:8); end; procedure zapoln_tabl; var i,j:integer; begin for i:=2 to 6 do for j:=6-i+1 downto 1 do uzels[j,i]:=uzels[j+1,i-1]-uzels[j,i-1]; end; procedure print; var i,j:integer; begin for i:=1 to 6 do begin for j:=1 to 6 do write(uzels[i,j]:10:4); writeln; end; end; function nuton(x:real; h:real):real; var i,j:integer; fak:longint; q,qq,p:real; begin fak:=1; q:=(x)/h; qq:=q; p:=uzels[1,1]; for i:=2 to 6 do begin p:=p+(uzels[1,i]*qq)/fak; qq:=qq*(q-i+1); fak:=fak*i; end; nuton:=p; end; procedure graphik; var i:real; j,gm,gd,ox,oy:integer; yy:Typey; begin gm:=0; gd:=0; initgraph(gm,gd,'c:\tp\bgi'); cleardevice; settextstyle(7,0,3); outtextxy(170,150,'Гpафик функции найденой из ДУ'); setcolor(red); outtextxy(170,200,'График интерполирующей функции'); ox:=20; {Прорисовка осей координат} oy:=470; { } uzels[1,1]:=y_0; j:=1; yy[1]:=y_0; yy[2]:=kkk; setcolor(white); line(ox,0,ox,480); line(0,oy,640,oy); i:=0; moveto(round(i*rastx)+ox,oy-round(y_0*rasty)); while i<=1 do begin Runge_Kutt(i,yy,endh); i:=i+endh; lineto(round(i*rastx)+ox,oy-round(yy[1]*rasty)); if round(i*1000)=round(200*j) then begin uzels[j+1,1]:=yy[1]; inc(j); end; end; readkey; zapoln_tabl; setcolor(red); i:=0; moveto(round(i*rastx)+ox,oy-round(nuton(i,0.2)*rasty)); while i< 1.1 do begin i:=i+endh; lineto(round(i*rastx)+ox,oy-round(nuton(i,0.2)*rasty)); end; setcolor(white); for j:=0 to 5 do circle(round((j/5)*rastx)+ox,oy-round(uzels[j+1,1]*rasty),3); readkey; closegraph; end; procedure vivodSilaToka; var x: real; i:byte; begin clrscr; writeln('Сила тока в моменты времени'); writeln('==========================='); x:=0.0; while x<1.05 do begin writeln('Сила тока(',x:1:2,')= ',Nuton(x,0.2):10:10); x:=x+0.05; end; end; {Вывод на экран значений финкции производной и Ньютона в точках} {из интервала [0,1] c шагом 0.05} procedure vivod; var i:integer; yy:typeY; x:real; begin clrscr; x:=0; yy[1]:=y_0; yy[2]:=kkk; i:=1; writeln('y(',x:2:2,')= ',yy[1]:13:10,' ','y`(',x:2:2,')= ',yy[2]:13:10,' ','nuton(',x:2:2,')= ',nuton(x,0.05):13:10); while x<=1 do begin Runge_Kutt(x,yy,endh); x:=x+endh; if round(x*1000000)=round(50000*i) then {округление} begin writeln('y(',x:2:2,')= ',yy[1]:13:10,' ','y`(',x:2:2,')= ', yy[2]:13:10,' ','nuton(',x:2:2,')= ',nuton(x,0.2):13:10); inc(i); end; end; readkey; end; begin clrscr; writeln; writeln(' Идет процесс метода стрельб...'); strelba; writeln('Жми Enter...'); readkey; graphik; clrscr; writeln('Таблица конечных разностей :'); print; readkey; vivod; vivodSilaToka; readkey; end. Comments: Решение дифферинциального уравнения начинается с краевой задачи. Известно: Значение функции в точке 0 и в точке 1, хотя для решения диф. уравнения нам необходимо значение первой производной в точке 0. Для того, чтобы ее найти, используется метод стрельб. В качестве метода стрельб будем использовать например метод половинного деления. Нужно подобрать такую первую производную в точке 0, чтобы при ее подстановке в диф. уравнение функция в точке 1 была равна 0.5. Что и делает метод стрельб. Метод стрельб подставляет первую производную в точке 0 в DoublePer который возвращает значение функции и значение производной в точке 1 и сравнивает с 0.5 т.е с начальными условиями. Двойной пересчет считает значение функции и значение производной с шагом h и h/2 от 0 до 1 и сравнивается по точности. Считая значения в точках, двойной пересчет вызывает метод Runge_Kutt и запоминает конечный шаг в котором достигается точность. Метод Рунге-Кутта выдает y и y` в точке x+h с подставленными параметрами x, y, y`. Метод Рунге-Кутта использует значение второй производной, которое выдает Difura, но вторая производная задана не явно. Поэтому функция Difura решает методом хорд уравнение, где неизвестной является вторая производная. В итоге найдено значение производной в точке 0 то которое нужно. Подставляя это значение, то есть начальные параметры, в Runge_Kutt получается значение функции в различных точках. Для нахождения силы тока в точках просто возводится в квадрат значение функции в этих точках.
unit FC.Trade.Trader.MACross2_15m; {$I Compiler.inc} interface uses Classes, Math,Graphics, Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions, StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators, Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage; type //Пока здесь объявлен. Потом как устоится, вынести в Definitions IStockTraderMACross2_15m = interface ['{EC889CBD-A75E-4ECE-A5DF-0630E8CE38C7}'] end; TStockTraderMACross2_15m = class (TStockTraderBase,IStockTraderMACross2_15m) private FBarHeightD1 : ISCIndicatorBarHeight; FFastMA_M15,FSlowMA_M15: ISCIndicatorMA; //FLWMA21_M15,FLWMA55_M15: ISCIndicatorMA; //FMA84_M15,FMA220_M15: ISCIndicatorMA; FLastOpenOrderTime : TDateTime; FPropFullBarsOnly : TPropertyYesNo; protected function CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight; function CreateMA_M15(const aChart: IStockChart; aPeriod: integer; aMethod: TSCIndicatorMAMethod): ISCIndicatorMA; //Считает, на какой примерно цене сработает Stop Loss или Trailing Stop function GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber; //Считает, какой убыток будет, если закроется по StopLoss или Trailing Stop function GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber; procedure CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string); procedure CloseAllOrders(aKind: TSCOrderKind;const aComment: string); function GetRecommendedLots: TStockOrderLots; override; procedure SetTP(const aOrder: IStockOrder; const aTP: TStockRealNumber; const aComment: string); function GetMainTrend(index: integer): TSCRealNumber; function GetFastTrend(index: integer): TSCRealNumber; function GetCross(index: integer): integer; function PriceToPoint(const aPrice: TSCRealNumber): integer; public procedure SetProject(const aValue : IStockProject); override; procedure OnBeginWorkSession; override; //Посчитать procedure UpdateStep2(const aTime: TDateTime); override; function OpenMASnappedOrder(aKind: TStockOrderKind;const aMALevel:TSCRealNumber; const aComment: string=''): IStockOrder; constructor Create; override; destructor Destroy; override; procedure Dispose; override; end; implementation uses DateUtils,Variants,Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message, StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory, FC.DataUtils; { TStockTraderMACross2_15m } procedure TStockTraderMACross2_15m.CloseAllOrders(aKind: TSCOrderKind;const aComment: string); var i: Integer; aOrders : IStockOrderCollection; begin aOrders:=GetOrders; for i := aOrders.Count- 1 downto 0 do begin if (aOrders[i].GetKind=aKind) then if aOrders[i].GetState=osOpened then CloseOrder(aOrders[i],aComment) else if aOrders[i].GetState=osPending then aOrders[i].RevokePending; end; end; procedure TStockTraderMACross2_15m.CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string); var i: Integer; aOrders : IStockOrderCollection; begin aOrders:=GetOrders; for i := aOrders.Count- 1 downto 0 do begin if (aOrders[i].GetKind=aKind) and (aOrders[i].GetCurrentProfit>0) then CloseOrder(aOrders[i],aComment); end; end; constructor TStockTraderMACross2_15m.Create; begin inherited Create; FPropFullBarsOnly := TPropertyYesNo.Create('Method','Full Bars Only',self); FPropFullBarsOnly.Value:=true; RegisterProperties([FPropFullBarsOnly]); //UnRegisterProperties([PropLotDefaultRateSize,PropLotDynamicRate]); end; function TStockTraderMACross2_15m.CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight; var aCreated: boolean; begin result:=CreateOrFindIndicator(aChart,ISCIndicatorBarHeight,'BarHeightD1',true, aCreated) as ISCIndicatorBarHeight; //Ничего не нашли, создадим нового эксперта if aCreated then begin Result.SetPeriod(3); Result.SetBarHeight(bhHighLow); end; end; function TStockTraderMACross2_15m.CreateMA_M15(const aChart: IStockChart;aPeriod: integer; aMethod: TSCIndicatorMAMethod): ISCIndicatorMA; var aCreated: boolean; begin result:=CreateOrFindIndicator(aChart,ISCIndicatorMA,'MA'+IntToStr(integer(aMethod))+'_'+IntToStr(aPeriod)+'_M15',true, aCreated) as ISCIndicatorMA; //Ничего не нашли, создадим нового эксперта if aCreated then begin Result.SetMAMethod(aMethod); Result.SetPeriod(aPeriod); end; end; destructor TStockTraderMACross2_15m.Destroy; begin inherited; end; procedure TStockTraderMACross2_15m.Dispose; begin inherited; end; function TStockTraderMACross2_15m.GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber; begin result:=aOrder.GetStopLoss; if aOrder.GetState=osOpened then if aOrder.GetKind=okBuy then result:=max(result,aOrder.GetBestPrice-aOrder.GetTrailingStop) else result:=min(result,aOrder.GetBestPrice+aOrder.GetTrailingStop); end; function TStockTraderMACross2_15m.GetFastTrend(index: integer): TSCRealNumber; begin result:=0;//FLWMA21_M15.GetValue(index)-FLWMA55_M15.GetValue(index); end; function TStockTraderMACross2_15m.GetRecommendedLots: TStockOrderLots; var aDayVolatility,aDayVolatilityM,k: TStockRealNumber; begin if not PropLotDynamicRate.Value then exit(inherited GetRecommendedLots); aDayVolatility:=FBarHeightD1.GetValue(FBarHeightD1.GetInputData.Count-1); //Считаем какая волатильность в деньгах у нас была последние дни aDayVolatilityM:=GetBroker.PriceToMoney(GetSymbol,aDayVolatility,1); //Считаем, сколько таких волатильностей вынесет наш баланс k:=(GetBroker.GetEquity/aDayVolatilityM); //Теперь берем допустимый процент result:=RoundTo(k*PropLotDynamicRateSize.Value/100,-2); end; function TStockTraderMACross2_15m.GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber; begin if aOrder.GetKind=okBuy then result:=aOrder.GetOpenPrice-GetExpectedStopLossPrice(aOrder) else result:=GetExpectedStopLossPrice(aOrder) - aOrder.GetOpenPrice; end; procedure TStockTraderMACross2_15m.SetProject(const aValue: IStockProject); begin if GetProject=aValue then exit; inherited; if aValue <> nil then begin //Создае нужных нам экспертов FBarHeightD1:=CreateBarHeightD1(aValue.GetStockChart(sti1440)); FFastMA_M15:= CreateMA_M15(aValue.GetStockChart(sti15),21*4,mamSimple); FSlowMA_M15:= CreateMA_M15(aValue.GetStockChart(sti15),40*4,mamSimple); // FLWMA21_M15:= CreateMA_M15(aValue.GetStockChart(sti15),21,mamLinearWeighted); // FLWMA55_M15:= CreateMA_M15(aValue.GetStockChart(sti15),55,mamLinearWeighted); // FMA84_M15:= CreateMA_M15(aValue.GetStockChart(sti15),84,mamSimple); //FMA220_M15:= CreateMA_M15(aValue.GetStockChart(sti15),220,mamSimple); end; end; procedure TStockTraderMACross2_15m.SetTP(const aOrder: IStockOrder;const aTP: TStockRealNumber; const aComment: string); var aNew : TStockRealNumber; begin aNew:=GetBroker.RoundPrice(aOrder.GetSymbol,aTP); if not SameValue(aNew,aOrder.GetTakeProfit) then begin if aComment<>'' then GetBroker.AddMessage(aOrder,aComment); aOrder.SetTakeProfit(aNew); end; end; function TStockTraderMACross2_15m.GetMainTrend(index: integer): TSCRealNumber; begin result:=0;//FMA84_M15.GetValue(index)-FMA220_M15.GetValue(index); end; function TStockTraderMACross2_15m.GetCross(index: integer): integer; var x1,x2: integer; begin x1:=Sign(FFastMA_M15.GetValue(index)-FSlowMA_M15.GetValue(index)); x2:=Sign(FFastMA_M15.GetValue(index-1)-FSlowMA_M15.GetValue(index-1)); if x1=x2 then exit(0); result:=x1; end; procedure TStockTraderMACross2_15m.UpdateStep2(const aTime: TDateTime); var idx15: integer; aInputData : ISCInputDataCollection; aChart : IStockChart; aOpenedOrder: IStockOrder; aOpen : integer; aMaCross : integer; aTime15 : TDateTime; //aFastTrend : TSCRealNumber; //aPrice : TSCRealNumber; i: Integer; begin if FPropFullBarsOnly.Value then begin if ((MinuteOf(aTime) mod 15)<>0) then exit; end; if SecondOf(aTime)<>0 then exit; aTime15:=TStockDataUtils.AlignTimeToLeft(aTime,sti15); if SameDateTime(FLastOpenOrderTime,aTime15) then exit; //Брокер может закрыть ордера и без нас. У нас в списке они останутся, //но будут уже закрыты. Если их не убрать, то открываться в этоу же сторону мы не //сможем, пока не будет сигнала от эксперта. Если же их удалить, сигналы //от эксперта в эту же сторону опять можно отрабатывать RemoveClosedOrders; aChart:=GetParentStockChart(FFastMA_M15); aInputData:=aChart.GetInputData; idx15:=aChart.FindBar(aTime); if (idx15<>-1) and (idx15>=FSlowMA_M15.GetPeriod) then begin aOpen:=0; for i := idx15 downto idx15-0 do begin aMaCross:=GetCross(i); //Открываем ордер if aMaCross>0 then aOpen:=1 else if aMaCross<0 then aOpen:=-1; if aOpen<>0 then break; end; if aOpen<>0 then begin //BUY if (aOpen=1) and (LastOrderType<>lotBuy) then begin CloseAllOrders(okSell,('Trader: Open opposite')); aOpenedOrder:=OpenMASnappedOrder(okBuy,FFastMA_M15.GetValue(idx15)); FLastOpenOrderTime:=aTime15; end //SELL else if (aOpen=-1) and (LastOrderType<>lotSell) then begin CloseAllOrders(okBuy,('Trader: Open opposite')); aOpenedOrder:=OpenMASnappedOrder(okSell,FFastMA_M15.GetValue(idx15)); FLastOpenOrderTime:=aTime15; end; end; end; end; procedure TStockTraderMACross2_15m.OnBeginWorkSession; begin inherited; FLastOpenOrderTime:=0; end; function TStockTraderMACross2_15m.OpenMASnappedOrder(aKind: TStockOrderKind;const aMALevel:TSCRealNumber; const aComment: string=''): IStockOrder; var aOpenPrice: TSCRealNumber; aSpread: TSCRealNumber; aExpTime: TDateTime; begin aSpread:=GetBroker.PointToPrice(GetSymbol,GetBroker.GetMarketInfo(GetSymbol).Spread); result:=nil; if aKind=okBuy then begin aOpenPrice :=aMALevel+aSpread;//GetBroker.GetCurrentPrice(GetSymbol,bpkAsk))/2+aSpread; if Abs(GetBroker.GetCurrentPrice(GetSymbol,bpkAsk)-aOpenPrice)<=aSpread then result:=OpenOrder(aKind,aComment); end else begin aOpenPrice := aMALevel;//+GetBroker.GetCurrentPrice(GetSymbol,bpkBid))/2-aSpread; if Abs(GetBroker.GetCurrentPrice(GetSymbol,bpkBid)-aOpenPrice)<=aSpread then result:=OpenOrder(aKind,aComment); end; if result=nil then begin result:=inherited OpenOrderAt(aKind,aOpenPrice,aComment); aExpTime:=TStockDataUtils.AlignTimeToLeft(GetBroker.GetCurrentTime,sti15); aExpTime:=IncMinute(aExpTime,(FFastMA_M15.GetPeriod div 4)*15+1); result.SetPendingExpirationTime(aExpTime); end; end; function TStockTraderMACross2_15m.PriceToPoint(const aPrice: TSCRealNumber): integer; begin result:=GetBroker.PriceToPoint(GetSymbol,aPrice); end; initialization FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','MA Cross 2 (15 min)',TStockTraderMACross2_15m,IStockTraderMACross2_15m); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2015-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Android.Beacon; interface uses System.Beacon, System.Bluetooth; type /// <summary> /// Implements TBeaconAdvertiser for Android platform /// </summary> TPlatformBeaconAdvertiser = class(TBeaconAdvertiser) public /// <summary> Gets an instance of the Beacon Device for the current platform </summary> class function GetInstance(const AGattServer: TBluetoothGattServer = nil): TBeaconAdvertiser; override; /// <summary> Gets an instance of the Beacon Device as a purpose of help, without GattServer for the current platform </summary> class function GetHelperInstance: TBeaconAdvertiser; override; end; implementation uses System.SysUtils, System.Types; type TAndroidBeaconAdvertiser = class(TBeaconAdvertiser) private function GetDefaultTxPower: Integer; protected function GetManufacturerData: TBytes; override; class function GetInstance(const AGattServer: TBluetoothGattServer = nil): TBeaconAdvertiser; override; class function GetHelperInstance: TBeaconAdvertiser; override; end; { TPlatformBeaconAdvertiser } class function TPlatformBeaconAdvertiser.GetInstance(const AGattServer: TBluetoothGattServer): TBeaconAdvertiser; begin Result := TAndroidBeaconAdvertiser.GetInstance(AGattServer); end; class function TPlatformBeaconAdvertiser.GetHelperInstance: TBeaconAdvertiser; begin Result := TAndroidBeaconAdvertiser.GetHelperInstance; end; { TAndroidBeaconAdvertiser } function TAndroidBeaconAdvertiser.GetDefaultTxPower: Integer; begin Result := TxPower; end; class function TAndroidBeaconAdvertiser.GetInstance(const AGattServer: TBluetoothGattServer = nil): TBeaconAdvertiser; begin Result := TAndroidBeaconAdvertiser.Create(AGattServer); end; class function TAndroidBeaconAdvertiser.GetHelperInstance: TBeaconAdvertiser; begin Result := TAndroidBeaconAdvertiser.Create(nil, True); end; function TAndroidBeaconAdvertiser.GetManufacturerData: TBytes; const // Beacon (ManufacturerData) packet format // ID Type GUID Major Minor TX Alt //[0..1][2..3][4..19][20..21][22..23][24]//[25] UUID_BYTES_128_BIT = 16; BEACON_STANDARD_ADV_LENGTH = 25; BEACON_ADV_MAJOR_POSITION = 20; BEACON_ADV_MINOR_POSITION = 22; BEACON_ADV_TXPOWER_POSITION = 24; var LTxPower: Integer; BEACON_PREFIXLength: Integer; ADVLength: Integer; begin BEACON_PREFIXLength := Length(BEACON_PREFIX); Setlength(Result, BEACON_PREFIXLength); Move(BEACON_PREFIX[0], Result[0], BEACON_PREFIXLength); if BeaconType = BEACON_ST_TYPE then ADVLength := BEACON_STANDARD_ADV_LENGTH else begin ADVLength := ALTERNATIVE_DATA_LENGTH; PWord(@Result[BEACON_MANUFACTURER_ID_POSITION])^ := ManufacturerId; PWord(@Result[BEACON_TYPE_POS])^ := Swap(BeaconType); end; if TxPower = DEFAULT_TXPOWER then LTxPower := GetDefaultTxPower else LTxPower := TxPower; SetLength(Result, ADVLength); Move(GUID.ToByteArray(TEndian.Big)[0], Result[BEACON_PREFIXLength], UUID_BYTES_128_BIT); PWord(@Result[BEACON_ADV_MAJOR_POSITION])^ := Swap(Major); PWord(@Result[BEACON_ADV_MINOR_POSITION])^ := Swap(Minor); PShortInt(@Result[BEACON_ADV_TXPOWER_POSITION])^ := Int8(LTxPower); if BeaconType <> BEACON_ST_TYPE then PShortInt(@Result[BEACON_ADV_TXPOWER_POSITION + 1])^ := MFGReserved; end; end.
{ AD.A.P.T. Library Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved Original Source Location: https://github.com/LaKraven/ADAPT Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md } unit ADAPT.Hashers; {$I ADAPT.inc} interface uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} ADAPT, ADAPT.Intf, ADAPT.Hashers.Intf; {$I ADAPT_RTTI.inc} /// <comments> /// <para><c>For 32bit CPUs uses </c><see DisplayName="ADSuperFastHash32" cref="ADAPT.Generics.Defaults|ADSuperFastHash32"/><c>.</c></para> /// <para><c>For 64bit CPUs uses </c><see DisplayName="ADSuperFastHash64" cref="ADAPT.Generics.Defaults|ADSuperFastHash64"/><c>.</c></para> /// </comments> function ADSuperFastHash(AData: Pointer; ADataLength: Integer): LongWord; /// <comments> /// <para><c>For 32bit CPUs</c></para> /// <para><c>Pascal translation of the SuperFastHash function by Paul Hsieh</c></para> /// <para><c>More info: http://www.azillionmonkeys.com/qed/hash.html</c></para> /// <para><c>Translation by: Davy Landman</c></para> /// <para><c>Translation found at: http://landman-code.blogspot.co.uk/2008/06/superfasthash-from-paul-hsieh.html</c></para> /// <para><c>Source appears to be made available as "Public Domain" and is used in good faith.</c></para> /// </comments> function ADSuperFastHash32(AData: Pointer; ADataLength: Integer): LongWord; /// <comments> /// <para><c>For 64bit CPUs</c></para> /// <para><c>Pascal translation of the SuperFastHash function by Paul Hsieh</c></para> /// <para><c>More info: http://www.azillionmonkeys.com/qed/hash.html</c></para> /// <para><c>Translation by: Davy Landman</c></para> /// <para><c>Translation found at: http://landman-code.blogspot.co.uk/2008/06/superfasthash-from-paul-hsieh.html</c></para> /// <para><c>Source appears to be made available as "Public Domain" and is used in good faith.</c></para> /// <para><c>64bit Fixes by: Simon J Stuart</c></para> /// </comments> function ADSuperFastHash64(AData: Pointer; ADataLength: Integer): LongWord; implementation function ADSuperFastHash32(AData: Pointer; ADataLength: Integer): LongWord; var LTmpPart: LongWord; LBytesRemaining: Integer; begin if not Assigned(AData) or (ADataLength <= 0) then begin Result := 0; Exit; end; Result := ADataLength; LBytesRemaining := ADataLength and 3; ADataLength := ADataLength shr 2; // div 4, so var name is not correct anymore.. // main loop while ADataLength > 0 do begin inc(Result, PWord(AData)^); LTmpPart := (PWord(Pointer(Cardinal(AData)+2))^ shl 11) xor Result; Result := (Result shl 16) xor LTmpPart; AData := Pointer(Cardinal(AData) + 4); inc(Result, Result shr 11); dec(ADataLength); end; // end case if LBytesRemaining = 3 then begin inc(Result, PWord(AData)^); Result := Result xor (Result shl 16); Result := Result xor (PByte(Pointer(Cardinal(AData)+2))^ shl 18); inc(Result, Result shr 11); end else if LBytesRemaining = 2 then begin inc(Result, PWord(AData)^); Result := Result xor (Result shl 11); inc(Result, Result shr 17); end else if LBytesRemaining = 1 then begin inc(Result, PByte(AData)^); Result := Result xor (Result shl 10); inc(Result, Result shr 1); end; Result := Result xor (Result shl 3); inc(Result, Result shr 5); Result := Result xor (Result shl 4); inc(Result, Result shr 17); Result := Result xor (Result shl 25); inc(Result, Result shr 6); end; function ADSuperFastHash64(AData: Pointer; ADataLength: Integer): LongWord; var LTmpPart: UInt64; LBytesRemaining: Int64; begin if not Assigned(AData) or (ADataLength <= 0) then begin Result := 0; Exit; end; Result := ADataLength; LBytesRemaining := ADataLength and 3; ADataLength := ADataLength shr 2; // div 4, so var name is not correct anymore.. // main loop while ADataLength > 0 do begin inc(Result, PWord(AData)^); LTmpPart := (PWord(Pointer(UInt64(AData)+2))^ shl 11) xor Result; Result := (Result shl 16) xor LTmpPart; AData := Pointer(UInt64(AData) + 4); inc(Result, Result shr 11); dec(ADataLength); end; // end case if LBytesRemaining = 3 then begin inc(Result, PWord(AData)^); Result := Result xor (Result shl 16); Result := Result xor (PByte(Pointer(UInt64(AData)+2))^ shl 18); inc(Result, Result shr 11); end else if LBytesRemaining = 2 then begin inc(Result, PWord(AData)^); Result := Result xor (Result shl 11); inc(Result, Result shr 17); end else if LBytesRemaining = 1 then begin inc(Result, PByte(AData)^); Result := Result xor (Result shl 10); inc(Result, Result shr 1); end; Result := Result xor (Result shl 3); inc(Result, Result shr 5); Result := Result xor (Result shl 4); inc(Result, Result shr 17); Result := Result xor (Result shl 25); inc(Result, Result shr 6); end; function ADSuperFastHash(AData: Pointer; ADataLength: Integer): LongWord; begin {$IFDEF CPUX64} Result := ADSuperFastHash64(AData, ADataLength); {$ELSE} Result := ADSuperFastHash32(AData, ADataLength); {$ENDIF CPUX64} end; end.
PROGRAM OneDigit(INPUT, OUTPUT); VAR Number: INTEGER; PROCEDURE ReadNumber(VAR FromFile: TEXT; VAR Number: INTEGER); {Преобразует строку цифр из файла до первого нецифрового символа, в соответствующее целое число N} VAR Digit: INTEGER; PROCEDURE ReadDigit(VAR FromFile: TEXT; VAR Digit: INTEGER); {Считывает текущий символ из файла, если он - цифра, возвращает его преобразуя в значение типа INTEGER. Если считанный символ не цифра возвращает -1} VAR Ch: CHAR; BEGIN{ReadDigit} Digit := -1; IF NOT EOLN(FromFile) THEN BEGIN READ(FromFile, Ch); IF Ch = '0' THEN Digit := 0 ELSE IF Ch = '1' THEN Digit := 1 ELSE IF Ch = '2' THEN Digit := 2 ELSE IF Ch = '3' THEN Digit := 3 ELSE IF Ch = '4' THEN Digit := 4 ELSE IF Ch = '5' THEN Digit := 5 ELSE IF Ch = '6' THEN Digit := 6 ELSE IF Ch = '7' THEN Digit := 7 ELSE IF Ch = '8' THEN Digit := 8 ELSE IF Ch = '9' THEN Digit := 9 END END;{ReadDigit} BEGIN{ReadNumber} Digit := 0; Number := 0; WHILE NOT EOLN(FromFile) AND (Number <> -1) AND (Digit <> -1) DO BEGIN ReadDigit(FromFile, Digit); IF (( Number > (MAXINT DIV 10)) OR ((Number = MAXINT DIV 10) AND (Digit > MAXINT MOD 10))) AND (Digit <> -1) {AND DIGIT <> -1 НУЖЕН ДЛЯ ТАКИХ СЛУЧАЕВ 2147483647МЧМЧМ. КОГДА ПРОГРАММА ДОЙДЕТ ДО 2147483647, ТО УСЛОВИЕ DIGIT <> -1 ПРОВЕРИТ ЕСЛИ СПРАВА СТОИТ ЦИФРА, ТО КОГДА ДОБАВИМ ЕЕ К НАШЕМУ ЧИСЛУ, У НАС БУДЕТ ПЕРЕБОР} THEN Number := -1 ELSE IF Digit <> -1 THEN Number := Number * 10 + Digit ELSE Digit := -1 END END;{ReadNumber} BEGIN{OneDigit} ReadNumber(INPUT, Number); WRITELN('Преобразование: ', Number) END.{OneDigit}
{** Logging and benchmarking functions for debugging Not supposed to be used in production } unit bbdebugtools; {$mode objfpc}{$H+} interface uses Classes, SysUtils; procedure log(const s: string); procedure startTiming(const title:string='global'); procedure stopTiming(const title:string = ''); procedure stoplogging(); type TStringNotifyEvent = procedure(message: string) of object; var logging: boolean=false; logFileCreated: boolean=false; logFile: TextFile; logFileSection: TRTLCriticalSection; logFileName: string; timing: TStringList=nil; //wird zur Speicherplatzoptimierung nicht freigegeben //(bzw. erst nach Programmende von Windows) OnLog: TStringNotifyEvent = nil; {$ifdef android} function __android_log_write(prio:longint;tag,text:pchar):longint; cdecl; external 'liblog.so' name '__android_log_write'; {$endif} implementation uses bbutils; function dateTimeFormatNow(const mask: string): string; var st: TSystemTime; begin st := default(TSystemTime); GetLocalTime(st); result := dateTimeFormat(mask, st.Year, st.month, st.Day, st.Hour, st.Minute, st.Second, st.MilliSecond * 1000000); end; procedure log(const s: string); var t:string; {$ifndef android} sl: TStringArray; i: Integer; {$endif} begin if logging then begin t:=dateTimeFormatNow('yyyy-mm-dd:hh:nn:ss:zzz')+' ('+inttostr(GetThreadID)+'): '+s; if not logFileCreated then begin system.InitCriticalSection(logFileSection); system.EnterCriticalSection(logFileSection); logFileCreated:=true; {$ifndef android} logFileName := fileNameExpand(GetTempDir+'videLibriLogFile_'+dateTimeFormatNow('yyyymmdd_hhnnss')); AssignFile(logFile, logFileName); Rewrite(logFile); WriteLn(logFile,'Logging gestartet am '+dateTimeFormatNow('yyyy-mm-dd "um" hh:nn:ss')); {$endif} end else system.EnterCriticalSection(logFileSection); {$ifndef android} if length(t) <= 255 then WriteLn(logFile,t) else begin sl := strSplit(t, LineEnding); for i:=0 to high(sl) do writeln(logFile, sl[i]); end; Flush(logFile); {$IFNDEF WIN32} if length(t) <= 255 then WriteLn(stderr,t) else begin for i:=0 to high(sl) do writeln(stderr, sl[i]); end; {$ENDIF} {$else} __android_log_write({INFO}4, 'VideLibri', pchar(t)); {$endif} system.LeaveCriticalSection(logFileSection); if assigned(OnLog) then OnLog(t); end; end; procedure startTiming(const title: string); var index:longint; begin logging := true; { if ThreadID<>MainThreadID then exit; //timing isn't thread save} if timing=nil then timing:=TStringList.Create; index:=timing.IndexOf(title); if index=-1 then begin index:=timing.count; timing.add(title); end; log('started timing of '+title); timing.Objects[index]:=tobject(pointer(trunc(frac(now)*MSecsPerDay))); end; procedure stopTiming(const title: string); var time,oldtime:cardinal; i: Integer; begin { if ThreadID<>MainThreadID then exit; //timing isn't thread save } time:=trunc(frac(now)*MSecsPerDay); if (timing.count = 1) and (title = '') then i := 0 else i := timing.IndexOf(title); oldtime:=cardinal(pointer(timing.Objects[i])); if (timing.count > 1) or (title <> '') then log('stopped timing of '+title+' run-time: '+IntToStr(time-oldtime)+' ms') else log('run-time: '+IntToStr(time-oldtime)+' ms'); timing.Delete(i); end; procedure stoplogging(); begin if not logFileCreated then exit; {$ifdef android}exit;{$endif} system.EnterCriticalSection(logFileSection); CloseFile(logFile); logFileCreated:=false; system.LeaveCriticalsection(logFileSection); system.DoneCriticalsection(logFileSection); end; end.
unit U_SplashScreen; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Winapi.ShellAPI, VAUtils, JAWSImplementation, VA508AccessibilityConst, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ImgList, Vcl.Imaging.pngimage, Vcl.AppEvnts, System.ImageList; type TStaticText = class(Vcl.StdCtrls.TStaticText) private FFocused: Boolean; protected procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; end; TButton = class(Vcl.StdCtrls.TButton) private f508Label: TStaticText; procedure CMEnabledChanged(var Msg: TMessage); message CM_ENABLEDCHANGED; destructor Destroy; override; end; tStatus = (DS_RUN, DS_ERROR, DS_CHECK); TExecutEvent = function(ComponentCallBackProc: TComponentDataRequestProc): BOOL; tSplahThread = Class(TThread) private fOnExecute: TExecutEvent; fSplashDialog: TComponent; fComponentCallBackProc: TComponentDataRequestProc; protected procedure Execute; override; public constructor Create(aSplashCTRL: TComponent; ComponentCallBackProc: TComponentDataRequestProc); destructor Destroy; override; property OnExecute: TExecutEvent read fOnExecute write fOnExecute; End; TErrType = (Err_Sys, Err_Other); tErrorRec = Record Title: String; ErrorMessage: String; ErrType: TErrType; End; TSplashScrn = class(TForm) pnlButtons: TPanel; btnContinue: TButton; ImageList2: TImageList; btnErrors: TButton; btnLog: TButton; Panel2: TPanel; pnlRight: TPanel; ProgressBar1: TProgressBar; pnlLeft: TPanel; imgFoot: TImage; imgError: TImage; imgInfo: TImage; pnlLog: TPanel; StaticText1: TStaticText; pnlForce: TPanel; lblForce: TStaticText; lblFoot: TStaticText; lblTitle: TStaticText; lblMessage: TStaticText; ApplicationEvents1: TApplicationEvents; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); private { Private declarations } fInit: Boolean; fOrigCaption: String; fRunTime: TDateTime; fDoneRunning: Boolean; public { Public declarations } end; tSplashTaskDialog = class(TComponent) private // fTaskDialog: TTaskDialog; fSplashScreen: TSplashScrn; fSplashThread: tSplahThread; fTaskText: String; fTaskTitle: String; fTaskError: String; fProgMax: Integer; fProgMoveBy: Integer; fThreadResult: BOOL; fErrorsExist: Boolean; fMainImageID: Integer; fLogPath: String; fSysErrorShowing: Boolean; fErrorRecs: array of tErrorRec; fErrNum: Integer; fStopViewErr: Boolean; rtnCurson: Integer; procedure SetTaskText(aValue: string); procedure SetTaskTitle(aValue: string); procedure SetTaskError(aValue: string); Procedure SetTaskMaxProg(aValue: Integer); Procedure SetMainImageId(aValue: Integer); procedure SyncTaskText; procedure SyncTaskTitle; procedure SyncTaskEError; procedure SyncIncProg; procedure SyncMaxProg; procedure ShowErrorDialog; procedure ErrorDialogClick(aSender: TObject; AModalResult: TModalResult; var CanClose: Boolean); procedure ErrorDialogClose(Sender: TObject); procedure SplashTaskDialogClose(Sender: TObject); procedure BundleErrorMessages; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); property ImageID: Integer read fMainImageID write SetMainImageId; public constructor Create(ExecuteEvent: TExecutEvent; ComponentCallBackProc: TComponentDataRequestProc; LogLink: Boolean = false; ForceUPD: Integer = -1); destructor Destroy; Procedure IncProg(ByCnt: Integer = 1); procedure ShowSystemError(aErrorText: string); procedure Show; property TaskText: string read fTaskText write SetTaskText; property TaskTitle: string read fTaskTitle write SetTaskTitle; property TaskError: string write SetTaskError; property TaskMaxProg: Integer read fProgMax write SetTaskMaxProg; property ReturnValue: BOOL read fThreadResult; property ErrorsExist: Boolean read fErrorsExist; property LogPath: string read fLogPath write fLogPath; end; Const CAP_FOOT = 'Errors Found'; LINE_MAX = 15; implementation {$R *.dfm} {$REGION 'tSplashTaskDialog'} procedure tSplashTaskDialog.ShowErrorDialog; var I: Integer; begin // Create the error dialog with TTaskDialog.Create(self) do begin Caption := 'Error Log Viewer'; Title := fErrorRecs[fErrNum].Title; Text := fErrorRecs[fErrNum].ErrorMessage; MainIcon := tdiError; flags := []; CommonButtons := []; with TTaskDialogButtonItem(Buttons.Add) do begin Caption := 'Stop Viewing'; ModalResult := mrAbort; Enabled := true; CommandLinkHint := 'This will close the rest of the errors that were logged' end; with TTaskDialogButtonItem(Buttons.Add) do begin Caption := 'Previous'; ModalResult := mrYes; Enabled := fErrNum > Low(fErrorRecs); CommandLinkHint := 'View the previous error in the log'; if fErrNum = high(fErrorRecs) then default := true; end; with TTaskDialogButtonItem(Buttons.Add) do begin Caption := 'Next'; ModalResult := mrNo; Enabled := fErrNum < high(fErrorRecs); default := Enabled; CommandLinkHint := 'View the next error in the log'; end; FooterIcon := tdiInformation; FooterText := 'Error ' + IntToStr(fErrNum + 1) + ' of ' + IntToStr(High(fErrorRecs) + 1); OnButtonClicked := ErrorDialogClick; OnDialogDestroyed := ErrorDialogClose; // SpeakText(PChar(Title + ', ' + Text)); Execute; end; end; procedure tSplashTaskDialog.ErrorDialogClick(aSender: TObject; AModalResult: TModalResult; var CanClose: Boolean); begin CanClose := true; case AModalResult of mrAbort: fStopViewErr := true; mrYes: Dec(fErrNum); mrNo: Inc(fErrNum); end; end; procedure tSplashTaskDialog.ErrorDialogClose(Sender: TObject); begin if not fStopViewErr then begin if (fErrNum >= low(fErrorRecs)) and (fErrNum <= high(fErrorRecs)) then begin ShowErrorDialog; end; end else fStopViewErr := false; end; procedure tSplashTaskDialog.SplashTaskDialogClose(Sender: TObject); begin inherited; // if fTaskDialog.ModalResult = mrAbort then // Application.Terminate; end; procedure tSplashTaskDialog.SetTaskText(aValue: string); begin if Assigned(fSplashScreen) then begin fTaskText := aValue; if Assigned(fSplashThread) then fSplashThread.Synchronize(SyncTaskText) else SyncTaskText; end; end; procedure tSplashTaskDialog.SyncTaskText; var tmp: tStringList; I, OriglineNum: Integer; OrigTxt: String; begin fSplashScreen.lblMessage.Caption := fTaskText; SpeakText(PWideChar(fTaskText)); end; procedure tSplashTaskDialog.SetTaskTitle(aValue: string); begin if Assigned(fSplashScreen) then begin fTaskTitle := aValue; if Assigned(fSplashThread) then fSplashThread.Synchronize(SyncTaskTitle) else SyncTaskTitle; end; end; procedure tSplashTaskDialog.SyncTaskTitle; begin fSplashScreen.lblTitle.Caption := fTaskTitle; SpeakText(PWideChar(fTaskTitle)); end; procedure tSplashTaskDialog.SetTaskError(aValue: string); begin if Assigned(fSplashScreen) then begin fTaskError := aValue; if Assigned(fSplashThread) then fSplashThread.Synchronize(SyncTaskEError) else SyncTaskEError; end; end; procedure tSplashTaskDialog.SyncTaskEError; begin if not fSplashScreen.imgFoot.Visible then begin fSplashScreen.imgFoot.Visible := true; fSplashScreen.lblFoot.Visible := true; SpeakText(PWideChar(fSplashScreen.lblFoot.Caption)); end; SetLength(fErrorRecs, Length(fErrorRecs) + 1); fErrorRecs[High(fErrorRecs)].Title := fTaskTitle; fErrorRecs[High(fErrorRecs)].ErrorMessage := fTaskError; fErrorRecs[High(fErrorRecs)].ErrType := Err_Other; fErrorsExist := true; end; Procedure tSplashTaskDialog.SetTaskMaxProg(aValue: Integer); begin fProgMax := aValue; if Assigned(fSplashThread) then fSplashThread.Synchronize(SyncMaxProg) else SyncMaxProg; end; procedure tSplashTaskDialog.SyncMaxProg; begin fSplashScreen.ProgressBar1.Max := fProgMax; end; Procedure tSplashTaskDialog.IncProg(ByCnt: Integer = 1); begin fProgMoveBy := ByCnt; if Assigned(fSplashThread) then fSplashThread.Synchronize(SyncIncProg) else SyncIncProg; end; procedure tSplashTaskDialog.SyncIncProg; begin fSplashScreen.ProgressBar1.Position := fSplashScreen.ProgressBar1.Position + fProgMoveBy; end; procedure tSplashTaskDialog.ShowSystemError(aErrorText: string); begin fSysErrorShowing := true; SetTaskText(aErrorText); // sync with generic fSplashThread.Synchronize( procedure begin ImageID := 0; fSplashScreen.btnContinue.Enabled := true; fSplashScreen.btnContinue.SetFocus; Screen.Cursor := rtnCurson; end); SetLength(fErrorRecs, Length(fErrorRecs) + 1); fErrorRecs[High(fErrorRecs)].Title := fTaskTitle; fErrorRecs[High(fErrorRecs)].ErrorMessage := aErrorText; fErrorRecs[High(fErrorRecs)].ErrType := Err_Sys; fSplashThread.Suspended := true; end; Procedure tSplashTaskDialog.SetMainImageId(aValue: Integer); begin if Assigned(fSplashScreen) then begin fMainImageID := aValue; case aValue of 0: begin fSplashScreen.imgError.Visible := true; fSplashScreen.imgInfo.Visible := false; end; 1: begin fSplashScreen.imgError.Visible := false; fSplashScreen.imgInfo.Visible := true; end; end; end; end; constructor tSplashTaskDialog.Create(ExecuteEvent: TExecutEvent; ComponentCallBackProc: TComponentDataRequestProc; LogLink: Boolean = false; ForceUPD: Integer = -1); function GetDLLName: string; var aName: array [0 .. MAX_PATH] of char; begin fillchar(aName, SizeOf(aName), #0); GetModuleFileName(HInstance, aName, MAX_PATH); Result := aName; end; var DLLName, FileVersion: string; begin inherited Create(nil); rtnCurson := Screen.Cursor; DLLName := GetDLLName; FileVersion := FileVersionValue(DLLName, FILE_VER_FILEVERSION); fErrorsExist := false; fSplashScreen := TSplashScrn.Create(self); try fSplashScreen.Caption := 'VA 508 Jaws Framework - Version: ' + FileVersion; fSplashScreen.fOrigCaption := fSplashScreen.Caption; SetTaskTitle('Jaws Framework'); SetTaskText('Starting the jaws framework. Please wait ' + ExtractFileName(Application.ExeName) + ' will open on it''s own if no errors were found.'); ImageID := 1; fSplashScreen.btnLog.Enabled := LogLink; fSplashScreen.pnlLog.Visible := LogLink; if ForceUPD <> -1 then begin fSplashScreen.pnlForce.Visible := true; if ForceUPD = 0 then fSplashScreen.lblForce.Caption := 'Force update all versions' else fSplashScreen.lblForce.Caption := 'Force update version ' + IntToStr(ForceUPD); end; fSplashScreen.OnDestroy := SplashTaskDialogClose; fSplashScreen.OnCloseQuery := FormCloseQuery; fSplashThread := tSplahThread.Create(self, ComponentCallBackProc); fSplashThread.OnExecute := ExecuteEvent; SetLength(fErrorRecs, 0); fErrNum := 0; except fSplashScreen.Free; end; end; Procedure tSplashTaskDialog.Show; begin fSplashThread.Start; fSplashScreen.ShowModal; fThreadResult := fThreadResult; // if fTaskDialog.ModalResult = mrAbort then // Application.Terminate; end; destructor tSplashTaskDialog.Destroy; begin FreeAndNil(fSplashScreen); SetLength(fErrorRecs, 0); inherited; end; procedure tSplashTaskDialog.BundleErrorMessages; var I, X: Integer; CloneArry: array of tErrorRec; TitleList: tStringList; begin SetLength(CloneArry, 0); TitleList := tStringList.Create; try TitleList.Sorted := true; TitleList.Duplicates := dupIgnore; for I := Low(fErrorRecs) to High(fErrorRecs) do begin SetLength(CloneArry, Length(CloneArry) + 1); CloneArry[High(CloneArry)].Title := fErrorRecs[I].Title; CloneArry[High(CloneArry)].ErrorMessage := fErrorRecs[I].ErrorMessage; CloneArry[High(CloneArry)].ErrType := fErrorRecs[I].ErrType; // system errors always display un bundled if fErrorRecs[I].ErrType <> Err_Sys then TitleList.Add(fErrorRecs[I].Title); end; SetLength(fErrorRecs, 0); // gather the system level errors for I := Low(CloneArry) to High(CloneArry) do begin if CloneArry[I].ErrType = Err_Sys then begin SetLength(fErrorRecs, Length(fErrorRecs) + 1); fErrorRecs[High(fErrorRecs)].Title := CloneArry[I].Title; fErrorRecs[High(fErrorRecs)].ErrorMessage := CloneArry[I].ErrorMessage; fErrorRecs[High(fErrorRecs)].ErrType := CloneArry[I].ErrType; end; end; // Loop through our unique enteries and bundle them for X := 0 to TitleList.Count - 1 do begin SetLength(fErrorRecs, Length(fErrorRecs) + 1); fErrorRecs[High(fErrorRecs)].Title := TitleList[X]; fErrorRecs[High(fErrorRecs)].ErrType := Err_Other; for I := Low(CloneArry) to High(CloneArry) do begin if CloneArry[I].Title = TitleList[X] then fErrorRecs[High(fErrorRecs)].ErrorMessage := CloneArry[High(fErrorRecs)].ErrorMessage + CRLF + CloneArry[I].ErrorMessage; end; end; finally TitleList.Free; end; end; procedure tSplashTaskDialog.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := false; case TSplashScrn(Sender).ModalResult of mrNo: ShellExecute(Application.Handle, 'open', PChar(fLogPath), '', '', SW_NORMAL); mrIgnore: begin ShowErrorDialog; end; mrYes: begin if fSysErrorShowing then begin fSysErrorShowing := false; // no need to sync since thread is not running here ImageID := 1; fSplashScreen.btnContinue.Enabled := false; Screen.Cursor := crHourGlass; fSplashThread.Resume; end else CanClose := true; end; end; end; {$ENDREGION} {$REGION 'tSplahThread'} procedure tSplahThread.Execute; begin if Assigned(fOnExecute) then begin // Sleep(1000); tSplashTaskDialog(fSplashDialog).fThreadResult := fOnExecute(fComponentCallBackProc); end; end; constructor tSplahThread.Create(aSplashCTRL: TComponent; ComponentCallBackProc: TComponentDataRequestProc); begin inherited Create(true); FreeOnTerminate := true; fOnExecute := nil; fSplashDialog := aSplashCTRL; fComponentCallBackProc := ComponentCallBackProc; end; destructor tSplahThread.Destroy; begin // generic sync Synchronize( procedure begin if not tSplashTaskDialog(fSplashDialog).ErrorsExist then begin tSplashTaskDialog(fSplashDialog).fSplashScreen.btnContinue.Click; // SpeakText(PChar('Please wait, opening ' + ExtractFileName(Application.ExeName))); end else begin tSplashTaskDialog(fSplashDialog).SetTaskTitle('General'); tSplashTaskDialog(fSplashDialog).SetTaskText('Bundling errors'); tSplashTaskDialog(fSplashDialog).BundleErrorMessages; tSplashTaskDialog(fSplashDialog).ImageID := 0; tSplashTaskDialog(fSplashDialog).SetTaskTitle('Error Check'); tSplashTaskDialog(fSplashDialog).SetTaskText('Potential errors where found while trying to process the Jaws scripts. ' + 'Press continue to ignore these errors and open ' + ExtractFileName(Application.ExeName) + '. Please note that the framework may not work correctly. ' + CRLF + 'If you continue to experience this issue please contact your local system administrator for assistance.'); tSplashTaskDialog(fSplashDialog).fSplashScreen.btnErrors.Enabled := true; tSplashTaskDialog(fSplashDialog).fSplashScreen.btnLog.Enabled := true; tSplashTaskDialog(fSplashDialog).fSplashScreen.btnContinue.ImageIndex := 2; tSplashTaskDialog(fSplashDialog).fSplashScreen.btnContinue.Enabled := true; tSplashTaskDialog(fSplashDialog).fSplashScreen.btnContinue.SetFocus; Screen.Cursor := tSplashTaskDialog(fSplashDialog).rtnCurson; end; tSplashTaskDialog(fSplashDialog).fSplashScreen.fDoneRunning := true; end); inherited; end; {$ENDREGION} {$REGION 'TSplashScrn'} procedure TSplashScrn.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); begin //Hack since the thread does not want to fire unless a message is being sent to the form CheckSynchronize; if not fDoneRunning then begin //self.caption := fOrigCaption + ' - RunTime: '+ formatdatetime('nn:ss:zz', fRunTime - now()); Self.Caption := Self.Caption + ' '; end; end; procedure TSplashScrn.FormCreate(Sender: TObject); begin SetWindowLong(Handle, GWL_EXSTYLE, WS_EX_APPWINDOW); Application.Icon.LoadFromResourceName(HInstance, 'AppIcon1'); fInit := true; fDoneRunning := false; end; procedure TSplashScrn.FormShow(Sender: TObject); begin if fInit then begin Screen.Cursor := crHourGlass; fInit := false; fRunTime := Now; end; end; {$ENDREGION} {$REGION 'TStaticText'} procedure TStaticText.WMSetFocus(var Message: TWMSetFocus); begin FFocused := True; Invalidate; inherited; end; procedure TStaticText.WMKillFocus(var Message: TWMKillFocus); begin FFocused := False; Invalidate; inherited; end; procedure TStaticText.WMPaint(var Message: TWMPaint); var DC: HDC; R: TRect; begin inherited; if FFocused then begin DC := GetDC(Handle); GetClipBox(DC, R); DrawFocusRect(DC, R); ReleaseDC(Handle, DC); end; end; {$ENDREGION} {$REGION 'TButton'} procedure TButton.CMEnabledChanged(var Msg: TMessage); begin inherited; if not Self.Enabled and Self.Visible then begin f508Label := TStaticText.Create(self); f508Label.Parent := Self.Parent; f508Label.SendToBack; f508Label.TabStop := true; f508Label.TabOrder := Self.TabOrder; f508Label.Caption := ' ' + self.Caption; f508Label.Top := self.Top - 2; f508Label.Left := self.Left - 2; f508Label.Width := self.Width + 5; f508Label.Height := self.Height + 5; end else begin if Assigned(f508Label) then FreeAndNil(f508Label); end; end; destructor TButton.Destroy; begin if Assigned(f508Label) then FreeAndNil(f508Label); Inherited; end; {$ENDREGION} end.
unit PullSupplier_Impl; interface uses CORBA, COSEvent; type TPullSupplier = class(TInterfacedObject, PullSupplier) public constructor Create; function pull : Any; function try_pull(out has_event : Boolean): Any; procedure disconnect_pull_supplier; end; implementation uses SysUtils, PullSupplierMain; constructor TPullSupplier.Create; begin inherited; end; function TPullSupplier.pull : Any; begin if (Form1 <> nil) and (Form1.Edit1.Text <> '') then result := Form1.Edit1.Text else result := 'No Value yet'; end; function TPullSupplier.try_pull(out has_event : Boolean): Any; begin has_event := False; result := 'No Data Yet'; if (Form1 <> nil) and (Form1.Edit1.Text <> '' ) then begin has_event := True; result := pull; end; end; procedure TPullSupplier.disconnect_pull_supplier; begin boa.ExitImplReady; end; end.
program Sample; var H : String; procedure PRINTIT(F : String); begin WriteLn('F: ', F); end; begin H := 'Hello World'; WriteLn('H: ', H); PRINTIT(H); end.
unit PNGMainForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, Buttons, PNGImage, ExtDlgs, ImgList, Win95Pie, Math, jpeg; type {Pixel memory access} pRGBLine = ^TRGBLine; TRGBLine = Array[Word] of TRGBTriple; pRGBALine = ^TRGBALine; TRGBALine = Array[Word] of TRGBQuad; TIDATAccess = class(TChunkIDAT); TGammaTester = class(TCustomPanel) constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint; Override; procedure OnResize(var Message: TWMSize); message WM_SIZE; procedure RecreateBitmap; private Table: Array[Byte] of Byte; Bitmap: TBitmap; vGamma: Double; procedure SetGamma(Value: Double); public property Gamma: Double read vGamma write SetGamma; end; TMainForm = class(TForm) TOPPANEL: TPanel; MainIcon: TImage; TopTITLE: TLabel; TopExplanation: TLabel; RightPanel: TPanel; RightTitle: TLabel; ChunkList: TListView; AddChunk: TSpeedButton; DeleteChunk: TSpeedButton; Status: TStatusBar; LeftPanel: TPanel; LeftTitle: TLabel; BrowseFolder: TSpeedButton; FileList: TListView; SaveFile: TSpeedButton; LoadFile: TSpeedButton; ToggleLeft: TSpeedButton; ToggleRight: TSpeedButton; LoadFileDialog: TOpenPictureDialog; Props: TNotebook; PaletteArea: TPaintBox; PaletteTitle: TPanel; IHDR: TTreeView; Images: TImageList; Progressive: TCheckBox; Reload: TSpeedButton; Divide: TShape; BarHolder: TPanel; SizeHolder: TGroupBox; CSize: TLabel; USize: TLabel; Legend1: TShape; Legend2: TShape; GAMA: TLabel; TestGroup: TGroupBox; NoGammaLabel: TLabel; DefaultGammaLabel: TLabel; KeywordLabel: TLabel; Keyword: TComboBox; TextLabel: TLabel; Text: TMemo; SaveFileDialog: TSaveDialog; SpeedButton1: TSpeedButton; MonthLabel: TLabel; DayLabel: TLabel; YearLabel: TLabel; MonthEdit: TEdit; DayEdit: TEdit; YearEdit: TEdit; MonthScroll: TUpDown; YearScroll: TUpDown; DayScroll: TUpDown; HourScroll: TUpDown; HourEdit: TEdit; HourLabel: TLabel; MinLabel: TLabel; MinEdit: TEdit; SecondEdit: TEdit; SecondLabel: TLabel; MinScroll: TUpDown; SecondScroll: TUpDown; procedure StatusDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); procedure ToggleLeftClick(Sender: TObject); procedure ToggleRightClick(Sender: TObject); procedure ChunkListAdvancedCustomDraw(Sender: TCustomListView; const ARect: TRect; Stage: TCustomDrawStage; var DefaultDraw: Boolean); procedure LoadFileClick(Sender: TObject); procedure ImageProgress(Sender: TObject; Stage: TProgressStage; PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: String); procedure PropsClick(Sender: TObject); procedure PaletteAreaPaint(Sender: TObject); procedure ChunkListChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure FormPaint(Sender: TObject); procedure FormResize(Sender: TObject); procedure ReloadClick(Sender: TObject); procedure SaveFileClick(Sender: TObject); procedure TextExit(Sender: TObject); procedure SaveFileDialogShow(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private { Private declarations } public { Public declarations } MyPie: TWin95PieChart; PLTEPalette: TBitmap; Gamma1, Gamma2: TGammaTester; LoadPicture: TPicture; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Progress(Value: Byte); procedure LoadFromFile(Filename: String); end; var MainForm: TMainForm; implementation var Loading: Boolean = FALSE; LastPos: Integer; {$R *.DFM} { TMainForm } {Toggle the visibility of a panel} procedure TogglePanel(Panel: TPanel; Button: TSpeedButton); var Visible: Boolean; begin Visible := (Button.Caption = '«'); {Save the old width} if not Visible then begin Button.Caption := '«'; Panel.Tag := Panel.Width; while Panel.Width > 14 do begin Panel.Width := Panel.Width - 1; {From time to time make it appears sliding} if Panel.Width mod 4 = 0 then Application.Processmessages; end; end else begin Button.Caption := '»'; while Panel.Width < Panel.Tag do begin Panel.Width := Panel.Width + 1; {From time to time make it appears sliding} if Panel.Width mod 4 = 0 then Application.Processmessages; end; end; end; {When the form is being created} constructor TMainForm.Create(AOwner: TComponent); var i : Integer; begin inherited; Props.PageIndex := 0; Gamma1 := TGammaTester.Create(TestGroup); Gamma2 := TGammaTester.Create(TestGroup); with Gamma1 do begin Parent := TestGroup; Visible := True; SetBounds(NoGammaLabel.Left, NoGammaLabel.Top + 3 + NoGammaLabel.Height, TestGroup.Width - (NoGammaLabel.Left * 2), 15); Gamma := 1; end; with Gamma2 do begin Parent := TestGroup; Visible := True; SetBounds(DefaultGammaLabel.Left, DefaultGammaLabel.Top + 3 + DefaultGammaLabel.Height, TestGroup.Width - (DefaultGammaLabel.Left * 2), 15); end; Mypie := TWin95PieChart.Create(BarHolder); with MyPie do begin Parent := BarHolder; Visible := TRUE; Align := alClient; Color := clAppWorkspace; Depth := 10; DoubleBuffered := TRUE; end; LoadPicture := TPicture.Create; LoadPicture.OnProgress := ImageProgress; {Create bitmap to show the PNG palette} PltePalette := TBitmap.Create; with PltePalette do begin PixelFormat := pf24Bit; Width := Props.Width; Height := Props.Height; end; {Turn on double buffering to avoid flickering} IF ComponentCount > 0 THEN FOR i := 0 TO ComponentCount - 1 DO IF Components[i] is TWINControl then TWINControl(Components[i]).DoubleBuffered := TRUE; end; {Change the value of the progress area} procedure TMainForm.Progress(Value: Byte); begin {Ensures that the value does not pass 100} if Value > 100 then Value := 100; {Set the panel text} Status.Panels[1].Text := INTTOSTR(Value); end; {Custom drawning for a panel} procedure TMainForm.StatusDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); var CleanRect, DrawRect : TRect; begin {Test if it is the progress panel} if Panel.Index = 1 then begin {Make a copy of the rect} DrawRect := Rect; {Set the rect of the drawning area} DrawRect.Right := Rect.Left + strtointdef(Panel.Text, 0); {Draw the blue area} FillRect(StatusBar.Canvas.Handle, DrawRect, COLOR_HIGHLIGHT + 1); {Set to drawn the non used area} SubtractRect(CleanRect, Rect, DrawRect); FillRect(StatusBar.Canvas.Handle, CleanRect, COLOR_BTNFACE + 1); end; end; {Toggle left panel size} procedure TMainForm.ToggleLeftClick(Sender: TObject); begin TogglePanel(LeftPanel, TSpeedButton(Sender)); end; {Toggle right panel size} procedure TMainForm.ToggleRightClick(Sender: TObject); begin ChunkList.ShowColumnHeaders := FALSE; TogglePanel(RightPanel, TSpeedButton(Sender)); ChunkList.ShowColumnHeaders := TRUE; end; {When drawing the chunk list} procedure TMainForm.ChunkListAdvancedCustomDraw(Sender: TCustomListView; const ARect: TRect; Stage: TCustomDrawStage; var DefaultDraw: Boolean); var OldFont, NewFont: HFont; begin {If not a TPNGImage then} if not (LoadPicture.Graphic is TPNGImage) then begin {Create a font} NewFont := CreateFont(-20, 20, -450, -450, FW_BOLD, 1, 0, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS , CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH, 'Tahoma'); OldFont := SelectObject(Sender.Canvas.Handle, NewFont); {Draw the text} SetTextColor(Sender.Canvas.Handle, GetSysColor(COLOR_APPWORKSPACE)); TextOut(Sender.Canvas.Handle, 14, 20, 'Not a PNG', 9); DeleteObject(SelectObject(Sender.Canvas.Handle, OldFont)); end; end; {Load a file using open dialog} procedure TMainForm.LoadFileClick(Sender: TObject); begin if LoadFileDialog.Execute then LoadFromFile(LoadFileDialog.Filename); end; {Load a file} procedure TMainForm.LoadFromFile(Filename: String); var PNG: TPNGImage; i: Integer; Tempo: Double; begin LastPos := 0; Loading := TRUE; {Checks if shows the image progressively} if Progressive.Checked then LoadPicture.OnProgress := ImageProgress else LoadPicture.OnProgress := nil; FillRect(Canvas.Handle, ClientRect, COLOR_BTNFACE + 1); {Load the image} Tempo := GetTickCount; LoadPicture.LoadFromFile(Filename); Progress(0); {Set the file panel} Status.Panels[0].Text := Extractfilename(Filename); Props.PageIndex := 0; {Set the chunk listbox} ChunkList.Items.Clear; {Do the work if it is a PNG image} if LoadPicture.Graphic is TPNGImage then begin {Copy pointer} PNG := TPNGImage(LoadPicture.Graphic); if PNG.Chunks.Count > 0 then FOR i := 0 TO PNG.Chunks.Count - 1 DO with ChunkList.Items.Add do begin Caption := PNG.Chunks[I].ChunkType; subitems.Add(Format('%d bytes', [PNG.Chunks[i].Size])); end; end; Status.Panels[2].Text := format('%n s', [(GetTickCount - Tempo) / 1000]); Loading := FALSE; Canvas.Draw((Width div 2) - (LoadPicture.Width div 2), ((Height) div 2) - (LoadPicture.Height div 2), LoadPicture.Graphic); end; {Loading progress} procedure TMainForm.ImageProgress(Sender: TObject; Stage: TProgressStage; PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: String); begin {If it is a TPNG image we can show it progressive} if Sender is TPNGImage then begin Progress(PercentDone); if (PercentDone mod 5 = 0) and (TChunkIHDR(TPNGIMAGE(SENDER).Chunks[0]).Interlaced = 0) then begin BitBlt(Canvas.Handle, (Width - TBitmap(Sender).Width) div 2, ((Height - TBitmap(Sender).Height) div 2) + LastPos, R.Right, R.Bottom - LastPos, TBitmap(Sender).Canvas.Handle, 0, LastPos, SRCCOPY); LastPos := R.Bottom; end else if (TChunkIHDR(TPNGIMAGE(SENDER).Chunks[0]).Interlaced = 1) then Canvas.Draw((Width - TBitmap(Sender).Width) div 2, ((Height) - TBitmap(Sender).Height) div 2, TBItmap(sender)); end; Application.Processmessages; end; procedure TMainForm.PropsClick(Sender: TObject); begin end; {When the main form is being destroyed} destructor TMainForm.Destroy; begin Gamma1.Free; Gamma2.Free; Mypie.free; LoadPicture.Free; PltePalette.Free; inherited; end; {When painting the area that shows the image palette} procedure TMainForm.PaletteAreaPaint(Sender: TObject); begin if Assigned(PltePalette) then PaletteArea.Canvas.Draw(0, 0, PltePalette); end; {When changing ocurrs (like selection change)} procedure TMainForm.ChunkListChange(Sender: TObject; Item: TListItem; Change: TItemChange); label finished; var IDATC : TChunkIDAT; PalEntries: WORD; IHDRC : TChunkIHDR; TEXTC : TChunkText; TIMEC : TChunkTime; ZTXTC : TChunkZTXT; i, j, x : Integer; MaxPal : TMaxLogPalette; Pal : HPalette; Value1, Value2, Value3, Value4 : Word; DateTime : TDateTime; begin {Only selection matters} if not Assigned(ChunkList.Selected) then exit; if (ChunkList.Selected.Caption = 'tIME') then begin Props.PageIndex := 6; TIMEC := TChunkTIME(TPNGIMAGE(LoadPicture.Graphic).Chunks[ ChunkList.Selected.Index]); DateTime := TIMEC.DateTime; {Get the values} {time} DecodeTime(DateTime, Value1, Value2, Value3, Value4); HourScroll.Position := Value1; MinScroll.Position := Value2; SecondScroll.Position := Value3; {date} DecodeDate(DateTime, Value1, Value2, Value3); YearScroll.Position := Value1; MonthScroll.Position := Value2; DayScroll.Position := Value3; end else if (ChunkList.Selected.Caption = 'zTXt') then begin Props.PageIndex := 5; ZTXTC := TChunkZTXT(TPNGIMAGE(LoadPicture.Graphic).Chunks[ ChunkList.Selected.Index]); {Set the text values} Keyword.Text := ZTXTC.Keyword; Text.Text := ZTXTC.Text; end {If the current selected item is a tEXt chunk} else if (ChunkList.Selected.Caption = 'tEXt') then begin Props.PageIndex := 5; TEXTC := TChunkTEXT(TPNGIMAGE(LoadPicture.Graphic).Chunks[ ChunkList.Selected.Index]); {Set the text values} Keyword.Text := TEXTC.Keyword; Text.Text := TEXTC.Text; end {If the current selected item is a gama chunk} else if ChunkList.Selected.Caption = 'gAMA' then begin Props.PageIndex := 4; Gama.Caption := 'Gamma intensity: ' + floattostr( TChunkGAMA(TPNGIMAGE(LoadPicture.Graphic).Chunks[ ChunkList.Selected.Index]).Value / 100000); Gamma2.Gamma := TChunkGAMA(TPNGIMAGE(LoadPicture.Graphic).Chunks[ ChunkList.Selected.Index]).Value / 100000; end {If the current selected item is a palette} else if ChunkList.Selected.Caption = 'IDAT' then begin {Select the IDAT page} Props.PageIndex := 3; IDATC := TChunkIDAT(TPNGImage(LoadPicture.Graphic).Chunks[ChunkList.Selected.Index]); MyPie.Maximum := 100; MyPie.Value := MulDiv(100, IDATC.Size, ((TIDATAccess(IDATC).GetBufferWidth + 1) * LoadPicture.Height)); CSize.Caption := ' Compressed: ' + inttostr(MyPie.Value) + '%'#13#10 + ChunkList.Selected.subitems[0]; USize.Caption := ' Uncompressed: 100%'#13#10 + inttostr((TIDATAccess(IDATC).GetBufferWidth + 1) * LoadPicture.Height) + ' bytes'; end {If the current selected item is a palette} else if ChunkList.Selected.Caption = 'PLTE' then begin {Select the palette area} Props.PageIndex := 1; {Get palette info} Pal := TChunkPLTE(TPNGImage(LoadPicture.Graphic).Chunks[ChunkList.Selected.Index]).Palette; GetObject(Pal, SIZEOF(WORD), @PalEntries); GetPaletteEntries(Pal, 0, PalEntries, MaxPal.palpalentry); PaletteTitle.Caption := 'Palette entries: ' + inttostr(palentries); {Draw the pallete} x := 0; j := 0; PltePalette.Canvas.Brush.Color := clWhite; PltePalette.Canvas.FillRect(Rect(0, 0, PltePalette.Width, PltePalette.Height)); repeat i := 0; repeat with MaxPal.palPalEntry[x] do PltePalette.Canvas.Brush.Color := RGB(peRed, peGreen, peBlue); PltePalette.Canvas.Rectangle(i, j, i + 10, j + 10); inc(x); inc(i, 10); if x > PalEntries - 1 then goto FInished; until i >= PltePalette.Width; inc(j, 10); until j >= PltePalette.Height; finished: {Repaint the palette area} PaletteAreaPaint(Sender); end else if ChunkList.Selected.Caption = 'IHDR' then begin {Select IHDR page} Props.PageIndex := 2; {Expand all nodes and remove "checks"} FOR i := 0 to IHDR.Items.Count - 1 do begin IHDR.Items[i].Expand(TRUE); if (IHDR.Items[i].ImageIndex = 0) and (IHDR.Items[i].Owner.Count > 1) then begin IHDR.Items[i].ImageIndex := -1; IHDR.Items[i].SelectedIndex := -1; end; end; {Pointer to the IHDR chunk} IHDRC := TChunkIHDR(TPNGImage(LoadPicture.Graphic).Chunks[ChunkList.Selected.Index]); {Compression} IHDR.Items[13].ImageIndex := 0; IHDR.Items[13].SelectedIndex := 0; {Filter set} IHDR.Items[15].ImageIndex := 0; IHDR.Items[15].SelectedIndex := 0; {Filter set} IHDR.Items[19].Text := 'Width: ' + inttostr(IHDRC.Width); {Filter set} IHDR.Items[20].Text := 'Height: ' + inttostr(IHDRC.Height); {Interlacing} if IHDRC.Interlaced = 1 then begin IHDR.Items[17].ImageIndex := 0; IHDR.Items[17].SelectedIndex := 0; end else begin IHDR.Items[18].ImageIndex := 0; IHDR.Items[18].SelectedIndex := 0; end; {Bit depth} CASE IHDRC.BitDepth of 1:begin IHDR.Items[7].ImageIndex := 0; IHDR.Items[7].SelectedIndex := 0; end; 2:begin IHDR.Items[8].ImageIndex := 0; IHDR.Items[8].SelectedIndex := 0; end; 4:begin IHDR.Items[9].ImageIndex := 0; IHDR.Items[9].SelectedIndex := 0; end; 8:begin IHDR.Items[10].ImageIndex := 0; IHDR.Items[10].SelectedIndex := 0; end; 16:begin IHDR.Items[11].ImageIndex := 0; IHDR.Items[11].SelectedIndex := 0; end; end; {Set the color type} CASE IHDRC.ColorType of 0:begin IHDR.Items[1].ImageIndex := 0; IHDR.Items[1].SelectedIndex := 0; end; 2:begin IHDR.Items[2].ImageIndex := 0; IHDR.Items[2].SelectedIndex := 0; end; 3:begin IHDR.Items[3].ImageIndex := 0; IHDR.Items[3].SelectedIndex := 0; end; 4:begin IHDR.Items[4].ImageIndex := 0; IHDR.Items[4].SelectedIndex := 0; end; 6:begin IHDR.Items[5].ImageIndex := 0; IHDR.Items[5].SelectedIndex := 0; end; end; IHDR.ScrollBy(0, -1000); end else Props.PageIndex := 0; end; {When painting the form} procedure TMainForm.FormPaint(Sender: TObject); begin if Loading then exit; FillRect(Canvas.Handle, ClientRect, COLOR_BTNFACE + 1); Canvas.Draw((Width div 2) - (LoadPicture.Width div 2), ((Height) div 2) - (LoadPicture.Height div 2), LoadPicture.Graphic); end; procedure TMainForm.FormResize(Sender: TObject); begin FormPaint(Sender); end; {Reload the last file} procedure TMainForm.ReloadClick(Sender: TObject); begin if Fileexists(LoadFileDialog.Filename) then LoadFromFile(LoadFileDialog.Filename) else Showmessage('No last file loaded!'); end; { TGammaTester } {When the object is being created} constructor TGammaTester.Create(AOwner: TComponent); begin inherited; DoubleBuffered := TRUE; {Create the backbuffer bitmap} Bitmap := TBitmap.Create; {Set 24bits format} with Bitmap do PixelFormat := pf24bit; end; {When the object is being destroyed} destructor TGammaTester.Destroy; begin {Free the backbuffer bitmap} Bitmap.Free; inherited; end; {When the control is being resized} procedure TGammaTester.OnResize(var Message: TWMSize); begin inherited; RecreateBitmap; end; {When the control is being painted} procedure TGammaTester.Paint; begin inherited; Canvas.Draw(0, 0, Bitmap); end; {Redraw the gamma bitmap} procedure TGammaTester.RecreateBitmap; var Line : pRGBLine; x, y : Integer; begin {Set the bitmap size} Bitmap.Width := Width; Bitmap.Height := Height; {Paint each line} for y := 0 to Bitmap.Height - 1 do begin Line := Bitmap.ScanLine[y]; for x := 0 to Bitmap.Width - 1 do begin {Set the line color} with Line^[x] do begin rgbtRed := Table[MulDiv(255, x, Bitmap.Width)]; rgbtGreen := rgbtRed; rgbtBlue := rgbtRed; end; end; end; {Repaint} Paint; end; {When the property gamma is being set} procedure TGammaTester.SetGamma(Value: Double); var I: Integer; begin FOR I := 0 TO 255 DO Table[I] := Round(Power((I / 255), 1 / (Value * 2.2)) * 255); vGamma := Value; RecreateBitmap; end; procedure TMainForm.SaveFileClick(Sender: TObject); var SaveFilters: TEncodeFilterSet; Tempo: Double; begin if LoadPicture.Graphic = nil then begin showmessage('There is no image currently loaded to save.'); exit; end; if SaveFileDialog.Execute then begin Tempo := GetTickCount; with TPNGImage.Create do begin {Test which filters the user selected} // SaveFilters := []; { with SaveSelect.FilterSelect do begin if Items[0].Checked then Include(SaveFilters, efSub); if Items[1].Checked then Include(SaveFilters, efUp); if Items[2].Checked then Include(SaveFilters, efAverage); if Items[3].Checked then Include(SaveFilters, efPaeth); end;} {Set the filters to use} SaveFilters := [efUp]; Filter := SaveFilters; Assign(LoadPicture.Graphic); SaveToFile(SaveFileDialog.Filename); Status.Panels[2].Text := format('%n s', [(GetTickCount - Tempo) / 1000]); free; end; end; end; {When the Text TMEMO for editing the tEXt chunk} {is changed, change the chunk} procedure TMainForm.TextExit(Sender: TObject); var TEXTC: TChunkText; ZTXTC: TChunkZTXT; begin if TPNGIMAGE(LoadPicture.Graphic).Chunks[ChunkList.Selected.Index] is TChunkText then begin {Copy pointer to the chunk} TEXTC := TChunkTEXT(TPNGIMAGE(LoadPicture.Graphic).Chunks[ ChunkList.Selected.Index]); {Change the value} TEXTC.Keyword := Keyword.Text; TEXTC.Text := Text.Lines.Text; ChunkList.Selected.SubItems[0] := inttostr(TEXTC.Size) + ' bytes'; end else begin {Copy pointer to the chunk} ZTXTC := TChunkZTXT(TPNGIMAGE(LoadPicture.Graphic).Chunks[ ChunkList.Selected.Index]); {Change the value} ZTXTC.Keyword := Keyword.Text; ZTXTC.Text := Text.Lines.Text; ChunkList.Selected.SubItems[0] := inttostr(ZTXTC.Size) + ' bytes'; end; end; procedure TMainForm.SaveFileDialogShow(Sender: TObject); var SaveHandle:integer; begin SaveHandle := GetParent(SaveFileDIalog.handle); SetWindowPos(SaveHandle, HWND_TOP, 0, 0, 480, 400, SWP_NOMOVE); end; procedure TMainForm.SpeedButton1Click(Sender: TObject); var MainForm: TForm; EWidth, EHeight: TEdit; StretchPNG: TPNGImage; begin if LoadPicture.Graphic = nil then begin showmessage('There is no image currently loaded to stretch.'); exit; end; MainForm := TForm.Create(Self); with MainForm do begin {Dialog properties} Caption := 'Select the new size:'; BorderStyle := bsDialog; Position := poMainFormCenter; {Size} Width := 200; Height := 150; {Creates the OK button} with TButton.Create(MainForm) do begin Parent := MainForm; Caption := '&Ok'; SetBounds(110, 94, Width, Height); ModalResult := mrOk; end; {Creates the divisor from the buttons and text area} with TBevel.Create(MainForm) do begin Parent := MainForm; SetBounds(10, 84, 180, 2); end; {Creates the width edit} EWidth := TEdit.Create(MainForm); with EWidth do begin {Width label} with TLabel.Create(MainForm) do begin Parent := MainForm; Caption := 'Width:'; SetBounds(10, 20, 50, 20); end; Text := inttostr(LoadPicture.Width); Parent := MainForm; SetBounds(50, 15, 50, 20); end; EHeight := TEdit.Create(MainForm); with EHeight do begin Text := inttostr(LoadPicture.Height); {Height label} with TLabel.Create(MainForm) do begin Parent := MainForm; Caption := 'Height:'; SetBounds(10, 47, 50, 20); end; SetBounds(50, 44, 50, 20); Parent := MainForm; end; {Creates the cancel button} with TButton.Create(MainForm) do begin Parent := MainForm; Caption := '&Cancel'; SetBounds(10, 94, Width, Height); ModalResult := mrOk; end; {Show the dialog} if ShowModal = mrOk then begin StretchPNG := TPNGImage.Create; with StretchPNG do begin Assign(LoadPicture.Graphic); Width := strtointdef(EWidth.Text, LoadPicture.Width); Height := strtointdef(EHeight.Text, LoadPicture.Height); Canvas.StretchDraw(Rect(0, 0, Width, Height), LoadPicture.Graphic); LoadPicture.Assign(StretchPNG); Free; end; end; {Free the dialog} free; end; Repaint; end; end.
{ Oracle Deploy System ver.1.0 (ORDESY) by Volodymyr Sedler aka scribe 2016 Desc: wrap/deploy/save objects of oracle database. No warranty of using this program. Just Free. With bugs, suggestions please write to justscribe@yahoo.com On Github: github.com/justscribe/ORDESY Dialog for wrapping objects from selected base + scheme. } unit uWrap; interface uses // ORDESY Modules uORDESY, uErrorHandle, // Delphi Modules Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TWrapComboBox = class(TComboBox) protected procedure WM_CB_SETCURSEL(var Message: TMessage); message CB_SETCURSEL; end; TfmWrap = class(TForm) cbxItemType: TComboBox; lblItemType: TLabel; pnlMain: TPanel; lbxList: TListBox; btnUpdate: TButton; btnWrap: TButton; btnClose: TButton; lblProject: TLabel; lblModule: TLabel; lblBase: TLabel; lblScheme: TLabel; lblBaseList: TLabel; lblSchemeList: TLabel; procedure btnCloseClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnUpdateClick(Sender: TObject); procedure lbxListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure cbxBaseListSelect(Sender: TObject); procedure cbxSchemeListSelect(Sender: TObject); procedure PrepareGUI; procedure btnWrapClick(Sender: TObject); procedure cbxItemTypeChange(Sender: TObject); procedure lbxListClick(Sender: TObject); private CurrentProject: TORDESYProject; CurrentBase: TOraBase; CurrentScheme: TOraScheme; CurrentType: string; CurrentName: string; CurrentValid: boolean; end; function ShowWrapDialog(aModule: TORDESYModule; aProjectList: TORDESYProjectList): boolean; implementation {$R *.dfm} uses uMain; function ShowWrapDialog(aModule: TORDESYModule; aProjectList: TORDESYProjectList): boolean; var iScheme: TOraScheme; iWrapBase, iWrapScheme: TWrapComboBox; i, n: integer; begin with TfmWrap.Create(Application) do try try Result:= false; PrepareGUI; CurrentProject:= TORDESYProject(aModule.ProjectRef); for n := 0 to pnlMain.ControlCount - 1 do begin if (pnlMain.Controls[n] is TWrapComboBox) and (TWrapComboBox(pnlMain.Controls[n]).Name = 'cbxWrapBase') then iWrapBase:= TWrapComboBox(pnlMain.Controls[n]); if (pnlMain.Controls[n] is TWrapComboBox) and (TWrapComboBox(pnlMain.Controls[n]).Name = 'cbxWrapScheme') then iWrapScheme:= TWrapComboBox(pnlMain.Controls[n]); end; for i := 0 to aProjectList.OraBaseCount - 1 do iWrapBase.Items.AddObject(aProjectList.GetOraBaseNameByIndex(i), aProjectList.GetOraBaseByIndex(i)); if iWrapBase.Items.Count <> 0 then iWrapBase.ItemIndex:= 0; for i := 0 to aProjectList.OraSchemeCount - 1 do iWrapScheme.Items.AddObject(aProjectList.GetOraSchemeLoginByIndex(i), aProjectList.GetOraSchemeByIndex(i)); if iWrapScheme.Items.Count <> 0 then iWrapScheme.ItemIndex:= 0; lblProject.Caption:= 'Project: ' + CurrentProject.Name; lblModule.Caption:= 'Module: ' + aModule.Name; if Assigned(CurrentBase) then lblBase.Caption:= 'Base: ' + CurrentBase.Name; if Assigned(CurrentScheme) then lblScheme.Caption:= 'Scheme: ' + CurrentScheme.Login; except on E: Exception do HandleError([ClassName, 'ShowWrapDialog', E.Message]); end; if ShowModal = mrOk then begin try Result:= CurrentProject.WrapItem(aModule.Id, CurrentBase.Id, CurrentScheme.Id, CurrentName, TOraItem.GetItemType(CurrentType), CurrentValid); except on E: Exception do HandleError([ClassName, 'WrapItem', E.Message]); end; end; finally Free; end; end; procedure TfmWrap.btnCloseClick(Sender: TObject); begin Close; end; procedure TfmWrap.btnUpdateClick(Sender: TObject); begin try if Assigned(CurrentProject) and Assigned(CurrentBase) and Assigned(CurrentScheme) then begin CurrentScheme.Connect(CurrentBase.Id); CurrentScheme.GetItemList(TOraItem.GetItemType(cbxItemType.Items[cbxItemType.ItemIndex]), lbxList.Items); end; except on E: Exception do HandleError([ClassName, 'btnUpdateClick', E.Message]); end; end; procedure TfmWrap.btnWrapClick(Sender: TObject); begin if not Assigned(CurrentProject) or not Assigned(CurrentBase) or not Assigned(CurrentScheme) or (CurrentType = '') or (CurrentName = '') then ModalResult:= mrNone; end; procedure TfmWrap.cbxBaseListSelect(Sender: TObject); begin if (Sender is TWrapComboBox) and (TWrapComboBox(Sender).Items.Count > 0) and (TWrapComboBox(Sender).Items.Objects[TWrapComboBox(Sender).ItemIndex] <> nil) and (TObject(TWrapComboBox(Sender).Items.Objects[TWrapComboBox(Sender).ItemIndex]) is TOraBase) then begin CurrentBase:= TOraBase(TWrapComboBox(Sender).Items.Objects[TWrapComboBox(Sender).ItemIndex]); lblBase.Caption:= 'Base: ' + CurrentBase.Name; end; end; procedure TfmWrap.cbxItemTypeChange(Sender: TObject); begin try if (cbxItemType.Items.Count > 0) and (cbxItemType.ItemIndex >= 0) and (cbxItemType.ItemIndex < cbxItemType.Items.Count) then CurrentType:= cbxItemType.Items.Strings[cbxItemType.ItemIndex] else CurrentType:= ''; except on E: Exception do HandleError([ClassName, 'cbxItemTypeChange', E.Message]); end; end; procedure TfmWrap.cbxSchemeListSelect(Sender: TObject); begin try if (Sender is TWrapComboBox) and (TWrapComboBox(Sender).Items.Count > 0) and (TWrapComboBox(Sender).Items.Objects[TWrapComboBox(Sender).ItemIndex] <> nil) and (TObject(TWrapComboBox(Sender).Items.Objects[TWrapComboBox(Sender).ItemIndex]) is TOraScheme) then begin CurrentScheme:= TOraScheme(TWrapComboBox(Sender).Items.Objects[TWrapComboBox(Sender).ItemIndex]); lblScheme.Caption:= Format('Scheme: %s', [CurrentScheme.Login]); end; except on E: Exception do HandleError([ClassName, 'cbxSchemeListSelect', E.Message]); end; end; procedure TfmWrap.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:= caFree; end; procedure TfmWrap.lbxListClick(Sender: TObject); begin try if (lbxList.Count > 0) and (lbxList.ItemIndex >= 0) and (lbxList.ItemIndex < lbxList.Count) then begin CurrentName:= lbxList.Items.Strings[lbxList.ItemIndex]; CurrentValid:= TOraItemHead(lbxList.Items.Objects[lbxList.ItemIndex]).Valid; end else begin CurrentName:= ''; CurrentValid:= false; end; except on E: Exception do HandleError([ClassName, 'lbxListClick', E.Message]); end; end; procedure TfmWrap.lbxListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var IItem: TOraItemHead; ValidIcon: TBitmap; NotValidIcon: TIcon; begin try if (Assigned(lbxList.Items.Objects[Index])) and (lbxList.Items.Objects[Index] is TOraItemHead) then begin try ValidIcon:= TBitmap.Create; NotValidIcon:= TIcon.Create; fmMain.imlMain.GetIcon(1, NotValidIcon); IItem:= TOraItemHead(lbxList.Items.Objects[Index]); case IItem.ItemType of OraProcedure: begin fmMain.imlMain.GetBitmap(15, ValidIcon); end; OraFunction: begin fmMain.imlMain.GetBitmap(14, ValidIcon); end; OraPackage: begin fmMain.imlMain.GetBitmap(9, ValidIcon); end; end; if not IItem.Valid then ValidIcon.Canvas.Draw(0, 0, NotValidIcon); lbxList.ItemHeight:= ValidIcon.Height + 2; lbxList.Canvas.FillRect(Rect); lbxList.Canvas.Draw(1, Rect.Top + 1, ValidIcon); lbxList.Canvas.TextOut(20, Rect.Top + ((lbxList.ItemHeight div 2) - (Canvas.TextHeight('A') div 2)), lbxList.Items[Index]); finally ValidIcon.Free; NotValidIcon.Free; end; end; except on E: Exception do HandleError([ClassName, 'lbxListDrawItem', E.Message]); end; end; procedure TfmWrap.PrepareGUI; var cbxWrapBase: TWrapComboBox; cbxWrapScheme: TWrapComboBox; begin cbxWrapBase:= TWrapComboBox.Create(Self); cbxWrapBase.Anchors:= [akLeft, akTop]; cbxWrapBase.Name:= 'cbxWrapBase'; cbxWrapBase.OnChange:= cbxBaseListSelect; cbxWrapBase.Left:= 8; cbxWrapBase.Top:= 27; cbxWrapBase.Width:= 150; cbxWrapBase.Height:= 21; cbxWrapBase.Style:= csDropDownList; cbxWrapBase.Visible:= true; cbxWrapBase.Parent:= pnlMain; // cbxWrapScheme:= TWrapComboBox.Create(Self); cbxWrapScheme.Anchors:= [akLeft, akTop]; cbxWrapScheme.Name:= 'cbxWrapScheme'; cbxWrapScheme.OnChange:= cbxSchemeListSelect; cbxWrapScheme.Left:= 162; cbxWrapScheme.Top:= 27; cbxWrapScheme.Width:= 150; cbxWrapScheme.Height:= 21; cbxWrapScheme.Style:= csDropDownList; cbxWrapScheme.Visible:= true; cbxWrapScheme.Parent:= pnlMain; // CurrentType:= 'PROCEDURE'; end; { TWrapComboBox } procedure TWrapComboBox.WM_CB_SETCURSEL(var Message: TMessage); begin inherited; if Assigned(OnChange) then OnChange(Self); end; end.
unit SQLiteTemplate; interface uses System.Generics.Collections, HGM.SQLite, SQLiteHGM, HGM.SQLang; type TMyRecord = record ID: Integer; Name: string; Desc: string; DateCreate: TDateTime; //procedure SetFromTable(Table: TSQLiteTable); end; TMyTable = class(TList<TMyRecord>) const tnTableName = 'my_table'; fnID = 'mtID'; fnName = 'mtName'; fnDesc = 'mtDesc'; fnDateCreate = 'mtCreate'; private FDB: TDB; public constructor Create(ADB: TDB); destructor Destroy; override; procedure Load; //Загрузка данных из базы procedure Update(var Item: TMyRecord); overload; //Обновление/Вставка записи в таблицу procedure Update(Index: Integer); overload; //Обновление/Вставка записи в таблицу procedure Delete(Index: Integer); //Удаление по порядковому номеру в списке из базы procedure DeleteByID(ID: Integer); //Удаление по ИД записи из базы procedure Drop; //Очистка таблицы (не фактический Drop) procedure Save; //Сохранение таблицы (Обновление измененых записей, добавление новых) end; implementation { TMyTable } constructor TMyTable.Create(ADB: TDB); begin inherited Create; FDB := ADB; if not FDB.DB.TableExists(tnTableName) then begin with SQL.CreateTable(tnTableName) do begin AddField(fnID, ftInteger, True, True); AddField(fnName, ftString); AddField(fnDesc, ftString); AddField(fnDateCreate, ftDateTime); FDB.DB.ExecSQL(GetSQL); EndCreate; end; end; end; destructor TMyTable.Destroy; begin Clear; inherited; end; procedure TMyTable.Load; var Table: TSQLiteTable; Item: TMyRecord; begin Clear; with SQL.Select(tnTableName, [fnID, fnName, fnDesc, fnDateCreate]) do begin OrderBy(fnName, True); Table := FDB.DB.GetTable(GetSQL); EndCreate; Table.MoveFirst; while not Table.EOF do begin Item.ID := Table.FieldAsInteger(fnID); Item.Name := Table.FieldAsString(fnName); Item.Desc := Table.FieldAsString(fnDesc); Item.DateCreate := Table.FieldAsDateTime(fnDateCreate); Add(Item); Table.Next; end; Table.Free; end; end; procedure TMyTable.Update(Index: Integer); var Item: TMyRecord; begin Item := Items[Index]; Update(Item); Items[Index] := Item; end; procedure TMyTable.Update(var Item: TMyRecord); {var Mem: TMemoryStream;} begin if Item.ID < 0 then with SQL.InsertInto(tnTableName) do begin AddValue(fnName, Item.Name); AddValue(fnDesc, Item.Desc); AddValue(fnDateCreate, Item.DateCreate); FDB.DB.ExecSQL(GetSQL); Item.ID := FDB.DB.GetLastInsertRowID; EndCreate; end else with SQL.Update(tnTableName) do begin AddValue(fnName, Item.Name); AddValue(fnDesc, Item.Desc); AddValue(fnDateCreate, Item.DateCreate); WhereFieldEqual(fnID, Item.ID); FDB.DB.ExecSQL(GetSQL); EndCreate; end; {if Assigned(Item.Image) then with SQL.UpdateBlob(tnTableName, fnImage) do begin WhereFieldEqual(fnID, Item.ID); Item.Image.SaveToStream(Mem); DataBase.DB.UpdateBlob(GetSQL, Mem); Mem.Free; EndCreate; end; } end; procedure TMyTable.Delete(Index: Integer); begin with SQL.Delete(tnTableName) do begin WhereFieldEqual(fnID, Items[Index].ID); FDB.DB.ExecSQL(GetSQL); EndCreate; end; inherited; end; procedure TMyTable.DeleteByID(ID: Integer); var i: Integer; begin for i := 0 to Count - 1 do begin if Items[i].ID = ID then begin Delete(i); Exit; end; end; end; procedure TMyTable.Drop; begin Clear; with SQL.Delete(tnTableName) do begin FDB.DB.ExecSQL(GetSQL); EndCreate; end; end; procedure TMyTable.Save; var i: Integer; Item: TMyRecord; begin for i := 0 to Count - 1 do begin Item := Items[i]; Update(Item); Items[i] := Item; end; end; end.
unit UDaoCondicaoPagamento; interface uses uDao, DB, SysUtils, Messages, UCondicaoPagamento, UDaoFormaPagamento; type DaoCondicaoPagamento = class(Dao) private protected umCondicaoPagamento : CondicaoPagamento; umaDaoFormaPagamento : DaoFormaPagamento; public Constructor CrieObjeto; Destructor Destrua_se; function Salvar(obj:TObject): string; override; function GetDS : TDataSource; override; function Carrega(obj:TObject): TObject; override; function Buscar(obj : TObject) : Boolean; override; function Excluir(obj : TObject) : string ; override; procedure AtualizaGrid; procedure Ordena(campo: string); end; implementation { DaoCondicaoPagamento } function DaoCondicaoPagamento.Buscar(obj: TObject): Boolean; var prim: Boolean; sql, e, onde: string; umCondicaoPagamento: CondicaoPagamento; begin e := ' and '; onde := ' where'; prim := true; umCondicaoPagamento := CondicaoPagamento(obj); sql := 'select * from condicaopagamento'; if umCondicaoPagamento.getId <> 0 then begin if prim then //SE FOR O PRIMEIRO, SETA COMO FLAG COMO FALSO PQ É O PRIMEIRO begin prim := false; sql := sql+onde; end else //SE NAO, COLOCA CLAUSULA AND PARA JUNTAR CONDIÇOES sql := sql+e; sql := sql+' idcondicaopagamento = '+inttostr(umCondicaoPagamento.getId); //COLOCA CONDIÇAO NO SQL end; if umCondicaoPagamento.getDescricao <> '' then begin if prim then begin prim := false; sql := sql+onde; end else sql := sql+e; sql := sql+' descricao like '+quotedstr('%'+umCondicaoPagamento.getDescricao+'%'); end; if umCondicaoPagamento.getUmaFormaPagamento.getId <> 0 then begin if prim then begin prim := false; sql := sql+onde; end else sql := sql+e; sql := sql+' idformapagamento = '+inttostr(umCondicaoPagamento.getUmaFormaPagamento.getId); end; with umDM do begin QCondicaoPagamento.Close; QCondicaoPagamento.sql.Text := sql+' order by idcondicaopagamento'; QCondicaoPagamento.Open; if QCondicaoPagamento.RecordCount > 0 then result := True else result := false; end; end; procedure DaoCondicaoPagamento.AtualizaGrid; begin with umDM do begin QCondicaoPagamento.Close; QCondicaoPagamento.sql.Text := 'select * from condicaopagamento order by idcondicaopagamento'; QCondicaoPagamento.Open; end; end; function DaoCondicaoPagamento.Carrega(obj: TObject): TObject; var umaCondicaoPagamento: CondicaoPagamento; I : Integer; begin umaCondicaoPagamento := CondicaoPagamento(obj); with umDM do begin if not QCondicaoPagamento.Active then QCondicaoPagamento.Open; if umaCondicaoPagamento.getId <> 0 then begin QCondicaoPagamento.Close; QCondicaoPagamento.SQL.Text := 'select * from condicaopagamento where idcondicaopagamento = '+IntToStr(umaCondicaoPagamento.getId); QCondicaoPagamento.Open; end; umaCondicaoPagamento.setId(QCondicaoPagamentoidcondicaopagamento.AsInteger); umaCondicaoPagamento.setDescricao(QCondicaoPagamentodescricao.AsString); umaCondicaoPagamento.setDataCadastro(QCondicaoPagamentodatacadastro.AsDateTime); umaCondicaoPagamento.setDataAlteracao(QCondicaoPagamentodataalteracao.AsDateTime); // Busca a Forma de Pagamento referente ao Condicao de Pagamento umaCondicaoPagamento.getumaFormaPagamento.setId(QCondicaoPagamentoidformapagamento.AsInteger); umaDaoFormaPagamento.Carrega(umaCondicaoPagamento.getumaFormaPagamento); //Carrega as Parcelas QParcelas.Close; QParcelas.SQL.Text := 'select * from parcelas where idcondicaopagamento = '+IntToStr(umaCondicaoPagamento.getId); QParcelas.Open; QParcelas.First; for i := 0 to UmaCondicaoPagamento.P - 1 do UmaCondicaoPagamento.removeParcela; while not QParcelas.Eof do begin UmaCondicaoPagamento.addParcela; UmaCondicaoPagamento.getParcela.setNumParcela(QParcelasnumparcela.AsInteger); UmaCondicaoPagamento.getParcela.setDias(QParcelasnumdias.AsInteger); UmaCondicaoPagamento.getParcela.setPorcentagem(QParcelasporcentagem.AsFloat); QParcelas.Next; end; end; result := umCondicaoPagamento; Self.AtualizaGrid; end; constructor DaoCondicaoPagamento.CrieObjeto; begin inherited; umaDaoFormaPagamento := DaoFormaPagamento.CrieObjeto; end; destructor DaoCondicaoPagamento.Destrua_se; begin inherited; end; function DaoCondicaoPagamento.Excluir(obj: TObject): string; var umaCondicaoPagamento: CondicaoPagamento; i : integer; begin umaCondicaoPagamento := CondicaoPagamento(obj); with umDM do begin try beginTrans; QParcelas.SQL := UpdateParcelas.DeleteSQL; QParcelas.Params.ParamByName('OLD_idcondicaopagamento').Value := umaCondicaoPagamento.getId; QCondicaoPagamento.SQL := UpdateCondicaoPagamento.DeleteSQL; QCondicaoPagamento.Params.ParamByName('OLD_idcondicaopagamento').Value := umaCondicaoPagamento.getId; QParcelas.ExecSQL; QCondicaoPagamento.ExecSQL; Commit; result := 'CondicaoPagamento excluída com sucesso!'; except on e:Exception do begin rollback; if pos('violates foreign key',e.Message)>0 then result := 'Ocorreu um erro! A CondicaoPagamento não pode ser excluída pois ja está sendo usado pelo sistema.' else result := 'Ocorreu um erro! CondicaoPagamento não foi excluída. Erro: '+e.Message; end; end; end; Self.AtualizaGrid; end; function DaoCondicaoPagamento.GetDS: TDataSource; begin result := umDM.DSCondicaoPagamento; end; procedure DaoCondicaoPagamento.Ordena(campo: string); begin umDM.QCondicaoPagamento.IndexFieldNames := campo; end; function DaoCondicaoPagamento.Salvar(obj: TObject): string; var umaCondicaoPagamento : CondicaoPagamento; i : Integer; begin umaCondicaoPagamento := CondicaoPagamento(obj); with umDM do begin try beginTrans; QCondicaoPagamento.Close; if umaCondicaoPagamento.getId = 0 then QCondicaoPagamento.SQL := UpdateCondicaoPagamento.InsertSQL else begin QParcelas.SQL := UpdateParcelas.DeleteSQL; QParcelas.Params.ParamByName('OLD_idcondicaopagamento').Value := umaCondicaoPagamento.getId; QParcelas.ExecSQL; QCondicaoPagamento.SQL := UpdateCondicaoPagamento.ModifySQL; QCondicaoPagamento.Params.ParamByName('OLD_idcondicaopagamento').Value := umaCondicaoPagamento.getId; end; QCondicaoPagamento.Params.ParamByName('descricao').Value := umaCondicaoPagamento.getDescricao; QCondicaoPagamento.Params.ParamByName('idformapagamento').Value := umaCondicaoPagamento.getUmaFormaPagamento.getId; QCondicaoPagamento.Params.ParamByName('datacadastro').Value := umaCondicaoPagamento.getDataCadastro; QCondicaoPagamento.Params.ParamByName('dataalteracao').Value := umaCondicaoPagamento.getDataAlteracao; QCondicaoPagamento.ExecSQL; if umaCondicaoPagamento.getId = 0 then begin QGenerica.Close; QGenerica.SQL.Text := 'Select last_value as idcondicaopagamento from idcondicaopagamento_seq'; QGenerica.Open; umaCondicaoPagamento.setId(QGenerica.Fields.FieldByName('idcondicaopagamento').Value); end; for i := 0 to umaCondicaoPagamento.p - 1 do begin QParcelas.SQL := UpdateParcelas.InsertSQL; QParcelas.Params.ParamByName('idcondicaopagamento').Value := umaCondicaoPagamento.getId; QParcelas.Params.ParamByName('numparcela').Value := umaCondicaoPagamento.getParcela(i).getNumParcela; QParcelas.Params.ParamByName('numdias').Value := umaCondicaoPagamento.getParcela(i).getDias; QParcelas.Params.ParamByName('porcentagem').Value := umaCondicaoPagamento.getParcela(i).getPorcentagem; QParcelas.ExecSQL; end; Commit; result := 'Condição de Pagamento salva com sucesso!'; except on e: Exception do begin rollback; Result := 'Ocorreu um erro! A Condição de Pagamento não foi salva. Erro: '+e.Message; end; end; end; Self.AtualizaGrid; end; end.
{: GLTextureImageEditors<p> Standard texture image editors for standard texture image classes.<p> <b>History : </b><font size=-1><ul> <li>10/11/12 - PW - Added CPPB compatibility: used dummy method instead abstract class function Edit for GLS_CPPB <li>22/01/10 - Yar - Added to TGLBlankImage property editor ability to set the depth <li>03/07/04 - LR - Make change for Linux <li>24/07/03 - EG - Creation </ul></font> } unit GLTextureImageEditors; interface {$i GLScene.inc} uses Classes, SysUtils, GLTexture, GLProcTextures; type // TGLTextureImageEditor // TGLTextureImageEditor = class(TObject) public { Public Properties } {: Request to edit a textureImage.<p> Returns True if changes have been made.<br> This method may be invoked from the IDE or at run-time. } class function Edit(aTexImage : TGLTextureImage) : Boolean; virtual; end; TGLTextureImageEditorClass = class of TGLTextureImageEditor; // TGLBlankTIE // TGLBlankTIE = class(TGLTextureImageEditor) public { Public Properties } class function Edit(aTexImage : TGLTextureImage) : Boolean; override; end; // TGLPersistentTIE // TGLPersistentTIE = class(TGLTextureImageEditor) public { Public Properties } class function Edit(aTexImage : TGLTextureImage) : Boolean; override; end; // TGLPicFileTIE // TGLPicFileTIE = class(TGLTextureImageEditor) public { Public Properties } class function Edit(aTexImage : TGLTextureImage) : Boolean; override; end; // TGLProcTextureNoiseTIE // TGLProcTextureNoiseTIE = class(TGLTextureImageEditor) public { Public Properties } class function Edit(aTexImage : TGLTextureImage) : Boolean; override; end; //: Invokes the editor for the given TGLTextureImage function EditGLTextureImage(aTexImage : TGLTextureImage) : Boolean; procedure RegisterGLTextureImageEditor(aTexImageClass : TGLTextureImageClass; texImageEditor : TGLTextureImageEditorClass); procedure UnRegisterGLTextureImageEditor(texImageEditor : TGLTextureImageEditorClass); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ uses GLCrossPlatform, GLUtils; var vTIEClass, vTIEEditor : TList; // Dummy method for CPP // class function TGLTextureImageEditor.Edit(ATexImage: TGLTextureImage): Boolean; begin Result := True; end; // EditGLTextureImage // function EditGLTextureImage(aTexImage : TGLTextureImage) : Boolean; var i : Integer; editor : TGLTextureImageEditorClass; begin if Assigned(vTIEClass) then begin i:=vTIEClass.IndexOf(Pointer(aTexImage.ClassType)); if i>=0 then begin editor:=TGLTextureImageEditorClass(vTIEEditor[i]); Result:=editor.Edit(aTexImage); Exit; end; end; InformationDlg(aTexImage.ClassName+': editing not supported.'); Result:=False; end; // RegisterGLTextureImageEditor // procedure RegisterGLTextureImageEditor(aTexImageClass : TGLTextureImageClass; texImageEditor : TGLTextureImageEditorClass); begin if not Assigned(vTIEClass) then begin vTIEClass:=TList.Create; vTIEEditor:=TList.Create; end; vTIEClass.Add(Pointer(aTexImageClass)); vTIEEditor.Add(texImageEditor); end; // UnRegisterGLTextureImageEditor // procedure UnRegisterGLTextureImageEditor(texImageEditor : TGLTextureImageEditorClass); var i : Integer; begin if Assigned(vTIEClass) then begin i:=vTIEEditor.IndexOf(texImageEditor); if i>=0 then begin vTIEClass.Delete(i); vTIEEditor.Delete(i); end; end; end; // ------------------ // ------------------ TGLBlankTIE ------------------ // ------------------ // Edit // class function TGLBlankTIE.Edit(aTexImage : TGLTextureImage) : Boolean; var p1, p2 : Integer; buf, part : String; texImage : TGLBlankImage; begin texImage:=(aTexImage as TGLBlankImage); if texImage.Depth=0 then buf:=InputDlg('Blank Image', 'Enter size', Format('%d x %d', [texImage.Width, texImage.Height])) else buf:=InputDlg('Blank Image', 'Enter size', Format('%d x %d x %d', [texImage.Width, texImage.Height, texImage.Depth])); p1:=Pos('x', buf); if p1>0 then begin texImage.Width:=StrToIntDef(Trim(Copy(buf, 1, p1-1)), 256); part := Copy(buf, p1+1, MaxInt); p2:=Pos('x', part); if p2>0 then begin texImage.Height:=StrToIntDef(Trim(Copy(part, 1, p2-1)), 256); texImage.Depth:=StrToIntDef(Trim(Copy(part, p2+1, MaxInt)), 1) end else begin texImage.Height:=StrToIntDef(Trim(Copy(buf, p1+1, MaxInt)), 256); texImage.Depth:=0; end; Result:=True; end else begin InformationDlg('Invalid size'); Result:=False; end; end; // ------------------ // ------------------ TGLPersistentTIE ------------------ // ------------------ // Edit // class function TGLPersistentTIE.Edit(aTexImage : TGLTextureImage) : Boolean; var fName : String; begin fName:=''; Result:=OpenPictureDialog(fName); if Result then begin aTexImage.LoadFromFile(fName); aTexImage.NotifyChange(aTexImage); end; end; // ------------------ // ------------------ TGLPicFileTIE ------------------ // ------------------ // Edit // class function TGLPicFileTIE.Edit(aTexImage : TGLTextureImage) : Boolean; var newName : String; texImage : TGLPicFileImage; begin { TODO : A better TGLPicFileImage.Edit is needed... } texImage:=(aTexImage as TGLPicFileImage); newName:=InputDlg('PicFile Image', 'Enter filename', texImage.PictureFileName); Result:=(texImage.PictureFileName<>newName); if Result then texImage.PictureFileName:=newName end; // Edit // class function TGLProcTextureNoiseTIE.Edit(aTexImage : TGLTextureImage) : Boolean; var p : Integer; buf : String; begin with aTexImage as TGLProcTextureNoise do begin buf:=InputDlg(TGLProcTextureNoise.FriendlyName, 'Enter size', Format('%d x %d', [Width, Height])); p:=Pos('x', buf); if p>0 then begin Width:=StrToIntDef(Trim(Copy(buf, 1, p-1)), 256); Height:=StrToIntDef(Trim(Copy(buf, p+1, MaxInt)), 256); buf:=InputDlg(TGLProcTextureNoise.FriendlyName, 'Minimum Cut', IntToStr(MinCut)); MinCut := StrToIntDef(buf, 0); buf:=InputDlg(TGLProcTextureNoise.FriendlyName, 'Noise Sharpness', FloatToStr(NoiseSharpness)); NoiseSharpness := GLUtils.StrToFloatDef(buf, 0.9); buf:=InputDlg(TGLProcTextureNoise.FriendlyName, 'Random Seed', IntToStr(NoiseRandSeed)); NoiseRandSeed := StrToIntDef(buf, 0); RandSeed := NoiseRandSeed; buf := InputDlg(TGLProcTextureNoise.FriendlyName, 'Generate Seamless Texture (0,1)', IntToStr(Ord(Seamless))); Seamless := (buf<>'0'); Result:=True; Invalidate; end else begin InformationDlg('Invalid size'); Result:=False; end; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterGLTextureImageEditor(TGLBlankImage, TGLBlankTIE); RegisterGLTextureImageEditor(TGLPersistentImage, TGLPersistentTIE); RegisterGLTextureImageEditor(TGLPicFileImage, TGLPicFileTIE); RegisterGLTextureImageEditor(TGLProcTextureNoise, TGLProcTextureNoiseTIE); finalization UnRegisterGLTextureImageEditor(TGLBlankTIE); UnRegisterGLTextureImageEditor(TGLPersistentTIE); UnRegisterGLTextureImageEditor(TGLPicFileTIE); UnRegisterGLTextureImageEditor(TGLProcTextureNoiseTIE); FreeAndNil(vTIEClass); FreeAndNil(vTIEEditor); end.
unit uDrawingPage; interface uses uBase, uGraphicPrimitive, Windows, Graphics, GdiPlus, SysUtils, uExceptions, System.Generics.Collections; type TDrawingPage = class(TBaseObject) private FRoot: TBackground; // рамка выделения мышкой FSelect : TSelectArea; FNeedToDrawSelect : boolean; // нормальная битмапка FBitMap: TBitMap; FGraphics: IGPGraphics; // битмапка для быстрого поиска примитивов по координатам мыши FFakeBitMap : TBitMap; FFakeGraphics : IGPGraphics; FSelectedPrimitivs : TList<TGraphicPrimitive>; function GetPrimitiveByIndexColor( const aIndexColor : TColor ) : TGraphicPrimitive; procedure GetPrimitives( var aPrimitives : TGraphicPrimitives ); public constructor Create; destructor Destroy; override; procedure NewSize(const aWidth, aHeight: integer); function GetBitmap: TBitMap; function GetPrimitiveByCoord( const aX, aY : integer ) : TGraphicPrimitive; function GetPrimitiveByID( const aID : string ) : TGraphicPrimitive; function AddPrimitive( const aX, aY : integer; const aType : TPrimitiveType ) : TGraphicPrimitive; procedure SelectOnePrimitive( const aPrim : TGraphicPrimitive ); procedure UnSelectAll; procedure ChangeSelectedPos( const aDX, aDY : integer ); property RootPrimitive: TBackground read FRoot; property SelectAreaPrimitive : TSelectArea read FSelect; property NeedToDrawSelect : boolean read FNeedToDrawSelect write FNeedToDrawSelect; end; function PrimitiveFactory( const aPage : TDrawingPage; const aType : TPrimitiveType ) : TGraphicPrimitive; implementation const PrimitivesClasses : array [ TPrimitiveType ] of TGraphicPrimitiveClass = ( nil, TBox ); function PrimitiveFactory( const aPage : TDrawingPage; const aType : TPrimitiveType ) : TGraphicPrimitive; begin if not Assigned( PrimitivesClasses[ aType ] ) then ContractFailure; Result := PrimitivesClasses[ aType ].Create( aPage.RootPrimitive ); end; { TDrawingPage } function TDrawingPage.AddPrimitive( const aX, aY : integer; const aType : TPrimitiveType ): TGraphicPrimitive; begin Result := PrimitiveFactory( Self, aType ); end; procedure TDrawingPage.ChangeSelectedPos(const aDX, aDY: integer); var i : integer; begin for I := 0 to FSelectedPrimitivs.Count - 1 do begin FSelectedPrimitivs[i].ChangePos( aDX, aDY ); end; end; constructor TDrawingPage.Create; begin inherited Create; FBitMap := TBitMap.Create; FBitMap.PixelFormat := pf24bit; FFakeBitMap := TBitmap.Create; FFakeBitMap.PixelFormat := pf24bit; FGraphics := nil; FFakeGraphics := nil; NewSize(0, 0); // создадим Graphics FRoot := TBackground.Create(nil); FRoot.Points.Add( 0, 0 ); FSelect := TSelectArea.Create(nil); FNeedToDrawSelect := false; FSelectedPrimitivs := TList<TGraphicPrimitive>.Create; end; destructor TDrawingPage.Destroy; begin FGraphics := nil; FreeAndNil(FBitMap); FreeAndNil(FRoot); FreeAndNil(FSelect); FreeAndNil(FSelectedPrimitivs); inherited; end; function TDrawingPage.GetBitmap: TBitMap; var Prims : TGraphicPrimitives; i : integer; begin FRoot.Points.Point[0] := TPoint.Create( FBitMap.Width, FBitMap.Height ); GetPrimitives( Prims ); try for I := 0 to length( Prims ) - 1 do begin Prims[i].DrawNormal( FGraphics ); Prims[i].DrawIndex( FFakeGraphics ); end; finally Setlength( Prims, 0 ); end; if FNeedToDrawSelect then FSelect.DrawNormal( FGraphics ); Result := FBitMap; end; function TDrawingPage.GetPrimitiveByCoord(const aX, aY: integer): TGraphicPrimitive; begin if ( aX > FFakeBitMap.Width ) or ( aY > FFakeBitMap.Height ) then begin Result := FRoot; exit; end; Result := GetPrimitiveByIndexColor( FFakeBitMap.Canvas.Pixels[ aX, aY ] ); if Result = nil then Result := FRoot; end; function TDrawingPage.GetPrimitiveByID(const aID: string): TGraphicPrimitive; function FindPrimitive ( const aParent : TGraphicPrimitive; const aID : string ) : TGraphicPrimitive; var i : integer; Child : TGraphicPrimitive; begin Result := nil; for I := 0 to aParent.ChildCount-1 do begin Child := aParent.Child[i]; if SameStr( Child.IDAsStr, aID ) then begin Result := Child; exit; end; if Child.ChildCount > 0 then begin Result := FindPrimitive( Child, aID ); end; end; end; begin if SameStr( FRoot.IDAsStr, aID ) then Result := FRoot else Result := FindPrimitive( FRoot, aID ); end; function TDrawingPage.GetPrimitiveByIndexColor( const aIndexColor: TColor): TGraphicPrimitive; function FindByColor( const aPrimitive : TGraphicPrimitive; const aColor : TColor ) : TGraphicPrimitive; var i : integer; Prim : TGraphicPrimitive; begin Result := nil; for i := 0 to aPrimitive.ChildCount - 1 do begin Prim := aPrimitive.Child[i]; if Prim.IndexColor = aColor then begin Result := Prim; exit; end; if Prim.ChildCount > 0 then Result := FindByColor( Prim, aColor ); end; end; begin if FRoot.IndexColor = aIndexColor then begin Result := FRoot; end else begin Result := FindByColor( FRoot, aIndexColor ); end; end; procedure TDrawingPage.GetPrimitives( var aPrimitives : TGraphicPrimitives ); type TByPassProc = reference to procedure ( const aPrim : TGraphicPrimitive; var aList : TGraphicPrimitives ); var Proc : TByPassProc; i : integer; begin i := 0; Proc := procedure ( const aPrim : TGraphicPrimitive; var aList : TGraphicPrimitives ) var j : integer; begin if length( aList ) >= i then begin Setlength( aList, i + 10 ); end; aList[i] := aPrim; inc( i ); if aPrim.ChildCount > 0 then begin for j := 0 to aPrim.ChildCount - 1 do Proc( aPrim.Child[j], aList ); end; end; Proc( FRoot, aPrimitives ); Setlength( aPrimitives, i ); end; procedure TDrawingPage.NewSize(const aWidth, aHeight: integer); begin FBitMap.Width := aWidth; FBitMap.Height := aHeight; FGraphics := TGPGraphics.FromHDC( FBitMap.Canvas.Handle ); FFakeBitMap.Width := aWidth; FFakeBitMap.Height := aHeight; FFakeGraphics := TGPGraphics.FromHDC( FFakeBitMap.Canvas.Handle ); end; procedure TDrawingPage.SelectOnePrimitive(const aPrim: TGraphicPrimitive); begin UnSelectAll; FSelectedPrimitivs.Add( aPrim ); TBorder.Create( aPrim ); end; procedure TDrawingPage.UnSelectAll; var i : integer; Prim : TGraphicPrimitive; begin for I := 0 to FSelectedPrimitivs.Count-1 do begin Prim := FSelectedPrimitivs[i]; Prim.RemoveAllChildren; end; FSelectedPrimitivs.Clear; end; end.
unit ReleaseRecipient; interface uses Recipient; type TReleaseMethod = class private FId: string; FName: string; public property Id: string read FId write FId; property Name: string read FName write FName; constructor Create(const id: string; const name: string); end; type TReleaseRecipient = class(TObject) private FRecipient: TRecipient; FLocationCode: string; FLocationName: string; FReleaseMethod: TReleaseMethod; FAmount: currency; FDate: TDate; public property Recipient: TRecipient read FRecipient write FRecipient; property LocationCode: string read FLocationCode write FLocationCode; property LocationName: string read FLocationName write FLocationName; property ReleaseMethod: TReleaseMethod read FReleaseMethod write FReleaseMethod; property Amount: currency read FAmount write FAmount; property Date: TDate read FDate write FDate; constructor Create; overload; constructor Create(const rpt: TRecipient; rm: TReleaseMethod; const locCode, locName: string; const amt: currency; const dt: TDate); overload; end; var rrp: TReleaseRecipient; implementation constructor TReleaseMethod.Create(const id: string; const name: string); begin FId := id; FName := name; end; constructor TReleaseRecipient.Create; begin inherited; end; constructor TReleaseRecipient.Create(const rpt: TRecipient; rm: TReleaseMethod; const locCode, locName: string; const amt: currency; const dt: TDate); begin FRecipient := rpt; FLocationCode := locCode; FLocationName := locName; FReleaseMethod := rm; FAmount := amt; FDate := dt; end; end.
inherited QueryBodyData: TQueryBodyData inherited Label1: TLabel Width = 63 Caption = 'BodyData' ExplicitWidth = 63 end inherited FDQuery: TFDQuery UpdateOptions.AssignedValues = [uvRefreshMode] UpdateOptions.RefreshMode = rmAll UpdateObject = FDUpdateSQL SQL.Strings = ( 'select ' ' ID,' ' IDProducer,' ' IDBody,' ' BodyData' 'from BodyData') end object FDUpdateSQL: TFDUpdateSQL InsertSQL.Strings = ( 'INSERT INTO BODYDATA' '(IDPRODUCER, IDBODY, BODYDATA)' 'VALUES (:NEW_IDPRODUCER, :NEW_IDBODY, :NEW_BODYDATA);' '' 'SELECT ID, IDPRODUCER, IDBODY, BODYDATA' 'FROM BODYDATA' 'WHERE ID = LAST_INSERT_AUTOGEN()') ModifySQL.Strings = ( 'UPDATE BODYDATA' 'SET IDPRODUCER = :NEW_IDPRODUCER, IDBODY = :NEW_IDBODY, BODYDATA' + ' = :NEW_BODYDATA' 'WHERE ID = :OLD_ID;' '' 'SELECT ID, IDPRODUCER, IDBODY, BODYDATA' 'FROM BODYDATA' 'WHERE ID = :NEW_ID') DeleteSQL.Strings = ( 'DELETE FROM BODYDATA' 'WHERE ID = :OLD_ID') FetchRowSQL.Strings = ( 'SELECT ID, IDPRODUCER, IDBODY, BODYDATA' 'FROM BODYDATA' 'WHERE ID = :ID') Left = 73 Top = 25 end end
{$I ..\DelphiVersions.Inc} unit Amazon.IndyRestClient; interface uses IdSSLOpenSSL, {IPPeerAPI,} IdHttp, classes, SysUtils, IdStack, IdGlobal, {IPPeerClient,} Amazon.Interfaces; type TAmazonIndyRestClient = class(TInterfacedObject, IAmazonRestClient) private fsAccept: string; fsAcceptCharset: string; fsContent_type: string; fiErrorCode: Integer; fsErrorMessage: String; fsUserAgent: string; //FIdHttp: IIPHTTP; FIdHttp: TIDHttp; protected function GetAcceptCharset: string; procedure SetAcceptCharset(value: string); function GetResponseCode: Integer; function GetResponseText: String; function GetContent_type: string; function GetErrorCode: Integer; procedure SetContent_type(value: string); function GetErrorMessage: String; function GetUserAgent: string; procedure SetUserAgent(value:string); function GetAccept: string; procedure SetAccept(value: string); public constructor Create; destructor Destory; procedure AddHeader(aName, aValue: UTF8String); procedure Post(aUrl: string; aRequest: UTF8String; var aResponse: UTF8String); property ResponseCode: Integer read GetResponseCode; property ResponseText: string read GetResponseText; property Content_type: String read GetContent_type write SetContent_type; property ErrorCode: Integer read GetErrorCode; property ErrorMessage: String read GetErrorMessage; property UserAgent: string read GetUserAgent write SetUserAgent; property AcceptCharset: string read GetAcceptCharset write SetAcceptCharset; property Accept: string read GetAccept write SetAccept; end; implementation constructor TAmazonIndyRestClient.Create; begin fsContent_type := ''; fiErrorCode := 0; fsErrorMessage := ''; FIdHttp := tIDHttp.Create(NIL); FIdHttp.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(NIL); //FIdHttp := PeerFactory.CreatePeer('', IIPHTTP, nil) as IIPHTTP; // FIdHttp.IOHandler := PeerFactory.CreatePeer('', IIPSSLIOHandlerSocketOpenSSL, // nil) as IIPSSLIOHandlerSocketOpenSSL; FIdHttp.Request.CustomHeaders.FoldLines := false; end; destructor TAmazonIndyRestClient.Destory; begin FreeandNil(FIdHttp); end; procedure TAmazonIndyRestClient.AddHeader(aName, aValue: UTF8String); begin FIdHttp.Request.CustomHeaders.AddValue(aName, aValue); end; procedure TAmazonIndyRestClient.Post(aUrl: string; aRequest: UTF8String; var aResponse: UTF8String); Var FSource, FResponseContent: TStringStream; begin try {$IFNDEF FPC} FSource := TStringStream.Create(aRequest, TEncoding.ANSI); {$ELSE} FSource := TStringStream.Create(aRequest); {$ENDIF} FSource.Position := 0; FResponseContent := TStringStream.Create(''); FIdHttp.Request.ContentType := Content_type; {$IFDEF DELPHIXE8_UP} FIdHttp.Request.UserAgent := UserAgent; {$ENDIF} FIdHttp.Request.Accept := Accept; {$IFDEF DELPHIXE8_UP} FIdHttp.Request.AcceptCharset := AcceptCharset; {$ENDIF} //FIdHttp.DoPost(aUrl, FSource, FResponseContent); FIdHttp.Post(aUrl, FSource, FResponseContent); aResponse := FResponseContent.DataString; FResponseContent.Free; FSource.Free; except on E: EIdHTTPProtocolException do begin fiErrorCode := E.ErrorCode; fsErrorMessage := E.ErrorMessage; if Trim(aResponse) = '' then aResponse := fsErrorMessage; FIdHttp.Disconnect; end; end; end; function TAmazonIndyRestClient.GetResponseCode: Integer; begin Result := FIdHttp.ResponseCode; end; function TAmazonIndyRestClient.GetResponseText: String; begin Result := FIdHttp.ResponseText; end; function TAmazonIndyRestClient.GetContent_type: string; begin Result := fsContent_type; end; function TAmazonIndyRestClient.GetErrorCode: Integer; begin Result := fiErrorCode; end; procedure TAmazonIndyRestClient.SetContent_type(value: string); begin fsContent_type := value; end; function TAmazonIndyRestClient.GetErrorMessage: String; begin Result := fsErrorMessage; end; function TAmazonIndyRestClient.GetUserAgent: string; begin if (Trim(fsUserAgent) = '') then begin {$IFDEF DELPHIXE8_UP} if Assigned(FIdHttp.Request) then fsUserAgent := FIdHttp.Request.UserAgent; {$ENDIF} end; Result := fsUserAgent; end; procedure TAmazonIndyRestClient.SetUserAgent(value:string); begin fsUserAgent := value; end; function TAmazonIndyRestClient.GetAcceptCharset: string; begin if Trim(fsAcceptCharset) = '' then begin {$IFDEF DELPHIXE8_UP} if Assigned(FIdHttp.Request) then fsAcceptCharset := FIdHttp.Request.AcceptCharSet; {$ENDIF} end; Result := fsAcceptCharset; end; procedure TAmazonIndyRestClient.SetAcceptCharset(value:string); begin fsAcceptCharset := value; end; function TAmazonIndyRestClient.GetAccept: string; begin if Trim(fsAcceptCharset) = '' then begin if Assigned(FIdHttp.Request) then fsAccept := FIdHttp.Request.Accept; end; Result := fsAccept; end; procedure TAmazonIndyRestClient.SetAccept(value:string); begin fsAccept := value; end; end.
unit ncsDMBackup; interface uses SysUtils, Classes, nxdbBackupController, nxdb, nxllComponent; type TdmBackup = class(TDataModule) nxDBD: TnxDatabase; nxDBO: TnxDatabase; nxSession: TnxSession; nxBackup: TnxBackupController; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FTables: TStrings; { Private declarations } procedure IncluirTabela(aSender : TnxBackupController; const aTableName : string; var aUseTable : Boolean); public procedure FazBackup(aTables, aDestino: String); class procedure Copiar(aTables, aDestino: String); { Public declarations } end; var dmBackup: TdmBackup; implementation uses ncServBD, ncTableDefs; {$R *.dfm} class procedure TdmBackup.Copiar(aTables, aDestino: String); begin with TdmBackup.Create(nil) do try FazBackup(aTables, aDestino); finally Free; end; end; procedure TdmBackup.DataModuleCreate(Sender: TObject); begin FTables := TStringList.Create; end; procedure TdmBackup.DataModuleDestroy(Sender: TObject); begin FTables.Free; end; procedure TdmBackup.FazBackup(aTables, aDestino: String); begin FTables.Text := aTables; nxSession.ServerEngine := dmServidorBD.ServerEngine; nxSession.Active := True; nxSession.PasswordAdd(sEncpass); nxDBD.AliasPath := aDestino; if not DirectoryExists(nxDBD.AliasPath) then ForceDirectories(nxDBD.AliasPath); nxDBO.Active := True; nxDBD.Active := True; try nxBackup.OnIncludeTable := IncluirTabela; nxBackup.Backup; finally nxDBD.Active := False; nxDBO.Active := False; nxSession.CloseInactiveTables; nxSession.CloseInactiveFolders; nxSession.Active := False; nxSession.ServerEngine := nil; nxBackup.Close; end; end; procedure TdmBackup.IncluirTabela(aSender: TnxBackupController; const aTableName: string; var aUseTable: Boolean); begin aUseTable := (FTables.IndexOf(aTableName)>=0); end; end.
unit uComponente; interface type TComponente = class; TComponenteArray = array of TComponente; TComponente = class private FComponentes: TComponenteArray; FAltura: Integer; FLargura: Integer; FX: Integer; FY: Integer; FParente: TComponente; FoldAltura: Integer; FoldLargura: Integer; FoldX: Integer; FoldY: Integer; procedure SetAltura(const Value: Integer); procedure SetComponentes(const Value: TComponenteArray); procedure SetLargura(const Value: Integer); procedure SetX(const Value: Integer); procedure SetY(const Value: Integer); procedure SetParente(const Value: TComponente); public property oldX: Integer read FoldX write FoldX; property oldY: Integer read FoldY write FoldY; property oldAltura: Integer read FoldAltura write FoldAltura; property oldLargura: Integer read FoldLargura write FoldLargura; property X: Integer read FX write SetX; property Y: Integer read FY write SetY; property Altura: Integer read FAltura write SetAltura; property Largura: Integer read FLargura write SetLargura; property Componentes: TComponenteArray read FComponentes write SetComponentes; property Parente: TComponente read FParente write SetParente; constructor Create(aAltura, aLargura, aX, aY: Integer); destructor Destroy(aComponente: TComponente); virtual; procedure AdicionaComponente(aComponente: TComponente); virtual; procedure RemoveComponente(aComponente: TComponente); virtual; procedure RedimensionaComponente(aComponente: TComponente); virtual; end; implementation procedure TComponente.AdicionaComponente(aComponente: TComponente); begin SetLength(FComponentes, Length(FComponentes) + 1); FComponentes[Length(FComponentes)] := aComponente; end; procedure TComponente.RemoveComponente(aComponente: TComponente); var i, j: integer; begin inherited; for i := 0 to Length(FComponentes) do if FComponentes[i] = aComponente then begin for j := i + 1 to Length(FComponentes) - 1 do FComponentes[j - 1] := FComponentes[j]; SetLength(FComponentes, Length(FComponentes) - 1); FComponentes[i].Destroy(FComponentes[i]); end; end; procedure TComponente.RedimensionaComponente(aComponente: TComponente); var i: Integer; begin if Length(FComponentes) > 0 then begin for i := 0 to Length(FComponentes) -1 do FComponentes[i].RedimensionaComponente(FComponentes[i]); end; end; constructor TComponente.Create(aAltura, aLargura, aX, aY: Integer); begin SetAltura(aAltura); SetLargura(aLargura); SetX(aX); SetY(aY); oldX := aX; oldY := aY; oldAltura := aAltura; oldLargura := aLargura; end; destructor TComponente.Destroy(aComponente: TComponente); begin RemoveComponente(aComponente); aComponente.Free; end; procedure TComponente.SetAltura(const Value: Integer); begin oldAltura := FAltura; FAltura := Value; RedimensionaComponente(Self); end; procedure TComponente.SetComponentes(const Value: TComponenteArray); begin FComponentes := Value; end; procedure TComponente.SetLargura(const Value: Integer); begin oldLargura := FLargura; FLargura := Value; RedimensionaComponente(Self); end; procedure TComponente.SetParente(const Value: TComponente); begin FParente := Value; end; procedure TComponente.SetX(const Value: Integer); begin oldX := X; FX := Value; RedimensionaComponente(Self); end; procedure TComponente.SetY(const Value: Integer); begin oldY := Y; FY := Value; RedimensionaComponente(Self); end; end.
unit WiseHardware; interface uses Windows, Messages, SysUtils, Classes, cbw, Winsock; Const MaxTries = 5; MaxTimeout = 100; // microseconds between port reads FullPortMask = $ff; MaxBoards = 3; // Max number of boards supported MaxPortsPerBoard = 8; // FIRST to EIGHTH BytesPerPort = 3; // FIRSTPORTA(8), FIRSTPORTB(8), FIRSTPORTCL(4), FIRSTPORTCH(4) type TWiseDirection = (DirNone = 0, DirCW = 1, DirCCW = 2); type TWiseObject = class public Name: string; constructor Create(Name: string); end; type TPortId = FIRSTPORTA .. EIGHTHPORTCH; EWiseError = class(Exception); EWiseConfigError = class(EWiseError); EWiseEncoderError = class(EWiseError); EWisePinError = class(EWiseError); EWisePortError = class(EWiseError); var DirNames: array[DIGITALOUT .. DIGITALIN] of string = ('DIGITALOUT', 'DIGITALIN'); production: boolean; implementation var hostname: array[0..256] of Char; WSAData: TWSAData; { TWiseControl implementation } constructor TWiseObject.Create(Name: string); begin Self.Name := Name; end; initialization production := false; if (WSAStartup($0101,WSAData) = 0) and ((gethostname(hostname, sizeof(hostname)) = 0) and (hostname = 'dome-pc')) then production := true; end.
unit ImageUtils; interface uses Windows, Graphics, Classes; const PROPRTIONAL_RESIZE = -300; // Утилитне функции для изменения размера изображения procedure ResizeImage(anInBitmap, anOutBitmap: TBitmap; aNewHeight, aNewWidth: Integer); // Изменить большой procedure ResizeBitmap(Bitmap: TBitmap; const NewWidth, NewHeight: integer); // Вывести изображение прозрачным procedure DrawTransparentBmp(Cnv: TCanvas; x,y: Integer; Bmp: TBitmap; clTransparent: TColor); procedure DrawTransparentBitmap(DC: HDC; hBmp : HBITMAP ; xStart: integer; yStart : integer; cTransparentColor : COLORREF); procedure DrawOpacityBrush(ACanvas: TCanvas; X, Y: Integer; AColor: TColor; ASize: Integer; Opacity: Byte); // Получить RGB копмпоненты значения цветов function GetRedCompColor(aColor: TColor): Byte; function GetGreenCompColor(aColor: TColor): Byte; function GetBlueCompColor(aColor: TColor): Byte; implementation procedure DrawOpacityBrush(ACanvas: TCanvas; X, Y: Integer; AColor: TColor; ASize: Integer; Opacity: Byte); var Bmp: TBitmap; I, J: Integer; Pixels: PRGBQuad; ColorRgb: Integer; ColorR, ColorG, ColorB: Byte; begin Bmp := TBitmap.Create; try Bmp.PixelFormat := pf32Bit; // needed for an alpha channel Bmp.SetSize(ASize, ASize); with Bmp.Canvas do begin Brush.Color := clFuchsia; // background color to mask out ColorRgb := ColorToRGB(Brush.Color); FillRect(Rect(0, 0, ASize, ASize)); Pen.Color := AColor; Pen.Style := psSolid; Pen.Width := ASize; MoveTo(ASize div 2, ASize div 2); LineTo(ASize div 2, ASize div 2); end; ColorR := GetRValue(ColorRgb); ColorG := GetGValue(ColorRgb); ColorB := GetBValue(ColorRgb); for I := 0 to Bmp.Height-1 do begin Pixels := PRGBQuad(Bmp.ScanLine[I]); for J := 0 to Bmp.Width-1 do begin with Pixels^ do begin if (rgbRed = ColorR) and (rgbGreen = ColorG) and (rgbBlue = ColorB) then rgbReserved := 0 else rgbReserved := Opacity; // must pre-multiply the pixel with its alpha channel before drawing rgbRed := (rgbRed * rgbReserved) div $FF; rgbGreen := (rgbGreen * rgbReserved) div $FF; rgbBlue := (rgbBlue * rgbReserved) div $FF; end; Inc(Pixels); end; end; ACanvas.Draw(X, Y, Bmp, 255); finally Bmp.Free; end; end; procedure ResizeImage(anInBitmap, anOutBitmap: TBitmap; aNewHeight, aNewWidth: Integer); var aProprotion: Integer; begin if aNewWidth = PROPRTIONAL_RESIZE then begin aProprotion := anInBitmap.Height div aNewHeight; aNewWidth := anInBitmap.Width div aProprotion; end; anOutBitmap.Assign(anInBitmap); anOutBitmap.Canvas.StretchDraw( Rect(0, 0, aNewWidth, aNewHeight), anOutBitmap); anOutBitmap.SetSize(aNewWidth, aNewHeight); end; procedure DrawTransparentBitmap(DC: HDC; hBmp : HBITMAP ; xStart: integer; yStart : integer; cTransparentColor : COLORREF); var bm: BITMAP; cColor: COLORREF; bmAndBack, bmAndObject, bmAndMem, bmSave: HBITMAP; bmBackOld, bmObjectOld, bmMemOld, bmSaveOld: HBITMAP; hdcMem, hdcBack, hdcObject, hdcTemp, hdcSave: HDC; ptSize: TPOINT; begin hdcTemp := CreateCompatibleDC(dc); SelectObject(hdcTemp, hBmp); // Select the bitmap GetObject(hBmp, sizeof(BITMAP), @bm); ptSize.x := bm.bmWidth; // Get width of bitmap ptSize.y := bm.bmHeight; // Get height of bitmap DPtoLP(hdcTemp, ptSize, 1); // Convert from device // to logical points // Create some DCs to hold temporary data. hdcBack := CreateCompatibleDC(dc); hdcObject := CreateCompatibleDC(dc); hdcMem := CreateCompatibleDC(dc); hdcSave := CreateCompatibleDC(dc); // Create a bitmap for each DC. DCs are required for a number of // GDI functions. // Monochrome DC bmAndBack := CreateBitmap(ptSize.x, ptSize.y, 1, 1, nil); // Monochrome DC bmAndObject := CreateBitmap(ptSize.x, ptSize.y, 1, 1, nil); bmAndMem := CreateCompatibleBitmap(dc, ptSize.x, ptSize.y); bmSave := CreateCompatibleBitmap(dc, ptSize.x, ptSize.y); // Each DC must select a bitmap object to store pixel data. bmBackOld := SelectObject(hdcBack, bmAndBack); bmObjectOld := SelectObject(hdcObject, bmAndObject); bmMemOld := SelectObject(hdcMem, bmAndMem); bmSaveOld := SelectObject(hdcSave, bmSave); // Set proper mapping mode. SetMapMode(hdcTemp, GetMapMode(dc)); // Save the bitmap sent here, because it will be overwritten. BitBlt(hdcSave, 0, 0, ptSize.x, ptSize.y, hdcTemp, 0, 0, SRCCOPY); // Set the background color of the source DC to the color. // contained in the parts of the bitmap that should be transparent cColor := SetBkColor(hdcTemp, cTransparentColor); // Create the object mask for the bitmap by performing a BitBlt // from the source bitmap to a monochrome bitmap. BitBlt(hdcObject, 0, 0, ptSize.x, ptSize.y, hdcTemp, 0, 0, SRCCOPY); // Set the background color of the source DC back to the original // color. SetBkColor(hdcTemp, cColor); // Create the inverse of the object mask. BitBlt(hdcBack, 0, 0, ptSize.x, ptSize.y, hdcObject, 0, 0, NOTSRCCOPY); // Copy the background of the main DC to the destination. BitBlt(hdcMem, 0, 0, ptSize.x, ptSize.y, dc, xStart, yStart, SRCCOPY); // Mask out the places where the bitmap will be placed. BitBlt(hdcMem, 0, 0, ptSize.x, ptSize.y, hdcObject, 0, 0, SRCAND); // Mask out the transparent colored pixels on the bitmap. BitBlt(hdcTemp, 0, 0, ptSize.x, ptSize.y, hdcBack, 0, 0, SRCAND); // XOR the bitmap with the background on the destination DC. BitBlt(hdcMem, 0, 0, ptSize.x, ptSize.y, hdcTemp, 0, 0, SRCPAINT); // Copy the destination to the screen. BitBlt(dc, xStart, yStart, ptSize.x, ptSize.y, hdcMem, 0, 0, SRCCOPY); // Place the original bitmap back into the bitmap sent here. BitBlt(hdcTemp, 0, 0, ptSize.x, ptSize.y, hdcSave, 0, 0, SRCCOPY); // Delete the memory bitmaps. DeleteObject(SelectObject(hdcBack, bmBackOld)); DeleteObject(SelectObject(hdcObject, bmObjectOld)); DeleteObject(SelectObject(hdcMem, bmMemOld)); DeleteObject(SelectObject(hdcSave, bmSaveOld)); // Delete the memory DCs. DeleteDC(hdcMem); DeleteDC(hdcBack); DeleteDC(hdcObject); DeleteDC(hdcSave); DeleteDC(hdcTemp); end; procedure DrawTransparentBmp(Cnv: TCanvas; x,y: Integer; Bmp: TBitmap; clTransparent: TColor); var bmpXOR, bmpAND, bmpINVAND, bmpTarget: TBitmap; oldcol: Longint; begin bmpAND := TBitmap.Create; bmpTarget := TBitmap.Create; bmpXOR := TBitmap.Create; bmpINVAND := TBitmap.Create; try bmpAND.Width := Bmp.Width; bmpAND.Height := Bmp.Height; bmpAND.Monochrome := True; oldcol := SetBkColor(Bmp.Canvas.Handle, ColorToRGB(clTransparent)); BitBlt(bmpAND.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY); SetBkColor(Bmp.Canvas.Handle, oldcol); bmpINVAND.Width := Bmp.Width; bmpINVAND.Height := Bmp.Height; bmpINVAND.Monochrome := True; BitBlt(bmpINVAND.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, bmpAND.Canvas.Handle, 0, 0, NOTSRCCOPY); bmpXOR.Width := Bmp.Width; bmpXOR.Height := Bmp.Height; BitBlt(bmpXOR.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY); BitBlt(bmpXOR.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, bmpINVAND.Canvas.Handle, 0, 0, SRCAND); bmpTarget.Width := Bmp.Width; bmpTarget.Height := Bmp.Height; BitBlt(bmpTarget.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, Cnv.Handle, x, y, SRCCOPY); BitBlt(bmpTarget.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, bmpAND.Canvas.Handle, 0, 0, SRCAND); BitBlt(bmpTarget.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, bmpXOR.Canvas.Handle, 0, 0, SRCINVERT); BitBlt(Cnv.Handle, x, y, Bmp.Width, Bmp.Height, bmpTarget.Canvas.Handle, 0, 0, SRCCOPY); finally bmpXOR.Free; bmpAND.Free; bmpINVAND.Free; bmpTarget.Free; end; end; procedure ResizeBitmap(Bitmap: TBitmap; const NewWidth, NewHeight: integer); begin Bitmap.Canvas.StretchDraw( Rect(0, 0, NewWidth, NewHeight), Bitmap); Bitmap.SetSize(NewWidth, NewHeight); end; function GetRedCompColor(aColor: TColor): Byte; begin Result := aColor; end; function GetGreenCompColor(aColor: TColor): Byte; begin Result := aColor shr 8; end; function GetBlueCompColor(aColor: TColor): Byte; begin Result := aColor shr 16; end; end.
program Sample; var S : Char; H, W, HW : String; begin S := ' '; H := 'Hello'; W := 'World'; HW := H + S + W; WriteLn(HW); end.
unit Player.AudioOutput.Base; {$WARN SYMBOL_PLATFORM OFF} interface uses Messages, Windows, Forms, Graphics, SysUtils, Controls, Classes, SyncObjs, Contnrs,Generics.Collections, MMSystem,MediaProcessing.Definitions; type TPlayerAudioOutput = class; TAudioVolume = 0..100; TPCMFormat = packed record Channels: cardinal; BitsPerSample: cardinal; SamplesPerSec: cardinal; end; //Decode To PCM TAudioOutputDecoder = class public function DecodeToPCM( const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal; out aPcmFormat: TPCMFormat; out aPcmData: pointer; out aPcmDataSize: cardinal):boolean; virtual; abstract; function IsDataValid(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal):boolean; virtual; procedure ResetBuffer; virtual; constructor Create; virtual; end; TAudioOutputDecoderClass = class of TAudioOutputDecoder; TPlayerAudioOutput = class private FStreamType : TStreamType; FServiceWndHandle : THandle; FDecoder : TAudioOutputDecoder; FDecoderClasses: TDictionary<TStreamType,TAudioOutputDecoderClass>; FLastUnspportedStreamType: TStreamType; FEnabled: boolean; FSyncronousPlay: boolean; procedure WndProc (var Message : TMessage); protected function GetVolume: TAudioVolume; virtual; abstract; procedure SetVolume(const Value: TAudioVolume); virtual; abstract; function IsDataValid(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal):boolean; procedure SetStreamType(const Value: TStreamType); procedure RegisterDecoderClass(aStreamType:TStreamType;aClass: TAudioOutputDecoderClass); function GetStreamTypeHandlerClass(aType: TStreamType): TAudioOutputDecoderClass; virtual; procedure PlayPCM(const aPcmFormat: TPCMFormat; aPcmData: pointer;aPcmDataSize: cardinal); virtual; abstract; procedure TraceLine(const aMessage: string); public procedure ResetBuffer; virtual; abstract; procedure DeallocateAudioContext; virtual; abstract; procedure WriteAudioData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); virtual; function StatusInfo:string; virtual; //сколько в буфере сейчас лежит данных в мс function GetBufferedDataDuration: cardinal; virtual; // property SyncronousPlay: boolean read FSyncronousPlay write FSyncronousPlay; constructor Create; virtual; destructor Destroy; override; property StreamType: TStreamType read FStreamType write SetStreamType; property Volume: TAudioVolume read GetVolume write SetVolume; property Enabled: boolean read FEnabled write FEnabled; end; TPlayerAudioOutputClass = class of TPlayerAudioOutput; TWaveOutBuffer = record Buffer : PAnsiChar; BufferSize: cardinal; Header: WAVEHDR; Playing: boolean; end; TPcmInputBufferItem = class private FData: TBytes; FActualDataSize: cardinal; public constructor Create(aSize: integer); procedure Assign(aData: pointer; aDataSize: cardinal); procedure Append(aData: pointer; aDataSize: cardinal); end; TInputBuffer = class (TQueue<TPcmInputBufferItem>) private FLastAdded:TPcmInputBufferItem; protected procedure Notify(const Item: TPcmInputBufferItem; Action: TCollectionNotification); override; end; TPlayerAudioOutputWaveOut = class (TPlayerAudioOutput) private //2 - обязательный минимум для флипа, остальные - резервные на случай задержек. //Каждый буфер - 40 мс. 40*2(флип) = 80 - Это минимальное значение, когда еще не чувствуется отставание звука //Итого буферы держат n*40 мс данных, что позволяет не "захлебыватья" при небольших перебоях с поставками данных FWaveOutBuffers: array [0..2] of TWaveOutBuffer; FWaveOutBuffersLock: TCriticalSection; FAudioDeviceId: cardinal; FWaveOutHandle: HWAVEOUT; FWindowHandle: THandle; FInputBufferLock : TCriticalSection; FInputBuffer : TInputBuffer; FInputBufferItemPool: TList<TPcmInputBufferItem>; FInputBufferEmptyTriggered: boolean; FAudioChannels: cardinal; FAudioBitsPerSample: cardinal; FAudioSamplesPerSec: cardinal; FAvgBytesPerSec : cardinal; //FWaitIntervalWhenOutOfBuffer: cardinal; FNoAudioDevice : boolean; FInitialBufferedDataDuration: cardinal; FAdaptedInitialBufferedDataDuration: cardinal; FPlayedDataDuration: cardinal; FFirstPlayTimeStamp: cardinal; FLastPlayedDataTimeStamp: cardinal; FInputBufferEmptyEventCount: cardinal; FVolume : TAudioVolume; procedure OnWaveOutBufferDone(aBuffer: PWaveHdr); procedure LoadWaveOutBuffer(aBufferIndex: cardinal); procedure StartPcmDriverPlayIfPossible; procedure ClearInputBuffer; procedure WndProc(var Message: TMessage); procedure SetInitialBufferedDataDuration(const Value: cardinal); protected procedure OpenInternal(aAudioChannels: cardinal; aBitsPerSample: Cardinal; aSamplesPerSec: cardinal); procedure CloseInternal; function Opened:boolean; procedure CheckOpened; function GetVolume: TAudioVolume; override; procedure SetVolume(const Value: TAudioVolume); override; procedure PlayPCM(const aPcmFormat: TPCMFormat; aPcmData: pointer;aPcmDataSize: cardinal); override; procedure PlayPCMInternal(aPcmData: pointer;aPcmDataSize: cardinal); procedure OnInputBufferEmpty; public procedure ResetBuffer; override; procedure DeallocateAudioContext; override; procedure WriteAudioData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); override; function GetBufferedDataDuration: cardinal; override; function GetInputBufferDuration: cardinal; function GetOutputBufferDuration: cardinal; function StatusInfo:string; override; //Сколько забуферизировать до начала проигрывания. чем больше значение, тем меньше шансов на "щелчки", но увеличиывается отставание звука property InitialBufferedDataDuration: cardinal read FInitialBufferedDataDuration write SetInitialBufferedDataDuration; constructor Create; override; destructor Destroy; override; property AudioDeviceId: cardinal read FAudioDeviceId write FAudioDeviceId; end; ENoSoundDeviceError = class (Exception) public constructor Create; end; implementation uses Math,uTrace; const WM_SETSTREAMTTYPE = WM_USER+$100; const WaveOutDriverBufferSizeMsec = 40; { TPcmInputBufferItem } procedure TPcmInputBufferItem.Append(aData: pointer; aDataSize: cardinal); begin Assert(FActualDataSize+aDataSize<=cardinal(Length(FData))); CopyMemory(@FData[FActualDataSize],aData,aDataSize); inc(FActualDataSize,aDataSize); end; procedure TPcmInputBufferItem.Assign(aData: pointer; aDataSize: cardinal); begin Assert(cardinal(Length(FData))>=aDataSize); FActualDataSize:=aDataSize; CopyMemory(@FData[0], aData,aDataSize); end; constructor TPcmInputBufferItem.Create(aSize: integer); begin SetLength(FData,aSize); end; { TPlayerAudioOutput } constructor TPlayerAudioOutput.Create; begin FDecoderClasses:=TDictionary<TStreamType,TAudioOutputDecoderClass>.Create; FStreamType:=INVALID_HANDLE_VALUE; FServiceWndHandle := AllocateHWnd(WndProc); FEnabled:=true; Assert(FServiceWndHandle<>0); end; destructor TPlayerAudioOutput.Destroy; begin inherited; FreeAndNil(FDecoderClasses); DeallocateHWnd(FServiceWndHandle); FServiceWndHandle:=0; end; function TPlayerAudioOutput.GetBufferedDataDuration: cardinal; begin result:=0; end; function TPlayerAudioOutput.GetStreamTypeHandlerClass( aType: TStreamType): TAudioOutputDecoderClass; begin if not FDecoderClasses.TryGetValue(aType,result) then result:=nil; end; function TPlayerAudioOutput.IsDataValid(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal): boolean; begin result:=(aFormat.biMediaType=mtAudio) and (aData<>nil) and (aDataSize<>0); if result then if FDecoder<>nil then result:=FDecoder.IsDataValid(aFormat,aData,aDataSize,aInfo,aInfoSize); end; procedure TPlayerAudioOutput.RegisterDecoderClass(aStreamType: TStreamType; aClass: TAudioOutputDecoderClass); begin FDecoderClasses.Add(aStreamType,aClass); end; procedure TPlayerAudioOutput.SetStreamType(const Value: TStreamType); var aClass: TAudioOutputDecoderClass; begin Assert(GetCurrentThreadId=MainThreadID); if FStreamType<>Value then FreeAndNil(FDecoder); if FDecoder<>nil then exit; FStreamType:=INVALID_HANDLE_VALUE; aClass:=GetStreamTypeHandlerClass(Value); if aClass=nil then raise Exception.Create(Format('Неподдерживаемый тип потока %s',[GetStreamTypeName(Value)])); FDecoder:=aClass.Create; FStreamType:=Value; end; function TPlayerAudioOutput.StatusInfo: string; begin result:='General'+#13#10; result:=result+ Format(' Type:%s'#13#10,[ClassName]); //result:=result+'Settings: '#13#10; //result:=result+ Format(' SynchronousDisplay:%s'#13#10,[BoolToStr(SynchronousDisplay,true)]); //result:=result+ Format(' WaitOnOutOfBuffer:%s'#13#10,[BoolToStr(WaitOnOutOfBuffer,true)]); result:=result+'Statistics: '#13#10; result:=result+ Format(' BufferedData (secs):%.2f'#13#10,[GetBufferedDataDuration/1000]); end; procedure TPlayerAudioOutput.TraceLine(const aMessage: string); begin uTrace.TraceLine(ClassName,aMessage); end; procedure TPlayerAudioOutput.WndProc(var Message: TMessage); begin if Message.Msg=WM_SETSTREAMTTYPE then begin try FLastUnspportedStreamType:=0; SetStreamType(Message.WParam); except FLastUnspportedStreamType:=Message.WParam; end; exit; end; Message.result := DefWindowProc(FServiceWndHandle, Message.Msg, Message.wParam, Message.lParam); end; procedure TPlayerAudioOutput.WriteAudioData( const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); var aPcmData: pointer; aPcmDataSize: cardinal; aPcmFormat: TPCMFormat; begin if not FEnabled then exit; try if FStreamType<>aFormat.biStreamType then begin if FLastUnspportedStreamType=aFormat.biStreamType then //В случае если формат не поддерживается, не надо генерировать постоянно исключения. Будем тихо выходить exit; SendMessage(FServiceWndHandle,WM_SETSTREAMTTYPE,aFormat.biStreamType,0); end; if FDecoder=nil then exit; if (aDataSize=0) or not IsDataValid(aFormat,aData,aDataSize,aInfo,aInfoSize)then exit; if not FDecoder.DecodeToPCM(aFormat, aData,aDataSize,aInfo,aInfoSize,aPcmFormat, aPcmData,aPcmDataSize) then exit; PlayPCM(aPcmFormat, aPcmData,aPcmDataSize); except on E:Exception do TraceLine('Exception: '+E.Message); end; end; { TPlayerAudioOutputWaveOut } procedure TPlayerAudioOutputWaveOut.CheckOpened; begin if FWaveOutHandle=0 then raise Exception.Create('Вывод аудио еще не инициализирован'); end; procedure TPlayerAudioOutputWaveOut.ClearInputBuffer; begin FInputBufferLock.Enter; try while FInputBuffer.Count>0 do FInputBufferItemPool.Add(FInputBuffer.Dequeue); finally FInputBufferLock.Leave; end; end; procedure TPlayerAudioOutputWaveOut.CloseInternal; var i: integer; begin ClearInputBuffer; for i := 0 to FInputBufferItemPool.Count-1 do FInputBufferItemPool[i].Free; FInputBufferItemPool.Clear; if FWaveOutHandle<>0 then begin FWaveOutBuffersLock.Enter; try waveOutReset(FWaveOutHandle); for i:=0 to High(FWaveOutBuffers) do begin if FWaveOutBuffers[i].Buffer<>nil then GlobalFree(HGLOBAL(FWaveOutBuffers[i].Buffer)); WaveOutUnprepareHeader(FWaveOutHandle,@FWaveOutBuffers[i].Header,sizeof(FWaveOutBuffers[i].Header)); FWaveOutBuffers[i].Buffer:=nil; ZeroMemory(@FWaveOutBuffers[i].Header,sizeof(FWaveOutBuffers[i].Header)); end; WaveOutClose(FWaveOutHandle); FWaveOutHandle:=0; finally FWaveOutBuffersLock.Leave; end; end; end; procedure TPlayerAudioOutputWaveOut.LoadWaveOutBuffer(aBufferIndex: cardinal); var i: integer; aInputBufferItem: TPcmInputBufferItem; begin FWaveOutBuffersLock.Enter; try //Если буфер еще занят - ничего не делаем if (FWaveOutBuffers[aBufferIndex].Playing) then exit; Assert(aBufferIndex<cardinal(Length(FWaveOutBuffers))); aInputBufferItem:=nil; FInputBufferLock.Enter; try //Если в очереди единственный элемент, то не будем его трогать пока он не наполниться под завязку. Иначе //мы можем "завязнуть" в частом переключении буферов драйвера if (FInputBuffer.Count=1) and (FInputBuffer.Peek.FActualDataSize<FWaveOutBuffers[0].BufferSize) then //Do nothing else if FInputBuffer.Count>0 then aInputBufferItem:=FInputBuffer.Dequeue finally FInputBufferLock.Leave; end; if aInputBufferItem<>nil then begin with FWaveOutBuffers[aBufferIndex] do begin Assert(aInputBufferItem.FActualDataSize<=BufferSize); Playing:=true; Header.dwFlags:=WHDR_PREPARED; Header.dwBufferLength:=aInputBufferItem.FActualDataSize; CopyMemory(Header.lpData,aInputBufferItem.FData,Header.dwBufferLength); i:=waveOutWrite(FWaveOutHandle,@Header,sizeof(Header)); if i<>MMSYSERR_NOERROR then RaiseLastOSError; end; FInputBufferLock.Enter; try FInputBufferItemPool.Add(aInputBufferItem); finally FInputBufferLock.Leave; end; end; finally FWaveOutBuffersLock.Leave; end; end; constructor TPlayerAudioOutputWaveOut.Create; begin inherited; FWindowHandle:=AllocateHWnd(WndProc); FInputBufferLock:=TCriticalSection.Create; FWaveOutBuffersLock:=TCriticalSection.Create; FInputBuffer := TInputBuffer.Create; FInputBufferItemPool:=TList<TPcmInputBufferItem>.Create; SetInitialBufferedDataDuration(80); end; procedure TPlayerAudioOutputWaveOut.DeallocateAudioContext; begin CloseInternal; end; destructor TPlayerAudioOutputWaveOut.Destroy; begin CloseInternal; inherited; FreeAndNil(FInputBuffer); FreeAndNil(FInputBufferItemPool); FreeAndNil(FInputBufferLock); FreeAndNil(FWaveOutBuffersLock); DeallocateHWnd(FWindowHandle); end; function TPlayerAudioOutputWaveOut.GetBufferedDataDuration: cardinal; begin result:=GetInputBufferDuration+GetOutputBufferDuration; end; function TPlayerAudioOutputWaveOut.GetInputBufferDuration: cardinal; var aIt: TEnumerator<TPcmInputBufferItem>; begin result:=0; if FAvgBytesPerSec=0 then exit; FInputBufferLock.Enter; try aIt:=FInputBuffer.GetEnumerator; try while aIt.MoveNext do inc(result,aIt.Current.FActualDataSize); finally aIt.Free; end; finally FInputBufferLock.Leave; end; result:=int64(result)*1000 div FAvgBytesPerSec; end; function TPlayerAudioOutputWaveOut.GetOutputBufferDuration: cardinal; var i: integer; begin; result:=0; if FAvgBytesPerSec=0 then exit; FWaveOutBuffersLock.Enter; try for i := 0 to High(FWaveOutBuffers) do begin if FWaveOutBuffers[i].Playing then inc(result,FWaveOutBuffers[i].Header.dwBufferLength); end; finally FWaveOutBuffersLock.Leave; end; result:=int64(result)*1000 div FAvgBytesPerSec; end; function TPlayerAudioOutputWaveOut.GetVolume: TAudioVolume; var aX: cardinal; begin result:=FVolume; if FWaveOutHandle<>0 then begin if waveOutGetVolume(FWaveOutHandle,@aX)<>MMSYSERR_NOERROR then RaiseLastOSError; result:=Word(aX)*100 div $FFFF; end; end; procedure TPlayerAudioOutputWaveOut.OnInputBufferEmpty; begin FInputBufferEmptyTriggered:=true; FAdaptedInitialBufferedDataDuration:=FAdaptedInitialBufferedDataDuration+100; //добавлям по 100 мс inc(FInputBufferEmptyEventCount); end; procedure TPlayerAudioOutputWaveOut.OnWaveOutBufferDone(aBuffer: PWaveHdr); begin FWaveOutBuffersLock.Enter; try inc(FPlayedDataDuration,FWaveOutBuffers[aBuffer.dwUser].Header.dwBufferLength * 1000 div FAvgBytesPerSec); FLastPlayedDataTimeStamp:=GetTickCount; FWaveOutBuffers[aBuffer.dwUser].Playing:=false; if FInputBuffer.Count=0 then OnInputBufferEmpty else begin if FInputBufferEmptyTriggered then //Если есть щелчки - ничего не делаем пока не наберется достаточный буфер, иначе будет щелкать постоянно StartPcmDriverPlayIfPossible else begin LoadWaveOutBuffer(aBuffer.dwUser); if FInputBuffer.Count>0 then begin if FAdaptedInitialBufferedDataDuration>FInitialBufferedDataDuration then dec(FAdaptedInitialBufferedDataDuration); end; end; end; finally FWaveOutBuffersLock.Leave; end; end; function TPlayerAudioOutputWaveOut.Opened: boolean; begin result:=FWaveOutHandle<>0; end; procedure waveOutProc( hwo: HWAVEOUT; uMsg: UINT; dwInstance: DWORD_PTR; dwParam1: DWORD_PTR; dwParam2: DWORD_PTR); stdcall; begin if uMsg=WOM_DONE then TPlayerAudioOutputWaveOut(dwInstance).OnWaveOutBufferDone(PWaveHdr(dwParam1)); end; procedure TPlayerAudioOutputWaveOut.OpenInternal(aAudioChannels: cardinal; aBitsPerSample: Cardinal; aSamplesPerSec: cardinal); var aFormat:TWaveFormatEx; aWaveOutDevCaps: WAVEOUTCAPS; res: integer; aBuffSize: cardinal; i: integer; begin ClearInputBuffer; res:=waveOutGetNumDevs; if res=0 then raise ENoSoundDeviceError.Create; res:=waveOutGetDevCaps(FAudioDeviceId,@aWaveOutDevCaps,sizeof(aWaveOutDevCaps)); if(res<>MMSYSERR_NOERROR) then raise ENoSoundDeviceError.Create; aFormat.wFormatTag:=WAVE_FORMAT_PCM; aFormat.nChannels :=aAudioChannels; // один канал - МОНО, 2- СТЕРЕО aFormat.wBitsPerSample:=aBitsPerSample; //16; aFormat.nSamplesPerSec:=aSamplesPerSec;// 8000; aFormat.nBlockAlign:=(aFormat.wBitsPerSample div 8) * aFormat.nChannels; aFormat.nAvgBytesPerSec:=aFormat.nBlockAlign * aFormat.nSamplesPerSec; aFormat.cbSize:= 0; try Win32Check(waveOutOpen(@FWaveOutHandle,WAVE_MAPPER,@aFormat,FWindowHandle,dword(self),CALLBACK_WINDOW)=MMSYSERR_NOERROR); except on E:Exception do raise ENoSoundDeviceError.Create; end; //Нельзя использовать callback функцию потому что запрещено в callback догружать данные. //Win32Check(waveOutOpen(@FWaveOutHandle,WAVE_MAPPER,@aFormat,DWORD(@waveOutProc),dword(self),CALLBACK_FUNCTION)=MMSYSERR_NOERROR); FAvgBytesPerSec:=aFormat.nAvgBytesPerSec; aBuffSize:=(FAvgBytesPerSec*WaveOutDriverBufferSizeMsec) div 1000; //Держим буфер размером WaveOutDriverBufferSizeMsec for i:=0 to High(FWaveOutBuffers) do begin FWaveOutBuffers[i].Buffer:=pointer(GlobalAlloc(GMEM_FIXED or GMEM_NOCOMPACT or GMEM_NODISCARD, aBuffSize)); if FWaveOutBuffers[i].Buffer=nil then RaiseLastOSError; FWaveOutBuffers[i].BufferSize:=aBuffSize; FWaveOutBuffers[i].Header.lpData := FWaveOutBuffers[i].Buffer; FWaveOutBuffers[i].Header.dwBufferLength := aBuffSize; FWaveOutBuffers[i].Header.dwFlags:=0; FWaveOutBuffers[i].Header.dwLoops:=0; FWaveOutBuffers[i].Header.dwUser:=i; //Номер буфера у нас Win32Check(waveOutPrepareHeader(FwaveOutHandle,@FWaveOutBuffers[i].Header,sizeof(FWaveOutBuffers[i].Header))=MMSYSERR_NOERROR); FWaveOutBuffers[i].Playing:=false; end; FAudioChannels:=aAudioChannels; FAudioBitsPerSample:=aBitsPerSample; FAudioSamplesPerSec:=aSamplesPerSec; FPlayedDataDuration:=0; FFirstPlayTimeStamp:=DWORD(-1); FLastPlayedDataTimeStamp:=DWORD(-1); FInputBufferEmptyEventCount:=0; FInputBufferEmptyTriggered:=true; //отмечаем, что начальный буфер пустой SetVolume(GetVolume); //Применим декларированное значение громкости к физическому устройству end; procedure TPlayerAudioOutputWaveOut.PlayPCMInternal(aPcmData: pointer;aPcmDataSize: cardinal); var aInputBufferItem: TPcmInputBufferItem; x: integer; begin Assert(aPcmDataSize<=FWaveOutBuffers[0].BufferSize); if aPcmDataSize=0 then exit; FInputBufferLock.Enter; try //Пытаемся забить под завязку последний элемент очереди //В основном, это необходимо для того, чтобы набрать первичный буфер в 80 мс, а это 2 элемента буфера) //TODO научиться доставать последний элемент. Пока достаем не последний, а первый на выход, работает только при Count=1 if (FInputBuffer.Count<>0) and (FInputBuffer.FLastAdded<>nil) then begin aInputBufferItem:=FInputBuffer.FLastAdded; if (aInputBufferItem.FActualDataSize<FWaveOutBuffers[0].BufferSize) then begin x:=min(FWaveOutBuffers[0].BufferSize-aInputBufferItem.FActualDataSize,aPcmDataSize); aInputBufferItem.Append(aPcmData,x); PByte(aPcmData):=PByte(aPcmData)+x; Assert(x<=integer(aPcmDataSize)); dec(aPcmDataSize,x); end; end; if (aPcmDataSize>0) then begin if FInputBufferItemPool.Count>0 then begin aInputBufferItem:=FInputBufferItemPool[FInputBufferItemPool.Count-1]; FInputBufferItemPool.Delete(FInputBufferItemPool.Count-1); end else aInputBufferItem:=TPcmInputBufferItem.Create(FWaveOutBuffers[0].BufferSize); end else begin aInputBufferItem:=nil; end; finally FInputBufferLock.Leave; end; if aInputBufferItem<>nil then begin aInputBufferItem.Assign(aPcmData,aPcmDataSize); FInputBufferLock.Enter; try FInputBuffer.Enqueue(aInputBufferItem); //TODO здесь нужно добавить вырезание тишины, если мы "сильно" опаздываем finally FInputBufferLock.Leave; end; end; StartPcmDriverPlayIfPossible; x:=aPcmDataSize*1000 div FAvgBytesPerSec; if FSyncronousPlay then while (FInputBuffer.Count>1) do //and (GetInputBufferDuration>=MaxInputBufferDuration) do begin Sleep(1); dec(x); if x<-10 then break; if FWaveOutHandle=0 then break; if FInputBufferEmptyTriggered then break; end; end; procedure TPlayerAudioOutputWaveOut.PlayPCM( const aPcmFormat: TPCMFormat; aPcmData: pointer;aPcmDataSize: cardinal); var aMaxAllowableSize: cardinal; begin if Opened then begin if (FAudioChannels<>aPcmFormat.Channels) or (FAudioBitsPerSample<>aPcmFormat.BitsPerSample) or (FAudioSamplesPerSec<>aPcmFormat.SamplesPerSec) then CloseInternal; end; if not Opened then begin try OpenInternal(aPcmFormat.Channels,aPcmFormat.BitsPerSample,aPcmFormat.SamplesPerSec); except on E:ENoSoundDeviceError do begin FNoAudioDevice:=true; exit; end; end; end; if FFirstPlayTimeStamp=DWORD(-1) then FFirstPlayTimeStamp:=GetTickCount; while true do begin aMaxAllowableSize:=FWaveOutBuffers[0].BufferSize; //Так как все буферы одинаковой длины, то можно сверять с любым if (aPcmDataSize<=aMaxAllowableSize) then begin PlayPCMInternal(aPcmData,aPcmDataSize); break; end else begin PlayPCMInternal(aPcmData,aMaxAllowableSize); aPcmData:=PByte(aPcmData)+aMaxAllowableSize; Assert(aPcmDataSize>aMaxAllowableSize); dec(aPcmDataSize,aMaxAllowableSize); end; end; end; procedure TPlayerAudioOutputWaveOut.ResetBuffer; var i: Integer; begin FInputBufferLock.Enter; try for i := 0 to FInputBuffer.Count-1 do FInputBufferItemPool.Add(FInputBuffer.Dequeue); finally FInputBufferLock.Leave; end; end; procedure TPlayerAudioOutputWaveOut.SetInitialBufferedDataDuration( const Value: cardinal); begin FInitialBufferedDataDuration := Value; FAdaptedInitialBufferedDataDuration:=Value; end; procedure TPlayerAudioOutputWaveOut.SetVolume(const Value: TAudioVolume); var aX: cardinal; begin FVolume:=Value; if FWaveOutHandle<>0 then begin aX:=Value*$FFFF div 100; waveOutSetVolume(FWaveOutHandle,MakeLong(aX,aX)); end; end; procedure TPlayerAudioOutputWaveOut.StartPcmDriverPlayIfPossible; var i: Integer; x: cardinal; begin FWaveOutBuffersLock.Enter; try //Драйвер полностью разгружен if FInputBufferEmptyTriggered then begin x:=GetInputBufferDuration; Assert(FAdaptedInitialBufferedDataDuration>=FInitialBufferedDataDuration); //Только если в буфере есть как минимум 2 элемента, чтобы было чем заменять. //Итого мы всегда имеем задержку в 40 мс от настоящего времени if x>=FAdaptedInitialBufferedDataDuration then begin for i := 0 to High(FWaveOutBuffers) do LoadWaveOutBuffer(i); FInputBufferEmptyTriggered:=false; end; end //Не все буферы драйвера задействованы else begin for i := 0 to High(FWaveOutBuffers) do LoadWaveOutBuffer(i); end; finally FWaveOutBuffersLock.Leave; end; end; function TPlayerAudioOutputWaveOut.StatusInfo: string; var x,y: int64; begin result:=inherited StatusInfo; result:=result+ Format(' Input Buffer Length (ms): %d'#13#10,[GetInputBufferDuration]); result:=result+ Format(' Output Buffer Length (ms): %d'#13#10,[GetOutputBufferDuration]); result:=result+ Format(' Played Data Length (ms): %d'#13#10,[FPlayedDataDuration]); result:=result+ Format(' Played Time (ms): %d'#13#10,[FLastPlayedDataTimeStamp-FFirstPlayTimeStamp]); if FPlayedDataDuration>0 then begin x:=FPlayedDataDuration; y:=FLastPlayedDataTimeStamp-FFirstPlayTimeStamp; result:=result+ Format(' Synchronization Discrepancy (%%): %.1f'#13#10,[(x-y)*100/x]); end; result:=result+ Format(' Empty Input Buffer Events: %d'#13#10,[FInputBufferEmptyEventCount]); end; procedure TPlayerAudioOutputWaveOut.WndProc(var Message: TMessage); begin if Message.Msg=WOM_DONE then OnWaveOutBufferDone(PWaveHdr(Message.LParam)) else Message.Result := DefWindowProc(FWindowHandle, Message.Msg, Message.wParam, Message.lParam); end; procedure TPlayerAudioOutputWaveOut.WriteAudioData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); begin if FNoAudioDevice then exit; inherited WriteAudioData(aFormat,aData,aDataSize,aInfo,aInfoSize); end; { ENoSoundDeviceError } constructor ENoSoundDeviceError.Create; begin inherited Create('Не обнаружено входное Audio-устройство'); end; { TAudioOutputDecoder } constructor TAudioOutputDecoder.Create; begin end; function TAudioOutputDecoder.IsDataValid(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal): boolean; begin result:=true; end; procedure TAudioOutputDecoder.ResetBuffer; begin end; { TInputBuffer } procedure TInputBuffer.Notify(const Item: TPcmInputBufferItem; Action: TCollectionNotification); begin inherited; case Action of cnAdded: FLastAdded:=Item; cnRemoved, cnExtracted: if FLastAdded=Item then FLastAdded:=nil; end; end; end.
{ Double Commander ------------------------------------------------------------------------- Drives list button options page Copyright (C) 2006-2011 Koblov Alexander (Alexx2000@mail.ru) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } unit fOptionsDrivesListButton; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StdCtrls, fOptionsFrame; type { TfrmOptionsDrivesListButton } TfrmOptionsDrivesListButton = class(TOptionsEditor) cbShowLabel: TCheckBox; cbShowFileSystem: TCheckBox; cbShowFreeSpace: TCheckBox; gbDrivesList: TGroupBox; protected procedure Load; override; function Save: TOptionsEditorSaveFlags; override; public class function GetIconIndex: Integer; override; class function GetTitle: String; override; end; implementation {$R *.lfm} uses uGlobs, uLng; { TfrmOptionsDrivesListButton } procedure TfrmOptionsDrivesListButton.Load; begin cbShowLabel.Checked := dlbShowLabel in gDrivesListButtonOptions; cbShowFileSystem.Checked := dlbShowFileSystem in gDrivesListButtonOptions; cbShowFreeSpace.Checked := dlbShowFreeSpace in gDrivesListButtonOptions; end; function TfrmOptionsDrivesListButton.Save: TOptionsEditorSaveFlags; begin gDrivesListButtonOptions := []; if cbShowLabel.Checked then Include(gDrivesListButtonOptions, dlbShowLabel); if cbShowFileSystem.Checked then Include(gDrivesListButtonOptions, dlbShowFileSystem); if cbShowFreeSpace.Checked then Include(gDrivesListButtonOptions, dlbShowFreeSpace); Result := []; end; class function TfrmOptionsDrivesListButton.GetIconIndex: Integer; begin Result := 31; end; class function TfrmOptionsDrivesListButton.GetTitle: String; begin Result := rsOptionsEditorDrivesListButton; end; end.
unit IssueErrors; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, DBClient, DB, IssuesServerUnit; type TUpdateErrorDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; Memo1: TMemo; Button1: TButton; Button2: TButton; procedure CancelBtnClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure Edit2Change(Sender: TObject); procedure Edit3Change(Sender: TObject); private { Private declarations } public { Public declarations } Delta: TClientDataSet; DataSet: TClientDataSet; Issue: TIssue; end; var UpdateErrorDlg: TUpdateErrorDlg; implementation {$R *.dfm} procedure TUpdateErrorDlg.CancelBtnClick(Sender: TObject); begin DataSet.CancelUpdates; end; procedure TUpdateErrorDlg.Button1Click(Sender: TObject); begin Edit1.ReadOnly := False; Edit2.ReadOnly := False; Edit3.ReadOnly := False; Edit1.SetFocus; end; procedure TUpdateErrorDlg.Edit1Change(Sender: TObject); begin Issue.ID := StrToInt(Edit1.Text); end; procedure TUpdateErrorDlg.Edit2Change(Sender: TObject); begin Issue.Owner := Edit2.Text; end; procedure TUpdateErrorDlg.Edit3Change(Sender: TObject); begin Issue.DateOpened.AsDateTime := StrToDate(Edit3.Text); end; end.
unit Unit4; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Grids, StdCtrls, functionsUnit; type { TForm4 } TForm4 = class(TForm) Button1: TButton; StringGrid1: TStringGrid; StringGrid2: TStringGrid; function safeStrToInt(s:String):Integer; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private public end; const ARR_SIZE_N = 5; ARR_SIZE_M = 5; NUMERIC_CHARS = '-1234567890'; var Form4: TForm4; z : array[0..ARR_SIZE_N,0..ARR_SIZE_M] of Integer; implementation procedure TForm4.FormCreate(Sender: TObject); Var i,j:Integer; begin For i := 0 to ARR_SIZE_N - 1 do For j := 0 to ARR_SIZE_M - 1 do Begin z[i, j] := ARR_SIZE_M * i + j; StringGrid1.Cells[j, i] := IntToStr(z[i,j]); end; end; //If string contains a number then returns the number, otherwise returns zero function TForm4.safeStrToInt(s:String):Integer; Begin If IsStringCorrect(s, NUMERIC_CHARS) then result := StrToInt(s) else result := 0; end; procedure TForm4.Button1Click(Sender: TObject); Var minV:Integer; buff:Integer; i,j:Integer; begin For i := 0 to ARR_SIZE_N - 1 do Begin minV := safeStrToInt(StringGrid1.Cells[0, i]); For j := 0 to ARR_SIZE_M - 1 do Begin buff := safeStrToInt(StringGrid1.Cells[j, i]); If buff < minV then minV := buff; end; StringGrid2.Cells[0, i] := IntToStr(minV); end; end; {$R *.lfm} end.
unit ejb_sidl_javax_ejb_i; {This file was generated on 28 Feb 2001 10:06:55 GMT by version 03.03.03.C1.06} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file sidl.idl. } {Delphi Pascal unit : ejb_sidl_javax_ejb_i } {derived from IDL module : ejb } interface uses CORBA, ejb_sidl_java_lang_i; type EJBMetaData = interface; EJBHome = interface; EJBObject = interface; EJBMetaData = interface ['{A741BF7B-007B-A116-AD07-55C0A48B6D77}'] function _get_home : ejb_sidl_javax_ejb_i.EJBHome; procedure _set_home (const home : ejb_sidl_javax_ejb_i.EJBHome); function _get_homeInterfaceClass : ejb_sidl_java_lang_i._Class; procedure _set_homeInterfaceClass (const homeInterfaceClass : ejb_sidl_java_lang_i._Class); function _get_primaryKeyClass : ejb_sidl_java_lang_i._Class; procedure _set_primaryKeyClass (const primaryKeyClass : ejb_sidl_java_lang_i._Class); function _get_remoteInterfaceClass : ejb_sidl_java_lang_i._Class; procedure _set_remoteInterfaceClass (const remoteInterfaceClass : ejb_sidl_java_lang_i._Class); function _get_session : Boolean; procedure _set_session (const session : Boolean); function _get_statelessSession : Boolean; procedure _set_statelessSession (const statelessSession : Boolean); property home : ejb_sidl_javax_ejb_i.EJBHome read _get_home write _set_home; property homeInterfaceClass : ejb_sidl_java_lang_i._Class read _get_homeInterfaceClass write _set_homeInterfaceClass; property primaryKeyClass : ejb_sidl_java_lang_i._Class read _get_primaryKeyClass write _set_primaryKeyClass; property remoteInterfaceClass : ejb_sidl_java_lang_i._Class read _get_remoteInterfaceClass write _set_remoteInterfaceClass; property session : Boolean read _get_session write _set_session; property statelessSession : Boolean read _get_statelessSession write _set_statelessSession; end; EJBHome = interface ['{8690977F-AE06-9989-F244-F20E959FF785}'] function getEJBMetaData : ejb_sidl_javax_ejb_i.EJBMetaData; procedure remove (const primaryKey : ANY); function getSimplifiedIDL : AnsiString; end; EJBObject = interface ['{746050E3-15AF-145A-77BC-31C2F22E6701}'] function getEJBHome : ejb_sidl_javax_ejb_i.EJBHome; function getPrimaryKey : ANY; procedure remove ; end; implementation initialization end.
unit Common.GoogleAuth; interface uses ibggdrive, ibgoauth, ibgcore, Common.Utils, System.Classes, System.SysUtils; const AuthKeysArray: array[0..1] of string = ( 'Bearer ya29.GlsUBKDsCD6SbtcN8J9JTdMszZLjLrsHxQmnzZ6GWPXXP00ky7t5fDLEFmFO7yEnKZpe9dZsK801VBxTPNy4FAaigvRo-h3sim9EMCV5XU4A6aANYPEwfQNoIrGY', 'Bearer ya29.GlsUBAgw23z37pHrliQjH2ro0s59haDvLW42E0qjQ6sfh_eMPb2hzkiOOrlbamiBv6EFPmhG-j4QREM6SRzCZElLUdh61NlHPZKo6-bO-11_Oi0LbbBE3XEEaWj-' ); cClientID = {'157623334268-pdch1uarb3180t5hq2s16ash9ei315j0.apps.googleusercontent.com';} '496929878224-n96vi711iu5buhki7m6p3r8ne5n14j66.apps.googleusercontent.com'; cClientSecret = {'k4NSk71U-p2sU8lB8Qv3G24R';} 'IbmtJrRD2GfJE6BKkAmGNFci'; cServerAuthURL = 'https://accounts.google.com/o/oauth2/auth'; cServerTokenURL = 'https://accounts.google.com/o/oauth2/token'; cAuthorizationScope = 'https://www.googleapis.com/auth/drive'; type TGoogleAuth = class private class var AuthKeys: TStringList; class var LastKey: string; class function GenerateAuthKey: string; class procedure AuthKeysInit(AStrings: TStringList); public class procedure DownloadFile(ALocalFile: string); class procedure UploadFile(ALocalFile: string); class function Authorization(AGD: TibgGDrive): Boolean; class function FindFile(AGD: TibgGDrive; AFileName: string): Integer; end; implementation uses System.IniFiles; { TGoogleAuth } function Auth(AGD: TibgGDrive; AKey: string): Boolean; begin AGD.Authorization := AKey; try AGD.ListResources; Result := True; except Result := False; end; end; // параметр ALocalFile - полный путь к файлу class procedure TGoogleAuth.AuthKeysInit(AStrings: TStringList); var I: Integer; StoreKey: string; begin for I := 0 to High(AuthKeysArray) do AStrings.Add(AuthKeysArray[ I ]); with TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'auth.key') do try StoreKey := ReadString('AUTH', 'AUTHKEY', ''); finally Free; end; if not StoreKey.IsEmpty then AStrings.Add(StoreKey); end; class function TGoogleAuth.Authorization(AGD: TibgGDrive): Boolean; var I: Integer; begin for I := 0 to AuthKeys.Count - 1 do begin Result := Auth(AGD, AuthKeys[ I ]); if Result then Break; end; if not Result then begin LastKey := GenerateAuthKey; Result := Auth(AGD, LastKey); end; end; class procedure TGoogleAuth.DownloadFile(ALocalFile: string); var GD: TibgGDrive; I: Integer; FName: string; begin GD := TibgGDrive.Create(nil); try // инициализируем коллекцию ключей AuthKeys := TStringList.Create; AuthKeysInit(AuthKeys); try if not Authorization(GD) then raise Exception.Create('Не удалось подключить Google Drive.') else begin with TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'auth.key') do try WriteString('AUTH', 'AUTHKEY', LastKey); finally Free; end; end; finally AuthKeys.Free; end; if GD.ResourceCount = 0 then raise Exception.Create('Не удалось получить список файлов с Google Drive.'); FName := ExtractFileName(ALocalFile); // поиск файла GD.ResourceIndex := FindFile(GD, FName); if GD.ResourceIndex = -1 then raise Exception.CreateFmt('Не удалось найти файл %s Google Drive.', [FName]); GD.LocalFile := ALocalFile; GD.Overwrite := True; try GD.DownloadFile(''); ShowInfoFmt('Файл %s успешно загружен c Google Drive.', [FName]); except on ex: EInGoogle do ShowError('Ошибка загрузки файла с Google Drive: ' + ex.Message); end; finally GD.Free; end; end; class function TGoogleAuth.FindFile(AGD: TibgGDrive; AFileName: string): Integer; var i: Integer; begin Result := -1; for i := 0 to AGD.ResourceCount - 1 do begin AGD.ResourceIndex := i; if CompareText(AFileName, Utf8ToAnsi(AGD.ResourceTitle)) = 0 then begin Result := AGD.ResourceIndex; Break; end; end; end; class function TGoogleAuth.GenerateAuthKey: string; var OAuth: TibgOAuth; begin OAuth := TibgOAuth.Create(nil); try OAuth.ClientId := cClientID; OAuth.ClientSecret := cClientSecret; OAuth.ServerAuthURL := cServerAuthURL; OAuth.ServerTokenURL := cServerTokenURL; OAuth.AuthorizationScope := cAuthorizationScope; Result := OAuth.GetAuthorization; finally OAuth.Free; end; end; class procedure TGoogleAuth.UploadFile(ALocalFile: string); var GD: TibgGDrive; I: Integer; FName: string; begin GD := TibgGDrive.Create(nil); try // инициализируем коллекцию ключей AuthKeys := TStringList.Create; AuthKeysInit(AuthKeys); try if not Authorization(GD) then raise Exception.Create('Не удалось подключить Google Drive.') else begin with TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'auth.key') do try WriteString('AUTH', 'AUTHKEY', LastKey); finally Free; end; end; finally AuthKeys.Free; end; if GD.ResourceCount = 0 then raise Exception.Create('Не удалось получить список файлов с Google Drive.'); FName := ExtractFileName(ALocalFile); // поиск файла GD.ResourceIndex := FindFile(GD, FName); // нашли - удалим if GD.ResourceIndex <> -1 then begin GD.DeleteResource(); end; GD.ResourceIndex := -1; GD.LocalFile := ALocalFile; try GD.UploadFile(FName); ShowInfoFmt('Файл %s успешно загружен на Google Drive.', [FName]); except on ex: EInGoogle do ShowError('Ошибка сохранения файла в Google Drive: ' + ex.Message); end; finally GD.Free; end; end; end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Backend.EndPoint; interface uses System.Classes, System.SysUtils, System.Generics.Collections, REST.Backend.Providers, REST.Client, REST.Backend.ServiceTypes, System.JSON; type // Base class for provider components derived from TCustomRESTRequest TBackendRequestComponent = class(TCustomRESTRequest, IBackendServiceComponent) private FProvider: IBackendProvider; FRESTClient: TRESTClient; function GetProvider: IBackendProvider; // IBackendServiceComponent function IBackendServiceComponent.GetServiceIID = GetBackendServiceIID; protected procedure ProviderChanged; virtual; function CreateService(const AProvider: IBackendProvider): IBackendService; procedure SetProvider(const Value: IBackendProvider); function GetBackendServiceIID: TGUID; virtual; abstract; procedure UpdateProvider(const AProvider: IBackendProvider); virtual; abstract; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure ClearProvider; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property ServiceIID: TGUID read GetBackendServiceIID; property Provider: IBackendProvider read GetProvider write SetProvider; end; TBackendRequestComponent<TI: IBackendService; T: Class> = class(TBackendRequestComponent) public type TExecuteProc = TProc<T>; TExecuteEvent = procedure(Sender: TObject; AAPI: T) of object; TAPIThread = TBackendAPIThread<T>; private FBackendService: TI; FBackendServiceAPI: T; FAPIThread: TAPIThread; function CreateService(const AProvider: IBackendProvider): TI; procedure SetAPIThread( const AValue: TAPIThread); protected function GetBackendServiceAPI: T; function GetBackendService: TI; procedure ClearProvider; override; function GetBackendServiceIID: TGUID; override; procedure UpdateProvider(const AValue: IBackendProvider); override; function InternalCreateBackendServiceAPI: T; virtual; abstract; function InternalCreateIndependentBackendServiceAPI: T; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property APIThread: TAPIThread read FAPIThread write SetAPIThread; end; TBackendRequestComponentAuth<TI: IBackendService; T: Class> = class(TBackendRequestComponent<TI, T>) private FAuth: IBackendAuthReg; FAuthAccess: IAuthAccess; procedure SetAuth(const Value: IBackendAuthReg); protected function CreateAuthAccess: IAuthAccess; virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public destructor Destroy; override; property Auth: IBackendAuthReg read FAuth write SetAuth; end; TCustomBackendEndpoint = class(TBackendRequestComponentAuth<IBackendCustomEndpointService, TBackendCustomEndpointAPI>, IRESTResponseJSON) public type TAllowHTTPErrors = (None, Any, ClientErrors, ClientErrorNotFound_404); private FJSONNotifyList: TList<TNotifyEvent>; FAllowHTTPErrors: TAllowHTTPErrors; function GetEndpointAPI: TBackendCustomEndpointApi; procedure JSONValueChanged(Sender: TObject); protected { IRESTResponseJSON } // Support ResponseAdapter procedure AddJSONChangedEvent(const ANotify: TNotifyEvent); procedure RemoveJSONChangedEvent(const ANotify: TNotifyEvent); procedure GetJSONResponse(out AJSONValue: TJSONValue; out AHasOwner: Boolean); function HasJSONResponse: Boolean; function HasResponseContent: Boolean; procedure DoResponseChanged; override; procedure DoResponseChanging; override; function InternalCreateBackendServiceAPI: TBackendCustomEndpointAPI; override; function InternalCreateIndependentBackendServiceAPI: TBackendCustomEndpointAPI; override; procedure DoBeforeExecute; override; procedure DoAfterExecute; override; function CreateAuthAccess: IAuthAccess; override; function CreateRequestBindSource: TSubRESTRequestBindSource; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property EndpointApi: TBackendCustomEndpointAPI read GetEndpointAPI; property AllowHTTPErrors: TAllowHTTPErrors read FAllowHTTPErrors write FAllowHTTPErrors default TAllowHTTPErrors.None; end; TBackendEndpoint = class(TCustomBackendEndPoint) published property Provider; property Auth; // property Accept; // property AcceptCharset; // property AcceptEncoding; property AutoCreateParams; // property HandleRedirects; // property Client; property Method; property Params; property Resource; property ResourceSuffix; property Response; property Timeout; property OnAfterExecute; // property ExecutionPerformance; // property SynchronizedEvents; // property OnHTTPProtocolError; property BindSource; property AllowHTTPErrors; end; implementation uses System.TypInfo, REST.Utils, REST.Backend.Exception, REST.Backend.Consts, REST.Backend.ServiceComponents, Data.Bind.Components, REST.JSON; { TCustomBackendEndpoint } procedure TCustomBackendEndpoint.AddJSONChangedEvent( const ANotify: TNotifyEvent); begin Assert(not FJSONNotifyList.Contains(ANotify)); if not FJSONNotifyList.Contains(ANotify) then FJSONNotifyList.Add(ANotify); end; constructor TCustomBackendEndpoint.Create(AOwner: TComponent); begin /// it is important to create the notify-list before /// calling the inherited constructor FJSONNotifyList := TList<TNotifyEvent>.Create; inherited; end; function TCustomBackendEndpoint.CreateAuthAccess: IAuthAccess; begin Result := TAuthAccess.Create(Self, function: IBackendAuthenticationApi begin Result := Self.GetEndpointAPI.AuthenticationApi; end); end; type TSubBackendEndpointBindSource = class(TSubRESTRequestBindSource) protected function CreateRequestAdapter: TRESTRequestAdapter; override; end; function TCustomBackendEndpoint.CreateRequestBindSource: TSubRESTRequestBindSource; begin Result := TSubBackendEndpointBindSource.Create(self); end; procedure TCustomBackendEndpoint.JSONValueChanged(Sender: TObject); var LNotifyEvent: TNotifyEvent; begin PropertyValueChanged; for LNotifyEvent in FJSONNotifyList do LNotifyEvent(Self); end; procedure TCustomBackendEndpoint.RemoveJSONChangedEvent( const ANotify: TNotifyEvent); begin Assert(FJSONNotifyList.Contains(ANotify)); FJSONNotifyList.Remove(ANotify); end; destructor TCustomBackendEndpoint.Destroy; begin FJSONNotifyList.Free; inherited; end; procedure TCustomBackendEndpoint.DoAfterExecute; begin inherited; case AllowHTTPErrors of None: GetBackendServiceApi.CheckForResponseErrors(Self.Response, []); Any: ; // No error checking ClientErrors: if not Self.Response.Status.ClientError then GetBackendServiceApi.CheckForResponseErrors(Self.Response, []); ClientErrorNotFound_404: GetBackendServiceApi.CheckForResponseErrors(Self.Response, TArray<Integer>.Create(404)); end; end; procedure TCustomBackendEndpoint.DoBeforeExecute; begin GetBackendServiceApi.PrepareClient(FRESTClient); GetBackendServiceApi.PrepareRequest(Self); inherited; end; procedure TCustomBackendEndpoint.DoResponseChanged; var Intf: IRESTResponseJSON; begin if Supports(Response, IRESTResponseJSON, Intf) then begin Intf.AddJSONChangedEvent(JSONValueChanged); if ([csLoading, csDestroying] * ComponentState) = [] then JSONValueChanged(Self); end; end; procedure TCustomBackendEndpoint.DoResponseChanging; var Intf: IRESTResponseJSON; begin if Supports(Response, IRESTResponseJSON, Intf) then Intf.RemoveJSONChangedEvent(JSONValueChanged); end; function TCustomBackendEndpoint.InternalCreateBackendServiceAPI: TBackendCustomEndpointApi; begin Result := TBackendCustomEndpointApi.Create(GetBackendService); // Service.CreateStorageApi); end; function TCustomBackendEndpoint.InternalCreateIndependentBackendServiceAPI: TBackendCustomEndpointApi; begin Result := TBackendCustomEndpointApi.Create(GetBackendService.CreateCustomEndpointApi); // Service.CreateStorageApi); end; function TCustomBackendEndpoint.GetEndpointAPI: TBackendCustomEndpointApi; begin Result := GetBackendServiceAPI; end; procedure TCustomBackendEndpoint.GetJSONResponse(out AJSONValue: TJSONValue; out AHasOwner: Boolean); begin if (Response <> nil) and (Response.JSONValue <> nil) then begin AJSONValue := Response.JSONValue; AHasOwner := True; end else begin AJSONValue := nil; AHasOwner := False; end; end; function TCustomBackendEndpoint.HasJSONResponse: Boolean; begin Result := (Response <> nil) and (Response.JSONValue <> nil); end; function TCustomBackendEndpoint.HasResponseContent: Boolean; begin Result := (Response <> nil) and (Response.ContentLength > 0); end; { TBackendServiceComponent } procedure TBackendRequestComponent.SetProvider(const Value: IBackendProvider); begin if FProvider <> Value then begin if FProvider <> nil then begin if FProvider is TComponent then TComponent(FProvider).RemoveFreeNotification(Self); end; UpdateProvider(Value); FProvider := Value; if FProvider <> nil then begin if FProvider is TComponent then TComponent(FProvider).FreeNotification(Self); end; ProviderChanged; end; end; procedure TBackendRequestComponent.ProviderChanged; begin end; procedure TBackendRequestComponent.ClearProvider; begin FProvider := nil; end; constructor TBackendRequestComponent.Create(AOwner: TComponent); var LProvider: IBackendProvider; begin inherited; FRESTClient := TRESTClient.Create(nil); Client := FRESTClient; SynchronizedEvents := False; Client.SynchronizedEvents := False; Client.RaiseExceptionOn500 := False; // Find a default provider if not Supports(AOwner, IBackendProvider, LProvider) then if csDesigning in ComponentState then LProvider := TRESTFindDefaultComponent.FindDefaultIntfT<IBackendProvider>(Self); if LProvider <> nil then if TBackendProviders.Instance.FindService(LProvider.ProviderID, ServiceIID) <> nil then // Valid provider Provider := LProvider; end; function TBackendRequestComponent.CreateService( const AProvider: IBackendProvider): IBackendService; var LService: TBackendProviders.TService; begin LService := TBackendProviders.Instance.FindService(AProvider.ProviderID, ServiceIID); if LService <> nil then begin Result := LService.FactoryProc(AProvider, ServiceIID) as IBackendService; end else raise EBackendServiceError.CreateFmt(sServiceNotSupportedByProvider, [AProvider.ProviderID]); end; destructor TBackendRequestComponent.Destroy; begin FRESTClient.Free; inherited; end; function TBackendRequestComponent.GetProvider: IBackendProvider; begin Result := FProvider; end; procedure TBackendRequestComponent.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; /// clean up component-references if (Operation = opRemove) then begin if (FProvider is TComponent) and (TComponent(FProvider) = AComponent) then ClearProvider; end; end; { TBackendServiceComponent<TService: IBackendService; TApi: Class> } destructor TBackendRequestComponent<TI, T>.Destroy; begin FAPIThread.Free; ClearProvider; inherited; end; constructor TBackendRequestComponent<TI, T>.Create(AOwner: TComponent); begin inherited; FAPIThread := TAPIThread.Create; FAPIThread.OnCreateAPI := function: T begin Result := InternalCreateIndependentBackendServiceAPI; end; end; function TBackendRequestComponent<TI, T>.CreateService( const AProvider: IBackendProvider): TI; begin Result := TI(inherited CreateService(AProvider)); Assert(Supports(Result, ServiceIID)); end; function TBackendRequestComponent<TI, T>.GetBackendServiceAPI: T; begin if FBackendServiceAPI = nil then begin if FBackendService <> nil then FBackendServiceAPI := InternalCreateBackendServiceAPI // TBackendQueryApi.Create(FService.CreateQueryApi) else raise EBackendServiceError.CreateFmt(sNoBackendService, [Self.ClassName]); end; Result := FBackendServiceAPI; end; function TBackendRequestComponent<TI, T>.GetBackendService: TI; begin Result := FBackendService; end; function TBackendRequestComponent<TI, T>.GetBackendServiceIID: TGUID; begin Result := GetTypeData(TypeInfo(TI)).Guid; end; function TBackendRequestComponent<TI, T>.InternalCreateIndependentBackendServiceAPI: T; begin raise ENotImplemented.Create('InternalCreateIndependentBackendServiceAPI'); // do not localize end; procedure TBackendRequestComponent<TI, T>.SetAPIThread(const AValue: TAPIThread); begin FAPIThread.Assign(AValue); end; procedure TBackendRequestComponent<TI, T>.ClearProvider; begin inherited; FBackendService := nil; FreeAndNil(FBackendServiceAPI); end; procedure TBackendRequestComponent<TI, T>.UpdateProvider(const AValue: IBackendProvider); begin ClearProvider; if AValue <> nil then FBackendService := CreateService(AValue); // May raise an exception end; { TBackendRequestComponentAuth<TI, T> } function TBackendRequestComponentAuth<TI, T>.CreateAuthAccess: IAuthAccess; begin Result := nil; end; destructor TBackendRequestComponentAuth<TI, T>.Destroy; begin Auth := nil; // Unregister for auth inherited; end; procedure TBackendRequestComponentAuth<TI, T>.Notification( AComponent: TComponent; Operation: TOperation); begin inherited; /// clean up component-references if (Operation = opRemove) then begin if (FAuth is TComponent) and (TComponent(FAuth) = AComponent) then Auth := nil; end; end; procedure TBackendRequestComponentAuth<TI, T>.SetAuth( const Value: IBackendAuthReg); begin if FAuth <> Value then begin if FAuth <> nil then begin if FAuth is TComponent then TComponent(FAuth).RemoveFreeNotification(Self); if FAuthAccess <> nil then try FAuth.UnregisterForAuth(FAuthAccess); finally FAuthAccess := nil; end; end; FAuth := Value; if FAuth <> nil then begin if FAuth is TComponent then TComponent(FAuth).FreeNotification(Self); FAuthAccess := CreateAuthAccess; if FAuthAccess <> nil then FAuth.RegisterForAuth(FAuthAccess); end; end; end; { TBackendEndpointRequestAdapter } type TBackendEndpointRequestAdapter = class(TRESTRequestAdapter) protected procedure CreatePropertyFields; override; end; function TSubBackendEndpointBindSource.CreateRequestAdapter: TRESTRequestAdapter; begin Result := TBackendEndpointRequestAdapter.Create(Self); end; procedure TBackendEndpointRequestAdapter.CreatePropertyFields; const sJSONText = 'Response.JSONText'; begin inherited; CreateReadOnlyField<string>(sJSONText, nil, TScopeMemberType.mtText, function: string begin if Request.Response <> nil then result := Request.Response.JSONText else Result := ''; end); end; end.
unit BrickCamp.Repositories.TAnswer; interface uses System.JSON, Spring.Container.Injection, Spring.Container.Common, BrickCamp.IDB, BrickCamp.Model.TAnswer, BrickCamp.Repositories.IAnswer; type TAnswerRepository = class(TInterfacedObject, IAnswerRepository) protected [Inject] FDb: IBrickCampDb; public function GetOne(const Id: Integer): TAnswer; function GetList: TJSONArray; procedure Insert(const Answer: TAnswer); procedure Update(const Answer: TAnswer); procedure Delete(const Id: Integer); function GetListByQuestionId(const QuestionId: Integer): TJSONArray; end; implementation uses Spring.Collections, Spring.Persistence.Criteria.Interfaces, Spring.Persistence.Criteria.Properties, MARS.Core.Utils; { TAnswerRepository } procedure TAnswerRepository.Delete(const Id: Integer); var Answer: TAnswer; begin Answer := FDb.GetSession.FindOne<TAnswer>(Id); if Assigned(Answer) then FDb.GetSession.Delete(Answer); end; function TAnswerRepository.GetList: TJSONArray; var LList: IList<TAnswer>; LItem: TAnswer; begin LList := FDb.GetSession.FindAll<TAnswer>; result := TJSONArray.Create; for LItem in LList do Result.Add(ObjectToJson(LItem)); end; function TAnswerRepository.GetListByQuestionId(const QuestionId: Integer): TJSONArray; var QuestionIdCriteria: Prop; LList: IList<TAnswer>; LItem: TAnswer; begin QuestionIdCriteria := Prop.Create('QUESR'); LList := FDb.GetSession.FindWhere<TAnswer>(QuestionIdCriteria = QuestionId); result := TJSONArray.Create; for LItem in LList do Result.Add(ObjectToJson(LItem)); end; function TAnswerRepository.GetOne(const Id: Integer): TAnswer; begin result := FDb.GetSession.FindOne<TAnswer>(Id); end; procedure TAnswerRepository.Insert(const Answer: TAnswer); begin FDb.GetSession.Insert(Answer); end; procedure TAnswerRepository.Update(const Answer: TAnswer); begin FDb.GetSession.Update(Answer); end; end.
unit LngTools; {$I DEFINE.INC} interface uses Forms, Windows; {$I ..\LNG\LNGC.INC} {$I ..\LNG\CCONST.INC} {$I ..\LNG\FCONST.INC} const idlEnglish = 0; {$IFDEF LNG_RUSSIAN} idlRussian = 1; {$ENDIF} {$IFDEF LNG_MITKY} idlMitky = 2; {$ENDIF} {$IFDEF LNG_ROMANIAN} idlRomanian = 3; {$ENDIF} {$IFDEF LNG_CHECH} idlCzech = 4; {$ENDIF} {$IFDEF LNG_UKRAINIAN} idlUkrainian = 5; {$ENDIF} {$IFDEF LNG_BULGARIAN} idlBulgarian = 6; {$ENDIF} {$IFDEF LNG_POLISH} idlPolish = 7; {$ENDIF} {$IFDEF LNG_GERMAN} idlGerman = 8; {$ENDIF} {$IFDEF LNG_DUTCH} idlDutch = 9; {$ENDIF} {$IFDEF LNG_SPANISH} idlSpanish = 10; {$ENDIF} {$IFDEF LNG_DANISH} idlDanish = 11; {$ENDIF} var ResLngBase: Integer; CurrentLng: Integer; procedure GridFillColLng(AG: Pointer; Id: Integer); procedure _GridFillColLng(AG: Pointer; Id: Integer; lngbase: integer); procedure GridFillRowLng(AG: Pointer; Id: Integer); procedure DisplayErrorLng(Id: Integer; Handle: DWORD); procedure DisplayInfoLng(Id: Integer; Handle: DWORD); procedure DisplayErrorFmtLng(Id: Integer; const Args: array of const; Handle: DWORD); function YesNoConfirmLng(Id: Integer; AHandle: DWORD): Boolean; function OkCancelConfirmLng(Id: Integer; AHandle: DWORD): Boolean; function LngStr(i: Integer): string; function _LngStr(i: Integer; lngbase:integer): string; function FormatLng(Id: Integer; const Args: array of const): string; procedure FillForm(f: TForm; Id: Integer); procedure _FillForm(f: TForm; Id: Integer; lngbase: integer); procedure SetLanguage(Index: Integer); procedure LanguageDone; implementation uses mGrids, xBase, SysUtils, Classes, Menus, StdCtrls, ExtCtrls, ComCtrls, CheckLst; {$R ..\LNG\ENG.RES} {$IFDEF LNG_GERMAN} {$R ..\LNG\GER.RES} {$ENDIF} {$IFDEF LNG_RUSSIAN} {$R ..\LNG\RUS.RES} {$ENDIF} {$IFDEF LNG_DUTCH} {$R ..\LNG\DUT.RES} {$ENDIF} {$IFDEF LNG_DANISH} {$R ..\LNG\DAN.RES} {$ENDIF} procedure GridFillColLng(AG: Pointer; Id: Integer); var g: TAdvGrid absolute AG; s,z: string; i: Integer; begin s := LngStr(Id); i := 0; while s <> '' do begin GetWrd(s, z, '|'); g.Cells[I, 0] := ' ' + z; Inc(i); end; end; procedure _GridFillColLng(AG: Pointer; Id: Integer; lngbase: Integer); var g: TAdvGrid absolute AG; s,z: string; i: Integer; begin s := _LngStr(Id, lngbase); i := 0; while s <> '' do begin GetWrd(s, z, '|'); g.Cells[I, 0] := ' ' + z; Inc(i); end; end; procedure GridFillRowLng(AG: Pointer; Id: Integer); var g: TAdvGrid absolute AG; s,z: string; i: Integer; begin s := LngStr(Id); i := 0; while s <> '' do begin GetWrd(s, z, '|'); g.Cells[0, I] := ' '+z; Inc(i); end; end; procedure DisplayErrorLng(Id: Integer; Handle: DWORD); begin DisplayError(LngStr(Id), Handle); end; procedure DisplayInfoLng(Id: Integer; Handle: DWORD); begin DisplayCustomInfo(LngStr(Id), Handle); end; procedure DisplayErrorFmtLng(Id: Integer; const Args: array of const; Handle: DWORD); begin DisplayError(FormatLng(Id, Args), Handle); end; function LngStr(i: Integer): string; const StrBufSize = $1000; var Buf: array[0..StrBufSize] of Char; l: Integer; begin // SetThreadLocale(LANG_RUSSIAN); l := LoadString(HInstance, i + ResLngBase, @Buf, StrBufSize); if l = 0 then GlobalFail('LoadString Idx %d Error %d (ResLngBase=%d)', [i, GetLastError, ResLngBase]); SetLength(Result, l); Move(Buf, Result[1], l); end; function _LngStr(i: Integer; lngbase:integer): string; const StrBufSize = $1000; var Buf: array[0..StrBufSize] of Char; l: Integer; begin // SetThreadLocale(LANG_RUSSIAN); l := LoadString(HInstance, i + LngBase, @Buf, StrBufSize); if l = 0 then GlobalFail('LoadString Idx %d Error %d (ResLngBase=%d)', [i, GetLastError, ResLngBase]); SetLength(Result, l); Move(Buf, Result[1], l); end; function FormatLng(Id: Integer; const Args: array of const): string; begin Result := Format(LngStr(Id), Args); end; function YesNoConfirmLng(Id: Integer; AHandle: DWORD): Boolean; begin Result := YesNoConfirm(LngStr(Id), AHandle); end; function OkCancelConfirmLng(Id: Integer; AHandle: DWORD): Boolean; begin Result := OkCancelConfirm(LngStr(Id), AHandle); end; procedure FillForm; var s, z: string; L: TStringColl; i, j: Integer; C: TComponent; begin L := TStringColl.Create('FillForm.L'); L.LoadFromString(LngStr(Id)); F.Caption := L[0]; for i := 1 to L.Count - 1 do begin s := L[i]; GetWrd(s, z, '|'); C := F.FindComponent(z); if C = nil then Continue; GetWrd(s, z, '|'); if C is TMenuItem then TMenuItem(C).Caption := z else if C is TLabel then TLabel(C).Caption := z else if C is TStaticText then TStaticText(C).Caption := z else if C is TButton then TButton(C).Caption := z else if C is TCheckBox then TCheckBox(C).Caption := z else if C is TRadioButton then TRadioButton(C).Caption := z else if C is TGroupBox then TGroupBox (C).Caption := z else if C is TPanel then TPanel(C).Caption := z else if C is TRadioGroup then begin TRadioGroup(C).Caption := z; j := 0; while s <> '' do begin GetWrd(s, z, '|'); TRadioGroup(C).Items[j] := z; Inc(j); end; end else if C is TPageControl then begin TPageControl(C).Pages[0].Caption := z; j := 1; while s <> '' do begin GetWrd(s, z, '|'); TPageControl(C).Pages[j].Caption := z; Inc(j); end; end else if C is TListView then begin TListView(C).Columns[0].Caption := z; j := 1; while s <> '' do begin GetWrd(s, z, '|'); TListView(C).Columns[j].Caption := z; Inc(j); end; end else if C is THeaderControl then begin THeaderControl(C).Sections[0].Text := z; j := 1; while s <> '' do begin GetWrd(s, z, '|'); THeaderControl(C).Sections[j].Text := z; Inc(j); end; end; if C is TComboBox then begin j := 0; while s <> '' do begin GetWrd(s, z, '|'); TComboBox(C).Items[j] := z; Inc(j); if TComboBox(C).Items.Count - 1 < j then break; end; end; if C is TCheckListBox then begin j := 0; while s <> '' do begin GetWrd(s, z, '|'); TCheckListBox(C).Items[j] := z; Inc(j); if TCheckListBox(C).Items.Count - 1 < j then break; end; end; end; FreeObject(L); end; procedure _FillForm; var s, z: string; L: TStringColl; i, j: Integer; C: TComponent; begin L := TStringColl.Create('_FillForm.L'); L.LoadFromString(_LngStr(Id, lngbase)); F.Caption := L[0]; for i := 1 to L.Count - 1 do begin s := L[i]; GetWrd(s, z, '|'); C := F.FindComponent(z); if C = nil then Continue; GetWrd(s, z, '|'); if C is TMenuItem then TMenuItem(C).Caption := z else if C is TLabel then TLabel(C).Caption := z else if C is TStaticText then TStaticText(C).Caption := z else if C is TButton then TButton(C).Caption := z else if C is TCheckBox then TCheckBox(C).Caption := z else if C is TRadioButton then TRadioButton(C).Caption := z else if C is TGroupBox then TGroupBox (C).Caption := z else if C is TPanel then TPanel(C).Caption := z else if C is TRadioGroup then begin TRadioGroup(C).Caption := z; j := 0; while s <> '' do begin GetWrd(s, z, '|'); TRadioGroup(C).Items[j] := z; Inc(j); end; end else if C is TPageControl then begin TPageControl(C).Pages[0].Caption := z; j := 1; while s <> '' do begin GetWrd(s, z, '|'); TPageControl(C).Pages[j].Caption := z; Inc(j); end; end else if C is TListView then begin TListView(C).Columns[0].Caption := z; j := 1; while s <> '' do begin GetWrd(s, z, '|'); TListView(C).Columns[j].Caption := z; Inc(j); end; end else if C is THeaderControl then begin THeaderControl(C).Sections[0].Text := z; j := 1; while s <> '' do begin GetWrd(s, z, '|'); THeaderControl(C).Sections[j].Text := z; Inc(j); end; end; if C is TComboBox then begin j := 0; while s <> '' do begin GetWrd(s, z, '|'); TComboBox(C).Items[j] := z; Inc(j); if TComboBox(C).Items.Count - 1 < j then break; end; end; if C is TCheckListBox then begin j := 0; while s <> '' do begin GetWrd(s, z, '|'); TCheckListBox(C).Items[j] := z; Inc(j); if TCheckListBox(C).Items.Count - 1 < j then break; end; end; end; FreeObject(L); end; procedure SetLanguage; begin CurrentLng := Index; case Index of MaxInt :; {$IFDEF LNG_SPANISH} idlSpanish: ResLngBase := LngBaseSpanish; {$ENDIF} {$IFDEF LNG_DUTCH} idlDutch: ResLngBase := LngBaseDutch; {$ENDIF} {$IFDEF LNG_GERMAN} idlGerman: ResLngBase := LngBaseGerman; {$ENDIF} {$IFDEF LNG_DANISH} idlDanish: ResLngBase := LngBaseDanish; {$ENDIF} {$IFDEF LNG_RUSSIAN} idlRussian: ResLngBase := LngBaseRussian; {$ENDIF} else begin CurrentLng := 0; ResLngBase := LngBaseEnglish; end; end; end; procedure LanguageDone; begin end; initialization ResLngBase := LngBaseEnglish; CurrentLng := -1; end.
unit SoundSynthesizer; interface uses SoundRepository, SettingsManager, TextTokenizer, WaveStorage, Generics.Collections, SysUtils, Classes; type TSoundSynthesizer = class private FRepository: TSoundRepository; FSettings: TSettingsManager; FTokenizer: TTextTokenizer; FSoundsNames: TStringList; private procedure SetRepository(const ARepository: TSoundRepository); procedure SetSettings(const ASettings: TSettingsManager); procedure SetTokenizer(const ATokenizer: TTextTokenizer); function GetSoundsNames(): TStringList; function VocalizeWord(const AWord: String): TArray<TWave>; function VocalizeSentence(const ATokenizedSentence: TArray<TTextTokenizer.TSentenceUnit>): TWave; overload; procedure MergeWaves(var ADestination: TWave; const ASource: TArray<TWave>); function GetRepository: TSoundRepository; function GetSettings: TSettingsManager; function GetTokenizer: TTextTokenizer; function IsSoftOrHardSign(AChar: String): Boolean; public constructor Create(); overload; constructor Create(const ARepository: TSoundRepository; const ASettings: TSettingsManager; const ATokenizer: TTextTokenizer); overload; destructor Destroy(); override; function VocalizeSentence(const ASentence: String): TWave; overload; function VocalizeText(const AText: String): TWave; published property Repository: TSoundRepository read GetRepository write SetRepository; property Settings: TSettingsManager read GetSettings write SetSettings; property Tokenizer: TTextTokenizer read GetTokenizer write SetTokenizer; end; implementation constructor TSoundSynthesizer.Create; begin end; constructor TSoundSynthesizer.Create(const ARepository: TSoundRepository; const ASettings: TSettingsManager; const ATokenizer: TTextTokenizer); begin FRepository := ARepository; FSettings := ASettings; FTokenizer := ATokenizer; FSoundsNames := TStringList.Create; FSoundsNames.AddStrings(FRepository.GetSoundsNames); end; destructor TSoundSynthesizer.Destroy; begin inherited; FreeAndNil(FSoundsNames); end; function TSoundSynthesizer.GetRepository: TSoundRepository; begin Result := FRepository; end; function TSoundSynthesizer.GetSettings: TSettingsManager; begin Result := FSettings; end; function TSoundSynthesizer.GetSoundsNames: TStringList; begin Result := FSoundsNames; end; function TSoundSynthesizer.GetTokenizer: TTextTokenizer; begin Result := FTokenizer; end; function TSoundSynthesizer.IsSoftOrHardSign(AChar: String): Boolean; begin Result := (AChar.Contains('ь') or AChar.Contains('ъ')); end; procedure TSoundSynthesizer.SetRepository(const ARepository: TSoundRepository); begin FRepository := ARepository; end; procedure TSoundSynthesizer.SetSettings(const ASettings: TSettingsManager); begin FSettings := ASettings; end; procedure TSoundSynthesizer.SetTokenizer(const ATokenizer: TTextTokenizer); begin FTokenizer := ATokenizer; end; procedure TSoundSynthesizer.MergeWaves(var ADestination: TWave; const ASource: TArray<TWave>); var i: Integer; begin for i := Low(ASource) to High(ASource) do begin if (ADestination.Empty) then begin ADestination.Assign(ASource[i]); end else begin ADestination.Insert(INFINITE, ASource[i]); end; end; end; function TSoundSynthesizer.VocalizeSentence(const ASentence: String): TWave; var TokenizedSentence: TArray<TTextTokenizer.TSentenceUnit>; begin TokenizedSentence := Tokenizer.GetTokenizedSentence(ASentence); Result := VocalizeSentence(TokenizedSentence); end; function TSoundSynthesizer.VocalizeText(const AText: String): TWave; var TokenizedSentences: TArray<TArray<TTextTokenizer.TSentenceUnit>>; TokenizedSentence: TArray<TTextTokenizer.TSentenceUnit>; VocalizedSentence: TWave; begin Result := TWave.Create; TokenizedSentences := Tokenizer.GetTokenizedSentences(AText); for TokenizedSentence in TokenizedSentences do begin VocalizedSentence := VocalizeSentence(TokenizedSentence); if (Result.Empty) then begin Result.Assign(VocalizedSentence); end else begin Result.Insert(INFINITE, VocalizedSentence); end; FreeAndNil(VocalizedSentence); end; end; function TSoundSynthesizer.VocalizeSentence(const ATokenizedSentence: TArray<TTextTokenizer.TSentenceUnit>): TWave; var i: Integer; begin Result := TWave.Create; for i := Low(ATokenizedSentence) to High(ATokenizedSentence) do begin case ATokenizedSentence[i].UnitType of utNone: raise Exception.CreateFmt('Unrecognized token: "%s"', [ATokenizedSentence[i].Text]); utHyphen: Result.InsertSilence(INFINITE, Settings.HyphenDelay); utExclamationMark: Result.InsertSilence(INFINITE, Settings.ExclamationMarkDelay); utComa: Result.InsertSilence(INFINITE, Settings.ComaDelay); utColon: Result.InsertSilence(INFINITE, Settings.ColonDelay); utSemicolon: Result.InsertSilence(INFINITE, Settings.SemicolonDelay); utDot: Result.InsertSilence(INFINITE, Settings.DotDelay); utQuestionMark: Result.InsertSilence(INFINITE, Settings.QuestionMarkDelay); utSpace: Result.InsertSilence(INFINITE, Settings.SpaceDelay); utWord: MergeWaves(Result, VocalizeWord(ATokenizedSentence[i].Text)); end; end; end; function TSoundSynthesizer.VocalizeWord(const AWord: String): TArray<TWave>; var Index, Length: Integer; CharactersLeft: Integer; Wave: TWave; Waves: TList<TWave>; Exist: Integer; begin Waves := TList<TWave>.Create; Wave := Repository.GetSoundByName(AWord); if (Wave <> nil) then begin Waves.Add(Wave); Result := Waves.ToArray; FreeAndNil(Waves); Exit; end; Index := 1; CharactersLeft := AWord.Length; while True do begin if (CharactersLeft <= 0) then begin break; end; Length := 1; repeat Exist := FSoundsNames.IndexOf(Copy(AWord, Index, Length)); Inc(Length); until (Exist = -1) or ((Index + Length) > (High(AWord) + 1)); if (Exist = -1) then begin Dec(Length, 2); end else begin Dec(Length); end; if (Length = 0) then begin if (IsSoftOrHardSign(Copy(AWord, Index, 1))) then begin Inc(Index); Dec(CharactersLeft); continue; end; raise Exception.CreateFmt('Impossible to form a word "%s" at index: %d', [AWord, Index]); end; Wave := Repository.GetSoundByName(Copy(AWord, Index, Length)); Waves.Add(Wave); Inc(Index, Length); Dec(CharactersLeft, Length); end; Result := Waves.ToArray; FreeAndNil(Waves); end; end.
unit DataUtil; interface uses SysUtils, Classes, DB, SqlExpr, DBClient, Controls, Variants, { helsonsant } Util; type { Acoes de Registro } AcaoDeRegistro = (adrIncluir, adrCarregar, adrExcluir, adrOutra); { Operacao de Registro } OperacaoDeRegistro = (odrIncluir, odrAlterar, odrExcluir, odrInativar); { Status de Registro } StatusRegistro = (srAtivo, srInativo, srExcluido, srCancelado); { Status de Comanda } StatusComanda = (scAberta, scPendente, scQuitada); { Débito e Crédito } DebitoCredito = (dcDebito, dcCredito); { Tipos de Origem de Movimento de Caixa } TiposDeOrigemDeMovimentoDeCaixa = (tomcComanda, tomcFechamentoDeConta, tomcCaixa, tomcVendaRapida); { Meios de Pagamento } MeiosDePagamento = (mpagDinheiro, mpagCartaoDebito, mpagCartaoCredito, mpagCheque, mpagBoleto, mpagNotaPromissoria, mpagDuplicata); { Operações de Caixa } OperacoesDeCaixa = (odcAbertura, odcTroco, odcSaida, odcSuprimento, odcSangria, odcFechamento, odcRecebimentoDeVenda, odcRecebimentoDeVendaAPrazo, odcExtrato); TSql = class private FSelect: string; FFrom: string; FWhere: string; FGroup: string; FHaving: string; FOrder: string; FMetaDados: string; FCondicaoDeJuncao: string; public function Select(const Select: string): TSql; function From(const From: string): TSql; function Where(const Where: string): TSql; function Group(const Group: string): TSql; function Having(const Having: string): TSql; function Order(const Order: string): TSql; function CondicaoDeJuncao(const CondicaoDeJuncao: string): TSql; function ObterSql: string; function ObterSqlComCondicaoDeJuncao: string; function ObterSqlFiltrado(const Filtro: string): string; function ObterSqlMetadados: string; function MetaDados(const MetaDados: string): TSql; end; TTipoCriterio = (tcIgual, tcComo, tcEntre, tcMaior, tcMenor, tcMaiorOuIgual, tcMenorOuIgual); Criterio = class of TCriterio; TCriterio = class public class function Campo(const NomeCampo: string): Criterio; class function Igual(const Valor: Variant): Criterio; class function Como(const Valor: string): Criterio; class function Entre(const ValorInicial: Variant): Criterio; class function E(const ValorFinal: Variant): Criterio; class function MaiorQue(const Valor: Variant): Criterio; class function MaiorOuIgualQue(const Valor: Variant): Criterio; class function MenorQue(const Valor: Variant): Criterio; class function MenorOuIgualQue(const Valor: Variant): Criterio; class function Obter: string; class function ConectorE: string; class function ConectorOu: string; end; TObjectIdentificator = class(TObject) private FQuery: TSqlDataSet; protected FHigh: Int64; FLow: Int64; procedure GetNextHigh; public constructor Create(const QueryComponent: TSqlDataSet); reintroduce; function GetHigh: Int64; function GetLow: Int64; function GetOID: string; end; TDataUtil = class(TObject) private FObjectIdentificator: TObjectIdentificator; private class function ExistemFlags(DataSet: TDataSet): Boolean; public class procedure ConnectionCleanUp(DataModule: TDataModule); class function GenerateDocumentNumber(const DocumentName: string; QueryComponent: TSqlDataSet): string; function GetOIDGenerator( const QueryComponent: TSqlDataSet): TObjectIdentificator; class procedure GravarFlagsDoRegistro(const DataSet: TDataSet; const Operacao: OperacaoDeRegistro); procedure OidVerify(const DataSet: TDataSet; const KeyField: string); class procedure PostChanges(const DataSet: TDataSet); end; function RetornarAcaoDeRegistro( const CodigoDaAcaoDeRegistro: Integer): AcaoDeRegistro; var FCampo: string; FValorInicial: Variant; FValorFinal: Variant; FTipoCriterio: TTipoCriterio; implementation uses { helsonsant } UnModelo; function RetornarAcaoDeRegistro( const CodigoDaAcaoDeRegistro: Integer): AcaoDeRegistro; begin if CodigoDaAcaoDeRegistro = 0 then Result := adrIncluir else if CodigoDaAcaoDeRegistro = 1 then Result := adrCarregar else Result := adrOutra; end; { TFlObjetcIdentificator } constructor TObjectIdentificator.Create(const QueryComponent: TSqlDataSet); begin inherited Create; Self.FQuery := QueryComponent; end; function TObjectIdentificator.GetHigh: Int64; begin if Self.FHigh = 0 then Self.GetNextHigh(); Result := Self.FHigh; end; function TObjectIdentificator.GetLow: Int64; begin if Self.FLow = 9999 then begin Self.GetNextHigh(); Self.FLow := 1; end else Inc(Self.FLow); Result := Self.FLow; end; procedure TObjectIdentificator.GetNextHigh; begin Self.FQuery.Active := False; Self.FQuery.CommandText := 'SELECT GEN_ID(OIDS, 1) NEXT_HIGH ' + ' FROM ESCLR'; Self.FQuery.Open(); Self.FHigh := Self.FQuery.Fields[0].Value; Self.FQuery.Close(); end; function TObjectIdentificator.GetOID: string; var _high: string; _low: string; begin _high := IntToStr(Self.GetHigh()); _low := IntToStr(Self.GetLow()); Result := UpperCase(TText.EZeros(_high, 10) + TText.EZeros(_low, 4)); end; { TDataUtil } class procedure TDataUtil.ConnectionCleanUp(DataModule: TDataModule); var i: Integer; begin for i := 0 to DataModule.ComponentCount-1 do if (DataModule.Components[i] is TClientDataSet) and TClientDataSet(DataModule.Components[i]).Active then begin TClientDataSet(DataModule.Components[i]).EmptyDataSet(); TClientDataSet(DataModule.Components[i]).Close(); end; end; class function TDataUtil.ExistemFlags(DataSet: TDataSet): Boolean; begin Result := (DataSet.FindField('REC_STT') <> nil) and (DataSet.FindField('REC_INS') <> nil) and (DataSet.FindField('REC_UPD') <> nil) and (DataSet.FindField('REC_DEL') <> nil); end; class function TDataUtil.GenerateDocumentNumber(const DocumentName: string; QueryComponent: TSqlDataSet): string; begin QueryComponent.Active := False; QueryComponent.CommandText := Format('SELECT GEN_ID(%s, 1) NEXT_DOCUMENT ' + ' FROM ESCLR ', [DocumentName]); QueryComponent.Open(); Result := QueryComponent.Fields[0].AsString; QueryComponent.Close(); end; function TDataUtil.GetOIDGenerator( const QueryComponent: TSqlDataSet): TObjectIdentificator; begin if Self.FObjectIdentificator = nil then Self.FObjectIdentificator := TObjectIdentificator.Create(QueryComponent); Result := Self.FObjectIdentificator end; class procedure TDataUtil.GravarFlagsDoRegistro(const DataSet: TDataSet; const Operacao: OperacaoDeRegistro); var _existemFlags: Boolean; _agora: TDate; begin _agora := Now; _existemFlags := Self.ExistemFlags(DataSet); if _existemFlags then begin if DataSet.FieldByName('REC_STT').AsString = '' then DataSet.FieldByName('REC_STT').AsInteger := Ord(srAtivo); if Operacao = odrIncluir then DataSet.FieldByName('REC_INS').AsDateTime := _agora; DataSet.FieldByName('REC_UPD').AsDateTime := _agora; end; end; procedure TDataUtil.OidVerify(const DataSet: TDataSet; const KeyField: string); var _operacao: OperacaoDeRegistro; begin if DataSet.FieldByName(KeyField).AsString = '' then begin DataSet.FieldByName(KeyField).Value := Self.GetOIDGenerator(nil).GetOID(); _operacao := odrIncluir; end else _operacao := odrAlterar; Self.GravarFlagsDoRegistro(DataSet, _operacao); end; class procedure TDataUtil.PostChanges(const DataSet: TDataSet); begin if DataSet.State in [dsEdit, dsInsert] then DataSet.Post; end; { TSql } function TSql.From(const From: string): TSql; begin Self.FFrom := from; Result := Self; end; function TSql.ObterSqlFiltrado(const Filtro: string): string; begin Result := Format('SELECT %s FROM %s ', [Self.FSelect, Self.FFrom]); if Self.FWhere <> '' then if Filtro <> '' then Result := Format('%s WHERE %s AND %s ', [Result, Self.FWhere, Filtro]) else Result := Format('%s WHERE %s ', [Result, Self.FWhere]) else if Filtro <> '' then Result := Format('%s WHERE %s ', [Result, Filtro]); if Self.FGroup <> '' then Result := Format('%s GROUP BY %s ', [Result, Self.FGroup]); if Self.FHaving <> '' then Result := Format('%s HAVING %s ', [Result, Self.FHaving]); if Self.FOrder <> '' then Result := Format('%s ORDER BY %s', [Result, Self.FOrder]); end; function TSql.ObterSql: string; begin Result := Self.ObterSQLFiltrado(''); end; function TSql.Group(const Group: string): TSql; begin Self.FGroup := Group; Result := Self; end; function TSql.having(const Having: string): TSql; begin Self.FHaving := Having; Result := Self; end; function TSql.order(const Order: string): TSql; begin Self.FOrder := Order; Result := Self; end; function TSql.Select(const Select: string): TSql; begin Self.FSelect := Select; Result := Self; end; function TSql.Where(const Where: string): TSql; begin Self.FWhere := Where; Result := Self; end; function TSql.MetaDados(const MetaDados: string): TSql; begin Self.FMetadados := MetaDados; Result := Self; end; function TSql.ObterSqlMetadados: string; begin Result := Self.ObterSqlFiltrado(Self.FMetaDados) end; function TSql.CondicaoDeJuncao(const CondicaoDeJuncao: string): TSql; begin Self.FCondicaoDeJuncao := CondicaoDeJuncao; Result := Self; end; function TSql.ObterSqlComCondicaoDeJuncao: string; begin Result := Self.ObterSqlFiltrado(Self.FCondicaoDeJuncao); end; { TCriterio } class function TCriterio.Campo(const NomeCampo: string): Criterio; begin FCampo := NomeCampo; Result := Self; end; class function TCriterio.Como(const Valor: string): Criterio; begin FValorInicial := Valor; FTipoCriterio := tcComo; Result := Self; end; class function TCriterio.ConectorE: string; begin Result := ' AND '; end; class function TCriterio.ConectorOu: string; begin Result := ' OR '; end; class function TCriterio.E(const ValorFinal: Variant): Criterio; begin FValorFinal := ValorFinal; Result := Self; end; class function TCriterio.Entre(const ValorInicial: Variant): Criterio; begin FValorInicial := ValorInicial; FTipoCriterio := tcEntre; Result := Self; end; class function TCriterio.Igual(const Valor: Variant): Criterio; begin FValorInicial := Valor; FTipoCriterio := tcIgual; Result := Self; end; class function TCriterio.MaiorOuIgualQue(const Valor: Variant): Criterio; begin FValorInicial := Valor; FTipoCriterio := tcMaiorOuIgual; Result := Self; end; class function TCriterio.MaiorQue(const Valor: Variant): Criterio; begin FValorInicial := Valor; FTipoCriterio := tcMaior; Result := Self; end; class function TCriterio.MenorOuIgualQue(const Valor: Variant): Criterio; begin FValorInicial := Valor; FTipoCriterio := tcMenorOuIgual; Result := Self; end; class function TCriterio.MenorQue(const Valor: Variant): Criterio; begin FValorInicial := Valor; FTipoCriterio := tcMenor; Result := Self; end; class function TCriterio.Obter: string; begin case FTipoCriterio of tcIgual: begin if VarType(FValorInicial) = varString then Result := FCampo + '=' + QuotedStr(FValorInicial) else Result := FCampo + '=' + VarToStr(FValorInicial); end; tcComo: begin Result := FCampo + ' LIKE ' + QuotedStr('%' + FValorInicial + '%'); end; tcMaior: begin if VarType(FValorInicial) = varString then Result := FCampo + '>' + QuotedStr(FValorInicial) else Result := FCampo + '>' + VarToStr(FValorInicial); end; tcMenor: begin if VarType(FValorInicial) = varString then Result := FCampo + '<' + QuotedStr(FValorInicial) else Result := FCampo + '<' + VarToStr(FValorInicial); end; tcMaiorOuIgual: begin if VarType(FValorInicial) = varString then Result := FCampo + '>=' + QuotedStr(FValorInicial) else Result := FCampo + '>=' + VarToStr(FValorInicial); end; tcMenorOuIgual: begin if VarType(FValorInicial) = varString then Result := FCampo + '<=' + QuotedStr(FValorInicial) else Result := FCampo + '<=' + VarToStr(FValorInicial); end; tcEntre: begin if (VarType(FValorInicial) = varString) then Result := FCampo + ' BETWEEN ' + QuotedStr(FValorInicial) + ' AND ' + QuotedStr(FValorFinal) else if VarType(FValorInicial) = varDate then Result := FCampo + ' BETWEEN CAST(' + QuotedStr(FormatDateTime('mm/dd/yyyy', FValorInicial)) + ' as Date) AND CAST(' + QuotedStr(FormatDateTime('mm/dd/yyyy', FValorFinal)) + ' as Date)' else Result := FCampo + ' BETWEEN ' + VarToStr(FValorInicial) + ' AND ' + VarToStr(FValorFinal); end; end; end; end.
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2020-2020 Skybuck Flying // Copyright (c) 2020-2020 The Delphicoin Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Bitcoin file: src/chain.h // Bitcoin file: src/chain.cpp // Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c unit Unit_TBlockFileInfo; interface type TBlockFileInfo = class public nBlocks: Cardinal; //!< number of blocks stored in file nSize: Cardinal; //!< number of used bytes of block file nUndoSize: Cardinal; //!< number of used bytes in the undo file nHeightFirst: Cardinal; //!< lowest height of block in file nHeightLast: Cardinal; //!< highest height of block in file nTimeFirst: uint64; //!< earliest time of block in file nTimeLast: uint64; //!< latest time of block in file constructor Create; procedure SetNull; // Skybuck not sure what this is: // procedure SERIALIZE_METHODS(CBlockFileInfo, obj); procedure AddBlock( nHeightIn : cardinal; nTimeIn : uint64); // function ToString() : string; override; // Skybuck: since implementation is missing keeping Tobject.ToString by disabling this. end; implementation constructor TBlockFileInfo.Create; begin SetNull(); end; procedure TBlockFileInfo.SetNull; begin nBlocks := 0; nSize := 0; nUndoSize := 0; nHeightFirst := 0; nHeightLast := 0; nTimeFirst := 0; nTimeLast := 0; end; // Skybuck not sure what this is leaving it untouched for now :) (* SERIALIZE_METHODS(CBlockFileInfo, obj) { READWRITE(VARINT(obj.nBlocks)); READWRITE(VARINT(obj.nSize)); READWRITE(VARINT(obj.nUndoSize)); READWRITE(VARINT(obj.nHeightFirst)); READWRITE(VARINT(obj.nHeightLast)); READWRITE(VARINT(obj.nTimeFirst)); READWRITE(VARINT(obj.nTimeLast)); } *) {** update statistics (does not update nSize) *} procedure TBlockFileInfo.AddBlock( nHeightIn : cardinal; nTimeIn : uint64); begin if (nBlocks=0) or (nHeightFirst > nHeightIn) then nHeightFirst := nHeightIn; if (nBlocks=0) or (nTimeFirst > nTimeIn) then nTimeFirst := nTimeIn; Inc(nBlocks); if (nHeightIn > nHeightLast) then nHeightLast := nHeightIn; if (nTimeIn > nTimeLast) then nTimeLast := nTimeIn; end; { function TBlockFileInfo.ToString() : string; begin // Skybuck: implementation missing ? or automated ? end; } end.
{ ID: a2peter1 PROG: barn1 LANG: PASCAL } {$B-,I-,Q-,R-,S-} const problem = 'barn1'; MaxN = 1000; type list = array[0..MaxN] of longint; var stall,dif : list; N,M,S,i,sol : longint; procedure sort(d,h: longint; var ls: list); var p,tmp : longint; procedure qsort(d,h: longint); var i,j : longint; begin i := d; j := h; p := ls[(d + h) shr 1]; repeat while ls[i] < p do inc(i); while ls[j] > p do dec(j); if i <= j then begin tmp := ls[i]; ls[i] := ls[j]; ls[j] := tmp; inc(i); dec(j); end;{then} until i > j; if i < h then qsort(i,h); if j > d then qsort(d,j); end;{qsort} begin qsort(d,h); end;{sort} begin assign(input,problem + '.in'); reset(input); assign(output,problem + '.out'); rewrite(output); readln(N,S,M); for i := 1 to M do readln(stall[i]); sort(1,M,stall); for i := 1 to M - 1 do dif[i] := stall[i + 1] - stall[i] - 1; sort(1,M - 1,dif); for i := 1 to M - N do inc(sol,dif[i]); sol := sol + M; writeln(sol); close(output); end.{main}
unit Security.Login.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Vcl.AppEvnts, Vcl.Imaging.jpeg, Vcl.Imaging.pngimage, PngFunctions, PngSpeedButton, Security.Login.Interfaces ; type TSecurityLoginView = class(TForm, iLoginView, iLoginViewProperties, iLoginViewEvents) EditEmail: TEdit; EditPassword: TEdit; ImageEmail: TImage; ImageEmailError: TImage; ImageLogo: TImage; ImagePassword: TImage; ImagePasswordError: TImage; LabelEmail: TLabel; LabelIPComputerCaption: TLabel; LabelComputerIPValue: TLabel; LabelIPServerCaption: TLabel; LabelServerIPValue: TLabel; LabelPassword: TLabel; PanelEmail: TPanel; PanelImageEmail: TPanel; PanelImageEmailError: TPanel; PanelImagePassword: TPanel; PanelImagePasswordError: TPanel; PanelPassword: TPanel; PanelStatus: TPanel; PanelStatusBackground: TPanel; PanelStatusBackgroundClient: TPanel; PanelStatusShapeBottom: TShape; PanelStatusShapeLeft: TShape; PanelStatusShapeRight: TShape; PanelTitle: TPanel; PanelTitleAppInfo: TPanel; PanelTitleAppInfoUpdated: TPanel; PanelTitleAppInfoUpdatedCaption: TLabel; PanelTitleAppInfoUpdatedValue: TLabel; PanelTitleAppInfoVersion: TPanel; PanelTitleAppInfoVersionCaption: TLabel; PanelTitleAppInfoVersionValue: TLabel; PanelTitleBackgroung: TPanel; PanelTitleDOT: TLabel; PanelTitleLabelSigla: TLabel; PanelTitleLabelAutenticacao: TLabel; PanelToolbar: TPanel; ShapeBodyLeft: TShape; ShapeBodyRight: TShape; ShapePanelTitleLeft: TShape; ShapePanelTitleRight: TShape; ShapePanelTitleTop: TShape; ShapeToolbarLeft: TShape; ShapeToolbarRight: TShape; ShapePanelTitleBottom: TShape; pl_Fundo: TPanel; PngSpeedButtonOk: TPngSpeedButton; PngSpeedButtonCancelar: TPngSpeedButton; Shape1: TShape; Shape2: TShape; procedure EditEmailChange(Sender: TObject); procedure EditPasswordChange(Sender: TObject); procedure PngSpeedButtonCancelarClick(Sender: TObject); procedure PngSpeedButtonOkClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); strict private FOnAuth : Security.Login.Interfaces.TAuthNotifyEvent; FOnResult : Security.Login.Interfaces.TResultNotifyEvent; FAuthenticated: Boolean; { Strict private declarations } private { Private declarations } function getOnAuth: Security.Login.Interfaces.TAuthNotifyEvent; function getOnResult: Security.Login.Interfaces.TResultNotifyEvent; procedure setOnAuth(const Value: Security.Login.Interfaces.TAuthNotifyEvent); procedure setOnResult(const Value: Security.Login.Interfaces.TResultNotifyEvent); function getComputerIP: string; function getServerIP: string; function getSigla: string; function getUpdatedAt: string; function getVersion: string; procedure setComputerIP(const Value: string); procedure setServerIP(const Value: string); procedure setSigla(const Value: string); procedure setUpdatedAt(const Value: string); procedure setVersion(const Value: string); protected { Protected declarations } procedure doLogin(const aEmail: string; const aPassword: string); procedure doResult; public { Public declarations } function Properties: iLoginViewProperties; function Events: iLoginViewEvents; published { Published declarations Properties } property ComputerIP: string read getComputerIP write setComputerIP; property ServerIP : string read getServerIP write setServerIP; property Sigla : string read getSigla write setSigla; property Version : string read getVersion write setVersion; property UpdatedAt : string read getUpdatedAt write setUpdatedAt; { Published declarations Events } property OnAuth : Security.Login.Interfaces.TAuthNotifyEvent read getOnAuth write setOnAuth; property OnResult: Security.Login.Interfaces.TResultNotifyEvent read getOnResult write setOnResult; end; var SecurityLoginView: TSecurityLoginView; implementation uses Security.Internal; {$R *.dfm} procedure TSecurityLoginView.EditEmailChange(Sender: TObject); begin PanelImageEmailError.Visible := false; end; procedure TSecurityLoginView.EditPasswordChange(Sender: TObject); begin PanelImagePasswordError.Visible := false; end; procedure TSecurityLoginView.FormActivate(Sender: TObject); begin EditEmail.Clear; EditPassword.Clear; FAuthenticated := false; BringToFront; Application.NormalizeAllTopMosts; end; procedure TSecurityLoginView.FormClose(Sender: TObject; var Action: TCloseAction); begin Application.RestoreTopMosts; doResult; end; procedure TSecurityLoginView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: begin if ActiveControl = EditPassword then PngSpeedButtonOk.Click else SelectNext(ActiveControl, true, true); Key := VK_CANCEL; end; VK_F9: if DEBUG_PROCESS <> 0 then begin EditEmail.Text := 'luisnt'; EditPassword.Text := '7ujkl05'; PngSpeedButtonOk.Click; end; end; end; function TSecurityLoginView.getComputerIP: string; begin Result := LabelComputerIPValue.Caption; end; function TSecurityLoginView.getServerIP: string; begin Result := LabelServerIPValue.Caption; end; function TSecurityLoginView.getOnAuth: Security.Login.Interfaces.TAuthNotifyEvent; begin Result := FOnAuth; end; function TSecurityLoginView.getOnResult: Security.Login.Interfaces.TResultNotifyEvent; begin Result := FOnResult; end; function TSecurityLoginView.getSigla: string; begin Result := PanelTitleLabelSigla.Caption; end; function TSecurityLoginView.getUpdatedAt: string; begin Result := PanelTitleAppInfoUpdatedValue.Caption; end; function TSecurityLoginView.getVersion: string; begin Result := PanelTitleAppInfoVersionValue.Caption; end; procedure TSecurityLoginView.setComputerIP(const Value: string); begin LabelComputerIPValue.Caption := Value; end; procedure TSecurityLoginView.setServerIP(const Value: string); begin LabelServerIPValue.Caption := Value; end; procedure TSecurityLoginView.setOnAuth(const Value: Security.Login.Interfaces.TAuthNotifyEvent); begin FOnAuth := Value; end; procedure TSecurityLoginView.setOnResult(const Value: Security.Login.Interfaces.TResultNotifyEvent); begin FOnResult := Value; end; procedure TSecurityLoginView.setSigla(const Value: string); begin PanelTitleLabelSigla.Caption := Value; end; procedure TSecurityLoginView.setUpdatedAt(const Value: string); begin PanelTitleAppInfoUpdatedValue.Caption := Value; end; procedure TSecurityLoginView.setVersion(const Value: string); begin PanelTitleAppInfoVersionValue.Caption := Value; end; procedure TSecurityLoginView.doLogin(const aEmail: string; const aPassword: string); var LEmailError : string; LPasswordError: string; begin SelectFirst; LEmailError := EmptyStr; LPasswordError := EmptyStr; FAuthenticated := false; Internal.Validate(EditEmail); Internal.Validate(EditPassword); Internal.Required(FOnAuth); OnAuth(aEmail, aPassword, FAuthenticated, LEmailError, LPasswordError); if FAuthenticated then begin Close; Exit; end; if SameStr(LEmailError + LPasswordError, EmptyStr) then LEmailError := 'Acesso negado!'; Internal.Validate(LEmailError, EditEmail, ImageEmailError, PanelImageEmailError); Internal.Validate(LPasswordError, EditPassword, ImagePasswordError, PanelImagePasswordError); end; procedure TSecurityLoginView.doResult; begin try if not Assigned(FOnResult) then Exit; FOnResult(FAuthenticated); finally Application.NormalizeAllTopMosts; BringToFront; end; end; function TSecurityLoginView.Properties: iLoginViewProperties; begin Result := Self; end; function TSecurityLoginView.Events: iLoginViewEvents; begin Result := Self; end; procedure TSecurityLoginView.PngSpeedButtonOkClick(Sender: TObject); begin doLogin(EditEmail.Text, EditPassword.Text); end; procedure TSecurityLoginView.PngSpeedButtonCancelarClick(Sender: TObject); begin FAuthenticated := false; Close; end; end.
unit caServices; {$INCLUDE ca.inc} interface uses // Standard Delphi units  Windows, SysUtils, Classes, Contnrs, WinSvc; type //--------------------------------------------------------------------------- // TcaService   //--------------------------------------------------------------------------- TcaServiceStatus = (ssUndefined, ssStopped, ssStartPending, ssStopPending, ssRunning, ssContinuePending, ssPausePending, ssPaused); TcaUpdateCallback = procedure of object; TcaService = class(TObject) private // private members... FMachineName: string; FServiceName: string; FDisplayName: string; FServiceStatus: TServiceStatus; FUpdateCallback: TcaUpdateCallback; // property methods... function GetServiceStatus: TcaServiceStatus; public // lifetime... constructor Create(const AMachineName, AServiceName, ADisplayName: string; AServiceStatus: TServiceStatus); // public methods... function Start: Boolean; function Stop: Boolean; // public properties... property ServiceName: string read FServiceName; property DisplayName: string read FDisplayName; property ServiceStatus: TcaServiceStatus read GetServiceStatus; property UpdateCallback: TcaUpdateCallback read FUpdateCallback write FUpdateCallback; end; //--------------------------------------------------------------------------- // IcaServiceList   //--------------------------------------------------------------------------- IcaServiceList = interface ['{0F9F855C-A80B-40AB-A114-173FC2581EA1}'] // property methods... function GetIgnoreInactive: Boolean; function GetMachine: string; function GetService(Index: Integer): TcaService; function GetServiceCount: Integer; function GetServiceType: DWORD; procedure SetIgnoreInactive(const Value: Boolean); procedure SetMachine(const Value: string); procedure SetServiceType(Value: DWORD); // interface methods - IcaServiceList... function FindServiceName(const AServiceName: string; AllowPartialMatch: Boolean): TcaService; function FindDisplayName(const AServiceName: string; AllowPartialMatch: Boolean): TcaService; procedure GetServiceNamesAsStrings(AList: TStrings); procedure SortByDisplayName; procedure Update; // interface properties - IcaServiceList... property IgnoreInactive: Boolean read GetIgnoreInactive write SetIgnoreInactive; property Machine: string read GetMachine write SetMachine; property ServiceCount: Integer read GetServiceCount; property Services[Index: Integer]: TcaService read GetService; default; property ServiceType: DWORD read GetServiceType write SetServiceType; end; //--------------------------------------------------------------------------- // TcaServiceList   //--------------------------------------------------------------------------- TcaServiceList = class(TInterfacedObject, IcaServiceList) private // Private fields  FList: TObjectList; // property fields... FIgnoreInactive: Boolean; FMachineName: string; FServiceType: DWORD; // private methods... function FindService(const ASearchName: string; AllowPartialMatch, UseServiceName: Boolean): TcaService; procedure BuildList; procedure Initialize; // property methods... function GetIgnoreInactive: Boolean; function GetMachine: string; function GetService(Index: Integer): TcaService; function GetServiceCount: Integer; function GetServiceType: DWORD; procedure SetIgnoreInactive(const Value: Boolean); procedure SetMachine(const Value: string); procedure SetServiceType(Value: DWORD); protected // interface methods - IcaServiceList... function FindServiceName(const AServiceName: string; AllowPartialMatch: Boolean): TcaService; function FindDisplayName(const AServiceName: string; AllowPartialMatch: Boolean): TcaService; procedure GetServiceNamesAsStrings(AList: TStrings); procedure SortByDisplayName; procedure Update; public // lifetime... constructor Create; overload; constructor Create(const AMachineName: string); overload; destructor Destroy; override; end; implementation //--------------------------------------------------------------------------- // TcaService //--------------------------------------------------------------------------- // lifetime... constructor TcaService.Create(const AMachineName, AServiceName, ADisplayName: string; AServiceStatus: TServiceStatus); begin inherited Create; FMachineName := AMachineName; FServiceName := AServiceName; FDisplayName := ADisplayName; FServiceStatus := AServiceStatus; end; // public methods... function TcaService.Start: Boolean; var ServiceControlManager: SC_HANDLE; ServiceHandle: SC_HANDLE; Flags: Cardinal; ArgVectors: PChar; ServStatus: TServiceStatus; CheckPoint: DWORD; Started: Boolean; begin ServStatus.dwCurrentState := Cardinal(-1); Started := False; ServiceControlManager := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_ALL_ACCESS); if ServiceControlManager <> 0 then begin Flags := SERVICE_START or SERVICE_QUERY_STATUS; ServiceHandle := OpenService(ServiceControlManager, PChar(FServiceName), Flags); if ServiceHandle <> 0 then begin ArgVectors := nil; if StartService(ServiceHandle, 0, ArgVectors) then begin Started := True; if QueryServiceStatus(ServiceHandle, ServStatus) then begin while (ServStatus.dwCurrentState <> SERVICE_RUNNING) and (ServStatus.dwCurrentState <> SERVICE_STOPPED) do begin CheckPoint := ServStatus.dwCheckPoint; Sleep(ServStatus.dwWaitHint); if not QueryServiceStatus(ServiceHandle, ServStatus) then // couldn't check status... Break; if ServStatus.dwCheckPoint < CheckPoint then // avoid infinite loop... Break; end; end; end; CloseServiceHandle(ServiceHandle); end; CloseServiceHandle(ServiceControlManager); end; Result := (ServStatus.dwCurrentState = SERVICE_RUNNING) or ((ServStatus.dwCurrentState = SERVICE_STOPPED) and Started); if Assigned(FUpdateCallback) then FUpdateCallback; end; function TcaService.Stop: Boolean; var ServiceControlManager: SC_HANDLE; ServiceHandle: SC_HANDLE; Flags: Cardinal; ServStatus: TServiceStatus; CheckPoint: DWORD; begin ServStatus.dwCurrentState := Cardinal(-1); ServiceControlManager := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_ALL_ACCESS); if ServiceControlManager <> 0 then begin Flags := SERVICE_STOP or SERVICE_QUERY_STATUS; ServiceHandle := OpenService(ServiceControlManager, PChar(FServiceName), Flags); if ServiceHandle <> 0 then begin if ControlService(ServiceHandle, SERVICE_CONTROL_STOP, ServStatus) then begin if QueryServiceStatus(ServiceHandle, ServStatus) then begin while ServStatus.dwCurrentState <> SERVICE_STOPPED do begin CheckPoint := ServStatus.dwCheckPoint; Sleep(ServStatus.dwWaitHint); if not QueryServiceStatus(ServiceHandle, ServStatus) then // couldn't check status... Break; if ServStatus.dwCheckPoint < CheckPoint then // avoid infinite loop... Break; end; end; end; CloseServiceHandle(ServiceHandle); end; CloseServiceHandle(ServiceControlManager); end; Result := ServStatus.dwCurrentState = SERVICE_STOPPED; if Assigned(FUpdateCallback) then FUpdateCallback; end; // property methods... function TcaService.GetServiceStatus: TcaServiceStatus; begin case FServiceStatus.dwCurrentState of SERVICE_STOPPED: Result := ssStopped; SERVICE_START_PENDING: Result := ssStartPending; SERVICE_STOP_PENDING: Result := ssStopPending; SERVICE_RUNNING: Result := ssRunning; SERVICE_CONTINUE_PENDING: Result := ssContinuePending; SERVICE_PAUSE_PENDING: Result := ssPausePending; SERVICE_PAUSED: Result := ssPaused; else Result := ssUndefined; end; end; { SERVICE_STOPPED = $00000001; SERVICE_START_PENDING = $00000002; SERVICE_STOP_PENDING = $00000003; SERVICE_RUNNING = $00000004; SERVICE_CONTINUE_PENDING = $00000005; SERVICE_PAUSE_PENDING = $00000006; SERVICE_PAUSED = $00000007; } //--------------------------------------------------------------------------- // TcaServiceList   //--------------------------------------------------------------------------- // lifetime... constructor TcaServiceList.Create; begin inherited; Initialize; Update; end; constructor TcaServiceList.Create(const AMachineName: string); begin inherited Create; FMachineName := AMachineName; Initialize; Update; end; destructor TcaServiceList.Destroy; begin FList.Free; inherited; end; // interface methods - IcaServiceList... function TcaServiceList.FindDisplayName(const AServiceName: string; AllowPartialMatch: Boolean): TcaService; begin Result := FindService(AServiceName, AllowPartialMatch, False); end; function TcaServiceList.FindServiceName(const AServiceName: string; AllowPartialMatch: Boolean): TcaService; begin Result := FindService(AServiceName, AllowPartialMatch, True); end; procedure TcaServiceList.GetServiceNamesAsStrings(AList: TStrings); var Index: Integer; Service: TcaService; ListEntry: String; begin AList.Clear; AList.BeginUpdate; try for Index := 0 to Pred(GetServiceCount) do begin Service := GetService(Index); ListEntry := Service.ServiceName; AList.Add(ListEntry); end; finally AList.EndUpdate; end; end; function CompareDisplayNames(Item1, Item2: Pointer): Integer; begin Result := CompareText(TcaService(Item1).DisplayName, TcaService(Item2).DisplayName); end; procedure TcaServiceList.SortByDisplayName; begin FList.Sort(@CompareDisplayNames); end; procedure TcaServiceList.Update; begin BuildList; end; // private methods... function TcaServiceList.FindService(const ASearchName: string; AllowPartialMatch, UseServiceName: Boolean): TcaService; var Ptr: Pointer; Service: TcaService; Name: string; Matched: Boolean; begin Result := nil; for Ptr in FList do begin Service := TcaService(Ptr); if UseServiceName then Name := Service.ServiceName else Name := Service.DisplayName; if AllowPartialMatch then Matched := Pos(AnsiLowerCase(ASearchName), AnsiLowerCase(Name)) > 0 else Matched := AnsiLowerCase(ASearchName) = AnsiLowerCase(Name); if Matched then begin Result := Service; Break; end; end; end; procedure TcaServiceList.BuildList; const MAX_SERVICE_COUNT = 4096; type TServiceArray = array[0..Pred(MAX_SERVICE_COUNT)] of TEnumServiceStatus; PServiceArray = ^TServiceArray; var Index: Integer; ServiceControlManager: SC_HANDLE; ServiceState: DWORD; BytesNeeded: DWORD; ServiceCount: DWORD; ResumeHandle : DWord; ServiceArray : PServiceArray; Service: TcaService; begin FList.Clear; if FIgnoreInactive then ServiceState := SERVICE_ACTIVE else ServiceState := SERVICE_STATE_ALL; // connect to the service control manager... ServiceControlManager := OpenSCManager(PChar(FMachineName), nil, SC_MANAGER_ALL_ACCESS); // if successful... if ServiceControlManager <> 0 then begin ResumeHandle := 0; New(ServiceArray); EnumServicesStatus(ServiceControlManager, FServiceType, ServiceState, ServiceArray^[0], SizeOf(ServiceArray^), BytesNeeded, ServiceCount, ResumeHandle ); for Index := 0 to Pred(ServiceCount) do begin Service := TcaService.Create(FMachineName, ServiceArray^[Index].lpServiceName, ServiceArray^[Index].lpDisplayName, ServiceArray^[Index].ServiceStatus); Service.UpdateCallback := Update; FList.Add(Service); end; Dispose(ServiceArray); CloseServiceHandle(ServiceControlManager); end; end; procedure TcaServiceList.Initialize; begin FList := TObjectList.Create(True); FServiceType := SERVICE_TYPE_ALL; end; // property methods... function TcaServiceList.GetIgnoreInactive: Boolean; begin Result := FIgnoreInactive; end; function TcaServiceList.GetMachine: string; begin Result := FMachineName; end; function TcaServiceList.GetService(Index: Integer): TcaService; begin Result := TcaService(FList[Index]); end; function TcaServiceList.GetServiceCount: Integer; begin Result := FList.Count; end; function TcaServiceList.GetServiceType: DWORD; begin Result := FServiceType; end; procedure TcaServiceList.SetIgnoreInactive(const Value: Boolean); begin if Value <> FIgnoreInactive then begin FIgnoreInactive := Value; Update; end; end; procedure TcaServiceList.SetMachine(const Value: string); begin if Value <> FMachineName then begin FMachineName := Value; Update; end; end; procedure TcaServiceList.SetServiceType(Value: DWORD); begin if Value <> FServiceType then begin FServiceType := Value; Update; end; end; end.
unit uInvestigator; interface type TInvestigator = class private fId: integer; fName: string; fSanity: integer; fStamina: integer; fStartLok: integer; fMoney: integer; fClues: integer; fItems: array [1..10] of integer; // Possessions including of player's choises fItemsCount: integer; // How many different items in investigator's possession fCanTake: array [1..5] of integer; // How many of certain item fAlly: integer; fFocus: integer; fStats: array [1..6] of integer; function GetStat(i: integer): integer; function GetItem(i: integer): integer; function GetCanTake(i: integer): integer; procedure SetCanTake(i, value: integer); procedure SetSpeed(value: integer); procedure SetSneak(value: integer); procedure SetFight(value: integer); procedure SetWill(value: integer); procedure Setlore(value: integer); procedure SetLuck(value: integer); public property id: Integer read fId write fId; property name: string read fName write fName; property sanity: Integer read fSanity write fSanity; property stamina: Integer read fStamina write fStamina; property start_lok: Integer read fStartLok write fStartLok; property money: Integer read fMoney write fMoney; property clues: Integer read fClues write fClues; property items[i: integer]: Integer read GetItem; property items_count: Integer read fItemsCount; property can_take[i: integer]: integer read GetCanTake write SetCanTake; property ally: Integer read fAlly write fAlly; property focus: Integer read fFocus write fFocus; property stat[i: integer]: integer read GetStat; property speed: integer write SetSpeed; property sneak: integer write SetSneak; property fight: integer write SetFight; property will: integer write SetWill; property lore: integer write SetLore; property luck: integer write SetLuck; constructor Create; procedure AddItem(item_id: integer); // Adding items on start screen //procedure SetCanTake(i, j, value: integer); end; implementation constructor TInvestigator.Create(); var i, j, k: Integer; begin name := 'Noname'; sanity := 0; stamina := 0; start_lok := 0; money := 0; clues := 0; for i := 1 to 10 do fItems[i] := 0; // Possessions fItemsCount := 0; // How many different items is in investigator's possession ally := 0; focus := 0; speed := 0; sneak := 0; fight := 0; will := 0; lore := 0; luck := 0; for i := 1 to 5 do fCanTake[i] := 0; // How many end; function TInvestigator.GetStat(i: integer): integer; begin GetStat := fStats[i]; end; procedure TInvestigator.SetSpeed(value: integer); begin fStats[1] := value; end; procedure TInvestigator.SetSneak(value: integer); begin fStats[2] := value; end; procedure TInvestigator.SetFight(value: integer); begin fStats[3] := value; end; procedure TInvestigator.SetWill(value: integer); begin fStats[4] := value; end; procedure TInvestigator.SetLore(value: integer); begin fStats[5] := value; end; procedure TInvestigator.SetLuck(value: integer); begin fStats[6] := value; end; procedure TInvestigator.AddItem(item_id: integer); begin fItemsCount := fItemsCount + 1; fItems[fItemsCount] := item_id; end; function TInvestigator.GetItem(i: integer): integer; begin GetItem := fItems[i]; end; function TInvestigator.GetCanTake(i: integer): integer; begin GetCanTake := fCanTake[i]; end; procedure TInvestigator.SetCanTake(i, value: integer); begin fCanTake[i] := value; end; end.
unit gfx_tiff; {*********************************************************************** Unit gfx_tiff.PAS v1.0 0400 (c) by Andreas Moser, amoser@amoser.de, Delphi version : Delphi 4 gfx_tiff is part of the gfx_library collection You may use this sourcecode for your freewareproducts. You may modify this source-code for your own use. You may recompile this source-code for your own use. All functions, procedures and classes may NOT be used in commercial products without the permission of the author. For parts of this library not written by me, you have to ask for permission by their respective authors. Disclaimer of warranty: "This software is supplied as is. The author disclaims all warranties, expressed or implied, including, without limitation, the warranties of merchantability and of fitness for any purpose. The author assumes no liability for damages, direct or consequential, which may result from the use of this software." All brand and product names are marks or registered marks of their respective companies. Please report bugs to: Andreas Moser amoser@amoser.de The TIFF converter algorythms are based on source codes by Mike Lischke (public@lischke-online.de) (decoder) and Wolfgang Krug (krug@sdm.de) (encoder) ********************************************************************************} interface uses Windows, Graphics, Classes, SysUtils, gfx_errors, gfx_compression, gfx_basedef; // ----------------------------------------------------------------------------- // // TIFF classes // // ----------------------------------------------------------------------------- type TTIFFHeader = packed record tiffBOrder: Word; tiffVersion: Word; tiffIFD: Cardinal; end; TImgFDEntry = packed record tiffTag: Word; tiffDataType: Word; tiffDataLength: Cardinal; tiffOffset: Cardinal; end; TTiffParams = packed record tiffBitsPerPlane :Byte; tiffPhotoMetric :Byte; tiffSamplesPerPixel :Byte; tiffExtraSamples :Byte; tiffRowsPerStrip :TCardinalArray; tiffBitsPerSample :TCardinalArray; tiffByteCount :TCardinalArray; tiffOffsets :TCardinalArray; tiffColorMap :Cardinal; tiffStrip_Count :Cardinal; tiffStripOffsets :Cardinal; tiffStripByteCount :Cardinal; tiffCompressionType :Word; tiffPrediction :Word; tiffColorSpace :TColorSpace; end; TTIFFBitmap = class(TBitmap) public procedure LoadFromStream(Stream: TStream); override; end; Type TTIFFFile = class(TObject) fTIFFHeader :TTIFFHeader; fTIFFParams :TTiffParams; fBIG_ENDIAN :Boolean; FBitmap :TBitmap; FPalette :TPaletteWordArray; FStreamBase :Integer; tiffIFD :array of TImgFDEntry; fid_c:WORD; private procedure ReadTIFFHeader(Stream:TStream); procedure ReadTIFFPalette(Stream:TStream; Colormap:Cardinal; BitsPerPixel:Byte; PMetric:Cardinal); procedure IFD_to_BIGENDIAN; function GetParams(Param:Cardinal):Cardinal; procedure GetParamList(Param:Cardinal;Stream:TSTream; var VList: TCardinalArray ); function GetParamsLen(Param:Cardinal):Cardinal; public constructor Create; destructor Destroy;override; procedure LoadFromFile(filename: String); procedure LoadFromStream(Stream: TStream); procedure SaveToFile(filename: String); procedure SaveToStream(Stream: TStream); procedure AssignBitmap(Bitmap:TBitmap); property Bitmap:TBitmap read FBitmap; end; // ----------------------------------------------------------------------------- // // const // // ----------------------------------------------------------------------------- const TIFF_NOTYPE = 0; TIFF_BYTE = 1; TIFF_ASCII = 2; TIFF_SHORT = 3; TIFF_LONG = 4; TIFF_RATIONAL = 5; TIFF_SBYTE = 6; TIFF_UNDEFINED = 7; TIFF_SSHORT = 8; TIFF_SLONG = 9; TIFF_SRATIONAL = 10; TIFF_FLOAT = 11; TIFF_DOUBLE = 12; TIFF_BIGENDIAN = $4D4D; TIFF_LITTLEENDIAN = $4949; TIFF_SUBFILETYPE = 254; FILETYPE_REDUCEDIMAGE = $1; FILETYPE_PAGE = $2; FILETYPE_MASK = $4; TIFF_OSUBFILETYPE = 255; OFILETYPE_IMAGE = 1; OFILETYPE_REDUCEDIMAGE = 2; OFILETYPE_PAGE = 3; TIFF_IMAGEWIDTH = 256; TIFF_IMAGELENGTH = 257; TIFF_BITSPERSAMPLE = 258; TIFF_COMPRESSION = 259; COMPRESSION_NONE = 1; COMPRESSION_CCITTRLE = 2; COMPRESSION_LZW = 5; COMPRESSION_PACKBITS = 32773; TIFF_PHOTOMETRIC = 262; PHOTOMETRIC_MINISWHITE = 0; PHOTOMETRIC_MINISBLACK = 1; PHOTOMETRIC_RGB = 2; PHOTOMETRIC_PALETTE = 3; PHOTOMETRIC_MASK = 4; PHOTOMETRIC_SEPARATED = 5; PHOTOMETRIC_YCBCR = 6; PHOTOMETRIC_CIELAB = 8; TIFF_DOCUMENTNAME = 269; TIFF_IMAGEDESCRIPTION = 270; TIFF_STRIPOFFSETS = 273; TIFF_ORIENTATION = 274; ORIENTATION_TOPLEFT = 1; ORIENTATION_TOPRIGHT = 2; ORIENTATION_BOTRIGHT = 3; ORIENTATION_BOTLEFT = 4; ORIENTATION_LEFTTOP = 5; ORIENTATION_RIGHTTOP = 6; ORIENTATION_RIGHTBOT = 7; ORIENTATION_LEFTBOT = 8; TIFF_SAMPLESPERPIXEL = 277; TIFF_ROWSPERSTRIP = 278; TIFF_STRIPBYTECOUNTS = 279; TIFF_XRESOLUTION = 282; TIFF_YRESOLUTION = 283; TIFF_PLANARCONFIG = 284; PLANARCONFIG_CONTIG = 1; PLANARCONFIG_SEPARATE = 2; TIFF_RESOLUTIONUNIT = 296; RESUNIT_NONE = 1; RESUNIT_INCH = 2; RESUNIT_CENTIMETER = 3; TIFF_SOFTWARE = 305; TIFF_DATETIME = 306; TIFF_ARTIST = 315; TIFF_PREDICTOR = 317; PREDICTION_NONE = 1; PREDICTION_HORZ_DIFFERENCING = 2; TIFF_COLORMAP = 320; TIFF_EXTRASAMPLES = 338; EXTRASAMPLE_UNSPECIFIED = 0; EXTRASAMPLE_ASSOCALPHA = 1; EXTRASAMPLE_UNASSALPHA = 2; TIFF_VERSION = 42; // ----------------------------------------------------------------------------- // // vars // // ----------------------------------------------------------------------------- var tiffIFD_RGB : array[0..15] of TImgFDEntry = ( ( tiffTag: TIFF_SUBFILETYPE; tiffDataType: $0004; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_IMAGEWIDTH; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_IMAGELENGTH; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_BITSPERSAMPLE; tiffDataType: $0003; tiffDataLength: $00000003; tiffOffset: $00000008 ), ( tiffTag: TIFF_COMPRESSION; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: COMPRESSION_NONE ), ( tiffTag: TIFF_PHOTOMETRIC; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: PHOTOMETRIC_RGB), ( tiffTag: TIFF_STRIPOFFSETS; tiffDataType: $0004; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_SAMPLESPERPIXEL; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: $00000003 ), ( tiffTag: TIFF_ROWSPERSTRIP; tiffDataType: $0004; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_STRIPBYTECOUNTS; tiffDataType: $0004; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_XRESOLUTION; tiffDataType: $0005; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_YRESOLUTION; tiffDataType: $0005; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_PLANARCONFIG; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: PLANARCONFIG_CONTIG ), ( tiffTag: TIFF_RESOLUTIONUNIT; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: RESUNIT_INCH), ( tiffTag: TIFF_SOFTWARE; tiffDataType: $0002; tiffDataLength: $0000000C; tiffOffset: $00000000 ), ( tiffTag: TIFF_EXTRASAMPLES; tiffDataType: $0002; tiffDataLength: $00000001; tiffOffset: EXTRASAMPLE_UNSPECIFIED )); tiffIFD_PAL : array[0..14] of TImgFDEntry = ( ( tiffTag: TIFF_SUBFILETYPE; tiffDataType: $0004; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_IMAGEWIDTH; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_IMAGELENGTH; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_BITSPERSAMPLE; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: $00000008 ), ( tiffTag: TIFF_COMPRESSION; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: COMPRESSION_NONE ), ( tiffTag: TIFF_PHOTOMETRIC; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: PHOTOMETRIC_PALETTE), ( tiffTag: TIFF_STRIPOFFSETS; tiffDataType: $0004; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_SAMPLESPERPIXEL; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: $00000001 ), ( tiffTag: TIFF_ROWSPERSTRIP; tiffDataType: $0004; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_STRIPBYTECOUNTS; tiffDataType: $0004; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_XRESOLUTION; tiffDataType: $0005; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_YRESOLUTION; tiffDataType: $0005; tiffDataLength: $00000001; tiffOffset: $00000000 ), ( tiffTag: TIFF_RESOLUTIONUNIT; tiffDataType: $0003; tiffDataLength: $00000001; tiffOffset: RESUNIT_INCH), ( tiffTag: TIFF_SOFTWARE; tiffDataType: $0002; tiffDataLength: $0000000C; tiffOffset: $00000000 ), ( tiffTag: TIFF_COLORMAP; tiffDataType: $0003; tiffDataLength: $00000300; tiffOffset: $00000008 )); NoOfDirs : array[0..1] of Byte = ( $0F, $00 ); NullString : array[0..3] of Byte = ( $00, $00, $00, $00 ); XRes : array[0..7] of Byte = ( $6D,$03,$00,$00, $0A,$00,$00,$00 ); YRes : array[0..7] of Byte = ( $6D,$03,$00,$00, $0A,$00,$00,$00 ); Software : array[0..11] of Char = ( 'M', 'O', 'S', '-', 'P', 'R', 'O', 'J', 'E', 'C', 'T', 'S'); BPS : array[0..2] of Word = ( $0008, $0008, $0008 ); var ScanLineArray:Array[0..65535] Of Byte; implementation //*********************************************************** // // TTIFFFile // //*********************************************************** // ----------------------------------------------------------------------------- // // LoadFromStream // // ----------------------------------------------------------------------------- procedure TTIFFBitmap.LoadFromStream(Stream: TStream); var aTIFF: TTIFFFile; aStream: TMemoryStream; begin aTIFF := TTIFFFile.Create; try aTIFF.LoadFromStream(Stream); aStream := TMemoryStream.Create; try aTIFF.Bitmap.SaveToStream(aStream); aStream.Position:=0; inherited LoadFromStream(aStream); finally aStream.Free; end; finally aTIFF.Free; end; end; // ----------------------------------------------------------------------------- // // LoadFromFile // // ----------------------------------------------------------------------------- procedure TTIFFFile.LoadFromFile(FileName: String); var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Stream.LoadFromFile(Filename); LoadFromStream(Stream); finally Stream.Free; end; end; // ----------------------------------------------------------------------------- // // LoadFromStream // // ----------------------------------------------------------------------------- procedure TTIFFFile.LoadFromStream(Stream: TStream); begin Stream.Position := 0; FStreamBase:=Stream.Position; ReadTIFFHeader(Stream); end; // ----------------------------------------------------------------------------- // // SaveToFile // // ----------------------------------------------------------------------------- procedure TTIFFFile.SaveToFile(FileName: String); var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; SaveToStream(Stream); Stream.SaveToFile(filename); Stream.Free; end; // ----------------------------------------------------------------------------- // // SaveToStream // // ----------------------------------------------------------------------------- procedure TTIFFFile.SaveToStream(Stream: TStream); var cBuffer:Cardinal; i,j,divisor, shift ,bs,col_count,bps, width:Integer; picStream:TMemoryStream; RGB:TRGBTriple; BGR:TBGRTripleByte; BGRA:TBGRAQuadByte; SrcRow:pRGBArray; SrcScanLine:pScanLine; o_ColMap,o_IFD, o_XRES,o_YRES,o_BPS,o_SOFTWARE, o_STRIP: Integer; fPal:TPaletteEntries; fPalArray:TPaletteWordArray; begin if not Assigned(FBitmap) then Exit; Stream.Write ( fTIFFHeader, sizeof(fTIFFHeader)); o_XRES := Stream.Position; Stream.Write (XRes,sizeof(XRes)); o_YRES := Stream.Position; Stream.Write (YRes,sizeof(YRes)); o_BPS := Stream.Position; Stream.Write (BPS,sizeof(BPS)); o_SOFTWARE := Stream.Position; Stream.Write (Software,sizeof(Software)); o_STRIP := Stream.Position; picStream:=TMemoryStream.Create; try picStream.Position:=0; width:=FBitmap.Width; divisor:=1; case fTIFFParams.tiffColorSpace of cs8Bit,cs4bit,cs1bit: begin case fTIFFParams.tiffColorSpace of cs1Bit:begin col_count:=2; bps:=1; width := (width div 8) * 8; divisor:=8; end; cs4Bit:begin col_count:=16; bps:=4; shift:=0; width := (width div bps) * bps; divisor:=2; end; cs8Bit:begin col_count:=256; shift:=8; bps:=8; divisor:=1; end; end; GetPaletteEntries(FBitmap.Palette,0,col_Count,fPal); for i:=0 to col_count-1 do begin case fTIFFParams.tiffColorSpace of cs1Bit:begin fPalArray[0,i]:=fPal[i].peRed + fPal[i].peRed shl 8 ; fPalArray[1,i]:=fPal[i].peGreen +fPal[i].peGreen shl 8; fPalArray[2,i]:=fPal[i].peBlue + fPal[i].peBlue shl 8; end; cs4Bit:begin fPalArray[0,i]:=fPal[i].peRed+ fPal[i].peRed shl 8; fPalArray[0,i+16]:=fPal[i].peGreen +fPal[i].peGreen shl 8; fPalArray[0,i+32]:=fPal[i].peBlue + fPal[i].peBlue shl 8; end; cs8Bit:begin fPalArray[0,i]:=fPal[i].peRed shl 8; fPalArray[1,i]:=fPal[i].peGreen shl 8; fPalArray[2,i]:=fPal[i].peBlue shl 8; end; end; end; o_colmap:=Stream.Position; Stream.Write ( fPalArray, 2* 3* col_Count); o_STRIP:=Stream.Position; picStream.Position:=0; for i:=0 to FBitmap.Height-1 do begin SrcScanLine:=FBitmap.ScanLine[i]; picStream.Write(SrcScanLine^,Width div Divisor); end; picStream.Position:=0; Stream.CopyFrom(picStream,picStream.Size); tiffIFD_PAL[1].tiffOffset := Cardinal(Width); tiffIFD_PAL[2].tiffOffset := Cardinal(FBitmap.Height); tiffIFD_PAL[3].tiffOffset := Cardinal(bps); if fTIFFParams.tiffColorSpace=cs1bit then tiffIFD_PAL[5].tiffOffset := Cardinal(PHOTOMETRIC_MINISWHITE); tiffIFD_PAL[8].tiffOffset := Cardinal(FBitmap.Height); tiffIFD_PAL[9].tiffOffset := Cardinal(width *FBitmap.Height); tiffIFD_PAL[14].tiffDataLength := Cardinal(col_count * 3); tiffIFD_PAL[14].tiffOffset := o_Colmap; tiffIFD_PAL[ 6].tiffOffset := o_STRIP; tiffIFD_PAL[10].tiffOffset := o_XRES; tiffIFD_PAL[11].tiffOffset := o_YRES; tiffIFD_PAL[13].tiffOffset := o_SOFTWARE; end; csRGB: begin for i:= 0 to fBitmap.Height-1 do begin SrcRow:=FBitmap.ScanLine[i]; for j:=0 to Width -1 do begin case fTIFFParams.tiffColorSpace of csRGB:begin RGB:=SrcRow[j]; BGR.bgrBlue:=RGB.rgbtRed; BGR.bgrGreen:=RGB.rgbtGreen; BGR.bgrRed:=RGB.rgbtBlue; picStream.Write(BGR,SizeOf(BGR)); end; end; end; end; picStream.Position:=0; Stream.CopyFrom(picStream,picStream.Size); tiffIFD_RGB[1].tiffOffset := Cardinal(FBitmap.Width); tiffIFD_RGB[2].tiffOffset := Cardinal(FBitmap.Height); tiffIFD_RGB[8].tiffOffset := Cardinal(FBitmap.Height); tiffIFD_RGB[9].tiffOffset := Cardinal(3*FBitmap.Width*FBitmap.Height); tiffIFD_RGB[ 3].tiffOffset := o_BPS; tiffIFD_RGB[ 6].tiffOffset := o_STRIP; tiffIFD_RGB[10].tiffOffset := o_XRES; tiffIFD_RGB[11].tiffOffset := o_YRES; tiffIFD_RGB[14].tiffOffset := o_SOFTWARE; end; end; finally picStream.Free; end; case ftiffParams.tiffColorSpace of csRGBA: tiffIFD_RGB[15].tiffOffset := EXTRASAMPLE_ASSOCALPHA; else tiffIFD_RGB[15].tiffOffset := EXTRASAMPLE_UNSPECIFIED; end; o_IFD := Stream.Position ; Stream.Write ( NoOfDirs, sizeof(NoOfDirs)); case fTIFFParams.tiffColorSpace of csRGB,csCMYK,csCIELAB,csYCBCR: Stream.Write ( tiffIFD_RGB, sizeof(tiffIFD_RGB)); cs1Bit,cs4Bit,cs8Bit: Stream.Write ( tiffIFD_PAL, sizeof(tiffIFD_PAL)); end; Stream.Write ( NullString, sizeof(NullString)); Stream.Seek ( 4, soFromBeginning ) ; Stream.Write ( o_IFD, sizeof(o_IFD)); end; // ----------------------------------------------------------------------------- // // AssignBitmap // // ----------------------------------------------------------------------------- procedure TTIFFFile.AssignBitmap(Bitmap:TBitmap); begin FBitmap.Assign(Bitmap); with fTIFFHeader do begin tiffBOrder:=$4949; tiffVersion:=TIFF_VERSION; tiffIFD:=$00000000; end; with fTIFFParams do begin SetLength(tiffBitsPerSample,1); case FBitmap.PixelFormat of pf1bit:begin tiffPhotoMetric:=PHOTOMETRIC_MINISBLACK; tiffSamplesPerPixel:=1; tiffBitsPerSample[0]:=1; tiffColorSpace:=cs1Bit; end; pf4bit:begin tiffPhotoMetric:=PHOTOMETRIC_PALETTE; tiffSamplesPerPixel:=1; tiffBitsPerSample[0]:=4; tiffColorSpace:=cs4Bit; end; pf8bit:begin tiffPhotoMetric:=PHOTOMETRIC_PALETTE; tiffSamplesPerPixel:=1; tiffBitsPerSample[0]:=8; tiffColorSpace:=cs8Bit; end; pf24bit,pf15Bit,pf16Bit:begin tiffPhotoMetric:=PHOTOMETRIC_RGB; tiffSamplesPerPixel:=3; tiffBitsPerSample[0]:=8; tiffColorSpace:=csRGB; end; pf32bit:begin tiffPhotoMetric:=PHOTOMETRIC_RGB; tiffSamplesPerPixel:=3; tiffBitsPerSample[0]:=8; tiffColorSpace:=csRGB; end; end; tiffCompressionType:=COMPRESSION_NONE; end; end; // ----------------------------------------------------------------------------- // // Create // // ----------------------------------------------------------------------------- constructor TTIFFFile.Create; begin FBitmap:=TBitmap.Create; end; // ----------------------------------------------------------------------------- // // Destroy // // ----------------------------------------------------------------------------- destructor TTIFFFile.Destroy; begin FBitmap.Free; inherited; end; // ----------------------------------------------------------------------------- // // ReadTIFFHeader // // ----------------------------------------------------------------------------- procedure TTiffFile.ReadTIFFHeader(Stream:TStream); var pixels, eBuff: Pointer; depredict_scheme :Integer; compression_scheme :Integer; line,row_size,ssize,j,i,k: Integer; fWidth,fHeight:Word; dBuff,xBuff:PChar; DestRow :pRGBArray; RGB:TRGBTriple; BGR:TBGRTriple; BGRA:TBGRAQuad; RGBA:TRGBAQuad; CMYK:TCMYKQuad; CIELAB:TCIELABTriple; begin fid_c:=0; line:=0; with fTIFFParams do begin tiffColorMap:=0; Stream.ReadBuffer(ftiffHeader,sizeof(fTiffHeader)); if FTIFFHeader.tiffBOrder =TIFF_BIGENDIAN then fBIG_ENDIAN:=True else fBIG_ENDIAN:=False; if fBIG_ENDIAN then begin FTIFFHeader.tiffVersion:=Swap(FTIFFHeader.tiffVersion); FTIFFHeader.tiffIFD:=SwapL(FTIFFHeader.tiffIFD); end; if FTIFFHeader.tiffVersion <> TIFF_VERSION then begin if GFXRaiseErrors then raise EGraphicFormat.Create('TIFF: Unsupported version'); GFXFileErrorList.Add('TIFF: TIFF: Unsupported version'); exit; end; Stream.Position:=FStreamBase+FTIFFHeader.tiffIFD; Stream.ReadBuffer(fid_c,sizeof(fid_c)); if fBIG_ENDIAN then fid_c:=swap(fid_c); SetLength(tiffIFD,fid_c); Stream.ReadBuffer(tiffIFD[0], fid_c* SizeOf(TImgFDEntry)); if fBIG_ENDIAN then IFD_to_BIGENDIAN; //get the tiff-parameters tiffPrediction:=GetParams(TIFF_PREDICTOR); tiffPhotoMetric:=GetParams(TIFF_PHOTOMETRIC); tiffSamplesPerPixel:=GetParams(TIFF_SAMPLESPERPIXEL); if tiffSamplesPerPixel=0 then tiffSamplesPerPixel:=1; tiffExtraSamples:=GetParams(TIFF_EXTRASAMPLES); tiffCompressionType:=GetParams(TIFF_COMPRESSION); tiffStripOffsets:=GetParams(TIFF_STRIPOFFSETS); tiffStrip_Count:=GetParamsLen(TIFF_STRIPOFFSETS); tiffStripByteCount:=GetParams(TIFF_STRIPBYTECOUNTS); GetParamList(TIFF_BITSPERSAMPLE,Stream,tiffBitsPerSample); if Length(tiffBitsPerSample)=0 then begin SetLength(tiffBitsPerSample,1);tiffBitsPerSample[0]:=1;end; GetParamList(TIFF_ROWSPERSTRIP,Stream,tiffRowsPerStrip); fWidth := GetParams(TIFF_IMAGEWIDTH); fHeight := GetParams(TIFF_IMAGELENGTH); tiffColorMap:=GetParams(TIFF_COLORMAP); if (fHeight= 0) or (fWidth=0) then begin if GFXRaiseErrors then raise EGraphicFormat.Create('TIFF: Illegal image dimensions'); GFXFileErrorList.Add('TIFF: TIFF: Illegal image dimensions'); exit; end; SetLength(tiffOffsets,tiffStrip_Count); SetLength(tiffByteCount,tiffStrip_Count); tiffBitsPerPlane:=tiffBitsPerSample[0]*tiffSamplesPerPixel; row_size:=(tiffBitsPerPlane* fWidth +7 ) div 8; if tiffStrip_Count>1 then begin Stream.Position:=FStreamBase+tiffStripOffsets; Stream.ReadBuffer(tiffOffsets[0], tiffStrip_Count*4 ); if fBIG_ENDIAN then for i:=0 to (tiffStrip_Count *4)-1 do SwapL(tiffOffsets[i]); Stream.Position:=FStreamBase+tiffStripByteCount; Stream.ReadBuffer(tiffByteCount[0],tiffStrip_Count*4); if fBIG_ENDIAN then for i:=0 to (tiffByteCount[0] *4)-1 do SwapL(tiffOffsets[i]); end else begin if tiffStrip_Count = 1 then begin SetLength(tiffRowsPerStrip,1); tiffRowsPerStrip[0]:=fHeight; end; tiffOffsets[0]:=tiffStripOffsets; tiffByteCount[0]:=tiffStripByteCount; end; tiffColorSpace:=csNone; case tiffSamplesPerPixel of 1:begin case tiffBitsPerSample[0] of 1: begin FBitmap.PixelFormat:=pf1Bit; tiffColorSpace:=cs1Bit; end; 4: begin FBitmap.PixelFormat:=pf4Bit; tiffColorSpace:=cs4Bit; end; 8,16: begin FBitmap.PixelFormat:=pf8Bit; tiffColorSpace:=cs8Bit; end; else begin if GFXRaiseErrors then raise EGraphicFormat.Create('TIFF: Unsupported Bits Per Sample'); GFXFileErrorList.Add('TIFF: TIFF: Unsupported Bits Per Sample'); exit; end; end; //image has a palette... ReadTIFFPalette(Stream, tiffColorMap, tiffBitsPerPlane, tiffPhotoMetric); end; 3:begin case tiffPhotoMetric of PHOTOMETRIC_RGB: begin if tiffExtraSamples>0 then begin FBitmap.PixelFormat:=pf32Bit; tiffColorSpace:=csRGBA; end else begin FBitmap.PixelFormat:=pf24Bit; tiffColorSpace:=csRGB; end; end; PHOTOMETRIC_YCBCR: begin FBitmap.PixelFormat:=pf24bit; tiffColorSpace:=csYCBCR; end; PHOTOMETRIC_CIELAB: begin FBitmap.PixelFormat:=pf24bit; tiffColorSpace:=csCIELAB; end; else begin if GFXRaiseErrors then raise EGraphicFormat.Create('TIFF: Unsupported photometric interpretation'); GFXFileErrorList.Add('TIFF: Unsupported photometric interpretation'); exit; end; end; end; 4:begin case tiffPhotoMetric of PHOTOMETRIC_RGB: begin FBitmap.PixelFormat:=pf24Bit; tiffColorSpace:=csRGB; end; PHOTOMETRIC_SEPARATED: begin FBitmap.PixelFormat:=pf24bit; tiffColorSpace:=csCMYK; end; else begin if GFXRaiseErrors then raise EGraphicFormat.Create('TIFF: Unsupported photometric interpretation'); GFXFileErrorList.Add('TIFF: Unsupported photometric interpretation'); exit; end; end; end; else FBitmap.PixelFormat:=pfDevice; end;{end case} FBitmap.Width:=fWidth; FBitmap.Height:=fHeight; // deprediction if tiffPrediction = PREDICTION_HORZ_DIFFERENCING then case tiffSamplesPerPixel of 3:depredict_scheme:=3; 4:depredict_scheme:=4; else depredict_scheme:=1; end else depredict_scheme:=0; // compression check if ( tiffCompressionType <> COMPRESSION_NONE ) and // (tiffCompressionType <> COMPRESSION_LZW ) and // removed to avoid copyright problems (tiffCompressionType <> COMPRESSION_PACKBITS) then begin if GFXRaiseErrors then raise EGraphicFormat.Create('TIFF: Unsupported compression scheme'); GFXFileErrorList.Add('TIFF: Unsupported compression scheme'); exit; end; line:=0; j:=0; for i:=0 to tiffStrip_Count -1 do begin Stream.Position:=FStreamBase+tiffOffsets[i]; if i < Length(tiffRowsPerStrip) then ssize := row_size * tiffRowsPerStrip[i] else ssize := row_size * tiffRowsPerStrip[High(tiffRowsPerStrip)]; GetMem(dBuff, ssize); if tiffCompressionType<> COMPRESSION_NONE then begin GetMem(eBuff, tiffByteCount[i]); Stream.Read(eBuff^, tiffByteCount[i]); case tiffCompressionType of // COMPRESSION_LZW: DecodeTIFFLZW(eBuff, dBuff, tiffByteCount[i], ssize); // removed to avoid copyright problems COMPRESSION_PACKBITS : DecodeTIFFPackBits(eBuff, dBuff, tiffByteCount[i], ssize); end; FreeMem(eBuff); end else begin Stream.Read(dBuff^, ssize); end; xBuff:=dBuff; while (line < fHeight) and ((xBuff-dBuff) < Integer(ssize)) do begin if line > fHeight then break; DestRow:=FBitmap.ScanLine[line]; Inc(Line); case depredict_scheme of 1:Deprediction1(xBuff,fWidth-1); 3:Deprediction3(xBuff,fWidth-1); 4:Deprediction4(xBuff,fWidth-1); end; j:=0; case tiffColorSpace of csRGB,cscmyk, csCIELAB,csRGBA : while ((xBuff-dBuff) < ssize-1) and (j<fWidth) do begin case tiffColorSpace of csRGBA: begin BGRA.bgrBlue:=pBGRAQuad(xBuff).bgrBlue; BGRA.bgrGreen:=pBGRAQuad(xBuff).bgrGreen; BGRA.bgrRed:=pBGRAQuad(xBuff).bgrRed; BGRA.bgrAlpha:=pBGRAQuad(xBuff).bgrAlpha; if tiffExtraSamples>0 then RGBAtoBGRA_16(RGBA,BGRA) else RGBAtoBGRA(RGBA,BGRA); RGB.rgbtRed := BGRA.bgrRed; RGB.rgbtGreen := BGRA.bgrGreen; RGB.rgbtBlue := BGRA.bgrBlue; DestRow[j]:=RGB; Inc(pBGRAQuad(xBuff)); end; csRGB: begin RGB.rgbtBlue:=pRGBTriple(xBuff).rgbtRed; RGB.rgbtRed:=pRGBTriple(xBuff).rgbtBlue; RGB.rgbtGreen:=pRGBTriple(xBuff).rgbtGreen; DestRow[j]:=RGB; Inc(pRGBTriple(xBuff)); end; csCMYK : begin CMYK.cmykCyan:=pCMYKQuad(xBuff).cmykCyan; CMYK.cmykMagenta:=pCMYKQuad(xBuff).cmykMagenta; CMYK.cmykYellow:=pCMYKQuad(xBuff).cmykYellow; CMYK.cmykK:=pCMYKQuad(xBuff).cmykK; CMYKtoRGB(CMYK,RGB); DestRow[j].rgbtRed :=RGB.rgbtBlue; DestRow[j].rgbtBlue :=RGB.rgbtRed; DestRow[j].rgbtGreen :=RGB.rgbtGreen; Inc(pCMYKQuad(xBuff)); end; csCIELAB : begin CIELAB.L:=pCIELABTriple(xBuff).L; CIELAB.A:=pCIELABTriple(xBuff).A; CIELAB.B:=pCIELABTriple(xBuff).B; CIELABtoBGR(CIELAB,BGR); DestRow[j].rgbtRed :=BGR.bgrRed ; DestRow[j].rgbtBlue :=BGR.bgrBlue; DestRow[j].rgbtGreen :=BGR.bgrGreen; Inc(pCIELABTriple(xBuff)); end; end;{end case} Inc(j); end;{end while} cs8Bit, cs1Bit, cs4Bit: begin Move(xBuff^,DestRow[0], row_size); Inc(pChar(xBuff),row_size) end; end;{end case} end; FreeMem(dBuff); end; end; end; // ----------------------------------------------------------------------------- // // IFD_TO_BIGENDIAN // // ----------------------------------------------------------------------------- procedure TTIFFFile.IFD_to_BIGENDIAN; var i:Integer; begin for i:=0 to High(tiffIFD) do begin tiffIFD[i].tiffTag:=Swap(tiffIFD[i].tiffTag); tiffIFD[i].tiffDataLength:=Swap(tiffIFD[i].tiffDataLength); tiffIFD[i].tiffDataType:=Swap(tiffIFD[i].tiffDataType); case tiffIFD[i].tiffDataType of TIFF_SHORT,TIFF_SSHORT: if tiffIFD[i].tiffDataLength >1 then tiffIFD[i].tiffOffset:=SwapL(tiffIFD[i].tiffOffset) else tiffIFD[i].tiffOffset:=Swap(tiffIFD[i].tiffOffset); TIFF_LONG,TIFF_SLONG: tiffIFD[i].tiffOffset:=SwapL(tiffIFD[i].tiffOffset); end; end; end; // ----------------------------------------------------------------------------- // // GetParamsLen // // ----------------------------------------------------------------------------- function TTIFFFile.GetParamsLen(Param:Cardinal):Cardinal; var i,p:Integer; begin p:=-1; Result:=1; for i:=0 to fid_c-1 do begin if tiffIFD[i].tiffTag=Param then begin p:=i; break; end; end; if p=-1 then exit; Result:=tiffIFD[p].tiffDataLength; Case tiffIFD[p].tiffDataType of TIFF_ASCII,TIFF_BYTE,TIFF_SBYTE: Result:=Byte(Result); TIFF_SHORT, TIFF_SSHORT:Result:=Word(Result); TIFF_LONG, TIFF_SLONG: end; end; // ----------------------------------------------------------------------------- // // GetParams // // ----------------------------------------------------------------------------- function TTIFFFile.GetParams(Param:Cardinal):Cardinal; var i,p:Integer; begin p:=-1; Result:=0; for i:=0 to fid_c-1 do begin if tiffIFD[i].tiffTag=Param then begin p:=i; break; end; end; if p=-1 then exit; Result:=tiffIFD[p].tiffOffset; if tiffIFD[p].tiffDataLength=1 then begin case tiffIFD[p].tiffDataType of TIFF_BYTE: Result:=Byte(Result); TIFF_SHORT, TIFF_SSHORT: Result:=Word(Result); end; end; end; // ----------------------------------------------------------------------------- // // GetParamList // // ----------------------------------------------------------------------------- procedure TTIFFFile.GetParamList(Param:Cardinal;Stream:TSTream; var VList: TCardinalArray); var i,p:Integer; v:Cardinal; begin p:=-1; for i:=0 to fid_c-1 do begin if tiffIFD[i].tiffTag=Param then begin p:=i; break; end; end; if p=-1 then exit; VList:=nil; SetLength(VList, tiffIFD[p].tiffDataLength); if tiffIFD[p].tiffDataLength=1 then VList[0]:=tiffIFD[p].tiffOffset else begin Stream.Position:=FStreamBase+tiffIFD[p].tiffOffset; for i:=0 to tiffIFD[p].tiffDataLength-1 do begin Case tiffIFD[p].tiffDataType of TIFF_ASCII,TIFF_BYTE,TIFF_SBYTE: begin Stream.Read(v,1); v:=Byte(V); end; TIFF_SHORT, TIFF_SSHORT: begin Stream.Read(v,2); if fBIG_ENDIAN then v:=Swap(v) else v:=Word(v); end; TIFF_LONG, TIFF_SLONG: begin Stream.Read(v,4); if fBIG_ENDIAN then v:=SwapL(v); end; end; VList[i]:=v; end; end; end; // ----------------------------------------------------------------------------- // // ReadTIFFpalette // // ----------------------------------------------------------------------------- procedure TTIFFFile.ReadTIFFPalette(Stream:TStream; Colormap:Cardinal; BitsPerPixel:Byte; PMetric:Cardinal); var fPal:TMaxLogPalette; col_count,i,j,v,o,count:Integer; begin fillchar(fpalette,sizeof(fpalette),0); fillchar(fpal,sizeof(fpal),0); count:=0; case BitsperPixel of 1: Count := 1; 4: Count := 15; 8,16: Count := 255; end; if (ColorMap >0 ) and (PMetric= PHOTOMETRIC_PALETTE) then begin Stream.Position:=FStreamBase+Colormap; Stream.ReadBuffer(fPalette[0,0],2*3*(count+1)); //SizeOf(fPalette) end; if fBIG_ENDIAN then for i:=0 to 2 do for j:=0 to count do SwapS(fPalette[i,j]); fPal.palVersion := $300; fPal.palNumEntries := 1 + Count; for i:=0 to Count do begin case BitsPerPixel of 1: begin case PMetric of PHOTOMETRIC_MINISWHITE: v:= 255 * (1-i); PHOTOMETRIC_MINISBLACK: v:= 255 *i; else v:=i; end; if pMetric = PHOTOMETRIC_PALETTE then begin fPal.palPalEntry[i].peRed := fPalette[0,i]; fPal.palPalEntry[i].peGreen := fPalette[0,i+1] ; fPal.palPalEntry[i].peBlue := fPalette[0,i+2] ; fPal.palPalEntry[i].peFlags:=0; end else begin fPal.palPalEntry[i].peRed := v; fPal.palPalEntry[i].peGreen := v; fPal.palPalEntry[i].peBlue := v; fPal.palPalEntry[i].peFlags:=0; end; end; 4: begin case PMetric of PHOTOMETRIC_MINISWHITE: o:= count-i; PHOTOMETRIC_MINISBLACK: o:= i; else o:=i; end; case PMetric of PHOTOMETRIC_MINISWHITE,PHOTOMETRIC_MINISBLACK: begin v:=16 * i; fPal.palPalEntry[o].peRed := v; fPal.palPalEntry[o].peGreen := v; fPal.palPalEntry[o].peBlue := v; fPal.palPalEntry[o].peFlags:=0; end; PHOTOMETRIC_PALETTE: begin fPal.palPalEntry[i].peRed := fPalette[0,i]; fPal.palPalEntry[i].peGreen := fPalette[0,i+16] ; fPal.palPalEntry[i].peBlue := fPalette[0,i+32] ; fPal.palPalEntry[i].peFlags:=0; end; end; end; 8: case PMetric of PHOTOMETRIC_PALETTE: begin fPal.palPalEntry[i].peRed := fPalette[0,i] shr 8; fPal.palPalEntry[i].peGreen := fPalette[1,i] shr 8; fPal.palPalEntry[i].peBlue := fPalette[2,i] shr 8; fPal.palPalEntry[i].peFlags:=0; end; PHOTOMETRIC_MINISWHITE,PHOTOMETRIC_MINISBLACK: begin case PMetric of PHOTOMETRIC_MINISWHITE: o:= count-i; PHOTOMETRIC_MINISBLACK: o:= i; else o:= i; end; fPal.palPalEntry[o].peRed := i; fPal.palPalEntry[o].peGreen := i; fPal.palPalEntry[o].peBlue := i; fPal.palPalEntry[o].peFlags:=0; end; end; end; end; FBitmap.Palette:=CreatePalette(pLogPalette(@fPal)^); FBitMap.IgnorePalette:=False; end; initialization TPicture.RegisterFileFormat('TIF','TIFF-Format', TTIFFBitmap); finalization TPicture.UnRegisterGraphicClass(TTIFFBitmap); end.
unit UnitRegistryEditor; interface uses Windows, SysUtils, Registry; function ListKeys(Clave: String): String; function ListValues(Clave: String): String; function AddRegValue(kPath, RegName, RegType, RegValue: String): Boolean; function AddRegKey(kPath: string):Boolean; function DeleteRegkey(kPath, RegName: String; DeleteKey: Boolean): Boolean; function RenameRegistryItem(Old, New: String): boolean; implementation var rKey: HKEY; //From SSRAT //---- function ToKey(Clave: String):HKEY; begin if Clave='HKEY_CLASSES_ROOT' then Result:=HKEY_CLASSES_ROOT else if Clave='HKEY_CURRENT_CONFIG' then Result:=HKEY_CURRENT_CONFIG else if Clave='HKEY_CURRENT_USER' then Result:=HKEY_CURRENT_USER else if Clave='HKEY_LOCAL_MACHINE' then Result:=HKEY_LOCAL_MACHINE else if Clave='HKEY_USERS' then Result:=HKEY_USERS else Result:=0; end; function ListValues(Clave: String): String; var phkResult: HKEY; dwIndex, lpcbValueName,lpcbData: Cardinal; lpData: PChar; lpType: DWORD; lpValueName: PChar; strTipo, strDatos, Nombre: String; j, Resultado: integer; DValue: PDWORD; Temp:string; begin Result := ''; if RegOpenKeyEx(ToKey(Copy(Clave, 1, Pos('\', Clave) - 1)),PChar(Copy(Clave, Pos('\', Clave) + 1, Length(Clave))),0, KEY_QUERY_VALUE, phkResult) <> ERROR_SUCCESS then exit; dwIndex := 0; GetMem(lpValueName, 16383); Resultado := ERROR_SUCCESS; while (Resultado = ERROR_SUCCESS) do begin Resultado := RegEnumValue(phkResult, dwIndex, lpValueName, lpcbValueName, nil, @lpType, nil, @lpcbData); GetMem(lpData,lpcbData); lpcbValueName := 16383; Resultado := RegEnumValue(phkResult, dwIndex, lpValueName, lpcbValueName, nil, @lpType, PByte(lpData), @lpcbData); if Resultado = ERROR_SUCCESS then begin strDatos := ''; if lpType = REG_DWORD then begin DValue := PDWORD(lpData); strDatos := '0x'+ IntToHex(DValue^, 8) + ' (' + IntToStr(DValue^) + ')'; //0xHexValue (IntValue) end else if lpType = REG_BINARY then begin if lpcbData = 0 then strDatos := '(No Data)' else for j := 0 to lpcbData - 1 do strDatos := strDatos + IntToHex(Ord(lpData[j]), 2) + ' '; end else if lpType = REG_MULTI_SZ then begin for j := 0 to lpcbData - 1 do if lpData[j] = #0 then lpData[j] := ' '; strDatos := lpData; end else strDatos := lpData; if lpValueName[0] = #0 then Nombre := '(End)' else Nombre := lpValueName; case lpType of REG_BINARY: strTipo := 'REG_BINARY'; REG_DWORD: strTipo := 'REG_DWORD'; REG_DWORD_BIG_ENDIAN: strTipo := 'REG_DWORD_BIG_ENDIAN'; REG_EXPAND_SZ: strTipo := 'REG_EXPAND_SZ'; REG_LINK: strTipo := 'REG_LINK'; REG_MULTI_SZ: strTipo := 'REG_MULTI_SZ'; REG_NONE: strTipo := 'REG_NONE'; REG_SZ: strTipo := 'REG_SZ'; end; if strDatos = '' then strdatos := '(No Data)'; Temp := Temp + Nombre + '|' + strTipo + '|' + strDatos + '|' + #13#10; Inc(dwIndex); end; FreeMem(lpData); end; If Temp <> '' then Result := Temp; FreeMem(lpValueName); RegCloseKey(phkResult); end; function ListKeys(Clave: String): String; var phkResult: HKEY; lpName: PChar; lpcbName, dwIndex: Cardinal; lpftLastWriteTime: FileTime; Temp:string; begin Temp := ''; RegOpenKeyEx(ToKey(Copy(Clave, 1, Pos('\', Clave) - 1)),PChar(Copy(Clave, Pos('\', Clave) + 1, Length(Clave))), 0,KEY_ENUMERATE_SUB_KEYS,phkResult); lpcbName := 255; GetMem(lpName, lpcbName); dwIndex := 0; while RegEnumKeyEx(phkResult, dwIndex, @lpName[0] , lpcbName, nil, nil, nil, @lpftLastWriteTime) = ERROR_SUCCESS do begin temp := temp + lpName + '|'; Inc(dwIndex); lpcbName := 255; end; Result := temp; RegCloseKey(phkResult); end; //----- function StrToKeyType(sKey: wideString): integer; begin if sKey = 'REG_DWORD' then Result := REG_DWORD; if sKey = 'REG_BINARY' then Result := REG_BINARY; if sKey = 'REG_EXPAND_SZ' then Result := REG_EXPAND_SZ; if sKey = 'REG_MULTI_SZ' then Result := REG_MULTI_SZ; if sKey = 'REG_SZ' then Result := REG_SZ; end; function AddRegValue(kPath, RegName, RegType, RegValue: String):Boolean; var RegKey: string; begin RegKey := Copy(kPath, 1, Pos('\', kPath)-1); Delete(kPath, 1, Pos('\', kPath)); RegCreateKey(ToKey(RegKey), PChar(kPath), rKey); Result := RegSetValueEx(rKey, PChar(string(RegName)), 0, StrToKeyType(RegType), PChar(RegValue), Length(PChar(RegValue))) = 0; RegCloseKey(rKey); end; function AddRegKey(kPath: string):Boolean; var RegKey, KeyName: string; begin RegKey := Copy(kPath, 1, Pos('\', kPath)-1); Delete(kPath, 1, Pos('\', kPath)); KeyName := Copy(kPath, LastDelimiter('\', kPath)+1, Length(kPath)); Delete(kPath, LastDelimiter('\', kPath), Length(kPath)); RegOpenKeyEx(ToKey(RegKey), PChar(kPath), 0, KEY_CREATE_SUB_KEY, rKey); Result := RegCreateKey(rKey, PChar(KeyName), rKey) = 0; RegCloseKey(rKey); end; function Removekey(const hRootKey: HKey; const strKey, strName: String; bolKeyValue: Boolean): Boolean; begin with TRegistry.Create do try RootKey := hRootKey; OpenKey(strKey, True); if bolKeyValue then if DeleteValue(strName) then Result := True else Result := False else if DeleteKey(strName) then Result := True else Result := False; finally CloseKey; Free; end; end; function DeleteRegkey(kPath, RegName: String; DeleteKey: Boolean):boolean; var RegKey: string; begin RegKey := Copy(kPath, 1, Pos('\', kPath)-1); Delete(kPath, 1, Pos('\', kPath)); Result := Removekey(ToKey(RegKey), kPath, RegName, DeleteKey); end; function AllocMem(Size: Cardinal): Pointer; begin GetMem(Result, Size); FillChar(Result^, Size, 0); end; function CopyRegistryKey(Source, Dest: HKEY): boolean; const DefValueSize = 512; DefBufferSize = 8192; var Status : Integer; Key : Integer; ValueSize, BufferSize : Cardinal; KeyType : Integer; ValueName : String; Buffer : Pointer; NewTo, NewFrom : HKEY; begin result := false; SetLength(ValueName,DefValueSize); Buffer := AllocMem(DefBufferSize); try Key := 0; repeat ValueSize := DefValueSize; BufferSize := DefBufferSize; Status := RegEnumValue(Source,Key,PChar(ValueName),ValueSize,nil,@KeyType,Buffer,@BufferSize); if Status = ERROR_SUCCESS then begin Status := RegSetValueEx(Dest,PChar(ValueName),0,KeyType,Buffer,BufferSize); RegDeleteValue(Source,PChar(ValueName)); end; until Status <> ERROR_SUCCESS; Key := 0; repeat ValueSize := DefValueSize; BufferSize := DefBufferSize; Status := RegEnumKeyEx(Source,Key,PChar(ValueName),ValueSize,nil,Buffer,@BufferSize,nil); if Status = ERROR_SUCCESS then begin Status := RegCreateKey(Dest,PChar(ValueName),NewTo); if Status = ERROR_SUCCESS then begin Status := RegCreateKey(Source,PChar(ValueName),NewFrom); if Status = ERROR_SUCCESS then begin CopyRegistryKey(NewFrom,NewTo); RegCloseKey(NewFrom); RegDeleteKey(Source,PChar(ValueName)); end; RegCloseKey(NewTo); end; end; until Status <> ERROR_SUCCESS; finally FreeMem(Buffer); end; end; function RegKeyExists(const RootKey: HKEY; Key: String): Boolean; var Handle : HKEY; begin if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_ENUMERATE_SUB_KEYS, Handle) = ERROR_SUCCESS then begin Result := True; RegCloseKey(Handle); end else Result := False; end; procedure RenRegItem(AKey: HKEY; Old, New: String); var OldKey, NewKey : HKEY; Status : Integer; begin Status := RegOpenKey(AKey,PChar(Old),OldKey); if Status = ERROR_SUCCESS then begin Status := RegCreateKey(AKey,PChar(New),NewKey); if Status = ERROR_SUCCESS then CopyRegistryKey(OldKey,NewKey); RegCloseKey(OldKey); RegCloseKey(NewKey); RegDeleteKey(AKey,PChar(Old)); end; end; function RenameRegistryItem(Old, New: String): boolean; var AKey : HKEY; ClaveBase: string; begin ClaveBase := Copy(Old, 1, Pos('\', Old) - 1); AKey := ToKey(ClaveBase); delete(new, 1, pos('\', new)); delete(Old, 1, pos('\', Old)); if RegKeyExists(AKey, New) = true then begin result := false; exit; end; RenRegItem(AKey, old, new); if RegKeyExists(AKey, old) = true then begin result := false; exit; end; result := RegKeyExists(AKey, new); end; end.
unit SIP_Env; interface uses SIP_Library,SIP_Sound,Classes,SIP_Event; type ISIPEnv = interface function SIPLibrary:TSIPLibrary; function SIPSound:TSIPAnnouncementList; function SIPAddress:TStringList; function SIPDTMF:TStringList; function SIPMobile:TStringList; function SIPHome:TStringList; function SIPMail:TStringList; function SIPSettings:TStringList; function RingGroups:TStringList; function EventLibrary:TSIPEventLibrary; function FileNames:TStringList; function DatabaseID:Integer; end; TSIPEnv =class (TInterfacedObject,ISIPEnv) private FSIPLibrary:TSIPLibrary; FSIPSound:TSIPAnnouncementList; FSIPAddress:TStringList; FSIPMobile:TStringList; FSIPHome:TStringList; FSIPMail:TStringList; FSIPDTMF:TStringList; FRingGroups:TStringList; FSIPSettings:TStringList; FEventLibrary:TSIPEventLibrary; FFileNames:TStringList; FDatabaseID:Integer; FID:Integer; public constructor Create(DatabaseID:Integer;Log:Boolean); destructor Destroy;override; function SIPLibrary:TSIPLibrary; function SIPSound:TSIPAnnouncementList; function SIPAddress:TStringList; function SIPMobile:TStringList; function SIPHome:TStringList; function SIPMail:TStringList; function SIPDTMF:TStringList; function SIPSettings:TStringList; function RingGroups:TStringList; function EventLibrary:TSIPEventLibrary; function FileNames:TStringList; function DatabaseID:Integer; end; implementation uses SysUtils, dm_Alarm, Windows, Util; { TSIPEnv } var EventCounter:Integer=0; constructor TSIPEnv.Create; begin FID:=InterlockedIncrement(EventCounter); FDatabaseID:=DatabaseID; FSIPLibrary:=TSIPLibrary.Create; FSIPSound:=TSIPAnnouncementList.Create; FSIPAddress:=TStringList.Create; FSIPMobile:=TStringList.Create; FSIPHome:=TStringList.Create; FSIPMail:=TStringList.Create; FSIPDTMF:=TStringList.Create; FRingGroups:=TStringList.Create; FEventLibrary:=TSIPEventLibrary.Create; FSIPSettings:=TStringList.Create; FFileNames:=TStringList.Create; end; function TSIPEnv.DatabaseID: Integer; begin Result:=FDatabaseID; end; destructor TSIPEnv.Destroy; begin FreeAndNil(FFileNames); FreeAndNil(FSIPSettings); FreeAndNil(FEventLibrary); FreeAndNil(FSIPLibrary); FreeAndNil(FSIPSound); FreeAndNil(FSIPAddress); FreeAndNil(FSIPMobile); FreeAndNil(FSIPHome); FreeAndNil(FSIPMail); FreeAndNil(FSIPDTMF); FreeAndNil(FRingGroups); inherited; end; function TSIPEnv.EventLibrary: TSIPEventLibrary; begin Result:=FEventLibrary; end; function TSIPEnv.FileNames: TStringList; begin Result:=FFileNames; end; function TSIPEnv.RingGroups: TStringList; begin Result:=FRingGroups; end; function TSIPEnv.SIPAddress: TStringList; begin Result:=FSIPAddress; end; function TSIPEnv.SIPMobile: TStringList; begin Result:=FSIPMobile; end; function TSIPEnv.SIPHome: TStringList; begin Result:=FSIPHome; end; function TSIPEnv.SIPMail: TStringList; begin Result:=FSIPMail; end; function TSIPEnv.SIPDTMF: TStringList; begin Result:=FSIPDTMF; end; function TSIPEnv.SIPLibrary: TSIPLibrary; begin Result:=FSIPLibrary; end; function TSIPEnv.SIPSettings: TStringList; begin Result:=FSIPSettings; end; function TSIPEnv.SIPSound: TSIPAnnouncementList; begin Result:=FSIPSound; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995-2002 Borland Software Corporation } { } {*******************************************************} unit StdCtrls; {$R-,T-,H+,X+} interface uses Messages, {$IFDEF LINUX} WinUtils, {$ENDIF} Windows, SysUtils, Classes, Controls, Forms, Menus, Graphics; type TCustomGroupBox = class(TCustomControl) private procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure WMSize(var Message: TMessage); message WM_SIZE; protected procedure AdjustClientRect(var Rect: TRect); override; procedure CreateParams(var Params: TCreateParams); override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; end; TGroupBox = class(TCustomGroupBox) published property Align; property Anchors; property BiDiMode; property Caption; property Color; property Constraints; property Ctl3D; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentBackground default True; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDockDrop; property OnDockOver; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; property OnUnDock; end; TTextLayout = (tlTop, tlCenter, tlBottom); TCustomLabel = class(TGraphicControl) private FFocusControl: TWinControl; FAlignment: TAlignment; FAutoSize: Boolean; FLayout: TTextLayout; FWordWrap: Boolean; FShowAccelChar: Boolean; FOnMouseLeave: TNotifyEvent; FOnMouseEnter: TNotifyEvent; FTransparentSet: Boolean; function GetTransparent: Boolean; procedure SetAlignment(Value: TAlignment); procedure SetFocusControl(Value: TWinControl); procedure SetShowAccelChar(Value: Boolean); procedure SetTransparent(Value: Boolean); procedure SetLayout(Value: TTextLayout); procedure SetWordWrap(Value: Boolean); procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; protected procedure AdjustBounds; dynamic; procedure DoDrawText(var Rect: TRect; Flags: Longint); dynamic; function GetLabelText: string; virtual; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Paint; override; procedure SetAutoSize(Value: Boolean); override; property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify; property AutoSize: Boolean read FAutoSize write SetAutoSize default True; property FocusControl: TWinControl read FFocusControl write SetFocusControl; property ShowAccelChar: Boolean read FShowAccelChar write SetShowAccelChar default True; property Transparent: Boolean read GetTransparent write SetTransparent stored FTransparentSet; property Layout: TTextLayout read FLayout write SetLayout default tlTop; property WordWrap: Boolean read FWordWrap write SetWordWrap default False; public constructor Create(AOwner: TComponent); override; property Caption; property Canvas; property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave; end; TLabel = class(TCustomLabel) published property Align; property Alignment; property Anchors; property AutoSize; property BiDiMode; property Caption; property Color nodefault; property Constraints; property DragCursor; property DragKind; property DragMode; property Enabled; property FocusControl; property Font; property ParentBiDiMode; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowAccelChar; property ShowHint; property Transparent; property Layout; property Visible; property WordWrap; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseEnter; property OnMouseLeave; property OnStartDock; property OnStartDrag; end; TEditCharCase = (ecNormal, ecUpperCase, ecLowerCase); TCustomEdit = class(TWinControl) private FMaxLength: Integer; FBorderStyle: TBorderStyle; FPasswordChar: Char; FReadOnly: Boolean; FAutoSize: Boolean; FAutoSelect: Boolean; FHideSelection: Boolean; FOEMConvert: Boolean; FCharCase: TEditCharCase; FCreating: Boolean; FModified: Boolean; FOnChange: TNotifyEvent; procedure AdjustHeight; function GetModified: Boolean; function GetCanUndo: Boolean; procedure SetBorderStyle(Value: TBorderStyle); procedure SetCharCase(Value: TEditCharCase); procedure SetHideSelection(Value: Boolean); procedure SetMaxLength(Value: Integer); procedure SetModified(Value: Boolean); procedure SetOEMConvert(Value: Boolean); procedure SetPasswordChar(Value: Char); procedure SetReadOnly(Value: Boolean); procedure SetSelText(const Value: string); procedure UpdateHeight; procedure WMSetFont(var Message: TWMSetFont); message WM_SETFONT; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure WMContextMenu(var Message: TWMContextMenu); message WM_CONTEXTMENU; protected procedure Change; dynamic; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWindowHandle(const Params: TCreateParams); override; procedure CreateWnd; override; procedure DestroyWnd; override; procedure DoSetMaxLength(Value: Integer); virtual; function GetSelLength: Integer; virtual; function GetSelStart: Integer; virtual; function GetSelText: string; virtual; procedure SetAutoSize(Value: Boolean); override; procedure SetSelLength(Value: Integer); virtual; procedure SetSelStart(Value: Integer); virtual; property AutoSelect: Boolean read FAutoSelect write FAutoSelect default True; property AutoSize: Boolean read FAutoSize write SetAutoSize default True; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property CharCase: TEditCharCase read FCharCase write SetCharCase default ecNormal; property HideSelection: Boolean read FHideSelection write SetHideSelection default True; property MaxLength: Integer read FMaxLength write SetMaxLength default 0; property OEMConvert: Boolean read FOEMConvert write SetOEMConvert default False; property PasswordChar: Char read FPasswordChar write SetPasswordChar default #0; property ParentColor default False; property ReadOnly: Boolean read FReadOnly write SetReadOnly default False; property OnChange: TNotifyEvent read FOnChange write FOnChange; public constructor Create(AOwner: TComponent); override; procedure Clear; virtual; procedure ClearSelection; procedure CopyToClipboard; procedure CutToClipboard; procedure DefaultHandler(var Message); override; procedure PasteFromClipboard; procedure Undo; procedure ClearUndo; function GetSelTextBuf(Buffer: PChar; BufSize: Integer): Integer; virtual; procedure SelectAll; procedure SetSelTextBuf(Buffer: PChar); property CanUndo: Boolean read GetCanUndo; property Modified: Boolean read GetModified write SetModified; property SelLength: Integer read GetSelLength write SetSelLength; property SelStart: Integer read GetSelStart write SetSelStart; property SelText: string read GetSelText write SetSelText; property Text; published property TabStop default True; end; TEdit = class(TCustomEdit) published property Anchors; property AutoSelect; property AutoSize; property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property BiDiMode; property BorderStyle; property CharCase; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PasswordChar; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Text; property Visible; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; TScrollStyle = (ssNone, ssHorizontal, ssVertical, ssBoth); TCustomMemo = class(TCustomEdit) private FLines: TStrings; FAlignment: TAlignment; FScrollBars: TScrollStyle; FWordWrap: Boolean; FWantReturns: Boolean; FWantTabs: Boolean; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure WMNCDestroy(var Message: TWMNCDestroy); message WM_NCDESTROY; protected function GetCaretPos: TPoint; virtual; procedure SetCaretPos(const Value: TPoint); virtual; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWindowHandle(const Params: TCreateParams); override; procedure KeyPress(var Key: Char); override; procedure Loaded; override; procedure SetAlignment(Value: TAlignment); procedure SetLines(Value: TStrings); procedure SetScrollBars(Value: TScrollStyle); procedure SetWordWrap(Value: Boolean); property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify; property ScrollBars: TScrollStyle read FScrollBars write SetScrollBars default ssNone; property WantReturns: Boolean read FWantReturns write FWantReturns default True; property WantTabs: Boolean read FWantTabs write FWantTabs default False; property WordWrap: Boolean read FWordWrap write SetWordWrap default True; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetControlsAlignment: TAlignment; override; property CaretPos: TPoint read GetCaretPos write SetCaretPos; property Lines: TStrings read FLines write SetLines; end; TMemo = class(TCustomMemo) published property Align; property Alignment; property Anchors; property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property BiDiMode; property BorderStyle; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property Lines; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ScrollBars; property ShowHint; property TabOrder; property TabStop; property Visible; property WantReturns; property WantTabs; property WordWrap; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; TOwnerDrawState = Windows.TOwnerDrawState; {$NODEFINE TOwnerDrawState} TCustomCombo = class; TDrawItemEvent = procedure(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState) of object; TMeasureItemEvent = procedure(Control: TWinControl; Index: Integer; var Height: Integer) of object; TCustomComboBoxStrings = class(TStrings) private FComboBox: TCustomCombo; protected function GetCount: Integer; override; function Get(Index: Integer): string; override; function GetObject(Index: Integer): TObject; override; procedure PutObject(Index: Integer; AObject: TObject); override; procedure SetUpdateState(Updating: Boolean); override; property ComboBox: TCustomCombo read FComboBox write FComboBox; public procedure Clear; override; procedure Delete(Index: Integer); override; function IndexOf(const S: string): Integer; override; end; TCustomComboBoxStringsClass = class of TCustomComboBoxStrings; TCustomCombo = class(TCustomListControl) private FCanvas: TCanvas; FMaxLength: Integer; FDropDownCount: Integer; FItemIndex: Integer; FOnChange: TNotifyEvent; FOnSelect: TNotifyEvent; FOnDropDown: TNotifyEvent; FOnCloseUp: TNotifyEvent; FItemHeight: Integer; FItems: TStrings; procedure WMCreate(var Message: TWMCreate); message WM_CREATE; procedure CMCancelMode(var Message: TCMCancelMode); message CM_CANCELMODE; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; procedure WMDrawItem(var Message: TWMDrawItem); message WM_DRAWITEM; procedure WMMeasureItem(var Message: TWMMeasureItem); message WM_MEASUREITEM; procedure WMDeleteItem(var Message: TWMDeleteItem); message WM_DELETEITEM; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; protected FEditHandle: HWnd; FListHandle: HWnd; FDropHandle: HWnd; FEditInstance: Pointer; FDefEditProc: Pointer; FListInstance: Pointer; FDefListProc: Pointer; FDroppingDown: Boolean; FFocusChanged: Boolean; FIsFocused: Boolean; FSaveIndex: Integer; procedure AdjustDropDown; virtual; procedure ComboWndProc(var Message: TMessage; ComboWnd: HWnd; ComboProc: Pointer); virtual; procedure CreateWnd; override; procedure EditWndProc(var Message: TMessage); function GetItemsClass: TCustomComboBoxStringsClass; virtual; abstract; procedure WndProc(var Message: TMessage); override; function GetItemHt: Integer; virtual; abstract; procedure SetItemHeight(Value: Integer); virtual; function GetCount: Integer; override; function GetItemCount: Integer; virtual; abstract; function GetItemIndex: Integer; override; function GetDroppedDown: Boolean; function GetSelLength: Integer; function GetSelStart: Integer; procedure ListWndProc(var Message: TMessage); procedure Loaded; override; procedure Change; dynamic; procedure Select; dynamic; procedure DropDown; dynamic; procedure CloseUp; dynamic; procedure DestroyWindowHandle; override; procedure SetDroppedDown(Value: Boolean); procedure SetSelLength(Value: Integer); procedure SetSelStart(Value: Integer); procedure SetMaxLength(Value: Integer); procedure SetDropDownCount(const Value: Integer); virtual; procedure SetItemIndex(const Value: Integer); override; procedure SetItems(const Value: TStrings); virtual; property DropDownCount: Integer read FDropDownCount write SetDropDownCount default 8; property EditHandle: HWnd read FEditHandle; property ItemCount: Integer read GetItemCount; property ItemHeight: Integer read GetItemHt write SetItemHeight; property ListHandle: HWnd read FListHandle; property MaxLength: Integer read FMaxLength write SetMaxLength default 0; property ParentColor default False; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnDropDown: TNotifyEvent read FOnDropDown write FOnDropDown; property OnSelect: TNotifyEvent read FOnSelect write FOnSelect; property OnCloseUp: TNotifyEvent read FOnCloseUp write FOnCloseUp; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddItem(Item: String; AObject: TObject); override; procedure Clear; override; procedure ClearSelection; override; procedure CopySelection(Destination: TCustomListControl); override; procedure DeleteSelected; override; function Focused: Boolean; override; procedure SelectAll; override; property Canvas: TCanvas read FCanvas; property DroppedDown: Boolean read GetDroppedDown write SetDroppedDown; property Items: TStrings read FItems write SetItems; property SelLength: Integer read GetSelLength write SetSelLength; property SelStart: Integer read GetSelStart write SetSelStart; property TabStop default True; end; TComboBoxStyle = (csDropDown, csSimple, csDropDownList, csOwnerDrawFixed, csOwnerDrawVariable); TCustomComboBox = class(TCustomCombo) private FAutoComplete: Boolean; FAutoDropDown: Boolean; FLastTime: Cardinal; FFilter: String; FCharCase: TEditCharCase; FSorted: Boolean; FStyle: TComboBoxStyle; FSaveItems: TStringList; FOnDrawItem: TDrawItemEvent; FOnMeasureItem: TMeasureItemEvent; FAutoCloseUp: Boolean; procedure SetCharCase(Value: TEditCharCase); procedure SetSelText(const Value: string); procedure SetSorted(Value: Boolean); procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure CMParentColorChanged(var Message: TMessage); message CM_PARENTCOLORCHANGED; procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM; procedure CNMeasureItem(var Message: TWMMeasureItem); message CN_MEASUREITEM; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMNCCalcSize(var Message: TWMNCCalcSize); message WM_NCCALCSIZE; protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure DestroyWnd; override; procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); virtual; function GetItemHt: Integer; override; function GetItemsClass: TCustomComboBoxStringsClass; override; function GetSelText: string; procedure KeyPress(var Key: Char); override; procedure MeasureItem(Index: Integer; var Height: Integer); virtual; function SelectItem(const AnItem: String): Boolean; procedure SetStyle(Value: TComboBoxStyle); virtual; property Sorted: Boolean read FSorted write SetSorted default False; property Style: TComboBoxStyle read FStyle write SetStyle default csDropDown; property OnDrawItem: TDrawItemEvent read FOnDrawItem write FOnDrawItem; property OnMeasureItem: TMeasureItemEvent read FOnMeasureItem write FOnMeasureItem; procedure WndProc(var Message: TMessage); override; function GetItemCount: Integer; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property AutoComplete: Boolean read FAutoComplete write FAutoComplete default True; property AutoCloseUp: Boolean read FAutoCloseUp write FAutoCloseUp default False; property AutoDropDown: Boolean read FAutoDropDown write FAutoDropDown default False; property CharCase: TEditCharCase read FCharCase write SetCharCase default ecNormal; property SelText: string read GetSelText write SetSelText; end; TComboBox = class(TCustomComboBox) published property AutoComplete default True; property AutoDropDown default False; property AutoCloseUp default False; property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property Style; {Must be published before Items} property Anchors; property BiDiMode; property CharCase; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property DropDownCount; property Enabled; property Font; property ImeMode; property ImeName; property ItemHeight; property ItemIndex default -1; property MaxLength; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Sorted; property TabOrder; property TabStop; property Text; property Visible; property OnChange; property OnClick; property OnCloseUp; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnDropDown; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; property OnSelect; property OnStartDock; property OnStartDrag; property Items; { Must be published after OnMeasureItem } end; { TButtonControl } TButtonControl = class; TButtonActionLink = class(TWinControlActionLink) protected FClient: TButtonControl; procedure AssignClient(AClient: TObject); override; function IsCheckedLinked: Boolean; override; procedure SetChecked(Value: Boolean); override; end; TButtonActionLinkClass = class of TButtonActionLink; TButtonControl = class(TWinControl) private FClicksDisabled: Boolean; FWordWrap: Boolean; function IsCheckedStored: Boolean; procedure CNCtlColorStatic(var Message: TWMCtlColorStatic); message CN_CTLCOLORSTATIC; procedure WMEraseBkGnd(var Message: TWMEraseBkGnd); message WM_ERASEBKGND; procedure SetWordWrap(const Value: Boolean); protected procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; function GetActionLinkClass: TControlActionLinkClass; override; function GetChecked: Boolean; virtual; procedure SetChecked(Value: Boolean); virtual; procedure WndProc(var Message: TMessage); override; procedure CreateParams(var Params: TCreateParams); override; property Checked: Boolean read GetChecked write SetChecked stored IsCheckedStored default False; property ClicksDisabled: Boolean read FClicksDisabled write FClicksDisabled; property WordWrap: Boolean read FWordWrap write SetWordWrap default False; public constructor Create(AOwner: TComponent); override; end; TButton = class(TButtonControl) private FDefault: Boolean; FCancel: Boolean; FActive: Boolean; FModalResult: TModalResult; procedure SetDefault(Value: Boolean); procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED; procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; procedure CNCtlColorBtn(var Message: TWMCtlColorBtn); message CN_CTLCOLORBTN; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure SetButtonStyle(ADefault: Boolean); virtual; public constructor Create(AOwner: TComponent); override; procedure Click; override; function UseRightToLeftAlignment: Boolean; override; published property Action; property Anchors; property BiDiMode; property Cancel: Boolean read FCancel write FCancel default False; property Caption; property Constraints; property Default: Boolean read FDefault write SetDefault default False; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ModalResult: TModalResult read FModalResult write FModalResult default 0; property ParentBiDiMode; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop default True; property Visible; property WordWrap; property OnClick; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; TCheckBoxState = (cbUnchecked, cbChecked, cbGrayed); TCustomCheckBox = class(TButtonControl) private FAlignment: TLeftRight; FAllowGrayed: Boolean; FState: TCheckBoxState; procedure SetAlignment(Value: TLeftRight); procedure SetState(Value: TCheckBoxState); procedure WMSize(var Message: TMessage); message WM_SIZE; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; protected procedure Toggle; virtual; procedure Click; override; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; function GetChecked: Boolean; override; procedure SetChecked(Value: Boolean); override; property Alignment: TLeftRight read FAlignment write SetAlignment default taRightJustify; property AllowGrayed: Boolean read FAllowGrayed write FAllowGrayed default False; property State: TCheckBoxState read FState write SetState default cbUnchecked; public constructor Create(AOwner: TComponent); override; function GetControlsAlignment: TAlignment; override; published property TabStop default True; end; TCheckBox = class(TCustomCheckBox) published property Action; property Alignment; property AllowGrayed; property Anchors; property BiDiMode; property Caption; property Checked; property Color nodefault; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property State; property TabOrder; property TabStop; property Visible; property WordWrap; property OnClick; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; TRadioButton = class(TButtonControl) private FAlignment: TLeftRight; FChecked: Boolean; procedure SetAlignment(Value: TLeftRight); procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; protected function GetChecked: Boolean; override; procedure SetChecked(Value: Boolean); override; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; public constructor Create(AOwner: TComponent); override; function GetControlsAlignment: TAlignment; override; published property Action; property Alignment: TLeftRight read FAlignment write SetAlignment default taRightJustify; property Anchors; property BiDiMode; property Caption; property Checked; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property WordWrap; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; TListBoxStyle = (lbStandard, lbOwnerDrawFixed, lbOwnerDrawVariable, lbVirtual, lbVirtualOwnerDraw); TLBGetDataEvent = procedure(Control: TWinControl; Index: Integer; var Data: string) of object; TLBGetDataObjectEvent = procedure(Control: TWinControl; Index: Integer; var DataObject: TObject) of object; TLBFindDataEvent = function(Control: TWinControl; FindString: string): Integer of object; TCustomListBox = class(TCustomMultiSelectListControl) private FAutoComplete: Boolean; FCount: Integer; FItems: TStrings; FFilter: String; FLastTime: Cardinal; FBorderStyle: TBorderStyle; FCanvas: TCanvas; FColumns: Integer; FItemHeight: Integer; FOldCount: Integer; FStyle: TListBoxStyle; FIntegralHeight: Boolean; FSorted: Boolean; FExtendedSelect: Boolean; FTabWidth: Integer; FSaveItems: TStringList; FSaveTopIndex: Integer; FSaveItemIndex: Integer; FOnDrawItem: TDrawItemEvent; FOnMeasureItem: TMeasureItemEvent; FOnData: TLBGetDataEvent; FOnDataFind: TLBFindDataEvent; FOnDataObject: TLBGetDataObjectEvent; function GetItemHeight: Integer; function GetTopIndex: Integer; procedure LBGetText(var Message: TMessage); message LB_GETTEXT; procedure LBGetTextLen(var Message: TMessage); message LB_GETTEXTLEN; procedure SetBorderStyle(Value: TBorderStyle); procedure SetColumnWidth; procedure SetColumns(Value: Integer); procedure SetCount(const Value: Integer); procedure SetExtendedSelect(Value: Boolean); procedure SetIntegralHeight(Value: Boolean); procedure SetItemHeight(Value: Integer); procedure SetItems(Value: TStrings); procedure SetSelected(Index: Integer; Value: Boolean); procedure SetSorted(Value: Boolean); procedure SetStyle(Value: TListBoxStyle); procedure SetTabWidth(Value: Integer); procedure SetTopIndex(Value: Integer); procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM; procedure CNMeasureItem(var Message: TWMMeasureItem); message CN_MEASUREITEM; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; function GetScrollWidth: Integer; procedure SetScrollWidth(const Value: Integer); protected FMoving: Boolean; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure DestroyWnd; override; function DoGetData(const Index: Integer): String; function DoGetDataObject(const Index: Integer): TObject; function DoFindData(const Data: String): Integer; procedure WndProc(var Message: TMessage); override; procedure DragCanceled; override; procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); virtual; function GetCount: Integer; override; function GetSelCount: Integer; override; procedure MeasureItem(Index: Integer; var Height: Integer); virtual; function InternalGetItemData(Index: Integer): Longint; dynamic; procedure InternalSetItemData(Index: Integer; AData: Longint); dynamic; function GetItemData(Index: Integer): LongInt; dynamic; function GetItemIndex: Integer; override; function GetSelected(Index: Integer): Boolean; procedure KeyPress(var Key: Char); override; procedure SetItemData(Index: Integer; AData: LongInt); dynamic; procedure ResetContent; dynamic; procedure DeleteString(Index: Integer); dynamic; procedure SetMultiSelect(Value: Boolean); override; procedure SetItemIndex(const Value: Integer); override; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property Columns: Integer read FColumns write SetColumns default 0; property ExtendedSelect: Boolean read FExtendedSelect write SetExtendedSelect default True; property IntegralHeight: Boolean read FIntegralHeight write SetIntegralHeight default False; property ItemHeight: Integer read GetItemHeight write SetItemHeight; property ParentColor default False; property Sorted: Boolean read FSorted write SetSorted default False; property Style: TListBoxStyle read FStyle write SetStyle default lbStandard; property TabWidth: Integer read FTabWidth write SetTabWidth default 0; property OnDrawItem: TDrawItemEvent read FOnDrawItem write FOnDrawItem; property OnMeasureItem: TMeasureItemEvent read FOnMeasureItem write FOnMeasureItem; property OnData: TLBGetDataEvent read FOnData write FOnData; property OnDataObject: TLBGetDataObjectEvent read FOnDataObject write FOnDataObject; property OnDataFind: TLBFindDataEvent read FOnDataFind write FOnDataFind; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddItem(Item: String; AObject: TObject); override; procedure Clear; override; procedure ClearSelection; override; procedure CopySelection(Destination: TCustomListControl); override; procedure DeleteSelected; override; function ItemAtPos(Pos: TPoint; Existing: Boolean): Integer; function ItemRect(Index: Integer): TRect; procedure SelectAll; override; property AutoComplete: Boolean read FAutoComplete write FAutoComplete default True; property Canvas: TCanvas read FCanvas; property Count: Integer read GetCount write SetCount; property Items: TStrings read FItems write SetItems; property Selected[Index: Integer]: Boolean read GetSelected write SetSelected; property ScrollWidth: Integer read GetScrollWidth write SetScrollWidth default 0; property TopIndex: Integer read GetTopIndex write SetTopIndex; published property TabStop default True; end; TListBox = class(TCustomListBox) published property Style; property AutoComplete; property Align; property Anchors; property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property BiDiMode; property BorderStyle; property Color; property Columns; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property ExtendedSelect; property Font; property ImeMode; property ImeName; property IntegralHeight; property ItemHeight; property Items; property MultiSelect; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ScrollWidth; property ShowHint; property Sorted; property TabOrder; property TabStop; property TabWidth; property Visible; property OnClick; property OnContextPopup; property OnData; property OnDataFind; property OnDataObject; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; TScrollCode = (scLineUp, scLineDown, scPageUp, scPageDown, scPosition, scTrack, scTop, scBottom, scEndScroll); TScrollEvent = procedure(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer) of object; TScrollBar = class(TWinControl) private FKind: TScrollBarKind; FPosition: Integer; FMin: Integer; FMax: Integer; FPageSize: Integer; FRTLFactor: Integer; FSmallChange: TScrollBarInc; FLargeChange: TScrollBarInc; FOnChange: TNotifyEvent; FOnScroll: TScrollEvent; procedure DoScroll(var Message: TWMScroll); function NotRightToLeft: Boolean; procedure SetKind(Value: TScrollBarKind); procedure SetMax(Value: Integer); procedure SetMin(Value: Integer); procedure SetPosition(Value: Integer); procedure SetPageSize(Value: Integer); procedure CNHScroll(var Message: TWMHScroll); message CN_HSCROLL; procedure CNVScroll(var Message: TWMVScroll); message CN_VSCROLL; procedure CNCtlColorScrollBar(var Message: TMessage); message CN_CTLCOLORSCROLLBAR; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure Change; dynamic; procedure Scroll(ScrollCode: TScrollCode; var ScrollPos: Integer); dynamic; public constructor Create(AOwner: TComponent); override; procedure SetParams(APosition, AMin, AMax: Integer); published property Align; property Anchors; property BiDiMode; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Kind: TScrollBarKind read FKind write SetKind default sbHorizontal; property LargeChange: TScrollBarInc read FLargeChange write FLargeChange default 1; property Max: Integer read FMax write SetMax default 100; property Min: Integer read FMin write SetMin default 0; property PageSize: Integer read FPageSize write SetPageSize; property ParentBiDiMode; property ParentCtl3D; property ParentShowHint; property PopupMenu; property Position: Integer read FPosition write SetPosition default 0; property ShowHint; property SmallChange: TScrollBarInc read FSmallChange write FSmallChange default 1; property TabOrder; property TabStop default True; property Visible; property OnContextPopup; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnScroll: TScrollEvent read FOnScroll write FOnScroll; property OnStartDock; property OnStartDrag; end; TStaticBorderStyle = (sbsNone, sbsSingle, sbsSunken); TCustomStaticText = class(TWinControl) private FAlignment: TAlignment; FAutoSize: Boolean; FBorderStyle: TStaticBorderStyle; FFocusControl: TWinControl; FShowAccelChar: Boolean; procedure CNCtlColorStatic(var Message: TWMCtlColorStatic); message CN_CTLCOLORSTATIC; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure AdjustBounds; procedure SetAlignment(Value: TAlignment); procedure SetBorderStyle(Value: TStaticBorderStyle); procedure SetFocusControl(Value: TWinControl); procedure SetShowAccelChar(Value: Boolean); procedure SetTransparent(const Value: Boolean); function GetTransparent: Boolean; protected procedure CreateParams(var Params: TCreateParams); override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetAutoSize(Value: Boolean); override; property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify; property AutoSize: Boolean read FAutoSize write SetAutoSize default True; property BorderStyle: TStaticBorderStyle read FBorderStyle write SetBorderStyle default sbsNone; property FocusControl: TWinControl read FFocusControl write SetFocusControl; property ShowAccelChar: Boolean read FShowAccelChar write SetShowAccelChar default True; property Transparent: Boolean read GetTransparent write SetTransparent default True; public constructor Create(AOwner: TComponent); override; end; TStaticText = class(TCustomStaticText) published property Align; property Alignment; property Anchors; property AutoSize; property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property BiDiMode; property BorderStyle; property Caption; property Color nodefault; property Constraints; property DragCursor; property DragKind; property DragMode; property Enabled; property FocusControl; property Font; property ParentBiDiMode; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowAccelChar; property ShowHint; property TabOrder; property TabStop; property Transparent; property Visible; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; implementation uses Consts, RTLConsts, ActnList, Themes; function HasPopup(Control: TControl): Boolean; begin Result := True; while Control <> nil do if TCustomEdit(Control).PopupMenu <> nil then Exit else Control := Control.Parent; Result := False; end; type TSelection = record StartPos, EndPos: Integer; end; TMemoStrings = class(TStrings) private Memo: TCustomMemo; protected function Get(Index: Integer): string; override; function GetCount: Integer; override; function GetTextStr: string; override; procedure Put(Index: Integer; const S: string); override; procedure SetTextStr(const Value: string); override; procedure SetUpdateState(Updating: Boolean); override; public procedure Clear; override; procedure Delete(Index: Integer); override; procedure Insert(Index: Integer; const S: string); override; end; TComboBoxStrings = class(TCustomComboBoxStrings) public function Add(const S: string): Integer; override; procedure Insert(Index: Integer; const S: string); override; end; TListBoxStrings = class(TStrings) private ListBox: TCustomListBox; protected procedure Put(Index: Integer; const S: string); override; function Get(Index: Integer): string; override; function GetCount: Integer; override; function GetObject(Index: Integer): TObject; override; procedure PutObject(Index: Integer; AObject: TObject); override; procedure SetUpdateState(Updating: Boolean); override; public function Add(const S: string): Integer; override; procedure Clear; override; procedure Delete(Index: Integer); override; procedure Exchange(Index1, Index2: Integer); override; function IndexOf(const S: string): Integer; override; procedure Insert(Index: Integer; const S: string); override; procedure Move(CurIndex, NewIndex: Integer); override; end; const BorderStyles: array[TBorderStyle] of DWORD = (0, WS_BORDER); { TCustomGroupBox } constructor TCustomGroupBox.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csSetCaption, csDoubleClicks, csReplicatable, csParentBackground]; Width := 185; Height := 105; end; procedure TCustomGroupBox.AdjustClientRect(var Rect: TRect); begin inherited AdjustClientRect(Rect); Canvas.Font := Font; Inc(Rect.Top, Canvas.TextHeight('0')); InflateRect(Rect, -1, -1); if Ctl3d then InflateRect(Rect, -1, -1); end; procedure TCustomGroupBox.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params.WindowClass do style := style and not (CS_HREDRAW or CS_VREDRAW); end; procedure TCustomGroupBox.Paint; var H: Integer; R: TRect; Flags: Longint; CaptionRect, OuterRect: TRect; Size: TSize; Box: TThemedButton; Details: TThemedElementDetails; begin with Canvas do begin Font := Self.Font; if ThemeServices.ThemesEnabled then begin if Text <> '' then begin GetTextExtentPoint32(Handle, PChar(Text), Length(Text), Size); CaptionRect := Rect(0, 0, Size.cx, Size.cy); if not UseRightToLeftAlignment then OffsetRect(CaptionRect, 8, 0) else OffsetRect(CaptionRect, Width - 8 - CaptionRect.Right, 0); end else CaptionRect := Rect(0, 0, 0, 0); OuterRect := ClientRect; OuterRect.Top := (CaptionRect.Bottom - CaptionRect.Top) div 2; with CaptionRect do ExcludeClipRect(Handle, Left, Top, Right, Bottom); if Enabled then Box := tbGroupBoxNormal else Box := tbGroupBoxDisabled; Details := ThemeServices.GetElementDetails(Box); ThemeServices.DrawElement(Handle, Details, OuterRect); SelectClipRgn(Handle, 0); if Text <> '' then ThemeServices.DrawText(Handle, Details, Text, CaptionRect, DT_LEFT, 0); end else begin H := TextHeight('0'); R := Rect(0, H div 2 - 1, Width, Height); if Ctl3D then begin Inc(R.Left); Inc(R.Top); Brush.Color := clBtnHighlight; FrameRect(R); OffsetRect(R, -1, -1); Brush.Color := clBtnShadow; end else Brush.Color := clWindowFrame; FrameRect(R); if Text <> '' then begin if not UseRightToLeftAlignment then R := Rect(8, 0, 0, H) else R := Rect(R.Right - Canvas.TextWidth(Text) - 8, 0, 0, H); Flags := DrawTextBiDiModeFlags(DT_SINGLELINE); DrawText(Handle, PChar(Text), Length(Text), R, Flags or DT_CALCRECT); Brush.Color := Color; DrawText(Handle, PChar(Text), Length(Text), R, Flags); end; end; end; end; procedure TCustomGroupBox.CMDialogChar(var Message: TCMDialogChar); begin with Message do if IsAccel(CharCode, Caption) and CanFocus then begin SelectFirst; Result := 1; end else inherited; end; procedure TCustomGroupBox.CMTextChanged(var Message: TMessage); begin Invalidate; Realign; end; procedure TCustomGroupBox.CMCtl3DChanged(var Message: TMessage); begin inherited; Invalidate; Realign; end; procedure TCustomGroupBox.WMSize(var Message: TMessage); begin inherited; Invalidate; end; { TCustomLabel } constructor TCustomLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; Width := 65; Height := 17; FAutoSize := True; FShowAccelChar := True; { The "default" value for the Transparent property depends on if you have Themes available and enabled or not. If you have ever explicitly set it, that will override the default value. } if ThemeServices.ThemesEnabled then ControlStyle := ControlStyle - [csOpaque] else ControlStyle := ControlStyle + [csOpaque]; end; function TCustomLabel.GetLabelText: string; begin Result := Caption; end; procedure TCustomLabel.DoDrawText(var Rect: TRect; Flags: Longint); var Text: string; begin Text := GetLabelText; if (Flags and DT_CALCRECT <> 0) and ((Text = '') or FShowAccelChar and (Text[1] = '&') and (Text[2] = #0)) then Text := Text + ' '; if not FShowAccelChar then Flags := Flags or DT_NOPREFIX; Flags := DrawTextBiDiModeFlags(Flags); Canvas.Font := Font; if not Enabled then begin OffsetRect(Rect, 1, 1); Canvas.Font.Color := clBtnHighlight; DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); OffsetRect(Rect, -1, -1); Canvas.Font.Color := clBtnShadow; DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); end else DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); end; procedure TCustomLabel.Paint; const Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER); WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK); var Rect, CalcRect: TRect; DrawStyle: Longint; begin with Canvas do begin if not Transparent then begin Brush.Color := Self.Color; Brush.Style := bsSolid; FillRect(ClientRect); end; Brush.Style := bsClear; Rect := ClientRect; { DoDrawText takes care of BiDi alignments } DrawStyle := DT_EXPANDTABS or WordWraps[FWordWrap] or Alignments[FAlignment]; { Calculate vertical layout } if FLayout <> tlTop then begin CalcRect := Rect; DoDrawText(CalcRect, DrawStyle or DT_CALCRECT); if FLayout = tlBottom then OffsetRect(Rect, 0, Height - CalcRect.Bottom) else OffsetRect(Rect, 0, (Height - CalcRect.Bottom) div 2); end; DoDrawText(Rect, DrawStyle); end; end; procedure TCustomLabel.Loaded; begin inherited Loaded; AdjustBounds; end; procedure TCustomLabel.AdjustBounds; const WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK); var DC: HDC; X: Integer; Rect: TRect; AAlignment: TAlignment; begin if not (csReading in ComponentState) and FAutoSize then begin Rect := ClientRect; DC := GetDC(0); Canvas.Handle := DC; DoDrawText(Rect, (DT_EXPANDTABS or DT_CALCRECT) or WordWraps[FWordWrap]); Canvas.Handle := 0; ReleaseDC(0, DC); X := Left; AAlignment := FAlignment; if UseRightToLeftAlignment then ChangeBiDiModeAlignment(AAlignment); if AAlignment = taRightJustify then Inc(X, Width - Rect.Right); SetBounds(X, Top, Rect.Right, Rect.Bottom); end; end; procedure TCustomLabel.SetAlignment(Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; Invalidate; end; end; procedure TCustomLabel.SetAutoSize(Value: Boolean); begin if FAutoSize <> Value then begin FAutoSize := Value; AdjustBounds; end; end; function TCustomLabel.GetTransparent: Boolean; begin Result := not (csOpaque in ControlStyle); end; procedure TCustomLabel.SetFocusControl(Value: TWinControl); begin FFocusControl := Value; if Value <> nil then Value.FreeNotification(Self); end; procedure TCustomLabel.SetShowAccelChar(Value: Boolean); begin if FShowAccelChar <> Value then begin FShowAccelChar := Value; Invalidate; end; end; procedure TCustomLabel.SetTransparent(Value: Boolean); begin if Transparent <> Value then begin if Value then ControlStyle := ControlStyle - [csOpaque] else ControlStyle := ControlStyle + [csOpaque]; Invalidate; end; FTransparentSet := True; end; procedure TCustomLabel.SetLayout(Value: TTextLayout); begin if FLayout <> Value then begin FLayout := Value; Invalidate; end; end; procedure TCustomLabel.SetWordWrap(Value: Boolean); begin if FWordWrap <> Value then begin FWordWrap := Value; AdjustBounds; Invalidate; end; end; procedure TCustomLabel.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FFocusControl) then FFocusControl := nil; end; procedure TCustomLabel.CMTextChanged(var Message: TMessage); begin Invalidate; AdjustBounds; end; procedure TCustomLabel.CMFontChanged(var Message: TMessage); begin inherited; AdjustBounds; end; procedure TCustomLabel.CMDialogChar(var Message: TCMDialogChar); begin if (FFocusControl <> nil) and Enabled and ShowAccelChar and IsAccel(Message.CharCode, Caption) then with FFocusControl do if CanFocus then begin SetFocus; Message.Result := 1; end; end; procedure TCustomLabel.CMMouseEnter(var Message: TMessage); begin inherited; if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); end; procedure TCustomLabel.CMMouseLeave(var Message: TMessage); begin inherited; if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; { TCustomEdit } constructor TCustomEdit.Create(AOwner: TComponent); const EditStyle = [csClickEvents, csSetCaption, csDoubleClicks, csFixedHeight]; begin inherited Create(AOwner); if NewStyleControls then ControlStyle := EditStyle else ControlStyle := EditStyle + [csFramed]; Width := 121; Height := 25; TabStop := True; ParentColor := False; FBorderStyle := bsSingle; FAutoSize := True; FAutoSelect := True; FHideSelection := True; AdjustHeight; end; procedure TCustomEdit.DoSetMaxLength(Value: Integer); begin SendMessage(Handle, EM_LIMITTEXT, Value, 0) end; procedure TCustomEdit.SetAutoSize(Value: Boolean); begin if FAutoSize <> Value then begin FAutoSize := Value; UpdateHeight; end; end; procedure TCustomEdit.SetBorderStyle(Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; UpdateHeight; RecreateWnd; end; end; procedure TCustomEdit.SetCharCase(Value: TEditCharCase); begin if FCharCase <> Value then begin FCharCase := Value; RecreateWnd; end; end; procedure TCustomEdit.SetHideSelection(Value: Boolean); begin if FHideSelection <> Value then begin FHideSelection := Value; RecreateWnd; end; end; procedure TCustomEdit.SetMaxLength(Value: Integer); begin if FMaxLength <> Value then begin FMaxLength := Value; if HandleAllocated then DoSetMaxLength(Value); end; end; procedure TCustomEdit.SetOEMConvert(Value: Boolean); begin if FOEMConvert <> Value then begin FOEMConvert := Value; RecreateWnd; end; end; function TCustomEdit.GetModified: Boolean; begin Result := FModified; if HandleAllocated then Result := SendMessage(Handle, EM_GETMODIFY, 0, 0) <> 0; end; function TCustomEdit.GetCanUndo: Boolean; begin Result := False; if HandleAllocated then Result := SendMessage(Handle, EM_CANUNDO, 0, 0) <> 0; end; procedure TCustomEdit.SetModified(Value: Boolean); begin if HandleAllocated then SendMessage(Handle, EM_SETMODIFY, Byte(Value), 0) else FModified := Value; end; procedure TCustomEdit.SetPasswordChar(Value: Char); begin if FPasswordChar <> Value then begin FPasswordChar := Value; if HandleAllocated then begin SendMessage(Handle, EM_SETPASSWORDCHAR, Ord(FPasswordChar), 0); SetTextBuf(PChar(Text)); end; end; end; procedure TCustomEdit.SetReadOnly(Value: Boolean); begin if FReadOnly <> Value then begin FReadOnly := Value; if HandleAllocated then SendMessage(Handle, EM_SETREADONLY, Ord(Value), 0); end; end; function TCustomEdit.GetSelStart: Integer; begin SendMessage(Handle, EM_GETSEL, Longint(@Result), 0); end; procedure TCustomEdit.SetSelStart(Value: Integer); begin SendMessage(Handle, EM_SETSEL, Value, Value); end; function TCustomEdit.GetSelLength: Integer; var Selection: TSelection; begin SendMessage(Handle, EM_GETSEL, Longint(@Selection.StartPos), Longint(@Selection.EndPos)); Result := Selection.EndPos - Selection.StartPos; end; procedure TCustomEdit.SetSelLength(Value: Integer); var Selection: TSelection; begin SendMessage(Handle, EM_GETSEL, Longint(@Selection.StartPos), Longint(@Selection.EndPos)); Selection.EndPos := Selection.StartPos + Value; SendMessage(Handle, EM_SETSEL, Selection.StartPos, Selection.EndPos); SendMessage(Handle, EM_SCROLLCARET, 0,0); end; procedure TCustomEdit.Clear; begin SetWindowText(Handle, ''); end; procedure TCustomEdit.ClearSelection; begin SendMessage(Handle, WM_CLEAR, 0, 0); end; procedure TCustomEdit.CopyToClipboard; begin SendMessage(Handle, WM_COPY, 0, 0); end; procedure TCustomEdit.CutToClipboard; begin SendMessage(Handle, WM_CUT, 0, 0); end; procedure TCustomEdit.PasteFromClipboard; begin SendMessage(Handle, WM_PASTE, 0, 0); end; procedure TCustomEdit.Undo; begin SendMessage(Handle, WM_UNDO, 0, 0); end; procedure TCustomEdit.ClearUndo; begin SendMessage(Handle, EM_EMPTYUNDOBUFFER, 0, 0); end; procedure TCustomEdit.SelectAll; begin SendMessage(Handle, EM_SETSEL, 0, -1); end; function TCustomEdit.GetSelTextBuf(Buffer: PChar; BufSize: Integer): Integer; var P: PChar; StartPos: Integer; begin StartPos := GetSelStart; Result := GetSelLength; P := StrAlloc(GetTextLen + 1); try GetTextBuf(P, StrBufSize(P)); if Result >= BufSize then Result := BufSize - 1; StrLCopy(Buffer, P + StartPos, Result); finally StrDispose(P); end; end; procedure TCustomEdit.SetSelTextBuf(Buffer: PChar); begin SendMessage(Handle, EM_REPLACESEL, 0, LongInt(Buffer)); end; function TCustomEdit.GetSelText: string; var P: PChar; SelStart, Len: Integer; begin SelStart := GetSelStart; Len := GetSelLength; SetString(Result, PChar(nil), Len); if Len <> 0 then begin P := StrAlloc(GetTextLen + 1); try GetTextBuf(P, StrBufSize(P)); Move(P[SelStart], Pointer(Result)^, Len); finally StrDispose(P); end; end; end; procedure TCustomEdit.SetSelText(const Value: String); begin SendMessage(Handle, EM_REPLACESEL, 0, Longint(PChar(Value))); end; procedure TCustomEdit.CreateParams(var Params: TCreateParams); const Passwords: array[Boolean] of DWORD = (0, ES_PASSWORD); ReadOnlys: array[Boolean] of DWORD = (0, ES_READONLY); CharCases: array[TEditCharCase] of DWORD = (0, ES_UPPERCASE, ES_LOWERCASE); HideSelections: array[Boolean] of DWORD = (ES_NOHIDESEL, 0); OEMConverts: array[Boolean] of DWORD = (0, ES_OEMCONVERT); begin inherited CreateParams(Params); CreateSubClass(Params, 'EDIT'); with Params do begin Style := Style or (ES_AUTOHSCROLL or ES_AUTOVSCROLL) or BorderStyles[FBorderStyle] or Passwords[FPasswordChar <> #0] or ReadOnlys[FReadOnly] or CharCases[FCharCase] or HideSelections[FHideSelection] or OEMConverts[FOEMConvert]; if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then begin Style := Style and not WS_BORDER; ExStyle := ExStyle or WS_EX_CLIENTEDGE; end; end; end; procedure TCustomEdit.CreateWindowHandle(const Params: TCreateParams); var P: TCreateParams; begin if SysLocale.FarEast and (Win32Platform <> VER_PLATFORM_WIN32_NT) and ((Params.Style and ES_READONLY) <> 0) then begin // Work around Far East Win95 API/IME bug. P := Params; P.Style := P.Style and (not ES_READONLY); inherited CreateWindowHandle(P); if WindowHandle <> 0 then SendMessage(WindowHandle, EM_SETREADONLY, Ord(True), 0); end else inherited CreateWindowHandle(Params); end; procedure TCustomEdit.CreateWnd; begin FCreating := True; try inherited CreateWnd; finally FCreating := False; end; DoSetMaxLength(FMaxLength); Modified := FModified; if FPasswordChar <> #0 then SendMessage(Handle, EM_SETPASSWORDCHAR, Ord(FPasswordChar), 0); UpdateHeight; end; procedure TCustomEdit.DestroyWnd; begin FModified := Modified; inherited DestroyWnd; end; procedure TCustomEdit.UpdateHeight; begin if FAutoSize and (BorderStyle = bsSingle) then begin ControlStyle := ControlStyle + [csFixedHeight]; AdjustHeight; end else ControlStyle := ControlStyle - [csFixedHeight]; end; procedure TCustomEdit.AdjustHeight; var DC: HDC; SaveFont: HFont; I: Integer; SysMetrics, Metrics: TTextMetric; begin DC := GetDC(0); GetTextMetrics(DC, SysMetrics); SaveFont := SelectObject(DC, Font.Handle); GetTextMetrics(DC, Metrics); SelectObject(DC, SaveFont); ReleaseDC(0, DC); if NewStyleControls then begin if Ctl3D then I := 8 else I := 6; I := GetSystemMetrics(SM_CYBORDER) * I; end else begin I := SysMetrics.tmHeight; if I > Metrics.tmHeight then I := Metrics.tmHeight; I := I div 4 + GetSystemMetrics(SM_CYBORDER) * 4; end; Height := Metrics.tmHeight + I; end; procedure TCustomEdit.Change; begin inherited Changed; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomEdit.DefaultHandler(var Message); begin case TMessage(Message).Msg of WM_SETFOCUS: if (Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and not IsWindow(TWMSetFocus(Message).FocusedWnd) then TWMSetFocus(Message).FocusedWnd := 0; end; inherited; end; procedure TCustomEdit.WMSetFont(var Message: TWMSetFont); begin inherited; if NewStyleControls and (GetWindowLong(Handle, GWL_STYLE) and ES_MULTILINE = 0) then SendMessage(Handle, EM_SETMARGINS, EC_LEFTMARGIN or EC_RIGHTMARGIN, 0); end; procedure TCustomEdit.CMCtl3DChanged(var Message: TMessage); begin if NewStyleControls and (FBorderStyle = bsSingle) then begin UpdateHeight; RecreateWnd; end; inherited; end; procedure TCustomEdit.CMFontChanged(var Message: TMessage); begin inherited; if (csFixedHeight in ControlStyle) and not ((csDesigning in ComponentState) and (csLoading in ComponentState)) then AdjustHeight; end; procedure TCustomEdit.CNCommand(var Message: TWMCommand); begin if (Message.NotifyCode = EN_CHANGE) and not FCreating then Change; end; procedure TCustomEdit.CMEnter(var Message: TCMGotFocus); begin if FAutoSelect and not (csLButtonDown in ControlState) and (GetWindowLong(Handle, GWL_STYLE) and ES_MULTILINE = 0) then SelectAll; inherited; end; procedure TCustomEdit.CMTextChanged(var Message: TMessage); begin inherited; if not HandleAllocated or (GetWindowLong(Handle, GWL_STYLE) and ES_MULTILINE <> 0) then Change; end; procedure TCustomEdit.WMContextMenu(var Message: TWMContextMenu); begin SetFocus; inherited; end; { TMemoStrings } function TMemoStrings.GetCount: Integer; begin Result := 0; if Memo.HandleAllocated or (Memo.WindowText <> nil) then begin Result := SendMessage(Memo.Handle, EM_GETLINECOUNT, 0, 0); if SendMessage(Memo.Handle, EM_LINELENGTH, SendMessage(Memo.Handle, EM_LINEINDEX, Result - 1, 0), 0) = 0 then Dec(Result); end; end; function TMemoStrings.Get(Index: Integer): string; var Text: array[0..4095] of Char; begin Word((@Text)^) := SizeOf(Text); SetString(Result, Text, SendMessage(Memo.Handle, EM_GETLINE, Index, Longint(@Text))); end; procedure TMemoStrings.Put(Index: Integer; const S: string); var SelStart: Integer; begin SelStart := SendMessage(Memo.Handle, EM_LINEINDEX, Index, 0); if SelStart >= 0 then begin SendMessage(Memo.Handle, EM_SETSEL, SelStart, SelStart + SendMessage(Memo.Handle, EM_LINELENGTH, SelStart, 0)); SendMessage(Memo.Handle, EM_REPLACESEL, 0, Longint(PChar(S))); end; end; procedure TMemoStrings.Insert(Index: Integer; const S: string); var SelStart, LineLen: Integer; Line: string; begin if Index >= 0 then begin SelStart := SendMessage(Memo.Handle, EM_LINEINDEX, Index, 0); if SelStart >= 0 then Line := S + #13#10 else begin SelStart := SendMessage(Memo.Handle, EM_LINEINDEX, Index - 1, 0); if SelStart < 0 then Exit; LineLen := SendMessage(Memo.Handle, EM_LINELENGTH, SelStart, 0); if LineLen = 0 then Exit; Inc(SelStart, LineLen); Line := #13#10 + s; end; SendMessage(Memo.Handle, EM_SETSEL, SelStart, SelStart); SendMessage(Memo.Handle, EM_REPLACESEL, 0, Longint(PChar(Line))); end; end; procedure TMemoStrings.Delete(Index: Integer); const Empty: PChar = ''; var SelStart, SelEnd: Integer; begin SelStart := SendMessage(Memo.Handle, EM_LINEINDEX, Index, 0); if SelStart >= 0 then begin SelEnd := SendMessage(Memo.Handle, EM_LINEINDEX, Index + 1, 0); if SelEnd < 0 then SelEnd := SelStart + SendMessage(Memo.Handle, EM_LINELENGTH, SelStart, 0); SendMessage(Memo.Handle, EM_SETSEL, SelStart, SelEnd); SendMessage(Memo.Handle, EM_REPLACESEL, 0, Longint(Empty)); end; end; procedure TMemoStrings.Clear; begin Memo.Clear; end; procedure TMemoStrings.SetUpdateState(Updating: Boolean); begin if Memo.HandleAllocated then begin SendMessage(Memo.Handle, WM_SETREDRAW, Ord(not Updating), 0); if not Updating then begin // WM_SETREDRAW causes visibility side effects in memo controls Memo.Perform(CM_SHOWINGCHANGED,0,0); // This reasserts the visibility we want Memo.Refresh; end; end; end; function TMemoStrings.GetTextStr: string; begin Result := Memo.Text; end; procedure TMemoStrings.SetTextStr(const Value: string); var NewText: string; begin NewText := AdjustLineBreaks(Value); if (Length(NewText) <> Memo.GetTextLen) or (NewText <> Memo.Text) then begin if SendMessage(Memo.Handle, WM_SETTEXT, 0, Longint(NewText)) = 0 then raise EInvalidOperation.Create(SInvalidMemoSize); Memo.Perform(CM_TEXTCHANGED, 0, 0); end; end; { TCustomMemo } constructor TCustomMemo.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 185; Height := 89; AutoSize := False; FWordWrap := True; FWantReturns := True; FLines := TMemoStrings.Create; TMemoStrings(FLines).Memo := Self; ParentBackground := False; end; destructor TCustomMemo.Destroy; begin FLines.Free; inherited Destroy; end; procedure TCustomMemo.CreateParams(var Params: TCreateParams); const Alignments: array[Boolean, TAlignment] of DWORD = ((ES_LEFT, ES_RIGHT, ES_CENTER),(ES_RIGHT, ES_LEFT, ES_CENTER)); ScrollBar: array[TScrollStyle] of DWORD = (0, WS_HSCROLL, WS_VSCROLL, WS_HSCROLL or WS_VSCROLL); WordWraps: array[Boolean] of DWORD = (0, ES_AUTOHSCROLL); begin inherited CreateParams(Params); with Params do begin Style := Style and not WordWraps[FWordWrap] or ES_MULTILINE or Alignments[UseRightToLeftAlignment, FAlignment] or ScrollBar[FScrollBars]; end; end; procedure TCustomMemo.CreateWindowHandle(const Params: TCreateParams); begin with Params do begin if SysLocale.FarEast and (Win32Platform <> VER_PLATFORM_WIN32_NT) and ((Style and ES_READONLY) <> 0) then begin // Work around Far East Win95 API/IME bug. WindowHandle := CreateWindowEx(ExStyle, WinClassName, '', Style and (not ES_READONLY), X, Y, Width, Height, WndParent, 0, HInstance, Param); if WindowHandle <> 0 then SendMessage(WindowHandle, EM_SETREADONLY, Ord(True), 0); end else WindowHandle := CreateWindowEx(ExStyle, WinClassName, '', Style, X, Y, Width, Height, WndParent, 0, HInstance, Param); SendMessage(WindowHandle, WM_SETTEXT, 0, Longint(Caption)); end; end; function TCustomMemo.GetCaretPos: TPoint; begin Result.X := LongRec(SendMessage(Handle, EM_GETSEL, 0, 0)).Hi; Result.Y := SendMessage(Handle, EM_LINEFROMCHAR, Result.X, 0); Result.X := Result.X - SendMessage(Handle, EM_LINEINDEX, -1, 0); end; procedure TCustomMemo.SetCaretPos(const Value: TPoint); var CharIdx: Integer; begin CharIdx := SendMessage(Handle, EM_LINEINDEX, Value.y, 0) + Value.x; SendMessage(Handle, EM_SETSEL, CharIdx, CharIdx); end; function TCustomMemo.GetControlsAlignment: TAlignment; begin Result := FAlignment; end; procedure TCustomMemo.Loaded; begin inherited Loaded; Modified := False; end; procedure TCustomMemo.SetAlignment(Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; procedure TCustomMemo.SetLines(Value: TStrings); begin FLines.Assign(Value); end; procedure TCustomMemo.SetScrollBars(Value: TScrollStyle); begin if FScrollBars <> Value then begin FScrollBars := Value; RecreateWnd; end; end; procedure TCustomMemo.SetWordWrap(Value: Boolean); begin if Value <> FWordWrap then begin FWordWrap := Value; RecreateWnd; end; end; procedure TCustomMemo.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; if FWantTabs then Message.Result := Message.Result or DLGC_WANTTAB else Message.Result := Message.Result and not DLGC_WANTTAB; if not FWantReturns then Message.Result := Message.Result and not DLGC_WANTALLKEYS; end; procedure TCustomMemo.WMNCDestroy(var Message: TWMNCDestroy); begin inherited; end; procedure TCustomMemo.KeyPress(var Key: Char); begin inherited KeyPress(Key); if (Key = Char(VK_RETURN)) and not FWantReturns then Key := #0; end; { TCustomComboBoxStrings } function TCustomComboBoxStrings.GetCount: Integer; begin Result := SendMessage(ComboBox.Handle, CB_GETCOUNT, 0, 0); end; function TCustomComboBoxStrings.GetObject(Index: Integer): TObject; begin Result := TObject(SendMessage(ComboBox.Handle, CB_GETITEMDATA, Index, 0)); if Longint(Result) = CB_ERR then Error(SListIndexError, Index); end; procedure TCustomComboBoxStrings.PutObject(Index: Integer; AObject: TObject); begin SendMessage(ComboBox.Handle, CB_SETITEMDATA, Index, Longint(AObject)); end; function TCustomComboBoxStrings.Get(Index: Integer): string; var Len: Integer; begin Len := SendMessage(ComboBox.Handle, CB_GETLBTEXTLEN, Index, 0); if Len <> CB_ERR then begin SetLength(Result, Len); SendMessage(ComboBox.Handle, CB_GETLBTEXT, Index, Longint(PChar(Result))); end else SetLength(Result, 0); end; procedure TCustomComboBoxStrings.Clear; var S: string; begin S := ComboBox.Text; SendMessage(ComboBox.Handle, CB_RESETCONTENT, 0, 0); ComboBox.Text := S; ComboBox.Update; end; procedure TCustomComboBoxStrings.Delete(Index: Integer); begin SendMessage(ComboBox.Handle, CB_DELETESTRING, Index, 0); end; function TCustomComboBoxStrings.IndexOf(const S: string): Integer; begin Result := SendMessage(ComboBox.Handle, CB_FINDSTRINGEXACT, -1, LongInt(PChar(S))); end; procedure TCustomComboBoxStrings.SetUpdateState(Updating: Boolean); begin SendMessage(ComboBox.Handle, WM_SETREDRAW, Ord(not Updating), 0); if not Updating then ComboBox.Refresh; end; { TComboBoxStrings } function TComboBoxStrings.Add(const S: string): Integer; begin Result := SendMessage(ComboBox.Handle, CB_ADDSTRING, 0, Longint(PChar(S))); if Result < 0 then raise EOutOfResources.Create(SInsertLineError); end; procedure TComboBoxStrings.Insert(Index: Integer; const S: string); begin if SendMessage(ComboBox.Handle, CB_INSERTSTRING, Index, Longint(PChar(S))) < 0 then raise EOutOfResources.Create(SInsertLineError); end; { TCustomCombo } constructor TCustomCombo.Create(AOwner: TComponent); const ComboBoxStyle = [csCaptureMouse, csSetCaption, csDoubleClicks, csFixedHeight, csReflector]; begin inherited Create(AOwner); if NewStyleControls then ControlStyle := ComboBoxStyle else ControlStyle := ComboBoxStyle + [csFramed]; Width := 145; Height := 25; TabStop := True; ParentColor := False; FCanvas := TControlCanvas.Create; TControlCanvas(FCanvas).Control := Self; FItemHeight := 16; {$IFDEF MSWINDOWS} FEditInstance := Classes.MakeObjectInstance(EditWndProc); FListInstance := Classes.MakeObjectInstance(ListWndProc); {$ENDIF} {$IFDEF LINUX} FEditInstance := WinUtils.MakeObjectInstance(EditWndProc); FListInstance := WinUtils.MakeObjectInstance(ListWndProc); {$ENDIF} FDropDownCount := 8; FItemIndex := -1; FSaveIndex := -1; end; destructor TCustomCombo.Destroy; begin if HandleAllocated then DestroyWindowHandle; {$IFDEF MSWINDOWS} FreeObjectInstance(FListInstance); FreeObjectInstance(FEditInstance); {$ENDIF} {$IFDEF LINUX} WinUtils.FreeObjectInstance(FListInstance); WinUtils.FreeObjectInstance(FEditInstance); {$ENDIF} FCanvas.Free; inherited Destroy; end; procedure TCustomCombo.Clear; begin SetTextBuf(''); FItems.Clear; FSaveIndex := -1; end; procedure TCustomCombo.DestroyWindowHandle; begin inherited DestroyWindowHandle; { must be cleared after the main handle is destroyed as messages are sent to our internal WndProcs when the main handle is destroyed and we should not have NULL handles when we receive those messages. } FEditHandle := 0; FListHandle := 0; FDropHandle := 0; end; procedure TCustomCombo.SelectAll; begin SendMessage(Handle, CB_SETEDITSEL, 0, Integer($FFFF0000)); end; function TCustomCombo.GetDroppedDown: Boolean; begin Result := LongBool(SendMessage(Handle, CB_GETDROPPEDSTATE, 0, 0)); end; procedure TCustomCombo.SetDroppedDown(Value: Boolean); var R: TRect; begin SendMessage(Handle, CB_SHOWDROPDOWN, Longint(Value), 0); R := ClientRect; InvalidateRect(Handle, @R, True); end; function TCustomCombo.GetItemIndex: Integer; begin if csLoading in ComponentState then Result := FItemIndex else Result := SendMessage(Handle, CB_GETCURSEL, 0, 0); end; procedure TCustomCombo.SetItemIndex(const Value: Integer); begin if csLoading in ComponentState then FItemIndex := Value else if GetItemIndex <> Value then SendMessage(Handle, CB_SETCURSEL, Value, 0); end; function TCustomCombo.GetSelStart: Integer; begin SendMessage(Handle, CB_GETEDITSEL, Longint(@Result), 0); end; procedure TCustomCombo.SetSelStart(Value: Integer); var Selection: TSelection; begin Selection.StartPos := Value; Selection.EndPos := Value; SendMessage(Handle, CB_SETEDITSEL, 0, MakeLParam(Selection.StartPos, Selection.EndPos)); end; function TCustomCombo.GetSelLength: Integer; var Selection: TSelection; begin SendMessage(Handle, CB_GETEDITSEL, Longint(@Selection.StartPos), Longint(@Selection.EndPos)); Result := Selection.EndPos - Selection.StartPos; end; procedure TCustomCombo.SetSelLength(Value: Integer); var Selection: TSelection; begin SendMessage(Handle, CB_GETEDITSEL, Longint(@Selection.StartPos), Longint(@Selection.EndPos)); Selection.EndPos := Selection.StartPos + Value; SendMessage(Handle, CB_SETEDITSEL, 0, MakeLParam(Selection.StartPos, Selection.EndPos)); end; procedure TCustomCombo.SetMaxLength(Value: Integer); begin if Value < 0 then Value := 0; if FMaxLength <> Value then begin FMaxLength := Value; if HandleAllocated then SendMessage(Handle, CB_LIMITTEXT, Value, 0); end; end; procedure TCustomCombo.SetItemHeight(Value: Integer); begin if Value > 0 then begin FItemHeight := Value; RecreateWnd; end; end; procedure TCustomCombo.WMCreate(var Message: TWMCreate); begin inherited; if WindowText <> nil then SetWindowText(Handle, WindowText); end; procedure TCustomCombo.WMDrawItem(var Message: TWMDrawItem); begin DefaultHandler(Message); end; procedure TCustomCombo.WMMeasureItem(var Message: TWMMeasureItem); begin DefaultHandler(Message); end; procedure TCustomCombo.WMDeleteItem(var Message: TWMDeleteItem); begin DefaultHandler(Message); end; procedure TCustomCombo.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; if DroppedDown then Message.Result := Message.Result or DLGC_WANTALLKEYS; end; procedure TCustomCombo.CMCancelMode(var Message: TCMCancelMode); begin if Message.Sender <> Self then Perform(CB_SHOWDROPDOWN, 0, 0); end; procedure TCustomCombo.CMCtl3DChanged(var Message: TMessage); begin if NewStyleControls then RecreateWnd; inherited; end; procedure TCustomComboBox.CMParentColorChanged(var Message: TMessage); begin inherited; if not NewStyleControls and (Style < csDropDownList) then Invalidate; end; procedure TCustomCombo.EditWndProc(var Message: TMessage); var P: TPoint; Form: TCustomForm; begin if Message.Msg = WM_SYSCOMMAND then begin WndProc(Message); Exit; end else if (Message.Msg >= WM_KEYFIRST) and (Message.Msg <= WM_KEYLAST) then begin Form := GetParentForm(Self); if (Form <> nil) and Form.WantChildKey(Self, Message) then Exit; end; ComboWndProc(Message, FEditHandle, FDefEditProc); case Message.Msg of WM_LBUTTONDOWN, WM_LBUTTONDBLCLK: begin if DragMode = dmAutomatic then begin GetCursorPos(P); P := ScreenToClient(P); SendMessage(FEditHandle, WM_LBUTTONUP, 0,Longint(PointToSmallPoint(P))); BeginDrag(False); end; end; WM_SETFONT: if NewStyleControls then SendMessage(FEditHandle, EM_SETMARGINS, EC_LEFTMARGIN or EC_RIGHTMARGIN, 0); end; end; procedure TCustomCombo.ListWndProc(var Message: TMessage); begin ComboWndProc(Message, FListHandle, FDefListProc); end; procedure TCustomComboBox.SetCharCase(Value: TEditCharCase); begin if FCharCase <> Value then begin FCharCase := Value; RecreateWnd; end; end; procedure TCustomCombo.ComboWndProc(var Message: TMessage; ComboWnd: HWnd; ComboProc: Pointer); var Point: TPoint; Form: TCustomForm; begin try with Message do begin case Msg of WM_SETFOCUS: begin Form := GetParentForm(Self); if (Form <> nil) and not Form.SetFocusedControl(Self) then Exit; end; WM_KILLFOCUS: if csFocusing in ControlState then Exit; WM_KEYDOWN, WM_SYSKEYDOWN: if (ComboWnd <> FListHandle) and DoKeyDown(TWMKey(Message)) then Exit; WM_CHAR: begin if DoKeyPress(TWMKey(Message)) then Exit; if ((TWMKey(Message).CharCode = VK_RETURN) or (TWMKey(Message).CharCode = VK_ESCAPE)) and DroppedDown then begin DroppedDown := False; Exit; end; end; WM_KEYUP, WM_SYSKEYUP: if DoKeyUp(TWMKey(Message)) then Exit; WM_MOUSEMOVE: Application.HintMouseMessage(Self, Message); WM_RBUTTONUP: if HasPopup(Self) then begin with TWMRButtonUp(Message) do begin Point.X := Pos.X; Point.Y := Pos.Y; MapWindowPoints(ComboWnd, Handle, Point, 1); Pos.X := Point.X; Pos.Y := Point.Y; end; WndProc(Message); Exit; end; WM_GETDLGCODE: if DroppedDown then begin Result := DLGC_WANTALLKEYS; Exit; end; WM_NCHITTEST: if csDesigning in ComponentState then begin Result := HTTRANSPARENT; Exit; end; CN_KEYDOWN, CN_CHAR, CN_SYSKEYDOWN, CN_SYSCHAR: begin WndProc(Message); Exit; end; end; Result := CallWindowProc(ComboProc, ComboWnd, Msg, WParam, LParam); if (Msg = WM_LBUTTONDBLCLK) and (csDoubleClicks in ControlStyle) then DblClick; end; except Application.HandleException(Self); end; end; procedure TCustomCombo.WndProc(var Message: TMessage); begin {for auto drag mode, let listbox handle itself, instead of TControl} if not (csDesigning in ComponentState) and ((Message.Msg = WM_LBUTTONDOWN) or (Message.Msg = WM_LBUTTONDBLCLK)) and not Dragging then begin if DragMode = dmAutomatic then begin if IsControlMouseMsg(TWMMouse(Message)) then Exit; ControlState := ControlState + [csLButtonDown]; Dispatch(Message); {overrides TControl's BeginDrag} Exit; end; end; with Message do case Msg of WM_SIZE: { Prevent TWinControl from handling WM_SIZE when adjusting drop-down listbox size. } if FDroppingDown then begin DefaultHandler(Message); Exit; end; WM_CTLCOLORMSGBOX..WM_CTLCOLORSTATIC: begin SetTextColor(WParam, ColorToRGB(Font.Color)); SetBkColor(WParam, ColorToRGB(Brush.Color)); Result := Brush.Handle; Exit; end; WM_CHAR: begin if DoKeyPress(TWMKey(Message)) then Exit; if ((TWMKey(Message).CharCode = VK_RETURN) or (TWMKey(Message).CharCode = VK_ESCAPE)) and DroppedDown then begin DroppedDown := False; Exit; end; end; end; inherited WndProc(Message); end; procedure TCustomCombo.CNCommand(var Message: TWMCommand); begin case Message.NotifyCode of CBN_DBLCLK: DblClick; CBN_EDITCHANGE: Change; CBN_DROPDOWN: begin FFocusChanged := False; DropDown; AdjustDropDown; if FFocusChanged then begin PostMessage(Handle, WM_CANCELMODE, 0, 0); if not FIsFocused then PostMessage(Handle, CB_SHOWDROPDOWN, 0, 0); end; end; CBN_SELCHANGE: begin Text := Items[ItemIndex]; Click; Select; end; CBN_CLOSEUP: CloseUp; CBN_SETFOCUS: begin FIsFocused := True; FFocusChanged := True; SetIme; end; CBN_KILLFOCUS: begin FIsFocused := False; FFocusChanged := True; ResetIme; end; end; end; procedure TCustomCombo.Change; begin inherited Changed; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomComboBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); begin TControlCanvas(FCanvas).UpdateTextFlags; if Assigned(FOnDrawItem) then FOnDrawItem(Self, Index, Rect, State) else begin FCanvas.FillRect(Rect); if Index >= 0 then FCanvas.TextOut(Rect.Left + 2, Rect.Top, Items[Index]); end; end; procedure TCustomCombo.DropDown; begin if Assigned(FOnDropDown) then FOnDropDown(Self); end; procedure TCustomCombo.Loaded; begin inherited Loaded; if FItemIndex <> -1 then SetItemIndex(FItemIndex); end; function TCustomCombo.Focused: Boolean; var FocusedWnd: HWND; begin Result := False; if HandleAllocated then begin FocusedWnd := GetFocus; Result := (FocusedWnd = FEditHandle) or (FocusedWnd = FListHandle); end; end; procedure TCustomCombo.CloseUp; begin if Assigned(FOnCloseUp) then FOnCloseUp(Self); end; procedure TCustomCombo.Select; begin if Assigned(FOnSelect) then FOnSelect(Self) else Change; end; procedure TCustomCombo.CreateWnd; begin inherited CreateWnd; SendMessage(Handle, CB_LIMITTEXT, FMaxLength, 0); FEditHandle := 0; FListHandle := 0; end; procedure TCustomCombo.AdjustDropDown; var Count: Integer; begin Count := ItemCount; if Count > DropDownCount then Count := DropDownCount; if Count < 1 then Count := 1; FDroppingDown := True; try SetWindowPos(FDropHandle, 0, 0, 0, Width, ItemHeight * Count + Height + 2, SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_NOREDRAW or SWP_HIDEWINDOW); finally FDroppingDown := False; end; SetWindowPos(FDropHandle, 0, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_NOREDRAW or SWP_SHOWWINDOW); end; procedure TCustomCombo.SetItems(const Value: TStrings); begin if Assigned(FItems) then FItems.Assign(Value) else FItems := Value; end; procedure TCustomCombo.ClearSelection; begin ItemIndex := -1; end; procedure TCustomCombo.CopySelection(Destination: TCustomListControl); begin if ItemIndex <> -1 then Destination.AddItem(Items[ItemIndex], Items.Objects[ItemIndex]); end; procedure TCustomCombo.DeleteSelected; begin if ItemIndex <> -1 then Items.Delete(ItemIndex); end; function TCustomCombo.GetCount: Integer; begin Result := GetItemCount; end; procedure TCustomCombo.SetDropDownCount(const Value: Integer); begin FDropDownCount := Value; end; procedure TCustomCombo.AddItem(Item: String; AObject: TObject); begin Items.AddObject(Item, AObject); end; { TCustomComboBox } constructor TCustomComboBox.Create(AOwner: TComponent); begin inherited Create(AOwner); FItems := GetItemsClass.Create; TCustomComboBoxStrings(FItems).ComboBox := Self; FItemHeight := 16; FStyle := csDropDown; FLastTime := 0; FAutoComplete := True; FAutoCloseUp := False; end; destructor TCustomComboBox.Destroy; begin FItems.Free; FSaveItems.Free; inherited Destroy; end; function TCustomComboBox.GetSelText: string; begin Result := ''; if FStyle < csDropDownList then Result := Copy(Text, GetSelStart + 1, GetSelLength); end; procedure TCustomComboBox.SetSorted(Value: Boolean); begin if FSorted <> Value then begin FSorted := Value; RecreateWnd; end; end; procedure TCustomComboBox.SetSelText(const Value: string); begin if FStyle < csDropDownList then begin HandleNeeded; SendMessage(FEditHandle, EM_REPLACESEL, 0, Longint(PChar(Value))); end; end; procedure TCustomComboBox.SetStyle(Value: TComboBoxStyle); begin if FStyle <> Value then begin FStyle := Value; if Value = csSimple then ControlStyle := ControlStyle - [csFixedHeight] else ControlStyle := ControlStyle + [csFixedHeight]; RecreateWnd; end; end; function TCustomComboBox.GetItemHt: Integer; begin if FStyle in [csOwnerDrawFixed, csOwnerDrawVariable] then Result := FItemHeight else Result := Perform(CB_GETITEMHEIGHT, 0, 0); end; procedure TCustomComboBox.CreateParams(var Params: TCreateParams); const ComboBoxStyles: array[TComboBoxStyle] of DWORD = ( CBS_DROPDOWN, CBS_SIMPLE, CBS_DROPDOWNLIST, CBS_DROPDOWNLIST or CBS_OWNERDRAWFIXED, CBS_DROPDOWNLIST or CBS_OWNERDRAWVARIABLE); CharCases: array[TEditCharCase] of DWORD = (0, CBS_UPPERCASE, CBS_LOWERCASE); Sorts: array[Boolean] of DWORD = (0, CBS_SORT); begin inherited CreateParams(Params); CreateSubClass(Params, 'COMBOBOX'); with Params do Style := Style or (WS_VSCROLL or CBS_HASSTRINGS or CBS_AUTOHSCROLL) or ComboBoxStyles[FStyle] or Sorts[FSorted] or CharCases[FCharCase]; end; procedure TCustomComboBox.CreateWnd; var ChildHandle: THandle; begin inherited CreateWnd; FDropHandle := Handle; if FSaveItems <> nil then begin FItems.Assign(FSaveItems); FSaveItems.Free; FSaveItems := nil; if FSaveIndex <> -1 then begin if FItems.Count < FSaveIndex then FSaveIndex := Items.Count; SendMessage(Handle, CB_SETCURSEL, FSaveIndex, 0); end; end; if FStyle in [csDropDown, csSimple] then begin ChildHandle := GetWindow(Handle, GW_CHILD); if ChildHandle <> 0 then begin if FStyle = csSimple then begin FListHandle := ChildHandle; FDefListProc := Pointer(GetWindowLong(FListHandle, GWL_WNDPROC)); SetWindowLong(FListHandle, GWL_WNDPROC, Longint(FListInstance)); ChildHandle := GetWindow(ChildHandle, GW_HWNDNEXT); end; FEditHandle := ChildHandle; FDefEditProc := Pointer(GetWindowLong(FEditHandle, GWL_WNDPROC)); SetWindowLong(FEditHandle, GWL_WNDPROC, Longint(FEditInstance)); end; end; if NewStyleControls and (FEditHandle <> 0) then SendMessage(FEditHandle, EM_SETMARGINS, EC_LEFTMARGIN or EC_RIGHTMARGIN, 0); end; procedure TCustomComboBox.DestroyWnd; begin if FItems.Count > 0 then begin FSaveIndex := ItemIndex; FSaveItems := TStringList.Create; FSaveItems.Assign(FItems); end; inherited DestroyWnd; end; procedure TCustomComboBox.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin if Style = csSimple then begin FillRect(Message.DC, ClientRect, Parent.Brush.Handle); Message.Result := 1; end else DefaultHandler(Message); end; procedure TCustomComboBox.KeyPress(var Key: Char); function HasSelectedText(var StartPos, EndPos: DWORD): Boolean; begin SendMessage(Handle, CB_GETEDITSEL, Integer(@StartPos), Integer(@EndPos)); Result := EndPos > StartPos; end; procedure DeleteSelectedText; var StartPos, EndPos: DWORD; OldText: String; begin OldText := Text; SendMessage(Handle, CB_GETEDITSEL, Integer(@StartPos), Integer(@EndPos)); Delete(OldText, StartPos + 1, EndPos - StartPos); SendMessage(Handle, CB_SETCURSEL, -1, 0); Text := OldText; SendMessage(Handle, CB_SETEDITSEL, 0, MakeLParam(StartPos, StartPos)); end; var StartPos: DWORD; EndPos: DWORD; OldText: String; SaveText: String; Msg : TMSG; LastByte: Integer; begin inherited KeyPress(Key); if not AutoComplete then exit; if Style in [csDropDown, csSimple] then FFilter := Text else begin if GetTickCount - FLastTime >= 500 then FFilter := ''; FLastTime := GetTickCount; end; case Ord(Key) of VK_ESCAPE: exit; VK_TAB: if FAutoDropDown and DroppedDown then DroppedDown := False; VK_BACK: begin if HasSelectedText(StartPos, EndPos) then DeleteSelectedText else if (Style in [csDropDown, csSimple]) and (Length(Text) > 0) then begin SaveText := Text; LastByte := StartPos; while ByteType(SaveText, LastByte) = mbTrailByte do Dec(LastByte); OldText := Copy(SaveText, 1, LastByte - 1); SendMessage(Handle, CB_SETCURSEL, -1, 0); Text := OldText + Copy(SaveText, EndPos + 1, MaxInt); SendMessage(Handle, CB_SETEDITSEL, 0, MakeLParam(LastByte - 1, LastByte - 1)); FFilter := Text; end else begin while ByteType(FFilter, Length(FFilter)) = mbTrailByte do Delete(FFilter, Length(FFilter), 1); Delete(FFilter, Length(FFilter), 1); end; Key := #0; Change; end; else // case if FAutoDropDown and not DroppedDown then DroppedDown := True; if HasSelectedText(StartPos, EndPos) then SaveText := Copy(FFilter, 1, StartPos) + Key else SaveText := FFilter + Key; if Key in LeadBytes then begin if PeekMessage(Msg, Handle, 0, 0, PM_NOREMOVE) and (Msg.Message = WM_CHAR) then begin if SelectItem(SaveText + Char(Msg.wParam)) then begin PeekMessage(Msg, Handle, 0, 0, PM_REMOVE); Key := #0 end; end; end else if SelectItem(SaveText) then Key := #0 end; // case end; function TCustomComboBox.SelectItem(const AnItem: String): Boolean; var Idx: Integer; ValueChange: Boolean; begin if Length(AnItem) = 0 then begin Result := False; ItemIndex := -1; Change; exit; end; Idx := SendMessage(Handle, CB_FINDSTRING, -1, LongInt(PChar(AnItem))); Result := (Idx <> CB_ERR); if not Result then exit; ValueChange := Idx <> ItemIndex; if AutoCloseUp and (Items.IndexOf(AnItem) <> -1) then SendMessage(Handle, CB_SHOWDROPDOWN, 0, 0); SendMessage(Handle, CB_SETCURSEL, Idx, 0); if (Style in [csDropDown, csSimple]) then begin Text := AnItem + Copy(Items[Idx], Length(AnItem) + 1, MaxInt); SendMessage(Handle, CB_SETEDITSEL, 0, MakeLParam(Length(AnItem), Length(Text))); end else begin ItemIndex := Idx; FFilter := AnItem; end; if ValueChange then begin Click; Select; end; end; procedure TCustomComboBox.MeasureItem(Index: Integer; var Height: Integer); begin if Assigned(FOnMeasureItem) then FOnMeasureItem(Self, Index, Height) end; procedure TCustomComboBox.CNDrawItem(var Message: TWMDrawItem); var State: TOwnerDrawState; begin with Message.DrawItemStruct^ do begin State := TOwnerDrawState(LongRec(itemState).Lo); if itemState and ODS_COMBOBOXEDIT <> 0 then Include(State, odComboBoxEdit); if itemState and ODS_DEFAULT <> 0 then Include(State, odDefault); FCanvas.Handle := hDC; FCanvas.Font := Font; FCanvas.Brush := Brush; if (Integer(itemID) >= 0) and (odSelected in State) then begin FCanvas.Brush.Color := clHighlight; FCanvas.Font.Color := clHighlightText end; if Integer(itemID) >= 0 then DrawItem(itemID, rcItem, State) else FCanvas.FillRect(rcItem); if odFocused in State then DrawFocusRect(hDC, rcItem); FCanvas.Handle := 0; end; end; procedure TCustomComboBox.CNMeasureItem(var Message: TWMMeasureItem); begin with Message.MeasureItemStruct^ do begin itemHeight := FItemHeight; if FStyle = csOwnerDrawVariable then MeasureItem(itemID, Integer(itemHeight)); end; end; procedure TCustomComboBox.WMLButtonDown(var Message: TWMLButtonDown); var Form: TCustomForm; begin if (DragMode = dmAutomatic) and (Style = csDropDownList) and (Message.XPos < (Width - GetSystemMetrics(SM_CXHSCROLL))) then begin SetFocus; BeginDrag(False); Exit; end; inherited; if MouseCapture then begin Form := GetParentForm(Self); if (Form <> nil) and (Form.ActiveControl <> Self) then MouseCapture := False; end; end; procedure TCustomComboBox.WndProc(var Message: TMessage); begin with Message do case Msg of CN_CTLCOLORMSGBOX..CN_CTLCOLORSTATIC: if not NewStyleControls and (Style < csDropDownList) then begin Result := Parent.Brush.Handle; Exit; end; end; inherited WndProc(Message); end; function TCustomComboBox.GetItemCount: Integer; begin Result := FItems.Count; end; function TCustomComboBox.GetItemsClass: TCustomComboBoxStringsClass; begin Result := TComboBoxStrings; end; procedure TCustomComboBox.WMPaint(var Message: TWMPaint); const InnerStyles: array[TBevelCut] of Integer = (0, BDR_SUNKENINNER, BDR_RAISEDINNER, 0); OuterStyles: array[TBevelCut] of Integer = (0, BDR_SUNKENOUTER, BDR_RAISEDOUTER, 0); EdgeStyles: array[TBevelKind] of Integer = (0, 0, BF_SOFT, BF_FLAT); Ctl3DStyles: array[Boolean] of Integer = (BF_MONO, 0); var EdgeSize: Integer; WinStyle: Longint; C: TControlCanvas; R: TRect; begin inherited; if BevelKind = bkNone then Exit; C := TControlCanvas.Create; try C.Control:=Self; with C do begin R := ClientRect; C.Brush.Color := Color; FrameRect(R); InflateRect(R,-1,-1); FrameRect(R); if BevelKind <> bkNone then begin EdgeSize := 0; if BevelInner <> bvNone then Inc(EdgeSize, BevelWidth); if BevelOuter <> bvNone then Inc(EdgeSize, BevelWidth); if EdgeSize = 0 then begin R := ClientRect; C.Brush.Color := Color; FrameRect(R); InflateRect(R,-1,-1); FrameRect(R); end; R := ClientRect; with BoundsRect do begin WinStyle := GetWindowLong(Handle, GWL_STYLE); if beLeft in BevelEdges then Dec(Left, EdgeSize); if beTop in BevelEdges then Dec(Top, EdgeSize); if beRight in BevelEdges then Inc(Right, EdgeSize); if (WinStyle and WS_VSCROLL) <> 0 then Inc(Right, GetSystemMetrics(SM_CYVSCROLL)); if beBottom in BevelEdges then Inc(Bottom, EdgeSize); if (WinStyle and WS_HSCROLL) <> 0 then Inc(Bottom, GetSystemMetrics(SM_CXHSCROLL)); end; DrawEdge(C.Handle, R, InnerStyles[BevelInner] or OuterStyles[BevelOuter], Byte(BevelEdges) or EdgeStyles[BevelKind] or Ctl3DStyles[Ctl3D] or BF_ADJUST); R.Left := R.Right - GetSystemMetrics(SM_CXHTHUMB) - 1; if DroppedDown then DrawFrameControl(C.Handle, R, DFC_SCROLL, DFCS_FLAT or DFCS_SCROLLCOMBOBOX) else DrawFrameControl(C.Handle, R, DFC_SCROLL, DFCS_FLAT or DFCS_SCROLLCOMBOBOX); end; end; finally C.Free; end; end; procedure TCustomComboBox.WMNCCalcSize(var Message: TWMNCCalcSize); begin end; { TButtonActionLink } procedure TButtonActionLink.AssignClient(AClient: TObject); begin inherited AssignClient(AClient); FClient := AClient as TButtonControl; end; function TButtonActionLink.IsCheckedLinked: Boolean; begin Result := inherited IsCheckedLinked and (FClient.Checked = (Action as TCustomAction).Checked); end; procedure TButtonActionLink.SetChecked(Value: Boolean); begin if IsCheckedLinked then begin FClient.ClicksDisabled := True; try FClient.Checked := Value; finally FClient.ClicksDisabled := False; end; end; end; { TButtonControl } constructor TButtonControl.Create(AOwner: TComponent); begin inherited Create(AOwner); if SysLocale.FarEast and (Win32Platform = VER_PLATFORM_WIN32_NT) then ImeMode := imDisable; end; procedure TButtonControl.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin inherited ActionChange(Sender, CheckDefaults); if Sender is TCustomAction then with TCustomAction(Sender) do begin if not CheckDefaults or (Self.Checked = False) then Self.Checked := Checked; end; end; function TButtonControl.GetActionLinkClass: TControlActionLinkClass; begin Result := TButtonActionLink; end; function TButtonControl.GetChecked: Boolean; begin Result := False; end; function TButtonControl.IsCheckedStored: Boolean; begin Result := (ActionLink = nil) or not TButtonActionLink(ActionLink).IsCheckedLinked; end; procedure TButtonControl.SetChecked(Value: Boolean); begin end; procedure TButtonControl.WndProc(var Message: TMessage); begin case Message.Msg of WM_LBUTTONDOWN, WM_LBUTTONDBLCLK: if not (csDesigning in ComponentState) and not Focused then begin FClicksDisabled := True; Windows.SetFocus(Handle); FClicksDisabled := False; if not Focused then Exit; end; CN_COMMAND: if FClicksDisabled then Exit; end; inherited WndProc(Message); end; procedure TButtonControl.CNCtlColorStatic(var Message: TWMCtlColorStatic); begin with ThemeServices do if ThemesEnabled then begin DrawParentBackground(Handle, Message.ChildDC, nil, False); { Return an empty brush to prevent Windows from overpainting we just have created. } Message.Result := GetStockObject(NULL_BRUSH); end else inherited; end; procedure TButtonControl.WMEraseBkGnd(var Message: TWMEraseBkGnd); begin { Under theme services the background is drawn in CN_CTLCOLORSTATIC. } if ThemeServices.ThemesEnabled then Message.Result := 1 else inherited; end; procedure TButtonControl.CreateParams(var Params: TCreateParams); begin inherited; if FWordWrap then Params.Style := Params.Style or BS_MULTILINE; end; procedure TButtonControl.SetWordWrap(const Value: Boolean); begin if FWordWrap <> Value then begin FWordWrap := Value; RecreateWnd; end; end; { TButton } constructor TButton.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csSetCaption, csDoubleClicks]; Width := 75; Height := 25; TabStop := True; end; procedure TButton.Click; var Form: TCustomForm; begin Form := GetParentForm(Self); if Form <> nil then Form.ModalResult := ModalResult; inherited Click; end; function TButton.UseRightToLeftAlignment: Boolean; begin Result := False; end; procedure TButton.SetButtonStyle(ADefault: Boolean); const BS_MASK = $000F; var Style: Word; begin if HandleAllocated then begin if ADefault then Style := BS_DEFPUSHBUTTON else Style := BS_PUSHBUTTON; if GetWindowLong(Handle, GWL_STYLE) and BS_MASK <> Style then SendMessage(Handle, BM_SETSTYLE, Style, 1); end; end; procedure TButton.SetDefault(Value: Boolean); var Form: TCustomForm; begin FDefault := Value; if HandleAllocated then begin Form := GetParentForm(Self); if Form <> nil then Form.Perform(CM_FOCUSCHANGED, 0, Longint(Form.ActiveControl)); end; end; procedure TButton.CreateParams(var Params: TCreateParams); const ButtonStyles: array[Boolean] of DWORD = (BS_PUSHBUTTON, BS_DEFPUSHBUTTON); begin inherited CreateParams(Params); CreateSubClass(Params, 'BUTTON'); Params.Style := Params.Style or ButtonStyles[FDefault]; end; procedure TButton.CreateWnd; begin inherited CreateWnd; FActive := FDefault; end; procedure TButton.CNCommand(var Message: TWMCommand); begin if Message.NotifyCode = BN_CLICKED then Click; end; procedure TButton.CMDialogKey(var Message: TCMDialogKey); begin with Message do if (((CharCode = VK_RETURN) and FActive) or ((CharCode = VK_ESCAPE) and FCancel)) and (KeyDataToShiftState(Message.KeyData) = []) and CanFocus then begin Click; Result := 1; end else inherited; end; procedure TButton.CMDialogChar(var Message: TCMDialogChar); begin with Message do if IsAccel(CharCode, Caption) and CanFocus then begin Click; Result := 1; end else inherited; end; procedure TButton.CMFocusChanged(var Message: TCMFocusChanged); begin with Message do if Sender is TButton then FActive := Sender = Self else FActive := FDefault; SetButtonStyle(FActive); inherited; end; procedure TButton.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin if ThemeServices.ThemesEnabled then Message.Result := 1 else DefaultHandler(Message); end; procedure TButton.CNCtlColorBtn(var Message: TWMCtlColorBtn); begin with ThemeServices do if ThemesEnabled then begin DrawParentBackground(Handle, Message.ChildDC, nil, False); { Return an empty brush to prevent Windows from overpainting we just have created. } Message.Result := GetStockObject(NULL_BRUSH); end else inherited; end; { TCustomCheckBox } constructor TCustomCheckBox.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 97; Height := 17; TabStop := True; ControlStyle := [csSetCaption, csDoubleClicks]; FAlignment := taRightJustify; end; function TCustomCheckBox.GetControlsAlignment: TAlignment; begin if not UseRightToLeftAlignment then Result := taRightJustify else if FAlignment = taRightJustify then Result := taLeftJustify else Result := taRightJustify; end; procedure TCustomCheckBox.Toggle; begin case State of cbUnchecked: if AllowGrayed then State := cbGrayed else State := cbChecked; cbChecked: State := cbUnchecked; cbGrayed: State := cbChecked; end; end; procedure TCustomCheckBox.Click; begin inherited Changed; inherited Click; end; function TCustomCheckBox.GetChecked: Boolean; begin Result := State = cbChecked; end; procedure TCustomCheckBox.SetAlignment(Value: TLeftRight); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; procedure TCustomCheckBox.SetChecked(Value: Boolean); begin if Value then State := cbChecked else State := cbUnchecked; end; procedure TCustomCheckBox.SetState(Value: TCheckBoxState); begin if FState <> Value then begin FState := Value; if HandleAllocated then SendMessage(Handle, BM_SETCHECK, Integer(FState), 0); if not ClicksDisabled then Click; end; end; procedure TCustomCheckBox.CreateParams(var Params: TCreateParams); const Alignments: array[Boolean, TLeftRight] of DWORD = ((BS_LEFTTEXT, 0), (0, BS_LEFTTEXT)); begin inherited CreateParams(Params); CreateSubClass(Params, 'BUTTON'); with Params do begin Style := Style or BS_3STATE or Alignments[UseRightToLeftAlignment, FAlignment]; WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW); end; end; procedure TCustomCheckBox.CreateWnd; begin inherited CreateWnd; SendMessage(Handle, BM_SETCHECK, Integer(FState), 0); end; procedure TCustomCheckBox.WMSize(var Message: TMessage); begin inherited; Invalidate; end; procedure TCustomCheckBox.CMCtl3DChanged(var Message: TMessage); begin RecreateWnd; end; procedure TCustomCheckBox.CMDialogChar(var Message: TCMDialogChar); begin with Message do if IsAccel(CharCode, Caption) and CanFocus then begin SetFocus; if Focused then Toggle; Result := 1; end else inherited; end; procedure TCustomCheckBox.CNCommand(var Message: TWMCommand); begin if Message.NotifyCode = BN_CLICKED then Toggle; end; { TRadioButton } constructor TRadioButton.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 113; Height := 17; ControlStyle := [csSetCaption, csDoubleClicks]; FAlignment := taRightJustify; end; function TRadioButton.GetChecked: Boolean; begin Result := FChecked; end; function TRadioButton.GetControlsAlignment: TAlignment; begin if not UseRightToLeftAlignment then Result := taRightJustify else if FAlignment = taRightJustify then Result := taLeftJustify else Result := taRightJustify; end; procedure TRadioButton.SetAlignment(Value: TLeftRight); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; procedure TRadioButton.SetChecked(Value: Boolean); procedure TurnSiblingsOff; var I: Integer; Sibling: TControl; begin if Parent <> nil then with Parent do for I := 0 to ControlCount - 1 do begin Sibling := Controls[I]; if (Sibling <> Self) and (Sibling is TRadioButton) then with TRadioButton(Sibling) do begin if Assigned(Action) and (Action is TCustomAction) and TCustomAction(Action).AutoCheck then TCustomAction(Action).Checked := False; SetChecked(False); end; end; end; begin if FChecked <> Value then begin FChecked := Value; TabStop := Value; if HandleAllocated then SendMessage(Handle, BM_SETCHECK, Integer(Checked), 0); if Value then begin TurnSiblingsOff; inherited Changed; if not ClicksDisabled then Click; end; end; end; procedure TRadioButton.CreateParams(var Params: TCreateParams); const Alignments: array[Boolean, TLeftRight] of DWORD = ((BS_LEFTTEXT, 0), (0, BS_LEFTTEXT)); begin inherited CreateParams(Params); CreateSubClass(Params, 'BUTTON'); with Params do Style := Style or BS_RADIOBUTTON or Alignments[UseRightToLeftAlignment, FAlignment]; end; procedure TRadioButton.CreateWnd; begin inherited CreateWnd; SendMessage(Handle, BM_SETCHECK, Integer(FChecked), 0); end; procedure TRadioButton.CMCtl3DChanged(var Message: TMessage); begin RecreateWnd; end; procedure TRadioButton.CMDialogChar(var Message: TCMDialogChar); begin with Message do if IsAccel(Message.CharCode, Caption) and CanFocus then begin SetFocus; Result := 1; end else inherited; end; procedure TRadioButton.CNCommand(var Message: TWMCommand); begin case Message.NotifyCode of BN_CLICKED: SetChecked(True); BN_DOUBLECLICKED: DblClick; end; end; { TListBoxStrings } function TListBoxStrings.GetCount: Integer; begin Result := SendMessage(ListBox.Handle, LB_GETCOUNT, 0, 0); end; function TListBoxStrings.Get(Index: Integer): string; var Len: Integer; begin if ListBox.Style in [lbVirtual, lbVirtualOwnerDraw] then Result := ListBox.DoGetData(Index) else begin Len := SendMessage(ListBox.Handle, LB_GETTEXTLEN, Index, 0); if Len = LB_ERR then Error(SListIndexError, Index); SetLength(Result, Len); if Len <> 0 then begin Len := SendMessage(ListBox.Handle, LB_GETTEXT, Index, Longint(PChar(Result))); SetLength(Result, Len); // LB_GETTEXTLEN isn't guaranteed to be accurate end; end; end; function TListBoxStrings.GetObject(Index: Integer): TObject; begin if ListBox.Style in [lbVirtual, lbVirtualOwnerDraw] then Result := ListBox.DoGetDataObject(Index) else begin Result := TObject(ListBox.GetItemData(Index)); if Longint(Result) = LB_ERR then Error(SListIndexError, Index); end; end; procedure TListBoxStrings.Put(Index: Integer; const S: string); var I: Integer; TempData: Longint; begin I := ListBox.ItemIndex; TempData := ListBox.InternalGetItemData(Index); // Set the Item to 0 in case it is an object that gets freed during Delete ListBox.InternalSetItemData(Index, 0); Delete(Index); InsertObject(Index, S, nil); ListBox.InternalSetItemData(Index, TempData); ListBox.ItemIndex := I; end; procedure TListBoxStrings.PutObject(Index: Integer; AObject: TObject); begin if (Index <> -1) and not (ListBox.Style in [lbVirtual, lbVirtualOwnerDraw]) then ListBox.SetItemData(Index, LongInt(AObject)); end; function TListBoxStrings.Add(const S: string): Integer; begin Result := -1; if ListBox.Style in [lbVirtual, lbVirtualOwnerDraw] then exit; Result := SendMessage(ListBox.Handle, LB_ADDSTRING, 0, Longint(PChar(S))); if Result < 0 then raise EOutOfResources.Create(SInsertLineError); end; procedure TListBoxStrings.Insert(Index: Integer; const S: string); begin if ListBox.Style in [lbVirtual, lbVirtualOwnerDraw] then exit; if SendMessage(ListBox.Handle, LB_INSERTSTRING, Index, Longint(PChar(S))) < 0 then raise EOutOfResources.Create(SInsertLineError); end; procedure TListBoxStrings.Delete(Index: Integer); begin ListBox.DeleteString(Index); end; procedure TListBoxStrings.Exchange(Index1, Index2: Integer); var TempData: Longint; TempString: string; begin if ListBox.Style in [lbVirtual, lbVirtualOwnerDraw] then exit; BeginUpdate; try TempString := Strings[Index1]; TempData := ListBox.InternalGetItemData(Index1); Strings[Index1] := Strings[Index2]; ListBox.InternalSetItemData(Index1, ListBox.InternalGetItemData(Index2)); Strings[Index2] := TempString; ListBox.InternalSetItemData(Index2, TempData); if ListBox.ItemIndex = Index1 then ListBox.ItemIndex := Index2 else if ListBox.ItemIndex = Index2 then ListBox.ItemIndex := Index1; finally EndUpdate; end; end; procedure TListBoxStrings.Clear; begin ListBox.ResetContent; end; procedure TListBoxStrings.SetUpdateState(Updating: Boolean); begin SendMessage(ListBox.Handle, WM_SETREDRAW, Ord(not Updating), 0); if not Updating then ListBox.Refresh; end; function TListBoxStrings.IndexOf(const S: string): Integer; begin if ListBox.Style in [lbVirtual, lbVirtualOwnerDraw] then Result := ListBox.DoFindData(S) else Result := SendMessage(ListBox.Handle, LB_FINDSTRINGEXACT, -1, LongInt(PChar(S))); end; procedure TListBoxStrings.Move(CurIndex, NewIndex: Integer); var TempData: Longint; TempString: string; begin if ListBox.Style in [lbVirtual, lbVirtualOwnerDraw] then exit; BeginUpdate; ListBox.FMoving := True; try if CurIndex <> NewIndex then begin TempString := Get(CurIndex); TempData := ListBox.InternalGetItemData(CurIndex); ListBox.InternalSetItemData(CurIndex, 0); Delete(CurIndex); Insert(NewIndex, TempString); ListBox.InternalSetItemData(NewIndex, TempData); end; finally ListBox.FMoving := False; EndUpdate; end; end; { TCustomListBox } constructor TCustomListBox.Create(AOwner: TComponent); const ListBoxStyle = [csSetCaption, csDoubleClicks, csOpaque]; begin inherited Create(AOwner); if NewStyleControls then ControlStyle := ListBoxStyle else ControlStyle := ListBoxStyle + [csFramed]; Width := 121; Height := 97; TabStop := True; ParentColor := False; FAutoComplete := True; FItems := TListBoxStrings.Create; TListBoxStrings(FItems).ListBox := Self; FCanvas := TControlCanvas.Create; TControlCanvas(FCanvas).Control := Self; FItemHeight := 16; FBorderStyle := bsSingle; FExtendedSelect := True; FOldCount := -1; end; destructor TCustomListBox.Destroy; begin inherited Destroy; FCanvas.Free; FItems.Free; FSaveItems.Free; end; procedure TCustomListBox.AddItem(Item: String; AObject: TObject); var S: String; begin SetString(S, PChar(Item), StrLen(PChar(Item))); Items.AddObject(S, AObject); end; function TCustomListBox.GetItemData(Index: Integer): LongInt; begin Result := SendMessage(Handle, LB_GETITEMDATA, Index, 0); end; procedure TCustomListBox.SetItemData(Index: Integer; AData: LongInt); begin SendMessage(Handle, LB_SETITEMDATA, Index, AData); end; function TCustomListBox.InternalGetItemData(Index: Integer): LongInt; begin Result := GetItemData(Index); end; procedure TCustomListBox.InternalSetItemData(Index: Integer; AData: LongInt); begin SetItemData(Index, AData); end; procedure TCustomListBox.DeleteString( Index: Integer ); begin SendMessage(Handle, LB_DELETESTRING, Index, 0); end; procedure TCustomListBox.ResetContent; begin if Style in [lbVirtual, lbVirtualOwnerDraw] then exit; SendMessage(Handle, LB_RESETCONTENT, 0, 0); end; procedure TCustomListBox.Clear; begin FItems.Clear; end; procedure TCustomListBox.ClearSelection; var I: Integer; begin if MultiSelect then for I := 0 to Items.Count - 1 do Selected[I] := False else ItemIndex := -1; end; procedure TCustomListBox.CopySelection(Destination: TCustomListControl); var I: Integer; begin if MultiSelect then begin for I := 0 to Items.Count - 1 do if Selected[I] then Destination.AddItem(PChar(Items[I]), Items.Objects[I]); end else if ItemIndex <> -1 then Destination.AddItem(PChar(Items[ItemIndex]), Items.Objects[ItemIndex]); end; procedure TCustomListBox.DeleteSelected; var I: Integer; begin if MultiSelect then begin for I := Items.Count - 1 downto 0 do if Selected[I] then Items.Delete(I); end else if ItemIndex <> -1 then Items.Delete(ItemIndex); end; procedure TCustomListBox.SetColumnWidth; var ColWidth: Integer; begin if (FColumns > 0) and (Width > 0) then begin ColWidth := Trunc(ClientWidth / FColumns); if ColWidth < 1 then ColWidth := 1; SendMessage(Handle, LB_SETCOLUMNWIDTH, ColWidth, 0); end; end; procedure TCustomListBox.SetColumns(Value: Integer); begin if FColumns <> Value then if (FColumns = 0) or (Value = 0) then begin FColumns := Value; RecreateWnd; end else begin FColumns := Value; if HandleAllocated then SetColumnWidth; end; end; function TCustomListBox.GetItemIndex: Integer; begin if MultiSelect then Result := SendMessage(Handle, LB_GETCARETINDEX, 0, 0) else Result := SendMessage(Handle, LB_GETCURSEL, 0, 0); end; function TCustomListBox.GetCount: Integer; begin if Style in [lbVirtual, lbVirtualOwnerDraw] then Result := FCount else Result := Items.Count; end; function TCustomListBox.GetSelCount: Integer; begin Result := SendMessage(Handle, LB_GETSELCOUNT, 0, 0); end; procedure TCustomListBox.SetItemIndex(const Value: Integer); begin if GetItemIndex <> Value then if MultiSelect then SendMessage(Handle, LB_SETCARETINDEX, Value, 0) else SendMessage(Handle, LB_SETCURSEL, Value, 0); end; procedure TCustomListBox.SetExtendedSelect(Value: Boolean); begin if Value <> FExtendedSelect then begin FExtendedSelect := Value; RecreateWnd; end; end; procedure TCustomListBox.SetIntegralHeight(Value: Boolean); begin if Value <> FIntegralHeight then begin FIntegralHeight := Value; RecreateWnd; RequestAlign; end; end; function TCustomListBox.GetItemHeight: Integer; var R: TRect; begin Result := FItemHeight; if HandleAllocated and (FStyle = lbStandard) then begin Perform(LB_GETITEMRECT, 0, Longint(@R)); Result := R.Bottom - R.Top; end; end; procedure TCustomListBox.SetItemHeight(Value: Integer); begin if (FItemHeight <> Value) and (Value > 0) then begin FItemHeight := Value; RecreateWnd; end; end; procedure TCustomListBox.SetTabWidth(Value: Integer); begin if Value < 0 then Value := 0; if FTabWidth <> Value then begin FTabWidth := Value; RecreateWnd; end; end; procedure TCustomListBox.SetMultiSelect(Value: Boolean); begin if FMultiSelect <> Value then begin FMultiSelect := Value; RecreateWnd; end; end; function TCustomListBox.GetSelected(Index: Integer): Boolean; var R: Longint; begin R := SendMessage(Handle, LB_GETSEL, Index, 0); if R = LB_ERR then raise EListError.CreateResFmt(@SListIndexError, [Index]); Result := LongBool(R); end; procedure TCustomListBox.SetSelected(Index: Integer; Value: Boolean); begin if FMultiSelect then begin if SendMessage(Handle, LB_SETSEL, Longint(Value), Index) = LB_ERR then raise EListError.CreateResFmt(@SListIndexError, [Index]); end else if Value then begin if SendMessage(Handle, LB_SETCURSEL, Index, 0) = LB_ERR then raise EListError.CreateResFmt(@SListIndexError, [Index]) end else SendMessage(Handle, LB_SETCURSEL, -1, 0); end; procedure TCustomListBox.SetSorted(Value: Boolean); begin if Style in [lbVirtual, lbVirtualOwnerDraw] then exit; if FSorted <> Value then begin FSorted := Value; RecreateWnd; end; end; procedure TCustomListBox.SetStyle(Value: TListBoxStyle); begin if FStyle <> Value then begin if Value in [lbVirtual, lbVirtualOwnerDraw] then begin Items.Clear; Sorted := False; end; FStyle := Value; RecreateWnd; end; end; function TCustomListBox.GetTopIndex: Integer; begin Result := SendMessage(Handle, LB_GETTOPINDEX, 0, 0); end; procedure TCustomListBox.LBGetText(var Message: TMessage); var S: string; begin if Style in [lbVirtual, lbVirtualOwnerDraw] then begin if Assigned(FOnData) and (Message.WParam > -1) and (Message.WParam < Count) then begin S := ''; OnData(Self, Message.wParam, S); StrCopy(PChar(Message.lParam), PChar(S)); Message.Result := Length(S); end else Message.Result := LB_ERR; end else inherited; end; procedure TCustomListBox.LBGetTextLen(var Message: TMessage); var S: string; begin if Style in [lbVirtual, lbVirtualOwnerDraw] then begin if Assigned(FOnData) and (Message.WParam > -1) and (Message.WParam < Count) then begin S := ''; OnData(Self, Message.wParam, S); Message.Result := Length(S); end else Message.Result := LB_ERR; end else inherited; end; procedure TCustomListBox.SetBorderStyle(Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; RecreateWnd; end; end; procedure TCustomListBox.SetTopIndex(Value: Integer); begin if GetTopIndex <> Value then SendMessage(Handle, LB_SETTOPINDEX, Value, 0); end; procedure TCustomListBox.SetItems(Value: TStrings); begin if Style in [lbVirtual, lbVirtualOwnerDraw] then case Style of lbVirtual: Style := lbStandard; lbVirtualOwnerDraw: Style := lbOwnerDrawFixed; end; Items.Assign(Value); end; function TCustomListBox.ItemAtPos(Pos: TPoint; Existing: Boolean): Integer; var Count: Integer; ItemRect: TRect; begin if PtInRect(ClientRect, Pos) then begin Result := TopIndex; Count := Items.Count; while Result < Count do begin Perform(LB_GETITEMRECT, Result, Longint(@ItemRect)); if PtInRect(ItemRect, Pos) then Exit; Inc(Result); end; if not Existing then Exit; end; Result := -1; end; function TCustomListBox.ItemRect(Index: Integer): TRect; var Count: Integer; begin Count := Items.Count; if (Index = 0) or (Index < Count) then Perform(LB_GETITEMRECT, Index, Longint(@Result)) else if Index = Count then begin Perform(LB_GETITEMRECT, Index - 1, Longint(@Result)); OffsetRect(Result, 0, Result.Bottom - Result.Top); end else FillChar(Result, SizeOf(Result), 0); end; procedure TCustomListBox.CreateParams(var Params: TCreateParams); type PSelects = ^TSelects; TSelects = array[Boolean] of DWORD; const Styles: array[TListBoxStyle] of DWORD = (0, LBS_OWNERDRAWFIXED, LBS_OWNERDRAWVARIABLE, LBS_OWNERDRAWFIXED, LBS_OWNERDRAWFIXED); Sorteds: array[Boolean] of DWORD = (0, LBS_SORT); MultiSelects: array[Boolean] of DWORD = (0, LBS_MULTIPLESEL); ExtendSelects: array[Boolean] of DWORD = (0, LBS_EXTENDEDSEL); IntegralHeights: array[Boolean] of DWORD = (LBS_NOINTEGRALHEIGHT, 0); MultiColumns: array[Boolean] of DWORD = (0, LBS_MULTICOLUMN); TabStops: array[Boolean] of DWORD = (0, LBS_USETABSTOPS); CSHREDRAW: array[Boolean] of DWORD = (CS_HREDRAW, 0); Data: array[Boolean] of DWORD = (LBS_HASSTRINGS, LBS_NODATA); var Selects: PSelects; begin inherited CreateParams(Params); CreateSubClass(Params, 'LISTBOX'); with Params do begin Selects := @MultiSelects; if FExtendedSelect then Selects := @ExtendSelects; Style := Style or (WS_HSCROLL or WS_VSCROLL or Data[Self.Style in [lbVirtual, lbVirtualOwnerDraw]] or LBS_NOTIFY) or Styles[FStyle] or Sorteds[FSorted] or Selects^[FMultiSelect] or IntegralHeights[FIntegralHeight] or MultiColumns[FColumns <> 0] or BorderStyles[FBorderStyle] or TabStops[FTabWidth <> 0]; if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then begin Style := Style and not WS_BORDER; ExStyle := ExStyle or WS_EX_CLIENTEDGE; end; WindowClass.style := WindowClass.style and not (CSHREDRAW[UseRightToLeftAlignment] or CS_VREDRAW); end; end; procedure TCustomListBox.CreateWnd; var W, H: Integer; begin W := Width; H := Height; inherited CreateWnd; SetWindowPos(Handle, 0, Left, Top, W, H, SWP_NOZORDER or SWP_NOACTIVATE); if FTabWidth <> 0 then SendMessage(Handle, LB_SETTABSTOPS, 1, Longint(@FTabWidth)); SetColumnWidth; if (FOldCount <> -1) or Assigned(FSaveItems) then begin if (Style in [lbVirtual, lbVirtualOwnerDraw]) then Count := FOldCount; if FSaveItems <> nil then begin FItems.Assign(FSaveItems); FreeAndNil(FSaveItems); end; SetTopIndex(FSaveTopIndex); SetItemIndex(FSaveItemIndex); FOldCount := -1; end; end; procedure TCustomListBox.DestroyWnd; begin if (FItems.Count > 0) then begin if (Style in [lbVirtual, lbVirtualOwnerDraw]) then FOldCount := FItems.Count else begin FSaveItems := TStringList.Create; FSaveItems.Assign(FItems); end; FSaveTopIndex := GetTopIndex; FSaveItemIndex := GetItemIndex; end; inherited DestroyWnd; end; procedure TCustomListBox.WndProc(var Message: TMessage); begin {for auto drag mode, let listbox handle itself, instead of TControl} if not (csDesigning in ComponentState) and ((Message.Msg = WM_LBUTTONDOWN) or (Message.Msg = WM_LBUTTONDBLCLK)) and not Dragging then begin if DragMode = dmAutomatic then begin if IsControlMouseMsg(TWMMouse(Message)) then Exit; ControlState := ControlState + [csLButtonDown]; Dispatch(Message); {overrides TControl's BeginDrag} Exit; end; end; inherited WndProc(Message); end; procedure TCustomListBox.WMLButtonDown(var Message: TWMLButtonDown); var ItemNo : Integer; ShiftState: TShiftState; begin ShiftState := KeysToShiftState(Message.Keys); if (DragMode = dmAutomatic) and FMultiSelect then begin if not (ssShift in ShiftState) or (ssCtrl in ShiftState) then begin ItemNo := ItemAtPos(SmallPointToPoint(Message.Pos), True); if (ItemNo >= 0) and (Selected[ItemNo]) then begin BeginDrag (False); Exit; end; end; end; inherited; if (DragMode = dmAutomatic) and not (FMultiSelect and ((ssCtrl in ShiftState) or (ssShift in ShiftState))) then BeginDrag(False); end; procedure TCustomListBox.CNCommand(var Message: TWMCommand); begin case Message.NotifyCode of LBN_SELCHANGE: begin inherited Changed; Click; end; LBN_DBLCLK: DblClick; end; end; procedure TCustomListBox.WMPaint(var Message: TWMPaint); procedure PaintListBox; var DrawItemMsg: TWMDrawItem; MeasureItemMsg: TWMMeasureItem; DrawItemStruct: TDrawItemStruct; MeasureItemStruct: TMeasureItemStruct; R: TRect; Y, I, H, W: Integer; begin { Initialize drawing records } DrawItemMsg.Msg := CN_DRAWITEM; DrawItemMsg.DrawItemStruct := @DrawItemStruct; DrawItemMsg.Ctl := Handle; DrawItemStruct.CtlType := ODT_LISTBOX; DrawItemStruct.itemAction := ODA_DRAWENTIRE; DrawItemStruct.itemState := 0; DrawItemStruct.hDC := Message.DC; DrawItemStruct.CtlID := Handle; DrawItemStruct.hwndItem := Handle; { Intialize measure records } MeasureItemMsg.Msg := CN_MEASUREITEM; MeasureItemMsg.IDCtl := Handle; MeasureItemMsg.MeasureItemStruct := @MeasureItemStruct; MeasureItemStruct.CtlType := ODT_LISTBOX; MeasureItemStruct.CtlID := Handle; { Draw the listbox } Y := 0; I := TopIndex; GetClipBox(Message.DC, R); H := Height; W := Width; while Y < H do begin MeasureItemStruct.itemID := I; if I < Items.Count then MeasureItemStruct.itemData := Longint(Pointer(Items.Objects[I])); MeasureItemStruct.itemWidth := W; MeasureItemStruct.itemHeight := FItemHeight; DrawItemStruct.itemData := MeasureItemStruct.itemData; DrawItemStruct.itemID := I; Dispatch(MeasureItemMsg); DrawItemStruct.rcItem := Rect(0, Y, MeasureItemStruct.itemWidth, Y + Integer(MeasureItemStruct.itemHeight)); Dispatch(DrawItemMsg); Inc(Y, MeasureItemStruct.itemHeight); Inc(I); if I >= Items.Count then break; end; end; begin if Message.DC <> 0 then { Listboxes don't allow paint "sub-classing" like the other windows controls so we have to do it ourselves. } PaintListBox else inherited; end; procedure TCustomListBox.WMSize(var Message: TWMSize); begin inherited; SetColumnWidth; end; procedure TCustomListBox.DragCanceled; var M: TWMMouse; MousePos: TPoint; begin with M do begin Msg := WM_LBUTTONDOWN; GetCursorPos(MousePos); Pos := PointToSmallPoint(ScreenToClient(MousePos)); Keys := 0; Result := 0; end; DefaultHandler(M); M.Msg := WM_LBUTTONUP; DefaultHandler(M); end; procedure TCustomListBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); var Flags: Longint; Data: String; begin if Assigned(FOnDrawItem) then FOnDrawItem(Self, Index, Rect, State) else begin FCanvas.FillRect(Rect); if Index < Count then begin Flags := DrawTextBiDiModeFlags(DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX); if not UseRightToLeftAlignment then Inc(Rect.Left, 2) else Dec(Rect.Right, 2); Data := ''; if (Style in [lbVirtual, lbVirtualOwnerDraw]) then Data := DoGetData(Index) else Data := Items[Index]; DrawText(FCanvas.Handle, PChar(Data), Length(Data), Rect, Flags); end; end; end; procedure TCustomListBox.MeasureItem(Index: Integer; var Height: Integer); begin if Assigned(FOnMeasureItem) then FOnMeasureItem(Self, Index, Height) end; procedure TCustomListBox.CNDrawItem(var Message: TWMDrawItem); var State: TOwnerDrawState; begin with Message.DrawItemStruct^ do begin State := TOwnerDrawState(LongRec(itemState).Lo); FCanvas.Handle := hDC; FCanvas.Font := Font; FCanvas.Brush := Brush; if (Integer(itemID) >= 0) and (odSelected in State) then begin FCanvas.Brush.Color := clHighlight; FCanvas.Font.Color := clHighlightText end; if Integer(itemID) >= 0 then DrawItem(itemID, rcItem, State) else FCanvas.FillRect(rcItem); if odFocused in State then DrawFocusRect(hDC, rcItem); FCanvas.Handle := 0; end; end; procedure TCustomListBox.CNMeasureItem(var Message: TWMMeasureItem); begin with Message.MeasureItemStruct^ do begin itemHeight := FItemHeight; if FStyle = lbOwnerDrawVariable then MeasureItem(itemID, Integer(itemHeight)); end; end; procedure TCustomListBox.CMCtl3DChanged(var Message: TMessage); begin if NewStyleControls and (FBorderStyle = bsSingle) then RecreateWnd; inherited; end; procedure TCustomListBox.SelectAll; var I: Integer; begin if FMultiSelect then for I := 0 to Items.Count - 1 do Selected[I] := True; end; procedure TCustomListBox.KeyPress(var Key: Char); procedure FindString; var Idx: Integer; begin if Style in [lbVirtual, lbVirtualOwnerDraw] then Idx := DoFindData(FFilter) else Idx := SendMessage(Handle, LB_FINDSTRING, -1, LongInt(PChar(FFilter))); if Idx <> LB_ERR then begin if MultiSelect then begin ClearSelection; SendMessage(Handle, LB_SELITEMRANGE, 1, MakeLParam(Idx, Idx)) end; ItemIndex := Idx; Click; end; if not (Ord(Key) in [VK_RETURN, VK_BACK, VK_ESCAPE]) then Key := #0; // Clear so that the listbox's default search mechanism is disabled end; var Msg: TMsg; begin inherited KeyPress(Key); if not FAutoComplete then exit; if GetTickCount - FLastTime >= 500 then FFilter := ''; FLastTime := GetTickCount; if Ord(Key) <> VK_BACK then begin if Key in LeadBytes then begin if PeekMessage(Msg, Handle, WM_CHAR, WM_CHAR, PM_REMOVE) then begin FFilter := FFilter + Key + Chr(Msg.wParam); Key := #0; end; end else FFilter := FFilter + Key; end else begin while ByteType(FFilter, Length(FFilter)) = mbTrailByte do Delete(FFilter, Length(FFilter), 1); Delete(FFilter, Length(FFilter), 1); end; if Length(FFilter) > 0 then FindString else begin ItemIndex := 0; Click; end; end; procedure TCustomListBox.SetCount(const Value: Integer); var Error: Integer; begin if Style in [lbVirtual, lbVirtualOwnerDraw] then begin // Limited to 32767 on Win95/98 as per Win32 SDK Error := SendMessage(Handle, LB_SETCOUNT, Value, 0); if (Error <> LB_ERR) and (Error <> LB_ERRSPACE) then FCount := Value else raise Exception.CreateFmt(SErrorSettingCount, [Name]); end else raise Exception.CreateFmt(SListBoxMustBeVirtual, [Name]); end; function TCustomListBox.DoGetData(const Index: Integer): String; begin if Assigned(FOnData) then FOnData(Self, Index, Result); end; function TCustomListBox.DoGetDataObject(const Index: Integer): TObject; begin if Assigned(FOnDataObject) then FOnDataObject(Self, Index, Result); end; function TCustomListBox.DoFindData(const Data: String): Integer; begin if Assigned(FOnDataFind) then Result := FOnDataFind(Self, Data) else Result := -1; end; function TCustomListBox.GetScrollWidth: Integer; begin Result := SendMessage(Handle, LB_GETHORIZONTALEXTENT, 0, 0); end; procedure TCustomListBox.SetScrollWidth(const Value: Integer); begin if Value <> ScrollWidth then SendMessage(Handle, LB_SETHORIZONTALEXTENT, Value, 0); end; { TScrollBar } constructor TScrollBar.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 121; Height := GetSystemMetrics(SM_CYHSCROLL); TabStop := True; ControlStyle := [csFramed, csDoubleClicks, csOpaque]; FKind := sbHorizontal; FPosition := 0; FMin := 0; FMax := 100; FSmallChange := 1; FLargeChange := 1; if SysLocale.FarEast and (Win32Platform = VER_PLATFORM_WIN32_NT) then ImeMode := imDisable; end; procedure TScrollBar.CreateParams(var Params: TCreateParams); const Kinds: array[TScrollBarKind] of DWORD = (SBS_HORZ, SBS_VERT); begin inherited CreateParams(Params); CreateSubClass(Params, 'SCROLLBAR'); Params.Style := Params.Style or Kinds[FKind]; if FKind = sbVertical then if not UseRightToLeftAlignment then Params.Style := Params.Style or SBS_RIGHTALIGN else Params.Style := Params.Style or SBS_LEFTALIGN; if NotRightToLeft then FRTLFactor := 1 else FRTLFactor := -1; end; procedure TScrollBar.CreateWnd; var ScrollInfo: TScrollInfo; LBounds: TRect; begin // Windows' does not always create the window size we ask for, so we have // insist sometimes. Setting BoundsRect will only adjust the size if needed. LBounds := BoundsRect; inherited CreateWnd; BoundsRect := LBounds; SetScrollRange(Handle, SB_CTL, FMin, FMax, False); ScrollInfo.cbSize := SizeOf(ScrollInfo); ScrollInfo.nPage := FPageSize; ScrollInfo.fMask := SIF_PAGE; SetScrollInfo(Handle, SB_CTL, ScrollInfo, False); if NotRightToLeft then SetScrollPos(Handle, SB_CTL, FPosition, True) else SetScrollPos(Handle, SB_CTL, FMax - FPosition, True); end; function TScrollBar.NotRightToLeft: Boolean; begin Result := (not IsRightToLeft) or (FKind = sbVertical); end; procedure TScrollBar.SetKind(Value: TScrollBarKind); begin if FKind <> Value then begin FKind := Value; if not (csLoading in ComponentState) then SetBounds(Left, Top, Height, Width); RecreateWnd; end; end; procedure TScrollBar.SetParams(APosition, AMin, AMax: Integer); begin if (AMax < AMin) or (AMax < FPageSize) then raise EInvalidOperation.Create(SScrollBarRange); if APosition < AMin then APosition := AMin; if APosition > AMax then APosition := AMax; if (FMin <> AMin) or (FMax <> AMax) then begin FMin := AMin; FMax := AMax; if HandleAllocated then SetScrollRange(Handle, SB_CTL, AMin, AMax, FPosition = APosition); end; if FPosition <> APosition then begin FPosition := APosition; if HandleAllocated then if NotRightToLeft then SetScrollPos(Handle, SB_CTL, FPosition, True) else SetScrollPos(Handle, SB_CTL, FMax - FPosition, True); Enabled := True; Change; end; end; procedure TScrollBar.SetPosition(Value: Integer); begin SetParams(Value, FMin, FMax); end; procedure TScrollBar.SetPageSize(Value: Integer); var ScrollInfo: TScrollInfo; begin if (FPageSize = Value) or (Value > FMax) then exit; FPageSize := Value; ScrollInfo.cbSize := SizeOf(ScrollInfo); ScrollInfo.nPage := Value; ScrollInfo.fMask := SIF_PAGE; if HandleAllocated then SetScrollInfo(Handle, SB_CTL, ScrollInfo, True); end; procedure TScrollBar.SetMin(Value: Integer); begin SetParams(FPosition, Value, FMax); end; procedure TScrollBar.SetMax(Value: Integer); begin SetParams(FPosition, FMin, Value); end; procedure TScrollBar.Change; begin inherited Changed; if Assigned(FOnChange) then FOnChange(Self); end; procedure TScrollBar.Scroll(ScrollCode: TScrollCode; var ScrollPos: Integer); begin if Assigned(FOnScroll) then FOnScroll(Self, ScrollCode, ScrollPos); end; procedure TScrollBar.DoScroll(var Message: TWMScroll); var ScrollPos: Integer; NewPos: Longint; ScrollInfo: TScrollInfo; begin with Message do begin NewPos := FPosition; case TScrollCode(ScrollCode) of scLineUp: Dec(NewPos, FSmallChange * FRTLFactor); scLineDown: Inc(NewPos, FSmallChange * FRTLFactor); scPageUp: Dec(NewPos, FLargeChange * FRTLFactor); scPageDown: Inc(NewPos, FLargeChange * FRTLFactor); scPosition, scTrack: with ScrollInfo do begin cbSize := SizeOf(ScrollInfo); fMask := SIF_ALL; GetScrollInfo(Handle, SB_CTL, ScrollInfo); NewPos := nTrackPos; { We need to reverse the positioning because SetPosition below calls SetParams that reverses the position. This acts as a double negative. } if not NotRightToLeft then NewPos := FMax - NewPos; end; scTop: NewPos := FMin; scBottom: NewPos := FMax; end; if NewPos < FMin then NewPos := FMin; if NewPos > FMax then NewPos := FMax; ScrollPos := NewPos; Scroll(TScrollCode(ScrollCode), ScrollPos); SetPosition(ScrollPos); end; end; procedure TScrollBar.CNHScroll(var Message: TWMHScroll); begin DoScroll(Message); end; procedure TScrollBar.CNVScroll(var Message: TWMVScroll); begin DoScroll(Message); end; procedure TScrollBar.CNCtlColorScrollBar(var Message: TMessage); begin with Message do CallWindowProc(DefWndProc, Handle, Msg, WParam, LParam); end; procedure TScrollBar.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin DefaultHandler(Message); end; { TCustomStaticText } constructor TCustomStaticText.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csCaptureMouse, csClickEvents, csSetCaption, csReplicatable, csDoubleClicks]; Width := 65; Height := 17; FAutoSize := True; FShowAccelChar := True; AdjustBounds; end; procedure TCustomStaticText.CreateParams(var Params: TCreateParams); const Alignments: array[Boolean, TAlignment] of DWORD = ((SS_LEFT, SS_RIGHT, SS_CENTER), (SS_RIGHT, SS_LEFT, SS_CENTER)); Borders: array[TStaticBorderStyle] of DWORD = (0, WS_BORDER, SS_SUNKEN); begin inherited CreateParams(Params); CreateSubClass(Params, 'STATIC'); with Params do begin Style := Style or SS_NOTIFY or Alignments[UseRightToLeftAlignment, FAlignment] or Borders[FBorderStyle]; if not FShowAccelChar then Style := Style or SS_NOPREFIX; WindowClass.style := WindowClass.style and not CS_VREDRAW; end; end; procedure TCustomStaticText.CMDialogChar(var Message: TCMDialogChar); begin if (FFocusControl <> nil) and Enabled and ShowAccelChar and IsAccel(Message.CharCode, Caption) then with FFocusControl do if CanFocus then begin SetFocus; Message.Result := 1; end; end; procedure TCustomStaticText.CMFontChanged(var Message: TMessage); begin inherited; AdjustBounds; end; procedure TCustomStaticText.CMTextChanged(var Message: TMessage); begin inherited; AdjustBounds; Invalidate; end; procedure TCustomStaticText.Loaded; begin inherited Loaded; AdjustBounds; end; procedure TCustomStaticText.AdjustBounds; var DC: HDC; SaveFont: HFont; TextSize: TSize; begin if not (csReading in ComponentState) and FAutoSize then begin DC := GetDC(0); SaveFont := SelectObject(DC, Font.Handle); GetTextExtentPoint32(DC, PChar(Caption), Length(Caption), TextSize); SelectObject(DC, SaveFont); ReleaseDC(0, DC); SetBounds(Left, Top, TextSize.cx + (GetSystemMetrics(SM_CXBORDER) * 4), TextSize.cy + (GetSystemMetrics(SM_CYBORDER) * 4)); end; end; procedure TCustomStaticText.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FFocusControl) then FFocusControl := nil; end; procedure TCustomStaticText.SetAlignment(Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; procedure TCustomStaticText.SetAutoSize(Value: Boolean); begin if FAutoSize <> Value then begin FAutoSize := Value; if Value then AdjustBounds; end; end; procedure TCustomStaticText.SetBorderStyle(Value: TStaticBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; RecreateWnd; end; end; procedure TCustomStaticText.SetFocusControl(Value: TWinControl); begin FFocusControl := Value; if Value <> nil then Value.FreeNotification(Self); end; procedure TCustomStaticText.SetShowAccelChar(Value: Boolean); begin if FShowAccelChar <> Value then begin FShowAccelChar := Value; RecreateWnd; end; end; procedure TCustomStaticText.CNCtlColorStatic( var Message: TWMCtlColorStatic); begin with ThemeServices do if ThemesEnabled and Transparent then begin SetBkMode(Message.ChildDC, Windows.TRANSPARENT); DrawParentBackground(Handle, Message.ChildDC, nil, False); { Return an empty brush to prevent Windows from overpainting what we just have created. } Message.Result := GetStockObject(NULL_BRUSH); end else inherited; end; procedure TCustomStaticText.SetTransparent(const Value: Boolean); begin if Transparent <> Value then begin if Value then ControlStyle := ControlStyle - [csOpaque] else ControlStyle := ControlStyle + [csOpaque]; Invalidate; end; end; function TCustomStaticText.GetTransparent: Boolean; begin Result := not (csOpaque in ControlStyle); end; end.
(* StackUnit: MM, 2020-05-27 *) (* ------ *) (* A simple stack. *) (* ========================================================================= *) UNIT StackUnit; INTERFACE TYPE Stack = ^StackObj; StackObj = OBJECT DESTRUCTOR Done; VIRTUAL; PROCEDURE Push(e: INTEGER); VIRTUAL; PROCEDURE Pop(VAR e: INTEGER); VIRTUAL; FUNCTION IsEmpty: BOOLEAN; VIRTUAL; END; (* StackObj *) IMPLEMENTATION DESTRUCTOR StackObj.Done; BEGIN END; PROCEDURE StackObj.Push(e: INTEGER); BEGIN WriteLn('ERROR: StackObj.Push not implemented to simulate abstract base class.'); HALT; END; PROCEDURE StackObj.Pop(VAR e: INTEGER); BEGIN WriteLn('ERROR: StackObj.Pop not implemented to simulate abstract base class.'); HALT; END; FUNCTION StackObj.IsEmpty: BOOLEAN; BEGIN (* StackObj.IsEmpty *) WriteLn('ERROR: StackObj.IsEmpty not implemented to simulate abstract base class.'); HALT; END; (* StackObj.IsEmpty *) BEGIN (* StackUnit *) END. (* StackUnit *)
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info) unit SMARTSupport.JMicron60x; interface uses BufferInterpreter, Device.SMART.List, SMARTSupport, Support; type TJMicron60xSMARTSupport = class(TSMARTSupport) public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; override; function GetTypeName: String; override; function IsSSD: Boolean; override; function IsInsufficientSMART: Boolean; override; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; override; function IsWriteValueSupported(const SMARTList: TSMARTValueList): Boolean; override; protected function InnerIsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; function InnerIsCaution(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; end; implementation { TJMicron60xSMARTSupport } function TJMicron60xSMARTSupport.GetTypeName: String; begin result := 'SmartJMicron60x'; end; function TJMicron60xSMARTSupport.IsInsufficientSMART: Boolean; begin result := true; end; function TJMicron60xSMARTSupport.IsSSD: Boolean; begin result := true; end; function TJMicron60xSMARTSupport.IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := (SMARTList.Count >= 6) and (SMARTList[0].Id = $0C) and (SMARTList[1].Id = $09) and (SMARTList[2].Id = $C2) and (SMARTList[3].Id = $E5) and (SMARTList[4].Id = $E8) and (SMARTList[5].Id = $E9); end; function TJMicron60xSMARTSupport.InnerIsErrorAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TJMicron60xSMARTSupport.InnerIsCautionAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TJMicron60xSMARTSupport.InnerIsError( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result.Override := true; result.Status := false; end; function TJMicron60xSMARTSupport.InnerIsCaution( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result.Override := true; result.Status := false; end; function TJMicron60xSMARTSupport.IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; begin result := false; end; function TJMicron60xSMARTSupport.GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; begin FillChar(result, SizeOf(result), 0); end; end.
unit Uclasses; interface Type TFuncionario = Class //atributos Private Codigo: integer; Funcao: string; Nome: string[40]; Rg: integer; Cpf: string[11]; Endereco: string[50]; Cidade: string[20]; Estado: string[2]; Bairro: string[15]; Cep: Integer; Telefone1: string[10]; Telefone2: string[10]; Crm: integer; Public //métodos acessores //funções Function getCodigo: Integer; Function getFuncao: String; Function getNome: String; Function getRg: Integer; Function getCpf: String; Function getEndereco: String; Function getCidade: String; Function getEstado: String; Function getBairro: String; Function getCep: Integer; Function getTelefone1: String; Function getTelefone2: String; Function getCrm: Integer; //procedimentos Procedure setNome(N: String); Procedure setEndereco(E: String); Procedure setCidade(C: String); Procedure setEstado(ES: String); Procedure setBairro(B: String); Procedure setCep(CE: Integer); Procedure setTelefone1(T1: String); Procedure setTelefone2(T2: String); //construtor Constructor Create(C:Integer; F:String; N:String; R:Integer; CP:String; E:String; CI:String; ES:String; B:String; CE: Integer; T1:String; T2:String; CR:Integer); //destrutor Destructor Free; end; implementation Constructor TFuncionario.Create(C:Integer; F:String; N:String; R:Integer; CP:String; E:String; CI:String; ES:String; B:String; CE: Integer; T1:String; T2:String; CR:Integer); begin Codigo:= C; Funcao:= F; Nome:= N; Rg:= R; Cpf:= CP; Endereco:= E; Cidade:= CI; Estado:= ES; Bairro:= B; Cep:= CE; Telefone1:= T1; Telefone2:= T2; Crm:= CR; end; Destructor TFuncionario.Free; begin Codigo:= 0; Funcao:= ''; Nome:= ''; Rg:= 0; Cpf:= ''; Endereco:= ''; Cidade:= ''; Estado:= ''; Bairro:= ''; Cep:= 0; Telefone1:= ''; Telefone2:= ''; Crm:= 0; end; Function TFuncionario.getCodigo: Integer; begin Result:=Codigo; end; Function TFuncionario.getFuncao: String; begin Result:=Funcao; end; Function TFuncionario.getNome: String; begin Result:=Nome; end; Function TFuncionario.getRg: Integer; begin Result:=Rg; end; Function TFuncionario.getCpf: String; begin Result:=Cpf; end; Function TFuncionario.getEndereco: String; begin Result:=Endereco; end; Function TFuncionario.getCidade: String; begin Result:=Cidade; end; Function TFuncionario.getEstado: String; begin Result:=Estado; end; Function TFuncionario.getBairro: String; begin Result:=Bairro; end; Function TFuncionario.getCep: Integer; begin Result:=Cep; end; Function TFuncionario.getTelefone1: String; begin Result:=Telefone1; end; Function TFuncionario.getTelefone2: String; begin Result:=Telefone2; end; Function TFuncionario.getCrm: Integer; begin Result:=Crm; end; Procedure TFuncionario.setNome(N:String); begin Nome:=N; end; Procedure TFuncionario.setEndereco(E: String); begin Endereco:=E; end; Procedure TFuncionario.setCidade(C: String); begin Cidade:=C; end; Procedure TFuncionario.setEstado(ES: String); begin Estado:=ES; end; Procedure TFuncionario.setBairro(B: String); begin Bairro:=B; end; Procedure TFuncionario.setCep(CE: Integer); begin Cep:=CE; end; Procedure TFuncionario.setTelefone1(T1: String); begin Telefone1:=T1; end; Procedure TFuncionario.setTelefone2(T2: String); begin Telefone2:=T2; end; end.
unit uDateUtils; interface function DateTimeToUnix(dtDate: TDateTime): Longint; function UnixToDateTime(USec: Longint): TDateTime; implementation const UnixStartDate: TDateTime = 25569.0; // 01/01/1970 function DateTimeToUnix(dtDate: TDateTime): Longint; begin Result := Round((dtDate - UnixStartDate) * 86400); end; function UnixToDateTime(USec: Longint): TDateTime; begin Result := (Usec / 86400) + UnixStartDate; end; end.
unit EngineTypes; interface uses Points; type PMonster = ^Monster; PAPMonster = ^APMonster; PItem = ^Item; PAPItem = ^APItem; PSPoint = ^SPoint; PAPoint = ^APoint; PPoint = ^Point; PAPPoint = ^APPoint; PSector = ^Sector; PAPSector = ^APSector; PAFace = ^AFace; PFace = ^Face; PAPFace = ^APFace; PConvexInSector = ^ConvexInSector; PConvex = ^Convex; PAConvex = ^AConvex; PAPConvex = ^APConvex; PAInt = ^AInt; PTexture = ^Texture; PItemPoint = ^ItemPoint; PAItemPoint = ^AItemPoint; PItemModel = ^ItemModel; PBullet = ^Bullet; PWeapon = ^Weapon; AInt = array [0 .. MaxInt div sizeof(integer)-1] of integer; APoint = array [0 .. MaxInt div sizeof(Point)-1] of Point; APPoint = array [0 .. MaxInt div sizeof(PPoint)-1] of PPoint; RenderFunc = record vplt,vdx,vdy : float; end; RenderInfo = record w,tx,ty : RenderFunc; Txr : PTexture; Light : integer; end; Texture = record Pixels : PAInt; Dithering : boolean; maskx, masky : integer; shlx : integer; end; Face = record inProcess : boolean; // для обходов полезно Id : integer; // ид внутренний относительно сектора RI : RenderInfo; // для отрисовки NextSector : PSector; Penetrable : boolean; INorm : Point; // нормаль INormC : float; // для <P,INorm-INormC> < 0 CPoints : integer; Points : PAPPoint; // массив её вершин, да-да, от него не уйти! Texture : PTexture; Light : integer; VTx, VTy : Point; // информация для текстурирования, задаёт функцию R3->R2 для текстурных координат VTxc, VTyc : float; end; AFace = array [0 .. MaxInt div sizeof(Face)-1] of Face; APFace = array [0 .. MaxInt div sizeof(PFace)-1] of PFace; Line = record p1,p2: PPoint; // точки общие f1,f2 : PFace; // грани общие end; ALine = array [0 .. MaxInt div sizeof(Line)-1] of Line; PALine = ^ALine; Sector = record inProcess : integer; // для обходов полезно ID : integer; FConvex, LConvex : PConvexInSector; CFaces : integer; Faces : PAFace; // грани принадлежат лишь ему лично CLines : integer; Lines : PALine; // линии принадлежал лишь ему лично Gravity : float; // боковых гравитаций не будет, ибо монстры все выстроены по вертикали Skybox : boolean; end; APSector = array [0 .. MaxInt div sizeof(PSector)-1] of PSector; SPoint = record S : PSector; P : Point; end; ConvexInSector = record NC,PC,NS,PS : PConvexInSector; Convex : PConvex; Sector : PSector; end; Convex = record inProcess : boolean; FSector,LSector : PConvexInSector; // в каких комнатах сидит Item : PItem; CanCollide : boolean; // годится ли для коллиий Mass : float; // только для коллидеров Center : SPoint; // центр для отрисовки, коллизий Shift : Point; // смещение от центра предмета R : float; // радиус для коллизий G : Sector; // геометрия end; AConvex = array [0..MaxInt div sizeof(Convex)-1] of Convex; APConvex = array [0 .. MaxInt div sizeof(PConvex)-1] of PConvex; Controls = record Forw,Back,StrL,StrR,Jump,Sit : boolean; Shot : boolean; WeaponNumber : integer; dax, daz : float; end; ItemPoint = record cP : Point; iP : Point; tx, ty : float; end; AItemPoint = array [0..MaxInt div sizeof(ItemPoint)-1] of ItemPoint; ApplyItemProc = function (M : PMonster; It : PItem) : boolean; Item = record inProcess : boolean; Center : SPoint; Position : Matrix; CConvexes : integer; Convexes : PAConvex; Monster : PMonster; Bullet : PBullet; Weapon : PWeapon; // это для геометрии CPoints : integer; ItemPoints : PAItemPoint; Model : PItemModel; end; APItem = array [0..MaxInt div sizeof(PItem)-1] of PItem; Weapon = record IsWeapon : boolean; Item : Item; ReloadLeft : float; end; Monster = record Controls : Controls; CurrentWeapon : integer; Head,Body,Legs : PSPoint; anglex, anglez : float; StepStage : float; Fr : float; DeltaPos : Point; Health,Armor : float; Item : Item; ProcessTime : float; // <0 не в процессе DeathStage : float; // <=0 несдох LastDamage : float; Weapons : array [0..9] of Weapon; PrevShot : boolean; end; APMonster = array [0..MaxInt div sizeof(PMonster)-1] of PMonster; Bullet = record Item : Item; WPModel : PItemModel; DeltaPos : Point; TripDist : float; Owner : PMonster; Active : boolean; end; ModelKind = (mkBox,mkMonster,mkBullet,mkWeapon); ItemProc = procedure (var it : Item); ItemModel = record Kind : ModelKind; Name : string; CPoints : integer; CConvexes : integer; Connections : PAInt; ItemProc : ItemProc; Texture : PTexture; // бля монстров Player : boolean; Mass,HeadR,BodyR,LegsR,HB,MinBL,MaxBL,Speed,Spring,Lightness : float; InitialHealths : float; WeaponModels : array [0..9] of PItemModel; DefaultHasWeapon : array [0..9] of boolean; // бля аптечек,патронов,брони ApplyItemProc : ApplyItemProc; // бля оружия Instrument,Nota : byte; BulletSpeed,Range,Damage,BulletsPerShot,Dispersion,ReloadTime : float; BulletModel : PItemModel; Sabre : boolean; end; implementation end.
unit uModel.Endereco; interface uses System.SysUtils, System.Classes; type TEnderecoModel = class private FLogradouro: string; FNumero: string; FBairro: string; FCep: string; FCidade: string; FUF: string; public constructor Create; destructor Destroy; override; function Logradouro: string; overload; function Logradouro(Value: string): TEnderecoModel; overload; function Numero: string; overload; function Numero(Value: string): TEnderecoModel; overload; function Bairro: string; overload; function Bairro(Value: string): TEnderecoModel; overload; function Cep: string; overload; function Cep(Value: string): TEnderecoModel; overload; function Cidade: string; overload; function Cidade(Value: string): TEnderecoModel; overload; function UF: string; overload; function UF(Value: string): TEnderecoModel; overload; end; implementation { TEnderecoModel } function TEnderecoModel.Bairro: string; begin Result := FBairro; end; function TEnderecoModel.Bairro(Value: string): TEnderecoModel; begin Result := Self; FBairro := Value; end; function TEnderecoModel.Cep(Value: string): TEnderecoModel; begin Result := Self; FCep := Value; end; function TEnderecoModel.Cep: string; begin Result := FCep; end; function TEnderecoModel.Cidade: string; begin Result := FCidade; end; function TEnderecoModel.Cidade(Value: string): TEnderecoModel; begin Result := Self; FCidade := Value; end; constructor TEnderecoModel.Create; begin end; destructor TEnderecoModel.Destroy; begin inherited; end; function TEnderecoModel.Logradouro(Value: string): TEnderecoModel; begin Result := Self; FLogradouro := Value; end; function TEnderecoModel.Logradouro: string; begin Result := FLogradouro; end; function TEnderecoModel.Numero: string; begin Result := FNumero; end; function TEnderecoModel.Numero(Value: string): TEnderecoModel; begin Result := Self; FNumero := Value; end; function TEnderecoModel.UF: string; begin Result := FUF; end; function TEnderecoModel.UF(Value: string): TEnderecoModel; begin Result := Self; FUF := Value; end; end.
unit U_POWER_STATUS; interface uses SysUtils, Classes, U_CKM_DEVICE; type /// <summary> /// 三相功率状态 /// </summary> TPOWER_STATUS = class( TPersistent ) private FPowerType : TPOWER_OUTPUT_TYPE; FFrequency : Double; FPowerFactor : Double; FPowerActive : Double; FPowerReactive : Double; FU1 : Double; FI1 : Double; FO1 : Double; FU2 : Double; FI2 : Double; FO2 : Double; FU3 : Double; FI3 : Double; FO3 : Double; FOU1U2 : Double; FOU1U3 : Double; FOnChanged : TNotifyEvent; FOwnerPower: TCKM_POWER; public /// <summary> /// 相线类型 /// </summary> property PowerType : TPOWER_OUTPUT_TYPE read FPowerType write FPowerType; /// <summary> /// 频率 /// </summary> property Frequency : Double read FFrequency write FFrequency; /// <summary> /// 功率因数 /// </summary> property PowerFactor : Double read FPowerFactor write FPowerFactor; /// <summary> /// 有功功率 /// </summary> property PowerActive : Double read FPowerActive write FPowerActive; /// <summary> /// 无功功率 /// </summary> property PowerReactive : Double read FPowerReactive write FPowerReactive; /// <summary> /// 相线电压,电流及电压电流夹角 /// </summary> property U1 : Double read FU1 write FU1; // 三线时为U12 property I1 : Double read FI1 write FI1; property O1 : Double read FO1 write FO1; // 三线时为U12, I1夹角 property U2 : Double read FU2 write FU2; // 三线时不用 property I2 : Double read FI2 write FI2; // 三线时不用 property O2 : Double read FO2 write FO2; // 三线时不用 property U3 : Double read FU3 write FU3; // 三线时为U32 property I3 : Double read FI3 write FI3; property O3 : Double read FO3 write FO3; // 三线时为U32, I3夹角 /// <summary> /// 电压与电压之间夹角 /// </summary> property OU1U2 : Double read FOU1U2 write FOU1U2; property OU1U3 : Double read FOU1U3 write FOU1U3; /// <summary> /// 改变事件 /// </summary> property OnChanged : TNotifyEvent read FOnChanged write FOnChanged; /// <summary> /// 所属功率源 /// </summary> property OwnerPower : TCKM_POWER read FOwnerPower write FOwnerPower; public constructor Create; procedure Assign(Source: TPersistent); override; /// <summary> /// 清除 /// </summary> procedure Clear; end; /// <summary> /// 校准返回的实时向量图数据 /// </summary> procedure CalibratePowerStatus( AStatus : TPOWER_STATUS; APower : TCKM_POWER ); implementation procedure CalibratePowerStatus( AStatus : TPOWER_STATUS; APower : TCKM_POWER ); // 校准的值 function CalibrateUValue( AU : array of Double; AStdU : Double ) : Double; const C_MAX_VALUE = 0.15; var i: Integer; dSum : Double; nCount : Integer; begin dSum := 0; nCount := 0; for i := 0 to Length( AU ) - 1 do if ( Abs( AU[ i ] - AStdU ) < C_MAX_VALUE ) and ( Abs( AU[ i ] - AStdU ) < C_MAX_VALUE ) then begin dSum := dSum + AU[ i ]; Inc( nCount ); end; if nCount > 0 then Result := AStdU - dSum / nCount else Result := 0; end; var dValue : Double; dStdValue : Double; begin if not ( Assigned( AStatus ) and Assigned( APower ) ) then Exit; if APower.WorkStatus = psOn then dStdValue := APower.VoltagePercent / 100 else dStdValue := 0; with AStatus do begin if APower.PowerOutputType = ptThree then begin dValue := CalibrateUValue( [ U1, U3 ], dStdValue ); U1 := U1 + dValue; U3 := U3 + dValue; end else begin dValue := CalibrateUValue( [ U1, U2, U3 ], dStdValue ); U1 := U1 + dValue; U2 := U2 + dValue; U3 := U3 + dValue; end; end; end; { TPOWER_STATUS } procedure TPOWER_STATUS.Assign(Source: TPersistent); begin Assert( Source is TPOWER_STATUS ); FPowerType := TPOWER_STATUS( Source ).PowerType ; FFrequency := TPOWER_STATUS( Source ).Frequency ; FPowerFactor := TPOWER_STATUS( Source ).PowerFactor ; FPowerActive := TPOWER_STATUS( Source ).PowerActive ; FPowerReactive := TPOWER_STATUS( Source ).PowerReactive ; FU1 := TPOWER_STATUS( Source ).U1 ; FI1 := TPOWER_STATUS( Source ).I1 ; FO1 := TPOWER_STATUS( Source ).O1 ; FU2 := TPOWER_STATUS( Source ).U2 ; FI2 := TPOWER_STATUS( Source ).I2 ; FO2 := TPOWER_STATUS( Source ).O2 ; FU3 := TPOWER_STATUS( Source ).U3 ; FI3 := TPOWER_STATUS( Source ).I3 ; FO3 := TPOWER_STATUS( Source ).O3 ; FOU1U2 := TPOWER_STATUS( Source ).OU1U2 ; FOU1U3 := TPOWER_STATUS( Source ).OU1U3 ; end; procedure TPOWER_STATUS.Clear; begin FFrequency := 0; FPowerFactor := 0; FPowerActive := 0; FPowerReactive := 0; FU1 := 0; FI1 := 0; FO1 := 0; FU2 := 0; FI2 := 0; FO2 := 0; FU3 := 0; FI3 := 0; FO3 := 0; FOU1U2 := 0; FOU1U3 := 0; end; constructor TPOWER_STATUS.Create; begin Clear; end; end.
unit uwebdav; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fgl, fphttpclient; const //cWebDAVServer = 'https://webdav.yandex.ru/'; cWebDAVServer = 'https://{login}.stackstorage.com/'; cWebDAVSubdir = 'remote.php/webdav/'; type { TWDResource } TWDResource = class private FHref: string; FStatusCode: integer; FContentLength: int64; FCreationDate: TDateTime; FLastmodified: TDateTime; FDisplayName: string; FContentType: string; FCollection: boolean; public property Href: string read FHref write FHref; property StatusCode: integer read FStatusCode write FStatusCode; property ContentLength: int64 read FContentLength write FContentLength; property CreationDate: TDateTime read FCreationDate write FCreationDate; property Lastmodified: TDateTime read FLastmodified write FLastmodified; property DisplayName: string read FDisplayName write FDisplayName; property ContentType: string read FContentType write FContentType; property Collection: boolean read FCollection write FCollection; end; TWDResourceList = specialize TFPGObjectList<TWDResource>; type TWebDAVDrive = class private FLogin: string; FPassword: string; FDirectory: string; function EncodeUTF8URI(const URI: string): string; function GetRequestURL(const Element: string; EncodePath: boolean = False): string; public constructor Create; destructor Destroy; override; property Login: string read FLogin write FLogin; property Password: string read FPassword write FPassword; property Directory: string read FDirectory write FDirectory; // GET - Download a file function GET(const ElementHref: string; var Stream: TStream; Callback: TDataEvent): boolean; // PUT - Upload a file function PUT(const ElementHref: string; var Stream: TStream; Callback: TDataEvent): boolean; // DELETE - Delete a file function Delete(const ElementHref: string): boolean; // PROPFIND - Properties of files and directories // COPY - Copy a file // not implemented // MOVE - Move a file // not implemented function PROPFIND(Depth: integer {0/1}; const Element: string): string; // MKCOL - Create a directory function MKCOL(const ElementPath: string): boolean; // PROPPATCH - Change the properties of a file or directory // not implemented // LOCK - Zet een slot op het object // not implemented // OPEN - Unlock een bron // not implemented end; procedure ParseWebDavResources(const AXMLStr: string; var Resources: TWDResourceList); implementation uses Dialogs, laz2_XMLRead, laz2_DOM, ufphttphelper {ALWAYS LAST until fphttpclient is fixed}; { TTWebDAVDrive } constructor TWebDAVDrive.Create; begin inherited; end; destructor TWebDAVDrive.Destroy; begin inherited; end; type TSpecials = set of AnsiChar; const URLSpecialChar: TSpecials = [#$00..#$20, '<', '>', '"', '%', '{', '}', '|', '\', '^', '[', ']', '`', #$7F..#$FF]; function TWebDAVDrive.EncodeUTF8URI(const URI: string): string; var i: integer; char: AnsiChar; begin Result := ''; for i := 1 to length(URI) do begin if (URI[i] in URLSpecialChar) then begin for char in UTF8String(URI[i]) do Result := Result + '%' + IntToHex(Ord(char), 2); end else Result := Result + URI[i]; end; end; function TWebDAVDrive.GetRequestURL(const Element: string; EncodePath: boolean): string; var URI: string; WebDavStr: string; begin WebDavStr := StringReplace(cWebDAVServer, '{login}', Login, []); if Length(Element) > 0 then begin URI := Element; if URI[1] = '/' then System.Delete(URI, 1, 1); if EncodePath then Result := WebDavStr + EncodeUTF8URI(URI) else Result := WebDavStr + URI; end else Result := WebDavStr + cWebDAVSubdir; end; function TWebDAVDrive.GET(const ElementHref: string; var Stream: TStream; Callback: TDataEvent): boolean; var URL: string; HTTP: TFPHTTPClient; begin Result := False; if not Assigned(Stream) then exit; URL := GetRequestURL(ElementHref, False); HTTP := TFPHTTPClient.Create(nil); try HTTP.UserName := Login; HTTP.Password := Password; HTTP.RequestHeaders.Add('Accept: */*'); HTTP.RequestHeaders.Add('Connection: Close'); HTTP.OnDataReceived := Callback; try HTTP.Get(URL, Stream); Result := True; except on E: Exception do ShowMessage(E.Message); end; finally HTTP.Free; end; end; function TWebDAVDrive.PUT(const ElementHref: string; var Stream: TStream; Callback: TDataEvent): boolean; var URL, Rs: string; HTTP: TFPHTTPClient; begin Result := False; if not Assigned(Stream) then Exit; URL := GetRequestURL(ElementHref, True); HTTP := TFPHTTPClient.Create(nil); try HTTP.RequestBody := Stream; HTTP.UserName := Login; HTTP.Password := Password; HTTP.RequestHeaders.Add('Accept: */*'); HTTP.RequestHeaders.Add('Content-Type: application/binary'); HTTP.RequestHeaders.Add('Connection: Close'); HTTP.OnDataSent := Callback; Rs := HTTP.Put(URL); // ShowMessage(Rs); // created Result := True; finally HTTP.Free; end; end; function TWebDAVDrive.DELETE(const ElementHref: string): boolean; var HTTP: TFPHTTPClient; SS: TStringStream; begin Result := False; HTTP := TFPHTTPClient.Create(nil); SS := TStringStream.Create(''); try HTTP.UserName := Login; HTTP.Password := Password; HTTP.RequestHeaders.Add('Accept: */*'); HTTP.RequestHeaders.Add('Connection: Close'); HTTP.HTTPMethod('DELETE', GetRequestURL(ElementHref), SS, [204]); Result := True; //Result := SS.Datastring; finally SS.Free; HTTP.Free; end; end; function TWebDAVDrive.MKCOL(const ElementPath: string): boolean; var HTTP: TFPHTTPClient; SS: TStringStream; begin Result := False; HTTP := TFPHTTPClient.Create(nil); SS := TStringStream.Create(''); try HTTP.UserName := Login; HTTP.Password := Password; HTTP.RequestHeaders.Add('Accept: */*'); HTTP.RequestHeaders.Add('Connection: Close'); HTTP.HTTPMethod('MKCOL', GetRequestURL(ElementPath), SS, [201]); //Result := SS.Datastring; finally SS.Free; HTTP.Free; end; end; function TWebDAVDrive.PROPFIND(Depth: integer; const Element: string): string; var HTTP: TFPHTTPClient; SS: TStringStream; begin HTTP := TFPHTTPClient.Create(nil); SS := TStringStream.Create(''); try HTTP.UserName := Login; HTTP.Password := Password; HTTP.RequestHeaders.Add('Accept: */*'); HTTP.RequestHeaders.Add('Connection: Close'); HTTP.RequestHeaders.Add('Depth: ' + IntToStr(Depth)); HTTP.HTTPMethod('PROPFIND', GetRequestURL(Element), SS, [201, 207]); Result := SS.DataString; finally SS.Free; HTTP.Free; end; end; { Support functions } function SeparateLeft(const Value, Delimiter: string): string; var x: integer; begin x := Pos(Delimiter, Value); if x < 1 then Result := Value else Result := Copy(Value, 1, x - 1); end; function SeparateRight(const Value, Delimiter: string): string; var x: integer; begin x := Pos(Delimiter, Value); if x > 0 then x := x + Length(Delimiter) - 1; Result := Copy(Value, x + 1, Length(Value) - x); end; { WebDavResources } procedure ParseWebDavResources(const AXMLStr: string; var Resources: TWDResourceList); var XMLDoc: TXMLDocument; ResponseNode, ChildNode, PropNodeChild, PropertyNode: TDOMNode; s, su, Value: string; procedure ReadXMLString(Value: string); var S: TStringStream; begin S := TStringStream.Create(Value); try ReadXMLFile(XMLDoc, S); finally S.Free; end; end; begin // XMLDoc := TXMLDocument.Create; wordt in ReadXMLString gedaan //Showmessage(AXMLStr); ReadXMLString(AXMLStr); //XMLDoc.LoadFromXML(AXMLStr); try //if not XMLDoc.IsEmptyDoc then begin // Select the first node d: response ResponseNode := XMLDoc.DocumentElement.FirstChild; // ResponseNode:=XMLDoc.DocumentElement.ChildNodes.First; while Assigned(ResponseNode) do begin // Create a new resource record in the list Resources.Add(TWDResource.Create); // Iterate over the child nodes d: response ChildNode := ResponseNode.FirstChild; // ChildNode:=ResponseNode.ChildNodes.First; while Assigned(ChildNode) do begin if ChildNode.NodeName = 'd:href' then Resources.Last.Href := ChildNode.TextContent // .Text else // Find node with the resource properties if ChildNode.NodeName = 'd:propstat' then begin // Select the first child node, usually - it is d: status PropNodeChild := ChildNode.FirstChild; // .First; while Assigned(PropNodeChild) do begin // Read the status code if PropNodeChild.NodeName = 'd:status' then begin Value := PropNodeChild.TextContent; //.Text; s := Trim(SeparateRight(Value, ' ')); su := Trim(SeparateLeft(s, ' ')); Resources.Last.StatusCode := StrToIntDef(su, 0); end else // Find node d: prop - are passed on its child nodes if PropNodeChild.NodeName = 'd:prop' then begin PropertyNode := PropNodeChild.FirstChild; //.First; while Assigned(PropertyNode) do begin if PropertyNode.NodeName = 'd:creationdate' then Resources.Last.CreationDate := 0 // PropertyNode.TextContent not used else if PropertyNode.NodeName = 'd:displayname' then Resources.Last.DisplayName := PropertyNode.TextContent else if PropertyNode.NodeName = 'd:getcontentlength' then Resources.Last.ContentLength := StrToInt64(PropertyNode.TextContent) else if PropertyNode.NodeName = 'd:getlastmodified' then Resources.Last.Lastmodified := 0 // DecodeRfcDateTime(PropertyNode.TextContent) Fri, 15 Jul 2016 08:33:34 GMT else if PropertyNode.NodeName = 'd:resourcetype' then Resources.Last.Collection := PropertyNode.ChildNodes.Count > 0; // Select the next child node have d: prop PropertyNode := PropertyNode.NextSibling; end; end; // Select the next child node have d: propstat PropNodeChild := PropNodeChild.NextSibling; end; end; // Select the next child node have d: response ChildNode := ChildNode.NextSibling; end; // Select the next node d: response ResponseNode := ResponseNode.NextSibling; end; end; finally XMLDoc.Free; XMLDoc := nil; end; end; end.
unit TestMixedModeCaps; { AFS 9 July 2K test local types This code compiles, but is not semantically meaningfull. It is test cases for the code-formating utility directives .. reserved words in one context, not reserved in another They have a standard case when they are reserved, set by user when not } interface type TMixedMode = class(TObject) private fiSafeCall: integer; public { property directive used as procedure name and procedure directive used as property name } property SafeCall: integer Read fiSafeCall WRite fiSafeCall; procedure Read; SafeCall; procedure Write; SAFECall; end; implementation { TMixedMode } procedure TMixedMode.Read; begin // do nothing end; procedure TMixedMode.Write; begin // do nothing end; end.
unit enum_1; interface implementation type TEnum = (v1, v2, v3, v4, v5); var G1, G2: TEnum; procedure Test; begin G1 := v2; G2 := G1; end; initialization Test(); finalization Assert(G1 = V2); Assert(G2 = V2); end.
unit uParserBase; {$I ..\Include\IntXLib.inc} interface uses {$IFDEF DELPHI} Generics.Collections, {$ENDIF DELPHI} Math, SysUtils, uIParser, uStrings, uConstants, uXBits, uIntX, uIntXLibTypes; type /// <summary> /// Base class for parsers. /// Contains default implementations of parse operation over <see cref="TIntX" /> instances. /// </summary> TParserBase = class abstract(TInterfacedObject, IIParser) private /// <summary> /// parser for pow2 case /// </summary> F_pow2Parser: IIParser; public /// <summary> /// Checks if Input Char is WhiteSpace /// </summary> /// <param name="Value">Input Char.</param> class function IsWhiteSpace(const Value: Char): Boolean; inline; static; /// <summary> /// Creates new <see cref="ParserBase" /> instance. /// </summary> /// <param name="pow2Parser">Parser for pow2 case.</param> constructor Create(pow2Parser: IIParser); /// <summary> /// Destructor. /// </summary> destructor Destroy(); override; /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object. /// </summary> /// <param name="value">Number as string.</param> /// <param name="numberBase">Number base.</param> /// <param name="charToDigits">Char->digit dictionary.</param> /// <param name="checkFormat">Check actual format of number (0 or ("$" or "0x") at start).</param> /// <returns>Parsed object.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> /// <exception cref="EArgumentException"><paramref name="numberBase" /> is less then 2 or more then 16.</exception> /// <exception cref="EFormatException"><paramref name="value" /> is not in valid format.</exception> function Parse(const Value: String; numberBase: UInt32; charToDigits: TDictionary<Char, UInt32>; checkFormat: Boolean): TIntX; overload; virtual; /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object. /// </summary> /// <param name="value">Number as string.</param> /// <param name="startIndex">Index inside string from which to start.</param> /// <param name="endIndex">Index inside string on which to end.</param> /// <param name="numberBase">Number base.</param> /// <param name="charToDigits">Char->digit dictionary.</param> /// <param name="digitsRes">Resulting digits.</param> /// <returns>Parsed integer length.</returns> function Parse(const Value: String; startIndex: Integer; endIndex: Integer; numberBase: UInt32; charToDigits: TDictionary<Char, UInt32>; digitsRes: TIntXLibUInt32Array): UInt32; overload; virtual; end; implementation class function TParserBase.IsWhiteSpace(const Value: Char): Boolean; begin Result := Length(Trim(Value)) = 0; end; constructor TParserBase.Create(pow2Parser: IIParser); begin Inherited Create; F_pow2Parser := pow2Parser; end; destructor TParserBase.Destroy(); begin F_pow2Parser := Nil; Inherited Destroy; end; function TParserBase.Parse(const Value: String; numberBase: UInt32; charToDigits: TDictionary<Char, UInt32>; checkFormat: Boolean): TIntX; var startIndex, endIndex, valueLength, matchLength: Integer; negative, stringNotEmpty: Boolean; digitsLength: UInt32; newInt: TIntX; FirstPart, Hold: Char; begin // Exceptions matchLength := 0; if (Value = '') then begin raise EArgumentNilException.Create('value'); end; if (charToDigits = Nil) then begin raise EArgumentNilException.Create('charToDigits'); end; if ((numberBase < UInt32(2)) or (numberBase > UInt32(charToDigits.Count))) then begin raise EArgumentException(uStrings.ParseBaseInvalid + ' numberBase'); end; // Initially determine start and end indices (Trim is too slow) // if Zero-Based Indexed String, use startIndex := 0; startIndex := 1; while ((startIndex < (Length(Value))) and (IsWhiteSpace(Value[startIndex]))) do begin Inc(startIndex); end; // if Zero-Based Indexed String, replace with endIndex := Length(Value) - 1; endIndex := Length(Value); while (((endIndex) >= startIndex) and (IsWhiteSpace(Value[endIndex]))) do begin Dec(endIndex); end; negative := False; // number sign stringNotEmpty := False; // true if string is already guaranteed to // be non-empty // Determine sign and/or base FirstPart := Value[startIndex]; if (FirstPart = '-') then begin negative := True; Inc(matchLength); end else if (FirstPart = '+') then begin negative := False; Inc(matchLength); end; if (FirstPart = '$') or (FirstPart = '0') then begin Hold := Value[startIndex + 1]; if (FirstPart = '$') then begin if (checkFormat) then begin // '$' before the number - this is hex number // Pascal Style numberBase := UInt32(16); Inc(matchLength); end else begin // This is an error raise EFormatException.Create(uStrings.ParseInvalidChar); end end else if ((Hold = 'x') or (Hold = 'X')) then begin if (checkFormat) then begin // '0x' before the number - this is hex number // C Style numberBase := UInt32(16); Inc(matchLength, 2); end else begin // This is an error raise EFormatException.Create(uStrings.ParseInvalidChar); end end else if (FirstPart = '0') then begin if (checkFormat) then begin // 0 before the number - this is octal number numberBase := UInt32(8); Inc(matchLength); end else begin // This is an error raise EFormatException.Create(uStrings.ParseInvalidChar); end; stringNotEmpty := True; end end; // Skip leading sign and format startIndex := startIndex + matchLength; // If at this stage string is empty, this may mean an error if ((startIndex > endIndex) and (not stringNotEmpty)) then begin raise EFormatException.Create(uStrings.ParseNoDigits); end; // Iterate through string and skip all leading zeroes while ((startIndex <= (endIndex)) and (Value[startIndex] = '0')) do begin Inc(startIndex); end; // Return zero if length is zero if (startIndex > endIndex) then begin Result := TIntX.Create(0); Exit; end; // Determine length of new digits array and create new TIntX object with given length valueLength := endIndex - startIndex + 1; digitsLength := UInt32(Ceil(Ln(numberBase) / TConstants.DigitBaseLog * valueLength)); newInt := TIntX.Create(digitsLength, negative); // Now we have only (in)valid string which consists from numbers only. // Parse it newInt._length := Parse(Value, startIndex, endIndex, numberBase, charToDigits, newInt._digits); Result := newInt; end; function TParserBase.Parse(const Value: String; startIndex: Integer; endIndex: Integer; numberBase: UInt32; charToDigits: TDictionary<Char, UInt32>; digitsRes: TIntXLibUInt32Array): UInt32; begin // Default implementation - always call pow2 parser if numberBase is pow of 2 if numberBase = UInt32(1) shl TBits.Msb(numberBase) then begin Result := F_pow2Parser.Parse(Value, startIndex, endIndex, numberBase, charToDigits, digitsRes); Exit; end else begin Result := 0; Exit; end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {*******************************************************} { Helpers for C++ JSON binding. } {*******************************************************} unit System.Internal.JSONHlpr; {$WEAKPACKAGEUNIT} {$HPPEMIT NOUSINGNAMESPACE} interface uses System.Json; procedure InitInstantiations(I: Integer); implementation uses System.SysUtils; type TJSONHlpr = class class function HelperGetValue<T>(JV: TJSONValue; const APath: string; const AValue: T): T; static; end; class function TJSONHlpr.HelperGetValue<T>(JV: TJSONValue; const APath: string; const AValue: T): T; var Val: T; begin Val := AValue; if JV.TryGetValue(APath, Val) then Val := JV.GetValue<T>(APath, Val) else if JV.TryGetValue<T>(Val) then Val := JV.GetValue<T>(APath); Result := Val; end; var g_JSONArray: TJSONArray; g_JSONObject: TJSONObject; function JSONGetValue(JSONVal: TJSONValue; const APath: string; I: Integer; const ADefaultValue: Variant): Variant; begin Result := ADefaultValue; if JSONVal = nil then Exit; case I of 0: Result := TJSONHlpr.HelperGetValue<string>(JSONVal, APath, string('')); {$IFNDEF NEXTGEN} 1: Result := TJSONHlpr.HelperGetValue<AnsiChar>(JSONVal, APath, AnsiChar(0)); 2: Result := TJSONHlpr.HelperGetValue<WideString>(JSONVal, APath, WideString('')); 3: Result := TJSONHlpr.HelperGetValue<AnsiString>(JSONVal, APath, AnsiString('')); {$ENDIF} 4: Result := TJSONHlpr.HelperGetValue<UTF8String>(JSONVal, APath, UTF8String('')); 5: Result := TJSONHlpr.HelperGetValue<Cardinal>(JSONVal, APath, Cardinal(0)); 6: Result := TJSONHlpr.HelperGetValue<Integer>(JSONVal, APath, 0); 7: Result := TJSONHlpr.HelperGetValue<ShortInt>(JSONVal, APath, ShortInt(0)); 8: Result := TJSONHlpr.HelperGetValue<Word>(JSONVal, APath, Word(0)); 9: Result := TJSONHlpr.HelperGetValue<Byte>(JSONVal, APath, Byte(0)); 10: Result := TJSONHlpr.HelperGetValue<SmallInt>(JSONVal, APath, SmallInt(0)); 11: Result := TJSONHlpr.HelperGetValue<Char>(JSONVal, APath, Char(0)); 12: Result := TJSONHlpr.HelperGetValue<Boolean>(JSONVal, APath, False); 13: Result := TJSONHlpr.HelperGetValue<WideChar>(JSONVal, APath, WideChar(0)); 14: Result := TJSONHlpr.HelperGetValue<Real>(JSONVal, APath, Real(0.0)); 15: Result := TJSONHlpr.HelperGetValue<Double>(JSONVal, APath, Double(0.0)); 16: Result := TJSONHlpr.HelperGetValue<Extended>(JSONVal, APath, Extended(0.0)); 17: Result := TJSONHlpr.HelperGetValue<Int64>(JSONVal, APath, Int64(0)); 18: Result := TJSONHlpr.HelperGetValue<UInt64>(JSONVal, APath, UInt64(0)); 19: Result := TJSONHlpr.HelperGetValue<Currency>(JSONVal, APath, Currency(0)); 20: Result := TJSONHlpr.HelperGetValue<TDateTime>(JSONVal, APath, Now); 21: TJSONHlpr.HelperGetValue<TJSONArray>(JSONVal, APath, g_JSONArray); 22: TJSONHlpr.HelperGetValue<TJSONObject>(JSONVal, APath, g_JSONObject); end; end; procedure InitInstantiations(I: Integer); begin JSONGetValue(nil, '', I, ''); end; end.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {*******************************************************} { XML RTL Constants } {*******************************************************} unit Xml.XMLConst; interface {$HPPEMIT LEGACYHPP} const XmlDecimalSeparator = '.'; resourcestring { xmldom.pas } SDuplicateRegistration = '"%s" DOMImplementation already registered'; SNoMatchingDOMVendor = 'No matching DOM Vendor: "%s"'; SNoDOMNodeEx = 'Selected DOM Vendor does not support this property or method'; SDOMNotSupported = 'Property or Method "%s" is not supported by DOM Vendor "%s"'; SNoDOMVendorSelected = 'No selected DOM Vendor'; { msxmldom.pas } SNodeExpected = 'Node cannot be null'; SMSDOMNotInstalled = 'Microsoft MSXML is not installed'; { oxmldom.pas } {$IFDEF MSWINDOWS} SErrorDownloadingURL = 'Error downloading URL: %s'; SUrlMonDllMissing = 'Unable to load %s'; {$ENDIF} SNotImplemented = 'This property or method is not implemented in the Open XML Parser'; { XMLDoc.pas } SNotActive = 'No active document'; SNodeNotFound = 'Node "%s" not found'; SMissingNode = 'IDOMNode required'; SNoAttributes = 'Attributes are not supported on this node type'; SInvalidNodeType = 'Invalid node type'; SMismatchedRegItems = 'Mismatched paramaters to RegisterChildNodes'; SNotSingleTextNode = 'Element "%s" does not contain a single text node'; SNoDOMParseOptions = 'DOM Implementation does not support IDOMParseOptions'; SNotOnHostedNode = 'Invalid operation on a hosted node'; SMissingItemTag = 'ItemTag property is not initialized'; SNodeReadOnly = 'Node is readonly'; SUnsupportedEncoding = 'Unsupported character encoding "%s", try using LoadFromFile'; SNoRefresh = 'Refresh is only supported if the FileName or XML properties are set'; SMissingFileName = 'FileName cannot be blank'; SLine = 'Line'; SUnknown = 'Unknown'; { XMLSchema.pas } SInvalidSchema = 'Invalid or unsupported XML Schema document'; SNoLocalTypeName = 'Local type declarations cannot have a name. Element: %s'; SUnknownDataType = 'Unknown datatype "%s"'; SInvalidValue = 'Invalid %s value: "%s"'; SInvalidGroupDecl = 'Invalid group declaration in "%s"'; SMissingName = 'Missing Type name'; SInvalidDerivation = 'Invalid complex type derivation: %s'; SNoNameOnRef = 'Name not allowed on a ref item'; SNoGlobalRef = 'Global schema items may not contain a ref'; SNoRefPropSet = '%s cannot be set on a ref item'; SSetGroupRefProp = 'Set the GroupRef property for the cmGroupRef content model'; SNoContentModel = 'ContentModel not set'; SNoFacetsAllowed = 'Facets and Enumeration not allowed on this kind of datatype "%s"'; SNotBuiltInType = 'Invalid built-in type name "%s"'; SInvalidTargetNS = 'Included schema file "%s" has an invalid targetNamespace.' + sLineBreak + sLineBreak + 'Expected: %s' + sLineBreak + 'Found: %s'; SUndefinedTargetNS = 'No targetNamespace attribute'; SBuiltInType = 'Built-in Type'; { XMLDataToSchema.pas } SXMLDataTransDesc = 'XMLData to XML Schema Translator (.xml -> .xsd)'; { XMLSchema99.pas } S99TransDesc = '1999 XML Schema Translator (.xsd <-> .xsd)'; { DTDSchema.pas } SDTDTransDesc = 'DTD to XML Schema Translator (.dtd <-> .xsd)'; { XDRSchema.pas } SXDRTransDesc = 'XDR to XML Schema Translator (.xdr <-> .xsd)'; { Xml.Internal.WideStringUtils } // TUtilsWideStringStream error reports SCannotReadOddPos = 'Cannot Read WideString from odd byte position'; SCannotWriteOddPos = 'Cannot Write WideString to odd byte position'; SCapacityLessSize = 'Capacity cannot be less than size'; SOddSizeInvalid = 'Odd size not valid for WideString'; SNegativeSizeInvalid = 'Negative stream size invalid'; SOddPosInvalid = 'Odd byte position not valid for WideString'; // TUtilsNameValueTree error reports SInuse = 'Child name-value tree is in use elsewhere'; SCircularReference = 'Circular references are not allowed'; // TUtilsCustomWideStr error reports SInvalidCodePoint = '%d is not a valid ISO-10646-UCS4 code point'; // TUtilsWideStringList error reports SNoDuplicatesAllowed = 'String list does not allow duplicates'; SIndexOutOfBounds = 'List Index out of bounds (%d)'; SOnlyWhenSorted = 'Operation not allowed on Sorted string list'; { Xml.Internal.TreeUtils } SHierarchyRequestError = 'Hierarchy Request Error'; SListIndexError = 'List index out of bounds (%d)'; SNoModificationAllowedError = 'No Modification Allowed Error'; SNotAssignedError = 'Parameter Node Not Assigned Error'; SNotFoundError = 'Node Not Found Error.'; SWrongOwnerError = 'Wrong Owner Error'; { Xml.Internal.ParserUtilsWin32 } SByteOrderMarkMismatch = 'Specified input encoding does not match byte order mark.'; SDefaultEncodingNotSpecified = 'Default Encoding not specified.'; SEncodingNotSupported = 'Character encoding scheme not supported.'; SInputEncodingNotSpecified = 'Input Encoding not specified.'; SOutputEncodingNotSpecified = 'Output Encoding not specified.'; SStreamNotSpecified = 'Stream not specified.'; { Xml.Internal.EncodingUtils } SIndexOutOfRange = 'Index out of range'; { Xml.Internal.CodecUtilsWin32 } SCannotConvert = 'Unicode code point $%x has no equivalent in %s'; SCannotConvertUCS4 = 'Cannot convert $%8.8X to %s'; SHighSurrogateNotFound = 'High surrogate not found'; SInvalidCodePointPar = '$%x is not a valid %s code point'; SInvalidEncoding = 'Invalid %s encoding'; SLowSurrogateNotFound = 'Low surrogate not found'; SSurrogateNotAllowed = 'Surrogate value $%x found in %s. Values between $D800 and $DFFF are reserved for use with UTF-16'; SEncodingOutOfRange = '%s encoding out of range'; SUTF8Error = 'UTF-8 error %d'; sReason = 'Reason: %s' + sLineBreak; sLinePosError = 'Error on line %d, position %d'; sXMLParseError = 'XML Parse Error:' + sLineBreak; SMissingSourceFile = 'XMLDataFile must be specified'; SMissingTransform = 'TransformationFile must be specified'; SOldVersion = 'Version of Transformation File not supported'; implementation end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, Menus, ActnList, Game; type TFormMain = class(TForm) Tile1: TPanel; Tile2: TPanel; Tile3: TPanel; Tile4: TPanel; Tile5: TPanel; Tile6: TPanel; Tile7: TPanel; Tile8: TPanel; Tile9: TPanel; Tile10: TPanel; Tile11: TPanel; Tile12: TPanel; Tile13: TPanel; Tile14: TPanel; Tile15: TPanel; Tile16: TPanel; MainMenu: TMainMenu; MenuItemGame: TMenuItem; MenuItemHelp: TMenuItem; MenuItemAbout: TMenuItem; StatusBar: TStatusBar; MenuItemReset: TMenuItem; MenuItemExit: TMenuItem; ActionList: TActionList; ActionAbout: TAction; ActionExit: TAction; ActionReset: TAction; MenuItemSep1: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DrawBoard; procedure DrawTile(Tile: TTile; Panel: TPanel); procedure ActionResetExecute(Sender: TObject); procedure ActionExitExecute(Sender: TObject); procedure ActionAboutExecute(Sender: TObject); private MGame: TGame; end; var FormMain: TFormMain; implementation {$R *.dfm} const TileColors: array[0..11, 0..1] of TColor = ( (clBtnFace, clWindowText), (TColor($DAE4EE), TColor($656E77)), (TColor($C8E0ED), TColor($656E77)), (TColor($79B1F2), TColor($F2F6F9)), (TColor($6395F5), TColor($F2F6F9)), (TColor($5F7CF6), TColor($F2F6F9)), (TColor($3B5EF6), TColor($F2F6F9)), (TColor($72CFED), TColor($F2F6F9)), (TColor($61CCED), TColor($F2F6F9)), (TColor($50C8ED), TColor($F2F6F9)), (TColor($3FC5ED), TColor($F2F6F9)), (TColor($2EC2ED), TColor($F2F6F9)) ); procedure TFormMain.FormCreate(Sender: TObject); begin MGame := TGame.Create; DrawBoard; end; procedure TFormMain.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin MGame.KeyDown(Key); DrawBoard; end; procedure TFormMain.DrawBoard; begin DrawTile(MGame.Board[0, 0], Tile1); DrawTile(MGame.Board[1, 0], Tile2); DrawTile(MGame.Board[2, 0], Tile3); DrawTile(MGame.Board[3, 0], Tile4); DrawTile(MGame.Board[0, 1], Tile5); DrawTile(MGame.Board[1, 1], Tile6); DrawTile(MGame.Board[2, 1], Tile7); DrawTile(MGame.Board[3, 1], Tile8); DrawTile(MGame.Board[0, 2], Tile9); DrawTile(MGame.Board[1, 2], Tile10); DrawTile(MGame.Board[2, 2], Tile11); DrawTile(MGame.Board[3, 2], Tile12); DrawTile(MGame.Board[0, 3], Tile13); DrawTile(MGame.Board[1, 3], Tile14); DrawTile(MGame.Board[2, 3], Tile15); DrawTile(MGame.Board[3, 3], Tile16); StatusBar.Panels[0].Text := 'Score: ' + IntToStr(MGame.Score); end; function Log2(Number: Integer): Integer; asm bsr eax, eax end; procedure TFormMain.DrawTile(Tile: TTile; Panel: TPanel); var ColorIndex: Integer; begin if Tile.Value = 0 then Panel.Caption := '' else Panel.Caption := IntToStr(Tile.Value); ColorIndex := Log2(Tile.Value); Panel.Color := TileColors[ColorIndex, 0]; Panel.Font.Color := TileColors[ColorIndex, 1]; end; procedure TFormMain.ActionResetExecute(Sender: TObject); begin MGame.Reset; DrawBoard; end; procedure TFormMain.ActionExitExecute(Sender: TObject); begin Close; end; procedure TFormMain.ActionAboutExecute(Sender: TObject); begin ShowMessage('T2046' + #13#10 + 'Version 1.0'); end; end.
{****************************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 2010-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {****************************************************************} { Delphi-Objective-C Bridge } { Interfaces for Cocoa framework CoreMedia } { } { Copyright 2010-2012 Apple Inc. All rights reserved. } { } { Translator: Embarcadero Technologies, Inc. } { Copyright (c) 2012-2019 Embarcadero Technologies, Inc. } {****************************************************************} unit Macapi.CoreMedia; interface uses Posix.StdDef, Macapi.ObjCRuntime, Macapi.ObjectiveC, Macapi.CocoaTypes, Macapi.Foundation, Macapi.CoreFoundation; const kCMAttachmentMode_ShouldNotPropagate = 0; kCMAttachmentMode_ShouldPropagate = 1; kCMAudioCodecType_AAC_AudibleProtected = 1633771875; kCMAudioCodecType_AAC_LCProtected = 1885430115; kCMAudioFormatDescriptionMask_All = 15; kCMAudioFormatDescriptionMask_ChannelLayout = 4; kCMAudioFormatDescriptionMask_Extensions = 8; kCMAudioFormatDescriptionMask_MagicCookie = 2; kCMAudioFormatDescriptionMask_StreamBasicDescription = 1; kCMBlockBufferAlwaysCopyDataFlag = 2; kCMBlockBufferAssureMemoryNowFlag = 1; kCMBlockBufferBadCustomBlockSourceErr = -12702; kCMBlockBufferBadLengthParameterErr = -12704; kCMBlockBufferBadOffsetParameterErr = -12703; kCMBlockBufferBadPointerParameterErr = -12705; kCMBlockBufferBlockAllocationFailedErr = -12701; kCMBlockBufferCustomBlockSourceVersion = 0; kCMBlockBufferDontOptimizeDepthFlag = 4; kCMBlockBufferEmptyBBufErr = -12706; kCMBlockBufferNoErr = 0; kCMBlockBufferPermitEmptyReferenceFlag = 8; kCMBlockBufferStructureAllocationFailedErr = -12700; kCMBlockBufferUnallocatedBlockErr = -12707; kCMBufferQueueError_AllocationFailed = -12760; kCMBufferQueueError_BadTriggerDuration = -12765; kCMBufferQueueError_CannotModifyQueueFromTriggerCallback = -12766; kCMBufferQueueError_EnqueueAfterEndOfData = -12763; kCMBufferQueueError_InvalidBuffer = -12769; kCMBufferQueueError_InvalidCMBufferCallbacksStruct = -12762; kCMBufferQueueError_InvalidTriggerCondition = -12767; kCMBufferQueueError_InvalidTriggerToken = -12768; kCMBufferQueueError_QueueIsFull = -12764; kCMBufferQueueError_RequiredParameterMissing = -12761; kCMBufferQueueTrigger_WhenBufferCountBecomesGreaterThan = 11; kCMBufferQueueTrigger_WhenBufferCountBecomesLessThan = 10; kCMBufferQueueTrigger_WhenDataBecomesReady = 7; kCMBufferQueueTrigger_WhenDurationBecomesGreaterThan = 3; kCMBufferQueueTrigger_WhenDurationBecomesGreaterThanOrEqualTo = 4; kCMBufferQueueTrigger_WhenDurationBecomesLessThan = 1; kCMBufferQueueTrigger_WhenDurationBecomesLessThanOrEqualTo = 2; kCMBufferQueueTrigger_WhenEndOfDataReached = 8; kCMBufferQueueTrigger_WhenMaxPresentationTimeStampChanges = 6; kCMBufferQueueTrigger_WhenMinPresentationTimeStampChanges = 5; kCMBufferQueueTrigger_WhenReset = 9; kCMClosedCaptionFormatType_ATSC = 1635017571; kCMClosedCaptionFormatType_CEA608 = 1664495672; kCMClosedCaptionFormatType_CEA708 = 1664561208; kCMFormatDescriptionError_AllocationFailed = -12711; kCMFormatDescriptionError_InvalidParameter = -12710; kCMMPEG2VideoProfile_HDV_1080i50 = 1751414323; kCMMPEG2VideoProfile_HDV_1080i60 = 1751414322; kCMMPEG2VideoProfile_HDV_1080p24 = 1751414326; kCMMPEG2VideoProfile_HDV_1080p25 = 1751414327; kCMMPEG2VideoProfile_HDV_1080p30 = 1751414328; kCMMPEG2VideoProfile_HDV_720p24 = 1751414324; kCMMPEG2VideoProfile_HDV_720p25 = 1751414325; kCMMPEG2VideoProfile_HDV_720p30 = 1751414321; kCMMPEG2VideoProfile_HDV_720p50 = 1751414369; kCMMPEG2VideoProfile_HDV_720p60 = 1751414329; kCMMPEG2VideoProfile_XDCAM_EX_1080i50_VBR35 = 2019849827; kCMMPEG2VideoProfile_XDCAM_EX_1080i60_VBR35 = 2019849826; kCMMPEG2VideoProfile_XDCAM_EX_1080p24_VBR35 = 2019849828; kCMMPEG2VideoProfile_XDCAM_EX_1080p25_VBR35 = 2019849829; kCMMPEG2VideoProfile_XDCAM_EX_1080p30_VBR35 = 2019849830; kCMMPEG2VideoProfile_XDCAM_EX_720p24_VBR35 = 2019849780; kCMMPEG2VideoProfile_XDCAM_EX_720p25_VBR35 = 2019849781; kCMMPEG2VideoProfile_XDCAM_EX_720p30_VBR35 = 2019849777; kCMMPEG2VideoProfile_XDCAM_EX_720p50_VBR35 = 2019849825; kCMMPEG2VideoProfile_XDCAM_EX_720p60_VBR35 = 2019849785; kCMMPEG2VideoProfile_XDCAM_HD422_1080i50_CBR50 = 2019833187; kCMMPEG2VideoProfile_XDCAM_HD422_1080i60_CBR50 = 2019833186; kCMMPEG2VideoProfile_XDCAM_HD422_1080p24_CBR50 = 2019833188; kCMMPEG2VideoProfile_XDCAM_HD422_1080p25_CBR50 = 2019833189; kCMMPEG2VideoProfile_XDCAM_HD422_1080p30_CBR50 = 2019833190; kCMMPEG2VideoProfile_XDCAM_HD422_540p = 2019846194; kCMMPEG2VideoProfile_XDCAM_HD422_720p24_CBR50 = 2019833140; kCMMPEG2VideoProfile_XDCAM_HD422_720p25_CBR50 = 2019833141; kCMMPEG2VideoProfile_XDCAM_HD422_720p30_CBR50 = 2019833137; kCMMPEG2VideoProfile_XDCAM_HD422_720p50_CBR50 = 2019833185; kCMMPEG2VideoProfile_XDCAM_HD422_720p60_CBR50 = 2019833145; kCMMPEG2VideoProfile_XDCAM_HD_1080i50_VBR35 = 2019849779; kCMMPEG2VideoProfile_XDCAM_HD_1080i60_VBR35 = 2019849778; kCMMPEG2VideoProfile_XDCAM_HD_1080p24_VBR35 = 2019849782; kCMMPEG2VideoProfile_XDCAM_HD_1080p25_VBR35 = 2019849783; kCMMPEG2VideoProfile_XDCAM_HD_1080p30_VBR35 = 2019849784; kCMMPEG2VideoProfile_XDCAM_HD_540p = 2019846244; kCMMediaType_Audio = 'soun'; kCMMediaType_ClosedCaption = 'clcp'; kCMMediaType_Muxed = 'muxx'; kCMMediaType_Subtitle = 'sbtl'; kCMMediaType_Text = 'text'; kCMMediaType_TimeCode = 'tmcd'; kCMMediaType_TimedMetadata = 'tmet'; kCMMediaType_Video = 'vide'; kCMMuxedStreamType_DV = 'dv '; kCMMuxedStreamType_MPEG1System = 'mp1s'; kCMMuxedStreamType_MPEG2Program = 'mp2p'; kCMMuxedStreamType_MPEG2Transport = 'mp2t'; kCMPersistentTrackID_Invalid = 0; kCMPixelFormat_16BE555 = 16; kCMPixelFormat_16BE565 = 1110783541; kCMPixelFormat_16LE555 = 1278555445; kCMPixelFormat_16LE5551 = 892679473; kCMPixelFormat_16LE565 = 1278555701; kCMPixelFormat_24RGB = 24; kCMPixelFormat_32ARGB = 32; kCMPixelFormat_32BGRA = 1111970369; kCMPixelFormat_422YpCbCr10 = 1983000880; kCMPixelFormat_422YpCbCr16 = 1983000886; kCMPixelFormat_422YpCbCr8 = 846624121; kCMPixelFormat_422YpCbCr8_yuvs = 2037741171; kCMPixelFormat_4444YpCbCrA8 = 1983131704; kCMPixelFormat_444YpCbCr10 = 1983131952; kCMPixelFormat_444YpCbCr8 = 1983066168; kCMPixelFormat_8IndexedGray_WhiteIsZero = 40; kCMSampleBufferError_AllocationFailed = -12730; kCMSampleBufferError_AlreadyHasDataBuffer = -12732; kCMSampleBufferError_ArrayTooSmall = -12737; kCMSampleBufferError_BufferHasNoSampleSizes = -12735; kCMSampleBufferError_BufferHasNoSampleTimingInfo = -12736; kCMSampleBufferError_BufferNotReady = -12733; kCMSampleBufferError_CannotSubdivide = -12739; kCMSampleBufferError_InvalidEntryCount = -12738; kCMSampleBufferError_InvalidMediaFormat = -12743; kCMSampleBufferError_InvalidMediaTypeForOperation = -12741; kCMSampleBufferError_InvalidSampleData = -12742; kCMSampleBufferError_Invalidated = -12744; kCMSampleBufferError_RequiredParameterMissing = -12731; kCMSampleBufferError_SampleIndexOutOfRange = -12734; kCMSampleBufferError_SampleTimingInfoInvalid = -12740; kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment = 1; kCMSimpleQueueError_AllocationFailed = -12770; kCMSimpleQueueError_ParameterOutOfRange = -12772; kCMSimpleQueueError_QueueIsFull = -12773; kCMSimpleQueueError_RequiredParameterMissing = -12771; kCMTextDisplayFlag_allSubtitlesForced = 2147483648; kCMTextDisplayFlag_continuousKaraoke = 2048; kCMTextDisplayFlag_fillTextRegion = 262144; kCMTextDisplayFlag_forcedSubtitlesPresent = 1073741824; kCMTextDisplayFlag_scrollDirectionMask = 384; kCMTextDisplayFlag_scrollDirection_bottomToTop = 0; kCMTextDisplayFlag_scrollDirection_leftToRight = 384; kCMTextDisplayFlag_scrollDirection_rightToLeft = 128; kCMTextDisplayFlag_scrollDirection_topToBottom = 256; kCMTextDisplayFlag_scrollIn = 32; kCMTextDisplayFlag_scrollOut = 64; kCMTextDisplayFlag_writeTextVertically = 131072; kCMTextFormatType_3GText = 1954034535; kCMTextFormatType_QTText = 1952807028; kCMTextJustification_bottom_right = -1; kCMTextJustification_centered = 1; kCMTextJustification_left_top = 0; kCMTimeCodeFlag_24HourMax = 2; kCMTimeCodeFlag_DropFrame = 1; kCMTimeCodeFlag_NegTimesOK = 4; kCMTimeCodeFormatType_Counter32 = 'cn32'; kCMTimeCodeFormatType_Counter64 = 'cn64'; kCMTimeCodeFormatType_TimeCode32 = 'tmcd'; kCMTimeCodeFormatType_TimeCode64 = 'tc64'; kCMTimeFlags_HasBeenRounded = 2; kCMTimeFlags_ImpliedValueFlagsMask = 28; kCMTimeFlags_Indefinite = 16; kCMTimeFlags_NegativeInfinity = 8; kCMTimeFlags_PositiveInfinity = 4; kCMTimeFlags_Valid = 1; kCMTimeMaxTimescale = 2147483647; kCMTimeRoundingMethod_Default = 1; kCMTimeRoundingMethod_QuickTime = 4; kCMTimeRoundingMethod_RoundAwayFromZero = 3; kCMTimeRoundingMethod_RoundHalfAwayFromZero = 1; kCMTimeRoundingMethod_RoundTowardNegativeInfinity = 6; kCMTimeRoundingMethod_RoundTowardPositiveInfinity = 5; kCMTimeRoundingMethod_RoundTowardZero = 2; kCMTimedMetadataFormatType_Boxed = 'mebx'; kCMTimedMetadataFormatType_ICY = 'icy '; kCMTimedMetadataFormatType_ID3 = 'id3 '; kCMVideoCodecType_422YpCbCr8 = kCMPixelFormat_422YpCbCr8; kCMVideoCodecType_Animation = 'rle '; kCMVideoCodecType_AppleProRes422 = 'apcn'; kCMVideoCodecType_AppleProRes422HQ = 'apch'; kCMVideoCodecType_AppleProRes422LT = 'apcs'; kCMVideoCodecType_AppleProRes422Proxy = 'apco'; kCMVideoCodecType_AppleProRes4444 = 'ap4h'; kCMVideoCodecType_Cinepak = 'cvid'; kCMVideoCodecType_DVCNTSC = 'dvc '; kCMVideoCodecType_DVCPAL = 'dvcp'; kCMVideoCodecType_DVCPROHD1080i50 = 'dvh5'; kCMVideoCodecType_DVCPROHD1080i60 = 'dvh6'; kCMVideoCodecType_DVCPROHD1080p25 = 'dvh2'; kCMVideoCodecType_DVCPROHD1080p30 = 'dvh3'; kCMVideoCodecType_DVCPROHD720p50 = 'dvhq'; kCMVideoCodecType_DVCPROHD720p60 = 'dvhp'; kCMVideoCodecType_DVCPro50NTSC = 'dv5n'; kCMVideoCodecType_DVCPro50PAL = 'dv5p'; kCMVideoCodecType_DVCProPAL = 'dvpp'; kCMVideoCodecType_H263 = 'h263'; kCMVideoCodecType_H264 = 'avc1'; kCMVideoCodecType_JPEG = 'jpeg'; kCMVideoCodecType_JPEG_OpenDML = 'dmb1'; kCMVideoCodecType_MPEG1Video = 'mp1v'; kCMVideoCodecType_MPEG2Video = 'mp2v'; kCMVideoCodecType_MPEG4Video = 'mp4v'; kCMVideoCodecType_SorensonVideo = 'SVQ1'; kCMVideoCodecType_SorensonVideo3 = 'SVQ3'; type CMClockRef = Pointer; CMTimebaseRef = Pointer; // ===== External functions ===== const libCoreMedia = '/System/Library/Frameworks/CoreMedia.framework/CoreMedia'; function CMAudioFormatDescriptionCreate(allocator: CFAllocatorRef; asbd: PAudioStreamBasicDescription; layoutSize: size_t; layout: PAudioChannelLayout; magicCookieSize: size_t; magicCookie: Pointer; extensions: CFDictionaryRef; outDesc: PCMAudioFormatDescriptionRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMAudioFormatDescriptionCreate'; function CMAudioFormatDescriptionCreateSummary(allocator: CFAllocatorRef; formatDescriptionArray: CFArrayRef; flags: UInt32; summaryFormatDescriptionOut: PCMAudioFormatDescriptionRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMAudioFormatDescriptionCreateSummary'; function CMAudioFormatDescriptionEqual(desc1: CMAudioFormatDescriptionRef; desc2: CMAudioFormatDescriptionRef; equalityMask: CMAudioFormatDescriptionMask; equalityMaskOut: PCMAudioFormatDescriptionMask): Boolean; cdecl; external libCoreMedia name _PU + 'CMAudioFormatDescriptionEqual'; function CMAudioFormatDescriptionGetChannelLayout(desc: CMAudioFormatDescriptionRef; layoutSize: Psize_t): PAudioChannelLayout; cdecl; external libCoreMedia name _PU + 'CMAudioFormatDescriptionGetChannelLayout'; function CMAudioFormatDescriptionGetFormatList(desc: CMAudioFormatDescriptionRef; formatListSize: Psize_t): PAudioFormatListItem; cdecl; external libCoreMedia name _PU + 'CMAudioFormatDescriptionGetFormatList'; function CMAudioFormatDescriptionGetMagicCookie(desc: CMAudioFormatDescriptionRef; cookieSizeOut: Psize_t): Pointer; cdecl; external libCoreMedia name _PU + 'CMAudioFormatDescriptionGetMagicCookie'; function CMAudioFormatDescriptionGetMostCompatibleFormat(desc: CMAudioFormatDescriptionRef): PAudioFormatListItem; cdecl; external libCoreMedia name _PU + 'CMAudioFormatDescriptionGetMostCompatibleFormat'; function CMAudioFormatDescriptionGetRichestDecodableFormat(desc: CMAudioFormatDescriptionRef): PAudioFormatListItem; cdecl; external libCoreMedia name _PU + 'CMAudioFormatDescriptionGetRichestDecodableFormat'; function CMAudioFormatDescriptionGetStreamBasicDescription(desc: CMAudioFormatDescriptionRef): PAudioStreamBasicDescription; cdecl; external libCoreMedia name _PU + 'CMAudioFormatDescriptionGetStreamBasicDescription'; function CMAudioSampleBufferCreateWithPacketDescriptions(allocator: CFAllocatorRef; dataBuffer: CMBlockBufferRef; dataReady: Boolean; makeDataReadyCallback: CMSampleBufferMakeDataReadyCallback; makeDataReadyRefcon: Pointer; formatDescription: CMFormatDescriptionRef; numSamples: CMItemCount; sbufPTS: CMTime; packetDescriptions: PAudioStreamPacketDescription; sBufOut: PCMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMAudioSampleBufferCreateWithPacketDescriptions'; function CMBlockBufferAccessDataBytes(theBuffer: CMBlockBufferRef; offset: size_t; length: size_t; temporaryBlock: Pointer; returnedPointer: Pchar): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferAccessDataBytes'; function CMBlockBufferAppendBufferReference(theBuffer: CMBlockBufferRef; targetBBuf: CMBlockBufferRef; offsetToData: size_t; dataLength: size_t; flags: CMBlockBufferFlags): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferAppendBufferReference'; function CMBlockBufferAppendMemoryBlock(theBuffer: CMBlockBufferRef; memoryBlock: Pointer; blockLength: size_t; blockAllocator: CFAllocatorRef; customBlockSource: PCMBlockBufferCustomBlockSource; offsetToData: size_t; dataLength: size_t; flags: CMBlockBufferFlags): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferAppendMemoryBlock'; function CMBlockBufferAssureBlockMemory(theBuffer: CMBlockBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferAssureBlockMemory'; function CMBlockBufferCopyDataBytes(theSourceBuffer: CMBlockBufferRef; offsetToData: size_t; dataLength: size_t; destination: Pointer): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferCopyDataBytes'; function CMBlockBufferCreateContiguous(structureAllocator: CFAllocatorRef; sourceBuffer: CMBlockBufferRef; blockAllocator: CFAllocatorRef; customBlockSource: PCMBlockBufferCustomBlockSource; offsetToData: size_t; dataLength: size_t; flags: CMBlockBufferFlags; newBBufOut: PCMBlockBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferCreateContiguous'; function CMBlockBufferCreateEmpty(structureAllocator: CFAllocatorRef; subBlockCapacity: UInt32; flags: CMBlockBufferFlags; newBBufOut: PCMBlockBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferCreateEmpty'; function CMBlockBufferCreateWithBufferReference(structureAllocator: CFAllocatorRef; targetBuffer: CMBlockBufferRef; offsetToData: size_t; dataLength: size_t; flags: CMBlockBufferFlags; newBBufOut: PCMBlockBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferCreateWithBufferReference'; function CMBlockBufferCreateWithMemoryBlock(structureAllocator: CFAllocatorRef; memoryBlock: Pointer; blockLength: size_t; blockAllocator: CFAllocatorRef; customBlockSource: PCMBlockBufferCustomBlockSource; offsetToData: size_t; dataLength: size_t; flags: CMBlockBufferFlags; newBBufOut: PCMBlockBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferCreateWithMemoryBlock'; function CMBlockBufferFillDataBytes(fillByte: char; destinationBuffer: CMBlockBufferRef; offsetIntoDestination: size_t; dataLength: size_t): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferFillDataBytes'; function CMBlockBufferGetDataLength(theBuffer: CMBlockBufferRef): size_t; cdecl; external libCoreMedia name _PU + 'CMBlockBufferGetDataLength'; function CMBlockBufferGetDataPointer(theBuffer: CMBlockBufferRef; offset: size_t; lengthAtOffset: Psize_t; totalLength: Psize_t; dataPointer: Pchar): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferGetDataPointer'; function CMBlockBufferGetTypeID: CFTypeID; cdecl; external libCoreMedia name _PU + 'CMBlockBufferGetTypeID'; function CMBlockBufferIsEmpty(theBuffer: CMBlockBufferRef): Boolean; cdecl; external libCoreMedia name _PU + 'CMBlockBufferIsEmpty'; function CMBlockBufferIsRangeContiguous(theBuffer: CMBlockBufferRef; offset: size_t; length: size_t): Boolean; cdecl; external libCoreMedia name _PU + 'CMBlockBufferIsRangeContiguous'; function CMBlockBufferReplaceDataBytes(sourceBytes: Pointer; destinationBuffer: CMBlockBufferRef; offsetIntoDestination: size_t; dataLength: size_t): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBlockBufferReplaceDataBytes'; function CMBufferQueueCallForEachBuffer(queue: CMBufferQueueRef; callback: TCMBufferQueueCallback; refcon: Pointer): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueCallForEachBuffer'; function CMBufferQueueContainsEndOfData(queue: CMBufferQueueRef): Boolean; cdecl; external libCoreMedia name _PU + 'CMBufferQueueContainsEndOfData'; function CMBufferQueueCreate(allocator: CFAllocatorRef; capacity: CMItemCount; callbacks: PCMBufferCallbacks; queueOut: PCMBufferQueueRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueCreate'; function CMBufferQueueDequeueAndRetain(queue: CMBufferQueueRef): CMBufferRef; cdecl; external libCoreMedia name _PU + 'CMBufferQueueDequeueAndRetain'; function CMBufferQueueDequeueIfDataReadyAndRetain(queue: CMBufferQueueRef): CMBufferRef; cdecl; external libCoreMedia name _PU + 'CMBufferQueueDequeueIfDataReadyAndRetain'; function CMBufferQueueEnqueue(queue: CMBufferQueueRef; buf: CMBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueEnqueue'; function CMBufferQueueGetBufferCount(queue: CMBufferQueueRef): CMItemCount; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetBufferCount'; function CMBufferQueueGetCallbacksForSampleBuffersSortedByOutputPTS: PCMBufferCallbacks; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetCallbacksForSampleBuffersSortedByOutputPTS'; function CMBufferQueueGetCallbacksForUnsortedSampleBuffers: PCMBufferCallbacks; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetCallbacksForUnsortedSampleBuffers'; function CMBufferQueueGetDuration(queue: CMBufferQueueRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetDuration'; function CMBufferQueueGetEndPresentationTimeStamp(queue: CMBufferQueueRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetEndPresentationTimeStamp'; function CMBufferQueueGetFirstDecodeTimeStamp(queue: CMBufferQueueRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetFirstDecodeTimeStamp'; function CMBufferQueueGetFirstPresentationTimeStamp(queue: CMBufferQueueRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetFirstPresentationTimeStamp'; function CMBufferQueueGetHead(queue: CMBufferQueueRef): CMBufferRef; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetHead'; function CMBufferQueueGetMaxPresentationTimeStamp(queue: CMBufferQueueRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetMaxPresentationTimeStamp'; function CMBufferQueueGetMinDecodeTimeStamp(queue: CMBufferQueueRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetMinDecodeTimeStamp'; function CMBufferQueueGetMinPresentationTimeStamp(queue: CMBufferQueueRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetMinPresentationTimeStamp'; function CMBufferQueueGetTypeID: CFTypeID; cdecl; external libCoreMedia name _PU + 'CMBufferQueueGetTypeID'; function CMBufferQueueInstallTrigger(queue: CMBufferQueueRef; triggerCallback: CMBufferQueueTriggerCallback; triggerRefcon: Pointer; triggerCondition: CMBufferQueueTriggerCondition; triggerTime: CMTime; triggerTokenOut: PCMBufferQueueTriggerToken): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueInstallTrigger'; function CMBufferQueueInstallTriggerWithIntegerThreshold(queue: CMBufferQueueRef; triggerCallback: CMBufferQueueTriggerCallback; triggerRefcon: Pointer; triggerCondition: CMBufferQueueTriggerCondition; triggerThreshold: CMItemCount; triggerTokenOut: PCMBufferQueueTriggerToken): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueInstallTriggerWithIntegerThreshold'; function CMBufferQueueIsAtEndOfData(queue: CMBufferQueueRef): Boolean; cdecl; external libCoreMedia name _PU + 'CMBufferQueueIsAtEndOfData'; function CMBufferQueueIsEmpty(queue: CMBufferQueueRef): Boolean; cdecl; external libCoreMedia name _PU + 'CMBufferQueueIsEmpty'; function CMBufferQueueMarkEndOfData(queue: CMBufferQueueRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueMarkEndOfData'; function CMBufferQueueRemoveTrigger(queue: CMBufferQueueRef; triggerToken: CMBufferQueueTriggerToken): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueRemoveTrigger'; function CMBufferQueueReset(queue: CMBufferQueueRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueReset'; function CMBufferQueueResetWithCallback(queue: CMBufferQueueRef; callback: TCMBufferQueueResetCallback; refcon: Pointer): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueResetWithCallback'; function CMBufferQueueSetValidationCallback(queue: CMBufferQueueRef; validationCallback: CMBufferValidationCallback; validationRefCon: Pointer): OSStatus; cdecl; external libCoreMedia name _PU + 'CMBufferQueueSetValidationCallback'; function CMBufferQueueTestTrigger(queue: CMBufferQueueRef; triggerToken: CMBufferQueueTriggerToken): Boolean; cdecl; external libCoreMedia name _PU + 'CMBufferQueueTestTrigger'; function CMCopyDictionaryOfAttachments(allocator: CFAllocatorRef; target: CMAttachmentBearerRef; attachmentMode: CMAttachmentMode): CFDictionaryRef; cdecl; external libCoreMedia name _PU + 'CMCopyDictionaryOfAttachments'; function CMFormatDescriptionCreate(allocator: CFAllocatorRef; mediaType: CMMediaType; mediaSubtype: FourCharCode; extensions: CFDictionaryRef; descOut: PCMFormatDescriptionRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMFormatDescriptionCreate'; function CMFormatDescriptionEqual(desc1: CMFormatDescriptionRef; desc2: CMFormatDescriptionRef): Boolean; cdecl; external libCoreMedia name _PU + 'CMFormatDescriptionEqual'; function CMFormatDescriptionEqualIgnoringExtensionKeys(desc1: CMFormatDescriptionRef; desc2: CMFormatDescriptionRef; formatDescriptionExtensionKeysToIgnore: CFTypeRef; sampleDescriptionExtensionAtomKeysToIgnore: CFTypeRef): Boolean; cdecl; external libCoreMedia name _PU + 'CMFormatDescriptionEqualIgnoringExtensionKeys'; function CMFormatDescriptionGetExtension(desc: CMFormatDescriptionRef; extensionKey: CFStringRef): CFPropertyListRef; cdecl; external libCoreMedia name _PU + 'CMFormatDescriptionGetExtension'; function CMFormatDescriptionGetExtensions(desc: CMFormatDescriptionRef): CFDictionaryRef; cdecl; external libCoreMedia name _PU + 'CMFormatDescriptionGetExtensions'; function CMFormatDescriptionGetMediaSubType(desc: CMFormatDescriptionRef): FourCharCode; cdecl; external libCoreMedia name _PU + 'CMFormatDescriptionGetMediaSubType'; function CMFormatDescriptionGetMediaType(desc: CMFormatDescriptionRef): CMMediaType; cdecl; external libCoreMedia name _PU + 'CMFormatDescriptionGetMediaType'; function CMFormatDescriptionGetTypeID: CFTypeID; cdecl; external libCoreMedia name _PU + 'CMFormatDescriptionGetTypeID'; function CMGetAttachment(target: CMAttachmentBearerRef; key: CFStringRef; attachmentModeOut: PCMAttachmentMode): CFTypeRef; cdecl; external libCoreMedia name _PU + 'CMGetAttachment'; function CMMetadataFormatDescriptionCreateWithKeys(allocator: CFAllocatorRef; metadataType: CMMetadataFormatType; keys: CFArrayRef; outDesc: PCMMetadataFormatDescriptionRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMMetadataFormatDescriptionCreateWithKeys'; function CMMetadataFormatDescriptionGetKeyWithLocalID(desc: CMMetadataFormatDescriptionRef; localKeyID: OSType): CFDictionaryRef; cdecl; external libCoreMedia name _PU + 'CMMetadataFormatDescriptionGetKeyWithLocalID'; function CMMuxedFormatDescriptionCreate(allocator: CFAllocatorRef; muxType: CMMuxedStreamType; extensions: CFDictionaryRef; outDesc: PCMMuxedFormatDescriptionRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMMuxedFormatDescriptionCreate'; procedure CMPropagateAttachments(source: CMAttachmentBearerRef; destination: CMAttachmentBearerRef); cdecl; external libCoreMedia name _PU + 'CMPropagateAttachments'; procedure CMRemoveAllAttachments(target: CMAttachmentBearerRef); cdecl; external libCoreMedia name _PU + 'CMRemoveAllAttachments'; procedure CMRemoveAttachment(target: CMAttachmentBearerRef; key: CFStringRef); cdecl; external libCoreMedia name _PU + 'CMRemoveAttachment'; function CMSampleBufferCallForEachSample(sbuf: CMSampleBufferRef; callback: TCMSampleBufferCallback; refcon: Pointer): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferCallForEachSample'; function CMSampleBufferCopySampleBufferForRange(allocator: CFAllocatorRef; sbuf: CMSampleBufferRef; sampleRange: CFRange; sBufOut: PCMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferCopySampleBufferForRange'; function CMSampleBufferCreate(allocator: CFAllocatorRef; dataBuffer: CMBlockBufferRef; dataReady: Boolean; makeDataReadyCallback: CMSampleBufferMakeDataReadyCallback; makeDataReadyRefcon: Pointer; formatDescription: CMFormatDescriptionRef; numSamples: CMItemCount; numSampleTimingEntries: CMItemCount; sampleTimingArray: PCMSampleTimingInfo; numSampleSizeEntries: CMItemCount; sampleSizeArray: Psize_t; sBufOut: PCMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferCreate'; function CMSampleBufferCreateCopy(allocator: CFAllocatorRef; sbuf: CMSampleBufferRef; sbufCopyOut: PCMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferCreateCopy'; function CMSampleBufferCreateCopyWithNewTiming(allocator: CFAllocatorRef; originalSBuf: CMSampleBufferRef; numSampleTimingEntries: CMItemCount; sampleTimingArray: PCMSampleTimingInfo; sBufCopyOut: PCMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferCreateCopyWithNewTiming'; function CMSampleBufferCreateForImageBuffer(allocator: CFAllocatorRef; imageBuffer: CVImageBufferRef; dataReady: Boolean; makeDataReadyCallback: CMSampleBufferMakeDataReadyCallback; makeDataReadyRefcon: Pointer; formatDescription: CMVideoFormatDescriptionRef; sampleTiming: PCMSampleTimingInfo; sBufOut: PCMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferCreateForImageBuffer'; function CMSampleBufferDataIsReady(sbuf: CMSampleBufferRef): Boolean; cdecl; external libCoreMedia name _PU + 'CMSampleBufferDataIsReady'; function CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sbuf: CMSampleBufferRef; bufferListSizeNeededOut: Psize_t; bufferListOut: PAudioBufferList; bufferListSize: size_t; bbufStructAllocator: CFAllocatorRef; bbufMemoryAllocator: CFAllocatorRef; flags: UInt32; blockBufferOut: PCMBlockBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer'; function CMSampleBufferGetAudioStreamPacketDescriptions(sbuf: CMSampleBufferRef; packetDescriptionsSize: size_t; packetDescriptionsOut: PAudioStreamPacketDescription; packetDescriptionsSizeNeededOut: Psize_t): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetAudioStreamPacketDescriptions'; function CMSampleBufferGetAudioStreamPacketDescriptionsPtr(sbuf: CMSampleBufferRef; packetDescriptionsPtrOut: PAudioStreamPacketDescription; packetDescriptionsSizeOut: Psize_t): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetAudioStreamPacketDescriptionsPtr'; function CMSampleBufferGetDataBuffer(sbuf: CMSampleBufferRef): CMBlockBufferRef; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetDataBuffer'; function CMSampleBufferGetDecodeTimeStamp(sbuf: CMSampleBufferRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetDecodeTimeStamp'; function CMSampleBufferGetDuration(sbuf: CMSampleBufferRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetDuration'; function CMSampleBufferGetFormatDescription(sbuf: CMSampleBufferRef): CMFormatDescriptionRef; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetFormatDescription'; function CMSampleBufferGetImageBuffer(sbuf: CMSampleBufferRef): CVImageBufferRef; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetImageBuffer'; function CMSampleBufferGetNumSamples(sbuf: CMSampleBufferRef): CMItemCount; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetNumSamples'; function CMSampleBufferGetOutputDecodeTimeStamp(sbuf: CMSampleBufferRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetOutputDecodeTimeStamp'; function CMSampleBufferGetOutputDuration(sbuf: CMSampleBufferRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetOutputDuration'; function CMSampleBufferGetOutputPresentationTimeStamp(sbuf: CMSampleBufferRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetOutputPresentationTimeStamp'; function CMSampleBufferGetOutputSampleTimingInfoArray(sbuf: CMSampleBufferRef; timingArrayEntries: CMItemCount; timingArrayOut: PCMSampleTimingInfo; timingArrayEntriesNeededOut: PCMItemCount): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetOutputSampleTimingInfoArray'; function CMSampleBufferGetPresentationTimeStamp(sbuf: CMSampleBufferRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetPresentationTimeStamp'; function CMSampleBufferGetSampleAttachmentsArray(sbuf: CMSampleBufferRef; createIfNecessary: Boolean): CFArrayRef; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetSampleAttachmentsArray'; function CMSampleBufferGetSampleSize(sbuf: CMSampleBufferRef; sampleIndex: CMItemIndex): size_t; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetSampleSize'; function CMSampleBufferGetSampleSizeArray(sbuf: CMSampleBufferRef; sizeArrayEntries: CMItemCount; sizeArrayOut: Psize_t; sizeArrayEntriesNeededOut: PCMItemCount): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetSampleSizeArray'; function CMSampleBufferGetSampleTimingInfo(sbuf: CMSampleBufferRef; sampleIndex: CMItemIndex; timingInfoOut: PCMSampleTimingInfo): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetSampleTimingInfo'; function CMSampleBufferGetSampleTimingInfoArray(sbuf: CMSampleBufferRef; timingArrayEntries: CMItemCount; timingArrayOut: PCMSampleTimingInfo; timingArrayEntriesNeededOut: PCMItemCount): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetSampleTimingInfoArray'; function CMSampleBufferGetTotalSampleSize(sbuf: CMSampleBufferRef): size_t; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetTotalSampleSize'; function CMSampleBufferGetTypeID: CFTypeID; cdecl; external libCoreMedia name _PU + 'CMSampleBufferGetTypeID'; function CMSampleBufferInvalidate(sbuf: CMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferInvalidate'; function CMSampleBufferIsValid(sbuf: CMSampleBufferRef): Boolean; cdecl; external libCoreMedia name _PU + 'CMSampleBufferIsValid'; function CMSampleBufferMakeDataReady(sbuf: CMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferMakeDataReady'; function CMSampleBufferSetDataBuffer(sbuf: CMSampleBufferRef; dataBuffer: CMBlockBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferSetDataBuffer'; function CMSampleBufferSetDataBufferFromAudioBufferList(sbuf: CMSampleBufferRef; bbufStructAllocator: CFAllocatorRef; bbufMemoryAllocator: CFAllocatorRef; flags: UInt32; bufferList: PAudioBufferList): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferSetDataBufferFromAudioBufferList'; function CMSampleBufferSetDataReady(sbuf: CMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferSetDataReady'; function CMSampleBufferSetInvalidateCallback(sbuf: CMSampleBufferRef; invalidateCallback: CMSampleBufferInvalidateCallback; invalidateRefCon: UInt64): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferSetInvalidateCallback'; function CMSampleBufferSetOutputPresentationTimeStamp(sbuf: CMSampleBufferRef; outputPresentationTimeStamp: CMTime): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferSetOutputPresentationTimeStamp'; function CMSampleBufferTrackDataReadiness(sbuf: CMSampleBufferRef; sbufToTrack: CMSampleBufferRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSampleBufferTrackDataReadiness'; procedure CMSetAttachment(target: CMAttachmentBearerRef; key: CFStringRef; value: CFTypeRef; attachmentMode: CMAttachmentMode); cdecl; external libCoreMedia name _PU + 'CMSetAttachment'; procedure CMSetAttachments(target: CMAttachmentBearerRef; theAttachments: CFDictionaryRef; attachmentMode: CMAttachmentMode); cdecl; external libCoreMedia name _PU + 'CMSetAttachments'; function CMSimpleQueueCreate(allocator: CFAllocatorRef; capacity: Int32; queueOut: PCMSimpleQueueRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSimpleQueueCreate'; function CMSimpleQueueDequeue(queue: CMSimpleQueueRef): Pointer; cdecl; external libCoreMedia name _PU + 'CMSimpleQueueDequeue'; function CMSimpleQueueEnqueue(queue: CMSimpleQueueRef; element: Pointer): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSimpleQueueEnqueue'; function CMSimpleQueueGetCapacity(queue: CMSimpleQueueRef): Int32; cdecl; external libCoreMedia name _PU + 'CMSimpleQueueGetCapacity'; function CMSimpleQueueGetCount(queue: CMSimpleQueueRef): Int32; cdecl; external libCoreMedia name _PU + 'CMSimpleQueueGetCount'; function CMSimpleQueueGetHead(queue: CMSimpleQueueRef): Pointer; cdecl; external libCoreMedia name _PU + 'CMSimpleQueueGetHead'; function CMSimpleQueueGetTypeID: CFTypeID; cdecl; external libCoreMedia name _PU + 'CMSimpleQueueGetTypeID'; function CMSimpleQueueReset(queue: CMSimpleQueueRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMSimpleQueueReset'; function CMTextFormatDescriptionGetDefaultStyle(desc: CMFormatDescriptionRef; outLocalFontID: PUInt16; outBold: PBoolean; outItalic: PBoolean; outUnderline: PBoolean; outFontSize: PCGFloat; outColorComponents: PCGFloat): OSStatus; cdecl; external libCoreMedia name _PU + 'CMTextFormatDescriptionGetDefaultStyle'; function CMTextFormatDescriptionGetDefaultTextBox(desc: CMFormatDescriptionRef; originIsAtTopLeft: Boolean; heightOfTextTrack: CGFloat; outDefaultTextBox: PCGRect): OSStatus; cdecl; external libCoreMedia name _PU + 'CMTextFormatDescriptionGetDefaultTextBox'; function CMTextFormatDescriptionGetDisplayFlags(desc: CMFormatDescriptionRef; outDisplayFlags: PCMTextDisplayFlags): OSStatus; cdecl; external libCoreMedia name _PU + 'CMTextFormatDescriptionGetDisplayFlags'; function CMTextFormatDescriptionGetFontName(desc: CMFormatDescriptionRef; localFontID: UInt16; outFontName: PCFStringRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMTextFormatDescriptionGetFontName'; function CMTextFormatDescriptionGetJustification(desc: CMFormatDescriptionRef; outHorizontalJust: PCMTextJustificationValue; outVerticalJust: PCMTextJustificationValue): OSStatus; cdecl; external libCoreMedia name _PU + 'CMTextFormatDescriptionGetJustification'; function CMTimeAbsoluteValue(time: CMTime): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeAbsoluteValue'; function CMTimeAdd(addend1: CMTime; addend2: CMTime): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeAdd'; function CMTimeClampToRange(time: CMTime; range: CMTimeRange): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeClampToRange'; function CMTimeCodeFormatDescriptionCreate(allocator: CFAllocatorRef; timeCodeFormatType: CMTimeCodeFormatType; frameDuration: CMTime; frameQuanta: UInt32; tcFlags: UInt32; extensions: CFDictionaryRef; descOut: PCMTimeCodeFormatDescriptionRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMTimeCodeFormatDescriptionCreate'; function CMTimeCodeFormatDescriptionGetFrameDuration(timeCodeFormatDescription: CMTimeCodeFormatDescriptionRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeCodeFormatDescriptionGetFrameDuration'; function CMTimeCodeFormatDescriptionGetFrameQuanta(timeCodeFormatDescription: CMTimeCodeFormatDescriptionRef): UInt32; cdecl; external libCoreMedia name _PU + 'CMTimeCodeFormatDescriptionGetFrameQuanta'; function CMTimeCodeFormatDescriptionGetTimeCodeFlags(desc: CMTimeCodeFormatDescriptionRef): UInt32; cdecl; external libCoreMedia name _PU + 'CMTimeCodeFormatDescriptionGetTimeCodeFlags'; function CMTimeCompare(time1: CMTime; time2: CMTime): Int32; cdecl; external libCoreMedia name _PU + 'CMTimeCompare'; function CMTimeConvertScale(time: CMTime; newTimescale: Int32; method: CMTimeRoundingMethod): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeConvertScale'; function CMTimeCopyAsDictionary(time: CMTime; allocator: CFAllocatorRef): CFDictionaryRef; cdecl; external libCoreMedia name _PU + 'CMTimeCopyAsDictionary'; function CMTimeCopyDescription(allocator: CFAllocatorRef; time: CMTime): CFStringRef; cdecl; external libCoreMedia name _PU + 'CMTimeCopyDescription'; function CMTimeGetSeconds(time: CMTime): Float64; cdecl; external libCoreMedia name _PU + 'CMTimeGetSeconds'; function CMTimeMake(value: Int64; timescale: Int32): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMake'; function CMTimeMakeFromDictionary(dict: CFDictionaryRef): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMakeFromDictionary'; function CMTimeMakeWithEpoch(value: Int64; timescale: Int32; epoch: Int64): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMakeWithEpoch'; function CMTimeMakeWithSeconds(seconds: Float64; preferredTimeScale: Int32): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMakeWithSeconds'; function CMTimeMapDurationFromRangeToRange(dur: CMTime; fromRange: CMTimeRange; toRange: CMTimeRange): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMapDurationFromRangeToRange'; function CMTimeMapTimeFromRangeToRange(t: CMTime; fromRange: CMTimeRange; toRange: CMTimeRange): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMapTimeFromRangeToRange'; function CMTimeMaximum(time1: CMTime; time2: CMTime): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMaximum'; function CMTimeMinimum(time1: CMTime; time2: CMTime): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMinimum'; function CMTimeMultiply(time: CMTime; multiplier: Int32): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMultiply'; function CMTimeMultiplyByFloat64(time: CMTime; multiplier: Float64): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeMultiplyByFloat64'; function CMTimeRangeContainsTime(range: CMTimeRange; time: CMTime): Boolean; cdecl; external libCoreMedia name _PU + 'CMTimeRangeContainsTime'; function CMTimeRangeContainsTimeRange(range1: CMTimeRange; range2: CMTimeRange): Boolean; cdecl; external libCoreMedia name _PU + 'CMTimeRangeContainsTimeRange'; function CMTimeRangeCopyAsDictionary(range: CMTimeRange; allocator: CFAllocatorRef): CFDictionaryRef; cdecl; external libCoreMedia name _PU + 'CMTimeRangeCopyAsDictionary'; function CMTimeRangeCopyDescription(allocator: CFAllocatorRef; range: CMTimeRange): CFStringRef; cdecl; external libCoreMedia name _PU + 'CMTimeRangeCopyDescription'; function CMTimeRangeEqual(range1: CMTimeRange; range2: CMTimeRange): Boolean; cdecl; external libCoreMedia name _PU + 'CMTimeRangeEqual'; function CMTimeRangeFromTimeToTime(start: CMTime; end_: CMTime): CMTimeRange; cdecl; external libCoreMedia name _PU + 'CMTimeRangeFromTimeToTime'; function CMTimeRangeGetEnd(range: CMTimeRange): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeRangeGetEnd'; function CMTimeRangeGetIntersection(range1: CMTimeRange; range2: CMTimeRange): CMTimeRange; cdecl; external libCoreMedia name _PU + 'CMTimeRangeGetIntersection'; function CMTimeRangeGetUnion(range1: CMTimeRange; range2: CMTimeRange): CMTimeRange; cdecl; external libCoreMedia name _PU + 'CMTimeRangeGetUnion'; function CMTimeRangeMake(start: CMTime; duration: CMTime): CMTimeRange; cdecl; external libCoreMedia name _PU + 'CMTimeRangeMake'; function CMTimeRangeMakeFromDictionary(dict: CFDictionaryRef): CMTimeRange; cdecl; external libCoreMedia name _PU + 'CMTimeRangeMakeFromDictionary'; procedure CMTimeRangeShow(range: CMTimeRange); cdecl; external libCoreMedia name _PU + 'CMTimeRangeShow'; procedure CMTimeShow(time: CMTime); cdecl; external libCoreMedia name _PU + 'CMTimeShow'; function CMTimeSubtract(minuend: CMTime; subtrahend: CMTime): CMTime; cdecl; external libCoreMedia name _PU + 'CMTimeSubtract'; function CMVideoFormatDescriptionCreate(allocator: CFAllocatorRef; codecType: CMVideoCodecType; width: Int32; height: Int32; extensions: CFDictionaryRef; outDesc: PCMVideoFormatDescriptionRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMVideoFormatDescriptionCreate'; function CMVideoFormatDescriptionCreateForImageBuffer(allocator: CFAllocatorRef; imageBuffer: CVImageBufferRef; outDesc: PCMVideoFormatDescriptionRef): OSStatus; cdecl; external libCoreMedia name _PU + 'CMVideoFormatDescriptionCreateForImageBuffer'; function CMVideoFormatDescriptionGetCleanAperture(videoDesc: CMVideoFormatDescriptionRef; originIsAtTopLeft: Boolean): CGRect; cdecl; external libCoreMedia name _PU + 'CMVideoFormatDescriptionGetCleanAperture'; function CMVideoFormatDescriptionGetDimensions(videoDesc: CMVideoFormatDescriptionRef): CMVideoDimensions; cdecl; external libCoreMedia name _PU + 'CMVideoFormatDescriptionGetDimensions'; function CMVideoFormatDescriptionGetExtensionKeysCommonWithImageBuffers: CFArrayRef; cdecl; external libCoreMedia name _PU + 'CMVideoFormatDescriptionGetExtensionKeysCommonWithImageBuffers'; function CMVideoFormatDescriptionGetPresentationDimensions(videoDesc: CMVideoFormatDescriptionRef; usePixelAspectRatio: Boolean; useCleanAperture: Boolean): CGSize; cdecl; external libCoreMedia name _PU + 'CMVideoFormatDescriptionGetPresentationDimensions'; function CMVideoFormatDescriptionMatchesImageBuffer(desc: CMVideoFormatDescriptionRef; imageBuffer: CVImageBufferRef): Boolean; cdecl; external libCoreMedia name _PU + 'CMVideoFormatDescriptionMatchesImageBuffer'; function kCMTimeZero: CMTime; function kCMTimeIndefinite: CMTime; function kCMTimePositiveInfinity: CMTime; function kCMTimeNegativeInfinity: CMTime; implementation uses System.SysUtils; function kCMTimeZero: CMTime; begin Result := PCMTime(CocoaPointerConst(libCoreMedia, 'kCMTimeZero'))^; end; function kCMTimeIndefinite: CMTime; begin Result := PCMTime(CocoaPointerConst(libCoreMedia, 'kCMTimeIndefinite'))^; end; function kCMTimePositiveInfinity: CMTime; begin Result := PCMTime(CocoaPointerConst(libCoreMedia, 'kCMTimePositiveInfinity'))^; end; function kCMTimeNegativeInfinity: CMTime; begin Result := PCMTime(CocoaPointerConst(libCoreMedia, 'kCMTimeNegativeInfinity'))^; end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 公共DLL函数的调用单元 //主要实现: //-----------------------------------------------------------------------------} unit untEasyUtilDLL; interface uses Windows, SysUtils, Classes, Math; type TTimeOfWhat = ( ftCreationTime, ftLastAccessTime, ftLastWriteTime ); TFileTimeComparision = ( ftError, ftFileOneIsOlder, ftFileTimesAreEqual, ftFileTwoIsOlder ); TDriveType = (dtUnknown, dtNoDrive, dtFloppy, dtFixed, dtNetwork, dtCDROM, dtRAM); TVolumeInfo = record Name : String; SerialNumber : DWORD; MaxComponentLength : DWORD; FileSystemFlags : DWORD; FileSystemName : String; end; // TVolumeInfo PFixedFileInfo = ^TFixedFileInfo; TFixedFileInfo = record dwSignature : DWORD; dwStrucVersion : DWORD; wFileVersionMS : WORD; // Minor Version wFileVersionLS : WORD; // Major Version wProductVersionMS : WORD; // Build Number wProductVersionLS : WORD; // Release Version dwFileFlagsMask : DWORD; dwFileFlags : DWORD; dwFileOS : DWORD; dwFileType : DWORD; dwFileSubtype : DWORD; dwFileDateMS : DWORD; dwFileDateLS : DWORD; end; // TFixedFileInfo TWinVer = Packed Record dwVersion : DWORD; sVerSion : String; end; TKeyBit = (kb128, kb192, kb256); {$IFDEF VER130} // This is a bit awkward // 8-byte integer TInteger8 = Int64; // Delphi 5 {$ELSE} {$IFDEF VER120} TInteger8 = Int64; // Delphi 4 {$ELSE} TInteger8 = COMP; // Delphi 2 or 3 {$ENDIF} {$ENDIF} const START_YEAR=1901; END_YEAR=2050; DLLEasyOS = 'EasyOS.dll'; CalendarDLL = 'EasyCalendar.dll'; //---------------------------------------------------------------------------- //EasyOS.dll //获取系统版本 返回字符串 function GetWindowsVersion: string; stdcall; external 'EasyOS.dll'; //返回操作系统版本标识 {Win3x = $03000000; Win95 = $04000000; Win98ME = $04010000; WinNT40 = $04020000; Win2000 = $05000000; WinXP = $05010000; Win2003 = $05020000; WinVista = $06000000; Win2008 = $06000100;} function GetWindowsVersion_dw: DWORD; stdcall; external 'EasyOS.dll'; //获取计算机用户名 function GetComputerUserName: PChar; stdcall; external DLLEasyOS; //获取系统用户名 function GetSystemUserName: PChar; external DLLEasyOS; //检测TCP/IP协议是否安装 function IsIPInstalled : boolean; external DLLEasyOS; //得到本机的局域网Ip地址 Function GetLocalIp(var LocalIp:string): Boolean; external DLLEasyOS; //检测网络状态 Function CheckIPNetState(IpAddr : string): Boolean; external DLLEasyOS; //检测机器是否上网 Function NetInternetConnected: Boolean; external DLLEasyOS; {ERROR} //获取本地MAC地址 function GetLocalMAC:string; external DLLEasyOS; //获取本地MAC地址 调用DLL function GetLocalMAC_DLL: string; external DLLEasyOS; //* hosttoip 函数作用是将域名解析成ip function HostToIP(Name: string; var Ip: string): Boolean; external DLLEasyOS; {*out和in汇编指令在Window2000以上Ring3(普通级别)不能再使用,如果要使用,必须 进入Ring0指令级别(操作系统级),驱动程序工作在Ring0级别下*} function GetPrinterStatus : byte; external DLLEasyOS;//从并行端口读取打印机状态 function CheckPrinter : boolean; external DLLEasyOS;//获取打印机是否出错 function GetWindowsDirectory : String; external DLLEasyOS; //系统windows路径 function GetSystemDirectory : String; external DLLEasyOS; //系统system路径 function GetSystemTime : String; external DLLEasyOS; //获取系统时间 function GetLocalTime : String; external DLLEasyOS; //本地时间,和系统时间一样 //文件 function GetCurrentDirectory : String; external DLLEasyOS; //当前文件路径 function GetTempPath : String; external DLLEasyOS; //获取TEMP文件路径,为短路径格式 function GetLogicalDrives : String; external DLLEasyOS; //获取系统的所有盘符,组成一组字符串 //获取文件的创建、修改或最后一次的读取时间 function GetFileTime( const FileName : String; ComparisonType : TTimeOfWhat ) : TFileTime; external DLLEasyOS; function GlobalMemoryStatus( const Index : Integer ) : DWORD; external DLLEasyOS; //系统信息 function GetSystemInfoWORD( const Index : Integer ) : WORD; external DLLEasyOS; function GetSystemInfoDWORD( const Index : Integer ) : DWORD; external DLLEasyOS; function GetSystemVersion : String; external DLLEasyOS; function GetSystemInfoPtr( const Index : Integer ) : Pointer; external DLLEasyOS; //获取指定文件的信息 function GetFileInformation(const FileName, Value : String ): String; external DLLEasyOS; //获取文件大小 function FileSize(const FileName : String ) : LongInt; external DLLEasyOS; //判断两个文件的创建时间的早晚 function CompareFileTime(const FileNameOne, FileNameTwo : String; ComparisonType : TTimeOfWhat ): TFileTimeComparision; external DLLEasyOS; //获取文件的创、修改、最后操作时间 function GetFileTime_0(const FileName : String; ComparisonType : TTimeOfWhat ): TDateTime; external DLLEasyOS; //获取程序图标 function ExtractIcon(const FileName : String ): HIcon; external DLLEasyOS; function ExtractAssociatedIcon( const FileName : String ): HIcon; external DLLEasyOS; //磁盘 function GetFreeDiskSpace(const Drive : Char ) : LongInt; external DLLEasyOS; function GetAllDiskFreeSpace : string; external DLLEasyOS; function GetVolumeInformation(const Drive : Char ) : TVolumeInfo; external DLLEasyOS; function DriveType(const Drive : Char ) : TDriveType; external DLLEasyOS; function DisconnectNetworkDrive( const Drive : Char ): Boolean; external DLLEasyOS; function AddNetworkDrive( const Resource : String; const Drive : Char ): Boolean; external DLLEasyOS; function GetUniversalName( const Drive : Char ): String; external DLLEasyOS; procedure FormatDrive( const Drive : Char ); external DLLEasyOS; //短路径 function GetShortPathName(const Path : String ): String; external DLLEasyOS; function GetFullPathName(const Path : String ): String; external DLLEasyOS; //根据可执行文件名,查找可执行文件路径 function FindExecutable(const FileName : String ): String; external DLLEasyOS; procedure ShellAbout( const TitleBar, OtherText : String ); external DLLEasyOS; procedure ShutDown; external DLLEasyOS; function FileInfo(const FileName : String ) : TFixedFileInfo; external DLLEasyOS; //EMAIL有效性判断 procedure SendEMail_Hide; external DLLEasyOS; function CheckMailAddress(Value : string): boolean; external DLLEasyOS;//判断EMAIL地址是否合法 //---------------------------------------------------------------------------- //EasySysShell.dll //系统相关操作 //设置屏幕分辨率 function SetScreen(x,y: Word): Boolean; stdcall; external 'EasySysShell.dll'; {函数说明:} {第一个参数是要建立快捷方式的文件, 这是必须的; 其他都是可选参数} {第二个参数是快捷方式名称, 缺省使用参数一的文件名} {第三个参数是指定目的文件夹, 缺省目的是桌面; 如果有第四个参数, 该参数将被忽略} {第四个参数是用常数的方式指定目的文件夹; 该系列常数定义在 ShlObj 单元, CSIDL_ 打头} {测试 1: 把当前程序在桌面上建立快捷方式} // procedure TForm1.Button1Click(Sender: TObject); // begin // CreateShortcut(Application.ExeName); // end; // // {测试 2: 在桌面上建立快捷方式, 同时指定快捷方式名称} // procedure TForm1.Button2Click(Sender: TObject); // begin // CreateShortcut(Application.ExeName, 'NewLinkName'); // end; // // {测试 3: 在 C:\ 下建立快捷方式} // procedure TForm1.Button3Click(Sender: TObject); // begin // CreateShortcut(Application.ExeName, '', 'C:\'); // end; // // {测试 3: 在开始菜单的程序文件夹下建立快捷方式} // procedure TForm1.Button4Click(Sender: TObject); // begin // CreateShortcut(Application.ExeName, '', '', CSIDL_PROGRAMS); // end; function CreateShortcut(Exe:string; Lnk:string = ''; Dir:string = ''; ID:Integer = -1):Boolean; stdcall; external 'EasySysShell.dll'; //---------------------------------------------------------------------------- //EasyString.dll //简体和繁体互换 function GB2Big(GB: string): string; stdcall; external 'EasyString.dll'; function Big2GB(Big: string): string; stdcall; external 'EasyString.dll'; //---------------------------------------------------------------------------- //EasyIMCode.dll //获取汉字拼音 拼音转汉字 function MakeSpellCode(stText: string; iMode, iCount: Integer): string; stdcall; external 'EasyIMCode.dll'; { iMode 二进制功能位说明 X X X X X X X X X X X X X X X X 3 2 1 1: 0 - 只取各个汉字声母的第一个字母; 1 - 全取 2: 0 - 遇到不能翻译的字符不翻译; 1 - 翻译成 '?' (本选项目针对全角字符) 3: 0 - 生成的串不包括非数字, 字母的其他字符; 1 - 包括 (控制全角的要输出非数字, 字母字符的; 半角的非数字, 字母字符) } function GetSpellCode(szText: PChar; iMode, iCount: Integer): PChar; stdcall; external 'EasyIMCode.dll'; function GetPY(hzchar: string):char; stdcall; external 'EasyIMCode.dll'; //---------------------------------------------------------------------------- //EasyEncrypt.dll //字符串、文件加解密 //AES function StrToHex(Value: string): string; stdcall; external 'EasyEncrypt.dll'; function HexToStr(Value: string): string; stdcall; external 'EasyEncrypt.dll'; function EncryptString(Value: string; Key: string; KeyBit: TKeyBit = kb128): string; stdcall; external 'EasyEncrypt.dll'; function DecryptString(Value: string; Key: string; KeyBit: TKeyBit = kb128): string; stdcall; external 'EasyEncrypt.dll'; function EncryptStream(Src: TStream; Key: string; var Dest: TStream; KeyBit: TKeyBit = kb128): Boolean; stdcall; external 'EasyEncrypt.dll'; function DecryptStream(Src: TStream; Key: string; var Dest: TStream; KeyBit: TKeyBit = kb128): Boolean; stdcall; external 'EasyEncrypt.dll'; procedure EncryptFile(SourceFile, DestFile: string; Key: string; KeyBit: TKeyBit = kb128); stdcall; external 'EasyEncrypt.dll'; procedure DecryptFile(SourceFile, DestFile: string; Key: string; KeyBit: TKeyBit = kb128); stdcall; external 'EasyEncrypt.dll'; //MD5 function transfer(tran:widestring): widestring; external 'EasyEncrypt.dll'; function GetCode(Afilename:String): String; external 'EasyEncrypt.dll'; //Base64 function StrToBase64(const str: string): string; stdcall; external 'EasyEncrypt.dll'; function Base64ToStr(const Base64: string): string; stdcall; external 'EasyEncrypt.dll'; //CRC16 procedure CalcCRC16 (p: pointer; nbyte: WORD; var CRCvalue: WORD); stdcall; external 'EasyEncrypt.dll'; procedure CalcFileCRC16 (FromName: string; var CRCvalue: WORD; var IOBuffer: pointer; BufferSize: WORD; var error: WORD); stdcall; external 'EasyEncrypt.dll'; //CRC32 procedure CalcCRC32(p: pointer; ByteCount: DWORD; var CRCvalue: DWORD); stdcall; external 'EasyEncrypt.dll'; procedure CalcFileCRC32 (FromName: string; var CRCvalue: DWORD; var TotalBytes: TInteger8; var error: WORD); stdcall; external 'EasyEncrypt.dll'; //日期 //---------------------------------------------------------------------------- // ==> function IsLeapYear(Year: Word): Boolean; //计算iYear,iMonth,iDay对应是星期几 1年1月1日 --- 65535年12月31日 function WeekDay(iYear,iMonth,iDay:Word):Integer; stdcall; external CalendarDLL; // ==> function DayOfWeek(Date: TDateTime): Integer; //计算指定日期的周数,周0为新年开始后第一个星期天开始的周 function WeekNum_A(const TDT:TDateTime):Word;{overload; }stdcall; external CalendarDLL; function WeekNum_B(const iYear,iMonth,iDay:Word):Word;{overload; }stdcall; external CalendarDLL; //返回iYear年iMonth月的天数 1年1月 --- 65535年12月 function MonthDays(iYear,iMonth:Word):Word; stdcall; external CalendarDLL; //返回阴历iLunarYer年阴历iLunarMonth月的天数,如果iLunarMonth为闰月, //高字为第二个iLunarMonth月的天数,否则高字为0 // 1901年1月---2050年12月 function LunarMonthDays(iLunarYear,iLunarMonth:Word):Longword; stdcall; external CalendarDLL; //返回阴历iLunarYear年的总天数 // 1901年1月---2050年12月 function LunarYearDays(iLunarYear:Word):Word; stdcall; external CalendarDLL; //返回阴历iLunarYear年的闰月月份,如没有返回0 // 1901年1月---2050年12月 function GetLeapMonth(iLunarYear:Word):Word; stdcall; external CalendarDLL; //把iYear年格式化成天干记年法表示的字符串 procedure FormatLunarYear_A(iYear:Word;var pBuffer:string);{overload;} stdcall; external CalendarDLL; function FormatLunarYear_B(iYear:Word):string;{overload;} stdcall; external CalendarDLL; //把iMonth格式化成中文字符串 procedure FormatMonth_A(iMonth:Word;var pBuffer:string;bLunar:Boolean=True);{overload;} stdcall; external CalendarDLL; function FormatMonth_B(iMonth:Word;bLunar:Boolean=True):string;{overload;} stdcall; external CalendarDLL; //把iDay格式化成中文字符串 procedure FormatLunarDay_A(iDay:Word;var pBuffer:string);{overload; }stdcall; external CalendarDLL; function FormatLunarDay_B(iDay:Word):string;{overload; }stdcall; external CalendarDLL; //计算公历两个日期间相差的天数 1年1月1日 --- 65535年12月31日 function CalcDateDiff_A(iEndYear,iEndMonth,iEndDay:Word;iStartYear:Word=START_YEAR; iStartMonth:Word=1;iStartDay:Word=1):Longword;{overload; }stdcall; external CalendarDLL; function CalcDateDiff_B(EndDate,StartDate:TDateTime):Longword;{overload; }stdcall; external CalendarDLL; //计算公历iYear年iMonth月iDay日对应的阴历日期,返回对应的阴历节气 0-24 //1901年1月1日---2050年12月31日 function GetLunarDate_A(iYear,iMonth,iDay:Word; var iLunarYear,iLunarMonth,iLunarDay:Word):Word;{overload; }stdcall; external CalendarDLL; procedure GetLunarDate_B(InDate:TDateTime; var iLunarYear,iLunarMonth,iLunarDay:Word);{overload; }stdcall; external CalendarDLL; function GetLunarHolDay_A(InDate:TDateTime):string;{overload; }stdcall; external CalendarDLL; function GetLunarHolDay_B(iYear,iMonth,iDay:Word):string;{overload; }stdcall; external CalendarDLL; //private function-------------------------------------- //计算从1901年1月1日过iSpanDays天后的阴历日期 procedure l_CalcLunarDate(var iYear,iMonth,iDay:Word;iSpanDays:Longword); stdcall; external CalendarDLL; //计算公历iYear年iMonth月iDay日对应的节气 0-24,0表不是节气 function l_GetLunarHolDay(iYear,iMonth,iDay:Word):Word; stdcall; external CalendarDLL; //根据当前日期返回中国日历字符 function GetChinaDay: PChar; stdcall; external CalendarDLL; implementation end.
unit JdcOption; interface uses Classes, SysUtils, IniFiles, Registry, Winapi.Windows; type TIniProc = reference to procedure(AIni: TIniFile); TRegProc = reference to procedure(ARegistry: TRegistry); TOptionInterface = class abstract(TComponent) private FPath: String; procedure SetPath(const Value: String); protected function GetStringValue(const ASec, AIdent, ADefault: String): String; virtual; abstract; procedure SetStringValue(const ASec, AIdent, AValue: String); virtual; abstract; function GetIntegerValue(const ASec, AIdent: String; ADefault: Integer) : Integer; virtual; abstract; procedure SetIntegerValue(const ASec, AIdent: String; AValue: Integer); virtual; abstract; function GetFloatValue(const ASec, AIdent: String; ADefault: real): real; virtual; abstract; procedure SetFloatValue(const ASec, AIdent: String; AValue: real); virtual; abstract; function GetBoolValue(const ASec, AIdent: String; ADefault: Boolean) : Boolean; virtual; abstract; procedure SetBoolValue(const ASec, AIdent: String; AValue: Boolean); virtual; abstract; function GetDateTimeValue(const ASec, AIdent: String; ADefault: TDateTime) : TDateTime; virtual; abstract; procedure SetDateTimeValue(const ASec, AIdent: String; AValue: TDateTime); virtual; abstract; public constructor Create(AOwner: TComponent); override; function ReadSections: TStrings; virtual; abstract; function ReadSection(ASection: string): TStrings; virtual; abstract; function ReadSectionValues(ASection: string): TStrings; virtual; abstract; procedure EraseSection(const ASec: String); virtual; abstract; procedure DeleteKey(const ASec, AKey: String); virtual; abstract; function KeyExist(const ASec, AKey: String): Boolean; virtual; abstract; property Path: String read FPath write SetPath; end; TOptionIniFiles = class(TOptionInterface) private procedure IniTemplete(ACallBack: TIniProc); protected function GetStringValue(const ASec, AIdent, ADefault: String) : String; override; procedure SetStringValue(const ASec, AIdent, AValue: String); override; function GetIntegerValue(const ASec, AIdent: String; ADefault: Integer) : Integer; override; procedure SetIntegerValue(const ASec, AIdent: String; AValue: Integer); override; function GetFloatValue(const ASec, AIdent: String; ADefault: real) : real; override; procedure SetFloatValue(const ASec, AIdent: String; AValue: real); override; function GetBoolValue(const ASec, AIdent: String; ADefault: Boolean) : Boolean; override; procedure SetBoolValue(const ASec, AIdent: String; AValue: Boolean); override; function GetDateTimeValue(const ASec, AIdent: String; ADefault: TDateTime) : TDateTime; override; procedure SetDateTimeValue(const ASec, AIdent: String; AValue: TDateTime); override; public function ReadSections: TStrings; override; function ReadSection(ASection: string): TStrings; override; function ReadSectionValues(ASection: string): TStrings; override; procedure EraseSection(const ASec: String); override; procedure DeleteKey(const ASec, AKey: String); override; function KeyExist(const ASec, AKey: String): Boolean; override; end; TOptionRegistry = class(TOptionInterface) private FRootKey: HKEY; procedure RegistryTemplete(ASec: String; ACallBack: TRegProc); protected function GetStringValue(const ASec, AIdent, ADefault: String) : String; override; procedure SetStringValue(const ASec, AIdent, AValue: String); override; function GetIntegerValue(const ASec, AIdent: String; ADefault: Integer) : Integer; override; procedure SetIntegerValue(const ASec, AIdent: String; AValue: Integer); override; function GetFloatValue(const ASec, AIdent: String; ADefault: real) : real; override; procedure SetFloatValue(const ASec, AIdent: String; AValue: real); override; function GetBoolValue(const ASec, AIdent: String; ADefault: Boolean) : Boolean; override; procedure SetBoolValue(const ASec, AIdent: String; AValue: Boolean); override; function GetDateTimeValue(const ASec, AIdent: String; ADefault: TDateTime) : TDateTime; override; procedure SetDateTimeValue(const ASec, AIdent: String; AValue: TDateTime); override; public constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; AKey: HKEY); reintroduce; overload; function ReadSections: TStrings; override; function ReadSection(ASection: string): TStrings; override; function ReadSectionValues(ASection: string): TStrings; override; procedure EraseSection(const ASec: String); override; procedure DeleteKey(const ASec, AKey: String); override; function KeyExist(const ASec, AKey: String): Boolean; override; property RootKey: HKEY read FRootKey; end; implementation var MyObj: TOptionIniFiles = nil; { TOption } procedure TOptionIniFiles.DeleteKey(const ASec, AKey: String); begin IniTemplete( procedure(AIni: TIniFile) begin AIni.DeleteKey(ASec, AKey); end); end; procedure TOptionIniFiles.EraseSection(const ASec: String); begin IniTemplete( procedure(AIni: TIniFile) begin AIni.EraseSection(ASec); end); end; procedure TOptionIniFiles.SetFloatValue(const ASec, AIdent: String; AValue: real); begin IniTemplete( procedure(AIni: TIniFile) begin AIni.WriteFloat(ASec, AIdent, AValue); end); end; function TOptionIniFiles.ReadSection(ASection: string): TStrings; var Value: TStrings; begin Value := TStringList.Create; IniTemplete( procedure(AIni: TIniFile) begin AIni.ReadSection(ASection, Value); end); result := Value; end; function TOptionIniFiles.ReadSections: TStrings; var Value: TStrings; begin Value := TStringList.Create; IniTemplete( procedure(AIni: TIniFile) begin AIni.ReadSections(Value); end); result := Value; end; function TOptionIniFiles.ReadSectionValues(ASection: string): TStrings; var Value: TStrings; begin Value := TStringList.Create; IniTemplete( procedure(AIni: TIniFile) begin AIni.ReadSectionValues(ASection, Value); end); result := Value; end; function TOptionIniFiles.GetBoolValue(const ASec, AIdent: String; ADefault: Boolean): Boolean; var Value: Boolean; begin IniTemplete( procedure(AIni: TIniFile) begin Value := AIni.ReadBool(ASec, AIdent, ADefault); end); result := Value; end; function TOptionIniFiles.GetDateTimeValue(const ASec, AIdent: String; ADefault: TDateTime): TDateTime; var Value: TDateTime; begin IniTemplete( procedure(AIni: TIniFile) begin Value := AIni.ReadDateTime(ASec, AIdent, ADefault); end); result := Value; end; function TOptionIniFiles.GetFloatValue(const ASec, AIdent: String; ADefault: real): real; var Value: real; begin IniTemplete( procedure(AIni: TIniFile) begin Value := AIni.ReadFloat(ASec, AIdent, ADefault); end); result := Value; end; function TOptionIniFiles.GetIntegerValue(const ASec, AIdent: String; ADefault: Integer): Integer; var Value: Integer; begin IniTemplete( procedure(AIni: TIniFile) begin Value := AIni.ReadInteger(ASec, AIdent, ADefault); end); result := Value; end; function TOptionIniFiles.GetStringValue(const ASec, AIdent, ADefault: String): String; var Value: String; begin IniTemplete( procedure(AIni: TIniFile) begin Value := AIni.ReadString(ASec, AIdent, ADefault); end); result := Value; end; procedure TOptionIniFiles.IniTemplete(ACallBack: TIniProc); var IniFile: TIniFile; begin if FPath.IsEmpty then raise Exception.Create('Empty Option Path.'); IniFile := TIniFile.Create(FPath); try with IniFile do begin ACallBack(IniFile); end; finally IniFile.Free; end; end; function TOptionIniFiles.KeyExist(const ASec, AKey: String): Boolean; var Value: Boolean; begin IniTemplete( procedure(AIni: TIniFile) begin Value := AIni.ValueExists(ASec, AKey); end); result := Value; end; procedure TOptionIniFiles.SetBoolValue(const ASec, AIdent: String; AValue: Boolean); begin IniTemplete( procedure(AIni: TIniFile) begin AIni.WriteBool(ASec, AIdent, AValue); end); end; procedure TOptionIniFiles.SetDateTimeValue(const ASec, AIdent: String; AValue: TDateTime); begin IniTemplete( procedure(AIni: TIniFile) begin AIni.WriteDateTime(ASec, AIdent, AValue); end); end; procedure TOptionIniFiles.SetIntegerValue(const ASec, AIdent: String; AValue: Integer); begin IniTemplete( procedure(AIni: TIniFile) begin AIni.WriteInteger(ASec, AIdent, AValue); end); end; procedure TOptionIniFiles.SetStringValue(const ASec, AIdent, AValue: String); begin IniTemplete( procedure(AIni: TIniFile) begin AIni.WriteString(ASec, AIdent, AValue); end); end; { TOptionAbstract } constructor TOptionInterface.Create(AOwner: TComponent); begin Inherited; FPath := ''; end; procedure TOptionInterface.SetPath(const Value: String); begin FPath := Value; if Value.IsEmpty then raise Exception.Create ('::JdcOption:: Can not set empty string to Option Path.'); end; { TOptionRegistry } constructor TOptionRegistry.Create(AOwner: TComponent; AKey: HKEY); begin inherited Create(AOwner); FRootKey := AKey; end; constructor TOptionRegistry.Create(AOwner: TComponent); begin Create(AOwner, HKEY_CURRENT_USER); end; procedure TOptionRegistry.DeleteKey(const ASec, AKey: String); begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin ARegistry.DeleteValue(AKey); end); end; procedure TOptionRegistry.EraseSection(const ASec: String); begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin ARegistry.CloseKey; ARegistry.OpenKey('\SOFTWARE\' + FPath, True); ARegistry.DeleteKey(ASec); end); end; function TOptionRegistry.GetBoolValue(const ASec, AIdent: String; ADefault: Boolean): Boolean; var Value: Boolean; begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin if ARegistry.ValueExists(AIdent) then Value := ARegistry.ReadBool(AIdent) else Value := ADefault; end); result := Value; end; function TOptionRegistry.GetDateTimeValue(const ASec, AIdent: String; ADefault: TDateTime): TDateTime; var Value: TDateTime; begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin if ARegistry.ValueExists(AIdent) then Value := ARegistry.ReadDateTime(AIdent) else Value := ADefault; end); result := Value; end; function TOptionRegistry.GetFloatValue(const ASec, AIdent: String; ADefault: real): real; var Value: Double; begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin if ARegistry.ValueExists(AIdent) then Value := ARegistry.ReadFloat(AIdent) else Value := ADefault; end); result := Value; end; function TOptionRegistry.GetIntegerValue(const ASec, AIdent: String; ADefault: Integer): Integer; var Value: Integer; begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin if ARegistry.ValueExists(AIdent) then Value := ARegistry.ReadInteger(AIdent) else Value := ADefault; end); result := Value; end; function TOptionRegistry.GetStringValue(const ASec, AIdent, ADefault: String): String; var Value: String; begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin if ARegistry.ValueExists(AIdent) then Value := ARegistry.ReadString(AIdent) else Value := ADefault; end); result := Value; end; function TOptionRegistry.KeyExist(const ASec, AKey: String): Boolean; var Value: Boolean; begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin Value := ARegistry.KeyExists(AKey); end); result := Value; end; function TOptionRegistry.ReadSection(ASection: string): TStrings; var Value: TStrings; begin Value := TStringList.Create; RegistryTemplete(ASection, procedure(ARegistry: TRegistry) begin ARegistry.GetKeyNames(Value); end); result := Value; end; function TOptionRegistry.ReadSections: TStrings; var Value: TStrings; begin Value := TStringList.Create; RegistryTemplete('', procedure(ARegistry: TRegistry) begin ARegistry.GetKeyNames(Value); end); result := Value; end; function TOptionRegistry.ReadSectionValues(ASection: string): TStrings; var Value: TStrings; begin Value := TStringList.Create; RegistryTemplete(ASection, procedure(ARegistry: TRegistry) var tmp: TStrings; MyElem: String; begin tmp := TStringList.Create; try ARegistry.GetValueNames(tmp); for MyElem in tmp do begin Value.Values[MyElem] := ARegistry.ReadString(MyElem); end; finally tmp.Free; end; end); result := Value; end; procedure TOptionRegistry.RegistryTemplete(ASec: String; ACallBack: TRegProc); var Registry: TRegistry; begin if FPath.IsEmpty then raise Exception.Create('Empty Option Path.'); Registry := TRegistry.Create(KEY_READ or KEY_WRITE); try Registry.RootKey := FRootKey; Registry.OpenKey('\SOFTWARE\' + FPath + '\' + ASec, True); ACallBack(Registry); Registry.CloseKey; finally Registry.Free; end; end; procedure TOptionRegistry.SetBoolValue(const ASec, AIdent: String; AValue: Boolean); begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin ARegistry.WriteBool(AIdent, AValue); end); end; procedure TOptionRegistry.SetDateTimeValue(const ASec, AIdent: String; AValue: TDateTime); begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin ARegistry.WriteDateTime(AIdent, AValue); end); end; procedure TOptionRegistry.SetFloatValue(const ASec, AIdent: String; AValue: real); begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin ARegistry.WriteFloat(AIdent, AValue); end); end; procedure TOptionRegistry.SetIntegerValue(const ASec, AIdent: String; AValue: Integer); begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin ARegistry.WriteInteger(AIdent, AValue); end); end; procedure TOptionRegistry.SetStringValue(const ASec, AIdent, AValue: String); begin RegistryTemplete(ASec, procedure(ARegistry: TRegistry) begin ARegistry.WriteString(AIdent, AValue); end); end; end.
{**********************************************} { TCLVFunction (Accumulation/Distribution) } { Copyright (c) 2002-2004 by David Berneda } {**********************************************} unit TeeCLVFunction; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} OHLChart, TeEngine, TeCanvas, Chart, TeeBaseFuncEdit; type TCLVFunction=class(TTeeFunction) private FVolume: TChartSeries; FAccumulate: Boolean; // 6.01, renamed procedure SetVolume(const Value: TChartSeries); procedure SetAccumulate(const Value: Boolean); protected class Function GetEditorClass:String; override; Function IsValidSource(Value:TChartSeries):Boolean; override; procedure Notification( AComponent: TComponent; Operation: TOperation); override; public Constructor Create(AOwner:TComponent); override; procedure AddPoints(Source:TChartSeries); override; published property Accumulate:Boolean read FAccumulate write SetAccumulate default True; property Volume:TChartSeries read FVolume write SetVolume; end; TCLVFuncEditor = class(TBaseFunctionEditor) Label1: TLabel; CBVolume: TComboFlat; CBAccumulate: TCheckBox; procedure CBAccumulateClick(Sender: TObject); private { Private declarations } protected procedure ApplyFormChanges; override; Procedure SetFunction; override; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} uses TeeProCo, TeeConst; { TCLVFunction } constructor TCLVFunction.Create(AOwner: TComponent); begin inherited; InternalSetPeriod(1); CanUsePeriod:=False; SingleSource:=True; HideSourceList:=True; FAccumulate:=True; end; procedure TCLVFunction.AddPoints(Source: TChartSeries); var t : Integer; tmpHigh : Double; tmpClose : Double; tmpLow : Double; CLV : Double; tmpVolume : Boolean; begin tmpVolume:=Assigned(FVolume); ParentSeries.Clear; with Source as TOHLCSeries do for t:=0 to Count-1 do begin tmpHigh:=HighValues.Value[t]; tmpClose:=CloseValues.Value[t]; tmpLow:=LowValues.Value[t]; if (tmpHigh-tmpLow)=0 then // 7.0 #1201 CLV:=1 else CLV:=( (tmpClose-tmpLow)-(tmpHigh-tmpClose))/(tmpHigh-tmpLow); if tmpVolume and (FVolume.Count>t) then CLV:=CLV*FVolume.MandatoryValueList.Value[t]; if Accumulate then if t>0 then CLV:=CLV+ParentSeries.MandatoryValueList.Last; ParentSeries.AddXY(DateValues.Value[t],CLV); end; end; class function TCLVFunction.GetEditorClass: String; begin result:='TCLVFuncEditor'; end; function TCLVFunction.IsValidSource(Value: TChartSeries): Boolean; begin result:=Value is TOHLCSeries; end; procedure TCLVFunction.SetVolume(const Value: TChartSeries); begin if FVolume<>Value then begin {$IFDEF D5} if Assigned(FVolume) then FVolume.RemoveFreeNotification(Self); {$ENDIF} FVolume:=Value; if Assigned(FVolume) then FVolume.FreeNotification(Self); ReCalculate; end; end; procedure TCLVFunction.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation=opRemove) and (AComponent=FVolume) then Volume:=nil; end; procedure TCLVFunction.SetAccumulate(const Value: Boolean); begin if FAccumulate<>Value then begin FAccumulate:=Value; ReCalculate; end; end; procedure TCLVFuncEditor.ApplyFormChanges; begin inherited; with TCLVFunction(IFunction) do begin Volume:=TChartSeries(CBVolume.Items.Objects[CBVolume.ItemIndex]); Accumulate:=CBAccumulate.Checked; end; end; procedure TCLVFuncEditor.CBAccumulateClick(Sender: TObject); begin EnableApply; end; procedure TCLVFuncEditor.SetFunction; begin inherited; with TCLVFunction(IFunction) do begin CBVolume.ItemIndex:=CBVolume.Items.IndexOfObject(Volume); CBAccumulate.Checked:=Accumulate; end; with CBVolume do begin FillSeriesItems(Items,IFunction.ParentSeries.ParentChart.SeriesList); Items.InsertObject(0,TeeMsg_None,nil); Items.Delete(Items.IndexOfObject(IFunction.ParentSeries)); ItemIndex:=Items.IndexOfObject(TCLVFunction(IFunction).Volume); end; end; initialization RegisterClass(TCLVFuncEditor); RegisterTeeFunction( TCLVFunction, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionCLV, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryFinancial ); finalization UnRegisterTeeFunctions([ TCLVFunction ]); end.
unit uSpell; // Word settings need to be restored to origional settings! {$O-} {$DEFINE CPRS} {$UNDEF CPRS} interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, ComObj, StdCtrls, ComCtrls, rCore, ORFn, Word2000, Variants, clipbrd, ActiveX, Contnrs, PSAPI, ExtCtrls; type TSpellCheckAvailable = record Evaluated: boolean; Available: boolean; end; function SpellCheckInProgress: Boolean; procedure KillSpellCheck; function SpellCheckAvailable: Boolean; procedure SpellCheckForControl(AnEditControl: TCustomMemo); procedure GrammarCheckForControl(AnEditControl: TCustomMemo); // Do Not Call these routines - internal use only procedure InternalSpellCheck(SpellCheck: boolean; EditControl: TCustomMemo); procedure RefocusSpellCheckWindow; const SpellCheckerSettingName = 'SpellCheckerSettings'; var SpellCheckerSettings: string = ''; implementation uses VAUtils, fSpellNotify, uInit; const TX_ERROR_TITLE = 'Error'; TX_ERROR_INTRO = 'An error has occured.'; TX_TRY_AGAIN = 'Would you like to try again?'; TX_WINDOW_TITLE = 'CPRS-Chart Spell Checking #'; TX_NO_SPELL_CHECK = 'Spell checking is unavailable.'; TX_NO_GRAMMAR_CHECK = 'Grammar checking is unavailable.'; TX_SPELL_COMPLETE = 'The spelling check is complete.'; TX_GRAMMAR_COMPLETE = 'The grammar check is complete.'; TX_SPELL_ABORT = 'The spelling check terminated abnormally.'; TX_GRAMMAR_ABORT = 'The grammar check terminated abnormally.'; TX_SPELL_CANCELLED = 'Spelling check was cancelled before completion.'; TX_GRAMMAR_CANCELLED = 'Grammar check was cancelled before completion.'; TX_NO_DETAILS = 'No further details are available.'; TX_NO_CORRECTIONS = 'Corrections have NOT been applied.'; CRLF = #13#10; // TABOO_STARTING_CHARS = '!"#$%&()*+,./:;<=>?@[\]^_`{|}'; VALID_STARTING_CHARS = '''-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; type TMSWordThread = class(TThread) private FBeforeLines: TStringList; FAfterLines: TStringList; FWordSettings: TList; FEditControl: TCustomMemo; FShowingMessage: boolean; // FEmptyVar: OleVariant; FFalseVar: OleVariant; // FTrueVar: OleVariant; FNullStr: OleVariant; FWord: WordApplication; FDoc: WordDocument; FWordVersion: single; FDialog: OleVariant; FDocDlg: OleVariant; FText: string; FSpellCheck: boolean; FCanceled: boolean; FTitle: string; FDocWindowHandle: HWnd; FOldFormChange: TNotifyEvent; FOldOnActivate: TNotifyEvent; FError: Exception; FErrorText1: string; FErrorText2: string; FAllowErrorRetry: boolean; FRetryResult: TShow508MessageResult; FResultMessage: string; FSpellChecking: boolean; FLock: TRTLCriticalSection; procedure OnFormChange(Sender: TObject); procedure OnAppActivate(Sender: TObject); procedure OnThreadTerminate(Sender: TObject); procedure FindDocumentWindow; procedure TransferText; function RunWithErrorTrap(AMethod: TThreadMethod; SpellCheckErrorMessage, GrammarCheckErrorMessage, AdditionalErrorMessage: string; AllowRetry: boolean): boolean; procedure WordError; procedure StartWord; procedure CreateDocument; procedure DoCheck; procedure ConfigWord; procedure ConfigDoc; procedure GetDialogs; procedure SaveUserSettings; procedure LoadUserSettings; procedure ExitWord; procedure ReportResults; procedure SaveWordSettings; procedure RestoreWordSettings; function UserSetting(Index: integer): boolean; procedure ThreadLock; procedure ThreadUnlock; protected constructor CreateThread(SpellCheck: boolean; AEditControl: TCustomMemo); procedure Execute; override; public procedure RefocusSpellCheckDialog; property Text: string read FText; property Canceled: boolean read FCanceled; end; var MSWordThread: TMSWordThread = nil; function ControlHasText(SpellCheck: boolean; AnEditControl: TCustomMemo): boolean; var i: integer; begin Result := FALSE; if not assigned(AnEditControl) then ShowMsg('Spell Check programming error') else begin for i := 0 to AnEditControl.Lines.Count - 1 do begin if trim(AnEditControl.Lines[i]) <> '' then begin Result := TRUE; break; end; end; if not Result then begin if SpellCheck then ShowMsg(TX_SPELL_COMPLETE) else ShowMsg(TX_GRAMMAR_COMPLETE) end; end; end; function SpellCheckInProgress: boolean; begin Result := assigned(MSWordThread); end; var uSpellCheckAvailable: TSpellCheckAvailable; procedure KillSpellCheck; var checking: boolean; WordHandle: HWnd; ProcessID: DWORD; ProcessHandle: THandle; begin if assigned(MSWordThread) then begin with MSWordThread do begin ThreadLock; try checking := FSpellChecking; WordHandle := FDocWindowHandle; Terminate; finally ThreadUnlock; end; try if checking then begin GetWindowThreadProcessId(WordHandle, ProcessID); ProcessHandle := OpenProcess(PROCESS_TERMINATE, False, ProcessID); try TerminateProcess(ProcessHandle, 0); finally CloseHandle(ProcessHandle); end; end; if assigned(MSWordThread) then begin WaitFor; end; except end; end; end; end; { Spell Checking using Visual Basic for Applications script } function SpellCheckAvailable: Boolean; //const // WORD_VBA_CLSID = 'CLSID\{000209FF-0000-0000-C000-000000000046}'; begin // CHANGED FOR PT. SAFETY ISSUE RELEASE 19.16, PATCH OR*3*155 - ADDED NEXT 2 LINES: //result := false; //exit; // Reenabled in version 21.1, via parameter setting (RV) // Result := (GetUserParam('ORWOR SPELL CHECK ENABLED?') = '1'); with uSpellCheckAvailable do // only want to call this once per session!!! v23.10+ begin if not Evaluated then begin Available := (GetUserParam('ORWOR SPELL CHECK ENABLED?') = '1'); Evaluated := True; end; Result := Available; end; end; procedure DoSpellCheck(SpellCheck: boolean; AnEditControl: TCustomMemo); var frmSpellNotify: TfrmSpellNotify; begin if assigned(MSWordThread) then exit; if ControlHasText(SpellCheck, AnEditControl) then begin frmSpellNotify := TfrmSpellNotify.Create(Application); try SuspendTimeout; try frmSpellNotify.SpellCheck := SpellCheck; frmSpellNotify.EditControl := AnEditControl; frmSpellNotify.ShowModal; finally ResumeTimeout; end; finally frmSpellNotify.Free; end; end; end; procedure InternalSpellCheck(SpellCheck: boolean; EditControl: TCustomMemo); begin MSWordThread := TMSWordThread.CreateThread(SpellCheck, EditControl); while assigned(MSWordThread) do begin Application.ProcessMessages; sleep(50); end; end; procedure RefocusSpellCheckWindow; begin if assigned(MSWordThread) then MSWordThread.RefocusSpellCheckDialog; end; procedure SpellCheckForControl(AnEditControl: TCustomMemo); begin DoSpellCheck(True, AnEditControl); end; procedure GrammarCheckForControl(AnEditControl: TCustomMemo); begin DoSpellCheck(False, AnEditControl); end; { TMSWordThread } const RETRY_MAX = 3; usCheckSpellingAsYouType = 1; usCheckGrammarAsYouType = 2; usIgnoreInternetAndFileAddresses = 3; usIgnoreMixedDigits = 4; usIgnoreUppercase = 5; usCheckGrammarWithSpelling = 6; usShowReadabilityStatistics = 7; usSuggestFromMainDictionaryOnly = 8; usSuggestSpellingCorrections = 9; usHideSpellingErrors = 10; usHideGrammarErrors = 11; sTrueCode = 'T'; sFalseCode = 'F'; // AFAYT = AutoFormatAsYouType wsAFAYTApplyBorders = 0; wsAFAYTApplyBulletedLists = 1; wsAFAYTApplyFirstIndents = 2; wsAFAYTApplyHeadings = 3; wsAFAYTApplyNumberedLists = 4; wsAFAYTApplyTables = 5; wsAFAYTAutoLetterWizard = 6; wsAFAYTDefineStyles = 7; wsAFAYTFormatListItemBeginning = 8; wsAFAYTInsertClosings = 9; wsAFAYTReplaceQuotes = 10; wsAFAYTReplaceFractions = 11; wsAFAYTReplaceHyperlinks = 12; wsAFAYTReplaceOrdinals = 13; wsAFAYTReplacePlainTextEmphasis = 14; wsAFAYTReplaceSymbols = 15; wsAutoFormatReplaceQuotes = 16; wsTabIndentKey = 17; wsWindowState = 18; wsSaveInterval = 19; wsTrackRevisions = 20; wsShowRevisions = 21; wsShowSummary = 22; // not used for Word 2010 procedure TMSWordThread.Execute; var ok: boolean; procedure EnableAppActivation; begin FWord.Caption := FTitle; Synchronize(FindDocumentWindow); end; procedure Run(AMethod: TThreadMethod; force: boolean = false); begin if terminated then exit; if ok or force then begin ok := RunWithErrorTrap(AMethod, TX_SPELL_ABORT, TX_GRAMMAR_ABORT, '', FALSE); end; end; procedure BuildResultMessage; begin FResultMessage := ''; if FCanceled then begin if FSpellCheck then FResultMessage := TX_SPELL_CANCELLED else FResultMessage := TX_GRAMMAR_CANCELLED; FResultMessage := FResultMessage + CRLF + TX_NO_CORRECTIONS; end else begin if FSpellCheck then FResultMessage := TX_SPELL_COMPLETE else FResultMessage := TX_GRAMMAR_COMPLETE; end; end; procedure SetStatus(value, force: boolean); begin if ok or force then begin ThreadLock; FSpellChecking := value; ThreadUnlock; end; end; begin CoInitialize(nil); ok := true; try if RunWithErrorTrap(StartWord, TX_NO_SPELL_CHECK, TX_NO_GRAMMAR_CHECK, TX_TRY_AGAIN, TRUE) then begin try if RunWithErrorTrap(CreateDocument, TX_SPELL_ABORT, TX_GRAMMAR_ABORT, '', FALSE) then begin try EnableAppActivation; Run(SaveWordSettings); Run(ConfigWord); Run(ConfigDoc); Run(GetDialogs); Run(LoadUserSettings); SetStatus(True, False); Run(DoCheck); SetStatus(False, True); Run(SaveUserSettings); Run(RestoreWordSettings); Run(ExitWord, True); if ok and (not terminated) then begin Synchronize(TransferText); BuildResultMessage; Synchronize(ReportResults); end; finally FDoc := nil; end; end; finally FWord := nil; end; end; finally CoUninitialize; end; end; procedure TMSWordThread.ExitWord; var Save: OleVariant; Doc: OleVariant; begin VarClear(FDialog); VarClear(FDocDlg); VariantInit(Save); VariantInit(Doc); try Save := wdDoNotSaveChanges; Doc := wdWordDocument; FWord.Quit(Save, Doc, FFalseVar); finally VarClear(Save); VarClear(Doc); end; end; var WindowTitle: string; WindowHandle: HWnd; function FindDocWindow(Handle: HWND; Info: Pointer): BOOL; stdcall; var title: string; begin title := GetWindowTitle(Handle); if title = WindowTitle then begin WindowHandle := Handle; Result := FALSE; end else Result := True; end; procedure TMSWordThread.FindDocumentWindow; begin WindowTitle := FTitle; WindowHandle := 0; EnumWindows(@FindDocWindow, 0); FDocWindowHandle := WindowHandle; end; procedure TMSWordThread.GetDialogs; //var // DispParams: TDispParams; // OleArgs: array of OleVariant; // ExcepInfo: TExcepInfo; // Status: integer; begin // SetLength(OleArgs, 1); // VariantInit(OleArgs[0]); // try VariantInit(FDialog); FDialog := FWord.Dialogs.Item(wdDialogToolsOptionsSpellingAndGrammar); VariantInit(FDocDlg); FDocDlg := FWord.ActiveDocument; (* OleArgs[0] := wdDialogToolsOptionsSpellingAndGrammar; DispParams.rgvarg := @OleArgs[0]; DispParams.cArgs := 1; DispParams.rgdispidNamedArgs := nil; DispParams.cNamedArgs := 0; // FDialog := FWord.Dialogs.Item(wdDialogToolsOptionsSpellingAndGrammar); // dispid 0 is the Item method Status := FWord.Dialogs.Invoke(0, GUID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD or DISPATCH_PROPERTYGET, DispParams, @FDialog, @ExcepInfo, nil); if Status <> S_OK then DispatchInvokeError(Status, ExcepInfo); VariantInit(FDocDlg); DispParams.rgvarg := nil; DispParams.cArgs := 0; Status := FWord.Invoke(3, GUID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD or DISPATCH_PROPERTYGET, DispParams, @FDocDlg, @ExcepInfo, nil); if Status <> S_OK then DispatchInvokeError(Status, ExcepInfo); finally VarClear(OleArgs[0]); SetLength(OleArgs, 0); end; *) end; procedure TMSWordThread.LoadUserSettings; begin // load FUserSettings from server // these are default values (* 9 AlwaysSuggest, 8 SuggestFromMainDictOnly, 5 IgnoreAllCaps, 4 IgnoreMixedDigits, ResetIgnoreAll, Type, CustomDict1, CustomDict2, CustomDict3, CustomDict4, CustomDict5, CustomDict6, CustomDict7, CustomDict8, CustomDict9, CustomDict10, 1 AutomaticSpellChecking, 3 FilenamesEmailAliases, UserDict1, 2 AutomaticGrammarChecking, 6?? ForegroundGrammar, 7 ShowStatistics, Options, RecheckDocument, IgnoreAuxFind, IgnoreMissDictSearch, 10 HideGrammarErrors, CheckSpelling, GrLidUI, SpLidUI, DictLang1, DictLang2, DictLang3, DictLang4, DictLang5, DictLang6, DictLang7, DictLang8, DictLang9, DictLang10, 11 HideSpellingErrors, HebSpellStart, InitialAlefHamza, FinalYaa, GermanPostReformSpell, AraSpeller, ProcessCompoundNoun *) // FDialog. ThreadLock; try FDialog.AutomaticSpellChecking := UserSetting(usCheckSpellingAsYouType); FDialog.AutomaticGrammarChecking := UserSetting(usCheckGrammarAsYouType); FDialog.FilenamesEmailAliases := UserSetting(usIgnoreInternetAndFileAddresses); FDialog.IgnoreMixedDigits := UserSetting(usIgnoreMixedDigits); FDialog.ForegroundGrammar := UserSetting(usCheckGrammarWithSpelling); FDialog.ShowStatistics := UserSetting(usShowReadabilityStatistics); FDialog.SuggestFromMainDictOnly := UserSetting(usSuggestFromMainDictionaryOnly); FDialog.IgnoreAllCaps := UserSetting(usIgnoreUppercase); FDialog.AlwaysSuggest := UserSetting(usSuggestSpellingCorrections); FDialog.HideSpellingErrors := UserSetting(usHideSpellingErrors); FDialog.HideGrammarErrors := UserSetting(usHideGrammarErrors); FDialog.Execute; finally ThreadUnlock; end; // need list of custom dictionaries - default to CUSTOM.DIC (or query Word for it!!!) // FWord.CustomDictionaries end; procedure TMSWordThread.OnAppActivate(Sender: TObject); begin if assigned(FOldOnActivate) then FOldOnActivate(Sender); RefocusSpellCheckDialog; end; procedure TMSWordThread.OnFormChange(Sender: TObject); begin if assigned(FOldFormChange) then FOldFormChange(Sender); RefocusSpellCheckDialog; end; procedure TMSWordThread.OnThreadTerminate(Sender: TObject); begin Application.OnActivate := FOldOnActivate; Screen.OnActiveFormChange := FOldFormChange; // VarClear(FEmptyVar); VarClear(FFalseVar); // VarClear(FTrueVar); FWordSettings.Free; FBeforeLines.Free; FAfterLines.Free; DeleteCriticalSection(FLock); Screen.Cursor := crDefault; MSWordThread := nil; end; procedure TMSWordThread.RefocusSpellCheckDialog; begin Application.ProcessMessages; if Application.Active and (not FShowingMessage) and (FDocWindowHandle <> 0) then begin SetForegroundWindow(FDocWindowHandle); SetFocus(FDocWindowHandle); end; end; procedure TMSWordThread.ReportResults; var icon: TShow508MessageIcon; begin if not FCanceled then icon := smiInfo else icon := smiWarning; FShowingMessage := True; try ShowMsg(FResultMessage, icon, smbOK); finally FShowingMessage := False; end; end; procedure TMSWordThread.RestoreWordSettings; function Load(Index: integer): integer; begin if FWordSettings.Count > Index then Result := Integer(FWordSettings[Index]) else Result := 0 end; begin FWord.Options.AutoFormatAsYouTypeApplyBorders := boolean(Load(wsAFAYTApplyBorders)); FWord.Options.AutoFormatAsYouTypeApplyBulletedLists := boolean(Load(wsAFAYTApplyBulletedLists)); FWord.Options.AutoFormatAsYouTypeApplyFirstIndents := boolean(Load(wsAFAYTApplyFirstIndents)); FWord.Options.AutoFormatAsYouTypeApplyHeadings := boolean(Load(wsAFAYTApplyHeadings)); FWord.Options.AutoFormatAsYouTypeApplyNumberedLists := boolean(Load(wsAFAYTApplyNumberedLists)); FWord.Options.AutoFormatAsYouTypeApplyTables := boolean(Load(wsAFAYTApplyTables)); FWord.Options.AutoFormatAsYouTypeAutoLetterWizard := boolean(Load(wsAFAYTAutoLetterWizard)); FWord.Options.AutoFormatAsYouTypeDefineStyles := boolean(Load(wsAFAYTDefineStyles)); FWord.Options.AutoFormatAsYouTypeFormatListItemBeginning := boolean(Load(wsAFAYTFormatListItemBeginning)); FWord.Options.AutoFormatAsYouTypeInsertClosings := boolean(Load(wsAFAYTInsertClosings)); FWord.Options.AutoFormatAsYouTypeReplaceQuotes := boolean(Load(wsAFAYTReplaceQuotes)); FWord.Options.AutoFormatAsYouTypeReplaceFractions := boolean(Load(wsAFAYTReplaceFractions)); FWord.Options.AutoFormatAsYouTypeReplaceHyperlinks := boolean(Load(wsAFAYTReplaceHyperlinks)); FWord.Options.AutoFormatAsYouTypeReplaceOrdinals := boolean(Load(wsAFAYTReplaceOrdinals)); FWord.Options.AutoFormatAsYouTypeReplacePlainTextEmphasis := boolean(Load(wsAFAYTReplacePlainTextEmphasis)); FWord.Options.AutoFormatAsYouTypeReplaceSymbols := boolean(Load(wsAFAYTReplaceSymbols)); FWord.Options.AutoFormatReplaceQuotes := boolean(Load(wsAutoFormatReplaceQuotes)); FWord.Options.TabIndentKey := boolean(Load(wsTabIndentKey)); FWord.WindowState := Load(wsWindowState); FWord.Options.SaveInterval := Load(wsSaveInterval); FDoc.TrackRevisions := boolean(Load(wsTrackRevisions)); FDoc.ShowRevisions := boolean(Load(wsShowRevisions)); if (FWordVersion < 13) then // altered for Word 2010 FDoc.ShowSummary := boolean(Load(wsShowSummary)); end; function TMSWordThread.RunWithErrorTrap(AMethod: TThreadMethod; SpellCheckErrorMessage, GrammarCheckErrorMessage, AdditionalErrorMessage: string; AllowRetry: boolean): boolean; var RetryCount: integer; Done: boolean; begin RetryCount := 0; Result := TRUE; repeat Done := TRUE; try AMethod; except on E: Exception do begin if not terminated then begin inc(RetryCount); Done := FALSE; if RetryCount >= RETRY_MAX then begin FError := E; FAllowErrorRetry := AllowRetry; if FSpellCheck then FErrorText1 := SpellCheckErrorMessage else FErrorText1 := GrammarCheckErrorMessage; FErrorText2 := AdditionalErrorMessage; Synchronize(WordError); if AllowRetry and (FRetryResult = smrRetry) then RetryCount := 0 else begin Result := FALSE; Done := TRUE; end; end; end; end; end; until Done; end; procedure TMSWordThread.DoCheck; begin FDoc.Content.Text := FText; FDoc.Content.SpellingChecked := False; FDoc.Content.GrammarChecked := False; if FSpellCheck then begin FDocDlg.Content.CheckSpelling; // FDoc.CheckSpelling(FNullStr, FEmptyVar, FEmptyVar, {Ignore, Suggest, }FNullStr, FNullStr, // FNullStr, FNullStr, FNullStr, FNullStr, FNullStr, FNullStr, FNullStr); // FSucceeded := FDoc.Content.SpellingChecked; FText := FDoc.Content.Text; end else begin FDoc.Content.CheckGrammar; // FSucceeded := FDoc.Content.GrammarChecked; FText := FDoc.Content.Text; end; FCanceled := (FText = ''); end; procedure TMSWordThread.SaveUserSettings; procedure SaveSetting(Value: boolean; Index: integer); begin while length(SpellCheckerSettings) < Index do SpellCheckerSettings := SpellCheckerSettings + ' '; if Value then SpellCheckerSettings[Index] := sTrueCode else SpellCheckerSettings[Index] := sFalseCode; end; begin ThreadLock; try SpellCheckerSettings := ''; FDialog.Update; SaveSetting(FDialog.AutomaticSpellChecking, usCheckSpellingAsYouType); SaveSetting(FDialog.AutomaticGrammarChecking, usCheckGrammarAsYouType); SaveSetting(FDialog.FilenamesEmailAliases, usIgnoreInternetAndFileAddresses); SaveSetting(FDialog.IgnoreMixedDigits, usIgnoreMixedDigits); SaveSetting(FDialog.IgnoreAllCaps, usIgnoreUppercase); SaveSetting(FDialog.ForegroundGrammar, usCheckGrammarWithSpelling); SaveSetting(FDialog.ShowStatistics, usShowReadabilityStatistics); SaveSetting(FDialog.SuggestFromMainDictOnly, usSuggestFromMainDictionaryOnly); SaveSetting(FDialog.AlwaysSuggest, usSuggestSpellingCorrections); SaveSetting(FDialog.HideSpellingErrors, usHideSpellingErrors); SaveSetting(FDialog.HideGrammarErrors, usHideGrammarErrors); finally ThreadUnlock; end; (* 9 AlwaysSuggest, 8 SuggestFromMainDictOnly, 5 IgnoreAllCaps, 4 IgnoreMixedDigits, ResetIgnoreAll, Type, CustomDict1, CustomDict2, CustomDict3, CustomDict4, CustomDict5, CustomDict6, CustomDict7, CustomDict8, CustomDict9, CustomDict10, 1 AutomaticSpellChecking, 3 FilenamesEmailAliases, UserDict1, 2 AutomaticGrammarChecking, 6?? ForegroundGrammar, 7 ShowStatistics, Options, RecheckDocument, IgnoreAuxFind, IgnoreMissDictSearch, 10 HideGrammarErrors, CheckSpelling, GrLidUI, SpLidUI, DictLang1, DictLang2, DictLang3, DictLang4, DictLang5, DictLang6, DictLang7, DictLang8, DictLang9, DictLang10, 11 HideSpellingErrors, HebSpellStart, InitialAlefHamza, FinalYaa, GermanPostReformSpell, AraSpeller, ProcessCompoundNoun *) end; procedure TMSWordThread.SaveWordSettings; procedure Save(Value, Index: integer); begin while FWordSettings.Count <= Index do FWordSettings.Add(nil); FWordSettings[Index] := Pointer(Value); end; begin Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyBorders) , wsAFAYTApplyBorders); Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyBulletedLists) , wsAFAYTApplyBulletedLists); Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyFirstIndents) , wsAFAYTApplyFirstIndents); Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyHeadings) , wsAFAYTApplyHeadings); Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyNumberedLists) , wsAFAYTApplyNumberedLists); Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyTables) , wsAFAYTApplyTables); Save(Ord(FWord.Options.AutoFormatAsYouTypeAutoLetterWizard) , wsAFAYTAutoLetterWizard); Save(Ord(FWord.Options.AutoFormatAsYouTypeDefineStyles) , wsAFAYTDefineStyles); Save(Ord(FWord.Options.AutoFormatAsYouTypeFormatListItemBeginning) , wsAFAYTFormatListItemBeginning); Save(Ord(FWord.Options.AutoFormatAsYouTypeInsertClosings) , wsAFAYTInsertClosings); Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceQuotes) , wsAFAYTReplaceQuotes); Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceFractions) , wsAFAYTReplaceFractions); Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceHyperlinks) , wsAFAYTReplaceHyperlinks); Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceOrdinals) , wsAFAYTReplaceOrdinals); Save(Ord(FWord.Options.AutoFormatAsYouTypeReplacePlainTextEmphasis) , wsAFAYTReplacePlainTextEmphasis); Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceSymbols) , wsAFAYTReplaceSymbols); Save(Ord(FWord.Options.AutoFormatReplaceQuotes) , wsAutoFormatReplaceQuotes); Save(Ord(FWord.Options.TabIndentKey) , wsTabIndentKey); Save(Ord(FWord.WindowState) , wsWindowState); Save(Ord(FWord.Options.SaveInterval) , wsSaveInterval); Save(Ord(FDoc.TrackRevisions) , wsTrackRevisions); Save(Ord(FDoc.ShowRevisions) , wsShowRevisions); if (FWordVersion < 13) then // altered for Word 2010 Save(Ord(FDoc.ShowSummary) , wsShowSummary); end; procedure TMSWordThread.StartWord; begin FWord := CoWordApplication.Create; FWordVersion := StrToFloatDef(FWord.Version, 0.0); end; procedure TMSWordThread.ThreadLock; begin EnterCriticalSection(FLock); end; procedure TMSWordThread.ThreadUnlock; begin LeaveCriticalSection(FLock); end; procedure TMSWordThread.TransferText; var i: integer; Lines: TStringList; begin if (not FCanceled) then begin Lines := TStringList.Create; try Lines.Text := FText; // For some unknown reason spell check adds garbage lines to text while (Lines.Count > 0) and (trim(Lines[Lines.Count-1]) = '') do Lines.Delete(Lines.Count-1); for i := 0 to FBeforeLines.Count-1 do Lines.Insert(i, FBeforeLines[i]); for i := 0 to FAfterLines.Count-1 do Lines.Add(FAfterLines[i]); FEditControl.Lines.Text := Lines.Text; // FastAssign(Lines, FEditControl.Lines); finally Lines.Free; end; end; end; function TMSWordThread.UserSetting(Index: integer): boolean; begin if SpellCheckerSettings = '' then begin case Index of usCheckSpellingAsYouType: Result := True; usCheckGrammarAsYouType: Result := False; usIgnoreInternetAndFileAddresses: Result := True; usIgnoreMixedDigits: Result := True; usIgnoreUppercase: Result := True; usCheckGrammarWithSpelling: Result := False; usShowReadabilityStatistics: Result := False; usSuggestFromMainDictionaryOnly: Result := False; usSuggestSpellingCorrections: Result := True; usHideSpellingErrors: Result := False; usHideGrammarErrors: Result := True; else Result := False; end; end else Result := copy(SpellCheckerSettings,Index,1) = sTrueCode; end; procedure TMSWordThread.ConfigDoc; begin FDoc.TrackRevisions := False; FDoc.ShowRevisions := False; if (FWordVersion < 13) then // altered for Word 2010 FDoc.ShowSummary := False; FWord.Height := 1000; FWord.Width := 1000; FWord.Top := -2000; FWord.Left := -2000; end; procedure TMSWordThread.ConfigWord; begin // save all old values to FWord, restore when done. FWord.Options.AutoFormatAsYouTypeApplyBorders := False; FWord.Options.AutoFormatAsYouTypeApplyBulletedLists := False; FWord.Options.AutoFormatAsYouTypeApplyFirstIndents := False; FWord.Options.AutoFormatAsYouTypeApplyHeadings := False; FWord.Options.AutoFormatAsYouTypeApplyNumberedLists := False; FWord.Options.AutoFormatAsYouTypeApplyTables := False; FWord.Options.AutoFormatAsYouTypeAutoLetterWizard := False; FWord.Options.AutoFormatAsYouTypeDefineStyles := False; FWord.Options.AutoFormatAsYouTypeFormatListItemBeginning := False; FWord.Options.AutoFormatAsYouTypeInsertClosings := False; FWord.Options.AutoFormatAsYouTypeReplaceQuotes := False; FWord.Options.AutoFormatAsYouTypeReplaceFractions := False; FWord.Options.AutoFormatAsYouTypeReplaceHyperlinks := False; FWord.Options.AutoFormatAsYouTypeReplaceOrdinals := False; FWord.Options.AutoFormatAsYouTypeReplacePlainTextEmphasis := False; FWord.Options.AutoFormatAsYouTypeReplaceSymbols := False; FWord.Options.AutoFormatReplaceQuotes := False; FWord.Options.TabIndentKey := False; FWord.WindowState := wdWindowStateNormal; FWord.Options.SaveInterval := 0; FWord.ResetIgnoreAll; end; procedure TMSWordThread.CreateDocument; var DocType: OleVariant; begin VariantInit(DocType); try DocType := wdNewBlankDocument; FDoc := FWord.Documents.Add(FNullStr, FFalseVar, DocType, FFalseVar); FDoc.Activate; finally VarClear(DocType); end; end; constructor TMSWordThread.CreateThread(SpellCheck: boolean; AEditControl: TCustomMemo); function WordDocTitle: string; var Guid: TGUID; begin if ActiveX.Succeeded(CreateGUID(Guid)) then Result := GUIDToString(Guid) else Result := ''; Result := TX_WINDOW_TITLE + IntToStr(Application.Handle) + '/' + Result; end; function BeforeLineInvalid(Line: string): boolean; var i: integer; begin Result := (trim(Line) = ''); if not Result then begin for I := 1 to length(Line) do if pos(Line[i], VALID_STARTING_CHARS) > 0 then exit; Result := True; end; end; procedure GetTextFromComponent; var Lines: TStrings; begin Lines := TStringList.Create; try Lines.Text := AEditControl.Lines.Text; // FastAssign(AEditControl.Lines, Lines); while (Lines.Count > 0) and (trim(Lines[Lines.Count-1]) = '') do begin FAfterLines.Insert(0, Lines[Lines.Count-1]); Lines.Delete(Lines.Count-1); end; while (Lines.Count > 0) and (BeforeLineInvalid(Lines[0])) do begin FBeforeLines.Add(Lines[0]); Lines.Delete(0); end; FText := Lines.Text; finally Lines.Free; end; end; begin inherited Create(TRUE); Screen.Cursor := crHourGlass; InitializeCriticalSection(FLock); FBeforeLines := TStringList.Create; FAfterLines := TStringList.Create; FWordSettings := TList.Create; FSpellChecking := False; FEditControl := AEditControl; // VariantInit(FEmptyVar); VariantInit(FFalseVar); // VariantInit(FTrueVar); VariantInit(FNullStr); // TVarData(FEmptyVar).VType := VT_EMPTY; TVarData(FFalseVar).VType := VT_BOOL; // TVarData(FTrueVar).VType := VT_BOOL; TVarData(FNullStr).VType := VT_BSTR; // FEmptyVar := 0; FFalseVar := 0; // FTrueVar := -1; FNullStr := ''; FDocWindowHandle := 0; FSpellCheck := SpellCheck; GetTextFromComponent; FCanceled := FALSE; FTitle := WordDocTitle; FreeOnTerminate := True; OnTerminate := OnThreadTerminate; FOldOnActivate := Application.OnActivate; Application.OnActivate := OnAppActivate; FOldFormChange := Screen.OnActiveFormChange; Screen.OnActiveFormChange := OnFormChange; {$WARN SYMBOL_DEPRECATED OFF} Resume; {$WARN SYMBOL_DEPRECATED ON} end; procedure TMSWordThread.WordError; var btn: TShow508MessageButton; msg: string; procedure Append(txt: string); begin if txt <> '' then msg := msg + CRLF + txt; end; begin if FAllowErrorRetry then btn := smbRetryCancel else btn := smbOK; msg := TX_ERROR_INTRO; Append(FErrorText1); if FError.Message <> '' then Append(FError.Message) else Append(TX_NO_DETAILS); Append(FErrorText2); FShowingMessage := True; try FRetryResult := ShowMsg(Msg, TX_ERROR_TITLE, smiError, btn); finally FShowingMessage := False; end; end; initialization finalization KillSpellCheck; end.